@zinley/orion 1.2.29 → 1.2.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +246 -246
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- var Om=Object.defineProperty;var F=(i,e)=>()=>(i&&(e=i(i=0)),e);var Fe=(i,e)=>{for(var t in e)Om(i,t,{get:e[t],enumerable:!0})};var pe,Vt=F(()=>{"use strict";pe=[{name:"snowx-o4.6",displayName:"Claude Opus 4.6",provider:"ANTHROPIC",apiModelName:"claude-opus-4-6",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:2.5},{name:"snowx-c6",displayName:"Claude Sonnet 4.6",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-6",maxTokens:64e3,contextWindow:1e6,supportsVision:!0,creditMultiplier:1.25},{name:"snowx-o4.5",displayName:"Claude Opus 4.5",provider:"ANTHROPIC",apiModelName:"claude-opus-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:1.5},{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:1},{name:"snowx-c3",displayName:"Claude 4 Sonnet",provider:"ANTHROPIC",apiModelName:"claude-4-sonnet-20250514",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:1},{name:"snowx-c1",displayName:"Claude 3.7 Sonnet",provider:"BEDROCK",apiModelName:"us.anthropic.claude-3-7-sonnet-20250219-v1:0",maxTokens:4096,contextWindow:2e5,supportsVision:!0,creditMultiplier:1},{name:"snowx-h4",displayName:"Claude Haiku 4.5",provider:"ANTHROPIC",apiModelName:"claude-3-5-haiku-20241022",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:.5},{name:"snowx-5.2",displayName:"GPT-5.2 High",provider:"GPT",apiModelName:"gpt-5.2-high",maxTokens:32768,contextWindow:1047576,supportsVision:!0,creditMultiplier:1},{name:"snowx-5.2-chat",displayName:"GPT-5.2",provider:"GPT",apiModelName:"gpt-5.2",maxTokens:32768,contextWindow:1047576,supportsVision:!0,creditMultiplier:.5},{name:"snowx-4.1",displayName:"GPT-4.1",provider:"GPT",apiModelName:"gpt-4.1",maxTokens:4096,contextWindow:128e3,supportsVision:!0,creditMultiplier:.5},{name:"snowx-g6",displayName:"Gemini 3.1 Pro",provider:"google",apiModelName:"gemini-3.1-pro-preview",maxTokens:65536,contextWindow:1048576,supportsVision:!0,creditMultiplier:1.25},{name:"snowx-g4",displayName:"Gemini 3 Pro",provider:"google",apiModelName:"gemini-3-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0,creditMultiplier:1},{name:"snowx-g5",displayName:"Gemini 3 Flash",provider:"google",apiModelName:"gemini-3-flash",maxTokens:8192,contextWindow:1e6,supportsVision:!0,creditMultiplier:.5},{name:"snowx-g1",displayName:"Gemini 2.5 Pro",provider:"google",apiModelName:"gemini-2.5-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0,creditMultiplier:1}]});var bi,u,j=F(()=>{"use strict";bi=class i{static instance;logLevel=0;debugMode=!1;static getInstance(){return i.instance||(i.instance=new i),i.instance}setLogLevel(e){this.logLevel=e}setDebugMode(e){this.debugMode=e}getDebugMode(){return this.debugMode}error(e,...t){this.logLevel>=0&&console.error(`❌ ${e}`,...t)}warn(e,...t){this.logLevel>=1&&console.warn(`⚠️ ${e}`,...t)}info(e,...t){this.logLevel>=2&&console.log(`ℹ️ ${e}`,...t)}success(e,...t){this.logLevel>=2&&console.log(`✅ ${e}`,...t)}debug(e,...t){this.debugMode&&this.logLevel>=3&&console.log(`🔍 [DEBUG] ${e}`,...t)}status(e,...t){console.log(e,...t)}system(e){console.log(e)}},u=bi.getInstance()});var kt={};Fe(kt,{UserDefaults:()=>de});import Is from"fs";import yi from"path";import $m from"os";var vi,de,Le=F(()=>{"use strict";j();vi=class i{static instance;preferencesPath;preferences={};constructor(){let e=yi.join($m.homedir(),".orion");this.preferencesPath=yi.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadPreferences(){try{if(Is.existsSync(this.preferencesPath)){let e=Is.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),u.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{u.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=yi.dirname(this.preferencesPath);Is.existsSync(e)||Is.mkdirSync(e,{recursive:!0}),Is.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),u.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){u.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),u.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(),u.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},de=vi.getInstance()});var xe,wn=F(()=>{"use strict";Vt();Le();j();xe=class{static getDisplayName(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";case 3:return"Max";default:return"Free"}}static plusOnlyModels=[];static proOnlyModels=["snowx-o4.5","snowx-c6","snowx-5-pro"];static maxOnlyModels=["snowx-o4.6"];static getRequiredTier(e){return this.maxOnlyModels.includes(e)?3:this.proOnlyModels.includes(e)?2:this.plusOnlyModels.includes(e)?1:0}static getCurrentUserTier(){let e=de.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=3?e:0}static setUserTier(e){de.set("userSubscriptionTier",e),u.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){if(this.maxOnlyModels.includes(e)){let n=t===3;return u.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=MAX (exclusive), Access=${n}`),n}if(t===3)return u.debug(`Access check for ${e}: User tier=MAX (no limits), Access=true`),!0;if(this.proOnlyModels.includes(e)){let n=t===2;return u.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=PRO, Access=${n}`),n}if(t===2)return u.debug(`Access check for ${e}: User tier=PRO, Access=true`),!0;if(this.plusOnlyModels.includes(e)){let n=t>=1;return u.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=PLUS, Access=${n}`),n}return u.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=FREE, Access=true`),!0}static isModelAccessibleForCurrentUser(e){let t=this.getCurrentUserTier();return this.isModelAccessible(e,t)}static getAccessibleModels(e){return pe.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.";case 3:return"This model requires a Max subscription. Please upgrade to access.";default:return"This model is not available with your current subscription."}}static getModelDisplayNameWithTier(e){return e.displayName}}});import*as Ce from"@sentry/node";var Si,wi,Fc=F(()=>{"use strict";j();Si=class i{static instance;isEnabled=!0;userId=null;userEmail=null;deviceId=null;constructor(){this.isEnabled=process.env.ORION_DISABLE_TELEMETRY!=="true"}static getInstance(){return i.instance||(i.instance=new i),i.instance}setUser(e,t,n){this.userId=e,this.userEmail=t||null,this.isEnabled&&Ce.setUser({id:e,email:t,subscription:n})}setDevice(e){this.deviceId=e,this.isEnabled&&Ce.setTag("device_id",e)}clearUser(){this.userId=null,this.userEmail=null,this.isEnabled&&Ce.setUser(null)}captureException(e,t){if(!this.isEnabled)return u.debug("[SENTRY] Telemetry disabled, skipping error capture"),null;if(e instanceof Error){let n=e.message.toLowerCase();if(n.includes("[done]")||n.includes("stream ended"))return null}return Ce.withScope(n=>{if(t?.tags)for(let[r,o]of Object.entries(t.tags))n.setTag(r,o);t?.sessionId&&n.setTag("session_id",t.sessionId),t?.conversationId&&n.setTag("conversation_id",t.conversationId),t?.toolName&&n.setTag("tool_name",t.toolName),t?.endpoint&&n.setTag("endpoint",t.endpoint),t?.extra&&n.setExtras(t.extra),t?.toolArgs&&n.setExtra("tool_args",t.toolArgs);let s=Ce.captureException(e);return u.debug(`[SENTRY] Captured exception: ${s}`),s})}captureMessage(e,t="info",n){return this.isEnabled?Ce.withScope(s=>{if(n?.tags)for(let[o,a]of Object.entries(n.tags))s.setTag(o,a);n?.extra&&s.setExtras(n.extra);let r=Ce.captureMessage(e,t);return u.debug(`[SENTRY] Captured message: ${r}`),r}):null}addBreadcrumb(e,t,n,s="info"){this.isEnabled&&Ce.addBreadcrumb({message:e,category:t,data:n,level:s,timestamp:Date.now()/1e3})}trackApiCall(e,t,n){this.addBreadcrumb(`${t} ${e}`,"api_call",{endpoint:e,method:t,statusCode:n})}trackToolExecution(e,t,n){this.addBreadcrumb(`Tool: ${e} - ${t?"success":"failed"}`,"tool_execution",{toolName:e,success:t,duration:n},t?"info":"warning")}trackUserAction(e,t){this.addBreadcrumb(e,"user_action",t)}trackNavigation(e,t){this.addBreadcrumb(`${e} -> ${t}`,"navigation",{from:e,to:t})}setTag(e,t){this.isEnabled&&Ce.setTag(e,t)}setExtra(e,t){this.isEnabled&&Ce.setExtra(e,t)}startTransaction(e,t){return this.isEnabled?Ce.startInactiveSpan({name:e,op:t}):null}},wi=Si.getInstance()});var Ds={};Fe(Ds,{SecureStorageService:()=>Ir,secureStorage:()=>Hm});import ks from"crypto";import Xt from"os";import Tn from"fs";import Ti from"path";import{execSync as Fm}from"child_process";var Lc,Ps,Uc,Lm,Um,Bm,As,Wm,Ir,Hm,Ms=F(()=>{"use strict";j();Lc="aes-256-gcm",Ps=16,Uc=16,Lm=32,Um=32,Bm=1e5,As="__enc__",Wm=["snowx_auth_token","snowx_access_token","snowx_user_data","snowx_device_id","orion_device_id","firebase_custom_token"],Ir=class i{static instance;storagePath;storage={};encryptionKey=null;salt=null;isProduction;constructor(){let e=Ti.join(Xt.homedir(),".orion-cli");this.storagePath=Ti.join(e,"secure-storage.json"),this.isProduction=!0,this.loadStorage(),this.initializeEncryption()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadStorage(){try{if(Tn.existsSync(this.storagePath)){let e=Tn.readFileSync(this.storagePath,"utf8"),t=JSON.parse(e);this.storage=t.data||{},this.salt=t.salt?Buffer.from(t.salt,"base64"):null,u.debug("[SECURE] Loaded secure storage")}}catch{u.debug("[SECURE] Failed to load secure storage, starting fresh"),this.storage={}}}saveStorage(){try{let e=Ti.dirname(this.storagePath);Tn.existsSync(e)||Tn.mkdirSync(e,{recursive:!0});let t={data:this.storage,salt:this.salt?.toString("base64")};Tn.writeFileSync(this.storagePath,JSON.stringify(t,null,2),{mode:384}),u.debug("[SECURE] Saved secure storage")}catch(e){u.debug(`[SECURE] Failed to save: ${e.message}`)}}initializeEncryption(){this.salt||(this.salt=ks.randomBytes(Lm));let e=this.generateDeviceSeed();this.encryptionKey=ks.pbkdf2Sync(e,this.salt,Bm,Um,"sha256"),u.debug("[SECURE] Encryption initialized")}generateDeviceSeed(){return[Xt.hostname(),Xt.platform(),Xt.arch(),Xt.cpus()[0]?.model||"unknown-cpu",Xt.userInfo().username,this.getMachineId()].join("|")}getMachineId(){try{if(process.platform==="linux"&&Tn.existsSync("/etc/machine-id"))return Tn.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let t=Fm("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID" = "([^"]+)"/);if(t)return t[1]}}catch{}return Xt.hostname()+Xt.userInfo().uid}shouldEncrypt(e){return!this.isProduction&&process.env.ORION_SKIP_ENCRYPTION==="true"?!1:Wm.some(t=>e.includes(t))}encrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");let t=ks.randomBytes(Ps),n=ks.createCipheriv(Lc,this.encryptionKey,t),s=n.update(e,"utf8","base64");s+=n.final("base64");let r=n.getAuthTag(),o=Buffer.concat([t,r,Buffer.from(s,"base64")]);return As+o.toString("base64")}decrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");if(!e.startsWith(As))return e;let t=Buffer.from(e.slice(As.length),"base64"),n=t.subarray(0,Ps),s=t.subarray(Ps,Ps+Uc),r=t.subarray(Ps+Uc),o=ks.createDecipheriv(Lc,this.encryptionKey,n);o.setAuthTag(s);let a=o.update(r.toString("base64"),"base64","utf8");return a+=o.final("utf8"),a}setItem(e,t){try{this.shouldEncrypt(e)?(this.storage[e]=this.encrypt(t),u.debug(`[SECURE] Stored encrypted: ${e}`)):(this.storage[e]=t,u.debug(`[SECURE] Stored plaintext: ${e}`)),this.saveStorage()}catch(n){u.error(`[SECURE] Failed to set ${e}: ${n.message}`)}}getItem(e){try{let t=this.storage[e];return t===void 0?null:t.startsWith(As)?this.decrypt(t):t}catch(t){return u.error(`[SECURE] Failed to get ${e}: ${t.message}`),null}}removeItem(e){delete this.storage[e],this.saveStorage(),u.debug(`[SECURE] Removed: ${e}`)}hasItem(e){return this.storage[e]!==void 0}getAllKeys(){return Object.keys(this.storage)}clear(){this.storage={},this.saveStorage(),u.debug("[SECURE] Cleared all secure storage")}migrateToEncrypted(){let e=0;for(let t of Object.keys(this.storage)){let n=this.storage[t];this.shouldEncrypt(t)&&!n.startsWith(As)&&(this.storage[t]=this.encrypt(n),e++)}e>0&&(this.saveStorage(),u.debug(`[SECURE] Migrated ${e} values to encrypted storage`))}},Hm=Ir.getInstance()});import Gm from"axios";import{EventEmitter as jm}from"events";var Yt,Pt,Rs=F(()=>{"use strict";Yt="firebase_timestamp",Pt=class i extends jm{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=Gm.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:3e4})}static getInstance(){return i.instance||(i.instance=new i),i.instance}async getAccessToken(){let{UserDefaults:e}=await Promise.resolve().then(()=>(Le(),kt));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(Te(),Bc));return await e.getInstance().getFirebaseIdToken()}async addAuthorizationHeader(e){let t=await this.getFirebaseIdToken();if(t)e.Authorization=`Bearer ${t}`;else{let n=await this.getAccessToken();n&&(e.Authorization=n)}}async createDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let r={collection:e,docId:t,data:n};try{let a=(await this.client.post("/documents",r,{headers:s})).data;if(!a.success){let c=a.error||"Unknown error";throw console.error("❌ [SnowXFirebaseAPI] API returned success=false:",c),new Error(c)}}catch(o){throw console.error("❌ [SnowXFirebaseAPI] createDocument failed:"),console.error("❌ [SnowXFirebaseAPI] Error status:",o.response?.status),console.error("❌ [SnowXFirebaseAPI] Error data:",o.response?.data),console.error("❌ [SnowXFirebaseAPI] Full error:",o),o}}async createConversation(e,t){return this.createDocument("snowx_conversations",e,t)}async updateConversation(e,t){return this.updateDocument("snowx_conversations",e,t)}async getDocuments(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};t&&(s.limit=t.toString());try{let o=(await this.client.get("/documents",{params:s,headers:n})).data;if(o.success)return Array.isArray(o.doc)?o.doc:[];{let a=o.error||"Unknown error";throw new Error(a)}}catch(r){throw r}}async queryDocuments(e,t,n,s,r,o,a){let c={};await this.addAuthorizationHeader(c);let l={collection:e,field:t,operator:n,value:String(s)};r&&(l.limit=r.toString()),o&&(l.orderBy=o),a&&(l.orderDirection=a);try{let g=(await this.client.get("/documents/query",{params:l,headers:c})).data;if(g.success)return Array.isArray(g.doc)?g.doc:g.doc&&typeof g.doc=="object"?[g.doc]:[];{let m=g.error||"Unknown error";throw new Error(m)}}catch(d){throw d}}async getDocument(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let o=(await this.client.get(`/documents/${t}`,{params:s,headers:n})).data;return o.success?o.doc:null}catch(r){throw r}}async updateDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let r={collection:e,data:n};try{let a=(await this.client.patch(`/documents/${t}`,r,{headers:s})).data;if(!a.success){let c=a.error||"Unknown error";throw new Error(c)}}catch(o){throw o}}async deleteDocument(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let o=(await this.client.delete(`/documents/${t}`,{params:s,headers:n})).data;if(!o.success){let a=o.error||"Unknown error";throw new Error(a)}}catch(r){throw r}}async createDocumentInSubcollection(e,t,n,s,r){let o=`${e}/${t}/${n}`;return this.createDocument(o,s,r)}async getUserConversations(e,t){return this.queryDocuments("snowx_conversations","userId","==",e,t,"updatedAt","desc")}async saveConversationMessages(e,t){let n=`snowx_conversations/${e}/messages`;try{let s=await this.getDocuments(n);for(let r of s)r.id&&await this.deleteDocument(n,r.id);for(let[r,o]of t.entries()){if(o.role==="system"||o.isStreaming)continue;let a=`message_${r}_${Date.now()}`,c={id:a,role:o.role,content:o.content,timestamp:o.timestamp||new Date,order:r,conversationId:e};try{await this.createDocument(n,a,c)}catch{}}}catch(s){throw s}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((s,r)=>{if(s.order!==void 0&&r.order!==void 0)return s.order-r.order;let o=new Date(s.timestamp||0).getTime(),a=new Date(r.timestamp||0).getTime();return o-a})}async updateRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,updates:t};try{let o=(await this.client.put("/realtime",s,{headers:n})).data;if(!o.success){let a=o.error||"Unknown error";throw new Error(a)}}catch(r){throw r}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let r=(await this.client.get("/realtime",{params:n,headers:t})).data;if(r.success)return r.doc;{let o=r.error||"Unknown error";throw new Error(o)}}catch(s){throw s}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let r=(await this.client.delete("/realtime",{params:n,headers:t})).data;if(!r.success){let o=r.error||"Unknown error";throw new Error(o)}}catch(s){throw s}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let s=await this.client.get("/realtime",{params:n,headers:t}),r=s.data;if(r.success)return s.data.data;{let o=r.error||"Unknown error";throw new Error(o)}}catch(s){throw s}}async writeRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let o=(await this.client.post("/realtime",s,{headers:n})).data;if(!o.success){let a=o.error||"Unknown error";throw new Error(a)}}catch(r){throw r}}async pushRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let o=(await this.client.post("/realtime/push",s,{headers:n})).data;if(o.success){if(o.key)return o.key;throw new Error("No key returned")}else{let a=o.error||"Unknown error";throw new Error(a)}}catch(r){throw r}}setAuthToken(e){console.warn("⚠️ setAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}clearAuthToken(){console.warn("⚠️ clearAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}}});var xi={};Fe(xi,{DeviceRegistrationService:()=>Pe});import{EventEmitter as zm}from"events";import{v4 as Wc}from"uuid";import Os from"os";import Hc from"fs/promises";import qm from"path";import{execSync as Ns}from"child_process";import Km from"crypto";var Pe,At=F(()=>{"use strict";Rs();Te();j();Pe=class i extends zm{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=Pt.getInstance(),this.authService=X.getInstance(),this.configDir=qm.join(Os.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return i.instance||(i.instance=new i),i.instance}setupAuthenticationListener(){u.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{u.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{u.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();u.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(u.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){u.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),u.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(u.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,u.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),u.debug(`[DeviceRegistration] ✅ Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw u.debug("[DeviceRegistration] ❌ FAILED to get device ID:",t.message),t}u.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),u.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){u.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return u.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){try{let e=Os.platform();if(e==="darwin")try{let s=Ns("scutil --get ComputerName",{encoding:"utf8"}).trim();if(s)return u.debug(`[DEVICE REG] macOS ComputerName: ${s}`),s}catch{u.debug("[DEVICE REG] Failed to get ComputerName via scutil, using hostname")}else if(e==="win32")try{let s=Ns('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName" /v ComputerName',{encoding:"utf8"}).match(/ComputerName\s+REG_SZ\s+(.+)/i);if(s&&s[1]){let r=s[1].trim();if(r)return u.debug(`[DEVICE REG] Windows ComputerName: ${r}`),r}}catch{u.debug("[DEVICE REG] Failed to get ComputerName from registry, using hostname")}let t=Os.hostname();return u.debug(`[DEVICE REG] Using hostname: ${t}`),t||"Unknown CLI Device"}catch(e){return u.debug(`[DEVICE REG] Error getting computer name: ${e}`),Os.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=Os.platform();try{let t=null;switch(e){case"darwin":try{let a=Ns("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],u.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{u.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let c=Ns("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);c&&c[1]&&(t=c[1],u.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{u.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await Hc.readFile("/etc/machine-id","utf-8").then(o=>o.trim()),u.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await Hc.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),u.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{u.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=Ns("wmic csproduct get UUID",{encoding:"utf8"}).split(`
3
- `).filter(c=>c.trim()&&c.trim()!=="UUID");a.length>0&&(t=a[0].trim(),u.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{u.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:u.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let o=Km.createHash("sha256").update(t).digest("hex"),a=[o.substring(0,8),o.substring(8,12),o.substring(12,16),o.substring(16,20),o.substring(20,32)].join("-");return u.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:n}=await Promise.resolve().then(()=>(Le(),kt)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${r}`):(r=Wc(),n.set(s,r),u.debug(`[DEVICE REG] Generated NEW fallback UUID: ${r}`)),r}catch(t){u.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:n}=await Promise.resolve().then(()=>(Le(),kt)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${r}`):(r=Wc(),n.set(s,r),u.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${r}`)),r}}async registerDevice(e,t,n){if(this.isRegistering)return this.registrationPromise||Promise.resolve();this.isRegistering=!0,this.registrationPromise=this.performRegistration(e,t,n);try{await this.registrationPromise}finally{this.isRegistering=!1,this.registrationPromise=null}}async performRegistration(e,t,n){try{let s=await this.api.getDocument(this.devicesCollection,e);if(s&&s.devices){let r=s.devices;if(r.some(a=>a.deviceId===t)){let a=r.map(c=>c.deviceId===t?{...c,lastSeenAt:Yt,computerName:n,type:"on-device"}:c);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:Yt,lastSeenAt:Yt};r.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:r})}}else{let o={userId:e,devices:[{deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:Yt,lastSeenAt:Yt}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,o)}u.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:n})}catch(s){throw u.error("[DeviceRegistration] Failed to register device:",{userId:e,deviceId:t,error:s.message,code:s.code}),s}}getCurrentDeviceId(){return this.currentDeviceId}getCurrentUserId(){return this.currentUserId}getCurrentDeviceInfo(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,computerName:this.getComputerName()}}async refreshDeviceRegistration(){this.currentUserId&&this.currentDeviceId&&await this.autoRegisterDevice(this.currentUserId)}async removeDeviceRegistration(e){try{let t=await this.getUserDeviceId(e);if(!t||t.trim()===""){console.log("⚠️ [DEVICE REG] No device ID found, skipping device removal");return}let n=await this.api.getDocument(this.devicesCollection,e);if(!n||!n.devices||!Array.isArray(n.devices)){console.log("⚠️ [DEVICE REG] No devices document found for user");return}let s=n.devices;if(!s.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let o=s.filter(a=>a.deviceId!==t);o.length===0?await this.api.deleteDocument(this.devicesCollection,e):await this.api.updateDocument(this.devicesCollection,e,{devices:o})}catch(t){console.error(`❌ [DEVICE REG] Failed to remove device registration: ${t.message}`)}}async getUserDeviceId(e){return this.currentDeviceId?this.currentDeviceId:await this.getHardwareDeviceId()}}});var Bc={};Fe(Bc,{AuthService:()=>X});import{EventEmitter as Vm}from"events";import{signInAnonymously as Xm,signInWithEmailAndPassword as Ym,createUserWithEmailAndPassword as Qm,signOut as Jm,onAuthStateChanged as Gc,updateProfile as Zm,signInWithCustomToken as ep}from"firebase/auth";import Qt from"axios";import Ci from"fs/promises";import jc from"path";import tp from"os";function zc(i,e,t){return Promise.race([i,new Promise((n,s)=>setTimeout(()=>s(new Error(t)),e))])}var X,Te=F(()=>{"use strict";wn();j();Fc();X=class i extends Vm{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=jc.join(tp.homedir(),".orion-cli","auth.json")}static getInstance(){return i.instance||(i.instance=new i),i.instance}async initializeTokenFile(){try{let e=jc.dirname(this.tokenFilePath);await Ci.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{secureStorage:e}=await Promise.resolve().then(()=>(Ms(),Ds)),{UserDefaults:t}=await Promise.resolve().then(()=>(Le(),kt)),n=e.getItem("snowx_auth_token"),s=e.getItem("snowx_access_token");if((!n||!s)&&(n=t.string("snowx_auth_token"),s=t.string("snowx_access_token"),n&&s&&(u.debug("Migrating tokens from UserDefaults to secure storage..."),e.setItem("snowx_auth_token",n),e.setItem("snowx_access_token",s),t.remove("snowx_auth_token"),t.remove("snowx_access_token"),u.debug("Token migration to secure storage completed"))),!n||!s)try{let r=await Ci.readFile(this.tokenFilePath,"utf-8"),o=JSON.parse(r);o.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to secure storage..."),e.setItem("snowx_auth_token",o.userId),e.setItem("snowx_access_token",o.token),n=o.userId,s=o.token,await Ci.unlink(this.tokenFilePath),console.log("✅ Migration completed - old auth file removed"))}catch{}if(n&&s){let r={token:s,userId:n,email:void 0,tier:0,expiresAt:Date.now()+2592e6};this.authToken=r,u.debug("Session restored from UserDefaults");try{let o=await this.getUserProfile();o&&o.tier!==void 0?this.authToken.tier=o.tier:await this.updateUserTierFromToken(r)}catch(o){console.warn("⚠️ Failed to fetch user profile during session restore:",o instanceof Error?o.message:"Unknown error"),await this.updateUserTierFromToken(r)}this.emit("authenticated",r)}}catch(e){console.warn("⚠️ Failed to load stored session:",e)}}async saveToken(e){try{let{secureStorage:t}=await Promise.resolve().then(()=>(Ms(),Ds));t.setItem("snowx_auth_token",e.userId),t.setItem("snowx_access_token",e.token);let{UserDefaults:n}=await Promise.resolve().then(()=>(Le(),kt));n.set("snowx_user_tier",e.tier||0),this.authToken=e,this.emit("authenticated",e);let s=e.tier===2?"pro":e.tier===1?"plus":"free";wi.setUser(e.userId,e.email,s)}catch(t){console.error("❌ Failed to save auth token:",t)}}async clearStoredToken(){try{let{secureStorage:e}=await Promise.resolve().then(()=>(Ms(),Ds)),{UserDefaults:t}=await Promise.resolve().then(()=>(Le(),kt));e.removeItem("snowx_auth_token"),e.removeItem("snowx_access_token"),t.remove("snowx_auth_token"),t.remove("snowx_access_token"),this.authToken=null,wi.clearUser()}catch(e){console.error("❌ Failed to clear auth token:",e)}}setFirebaseAuth(e){this.auth=e,Gc(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}xe.setUserTier(t);let{UserDefaults:n}=await Promise.resolve().then(()=>(Le(),kt));n.set("userSubscriptionTier",e.tier||0),n.set("isTrialUser",!1),u.debug(`User tier updated: ${xe.getDisplayName(t)} (${e.tier})`),u.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let e=await Xm(this.auth);this.currentUser=e.user;let t={token:`anonymous_${e.user.uid}`,userId:e.user.uid,tier:0,expiresAt:Date.now()+1440*60*1e3};return await this.saveToken(t),this.updateUserTierFromToken(t),!0}catch(e){return console.error("❌ Failed to sign in anonymously:",e),!1}}async signInWithEmail(e,t){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let n=await Ym(this.auth,e,t);return this.currentUser=n.user,!0}catch(n){return console.error("❌ Failed to sign in with email:",n.message),!1}}async signUpWithEmail(e,t,n){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let s=await Qm(this.auth,e,t);return this.currentUser=s.user,n&&await Zm(s.user,{displayName:n}),!0}catch(s){return console.error("❌ Failed to sign up with email:",s.message),!1}}async signOut(){try{let e=this.getUserId();if(e)try{let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(At(),xi));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Jm(this.auth)}catch(t){console.warn("⚠️ [AUTH] Firebase sign out error:",t)}return this.currentUser=null,this.authToken=null,await this.clearStoredToken(),await this.clearAllSnowXUserDefaults(e),this.emit("signed_out"),!0}catch(e){return console.error("❌ [AUTH] Failed to sign out:",e),!1}}async getCurrentDeviceId(){if(!this.getUserId())return null;let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(At(),xi));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(Le(),kt)),n=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let o of n)t.remove(o);if(e){let o=`snowx_device_id_${e}`;t.remove(o)}let r=t.getAllKeys().filter(o=>o.startsWith("snowx_device_id_"));for(let o of r)t.remove(o)}catch(t){console.warn("⚠️ [AUTH] Failed to clear some user preferences:",t)}}async authenticateWithSnowX(e){try{let t;if(e?t=await Qt.post(`${this.snowxAuthEndpoint}/login`,e):t=await Qt.post(`${this.snowxAuthEndpoint}/guest`),t.data?.token){let n={token:t.data.token,userId:t.data.userId||"anonymous",email:t.data.email,tier:t.data.tier??0,expiresAt:Date.now()+(t.data.expiresIn||86400)*1e3};return await this.saveToken(n),!0}return!1}catch(t){return console.error("❌ Failed to authenticate with Orion:",t.response?.data?.message||t.message),!1}}async refreshToken(){if(!this.authToken)return!1;try{let e=await Qt.post(`${this.snowxAuthEndpoint}/refresh`,{token:this.authToken.token});if(e.data?.token){let t={...this.authToken,token:e.data.token,expiresAt:Date.now()+(e.data.expiresIn||86400)*1e3};return await this.saveToken(t),!0}return!1}catch(e){return console.warn("⚠️ Failed to refresh token:",e),!1}}getCurrentUser(){return this.currentUser}getAuthToken(){return this.authToken}getAccessToken(){return this.authToken?.token||null}async getAccessTokenFromStorage(){let{secureStorage:e}=await Promise.resolve().then(()=>(Ms(),Ds)),t=e.getItem("snowx_access_token");if(t)return t;let{UserDefaults:n}=await Promise.resolve().then(()=>(Le(),kt));return n.string("snowx_access_token")}async getFirebaseIdToken(){if(this.currentUser)try{return await this.currentUser.getIdToken(!0)}catch(t){console.error("❌ Failed to get Firebase ID token:",t)}if(this.auth){let n=await new Promise(s=>{let r=!1,o,a=Gc(this.auth,async c=>{if(!r)if(r=!0,clearTimeout(o),a(),c)try{let l=await c.getIdToken(!0);s(l)}catch{s(null)}else s(null)});o=setTimeout(()=>{r||(r=!0,a(),s(null))},2e3)});if(n)return n}let e=await this.getAccessTokenFromStorage();return e?(u.debug("Using stored access token as fallback (Firebase SDK not signed in)"),e):null}getUserId(){return this.authToken?.userId||this.currentUser?.uid||null}getUserEmail(){return this.authToken?.email||this.currentUser?.email||null}async getUserTier(){if(this.authToken?.tier!==void 0)return this.authToken.tier;try{return(await this.getUserProfile())?.tier??0}catch{return console.warn("⚠️ Failed to fetch user tier, defaulting to Free tier"),0}}getCachedUserTier(){return this.authToken?.tier??0}isAuthenticated(){return!!this.authToken&&this.authToken.expiresAt>Date.now()}isFirebaseAuthenticated(){if(this.currentUser)return!0;if(this.authToken?.token&&this.isFirebaseIdToken(this.authToken.token)){let e=this.parseFirebaseIdToken(this.authToken.token);if(e&&Date.now()<=e.exp*1e3)return!0}return!1}async autoAuthenticate(){if(await this.initializeTokenFile(),this.isAuthenticated()){let e=this.getUserId(),t=this.authToken?.token;if(e&&t){u.debug("Using existing authentication token"),u.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e);try{if(this.isFirebaseIdToken(t)){let n=this.parseFirebaseIdToken(t);return n&&Date.now()<=n.exp*1e3?(u.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(u.error("Firebase ID Token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}return await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}catch(n){return u.error("Failed to authenticate with Firebase during auto-authenticate:",n.message),n.response?.status===401||n.response?.status===403||n.response?.status===404?(u.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):u.warn("Transient Firebase auth error - keeping stored token for retry"),!1}}}return!1}async authenticateFirebaseWithStoredToken(){if(console.log("🔥 [AUTH] Starting Firebase authentication..."),!this.auth)throw console.error("❌ [AUTH] Firebase Auth not initialized!"),u.error("Firebase Auth not initialized - cannot authenticate"),new Error("Firebase Auth not initialized. Please ensure ServiceManager is initialized first.");if(console.log("✅ [AUTH] Firebase Auth instance is available"),!this.authToken)throw console.error("❌ [AUTH] No auth token available!"),u.error("No auth token available - cannot authenticate with Firebase"),new Error("No authentication token available");if(console.log("✅ [AUTH] Auth token is available"),console.log(`📋 [AUTH] User ID: ${this.authToken.userId}`),this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log(`✅ [AUTH] Firebase already authenticated for user: ${this.authToken.userId}`),u.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),u.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await zc(this.getCustomTokenFromAPIInternal(this.authToken.userId),3e4,"getCustomToken timeout during authentication");console.log("✅ [AUTH] Custom token received from API"),console.log("🔐 [AUTH] Signing into Firebase with custom token..."),u.debug("Signing into Firebase with custom token...");let t=await zc(ep(this.auth,e),1e4,"Firebase signin timeout during authentication");console.log(`✅ [AUTH] Firebase sign-in successful - UID: ${t.user.uid}`),u.debug(`Firebase Auth successful - UID: ${t.user.uid}`),this.currentUser=t.user,console.log("✅ Firebase authentication successful")}catch(e){throw console.error("❌ [AUTH] Firebase authentication FAILED!"),console.error(`❌ [AUTH] Error details: ${e.message}`),console.error(`❌ [AUTH] Error code: ${e.code||"none"}`),console.error(`❌ [AUTH] HTTP status: ${e.response?.status||"none"}`),u.error("Firebase authentication failed:",{userId:this.authToken.userId,errorMessage:e.message,errorCode:e.code,errorStatus:e.response?.status,errorData:e.response?.data}),new Error(`Firebase authentication failed: ${e.message}`)}}async getCustomTokenFromAPIInternal(e,t=3){let n=4-t;console.log(`📡 [AUTH-API] Attempt ${n}/3: Getting custom token for user: ${e}`),u.debug(`Getting custom token from API for user: ${e} (attempt ${n}/3)`);let s="https://snowx.ai/api-beta/api/fb/custom-token",r={userId:e},o=this.authToken?.token,a={"Content-Type":"application/json"};o?(a.Authorization=`Bearer ${o}`,console.log("📋 [AUTH-API] Access token added to request headers")):console.warn("⚠️ [AUTH-API] No access token available for authorization"),console.log(`📡 [AUTH-API] Sending POST to: ${s}`);try{let c=await Qt.post(s,r,{headers:a,timeout:15e3});if(console.log(`✅ [AUTH-API] Received response with status: ${c.status}`),c.status!==200){let d=c.data?.message||`HTTP ${c.status}`;throw console.error(`❌ [AUTH-API] API returned non-200 status: ${d}`),new Error(`Custom token API failed: ${d}`)}let l=c.data;if(!l?.success||!l?.customToken)throw console.error("❌ [AUTH-API] API response missing success/customToken fields"),console.error("❌ [AUTH-API] Response data:",JSON.stringify(l)),new Error("Invalid custom token response from API");return console.log("✅ [AUTH-API] Custom token successfully received"),u.debug("Successfully received custom token from SnowX API"),l.customToken}catch(c){if(console.error(`❌ [AUTH-API] Request failed on attempt ${n}/3`),console.error(`❌ [AUTH-API] Error message: ${c.message}`),console.error(`❌ [AUTH-API] Error code: ${c.code||"none"}`),console.error(`❌ [AUTH-API] HTTP status: ${c.response?.status||"none"}`),c.response?.data&&console.error(`❌ [AUTH-API] Response data: ${JSON.stringify(c.response.data)}`),u.error("Failed to get custom token:",{attempt:n,error:c.message,code:c.code,status:c.response?.status,responseData:c.response?.data}),t>0&&(c.code==="ECONNABORTED"||c.code==="ETIMEDOUT"||c.code==="ECONNREFUSED"||c.code==="ENOTFOUND"||c.response?.status>=500&&c.response?.status<600)){let d=Math.pow(2,n)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${d}ms... (${t-1} attempts remaining)`),u.debug(`Retrying in ${d}ms...`),await new Promise(g=>setTimeout(g,d)),this.getCustomTokenFromAPIInternal(e,t-1)}throw console.error("❌ [AUTH-API] All retry attempts exhausted or non-retryable error"),c}}isFirebaseIdToken(e){try{let t=e.split(".");return t.length!==3?!1:JSON.parse(Buffer.from(t[1],"base64url").toString()).iss?.includes("securetoken.google.com")}catch{return!1}}parseFirebaseIdToken(e){try{let t=e.split(".");if(t.length!==3)return null;let n=JSON.parse(Buffer.from(t[1],"base64url").toString());return{userId:n.user_id||n.sub,email:n.email,name:n.name,exp:n.exp}}catch{return null}}async authenticateWithAccessToken(e){try{return this.isFirebaseIdToken(e)?await this.authenticateWithFirebaseIdToken(e):await this.authenticateWithSnowXAccessToken(e)}catch(t){return console.error("❌ Failed to authenticate with access token:",t.response?.data?.message||t.message),console.error("Full error details:",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,url:t.config?.url}),!1}}async authenticateWithFirebaseIdToken(e){console.log("🔥 Detected Firebase ID Token, using direct authentication...");let t=this.parseFirebaseIdToken(e);if(!t)return console.error("❌ Failed to parse Firebase ID Token"),!1;if(Date.now()>t.exp*1e3)return console.error("❌ Firebase ID Token has expired"),!1;console.log(`📋 User ID from token: ${t.userId}`),console.log(`📋 Email from token: ${t.email||"N/A"}`);let n={token:e,userId:t.userId,email:t.email,tier:0,expiresAt:t.exp*1e3};await this.saveToken(n);try{let s=await this.getUserProfileWithIdToken(e,t.userId);s&&(this.authToken.tier=s.tier,await this.saveToken(this.authToken))}catch{console.warn("⚠️ Failed to fetch user profile, using default tier")}return this.userProfile={name:t.name,email:t.email},await this.updateUserTierFromToken(this.authToken),this.emit("authStateChanged",this.authToken),this.emit("AuthenticationComplete",t.userId),console.log("✅ Firebase ID Token authentication successful!"),!0}async getUserProfileWithIdToken(e,t){try{let n=await Qt.get(`https://snowx.ai/api-beta/api/fb/documents/${t}?collection=users`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(n.data?.success&&n.data?.doc){let s=n.data.doc,r=s.subscription?.tier??0;return{id:t,email:s.email,tier:r}}return null}catch(n){return console.warn(`⚠️ Failed to fetch user profile with ID Token: ${n.response?.status||n.message}`),null}}async authenticateWithSnowXAccessToken(e){let t=await Qt.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(t.data?.data){let n=t.data.data,s=n.id||n.uid||n.user_id||n.userId||n.email;if(!s)throw new Error("No user ID found in API response");let r={token:e,userId:s,email:n.email,tier:n.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(r),this.userProfile=n,await this.updateUserTierFromToken(r);try{await this.authenticateFirebaseWithStoredToken()}catch(o){throw o.response?.status===401||o.response?.status===403||o.response?.status===404?(u.error("Firebase auth failed with permanent error - clearing token"),await this.clearStoredToken(),this.authToken=null,this.userProfile=null):u.warn("Firebase auth failed with transient error - keeping token for retry"),o}return this.emit("authStateChanged",r),this.emit("AuthenticationComplete",s),!0}return!1}async getUserInfo(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available"),null;try{let e=await Qt.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});return e.data?.data?(this.userProfile=e.data.data,this.userProfile):null}catch(e){throw e.response?.status===401&&(console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),n=t===1?1:t===2?2:0;return xe.isModelAccessible(e,n)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available for profile fetch"),null;try{let e=await Qt.get(`https://snowx.ai/api-beta/api/fb/documents/${this.authToken.userId}?collection=users`,{headers:{Authorization:`${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});if(e.data?.success&&e.data?.doc){let t=e.data.doc,n=t.subscription?.tier??0;return this.authToken.email=t.email,this.authToken.tier=n,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),{id:this.authToken.userId,email:t.email,tier:n}}return console.warn("⚠️ Empty response from profile API"),null}catch(e){return console.warn(`⚠️ Failed to fetch user profile: ${e.response?.status||e.message}`),this.authToken.tier=0,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),null}}async hasUserProfile(){return await this.getUserProfile()!==null}}});import{EventEmitter as np}from"events";import sp from"crypto";var ct,zn=F(()=>{"use strict";j();ct=class i extends np{static instance;queuedMessages=[];isProcessingQueue=!1;maxQueueSize=5;constructor(){super()}static getInstance(){return i.instance||(i.instance=new i),i.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),u.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),u.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 sp.randomUUID()}}});import{encode as Kc,decode as Vc,isWithinTokenLimit as Xc,countTokens as rp}from"gpt-tokenizer/encoding/cl100k_base";var qn,op,ip,lt,Kn=F(()=>{"use strict";qn=25e3,op=1400,ip=17e3,lt=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??qn,this.previewTokens=e?.previewTokens??op,this.maxContentTokens=e?.maxContentTokens??ip}count(e){return e?rp(e):0}encode(e){return e?Kc(e):[]}decode(e){return!e||e.length===0?"":Vc(e)}isWithinLimit(e,t){return e?Xc(e,t??this.maxResponseTokens):0}exceedsResponseLimit(e){return this.isWithinLimit(e,this.maxResponseTokens)===!1}exceedsContentLimit(e){return this.isWithinLimit(e,this.maxContentTokens)===!1}truncate(e,t){if(!e)return{text:"",tokens:0,truncated:!1};let n=t??this.maxResponseTokens,s=Xc(e,n);if(s!==!1)return{text:e,tokens:s,truncated:!1};let o=Kc(e).slice(0,n);return{text:Vc(o),tokens:n,truncated:!0}}generatePreview(e,t){if(!e)return{preview:"",totalTokens:0,previewTokens:0,remainingTokens:0};let n=t??this.previewTokens,s=this.count(e);if(s<=n)return{preview:e,totalTokens:s,previewTokens:s,remainingTokens:0};let{text:r,tokens:o}=this.truncate(e,n);return{preview:r,totalTokens:s,previewTokens:o,remainingTokens:s-o}}truncateContent(e,t){let n=t??this.maxContentTokens,s=this.truncate(e,n);return s.truncated?s.text+`
2
+ var Om=Object.defineProperty;var $=(i,e)=>()=>(i&&(e=i(i=0)),e);var Le=(i,e)=>{for(var t in e)Om(i,t,{get:e[t],enumerable:!0})};var pe,Xt=$(()=>{"use strict";pe=[{name:"snowx-o4.6",displayName:"Claude Opus 4.6",provider:"ANTHROPIC",apiModelName:"claude-opus-4-6",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:2.5},{name:"snowx-c6",displayName:"Claude Sonnet 4.6",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-6",maxTokens:64e3,contextWindow:1e6,supportsVision:!0,creditMultiplier:1.25},{name:"snowx-o4.5",displayName:"Claude Opus 4.5",provider:"ANTHROPIC",apiModelName:"claude-opus-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:1.5},{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:1},{name:"snowx-c3",displayName:"Claude 4 Sonnet",provider:"ANTHROPIC",apiModelName:"claude-4-sonnet-20250514",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:1},{name:"snowx-c1",displayName:"Claude 3.7 Sonnet",provider:"BEDROCK",apiModelName:"us.anthropic.claude-3-7-sonnet-20250219-v1:0",maxTokens:4096,contextWindow:2e5,supportsVision:!0,creditMultiplier:1},{name:"snowx-h4",displayName:"Claude Haiku 4.5",provider:"ANTHROPIC",apiModelName:"claude-3-5-haiku-20241022",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:.5},{name:"snowx-5.2",displayName:"GPT-5.2 High",provider:"GPT",apiModelName:"gpt-5.2-high",maxTokens:32768,contextWindow:1047576,supportsVision:!0,creditMultiplier:1},{name:"snowx-5.2-chat",displayName:"GPT-5.2",provider:"GPT",apiModelName:"gpt-5.2",maxTokens:32768,contextWindow:1047576,supportsVision:!0,creditMultiplier:.5},{name:"snowx-4.1",displayName:"GPT-4.1",provider:"GPT",apiModelName:"gpt-4.1",maxTokens:4096,contextWindow:128e3,supportsVision:!0,creditMultiplier:.5},{name:"snowx-g6",displayName:"Gemini 3.1 Pro",provider:"google",apiModelName:"gemini-3.1-pro-preview",maxTokens:65536,contextWindow:1048576,supportsVision:!0,creditMultiplier:1.25},{name:"snowx-g4",displayName:"Gemini 3 Pro",provider:"google",apiModelName:"gemini-3-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0,creditMultiplier:1},{name:"snowx-g5",displayName:"Gemini 3 Flash",provider:"google",apiModelName:"gemini-3-flash",maxTokens:8192,contextWindow:1e6,supportsVision:!0,creditMultiplier:.5},{name:"snowx-g1",displayName:"Gemini 2.5 Pro",provider:"google",apiModelName:"gemini-2.5-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0,creditMultiplier:1}]});var bi,u,z=$(()=>{"use strict";bi=class i{static instance;logLevel=0;debugMode=!1;static getInstance(){return i.instance||(i.instance=new i),i.instance}setLogLevel(e){this.logLevel=e}setDebugMode(e){this.debugMode=e}getDebugMode(){return this.debugMode}error(e,...t){this.logLevel>=0&&console.error(`❌ ${e}`,...t)}warn(e,...t){this.logLevel>=1&&console.warn(`⚠️ ${e}`,...t)}info(e,...t){this.logLevel>=2&&console.log(`ℹ️ ${e}`,...t)}success(e,...t){this.logLevel>=2&&console.log(`✅ ${e}`,...t)}debug(e,...t){this.debugMode&&this.logLevel>=3&&console.log(`🔍 [DEBUG] ${e}`,...t)}status(e,...t){console.log(e,...t)}system(e){console.log(e)}},u=bi.getInstance()});var kt={};Le(kt,{UserDefaults:()=>de});import ks from"fs";import yi from"path";import $m from"os";var vi,de,Ue=$(()=>{"use strict";z();vi=class i{static instance;preferencesPath;preferences={};constructor(){let e=yi.join($m.homedir(),".orion");this.preferencesPath=yi.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadPreferences(){try{if(ks.existsSync(this.preferencesPath)){let e=ks.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),u.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{u.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=yi.dirname(this.preferencesPath);ks.existsSync(e)||ks.mkdirSync(e,{recursive:!0}),ks.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),u.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){u.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),u.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(),u.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},de=vi.getInstance()});var Ce,xn=$(()=>{"use strict";Xt();Ue();z();Ce=class{static getDisplayName(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";case 3:return"Max";default:return"Free"}}static plusOnlyModels=[];static proOnlyModels=["snowx-o4.5","snowx-c6","snowx-5-pro"];static maxOnlyModels=["snowx-o4.6"];static getRequiredTier(e){return this.maxOnlyModels.includes(e)?3:this.proOnlyModels.includes(e)?2:this.plusOnlyModels.includes(e)?1:0}static getCurrentUserTier(){let e=de.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=3?e:0}static setUserTier(e){de.set("userSubscriptionTier",e),u.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){if(this.maxOnlyModels.includes(e)){let n=t===3;return u.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=MAX (exclusive), Access=${n}`),n}if(t===3)return u.debug(`Access check for ${e}: User tier=MAX (no limits), Access=true`),!0;if(this.proOnlyModels.includes(e)){let n=t===2;return u.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=PRO, Access=${n}`),n}if(t===2)return u.debug(`Access check for ${e}: User tier=PRO, Access=true`),!0;if(this.plusOnlyModels.includes(e)){let n=t>=1;return u.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=PLUS, Access=${n}`),n}return u.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=FREE, Access=true`),!0}static isModelAccessibleForCurrentUser(e){let t=this.getCurrentUserTier();return this.isModelAccessible(e,t)}static getAccessibleModels(e){return pe.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.";case 3:return"This model requires a Max subscription. Please upgrade to access.";default:return"This model is not available with your current subscription."}}static getModelDisplayNameWithTier(e){return e.displayName}}});import*as Ee from"@sentry/node";var Si,wi,Fc=$(()=>{"use strict";z();Si=class i{static instance;isEnabled=!0;userId=null;userEmail=null;deviceId=null;constructor(){this.isEnabled=process.env.ORION_DISABLE_TELEMETRY!=="true"}static getInstance(){return i.instance||(i.instance=new i),i.instance}setUser(e,t,n){this.userId=e,this.userEmail=t||null,this.isEnabled&&Ee.setUser({id:e,email:t,subscription:n})}setDevice(e){this.deviceId=e,this.isEnabled&&Ee.setTag("device_id",e)}clearUser(){this.userId=null,this.userEmail=null,this.isEnabled&&Ee.setUser(null)}captureException(e,t){if(!this.isEnabled)return u.debug("[SENTRY] Telemetry disabled, skipping error capture"),null;if(e instanceof Error){let n=e.message.toLowerCase();if(n.includes("[done]")||n.includes("stream ended"))return null}return Ee.withScope(n=>{if(t?.tags)for(let[r,o]of Object.entries(t.tags))n.setTag(r,o);t?.sessionId&&n.setTag("session_id",t.sessionId),t?.conversationId&&n.setTag("conversation_id",t.conversationId),t?.toolName&&n.setTag("tool_name",t.toolName),t?.endpoint&&n.setTag("endpoint",t.endpoint),t?.extra&&n.setExtras(t.extra),t?.toolArgs&&n.setExtra("tool_args",t.toolArgs);let s=Ee.captureException(e);return u.debug(`[SENTRY] Captured exception: ${s}`),s})}captureMessage(e,t="info",n){return this.isEnabled?Ee.withScope(s=>{if(n?.tags)for(let[o,a]of Object.entries(n.tags))s.setTag(o,a);n?.extra&&s.setExtras(n.extra);let r=Ee.captureMessage(e,t);return u.debug(`[SENTRY] Captured message: ${r}`),r}):null}addBreadcrumb(e,t,n,s="info"){this.isEnabled&&Ee.addBreadcrumb({message:e,category:t,data:n,level:s,timestamp:Date.now()/1e3})}trackApiCall(e,t,n){this.addBreadcrumb(`${t} ${e}`,"api_call",{endpoint:e,method:t,statusCode:n})}trackToolExecution(e,t,n){this.addBreadcrumb(`Tool: ${e} - ${t?"success":"failed"}`,"tool_execution",{toolName:e,success:t,duration:n},t?"info":"warning")}trackUserAction(e,t){this.addBreadcrumb(e,"user_action",t)}trackNavigation(e,t){this.addBreadcrumb(`${e} -> ${t}`,"navigation",{from:e,to:t})}setTag(e,t){this.isEnabled&&Ee.setTag(e,t)}setExtra(e,t){this.isEnabled&&Ee.setExtra(e,t)}startTransaction(e,t){return this.isEnabled?Ee.startInactiveSpan({name:e,op:t}):null}},wi=Si.getInstance()});var Ms={};Le(Ms,{SecureStorageService:()=>kr,secureStorage:()=>Hm});import Ps from"crypto";import Yt from"os";import Cn from"fs";import Ti from"path";import{execSync as Fm}from"child_process";var Lc,As,Uc,Lm,Um,Bm,Ds,Wm,kr,Hm,Rs=$(()=>{"use strict";z();Lc="aes-256-gcm",As=16,Uc=16,Lm=32,Um=32,Bm=1e5,Ds="__enc__",Wm=["snowx_auth_token","snowx_access_token","snowx_user_data","snowx_device_id","orion_device_id","firebase_custom_token"],kr=class i{static instance;storagePath;storage={};encryptionKey=null;salt=null;isProduction;constructor(){let e=Ti.join(Yt.homedir(),".orion-cli");this.storagePath=Ti.join(e,"secure-storage.json"),this.isProduction=!0,this.loadStorage(),this.initializeEncryption()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadStorage(){try{if(Cn.existsSync(this.storagePath)){let e=Cn.readFileSync(this.storagePath,"utf8"),t=JSON.parse(e);this.storage=t.data||{},this.salt=t.salt?Buffer.from(t.salt,"base64"):null,u.debug("[SECURE] Loaded secure storage")}}catch{u.debug("[SECURE] Failed to load secure storage, starting fresh"),this.storage={}}}saveStorage(){try{let e=Ti.dirname(this.storagePath);Cn.existsSync(e)||Cn.mkdirSync(e,{recursive:!0});let t={data:this.storage,salt:this.salt?.toString("base64")};Cn.writeFileSync(this.storagePath,JSON.stringify(t,null,2),{mode:384}),u.debug("[SECURE] Saved secure storage")}catch(e){u.debug(`[SECURE] Failed to save: ${e.message}`)}}initializeEncryption(){this.salt||(this.salt=Ps.randomBytes(Lm));let e=this.generateDeviceSeed();this.encryptionKey=Ps.pbkdf2Sync(e,this.salt,Bm,Um,"sha256"),u.debug("[SECURE] Encryption initialized")}generateDeviceSeed(){return[Yt.hostname(),Yt.platform(),Yt.arch(),Yt.cpus()[0]?.model||"unknown-cpu",Yt.userInfo().username,this.getMachineId()].join("|")}getMachineId(){try{if(process.platform==="linux"&&Cn.existsSync("/etc/machine-id"))return Cn.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let t=Fm("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID" = "([^"]+)"/);if(t)return t[1]}}catch{}return Yt.hostname()+Yt.userInfo().uid}shouldEncrypt(e){return!this.isProduction&&process.env.ORION_SKIP_ENCRYPTION==="true"?!1:Wm.some(t=>e.includes(t))}encrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");let t=Ps.randomBytes(As),n=Ps.createCipheriv(Lc,this.encryptionKey,t),s=n.update(e,"utf8","base64");s+=n.final("base64");let r=n.getAuthTag(),o=Buffer.concat([t,r,Buffer.from(s,"base64")]);return Ds+o.toString("base64")}decrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");if(!e.startsWith(Ds))return e;let t=Buffer.from(e.slice(Ds.length),"base64"),n=t.subarray(0,As),s=t.subarray(As,As+Uc),r=t.subarray(As+Uc),o=Ps.createDecipheriv(Lc,this.encryptionKey,n);o.setAuthTag(s);let a=o.update(r.toString("base64"),"base64","utf8");return a+=o.final("utf8"),a}setItem(e,t){try{this.shouldEncrypt(e)?(this.storage[e]=this.encrypt(t),u.debug(`[SECURE] Stored encrypted: ${e}`)):(this.storage[e]=t,u.debug(`[SECURE] Stored plaintext: ${e}`)),this.saveStorage()}catch(n){u.error(`[SECURE] Failed to set ${e}: ${n.message}`)}}getItem(e){try{let t=this.storage[e];return t===void 0?null:t.startsWith(Ds)?this.decrypt(t):t}catch(t){return u.error(`[SECURE] Failed to get ${e}: ${t.message}`),null}}removeItem(e){delete this.storage[e],this.saveStorage(),u.debug(`[SECURE] Removed: ${e}`)}hasItem(e){return this.storage[e]!==void 0}getAllKeys(){return Object.keys(this.storage)}clear(){this.storage={},this.saveStorage(),u.debug("[SECURE] Cleared all secure storage")}migrateToEncrypted(){let e=0;for(let t of Object.keys(this.storage)){let n=this.storage[t];this.shouldEncrypt(t)&&!n.startsWith(Ds)&&(this.storage[t]=this.encrypt(n),e++)}e>0&&(this.saveStorage(),u.debug(`[SECURE] Migrated ${e} values to encrypted storage`))}},Hm=kr.getInstance()});import Gm from"axios";import{EventEmitter as jm}from"events";var Qt,Pt,Os=$(()=>{"use strict";Qt="firebase_timestamp",Pt=class i extends jm{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=Gm.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:3e4})}static getInstance(){return i.instance||(i.instance=new i),i.instance}async getAccessToken(){let{UserDefaults:e}=await Promise.resolve().then(()=>(Ue(),kt));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(xe(),Bc));return await e.getInstance().getFirebaseIdToken()}async addAuthorizationHeader(e){let t=await this.getFirebaseIdToken();if(t)e.Authorization=`Bearer ${t}`;else{let n=await this.getAccessToken();n&&(e.Authorization=n)}}async createDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let r={collection:e,docId:t,data:n};try{let a=(await this.client.post("/documents",r,{headers:s})).data;if(!a.success){let c=a.error||"Unknown error";throw console.error("❌ [SnowXFirebaseAPI] API returned success=false:",c),new Error(c)}}catch(o){throw console.error("❌ [SnowXFirebaseAPI] createDocument failed:"),console.error("❌ [SnowXFirebaseAPI] Error status:",o.response?.status),console.error("❌ [SnowXFirebaseAPI] Error data:",o.response?.data),console.error("❌ [SnowXFirebaseAPI] Full error:",o),o}}async createConversation(e,t){return this.createDocument("snowx_conversations",e,t)}async updateConversation(e,t){return this.updateDocument("snowx_conversations",e,t)}async getDocuments(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};t&&(s.limit=t.toString());try{let o=(await this.client.get("/documents",{params:s,headers:n})).data;if(o.success)return Array.isArray(o.doc)?o.doc:[];{let a=o.error||"Unknown error";throw new Error(a)}}catch(r){throw r}}async queryDocuments(e,t,n,s,r,o,a){let c={};await this.addAuthorizationHeader(c);let l={collection:e,field:t,operator:n,value:String(s)};r&&(l.limit=r.toString()),o&&(l.orderBy=o),a&&(l.orderDirection=a);try{let g=(await this.client.get("/documents/query",{params:l,headers:c})).data;if(g.success)return Array.isArray(g.doc)?g.doc:g.doc&&typeof g.doc=="object"?[g.doc]:[];{let m=g.error||"Unknown error";throw new Error(m)}}catch(d){throw d}}async getDocument(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let o=(await this.client.get(`/documents/${t}`,{params:s,headers:n})).data;return o.success?o.doc:null}catch(r){throw r}}async updateDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let r={collection:e,data:n};try{let a=(await this.client.patch(`/documents/${t}`,r,{headers:s})).data;if(!a.success){let c=a.error||"Unknown error";throw new Error(c)}}catch(o){throw o}}async deleteDocument(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let o=(await this.client.delete(`/documents/${t}`,{params:s,headers:n})).data;if(!o.success){let a=o.error||"Unknown error";throw new Error(a)}}catch(r){throw r}}async createDocumentInSubcollection(e,t,n,s,r){let o=`${e}/${t}/${n}`;return this.createDocument(o,s,r)}async getUserConversations(e,t){return this.queryDocuments("snowx_conversations","userId","==",e,t,"updatedAt","desc")}async saveConversationMessages(e,t){let n=`snowx_conversations/${e}/messages`;try{let s=await this.getDocuments(n);for(let r of s)r.id&&await this.deleteDocument(n,r.id);for(let[r,o]of t.entries()){if(o.role==="system"||o.isStreaming)continue;let a=`message_${r}_${Date.now()}`,c={id:a,role:o.role,content:o.content,timestamp:o.timestamp||new Date,order:r,conversationId:e};try{await this.createDocument(n,a,c)}catch{}}}catch(s){throw s}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((s,r)=>{if(s.order!==void 0&&r.order!==void 0)return s.order-r.order;let o=new Date(s.timestamp||0).getTime(),a=new Date(r.timestamp||0).getTime();return o-a})}async updateRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,updates:t};try{let o=(await this.client.put("/realtime",s,{headers:n})).data;if(!o.success){let a=o.error||"Unknown error";throw new Error(a)}}catch(r){throw r}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let r=(await this.client.get("/realtime",{params:n,headers:t})).data;if(r.success)return r.doc;{let o=r.error||"Unknown error";throw new Error(o)}}catch(s){throw s}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let r=(await this.client.delete("/realtime",{params:n,headers:t})).data;if(!r.success){let o=r.error||"Unknown error";throw new Error(o)}}catch(s){throw s}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let s=await this.client.get("/realtime",{params:n,headers:t}),r=s.data;if(r.success)return s.data.data;{let o=r.error||"Unknown error";throw new Error(o)}}catch(s){throw s}}async writeRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let o=(await this.client.post("/realtime",s,{headers:n})).data;if(!o.success){let a=o.error||"Unknown error";throw new Error(a)}}catch(r){throw r}}async pushRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let o=(await this.client.post("/realtime/push",s,{headers:n})).data;if(o.success){if(o.key)return o.key;throw new Error("No key returned")}else{let a=o.error||"Unknown error";throw new Error(a)}}catch(r){throw r}}setAuthToken(e){console.warn("⚠️ setAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}clearAuthToken(){console.warn("⚠️ clearAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}}});var xi={};Le(xi,{DeviceRegistrationService:()=>Ae});import{EventEmitter as zm}from"events";import{v4 as Wc}from"uuid";import Ns from"os";import Hc from"fs/promises";import qm from"path";import{execSync as _s}from"child_process";import Km from"crypto";var Ae,At=$(()=>{"use strict";Os();xe();z();Ae=class i extends zm{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=Pt.getInstance(),this.authService=X.getInstance(),this.configDir=qm.join(Ns.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return i.instance||(i.instance=new i),i.instance}setupAuthenticationListener(){u.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{u.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{u.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();u.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(u.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){u.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),u.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(u.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,u.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),u.debug(`[DeviceRegistration] ✅ Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw u.debug("[DeviceRegistration] ❌ FAILED to get device ID:",t.message),t}u.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),u.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){u.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return u.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){try{let e=Ns.platform();if(e==="darwin")try{let s=_s("scutil --get ComputerName",{encoding:"utf8"}).trim();if(s)return u.debug(`[DEVICE REG] macOS ComputerName: ${s}`),s}catch{u.debug("[DEVICE REG] Failed to get ComputerName via scutil, using hostname")}else if(e==="win32")try{let s=_s('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName" /v ComputerName',{encoding:"utf8"}).match(/ComputerName\s+REG_SZ\s+(.+)/i);if(s&&s[1]){let r=s[1].trim();if(r)return u.debug(`[DEVICE REG] Windows ComputerName: ${r}`),r}}catch{u.debug("[DEVICE REG] Failed to get ComputerName from registry, using hostname")}let t=Ns.hostname();return u.debug(`[DEVICE REG] Using hostname: ${t}`),t||"Unknown CLI Device"}catch(e){return u.debug(`[DEVICE REG] Error getting computer name: ${e}`),Ns.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=Ns.platform();try{let t=null;switch(e){case"darwin":try{let a=_s("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],u.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{u.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let c=_s("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);c&&c[1]&&(t=c[1],u.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{u.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await Hc.readFile("/etc/machine-id","utf-8").then(o=>o.trim()),u.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await Hc.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),u.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{u.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=_s("wmic csproduct get UUID",{encoding:"utf8"}).split(`
3
+ `).filter(c=>c.trim()&&c.trim()!=="UUID");a.length>0&&(t=a[0].trim(),u.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{u.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:u.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let o=Km.createHash("sha256").update(t).digest("hex"),a=[o.substring(0,8),o.substring(8,12),o.substring(12,16),o.substring(16,20),o.substring(20,32)].join("-");return u.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:n}=await Promise.resolve().then(()=>(Ue(),kt)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${r}`):(r=Wc(),n.set(s,r),u.debug(`[DEVICE REG] Generated NEW fallback UUID: ${r}`)),r}catch(t){u.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:n}=await Promise.resolve().then(()=>(Ue(),kt)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${r}`):(r=Wc(),n.set(s,r),u.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${r}`)),r}}async registerDevice(e,t,n){if(this.isRegistering)return this.registrationPromise||Promise.resolve();this.isRegistering=!0,this.registrationPromise=this.performRegistration(e,t,n);try{await this.registrationPromise}finally{this.isRegistering=!1,this.registrationPromise=null}}async performRegistration(e,t,n){try{let s=await this.api.getDocument(this.devicesCollection,e);if(s&&s.devices){let r=s.devices;if(r.some(a=>a.deviceId===t)){let a=r.map(c=>c.deviceId===t?{...c,lastSeenAt:Qt,computerName:n,type:"on-device"}:c);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:Qt,lastSeenAt:Qt};r.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:r})}}else{let o={userId:e,devices:[{deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:Qt,lastSeenAt:Qt}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,o)}u.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:n})}catch(s){throw u.error("[DeviceRegistration] Failed to register device:",{userId:e,deviceId:t,error:s.message,code:s.code}),s}}getCurrentDeviceId(){return this.currentDeviceId}getCurrentUserId(){return this.currentUserId}getCurrentDeviceInfo(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,computerName:this.getComputerName()}}async refreshDeviceRegistration(){this.currentUserId&&this.currentDeviceId&&await this.autoRegisterDevice(this.currentUserId)}async removeDeviceRegistration(e){try{let t=await this.getUserDeviceId(e);if(!t||t.trim()===""){console.log("⚠️ [DEVICE REG] No device ID found, skipping device removal");return}let n=await this.api.getDocument(this.devicesCollection,e);if(!n||!n.devices||!Array.isArray(n.devices)){console.log("⚠️ [DEVICE REG] No devices document found for user");return}let s=n.devices;if(!s.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let o=s.filter(a=>a.deviceId!==t);o.length===0?await this.api.deleteDocument(this.devicesCollection,e):await this.api.updateDocument(this.devicesCollection,e,{devices:o})}catch(t){console.error(`❌ [DEVICE REG] Failed to remove device registration: ${t.message}`)}}async getUserDeviceId(e){return this.currentDeviceId?this.currentDeviceId:await this.getHardwareDeviceId()}}});var Bc={};Le(Bc,{AuthService:()=>X});import{EventEmitter as Vm}from"events";import{signInAnonymously as Xm,signInWithEmailAndPassword as Ym,createUserWithEmailAndPassword as Qm,signOut as Jm,onAuthStateChanged as Gc,updateProfile as Zm,signInWithCustomToken as ep}from"firebase/auth";import Jt from"axios";import Ci from"fs/promises";import jc from"path";import tp from"os";function zc(i,e,t){return Promise.race([i,new Promise((n,s)=>setTimeout(()=>s(new Error(t)),e))])}var X,xe=$(()=>{"use strict";xn();z();Fc();X=class i extends Vm{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=jc.join(tp.homedir(),".orion-cli","auth.json")}static getInstance(){return i.instance||(i.instance=new i),i.instance}async initializeTokenFile(){try{let e=jc.dirname(this.tokenFilePath);await Ci.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{secureStorage:e}=await Promise.resolve().then(()=>(Rs(),Ms)),{UserDefaults:t}=await Promise.resolve().then(()=>(Ue(),kt)),n=e.getItem("snowx_auth_token"),s=e.getItem("snowx_access_token");if((!n||!s)&&(n=t.string("snowx_auth_token"),s=t.string("snowx_access_token"),n&&s&&(u.debug("Migrating tokens from UserDefaults to secure storage..."),e.setItem("snowx_auth_token",n),e.setItem("snowx_access_token",s),t.remove("snowx_auth_token"),t.remove("snowx_access_token"),u.debug("Token migration to secure storage completed"))),!n||!s)try{let r=await Ci.readFile(this.tokenFilePath,"utf-8"),o=JSON.parse(r);o.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to secure storage..."),e.setItem("snowx_auth_token",o.userId),e.setItem("snowx_access_token",o.token),n=o.userId,s=o.token,await Ci.unlink(this.tokenFilePath),console.log("✅ Migration completed - old auth file removed"))}catch{}if(n&&s){let r={token:s,userId:n,email:void 0,tier:0,expiresAt:Date.now()+2592e6};this.authToken=r,u.debug("Session restored from UserDefaults");try{let o=await this.getUserProfile();o&&o.tier!==void 0?this.authToken.tier=o.tier:await this.updateUserTierFromToken(r)}catch(o){console.warn("⚠️ Failed to fetch user profile during session restore:",o instanceof Error?o.message:"Unknown error"),await this.updateUserTierFromToken(r)}this.emit("authenticated",r)}}catch(e){console.warn("⚠️ Failed to load stored session:",e)}}async saveToken(e){try{let{secureStorage:t}=await Promise.resolve().then(()=>(Rs(),Ms));t.setItem("snowx_auth_token",e.userId),t.setItem("snowx_access_token",e.token);let{UserDefaults:n}=await Promise.resolve().then(()=>(Ue(),kt));n.set("snowx_user_tier",e.tier||0),this.authToken=e,this.emit("authenticated",e);let s=e.tier===2?"pro":e.tier===1?"plus":"free";wi.setUser(e.userId,e.email,s)}catch(t){console.error("❌ Failed to save auth token:",t)}}async clearStoredToken(){try{let{secureStorage:e}=await Promise.resolve().then(()=>(Rs(),Ms)),{UserDefaults:t}=await Promise.resolve().then(()=>(Ue(),kt));e.removeItem("snowx_auth_token"),e.removeItem("snowx_access_token"),t.remove("snowx_auth_token"),t.remove("snowx_access_token"),this.authToken=null,wi.clearUser()}catch(e){console.error("❌ Failed to clear auth token:",e)}}setFirebaseAuth(e){this.auth=e,Gc(e,t=>{this.currentUser=t,this.emit("auth_state_changed",t)})}getFirebaseAuth(){return this.auth}async getCustomTokenFromAPI(e){return this.getCustomTokenFromAPIInternal(e)}async signInWithCustomToken(e){if(!this.auth)throw new Error("Firebase Auth not initialized");let{signInWithCustomToken:t}=await import("firebase/auth");return t(this.auth,e)}async updateUserTierFromToken(e){let t;switch(e.tier){case 1:t=1;break;case 2:t=2;break;case 0:default:t=0;break}Ce.setUserTier(t);let{UserDefaults:n}=await Promise.resolve().then(()=>(Ue(),kt));n.set("userSubscriptionTier",e.tier||0),n.set("isTrialUser",!1),u.debug(`User tier updated: ${Ce.getDisplayName(t)} (${e.tier})`),u.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let e=await Xm(this.auth);this.currentUser=e.user;let t={token:`anonymous_${e.user.uid}`,userId:e.user.uid,tier:0,expiresAt:Date.now()+1440*60*1e3};return await this.saveToken(t),this.updateUserTierFromToken(t),!0}catch(e){return console.error("❌ Failed to sign in anonymously:",e),!1}}async signInWithEmail(e,t){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let n=await Ym(this.auth,e,t);return this.currentUser=n.user,!0}catch(n){return console.error("❌ Failed to sign in with email:",n.message),!1}}async signUpWithEmail(e,t,n){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let s=await Qm(this.auth,e,t);return this.currentUser=s.user,n&&await Zm(s.user,{displayName:n}),!0}catch(s){return console.error("❌ Failed to sign up with email:",s.message),!1}}async signOut(){try{let e=this.getUserId();if(e)try{let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(At(),xi));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Jm(this.auth)}catch(t){console.warn("⚠️ [AUTH] Firebase sign out error:",t)}return this.currentUser=null,this.authToken=null,await this.clearStoredToken(),await this.clearAllSnowXUserDefaults(e),this.emit("signed_out"),!0}catch(e){return console.error("❌ [AUTH] Failed to sign out:",e),!1}}async getCurrentDeviceId(){if(!this.getUserId())return null;let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(At(),xi));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(Ue(),kt)),n=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let o of n)t.remove(o);if(e){let o=`snowx_device_id_${e}`;t.remove(o)}let r=t.getAllKeys().filter(o=>o.startsWith("snowx_device_id_"));for(let o of r)t.remove(o)}catch(t){console.warn("⚠️ [AUTH] Failed to clear some user preferences:",t)}}async authenticateWithSnowX(e){try{let t;if(e?t=await Jt.post(`${this.snowxAuthEndpoint}/login`,e):t=await Jt.post(`${this.snowxAuthEndpoint}/guest`),t.data?.token){let n={token:t.data.token,userId:t.data.userId||"anonymous",email:t.data.email,tier:t.data.tier??0,expiresAt:Date.now()+(t.data.expiresIn||86400)*1e3};return await this.saveToken(n),!0}return!1}catch(t){return console.error("❌ Failed to authenticate with Orion:",t.response?.data?.message||t.message),!1}}async refreshToken(){if(!this.authToken)return!1;try{let e=await Jt.post(`${this.snowxAuthEndpoint}/refresh`,{token:this.authToken.token});if(e.data?.token){let t={...this.authToken,token:e.data.token,expiresAt:Date.now()+(e.data.expiresIn||86400)*1e3};return await this.saveToken(t),!0}return!1}catch(e){return console.warn("⚠️ Failed to refresh token:",e),!1}}getCurrentUser(){return this.currentUser}getAuthToken(){return this.authToken}getAccessToken(){return this.authToken?.token||null}async getAccessTokenFromStorage(){let{secureStorage:e}=await Promise.resolve().then(()=>(Rs(),Ms)),t=e.getItem("snowx_access_token");if(t)return t;let{UserDefaults:n}=await Promise.resolve().then(()=>(Ue(),kt));return n.string("snowx_access_token")}async getFirebaseIdToken(){if(this.currentUser)try{return await this.currentUser.getIdToken(!0)}catch(t){console.error("❌ Failed to get Firebase ID token:",t)}if(this.auth){let n=await new Promise(s=>{let r=!1,o,a=Gc(this.auth,async c=>{if(!r)if(r=!0,clearTimeout(o),a(),c)try{let l=await c.getIdToken(!0);s(l)}catch{s(null)}else s(null)});o=setTimeout(()=>{r||(r=!0,a(),s(null))},2e3)});if(n)return n}let e=await this.getAccessTokenFromStorage();return e?(u.debug("Using stored access token as fallback (Firebase SDK not signed in)"),e):null}getUserId(){return this.authToken?.userId||this.currentUser?.uid||null}getUserEmail(){return this.authToken?.email||this.currentUser?.email||null}async getUserTier(){if(this.authToken?.tier!==void 0)return this.authToken.tier;try{return(await this.getUserProfile())?.tier??0}catch{return console.warn("⚠️ Failed to fetch user tier, defaulting to Free tier"),0}}getCachedUserTier(){return this.authToken?.tier??0}isAuthenticated(){return!!this.authToken&&this.authToken.expiresAt>Date.now()}isFirebaseAuthenticated(){if(this.currentUser)return!0;if(this.authToken?.token&&this.isFirebaseIdToken(this.authToken.token)){let e=this.parseFirebaseIdToken(this.authToken.token);if(e&&Date.now()<=e.exp*1e3)return!0}return!1}async autoAuthenticate(){if(await this.initializeTokenFile(),this.isAuthenticated()){let e=this.getUserId(),t=this.authToken?.token;if(e&&t){u.debug("Using existing authentication token"),u.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e);try{if(this.isFirebaseIdToken(t)){let n=this.parseFirebaseIdToken(t);return n&&Date.now()<=n.exp*1e3?(u.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(u.error("Firebase ID Token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}return await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}catch(n){return u.error("Failed to authenticate with Firebase during auto-authenticate:",n.message),n.response?.status===401||n.response?.status===403||n.response?.status===404?(u.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):u.warn("Transient Firebase auth error - keeping stored token for retry"),!1}}}return!1}async authenticateFirebaseWithStoredToken(){if(console.log("🔥 [AUTH] Starting Firebase authentication..."),!this.auth)throw console.error("❌ [AUTH] Firebase Auth not initialized!"),u.error("Firebase Auth not initialized - cannot authenticate"),new Error("Firebase Auth not initialized. Please ensure ServiceManager is initialized first.");if(console.log("✅ [AUTH] Firebase Auth instance is available"),!this.authToken)throw console.error("❌ [AUTH] No auth token available!"),u.error("No auth token available - cannot authenticate with Firebase"),new Error("No authentication token available");if(console.log("✅ [AUTH] Auth token is available"),console.log(`📋 [AUTH] User ID: ${this.authToken.userId}`),this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log(`✅ [AUTH] Firebase already authenticated for user: ${this.authToken.userId}`),u.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),u.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await zc(this.getCustomTokenFromAPIInternal(this.authToken.userId),3e4,"getCustomToken timeout during authentication");console.log("✅ [AUTH] Custom token received from API"),console.log("🔐 [AUTH] Signing into Firebase with custom token..."),u.debug("Signing into Firebase with custom token...");let t=await zc(ep(this.auth,e),1e4,"Firebase signin timeout during authentication");console.log(`✅ [AUTH] Firebase sign-in successful - UID: ${t.user.uid}`),u.debug(`Firebase Auth successful - UID: ${t.user.uid}`),this.currentUser=t.user,console.log("✅ Firebase authentication successful")}catch(e){throw console.error("❌ [AUTH] Firebase authentication FAILED!"),console.error(`❌ [AUTH] Error details: ${e.message}`),console.error(`❌ [AUTH] Error code: ${e.code||"none"}`),console.error(`❌ [AUTH] HTTP status: ${e.response?.status||"none"}`),u.error("Firebase authentication failed:",{userId:this.authToken.userId,errorMessage:e.message,errorCode:e.code,errorStatus:e.response?.status,errorData:e.response?.data}),new Error(`Firebase authentication failed: ${e.message}`)}}async getCustomTokenFromAPIInternal(e,t=3){let n=4-t;console.log(`📡 [AUTH-API] Attempt ${n}/3: Getting custom token for user: ${e}`),u.debug(`Getting custom token from API for user: ${e} (attempt ${n}/3)`);let s="https://snowx.ai/api-beta/api/fb/custom-token",r={userId:e},o=this.authToken?.token,a={"Content-Type":"application/json"};o?(a.Authorization=`Bearer ${o}`,console.log("📋 [AUTH-API] Access token added to request headers")):console.warn("⚠️ [AUTH-API] No access token available for authorization"),console.log(`📡 [AUTH-API] Sending POST to: ${s}`);try{let c=await Jt.post(s,r,{headers:a,timeout:15e3});if(console.log(`✅ [AUTH-API] Received response with status: ${c.status}`),c.status!==200){let d=c.data?.message||`HTTP ${c.status}`;throw console.error(`❌ [AUTH-API] API returned non-200 status: ${d}`),new Error(`Custom token API failed: ${d}`)}let l=c.data;if(!l?.success||!l?.customToken)throw console.error("❌ [AUTH-API] API response missing success/customToken fields"),console.error("❌ [AUTH-API] Response data:",JSON.stringify(l)),new Error("Invalid custom token response from API");return console.log("✅ [AUTH-API] Custom token successfully received"),u.debug("Successfully received custom token from SnowX API"),l.customToken}catch(c){if(console.error(`❌ [AUTH-API] Request failed on attempt ${n}/3`),console.error(`❌ [AUTH-API] Error message: ${c.message}`),console.error(`❌ [AUTH-API] Error code: ${c.code||"none"}`),console.error(`❌ [AUTH-API] HTTP status: ${c.response?.status||"none"}`),c.response?.data&&console.error(`❌ [AUTH-API] Response data: ${JSON.stringify(c.response.data)}`),u.error("Failed to get custom token:",{attempt:n,error:c.message,code:c.code,status:c.response?.status,responseData:c.response?.data}),t>0&&(c.code==="ECONNABORTED"||c.code==="ETIMEDOUT"||c.code==="ECONNREFUSED"||c.code==="ENOTFOUND"||c.response?.status>=500&&c.response?.status<600)){let d=Math.pow(2,n)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${d}ms... (${t-1} attempts remaining)`),u.debug(`Retrying in ${d}ms...`),await new Promise(g=>setTimeout(g,d)),this.getCustomTokenFromAPIInternal(e,t-1)}throw console.error("❌ [AUTH-API] All retry attempts exhausted or non-retryable error"),c}}isFirebaseIdToken(e){try{let t=e.split(".");return t.length!==3?!1:JSON.parse(Buffer.from(t[1],"base64url").toString()).iss?.includes("securetoken.google.com")}catch{return!1}}parseFirebaseIdToken(e){try{let t=e.split(".");if(t.length!==3)return null;let n=JSON.parse(Buffer.from(t[1],"base64url").toString());return{userId:n.user_id||n.sub,email:n.email,name:n.name,exp:n.exp}}catch{return null}}async authenticateWithAccessToken(e){try{return this.isFirebaseIdToken(e)?await this.authenticateWithFirebaseIdToken(e):await this.authenticateWithSnowXAccessToken(e)}catch(t){return console.error("❌ Failed to authenticate with access token:",t.response?.data?.message||t.message),console.error("Full error details:",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,url:t.config?.url}),!1}}async authenticateWithFirebaseIdToken(e){console.log("🔥 Detected Firebase ID Token, using direct authentication...");let t=this.parseFirebaseIdToken(e);if(!t)return console.error("❌ Failed to parse Firebase ID Token"),!1;if(Date.now()>t.exp*1e3)return console.error("❌ Firebase ID Token has expired"),!1;console.log(`📋 User ID from token: ${t.userId}`),console.log(`📋 Email from token: ${t.email||"N/A"}`);let n={token:e,userId:t.userId,email:t.email,tier:0,expiresAt:t.exp*1e3};await this.saveToken(n);try{let s=await this.getUserProfileWithIdToken(e,t.userId);s&&(this.authToken.tier=s.tier,await this.saveToken(this.authToken))}catch{console.warn("⚠️ Failed to fetch user profile, using default tier")}return this.userProfile={name:t.name,email:t.email},await this.updateUserTierFromToken(this.authToken),this.emit("authStateChanged",this.authToken),this.emit("AuthenticationComplete",t.userId),console.log("✅ Firebase ID Token authentication successful!"),!0}async getUserProfileWithIdToken(e,t){try{let n=await Jt.get(`https://snowx.ai/api-beta/api/fb/documents/${t}?collection=users`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(n.data?.success&&n.data?.doc){let s=n.data.doc,r=s.subscription?.tier??0;return{id:t,email:s.email,tier:r}}return null}catch(n){return console.warn(`⚠️ Failed to fetch user profile with ID Token: ${n.response?.status||n.message}`),null}}async authenticateWithSnowXAccessToken(e){let t=await Jt.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(t.data?.data){let n=t.data.data,s=n.id||n.uid||n.user_id||n.userId||n.email;if(!s)throw new Error("No user ID found in API response");let r={token:e,userId:s,email:n.email,tier:n.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(r),this.userProfile=n,await this.updateUserTierFromToken(r);try{await this.authenticateFirebaseWithStoredToken()}catch(o){throw o.response?.status===401||o.response?.status===403||o.response?.status===404?(u.error("Firebase auth failed with permanent error - clearing token"),await this.clearStoredToken(),this.authToken=null,this.userProfile=null):u.warn("Firebase auth failed with transient error - keeping token for retry"),o}return this.emit("authStateChanged",r),this.emit("AuthenticationComplete",s),!0}return!1}async getUserInfo(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available"),null;try{let e=await Jt.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});return e.data?.data?(this.userProfile=e.data.data,this.userProfile):null}catch(e){throw e.response?.status===401&&(console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),n=t===1?1:t===2?2:0;return Ce.isModelAccessible(e,n)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available for profile fetch"),null;try{let e=await Jt.get(`https://snowx.ai/api-beta/api/fb/documents/${this.authToken.userId}?collection=users`,{headers:{Authorization:`${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});if(e.data?.success&&e.data?.doc){let t=e.data.doc,n=t.subscription?.tier??0;return this.authToken.email=t.email,this.authToken.tier=n,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),{id:this.authToken.userId,email:t.email,tier:n}}return console.warn("⚠️ Empty response from profile API"),null}catch(e){return console.warn(`⚠️ Failed to fetch user profile: ${e.response?.status||e.message}`),this.authToken.tier=0,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),null}}async hasUserProfile(){return await this.getUserProfile()!==null}}});import{EventEmitter as np}from"events";import sp from"crypto";var ct,Kn=$(()=>{"use strict";z();ct=class i extends np{static instance;queuedMessages=[];isProcessingQueue=!1;maxQueueSize=5;constructor(){super()}static getInstance(){return i.instance||(i.instance=new i),i.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),u.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),u.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 sp.randomUUID()}}});import{encode as Kc,decode as Vc,isWithinTokenLimit as Xc,countTokens as rp}from"gpt-tokenizer/encoding/cl100k_base";var Vn,op,ip,lt,Xn=$(()=>{"use strict";Vn=25e3,op=1400,ip=17e3,lt=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??Vn,this.previewTokens=e?.previewTokens??op,this.maxContentTokens=e?.maxContentTokens??ip}count(e){return e?rp(e):0}encode(e){return e?Kc(e):[]}decode(e){return!e||e.length===0?"":Vc(e)}isWithinLimit(e,t){return e?Xc(e,t??this.maxResponseTokens):0}exceedsResponseLimit(e){return this.isWithinLimit(e,this.maxResponseTokens)===!1}exceedsContentLimit(e){return this.isWithinLimit(e,this.maxContentTokens)===!1}truncate(e,t){if(!e)return{text:"",tokens:0,truncated:!1};let n=t??this.maxResponseTokens,s=Xc(e,n);if(s!==!1)return{text:e,tokens:s,truncated:!1};let o=Kc(e).slice(0,n);return{text:Vc(o),tokens:n,truncated:!0}}generatePreview(e,t){if(!e)return{preview:"",totalTokens:0,previewTokens:0,remainingTokens:0};let n=t??this.previewTokens,s=this.count(e);if(s<=n)return{preview:e,totalTokens:s,previewTokens:s,remainingTokens:0};let{text:r,tokens:o}=this.truncate(e,n);return{preview:r,totalTokens:s,previewTokens:o,remainingTokens:s-o}}truncateContent(e,t){let n=t??this.maxContentTokens,s=this.truncate(e,n);return s.truncated?s.text+`
4
4
  ... [Content truncated at ${s.tokens.toLocaleString()} tokens]`:e}truncateOutput(e,t){let n=t??this.maxResponseTokens,s=this.truncate(e,n);return s.truncated?s.text+`
5
5
 
6
6
  [Output truncated at ${s.tokens.toLocaleString()} tokens]`:e}formatLargeResponsePreview(e,t,n){let{preview:s,totalTokens:r,previewTokens:o,remainingTokens:a}=this.generatePreview(e,n?.previewTokens??this.previewTokens),c=`Response too large (${r.toLocaleString()} tokens > ${this.maxResponseTokens.toLocaleString()} limit), saved to temporary file.
@@ -24,9 +24,9 @@ To read full content: use tools like 'read_file' with path above`,c}formatLargeF
24
24
  `,c+=`${"─".repeat(50)}
25
25
  `,c+=s,a>0&&(c+=`
26
26
  ${"─".repeat(50)}`,c+=`
27
- ... (${a.toLocaleString()} more tokens)`),c}get maxResponse(){return this.maxResponseTokens}get maxContent(){return this.maxContentTokens}get maxPreview(){return this.previewTokens}}});import{EventEmitter as ap}from"events";var Yc,Qc,cp,Jc,lp,_s,Zc,Ei=F(()=>{"use strict";j();Yc=10,Qc=2e3,cp=5e3,Jc=200,lp=3e3,_s=class i extends ap{static instance;operations=new Map;cleanupTimers=new Map;constructor(){super(),u.debug("[SubAgentManager] Initialized")}static getInstance(){return i.instance||(i.instance=new i),i.instance}handleEvent(e){let{type:t}=e;switch(t){case"spawn_agents_started":this.handleSpawnStarted(e);break;case"sub_agent_started":this.handleAgentStarted(e);break;case"sub_agent_streaming":this.handleAgentStreaming(e);break;case"sub_agent_completed":this.handleAgentCompleted(e);break;case"spawn_agents_completed":this.handleSpawnCompleted(e);break;default:u.debug(`[SubAgentManager] Unknown event type: ${t}`)}}handleSpawnStarted(e){let{operationId:t,totalAgents:n,tasks:s}=e,r=n||s?.length||0;if(!t||!r){u.debug("[SubAgentManager] Invalid spawn_agents_started event");return}this.cleanupOldOperations();let o={operationId:t,totalAgents:r,agents:new Map,status:"starting",startTime:new Date};for(let a=1;a<=r;a++){let c=s?.[a-1]||"";o.agents.set(a,{agentNumber:a,task:this.truncateString(c,Jc),status:"pending"})}this.operations.set(t,o),u.debug(`[SubAgentManager] Spawn started: ${t} with ${r} agents`),this.emit("spawn_started",{operationId:t,totalAgents:r}),this.emitProgressUpdate(t)}handleAgentStarted(e){let{operationId:t,agentNumber:n,task:s}=e;if(!t||!n)return;let r=this.operations.get(t);if(!r){u.debug(`[SubAgentManager] Operation not found: ${t}`);return}r.status==="starting"&&(r.status="running");let o=r.agents.get(n),a=this.truncateString(s||o?.task||"",Jc);r.agents.set(n,{...o,agentNumber:n,task:a,status:"running",startTime:new Date}),u.debug(`[SubAgentManager] Agent ${n} started: ${a.substring(0,50)}...`),this.emit("agent_started",{operationId:t,agentNumber:n,task:a}),this.emitProgressUpdate(t)}handleAgentStreaming(e){let{operationId:t,agentNumber:n,content:s}=e;if(!t||!n||!s)return;let r=this.operations.get(t);if(!r)return;let o=r.agents.get(n);if(!o)return;let c=(o.streamingContent||"")+s;c.length>Qc?o.streamingContent=c.slice(-Qc):o.streamingContent=c,this.emit("agent_streaming",{operationId:t,agentNumber:n,content:o.streamingContent})}handleAgentCompleted(e){let{operationId:t,agentNumber:n,result:s,error:r,status:o}=e;if(!t||!n)return;let a=this.operations.get(t);if(!a)return;let c=a.agents.get(n);if(!c)return;let l;o==="timeout"?l="timeout":o==="failed"||r?l="failed":l="completed",c.status=l,c.endTime=new Date,c.result=this.truncateString(s||"",cp),c.error=r;let d=c.startTime?(c.endTime.getTime()-c.startTime.getTime())/1e3:0;u.debug(`[SubAgentManager] Agent ${n} ${l} (${d.toFixed(1)}s)`),this.emit("agent_completed",{operationId:t,agentNumber:n,status:l,duration:d}),this.emitProgressUpdate(t)}handleSpawnCompleted(e){let{operationId:t,success:n}=e;if(!t)return;let s=this.operations.get(t);if(!s)return;let r=0,o=0,a=0;for(let l of s.agents.values())l.status==="completed"?r++:l.status==="failed"?o++:l.status==="timeout"&&a++;n!==void 0?s.status=n?"completed":"failed":s.status=o>0||a>0?"failed":"completed",s.endTime=new Date;let c=(s.endTime.getTime()-s.startTime.getTime())/1e3;u.debug(`[SubAgentManager] Spawn completed: ${r} success, ${o} failed (${c.toFixed(1)}s)`),this.emit("spawn_completed",{operationId:t,status:s.status,duration:c,successCount:r,failCount:o,totalAgents:s.totalAgents}),this.emitProgressUpdate(t),this.scheduleCleanup(t)}emitProgressUpdate(e){let t=this.operations.get(e);if(!t)return;let n=0,s=0,r=0,o=0,a=0,c=[];for(let l of t.agents.values()){switch(l.status){case"pending":n++;break;case"running":s++;break;case"completed":r++;break;case"failed":o++;break;case"timeout":a++;break}c.push({agentNumber:l.agentNumber,task:l.task,status:l.status})}this.emit("progress",{operationId:e,status:t.status,totalAgents:t.totalAgents,pending:n,running:s,completed:r,failed:o,timeout:a,agents:c})}getProgressString(e){let t=this.operations.get(e);if(!t)return"";let n=0,s=0,r=0,o=0;for(let l of t.agents.values())switch(l.status){case"running":n++;break;case"completed":s++;break;case"failed":r++;break;case"timeout":o++;break}let c=`${{starting:"🚀",running:"⏳",completed:"✅",failed:"❌"}[t.status]||"❓"} Sub-agents: ${s}/${t.totalAgents} complete`;return n>0&&(c+=` (${n} running)`),r>0&&(c+=` [${r} failed]`),o>0&&(c+=` [${o} timeout]`),c}getAgentListString(e){let t=this.operations.get(e);if(!t)return"";let n=[],s=Array.from(t.agents.values()).sort((r,o)=>r.agentNumber-o.agentNumber);for(let r of s){let o={pending:"⏸️",running:"🔄",completed:"✅",failed:"❌",timeout:"⏰"}[r.status]||"❓",a=r.task?`: ${r.task.substring(0,60)}${r.task.length>60?"...":""}`:"";n.push(` ${o} Agent ${r.agentNumber}${a}`),r.error&&n.push(` └─ Error: ${r.error.substring(0,80)}${r.error.length>80?"...":""}`)}return n.join(`
28
- `)}cleanupOldOperations(){if(this.operations.size<Yc)return;let e=[];for(let[n,s]of this.operations)(s.status==="completed"||s.status==="failed")&&e.push({id:n,endTime:s.endTime?.getTime()||s.startTime.getTime()});e.sort((n,s)=>n.endTime-s.endTime);let t=e.slice(0,Math.max(1,e.length-Yc+1));for(let{id:n}of t){this.operations.delete(n);let s=this.cleanupTimers.get(n);s&&(clearTimeout(s),this.cleanupTimers.delete(n)),u.debug(`[SubAgentManager] Cleaned up old operation: ${n}`)}}scheduleCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.operations.delete(e),this.cleanupTimers.delete(e),u.debug(`[SubAgentManager] Cleaned up operation: ${e}`)},lp);this.cleanupTimers.set(e,n)}truncateString(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}getOperations(){return new Map(this.operations)}getActiveOperations(){return Array.from(this.operations.values()).filter(e=>e.status==="starting"||e.status==="running")}getOperation(e){return this.operations.get(e)}hasActiveOperations(){return this.getActiveOperations().length>0}clear(){for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear(),this.operations.clear(),u.debug("[SubAgentManager] Cleared all operations")}},Zc=_s.getInstance()});var kr,el=F(()=>{"use strict";j();kr=class{tools=new Map;register(e){for(let t of e.toolNames)this.tools.set(t,e),u.debug(`[ToolRegistry] Registered tool: ${t}`)}getTool(e){let t=this.tools.get(e);if(t)return t;let n=e.toLowerCase();for(let[s,r]of this.tools.entries())if(s.toLowerCase()===n)return r}async executeTool(e,t,n,s){let r=this.getTool(e);if(!r)return u.error(`[ToolRegistry] Unknown tool: ${e}`),{id:t,toolName:e,success:!1,output:"",error:`Unknown tool: ${e}`};try{u.debug(`[ToolRegistry] Executing tool: ${e} (id: ${t})`);let o=Date.now(),a=await r.execute(t,e,n,s),c=Date.now()-o;u.debug(`[ToolRegistry] Tool ${e} completed in ${c}ms`);let l=a.map(d=>d.text||"").join(`
29
- `);return{id:t,toolName:e,success:!0,output:l,content:a}}catch(o){return u.error(`[ToolRegistry] Tool execution error (${e}):`,o),{id:t,toolName:e,success:!1,output:"",error:o instanceof Error?o.message:String(o)}}}getAllToolNames(){return Array.from(this.tools.keys())}hasToolRegistered(e){return this.getTool(e)!==void 0}unregister(e){let t=e.toLowerCase(),n=[];for(let s of this.tools.keys())s.toLowerCase()===t&&n.push(s);for(let s of n)this.tools.delete(s);u.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),u.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var tl={};Fe(tl,{ToolDisplay:()=>Y});import ue from"chalk";var Y,Tt=F(()=>{"use strict";Y=class i{static customUIMode=!1;static enableCustomUI(){i.customUIMode=!0}static disableCustomUI(){i.customUIMode=!1}static start(e,t,n){if(i.customUIMode)return;let s=this.getToolPrefix(e);if(console.log(ue.cyan(`
27
+ ... (${a.toLocaleString()} more tokens)`),c}get maxResponse(){return this.maxResponseTokens}get maxContent(){return this.maxContentTokens}get maxPreview(){return this.previewTokens}}});import{EventEmitter as ap}from"events";var Yc,Qc,cp,Jc,lp,$s,Zc,Ei=$(()=>{"use strict";z();Yc=10,Qc=2e3,cp=5e3,Jc=200,lp=3e3,$s=class i extends ap{static instance;operations=new Map;cleanupTimers=new Map;constructor(){super(),u.debug("[SubAgentManager] Initialized")}static getInstance(){return i.instance||(i.instance=new i),i.instance}handleEvent(e){let{type:t}=e;switch(t){case"spawn_agents_started":this.handleSpawnStarted(e);break;case"sub_agent_started":this.handleAgentStarted(e);break;case"sub_agent_streaming":this.handleAgentStreaming(e);break;case"sub_agent_completed":this.handleAgentCompleted(e);break;case"spawn_agents_completed":this.handleSpawnCompleted(e);break;default:u.debug(`[SubAgentManager] Unknown event type: ${t}`)}}handleSpawnStarted(e){let{operationId:t,totalAgents:n,tasks:s}=e,r=n||s?.length||0;if(!t||!r){u.debug("[SubAgentManager] Invalid spawn_agents_started event");return}this.cleanupOldOperations();let o={operationId:t,totalAgents:r,agents:new Map,status:"starting",startTime:new Date};for(let a=1;a<=r;a++){let c=s?.[a-1]||"";o.agents.set(a,{agentNumber:a,task:this.truncateString(c,Jc),status:"pending"})}this.operations.set(t,o),u.debug(`[SubAgentManager] Spawn started: ${t} with ${r} agents`),this.emit("spawn_started",{operationId:t,totalAgents:r}),this.emitProgressUpdate(t)}handleAgentStarted(e){let{operationId:t,agentNumber:n,task:s}=e;if(!t||!n)return;let r=this.operations.get(t);if(!r){u.debug(`[SubAgentManager] Operation not found: ${t}`);return}r.status==="starting"&&(r.status="running");let o=r.agents.get(n),a=this.truncateString(s||o?.task||"",Jc);r.agents.set(n,{...o,agentNumber:n,task:a,status:"running",startTime:new Date}),u.debug(`[SubAgentManager] Agent ${n} started: ${a.substring(0,50)}...`),this.emit("agent_started",{operationId:t,agentNumber:n,task:a}),this.emitProgressUpdate(t)}handleAgentStreaming(e){let{operationId:t,agentNumber:n,content:s}=e;if(!t||!n||!s)return;let r=this.operations.get(t);if(!r)return;let o=r.agents.get(n);if(!o)return;let c=(o.streamingContent||"")+s;c.length>Qc?o.streamingContent=c.slice(-Qc):o.streamingContent=c,this.emit("agent_streaming",{operationId:t,agentNumber:n,content:o.streamingContent})}handleAgentCompleted(e){let{operationId:t,agentNumber:n,result:s,error:r,status:o}=e;if(!t||!n)return;let a=this.operations.get(t);if(!a)return;let c=a.agents.get(n);if(!c)return;let l;o==="timeout"?l="timeout":o==="failed"||r?l="failed":l="completed",c.status=l,c.endTime=new Date,c.result=this.truncateString(s||"",cp),c.error=r;let d=c.startTime?(c.endTime.getTime()-c.startTime.getTime())/1e3:0;u.debug(`[SubAgentManager] Agent ${n} ${l} (${d.toFixed(1)}s)`),this.emit("agent_completed",{operationId:t,agentNumber:n,status:l,duration:d}),this.emitProgressUpdate(t)}handleSpawnCompleted(e){let{operationId:t,success:n}=e;if(!t)return;let s=this.operations.get(t);if(!s)return;let r=0,o=0,a=0;for(let l of s.agents.values())l.status==="completed"?r++:l.status==="failed"?o++:l.status==="timeout"&&a++;n!==void 0?s.status=n?"completed":"failed":s.status=o>0||a>0?"failed":"completed",s.endTime=new Date;let c=(s.endTime.getTime()-s.startTime.getTime())/1e3;u.debug(`[SubAgentManager] Spawn completed: ${r} success, ${o} failed (${c.toFixed(1)}s)`),this.emit("spawn_completed",{operationId:t,status:s.status,duration:c,successCount:r,failCount:o,totalAgents:s.totalAgents}),this.emitProgressUpdate(t),this.scheduleCleanup(t)}emitProgressUpdate(e){let t=this.operations.get(e);if(!t)return;let n=0,s=0,r=0,o=0,a=0,c=[];for(let l of t.agents.values()){switch(l.status){case"pending":n++;break;case"running":s++;break;case"completed":r++;break;case"failed":o++;break;case"timeout":a++;break}c.push({agentNumber:l.agentNumber,task:l.task,status:l.status})}this.emit("progress",{operationId:e,status:t.status,totalAgents:t.totalAgents,pending:n,running:s,completed:r,failed:o,timeout:a,agents:c})}getProgressString(e){let t=this.operations.get(e);if(!t)return"";let n=0,s=0,r=0,o=0;for(let l of t.agents.values())switch(l.status){case"running":n++;break;case"completed":s++;break;case"failed":r++;break;case"timeout":o++;break}let c=`${{starting:"🚀",running:"⏳",completed:"✅",failed:"❌"}[t.status]||"❓"} Sub-agents: ${s}/${t.totalAgents} complete`;return n>0&&(c+=` (${n} running)`),r>0&&(c+=` [${r} failed]`),o>0&&(c+=` [${o} timeout]`),c}getAgentListString(e){let t=this.operations.get(e);if(!t)return"";let n=[],s=Array.from(t.agents.values()).sort((r,o)=>r.agentNumber-o.agentNumber);for(let r of s){let o={pending:"⏸️",running:"🔄",completed:"✅",failed:"❌",timeout:"⏰"}[r.status]||"❓",a=r.task?`: ${r.task.substring(0,60)}${r.task.length>60?"...":""}`:"";n.push(` ${o} Agent ${r.agentNumber}${a}`),r.error&&n.push(` └─ Error: ${r.error.substring(0,80)}${r.error.length>80?"...":""}`)}return n.join(`
28
+ `)}cleanupOldOperations(){if(this.operations.size<Yc)return;let e=[];for(let[n,s]of this.operations)(s.status==="completed"||s.status==="failed")&&e.push({id:n,endTime:s.endTime?.getTime()||s.startTime.getTime()});e.sort((n,s)=>n.endTime-s.endTime);let t=e.slice(0,Math.max(1,e.length-Yc+1));for(let{id:n}of t){this.operations.delete(n);let s=this.cleanupTimers.get(n);s&&(clearTimeout(s),this.cleanupTimers.delete(n)),u.debug(`[SubAgentManager] Cleaned up old operation: ${n}`)}}scheduleCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.operations.delete(e),this.cleanupTimers.delete(e),u.debug(`[SubAgentManager] Cleaned up operation: ${e}`)},lp);this.cleanupTimers.set(e,n)}truncateString(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}getOperations(){return new Map(this.operations)}getActiveOperations(){return Array.from(this.operations.values()).filter(e=>e.status==="starting"||e.status==="running")}getOperation(e){return this.operations.get(e)}hasActiveOperations(){return this.getActiveOperations().length>0}clear(){for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear(),this.operations.clear(),u.debug("[SubAgentManager] Cleared all operations")}},Zc=$s.getInstance()});var Pr,el=$(()=>{"use strict";z();Pr=class{tools=new Map;register(e){for(let t of e.toolNames)this.tools.set(t,e),u.debug(`[ToolRegistry] Registered tool: ${t}`)}getTool(e){let t=this.tools.get(e);if(t)return t;let n=e.toLowerCase();for(let[s,r]of this.tools.entries())if(s.toLowerCase()===n)return r}async executeTool(e,t,n,s){let r=this.getTool(e);if(!r)return u.error(`[ToolRegistry] Unknown tool: ${e}`),{id:t,toolName:e,success:!1,output:"",error:`Unknown tool: ${e}`};try{u.debug(`[ToolRegistry] Executing tool: ${e} (id: ${t})`);let o=Date.now(),a=await r.execute(t,e,n,s),c=Date.now()-o;u.debug(`[ToolRegistry] Tool ${e} completed in ${c}ms`);let l=a.map(d=>d.text||"").join(`
29
+ `);return{id:t,toolName:e,success:!0,output:l,content:a}}catch(o){return u.error(`[ToolRegistry] Tool execution error (${e}):`,o),{id:t,toolName:e,success:!1,output:"",error:o instanceof Error?o.message:String(o)}}}getAllToolNames(){return Array.from(this.tools.keys())}hasToolRegistered(e){return this.getTool(e)!==void 0}unregister(e){let t=e.toLowerCase(),n=[];for(let s of this.tools.keys())s.toLowerCase()===t&&n.push(s);for(let s of n)this.tools.delete(s);u.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),u.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var tl={};Le(tl,{ToolDisplay:()=>Q});import ue from"chalk";var Q,Tt=$(()=>{"use strict";Q=class i{static customUIMode=!1;static enableCustomUI(){i.customUIMode=!0}static disableCustomUI(){i.customUIMode=!1}static start(e,t,n){if(i.customUIMode)return;let s=this.getToolPrefix(e);if(console.log(ue.cyan(`
30
30
  ${s} ${ue.bold(e)}`)),t&&console.log(ue.gray(` ${t}`)),n){let r=n.length>120?n.substring(0,120)+ue.gray("..."):n;console.log(ue.white(` ${r}`))}}static getToolPrefix(e){let t=e.toLowerCase();return t.includes("bash")||t.includes("command")?"▸":t.includes("write")?"→":t.includes("edit")?"✎":t.includes("read")?"◆":t.includes("search")||t.includes("grep")?"⌕":"•"}static result(e){if(i.customUIMode)return;let{toolName:t,output:n,success:s,executionTime:r,truncateLines:o=50}=e,a=n||"";n&&(t.toLowerCase().includes("edit")?a=this.formatEditOutput(n,o):t.toLowerCase().includes("write")?a=this.formatWriteOutput(n,o):t.toLowerCase().includes("bash")||t.toLowerCase().includes("command")?a=this.formatBashOutput(n,o):a=this.formatGenericOutput(n,o)),a&&a.trim()&&console.log(a);let c=s?ue.green("✓"):ue.red("✗"),l=s?ue.green("SUCCESS"):ue.red("FAILED"),d=r?ue.gray(` (${r}ms)`):"";console.log(`${c} ${l}${d}
31
31
  `)}static formatEditOutput(e,t){if(e.includes("- ")&&e.includes("+ ")){let a=e.split(`
32
32
  `),l=a.slice(0,20).map(d=>ue.gray(" ")+d).join(`
@@ -40,19 +40,19 @@ ${s} ${ue.bold(e)}`)),t&&console.log(ue.gray(` ${t}`)),n){let r=n.length>120?n
40
40
  `);let r=n.slice(0,t).map(o=>ue.gray(" ")+ue.dim(o)).join(`
41
41
  `);return r+=`
42
42
  `+ue.gray(` ... (${n.length-t} more lines)`),r}static error(e,t){i.customUIMode||(console.log(`
43
- ${ue.red("✗")} ${ue.red.bold(e)} ${ue.red("ERROR")}`),console.log(ue.gray(" ")+ue.white(t)),console.log(""))}}});import nl from"os";import Ii from"path";function Pr(){return process.platform==="win32"}function xn(i){if(!i)return i;let e=i.trim();return e.startsWith("~")&&(e=e.replace(/^~/,nl.homedir())),Pr()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,nl.homedir())),!Pr()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),Pr()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function Vn(i){if(!i||typeof i!="string")return{valid:!1,error:"File path is required"};let e=xn(i);if(Pr()){let n=Ii.basename(e).split(".")[0].toUpperCase();if(up.includes(n))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${n}`}}return Ii.isAbsolute(e)?Ii.resolve(e).includes("..")?{valid:!1,error:`Security Error: Path traversal not allowed: ${i}`}:{valid:!0}:{valid:!1,error:`Invalid path format: "${i}"
43
+ ${ue.red("✗")} ${ue.red.bold(e)} ${ue.red("ERROR")}`),console.log(ue.gray(" ")+ue.white(t)),console.log(""))}}});import nl from"os";import Ii from"path";function Ar(){return process.platform==="win32"}function En(i){if(!i)return i;let e=i.trim();return e.startsWith("~")&&(e=e.replace(/^~/,nl.homedir())),Ar()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,nl.homedir())),!Ar()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),Ar()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function Yn(i){if(!i||typeof i!="string")return{valid:!1,error:"File path is required"};let e=En(i);if(Ar()){let n=Ii.basename(e).split(".")[0].toUpperCase();if(up.includes(n))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${n}`}}return Ii.isAbsolute(e)?Ii.resolve(e).includes("..")?{valid:!1,error:`Security Error: Path traversal not allowed: ${i}`}:{valid:!0}:{valid:!1,error:`Invalid path format: "${i}"
44
44
 
45
45
  Path must be absolute (start with / on Unix or C:\\ on Windows)
46
46
 
47
47
  Wrong: Downloads/file.pdf
48
- Correct: /Users/username/Downloads/file.pdf`}}var up,Ar=F(()=>{"use strict";up=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});import sl from"path";var dp,gp,Dr,rl=F(()=>{"use strict";j();Tt();Ar();Kn();dp=["png","jpg","jpeg","gif","bmp","webp","ico","tiff","tif"],gp={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon",tiff:"image/tiff",tif:"image/tiff"},Dr=class{toolNames=["read","Read"];async execute(e,t,n,s){let r=n.file_path||n.path,o=n.offset,a=n.limit;if(!r)throw new Error("Missing file_path or path argument");let c=xn(r),l=Vn(c);if(!l.valid)return[{type:"text",text:`Error: ${l.error}`}];u.debug(`[ReadFileTool] Reading file: ${c}${o!==void 0?`, offset: ${o}`:""}${a!==void 0?`, limit: ${a}`:""}`);let d=Date.now();Y.start("Read",n.description,c);try{let g=await import("fs/promises");try{await g.access(c)}catch{return[{type:"text",text:`Error: File does not exist at path: ${c}`}]}let m=await g.stat(c);if(m.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${c}`}];let p=sl.extname(c).substring(1).toLowerCase();if(dp.includes(p)){u.debug(`[ReadFileTool] Image file detected: ${c}`);let $=(await g.readFile(c)).toString("base64"),D=gp[p]||"application/octet-stream",_=sl.basename(c);u.debug(`[ReadFileTool] Image converted to base64: ${_} (${$.length} chars)`);let N=Date.now()-d;return Y.result({toolName:"Read",filePath:c,output:`Image loaded: ${_}`,success:!0,executionTime:N}),[{type:"image_url",image_url:{url:`data:${D};base64,${$}`}}]}let f=await g.readFile(c,"utf-8"),y=f.length,T=f.split(`
49
- `),x=T.length,w=Math.max(o??0,0),C=new lt;if(o===void 0&&a===void 0&&C.exceedsResponseLimit(f)){let R=C.count(f),$=m.size/1024,D=$/1024,_=D>=1?`${D.toFixed(2)} MB`:`${$.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
48
+ Correct: /Users/username/Downloads/file.pdf`}}var up,Dr=$(()=>{"use strict";up=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});import sl from"path";var dp,gp,Mr,rl=$(()=>{"use strict";z();Tt();Dr();Xn();dp=["png","jpg","jpeg","gif","bmp","webp","ico","tiff","tif"],gp={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon",tiff:"image/tiff",tif:"image/tiff"},Mr=class{toolNames=["read","Read"];async execute(e,t,n,s){let r=n.file_path||n.path,o=n.offset,a=n.limit;if(!r)throw new Error("Missing file_path or path argument");let c=En(r),l=Yn(c);if(!l.valid)return[{type:"text",text:`Error: ${l.error}`}];u.debug(`[ReadFileTool] Reading file: ${c}${o!==void 0?`, offset: ${o}`:""}${a!==void 0?`, limit: ${a}`:""}`);let d=Date.now();Q.start("Read",n.description,c);try{let g=await import("fs/promises");try{await g.access(c)}catch{return[{type:"text",text:`Error: File does not exist at path: ${c}`}]}let m=await g.stat(c);if(m.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${c}`}];let p=sl.extname(c).substring(1).toLowerCase();if(dp.includes(p)){u.debug(`[ReadFileTool] Image file detected: ${c}`);let _=(await g.readFile(c)).toString("base64"),F=gp[p]||"application/octet-stream",R=sl.basename(c);u.debug(`[ReadFileTool] Image converted to base64: ${R} (${_.length} chars)`);let N=Date.now()-d;return Q.result({toolName:"Read",filePath:c,output:`Image loaded: ${R}`,success:!0,executionTime:N}),[{type:"image_url",image_url:{url:`data:${F};base64,${_}`}}]}let f=await g.readFile(c,"utf-8"),y=f.length,T=f.split(`
49
+ `),C=T.length,w=Math.max(o??0,0),E=new lt;if(o===void 0&&a===void 0&&E.exceedsResponseLimit(f)){let M=E.count(f),_=m.size/1024,F=_/1024,R=F>=1?`${F.toFixed(2)} MB`:`${_.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
50
50
 
51
51
  File Information:
52
52
  - Path: ${c}
53
- - Size: ${_} (${R.toLocaleString()} tokens)
54
- - Total Lines: ${x}
55
- - Token Limit: ${qn.toLocaleString()}
53
+ - Size: ${R} (${M.toLocaleString()} tokens)
54
+ - Total Lines: ${C}
55
+ - Token Limit: ${Vn.toLocaleString()}
56
56
 
57
57
  Suggested Solutions:
58
58
  1. Read specific lines using offset and limit:
@@ -66,19 +66,19 @@ Suggested Solutions:
66
66
  - Lines 2000-4000: Read(path: "${c}", offset: 2000, limit: 2000)
67
67
  - And so on...
68
68
 
69
- The file has ${x.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(x===0||f.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(w>=x)return[{type:"text",text:`Error: Offset ${w} is beyond file length. File has ${x} total lines. Try a smaller offset (0 to ${x-1}).`}];let v=a!==void 0?Math.min(w+a,x):x,E=T.slice(w,v),S=E.map((R,$)=>`${(w+$+1).toString().padStart(6," ")} ${R}`).join(`
70
- `),I=S;if(o!==void 0||a!==void 0){let R=`
69
+ The file has ${C.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(C===0||f.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(w>=C)return[{type:"text",text:`Error: Offset ${w} is beyond file length. File has ${C} total lines. Try a smaller offset (0 to ${C-1}).`}];let v=a!==void 0?Math.min(w+a,C):C,x=T.slice(w,v),S=x.map((M,_)=>`${(w+_+1).toString().padStart(6," ")} ${M}`).join(`
70
+ `),I=S;if(o!==void 0||a!==void 0){let M=`
71
71
 
72
- [Read ${E.length} lines (${w+1}-${v}) of ${x} total lines]`;I=S+R}let P=Date.now()-d;return Y.result({toolName:"Read",filePath:c,output:I,success:!0,executionTime:P}),[{type:"text",text:I}]}catch(g){u.debug(`[ReadFileTool] Failed to read file: ${g.message}`);let m;g.code==="ENOENT"?m=`Error: File does not exist at path: ${c}`:g.code==="EACCES"?m=`Error: Permission denied. Cannot read file: ${c}`:g.code==="EISDIR"?m=`Error: Path is a directory, not a file: ${c}`:m=`Error reading file: ${g.message}`;let p=Date.now()-d;return Y.result({toolName:"Read",filePath:c,output:m,success:!1,executionTime:p}),[{type:"text",text:m}]}}}});import Mr from"fs/promises";import mp from"form-data";import ki from"axios";import Pi from"path";var Rr,ol=F(()=>{"use strict";j();Tt();Te();Rr=class{toolNames=["read_special_file","read_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm","png","jpg","jpeg","gif","bmp","webp","ico"];imageExtensions=["png","jpg","jpeg","gif","bmp","webp","ico"];imageMimeTypes={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon"};async execute(e,t,n,s){let r=n.path;if(!r)throw new Error("Missing path argument");u.debug(`[ReadSpecialFileTool] Converting file: ${r}`);let o=Date.now();Y.start("ReadSpecialFile",n.description,r);try{try{await Mr.access(r)}catch{return[{type:"text",text:`Error: File does not exist at path: ${r}`}]}let a=Pi.extname(r).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let w=this.supportedExtensions.join(", ");return[{type:"text",text:`Error: Unsupported file type '${a}'. The read_special_file tool only supports Microsoft Office documents (docx, doc, xlsx, xls, pptx, ppt), PDF files (pdf), audio/video files (mp3, mp4, wav), web files (html, htm), and images (png, jpg, jpeg, gif, bmp, webp, ico). For plain text files, use the run_command tool with 'cat' instead.
72
+ [Read ${x.length} lines (${w+1}-${v}) of ${C} total lines]`;I=S+M}let D=Date.now()-d;return Q.result({toolName:"Read",filePath:c,output:I,success:!0,executionTime:D}),[{type:"text",text:I}]}catch(g){u.debug(`[ReadFileTool] Failed to read file: ${g.message}`);let m;g.code==="ENOENT"?m=`Error: File does not exist at path: ${c}`:g.code==="EACCES"?m=`Error: Permission denied. Cannot read file: ${c}`:g.code==="EISDIR"?m=`Error: Path is a directory, not a file: ${c}`:m=`Error reading file: ${g.message}`;let p=Date.now()-d;return Q.result({toolName:"Read",filePath:c,output:m,success:!1,executionTime:p}),[{type:"text",text:m}]}}}});import Rr from"fs/promises";import mp from"form-data";import ki from"axios";import Pi from"path";var Or,ol=$(()=>{"use strict";z();Tt();xe();Or=class{toolNames=["read_special_file","read_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm","png","jpg","jpeg","gif","bmp","webp","ico"];imageExtensions=["png","jpg","jpeg","gif","bmp","webp","ico"];imageMimeTypes={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon"};async execute(e,t,n,s){let r=n.path;if(!r)throw new Error("Missing path argument");u.debug(`[ReadSpecialFileTool] Converting file: ${r}`);let o=Date.now();Q.start("ReadSpecialFile",n.description,r);try{try{await Rr.access(r)}catch{return[{type:"text",text:`Error: File does not exist at path: ${r}`}]}let a=Pi.extname(r).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let w=this.supportedExtensions.join(", ");return[{type:"text",text:`Error: Unsupported file type '${a}'. The read_special_file tool only supports Microsoft Office documents (docx, doc, xlsx, xls, pptx, ppt), PDF files (pdf), audio/video files (mp3, mp4, wav), web files (html, htm), and images (png, jpg, jpeg, gif, bmp, webp, ico). For plain text files, use the run_command tool with 'cat' instead.
73
73
 
74
- Supported file types: ${w}`}]}let c=await Mr.stat(r),l=Pi.basename(r);if(u.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${l} (${c.size} bytes)`),this.imageExtensions.includes(a)){u.debug(`[ReadSpecialFileTool] Image file detected: ${r}`);let C=(await Mr.readFile(r)).toString("base64"),v=this.imageMimeTypes[a]||"application/octet-stream";u.debug(`[ReadSpecialFileTool] Image converted to base64: ${l} (${C.length} chars)`);let E=Date.now()-o;return Y.result({toolName:"ReadSpecialFile",filePath:r,output:`Image loaded: ${l}`,success:!0,executionTime:E}),[{type:"image_url",image_url:{url:`data:${v};base64,${C}`}}]}let d=await this.uploadToBatchAPI(r,l);u.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${d}`);let g=await this.pollBatchStatus(d);u.debug("[ReadSpecialFileTool] Conversion completed");let m=g.files[0];if(!m||m.status==="failed"){let w=m?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${w}`}]}let p=await this.fetchFileContent(m.file_id);if(!p.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let h=c.size/1024,f=h/1024,y=f>=1?`${f.toFixed(2)} MB`:`${h.toFixed(2)} KB`,T=`# File: ${l}
74
+ Supported file types: ${w}`}]}let c=await Rr.stat(r),l=Pi.basename(r);if(u.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${l} (${c.size} bytes)`),this.imageExtensions.includes(a)){u.debug(`[ReadSpecialFileTool] Image file detected: ${r}`);let E=(await Rr.readFile(r)).toString("base64"),v=this.imageMimeTypes[a]||"application/octet-stream";u.debug(`[ReadSpecialFileTool] Image converted to base64: ${l} (${E.length} chars)`);let x=Date.now()-o;return Q.result({toolName:"ReadSpecialFile",filePath:r,output:`Image loaded: ${l}`,success:!0,executionTime:x}),[{type:"image_url",image_url:{url:`data:${v};base64,${E}`}}]}let d=await this.uploadToBatchAPI(r,l);u.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${d}`);let g=await this.pollBatchStatus(d);u.debug("[ReadSpecialFileTool] Conversion completed");let m=g.files[0];if(!m||m.status==="failed"){let w=m?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${w}`}]}let p=await this.fetchFileContent(m.file_id);if(!p.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let h=c.size/1024,f=h/1024,y=f>=1?`${f.toFixed(2)} MB`:`${h.toFixed(2)} KB`,T=`# File: ${l}
75
75
  **Type:** ${a.toUpperCase()}
76
76
  **Size:** ${y}
77
77
  **Conversion:** ✅ Successful
78
78
 
79
79
  ---
80
80
 
81
- ${p.markdown_content}`,x=Date.now()-o;return Y.result({toolName:"ReadSpecialFile",filePath:r,output:`Successfully converted ${l} (${y})`,success:!0,executionTime:x}),[{type:"text",text:T}]}catch(a){u.debug(`[ReadSpecialFileTool] Failed to convert file: ${a.message}`);let c=`Error converting file: ${a.message}
81
+ ${p.markdown_content}`,C=Date.now()-o;return Q.result({toolName:"ReadSpecialFile",filePath:r,output:`Successfully converted ${l} (${y})`,success:!0,executionTime:C}),[{type:"text",text:T}]}catch(a){u.debug(`[ReadSpecialFileTool] Failed to convert file: ${a.message}`);let c=`Error converting file: ${a.message}
82
82
 
83
83
  This could be due to:
84
84
  • File corruption or invalid format
@@ -86,37 +86,37 @@ This could be due to:
86
86
  • Unsupported document structure
87
87
  • File is password-protected or encrypted
88
88
 
89
- For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,l=Date.now()-o;return Y.result({toolName:"ReadSpecialFile",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}async uploadToBatchAPI(e,t){let n=await Mr.readFile(e),s=Pi.extname(t).substring(1).toLowerCase(),o=await X.getInstance().getFirebaseIdToken(),a=new mp;a.append("files",n,{filename:t,contentType:this.getMimeType(s)});try{let c={...a.getHeaders()};o&&(c.Authorization=`Bearer ${o}`);let l=await ki.post(`${this.baseEndpoint}/convert-batch`,a,{headers:c,timeout:3e4});if(l.status!==202)throw new Error(`Upload failed with HTTP ${l.status}`);return l.data.request_id}catch(c){throw c.response?new Error(`Upload failed (HTTP ${c.response.status}): ${JSON.stringify(c.response.data)}`):new Error(`Upload failed: ${c.message}`)}}async pollBatchStatus(e){let n=await X.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);for(let r=1;r<=this.maxPollAttempts;r++)try{let a=(await ki.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4,headers:s})).data;if(u.debug(`[ReadSpecialFileTool] Poll ${r} - Status: ${a.files[0]?.status}, Progress: ${a.completed}/${a.total_files}`),a.completed+a.failed>=a.total_files)return a;await this.sleep(this.pollInterval)}catch(o){throw o.response?.status===404?new Error("Batch request not found or expired"):new Error(`Status check failed: ${o.message}`)}throw new Error(`Conversion timeout after ${this.maxPollAttempts*this.pollInterval/1e3} seconds`)}async fetchFileContent(e){let n=await X.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);try{let r=await ki.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4,headers:s});if(r.data.status==="failed")throw new Error(r.data.error||"Unknown conversion error");return r.data}catch(r){throw r.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${r.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 Or,il=F(()=>{"use strict";j();Tt();Ar();Or=class{toolNames=["write","Write","write_file"];async execute(e,t,n,s){let r=n.file_path,o=n.content,a=n.edits;if(!r)throw new Error("Missing file_path argument");let c=xn(r),l=Vn(c);if(!l.valid)return[{type:"text",text:`Error: ${l.error}`}];let d=Date.now();return Y.start("Write",n.description,c),o!=null?await this.executeSimpleWrite(c,o,d):await this.executeEditsMode(c,a,d)}async executeSimpleWrite(e,t,n){u.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let s=await import("fs/promises"),r=await import("path");try{let g=await s.stat(e);if(g.isDirectory()){let m=`Error: Cannot write to '${e}' - path is a directory, not a file.`,p=Date.now()-n;return Y.result({toolName:"Write",filePath:e,output:m,success:!1,executionTime:p}),[{type:"text",text:m}]}if(g.isFile()){let m=`Error: File already exists at '${e}'. Use the Edit tool to modify existing files, or delete the file first if you want to replace it entirely.`,p=Date.now()-n;return Y.result({toolName:"Write",filePath:e,output:m,success:!1,executionTime:p}),[{type:"text",text:m}]}}catch(g){if(g.code!=="ENOENT")throw g}let o=r.dirname(e);await s.mkdir(o,{recursive:!0}),await s.writeFile(e,t,"utf-8");let a=t.split(`
89
+ For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,l=Date.now()-o;return Q.result({toolName:"ReadSpecialFile",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}async uploadToBatchAPI(e,t){let n=await Rr.readFile(e),s=Pi.extname(t).substring(1).toLowerCase(),o=await X.getInstance().getFirebaseIdToken(),a=new mp;a.append("files",n,{filename:t,contentType:this.getMimeType(s)});try{let c={...a.getHeaders()};o&&(c.Authorization=`Bearer ${o}`);let l=await ki.post(`${this.baseEndpoint}/convert-batch`,a,{headers:c,timeout:3e4});if(l.status!==202)throw new Error(`Upload failed with HTTP ${l.status}`);return l.data.request_id}catch(c){throw c.response?new Error(`Upload failed (HTTP ${c.response.status}): ${JSON.stringify(c.response.data)}`):new Error(`Upload failed: ${c.message}`)}}async pollBatchStatus(e){let n=await X.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);for(let r=1;r<=this.maxPollAttempts;r++)try{let a=(await ki.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4,headers:s})).data;if(u.debug(`[ReadSpecialFileTool] Poll ${r} - Status: ${a.files[0]?.status}, Progress: ${a.completed}/${a.total_files}`),a.completed+a.failed>=a.total_files)return a;await this.sleep(this.pollInterval)}catch(o){throw o.response?.status===404?new Error("Batch request not found or expired"):new Error(`Status check failed: ${o.message}`)}throw new Error(`Conversion timeout after ${this.maxPollAttempts*this.pollInterval/1e3} seconds`)}async fetchFileContent(e){let n=await X.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);try{let r=await ki.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4,headers:s});if(r.data.status==="failed")throw new Error(r.data.error||"Unknown conversion error");return r.data}catch(r){throw r.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${r.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 Nr,il=$(()=>{"use strict";z();Tt();Dr();Nr=class{toolNames=["write","Write","write_file"];async execute(e,t,n,s){let r=n.file_path,o=n.content,a=n.edits;if(!r)throw new Error("Missing file_path argument");let c=En(r),l=Yn(c);if(!l.valid)return[{type:"text",text:`Error: ${l.error}`}];let d=Date.now();return Q.start("Write",n.description,c),o!=null?await this.executeSimpleWrite(c,o,d):await this.executeEditsMode(c,a,d)}async executeSimpleWrite(e,t,n){u.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let s=await import("fs/promises"),r=await import("path");try{let g=await s.stat(e);if(g.isDirectory()){let m=`Error: Cannot write to '${e}' - path is a directory, not a file.`,p=Date.now()-n;return Q.result({toolName:"Write",filePath:e,output:m,success:!1,executionTime:p}),[{type:"text",text:m}]}if(g.isFile()){let m=`Error: File already exists at '${e}'. Use the Edit tool to modify existing files, or delete the file first if you want to replace it entirely.`,p=Date.now()-n;return Q.result({toolName:"Write",filePath:e,output:m,success:!1,executionTime:p}),[{type:"text",text:m}]}}catch(g){if(g.code!=="ENOENT")throw g}let o=r.dirname(e);await s.mkdir(o,{recursive:!0}),await s.writeFile(e,t,"utf-8");let a=t.split(`
90
90
  `),c="";for(let g=0;g<Math.min(a.length,8);g++)c+=`+ ${a[g]}
91
91
  `;a.length>8&&(c+=`+ ...
92
92
 
93
- (${a.length-8} more lines)`);let l=c.trim();u.debug(`[WriteFileTool] Successfully wrote ${t.length} characters`);let d=Date.now()-n;return Y.result({toolName:"Write",filePath:e,output:l,success:!0,executionTime:d}),[{type:"text",text:l}]}catch(s){u.debug(`[WriteFileTool] Failed to write file: ${s.message}`);let r=`Error writing file: ${s.message}`,o=Date.now()-n;return Y.result({toolName:"Write",filePath:e,output:r,success:!1,executionTime:o}),[{type:"text",text:r}]}}async executeEditsMode(e,t,n){if(!t||!Array.isArray(t)||t.length===0)throw new Error("Missing content or edits array");if(t.length>50)throw new Error("Too many edit operations. Maximum 50 edits allowed per operation.");u.debug(`[WriteFileTool] Writing file: ${e} with ${t.length} edits`);try{let s=await import("fs/promises"),r=await import("path");for(let p=0;p<t.length;p++){let h=t[p];if(!h||typeof h!="object")throw new Error(`Edit operation ${p+1} must be an object with 'search' and 'replace' fields`);if(!h.hasOwnProperty("search")||typeof h.search!="string")throw new Error(`Edit operation ${p+1} missing required 'search' field (must be string)`);if(!h.hasOwnProperty("replace")||typeof h.replace!="string")throw new Error(`Edit operation ${p+1} missing required 'replace' field (must be string)`)}let o=t[0].search==="",a;if(o)if(u.debug("[WriteFileTool] Creating new file"),a="",t.length===1&&t[0].search===""){a=t[0].replace;let p=r.dirname(e);await s.mkdir(p,{recursive:!0}),await s.writeFile(e,a,"utf-8");let h=a.split(`
93
+ (${a.length-8} more lines)`);let l=c.trim();u.debug(`[WriteFileTool] Successfully wrote ${t.length} characters`);let d=Date.now()-n;return Q.result({toolName:"Write",filePath:e,output:l,success:!0,executionTime:d}),[{type:"text",text:l}]}catch(s){u.debug(`[WriteFileTool] Failed to write file: ${s.message}`);let r=`Error writing file: ${s.message}`,o=Date.now()-n;return Q.result({toolName:"Write",filePath:e,output:r,success:!1,executionTime:o}),[{type:"text",text:r}]}}async executeEditsMode(e,t,n){if(!t||!Array.isArray(t)||t.length===0)throw new Error("Missing content or edits array");if(t.length>50)throw new Error("Too many edit operations. Maximum 50 edits allowed per operation.");u.debug(`[WriteFileTool] Writing file: ${e} with ${t.length} edits`);try{let s=await import("fs/promises"),r=await import("path");for(let p=0;p<t.length;p++){let h=t[p];if(!h||typeof h!="object")throw new Error(`Edit operation ${p+1} must be an object with 'search' and 'replace' fields`);if(!h.hasOwnProperty("search")||typeof h.search!="string")throw new Error(`Edit operation ${p+1} missing required 'search' field (must be string)`);if(!h.hasOwnProperty("replace")||typeof h.replace!="string")throw new Error(`Edit operation ${p+1} missing required 'replace' field (must be string)`)}let o=t[0].search==="",a;if(o)if(u.debug("[WriteFileTool] Creating new file"),a="",t.length===1&&t[0].search===""){a=t[0].replace;let p=r.dirname(e);await s.mkdir(p,{recursive:!0}),await s.writeFile(e,a,"utf-8");let h=a.split(`
94
94
  `),f="";for(let y=0;y<Math.min(h.length,8);y++)f+=`+ ${h[y]}
95
95
  `;return h.length>8&&(f+=`+ ...
96
96
 
97
- (${h.length-8} more lines)`),u.debug(`[WriteFileTool] Created new file with ${a.length} characters`),[{type:"text",text:f.trim()}]}else throw new Error("For new files, only one edit with empty search string is allowed");else{u.debug("[WriteFileTool] Reading existing file");try{a=await s.readFile(e,"utf-8"),u.debug(`[WriteFileTool] Read ${a.length} characters from existing file`)}catch(p){throw p.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: ${p.message}`)}}let c=0,l=a,d=[];for(let p=0;p<t.length;p++){let h=t[p];if(u.debug(`[WriteFileTool] Applying edit ${p+1}/${t.length}`),h.search==="")if(o){d.push({index:p+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{u.debug("[WriteFileTool] Rewriting entire existing file"),l=h.replace,d.push({index:p+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),c++;continue}let f=l.indexOf(h.search);if(f!==-1)l=l.substring(0,f)+h.replace+l.substring(f+h.search.length),u.debug("[WriteFileTool] Replaced first occurrence"),d.push({index:p+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),c++;else{let y=`Search string not found: '${h.search}'`;return d.push({index:p+1,success:!1,message:y,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${p+1}: '${h.search}'\\n\\nEdit Summary:\\n- Total edits: ${d.length}\\n- Successful: ${d.filter(x=>x.success).length}\\n- Failed: ${d.filter(x=>!x.success).length}\\n\\nIndividual Edit Results:\\n`+d.map(x=>`${x.success?"✅":"❌"} Edit ${x.index}: ${x.message}`).join("\\n")}]}}await s.writeFile(e,l,"utf-8"),u.debug(`[WriteFileTool] Successfully wrote ${l.length} characters to file`);let g=l.split(`
97
+ (${h.length-8} more lines)`),u.debug(`[WriteFileTool] Created new file with ${a.length} characters`),[{type:"text",text:f.trim()}]}else throw new Error("For new files, only one edit with empty search string is allowed");else{u.debug("[WriteFileTool] Reading existing file");try{a=await s.readFile(e,"utf-8"),u.debug(`[WriteFileTool] Read ${a.length} characters from existing file`)}catch(p){throw p.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: ${p.message}`)}}let c=0,l=a,d=[];for(let p=0;p<t.length;p++){let h=t[p];if(u.debug(`[WriteFileTool] Applying edit ${p+1}/${t.length}`),h.search==="")if(o){d.push({index:p+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{u.debug("[WriteFileTool] Rewriting entire existing file"),l=h.replace,d.push({index:p+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),c++;continue}let f=l.indexOf(h.search);if(f!==-1)l=l.substring(0,f)+h.replace+l.substring(f+h.search.length),u.debug("[WriteFileTool] Replaced first occurrence"),d.push({index:p+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),c++;else{let y=`Search string not found: '${h.search}'`;return d.push({index:p+1,success:!1,message:y,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${p+1}: '${h.search}'\\n\\nEdit Summary:\\n- Total edits: ${d.length}\\n- Successful: ${d.filter(C=>C.success).length}\\n- Failed: ${d.filter(C=>!C.success).length}\\n\\nIndividual Edit Results:\\n`+d.map(C=>`${C.success?"✅":"❌"} Edit ${C.index}: ${C.message}`).join("\\n")}]}}await s.writeFile(e,l,"utf-8"),u.debug(`[WriteFileTool] Successfully wrote ${l.length} characters to file`);let g=l.split(`
98
98
  `),m="";for(let p=0;p<Math.min(g.length,8);p++)m+=`+ ${g[p]}
99
99
  `;return g.length>8&&(m+=`+ ...
100
100
 
101
- (${g.length-8} more lines)`),[{type:"text",text:m.trim()}]}catch(s){return u.debug(`[WriteFileTool] Failed to write file: ${s.message}`),[{type:"text",text:`Error writing file: ${s.message}`}]}}}});var Nr,al=F(()=>{"use strict";j();Tt();Ar();Nr=class{toolNames=["edit","Edit"];async execute(e,t,n,s){let r=n.file_path,o=n.old_string,a=n.new_string,c=n.replace_all===!0;if(!r)throw new Error("Missing file_path argument");if(o==null)throw new Error("Missing old_string argument");if(a==null)throw new Error("Missing new_string argument");let l=xn(r),d=Vn(l);if(!d.valid)return[{type:"text",text:`Error: ${d.error}`}];u.debug(`[EditFileTool] Editing file: ${l}`);let g=Date.now();Y.start("Edit",n.description,l);try{let m=await import("fs/promises"),p=await m.readFile(l,"utf-8"),h,f=0;if(c)for(h=p;h.includes(o);)h=h.replace(o,a),f++;else p.includes(o)?(h=p.replace(o,a),f=1):h=p;if(f===0){let C=`No matches found for the specified old_string in file: ${l}`,v=Date.now()-g;return Y.result({toolName:"Edit",filePath:l,output:C,success:!1,executionTime:v}),[{type:"text",text:C}]}await m.writeFile(l,h,"utf-8");let y=`Successfully edited file: Replaced ${f} occurrence(s)`;u.debug(`[EditFileTool] ${y}`);let T=Date.now()-g,x=(await import("chalk")).default,w=`${x.red("- "+o.split(`
101
+ (${g.length-8} more lines)`),[{type:"text",text:m.trim()}]}catch(s){return u.debug(`[WriteFileTool] Failed to write file: ${s.message}`),[{type:"text",text:`Error writing file: ${s.message}`}]}}}});var _r,al=$(()=>{"use strict";z();Tt();Dr();_r=class{toolNames=["edit","Edit"];async execute(e,t,n,s){let r=n.file_path,o=n.old_string,a=n.new_string,c=n.replace_all===!0;if(!r)throw new Error("Missing file_path argument");if(o==null)throw new Error("Missing old_string argument");if(a==null)throw new Error("Missing new_string argument");let l=En(r),d=Yn(l);if(!d.valid)return[{type:"text",text:`Error: ${d.error}`}];u.debug(`[EditFileTool] Editing file: ${l}`);let g=Date.now();Q.start("Edit",n.description,l);try{let m=await import("fs/promises"),p=await m.readFile(l,"utf-8"),h,f=0;if(c)for(h=p;h.includes(o);)h=h.replace(o,a),f++;else p.includes(o)?(h=p.replace(o,a),f=1):h=p;if(f===0){let E=`No matches found for the specified old_string in file: ${l}`,v=Date.now()-g;return Q.result({toolName:"Edit",filePath:l,output:E,success:!1,executionTime:v}),[{type:"text",text:E}]}await m.writeFile(l,h,"utf-8");let y=`Successfully edited file: Replaced ${f} occurrence(s)`;u.debug(`[EditFileTool] ${y}`);let T=Date.now()-g,C=(await import("chalk")).default,w=`${C.red("- "+o.split(`
102
102
  `).slice(0,5).join(`
103
103
  - `))}
104
- ${x.green("+ "+a.split(`
104
+ ${C.green("+ "+a.split(`
105
105
  `).slice(0,5).join(`
106
106
  + `))}
107
107
 
108
- Replaced ${f} occurrence(s)`;return Y.result({toolName:"Edit",filePath:l,output:w,success:!0,executionTime:T}),[{type:"text",text:y}]}catch(m){u.debug(`[EditFileTool] Failed to edit file: ${m.message}`);let p=`Error editing file: ${m.message}`,h=Date.now()-g;return Y.result({toolName:"Edit",filePath:l,output:p,success:!1,executionTime:h}),[{type:"text",text:p}]}}}});var _r,cl=F(()=>{"use strict";j();_r=class{toolNames=["upload_file"];async execute(e,t,n,s){let r=n.file_path;if(!r)throw new Error("Missing file_path argument");return u.debug(`[UploadFileTool] Upload file not implemented for CLI: ${r}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${r}`}]}}});import Ai from"fs/promises";import pp from"path";import hp from"form-data";import fp from"axios";var $r,ll=F(()=>{"use strict";j();Tt();Te();$r=class{toolNames=["deploy_zip_html","DeployZipHTML"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let r=n.zip_file_path;if(!r)throw new Error("Missing zip_file_path argument");let o=Date.now();Y.start("DeployZipHTML",n.description,r);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let S=Math.ceil((this.windowMs-(a-this.lastDeployTime))/1e3);throw new Error(`Rate limit exceeded. You can only deploy ${this.maxDeploysPerWindow} projects every ${this.windowMs/6e4} minutes. Please try again in ${S} seconds.`)}u.debug(`[DeployZipHTML] Deploying HTML project: ${r}`);try{await Ai.access(r)}catch{throw new Error(`ZIP file not found at path: ${r}`)}if(!r.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${r}`);let c=await Ai.stat(r),l=100*1024*1024;if(c.size>l)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(c.size/1024/1024).toFixed(2)}MB`);let d=await Ai.readFile(r),g=pp.basename(r).replace(/[\r\n\t"']/g,"_");u.debug(`[DeployZipHTML] File: ${g}, Size: ${c.size} bytes`);let p=await X.getInstance().getFirebaseIdToken();if(!p)throw new Error("User must be authenticated to deploy projects");let h=new hp;h.append("zipFile",d,{filename:g,contentType:"application/zip"});let f="https://snowx.ai/api/v2/deploy-zip";u.debug(`[DeployZipHTML] Uploading to ${f}`);let y=await fp.post(f,h,{headers:{...h.getHeaders(),Authorization:`Bearer ${p}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(y.status!==200&&y.status!==201)throw new Error(`Deployment failed with status ${y.status}: ${JSON.stringify(y.data)}`);let T=y.data;u.debug("[DeployZipHTML] Deployed successfully"),u.debug(`[DeployZipHTML] Response: ${JSON.stringify(T,null,2)}`);let x=T.data?.deployUrl||T.deployUrl||T.url||T.deploymentUrl||T.site_url||T.siteUrl||T.website_url,w=T.data?.deployId||T.deployId||T.projectId||T.deploymentId,C=T.data?.siteId||T.siteId;this.deployCount++;let v=`# HTML Project Deployed Successfully!
108
+ Replaced ${f} occurrence(s)`;return Q.result({toolName:"Edit",filePath:l,output:w,success:!0,executionTime:T}),[{type:"text",text:y}]}catch(m){u.debug(`[EditFileTool] Failed to edit file: ${m.message}`);let p=`Error editing file: ${m.message}`,h=Date.now()-g;return Q.result({toolName:"Edit",filePath:l,output:p,success:!1,executionTime:h}),[{type:"text",text:p}]}}}});var $r,cl=$(()=>{"use strict";z();$r=class{toolNames=["upload_file"];async execute(e,t,n,s){let r=n.file_path;if(!r)throw new Error("Missing file_path argument");return u.debug(`[UploadFileTool] Upload file not implemented for CLI: ${r}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${r}`}]}}});import Ai from"fs/promises";import pp from"path";import hp from"form-data";import fp from"axios";var Fr,ll=$(()=>{"use strict";z();Tt();xe();Fr=class{toolNames=["deploy_zip_html","DeployZipHTML"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let r=n.zip_file_path;if(!r)throw new Error("Missing zip_file_path argument");let o=Date.now();Q.start("DeployZipHTML",n.description,r);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let S=Math.ceil((this.windowMs-(a-this.lastDeployTime))/1e3);throw new Error(`Rate limit exceeded. You can only deploy ${this.maxDeploysPerWindow} projects every ${this.windowMs/6e4} minutes. Please try again in ${S} seconds.`)}u.debug(`[DeployZipHTML] Deploying HTML project: ${r}`);try{await Ai.access(r)}catch{throw new Error(`ZIP file not found at path: ${r}`)}if(!r.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${r}`);let c=await Ai.stat(r),l=100*1024*1024;if(c.size>l)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(c.size/1024/1024).toFixed(2)}MB`);let d=await Ai.readFile(r),g=pp.basename(r).replace(/[\r\n\t"']/g,"_");u.debug(`[DeployZipHTML] File: ${g}, Size: ${c.size} bytes`);let p=await X.getInstance().getFirebaseIdToken();if(!p)throw new Error("User must be authenticated to deploy projects");let h=new hp;h.append("zipFile",d,{filename:g,contentType:"application/zip"});let f="https://snowx.ai/api/v2/deploy-zip";u.debug(`[DeployZipHTML] Uploading to ${f}`);let y=await fp.post(f,h,{headers:{...h.getHeaders(),Authorization:`Bearer ${p}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(y.status!==200&&y.status!==201)throw new Error(`Deployment failed with status ${y.status}: ${JSON.stringify(y.data)}`);let T=y.data;u.debug("[DeployZipHTML] Deployed successfully"),u.debug(`[DeployZipHTML] Response: ${JSON.stringify(T,null,2)}`);let C=T.data?.deployUrl||T.deployUrl||T.url||T.deploymentUrl||T.site_url||T.siteUrl||T.website_url,w=T.data?.deployId||T.deployId||T.projectId||T.deploymentId,E=T.data?.siteId||T.siteId;this.deployCount++;let v=`# HTML Project Deployed Successfully!
109
109
 
110
- **Deployment URL**: ${x}
110
+ **Deployment URL**: ${C}
111
111
 
112
112
  **Project**: ${g}
113
113
  **Type**: Static HTML
114
114
  ${w?`**Deploy ID**: ${w}
115
- `:""}${C?`**Site ID**: ${C}
115
+ `:""}${E?`**Site ID**: ${E}
116
116
  `:""}
117
117
  Your site is now live and accessible!
118
118
 
119
- ${T.message||""}`,E=Date.now()-o;return Y.result({toolName:"DeployZipHTML",filePath:r,output:`Deployed to ${x}`,success:!0,executionTime:E}),[{type:"text",text:v}]}catch(a){u.error(`[DeployZipHTML] Deployment failed: ${a.message}`);let c=`HTML deployment failed
119
+ ${T.message||""}`,x=Date.now()-o;return Q.result({toolName:"DeployZipHTML",filePath:r,output:`Deployed to ${C}`,success:!0,executionTime:x}),[{type:"text",text:v}]}catch(a){u.error(`[DeployZipHTML] Deployment failed: ${a.message}`);let c=`HTML deployment failed
120
120
 
121
121
  ${a.message}
122
122
 
@@ -127,18 +127,18 @@ Troubleshooting:
127
127
  4. Check network connectivity
128
128
  5. Ensure ZIP file is under 100MB
129
129
 
130
- If the issue persists, contact support.`,l=Date.now()-o;return Y.result({toolName:"DeployZipHTML",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});import Di from"fs/promises";import bp from"path";import yp from"form-data";import vp from"axios";var Fr,ul=F(()=>{"use strict";j();Tt();Te();Fr=class{toolNames=["deploy_zip_react","DeployZipReact"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let r=n.zip_file_path;if(!r)throw new Error("Missing zip_file_path argument");let o=Date.now();Y.start("DeployZipReact",n.description,r);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let S=Math.ceil((this.windowMs-(a-this.lastDeployTime))/1e3);throw new Error(`Rate limit exceeded. You can only deploy ${this.maxDeploysPerWindow} projects every ${this.windowMs/6e4} minutes. Please try again in ${S} seconds.`)}u.debug(`[DeployZipReact] Deploying React project: ${r}`);try{await Di.access(r)}catch{throw new Error(`ZIP file not found at path: ${r}`)}if(!r.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${r}`);let c=await Di.stat(r),l=100*1024*1024;if(c.size>l)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(c.size/1024/1024).toFixed(2)}MB`);let d=await Di.readFile(r),g=bp.basename(r).replace(/[\r\n\t"']/g,"_");u.debug(`[DeployZipReact] File: ${g}, Size: ${c.size} bytes`);let p=await X.getInstance().getFirebaseIdToken();if(!p)throw new Error("User must be authenticated to deploy projects");let h=new yp;h.append("zipFile",d,{filename:g,contentType:"application/zip"});let f="https://snowx.ai/api/v2/deploy-zip-react";u.debug(`[DeployZipReact] Uploading to ${f}`);let y=await vp.post(f,h,{headers:{...h.getHeaders(),Authorization:`Bearer ${p}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(y.status!==200&&y.status!==201)throw new Error(`Deployment failed with status ${y.status}: ${JSON.stringify(y.data)}`);let T=y.data;u.debug("[DeployZipReact] Deployed successfully"),u.debug(`[DeployZipReact] Response: ${JSON.stringify(T,null,2)}`);let x=T.data?.deployUrl||T.deployUrl||T.url||T.deploymentUrl||T.site_url||T.siteUrl||T.website_url,w=T.data?.deployId||T.deployId||T.projectId||T.deploymentId,C=T.data?.siteId||T.siteId;this.deployCount++;let v=`# React Project Deployed Successfully!
130
+ If the issue persists, contact support.`,l=Date.now()-o;return Q.result({toolName:"DeployZipHTML",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});import Di from"fs/promises";import bp from"path";import yp from"form-data";import vp from"axios";var Lr,ul=$(()=>{"use strict";z();Tt();xe();Lr=class{toolNames=["deploy_zip_react","DeployZipReact"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let r=n.zip_file_path;if(!r)throw new Error("Missing zip_file_path argument");let o=Date.now();Q.start("DeployZipReact",n.description,r);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let S=Math.ceil((this.windowMs-(a-this.lastDeployTime))/1e3);throw new Error(`Rate limit exceeded. You can only deploy ${this.maxDeploysPerWindow} projects every ${this.windowMs/6e4} minutes. Please try again in ${S} seconds.`)}u.debug(`[DeployZipReact] Deploying React project: ${r}`);try{await Di.access(r)}catch{throw new Error(`ZIP file not found at path: ${r}`)}if(!r.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${r}`);let c=await Di.stat(r),l=100*1024*1024;if(c.size>l)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(c.size/1024/1024).toFixed(2)}MB`);let d=await Di.readFile(r),g=bp.basename(r).replace(/[\r\n\t"']/g,"_");u.debug(`[DeployZipReact] File: ${g}, Size: ${c.size} bytes`);let p=await X.getInstance().getFirebaseIdToken();if(!p)throw new Error("User must be authenticated to deploy projects");let h=new yp;h.append("zipFile",d,{filename:g,contentType:"application/zip"});let f="https://snowx.ai/api/v2/deploy-zip-react";u.debug(`[DeployZipReact] Uploading to ${f}`);let y=await vp.post(f,h,{headers:{...h.getHeaders(),Authorization:`Bearer ${p}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(y.status!==200&&y.status!==201)throw new Error(`Deployment failed with status ${y.status}: ${JSON.stringify(y.data)}`);let T=y.data;u.debug("[DeployZipReact] Deployed successfully"),u.debug(`[DeployZipReact] Response: ${JSON.stringify(T,null,2)}`);let C=T.data?.deployUrl||T.deployUrl||T.url||T.deploymentUrl||T.site_url||T.siteUrl||T.website_url,w=T.data?.deployId||T.deployId||T.projectId||T.deploymentId,E=T.data?.siteId||T.siteId;this.deployCount++;let v=`# React Project Deployed Successfully!
131
131
 
132
- **Deployment URL**: ${x}
132
+ **Deployment URL**: ${C}
133
133
 
134
134
  **Project**: ${g}
135
135
  **Type**: React / SPA
136
136
  ${w?`**Deploy ID**: ${w}
137
- `:""}${C?`**Site ID**: ${C}
137
+ `:""}${E?`**Site ID**: ${E}
138
138
  `:""}
139
139
  Your React app is now live and accessible!
140
140
 
141
- ${T.message||""}`,E=Date.now()-o;return Y.result({toolName:"DeployZipReact",filePath:r,output:`Deployed to ${x}`,success:!0,executionTime:E}),[{type:"text",text:v}]}catch(a){u.error(`[DeployZipReact] Deployment failed: ${a.message}`);let c=`React deployment failed
141
+ ${T.message||""}`,x=Date.now()-o;return Q.result({toolName:"DeployZipReact",filePath:r,output:`Deployed to ${C}`,success:!0,executionTime:x}),[{type:"text",text:v}]}catch(a){u.error(`[DeployZipReact] Deployment failed: ${a.message}`);let c=`React deployment failed
142
142
 
143
143
  ${a.message}
144
144
 
@@ -149,8 +149,8 @@ Troubleshooting:
149
149
  4. Check network connectivity
150
150
  5. Ensure ZIP file is under 100MB
151
151
 
152
- If the issue persists, contact support.`,l=Date.now()-o;return Y.result({toolName:"DeployZipReact",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});var dl=F(()=>{"use strict"});function Sp(i){let e=i.toLowerCase();if(!e.includes("|"))return!1;let t=e.split("|"),s=t[t.length-1].trim().split(/\s+/)[0]||"";return new Set(["head","tail","sed","awk","cut","wc","uniq","sort","grep","fgrep","egrep","rg","ag","tee","cat","tr","fold","fmt","nl","pr"]).has(s)}function $s(i){let e=i.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(Sp(i))return ut.pipedWithTerminator;if(i.includes("<<")&&(i.includes("EOF")||i.includes("'EOF'")||i.includes('"EOF"')||i.includes("END")||i.includes("SCRIPT")||i.includes("DOC")))return ut.extended;let n=["python","python3","python2","node ",`node
153
- `,"ruby","perl","php","julia","r ","rscript","scala","groovy","kotlin"];for(let l of n)if(e.includes(l))return ut.extended;let s=["pandas","numpy","scipy","matplotlib","import pd","import np","read_csv","read_excel","to_csv","dataframe","groupby","merge"];for(let l of s)if(e.includes(l))return ut.extended;return(i.match(/\n/g)||[]).length>5?ut.extended:new Set(["echo","pwd","date","whoami","id","hostname","uname","which","type","true","false","printf","env","printenv","basename","dirname","realpath","readlink","write-host","write-output","get-date","get-location","hostname.exe"]).has(t)?ut.instant:new Set(["ls","cat","head","tail","wc","grep","awk","sed","sort","uniq","cut","tr","stat","file","du","df","free","uptime","ps","touch","mkdir","rmdir","mv","cp","chmod","chown","ln","test","[","expr","dir","get-childitem","get-content","select-object","where-object","measure-object","sort-object","get-process","get-service"]).has(t)?i.length<100?ut.fast:ut.default:new Set(["make","cmake","npm","yarn","pnpm","pip","pip3","pipx","cargo","mvn","gradle","ant","docker","docker-compose","podman","git","rsync","scp","sftp","ssh","curl","wget","aria2c","find","locate","updatedb","mlocate","tar","zip","unzip","gzip","bzip2","xz","7z","brew","apt","apt-get","yum","dnf","pacman","apk","convert","ffmpeg","imagemagick","install-module","update-module","invoke-webrequest","start-job","invoke-command","enter-pssession","new-pssession","msiexec"]).has(t)?ut.extended:i.includes("|")?ut.default:i.length<30?ut.fast:ut.default}var ut,Mi=F(()=>{"use strict";dl();ut={instant:{activityTimeout:1e3,maxTimeout:3e3,initialTimeout:500,useActivityTimeout:!1},fast:{activityTimeout:2e3,maxTimeout:1e4,initialTimeout:2e3,useActivityTimeout:!1},default:{activityTimeout:15e3,maxTimeout:12e4,initialTimeout:1e4,useActivityTimeout:!0},extended:{activityTimeout:3e4,maxTimeout:3e5,initialTimeout:3e4,useActivityTimeout:!0},pipedWithTerminator:{activityTimeout:5e3,maxTimeout:6e4,initialTimeout:1e4,useActivityTimeout:!0}}});import{spawn as wp,exec as Tp,execSync as xp}from"child_process";import{promisify as Cp}from"util";function Ni(){return process.platform}function Ft(){return process.platform==="win32"}function kp(){return process.platform==="darwin"}function Xn(i,e="SIGTERM"){if(i)try{if(Ft())try{xp(`taskkill /PID ${i} /T /F`,{timeout:5e3,stdio:"ignore"})}catch{}else try{process.kill(-i,e)}catch{try{process.kill(i,e)}catch{}}}catch(t){u.debug(`[killProcessTree] Failed for PID ${i}: ${t}`)}}function Pp(i){let e=i.trim().toLowerCase();if(e.startsWith("sudo "))return{isPrivileged:!0,reason:"Direct sudo usage"};if(/(\||&&|;)\s*sudo\s+/.test(e))return{isPrivileged:!0,reason:"Sudo in command chain"};if(Ft()&&(e.includes("runas")||e.includes("-verb")&&e.includes("runas")||e.includes("start-process")&&e.includes("runas")))return{isPrivileged:!0,reason:"Windows administrator elevation"};let s=["apt-get","apt ","yum ","dnf ","pacman ","zypper ","systemctl ","service ","mount ","umount ","iptables ","firewall-cmd ","useradd ","userdel ","usermod ","groupadd ","groupdel ","chmod 777","chown "].find(a=>e.startsWith(a)||e.includes(`&& ${a}`)||e.includes(`; ${a}`)||e.includes(`| ${a}`));if(s)return{isPrivileged:!0,reason:`Privileged command: ${s.trim()}`};let o=[{pattern:/>\s*\/etc\//,desc:"Writing to /etc/"},{pattern:/>\s*\/usr\//,desc:"Writing to /usr/"},{pattern:/>\s*\/var\//,desc:"Writing to /var/"},{pattern:/>\s*\/opt\//,desc:"Writing to /opt/"},{pattern:/>\s*\/System\//,desc:"Writing to /System/ (macOS)"},{pattern:/tee\s+\/etc\//,desc:"Tee to /etc/"},{pattern:/tee\s+\/usr\//,desc:"Tee to /usr/"},{pattern:/tee\s+\/var\//,desc:"Tee to /var/"}].find(({pattern:a})=>a.test(e));return o?{isPrivileged:!0,reason:o.desc}:{isPrivileged:!1}}function gl(){return Ft()?"PowerShell or Command Prompt":(kp(),"Terminal")}function Ri(i,e,t="max",n){let s=f=>{if(f>=6e4){let T=Math.round(f/6e4);return`${T} minute${T>1?"s":""}`}let y=Math.round(f/1e3);return`${y} second${y>1?"s":""}`},r=()=>{switch(process.platform){case"darwin":return"Terminal.app (or iTerm2)";case"win32":return"PowerShell or Windows Terminal";case"linux":return"your terminal emulator (e.g., GNOME Terminal, Konsole)";default:return"your system terminal"}},o=()=>{switch(process.platform){case"darwin":return'Press Cmd+Space, type "Terminal", and press Enter';case"win32":return'Press Win+X and select "Windows Terminal" or "PowerShell"';case"linux":return"Press Ctrl+Alt+T or open your terminal from the applications menu";default:return"Open your system terminal application"}},a=()=>process.platform==="darwin"?["","🔍 Tip: You can also start the command in Terminal and ask me to monitor it."," I can track running Terminal processes and capture their output using the"," MonitorRunningCli tool - just tell me the Terminal window/tab to monitor."]:null,c=()=>{switch(t){case"max":return`The command exceeded the maximum allowed execution time of ${s(e)}.`;case"initial":return`The command produced no output within the initial ${s(e)} window.`;case"activity":return`The command stopped producing output for ${s(e)} (activity timeout).`;default:return`The command timed out after ${s(e)}.`}},l=r(),d=o(),g=c(),m=a(),p=["","❌ Command Timed Out","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","",g,""];n&&p.push(`Details: ${n}`,"");let h=i.length>100?i.substring(0,97)+"...":i;return p.push(`Command: ${h}`,""),p.push(`💡 For long-running commands, consider using ${l}:`,"",` 1. ${d}`," 2. Run your command there:",` ${h}`," 3. The command will continue running regardless of duration",""),m&&p.push(...m),p.push("","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","This is expected behavior for commands that take a long time to execute.","The Bash tool is designed for quick operations and has built-in timeouts","to prevent hanging indefinitely."),p.join(`
152
+ If the issue persists, contact support.`,l=Date.now()-o;return Q.result({toolName:"DeployZipReact",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});var dl=$(()=>{"use strict"});function Sp(i){let e=i.toLowerCase();if(!e.includes("|"))return!1;let t=e.split("|"),s=t[t.length-1].trim().split(/\s+/)[0]||"";return new Set(["head","tail","sed","awk","cut","wc","uniq","sort","grep","fgrep","egrep","rg","ag","tee","cat","tr","fold","fmt","nl","pr"]).has(s)}function Fs(i){let e=i.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(Sp(i))return ut.pipedWithTerminator;if(i.includes("<<")&&(i.includes("EOF")||i.includes("'EOF'")||i.includes('"EOF"')||i.includes("END")||i.includes("SCRIPT")||i.includes("DOC")))return ut.extended;let n=["python","python3","python2","node ",`node
153
+ `,"ruby","perl","php","julia","r ","rscript","scala","groovy","kotlin"];for(let l of n)if(e.includes(l))return ut.extended;let s=["pandas","numpy","scipy","matplotlib","import pd","import np","read_csv","read_excel","to_csv","dataframe","groupby","merge"];for(let l of s)if(e.includes(l))return ut.extended;return(i.match(/\n/g)||[]).length>5?ut.extended:new Set(["echo","pwd","date","whoami","id","hostname","uname","which","type","true","false","printf","env","printenv","basename","dirname","realpath","readlink","write-host","write-output","get-date","get-location","hostname.exe"]).has(t)?ut.instant:new Set(["ls","cat","head","tail","wc","grep","awk","sed","sort","uniq","cut","tr","stat","file","du","df","free","uptime","ps","touch","mkdir","rmdir","mv","cp","chmod","chown","ln","test","[","expr","dir","get-childitem","get-content","select-object","where-object","measure-object","sort-object","get-process","get-service"]).has(t)?i.length<100?ut.fast:ut.default:new Set(["make","cmake","npm","yarn","pnpm","pip","pip3","pipx","cargo","mvn","gradle","ant","docker","docker-compose","podman","git","rsync","scp","sftp","ssh","curl","wget","aria2c","find","locate","updatedb","mlocate","tar","zip","unzip","gzip","bzip2","xz","7z","brew","apt","apt-get","yum","dnf","pacman","apk","convert","ffmpeg","imagemagick","install-module","update-module","invoke-webrequest","start-job","invoke-command","enter-pssession","new-pssession","msiexec"]).has(t)?ut.extended:i.includes("|")?ut.default:i.length<30?ut.fast:ut.default}var ut,Mi=$(()=>{"use strict";dl();ut={instant:{activityTimeout:1e3,maxTimeout:3e3,initialTimeout:500,useActivityTimeout:!1},fast:{activityTimeout:2e3,maxTimeout:1e4,initialTimeout:2e3,useActivityTimeout:!1},default:{activityTimeout:15e3,maxTimeout:12e4,initialTimeout:1e4,useActivityTimeout:!0},extended:{activityTimeout:3e4,maxTimeout:3e5,initialTimeout:3e4,useActivityTimeout:!0},pipedWithTerminator:{activityTimeout:5e3,maxTimeout:6e4,initialTimeout:1e4,useActivityTimeout:!0}}});import{spawn as wp,exec as Tp,execSync as xp}from"child_process";import{promisify as Cp}from"util";function Ni(){return process.platform}function Lt(){return process.platform==="win32"}function kp(){return process.platform==="darwin"}function Qn(i,e="SIGTERM"){if(i)try{if(Lt())try{xp(`taskkill /PID ${i} /T /F`,{timeout:5e3,stdio:"ignore"})}catch{}else try{process.kill(-i,e)}catch{try{process.kill(i,e)}catch{}}}catch(t){u.debug(`[killProcessTree] Failed for PID ${i}: ${t}`)}}function Pp(i){let e=i.trim().toLowerCase();if(e.startsWith("sudo "))return{isPrivileged:!0,reason:"Direct sudo usage"};if(/(\||&&|;)\s*sudo\s+/.test(e))return{isPrivileged:!0,reason:"Sudo in command chain"};if(Lt()&&(e.includes("runas")||e.includes("-verb")&&e.includes("runas")||e.includes("start-process")&&e.includes("runas")))return{isPrivileged:!0,reason:"Windows administrator elevation"};let s=["apt-get","apt ","yum ","dnf ","pacman ","zypper ","systemctl ","service ","mount ","umount ","iptables ","firewall-cmd ","useradd ","userdel ","usermod ","groupadd ","groupdel ","chmod 777","chown "].find(a=>e.startsWith(a)||e.includes(`&& ${a}`)||e.includes(`; ${a}`)||e.includes(`| ${a}`));if(s)return{isPrivileged:!0,reason:`Privileged command: ${s.trim()}`};let o=[{pattern:/>\s*\/etc\//,desc:"Writing to /etc/"},{pattern:/>\s*\/usr\//,desc:"Writing to /usr/"},{pattern:/>\s*\/var\//,desc:"Writing to /var/"},{pattern:/>\s*\/opt\//,desc:"Writing to /opt/"},{pattern:/>\s*\/System\//,desc:"Writing to /System/ (macOS)"},{pattern:/tee\s+\/etc\//,desc:"Tee to /etc/"},{pattern:/tee\s+\/usr\//,desc:"Tee to /usr/"},{pattern:/tee\s+\/var\//,desc:"Tee to /var/"}].find(({pattern:a})=>a.test(e));return o?{isPrivileged:!0,reason:o.desc}:{isPrivileged:!1}}function gl(){return Lt()?"PowerShell or Command Prompt":(kp(),"Terminal")}function Ri(i,e,t="max",n){let s=f=>{if(f>=6e4){let T=Math.round(f/6e4);return`${T} minute${T>1?"s":""}`}let y=Math.round(f/1e3);return`${y} second${y>1?"s":""}`},r=()=>{switch(process.platform){case"darwin":return"Terminal.app (or iTerm2)";case"win32":return"PowerShell or Windows Terminal";case"linux":return"your terminal emulator (e.g., GNOME Terminal, Konsole)";default:return"your system terminal"}},o=()=>{switch(process.platform){case"darwin":return'Press Cmd+Space, type "Terminal", and press Enter';case"win32":return'Press Win+X and select "Windows Terminal" or "PowerShell"';case"linux":return"Press Ctrl+Alt+T or open your terminal from the applications menu";default:return"Open your system terminal application"}},a=()=>process.platform==="darwin"?["","🔍 Tip: You can also start the command in Terminal and ask me to monitor it."," I can track running Terminal processes and capture their output using the"," MonitorRunningCli tool - just tell me the Terminal window/tab to monitor."]:null,c=()=>{switch(t){case"max":return`The command exceeded the maximum allowed execution time of ${s(e)}.`;case"initial":return`The command produced no output within the initial ${s(e)} window.`;case"activity":return`The command stopped producing output for ${s(e)} (activity timeout).`;default:return`The command timed out after ${s(e)}.`}},l=r(),d=o(),g=c(),m=a(),p=["","❌ Command Timed Out","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","",g,""];n&&p.push(`Details: ${n}`,"");let h=i.length>100?i.substring(0,97)+"...":i;return p.push(`Command: ${h}`,""),p.push(`💡 For long-running commands, consider using ${l}:`,"",` 1. ${d}`," 2. Run your command there:",` ${h}`," 3. The command will continue running regardless of duration",""),m&&p.push(...m),p.push("","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","This is expected behavior for commands that take a long time to execute.","The Bash tool is designed for quick operations and has built-in timeouts","to prevent hanging indefinitely."),p.join(`
154
154
  `)}function Ap(i,e){let t=gl();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
155
155
 
156
156
  Reason: ${e}
@@ -195,17 +195,17 @@ The Bash tool will NEVER execute commands that could destroy your system.
195
195
  If you believe this is a false positive, please:
196
196
  1. Review the command carefully
197
197
  2. Run it manually in your terminal if you're certain it's safe
198
- 3. Consider breaking down the operation into safer steps`}function ml(i){let e=Op(i);if(e.isCatastrophic)return Np(i,e);let t=Pp(i);if(t.isPrivileged)return Ap(i,t.reason||"Privileged command detected");let n=Dp(i);return n.isInteractive?Mp(i,n.reason||"Interactive command detected"):null}function pl(i){let e=i.trim();for(let t of _p)if(t.test(e))return{isDelete:!0,paths:$p(e),category:Fp(e)};return{isDelete:!1,paths:[]}}function $p(i){let e=[],t=i.split(/\s+/),n=!1;for(let s=1;s<t.length;s++){let r=t[s];if(n){n=!1;continue}if(r.startsWith("-")){["-f","-o","-t","--target","--output"].includes(r)&&(n=!0);continue}r.length>0&&!r.startsWith("-")&&e.push(r)}return e}function Fp(i){let e=i.toLowerCase();return/^(rm|rmdir|unlink|del|rd|erase|remove-item)/i.test(e)?"File/Directory Deletion":/^git\s+(rm|clean)/.test(e)?"Git File Deletion":/^docker\s+volume/.test(e)?"Docker Volume Deletion":/^(aws\s+s3|gsutil|az\s+storage|rclone)/.test(e)?"Cloud Storage Deletion":/drop\s+(table|database|schema)/i.test(e)||/^(dropdb|dropuser)/.test(e)?"Database Deletion":/^(dd|mkfs|format|fdisk|parted|gdisk)/.test(e)?"Disk/Filesystem Operation":"Delete Operation"}var Ep,Ip,Fs,Oi,Ue,Ls,Rp,_p,Yn=F(()=>{"use strict";Mi();Kn();j();Ep=Cp(Tp),Ip=8500,Fs=new lt({maxResponseTokens:Ip});Oi=class{processes=new Map;MAX_COMPLETED_PROCESSES=50;COMPLETED_PROCESS_TTL=1800*1e3;addProcess(e){this.processes.set(e.id,e),this.cleanupOldProcesses(),u.debug(`[BackgroundProcessManager] Added process: ${e.id}`)}getProcess(e){return this.processes.get(e)}removeProcess(e){this.processes.delete(e),u.debug(`[BackgroundProcessManager] Removed process: ${e}`)}getAllProcesses(){return Array.from(this.processes.values())}getRunningProcesses(){return Array.from(this.processes.values()).filter(e=>e.status==="running")}getCompletedProcesses(){return Array.from(this.processes.values()).filter(e=>e.status!=="running")}updateProcess(e,t){let n=this.processes.get(e);return n?(Object.assign(n,t),u.debug(`[BackgroundProcessManager] Updated process: ${e}, status: ${n.status}`),!0):!1}cleanupOldProcesses(){let e=Date.now(),t=[],n=Array.from(this.processes.entries());for(let o=0;o<n.length;o++){let[a,c]=n[o];c.status!=="running"&&c.endTime&&t.push({id:a,endTime:c.endTime.getTime()})}let s=0;for(let o=0;o<t.length;o++){let{id:a,endTime:c}=t[o];e-c>this.COMPLETED_PROCESS_TTL&&(this.processes.delete(a),s++)}s>0&&u.debug(`[BackgroundProcessManager] Cleaned up ${s} old processes by TTL`);let r=t.filter(o=>e-o.endTime<=this.COMPLETED_PROCESS_TTL);if(r.length>this.MAX_COMPLETED_PROCESSES){r.sort((a,c)=>a.endTime-c.endTime);let o=r.slice(0,r.length-this.MAX_COMPLETED_PROCESSES);for(let a=0;a<o.length;a++){let{id:c}=o[a];this.processes.delete(c)}u.debug(`[BackgroundProcessManager] Cleaned up ${o.length} excess processes`)}}forceCleanupCompleted(){let e=0,t=Array.from(this.processes.entries());for(let n=0;n<t.length;n++){let[s,r]=t[n];r.status!=="running"&&(this.processes.delete(s),e++)}return u.debug(`[BackgroundProcessManager] Force cleaned ${e} completed processes`),e}getStats(){let e=this.getAllProcesses(),t=e.filter(n=>n.status==="running").length;return{total:e.length,running:t,completed:e.length-t}}clear(){this.processes.clear(),u.debug("[BackgroundProcessManager] Cleared all processes")}},Ue=new Oi;Ls=class i{static instance;constructor(){}static getInstance(){return i.instance||(i.instance=new i),i.instance}async executeCommand(e,t,n,s,r="new",o){let a=o||$s(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(Ft())await Ep(`taskkill /PID ${e} /T /F`,{timeout:5e3}).catch(()=>{});else try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}catch{}}cleanupStreams(e){try{e.stdout?.destroy(),e.stderr?.destroy(),e.stdin?.destroy()}catch{}}async executeInNewProcess(e,t){return new Promise(n=>{let s=Date.now(),r=Ni(),o,a;Ft()?(o="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(o="/bin/bash",a=["-c",e]);let c=wp(o,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!Ft()}),l="",d="",g=!1,m="",p="max",h=!1,f=!1,y=Date.now(),T=null,x=null,w=null,C=null,v=null,E=null,S=()=>{T&&(clearTimeout(T),T=null),x&&(clearTimeout(x),x=null),w&&(clearTimeout(w),w=null),C&&(clearTimeout(C),C=null),v&&(clearTimeout(v),v=null),E&&(clearTimeout(E),E=null)},I=$=>{h||(h=!0,S(),n($))},P=async($,D="max")=>{h||(g=!0,m=$,p=D,x&&(clearTimeout(x),x=null),w&&(clearTimeout(w),w=null),c.pid&&await this.killProcessTree(c.pid,"SIGTERM"),this.cleanupStreams(c),C=setTimeout(async()=>{h||(c.pid&&await this.killProcessTree(c.pid,"SIGKILL"),v=setTimeout(()=>{if(h)return;let _=Date.now()-s,N=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,k=Ri(e,N,p,m);I({output:l+d+k,exitCode:-9,isSuccess:!1,duration:_,platform:r})},500))},1e3))};T=setTimeout(()=>{P(`Max timeout reached (${t.maxTimeout}ms)`,"max")},t.maxTimeout),t.initialTimeout>0&&(w=setTimeout(()=>{!f&&!h&&P(`No output received within initial timeout (${t.initialTimeout}ms)`,"initial")},t.initialTimeout));let R=()=>{y=Date.now(),t.useActivityTimeout&&(x&&clearTimeout(x),x=setTimeout(()=>{if(!h){let $=Date.now()-y;P(`No output for ${$}ms (activity timeout: ${t.activityTimeout}ms)`,"activity")}},t.activityTimeout))};t.useActivityTimeout&&R(),c.stdout?.on("data",$=>{f=!0,R(),w&&(clearTimeout(w),w=null),l+=$.toString()}),c.stderr?.on("data",$=>{f=!0,R(),w&&(clearTimeout(w),w=null),d+=$.toString()}),c.on("exit",($,D)=>{D&&!g&&(d+=`
199
- [Process terminated by signal: ${D}]`),E=setTimeout(()=>{if(h)return;S(),this.cleanupStreams(c);let _=Date.now()-s,N=(l+d).trim();if(Fs.exceedsResponseLimit(N)){let k=Fs.truncate(N),M=k.text.split(`
198
+ 3. Consider breaking down the operation into safer steps`}function ml(i){let e=Op(i);if(e.isCatastrophic)return Np(i,e);let t=Pp(i);if(t.isPrivileged)return Ap(i,t.reason||"Privileged command detected");let n=Dp(i);return n.isInteractive?Mp(i,n.reason||"Interactive command detected"):null}function pl(i){let e=i.trim();for(let t of _p)if(t.test(e))return{isDelete:!0,paths:$p(e),category:Fp(e)};return{isDelete:!1,paths:[]}}function $p(i){let e=[],t=i.split(/\s+/),n=!1;for(let s=1;s<t.length;s++){let r=t[s];if(n){n=!1;continue}if(r.startsWith("-")){["-f","-o","-t","--target","--output"].includes(r)&&(n=!0);continue}r.length>0&&!r.startsWith("-")&&e.push(r)}return e}function Fp(i){let e=i.toLowerCase();return/^(rm|rmdir|unlink|del|rd|erase|remove-item)/i.test(e)?"File/Directory Deletion":/^git\s+(rm|clean)/.test(e)?"Git File Deletion":/^docker\s+volume/.test(e)?"Docker Volume Deletion":/^(aws\s+s3|gsutil|az\s+storage|rclone)/.test(e)?"Cloud Storage Deletion":/drop\s+(table|database|schema)/i.test(e)||/^(dropdb|dropuser)/.test(e)?"Database Deletion":/^(dd|mkfs|format|fdisk|parted|gdisk)/.test(e)?"Disk/Filesystem Operation":"Delete Operation"}var Ep,Ip,Ls,Oi,Be,Us,Rp,_p,Jn=$(()=>{"use strict";Mi();Xn();z();Ep=Cp(Tp),Ip=8500,Ls=new lt({maxResponseTokens:Ip});Oi=class{processes=new Map;MAX_COMPLETED_PROCESSES=50;COMPLETED_PROCESS_TTL=1800*1e3;addProcess(e){this.processes.set(e.id,e),this.cleanupOldProcesses(),u.debug(`[BackgroundProcessManager] Added process: ${e.id}`)}getProcess(e){return this.processes.get(e)}removeProcess(e){this.processes.delete(e),u.debug(`[BackgroundProcessManager] Removed process: ${e}`)}getAllProcesses(){return Array.from(this.processes.values())}getRunningProcesses(){return Array.from(this.processes.values()).filter(e=>e.status==="running")}getCompletedProcesses(){return Array.from(this.processes.values()).filter(e=>e.status!=="running")}updateProcess(e,t){let n=this.processes.get(e);return n?(Object.assign(n,t),u.debug(`[BackgroundProcessManager] Updated process: ${e}, status: ${n.status}`),!0):!1}cleanupOldProcesses(){let e=Date.now(),t=[],n=Array.from(this.processes.entries());for(let o=0;o<n.length;o++){let[a,c]=n[o];c.status!=="running"&&c.endTime&&t.push({id:a,endTime:c.endTime.getTime()})}let s=0;for(let o=0;o<t.length;o++){let{id:a,endTime:c}=t[o];e-c>this.COMPLETED_PROCESS_TTL&&(this.processes.delete(a),s++)}s>0&&u.debug(`[BackgroundProcessManager] Cleaned up ${s} old processes by TTL`);let r=t.filter(o=>e-o.endTime<=this.COMPLETED_PROCESS_TTL);if(r.length>this.MAX_COMPLETED_PROCESSES){r.sort((a,c)=>a.endTime-c.endTime);let o=r.slice(0,r.length-this.MAX_COMPLETED_PROCESSES);for(let a=0;a<o.length;a++){let{id:c}=o[a];this.processes.delete(c)}u.debug(`[BackgroundProcessManager] Cleaned up ${o.length} excess processes`)}}forceCleanupCompleted(){let e=0,t=Array.from(this.processes.entries());for(let n=0;n<t.length;n++){let[s,r]=t[n];r.status!=="running"&&(this.processes.delete(s),e++)}return u.debug(`[BackgroundProcessManager] Force cleaned ${e} completed processes`),e}getStats(){let e=this.getAllProcesses(),t=e.filter(n=>n.status==="running").length;return{total:e.length,running:t,completed:e.length-t}}clear(){this.processes.clear(),u.debug("[BackgroundProcessManager] Cleared all processes")}},Be=new Oi;Us=class i{static instance;constructor(){}static getInstance(){return i.instance||(i.instance=new i),i.instance}async executeCommand(e,t,n,s,r="new",o){let a=o||Fs(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(Lt())await Ep(`taskkill /PID ${e} /T /F`,{timeout:5e3}).catch(()=>{});else try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}catch{}}cleanupStreams(e){try{e.stdout?.destroy(),e.stderr?.destroy(),e.stdin?.destroy()}catch{}}async executeInNewProcess(e,t){return new Promise(n=>{let s=Date.now(),r=Ni(),o,a;Lt()?(o="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(o="/bin/bash",a=["-c",e]);let c=wp(o,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!Lt()}),l="",d="",g=!1,m="",p="max",h=!1,f=!1,y=Date.now(),T=null,C=null,w=null,E=null,v=null,x=null,S=()=>{T&&(clearTimeout(T),T=null),C&&(clearTimeout(C),C=null),w&&(clearTimeout(w),w=null),E&&(clearTimeout(E),E=null),v&&(clearTimeout(v),v=null),x&&(clearTimeout(x),x=null)},I=_=>{h||(h=!0,S(),n(_))},D=async(_,F="max")=>{h||(g=!0,m=_,p=F,C&&(clearTimeout(C),C=null),w&&(clearTimeout(w),w=null),c.pid&&await this.killProcessTree(c.pid,"SIGTERM"),this.cleanupStreams(c),E=setTimeout(async()=>{h||(c.pid&&await this.killProcessTree(c.pid,"SIGKILL"),v=setTimeout(()=>{if(h)return;let R=Date.now()-s,N=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,k=Ri(e,N,p,m);I({output:l+d+k,exitCode:-9,isSuccess:!1,duration:R,platform:r})},500))},1e3))};T=setTimeout(()=>{D(`Max timeout reached (${t.maxTimeout}ms)`,"max")},t.maxTimeout),t.initialTimeout>0&&(w=setTimeout(()=>{!f&&!h&&D(`No output received within initial timeout (${t.initialTimeout}ms)`,"initial")},t.initialTimeout));let M=()=>{y=Date.now(),t.useActivityTimeout&&(C&&clearTimeout(C),C=setTimeout(()=>{if(!h){let _=Date.now()-y;D(`No output for ${_}ms (activity timeout: ${t.activityTimeout}ms)`,"activity")}},t.activityTimeout))};t.useActivityTimeout&&M(),c.stdout?.on("data",_=>{f=!0,M(),w&&(clearTimeout(w),w=null),l+=_.toString()}),c.stderr?.on("data",_=>{f=!0,M(),w&&(clearTimeout(w),w=null),d+=_.toString()}),c.on("exit",(_,F)=>{F&&!g&&(d+=`
199
+ [Process terminated by signal: ${F}]`),x=setTimeout(()=>{if(h)return;S(),this.cleanupStreams(c);let R=Date.now()-s,N=(l+d).trim();if(Ls.exceedsResponseLimit(N)){let k=Ls.truncate(N),P=k.text.split(`
200
200
  `);N=k.text+`
201
201
 
202
202
  [Output truncated at `+k.tokens.toLocaleString()+` tokens]
203
- [Showing first `+M.length+" lines of output]"}if(g){let k=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,M=Ri(e,k,p,m);I({output:N+M,exitCode:-15,isSuccess:!1,duration:_,platform:r})}else I({output:N,exitCode:$||0,isSuccess:($||0)===0,duration:_,platform:r})},100)}),c.on("close",$=>{if(h)return;S();let D=Date.now()-s,_=(l+d).trim();if(Fs.exceedsResponseLimit(_)){let N=Fs.count(_),k=Fs.truncate(_),L=k.text.split(`
204
- `).length;_=k.text+`
203
+ [Showing first `+P.length+" lines of output]"}if(g){let k=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,P=Ri(e,k,p,m);I({output:N+P,exitCode:-15,isSuccess:!1,duration:R,platform:r})}else I({output:N,exitCode:_||0,isSuccess:(_||0)===0,duration:R,platform:r})},100)}),c.on("close",_=>{if(h)return;S();let F=Date.now()-s,R=(l+d).trim();if(Ls.exceedsResponseLimit(R)){let N=Ls.count(R),k=Ls.truncate(R),B=k.text.split(`
204
+ `).length;R=k.text+`
205
205
 
206
206
  [Output truncated at `+k.tokens.toLocaleString()+` tokens]
207
- [Showing first `+L+` lines of output]
208
- [Total output was `+N.toLocaleString()+" tokens]"}if(g){let N=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,k=Ri(e,N,p,m);I({output:_+k,exitCode:-15,isSuccess:!1,duration:D,platform:r})}else I({output:_,exitCode:$||0,isSuccess:($||0)===0,duration:D,platform:r})}),c.on("error",$=>{if(h)return;S();let D=Date.now()-s;I({output:"Process execution failed: "+$.message,exitCode:-1,isSuccess:!1,duration:D,platform:r})})})}formatExitCodeInfo(e){let t;switch(e){case 0:t="Success";break;case 1:t="General error";break;case 2:t="Misuse of shell command";break;case 126:t="Command cannot execute (permission denied)";break;case 127:t="Command not found";break;case 128:t="Invalid exit argument";break;case 130:t="Terminated by Ctrl+C (SIGINT)";break;case 137:t="Killed by SIGKILL";break;case 143:t="Terminated by SIGTERM";break;default:e>128?t=`Terminated by signal ${e-128}`:e<0?t="Terminated by timeout or force kill":t="Unknown error"}return`Exit code: ${e} (${t})`}static parseSessionMode(e){if(e.toLowerCase()==="new")return"new";throw new Error(`Invalid session mode: ${e}. Only 'new' mode is supported`)}};Rp=[{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/\*/,description:"rm -rf /* (wipes entire system)",category:"filesystem_destruction"},{pattern:/\brm\s+-[rR]\s+-[fF]\s+\/\*/,description:"rm -r -f /* (wipes entire system)",category:"filesystem_destruction"},{pattern:/\brm\s+-[fF]\s+-[rR]\s+\/\*/,description:"rm -f -r /* (wipes entire system)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/\s*$/,description:"rm -r / targeting root directory",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+~\/\*/,description:"rm -rf ~/* (wipes home directory)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+~\/\.\*/,description:"rm -rf ~/.* (wipes home hidden files)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+~\*/,description:"rm -rf ~* (wipes home)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\$HOME\/\*/,description:"rm -rf $HOME/* (wipes home directory)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\$HOME\/\.\*/,description:"rm -rf $HOME/.* (wipes home hidden files)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\$\{HOME\}\/\*/,description:"rm -rf ${HOME}/* (wipes home directory)",category:"filesystem_destruction"},{pattern:/\brm\s+.*--no-preserve-root/,description:"rm with --no-preserve-root",category:"filesystem_destruction"},{pattern:/\bdd\b.*\bof\s*=\s*\/dev\/(sd[a-z]|hd[a-z]|nvme\d|vd[a-z]|xvd[a-z]|mmcblk\d)\b/,description:"dd writing to disk device",category:"disk_destruction"},{pattern:/\bdd\b.*\bof\s*=\s*\/dev\/disk\d*/,description:"dd writing to disk device",category:"disk_destruction"},{pattern:/>\s*\/dev\/(sd[a-z]|hd[a-z]|nvme\d|vd[a-z]|xvd[a-z]|mmcblk\d)\b/,description:"redirect to disk device",category:"disk_destruction"},{pattern:/\bcat\b.*>\s*\/dev\/(sd[a-z]|hd[a-z]|nvme\d)\b/,description:"cat to disk device",category:"disk_destruction"},{pattern:/\bmkfs\.[a-z0-9]+\s+/,description:"mkfs.* filesystem format command",category:"filesystem_formatting"},{pattern:/\bmkfs\s+-t\s+/,description:"mkfs -t filesystem format command",category:"filesystem_formatting"},{pattern:/\bmkswap\s+\/dev\//,description:"mkswap on device",category:"filesystem_formatting"},{pattern:/\bwipefs\s+(-a|--all)\s+/,description:"wipefs -a (wipes filesystem signatures)",category:"filesystem_formatting"},{pattern:/\bwipefs\s+--all\s+/,description:"wipefs --all (wipes filesystem signatures)",category:"filesystem_formatting"},{pattern:/:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;?\s*:/,description:"fork bomb :(){ :|:& };:",category:"fork_bomb"},{pattern:/\bfork\s*\(\s*\)\s*while/,description:"fork bomb pattern",category:"fork_bomb"},{pattern:/while\s*\(\s*true\s*\)\s*;\s*do\s+fork/,description:"fork loop",category:"fork_bomb"},{pattern:/>\s*\/dev\/sda.*&.*>\s*\/dev\/sda/,description:"parallel disk destruction",category:"fork_bomb"},{pattern:/\.\(\)\s*\{\s*\.\s*\|\s*\.\s*&\s*\}/,description:"fork bomb variant",category:"fork_bomb"},{pattern:/bomb\s*\(\)\s*\{.*bomb.*\|.*bomb.*&/,description:"named fork bomb",category:"fork_bomb"},{pattern:/\bchmod\s+.*\b0{3}\s+\/\s*$/,description:"chmod 000 / (locks entire system)",category:"permission_destruction"},{pattern:/\bchmod\s+.*-[rR].*\b0{3}\s+\//,description:"chmod -R 000 / (recursive permission destruction)",category:"permission_destruction"},{pattern:/\bchmod\s+--recursive\s+.*\b0{3}\s+\//,description:"chmod --recursive 000 / (recursive permission destruction)",category:"permission_destruction"},{pattern:/\bchmod\s+.*-[rR].*\b777\s+\/\s*$/,description:"chmod -R 777 / (security destruction)",category:"permission_destruction"},{pattern:/\bchmod\s+--recursive\s+.*\b777\s+\/\s*$/,description:"chmod --recursive 777 / (security destruction)",category:"permission_destruction"},{pattern:/\bchown\s+.*-[rR].*\s+\S+\s+\/\s*$/,description:"chown -R on root",category:"permission_destruction"},{pattern:/\bchown\s+--recursive\s+.*\s+\S+\s+\/\s*$/,description:"chown --recursive on root",category:"permission_destruction"},{pattern:/\bmv\s+\/\*\s+\/dev\/null/,description:"mv /* /dev/null",category:"root_modification"},{pattern:/\bmv\s+\/\s+\S/,description:"mv / (moving root directory)",category:"root_modification"},{pattern:/>\s*\/proc\/sysrq-trigger/,description:"sysrq trigger (can cause kernel panic)",category:"kernel_panic"},{pattern:/>\s*\/proc\/sys\/kernel\/panic/,description:"kernel panic trigger",category:"kernel_panic"},{pattern:/\becho\s+[co]\s*>\s*\/proc\/sysrq/,description:"sysrq crash/oom trigger",category:"kernel_panic"},{pattern:/\becho\s+[bsuc]\s*>\s*\/proc\/sysrq-trigger/,description:"sysrq dangerous trigger (b=reboot, s=sync, u=remount, c=crash)",category:"kernel_panic"},{pattern:/\brm\s+(-[a-zA-Z]*\s+)*\/bin\/(bash|sh|zsh)\b/,description:"deleting system shell",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/bin\/?(\s|$)/,description:"deleting /bin directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/usr\/?(\s|$)/,description:"deleting /usr directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/etc\/?(\s|$)/,description:"deleting /etc directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/var\/?(\s|$)/,description:"deleting /var directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/lib\/?(\s|$)/,description:"deleting /lib directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/boot\/?(\s|$)/,description:"deleting /boot directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/sbin\/?(\s|$)/,description:"deleting /sbin directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/lib64\/?(\s|$)/,description:"deleting /lib64 directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/System\/?(\s|$)/,description:"deleting /System directory (macOS)",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/Library\/?(\s|$)/,description:"deleting /Library directory (macOS)",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/Applications\/?(\s|$)/,description:"deleting /Applications directory (macOS)",category:"environment_destruction"},{pattern:/\bfdisk\s+\/dev\//,description:"fdisk on device (partition modification)",category:"partition_destruction"},{pattern:/\bparted\s+.*\brm\b/,description:"parted rm (partition deletion)",category:"partition_destruction"},{pattern:/\bgdisk\s+.*\bd\b/,description:"gdisk delete partition",category:"partition_destruction"},{pattern:/\bsgdisk\s+.*(-d|--delete|-Z|--zap-all)/,description:"sgdisk partition deletion",category:"partition_destruction"},{pattern:/\bcfdisk\s+\/dev\//,description:"cfdisk on device",category:"partition_destruction"},{pattern:/\bsfdisk\s+.*--delete/,description:"sfdisk partition deletion",category:"partition_destruction"},{pattern:/\byes\s*\|\s*(rm|dd|mkfs|fdisk|parted)/,description:"yes piped to destructive command",category:"filesystem_destruction"},{pattern:/\bshred\s+.*\/(dev|bin|usr|etc|var|lib|boot)/,description:"shred on system directories",category:"environment_destruction"},{pattern:/set\s+\+o\s+noclobber.*>\s*\/dev\//,description:"noclobber bypass to device",category:"disk_destruction"}];_p=[/^rm\s+/,/^rm\s+-[rRfFiIvd]+/,/^rmdir\s+/,/^unlink\s+/,/^shred\s+/,/^wipe\s+/,/^srm\s+/,/^trash\s+/,/^trash-put\s+/,/^gio\s+trash/,/^gvfs-trash\s+/,/^del\s+/i,/^del\s+\/[fqsaP]+/i,/^rd\s+/i,/^rd\s+\/s/i,/^rmdir\s+\/s/i,/^erase\s+/i,/^Remove-Item\s+/i,/^ri\s+/i,/\|\s*xargs\s+(rm|del|erase|unlink)/i,/&&\s*rm\s+/,/;\s*rm\s+/,/\|\s*rm\s+/,/^find\s+.*-delete/,/^find\s+.*-exec\s+(rm|del|unlink)/i,/^git\s+rm\s+/,/^git\s+clean\s+-[fdxXe]+/,/^docker\s+volume\s+rm\s+/,/^docker\s+volume\s+prune/,/^aws\s+s3\s+rm\s+/,/^aws\s+s3\s+rb\s+/,/^gsutil\s+rm\s+/,/^gsutil\s+-m\s+rm/,/^gsutil\s+rb\s+/,/^az\s+storage\s+.*delete/,/^rclone\s+delete/,/^rclone\s+purge/,/drop\s+table\s+/i,/drop\s+database\s+/i,/drop\s+schema\s+/i,/drop\s+index\s+/i,/drop\s+view\s+/i,/drop\s+function\s+/i,/drop\s+procedure\s+/i,/drop\s+trigger\s+/i,/drop\s+sequence\s+/i,/drop\s+type\s+/i,/drop\s+user\s+/i,/drop\s+role\s+/i,/drop\s+tablespace\s+/i,/drop\s+keyspace\s+/i,/truncate\s+table\s+/i,/truncate\s+/i,/delete\s+from\s+/i,/^mongo.*\.drop\(/,/^mongosh.*\.drop\(/,/^mongo.*\.remove\(/,/^mongosh.*\.deleteMany\(/,/^redis-cli.*\s+del\s+/i,/^redis-cli.*\s+flushdb/i,/^redis-cli.*\s+flushall/i,/^redis-cli.*\s+unlink\s+/i,/^dropdb\s+/,/^dropuser\s+/,/^mysqladmin\s+drop/,/^cqlsh.*drop/i,/^influx.*delete/i,/^etcdctl\s+del/,/^dd\s+.*of=/,/^mkfs\s+/,/^mkfs\.[a-z0-9]+\s+/,/^format\s+/i,/^fdisk\s+/,/^parted\s+/,/^gdisk\s+/,/^wipefs\s+/,/^blkdiscard\s+/,/^hdparm\s+.*--security-erase/,/^truncate\s+/,/^:\s*>\s*\S+/,/^>\s*\S+/,/^cp\s+\/dev\/null\s+/,/^mv\s+.*\s+\/dev\/null/,/^rsync\s+.*--delete/,/^rsync\s+.*--remove-source-files/,/^ssh\s+.*\s+(rm|del|unlink)\s+/,/^borg\s+delete/,/^borg\s+prune/,/^duplicity\s+remove/,/^tmutil\s+delete/]});var _i={};Fe(_i,{ToolCallingService:()=>Us});import{EventEmitter as Lp}from"events";import hl from"axios";import{exec as Up,spawn as fl}from"child_process";import{promisify as Bp}from"util";import Be from"fs/promises";import Dt from"fs";import Qn from"path";import Wp from"os";var uE,Lr,bl,Hp,Us,Ur=F(()=>{"use strict";Yn();Mi();Kn();uE=Bp(Up),Lr=5,bl=20,Hp=new Set(["Bash","execute_command","read_file","write_file","Edit","Grep","Glob"]),Us=class i extends Lp{static instance;tools=new Map;executionHistory=[];tokenCounter=new lt;shellSessionManager=Ls.getInstance();currentUserId="orion-cli-user";fileStateCache=new Map;static MAX_FILE_STATE_CACHE_SIZE=100;backgroundProcesses=new Map;backgroundProcessCounter=0;static MAX_COMPLETED_PROCESSES=50;toolExecutionQueue=[];activeToolExecutions=0;activeToolIds=new Set;constructor(){super(),this.initializeDefaultTools()}generateToolExecId(){return`tool-${Date.now()}-${Math.random().toString(36).substr(2,6)}`}processToolQueue(){for(;this.activeToolExecutions<Lr&&this.toolExecutionQueue.length>0;){let e=this.toolExecutionQueue.shift();this.activeToolExecutions++,this.activeToolIds.add(e.id);let t=Date.now()-e.queuedAt;t>100&&console.log(`🔄 [ToolQueue] Dequeued ${e.toolName} (waited ${t}ms, active: ${this.activeToolExecutions}/${Lr})`),e.execute().then(n=>{e.resolve(n)}).catch(n=>{e.reject(n)}).finally(()=>{this.activeToolExecutions--,this.activeToolIds.delete(e.id),this.processToolQueue()})}}async queueToolExecution(e,t){if(!Hp.has(e))return t();if(this.activeToolExecutions<Lr){let n=this.generateToolExecId();this.activeToolExecutions++,this.activeToolIds.add(n);try{return await t()}finally{this.activeToolExecutions--,this.activeToolIds.delete(n),this.processToolQueue()}}if(this.toolExecutionQueue.length>=bl)throw console.warn(`⚠️ [ToolQueue] Queue full (${bl}), rejecting ${e}`),new Error("Tool execution queue full. Please wait for current operations to complete.");return new Promise((n,s)=>{let r=this.generateToolExecId();console.log(`📥 [ToolQueue] Queueing ${e} (queue: ${this.toolExecutionQueue.length+1}, active: ${this.activeToolExecutions}/${Lr})`),this.toolExecutionQueue.push({id:r,toolName:e,execute:t,resolve:n,reject:s,queuedAt:Date.now()})})}static getInstance(){return i.instance||(i.instance=new i),i.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. Supports reading specific line ranges with offset and limit.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to read"},offset:{type:"number",description:"The line number to start reading from (1-based). Only provide if the file is too large to read at once."},limit:{type:"number",description:"The number of lines to read. Only provide if the file is too large to read at once."}},required:["file_path"]},handler:this.readFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Read",description:"Read the contents of a file. Supports reading specific line ranges with offset and limit.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to read"},offset:{type:"number",description:"The line number to start reading from (1-based). Only provide if the file is too large to read at once."},limit:{type:"number",description:"The number of lines to read. Only provide if the file is too large to read at once."}},required:["file_path"]},handler:this.readFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"write_file",description:"Write content to a file. This will overwrite the existing file if there is one at the provided path.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to write (must be absolute, not relative)"},content:{type:"string",description:"The 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:"Write",description:"Write content to a file. This will overwrite the existing file if there is one at the provided path.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to write (must be absolute, not relative)"},content:{type:"string",description:"The content to write to the file"}},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},dangerouslyDisableSandbox:{type:"boolean",description:"Set to true to disable sandbox mode and run commands without sandboxing",default:!1},working_directory:{type:"string",description:"Working directory to execute the command in. Defaults to current working directory."}},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.
207
+ [Showing first `+B+` lines of output]
208
+ [Total output was `+N.toLocaleString()+" tokens]"}if(g){let N=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,k=Ri(e,N,p,m);I({output:R+k,exitCode:-15,isSuccess:!1,duration:F,platform:r})}else I({output:R,exitCode:_||0,isSuccess:(_||0)===0,duration:F,platform:r})}),c.on("error",_=>{if(h)return;S();let F=Date.now()-s;I({output:"Process execution failed: "+_.message,exitCode:-1,isSuccess:!1,duration:F,platform:r})})})}formatExitCodeInfo(e){let t;switch(e){case 0:t="Success";break;case 1:t="General error";break;case 2:t="Misuse of shell command";break;case 126:t="Command cannot execute (permission denied)";break;case 127:t="Command not found";break;case 128:t="Invalid exit argument";break;case 130:t="Terminated by Ctrl+C (SIGINT)";break;case 137:t="Killed by SIGKILL";break;case 143:t="Terminated by SIGTERM";break;default:e>128?t=`Terminated by signal ${e-128}`:e<0?t="Terminated by timeout or force kill":t="Unknown error"}return`Exit code: ${e} (${t})`}static parseSessionMode(e){if(e.toLowerCase()==="new")return"new";throw new Error(`Invalid session mode: ${e}. Only 'new' mode is supported`)}};Rp=[{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/\*/,description:"rm -rf /* (wipes entire system)",category:"filesystem_destruction"},{pattern:/\brm\s+-[rR]\s+-[fF]\s+\/\*/,description:"rm -r -f /* (wipes entire system)",category:"filesystem_destruction"},{pattern:/\brm\s+-[fF]\s+-[rR]\s+\/\*/,description:"rm -f -r /* (wipes entire system)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/\s*$/,description:"rm -r / targeting root directory",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+~\/\*/,description:"rm -rf ~/* (wipes home directory)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+~\/\.\*/,description:"rm -rf ~/.* (wipes home hidden files)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+~\*/,description:"rm -rf ~* (wipes home)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\$HOME\/\*/,description:"rm -rf $HOME/* (wipes home directory)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\$HOME\/\.\*/,description:"rm -rf $HOME/.* (wipes home hidden files)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\$\{HOME\}\/\*/,description:"rm -rf ${HOME}/* (wipes home directory)",category:"filesystem_destruction"},{pattern:/\brm\s+.*--no-preserve-root/,description:"rm with --no-preserve-root",category:"filesystem_destruction"},{pattern:/\bdd\b.*\bof\s*=\s*\/dev\/(sd[a-z]|hd[a-z]|nvme\d|vd[a-z]|xvd[a-z]|mmcblk\d)\b/,description:"dd writing to disk device",category:"disk_destruction"},{pattern:/\bdd\b.*\bof\s*=\s*\/dev\/disk\d*/,description:"dd writing to disk device",category:"disk_destruction"},{pattern:/>\s*\/dev\/(sd[a-z]|hd[a-z]|nvme\d|vd[a-z]|xvd[a-z]|mmcblk\d)\b/,description:"redirect to disk device",category:"disk_destruction"},{pattern:/\bcat\b.*>\s*\/dev\/(sd[a-z]|hd[a-z]|nvme\d)\b/,description:"cat to disk device",category:"disk_destruction"},{pattern:/\bmkfs\.[a-z0-9]+\s+/,description:"mkfs.* filesystem format command",category:"filesystem_formatting"},{pattern:/\bmkfs\s+-t\s+/,description:"mkfs -t filesystem format command",category:"filesystem_formatting"},{pattern:/\bmkswap\s+\/dev\//,description:"mkswap on device",category:"filesystem_formatting"},{pattern:/\bwipefs\s+(-a|--all)\s+/,description:"wipefs -a (wipes filesystem signatures)",category:"filesystem_formatting"},{pattern:/\bwipefs\s+--all\s+/,description:"wipefs --all (wipes filesystem signatures)",category:"filesystem_formatting"},{pattern:/:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;?\s*:/,description:"fork bomb :(){ :|:& };:",category:"fork_bomb"},{pattern:/\bfork\s*\(\s*\)\s*while/,description:"fork bomb pattern",category:"fork_bomb"},{pattern:/while\s*\(\s*true\s*\)\s*;\s*do\s+fork/,description:"fork loop",category:"fork_bomb"},{pattern:/>\s*\/dev\/sda.*&.*>\s*\/dev\/sda/,description:"parallel disk destruction",category:"fork_bomb"},{pattern:/\.\(\)\s*\{\s*\.\s*\|\s*\.\s*&\s*\}/,description:"fork bomb variant",category:"fork_bomb"},{pattern:/bomb\s*\(\)\s*\{.*bomb.*\|.*bomb.*&/,description:"named fork bomb",category:"fork_bomb"},{pattern:/\bchmod\s+.*\b0{3}\s+\/\s*$/,description:"chmod 000 / (locks entire system)",category:"permission_destruction"},{pattern:/\bchmod\s+.*-[rR].*\b0{3}\s+\//,description:"chmod -R 000 / (recursive permission destruction)",category:"permission_destruction"},{pattern:/\bchmod\s+--recursive\s+.*\b0{3}\s+\//,description:"chmod --recursive 000 / (recursive permission destruction)",category:"permission_destruction"},{pattern:/\bchmod\s+.*-[rR].*\b777\s+\/\s*$/,description:"chmod -R 777 / (security destruction)",category:"permission_destruction"},{pattern:/\bchmod\s+--recursive\s+.*\b777\s+\/\s*$/,description:"chmod --recursive 777 / (security destruction)",category:"permission_destruction"},{pattern:/\bchown\s+.*-[rR].*\s+\S+\s+\/\s*$/,description:"chown -R on root",category:"permission_destruction"},{pattern:/\bchown\s+--recursive\s+.*\s+\S+\s+\/\s*$/,description:"chown --recursive on root",category:"permission_destruction"},{pattern:/\bmv\s+\/\*\s+\/dev\/null/,description:"mv /* /dev/null",category:"root_modification"},{pattern:/\bmv\s+\/\s+\S/,description:"mv / (moving root directory)",category:"root_modification"},{pattern:/>\s*\/proc\/sysrq-trigger/,description:"sysrq trigger (can cause kernel panic)",category:"kernel_panic"},{pattern:/>\s*\/proc\/sys\/kernel\/panic/,description:"kernel panic trigger",category:"kernel_panic"},{pattern:/\becho\s+[co]\s*>\s*\/proc\/sysrq/,description:"sysrq crash/oom trigger",category:"kernel_panic"},{pattern:/\becho\s+[bsuc]\s*>\s*\/proc\/sysrq-trigger/,description:"sysrq dangerous trigger (b=reboot, s=sync, u=remount, c=crash)",category:"kernel_panic"},{pattern:/\brm\s+(-[a-zA-Z]*\s+)*\/bin\/(bash|sh|zsh)\b/,description:"deleting system shell",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/bin\/?(\s|$)/,description:"deleting /bin directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/usr\/?(\s|$)/,description:"deleting /usr directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/etc\/?(\s|$)/,description:"deleting /etc directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/var\/?(\s|$)/,description:"deleting /var directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/lib\/?(\s|$)/,description:"deleting /lib directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/boot\/?(\s|$)/,description:"deleting /boot directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/sbin\/?(\s|$)/,description:"deleting /sbin directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/lib64\/?(\s|$)/,description:"deleting /lib64 directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/System\/?(\s|$)/,description:"deleting /System directory (macOS)",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/Library\/?(\s|$)/,description:"deleting /Library directory (macOS)",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/Applications\/?(\s|$)/,description:"deleting /Applications directory (macOS)",category:"environment_destruction"},{pattern:/\bfdisk\s+\/dev\//,description:"fdisk on device (partition modification)",category:"partition_destruction"},{pattern:/\bparted\s+.*\brm\b/,description:"parted rm (partition deletion)",category:"partition_destruction"},{pattern:/\bgdisk\s+.*\bd\b/,description:"gdisk delete partition",category:"partition_destruction"},{pattern:/\bsgdisk\s+.*(-d|--delete|-Z|--zap-all)/,description:"sgdisk partition deletion",category:"partition_destruction"},{pattern:/\bcfdisk\s+\/dev\//,description:"cfdisk on device",category:"partition_destruction"},{pattern:/\bsfdisk\s+.*--delete/,description:"sfdisk partition deletion",category:"partition_destruction"},{pattern:/\byes\s*\|\s*(rm|dd|mkfs|fdisk|parted)/,description:"yes piped to destructive command",category:"filesystem_destruction"},{pattern:/\bshred\s+.*\/(dev|bin|usr|etc|var|lib|boot)/,description:"shred on system directories",category:"environment_destruction"},{pattern:/set\s+\+o\s+noclobber.*>\s*\/dev\//,description:"noclobber bypass to device",category:"disk_destruction"}];_p=[/^rm\s+/,/^rm\s+-[rRfFiIvd]+/,/^rmdir\s+/,/^unlink\s+/,/^shred\s+/,/^wipe\s+/,/^srm\s+/,/^trash\s+/,/^trash-put\s+/,/^gio\s+trash/,/^gvfs-trash\s+/,/^del\s+/i,/^del\s+\/[fqsaP]+/i,/^rd\s+/i,/^rd\s+\/s/i,/^rmdir\s+\/s/i,/^erase\s+/i,/^Remove-Item\s+/i,/^ri\s+/i,/\|\s*xargs\s+(rm|del|erase|unlink)/i,/&&\s*rm\s+/,/;\s*rm\s+/,/\|\s*rm\s+/,/^find\s+.*-delete/,/^find\s+.*-exec\s+(rm|del|unlink)/i,/^git\s+rm\s+/,/^git\s+clean\s+-[fdxXe]+/,/^docker\s+volume\s+rm\s+/,/^docker\s+volume\s+prune/,/^aws\s+s3\s+rm\s+/,/^aws\s+s3\s+rb\s+/,/^gsutil\s+rm\s+/,/^gsutil\s+-m\s+rm/,/^gsutil\s+rb\s+/,/^az\s+storage\s+.*delete/,/^rclone\s+delete/,/^rclone\s+purge/,/drop\s+table\s+/i,/drop\s+database\s+/i,/drop\s+schema\s+/i,/drop\s+index\s+/i,/drop\s+view\s+/i,/drop\s+function\s+/i,/drop\s+procedure\s+/i,/drop\s+trigger\s+/i,/drop\s+sequence\s+/i,/drop\s+type\s+/i,/drop\s+user\s+/i,/drop\s+role\s+/i,/drop\s+tablespace\s+/i,/drop\s+keyspace\s+/i,/truncate\s+table\s+/i,/truncate\s+/i,/delete\s+from\s+/i,/^mongo.*\.drop\(/,/^mongosh.*\.drop\(/,/^mongo.*\.remove\(/,/^mongosh.*\.deleteMany\(/,/^redis-cli.*\s+del\s+/i,/^redis-cli.*\s+flushdb/i,/^redis-cli.*\s+flushall/i,/^redis-cli.*\s+unlink\s+/i,/^dropdb\s+/,/^dropuser\s+/,/^mysqladmin\s+drop/,/^cqlsh.*drop/i,/^influx.*delete/i,/^etcdctl\s+del/,/^dd\s+.*of=/,/^mkfs\s+/,/^mkfs\.[a-z0-9]+\s+/,/^format\s+/i,/^fdisk\s+/,/^parted\s+/,/^gdisk\s+/,/^wipefs\s+/,/^blkdiscard\s+/,/^hdparm\s+.*--security-erase/,/^truncate\s+/,/^:\s*>\s*\S+/,/^>\s*\S+/,/^cp\s+\/dev\/null\s+/,/^mv\s+.*\s+\/dev\/null/,/^rsync\s+.*--delete/,/^rsync\s+.*--remove-source-files/,/^ssh\s+.*\s+(rm|del|unlink)\s+/,/^borg\s+delete/,/^borg\s+prune/,/^duplicity\s+remove/,/^tmutil\s+delete/]});var _i={};Le(_i,{ToolCallingService:()=>Bs});import{EventEmitter as Lp}from"events";import hl from"axios";import{exec as Up,spawn as fl}from"child_process";import{promisify as Bp}from"util";import We from"fs/promises";import Dt from"fs";import Zn from"path";import Wp from"os";var uE,Ur,bl,Hp,Bs,Br=$(()=>{"use strict";Jn();Mi();Xn();uE=Bp(Up),Ur=5,bl=20,Hp=new Set(["Bash","execute_command","read_file","write_file","Edit","Grep","Glob"]),Bs=class i extends Lp{static instance;tools=new Map;executionHistory=[];tokenCounter=new lt;shellSessionManager=Us.getInstance();currentUserId="orion-cli-user";fileStateCache=new Map;static MAX_FILE_STATE_CACHE_SIZE=100;backgroundProcesses=new Map;backgroundProcessCounter=0;static MAX_COMPLETED_PROCESSES=50;toolExecutionQueue=[];activeToolExecutions=0;activeToolIds=new Set;constructor(){super(),this.initializeDefaultTools()}generateToolExecId(){return`tool-${Date.now()}-${Math.random().toString(36).substr(2,6)}`}processToolQueue(){for(;this.activeToolExecutions<Ur&&this.toolExecutionQueue.length>0;){let e=this.toolExecutionQueue.shift();this.activeToolExecutions++,this.activeToolIds.add(e.id);let t=Date.now()-e.queuedAt;t>100&&console.log(`🔄 [ToolQueue] Dequeued ${e.toolName} (waited ${t}ms, active: ${this.activeToolExecutions}/${Ur})`),e.execute().then(n=>{e.resolve(n)}).catch(n=>{e.reject(n)}).finally(()=>{this.activeToolExecutions--,this.activeToolIds.delete(e.id),this.processToolQueue()})}}async queueToolExecution(e,t){if(!Hp.has(e))return t();if(this.activeToolExecutions<Ur){let n=this.generateToolExecId();this.activeToolExecutions++,this.activeToolIds.add(n);try{return await t()}finally{this.activeToolExecutions--,this.activeToolIds.delete(n),this.processToolQueue()}}if(this.toolExecutionQueue.length>=bl)throw console.warn(`⚠️ [ToolQueue] Queue full (${bl}), rejecting ${e}`),new Error("Tool execution queue full. Please wait for current operations to complete.");return new Promise((n,s)=>{let r=this.generateToolExecId();console.log(`📥 [ToolQueue] Queueing ${e} (queue: ${this.toolExecutionQueue.length+1}, active: ${this.activeToolExecutions}/${Ur})`),this.toolExecutionQueue.push({id:r,toolName:e,execute:t,resolve:n,reject:s,queuedAt:Date.now()})})}static getInstance(){return i.instance||(i.instance=new i),i.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. Supports reading specific line ranges with offset and limit.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to read"},offset:{type:"number",description:"The line number to start reading from (1-based). Only provide if the file is too large to read at once."},limit:{type:"number",description:"The number of lines to read. Only provide if the file is too large to read at once."}},required:["file_path"]},handler:this.readFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Read",description:"Read the contents of a file. Supports reading specific line ranges with offset and limit.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to read"},offset:{type:"number",description:"The line number to start reading from (1-based). Only provide if the file is too large to read at once."},limit:{type:"number",description:"The number of lines to read. Only provide if the file is too large to read at once."}},required:["file_path"]},handler:this.readFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"write_file",description:"Write content to a file. This will overwrite the existing file if there is one at the provided path.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to write (must be absolute, not relative)"},content:{type:"string",description:"The 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:"Write",description:"Write content to a file. This will overwrite the existing file if there is one at the provided path.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to write (must be absolute, not relative)"},content:{type:"string",description:"The content to write to the file"}},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},dangerouslyDisableSandbox:{type:"boolean",description:"Set to true to disable sandbox mode and run commands without sandboxing",default:!1},working_directory:{type:"string",description:"Working directory to execute the command in. Defaults to current working directory."}},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.
209
209
 
210
210
  🔧 SESSION MODE SELECTION (REQUIRED):
211
211
  • Use session: "existing" for workflows that need persistent state:
@@ -239,17 +239,17 @@ If you believe this is a false positive, please:
239
239
  4. LLM receives prompt details and makes decision
240
240
  5. LLM uses provide_input to send appropriate response
241
241
  6. Command execution continues with provided input
242
- 7. Normal command completion and result return`,parameters:{type:"object",properties:{input:{type:"string",description:'The input to provide to the interactive prompt. Should be appropriate for the prompt type (e.g., "y", "n", password, text, etc.)'}},required:["input"]},handler:this.provideInput.bind(this),category:"system",enabled:!0}),this.registerTool({name:"calculate",description:"Perform mathematical calculations",parameters:{type:"object",properties:{expression:{type:"string",description:"Mathematical expression to evaluate"}},required:["expression"]},handler:this.calculate.bind(this),category:"computation",enabled:!0}),this.registerTool({name:"http_request",description:"Make an HTTP request to a URL",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to request"},method:{type:"string",description:"HTTP method",enum:["GET","POST","PUT","DELETE"],default:"GET"},headers:{type:"object",description:"HTTP headers"},body:{type:"string",description:"Request body for POST/PUT requests"}},required:["url"]},handler:this.httpRequest.bind(this),category:"web",enabled:!0}),this.registerTool({name:"get_current_time",description:"Get the current date and time",parameters:{type:"object",properties:{format:{type:"string",description:"Date format (iso, local, unix)",enum:["iso","local","unix"],default:"iso"},timezone:{type:"string",description:"Timezone (e.g., America/New_York, UTC)",default:"local"}}},handler:this.getCurrentTime.bind(this),category:"system",enabled:!0}),this.registerTool({name:"Edit",description:"Performs exact string replacements in files with comprehensive validation",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to modify"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The text to replace it with (must be different from old_string)"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)",default:!1}},required:["file_path","old_string","new_string"]},handler:this.editFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Grep",description:"A powerful search tool built on ripgrep for searching file contents",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression pattern to search for in file contents"},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "**/*.tsx")'},type:{type:"string",description:"File type to search (rg --type). Common types: js, py, rust, go, java, etc."},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"},"-i":{type:"boolean",description:"Case insensitive search (rg -i)",default:!1},"-n":{type:"boolean",description:'Show line numbers in output (rg -n). Requires output_mode: "content".',default:!0},"-A":{type:"number",description:'Number of lines to show after each match (rg -A). Requires output_mode: "content".'},"-B":{type:"number",description:'Number of lines to show before each match (rg -B). Requires output_mode: "content".'},"-C":{type:"number",description:'Number of lines to show before and after each match (rg -C). Requires output_mode: "content".'},head_limit:{type:"number",description:'Limit output to first N lines/entries, equivalent to "| head -N". Defaults to 0 (unlimited).',default:0},offset:{type:"number",description:"Skip first N lines/entries before applying head_limit. Defaults to 0.",default:0},multiline:{type:"boolean",description:"Enable multiline mode where . matches newlines and patterns can span lines (rg -U --multiline-dotall).",default:!1},case_insensitive:{type:"boolean",description:"Case insensitive search (alias for -i)",default:!1}},required:["pattern"]},handler:this.grepFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Glob",description:"Fast file pattern matching tool that works with any codebase size",parameters:{type:"object",properties:{pattern:{type:"string",description:"The glob pattern to match files against"},path:{type:"string",description:"The directory to search in. Defaults to current working directory."}},required:["pattern"]},handler:this.globFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"NotebookEdit",description:"Edit Jupyter notebook (.ipynb) cells with cell-level precision",parameters:{type:"object",properties:{notebook_path:{type:"string",description:"The absolute path to the Jupyter notebook file to edit"},cell_id:{type:"string",description:"The ID of the cell to edit"},new_source:{type:"string",description:"The new source for the cell"},cell_type:{type:"string",enum:["code","markdown"],description:"The type of the cell (code or markdown)"},edit_mode:{type:"string",enum:["replace","insert","delete"],description:"The type of edit to make (replace, insert, delete). Defaults to replace.",default:"replace"}},required:["notebook_path","new_source"]},handler:this.editNotebook.bind(this),category:"file",enabled:!0})}registerTool(e){this.tools.set(e.name,e)}unregisterTool(e){let t=this.tools.delete(e);return t}async executeTool(e){let t=Date.now(),n=e.function.name;this.emit("tool_execution_start",{toolName:n,toolCall:e});let s={};try{s=JSON.parse(e.function.arguments)}catch(o){throw new Error(`Invalid arguments for tool '${n}': ${o}`)}let{ToolDisplay:r}=await Promise.resolve().then(()=>(Tt(),tl));r.start(n,s.description,s.command||s.file_path);try{let o=this.tools.get(n);if(!o)throw new Error(`Tool '${n}' not found`);if(!o.enabled)throw new Error(`Tool '${n}' is disabled`);let a=await this.queueToolExecution(n,()=>o.handler(s)),c=Date.now()-t,l=this.handleLargeResponse(a,n);for(this.executionHistory.push({toolName:n,args:s,result:l,timestamp:new Date,executionTime:c});this.executionHistory.length>100;)this.executionHistory.shift();return this.emit("tool_execution_complete",{toolName:n,result:l,executionTime:c}),r.result({toolName:n,command:s.command,filePath:s.file_path,description:s.description,output:this.extractOutputForDisplay(l),success:l.success,executionTime:c}),await this.captureFrontendToolResult(n,l),l}catch(o){let a=Date.now()-t,c={success:!1,error:o.message};return this.emit("tool_execution_error",{toolName:n,error:o,executionTime:a}),r.error(n,o.message),await this.captureFrontendToolResult(n,c),c}}extractOutputForDisplay(e){return e.success?e.result?typeof e.result=="string"?e.result:typeof e.result=="object"&&"stdout"in e.result?e.result.stdout||e.result.stderr||"":typeof e.result=="object"&&"content"in e.result?e.result.content||"":JSON.stringify(e.result,null,2):"":e.error||"Unknown error"}async captureFrontendToolResult(e,t){let{PersonalAgentService:n}=await Promise.resolve().then(()=>(xt(),Cn)),s=n.getInstance(),r=this.extractOutputForDisplay(t);s.captureFrontendToolResult(e,r,t.success)}async webSearch(e){try{let t=`https://api.duckduckgo.com/?q=${encodeURIComponent(e.query)}&format=json&no_html=1&skip_disambig=1`,s=(await hl.get(t,{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 o of s.RelatedTopics.slice(0,e.num_results||5))o.Text&&r.push({title:o.Text.split(" - ")[0]||"Related Topic",content:o.Text,url:o.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:e.query,results:r,total_results:r.length}}}catch(t){return{success:!1,error:`Web search failed: ${t.message}`}}}async readFile(e){try{let{file_path:t,offset:n,limit:s}=e,r=await Be.readFile(t,"utf-8");this.cacheFileState(t,r);let o=r,a=1,c;if(n!==void 0||s!==void 0){let l=r.split(`
242
+ 7. Normal command completion and result return`,parameters:{type:"object",properties:{input:{type:"string",description:'The input to provide to the interactive prompt. Should be appropriate for the prompt type (e.g., "y", "n", password, text, etc.)'}},required:["input"]},handler:this.provideInput.bind(this),category:"system",enabled:!0}),this.registerTool({name:"calculate",description:"Perform mathematical calculations",parameters:{type:"object",properties:{expression:{type:"string",description:"Mathematical expression to evaluate"}},required:["expression"]},handler:this.calculate.bind(this),category:"computation",enabled:!0}),this.registerTool({name:"http_request",description:"Make an HTTP request to a URL",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to request"},method:{type:"string",description:"HTTP method",enum:["GET","POST","PUT","DELETE"],default:"GET"},headers:{type:"object",description:"HTTP headers"},body:{type:"string",description:"Request body for POST/PUT requests"}},required:["url"]},handler:this.httpRequest.bind(this),category:"web",enabled:!0}),this.registerTool({name:"get_current_time",description:"Get the current date and time",parameters:{type:"object",properties:{format:{type:"string",description:"Date format (iso, local, unix)",enum:["iso","local","unix"],default:"iso"},timezone:{type:"string",description:"Timezone (e.g., America/New_York, UTC)",default:"local"}}},handler:this.getCurrentTime.bind(this),category:"system",enabled:!0}),this.registerTool({name:"Edit",description:"Performs exact string replacements in files with comprehensive validation",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to modify"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The text to replace it with (must be different from old_string)"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)",default:!1}},required:["file_path","old_string","new_string"]},handler:this.editFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Grep",description:"A powerful search tool built on ripgrep for searching file contents",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression pattern to search for in file contents"},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "**/*.tsx")'},type:{type:"string",description:"File type to search (rg --type). Common types: js, py, rust, go, java, etc."},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"},"-i":{type:"boolean",description:"Case insensitive search (rg -i)",default:!1},"-n":{type:"boolean",description:'Show line numbers in output (rg -n). Requires output_mode: "content".',default:!0},"-A":{type:"number",description:'Number of lines to show after each match (rg -A). Requires output_mode: "content".'},"-B":{type:"number",description:'Number of lines to show before each match (rg -B). Requires output_mode: "content".'},"-C":{type:"number",description:'Number of lines to show before and after each match (rg -C). Requires output_mode: "content".'},head_limit:{type:"number",description:'Limit output to first N lines/entries, equivalent to "| head -N". Defaults to 0 (unlimited).',default:0},offset:{type:"number",description:"Skip first N lines/entries before applying head_limit. Defaults to 0.",default:0},multiline:{type:"boolean",description:"Enable multiline mode where . matches newlines and patterns can span lines (rg -U --multiline-dotall).",default:!1},case_insensitive:{type:"boolean",description:"Case insensitive search (alias for -i)",default:!1}},required:["pattern"]},handler:this.grepFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Glob",description:"Fast file pattern matching tool that works with any codebase size",parameters:{type:"object",properties:{pattern:{type:"string",description:"The glob pattern to match files against"},path:{type:"string",description:"The directory to search in. Defaults to current working directory."}},required:["pattern"]},handler:this.globFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"NotebookEdit",description:"Edit Jupyter notebook (.ipynb) cells with cell-level precision",parameters:{type:"object",properties:{notebook_path:{type:"string",description:"The absolute path to the Jupyter notebook file to edit"},cell_id:{type:"string",description:"The ID of the cell to edit"},new_source:{type:"string",description:"The new source for the cell"},cell_type:{type:"string",enum:["code","markdown"],description:"The type of the cell (code or markdown)"},edit_mode:{type:"string",enum:["replace","insert","delete"],description:"The type of edit to make (replace, insert, delete). Defaults to replace.",default:"replace"}},required:["notebook_path","new_source"]},handler:this.editNotebook.bind(this),category:"file",enabled:!0})}registerTool(e){this.tools.set(e.name,e)}unregisterTool(e){let t=this.tools.delete(e);return t}async executeTool(e){let t=Date.now(),n=e.function.name;this.emit("tool_execution_start",{toolName:n,toolCall:e});let s={};try{s=JSON.parse(e.function.arguments)}catch(o){throw new Error(`Invalid arguments for tool '${n}': ${o}`)}let{ToolDisplay:r}=await Promise.resolve().then(()=>(Tt(),tl));r.start(n,s.description,s.command||s.file_path);try{let o=this.tools.get(n);if(!o)throw new Error(`Tool '${n}' not found`);if(!o.enabled)throw new Error(`Tool '${n}' is disabled`);let a=await this.queueToolExecution(n,()=>o.handler(s)),c=Date.now()-t,l=this.handleLargeResponse(a,n);for(this.executionHistory.push({toolName:n,args:s,result:l,timestamp:new Date,executionTime:c});this.executionHistory.length>100;)this.executionHistory.shift();return this.emit("tool_execution_complete",{toolName:n,result:l,executionTime:c}),r.result({toolName:n,command:s.command,filePath:s.file_path,description:s.description,output:this.extractOutputForDisplay(l),success:l.success,executionTime:c}),await this.captureFrontendToolResult(n,l),l}catch(o){let a=Date.now()-t,c={success:!1,error:o.message};return this.emit("tool_execution_error",{toolName:n,error:o,executionTime:a}),r.error(n,o.message),await this.captureFrontendToolResult(n,c),c}}extractOutputForDisplay(e){return e.success?e.result?typeof e.result=="string"?e.result:typeof e.result=="object"&&"stdout"in e.result?e.result.stdout||e.result.stderr||"":typeof e.result=="object"&&"content"in e.result?e.result.content||"":JSON.stringify(e.result,null,2):"":e.error||"Unknown error"}async captureFrontendToolResult(e,t){let{PersonalAgentService:n}=await Promise.resolve().then(()=>(xt(),In)),s=n.getInstance(),r=this.extractOutputForDisplay(t);s.captureFrontendToolResult(e,r,t.success)}async webSearch(e){try{let t=`https://api.duckduckgo.com/?q=${encodeURIComponent(e.query)}&format=json&no_html=1&skip_disambig=1`,s=(await hl.get(t,{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 o of s.RelatedTopics.slice(0,e.num_results||5))o.Text&&r.push({title:o.Text.split(" - ")[0]||"Related Topic",content:o.Text,url:o.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:e.query,results:r,total_results:r.length}}}catch(t){return{success:!1,error:`Web search failed: ${t.message}`}}}async readFile(e){try{let{file_path:t,offset:n,limit:s}=e,r=await We.readFile(t,"utf-8");this.cacheFileState(t,r);let o=r,a=1,c;if(n!==void 0||s!==void 0){let l=r.split(`
243
243
  `),d=n?Math.max(0,n-1):0,g=s?Math.min(l.length,d+s):l.length;a=d+1,c=g,o=l.slice(d,g).map((m,p)=>{let h=d+p+1;return`${" ".repeat(Math.max(0,6-String(h).length))}${h} ${m}`}).join(`
244
244
  `)}return{success:!0,result:{file_path:t,content:o,size:r.length,total_lines:r.split(`
245
- `).length,...n!==void 0&&{start_line:a},...c!==void 0&&{end_line:c}}}}catch(t){return{success:!1,error:`Failed to read file: ${t.message}`}}}async writeFile(e){try{let{file_path:t,content:n,mode:s="write"}=e;if(t.endsWith(".ipynb")&&Dt.existsSync(t)){let o=await Be.readFile(t,"utf-8"),a=JSON.parse(o);if(a.cells.length>0&&a.cells[0].id){let c=a.cells.findIndex(l=>l.id===a.cells[0].id);if(c!==-1)return a.cells[c].source=n,await Be.writeFile(t,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{file_path:t,bytes_written:n.length,message:"Notebook cell written successfully"}}}}Dt.existsSync(t)&&s!=="append"&&await this.validateFileNotModified(t);let r=Qn.dirname(t);return await Be.mkdir(r,{recursive:!0}),s==="append"?await Be.appendFile(t,n):await Be.writeFile(t,n),this.cacheFileState(t,n),{success:!0,result:{file_path:t,bytes_written:n.length,mode:s}}}catch(t){return{success:!1,error:`Failed to write file: ${t.message}`}}}async listDirectory(e){try{let t=await Be.readdir(e.directory_path,{withFileTypes:!0}),n=[];for(let s of t){if(!e.include_hidden&&s.name.startsWith("."))continue;let r=await Be.stat(Qn.join(e.directory_path,s.name));n.push({name:s.name,type:s.isDirectory()?"directory":"file",size:r.size,modified:r.mtime.toISOString()})}return{success:!0,result:{directory_path:e.directory_path,entries:n,total_count:n.length}}}catch(t){return{success:!1,error:`Failed to list directory: ${t.message}`}}}async executeCommandWithSession(e){try{let t=Ls.parseSessionMode(e.session),n=$s(e.command),s={activityTimeout:e.timeout||n.activityTimeout,maxTimeout:e.timeout||n.maxTimeout,initialTimeout:n.initialTimeout},r=await this.shellSessionManager.executeCommand(e.command,`tool-${Date.now()}`,this.currentUserId,e.session||"new",t,s);return{success:r.isSuccess,result:{command:e.command,stdout:r.output,stderr:"",exit_code:r.exitCode}}}catch(t){return{success:!1,error:`Command execution failed: ${t.message}`,result:{command:e.command,stdout:"",stderr:t.message||"",exit_code:-1}}}}async provideInput(e){return{success:!1,error:'Interactive input is not supported. Only "new" session mode is available, which does not support persistent interactive sessions.',result:{message:"Interactive input not supported",requested_input:e.input}}}async calculate(e){try{let t=e.expression.replace(/[^0-9+\-*/.() ]/g,"");if(t!==e.expression)throw new Error("Invalid characters in expression");let n=new Function("return "+t)();return{success:!0,result:{expression:e.expression,result:n,type:typeof n}}}catch(t){return{success:!1,error:`Calculation failed: ${t.message}`}}}async httpRequest(e){try{let t=await hl({method:e.method||"GET",url:e.url,headers:e.headers,data:e.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:e.url,status:t.status,headers:t.headers,data:typeof t.data=="string"?t.data.substring(0,1e4):t.data}}}catch(t){return{success:!1,error:`HTTP request failed: ${t.message}`,result:{url:e.url,status:t.response?.status||0,error_details:t.response?.data}}}}async getCurrentTime(e){try{let t=new Date,n={};switch(e.format){case"unix":n.timestamp=Math.floor(t.getTime()/1e3);break;case"local":n.datetime=t.toLocaleString();break;case"iso":default:n.datetime=t.toISOString();break}return n.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,n.format=e.format||"iso",{success:!0,result:n}}catch(t){return{success:!1,error:`Failed to get current time: ${t.message}`}}}async bashCommand(e){try{let{command:t,timeout:n,run_in_background:s=!1,working_directory:r}=e,o=r||process.cwd();if(s){this.backgroundProcessCounter++;let l=`bg-${this.backgroundProcessCounter}`,d=fl("/bin/bash",["-c",t],{env:process.env,cwd:o,stdio:["ignore","pipe","pipe"],detached:!0}),g={process:d,command:t,startTime:new Date,stdout:"",stderr:""},m=5*1024*1024;d.stdout.on("data",h=>{let f=h.toString();if(f){let y=this.backgroundProcesses.get(l);if(y&&y.stdout.length<m){let T=m-y.stdout.length;y.stdout+=f.substring(0,T),this.backgroundProcesses.set(l,y)}}}),d.stderr.on("data",h=>{let f=h.toString();if(f){let y=this.backgroundProcesses.get(l);if(y&&y.stderr.length<m){let T=m-y.stderr.length;y.stderr+=f.substring(0,T),this.backgroundProcesses.set(l,y)}}}),d.on("close",h=>{let f=this.backgroundProcesses.get(l);f&&(f.exitCode=h||0,this.backgroundProcesses.set(l,f),this.cleanupCompletedProcesses())}),this.backgroundProcesses.set(l,g);let p=`Command started in background with ID: ${l}
245
+ `).length,...n!==void 0&&{start_line:a},...c!==void 0&&{end_line:c}}}}catch(t){return{success:!1,error:`Failed to read file: ${t.message}`}}}async writeFile(e){try{let{file_path:t,content:n,mode:s="write"}=e;if(t.endsWith(".ipynb")&&Dt.existsSync(t)){let o=await We.readFile(t,"utf-8"),a=JSON.parse(o);if(a.cells.length>0&&a.cells[0].id){let c=a.cells.findIndex(l=>l.id===a.cells[0].id);if(c!==-1)return a.cells[c].source=n,await We.writeFile(t,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{file_path:t,bytes_written:n.length,message:"Notebook cell written successfully"}}}}Dt.existsSync(t)&&s!=="append"&&await this.validateFileNotModified(t);let r=Zn.dirname(t);return await We.mkdir(r,{recursive:!0}),s==="append"?await We.appendFile(t,n):await We.writeFile(t,n),this.cacheFileState(t,n),{success:!0,result:{file_path:t,bytes_written:n.length,mode:s}}}catch(t){return{success:!1,error:`Failed to write file: ${t.message}`}}}async listDirectory(e){try{let t=await We.readdir(e.directory_path,{withFileTypes:!0}),n=[];for(let s of t){if(!e.include_hidden&&s.name.startsWith("."))continue;let r=await We.stat(Zn.join(e.directory_path,s.name));n.push({name:s.name,type:s.isDirectory()?"directory":"file",size:r.size,modified:r.mtime.toISOString()})}return{success:!0,result:{directory_path:e.directory_path,entries:n,total_count:n.length}}}catch(t){return{success:!1,error:`Failed to list directory: ${t.message}`}}}async executeCommandWithSession(e){try{let t=Us.parseSessionMode(e.session),n=Fs(e.command),s={activityTimeout:e.timeout||n.activityTimeout,maxTimeout:e.timeout||n.maxTimeout,initialTimeout:n.initialTimeout},r=await this.shellSessionManager.executeCommand(e.command,`tool-${Date.now()}`,this.currentUserId,e.session||"new",t,s);return{success:r.isSuccess,result:{command:e.command,stdout:r.output,stderr:"",exit_code:r.exitCode}}}catch(t){return{success:!1,error:`Command execution failed: ${t.message}`,result:{command:e.command,stdout:"",stderr:t.message||"",exit_code:-1}}}}async provideInput(e){return{success:!1,error:'Interactive input is not supported. Only "new" session mode is available, which does not support persistent interactive sessions.',result:{message:"Interactive input not supported",requested_input:e.input}}}async calculate(e){try{let t=e.expression.replace(/[^0-9+\-*/.() ]/g,"");if(t!==e.expression)throw new Error("Invalid characters in expression");let n=new Function("return "+t)();return{success:!0,result:{expression:e.expression,result:n,type:typeof n}}}catch(t){return{success:!1,error:`Calculation failed: ${t.message}`}}}async httpRequest(e){try{let t=await hl({method:e.method||"GET",url:e.url,headers:e.headers,data:e.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:e.url,status:t.status,headers:t.headers,data:typeof t.data=="string"?t.data.substring(0,1e4):t.data}}}catch(t){return{success:!1,error:`HTTP request failed: ${t.message}`,result:{url:e.url,status:t.response?.status||0,error_details:t.response?.data}}}}async getCurrentTime(e){try{let t=new Date,n={};switch(e.format){case"unix":n.timestamp=Math.floor(t.getTime()/1e3);break;case"local":n.datetime=t.toLocaleString();break;case"iso":default:n.datetime=t.toISOString();break}return n.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,n.format=e.format||"iso",{success:!0,result:n}}catch(t){return{success:!1,error:`Failed to get current time: ${t.message}`}}}async bashCommand(e){try{let{command:t,timeout:n,run_in_background:s=!1,working_directory:r}=e,o=r||process.cwd();if(s){this.backgroundProcessCounter++;let l=`bg-${this.backgroundProcessCounter}`,d=fl("/bin/bash",["-c",t],{env:process.env,cwd:o,stdio:["ignore","pipe","pipe"],detached:!0}),g={process:d,command:t,startTime:new Date,stdout:"",stderr:""},m=5*1024*1024;d.stdout.on("data",h=>{let f=h.toString();if(f){let y=this.backgroundProcesses.get(l);if(y&&y.stdout.length<m){let T=m-y.stdout.length;y.stdout+=f.substring(0,T),this.backgroundProcesses.set(l,y)}}}),d.stderr.on("data",h=>{let f=h.toString();if(f){let y=this.backgroundProcesses.get(l);if(y&&y.stderr.length<m){let T=m-y.stderr.length;y.stderr+=f.substring(0,T),this.backgroundProcesses.set(l,y)}}}),d.on("close",h=>{let f=this.backgroundProcesses.get(l);f&&(f.exitCode=h||0,this.backgroundProcesses.set(l,f),this.cleanupCompletedProcesses())}),this.backgroundProcesses.set(l,g);let p=`Command started in background with ID: ${l}
246
246
  PID: ${d.pid}
247
247
  Command: ${t}
248
248
 
249
249
  Note: The process will continue running in the background.
250
- Output will be collected automatically.`;return{success:!0,result:{process_id:l,pid:d.pid,message:p}}}let a=n?{activityTimeout:n,maxTimeout:n,initialTimeout:n}:$s(t),c=await this.shellSessionManager.executeCommand(t,`tool-${Date.now()}`,this.currentUserId,"new","new",a);return{success:c.isSuccess,result:{command:t,stdout:c.output,stderr:"",exit_code:c.exitCode}}}catch(t){return{success:!1,error:`Bash command failed: ${t.message}`}}}async editFile(e){try{let{file_path:t,old_string:n,new_string:s,replace_all:r=!1}=e;if(n===s)throw new Error("No changes to make: old_string and new_string are identical");if(t.endsWith(".ipynb")&&Dt.existsSync(t)){let c=await Be.readFile(t,"utf-8"),l=JSON.parse(c);for(let d=0;d<l.cells.length;d++){let g=l.cells[d],m=Array.isArray(g.source)?g.source.join(""):g.source;if(m.includes(n)){let p=r?m.replaceAll(n,s):m.replace(n,s);return l.cells[d].source=p,await Be.writeFile(t,JSON.stringify(l,null,2),"utf-8"),{success:!0,result:{file_path:t,replacements:r?m.split(n).length-1:1,message:"Notebook cell edited successfully"}}}}throw new Error("String not found in notebook. The old_string does not exist in any cell.")}await this.validateFileNotModified(t);let o=await Be.readFile(t,"utf-8");if(!o.includes(n))throw new Error("String not found in file. Check for whitespace/indentation differences.");let a=r?o.replaceAll(n,s):o.replace(n,s);if(a===o)throw new Error("Edit failed: File content unchanged after replacement");return await Be.writeFile(t,a,"utf-8"),this.cacheFileState(t,a),{success:!0,result:{file_path:t,replacements:r?o.split(n).length-1:1,message:"File edited successfully"}}}catch(t){return{success:!1,error:`Edit failed: ${t.message}`}}}async grepFiles(e){try{let{pattern:t,path:n=process.cwd(),glob:s,type:r,output_mode:o="files_with_matches","-i":a=!1,"-n":c=!0,"-A":l,"-B":d,"-C":g,head_limit:m=0,offset:p=0,multiline:h=!1,case_insensitive:f=!1}=e,y=[];return(a||f)&&y.push("-i"),o==="files_with_matches"?y.push("-l"):o==="count"?y.push("-c"):o==="content"&&c&&y.push("-n"),s&&y.push("--glob",s),r&&y.push("--type",r),o==="content"&&(g!==void 0?y.push("-C",String(g)):(l!==void 0&&y.push("-A",String(l)),d!==void 0&&y.push("-B",String(d)))),h&&y.push("-U","--multiline-dotall"),y.push(t,n),new Promise(T=>{let x=fl("rg",y,{stdio:["ignore","pipe","pipe"]}),w="",C="";x.stdout.on("data",v=>{w+=v.toString()}),x.stderr.on("data",v=>{C+=v.toString()}),x.on("close",v=>{if(v!==0&&v!==1){T({success:!1,error:`ripgrep failed: ${C||"Unknown error"}`});return}let E=w.trim().split(`
251
- `).filter(I=>I);p>0&&(E=E.slice(p)),m>0&&(E=E.slice(0,m));let S=E.length;T({success:!0,result:{pattern:t,num_files:S,files:E,output:E.join(`
252
- `)}})}),x.on("error",v=>{T({success:!1,error:`Failed to execute ripgrep: ${v.message}. Make sure ripgrep is installed.`})})})}catch(t){return{success:!1,error:`Grep failed: ${t.message}`}}}globRegexCache=new Map;static MAX_GLOB_CACHE_SIZE=50;getGlobRegex(e){let t=this.globRegexCache.get(e);if(t)return t;let n=e;if(n=n.replace(/[.+^${}()|[\]\\]/g,"\\$&"),n=n.replace(/\*\*/g,"<DOUBLESTAR>"),n=n.replace(/\*/g,"[^/]*"),n=n.replace(/<DOUBLESTAR>/g,".*"),n=n.replace(/\?/g,"."),t=new RegExp(`^${n}$`),this.globRegexCache.size>=i.MAX_GLOB_CACHE_SIZE){let s=this.globRegexCache.keys().next().value;s&&this.globRegexCache.delete(s)}return this.globRegexCache.set(e,t),t}async globFiles(e){try{let{pattern:t,path:n=process.cwd()}=e,s=this.getGlobRegex(t),r=[],o=async a=>{try{let c=await Be.readdir(a,{withFileTypes:!0});for(let l of c){if(l.name.startsWith("."))continue;let d=Qn.join(a,l.name),g=Qn.relative(n,d);l.isDirectory()?await o(d):(s.test(g)||s.test(l.name))&&r.push(d)}}catch{}};return await o(n),{success:!0,result:{pattern:t,num_files:r.length,files:r}}}catch(t){return{success:!1,error:`Glob failed: ${t.message}`}}}async editNotebook(e){try{let{notebook_path:t,cell_id:n,new_source:s,cell_type:r="code",edit_mode:o="replace"}=e;if(!Dt.existsSync(t))throw new Error(`Notebook file does not exist: ${t}`);if(!t.endsWith(".ipynb"))throw new Error("File must be a Jupyter notebook (.ipynb file)");let a=await Be.readFile(t,"utf-8"),c=JSON.parse(a);switch(o){case"replace":{if(!n)throw new Error("cell_id is required for replace mode");let l=c.cells.findIndex(d=>d.id===n);if(l===-1)throw new Error(`Cell with id ${n} not found`);c.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(n){let d=c.cells.findIndex(g=>g.id===n);c.cells.splice(d+1,0,l)}else c.cells.unshift(l);break}case"delete":{if(!n)throw new Error("cell_id is required for delete mode");let l=c.cells.findIndex(d=>d.id===n);if(l===-1)throw new Error(`Cell with id ${n} not found`);c.cells.splice(l,1);break}default:throw new Error(`Invalid edit_mode: ${o}`)}return await Be.writeFile(t,JSON.stringify(c,null,2),"utf-8"),{success:!0,result:{notebook_path:t,edit_mode:o,cell_id:n,message:"Notebook edited successfully"}}}catch(t){return{success:!1,error:`NotebookEdit failed: ${t.message}`}}}cleanupCompletedProcesses(){let e=[];for(let[t,n]of this.backgroundProcesses.entries())n.exitCode!==void 0&&e.push(t);if(e.length>i.MAX_COMPLETED_PROCESSES){e.sort();let t=e.slice(0,e.length-i.MAX_COMPLETED_PROCESSES);for(let n of t)this.backgroundProcesses.delete(n)}}cacheFileState(e,t){try{let n=Dt.statSync(e);if(this.fileStateCache.size>=i.MAX_FILE_STATE_CACHE_SIZE){let s=this.fileStateCache.keys().next().value;s&&this.fileStateCache.delete(s)}this.fileStateCache.set(e,{content:t,modificationDate:n.mtime,filePath:e})}catch{}}async validateFileNotModified(e){let t=this.fileStateCache.get(e);if(!t){if(Dt.existsSync(e)){let s=await Be.readFile(e,"utf-8");this.cacheFileState(e,s)}return}if(Dt.statSync(e).mtime.getTime()!==t.modificationDate.getTime())throw new Error("File has been modified since last read. Read it again before editing.")}getAvailableTools(){let e=[];for(let[t,n]of this.tools.entries())n.enabled&&e.push({type:"function",function:{name:t,description:n.description,parameters:n.parameters}});return e}getToolsByCategory(e){return this.getAvailableTools().filter(t=>this.tools.get(t.function.name)?.category===e)}enableTool(e){let t=this.tools.get(e);return t?(t.enabled=!0,!0):!1}disableTool(e){let t=this.tools.get(e);return t?(t.enabled=!1,!0):!1}getExecutionHistory(e=10){return this.executionHistory.slice(-e)}getExecutionStats(){let e=this.executionHistory.length,t=this.executionHistory.filter(a=>a.result.success).length,n=e-t,s=e>0?this.executionHistory.reduce((a,c)=>a+c.executionTime,0)/e:0,r=new Map;this.executionHistory.forEach(a=>{r.set(a.toolName,(r.get(a.toolName)||0)+1)});let o=r.size>0?Array.from(r.entries()).reduce((a,c)=>c[1]>a[1]?c:a)[0]:null;return{total:e,successful:t,failed:n,averageTime:Math.round(s),mostUsed:o}}clearHistory(){this.executionHistory=[]}setUserId(e){this.currentUserId=e}getCurrentUserId(){return this.currentUserId}cleanupUserSession(e){}handleLargeResponse(e,t){if(!e.success||!e.result)return e;let n=typeof e.result=="string"?e.result:JSON.stringify(e.result);if(this.tokenCounter.exceedsResponseLimit(n)){let s=this.createTempFile(n,t);return s?{success:!0,result:this.tokenCounter.formatLargeResponsePreview(n,s)}:{success:!0,result:this.tokenCounter.truncateOutput(n)}}return e}createTempFile(e,t){try{let n=Wp.tmpdir(),s=Qn.join(n,"orion_tool_responses");Dt.existsSync(s)||Dt.mkdirSync(s,{recursive:!0});let r=Math.floor(Date.now()/1e3),o=Math.random().toString(36).substring(2,10),a=`${t}_${r}_${o}.txt`,c=Qn.join(s,a);return Dt.writeFileSync(c,e,"utf8"),c}catch{return null}}stopAllRunningTools(){}}});import{spawn as Gp}from"child_process";var Br,yl=F(()=>{"use strict";j();Yn();Br=class{toolNames=["bash","Bash","run_command"];async execute(e,t,n,s){let r=n.command;if(r==null)throw new Error("Missing command argument");if(typeof r!="string")throw new Error(`Command must be a string. Received: ${typeof r}`);if(r.trim().length===0)throw new Error("Command cannot be empty");let o=n.session;if(o==null)o="new";else{if(typeof o!="string")throw new Error(`Session must be a string. Received: ${typeof o}`);o=o.toLowerCase()}if(o!=="new"&&o!=="existing")throw new Error(`Invalid session mode '${o}' - must be 'new' or 'existing'`);let a;if(n.timeout!==void 0&&n.timeout!==null){if(typeof n.timeout=="string"){let T=Number(n.timeout);if(Number.isNaN(T))throw new Error(`Timeout must be a valid number. Received string: "${n.timeout}"`);a=T}else if(typeof n.timeout=="number"){if(Number.isNaN(n.timeout))throw new Error("Timeout cannot be NaN");if(!Number.isFinite(n.timeout))throw new Error(`Timeout must be finite. Received: ${n.timeout}`);a=n.timeout}else throw new Error(`Timeout must be a number. Received: ${typeof n.timeout}`);if(a<=0)throw new Error(`Timeout must be positive. Received: ${a}ms`);if(a>6e5)throw new Error(`Timeout cannot exceed 600000ms (10 minutes). Received: ${a}ms`);a=Math.floor(a)}let c=n.description;c!=null&&typeof c!="string"&&u.debug(`[RunCommandTool] Invalid description type: ${typeof c}, ignoring`);let l=!1;if(n.run_in_background!==void 0&&n.run_in_background!==null)if(typeof n.run_in_background=="boolean")l=n.run_in_background;else if(typeof n.run_in_background=="string")l=n.run_in_background.toLowerCase()==="true";else throw new Error(`run_in_background must be a boolean. Received: ${typeof n.run_in_background}`);let d=ml(r);if(d)return u.debug("[RunCommandTool] Command blocked by security check"),[{type:"text",text:d}];let g=pl(r);if(g.isDelete){u.debug("[RunCommandTool] Delete command detected, requesting confirmation"),u.debug(`[RunCommandTool] Affected targets: ${g.paths.join(", ")}`);let{FrontendWebSocketService:T}=await Promise.resolve().then(()=>(Jn(),$i)),x=T.getInstance(),w;if(x.hasElectronFrontend())w=await x.requestDeleteConfirmation(r,c);else{let{PersonalAgentService:C}=await Promise.resolve().then(()=>(xt(),Cn)),v=C.getInstance();w=await this.requestCliConfirmation(v,r,g.paths,c)}if(w==="declined")return u.debug("[RunCommandTool] User declined delete command"),[{type:"text",text:`User declined the delete. Command NOT executed: ${r}
250
+ Output will be collected automatically.`;return{success:!0,result:{process_id:l,pid:d.pid,message:p}}}let a=n?{activityTimeout:n,maxTimeout:n,initialTimeout:n}:Fs(t),c=await this.shellSessionManager.executeCommand(t,`tool-${Date.now()}`,this.currentUserId,"new","new",a);return{success:c.isSuccess,result:{command:t,stdout:c.output,stderr:"",exit_code:c.exitCode}}}catch(t){return{success:!1,error:`Bash command failed: ${t.message}`}}}async editFile(e){try{let{file_path:t,old_string:n,new_string:s,replace_all:r=!1}=e;if(n===s)throw new Error("No changes to make: old_string and new_string are identical");if(t.endsWith(".ipynb")&&Dt.existsSync(t)){let c=await We.readFile(t,"utf-8"),l=JSON.parse(c);for(let d=0;d<l.cells.length;d++){let g=l.cells[d],m=Array.isArray(g.source)?g.source.join(""):g.source;if(m.includes(n)){let p=r?m.replaceAll(n,s):m.replace(n,s);return l.cells[d].source=p,await We.writeFile(t,JSON.stringify(l,null,2),"utf-8"),{success:!0,result:{file_path:t,replacements:r?m.split(n).length-1:1,message:"Notebook cell edited successfully"}}}}throw new Error("String not found in notebook. The old_string does not exist in any cell.")}await this.validateFileNotModified(t);let o=await We.readFile(t,"utf-8");if(!o.includes(n))throw new Error("String not found in file. Check for whitespace/indentation differences.");let a=r?o.replaceAll(n,s):o.replace(n,s);if(a===o)throw new Error("Edit failed: File content unchanged after replacement");return await We.writeFile(t,a,"utf-8"),this.cacheFileState(t,a),{success:!0,result:{file_path:t,replacements:r?o.split(n).length-1:1,message:"File edited successfully"}}}catch(t){return{success:!1,error:`Edit failed: ${t.message}`}}}async grepFiles(e){try{let{pattern:t,path:n=process.cwd(),glob:s,type:r,output_mode:o="files_with_matches","-i":a=!1,"-n":c=!0,"-A":l,"-B":d,"-C":g,head_limit:m=0,offset:p=0,multiline:h=!1,case_insensitive:f=!1}=e,y=[];return(a||f)&&y.push("-i"),o==="files_with_matches"?y.push("-l"):o==="count"?y.push("-c"):o==="content"&&c&&y.push("-n"),s&&y.push("--glob",s),r&&y.push("--type",r),o==="content"&&(g!==void 0?y.push("-C",String(g)):(l!==void 0&&y.push("-A",String(l)),d!==void 0&&y.push("-B",String(d)))),h&&y.push("-U","--multiline-dotall"),y.push(t,n),new Promise(T=>{let C=fl("rg",y,{stdio:["ignore","pipe","pipe"]}),w="",E="";C.stdout.on("data",v=>{w+=v.toString()}),C.stderr.on("data",v=>{E+=v.toString()}),C.on("close",v=>{if(v!==0&&v!==1){T({success:!1,error:`ripgrep failed: ${E||"Unknown error"}`});return}let x=w.trim().split(`
251
+ `).filter(I=>I);p>0&&(x=x.slice(p)),m>0&&(x=x.slice(0,m));let S=x.length;T({success:!0,result:{pattern:t,num_files:S,files:x,output:x.join(`
252
+ `)}})}),C.on("error",v=>{T({success:!1,error:`Failed to execute ripgrep: ${v.message}. Make sure ripgrep is installed.`})})})}catch(t){return{success:!1,error:`Grep failed: ${t.message}`}}}globRegexCache=new Map;static MAX_GLOB_CACHE_SIZE=50;getGlobRegex(e){let t=this.globRegexCache.get(e);if(t)return t;let n=e;if(n=n.replace(/[.+^${}()|[\]\\]/g,"\\$&"),n=n.replace(/\*\*/g,"<DOUBLESTAR>"),n=n.replace(/\*/g,"[^/]*"),n=n.replace(/<DOUBLESTAR>/g,".*"),n=n.replace(/\?/g,"."),t=new RegExp(`^${n}$`),this.globRegexCache.size>=i.MAX_GLOB_CACHE_SIZE){let s=this.globRegexCache.keys().next().value;s&&this.globRegexCache.delete(s)}return this.globRegexCache.set(e,t),t}async globFiles(e){try{let{pattern:t,path:n=process.cwd()}=e,s=this.getGlobRegex(t),r=[],o=async a=>{try{let c=await We.readdir(a,{withFileTypes:!0});for(let l of c){if(l.name.startsWith("."))continue;let d=Zn.join(a,l.name),g=Zn.relative(n,d);l.isDirectory()?await o(d):(s.test(g)||s.test(l.name))&&r.push(d)}}catch{}};return await o(n),{success:!0,result:{pattern:t,num_files:r.length,files:r}}}catch(t){return{success:!1,error:`Glob failed: ${t.message}`}}}async editNotebook(e){try{let{notebook_path:t,cell_id:n,new_source:s,cell_type:r="code",edit_mode:o="replace"}=e;if(!Dt.existsSync(t))throw new Error(`Notebook file does not exist: ${t}`);if(!t.endsWith(".ipynb"))throw new Error("File must be a Jupyter notebook (.ipynb file)");let a=await We.readFile(t,"utf-8"),c=JSON.parse(a);switch(o){case"replace":{if(!n)throw new Error("cell_id is required for replace mode");let l=c.cells.findIndex(d=>d.id===n);if(l===-1)throw new Error(`Cell with id ${n} not found`);c.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(n){let d=c.cells.findIndex(g=>g.id===n);c.cells.splice(d+1,0,l)}else c.cells.unshift(l);break}case"delete":{if(!n)throw new Error("cell_id is required for delete mode");let l=c.cells.findIndex(d=>d.id===n);if(l===-1)throw new Error(`Cell with id ${n} not found`);c.cells.splice(l,1);break}default:throw new Error(`Invalid edit_mode: ${o}`)}return await We.writeFile(t,JSON.stringify(c,null,2),"utf-8"),{success:!0,result:{notebook_path:t,edit_mode:o,cell_id:n,message:"Notebook edited successfully"}}}catch(t){return{success:!1,error:`NotebookEdit failed: ${t.message}`}}}cleanupCompletedProcesses(){let e=[];for(let[t,n]of this.backgroundProcesses.entries())n.exitCode!==void 0&&e.push(t);if(e.length>i.MAX_COMPLETED_PROCESSES){e.sort();let t=e.slice(0,e.length-i.MAX_COMPLETED_PROCESSES);for(let n of t)this.backgroundProcesses.delete(n)}}cacheFileState(e,t){try{let n=Dt.statSync(e);if(this.fileStateCache.size>=i.MAX_FILE_STATE_CACHE_SIZE){let s=this.fileStateCache.keys().next().value;s&&this.fileStateCache.delete(s)}this.fileStateCache.set(e,{content:t,modificationDate:n.mtime,filePath:e})}catch{}}async validateFileNotModified(e){let t=this.fileStateCache.get(e);if(!t){if(Dt.existsSync(e)){let s=await We.readFile(e,"utf-8");this.cacheFileState(e,s)}return}if(Dt.statSync(e).mtime.getTime()!==t.modificationDate.getTime())throw new Error("File has been modified since last read. Read it again before editing.")}getAvailableTools(){let e=[];for(let[t,n]of this.tools.entries())n.enabled&&e.push({type:"function",function:{name:t,description:n.description,parameters:n.parameters}});return e}getToolsByCategory(e){return this.getAvailableTools().filter(t=>this.tools.get(t.function.name)?.category===e)}enableTool(e){let t=this.tools.get(e);return t?(t.enabled=!0,!0):!1}disableTool(e){let t=this.tools.get(e);return t?(t.enabled=!1,!0):!1}getExecutionHistory(e=10){return this.executionHistory.slice(-e)}getExecutionStats(){let e=this.executionHistory.length,t=this.executionHistory.filter(a=>a.result.success).length,n=e-t,s=e>0?this.executionHistory.reduce((a,c)=>a+c.executionTime,0)/e:0,r=new Map;this.executionHistory.forEach(a=>{r.set(a.toolName,(r.get(a.toolName)||0)+1)});let o=r.size>0?Array.from(r.entries()).reduce((a,c)=>c[1]>a[1]?c:a)[0]:null;return{total:e,successful:t,failed:n,averageTime:Math.round(s),mostUsed:o}}clearHistory(){this.executionHistory=[]}setUserId(e){this.currentUserId=e}getCurrentUserId(){return this.currentUserId}cleanupUserSession(e){}handleLargeResponse(e,t){if(!e.success||!e.result)return e;let n=typeof e.result=="string"?e.result:JSON.stringify(e.result);if(this.tokenCounter.exceedsResponseLimit(n)){let s=this.createTempFile(n,t);return s?{success:!0,result:this.tokenCounter.formatLargeResponsePreview(n,s)}:{success:!0,result:this.tokenCounter.truncateOutput(n)}}return e}createTempFile(e,t){try{let n=Wp.tmpdir(),s=Zn.join(n,"orion_tool_responses");Dt.existsSync(s)||Dt.mkdirSync(s,{recursive:!0});let r=Math.floor(Date.now()/1e3),o=Math.random().toString(36).substring(2,10),a=`${t}_${r}_${o}.txt`,c=Zn.join(s,a);return Dt.writeFileSync(c,e,"utf8"),c}catch{return null}}stopAllRunningTools(){}}});import{spawn as Gp}from"child_process";var Wr,yl=$(()=>{"use strict";z();Jn();Wr=class{toolNames=["bash","Bash","run_command"];async execute(e,t,n,s){let r=n.command;if(r==null)throw new Error("Missing command argument");if(typeof r!="string")throw new Error(`Command must be a string. Received: ${typeof r}`);if(r.trim().length===0)throw new Error("Command cannot be empty");let o=n.session;if(o==null)o="new";else{if(typeof o!="string")throw new Error(`Session must be a string. Received: ${typeof o}`);o=o.toLowerCase()}if(o!=="new"&&o!=="existing")throw new Error(`Invalid session mode '${o}' - must be 'new' or 'existing'`);let a;if(n.timeout!==void 0&&n.timeout!==null){if(typeof n.timeout=="string"){let T=Number(n.timeout);if(Number.isNaN(T))throw new Error(`Timeout must be a valid number. Received string: "${n.timeout}"`);a=T}else if(typeof n.timeout=="number"){if(Number.isNaN(n.timeout))throw new Error("Timeout cannot be NaN");if(!Number.isFinite(n.timeout))throw new Error(`Timeout must be finite. Received: ${n.timeout}`);a=n.timeout}else throw new Error(`Timeout must be a number. Received: ${typeof n.timeout}`);if(a<=0)throw new Error(`Timeout must be positive. Received: ${a}ms`);if(a>6e5)throw new Error(`Timeout cannot exceed 600000ms (10 minutes). Received: ${a}ms`);a=Math.floor(a)}let c=n.description;c!=null&&typeof c!="string"&&u.debug(`[RunCommandTool] Invalid description type: ${typeof c}, ignoring`);let l=!1;if(n.run_in_background!==void 0&&n.run_in_background!==null)if(typeof n.run_in_background=="boolean")l=n.run_in_background;else if(typeof n.run_in_background=="string")l=n.run_in_background.toLowerCase()==="true";else throw new Error(`run_in_background must be a boolean. Received: ${typeof n.run_in_background}`);let d=ml(r);if(d)return u.debug("[RunCommandTool] Command blocked by security check"),[{type:"text",text:d}];let g=pl(r);if(g.isDelete){u.debug("[RunCommandTool] Delete command detected, requesting confirmation"),u.debug(`[RunCommandTool] Affected targets: ${g.paths.join(", ")}`);let{FrontendWebSocketService:T}=await Promise.resolve().then(()=>(es(),$i)),C=T.getInstance(),w;if(C.hasElectronFrontend())w=await C.requestDeleteConfirmation(r,c);else{let{PersonalAgentService:E}=await Promise.resolve().then(()=>(xt(),In)),v=E.getInstance();w=await this.requestCliConfirmation(v,r,g.paths,c)}if(w==="declined")return u.debug("[RunCommandTool] User declined delete command"),[{type:"text",text:`User declined the delete. Command NOT executed: ${r}
253
253
 
254
254
  ALTERNATIVES (choose one):
255
255
  • Rename instead: mv [file] [file].old or mv [file] [file].legacy
@@ -273,10 +273,10 @@ DO NOT keep retrying the same delete command.`}];if(w==="error")return u.debug("
273
273
  Please try again or ask the user to confirm the deletion manually.`}];u.debug("[RunCommandTool] User confirmed delete command, proceeding")}let m=a||12e4,p=Ni();u.debug(`[RunCommandTool] Executing command on platform: ${p}`),u.debug(`[RunCommandTool] Command: ${r.substring(0,50)}${r.length>50?"...":""}`),c&&u.debug(`[RunCommandTool] Description: ${c}`),u.debug(`[RunCommandTool] Session: ${o}, Timeout: ${m}ms, Background: ${l}`);let h=this.detectMkdirCommand(r);if(h.isMkdir&&h.path){let T=await import("fs/promises");try{if((await T.stat(h.path)).isDirectory())return[{type:"text",text:`Error: Directory already exists at '${h.path}'.
274
274
 
275
275
  The mkdir command was not executed because the directory already exists.
276
- If you need to ensure the directory exists, this is already satisfied.`}]}catch{}}let f=this.detectTouchCommand(r);if(f.isTouch&&f.path){let T=await import("fs/promises");try{let x=await T.stat(f.path);if(x.isFile())return[{type:"text",text:`Error: File already exists at '${f.path}'.
276
+ If you need to ensure the directory exists, this is already satisfied.`}]}catch{}}let f=this.detectTouchCommand(r);if(f.isTouch&&f.path){let T=await import("fs/promises");try{let C=await T.stat(f.path);if(C.isFile())return[{type:"text",text:`Error: File already exists at '${f.path}'.
277
277
 
278
278
  The touch command was not executed because the file already exists.
279
- If you need to update the timestamp, use: touch -c "${f.path}"`}];if(x.isDirectory())return[{type:"text",text:`Error: A directory exists at '${f.path}'.
279
+ If you need to update the timestamp, use: touch -c "${f.path}"`}];if(C.isDirectory())return[{type:"text",text:`Error: A directory exists at '${f.path}'.
280
280
 
281
281
  Cannot create a file where a directory already exists.`}]}catch{}}let y=this.detectFileOverwriteCommand(r);if(y.isOverwrite&&y.targetPath){let T=await import("fs/promises");try{if((await T.stat(y.targetPath)).isFile())return[{type:"text",text:`Error: File already exists at '${y.targetPath}'.
282
282
 
@@ -285,19 +285,19 @@ The command would overwrite an existing file. For safety, this was blocked.
285
285
  Options:
286
286
  • Backup first: cp "${y.targetPath}" "${y.targetPath}.bak"
287
287
  • Delete first: rm "${y.targetPath}" (requires confirmation)
288
- • Use different name: Change the target filename`}]}catch{}}if(l)return this.executeBackground(e,r,m,s);try{let T=(await Promise.resolve().then(()=>(Ur(),_i))).ToolCallingService.getInstance(),x={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:r,session:o,timeout:m})}},w=await T.executeTool(x),C="";if(w.success){let v=(w.result?.stdout||"").trim(),E=w.result?.exitCode??0;if(C=`Command: ${r}
289
- `,C+=`Exit Code: ${E}
288
+ • Use different name: Change the target filename`}]}catch{}}if(l)return this.executeBackground(e,r,m,s);try{let T=(await Promise.resolve().then(()=>(Br(),_i))).ToolCallingService.getInstance(),C={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:r,session:o,timeout:m})}},w=await T.executeTool(C),E="";if(w.success){let v=(w.result?.stdout||"").trim(),x=w.result?.exitCode??0;if(E=`Command: ${r}
289
+ `,E+=`Exit Code: ${x}
290
290
 
291
291
  `,v.length>0){let S=v.split(`
292
- `),I=S.slice(0,15);C+=I.join(`
293
- `),S.length>15&&(C+=`
292
+ `),I=S.slice(0,15);E+=I.join(`
293
+ `),S.length>15&&(E+=`
294
294
 
295
- ... (showing first 15 of ${S.length} lines)`)}else C+="(no output)";return[{type:"text",text:C}]}else{let v=w.error||"Unknown error",E=w.result?.exitCode??1;return C=`Command: ${r}
296
- `,C+=`Exit Code: ${E}
295
+ ... (showing first 15 of ${S.length} lines)`)}else E+="(no output)";return[{type:"text",text:E}]}else{let v=w.error||"Unknown error",x=w.result?.exitCode??1;return E=`Command: ${r}
296
+ `,E+=`Exit Code: ${x}
297
297
 
298
- `,C+=`Error:
299
- ${v}`,[{type:"text",text:C}]}}catch(T){return u.debug(`[RunCommandTool] Failed to execute bash command: ${T.message}`),[{type:"text",text:`Command: ${r}
300
- Error: ${T.message}`}]}}async requestCliConfirmation(e,t,n,s){let r=`delete-cli-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,o=3e4;return u.debug(`[RunCommandTool] Requesting CLI confirmation: ${r}`),new Promise(a=>{let c=setTimeout(()=>{u.debug(`[RunCommandTool] CLI confirmation timed out: ${r}`),e.off("confirmation_response",l),a("timeout")},o),l=d=>{d.confirmationId===r&&(clearTimeout(c),e.off("confirmation_response",l),d.timedOut?a("timeout"):d.confirmed?a("confirmed"):a("declined"))};e.on("confirmation_response",l),e.emit("confirmation_request",{confirmationId:r,type:"confirmation",title:"Confirm Delete",message:"The AI wants to delete files. Continue?",command:t,targets:n,isDestructive:!0,timeout:o}),u.debug(`[RunCommandTool] CLI confirmation request emitted: ${r}`)})}async executeBackground(e,t,n,s){let r=`shell_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,o=s.workingDirectory||process.cwd();u.debug(`[RunCommandTool] Starting background process: ${r}`);let a,c;Ft()?(a="powershell.exe",c=["-ExecutionPolicy","Bypass","-Command",t]):(a="/bin/bash",c=["-c",t]);let l=Gp(a,c,{cwd:o,env:process.env,stdio:["ignore","pipe","pipe"],detached:!Ft()});l.unref();let d={id:r,command:t,startTime:new Date,status:"running",output:[],error:[],pid:l.pid};Ue.addProcess(d);let g=5*1024*1024,m=0,p=0;return l.stdout?.on("data",h=>{if(m<g){let f=h.toString();d.output.push(f),m+=f.length,m>=g&&d.output.push("[Output truncated - buffer limit reached]")}}),l.stderr?.on("data",h=>{if(p<g){let f=h.toString();d.error.push(f),p+=f.length,p>=g&&d.error.push("[Error output truncated - buffer limit reached]")}}),l.on("exit",h=>{u.debug(`[RunCommandTool] Background process ${r} exited with code ${h}`),Ue.updateProcess(r,{endTime:new Date,exitCode:h??0,status:(h??0)===0?"completed":"failed"})}),l.on("error",h=>{u.debug(`[RunCommandTool] Background process ${r} error: ${h.message}`),d.error.push(h.message),Ue.updateProcess(r,{endTime:new Date,status:"failed"})}),n&&setTimeout(()=>{let h=Ue.getProcess(r);h&&h.status==="running"&&(u.debug(`[RunCommandTool] Background process ${r} timed out, killing...`),Xn(l.pid,"SIGTERM"),setTimeout(()=>{let f=Ue.getProcess(r);f&&f.status==="running"&&Xn(l.pid,"SIGKILL")},3e3),Ue.updateProcess(r,{status:"killed",endTime:new Date}),d.error.push(`Process timed out after ${n}ms`))},n),[{type:"text",text:`Background process started with ID: ${r}
298
+ `,E+=`Error:
299
+ ${v}`,[{type:"text",text:E}]}}catch(T){return u.debug(`[RunCommandTool] Failed to execute bash command: ${T.message}`),[{type:"text",text:`Command: ${r}
300
+ Error: ${T.message}`}]}}async requestCliConfirmation(e,t,n,s){let r=`delete-cli-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,o=3e4;return u.debug(`[RunCommandTool] Requesting CLI confirmation: ${r}`),new Promise(a=>{let c=setTimeout(()=>{u.debug(`[RunCommandTool] CLI confirmation timed out: ${r}`),e.off("confirmation_response",l),a("timeout")},o),l=d=>{d.confirmationId===r&&(clearTimeout(c),e.off("confirmation_response",l),d.timedOut?a("timeout"):d.confirmed?a("confirmed"):a("declined"))};e.on("confirmation_response",l),e.emit("confirmation_request",{confirmationId:r,type:"confirmation",title:"Confirm Delete",message:"The AI wants to delete files. Continue?",command:t,targets:n,isDestructive:!0,timeout:o}),u.debug(`[RunCommandTool] CLI confirmation request emitted: ${r}`)})}async executeBackground(e,t,n,s){let r=`shell_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,o=s.workingDirectory||process.cwd();u.debug(`[RunCommandTool] Starting background process: ${r}`);let a,c;Lt()?(a="powershell.exe",c=["-ExecutionPolicy","Bypass","-Command",t]):(a="/bin/bash",c=["-c",t]);let l=Gp(a,c,{cwd:o,env:process.env,stdio:["ignore","pipe","pipe"],detached:!Lt()});l.unref();let d={id:r,command:t,startTime:new Date,status:"running",output:[],error:[],pid:l.pid};Be.addProcess(d);let g=5*1024*1024,m=0,p=0;return l.stdout?.on("data",h=>{if(m<g){let f=h.toString();d.output.push(f),m+=f.length,m>=g&&d.output.push("[Output truncated - buffer limit reached]")}}),l.stderr?.on("data",h=>{if(p<g){let f=h.toString();d.error.push(f),p+=f.length,p>=g&&d.error.push("[Error output truncated - buffer limit reached]")}}),l.on("exit",h=>{u.debug(`[RunCommandTool] Background process ${r} exited with code ${h}`),Be.updateProcess(r,{endTime:new Date,exitCode:h??0,status:(h??0)===0?"completed":"failed"})}),l.on("error",h=>{u.debug(`[RunCommandTool] Background process ${r} error: ${h.message}`),d.error.push(h.message),Be.updateProcess(r,{endTime:new Date,status:"failed"})}),n&&setTimeout(()=>{let h=Be.getProcess(r);h&&h.status==="running"&&(u.debug(`[RunCommandTool] Background process ${r} timed out, killing...`),Qn(l.pid,"SIGTERM"),setTimeout(()=>{let f=Be.getProcess(r);f&&f.status==="running"&&Qn(l.pid,"SIGKILL")},3e3),Be.updateProcess(r,{status:"killed",endTime:new Date}),d.error.push(`Process timed out after ${n}ms`))},n),[{type:"text",text:`Background process started with ID: ${r}
301
301
  PID: ${l.pid}
302
302
  Use BashOutput tool to get output.`}]}ensureMeaningfulOutput(e,t,n){let s=(e||"").trim();return s.length===0?n?`✅ Command '${t}' executed successfully.
303
303
 
@@ -316,7 +316,7 @@ If you expected output, the command may need different parameters or the operati
316
316
  Consider:
317
317
  • Checking the command syntax and parameters
318
318
  • Verifying file permissions and paths
319
- • Running the command with verbose flags for more details`:s}detectMkdirCommand(e){let t=e.trim(),n=t.match(/^mkdir\s+(?:-[pvm]+\s+)*["']?([^"'\s]+)["']?/i);if(n)return{isMkdir:!0,path:n[1]};let s=t.match(/^mkdir\s+(?:--\w+\s+)*["']?([^"'\s]+)["']?/i);return s?{isMkdir:!0,path:s[1]}:{isMkdir:!1}}detectTouchCommand(e){let n=e.trim().match(/^touch\s+(?:-[acm]+\s+)*["']?([^"'\s]+)["']?/i);return n?{isTouch:!0,path:n[1]}:{isTouch:!1}}detectFileOverwriteCommand(e){let t=e.trim(),n=t.match(/>\s*["']?([^"'\s>|&]+)["']?$/);if(n&&!t.includes(">>"))return{isOverwrite:!0,targetPath:n[1]};let s=t.match(/^cp\s+(?:-[frp]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(s)return{isOverwrite:!0,targetPath:s[1]};let r=t.match(/^mv\s+(?:-[fn]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(r)return{isOverwrite:!0,targetPath:r[1]};let o=t.match(/wget\s+.*-O\s*["']?([^"'\s]+)["']?/i);if(o)return{isOverwrite:!0,targetPath:o[1]};let a=t.match(/curl\s+.*-o\s*["']?([^"'\s]+)["']?/i);if(a)return{isOverwrite:!0,targetPath:a[1]};let c=t.match(/dd\s+.*of=["']?([^"'\s]+)["']?/i);if(c)return{isOverwrite:!0,targetPath:c[1]};let l=t.match(/scp\s+[^:]+:[^"'\s]+\s+["']?([^"'\s]+)["']?$/i);if(l)return{isOverwrite:!0,targetPath:l[1]};let d=t.match(/rsync\s+.*\s+["']?([^"'\s]+)["']?$/i);if(d&&!d[1].includes(":"))return{isOverwrite:!0,targetPath:d[1]};let g=t.match(/install\s+(?:-[Dmpv]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(g)return{isOverwrite:!0,targetPath:g[1]};let m=t.match(/\|\s*tee\s+(?!-a)["']?([^"'\s]+)["']?/i);return m?{isOverwrite:!0,targetPath:m[1]}:{isOverwrite:!1}}}});var Wr,vl=F(()=>{"use strict";j();Yn();Wr=class{toolNames=["bash_output","BashOutput","TaskOutput"];async execute(e,t,n,s){try{let r=n.bash_id||n.shell_id||n.task_id;if(!r)throw new Error("bash_id is required");if(typeof r!="string")throw new Error(`bash_id must be a string. Received: ${typeof r}`);u.debug(`[BashOutputTool] Retrieving output for process: ${r}`);let o=Ue.getProcess(r);if(!o)throw new Error(`Background process not found: ${r}`);let a=[...o.output,...o.error].join(""),c=o.status==="running",l=`Process ID: ${r}
319
+ • Running the command with verbose flags for more details`:s}detectMkdirCommand(e){let t=e.trim(),n=t.match(/^mkdir\s+(?:-[pvm]+\s+)*["']?([^"'\s]+)["']?/i);if(n)return{isMkdir:!0,path:n[1]};let s=t.match(/^mkdir\s+(?:--\w+\s+)*["']?([^"'\s]+)["']?/i);return s?{isMkdir:!0,path:s[1]}:{isMkdir:!1}}detectTouchCommand(e){let n=e.trim().match(/^touch\s+(?:-[acm]+\s+)*["']?([^"'\s]+)["']?/i);return n?{isTouch:!0,path:n[1]}:{isTouch:!1}}detectFileOverwriteCommand(e){let t=e.trim(),n=t.match(/>\s*["']?([^"'\s>|&]+)["']?$/);if(n&&!t.includes(">>"))return{isOverwrite:!0,targetPath:n[1]};let s=t.match(/^cp\s+(?:-[frp]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(s)return{isOverwrite:!0,targetPath:s[1]};let r=t.match(/^mv\s+(?:-[fn]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(r)return{isOverwrite:!0,targetPath:r[1]};let o=t.match(/wget\s+.*-O\s*["']?([^"'\s]+)["']?/i);if(o)return{isOverwrite:!0,targetPath:o[1]};let a=t.match(/curl\s+.*-o\s*["']?([^"'\s]+)["']?/i);if(a)return{isOverwrite:!0,targetPath:a[1]};let c=t.match(/dd\s+.*of=["']?([^"'\s]+)["']?/i);if(c)return{isOverwrite:!0,targetPath:c[1]};let l=t.match(/scp\s+[^:]+:[^"'\s]+\s+["']?([^"'\s]+)["']?$/i);if(l)return{isOverwrite:!0,targetPath:l[1]};let d=t.match(/rsync\s+.*\s+["']?([^"'\s]+)["']?$/i);if(d&&!d[1].includes(":"))return{isOverwrite:!0,targetPath:d[1]};let g=t.match(/install\s+(?:-[Dmpv]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(g)return{isOverwrite:!0,targetPath:g[1]};let m=t.match(/\|\s*tee\s+(?!-a)["']?([^"'\s]+)["']?/i);return m?{isOverwrite:!0,targetPath:m[1]}:{isOverwrite:!1}}}});var Hr,vl=$(()=>{"use strict";z();Jn();Hr=class{toolNames=["bash_output","BashOutput","TaskOutput"];async execute(e,t,n,s){try{let r=n.bash_id||n.shell_id||n.task_id;if(!r)throw new Error("bash_id is required");if(typeof r!="string")throw new Error(`bash_id must be a string. Received: ${typeof r}`);u.debug(`[BashOutputTool] Retrieving output for process: ${r}`);let o=Be.getProcess(r);if(!o)throw new Error(`Background process not found: ${r}`);let a=[...o.output,...o.error].join(""),c=o.status==="running",l=`Process ID: ${r}
320
320
  `;if(l+=`Status: ${o.status}
321
321
  `,l+=`PID: ${o.pid||"N/A"}
322
322
  `,l+=`Command: ${o.command}
@@ -328,7 +328,7 @@ Consider:
328
328
  --- Output ---
329
329
  `,a?l+=a:c?l+="(no output yet - process still running)":o.exitCode===0?l+=`Process completed successfully with no output.
330
330
 
331
- Note: Many commands run silently when successful (e.g., file operations, installations). The exit code 0 confirms success.`:l+="(no output)",[{type:"text",text:l}]}catch(r){return u.debug(`[BashOutputTool] Error: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});var Hr,Sl=F(()=>{"use strict";j();Yn();Hr=class{toolNames=["kill_shell","KillShell"];async execute(e,t,n,s){try{let r=n.shell_id||n.bash_id||n.task_id;if(!r)throw new Error("shell_id is required");if(typeof r!="string")throw new Error(`shell_id must be a string. Received: ${typeof r}`);u.debug(`[KillShellTool] Killing process: ${r}`);let o=Ue.getProcess(r);if(!o)throw new Error(`Background process not found: ${r}`);if(o.status!=="running")throw new Error(`Process is not running (status: ${o.status})`);if(o.pid){Xn(o.pid,"SIGTERM");let a=o.pid;setTimeout(()=>{let d=Ue.getProcess(r);d&&d.status==="running"&&Xn(a,"SIGKILL")},3e3).unref(),Ue.updateProcess(r,{status:"killed",endTime:new Date});let l=`Process ${r} (PID ${o.pid}) and its children killed successfully`;return u.debug(`[KillShellTool] ${l}`),[{type:"text",text:l}]}else throw new Error("Process has no PID")}catch(r){return u.debug(`[KillShellTool] Error: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});var Fi,jp,Gr,wl=F(()=>{"use strict";j();Yn();Fi=class i{static instance;monitoredProcesses=new Map;POLL_INTERVAL=1e3;constructor(){u.debug("[ProcessMonitoringService] Initialized")}static getInstance(){return i.instance||(i.instance=new i),i.instance}startMonitoring(e,t,n){if(this.monitoredProcesses.has(e))return{success:!1,error:`Already monitoring process: ${e}`};let s=Ue.getProcess(e);if(!s)return{success:!1,error:`Process not found: ${e}`};if(s.status!=="running")return{success:!1,error:`Process already completed with status: ${s.status}`};let r=setInterval(()=>{this.checkProcess(e)},this.POLL_INTERVAL);return this.monitoredProcesses.set(e,{shellId:e,reason:t,startTime:new Date,intervalId:r,onComplete:n}),u.debug(`[ProcessMonitoringService] Started monitoring: ${e}`),{success:!0}}stopMonitoring(e){let t=this.monitoredProcesses.get(e);t&&(clearInterval(t.intervalId),this.monitoredProcesses.delete(e),u.debug(`[ProcessMonitoringService] Stopped monitoring: ${e}`))}checkProcess(e){let t=this.monitoredProcesses.get(e);if(!t)return;let n=Ue.getProcess(e);if(!n){this.stopMonitoring(e);return}n.status!=="running"&&(u.debug(`[ProcessMonitoringService] Process ${e} completed with status: ${n.status}`),t.onComplete&&t.onComplete(n),this.stopMonitoring(e),this.emitAutoPrompt(e,n,t.reason))}async emitAutoPrompt(e,t,n){try{let{FrontendWebSocketService:s}=await Promise.resolve().then(()=>(Jn(),$i)),r=s.getInstance();if(!r.isConnected()){u.debug("[ProcessMonitoringService] WebSocket not connected, cannot auto-prompt");return}let o,a=t.output.join(`
331
+ Note: Many commands run silently when successful (e.g., file operations, installations). The exit code 0 confirms success.`:l+="(no output)",[{type:"text",text:l}]}catch(r){return u.debug(`[BashOutputTool] Error: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});var Gr,Sl=$(()=>{"use strict";z();Jn();Gr=class{toolNames=["kill_shell","KillShell"];async execute(e,t,n,s){try{let r=n.shell_id||n.bash_id||n.task_id;if(!r)throw new Error("shell_id is required");if(typeof r!="string")throw new Error(`shell_id must be a string. Received: ${typeof r}`);u.debug(`[KillShellTool] Killing process: ${r}`);let o=Be.getProcess(r);if(!o)throw new Error(`Background process not found: ${r}`);if(o.status!=="running")throw new Error(`Process is not running (status: ${o.status})`);if(o.pid){Qn(o.pid,"SIGTERM");let a=o.pid;setTimeout(()=>{let d=Be.getProcess(r);d&&d.status==="running"&&Qn(a,"SIGKILL")},3e3).unref(),Be.updateProcess(r,{status:"killed",endTime:new Date});let l=`Process ${r} (PID ${o.pid}) and its children killed successfully`;return u.debug(`[KillShellTool] ${l}`),[{type:"text",text:l}]}else throw new Error("Process has no PID")}catch(r){return u.debug(`[KillShellTool] Error: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});var Fi,jp,jr,wl=$(()=>{"use strict";z();Jn();Fi=class i{static instance;monitoredProcesses=new Map;POLL_INTERVAL=1e3;constructor(){u.debug("[ProcessMonitoringService] Initialized")}static getInstance(){return i.instance||(i.instance=new i),i.instance}startMonitoring(e,t,n){if(this.monitoredProcesses.has(e))return{success:!1,error:`Already monitoring process: ${e}`};let s=Be.getProcess(e);if(!s)return{success:!1,error:`Process not found: ${e}`};if(s.status!=="running")return{success:!1,error:`Process already completed with status: ${s.status}`};let r=setInterval(()=>{this.checkProcess(e)},this.POLL_INTERVAL);return this.monitoredProcesses.set(e,{shellId:e,reason:t,startTime:new Date,intervalId:r,onComplete:n}),u.debug(`[ProcessMonitoringService] Started monitoring: ${e}`),{success:!0}}stopMonitoring(e){let t=this.monitoredProcesses.get(e);t&&(clearInterval(t.intervalId),this.monitoredProcesses.delete(e),u.debug(`[ProcessMonitoringService] Stopped monitoring: ${e}`))}checkProcess(e){let t=this.monitoredProcesses.get(e);if(!t)return;let n=Be.getProcess(e);if(!n){this.stopMonitoring(e);return}n.status!=="running"&&(u.debug(`[ProcessMonitoringService] Process ${e} completed with status: ${n.status}`),t.onComplete&&t.onComplete(n),this.stopMonitoring(e),this.emitAutoPrompt(e,n,t.reason))}async emitAutoPrompt(e,t,n){try{let{FrontendWebSocketService:s}=await Promise.resolve().then(()=>(es(),$i)),r=s.getInstance();if(!r.isConnected()){u.debug("[ProcessMonitoringService] WebSocket not connected, cannot auto-prompt");return}let o,a=t.output.join(`
332
332
  `).substring(0,1e3),c=t.error.join(`
333
333
  `).substring(0,500);t.status==="completed"?o=`Background process completed successfully (ID: ${e}, Exit: ${t.exitCode}).
334
334
 
@@ -350,21 +350,21 @@ Reason for monitoring: ${n}
350
350
 
351
351
  The process was terminated. Please check if this was intentional or if there was a timeout.`:o=`Background process ended with status: ${t.status} (ID: ${e}).
352
352
 
353
- Reason for monitoring: ${n}`,r.emit("auto_prompt",{type:"process_completed",shellId:e,status:t.status,exitCode:t.exitCode,reason:n,message:o,timestamp:new Date().toISOString()}),u.debug(`[ProcessMonitoringService] Emitted auto-prompt for: ${e}`)}catch(s){u.debug(`[ProcessMonitoringService] Failed to emit auto-prompt: ${s}`)}}getMonitoredCount(){return this.monitoredProcesses.size}getMonitoredIds(){return Array.from(this.monitoredProcesses.keys())}clear(){for(let[e,t]of this.monitoredProcesses)clearInterval(t.intervalId);this.monitoredProcesses.clear(),u.debug("[ProcessMonitoringService] Cleared all monitors")}},jp=Fi.getInstance(),Gr=class{toolNames=["monitor_running_cli","MonitorRunningCli"];async execute(e,t,n,s){let r=n.shell_id,o=n.reason;if(!r||typeof r!="string"||r.trim().length===0)return[{type:"text",text:"Error: shell_id is required and must be a non-empty string"}];if(!o||typeof o!="string"||o.trim().length===0)return[{type:"text",text:"Error: reason is required and must be a non-empty string"}];if(o.length>500)return[{type:"text",text:`Error: reason is too long (${o.length} characters). Maximum 500 characters allowed.`}];u.debug(`[MonitorRunningCliTool] Starting monitoring for ${r}`),u.debug(`[MonitorRunningCliTool] Reason: ${o}`);let a=jp.startMonitoring(r,o);return a.success?(u.debug("[MonitorRunningCliTool] Monitoring started successfully"),[{type:"text",text:`Started monitoring background process ${r}.
353
+ Reason for monitoring: ${n}`,r.emit("auto_prompt",{type:"process_completed",shellId:e,status:t.status,exitCode:t.exitCode,reason:n,message:o,timestamp:new Date().toISOString()}),u.debug(`[ProcessMonitoringService] Emitted auto-prompt for: ${e}`)}catch(s){u.debug(`[ProcessMonitoringService] Failed to emit auto-prompt: ${s}`)}}getMonitoredCount(){return this.monitoredProcesses.size}getMonitoredIds(){return Array.from(this.monitoredProcesses.keys())}clear(){for(let[e,t]of this.monitoredProcesses)clearInterval(t.intervalId);this.monitoredProcesses.clear(),u.debug("[ProcessMonitoringService] Cleared all monitors")}},jp=Fi.getInstance(),jr=class{toolNames=["monitor_running_cli","MonitorRunningCli"];async execute(e,t,n,s){let r=n.shell_id,o=n.reason;if(!r||typeof r!="string"||r.trim().length===0)return[{type:"text",text:"Error: shell_id is required and must be a non-empty string"}];if(!o||typeof o!="string"||o.trim().length===0)return[{type:"text",text:"Error: reason is required and must be a non-empty string"}];if(o.length>500)return[{type:"text",text:`Error: reason is too long (${o.length} characters). Maximum 500 characters allowed.`}];u.debug(`[MonitorRunningCliTool] Starting monitoring for ${r}`),u.debug(`[MonitorRunningCliTool] Reason: ${o}`);let a=jp.startMonitoring(r,o);return a.success?(u.debug("[MonitorRunningCliTool] Monitoring started successfully"),[{type:"text",text:`Started monitoring background process ${r}.
354
354
 
355
355
  Reason: ${o}
356
356
 
357
357
  You will be auto-prompted when the process completes. You can continue with other tasks in the meantime.
358
358
 
359
- To check status manually, use BashOutput tool with shell_id: ${r}`}]):(u.debug(`[MonitorRunningCliTool] Failed to start monitoring: ${a.error}`),[{type:"text",text:`Failed to start monitoring: ${a.error}`}])}}});var jr,Tl=F(()=>{"use strict";j();jr=class{toolNames=["grep","Grep"];async execute(e,t,n,s){let r=n.pattern,o=n.output_mode||"files_with_matches",a=n.path||process.cwd(),c=n.glob,l=n.type,d=n["-i"]===!0,g=n["-n"]===!0,m=n["-A"],p=n["-B"],h=n["-C"],f=n.multiline===!0,y=n.head_limit;if(!r)throw new Error("Missing pattern argument");if(r.trim().length===0)throw new Error("Pattern cannot be empty");u.debug(`[GrepTool] Grep search: pattern="${r}", path="${a}", output_mode="${o}"`);try{let{exec:T}=await import("child_process"),{promisify:x}=await import("util"),w=x(T),C="rg",v=!0;try{await w("which rg",{timeout:5e3})}catch{u.debug("[GrepTool] ripgrep not found, falling back to grep"),C="grep -r",v=!1}if(v){switch(d&&(C+=" -i"),g&&(C+=" -n"),o){case"files_with_matches":C+=" -l";break;case"count":C+=" -c";break;case"content":default:break}h!==void 0?C+=` -C ${h}`:(m!==void 0&&(C+=` -A ${m}`),p!==void 0&&(C+=` -B ${p}`)),f&&(C+=" -U --multiline-dotall"),C+=` "${r.replace(/"/g,'\\"')}"`,c&&(C+=` --glob="${c}"`),l&&(C+=` --type=${l}`),C+=` "${a}"`}else{switch(d&&(C+=" -i"),g&&(C+=" -n"),o){case"files_with_matches":C+=" -l";break;case"count":C+=" -c";break}h!==void 0?C+=` -C ${h}`:(m!==void 0&&(C+=` -A ${m}`),p!==void 0&&(C+=` -B ${p}`)),C+=` "${r.replace(/"/g,'\\"')}"`,c&&(C+=` --include="${c}"`),C+=` "${a}"`}y!==void 0&&y>0&&(C+=` | head -n ${y}`),u.debug(`[GrepTool] Executing: ${C}`);let{stdout:E,stderr:S}=await w(C,{maxBuffer:10*1024*1024,timeout:3e4});if(!E&&!S)return[{type:"text",text:"No matches found"}];let I=E||S;if(o==="content"&&I){let R=`
359
+ To check status manually, use BashOutput tool with shell_id: ${r}`}]):(u.debug(`[MonitorRunningCliTool] Failed to start monitoring: ${a.error}`),[{type:"text",text:`Failed to start monitoring: ${a.error}`}])}}});var zr,Tl=$(()=>{"use strict";z();zr=class{toolNames=["grep","Grep"];async execute(e,t,n,s){let r=n.pattern,o=n.output_mode||"files_with_matches",a=n.path||process.cwd(),c=n.glob,l=n.type,d=n["-i"]===!0,g=n["-n"]===!0,m=n["-A"],p=n["-B"],h=n["-C"],f=n.multiline===!0,y=n.head_limit;if(!r)throw new Error("Missing pattern argument");if(r.trim().length===0)throw new Error("Pattern cannot be empty");u.debug(`[GrepTool] Grep search: pattern="${r}", path="${a}", output_mode="${o}"`);try{let{exec:T}=await import("child_process"),{promisify:C}=await import("util"),w=C(T),E="rg",v=!0;try{await w("which rg",{timeout:5e3})}catch{u.debug("[GrepTool] ripgrep not found, falling back to grep"),E="grep -r",v=!1}if(v){switch(d&&(E+=" -i"),g&&(E+=" -n"),o){case"files_with_matches":E+=" -l";break;case"count":E+=" -c";break;case"content":default:break}h!==void 0?E+=` -C ${h}`:(m!==void 0&&(E+=` -A ${m}`),p!==void 0&&(E+=` -B ${p}`)),f&&(E+=" -U --multiline-dotall"),E+=` "${r.replace(/"/g,'\\"')}"`,c&&(E+=` --glob="${c}"`),l&&(E+=` --type=${l}`),E+=` "${a}"`}else{switch(d&&(E+=" -i"),g&&(E+=" -n"),o){case"files_with_matches":E+=" -l";break;case"count":E+=" -c";break}h!==void 0?E+=` -C ${h}`:(m!==void 0&&(E+=` -A ${m}`),p!==void 0&&(E+=` -B ${p}`)),E+=` "${r.replace(/"/g,'\\"')}"`,c&&(E+=` --include="${c}"`),E+=` "${a}"`}y!==void 0&&y>0&&(E+=` | head -n ${y}`),u.debug(`[GrepTool] Executing: ${E}`);let{stdout:x,stderr:S}=await w(E,{maxBuffer:10*1024*1024,timeout:3e4});if(!x&&!S)return[{type:"text",text:"No matches found"}];let I=x||S;if(o==="content"&&I){let M=`
360
360
 
361
361
  [Found ${I.trim().split(`
362
- `).length} matching line(s)]`;return[{type:"text",text:I+R}]}return[{type:"text",text:I}]}catch(T){return T.code===1?[{type:"text",text:"No matches found"}]:(u.debug(`[GrepTool] Grep failed: ${T.message}`),T.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 zr,xl=F(()=>{"use strict";j();zr=class{toolNames=["glob","Glob"];async execute(e,t,n,s){let r=n.pattern,o=n.path||process.cwd();if(!r)throw new Error("Missing pattern argument");u.debug(`[GlobTool] Glob search: pattern="${r}", path="${o}"`);try{let{exec:a}=await import("child_process"),{promisify:c}=await import("util"),l=c(a),d=r.replace(/\*\*/g,"*"),g=process.platform==="win32"?`dir /s /b "${o}\\${d}"`:`find "${o}" -name "${d}" 2>/dev/null`,{stdout:m}=await l(g,{timeout:3e4,maxBuffer:10*1024*1024});if(!m||m.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let p=m.trim().split(`
362
+ `).length} matching line(s)]`;return[{type:"text",text:I+M}]}return[{type:"text",text:I}]}catch(T){return T.code===1?[{type:"text",text:"No matches found"}]:(u.debug(`[GrepTool] Grep failed: ${T.message}`),T.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 qr,xl=$(()=>{"use strict";z();qr=class{toolNames=["glob","Glob"];async execute(e,t,n,s){let r=n.pattern,o=n.path||process.cwd();if(!r)throw new Error("Missing pattern argument");u.debug(`[GlobTool] Glob search: pattern="${r}", path="${o}"`);try{let{exec:a}=await import("child_process"),{promisify:c}=await import("util"),l=c(a),d=r.replace(/\*\*/g,"*"),g=process.platform==="win32"?`dir /s /b "${o}\\${d}"`:`find "${o}" -name "${d}" 2>/dev/null`,{stdout:m}=await l(g,{timeout:3e4,maxBuffer:10*1024*1024});if(!m||m.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let p=m.trim().split(`
363
363
  `);return[{type:"text",text:`Found ${p.length} file(s):
364
364
  ${p.join(`
365
- `)}`}]}catch(a){return u.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var qr,Cl=F(()=>{"use strict";j();qr=class{toolNames=["open_url"];async execute(e,t,n,s){let r=n.url;if(!r)throw new Error("Missing url argument");u.debug(`[OpenUrlTool] Opening URL: ${r}`),s.activeWebViewURLs.includes(r)||(s.activeWebViewURLs.push(r),u.debug(`[OpenUrlTool] Added to active URLs: ${r}`));try{let{exec:o}=await import("child_process"),a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return o(`${a} "${r}"`,c=>{c?u.debug(`[OpenUrlTool] Failed to open URL in browser: ${c.message}`):u.debug(`[OpenUrlTool] URL opened in default browser: ${r}`)}),[{type:"text",text:`✅ URL opened in default browser: ${r}`}]}catch(o){return u.debug(`[OpenUrlTool] Failed to open URL: ${o.message}`),[{type:"text",text:`❌ Failed to open URL: ${o.message}`}]}}}});import{exec as zp,execSync as UE}from"child_process";import{promisify as qp}from"util";function Kr(){return process.platform==="win32"}function El(){return process.platform==="darwin"}function Il(){return process.platform==="linux"}var WE,kl=F(()=>{"use strict";WE=qp(zp)});var Pl={};Fe(Pl,{DeviceKnowledgeService:()=>Vr,deviceKnowledgeService:()=>Se});import*as Ge from"fs";import*as Jt from"path";import*as ve from"os";var Vr,Se,Xr=F(()=>{"use strict";kl();Vr=class i{static instance;fileName="device-knowledge.md";constructor(){this.ensureDirectoryExists()}static shared(){return i.instance||(i.instance=new i),i.instance}get orionDirectory(){return Jt.join(ve.homedir(),".orion")}getKnowledgeFilePath(){return Jt.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!Ge.existsSync(this.orionDirectory))try{Ge.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),Kr()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{exec(`attrib +h "${this.orionDirectory}"`,e=>{e?console.warn("Failed to hide .orion directory on Windows:",e.message):console.log("Set hidden attribute on .orion directory (Windows)")})}catch(e){console.warn("Error hiding directory on Windows:",e)}}hasDeviceKnowledge(){return Ge.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return Ge.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),Ge.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let n=(this.readDeviceKnowledge()||"")+`
365
+ `)}`}]}catch(a){return u.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var Kr,Cl=$(()=>{"use strict";z();Kr=class{toolNames=["open_url"];async execute(e,t,n,s){let r=n.url;if(!r)throw new Error("Missing url argument");u.debug(`[OpenUrlTool] Opening URL: ${r}`),s.activeWebViewURLs.includes(r)||(s.activeWebViewURLs.push(r),u.debug(`[OpenUrlTool] Added to active URLs: ${r}`));try{let{exec:o}=await import("child_process"),a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return o(`${a} "${r}"`,c=>{c?u.debug(`[OpenUrlTool] Failed to open URL in browser: ${c.message}`):u.debug(`[OpenUrlTool] URL opened in default browser: ${r}`)}),[{type:"text",text:`✅ URL opened in default browser: ${r}`}]}catch(o){return u.debug(`[OpenUrlTool] Failed to open URL: ${o.message}`),[{type:"text",text:`❌ Failed to open URL: ${o.message}`}]}}}});import{exec as zp,execSync as UE}from"child_process";import{promisify as qp}from"util";function Vr(){return process.platform==="win32"}function El(){return process.platform==="darwin"}function Il(){return process.platform==="linux"}var WE,kl=$(()=>{"use strict";WE=qp(zp)});var Pl={};Le(Pl,{DeviceKnowledgeService:()=>Xr,deviceKnowledgeService:()=>Se});import*as je from"fs";import*as Zt from"path";import*as ve from"os";var Xr,Se,Yr=$(()=>{"use strict";kl();Xr=class i{static instance;fileName="device-knowledge.md";constructor(){this.ensureDirectoryExists()}static shared(){return i.instance||(i.instance=new i),i.instance}get orionDirectory(){return Zt.join(ve.homedir(),".orion")}getKnowledgeFilePath(){return Zt.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!je.existsSync(this.orionDirectory))try{je.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),Vr()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{exec(`attrib +h "${this.orionDirectory}"`,e=>{e?console.warn("Failed to hide .orion directory on Windows:",e.message):console.log("Set hidden attribute on .orion directory (Windows)")})}catch(e){console.warn("Error hiding directory on Windows:",e)}}hasDeviceKnowledge(){return je.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return je.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),je.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let n=(this.readDeviceKnowledge()||"")+`
366
366
 
367
- `+e;return this.writeDeviceKnowledge(n)}getKnowledgeFileSize(){try{return Ge.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
367
+ `+e;return this.writeDeviceKnowledge(n)}getKnowledgeFileSize(){try{return je.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
368
368
 
369
369
  `;e+=`**File Location**: \`${this.getKnowledgeFilePath()}\`
370
370
 
@@ -377,18 +377,18 @@ ${p.join(`
377
377
  `}catch{e+=`- **Username**: ${process.env.USER||process.env.USERNAME||"Unknown"}
378
378
  `}e+=`- **Home Directory**: ${ve.homedir()}
379
379
 
380
- `;let t=process.env.SHELL||process.env.COMSPEC||(Kr()?"cmd.exe":"Unknown");return e+=`## Shell Environment
380
+ `;let t=process.env.SHELL||process.env.COMSPEC||(Vr()?"cmd.exe":"Unknown");return e+=`## Shell Environment
381
381
  `,e+=`- **Default Shell**: ${t}
382
382
 
383
383
  `,e+=`## Important Directories
384
384
  `,e+=`- **Home**: ${ve.homedir()}
385
- `,e+=`- **Desktop**: ${Jt.join(ve.homedir(),"Desktop")}
386
- `,e+=`- **Documents**: ${Jt.join(ve.homedir(),"Documents")}
387
- `,e+=`- **Downloads**: ${Jt.join(ve.homedir(),"Downloads")}
385
+ `,e+=`- **Desktop**: ${Zt.join(ve.homedir(),"Desktop")}
386
+ `,e+=`- **Documents**: ${Zt.join(ve.homedir(),"Documents")}
387
+ `,e+=`- **Downloads**: ${Zt.join(ve.homedir(),"Downloads")}
388
388
  `,El()?e+=`- **Applications**: /Applications
389
- `:Kr()?(e+=`- **Program Files**: C:\\Program Files
390
- `,e+=`- **AppData**: ${Jt.join(ve.homedir(),"AppData")}
391
- `):Il()&&(e+=`- **Config**: ${Jt.join(ve.homedir(),".config")}
389
+ `:Vr()?(e+=`- **Program Files**: C:\\Program Files
390
+ `,e+=`- **AppData**: ${Zt.join(ve.homedir(),"AppData")}
391
+ `):Il()&&(e+=`- **Config**: ${Zt.join(ve.homedir(),".config")}
392
392
  `),e+=`
393
393
  `,e+=`## URL Handling Rules
394
394
  `,e+="- **staging.snowx.ai Redirect URLs**: Any URL in format `staging.snowx.ai/*` is a shortened URL that redirects to the main URL. Resolve the redirect to get the actual destination URL.\n\n",this.writeDeviceKnowledge(e)}updateKnowledgeSection(e,t){let s=(this.readDeviceKnowledge()||"").split(`
@@ -396,15 +396,15 @@ ${p.join(`
396
396
  `);return this.writeDeviceKnowledge(c)}addNote(e,t,n="Notes"){let s=new Date().toLocaleString(),r=`### ${e} (${s})
397
397
  ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
398
398
  `),c=[],l=!1,d=!1;for(let m of a)m.startsWith(`## ${n}`)?(l=!0,c.push(m)):m.startsWith("## ")&&l&&!d?(c.push(""),c.push(r),c.push(""),c.push(m),l=!1,d=!0):c.push(m);l&&!d&&(c.push(""),c.push(r));let g=c.join(`
399
- `);return this.writeDeviceKnowledge(g)}else return this.updateKnowledgeSection(n,r)}deleteDeviceKnowledge(){try{return Ge.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return Ge.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=Ge.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}},Se=Vr.shared()});var Yr,Al=F(()=>{"use strict";j();Tt();Xr();Yr=class{toolNames=["manage_device_knowledge"];async execute(e,t,n,s){let r=n.action,o=Date.now();u.debug(`[ManageDeviceKnowledgeTool] Executing action: ${r}`),Y.start("ManageDeviceKnowledge",r);try{let a,c=!0;switch(r){case"read":{let d=Se.readDeviceKnowledge();d?a=d:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await Se.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${Se.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",c=!1);break}case"write":{let d=n.content;d?Se.writeDeviceKnowledge(d)?a="Device knowledge updated successfully.":(a="Failed to write device knowledge.",c=!1):(a='Error: Missing "content" argument for write action.',c=!1);break}case"append":{let d=n.content;d?Se.appendDeviceKnowledge(d)?a="Content appended to device knowledge successfully.":(a="Failed to append to device knowledge.",c=!1):(a='Error: Missing "content" argument for append action.',c=!1);break}case"update_section":{let d=n.section,g=n.content;!d||!g?(a='Error: Missing "section" or "content" argument for update_section action.',c=!1):Se.updateKnowledgeSection(d,g)?a=`Section "${d}" updated successfully.`:(a=`Failed to update section "${d}".`,c=!1);break}case"add_note":{let d=n.title,g=n.content,m=n.category||"Notes";!d||!g?(a='Error: Missing "title" or "content" argument for add_note action.',c=!1):Se.addNote(d,g,m)?a=`Note "${d}" added to ${m} successfully.`:(a=`Failed to add note "${d}".`,c=!1);break}case"delete":{Se.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",c=!1);break}case"path":{a=Se.getKnowledgeFilePath();break}case"exists":{a=Se.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${Se.getKnowledgeFileSize()} bytes`;break}case"export":{let d=n.destination;d?Se.exportDeviceKnowledge(d)?a=`Device knowledge exported to: ${d}`:(a=`Failed to export device knowledge to: ${d}`,c=!1):(a='Error: Missing "destination" argument for export action.',c=!1);break}case"import":{let d=n.source;d?Se.importDeviceKnowledge(d)?a=`Device knowledge imported from: ${d}`:(a=`Failed to import device knowledge from: ${d}`,c=!1):(a='Error: Missing "source" argument for import action.',c=!1);break}default:a=`Unknown action: ${r}. Valid actions: read, initialize, write, append, update_section, add_note, delete, path, exists, size, export, import`,c=!1}let l=Date.now()-o;return Y.result({toolName:"ManageDeviceKnowledge",output:a.substring(0,200)+(a.length>200?"...":""),success:c,executionTime:l}),[{type:"text",text:a}]}catch(a){u.debug(`[ManageDeviceKnowledgeTool] Error: ${a.message}`);let c=`Error managing device knowledge: ${a.message}`,l=Date.now()-o;return Y.result({toolName:"ManageDeviceKnowledge",output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});var Qr,Dl=F(()=>{"use strict";j();Qr=class{toolNames=["operator_status"];async execute(e,t,n,s){let r=n.taskId,o=n.status,a=n.message;return u.debug(`[OperatorStatusTool] Operator status - Task ${r}: ${o} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var Jr,Ml=F(()=>{"use strict";j();Jr=class{toolNames=["provide_input"];async execute(e,t,n,s){let r=n.input;if(!r)throw new Error("Missing input argument");u.debug(`[ProvideInputTool] Delegating provide_input to backend: ${r.substring(0,20)}...`);try{let o=(await Promise.resolve().then(()=>(Ur(),_i))).ToolCallingService.getInstance(),a={id:`provide_input_${Date.now()}`,type:"function",function:{name:"provide_input",arguments:JSON.stringify({input:r})}},c=await o.executeTool(a);return c.success?[{type:"text",text:c.result?.message||"Input provided successfully"}]:[{type:"text",text:`Error: ${c.error||"Failed to provide input"}`}]}catch(o){return u.debug(`[ProvideInputTool] Failed to delegate provide_input: ${o.message}`),[{type:"text",text:`Error: ${o.message}`}]}}}});import{exec as Kp}from"child_process";import{promisify as Vp}from"util";import*as Zr from"fs/promises";import*as Rl from"path";import*as Ol from"os";var Xp,Zn,Li=F(()=>{"use strict";j();Xp=Vp(Kp),Zn=class i{static instance;constructor(){}static getInstance(){return i.instance||(i.instance=new i),i.instance}async captureScreen(){try{let e=Rl.join(Ol.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;
399
+ `);return this.writeDeviceKnowledge(g)}else return this.updateKnowledgeSection(n,r)}deleteDeviceKnowledge(){try{return je.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return je.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=je.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}},Se=Xr.shared()});var Qr,Al=$(()=>{"use strict";z();Tt();Yr();Qr=class{toolNames=["manage_device_knowledge"];async execute(e,t,n,s){let r=n.action,o=Date.now();u.debug(`[ManageDeviceKnowledgeTool] Executing action: ${r}`),Q.start("ManageDeviceKnowledge",r);try{let a,c=!0;switch(r){case"read":{let d=Se.readDeviceKnowledge();d?a=d:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await Se.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${Se.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",c=!1);break}case"write":{let d=n.content;d?Se.writeDeviceKnowledge(d)?a="Device knowledge updated successfully.":(a="Failed to write device knowledge.",c=!1):(a='Error: Missing "content" argument for write action.',c=!1);break}case"append":{let d=n.content;d?Se.appendDeviceKnowledge(d)?a="Content appended to device knowledge successfully.":(a="Failed to append to device knowledge.",c=!1):(a='Error: Missing "content" argument for append action.',c=!1);break}case"update_section":{let d=n.section,g=n.content;!d||!g?(a='Error: Missing "section" or "content" argument for update_section action.',c=!1):Se.updateKnowledgeSection(d,g)?a=`Section "${d}" updated successfully.`:(a=`Failed to update section "${d}".`,c=!1);break}case"add_note":{let d=n.title,g=n.content,m=n.category||"Notes";!d||!g?(a='Error: Missing "title" or "content" argument for add_note action.',c=!1):Se.addNote(d,g,m)?a=`Note "${d}" added to ${m} successfully.`:(a=`Failed to add note "${d}".`,c=!1);break}case"delete":{Se.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",c=!1);break}case"path":{a=Se.getKnowledgeFilePath();break}case"exists":{a=Se.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${Se.getKnowledgeFileSize()} bytes`;break}case"export":{let d=n.destination;d?Se.exportDeviceKnowledge(d)?a=`Device knowledge exported to: ${d}`:(a=`Failed to export device knowledge to: ${d}`,c=!1):(a='Error: Missing "destination" argument for export action.',c=!1);break}case"import":{let d=n.source;d?Se.importDeviceKnowledge(d)?a=`Device knowledge imported from: ${d}`:(a=`Failed to import device knowledge from: ${d}`,c=!1):(a='Error: Missing "source" argument for import action.',c=!1);break}default:a=`Unknown action: ${r}. Valid actions: read, initialize, write, append, update_section, add_note, delete, path, exists, size, export, import`,c=!1}let l=Date.now()-o;return Q.result({toolName:"ManageDeviceKnowledge",output:a.substring(0,200)+(a.length>200?"...":""),success:c,executionTime:l}),[{type:"text",text:a}]}catch(a){u.debug(`[ManageDeviceKnowledgeTool] Error: ${a.message}`);let c=`Error managing device knowledge: ${a.message}`,l=Date.now()-o;return Q.result({toolName:"ManageDeviceKnowledge",output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});var Jr,Dl=$(()=>{"use strict";z();Jr=class{toolNames=["operator_status"];async execute(e,t,n,s){let r=n.taskId,o=n.status,a=n.message;return u.debug(`[OperatorStatusTool] Operator status - Task ${r}: ${o} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var Zr,Ml=$(()=>{"use strict";z();Zr=class{toolNames=["provide_input"];async execute(e,t,n,s){let r=n.input;if(!r)throw new Error("Missing input argument");u.debug(`[ProvideInputTool] Delegating provide_input to backend: ${r.substring(0,20)}...`);try{let o=(await Promise.resolve().then(()=>(Br(),_i))).ToolCallingService.getInstance(),a={id:`provide_input_${Date.now()}`,type:"function",function:{name:"provide_input",arguments:JSON.stringify({input:r})}},c=await o.executeTool(a);return c.success?[{type:"text",text:c.result?.message||"Input provided successfully"}]:[{type:"text",text:`Error: ${c.error||"Failed to provide input"}`}]}catch(o){return u.debug(`[ProvideInputTool] Failed to delegate provide_input: ${o.message}`),[{type:"text",text:`Error: ${o.message}`}]}}}});import{exec as Kp}from"child_process";import{promisify as Vp}from"util";import*as eo from"fs/promises";import*as Rl from"path";import*as Ol from"os";var Xp,ts,Li=$(()=>{"use strict";z();Xp=Vp(Kp),ts=class i{static instance;constructor(){}static getInstance(){return i.instance||(i.instance=new i),i.instance}async captureScreen(){try{let e=Rl.join(Ol.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;
400
400
  [System.Windows.Forms.SendKeys]::SendWait('{PRTSC}');
401
401
  Start-Sleep -Milliseconds 100;
402
402
  $img = [System.Windows.Forms.Clipboard]::GetImage();
403
- $img.Save('${e.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Jpeg);`.replace(/\n/g," ")}"`;else return u.debug("[SCREENSHOT] Unsupported platform:",process.platform),null;await Xp(t);let n=await Zr.readFile(e),s=n.toString("base64");return await Zr.unlink(e).catch(()=>{}),u.debug(`[SCREENSHOT] Captured screenshot: ${n.length} bytes`),`data:image/jpeg;base64,${s}`}catch(e){return u.debug("[SCREENSHOT] Failed to capture screen:",e.message),process.platform==="linux"&&e.message.includes("scrot")?(console.log(`
403
+ $img.Save('${e.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Jpeg);`.replace(/\n/g," ")}"`;else return u.debug("[SCREENSHOT] Unsupported platform:",process.platform),null;await Xp(t);let n=await eo.readFile(e),s=n.toString("base64");return await eo.unlink(e).catch(()=>{}),u.debug(`[SCREENSHOT] Captured screenshot: ${n.length} bytes`),`data:image/jpeg;base64,${s}`}catch(e){return u.debug("[SCREENSHOT] Failed to capture screen:",e.message),process.platform==="linux"&&e.message.includes("scrot")?(console.log(`
404
404
  ⚠️ 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
405
405
  `)):process.platform==="darwin"&&(console.log(`
406
406
  ⚠️ Screenshot capture failed. This might be due to security settings.`),console.log(`Terminal applications usually don't need special permissions for screencapture.
407
- `)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}}});var eo,Nl=F(()=>{"use strict";j();Li();eo=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,n,s){u.debug("[TakeScreenshotTool] Capturing screenshot...");try{let o=await Zn.getInstance().captureScreen();if(!o)throw new Error("Failed to capture screenshot - no image data returned");return u.debug("[TakeScreenshotTool] Screenshot captured successfully"),[{type:"image_url",image_url:{url:o}}]}catch(r){return u.error(`[TakeScreenshotTool] Failed to capture screenshot: ${r.message}`),[{type:"text",text:`Failed to capture screenshot: ${r.message}`}]}}}});var Ui,Yp,b,dt=F(()=>{"use strict";Ui=process.env.BROWSER_USE_DEBUG==="1"||"false"?.includes("browser-use"),Yp={log:Ui?console.log.bind(console):()=>{},debug:Ui?console.debug.bind(console):()=>{},info:Ui?console.info.bind(console):()=>{}},b=Yp});import{EventEmitter as Qp}from"eventemitter3";function Ee(i,e){let t=process.env[i];if(t){let n=parseFloat(t);if(!isNaN(n)&&n>=0)return n;console.warn(`Warning: ${i}=${t} is not a valid number, using default ${e}`)}return e}var to,ee,Bi=F(()=>{"use strict";to=class extends Qp{pendingEvents=new Map;async dispatch(e,t,n){let s=`${e}_${Date.now()}_${Math.random()}`;return new Promise((r,o)=>{let a;n&&n>0&&(a=setTimeout(()=>{this.pendingEvents.delete(s),o(new Error(`Event ${e} timed out after ${n}s`))},n*1e3)),this.pendingEvents.set(s,{resolve:r,reject:o,timeout:a}),this.emit(e,{...t,_eventId:s})})}respondToEvent(e,t){let n=this.pendingEvents.get(e);n&&(n.timeout&&clearTimeout(n.timeout),n.resolve(t),this.pendingEvents.delete(e))}rejectEvent(e,t){let n=this.pendingEvents.get(e);n&&(n.timeout&&clearTimeout(n.timeout),n.reject(t),this.pendingEvents.delete(e))}};ee={NAVIGATE_TO_URL:Ee("TIMEOUT_NavigateToUrlEvent",15),CLICK_ELEMENT:Ee("TIMEOUT_ClickElementEvent",15),TYPE_TEXT:Ee("TIMEOUT_TypeTextEvent",60),SCROLL:Ee("TIMEOUT_ScrollEvent",8),SWITCH_TAB:Ee("TIMEOUT_SwitchTabEvent",10),CLOSE_TAB:Ee("TIMEOUT_CloseTabEvent",10),SCREENSHOT:Ee("TIMEOUT_ScreenshotEvent",15),BROWSER_STATE_REQUEST:Ee("TIMEOUT_BrowserStateRequestEvent",30),GO_BACK:Ee("TIMEOUT_GoBackEvent",15),GO_FORWARD:Ee("TIMEOUT_GoForwardEvent",15),REFRESH:Ee("TIMEOUT_RefreshEvent",15),WAIT:Ee("TIMEOUT_WaitEvent",60),SEND_KEYS:Ee("TIMEOUT_SendKeysEvent",60),UPLOAD_FILE:Ee("TIMEOUT_UploadFileEvent",30),GET_DROPDOWN_OPTIONS:Ee("TIMEOUT_GetDropdownOptionsEvent",15),SELECT_DROPDOWN_OPTION:Ee("TIMEOUT_SelectDropdownOptionEvent",8),SCROLL_TO_TEXT:Ee("TIMEOUT_ScrollToTextEvent",15),BROWSER_START:Ee("TIMEOUT_BrowserStartEvent",30),BROWSER_STOP:Ee("TIMEOUT_BrowserStopEvent",45)}});var z,Wi=F(()=>{"use strict";z={NAVIGATE_TO_URL:"navigate_to_url",CLICK_ELEMENT:"click_element",TYPE_TEXT:"type_text",SCROLL:"scroll",SWITCH_TAB:"switch_tab",CLOSE_TAB:"close_tab",SCREENSHOT:"screenshot",BROWSER_STATE_REQUEST:"browser_state_request",GO_BACK:"go_back",GO_FORWARD:"go_forward",REFRESH:"refresh",WAIT:"wait",SEND_KEYS:"send_keys",UPLOAD_FILE:"upload_file",GET_DROPDOWN_OPTIONS:"get_dropdown_options",SELECT_DROPDOWN_OPTION:"select_dropdown_option",SCROLL_TO_TEXT:"scroll_to_text",BROWSER_START:"browser_start",BROWSER_STOP:"browser_stop",TAB_CREATED:"tab_created",TAB_CLOSED:"tab_closed",NAVIGATION_STARTED:"navigation_started",NAVIGATION_COMPLETE:"navigation_complete",BROWSER_ERROR:"browser_error",FILE_DOWNLOADED:"file_downloaded"}});var _l,uI,Bs,$l=F(()=>{"use strict";dt();_l=["title","type","checked","id","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","aria-valuemin","aria-valuemax","aria-valuenow","aria-placeholder","pattern","min","max","minlength","maxlength","step","pseudo","selected","expanded","pressed","disabled","invalid","valuemin","valuemax","valuenow","keyshortcuts","haspopup","multiselectable","required","valuetext","level","busy","live","ax_name"],uI=["a[href]","button",'input:not([type="hidden"])',"select","textarea",'[role="button"]','[role="link"]','[role="checkbox"]','[role="radio"]','[role="tab"]','[role="menuitem"]','[role="option"]','[role="switch"]','[role="slider"]','[role="spinbutton"]','[role="combobox"]','[role="listbox"]','[role="textbox"]','[role="searchbox"]',"[onclick]","[onmousedown]","[onmouseup]",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])',"summary","details","label[for]"].join(", "),Bs=class i{constructor(e,t={}){this.page=e;this.crossOriginIframes=t.crossOriginIframes??!1,this.paintOrderFiltering=t.paintOrderFiltering??!0,this.maxIframes=t.maxIframes??100,this.maxIframeDepth=t.maxIframeDepth??5}cdpSession=null;previousElements=new Set;crossOriginIframes;paintOrderFiltering;maxIframes;maxIframeDepth;async getCDPSession(){if(!this.cdpSession){let e=this.page.context();this.cdpSession=await e.newCDPSession(this.page)}return this.cdpSession}async getViewportInfo(){try{let t=await(await this.getCDPSession()).send("Page.getLayoutMetrics"),n=t.visualViewport||{},s=t.cssVisualViewport||{},r=t.cssLayoutViewport||t.layoutViewport||{},o=s.clientWidth||r.clientWidth||1920,a=s.clientHeight||r.clientHeight||1080,c=n.clientWidth||o,l=s.clientWidth||o,d=l>0?c/l:1;return{width:o,height:a,scrollX:s.pageX||0,scrollY:s.pageY||0,devicePixelRatio:d}}catch{let t=this.page.viewportSize();return{width:t?.width||1920,height:t?.height||1080,scrollX:0,scrollY:0,devicePixelRatio:1}}}collectAllFrameIds(e){let t=[e.frame.id];if(e.childFrames&&e.childFrames.length>0)for(let n of e.childFrames)t.push(...this.collectAllFrameIds(n));return t}async getAccessibilityTree(){let e=new Map;try{let t=await this.getCDPSession();await t.send("Page.enable");let n=[];try{let a=(await t.send("Page.getFrameTree")).frameTree;a&&(n=this.collectAllFrameIds(a),b.debug(`Found ${n.length} frames for AX tree extraction`))}catch(o){b.debug("Failed to get frame tree, falling back to main frame only:",o)}let s=[];if(n.length>0)for(let o of n)s.push(t.send("Accessibility.getFullAXTree",{frameId:o}).catch(a=>(b.debug(`Failed to get AX tree for frame ${o}:`,a),{nodes:[]})));else s.push(t.send("Accessibility.getFullAXTree"));let r=await Promise.all(s);for(let o of r){let a=o.nodes||[];for(let c of a)c.backendDOMNodeId&&e.set(c.backendDOMNodeId,{nodeId:c.nodeId,ignored:c.ignored||!1,role:c.role?.value,name:c.name?.value,description:c.description?.value,value:c.value?.value,childIds:c.childIds,backendDOMNodeId:c.backendDOMNodeId,properties:c.properties})}}catch(t){b.debug("Failed to get accessibility tree:",t)}return e}async getDOMSnapshot(){try{return await(await this.getCDPSession()).send("DOMSnapshot.captureSnapshot",{computedStyles:["display","visibility","opacity","position","overflow","z-index","pointer-events"],includePaintOrder:this.paintOrderFiltering,includeDOMRects:!0})}catch(e){return b.debug("Failed to get DOM snapshot:",e),null}}isElementVisible(e){let t=(e.display||"").toLowerCase(),n=(e.visibility||"").toLowerCase(),s=e.opacity||"1",r=(e["pointer-events"]||"").toLowerCase();if(t==="none"||n==="hidden"||r==="none")return!1;try{if(parseFloat(s)<=0)return!1}catch{}return!0}buildSnapshotLookup(e,t){let n=new Map;if(!e?.documents||e.documents.length===0)return n;let s=e.strings||[],r=["display","visibility","opacity","overflow","overflow-x","overflow-y","cursor","pointer-events","position","background-color"];for(let o of e.documents){let a=o.nodes||{},c=o.layout||{},l=new Map,d=a.backendNodeId||[];for(let p=0;p<d.length;p++)l.set(d[p],p);let g=new Map,m=c.nodeIndex||[];for(let p=0;p<m.length;p++){let h=m[p];g.has(h)||g.set(h,p)}for(let[p,h]of l){let f={};if(a.isClickable){let T=a.isClickable?.index||[];f.isClickable=T.includes(h)}let y=g.get(h);if(y!==void 0){let T=c.bounds||[];if(y<T.length){let E=T[y];E&&E.length>=4&&(f.bounds={x:E[0]/t,y:E[1]/t,width:E[2]/t,height:E[3]/t})}let x=c.styles||[];if(y<x.length){let E=x[y]||[],S={};for(let I=0;I<E.length&&I<r.length;I++){let P=E[I];P>=0&&P<s.length&&(S[r[I]]=s[P])}Object.keys(S).length>0&&(f.computedStyles=S,f.cursorStyle=S.cursor)}let w=c.paintOrders||[];y<w.length&&(f.paintOrder=w[y]);let C=c.clientRects||[];if(y<C.length){let E=C[y];E&&E.length>=4&&(f.clientRects={x:E[0],y:E[1],width:E[2],height:E[3]})}let v=c.scrollRects||[];if(y<v.length){let E=v[y];E&&E.length>=4&&(f.scrollRects={x:E[0],y:E[1],width:E[2],height:E[3]})}}n.set(p,f)}}return n}isInteractiveNode(e,t,n,s,r,o,a){let c=e.toLowerCase();if(c==="html"||c==="body")return!1;if(a||(c==="iframe"||c==="frame")&&r&&r.width>100&&r.height>100)return!0;let l=["search","magnify","glass","lookup","find","query","search-icon","search-btn","search-button","searchbox"],d=(t.class||"").toLowerCase();if(l.some(f=>d.includes(f)))return!0;let g=(t.id||"").toLowerCase();if(l.some(f=>g.includes(f)))return!0;for(let[f,y]of Object.entries(t))if(f.startsWith("data-")&&y&&l.some(T=>y.toLowerCase().includes(T)))return!0;if(s&&s.properties)for(let f of s.properties)try{if(f.name==="disabled"&&f.value||f.name==="hidden"&&f.value)return!1;if(["focusable","editable","settable"].includes(f.name)&&f.value||["checked","expanded","pressed","selected"].includes(f.name)||["required","autocomplete"].includes(f.name)&&f.value||f.name==="keyshortcuts"&&f.value)return!0}catch{continue}if(new Set(["button","input","select","textarea","a","details","summary","option","optgroup"]).has(c))return!(c==="input"&&t.type==="hidden");if(["onclick","onmousedown","onmouseup","onkeydown","onkeyup","tabindex"].some(f=>f in t))return!0;let h=t.role?.toLowerCase();return!!(h&&new Set(["button","link","menuitem","option","radio","checkbox","tab","textbox","combobox","slider","spinbutton","search","searchbox"]).has(h)||s&&s.role&&new Set(["button","link","menuitem","option","radio","checkbox","tab","textbox","combobox","slider","spinbutton","listbox","search","searchbox"]).has(s.role)||r&&r.width>=10&&r.width<=50&&r.height>=10&&r.height<=50&&["class","role","onclick","data-action","aria-label"].some(y=>y in t)||t.contenteditable==="true"||o==="pointer")}isElementVisibleAccordingToAllParents(e,t){if(!e)return!1;let n=e.computedStyles||{},s=(n.display||"").toLowerCase(),r=(n.visibility||"").toLowerCase(),o=n.opacity||"1";if(s==="none"||r==="hidden")return!1;try{if(parseFloat(o)<=0)return!1}catch{}let a=e.bounds;if(!a)return!1;let c={...a};for(let l=t.length-1;l>=0;l--){let d=t[l];if((d.nodeName.toUpperCase()==="IFRAME"||d.nodeName.toUpperCase()==="FRAME")&&d.snapshotData?.bounds){let g=d.snapshotData.bounds;c.x+=g.x,c.y+=g.y}if(d.nodeName==="HTML"&&d.snapshotData){let g=d.snapshotData.scrollRects,m=d.snapshotData.clientRects;if(g&&m){let f=m.width,y=m.height,T=c.x-g.x,x=c.y-g.y;if(!(T<f&&T+c.width>0&&x<y+2e3&&x+c.height>-2e3))return!1;c.x-=g.x,c.y-=g.y}}}return!0}static rectIntersects(e,t){return!(e.x2<=t.x1||t.x2<=e.x1||e.y2<=t.y1||t.y2<=e.y1)}static rectContains(e,t){return e.x1<=t.x1&&e.y1<=t.y1&&e.x2>=t.x2&&e.y2>=t.y2}static splitDiff(e,t){let n=[];e.y1<t.y1&&n.push({x1:e.x1,y1:e.y1,x2:e.x2,y2:t.y1}),t.y2<e.y2&&n.push({x1:e.x1,y1:t.y2,x2:e.x2,y2:e.y2});let s=Math.max(e.y1,t.y1),r=Math.min(e.y2,t.y2);return e.x1<t.x1&&n.push({x1:e.x1,y1:s,x2:t.x1,y2:r}),t.x2<e.x2&&n.push({x1:t.x2,y1:s,x2:e.x2,y2:r}),n}static rectUnionContains(e,t){if(e.length===0)return!1;let n=[t];for(let s of e){let r=[];for(let o of n)i.rectContains(s,o)||(i.rectIntersects(o,s)?r.push(...i.splitDiff(o,s)):r.push(o));if(r.length===0)return!0;n=r}return!1}static rectUnionAdd(e,t){if(i.rectUnionContains(e,t))return[];let n=[t];for(let s of e){let r=[];for(let o of n)i.rectIntersects(o,s)?r.push(...i.splitDiff(o,s)):r.push(o);n=r}return n}applyPaintOrderFiltering(e){let t=[];for(let[a,c]of e.entries())c.snapshotNode?.paintOrder!==void 0&&c.snapshotNode?.paintOrder!==null&&c.snapshotNode?.bounds&&t.push({backendNodeId:a,node:c,paintOrder:c.snapshotNode.paintOrder,bounds:c.snapshotNode.bounds});if(t.length===0)return e;let n=new Map;for(let a of t)n.has(a.paintOrder)||n.set(a.paintOrder,[]),n.get(a.paintOrder).push(a);let s=new Set,r=[],o=Array.from(n.keys()).sort((a,c)=>c-a);for(let a of o){let c=n.get(a),l=[];for(let d of c){let g={x1:d.bounds.x,y1:d.bounds.y,x2:d.bounds.x+d.bounds.width,y2:d.bounds.y+d.bounds.height};i.rectUnionContains(r,g)&&s.add(d.backendNodeId);let m=d.node.snapshotNode?.computedStyles;if(m){let p=m["background-color"]||"rgba(0, 0, 0, 0)",h=parseFloat(m.opacity||"1");if(p==="rgba(0, 0, 0, 0)"||h<.8)continue}l.push(g)}for(let d of l){let g=i.rectUnionAdd(r,d);r.push(...g)}}if(s.size>0){b.debug(`🎨 [Paint Order] Filtering ${s.size} covered elements`);let a=new Map;for(let[c,l]of e.entries())s.has(c)||a.set(c,l);return a}return e}static PROPAGATING_ELEMENTS=[{tag:"a",role:null},{tag:"button",role:null},{tag:"div",role:"button"},{tag:"div",role:"combobox"},{tag:"span",role:"button"},{tag:"span",role:"combobox"},{tag:"input",role:"combobox"}];static DEFAULT_CONTAINMENT_THRESHOLD=.99;isPropagatingElement(e,t){let n=e.toLowerCase(),s=["tag","role"];for(let r of i.PROPAGATING_ELEMENTS)if(s.map(a=>a==="tag"?r.tag===null||r.tag===n:r.role===null||r.role===t).every(Boolean))return!0;return!1}isContained(e,t,n=i.DEFAULT_CONTAINMENT_THRESHOLD){let s=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y)),o=s*r,a=e.width*e.height;return a===0?!1:o/a>=n}shouldExcludeChild(e,t){let n=e.absolutePosition||e.snapshotNode?.bounds;if(!n||!this.isContained(n,t))return!1;let s=e.nodeName.toLowerCase(),r=e.attributes?.role;if(["input","select","textarea","label"].includes(s)||this.isPropagatingElement(s,r)||e.attributes?.onclick)return!1;let o=e.attributes?.["aria-label"];return!(o&&o.trim()||r&&["button","link","checkbox","radio","tab","menuitem","option"].includes(r))}applyBoundingBoxFiltering(e){let t=[];for(let[s,r]of e.entries()){let o=r.nodeName,a=r.attributes?.role,c=r.absolutePosition||r.snapshotNode?.bounds;this.isPropagatingElement(o,a)&&c&&t.push({backendNodeId:s,bounds:c})}if(t.length===0)return e;let n=new Set;for(let[s,r]of e.entries())if(!t.some(o=>o.backendNodeId===s)){for(let o of t)if(this.shouldExcludeChild(r,o.bounds)){n.add(s);break}}if(n.size>0){b.debug(`📦 [BBox Filter] Excluding ${n.size} elements contained within parent bounds`);let s=new Map;for(let[r,o]of e.entries())n.has(r)||s.set(r,o);return s}return e}detectModalOverlays(e,t){let n=[],s=t.width*t.height,r=.3;for(let[o,a]of e.entries()){let c=a.snapshotNode?.computedStyles,l=a.absolutePosition||a.snapshotNode?.bounds,d=a.nodeName.toLowerCase(),g=a.attributes||{},m=[],p=g.role?.toLowerCase()||"",h=g["aria-modal"]?.toLowerCase(),f=(g.class||"").toLowerCase(),y=(g.id||"").toLowerCase();(p==="dialog"||p==="alertdialog"||h==="true")&&m.push(`role=${p||"aria-modal"}`);let T=["modal","overlay","dialog","popup","drawer","backdrop","lightbox"];for(let x of T)if(f.includes(x)||y.includes(x)){m.push(`class/id contains "${x}"`);break}if(c&&l){let x=(c.position||"").toLowerCase(),C=l.width*l.height/s;if((x==="fixed"||x==="absolute")&&C>=r&&m.push(`${x} position, covers ${(C*100).toFixed(0)}% of viewport`),C>=.8){let v=parseFloat(c.opacity||"1");((c["background-color"]||"").includes("rgba")||v<1)&&m.push("full-screen semi-transparent overlay")}}m.length>0&&n.push({backendNodeId:o,nodeName:d,reason:m.join(", ")})}return n}async detectJsClickListeners(e){let t=new Set;try{let s=(await e.send("Runtime.evaluate",{expression:`
407
+ `)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}}});var to,Nl=$(()=>{"use strict";z();Li();to=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,n,s){u.debug("[TakeScreenshotTool] Capturing screenshot...");try{let o=await ts.getInstance().captureScreen();if(!o)throw new Error("Failed to capture screenshot - no image data returned");return u.debug("[TakeScreenshotTool] Screenshot captured successfully"),[{type:"image_url",image_url:{url:o}}]}catch(r){return u.error(`[TakeScreenshotTool] Failed to capture screenshot: ${r.message}`),[{type:"text",text:`Failed to capture screenshot: ${r.message}`}]}}}});var Ui,Yp,b,dt=$(()=>{"use strict";Ui=process.env.BROWSER_USE_DEBUG==="1"||"false"?.includes("browser-use"),Yp={log:Ui?console.log.bind(console):()=>{},debug:Ui?console.debug.bind(console):()=>{},info:Ui?console.info.bind(console):()=>{}},b=Yp});import{EventEmitter as Qp}from"eventemitter3";function Ie(i,e){let t=process.env[i];if(t){let n=parseFloat(t);if(!isNaN(n)&&n>=0)return n;console.warn(`Warning: ${i}=${t} is not a valid number, using default ${e}`)}return e}var no,te,Bi=$(()=>{"use strict";no=class extends Qp{pendingEvents=new Map;async dispatch(e,t,n){let s=`${e}_${Date.now()}_${Math.random()}`;return new Promise((r,o)=>{let a;n&&n>0&&(a=setTimeout(()=>{this.pendingEvents.delete(s),o(new Error(`Event ${e} timed out after ${n}s`))},n*1e3)),this.pendingEvents.set(s,{resolve:r,reject:o,timeout:a}),this.emit(e,{...t,_eventId:s})})}respondToEvent(e,t){let n=this.pendingEvents.get(e);n&&(n.timeout&&clearTimeout(n.timeout),n.resolve(t),this.pendingEvents.delete(e))}rejectEvent(e,t){let n=this.pendingEvents.get(e);n&&(n.timeout&&clearTimeout(n.timeout),n.reject(t),this.pendingEvents.delete(e))}};te={NAVIGATE_TO_URL:Ie("TIMEOUT_NavigateToUrlEvent",15),CLICK_ELEMENT:Ie("TIMEOUT_ClickElementEvent",15),TYPE_TEXT:Ie("TIMEOUT_TypeTextEvent",60),SCROLL:Ie("TIMEOUT_ScrollEvent",8),SWITCH_TAB:Ie("TIMEOUT_SwitchTabEvent",10),CLOSE_TAB:Ie("TIMEOUT_CloseTabEvent",10),SCREENSHOT:Ie("TIMEOUT_ScreenshotEvent",15),BROWSER_STATE_REQUEST:Ie("TIMEOUT_BrowserStateRequestEvent",30),GO_BACK:Ie("TIMEOUT_GoBackEvent",15),GO_FORWARD:Ie("TIMEOUT_GoForwardEvent",15),REFRESH:Ie("TIMEOUT_RefreshEvent",15),WAIT:Ie("TIMEOUT_WaitEvent",60),SEND_KEYS:Ie("TIMEOUT_SendKeysEvent",60),UPLOAD_FILE:Ie("TIMEOUT_UploadFileEvent",30),GET_DROPDOWN_OPTIONS:Ie("TIMEOUT_GetDropdownOptionsEvent",15),SELECT_DROPDOWN_OPTION:Ie("TIMEOUT_SelectDropdownOptionEvent",8),SCROLL_TO_TEXT:Ie("TIMEOUT_ScrollToTextEvent",15),BROWSER_START:Ie("TIMEOUT_BrowserStartEvent",30),BROWSER_STOP:Ie("TIMEOUT_BrowserStopEvent",45)}});var q,Wi=$(()=>{"use strict";q={NAVIGATE_TO_URL:"navigate_to_url",CLICK_ELEMENT:"click_element",TYPE_TEXT:"type_text",SCROLL:"scroll",SWITCH_TAB:"switch_tab",CLOSE_TAB:"close_tab",SCREENSHOT:"screenshot",BROWSER_STATE_REQUEST:"browser_state_request",GO_BACK:"go_back",GO_FORWARD:"go_forward",REFRESH:"refresh",WAIT:"wait",SEND_KEYS:"send_keys",UPLOAD_FILE:"upload_file",GET_DROPDOWN_OPTIONS:"get_dropdown_options",SELECT_DROPDOWN_OPTION:"select_dropdown_option",SCROLL_TO_TEXT:"scroll_to_text",BROWSER_START:"browser_start",BROWSER_STOP:"browser_stop",TAB_CREATED:"tab_created",TAB_CLOSED:"tab_closed",NAVIGATION_STARTED:"navigation_started",NAVIGATION_COMPLETE:"navigation_complete",BROWSER_ERROR:"browser_error",FILE_DOWNLOADED:"file_downloaded"}});var _l,uI,Ws,$l=$(()=>{"use strict";dt();_l=["title","type","checked","id","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","aria-valuemin","aria-valuemax","aria-valuenow","aria-placeholder","pattern","min","max","minlength","maxlength","step","pseudo","selected","expanded","pressed","disabled","invalid","valuemin","valuemax","valuenow","keyshortcuts","haspopup","multiselectable","required","valuetext","level","busy","live","ax_name"],uI=["a[href]","button",'input:not([type="hidden"])',"select","textarea",'[role="button"]','[role="link"]','[role="checkbox"]','[role="radio"]','[role="tab"]','[role="menuitem"]','[role="option"]','[role="switch"]','[role="slider"]','[role="spinbutton"]','[role="combobox"]','[role="listbox"]','[role="textbox"]','[role="searchbox"]',"[onclick]","[onmousedown]","[onmouseup]",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])',"summary","details","label[for]"].join(", "),Ws=class i{constructor(e,t={}){this.page=e;this.crossOriginIframes=t.crossOriginIframes??!1,this.paintOrderFiltering=t.paintOrderFiltering??!0,this.maxIframes=t.maxIframes??100,this.maxIframeDepth=t.maxIframeDepth??5}cdpSession=null;previousElements=new Set;crossOriginIframes;paintOrderFiltering;maxIframes;maxIframeDepth;async getCDPSession(){if(!this.cdpSession){let e=this.page.context();this.cdpSession=await e.newCDPSession(this.page)}return this.cdpSession}async getViewportInfo(){try{let t=await(await this.getCDPSession()).send("Page.getLayoutMetrics"),n=t.visualViewport||{},s=t.cssVisualViewport||{},r=t.cssLayoutViewport||t.layoutViewport||{},o=s.clientWidth||r.clientWidth||1920,a=s.clientHeight||r.clientHeight||1080,c=n.clientWidth||o,l=s.clientWidth||o,d=l>0?c/l:1;return{width:o,height:a,scrollX:s.pageX||0,scrollY:s.pageY||0,devicePixelRatio:d}}catch{let t=this.page.viewportSize();return{width:t?.width||1920,height:t?.height||1080,scrollX:0,scrollY:0,devicePixelRatio:1}}}collectAllFrameIds(e){let t=[e.frame.id];if(e.childFrames&&e.childFrames.length>0)for(let n of e.childFrames)t.push(...this.collectAllFrameIds(n));return t}async getAccessibilityTree(){let e=new Map;try{let t=await this.getCDPSession();await t.send("Page.enable");let n=[];try{let a=(await t.send("Page.getFrameTree")).frameTree;a&&(n=this.collectAllFrameIds(a),b.debug(`Found ${n.length} frames for AX tree extraction`))}catch(o){b.debug("Failed to get frame tree, falling back to main frame only:",o)}let s=[];if(n.length>0)for(let o of n)s.push(t.send("Accessibility.getFullAXTree",{frameId:o}).catch(a=>(b.debug(`Failed to get AX tree for frame ${o}:`,a),{nodes:[]})));else s.push(t.send("Accessibility.getFullAXTree"));let r=await Promise.all(s);for(let o of r){let a=o.nodes||[];for(let c of a)c.backendDOMNodeId&&e.set(c.backendDOMNodeId,{nodeId:c.nodeId,ignored:c.ignored||!1,role:c.role?.value,name:c.name?.value,description:c.description?.value,value:c.value?.value,childIds:c.childIds,backendDOMNodeId:c.backendDOMNodeId,properties:c.properties})}}catch(t){b.debug("Failed to get accessibility tree:",t)}return e}async getDOMSnapshot(){try{return await(await this.getCDPSession()).send("DOMSnapshot.captureSnapshot",{computedStyles:["display","visibility","opacity","position","overflow","z-index","pointer-events"],includePaintOrder:this.paintOrderFiltering,includeDOMRects:!0})}catch(e){return b.debug("Failed to get DOM snapshot:",e),null}}isElementVisible(e){let t=(e.display||"").toLowerCase(),n=(e.visibility||"").toLowerCase(),s=e.opacity||"1",r=(e["pointer-events"]||"").toLowerCase();if(t==="none"||n==="hidden"||r==="none")return!1;try{if(parseFloat(s)<=0)return!1}catch{}return!0}buildSnapshotLookup(e,t){let n=new Map;if(!e?.documents||e.documents.length===0)return n;let s=e.strings||[],r=["display","visibility","opacity","overflow","overflow-x","overflow-y","cursor","pointer-events","position","background-color"];for(let o of e.documents){let a=o.nodes||{},c=o.layout||{},l=new Map,d=a.backendNodeId||[];for(let p=0;p<d.length;p++)l.set(d[p],p);let g=new Map,m=c.nodeIndex||[];for(let p=0;p<m.length;p++){let h=m[p];g.has(h)||g.set(h,p)}for(let[p,h]of l){let f={};if(a.isClickable){let T=a.isClickable?.index||[];f.isClickable=T.includes(h)}let y=g.get(h);if(y!==void 0){let T=c.bounds||[];if(y<T.length){let x=T[y];x&&x.length>=4&&(f.bounds={x:x[0]/t,y:x[1]/t,width:x[2]/t,height:x[3]/t})}let C=c.styles||[];if(y<C.length){let x=C[y]||[],S={};for(let I=0;I<x.length&&I<r.length;I++){let D=x[I];D>=0&&D<s.length&&(S[r[I]]=s[D])}Object.keys(S).length>0&&(f.computedStyles=S,f.cursorStyle=S.cursor)}let w=c.paintOrders||[];y<w.length&&(f.paintOrder=w[y]);let E=c.clientRects||[];if(y<E.length){let x=E[y];x&&x.length>=4&&(f.clientRects={x:x[0],y:x[1],width:x[2],height:x[3]})}let v=c.scrollRects||[];if(y<v.length){let x=v[y];x&&x.length>=4&&(f.scrollRects={x:x[0],y:x[1],width:x[2],height:x[3]})}}n.set(p,f)}}return n}isInteractiveNode(e,t,n,s,r,o,a){let c=e.toLowerCase();if(c==="html"||c==="body")return!1;if(a||(c==="iframe"||c==="frame")&&r&&r.width>100&&r.height>100)return!0;let l=["search","magnify","glass","lookup","find","query","search-icon","search-btn","search-button","searchbox"],d=(t.class||"").toLowerCase();if(l.some(f=>d.includes(f)))return!0;let g=(t.id||"").toLowerCase();if(l.some(f=>g.includes(f)))return!0;for(let[f,y]of Object.entries(t))if(f.startsWith("data-")&&y&&l.some(T=>y.toLowerCase().includes(T)))return!0;if(s&&s.properties)for(let f of s.properties)try{if(f.name==="disabled"&&f.value||f.name==="hidden"&&f.value)return!1;if(["focusable","editable","settable"].includes(f.name)&&f.value||["checked","expanded","pressed","selected"].includes(f.name)||["required","autocomplete"].includes(f.name)&&f.value||f.name==="keyshortcuts"&&f.value)return!0}catch{continue}if(new Set(["button","input","select","textarea","a","details","summary","option","optgroup"]).has(c))return!(c==="input"&&t.type==="hidden");if(["onclick","onmousedown","onmouseup","onkeydown","onkeyup","tabindex"].some(f=>f in t))return!0;let h=t.role?.toLowerCase();return!!(h&&new Set(["button","link","menuitem","option","radio","checkbox","tab","textbox","combobox","slider","spinbutton","search","searchbox"]).has(h)||s&&s.role&&new Set(["button","link","menuitem","option","radio","checkbox","tab","textbox","combobox","slider","spinbutton","listbox","search","searchbox"]).has(s.role)||r&&r.width>=10&&r.width<=50&&r.height>=10&&r.height<=50&&["class","role","onclick","data-action","aria-label"].some(y=>y in t)||t.contenteditable==="true"||o==="pointer")}isElementVisibleAccordingToAllParents(e,t){if(!e)return!1;let n=e.computedStyles||{},s=(n.display||"").toLowerCase(),r=(n.visibility||"").toLowerCase(),o=n.opacity||"1";if(s==="none"||r==="hidden")return!1;try{if(parseFloat(o)<=0)return!1}catch{}let a=e.bounds;if(!a)return!1;let c={...a};for(let l=t.length-1;l>=0;l--){let d=t[l];if((d.nodeName.toUpperCase()==="IFRAME"||d.nodeName.toUpperCase()==="FRAME")&&d.snapshotData?.bounds){let g=d.snapshotData.bounds;c.x+=g.x,c.y+=g.y}if(d.nodeName==="HTML"&&d.snapshotData){let g=d.snapshotData.scrollRects,m=d.snapshotData.clientRects;if(g&&m){let f=m.width,y=m.height,T=c.x-g.x,C=c.y-g.y;if(!(T<f&&T+c.width>0&&C<y+2e3&&C+c.height>-2e3))return!1;c.x-=g.x,c.y-=g.y}}}return!0}static rectIntersects(e,t){return!(e.x2<=t.x1||t.x2<=e.x1||e.y2<=t.y1||t.y2<=e.y1)}static rectContains(e,t){return e.x1<=t.x1&&e.y1<=t.y1&&e.x2>=t.x2&&e.y2>=t.y2}static splitDiff(e,t){let n=[];e.y1<t.y1&&n.push({x1:e.x1,y1:e.y1,x2:e.x2,y2:t.y1}),t.y2<e.y2&&n.push({x1:e.x1,y1:t.y2,x2:e.x2,y2:e.y2});let s=Math.max(e.y1,t.y1),r=Math.min(e.y2,t.y2);return e.x1<t.x1&&n.push({x1:e.x1,y1:s,x2:t.x1,y2:r}),t.x2<e.x2&&n.push({x1:t.x2,y1:s,x2:e.x2,y2:r}),n}static rectUnionContains(e,t){if(e.length===0)return!1;let n=[t];for(let s of e){let r=[];for(let o of n)i.rectContains(s,o)||(i.rectIntersects(o,s)?r.push(...i.splitDiff(o,s)):r.push(o));if(r.length===0)return!0;n=r}return!1}static rectUnionAdd(e,t){if(i.rectUnionContains(e,t))return[];let n=[t];for(let s of e){let r=[];for(let o of n)i.rectIntersects(o,s)?r.push(...i.splitDiff(o,s)):r.push(o);n=r}return n}applyPaintOrderFiltering(e){let t=[];for(let[a,c]of e.entries())c.snapshotNode?.paintOrder!==void 0&&c.snapshotNode?.paintOrder!==null&&c.snapshotNode?.bounds&&t.push({backendNodeId:a,node:c,paintOrder:c.snapshotNode.paintOrder,bounds:c.snapshotNode.bounds});if(t.length===0)return e;let n=new Map;for(let a of t)n.has(a.paintOrder)||n.set(a.paintOrder,[]),n.get(a.paintOrder).push(a);let s=new Set,r=[],o=Array.from(n.keys()).sort((a,c)=>c-a);for(let a of o){let c=n.get(a),l=[];for(let d of c){let g={x1:d.bounds.x,y1:d.bounds.y,x2:d.bounds.x+d.bounds.width,y2:d.bounds.y+d.bounds.height};i.rectUnionContains(r,g)&&s.add(d.backendNodeId);let m=d.node.snapshotNode?.computedStyles;if(m){let p=m["background-color"]||"rgba(0, 0, 0, 0)",h=parseFloat(m.opacity||"1");if(p==="rgba(0, 0, 0, 0)"||h<.8)continue}l.push(g)}for(let d of l){let g=i.rectUnionAdd(r,d);r.push(...g)}}if(s.size>0){b.debug(`🎨 [Paint Order] Filtering ${s.size} covered elements`);let a=new Map;for(let[c,l]of e.entries())s.has(c)||a.set(c,l);return a}return e}static PROPAGATING_ELEMENTS=[{tag:"a",role:null},{tag:"button",role:null},{tag:"div",role:"button"},{tag:"div",role:"combobox"},{tag:"span",role:"button"},{tag:"span",role:"combobox"},{tag:"input",role:"combobox"}];static DEFAULT_CONTAINMENT_THRESHOLD=.99;isPropagatingElement(e,t){let n=e.toLowerCase(),s=["tag","role"];for(let r of i.PROPAGATING_ELEMENTS)if(s.map(a=>a==="tag"?r.tag===null||r.tag===n:r.role===null||r.role===t).every(Boolean))return!0;return!1}isContained(e,t,n=i.DEFAULT_CONTAINMENT_THRESHOLD){let s=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y)),o=s*r,a=e.width*e.height;return a===0?!1:o/a>=n}shouldExcludeChild(e,t){let n=e.absolutePosition||e.snapshotNode?.bounds;if(!n||!this.isContained(n,t))return!1;let s=e.nodeName.toLowerCase(),r=e.attributes?.role;if(["input","select","textarea","label"].includes(s)||this.isPropagatingElement(s,r)||e.attributes?.onclick)return!1;let o=e.attributes?.["aria-label"];return!(o&&o.trim()||r&&["button","link","checkbox","radio","tab","menuitem","option"].includes(r))}applyBoundingBoxFiltering(e){let t=[];for(let[s,r]of e.entries()){let o=r.nodeName,a=r.attributes?.role,c=r.absolutePosition||r.snapshotNode?.bounds;this.isPropagatingElement(o,a)&&c&&t.push({backendNodeId:s,bounds:c})}if(t.length===0)return e;let n=new Set;for(let[s,r]of e.entries())if(!t.some(o=>o.backendNodeId===s)){for(let o of t)if(this.shouldExcludeChild(r,o.bounds)){n.add(s);break}}if(n.size>0){b.debug(`📦 [BBox Filter] Excluding ${n.size} elements contained within parent bounds`);let s=new Map;for(let[r,o]of e.entries())n.has(r)||s.set(r,o);return s}return e}detectModalOverlays(e,t){let n=[],s=t.width*t.height,r=.3;for(let[o,a]of e.entries()){let c=a.snapshotNode?.computedStyles,l=a.absolutePosition||a.snapshotNode?.bounds,d=a.nodeName.toLowerCase(),g=a.attributes||{},m=[],p=g.role?.toLowerCase()||"",h=g["aria-modal"]?.toLowerCase(),f=(g.class||"").toLowerCase(),y=(g.id||"").toLowerCase();(p==="dialog"||p==="alertdialog"||h==="true")&&m.push(`role=${p||"aria-modal"}`);let T=["modal","overlay","dialog","popup","drawer","backdrop","lightbox"];for(let C of T)if(f.includes(C)||y.includes(C)){m.push(`class/id contains "${C}"`);break}if(c&&l){let C=(c.position||"").toLowerCase(),E=l.width*l.height/s;if((C==="fixed"||C==="absolute")&&E>=r&&m.push(`${C} position, covers ${(E*100).toFixed(0)}% of viewport`),E>=.8){let v=parseFloat(c.opacity||"1");((c["background-color"]||"").includes("rgba")||v<1)&&m.push("full-screen semi-transparent overlay")}}m.length>0&&n.push({backendNodeId:o,nodeName:d,reason:m.join(", ")})}return n}async detectJsClickListeners(e){let t=new Set;try{let s=(await e.send("Runtime.evaluate",{expression:`
408
408
  (() => {
409
409
  // getEventListeners is only available in DevTools context via includeCommandLineAPI
410
410
  if (typeof getEventListeners !== 'function') {
@@ -447,8 +447,8 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
447
447
  });
448
448
  return scrollData;
449
449
  })()
450
- `,returnByValue:!0})).result?.value;if(I)for(let[P,R]of Object.entries(I)){let $=R;c.set(parseInt(P),$),b.debug(`Iframe ${P} scroll position - scrollTop=${$.scrollTop}, scrollLeft=${$.scrollLeft}`)}}catch(S){b.debug("Failed to get iframe scroll positions:",S)}let l=new Map;try{let S=await n.send("DOMSnapshot.captureSnapshot",{computedStyles:["display","visibility","opacity","overflow","overflow-x","overflow-y","cursor","pointer-events","position","background-color"],includePaintOrder:this.paintOrderFiltering,includeDOMRects:!0,includeBlendedBackgroundColors:!1,includeTextColorOpacities:!1});l=this.buildSnapshotLookup(S,r.devicePixelRatio)}catch(S){b.debug("Failed to get DOM snapshot:",S)}let d=new Map,g=[],m=new Set,p=[],h=(S,I,P,R=0)=>{I===null&&(I=[]),P===null?P={x:0,y:0}:P={x:P.x,y:P.y};let $=S.backendNodeId,D=S.nodeName?.toLowerCase()||"",_=S.nodeType;if(_===9||_===11){let J=[];if(S.children)for(let $e of S.children){let St=h($e,I,P,R);St&&J.push(St)}return J.length===1?J[0]:J.length>0?{index:-1,tagName:D,children:J,isInteractive:!1,position:void 0}:null}if(_!==1)return null;let N={};if(S.attributes)for(let J=0;J<S.attributes.length;J+=2){let $e=S.attributes[J],St=S.attributes[J+1];$e&&(N[$e]=St||"")}let k={};for(let J of t)N[J]&&(k[J]=N[J]);let M=l.get($),L=M?.isClickable??!1,B=M?.bounds,H=M?.cursorStyle,V=o.get($),le;B&&(le={x:B.x+P.x,y:B.y+P.y,width:B.width,height:B.height});let W=[...I];_===1&&D==="html"&&S.frameId&&(W.push({nodeName:"HTML",frameId:S.frameId,snapshotData:M}),M?.scrollRects&&(P.x-=M.scrollRects.x,P.y-=M.scrollRects.y)),(D==="iframe"||D==="frame")&&B&&(W.push({nodeName:D.toUpperCase(),frameId:S.frameId,snapshotData:M}),P.x+=B.x,P.y+=B.y);let G=this.isElementVisibleAccordingToAllParents(M,W),tt=s.has($),Es=this.isInteractiveNode(D,N,L,V,B,H,tt),vt={index:Es?$:-1,tagName:D,children:[],isInteractive:Es,isVisible:G,position:le||B};if(Es&&G){m.add($);let J="",$e=k.role;if(V&&(J=V.name||"",$e=V.role||$e),!J&&S.children){let wt=Kt=>{let pi=[];if(Kt.nodeType===3&&Kt.nodeValue){let xr=Kt.nodeValue.trim();xr.length>1&&pi.push(xr)}if(Kt.children)for(let xr of Kt.children)pi.push(...wt(xr));return pi};J=wt(S).join(`
451
- `).trim()}!J&&S.nodeValue&&(J=S.nodeValue.trim().substring(0,200)),vt.text=J,vt.role=$e;let St={...k};if(V&&V.properties)for(let wt of V.properties)try{if(_l.includes(wt.name)&&wt.value!==null&&wt.value!==void 0){let Tr=wt.value?.value!==void 0?wt.value.value:wt.value;if(typeof Tr=="boolean")St[wt.name]=Tr.toString().toLowerCase();else{let Kt=String(Tr).trim();Kt&&(St[wt.name]=Kt)}}}catch{continue}V?.name&&!St.ax_name&&(St.ax_name=V.name),vt.attributes=St;let Mc=!this.previousElements.has($.toString());vt.isNew=Mc;let Rm={nodeId:S.nodeId,backendNodeId:$,sessionId:"",frameId:S.frameId||"",targetId:"",nodeType:"element",nodeName:D,attributes:St,isVisible:G,absolutePosition:le||B,text:J,role:$e,isNew:Mc,hasJsClickListener:tt,snapshotNode:M?{isClickable:M.isClickable,cursorStyle:M.cursorStyle,bounds:M.bounds,clientRects:M.clientRects,scrollRects:M.scrollRects,computedStyles:M.computedStyles,paintOrder:M.paintOrder}:null};d.set($,Rm)}let Sn=new Set;if(S.shadowRoots)for(let J of S.shadowRoots)J.nodeId&&Sn.add(J.nodeId);if(S.children)for(let J of S.children){if(J.nodeId&&Sn.has(J.nodeId))continue;let $e=h(J,W,P,R+1);$e&&vt.children.push($e)}if(S.contentDocument){let J=h(S.contentDocument,W,P,R+1);J&&vt.children.push(J)}else if((D==="iframe"||D==="frame")&&this.crossOriginIframes&&R<this.maxIframeDepth&&S.frameId){let J=B||M?.bounds;G&&J&&J.width>=50&&J.height>=50&&p.push({treeNode:vt,frameId:S.frameId,htmlFrames:W,totalFrameOffset:{...P},depth:R+1})}if(S.shadowRoots)for(let J of S.shadowRoots){let $e=h(J,W,P,R+1);$e&&vt.children.push($e)}return vt},f=h(a,null,null,0);if(f&&g.push(f),p.length>0&&this.crossOriginIframes){b.debug(`Processing ${p.length} cross-origin iframes...`);try{let I=(await n.send("Target.getTargets")).targetInfos||[];await n.send("Page.enable");let R=(await n.send("Page.getFrameTree")).frameTree,$=new Map,D=_=>{let N=_.frame||{};if(N.id){let k=I.find(M=>M.type==="iframe"&&M.url&&N.url&&M.url===N.url);k&&$.set(N.id,k.targetId)}for(let k of _.childFrames||[])D(k)};R&&D(R);for(let _ of p){let N=$.get(_.frameId);if(!N){b.debug(`No target found for cross-origin iframe ${_.frameId}`);continue}try{b.debug(`Found cross-origin iframe target: ${N} for frame ${_.frameId}`);let M=this.page.frames().find(L=>L.url().includes(_.frameId)||L.name()===_.frameId);if(M)try{let L=await M.content();L&&b.debug(`Got content from cross-origin frame ${_.frameId} (${L.length} chars)`)}catch{}}catch(k){b.debug(`Failed to process cross-origin iframe ${_.frameId}:`,k)}}}catch(S){b.debug("Failed to process cross-origin iframes:",S)}}this.previousElements=new Set(Array.from(m).map(S=>S.toString()));let y=this.detectModalOverlays(d,r);if(y.length>0){b.log(`🚨 [DOM] Detected ${y.length} potential modal/overlay elements that may block clicks`);for(let S of y)b.debug(` - ${S.nodeName} (backendNodeId=${S.backendNodeId}): ${S.reason}`)}let T=d,x=d.size;e.paintOrderFiltering!==!1&&(T=this.applyPaintOrderFiltering(d));let w=T.size;e.bboxFiltering!==!1&&(T=this.applyBoundingBoxFiltering(T));let C={url:this.page.url(),title:await this.page.title(),domTree:g,selectorMap:T,viewportInfo:r};if(e.includeScreenshot!==!1){let S=await this.page.screenshot({type:"png"});C.screenshot=S.toString("base64")}let v=x-w,E=w-T.size;return b.log(`📋 [DOM] Extracted ${T.size} interactive elements with real backendNodeIds (${v} filtered by paint order, ${E} filtered by bbox)`),C}formatDOMForLLM(e,t=0,n=!0,s){let r="";for(let o of e){let a=!s||s.has(o.index);if(o.isInteractive&&a){let c=" ".repeat(t),d=`${n&&o.isNew?"*":""}[${o.index}]`,g=`<${o.tagName}`,m="";if(o.attributes){let p=[],h={},f=["title","type","checked","id","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","aria-valuemin","aria-valuemax","aria-valuenow","aria-placeholder","pattern","min","max","minlength","maxlength","step","pseudo","selected","expanded","pressed","disabled","invalid","valuemin","valuemax","valuenow","keyshortcuts","haspopup","multiselectable","required","valuetext","level","busy","live","ax_name"];for(let T of f)o.attributes[T]!==void 0&&o.attributes[T]!==""&&(h[T]=String(o.attributes[T]).trim());if(Object.keys(h).length>1){let T={},x=[];for(let w of f)if(h[w]){let C=h[w];C.length>5&&(T[C]?x.push(w):T[C]=w)}for(let w of x)delete h[w]}h.role&&h.role.toLowerCase()===o.tagName.toLowerCase()&&delete h.role,h.type&&h.type.toLowerCase()===o.tagName.toLowerCase()&&delete h.type,h.invalid?.toLowerCase()==="false"&&delete h.invalid,h.expanded&&h["aria-expanded"]&&delete h["aria-expanded"];let y=o.text?.trim().toLowerCase()||"";for(let T of["aria-label","placeholder","title"])h[T]?.trim().toLowerCase()===y&&delete h[T];for(let T of f)if(h[T]){let x=h[T];x.length>100&&(x=x.substring(0,100)+"..."),p.push(`${T}=${x}`)}p.length>0&&(m=" "+p.join(" "))}if(r+=`${c}${d}${g}${m} />`,o.tagName.toLowerCase()==="select"&&o.children.length>0){let p=this.extractSelectOptions(o.children);p.length>0&&(r+=` [options: ${p.join(", ")}]`)}r+=`
450
+ `,returnByValue:!0})).result?.value;if(I)for(let[D,M]of Object.entries(I)){let _=M;c.set(parseInt(D),_),b.debug(`Iframe ${D} scroll position - scrollTop=${_.scrollTop}, scrollLeft=${_.scrollLeft}`)}}catch(S){b.debug("Failed to get iframe scroll positions:",S)}let l=new Map;try{let S=await n.send("DOMSnapshot.captureSnapshot",{computedStyles:["display","visibility","opacity","overflow","overflow-x","overflow-y","cursor","pointer-events","position","background-color"],includePaintOrder:this.paintOrderFiltering,includeDOMRects:!0,includeBlendedBackgroundColors:!1,includeTextColorOpacities:!1});l=this.buildSnapshotLookup(S,r.devicePixelRatio)}catch(S){b.debug("Failed to get DOM snapshot:",S)}let d=new Map,g=[],m=new Set,p=[],h=(S,I,D,M=0)=>{I===null&&(I=[]),D===null?D={x:0,y:0}:D={x:D.x,y:D.y};let _=S.backendNodeId,F=S.nodeName?.toLowerCase()||"",R=S.nodeType;if(R===9||R===11){let Z=[];if(S.children)for(let Fe of S.children){let St=h(Fe,I,D,M);St&&Z.push(St)}return Z.length===1?Z[0]:Z.length>0?{index:-1,tagName:F,children:Z,isInteractive:!1,position:void 0}:null}if(R!==1)return null;let N={};if(S.attributes)for(let Z=0;Z<S.attributes.length;Z+=2){let Fe=S.attributes[Z],St=S.attributes[Z+1];Fe&&(N[Fe]=St||"")}let k={};for(let Z of t)N[Z]&&(k[Z]=N[Z]);let P=l.get(_),B=P?.isClickable??!1,L=P?.bounds,W=P?.cursorStyle,G=o.get(_),Y;L&&(Y={x:L.x+D.x,y:L.y+D.y,width:L.width,height:L.height});let H=[...I];R===1&&F==="html"&&S.frameId&&(H.push({nodeName:"HTML",frameId:S.frameId,snapshotData:P}),P?.scrollRects&&(D.x-=P.scrollRects.x,D.y-=P.scrollRects.y)),(F==="iframe"||F==="frame")&&L&&(H.push({nodeName:F.toUpperCase(),frameId:S.frameId,snapshotData:P}),D.x+=L.x,D.y+=L.y);let j=this.isElementVisibleAccordingToAllParents(P,H),Te=s.has(_),Ft=this.isInteractiveNode(F,N,B,G,L,W,Te),vt={index:Ft?_:-1,tagName:F,children:[],isInteractive:Ft,isVisible:j,position:Y||L};if(Ft&&j){m.add(_);let Z="",Fe=k.role;if(G&&(Z=G.name||"",Fe=G.role||Fe),!Z&&S.children){let wt=Vt=>{let pi=[];if(Vt.nodeType===3&&Vt.nodeValue){let Cr=Vt.nodeValue.trim();Cr.length>1&&pi.push(Cr)}if(Vt.children)for(let Cr of Vt.children)pi.push(...wt(Cr));return pi};Z=wt(S).join(`
451
+ `).trim()}!Z&&S.nodeValue&&(Z=S.nodeValue.trim().substring(0,200)),vt.text=Z,vt.role=Fe;let St={...k};if(G&&G.properties)for(let wt of G.properties)try{if(_l.includes(wt.name)&&wt.value!==null&&wt.value!==void 0){let xr=wt.value?.value!==void 0?wt.value.value:wt.value;if(typeof xr=="boolean")St[wt.name]=xr.toString().toLowerCase();else{let Vt=String(xr).trim();Vt&&(St[wt.name]=Vt)}}}catch{continue}G?.name&&!St.ax_name&&(St.ax_name=G.name),vt.attributes=St;let Mc=!this.previousElements.has(_.toString());vt.isNew=Mc;let Rm={nodeId:S.nodeId,backendNodeId:_,sessionId:"",frameId:S.frameId||"",targetId:"",nodeType:"element",nodeName:F,attributes:St,isVisible:j,absolutePosition:Y||L,text:Z,role:Fe,isNew:Mc,hasJsClickListener:Te,snapshotNode:P?{isClickable:P.isClickable,cursorStyle:P.cursorStyle,bounds:P.bounds,clientRects:P.clientRects,scrollRects:P.scrollRects,computedStyles:P.computedStyles,paintOrder:P.paintOrder}:null};d.set(_,Rm)}let Tn=new Set;if(S.shadowRoots)for(let Z of S.shadowRoots)Z.nodeId&&Tn.add(Z.nodeId);if(S.children)for(let Z of S.children){if(Z.nodeId&&Tn.has(Z.nodeId))continue;let Fe=h(Z,H,D,M+1);Fe&&vt.children.push(Fe)}if(S.contentDocument){let Z=h(S.contentDocument,H,D,M+1);Z&&vt.children.push(Z)}else if((F==="iframe"||F==="frame")&&this.crossOriginIframes&&M<this.maxIframeDepth&&S.frameId){let Z=L||P?.bounds;j&&Z&&Z.width>=50&&Z.height>=50&&p.push({treeNode:vt,frameId:S.frameId,htmlFrames:H,totalFrameOffset:{...D},depth:M+1})}if(S.shadowRoots)for(let Z of S.shadowRoots){let Fe=h(Z,H,D,M+1);Fe&&vt.children.push(Fe)}return vt},f=h(a,null,null,0);if(f&&g.push(f),p.length>0&&this.crossOriginIframes){b.debug(`Processing ${p.length} cross-origin iframes...`);try{let I=(await n.send("Target.getTargets")).targetInfos||[];await n.send("Page.enable");let M=(await n.send("Page.getFrameTree")).frameTree,_=new Map,F=R=>{let N=R.frame||{};if(N.id){let k=I.find(P=>P.type==="iframe"&&P.url&&N.url&&P.url===N.url);k&&_.set(N.id,k.targetId)}for(let k of R.childFrames||[])F(k)};M&&F(M);for(let R of p){let N=_.get(R.frameId);if(!N){b.debug(`No target found for cross-origin iframe ${R.frameId}`);continue}try{b.debug(`Found cross-origin iframe target: ${N} for frame ${R.frameId}`);let P=this.page.frames().find(B=>B.url().includes(R.frameId)||B.name()===R.frameId);if(P)try{let B=await P.content();B&&b.debug(`Got content from cross-origin frame ${R.frameId} (${B.length} chars)`)}catch{}}catch(k){b.debug(`Failed to process cross-origin iframe ${R.frameId}:`,k)}}}catch(S){b.debug("Failed to process cross-origin iframes:",S)}}this.previousElements=new Set(Array.from(m).map(S=>S.toString()));let y=this.detectModalOverlays(d,r);if(y.length>0){b.log(`🚨 [DOM] Detected ${y.length} potential modal/overlay elements that may block clicks`);for(let S of y)b.debug(` - ${S.nodeName} (backendNodeId=${S.backendNodeId}): ${S.reason}`)}let T=d,C=d.size;e.paintOrderFiltering!==!1&&(T=this.applyPaintOrderFiltering(d));let w=T.size;e.bboxFiltering!==!1&&(T=this.applyBoundingBoxFiltering(T));let E={url:this.page.url(),title:await this.page.title(),domTree:g,selectorMap:T,viewportInfo:r};if(e.includeScreenshot!==!1){let S=await this.page.screenshot({type:"png"});E.screenshot=S.toString("base64")}let v=C-w,x=w-T.size;return b.log(`📋 [DOM] Extracted ${T.size} interactive elements with real backendNodeIds (${v} filtered by paint order, ${x} filtered by bbox)`),E}formatDOMForLLM(e,t=0,n=!0,s){let r="";for(let o of e){let a=!s||s.has(o.index);if(o.isInteractive&&a){let c=" ".repeat(t),d=`${n&&o.isNew?"*":""}[${o.index}]`,g=`<${o.tagName}`,m="";if(o.attributes){let p=[],h={},f=["title","type","checked","id","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","aria-valuemin","aria-valuemax","aria-valuenow","aria-placeholder","pattern","min","max","minlength","maxlength","step","pseudo","selected","expanded","pressed","disabled","invalid","valuemin","valuemax","valuenow","keyshortcuts","haspopup","multiselectable","required","valuetext","level","busy","live","ax_name"];for(let T of f)o.attributes[T]!==void 0&&o.attributes[T]!==""&&(h[T]=String(o.attributes[T]).trim());if(Object.keys(h).length>1){let T={},C=[];for(let w of f)if(h[w]){let E=h[w];E.length>5&&(T[E]?C.push(w):T[E]=w)}for(let w of C)delete h[w]}h.role&&h.role.toLowerCase()===o.tagName.toLowerCase()&&delete h.role,h.type&&h.type.toLowerCase()===o.tagName.toLowerCase()&&delete h.type,h.invalid?.toLowerCase()==="false"&&delete h.invalid,h.expanded&&h["aria-expanded"]&&delete h["aria-expanded"];let y=o.text?.trim().toLowerCase()||"";for(let T of["aria-label","placeholder","title"])h[T]?.trim().toLowerCase()===y&&delete h[T];for(let T of f)if(h[T]){let C=h[T];C.length>100&&(C=C.substring(0,100)+"..."),p.push(`${T}=${C}`)}p.length>0&&(m=" "+p.join(" "))}if(r+=`${c}${d}${g}${m} />`,o.tagName.toLowerCase()==="select"&&o.children.length>0){let p=this.extractSelectOptions(o.children);p.length>0&&(r+=` [options: ${p.join(", ")}]`)}r+=`
452
452
  `,o.text&&o.text.trim().length>1&&(r+=`${c} ${o.text.trim()}
453
453
  `)}if(o.children.length>0&&o.tagName.toLowerCase()!=="select"){let c=o.isInteractive&&a;r+=this.formatDOMForLLM(o.children,t+(c?1:0),n,s)}}return r}extractSelectOptions(e){let t=[];for(let n of e){let s=n.tagName.toLowerCase();if(s==="option"){let r=n.text?.trim()||n.attributes?.value||"";if(r){let o=n.attributes?.selected!==void 0||n.attributes?.["aria-selected"]==="true";t.push(o?`*${r}*`:r)}}else if(s==="optgroup"){let r=this.extractSelectOptions(n.children),o=n.attributes?.label||"Group";r.length>0&&t.push(`${o}: ${r.join(", ")}`)}}return t}generateLLMRepresentation(e,t={}){let{showNewElements:n=!0,maxLength:s=5e4}=t,r=`Current URL: ${e.url}
454
454
  `;return r+=`Page Title: ${e.title}
@@ -457,23 +457,23 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
457
457
 
458
458
  `),r+=`Interactive Elements:
459
459
  `,r+=this.formatDOMForLLM(e.domTree,0,n),r.length>s&&(r=r.substring(0,s)+`
460
- ...[truncated]`),r}async getElementByIndex(e,t){return t.get(e)||null}async findElementsByText(e,t){let n=[],s=e.toLowerCase();for(let r of t.values())r.text?.toLowerCase().includes(s)&&n.push(r);return n}async findElementsByRole(e,t){let n=[];for(let s of t.values())(s.role===e||s.attributes?.role===e)&&n.push(s);return n}async close(){this.cdpSession&&(await this.cdpSession.detach(),this.cdpSession=null)}}});import{chromium as pI}from"patchright";import gt from"fs";import Hi from"path";import Jp from"os";function En(){return Hi.join(Zp,eh)}async function Fl(i,e=En(),t=!0){let n=Hi.dirname(e);gt.existsSync(n)||gt.mkdirSync(n,{recursive:!0});let s=i;if(t&&gt.existsSync(e))try{let o=JSON.parse(gt.readFileSync(e,"utf-8"));s=nh(o,i),b.log("[ProfileImport] Merged with existing profile")}catch(o){console.warn(`[ProfileImport] Could not merge with existing profile: ${o.message}`)}let r=e+".tmp";if(gt.writeFileSync(r,JSON.stringify(s,null,2)),gt.existsSync(e)){let o=e+".bak";gt.renameSync(e,o)}gt.renameSync(r,e),b.log(`[ProfileImport] Saved profile to ${e}`),b.log(`[ProfileImport] Total: ${s.cookieCount} cookies, ${s.originCount} origins`)}function Ll(i=En()){if(!gt.existsSync(i))return null;try{return JSON.parse(gt.readFileSync(i,"utf-8"))}catch(e){return console.error(`[ProfileImport] Failed to load profile: ${e.message}`),null}}function es(i=En()){return gt.existsSync(i)}function th(i){return i?{cookies:i.cookies,origins:i.origins}:null}function Ws(i=En()){let e=Ll(i);return th(e)}function nh(i,e){let t=a=>`${a.domain}:${a.name}:${a.path}`,n=new Map;for(let a of i.cookies||[])n.set(t(a),a);for(let a of e.cookies||[])n.set(t(a),a);let s=new Map;for(let a of i.origins||[])s.set(a.origin,a);for(let a of e.origins||[]){let c=s.get(a.origin);if(c){let l=new Map;for(let d of c.localStorage||[])l.set(d.name,d.value);for(let d of a.localStorage||[])l.set(d.name,d.value);a.localStorage=Array.from(l.entries()).map(([d,g])=>({name:d,value:g}))}s.set(a.origin,a)}let r=Array.from(n.values()),o=Array.from(s.values());return{cookies:r,origins:o,importedAt:e.importedAt,sourceType:e.sourceType,cookieCount:r.length,originCount:o.length}}function no(i=En()){if(!gt.existsSync(i))return{exists:!1,cookieCount:0,originCount:0,importedAt:null,path:i};try{let t=Ll(i);return{exists:!0,cookieCount:t?.cookieCount||0,originCount:t?.originCount||0,importedAt:t?.importedAt||null,path:i}}catch{return{exists:!0,cookieCount:0,originCount:0,importedAt:null,path:i}}}var Zp,eh,so=F(()=>{"use strict";dt();Zp=Hi.join(Jp.homedir(),".orion"),eh="browser-profile.json"});import sh from"crypto";import{z as We}from"zod";function Hs(i){return i.nodeName.toLowerCase()}function ih(i){let e=[],t=i;for(;t&&(t.nodeType===1||t.nodeType===11);){if(t.nodeType===11){t=t.parentNode;continue}if(t.parentNode&&Hs(t.parentNode)==="iframe")break;let n=ah(t),s=Hs(t),r=n>0?`[${n}]`:"";e.unshift(`${s}${r}`),t=t.parentNode}return e.join("/")}function ah(i){if(!i.parentNode||!i.parentNode.childrenNodes)return 0;let e=i.parentNode.childrenNodes.filter(n=>n.nodeType===1&&Hs(n)===Hs(i));if(e.length<=1)return 0;let t=e.indexOf(i);return t>=0?t+1:0}function ch(i){let t=lh(i).join("/"),n=Object.entries(i.attributes).filter(([o])=>rh.has(o)).sort().map(([o,a])=>`${o}=${a}`).join(""),s=`${t}|${n}`,r=sh.createHash("sha256").update(s).digest("hex");return parseInt(r.substring(0,16),16)}function lh(i){let e=[],t=i;for(;t;)t.nodeType===1&&e.push(t),t=t.parentNode;return e.reverse(),e.map(n=>Hs(n))}function Bl(i){return{nodeId:i.nodeId,backendNodeId:i.backendNodeId,frameId:i.frameId,nodeType:i.nodeType,nodeValue:i.nodeValue,nodeName:i.nodeName,attributes:i.attributes,bounds:i.snapshotNode?.bounds,xPath:ih(i),elementHash:ch(i)}}var Ul,rh,ro,oh,TI,oo=F(()=>{"use strict";Ul=["title","type","checked","id","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","aria-valuemin","aria-valuemax","aria-valuenow","aria-placeholder","pattern","min","max","minlength","maxlength","step","pseudo","selected","expanded","pressed","disabled","invalid","valuemin","valuemax","valuenow","keyshortcuts","haspopup","multiselectable","required","valuetext","level","busy","live","ax_name"],rh=new Set(["class","id","name","type","placeholder","aria-label","title","role","data-testid","data-test","data-cy","data-selenium","for","required","disabled","readonly","checked","selected","multiple","href","target","rel","aria-describedby","aria-labelledby","aria-controls","aria-owns","aria-live","aria-atomic","aria-busy","aria-disabled","aria-hidden","aria-pressed","aria-checked","aria-selected","tabindex","alt","src","lang","itemscope","itemtype","itemprop","pseudo","aria-valuemin","aria-valuemax","aria-valuenow","aria-placeholder"]),ro=(m=>(m[m.ELEMENT_NODE=1]="ELEMENT_NODE",m[m.ATTRIBUTE_NODE=2]="ATTRIBUTE_NODE",m[m.TEXT_NODE=3]="TEXT_NODE",m[m.CDATA_SECTION_NODE=4]="CDATA_SECTION_NODE",m[m.ENTITY_REFERENCE_NODE=5]="ENTITY_REFERENCE_NODE",m[m.ENTITY_NODE=6]="ENTITY_NODE",m[m.PROCESSING_INSTRUCTION_NODE=7]="PROCESSING_INSTRUCTION_NODE",m[m.COMMENT_NODE=8]="COMMENT_NODE",m[m.DOCUMENT_NODE=9]="DOCUMENT_NODE",m[m.DOCUMENT_TYPE_NODE=10]="DOCUMENT_TYPE_NODE",m[m.DOCUMENT_FRAGMENT_NODE=11]="DOCUMENT_FRAGMENT_NODE",m[m.NOTATION_NODE=12]="NOTATION_NODE",m))(ro||{}),oh=We.object({x:We.number(),y:We.number(),width:We.number(),height:We.number()}),TI=We.object({nodeId:We.number(),backendNodeId:We.number(),frameId:We.string().nullable().optional(),nodeType:We.nativeEnum(ro),nodeValue:We.string(),nodeName:We.string(),attributes:We.record(We.string()).nullable().optional(),bounds:oh.nullable().optional(),xPath:We.string(),elementHash:We.number()})});import*as Mt from"path";import*as Hl from"os";import*as mt from"fs";import{v4 as EI}from"uuid";function uh(){if(In!==null)return In;try{if(mt.existsSync("/.dockerenv"))return In=!0,!0}catch{}try{if(mt.readFileSync("/proc/1/cgroup","utf-8").toLowerCase().includes("docker"))return In=!0,!0}catch{}try{let i=mt.readFileSync("/proc/1/cmdline","utf-8").replace(/\0/g," ");if(/\b(node|python|py|uv|app)\b/i.test(i))return In=!0,!0}catch{}try{if(mt.readdirSync("/proc").filter(t=>/^\d+$/.test(t)).length<10)return In=!0,!0}catch{}return In=!1,!1}function Gs(i,e){if(!i)return e;let t=i.toLowerCase().charAt(0);return t==="t"||t==="y"||t==="1"}function Gi(i){return i.startsWith("~")?Mt.join(Hl.homedir(),i.slice(1)):i}function dh(i){if(!Wl)try{mt.mkdirSync(i,{recursive:!0}),mt.mkdirSync(Mt.join(i,"profiles"),{recursive:!0}),mt.mkdirSync(Mt.join(i,"extensions"),{recursive:!0}),Wl=!0}catch{}}function Gl(){let i=Gi(process.env.XDG_CACHE_HOME||"~/.cache"),e=Gi(process.env.XDG_CONFIG_HOME||"~/.config"),t=Gi(process.env.BROWSER_USE_CONFIG_DIR||Mt.join(e,"browseruse"));dh(t);let n=Gs(process.env.ANONYMIZED_TELEMETRY,!0),s=process.env.IN_DOCKER,r=s!==void 0?Gs(s,!1):uh();return{version:"1.0.0",defaultTimeout:3e4,maxRetries:3,BROWSER_USE_LOGGING_LEVEL:(process.env.BROWSER_USE_LOGGING_LEVEL||"info").toLowerCase(),CDP_LOGGING_LEVEL:process.env.CDP_LOGGING_LEVEL||"WARNING",BROWSER_USE_DEBUG_LOG_FILE:process.env.BROWSER_USE_DEBUG_LOG_FILE||null,BROWSER_USE_INFO_LOG_FILE:process.env.BROWSER_USE_INFO_LOG_FILE||null,ANONYMIZED_TELEMETRY:n,BROWSER_USE_CLOUD_SYNC:Gs(process.env.BROWSER_USE_CLOUD_SYNC,n),BROWSER_USE_CLOUD_API_URL:process.env.BROWSER_USE_CLOUD_API_URL||"https://api.browser-use.com",BROWSER_USE_CLOUD_UI_URL:process.env.BROWSER_USE_CLOUD_UI_URL||"",XDG_CACHE_HOME:i,XDG_CONFIG_HOME:e,BROWSER_USE_CONFIG_DIR:t,BROWSER_USE_CONFIG_FILE:Mt.join(t,"config.json"),BROWSER_USE_CONFIG_PATH:process.env.BROWSER_USE_CONFIG_PATH||null,BROWSER_USE_PROFILES_DIR:Mt.join(t,"profiles"),BROWSER_USE_DEFAULT_USER_DATA_DIR:Mt.join(t,"profiles","default"),BROWSER_USE_EXTENSIONS_DIR:Mt.join(t,"extensions"),OPENAI_API_KEY:process.env.OPENAI_API_KEY||"",ANTHROPIC_API_KEY:process.env.ANTHROPIC_API_KEY||"",GOOGLE_API_KEY:process.env.GOOGLE_API_KEY||"",DEEPSEEK_API_KEY:process.env.DEEPSEEK_API_KEY||"",GROK_API_KEY:process.env.GROK_API_KEY||"",NOVITA_API_KEY:process.env.NOVITA_API_KEY||"",AZURE_OPENAI_ENDPOINT:process.env.AZURE_OPENAI_ENDPOINT||"",AZURE_OPENAI_KEY:process.env.AZURE_OPENAI_KEY||"",SKIP_LLM_API_KEY_VERIFICATION:Gs(process.env.SKIP_LLM_API_KEY_VERIFICATION,!1),DEFAULT_LLM:process.env.DEFAULT_LLM||"",IN_DOCKER:r,IS_IN_EVALS:Gs(process.env.IS_IN_EVALS,!1),WIN_FONT_DIR:process.env.WIN_FONT_DIR||"C:\\Windows\\Fonts"}}var In,Wl,jl=F(()=>{"use strict";In=null;Wl=!1});var Rt,js,io,zs=F(()=>{"use strict";Rt={"2xs":"10px",xs:"11px",sm:"12px","base-sm":"13px",base:"14.5px",md:"15.5px",lg:"18px",xl:"20px","2xl":"24px","3xl":"28px","4xl":"32px","5xl":"36px","6xl":"48px","7xl":"56px","8xl":"64px","9xl":"72px",input:"14.5px",button:"13.5px",label:"13.5px",badge:"11px"},js={"2xs":10,xs:11,sm:12,"base-sm":13,base:14,md:15,lg:18,xl:20,"2xl":24,"3xl":28,"4xl":32,"5xl":36,"6xl":48,"7xl":56,"8xl":64,"9xl":72},io={text:40,title:56,goal:44}});function gh(i,e){return i.toLowerCase()==="input"&&e&&(e==="button"||e==="submit")?ji.button:ji[i.toLowerCase()]||ji.default}function mh(i,e,t,n,s,r){let o=i.width,a=e+n*2,c=t+n*2,l=i.x+Math.floor((o-a)/2),d,g=i.y,m=r-(i.y+i.height);return g>=c+2?d=i.y-c-2:m>=c+2?d=i.y+i.height+2:(d=Math.max(0,i.y-c-2),l=Math.max(0,i.x-a-2)),l<0&&(l=0),d<0&&(d=0),l+a>s&&(l=s-a),d+c>r&&(d=r-c),{x:Math.round(l),y:Math.round(d)}}async function zl(i,e,t=1,n=!0){try{let s=await import("sharp").catch(()=>null);if(!s)return b.debug("Sharp library not available, returning original screenshot"),i;let r=Buffer.from(i,"base64"),o=await s.default(r).metadata(),a=o.width||1280,c=o.height||720,l=[];for(let[m,p]of e.entries())if(p.absolutePosition){let h=p.absolutePosition,f=Math.floor(h.x*t),y=Math.floor(h.y*t),T=Math.floor((h.x+(h.width||0))*t),x=Math.floor((h.y+(h.height||0))*t),w=Math.max(0,Math.min(f,a)),C=Math.max(0,Math.min(y,c)),v=Math.max(w,Math.min(T,a)),E=Math.max(C,Math.min(x,c)),S={x:w,y:C,width:v-w,height:E-C};if(S.width<2||S.height<2)continue;let I="";if(p.attributes){let R=["value","aria-label","title","placeholder","alt"];for(let $ of R)if(p.attributes[$]){I=p.attributes[$];break}}I||(I=p.text||""),I=I.trim();let P=n?I.length<3:!0;l.push({index:m,bbox:S,tagName:p.nodeName||"div",elementType:p.attributes?.type,text:P?String(m):void 0,backendNodeId:m})}if(l.length===0)return i;let d=ph(l,a,c,t);return(await s.default(r).composite([{input:Buffer.from(d),top:0,left:0}]).png().toBuffer()).toString("base64")}catch(s){return b.debug("Image highlighting not available (sharp library may not be installed):",s),i}}function ph(i,e,t,n){let s=e,r=Math.max(js["2xs"],Math.min(js.xl,Math.round(s*.01))),o=Math.max(4,Math.min(10,Math.round(s*.005))),a=`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}">`,c=6,l=4,d=2;function g(m,p,h,f,y,T,x){let w="";if(m===h){let C=Math.min(p,f),v=Math.max(p,f);for(;C<v;){let E=Math.min(C+c,v);w+=`<line x1="${m}" y1="${C}" x2="${m}" y2="${E}" stroke="${y}" stroke-width="${x}"/>`,C+=c+l}}else{let C=Math.min(m,h),v=Math.max(m,h);for(;C<v;){let E=Math.min(C+c,v);w+=`<line x1="${C}" y1="${p}" x2="${E}" y2="${p}" stroke="${y}" stroke-width="${x}"/>`,C+=c+l}}return w}for(let m of i){let{bbox:p,tagName:h,elementType:f,text:y}=m,T=gh(h,f),x=Math.max(0,Math.floor(p.x)),w=Math.max(0,Math.floor(p.y)),C=Math.min(Math.floor(p.x+p.width),e),v=Math.min(Math.floor(p.y+p.height),t);if(C-x<=0||v-w<=0)continue;a+=g(x,w,C,w,T,void 0,d),a+=g(C,w,C,v,T,void 0,d),a+=g(C,v,x,v,T,void 0,d),a+=g(x,v,x,w,T,void 0,d);let E=C-x,S=v-w;if(y){let I=y.length*(r*.6),P=r,R=I+o*2,$=P+o*2,_=mh({x,y:w,width:E,height:S},I,P,o,e,t),N=_.x,k=_.y;a+=`
461
- <rect x="${N}" y="${k}" width="${R}" height="${$}"
460
+ ...[truncated]`),r}async getElementByIndex(e,t){return t.get(e)||null}async findElementsByText(e,t){let n=[],s=e.toLowerCase();for(let r of t.values())r.text?.toLowerCase().includes(s)&&n.push(r);return n}async findElementsByRole(e,t){let n=[];for(let s of t.values())(s.role===e||s.attributes?.role===e)&&n.push(s);return n}async close(){this.cdpSession&&(await this.cdpSession.detach(),this.cdpSession=null)}}});import{chromium as pI}from"patchright";import gt from"fs";import Hi from"path";import Jp from"os";function kn(){return Hi.join(Zp,eh)}async function Fl(i,e=kn(),t=!0){let n=Hi.dirname(e);gt.existsSync(n)||gt.mkdirSync(n,{recursive:!0});let s=i;if(t&&gt.existsSync(e))try{let o=JSON.parse(gt.readFileSync(e,"utf-8"));s=nh(o,i),b.log("[ProfileImport] Merged with existing profile")}catch(o){console.warn(`[ProfileImport] Could not merge with existing profile: ${o.message}`)}let r=e+".tmp";if(gt.writeFileSync(r,JSON.stringify(s,null,2)),gt.existsSync(e)){let o=e+".bak";gt.renameSync(e,o)}gt.renameSync(r,e),b.log(`[ProfileImport] Saved profile to ${e}`),b.log(`[ProfileImport] Total: ${s.cookieCount} cookies, ${s.originCount} origins`)}function Ll(i=kn()){if(!gt.existsSync(i))return null;try{return JSON.parse(gt.readFileSync(i,"utf-8"))}catch(e){return console.error(`[ProfileImport] Failed to load profile: ${e.message}`),null}}function Pn(i=kn()){return gt.existsSync(i)}function th(i){return i?{cookies:i.cookies,origins:i.origins}:null}function ns(i=kn()){let e=Ll(i);return th(e)}function nh(i,e){let t=a=>`${a.domain}:${a.name}:${a.path}`,n=new Map;for(let a of i.cookies||[])n.set(t(a),a);for(let a of e.cookies||[])n.set(t(a),a);let s=new Map;for(let a of i.origins||[])s.set(a.origin,a);for(let a of e.origins||[]){let c=s.get(a.origin);if(c){let l=new Map;for(let d of c.localStorage||[])l.set(d.name,d.value);for(let d of a.localStorage||[])l.set(d.name,d.value);a.localStorage=Array.from(l.entries()).map(([d,g])=>({name:d,value:g}))}s.set(a.origin,a)}let r=Array.from(n.values()),o=Array.from(s.values());return{cookies:r,origins:o,importedAt:e.importedAt,sourceType:e.sourceType,cookieCount:r.length,originCount:o.length}}function Hs(i=kn()){if(!gt.existsSync(i))return{exists:!1,cookieCount:0,originCount:0,importedAt:null,path:i};try{let t=Ll(i);return{exists:!0,cookieCount:t?.cookieCount||0,originCount:t?.originCount||0,importedAt:t?.importedAt||null,path:i}}catch{return{exists:!0,cookieCount:0,originCount:0,importedAt:null,path:i}}}var Zp,eh,so=$(()=>{"use strict";dt();Zp=Hi.join(Jp.homedir(),".orion"),eh="browser-profile.json"});import sh from"crypto";import{z as He}from"zod";function Gs(i){return i.nodeName.toLowerCase()}function ih(i){let e=[],t=i;for(;t&&(t.nodeType===1||t.nodeType===11);){if(t.nodeType===11){t=t.parentNode;continue}if(t.parentNode&&Gs(t.parentNode)==="iframe")break;let n=ah(t),s=Gs(t),r=n>0?`[${n}]`:"";e.unshift(`${s}${r}`),t=t.parentNode}return e.join("/")}function ah(i){if(!i.parentNode||!i.parentNode.childrenNodes)return 0;let e=i.parentNode.childrenNodes.filter(n=>n.nodeType===1&&Gs(n)===Gs(i));if(e.length<=1)return 0;let t=e.indexOf(i);return t>=0?t+1:0}function ch(i){let t=lh(i).join("/"),n=Object.entries(i.attributes).filter(([o])=>rh.has(o)).sort().map(([o,a])=>`${o}=${a}`).join(""),s=`${t}|${n}`,r=sh.createHash("sha256").update(s).digest("hex");return parseInt(r.substring(0,16),16)}function lh(i){let e=[],t=i;for(;t;)t.nodeType===1&&e.push(t),t=t.parentNode;return e.reverse(),e.map(n=>Gs(n))}function Bl(i){return{nodeId:i.nodeId,backendNodeId:i.backendNodeId,frameId:i.frameId,nodeType:i.nodeType,nodeValue:i.nodeValue,nodeName:i.nodeName,attributes:i.attributes,bounds:i.snapshotNode?.bounds,xPath:ih(i),elementHash:ch(i)}}var Ul,rh,ro,oh,TI,oo=$(()=>{"use strict";Ul=["title","type","checked","id","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","aria-valuemin","aria-valuemax","aria-valuenow","aria-placeholder","pattern","min","max","minlength","maxlength","step","pseudo","selected","expanded","pressed","disabled","invalid","valuemin","valuemax","valuenow","keyshortcuts","haspopup","multiselectable","required","valuetext","level","busy","live","ax_name"],rh=new Set(["class","id","name","type","placeholder","aria-label","title","role","data-testid","data-test","data-cy","data-selenium","for","required","disabled","readonly","checked","selected","multiple","href","target","rel","aria-describedby","aria-labelledby","aria-controls","aria-owns","aria-live","aria-atomic","aria-busy","aria-disabled","aria-hidden","aria-pressed","aria-checked","aria-selected","tabindex","alt","src","lang","itemscope","itemtype","itemprop","pseudo","aria-valuemin","aria-valuemax","aria-valuenow","aria-placeholder"]),ro=(m=>(m[m.ELEMENT_NODE=1]="ELEMENT_NODE",m[m.ATTRIBUTE_NODE=2]="ATTRIBUTE_NODE",m[m.TEXT_NODE=3]="TEXT_NODE",m[m.CDATA_SECTION_NODE=4]="CDATA_SECTION_NODE",m[m.ENTITY_REFERENCE_NODE=5]="ENTITY_REFERENCE_NODE",m[m.ENTITY_NODE=6]="ENTITY_NODE",m[m.PROCESSING_INSTRUCTION_NODE=7]="PROCESSING_INSTRUCTION_NODE",m[m.COMMENT_NODE=8]="COMMENT_NODE",m[m.DOCUMENT_NODE=9]="DOCUMENT_NODE",m[m.DOCUMENT_TYPE_NODE=10]="DOCUMENT_TYPE_NODE",m[m.DOCUMENT_FRAGMENT_NODE=11]="DOCUMENT_FRAGMENT_NODE",m[m.NOTATION_NODE=12]="NOTATION_NODE",m))(ro||{}),oh=He.object({x:He.number(),y:He.number(),width:He.number(),height:He.number()}),TI=He.object({nodeId:He.number(),backendNodeId:He.number(),frameId:He.string().nullable().optional(),nodeType:He.nativeEnum(ro),nodeValue:He.string(),nodeName:He.string(),attributes:He.record(He.string()).nullable().optional(),bounds:oh.nullable().optional(),xPath:He.string(),elementHash:He.number()})});import*as Mt from"path";import*as Hl from"os";import*as mt from"fs";import{v4 as EI}from"uuid";function uh(){if(An!==null)return An;try{if(mt.existsSync("/.dockerenv"))return An=!0,!0}catch{}try{if(mt.readFileSync("/proc/1/cgroup","utf-8").toLowerCase().includes("docker"))return An=!0,!0}catch{}try{let i=mt.readFileSync("/proc/1/cmdline","utf-8").replace(/\0/g," ");if(/\b(node|python|py|uv|app)\b/i.test(i))return An=!0,!0}catch{}try{if(mt.readdirSync("/proc").filter(t=>/^\d+$/.test(t)).length<10)return An=!0,!0}catch{}return An=!1,!1}function js(i,e){if(!i)return e;let t=i.toLowerCase().charAt(0);return t==="t"||t==="y"||t==="1"}function Gi(i){return i.startsWith("~")?Mt.join(Hl.homedir(),i.slice(1)):i}function dh(i){if(!Wl)try{mt.mkdirSync(i,{recursive:!0}),mt.mkdirSync(Mt.join(i,"profiles"),{recursive:!0}),mt.mkdirSync(Mt.join(i,"extensions"),{recursive:!0}),Wl=!0}catch{}}function Gl(){let i=Gi(process.env.XDG_CACHE_HOME||"~/.cache"),e=Gi(process.env.XDG_CONFIG_HOME||"~/.config"),t=Gi(process.env.BROWSER_USE_CONFIG_DIR||Mt.join(e,"browseruse"));dh(t);let n=js(process.env.ANONYMIZED_TELEMETRY,!0),s=process.env.IN_DOCKER,r=s!==void 0?js(s,!1):uh();return{version:"1.0.0",defaultTimeout:3e4,maxRetries:3,BROWSER_USE_LOGGING_LEVEL:(process.env.BROWSER_USE_LOGGING_LEVEL||"info").toLowerCase(),CDP_LOGGING_LEVEL:process.env.CDP_LOGGING_LEVEL||"WARNING",BROWSER_USE_DEBUG_LOG_FILE:process.env.BROWSER_USE_DEBUG_LOG_FILE||null,BROWSER_USE_INFO_LOG_FILE:process.env.BROWSER_USE_INFO_LOG_FILE||null,ANONYMIZED_TELEMETRY:n,BROWSER_USE_CLOUD_SYNC:js(process.env.BROWSER_USE_CLOUD_SYNC,n),BROWSER_USE_CLOUD_API_URL:process.env.BROWSER_USE_CLOUD_API_URL||"https://api.browser-use.com",BROWSER_USE_CLOUD_UI_URL:process.env.BROWSER_USE_CLOUD_UI_URL||"",XDG_CACHE_HOME:i,XDG_CONFIG_HOME:e,BROWSER_USE_CONFIG_DIR:t,BROWSER_USE_CONFIG_FILE:Mt.join(t,"config.json"),BROWSER_USE_CONFIG_PATH:process.env.BROWSER_USE_CONFIG_PATH||null,BROWSER_USE_PROFILES_DIR:Mt.join(t,"profiles"),BROWSER_USE_DEFAULT_USER_DATA_DIR:Mt.join(t,"profiles","default"),BROWSER_USE_EXTENSIONS_DIR:Mt.join(t,"extensions"),OPENAI_API_KEY:process.env.OPENAI_API_KEY||"",ANTHROPIC_API_KEY:process.env.ANTHROPIC_API_KEY||"",GOOGLE_API_KEY:process.env.GOOGLE_API_KEY||"",DEEPSEEK_API_KEY:process.env.DEEPSEEK_API_KEY||"",GROK_API_KEY:process.env.GROK_API_KEY||"",NOVITA_API_KEY:process.env.NOVITA_API_KEY||"",AZURE_OPENAI_ENDPOINT:process.env.AZURE_OPENAI_ENDPOINT||"",AZURE_OPENAI_KEY:process.env.AZURE_OPENAI_KEY||"",SKIP_LLM_API_KEY_VERIFICATION:js(process.env.SKIP_LLM_API_KEY_VERIFICATION,!1),DEFAULT_LLM:process.env.DEFAULT_LLM||"",IN_DOCKER:r,IS_IN_EVALS:js(process.env.IS_IN_EVALS,!1),WIN_FONT_DIR:process.env.WIN_FONT_DIR||"C:\\Windows\\Fonts"}}var An,Wl,jl=$(()=>{"use strict";An=null;Wl=!1});var Rt,zs,io,qs=$(()=>{"use strict";Rt={"2xs":"10px",xs:"11px",sm:"12px","base-sm":"13px",base:"14.5px",md:"15.5px",lg:"18px",xl:"20px","2xl":"24px","3xl":"28px","4xl":"32px","5xl":"36px","6xl":"48px","7xl":"56px","8xl":"64px","9xl":"72px",input:"14.5px",button:"13.5px",label:"13.5px",badge:"11px"},zs={"2xs":10,xs:11,sm:12,"base-sm":13,base:14,md:15,lg:18,xl:20,"2xl":24,"3xl":28,"4xl":32,"5xl":36,"6xl":48,"7xl":56,"8xl":64,"9xl":72},io={text:40,title:56,goal:44}});function gh(i,e){return i.toLowerCase()==="input"&&e&&(e==="button"||e==="submit")?ji.button:ji[i.toLowerCase()]||ji.default}function mh(i,e,t,n,s,r){let o=i.width,a=e+n*2,c=t+n*2,l=i.x+Math.floor((o-a)/2),d,g=i.y,m=r-(i.y+i.height);return g>=c+2?d=i.y-c-2:m>=c+2?d=i.y+i.height+2:(d=Math.max(0,i.y-c-2),l=Math.max(0,i.x-a-2)),l<0&&(l=0),d<0&&(d=0),l+a>s&&(l=s-a),d+c>r&&(d=r-c),{x:Math.round(l),y:Math.round(d)}}async function zl(i,e,t=1,n=!0){try{let s=await import("sharp").catch(()=>null);if(!s)return b.debug("Sharp library not available, returning original screenshot"),i;let r=Buffer.from(i,"base64"),o=await s.default(r).metadata(),a=o.width||1280,c=o.height||720,l=[];for(let[m,p]of e.entries())if(p.absolutePosition){let h=p.absolutePosition,f=Math.floor(h.x*t),y=Math.floor(h.y*t),T=Math.floor((h.x+(h.width||0))*t),C=Math.floor((h.y+(h.height||0))*t),w=Math.max(0,Math.min(f,a)),E=Math.max(0,Math.min(y,c)),v=Math.max(w,Math.min(T,a)),x=Math.max(E,Math.min(C,c)),S={x:w,y:E,width:v-w,height:x-E};if(S.width<2||S.height<2)continue;let I="";if(p.attributes){let M=["value","aria-label","title","placeholder","alt"];for(let _ of M)if(p.attributes[_]){I=p.attributes[_];break}}I||(I=p.text||""),I=I.trim();let D=n?I.length<3:!0;l.push({index:m,bbox:S,tagName:p.nodeName||"div",elementType:p.attributes?.type,text:D?String(m):void 0,backendNodeId:m})}if(l.length===0)return i;let d=ph(l,a,c,t);return(await s.default(r).composite([{input:Buffer.from(d),top:0,left:0}]).png().toBuffer()).toString("base64")}catch(s){return b.debug("Image highlighting not available (sharp library may not be installed):",s),i}}function ph(i,e,t,n){let s=e,r=Math.max(zs["2xs"],Math.min(zs.xl,Math.round(s*.01))),o=Math.max(4,Math.min(10,Math.round(s*.005))),a=`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}">`,c=6,l=4,d=2;function g(m,p,h,f,y,T,C){let w="";if(m===h){let E=Math.min(p,f),v=Math.max(p,f);for(;E<v;){let x=Math.min(E+c,v);w+=`<line x1="${m}" y1="${E}" x2="${m}" y2="${x}" stroke="${y}" stroke-width="${C}"/>`,E+=c+l}}else{let E=Math.min(m,h),v=Math.max(m,h);for(;E<v;){let x=Math.min(E+c,v);w+=`<line x1="${E}" y1="${p}" x2="${x}" y2="${p}" stroke="${y}" stroke-width="${C}"/>`,E+=c+l}}return w}for(let m of i){let{bbox:p,tagName:h,elementType:f,text:y}=m,T=gh(h,f),C=Math.max(0,Math.floor(p.x)),w=Math.max(0,Math.floor(p.y)),E=Math.min(Math.floor(p.x+p.width),e),v=Math.min(Math.floor(p.y+p.height),t);if(E-C<=0||v-w<=0)continue;a+=g(C,w,E,w,T,void 0,d),a+=g(E,w,E,v,T,void 0,d),a+=g(E,v,C,v,T,void 0,d),a+=g(C,v,C,w,T,void 0,d);let x=E-C,S=v-w;if(y){let I=y.length*(r*.6),D=r,M=I+o*2,_=D+o*2,R=mh({x:C,y:w,width:x,height:S},I,D,o,e,t),N=R.x,k=R.y;a+=`
461
+ <rect x="${N}" y="${k}" width="${M}" height="${_}"
462
462
  fill="${T}" rx="3"/>
463
- `;let M=N+Math.floor((R-I)/2),L=k+Math.floor(($+P*.7)/2);a+=`
464
- <text x="${M+1}" y="${L+1}"
463
+ `;let P=N+Math.floor((M-I)/2),B=k+Math.floor((_+D*.7)/2);a+=`
464
+ <text x="${P+1}" y="${B+1}"
465
465
  fill="rgba(0,0,0,0.4)" font-family="Arial, sans-serif" font-size="${r}" font-weight="bold">
466
466
  ${y}
467
467
  </text>
468
468
  `,a+=`
469
- <text x="${M}" y="${L}"
469
+ <text x="${P}" y="${B}"
470
470
  fill="white" font-family="Arial, sans-serif" font-size="${r}" font-weight="bold">
471
471
  ${y}
472
472
  </text>
473
- `}}return a+="</svg>",a}var ji,ql=F(()=>{"use strict";dt();zs();ji={button:"#8FA3B8",input:"#A0B4C8",select:"#B8C5D0",a:"#7A92A8",textarea:"#C0CCD8",default:"#9CADB8"}});import{chromium as hh}from"patchright";import{v4 as fh}from"uuid";function bh(){let i=process.platform,e=process.env.HOME||process.env.USERPROFILE||"";return i==="darwin"?`${e}/Library/Application Support/Google/Chrome`:i==="win32"?`${process.env.LOCALAPPDATA}\\Google\\Chrome\\User Data`:`${e}/.config/google-chrome`}var kn,zi=F(()=>{"use strict";dt();Bi();Wi();$l();so();oo();jl();zs();ql();kn=class{id;eventBus;options;browser;context;pages=new Map;currentPageId;started=!1;cachedSelectorMap=new Map;cachedBrowserStateSummary=null;pageSelectorMaps=new Map;pendingRequests=new Set;networkIdleConfig={enabled:!0,idleTime:.5,maxInflight:2,timeout:10,pollInterval:.1};_downloadedFiles=[];cdpSession=null;pageCdpSessions=new Map;highlightsAdded=!1;constructor(e={}){this.id=e.id||fh(),this.options=e,this.eventBus=new to,this.registerEventHandlers()}registerEventHandlers(){this.eventBus.on(z.NAVIGATE_TO_URL,async e=>{await this.handleNavigateToUrl(e)}),this.eventBus.on(z.CLICK_ELEMENT,async e=>{await this.handleClickElement(e)}),this.eventBus.on(z.TYPE_TEXT,async e=>{await this.handleTypeText(e)}),this.eventBus.on(z.SCROLL,async e=>{await this.handleScroll(e)}),this.eventBus.on(z.BROWSER_STATE_REQUEST,async e=>{await this.handleBrowserStateRequest(e)}),this.eventBus.on(z.SCREENSHOT,async e=>{await this.handleScreenshot(e)}),this.eventBus.on(z.GO_BACK,async e=>{await this.handleGoBack(e)}),this.eventBus.on(z.GO_FORWARD,async e=>{await this.handleGoForward(e)}),this.eventBus.on(z.REFRESH,async e=>{await this.handleRefresh(e)}),this.eventBus.on(z.WAIT,async e=>{await this.handleWait(e)}),this.eventBus.on(z.SEND_KEYS,async e=>{await this.handleSendKeys(e)}),this.eventBus.on(z.UPLOAD_FILE,async e=>{await this.handleUploadFile(e)}),this.eventBus.on(z.GET_DROPDOWN_OPTIONS,async e=>{await this.handleGetDropdownOptions(e)}),this.eventBus.on(z.SELECT_DROPDOWN_OPTION,async e=>{await this.handleSelectDropdownOption(e)})}async start(){if(this.started)return;let e=["--disable-blink-features=AutomationControlled","--disable-infobars","--disable-dev-shm-usage","--disable-browser-side-navigation","--no-first-run","--no-default-browser-check","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--disable-component-update","--disable-features=TranslateUI"],t={headless:this.options.headless??!1,args:[...e,...this.options.args||[]],ignoreDefaultArgs:["--enable-automation"],channel:this.options.channel||"chrome"};this.options.executablePath&&(t.executablePath=this.options.executablePath,delete t.channel),this.options.disableSecurity&&t.args.push("--disable-web-security","--disable-features=IsolateOrigins,site-per-process");let n={acceptDownloads:this.options.acceptDownloads??!0};this.options.viewport?n.viewport=this.options.viewport:this.options.headless?n.viewport={width:1280,height:720}:n.viewport=null,this.options.userAgent&&(n.userAgent=this.options.userAgent),this.options.downloadsPath&&(n.downloadsPath=this.options.downloadsPath),this.options.storageState&&(n.storageState=this.options.storageState,b.log(`🍪 [BrowserSession] Restoring profile with ${this.options.storageState.cookies?.length||0} cookies`));let s=Gl(),r;this.options.useRealChromeProfile?(r=bh(),b.log(`🔐 [BrowserSession] Using REAL Chrome profile for maximum stealth: ${r}`),b.log("⚠️ [BrowserSession] Make sure Chrome is closed before starting!")):this.options.userDataDir?r=this.options.userDataDir:r=s.BROWSER_USE_DEFAULT_USER_DATA_DIR,b.log(`🗂️ [BrowserSession] Using persistent user data directory: ${r}`);let{storageState:o,...a}=n;if(this.context=await hh.launchPersistentContext(r,{...t,...a}),this.browser=this.context.browser?.()||null,o?.cookies&&o.cookies.length>0)try{await this.context.addCookies(o.cookies),b.log(`🍪 [BrowserSession] Applied ${o.cookies.length} imported cookies to persistent context`)}catch(d){console.warn(`⚠️ [BrowserSession] Failed to apply imported cookies: ${d.message}`)}let c=await this.context.newPage(),l=this.generatePageId();this.pages.set(l,c),this.currentPageId=l,await this.injectStealthScripts(c),this.setupPageListeners(c,l),this.context.on("close",async()=>{await this.saveStorageStateIfPossible()}),this.started=!0}async saveStorageState(){return this.saveStorageStateIfPossible()}async saveStorageStateIfPossible(){if(!this.context)return!1;try{let e=await this.context.storageState();if(e.cookies.length>0||e.origins.length>0){let t={cookies:e.cookies,origins:e.origins,importedAt:new Date().toISOString(),sourceType:"running-chrome",cookieCount:e.cookies.length,originCount:e.origins.length};return await Fl(t,En(),!0),b.log(`[BrowserSession] Saved ${e.cookies.length} cookies`),!0}}catch(e){b.debug("[BrowserSession] Could not save storage state:",e.message)}return!1}async stop(){this.started&&(await this.saveStorageStateIfPossible(),this.context&&await this.context.close(),this.browser&&await this.browser.close(),this.pages.clear(),this.started=!1)}async injectStealthScripts(e){try{await e.addInitScript(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}}),Object.defineProperty(navigator,"plugins",{get:()=>{let r=[{name:"Chrome PDF Plugin",filename:"internal-pdf-viewer",description:"Portable Document Format"},{name:"Chrome PDF Viewer",filename:"mhjfbmdgcfjbbpaeojofohoefgiehjai",description:""},{name:"Native Client",filename:"internal-nacl-plugin",description:""}];return r.item=o=>r[o]||null,r.namedItem=o=>r.find(a=>a.name===o)||null,r.refresh=()=>{},r}}),Object.defineProperty(navigator,"languages",{get:()=>["en-US","en"]}),Object.getOwnPropertyNames(window).filter(r=>r.startsWith("cdc_")||r.startsWith("$cdc_")).forEach(r=>{try{delete window[r]}catch{}}),window.chrome||(window.chrome={}),window.chrome.runtime||(window.chrome.runtime={connect:()=>{},sendMessage:()=>{},onMessage:{addListener:()=>{}}});let n=navigator.permissions?.query?.bind(navigator.permissions);n&&(navigator.permissions.query=r=>r.name==="notifications"?Promise.resolve({state:"denied",onchange:null}):n(r));let s=console.debug;console.debug=function(...r){if(!r.some(o=>String(o).includes("Runtime.enable")))return s.apply(console,r)}}),b.log("🛡️ [BrowserSession] Stealth scripts injected")}catch(t){console.warn(`[BrowserSession] Failed to inject stealth scripts: ${t.message}`)}}async handleCloudflareTurnstile(e,t){let n=e||this.getCurrentPage(),s=t?.timeout??1e4,r=t?.delayBeforeClick??2e3;try{b.log("🔐 [BrowserSession] Checking for Cloudflare Turnstile...");let o=['iframe[src*="challenges.cloudflare.com"]','iframe[src*="turnstile"]',".cf-turnstile iframe","[data-turnstile-callback] iframe"],a=null;for(let m of o)try{let p=await n.waitForSelector(m,{timeout:3e3});if(p){a=p;break}}catch{}if(!a)return b.log("🔐 [BrowserSession] No Turnstile detected, continuing..."),!1;b.log("🔐 [BrowserSession] Turnstile detected, waiting before click..."),await new Promise(m=>setTimeout(m,r+Math.random()*1e3));let c=await a.boundingBox();if(!c)return console.warn("🔐 [BrowserSession] Could not get Turnstile bounding box"),!1;let l=c.x+25+Math.random()*10,d=c.y+c.height/2+(Math.random()-.5)*10;await this.humanLikeMouseMove(n,l,d),await new Promise(m=>setTimeout(m,100+Math.random()*200)),await n.mouse.click(l,d),b.log("🔐 [BrowserSession] Clicked Turnstile checkbox"),await new Promise(m=>setTimeout(m,3e3));let g=await n.evaluate(()=>[document.querySelector('[data-turnstile-success="true"]'),document.querySelector(".cf-turnstile-success"),document.querySelector('input[name="cf-turnstile-response"]')].some(p=>p!==null));return g?b.log("✅ [BrowserSession] Turnstile challenge passed!"):console.warn("⚠️ [BrowserSession] Turnstile may require manual verification"),g}catch(o){return console.warn(`[BrowserSession] Turnstile handling failed: ${o.message}`),!1}}async humanLikeMouseMove(e,t,n){let s=e.viewportSize()||{width:1280,height:720},r=s.width/2,o=s.height/2,a=20+Math.floor(Math.random()*10),c=r+(t-r)*.5+(Math.random()-.5)*100,l=o+(n-o)*.5+(Math.random()-.5)*100;for(let d=0;d<=a;d++){let g=d/a,m=Math.pow(1-g,2)*r+2*(1-g)*g*c+Math.pow(g,2)*t,p=Math.pow(1-g,2)*o+2*(1-g)*g*l+Math.pow(g,2)*n;await e.mouse.move(m,p);let h=5+Math.random()*15*(1-Math.abs(g-.5)*2);await new Promise(f=>setTimeout(f,h))}}async navigateWithCloudflareBypass(e,t){let n=t||this.getCurrentPage();await n.goto(e,{waitUntil:"domcontentloaded"}),await new Promise(r=>setTimeout(r,2e3)),await n.evaluate(()=>{let r=document.title.toLowerCase(),o=document.body?.innerText?.toLowerCase()||"";return r.includes("just a moment")||r.includes("attention required")||o.includes("checking your browser")||o.includes("verify you are human")||document.querySelector('iframe[src*="challenges.cloudflare.com"]')!==null})&&(b.log("🔐 [BrowserSession] Cloudflare challenge detected, attempting bypass..."),await this.handleCloudflareTurnstile(n),await new Promise(o=>setTimeout(o,3e3)),await n.evaluate(()=>document.title.toLowerCase().includes("just a moment"))&&console.warn("⚠️ [BrowserSession] Still on Cloudflare challenge page - may need manual intervention"))}async autoHandleCloudflareIfNeeded(e){try{await e.evaluate(()=>{let n=document.title.toLowerCase(),s=document.body?.innerText?.substring(0,500).toLowerCase()||"";return n.includes("just a moment")||n.includes("attention required")||n.includes("please wait")||s.includes("checking your browser")||s.includes("verify you are human")||s.includes("enable javascript and cookies")||document.querySelector('iframe[src*="challenges.cloudflare.com"]')!==null||document.querySelector(".cf-turnstile")!==null})&&(b.log("🔐 [BrowserSession] Cloudflare challenge auto-detected"),await this.handleCloudflareTurnstile(e))}catch{}}getCurrentPage(){if(this.currentPageId&&this.pages.has(this.currentPageId))return this.pages.get(this.currentPageId);let e=Array.from(this.pages.entries());if(e.length>0){let[t,n]=e[e.length-1];return console.warn(`🔄 Current page closed, switching to fallback page ${t}`),this.currentPageId=t,n}throw new Error("No active page")}async ensurePage(){try{return this.getCurrentPage()}catch{if(this.context){console.warn("🔄 No active page, creating new one...");let e=await this.context.newPage(),t=this.generatePageId();return this.pages.set(t,e),this.currentPageId=t,await this.injectStealthScripts(e),this.setupPageListeners(e,t),e}throw new Error("No active page and no browser context available")}}getPage(e){return this.pages.get(e)}getPageOrCurrent(e){return e&&this.pages.has(e)?this.pages.get(e):this.getCurrentPage()}async createTabForAgent(e){if(!this.context)throw new Error("Browser context not available - call start() first");let t=await this.context.newPage(),n=e?`agent_${e}_${Date.now()}`:this.generatePageId();return this.pages.set(n,t),await this.injectStealthScripts(t),this.setupPageListeners(t,n),b.log(`🆕 [BrowserSession] Created new tab ${n} for agent${e?` ${e}`:""}`),b.log(`📊 [BrowserSession] Total tabs: ${this.pages.size}`),{pageId:n,page:t}}async getStateForPage(e,t={}){let n=this.pages.get(e);if(!n)throw new Error(`Page ${e} not found`);let s=await this.getStateFromPage(n,t);return s.domState?.selectorMap&&this.pageSelectorMaps.set(e,s.domState.selectorMap),s}getSelectorMapForPage(e){let t=this.pageSelectorMaps.get(e);return t||this.cachedSelectorMap}getElementByIndexForPage(e,t){let n=this.getSelectorMapForPage(e);return n.has(t)?n.get(t):null}async waitForPageReadiness(e,t={}){let n=t.timeout??5e3,s=t.minElements??10,r=t.stabilityChecks??2,o=Date.now(),a="unknown",c=0,l=0,d=0;for(;Date.now()-o<n;)try{let g=await e.evaluate(()=>{let p=document.readyState,h=performance.getEntriesByType("resource").filter(x=>x.responseEnd===0||x.transferSize===0&&x.decodedBodySize===0&&!x.name.startsWith("data:")).length,y=document.querySelectorAll('a, button, input, select, textarea, [role="button"], [onclick], [tabindex]').length,T=!!(document.querySelector('[class*="loading"]')||document.querySelector('[class*="skeleton"]')||document.querySelector('[class*="spinner"]')||document.querySelector('[class*="Spinner"]')||document.querySelector('[class*="Loading"]')||document.querySelector('[class*="Skeleton"]')||document.querySelector('[aria-busy="true"]')||document.querySelector('[data-loading="true"]')||document.querySelector(".placeholder"));return{readyState:p,pendingRequests:h,elementCount:y,hasLoadingIndicator:T}});if(g.elementCount===l&&g.elementCount>0?d++:d=0,a=g.readyState,c=g.pendingRequests,l=g.elementCount,(g.readyState==="complete"||g.readyState==="interactive"&&d>=r)&&g.pendingRequests<=2&&g.elementCount>=s&&!g.hasLoadingIndicator&&d>=r)return b.debug(`✅ Page ready: readyState=${g.readyState}, pending=${g.pendingRequests}, elements=${g.elementCount}, stable=${d}`),{ready:!0,pendingRequests:g.pendingRequests,readyState:g.readyState,elementCount:g.elementCount};await new Promise(p=>setTimeout(p,100))}catch{d=0,await new Promise(m=>setTimeout(m,100))}return b.debug(`⚠️ Page readiness timeout: readyState=${a}, pending=${c}, elements=${l}, stable=${d}`),{ready:!1,pendingRequests:c,readyState:a,elementCount:l}}async getStateFromPage(e,t={}){let n=await this.waitForPageReadiness(e,{timeout:5e3,minElements:5});n.ready||(b.debug(`⚠️ Proceeding with DOM extraction despite page not fully ready (readyState=${n.readyState})`),n.pendingRequests>0&&await new Promise(c=>setTimeout(c,300)));let s=await e.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,pageWidth:document.documentElement.scrollWidth,pageHeight:document.documentElement.scrollHeight})),r={viewportWidth:s.viewportWidth,viewportHeight:s.viewportHeight,pageWidth:s.pageWidth,pageHeight:s.pageHeight,scrollX:s.scrollX,scrollY:s.scrollY,pixelsAbove:s.scrollY,pixelsBelow:Math.max(0,s.pageHeight-s.viewportHeight-s.scrollY),pixelsLeft:s.scrollX,pixelsRight:Math.max(0,s.pageWidth-s.viewportWidth-s.scrollX)},o={root:null,selectorMap:new Map};if(t.includeDom!==!1)try{let c=new Bs(e,{paintOrderFiltering:!0,crossOriginIframes:!1}),l=await c.getPageState({includeScreenshot:!1,useCDPAccessibility:!0}),d=l.domTree,g=l.selectorMap;o={root:this.createSimplifiedNode(d,g),selectorMap:g,llmRepresentation:(m=[])=>c.formatDOMForLLM(d,0,!0,g)},await c.close()}catch(c){b.debug("DOM extraction failed:",c.message)}let a={domState:o,url:e.url(),title:await e.title(),tabs:await this.getAllTabs(),pageInfo:r,pixelsAbove:r.pixelsAbove,pixelsBelow:r.pixelsBelow,browserErrors:[],isPdfViewer:e.url().endsWith(".pdf")||e.url().includes("chrome-extension://")&&e.url().includes("pdf"),pendingNetworkRequests:[],paginationButtons:[]};if(t.includeScreenshot!==!1)try{let c=await e.screenshot({type:"png"});a.screenshot=c.toString("base64")}catch(c){b.debug("Screenshot failed:",c.message)}return a}switchToPage(e){return this.pages.has(e)?(this.currentPageId=e,b.log(`🔄 [BrowserSession] Switched to tab ${e}`),!0):(console.warn(`⚠️ [BrowserSession] Cannot switch to tab ${e} - not found`),!1)}getTabCount(){return this.pages.size}getAllTabIds(){return Array.from(this.pages.keys())}getCurrentPageId(){return this.currentPageId}hasTab(e){return this.pages.has(e)}generatePageId(){return`page_${Date.now()}_${Math.random().toString(36).substring(7)}`}setupPageListeners(e,t){e.on("close",()=>{this.pages.delete(t),this.pageSelectorMaps.delete(t);let n=this.pageCdpSessions.get(t);if(n&&(n.detach().catch(()=>{}),this.pageCdpSessions.delete(t)),this.currentPageId===t){let s=Array.from(this.pages.keys());this.currentPageId=s[0],this.cdpSession=null}b.log(`🗑️ [BrowserSession] Page ${t} closed, cleaned up resources`)}),e.on("framenavigated",n=>{if(n===e.mainFrame()){if(this.cdpSession=null,this.cachedSelectorMap.clear(),t){let s=this.pageSelectorMaps.get(t);s&&s.clear()}b.debug(`🔄 [framenavigated] Cleared cached state for page ${t||"main"}`)}}),e.on("domcontentloaded",()=>{if(this.cachedSelectorMap.clear(),t){let n=this.pageSelectorMaps.get(t);n&&n.clear()}b.debug(`🔄 [domcontentloaded] Cleared cached state for page ${t||"main"}`)}),e.on("request",n=>{let s=n.url();!s.startsWith("data:")&&!s.startsWith("blob:")&&this.pendingRequests.add(s)}),e.on("requestfinished",n=>{this.pendingRequests.delete(n.url())}),e.on("requestfailed",n=>{this.pendingRequests.delete(n.url())}),e.on("download",async n=>{try{let s=n.suggestedFilename(),r=this.options.downloadsPath?`${this.options.downloadsPath}/${s}`:s;await n.saveAs(r),this._downloadedFiles.push(r),b.log(`📥 Downloaded: ${r}`)}catch(s){console.error(`Failed to save download: ${s.message}`)}})}setNetworkIdleConfig(e){this.networkIdleConfig={...this.networkIdleConfig,...e}}getPendingRequestCount(){return this.pendingRequests.size}async waitForNetworkIdle(e){let t={idleTime:e?.idleTime??this.networkIdleConfig.idleTime,maxInflight:e?.maxInflight??this.networkIdleConfig.maxInflight,timeout:e?.timeout??this.networkIdleConfig.timeout,pollInterval:e?.pollInterval??this.networkIdleConfig.pollInterval},n=Date.now(),s=null;for(;;){let r=(Date.now()-n)/1e3;if(r>=t.timeout)return b.debug(`Network idle timeout after ${r.toFixed(2)}s`),!1;let o=this.pendingRequests.size;if(o<=t.maxInflight){if(s===null&&(s=Date.now()),(Date.now()-s)/1e3>=t.idleTime)return b.debug(`Network idle achieved: ${o} requests for ${t.idleTime}s`),!0}else s=null;await new Promise(a=>setTimeout(a,t.pollInterval*1e3))}}isNetworkIdle(e){let t=e??this.networkIdleConfig.maxInflight;return this.pendingRequests.size<=t}extractDomain(e){try{return new URL(e).hostname}catch{return""}}getSmartNavigationTimeout(e,t){let n=this.extractDomain(e),s=this.extractDomain(t),r=n===s&&n!=="",o=r?8e3:15e3;return b.debug(`Smart navigation timeout: ${o}ms (${r?"same":"different"} domain)`),o}async handleNavigateToUrl(e){try{let t=e.waitUntil||"load",n=e.newTab||!1,s=e.pageId,r=s?this.getPageOrCurrent(s):await this.ensurePage();if(!s){if(n){let c=r.url();this.isNewTabPage(c)&&(b.debug(`Already on new tab page (${c}), reusing instead of creating new tab`),n=!1)}if(!n){let c=this.findTabByUrl(e.url);if(c&&c!==this.currentPageId){b.debug(`URL already open in tab ${c}, switching to it`),this.currentPageId=c,r=await this.ensurePage(),this.eventBus.respondToEvent(e._eventId,null);return}}if(n){let c=await this.findOrCreateNewTab();c&&(r=c)}}let o=r.url(),a=e.timeoutMs??this.getSmartNavigationTimeout(o,e.url);await r.goto(e.url,{waitUntil:t,timeout:a}),await this.autoHandleCloudflareIfNeeded(r),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}isNewTabPage(e){return e==="about:blank"||e==="chrome://new-tab-page/"||e==="chrome://newtab/"||e.startsWith("chrome://newtab")}findTabByUrl(e){for(let[t,n]of this.pages.entries())if(n.url()===e)return t;return null}async findOrCreateNewTab(){for(let[e,t]of this.pages.entries())if(e!==this.currentPageId&&this.isNewTabPage(t.url()))return b.debug(`Found existing about:blank tab ${e}, reusing it`),this.currentPageId=e,t;if(this.context)try{let e=await this.context.newPage(),t=this.generatePageId();return this.pages.set(t,e),this.currentPageId=t,await this.injectStealthScripts(e),this.setupPageListeners(e,t),b.debug(`Created new tab ${t}`),e}catch(e){console.error("Failed to create new tab:",e)}return null}async handleClickElement(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage(),s=e.node,r=e.button||"left",o=(s.nodeName||"").toLowerCase(),a=(s.attributes?.type||"").toLowerCase();if(o==="select")throw new Error("Cannot click on <select> elements. Use dropdown options action instead.");if(o==="input"&&a==="file")throw new Error("Cannot click on file input element. Use upload_file action instead.");let c=t?await this.getCdpSessionForPage(t):await this.getCdpSession(),l={width:1280,height:720};try{let C=(await c.send("Page.getLayoutMetrics")).layoutViewport||{};l={width:C.clientWidth||n.viewportSize()?.width||1280,height:C.clientHeight||n.viewportSize()?.height||720},b.debug(`📐 [click] Viewport from CDP: ${l.width}x${l.height}`)}catch{b.debug("Failed to get layout metrics, using page.viewportSize()"),l=n.viewportSize()||{width:1280,height:720}}let d=s.backendNodeId;if(b.log(`🔍 [click] Using backendNodeId: ${d} for element: ${o}`),d&&d>0)try{let w=null,C=[];try{let v=await c.send("DOM.getContentQuads",{backendNodeId:d});v?.quads?.length>0&&(C=v.quads,b.debug(`Got ${C.length} quads from DOM.getContentQuads`))}catch(v){b.debug("getContentQuads failed:",v.message)}if(C.length===0)try{let v=await c.send("DOM.getBoxModel",{backendNodeId:d});if(v?.model?.content){let E=v.model.content;E.length>=8&&(C=[[E[0],E[1],E[2],E[3],E[4],E[5],E[6],E[7]]],b.debug("Got quad from DOM.getBoxModel"))}}catch(v){b.debug("getBoxModel failed:",v.message)}if(C.length===0)try{let E=(await c.send("DOM.resolveNode",{backendNodeId:d}))?.object?.objectId;if(E){let I=(await c.send("Runtime.callFunctionOn",{objectId:E,functionDeclaration:`function() {
473
+ `}}return a+="</svg>",a}var ji,ql=$(()=>{"use strict";dt();qs();ji={button:"#8FA3B8",input:"#A0B4C8",select:"#B8C5D0",a:"#7A92A8",textarea:"#C0CCD8",default:"#9CADB8"}});import{chromium as hh}from"patchright";import{v4 as fh}from"uuid";function bh(){let i=process.platform,e=process.env.HOME||process.env.USERPROFILE||"";return i==="darwin"?`${e}/Library/Application Support/Google/Chrome`:i==="win32"?`${process.env.LOCALAPPDATA}\\Google\\Chrome\\User Data`:`${e}/.config/google-chrome`}var en,zi=$(()=>{"use strict";dt();Bi();Wi();$l();so();oo();jl();qs();ql();en=class{id;eventBus;options;browser;context;pages=new Map;currentPageId;started=!1;cachedSelectorMap=new Map;cachedBrowserStateSummary=null;pageSelectorMaps=new Map;pendingRequests=new Set;networkIdleConfig={enabled:!0,idleTime:.5,maxInflight:2,timeout:10,pollInterval:.1};_downloadedFiles=[];cdpSession=null;pageCdpSessions=new Map;highlightsAdded=!1;constructor(e={}){this.id=e.id||fh(),this.options=e,this.eventBus=new no,this.registerEventHandlers()}registerEventHandlers(){this.eventBus.on(q.NAVIGATE_TO_URL,async e=>{await this.handleNavigateToUrl(e)}),this.eventBus.on(q.CLICK_ELEMENT,async e=>{await this.handleClickElement(e)}),this.eventBus.on(q.TYPE_TEXT,async e=>{await this.handleTypeText(e)}),this.eventBus.on(q.SCROLL,async e=>{await this.handleScroll(e)}),this.eventBus.on(q.BROWSER_STATE_REQUEST,async e=>{await this.handleBrowserStateRequest(e)}),this.eventBus.on(q.SCREENSHOT,async e=>{await this.handleScreenshot(e)}),this.eventBus.on(q.GO_BACK,async e=>{await this.handleGoBack(e)}),this.eventBus.on(q.GO_FORWARD,async e=>{await this.handleGoForward(e)}),this.eventBus.on(q.REFRESH,async e=>{await this.handleRefresh(e)}),this.eventBus.on(q.WAIT,async e=>{await this.handleWait(e)}),this.eventBus.on(q.SEND_KEYS,async e=>{await this.handleSendKeys(e)}),this.eventBus.on(q.UPLOAD_FILE,async e=>{await this.handleUploadFile(e)}),this.eventBus.on(q.GET_DROPDOWN_OPTIONS,async e=>{await this.handleGetDropdownOptions(e)}),this.eventBus.on(q.SELECT_DROPDOWN_OPTION,async e=>{await this.handleSelectDropdownOption(e)})}async start(){if(this.started)return;let e=["--disable-blink-features=AutomationControlled","--disable-infobars","--disable-dev-shm-usage","--disable-browser-side-navigation","--no-first-run","--no-default-browser-check","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--disable-component-update","--disable-features=TranslateUI"],t={headless:this.options.headless??!1,args:[...e,...this.options.args||[]],ignoreDefaultArgs:["--enable-automation"],channel:this.options.channel||"chrome"};this.options.executablePath&&(t.executablePath=this.options.executablePath,delete t.channel),this.options.disableSecurity&&t.args.push("--disable-web-security","--disable-features=IsolateOrigins,site-per-process");let n={acceptDownloads:this.options.acceptDownloads??!0};this.options.viewport?n.viewport=this.options.viewport:this.options.headless?n.viewport={width:1280,height:720}:n.viewport=null,this.options.userAgent&&(n.userAgent=this.options.userAgent),this.options.downloadsPath&&(n.downloadsPath=this.options.downloadsPath),this.options.storageState&&(n.storageState=this.options.storageState,b.log(`🍪 [BrowserSession] Restoring profile with ${this.options.storageState.cookies?.length||0} cookies`));let s=Gl(),r;this.options.useRealChromeProfile?(r=bh(),b.log(`🔐 [BrowserSession] Using REAL Chrome profile for maximum stealth: ${r}`),b.log("⚠️ [BrowserSession] Make sure Chrome is closed before starting!")):this.options.userDataDir?r=this.options.userDataDir:r=s.BROWSER_USE_DEFAULT_USER_DATA_DIR,b.log(`🗂️ [BrowserSession] Using persistent user data directory: ${r}`);let{storageState:o,...a}=n;if(this.context=await hh.launchPersistentContext(r,{...t,...a}),this.browser=this.context.browser?.()||null,o?.cookies&&o.cookies.length>0)try{await this.context.addCookies(o.cookies),b.log(`🍪 [BrowserSession] Applied ${o.cookies.length} imported cookies to persistent context`)}catch(d){console.warn(`⚠️ [BrowserSession] Failed to apply imported cookies: ${d.message}`)}let c=await this.context.newPage(),l=this.generatePageId();this.pages.set(l,c),this.currentPageId=l,await this.injectStealthScripts(c),this.setupPageListeners(c,l),this.context.on("close",async()=>{await this.saveStorageStateIfPossible()}),this.started=!0}async saveStorageState(){return this.saveStorageStateIfPossible()}async saveStorageStateIfPossible(){if(!this.context)return!1;try{let e=await this.context.storageState();if(e.cookies.length>0||e.origins.length>0){let t={cookies:e.cookies,origins:e.origins,importedAt:new Date().toISOString(),sourceType:"running-chrome",cookieCount:e.cookies.length,originCount:e.origins.length};return await Fl(t,kn(),!0),b.log(`[BrowserSession] Saved ${e.cookies.length} cookies`),!0}}catch(e){b.debug("[BrowserSession] Could not save storage state:",e.message)}return!1}async stop(){this.started&&(await this.saveStorageStateIfPossible(),this.context&&await this.context.close(),this.browser&&await this.browser.close(),this.pages.clear(),this.started=!1)}async injectStealthScripts(e){try{await e.addInitScript(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}}),Object.defineProperty(navigator,"plugins",{get:()=>{let r=[{name:"Chrome PDF Plugin",filename:"internal-pdf-viewer",description:"Portable Document Format"},{name:"Chrome PDF Viewer",filename:"mhjfbmdgcfjbbpaeojofohoefgiehjai",description:""},{name:"Native Client",filename:"internal-nacl-plugin",description:""}];return r.item=o=>r[o]||null,r.namedItem=o=>r.find(a=>a.name===o)||null,r.refresh=()=>{},r}}),Object.defineProperty(navigator,"languages",{get:()=>["en-US","en"]}),Object.getOwnPropertyNames(window).filter(r=>r.startsWith("cdc_")||r.startsWith("$cdc_")).forEach(r=>{try{delete window[r]}catch{}}),window.chrome||(window.chrome={}),window.chrome.runtime||(window.chrome.runtime={connect:()=>{},sendMessage:()=>{},onMessage:{addListener:()=>{}}});let n=navigator.permissions?.query?.bind(navigator.permissions);n&&(navigator.permissions.query=r=>r.name==="notifications"?Promise.resolve({state:"denied",onchange:null}):n(r));let s=console.debug;console.debug=function(...r){if(!r.some(o=>String(o).includes("Runtime.enable")))return s.apply(console,r)}}),b.log("🛡️ [BrowserSession] Stealth scripts injected")}catch(t){console.warn(`[BrowserSession] Failed to inject stealth scripts: ${t.message}`)}}async handleCloudflareTurnstile(e,t){let n=e||this.getCurrentPage(),s=t?.timeout??1e4,r=t?.delayBeforeClick??2e3;try{b.log("🔐 [BrowserSession] Checking for Cloudflare Turnstile...");let o=['iframe[src*="challenges.cloudflare.com"]','iframe[src*="turnstile"]',".cf-turnstile iframe","[data-turnstile-callback] iframe"],a=null;for(let m of o)try{let p=await n.waitForSelector(m,{timeout:3e3});if(p){a=p;break}}catch{}if(!a)return b.log("🔐 [BrowserSession] No Turnstile detected, continuing..."),!1;b.log("🔐 [BrowserSession] Turnstile detected, waiting before click..."),await new Promise(m=>setTimeout(m,r+Math.random()*1e3));let c=await a.boundingBox();if(!c)return console.warn("🔐 [BrowserSession] Could not get Turnstile bounding box"),!1;let l=c.x+25+Math.random()*10,d=c.y+c.height/2+(Math.random()-.5)*10;await this.humanLikeMouseMove(n,l,d),await new Promise(m=>setTimeout(m,100+Math.random()*200)),await n.mouse.click(l,d),b.log("🔐 [BrowserSession] Clicked Turnstile checkbox"),await new Promise(m=>setTimeout(m,3e3));let g=await n.evaluate(()=>[document.querySelector('[data-turnstile-success="true"]'),document.querySelector(".cf-turnstile-success"),document.querySelector('input[name="cf-turnstile-response"]')].some(p=>p!==null));return g?b.log("✅ [BrowserSession] Turnstile challenge passed!"):console.warn("⚠️ [BrowserSession] Turnstile may require manual verification"),g}catch(o){return console.warn(`[BrowserSession] Turnstile handling failed: ${o.message}`),!1}}async humanLikeMouseMove(e,t,n){let s=e.viewportSize()||{width:1280,height:720},r=s.width/2,o=s.height/2,a=20+Math.floor(Math.random()*10),c=r+(t-r)*.5+(Math.random()-.5)*100,l=o+(n-o)*.5+(Math.random()-.5)*100;for(let d=0;d<=a;d++){let g=d/a,m=Math.pow(1-g,2)*r+2*(1-g)*g*c+Math.pow(g,2)*t,p=Math.pow(1-g,2)*o+2*(1-g)*g*l+Math.pow(g,2)*n;await e.mouse.move(m,p);let h=5+Math.random()*15*(1-Math.abs(g-.5)*2);await new Promise(f=>setTimeout(f,h))}}async navigateWithCloudflareBypass(e,t){let n=t||this.getCurrentPage();await n.goto(e,{waitUntil:"domcontentloaded"}),await new Promise(r=>setTimeout(r,2e3)),await n.evaluate(()=>{let r=document.title.toLowerCase(),o=document.body?.innerText?.toLowerCase()||"";return r.includes("just a moment")||r.includes("attention required")||o.includes("checking your browser")||o.includes("verify you are human")||document.querySelector('iframe[src*="challenges.cloudflare.com"]')!==null})&&(b.log("🔐 [BrowserSession] Cloudflare challenge detected, attempting bypass..."),await this.handleCloudflareTurnstile(n),await new Promise(o=>setTimeout(o,3e3)),await n.evaluate(()=>document.title.toLowerCase().includes("just a moment"))&&console.warn("⚠️ [BrowserSession] Still on Cloudflare challenge page - may need manual intervention"))}async autoHandleCloudflareIfNeeded(e){try{await e.evaluate(()=>{let n=document.title.toLowerCase(),s=document.body?.innerText?.substring(0,500).toLowerCase()||"";return n.includes("just a moment")||n.includes("attention required")||n.includes("please wait")||s.includes("checking your browser")||s.includes("verify you are human")||s.includes("enable javascript and cookies")||document.querySelector('iframe[src*="challenges.cloudflare.com"]')!==null||document.querySelector(".cf-turnstile")!==null})&&(b.log("🔐 [BrowserSession] Cloudflare challenge auto-detected"),await this.handleCloudflareTurnstile(e))}catch{}}getCurrentPage(){if(this.currentPageId&&this.pages.has(this.currentPageId))return this.pages.get(this.currentPageId);let e=Array.from(this.pages.entries());if(e.length>0){let[t,n]=e[e.length-1];return console.warn(`🔄 Current page closed, switching to fallback page ${t}`),this.currentPageId=t,n}throw new Error("No active page")}async ensurePage(){try{return this.getCurrentPage()}catch{if(this.context){console.warn("🔄 No active page, creating new one...");let e=await this.context.newPage(),t=this.generatePageId();return this.pages.set(t,e),this.currentPageId=t,await this.injectStealthScripts(e),this.setupPageListeners(e,t),e}throw new Error("No active page and no browser context available")}}getPage(e){return this.pages.get(e)}getPageOrCurrent(e){return e&&this.pages.has(e)?this.pages.get(e):this.getCurrentPage()}async createTabForAgent(e){if(!this.context)throw new Error("Browser context not available - call start() first");let t=await this.context.newPage(),n=e?`agent_${e}_${Date.now()}`:this.generatePageId();return this.pages.set(n,t),await this.injectStealthScripts(t),this.setupPageListeners(t,n),b.log(`🆕 [BrowserSession] Created new tab ${n} for agent${e?` ${e}`:""}`),b.log(`📊 [BrowserSession] Total tabs: ${this.pages.size}`),{pageId:n,page:t}}async getStateForPage(e,t={}){let n=this.pages.get(e);if(!n)throw new Error(`Page ${e} not found`);let s=await this.getStateFromPage(n,t);return s.domState?.selectorMap&&this.pageSelectorMaps.set(e,s.domState.selectorMap),s}getSelectorMapForPage(e){let t=this.pageSelectorMaps.get(e);return t||this.cachedSelectorMap}getElementByIndexForPage(e,t){let n=this.getSelectorMapForPage(e);return n.has(t)?n.get(t):null}async waitForPageReadiness(e,t={}){let n=t.timeout??5e3,s=t.minElements??10,r=t.stabilityChecks??2,o=Date.now(),a="unknown",c=0,l=0,d=0;for(;Date.now()-o<n;)try{let g=await e.evaluate(()=>{let p=document.readyState,h=performance.getEntriesByType("resource").filter(C=>C.responseEnd===0||C.transferSize===0&&C.decodedBodySize===0&&!C.name.startsWith("data:")).length,y=document.querySelectorAll('a, button, input, select, textarea, [role="button"], [onclick], [tabindex]').length,T=!!(document.querySelector('[class*="loading"]')||document.querySelector('[class*="skeleton"]')||document.querySelector('[class*="spinner"]')||document.querySelector('[class*="Spinner"]')||document.querySelector('[class*="Loading"]')||document.querySelector('[class*="Skeleton"]')||document.querySelector('[aria-busy="true"]')||document.querySelector('[data-loading="true"]')||document.querySelector(".placeholder"));return{readyState:p,pendingRequests:h,elementCount:y,hasLoadingIndicator:T}});if(g.elementCount===l&&g.elementCount>0?d++:d=0,a=g.readyState,c=g.pendingRequests,l=g.elementCount,(g.readyState==="complete"||g.readyState==="interactive"&&d>=r)&&g.pendingRequests<=2&&g.elementCount>=s&&!g.hasLoadingIndicator&&d>=r)return b.debug(`✅ Page ready: readyState=${g.readyState}, pending=${g.pendingRequests}, elements=${g.elementCount}, stable=${d}`),{ready:!0,pendingRequests:g.pendingRequests,readyState:g.readyState,elementCount:g.elementCount};await new Promise(p=>setTimeout(p,100))}catch{d=0,await new Promise(m=>setTimeout(m,100))}return b.debug(`⚠️ Page readiness timeout: readyState=${a}, pending=${c}, elements=${l}, stable=${d}`),{ready:!1,pendingRequests:c,readyState:a,elementCount:l}}async getStateFromPage(e,t={}){let n=await this.waitForPageReadiness(e,{timeout:5e3,minElements:5});n.ready||(b.debug(`⚠️ Proceeding with DOM extraction despite page not fully ready (readyState=${n.readyState})`),n.pendingRequests>0&&await new Promise(c=>setTimeout(c,300)));let s=await e.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,pageWidth:document.documentElement.scrollWidth,pageHeight:document.documentElement.scrollHeight})),r={viewportWidth:s.viewportWidth,viewportHeight:s.viewportHeight,pageWidth:s.pageWidth,pageHeight:s.pageHeight,scrollX:s.scrollX,scrollY:s.scrollY,pixelsAbove:s.scrollY,pixelsBelow:Math.max(0,s.pageHeight-s.viewportHeight-s.scrollY),pixelsLeft:s.scrollX,pixelsRight:Math.max(0,s.pageWidth-s.viewportWidth-s.scrollX)},o={root:null,selectorMap:new Map};if(t.includeDom!==!1)try{let c=new Ws(e,{paintOrderFiltering:!0,crossOriginIframes:!1}),l=await c.getPageState({includeScreenshot:!1,useCDPAccessibility:!0}),d=l.domTree,g=l.selectorMap;o={root:this.createSimplifiedNode(d,g),selectorMap:g,llmRepresentation:(m=[])=>c.formatDOMForLLM(d,0,!0,g)},await c.close()}catch(c){b.debug("DOM extraction failed:",c.message)}let a={domState:o,url:e.url(),title:await e.title(),tabs:await this.getAllTabs(),pageInfo:r,pixelsAbove:r.pixelsAbove,pixelsBelow:r.pixelsBelow,browserErrors:[],isPdfViewer:e.url().endsWith(".pdf")||e.url().includes("chrome-extension://")&&e.url().includes("pdf"),pendingNetworkRequests:[],paginationButtons:[]};if(t.includeScreenshot!==!1)try{let c=await e.screenshot({type:"png"});a.screenshot=c.toString("base64")}catch(c){b.debug("Screenshot failed:",c.message)}return a}switchToPage(e){return this.pages.has(e)?(this.currentPageId=e,b.log(`🔄 [BrowserSession] Switched to tab ${e}`),!0):(console.warn(`⚠️ [BrowserSession] Cannot switch to tab ${e} - not found`),!1)}getTabCount(){return this.pages.size}getAllTabIds(){return Array.from(this.pages.keys())}getCurrentPageId(){return this.currentPageId}hasTab(e){return this.pages.has(e)}generatePageId(){return`page_${Date.now()}_${Math.random().toString(36).substring(7)}`}setupPageListeners(e,t){e.on("close",()=>{this.pages.delete(t),this.pageSelectorMaps.delete(t);let n=this.pageCdpSessions.get(t);if(n&&(n.detach().catch(()=>{}),this.pageCdpSessions.delete(t)),this.currentPageId===t){let s=Array.from(this.pages.keys());this.currentPageId=s[0],this.cdpSession=null}b.log(`🗑️ [BrowserSession] Page ${t} closed, cleaned up resources`)}),e.on("framenavigated",n=>{if(n===e.mainFrame()){if(this.cdpSession=null,this.cachedSelectorMap.clear(),t){let s=this.pageSelectorMaps.get(t);s&&s.clear()}b.debug(`🔄 [framenavigated] Cleared cached state for page ${t||"main"}`)}}),e.on("domcontentloaded",()=>{if(this.cachedSelectorMap.clear(),t){let n=this.pageSelectorMaps.get(t);n&&n.clear()}b.debug(`🔄 [domcontentloaded] Cleared cached state for page ${t||"main"}`)}),e.on("request",n=>{let s=n.url();!s.startsWith("data:")&&!s.startsWith("blob:")&&this.pendingRequests.add(s)}),e.on("requestfinished",n=>{this.pendingRequests.delete(n.url())}),e.on("requestfailed",n=>{this.pendingRequests.delete(n.url())}),e.on("download",async n=>{try{let s=n.suggestedFilename(),r=this.options.downloadsPath?`${this.options.downloadsPath}/${s}`:s;await n.saveAs(r),this._downloadedFiles.push(r),b.log(`📥 Downloaded: ${r}`)}catch(s){console.error(`Failed to save download: ${s.message}`)}})}setNetworkIdleConfig(e){this.networkIdleConfig={...this.networkIdleConfig,...e}}getPendingRequestCount(){return this.pendingRequests.size}async waitForNetworkIdle(e){let t={idleTime:e?.idleTime??this.networkIdleConfig.idleTime,maxInflight:e?.maxInflight??this.networkIdleConfig.maxInflight,timeout:e?.timeout??this.networkIdleConfig.timeout,pollInterval:e?.pollInterval??this.networkIdleConfig.pollInterval},n=Date.now(),s=null;for(;;){let r=(Date.now()-n)/1e3;if(r>=t.timeout)return b.debug(`Network idle timeout after ${r.toFixed(2)}s`),!1;let o=this.pendingRequests.size;if(o<=t.maxInflight){if(s===null&&(s=Date.now()),(Date.now()-s)/1e3>=t.idleTime)return b.debug(`Network idle achieved: ${o} requests for ${t.idleTime}s`),!0}else s=null;await new Promise(a=>setTimeout(a,t.pollInterval*1e3))}}isNetworkIdle(e){let t=e??this.networkIdleConfig.maxInflight;return this.pendingRequests.size<=t}extractDomain(e){try{return new URL(e).hostname}catch{return""}}getSmartNavigationTimeout(e,t){let n=this.extractDomain(e),s=this.extractDomain(t),r=n===s&&n!=="",o=r?8e3:15e3;return b.debug(`Smart navigation timeout: ${o}ms (${r?"same":"different"} domain)`),o}async handleNavigateToUrl(e){try{let t=e.waitUntil||"load",n=e.newTab||!1,s=e.pageId,r=s?this.getPageOrCurrent(s):await this.ensurePage();if(!s){if(n){let c=r.url();this.isNewTabPage(c)&&(b.debug(`Already on new tab page (${c}), reusing instead of creating new tab`),n=!1)}if(!n){let c=this.findTabByUrl(e.url);if(c&&c!==this.currentPageId){b.debug(`URL already open in tab ${c}, switching to it`),this.currentPageId=c,r=await this.ensurePage(),this.eventBus.respondToEvent(e._eventId,null);return}}if(n){let c=await this.findOrCreateNewTab();c&&(r=c)}}let o=r.url(),a=e.timeoutMs??this.getSmartNavigationTimeout(o,e.url);await r.goto(e.url,{waitUntil:t,timeout:a}),await this.autoHandleCloudflareIfNeeded(r),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}isNewTabPage(e){return e==="about:blank"||e==="chrome://new-tab-page/"||e==="chrome://newtab/"||e.startsWith("chrome://newtab")}findTabByUrl(e){for(let[t,n]of this.pages.entries())if(n.url()===e)return t;return null}async findOrCreateNewTab(){for(let[e,t]of this.pages.entries())if(e!==this.currentPageId&&this.isNewTabPage(t.url()))return b.debug(`Found existing about:blank tab ${e}, reusing it`),this.currentPageId=e,t;if(this.context)try{let e=await this.context.newPage(),t=this.generatePageId();return this.pages.set(t,e),this.currentPageId=t,await this.injectStealthScripts(e),this.setupPageListeners(e,t),b.debug(`Created new tab ${t}`),e}catch(e){console.error("Failed to create new tab:",e)}return null}async handleClickElement(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage(),s=e.node,r=e.button||"left",o=(s.nodeName||"").toLowerCase(),a=(s.attributes?.type||"").toLowerCase();if(o==="select")throw new Error("Cannot click on <select> elements. Use dropdown options action instead.");if(o==="input"&&a==="file")throw new Error("Cannot click on file input element. Use upload_file action instead.");let c=t?await this.getCdpSessionForPage(t):await this.getCdpSession(),l={width:1280,height:720};try{let E=(await c.send("Page.getLayoutMetrics")).layoutViewport||{};l={width:E.clientWidth||n.viewportSize()?.width||1280,height:E.clientHeight||n.viewportSize()?.height||720},b.debug(`📐 [click] Viewport from CDP: ${l.width}x${l.height}`)}catch{b.debug("Failed to get layout metrics, using page.viewportSize()"),l=n.viewportSize()||{width:1280,height:720}}let d=s.backendNodeId;if(b.log(`🔍 [click] Using backendNodeId: ${d} for element: ${o}`),d&&d>0)try{let w=null,E=[];try{let v=await c.send("DOM.getContentQuads",{backendNodeId:d});v?.quads?.length>0&&(E=v.quads,b.debug(`Got ${E.length} quads from DOM.getContentQuads`))}catch(v){b.debug("getContentQuads failed:",v.message)}if(E.length===0)try{let v=await c.send("DOM.getBoxModel",{backendNodeId:d});if(v?.model?.content){let x=v.model.content;x.length>=8&&(E=[[x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7]]],b.debug("Got quad from DOM.getBoxModel"))}}catch(v){b.debug("getBoxModel failed:",v.message)}if(E.length===0)try{let x=(await c.send("DOM.resolveNode",{backendNodeId:d}))?.object?.objectId;if(x){let I=(await c.send("Runtime.callFunctionOn",{objectId:x,functionDeclaration:`function() {
474
474
  const rect = this.getBoundingClientRect();
475
475
  return { x: rect.left, y: rect.top, width: rect.width, height: rect.height };
476
- }`,returnByValue:!0}))?.result?.value;if(I){let P=I.x,R=I.y,$=I.width,D=I.height;C=[[P,R,P+$,R,P+$,R+D,P,R+D]],b.debug("Got quad from getBoundingClientRect")}}}catch(v){b.debug("JS getBoundingClientRect failed:",v.message)}if(C.length===0){b.debug("Could not get element geometry from any method, falling back to JavaScript click");try{await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_no_quads"});return}catch(v){b.debug("JS click for no-quads case failed:",v.message)}}if(C.length>0){let v=null,E=0;for(let P of C){if(P.length<8)continue;let R=[P[0],P[2],P[4],P[6]],$=[P[1],P[3],P[5],P[7]],D=Math.min(...R),_=Math.max(...R),N=Math.min(...$),k=Math.max(...$);if(_<0||k<0||D>l.width||N>l.height)continue;let M=Math.max(0,D),L=Math.min(l.width,_),B=Math.max(0,N),H=Math.min(l.height,k),V=L-M,le=H-B,W=V*le;W>E&&(E=W,v=P)}if(!v){b.debug("🔄 [click] No visible quad found, scrolling element into view first...");try{await c.send("DOM.scrollIntoViewIfNeeded",{backendNodeId:d}),await new Promise(P=>setTimeout(P,100))}catch{}try{let P=await c.send("DOM.getContentQuads",{backendNodeId:d});if(P?.quads?.length>0){C=P.quads;for(let R of C){if(R.length<8)continue;let $=[R[0],R[2],R[4],R[6]],D=[R[1],R[3],R[5],R[7]],_=Math.min(...$),N=Math.max(...$),k=Math.min(...D),M=Math.max(...D);if(N<0||M<0||_>l.width||k>l.height)continue;let L=Math.max(0,_),B=Math.min(l.width,N),H=Math.max(0,k),V=Math.min(l.height,M),le=(B-L)*(V-H);le>E&&(E=le,v=R)}}}catch{}if(!v){b.debug("⚠️ [click] Still no visible quad after scroll, falling back to JS click"),await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_no_visible_quad"});return}}let S=(v[0]+v[2]+v[4]+v[6])/4,I=(v[1]+v[3]+v[5]+v[7])/4;S=Math.max(0,Math.min(l.width-1,S)),I=Math.max(0,Math.min(l.height-1,I)),w={x:S,y:I},b.log(`🖱️ [click] Calculated center: (${S.toFixed(1)}, ${I.toFixed(1)})`)}if(w)try{await c.send("DOM.scrollIntoViewIfNeeded",{backendNodeId:d}),await new Promise(v=>setTimeout(v,50));try{let v=await c.send("DOM.getContentQuads",{backendNodeId:d});if(v?.quads?.length>0){let E=v.quads[0];if(E.length>=8){let S=(E[0]+E[2]+E[4]+E[6])/4,I=(E[1]+E[3]+E[5]+E[7])/4;S>=0&&S<=l.width&&I>=0&&I<=l.height?(w={x:S,y:I},b.debug(`📍 [click] Updated coordinates after scroll: (${S.toFixed(1)}, ${I.toFixed(1)})`)):b.debug("⚠️ [click] Post-scroll coords out of viewport, keeping pre-scroll coords")}}}catch{b.debug("⚠️ [click] Re-fetch failed, keeping pre-scroll coords")}}catch{}if(w){if(await this.checkElementOcclusionCDP(c,d,w.x,w.y)){b.debug("🚫 Element is occluded, falling back to JavaScript click"),await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_occlusion"});return}await c.send("Input.dispatchMouseEvent",{type:"mouseMoved",x:w.x,y:w.y}),await new Promise(S=>setTimeout(S,50));let E=!1;try{await Promise.race([c.send("Input.dispatchMouseEvent",{type:"mousePressed",x:w.x,y:w.y,button:r,clickCount:1}),new Promise((S,I)=>setTimeout(()=>I(new Error("mousePressed timeout")),3e3))]),E=!0}catch(S){b.debug("mousePressed timed out (possibly dialog):",S.message)}E&&await new Promise(S=>setTimeout(S,80));try{await Promise.race([c.send("Input.dispatchMouseEvent",{type:"mouseReleased",x:w.x,y:w.y,button:r,clickCount:1}),new Promise((S,I)=>setTimeout(()=>I(new Error("mouseReleased timeout")),5e3))])}catch(S){b.debug("mouseReleased timed out:",S.message)}this.eventBus.respondToEvent(e._eventId,{success:!0,method:"cdp_click",backendNodeId:d,coordinates:w});return}}catch(w){b.debug("CDP click failed, falling back to JavaScript click:",w.message);try{await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_cdp_error"});return}catch(C){b.debug("JS click also failed:",C.message)}}finally{try{await(t?await this.getCdpSessionForPage(t):await this.getCdpSession()).send("Runtime.runIfWaitingForDebugger",{})}catch{}}if(!s.absolutePosition){b.debug("No coordinates available, attempting final JS click fallback"),await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click"});return}let{x:g,y:m,width:p,height:h}=s.absolutePosition,f=g+(p||0)/2,y=m+(h||0)/2;if(f<0||y<0||f>l.width||y>l.height){b.debug("Element out of viewport, scrolling into view");try{let w=Math.max(0,m-l.height/2);await n.evaluate(v=>window.scrollTo(0,v),w),await new Promise(v=>setTimeout(v,100));let C=await n.evaluate(()=>({x:window.scrollX,y:window.scrollY}));y=m-C.y+(h||0)/2,f=g-C.x+(p||0)/2}catch(w){b.debug("Failed to scroll element into view:",w)}}f=Math.max(1,Math.min(l.width-1,f)),y=Math.max(1,Math.min(l.height-1,y));let x=!1;if(d&&d>0&&(x=await this.checkElementOcclusionCDP(c,d,f,y)),x){b.debug("Element is occluded, falling back to JavaScript click"),await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click"});return}await n.mouse.move(f,y),await new Promise(w=>setTimeout(w,50)),await n.mouse.click(f,y,{button:r}),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"mouse_click",coordinates:{x:f,y}})}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async checkElementOcclusion(e,t,n,s){try{return await e.evaluate(({x:o,y:a,nodeId:c,nodeName:l})=>{let d=document.elementFromPoint(o,a);if(!d)return!0;let g=l?.toUpperCase()||"";return!(d.tagName===g||d.closest(g)||d.querySelector(g))},{x:n,y:s,nodeId:t.nodeId,nodeName:t.nodeName})}catch{return!1}}async checkElementOcclusionCDP(e,t,n,s){try{let o=(await e.send("DOM.resolveNode",{backendNodeId:t}))?.object?.objectId;if(!o)return b.debug("Could not resolve target element, assuming occluded"),!0;let c=(await e.send("Runtime.callFunctionOn",{objectId:o,functionDeclaration:`
476
+ }`,returnByValue:!0}))?.result?.value;if(I){let D=I.x,M=I.y,_=I.width,F=I.height;E=[[D,M,D+_,M,D+_,M+F,D,M+F]],b.debug("Got quad from getBoundingClientRect")}}}catch(v){b.debug("JS getBoundingClientRect failed:",v.message)}if(E.length===0){b.debug("Could not get element geometry from any method, falling back to JavaScript click");try{await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_no_quads"});return}catch(v){b.debug("JS click for no-quads case failed:",v.message)}}if(E.length>0){let v=null,x=0;for(let D of E){if(D.length<8)continue;let M=[D[0],D[2],D[4],D[6]],_=[D[1],D[3],D[5],D[7]],F=Math.min(...M),R=Math.max(...M),N=Math.min(..._),k=Math.max(..._);if(R<0||k<0||F>l.width||N>l.height)continue;let P=Math.max(0,F),B=Math.min(l.width,R),L=Math.max(0,N),W=Math.min(l.height,k),G=B-P,Y=W-L,H=G*Y;H>x&&(x=H,v=D)}if(!v){b.debug("🔄 [click] No visible quad found, scrolling element into view first...");try{await c.send("DOM.scrollIntoViewIfNeeded",{backendNodeId:d}),await new Promise(D=>setTimeout(D,100))}catch{}try{let D=await c.send("DOM.getContentQuads",{backendNodeId:d});if(D?.quads?.length>0){E=D.quads;for(let M of E){if(M.length<8)continue;let _=[M[0],M[2],M[4],M[6]],F=[M[1],M[3],M[5],M[7]],R=Math.min(..._),N=Math.max(..._),k=Math.min(...F),P=Math.max(...F);if(N<0||P<0||R>l.width||k>l.height)continue;let B=Math.max(0,R),L=Math.min(l.width,N),W=Math.max(0,k),G=Math.min(l.height,P),Y=(L-B)*(G-W);Y>x&&(x=Y,v=M)}}}catch{}if(!v){b.debug("⚠️ [click] Still no visible quad after scroll, falling back to JS click"),await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_no_visible_quad"});return}}let S=(v[0]+v[2]+v[4]+v[6])/4,I=(v[1]+v[3]+v[5]+v[7])/4;S=Math.max(0,Math.min(l.width-1,S)),I=Math.max(0,Math.min(l.height-1,I)),w={x:S,y:I},b.log(`🖱️ [click] Calculated center: (${S.toFixed(1)}, ${I.toFixed(1)})`)}if(w)try{await c.send("DOM.scrollIntoViewIfNeeded",{backendNodeId:d}),await new Promise(v=>setTimeout(v,50));try{let v=await c.send("DOM.getContentQuads",{backendNodeId:d});if(v?.quads?.length>0){let x=v.quads[0];if(x.length>=8){let S=(x[0]+x[2]+x[4]+x[6])/4,I=(x[1]+x[3]+x[5]+x[7])/4;S>=0&&S<=l.width&&I>=0&&I<=l.height?(w={x:S,y:I},b.debug(`📍 [click] Updated coordinates after scroll: (${S.toFixed(1)}, ${I.toFixed(1)})`)):b.debug("⚠️ [click] Post-scroll coords out of viewport, keeping pre-scroll coords")}}}catch{b.debug("⚠️ [click] Re-fetch failed, keeping pre-scroll coords")}}catch{}if(w){if(await this.checkElementOcclusionCDP(c,d,w.x,w.y)){b.debug("🚫 Element is occluded, falling back to JavaScript click"),await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_occlusion"});return}await c.send("Input.dispatchMouseEvent",{type:"mouseMoved",x:w.x,y:w.y}),await new Promise(S=>setTimeout(S,50));let x=!1;try{await Promise.race([c.send("Input.dispatchMouseEvent",{type:"mousePressed",x:w.x,y:w.y,button:r,clickCount:1}),new Promise((S,I)=>setTimeout(()=>I(new Error("mousePressed timeout")),3e3))]),x=!0}catch(S){b.debug("mousePressed timed out (possibly dialog):",S.message)}x&&await new Promise(S=>setTimeout(S,80));try{await Promise.race([c.send("Input.dispatchMouseEvent",{type:"mouseReleased",x:w.x,y:w.y,button:r,clickCount:1}),new Promise((S,I)=>setTimeout(()=>I(new Error("mouseReleased timeout")),5e3))])}catch(S){b.debug("mouseReleased timed out:",S.message)}this.eventBus.respondToEvent(e._eventId,{success:!0,method:"cdp_click",backendNodeId:d,coordinates:w});return}}catch(w){b.debug("CDP click failed, falling back to JavaScript click:",w.message);try{await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_cdp_error"});return}catch(E){b.debug("JS click also failed:",E.message)}}finally{try{await(t?await this.getCdpSessionForPage(t):await this.getCdpSession()).send("Runtime.runIfWaitingForDebugger",{})}catch{}}if(!s.absolutePosition){b.debug("No coordinates available, attempting final JS click fallback"),await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click"});return}let{x:g,y:m,width:p,height:h}=s.absolutePosition,f=g+(p||0)/2,y=m+(h||0)/2;if(f<0||y<0||f>l.width||y>l.height){b.debug("Element out of viewport, scrolling into view");try{let w=Math.max(0,m-l.height/2);await n.evaluate(v=>window.scrollTo(0,v),w),await new Promise(v=>setTimeout(v,100));let E=await n.evaluate(()=>({x:window.scrollX,y:window.scrollY}));y=m-E.y+(h||0)/2,f=g-E.x+(p||0)/2}catch(w){b.debug("Failed to scroll element into view:",w)}}f=Math.max(1,Math.min(l.width-1,f)),y=Math.max(1,Math.min(l.height-1,y));let C=!1;if(d&&d>0&&(C=await this.checkElementOcclusionCDP(c,d,f,y)),C){b.debug("Element is occluded, falling back to JavaScript click"),await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click"});return}await n.mouse.move(f,y),await new Promise(w=>setTimeout(w,50)),await n.mouse.click(f,y,{button:r}),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"mouse_click",coordinates:{x:f,y}})}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async checkElementOcclusion(e,t,n,s){try{return await e.evaluate(({x:o,y:a,nodeId:c,nodeName:l})=>{let d=document.elementFromPoint(o,a);if(!d)return!0;let g=l?.toUpperCase()||"";return!(d.tagName===g||d.closest(g)||d.querySelector(g))},{x:n,y:s,nodeId:t.nodeId,nodeName:t.nodeName})}catch{return!1}}async checkElementOcclusionCDP(e,t,n,s){try{let o=(await e.send("DOM.resolveNode",{backendNodeId:t}))?.object?.objectId;if(!o)return b.debug("Could not resolve target element, assuming occluded"),!0;let c=(await e.send("Runtime.callFunctionOn",{objectId:o,functionDeclaration:`
477
477
  function(x, y) {
478
478
  const getElementInfo = (el) => {
479
479
  return {
@@ -564,7 +564,7 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
564
564
  } catch (e) {
565
565
  return {success: false, error: e.message};
566
566
  }
567
- }`,returnByValue:!0});if(c.result?.value?.success)return b.debug(`Scrolled ${c.result.value.element} by ${c.result.value.scrolled}px`),!0}}catch(a){b.debug("Failed to scroll element container:",a)}return!1}catch(s){return b.debug("scrollElementContainer error:",s),!1}}async handleScreenshot(e){try{let t=e.pageId,r=(await(t?this.getPageOrCurrent(t):await this.ensurePage()).screenshot({fullPage:e.fullPage,clip:e.clip,type:"png"})).toString("base64");this.eventBus.respondToEvent(e._eventId,r)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleBrowserStateRequest(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage(),s=await n.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,pageWidth:document.documentElement.scrollWidth,pageHeight:document.documentElement.scrollHeight})),r={viewportWidth:s.viewportWidth,viewportHeight:s.viewportHeight,pageWidth:s.pageWidth,pageHeight:s.pageHeight,scrollX:s.scrollX,scrollY:s.scrollY,pixelsAbove:s.scrollY,pixelsBelow:Math.max(0,s.pageHeight-s.viewportHeight-s.scrollY),pixelsLeft:s.scrollX,pixelsRight:Math.max(0,s.pageWidth-s.viewportWidth-s.scrollX)},o={root:null,selectorMap:new Map};if(e.includeDom!==!1)try{let c=new Bs(n,{paintOrderFiltering:!0,crossOriginIframes:!1}),l=await c.getPageState({includeScreenshot:!1,useCDPAccessibility:!0});this.updateCachedSelectorMap(l.selectorMap);let d=l.domTree,g=l.selectorMap;o={root:this.createSimplifiedNode(d,g),selectorMap:g,llmRepresentation:(m=[])=>c.formatDOMForLLM(d,0,!0,g)},await c.close()}catch(c){b.debug("DOM extraction failed:",c.message)}let a={domState:o,url:n.url(),title:await n.title(),tabs:await this.getAllTabs(),pageInfo:r,pixelsAbove:r.pixelsAbove,pixelsBelow:r.pixelsBelow,browserErrors:[],isPdfViewer:n.url().endsWith(".pdf")||n.url().includes("chrome-extension://")&&n.url().includes("pdf"),pendingNetworkRequests:[],paginationButtons:[]};if(e.includeScreenshot!==!1){let l=(await n.screenshot({type:"png"})).toString("base64");if(o.selectorMap&&o.selectorMap.size>0)try{let d=await n.evaluate(()=>window.devicePixelRatio||1);l=await zl(l,o.selectorMap,d,!0)}catch(d){b.debug("Screenshot highlighting failed, using original:",d.message)}a.screenshot=l}this.cachedBrowserStateSummary=a,this.eventBus.respondToEvent(e._eventId,a)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}createSimplifiedNode(e,t){if(!e||e.length===0)return null;let n=r=>{if(!r)return null;let o=r.backendNodeId||0,c={isInteractive:t.has(o),isShadowHost:r.isShadowHost||!1,isNew:!1,shouldDisplay:!0,ignoredByPaintOrder:!1,excludedByParent:!1,isCompoundComponent:!1,children:[],originalNode:{nodeId:r.nodeId||0,backendNodeId:o,sessionId:r.sessionId||"",frameId:r.frameId||"",targetId:r.targetId||"",nodeType:r.nodeType||1,nodeName:r.nodeName||"",nodeValue:r.nodeValue||"",attributes:r.attributes||{}}};if(r.children&&Array.isArray(r.children))for(let l of r.children){let d=n(l);d&&c.children.push(d)}if(r.shadowRoots&&Array.isArray(r.shadowRoots))for(let l of r.shadowRoots){let d=n(l);d&&c.children.push(d)}if(r.contentDocument){let l=n(r.contentDocument);l&&c.children.push(l)}return c},s={isInteractive:!1,isShadowHost:!1,isNew:!1,shouldDisplay:!0,ignoredByPaintOrder:!1,excludedByParent:!1,isCompoundComponent:!1,children:[],originalNode:{nodeId:0,backendNodeId:0,sessionId:"",frameId:"",targetId:"",nodeType:9,nodeName:"#document",nodeValue:"",attributes:{}}};for(let r of e){let o=n(r);o&&s.children.push(o)}return s}async handleGoBack(e){try{let t=e.pageId;await(t?this.getPageOrCurrent(t):await this.ensurePage()).goBack(),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleGoForward(e){try{let t=e.pageId;await(t?this.getPageOrCurrent(t):await this.ensurePage()).goForward(),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleRefresh(e){try{let t=e.pageId;await(t?this.getPageOrCurrent(t):await this.ensurePage()).reload(),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleWait(e){try{let t=e.maxSeconds||60,n=Math.min(e.seconds,t);b.debug(`Waiting for ${n}s (requested: ${e.seconds}s, max: ${t}s)`),await new Promise(s=>setTimeout(s,n*1e3)),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}normalizeKeyName(e){let t={ctrl:"Control",control:"Control",cmd:"Meta",command:"Meta",meta:"Meta",win:"Meta",windows:"Meta",alt:"Alt",option:"Alt",shift:"Shift",enter:"Enter",return:"Enter",esc:"Escape",escape:"Escape",tab:"Tab",space:"Space",backspace:"Backspace",delete:"Delete",del:"Delete",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",arrowup:"ArrowUp",arrowdown:"ArrowDown",arrowleft:"ArrowLeft",arrowright:"ArrowRight",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown",insert:"Insert",ins:"Insert"},n=e.toLowerCase().trim();return t[n]||e}parseKeyCombination(e){if(e.includes("+")){let t=e.split("+").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)return null;let n=[],s="";for(let r=0;r<t.length;r++){let o=this.normalizeKeyName(t[r]);["Control","Alt","Shift","Meta"].includes(o)?n.push(o):s=o}if(!s&&t.length>0){s=this.normalizeKeyName(t[t.length-1]);let r=n.indexOf(s);r!==-1&&n.splice(r,1)}return{modifiers:n,key:s}}return{modifiers:[],key:this.normalizeKeyName(e)}}async handleSendKeys(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage(),s=e.keys,r=this.parseKeyCombination(s);if(!r)throw new Error(`Invalid key combination: ${s}`);let{modifiers:o,key:a}=r;if(o.length>0){for(let c of o)await n.keyboard.down(c);a&&await n.keyboard.press(a);for(let c=o.length-1;c>=0;c--)await n.keyboard.up(o[c])}else await n.keyboard.press(a);a==="Enter"&&await new Promise(c=>setTimeout(c,100)),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleUploadFile(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage();if(!e.node||!e.node.absolutePosition)throw new Error("Element position not available for file upload");let{x:s,y:r}=e.node.absolutePosition;await n.mouse.click(s+5,r+5);let o=l=>l.replace(/([!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~])/g,"\\$1"),a;e.node.attributes?.id?a=`#${o(e.node.attributes.id)}`:e.node.attributes?.name?a=`input[name="${o(e.node.attributes.name)}"]`:a='input[type="file"]';let c=Array.isArray(e.filePath)?e.filePath:[e.filePath];await n.setInputFiles(a,c),this.eventBus.respondToEvent(e._eventId,{success:!0})}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleGetDropdownOptions(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage();if(!e.node||!e.node.absolutePosition)throw new Error("Element position not available");if((e.node.nodeName?.toLowerCase()||"")==="select"){let r=e.node.attributes?.id?`#${e.node.attributes.id}`:e.node.attributes?.name?`select[name="${e.node.attributes.name}"]`:"select",o=await n.evaluate(a=>{let c=document.querySelector(a);return c?Array.from(c.options).map(l=>({value:l.value,text:l.text,selected:l.selected})):[]},r);this.eventBus.respondToEvent(e._eventId,{type:"native_select",options:o})}else{let{x:r,y:o,width:a,height:c}=e.node.absolutePosition;await n.mouse.click(r+a/2,o+c/2),await n.waitForTimeout(300);let l=await n.evaluate(()=>{let d=document.querySelectorAll('[role="option"], [role="menuitem"], [role="listitem"], li[data-value], .dropdown-item, .select-option');return Array.from(d).map(g=>({text:g.innerText?.trim()||"",value:g.getAttribute("data-value")||g.innerText?.trim()||""}))});this.eventBus.respondToEvent(e._eventId,{type:"custom_dropdown",options:l})}}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleSelectDropdownOption(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage();if(!e.node||!e.node.absolutePosition)throw new Error("Element position not available");if((e.node.nodeName?.toLowerCase()||"")==="select"){let r=e.node.attributes?.id?`#${e.node.attributes.id}`:e.node.attributes?.name?`select[name="${e.node.attributes.name}"]`:"select";await n.selectOption(r,{label:e.text}),this.eventBus.respondToEvent(e._eventId,{success:!0,selectedText:e.text})}else{let{x:r,y:o,width:a,height:c}=e.node.absolutePosition;await n.mouse.click(r+a/2,o+c/2),await n.waitForTimeout(300);let l=await n.evaluate(d=>{let g=d.toLowerCase().trim(),m=document.querySelectorAll('[role="option"], [role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"], [role="listitem"], li[data-value], .dropdown-item, .select-option, .item, .option, .menu-item, [data-value], li, a'),p=null,h=null,f=[];for(let T of Array.from(m)){let x=T,w=(x.innerText?.trim()||"").toLowerCase(),C=(x.getAttribute("data-value")||"").toLowerCase();if(!(!w&&!C)&&(w&&f.push(x.innerText?.trim()||""),!(x.getAttribute("aria-disabled")==="true"||x.hasAttribute("disabled")))){if(w===g||C===g){p=x;break}!h&&(w.includes(g)||C.includes(g))&&(h=x)}}let y=p||h;return y?(y.click(),y.dispatchEvent(new Event("input",{bubbles:!0})),y.dispatchEvent(new Event("change",{bubbles:!0})),{found:!0,selectedText:y.innerText?.trim()}):{found:!1,availableOptions:f.slice(0,20)}},e.text);if(!l.found){let d=l.availableOptions||[],g=d.length>0?` Available options: ${d.join(", ")}`:"";throw new Error(`Option "${e.text}" not found in dropdown.${g}`)}this.eventBus.respondToEvent(e._eventId,{success:!0,selectedText:e.text})}}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async getAllTabs(){let e=[];for(let[t,n]of this.pages.entries())e.push({targetId:t,url:n.url(),title:await n.title()});return e}async getState(e={}){return this.eventBus.dispatch(z.BROWSER_STATE_REQUEST,{includeScreenshot:e.includeScreenshot??!0,includeDom:e.includeDom??!0,includeRecentEvents:e.includeRecentEvents??!1},ee.BROWSER_STATE_REQUEST)}async navigate(e,t={}){return this.eventBus.dispatch(z.NAVIGATE_TO_URL,{url:e,...t},ee.NAVIGATE_TO_URL)}async screenshot(e={}){return this.eventBus.dispatch(z.SCREENSHOT,e,ee.SCREENSHOT)}async goBack(){return this.eventBus.dispatch(z.GO_BACK,{},ee.GO_BACK)}async goForward(){return this.eventBus.dispatch(z.GO_FORWARD,{},ee.GO_FORWARD)}async refresh(){return this.eventBus.dispatch(z.REFRESH,{},ee.REFRESH)}async getElementByIndex(e){return this.cachedSelectorMap&&this.cachedSelectorMap.has(e)?this.cachedSelectorMap.get(e):null}updateCachedSelectorMap(e){this.cachedSelectorMap=e}async getSelectorMap(){return this.cachedSelectorMap}clearCachedState(){b.debug("🔄 Clearing cached browser state (page navigation detected)"),this.cachedSelectorMap.clear(),this.cachedBrowserStateSummary=null;for(let[e,t]of this.pageSelectorMaps)t.clear();this.pendingRequests.clear()}async getIndexById(e){for(let[t,n]of this.cachedSelectorMap.entries())if(n.attributes&&n.attributes.id===e)return t;return null}async getIndexByClass(e){for(let[t,n]of this.cachedSelectorMap.entries())if(n.attributes&&(n.attributes.class||"").split(" ").includes(e))return t;return null}isFileInput(e){return e.nodeName?.toUpperCase()==="INPUT"&&e.attributes?.type?.toLowerCase()==="file"}async clickElement(e){return this.eventBus.dispatch(z.CLICK_ELEMENT,{node:e},ee.CLICK_ELEMENT)}async typeText(e,t){return this.eventBus.dispatch(z.TYPE_TEXT,{text:e,node:t},ee.TYPE_TEXT)}async scroll(e,t,n){return this.eventBus.dispatch(z.SCROLL,{direction:e,amount:t||500},ee.SCROLL)}async getTargetIdFromTabId(e){let t=await this.getAllTabs();for(let n of t)if(n.targetId.endsWith(e))return n.targetId;throw new Error(`No tab found with ID ending in: ${e}`)}async switchTab(e){let t=e.length===4?await this.getTargetIdFromTabId(e):e;this.currentPageId=t}async closeTab(e){let t=e.length===4?await this.getTargetIdFromTabId(e):e,n=this.pages.get(t);if(n)try{await n.close(),this.pages.delete(t),this.pageSelectorMaps.delete(t);let s=this.pageCdpSessions.get(t);if(s&&(s.detach().catch(()=>{}),this.pageCdpSessions.delete(t)),this.currentPageId===t){let r=Array.from(this.pages.keys());this.currentPageId=r.length>0?r[0]:void 0,b.log("🔄 [BrowserSession] Switched to another tab after closing current")}return b.log(`🗑️ [BrowserSession] Closed tab ${e}. Remaining tabs: ${this.pages.size}`),!0}catch(s){return console.error(`❌ [BrowserSession] Error closing tab ${e}: ${s.message}`),!1}return!1}async uploadFile(e,t){let n=await this.getElementByIndex(e);if(!n)throw new Error(`Element at index ${e} not found`);if(!this.isFileInput(n))throw new Error(`Element at index ${e} is not a file input`);return this.eventBus.dispatch(z.UPLOAD_FILE,{node:n,filePath:t},ee.UPLOAD_FILE||3e4)}async getDropdownOptions(e){let t=await this.getElementByIndex(e);if(!t)throw new Error(`Element at index ${e} not found`);return this.eventBus.dispatch(z.GET_DROPDOWN_OPTIONS,{node:t},ee.GET_DROPDOWN_OPTIONS||15e3)}async selectDropdownOption(e,t){let n=await this.getElementByIndex(e);if(!n)throw new Error(`Element at index ${e} not found`);return this.eventBus.dispatch(z.SELECT_DROPDOWN_OPTION,{node:n,text:t},ee.SELECT_DROPDOWN_OPTION||8e3)}async sendKeys(e){return this.eventBus.dispatch(z.SEND_KEYS,{keys:e.join("")},ee.SEND_KEYS)}async evaluate(e){return(await this.ensurePage()).evaluate(e)}get page(){return this.getCurrentPage()}get downloadedFiles(){return[...this._downloadedFiles]}async getCdpSession(){let e=await this.ensurePage();if(this.cdpSession)try{return await this.cdpSession.send("Runtime.evaluate",{expression:"1",returnByValue:!0}),this.cdpSession}catch(t){b.debug("CDP session stale, creating new one:",t.message);try{await this.cdpSession.detach()}catch{}this.cdpSession=null}return this.cdpSession=await e.context().newCDPSession(e),this.cdpSession}async getCdpSessionForPage(e){let t=this.pages.get(e);if(!t)throw new Error(`Page ${e} not found`);let n=this.pageCdpSessions.get(e);if(n)try{return await n.send("Runtime.evaluate",{expression:"1",returnByValue:!0}),n}catch(r){b.debug(`CDP session for page ${e} stale, creating new one:`,r.message);try{await n.detach()}catch{}this.pageCdpSessions.delete(e)}let s=await t.context().newCDPSession(t);return this.pageCdpSessions.set(e,s),s}async closeCdpSession(){this.cdpSession&&(await this.cdpSession.detach(),this.cdpSession=null)}async closeCdpSessionForPage(e){let t=this.pageCdpSessions.get(e);if(t){try{await t.detach()}catch{}this.pageCdpSessions.delete(e)}}async cookies(e){if(!this.context)throw new Error("Browser context not initialized");return this.context.cookies(e)}async setCookies(e){if(!this.context)throw new Error("Browser context not initialized");await this.context.addCookies(e)}async clearCookies(){if(!this.context)throw new Error("Browser context not initialized");await this.context.clearCookies()}async exportStorageState(e){if(!this.context)throw new Error("Browser context not initialized");return e?this.context.storageState({path:e}):this.context.storageState()}async importStorageState(e){console.warn("Storage state import is only supported during browser session initialization")}async getAllFrames(e=!0){let t=new Map,n=new Map;try{let s=await this.ensurePage(),r=await s.context().newCDPSession(s),c=((await r.send("Target.getTargets")).targetInfos||[]).filter(l=>!!(l.type==="page"||l.type==="iframe"&&e));for(let l of c){let d=l.targetId;try{let g;try{g=(await r.send("Target.attachToTarget",{targetId:d,flatten:!0})).sessionId}catch(m){b.debug(`Could not attach to target ${d}:`,m);continue}if(g){n.set(d,g),await r.send("Page.enable",void 0,g);let p=(await r.send("Page.getFrameTree",void 0,g)).frameTree;if(p){let h=(f,y=null)=>{let T=f.frame||{},x=T.id;if(x){let w=T.parentId||y,C={...T,frameTargetId:d,parentFrameId:w,childFrameIds:[],isCrossOrigin:l.type==="iframe"},v=T.crossOriginIsolatedContextType;v&&v!=="NotIsolated"&&(C.isCrossOrigin=!0);let E=f.childFrames||[];for(let S of E){let I=S.frame||{};I.id&&C.childFrameIds.push(I.id)}if(t.has(x)){let S=t.get(x);l.type==="iframe"&&(S.frameTargetId=d,S.isCrossOrigin=!0)}else t.set(x,C);for(let S of E)h(S,x)}};h(p)}}}catch(g){b.debug(`Failed to get frame tree for target ${d}:`,g)}}}catch(s){b.debug("Failed to get frames via CDP, falling back to Playwright:",s);let o=(await this.ensurePage()).mainFrame(),a=(c,l)=>{let d=c.name()||`frame_${t.size}`;t.set(d,{id:d,url:c.url(),name:c.name(),parentFrameId:l,isCrossOrigin:!1});for(let g of c.childFrames())a(g,d)};a(o,null)}return{frames:t,targetSessions:n}}async findFrameById(e){let{frames:t}=await this.getAllFrames();return t.get(e)||null}async getFrameByUrl(e){let n=(await this.ensurePage()).frames();for(let s of n)if(s.url()===e||s.url().includes(e))return s;return null}async removeHighlights(){if(this.highlightsAdded)try{await(await this.ensurePage()).evaluate(()=>{let t=document.getElementById("browser-use-debug-highlights");t&&t.remove();let n=document.getElementById("browser-use-highlights");n&&n.remove(),document.querySelectorAll("[data-browser-use-highlight]").forEach(o=>{o.remove()}),document.querySelectorAll("[data-browser-use-interaction-highlight]").forEach(o=>{o.remove()})}),this.highlightsAdded=!1}catch(e){b.debug(`Failed to remove highlights: ${e.message}`)}}async addHighlights(e){try{let t=await this.ensurePage();await this.removeHighlights(),await new Promise(s=>setTimeout(s,50));let n=[];for(let[s,r]of e.entries())if(r.absolutePosition){let{x:o,y:a,width:c,height:l}=r.absolutePosition;c>0&&l>0&&n.push({index:s,x:o,y:a,width:c,height:l,elementName:r.nodeName||"div",backendNodeId:r.backendNodeId||s})}if(n.length===0){b.debug("No valid elements to highlight");return}await t.evaluate(s=>{let r=document.getElementById("browser-use-debug-highlights");r&&r.remove(),document.querySelectorAll("[data-browser-use-highlight]").forEach(d=>d.remove());let a=2147483647,c=document.createElement("div");c.id="browser-use-debug-highlights",c.setAttribute("data-browser-use-highlight","container"),c.style.cssText=`
567
+ }`,returnByValue:!0});if(c.result?.value?.success)return b.debug(`Scrolled ${c.result.value.element} by ${c.result.value.scrolled}px`),!0}}catch(a){b.debug("Failed to scroll element container:",a)}return!1}catch(s){return b.debug("scrollElementContainer error:",s),!1}}async handleScreenshot(e){try{let t=e.pageId,r=(await(t?this.getPageOrCurrent(t):await this.ensurePage()).screenshot({fullPage:e.fullPage,clip:e.clip,type:"png"})).toString("base64");this.eventBus.respondToEvent(e._eventId,r)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleBrowserStateRequest(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage(),s=await n.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,pageWidth:document.documentElement.scrollWidth,pageHeight:document.documentElement.scrollHeight})),r={viewportWidth:s.viewportWidth,viewportHeight:s.viewportHeight,pageWidth:s.pageWidth,pageHeight:s.pageHeight,scrollX:s.scrollX,scrollY:s.scrollY,pixelsAbove:s.scrollY,pixelsBelow:Math.max(0,s.pageHeight-s.viewportHeight-s.scrollY),pixelsLeft:s.scrollX,pixelsRight:Math.max(0,s.pageWidth-s.viewportWidth-s.scrollX)},o={root:null,selectorMap:new Map};if(e.includeDom!==!1)try{let c=new Ws(n,{paintOrderFiltering:!0,crossOriginIframes:!1}),l=await c.getPageState({includeScreenshot:!1,useCDPAccessibility:!0});this.updateCachedSelectorMap(l.selectorMap);let d=l.domTree,g=l.selectorMap;o={root:this.createSimplifiedNode(d,g),selectorMap:g,llmRepresentation:(m=[])=>c.formatDOMForLLM(d,0,!0,g)},await c.close()}catch(c){b.debug("DOM extraction failed:",c.message)}let a={domState:o,url:n.url(),title:await n.title(),tabs:await this.getAllTabs(),pageInfo:r,pixelsAbove:r.pixelsAbove,pixelsBelow:r.pixelsBelow,browserErrors:[],isPdfViewer:n.url().endsWith(".pdf")||n.url().includes("chrome-extension://")&&n.url().includes("pdf"),pendingNetworkRequests:[],paginationButtons:[]};if(e.includeScreenshot!==!1){let l=(await n.screenshot({type:"png"})).toString("base64");if(o.selectorMap&&o.selectorMap.size>0)try{let d=await n.evaluate(()=>window.devicePixelRatio||1);l=await zl(l,o.selectorMap,d,!0)}catch(d){b.debug("Screenshot highlighting failed, using original:",d.message)}a.screenshot=l}this.cachedBrowserStateSummary=a,this.eventBus.respondToEvent(e._eventId,a)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}createSimplifiedNode(e,t){if(!e||e.length===0)return null;let n=r=>{if(!r)return null;let o=r.backendNodeId||0,c={isInteractive:t.has(o),isShadowHost:r.isShadowHost||!1,isNew:!1,shouldDisplay:!0,ignoredByPaintOrder:!1,excludedByParent:!1,isCompoundComponent:!1,children:[],originalNode:{nodeId:r.nodeId||0,backendNodeId:o,sessionId:r.sessionId||"",frameId:r.frameId||"",targetId:r.targetId||"",nodeType:r.nodeType||1,nodeName:r.nodeName||"",nodeValue:r.nodeValue||"",attributes:r.attributes||{}}};if(r.children&&Array.isArray(r.children))for(let l of r.children){let d=n(l);d&&c.children.push(d)}if(r.shadowRoots&&Array.isArray(r.shadowRoots))for(let l of r.shadowRoots){let d=n(l);d&&c.children.push(d)}if(r.contentDocument){let l=n(r.contentDocument);l&&c.children.push(l)}return c},s={isInteractive:!1,isShadowHost:!1,isNew:!1,shouldDisplay:!0,ignoredByPaintOrder:!1,excludedByParent:!1,isCompoundComponent:!1,children:[],originalNode:{nodeId:0,backendNodeId:0,sessionId:"",frameId:"",targetId:"",nodeType:9,nodeName:"#document",nodeValue:"",attributes:{}}};for(let r of e){let o=n(r);o&&s.children.push(o)}return s}async handleGoBack(e){try{let t=e.pageId;await(t?this.getPageOrCurrent(t):await this.ensurePage()).goBack(),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleGoForward(e){try{let t=e.pageId;await(t?this.getPageOrCurrent(t):await this.ensurePage()).goForward(),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleRefresh(e){try{let t=e.pageId;await(t?this.getPageOrCurrent(t):await this.ensurePage()).reload(),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleWait(e){try{let t=e.maxSeconds||60,n=Math.min(e.seconds,t);b.debug(`Waiting for ${n}s (requested: ${e.seconds}s, max: ${t}s)`),await new Promise(s=>setTimeout(s,n*1e3)),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}normalizeKeyName(e){let t={ctrl:"Control",control:"Control",cmd:"Meta",command:"Meta",meta:"Meta",win:"Meta",windows:"Meta",alt:"Alt",option:"Alt",shift:"Shift",enter:"Enter",return:"Enter",esc:"Escape",escape:"Escape",tab:"Tab",space:"Space",backspace:"Backspace",delete:"Delete",del:"Delete",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",arrowup:"ArrowUp",arrowdown:"ArrowDown",arrowleft:"ArrowLeft",arrowright:"ArrowRight",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown",insert:"Insert",ins:"Insert"},n=e.toLowerCase().trim();return t[n]||e}parseKeyCombination(e){if(e.includes("+")){let t=e.split("+").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)return null;let n=[],s="";for(let r=0;r<t.length;r++){let o=this.normalizeKeyName(t[r]);["Control","Alt","Shift","Meta"].includes(o)?n.push(o):s=o}if(!s&&t.length>0){s=this.normalizeKeyName(t[t.length-1]);let r=n.indexOf(s);r!==-1&&n.splice(r,1)}return{modifiers:n,key:s}}return{modifiers:[],key:this.normalizeKeyName(e)}}async handleSendKeys(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage(),s=e.keys,r=this.parseKeyCombination(s);if(!r)throw new Error(`Invalid key combination: ${s}`);let{modifiers:o,key:a}=r;if(o.length>0){for(let c of o)await n.keyboard.down(c);a&&await n.keyboard.press(a);for(let c=o.length-1;c>=0;c--)await n.keyboard.up(o[c])}else await n.keyboard.press(a);a==="Enter"&&await new Promise(c=>setTimeout(c,100)),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleUploadFile(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage();if(!e.node||!e.node.absolutePosition)throw new Error("Element position not available for file upload");let{x:s,y:r}=e.node.absolutePosition;await n.mouse.click(s+5,r+5);let o=l=>l.replace(/([!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~])/g,"\\$1"),a;e.node.attributes?.id?a=`#${o(e.node.attributes.id)}`:e.node.attributes?.name?a=`input[name="${o(e.node.attributes.name)}"]`:a='input[type="file"]';let c=Array.isArray(e.filePath)?e.filePath:[e.filePath];await n.setInputFiles(a,c),this.eventBus.respondToEvent(e._eventId,{success:!0})}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleGetDropdownOptions(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage();if(!e.node||!e.node.absolutePosition)throw new Error("Element position not available");if((e.node.nodeName?.toLowerCase()||"")==="select"){let r=e.node.attributes?.id?`#${e.node.attributes.id}`:e.node.attributes?.name?`select[name="${e.node.attributes.name}"]`:"select",o=await n.evaluate(a=>{let c=document.querySelector(a);return c?Array.from(c.options).map(l=>({value:l.value,text:l.text,selected:l.selected})):[]},r);this.eventBus.respondToEvent(e._eventId,{type:"native_select",options:o})}else{let{x:r,y:o,width:a,height:c}=e.node.absolutePosition;await n.mouse.click(r+a/2,o+c/2),await n.waitForTimeout(300);let l=await n.evaluate(()=>{let d=document.querySelectorAll('[role="option"], [role="menuitem"], [role="listitem"], li[data-value], .dropdown-item, .select-option');return Array.from(d).map(g=>({text:g.innerText?.trim()||"",value:g.getAttribute("data-value")||g.innerText?.trim()||""}))});this.eventBus.respondToEvent(e._eventId,{type:"custom_dropdown",options:l})}}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleSelectDropdownOption(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage();if(!e.node||!e.node.absolutePosition)throw new Error("Element position not available");if((e.node.nodeName?.toLowerCase()||"")==="select"){let r=e.node.attributes?.id?`#${e.node.attributes.id}`:e.node.attributes?.name?`select[name="${e.node.attributes.name}"]`:"select";await n.selectOption(r,{label:e.text}),this.eventBus.respondToEvent(e._eventId,{success:!0,selectedText:e.text})}else{let{x:r,y:o,width:a,height:c}=e.node.absolutePosition;await n.mouse.click(r+a/2,o+c/2),await n.waitForTimeout(300);let l=await n.evaluate(d=>{let g=d.toLowerCase().trim(),m=document.querySelectorAll('[role="option"], [role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"], [role="listitem"], li[data-value], .dropdown-item, .select-option, .item, .option, .menu-item, [data-value], li, a'),p=null,h=null,f=[];for(let T of Array.from(m)){let C=T,w=(C.innerText?.trim()||"").toLowerCase(),E=(C.getAttribute("data-value")||"").toLowerCase();if(!(!w&&!E)&&(w&&f.push(C.innerText?.trim()||""),!(C.getAttribute("aria-disabled")==="true"||C.hasAttribute("disabled")))){if(w===g||E===g){p=C;break}!h&&(w.includes(g)||E.includes(g))&&(h=C)}}let y=p||h;return y?(y.click(),y.dispatchEvent(new Event("input",{bubbles:!0})),y.dispatchEvent(new Event("change",{bubbles:!0})),{found:!0,selectedText:y.innerText?.trim()}):{found:!1,availableOptions:f.slice(0,20)}},e.text);if(!l.found){let d=l.availableOptions||[],g=d.length>0?` Available options: ${d.join(", ")}`:"";throw new Error(`Option "${e.text}" not found in dropdown.${g}`)}this.eventBus.respondToEvent(e._eventId,{success:!0,selectedText:e.text})}}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async getAllTabs(){let e=[];for(let[t,n]of this.pages.entries())e.push({targetId:t,url:n.url(),title:await n.title()});return e}async getState(e={}){return this.eventBus.dispatch(q.BROWSER_STATE_REQUEST,{includeScreenshot:e.includeScreenshot??!0,includeDom:e.includeDom??!0,includeRecentEvents:e.includeRecentEvents??!1},te.BROWSER_STATE_REQUEST)}async navigate(e,t={}){return this.eventBus.dispatch(q.NAVIGATE_TO_URL,{url:e,...t},te.NAVIGATE_TO_URL)}async screenshot(e={}){return this.eventBus.dispatch(q.SCREENSHOT,e,te.SCREENSHOT)}async goBack(){return this.eventBus.dispatch(q.GO_BACK,{},te.GO_BACK)}async goForward(){return this.eventBus.dispatch(q.GO_FORWARD,{},te.GO_FORWARD)}async refresh(){return this.eventBus.dispatch(q.REFRESH,{},te.REFRESH)}async getElementByIndex(e){return this.cachedSelectorMap&&this.cachedSelectorMap.has(e)?this.cachedSelectorMap.get(e):null}updateCachedSelectorMap(e){this.cachedSelectorMap=e}async getSelectorMap(){return this.cachedSelectorMap}clearCachedState(){b.debug("🔄 Clearing cached browser state (page navigation detected)"),this.cachedSelectorMap.clear(),this.cachedBrowserStateSummary=null;for(let[e,t]of this.pageSelectorMaps)t.clear();this.pendingRequests.clear()}async getIndexById(e){for(let[t,n]of this.cachedSelectorMap.entries())if(n.attributes&&n.attributes.id===e)return t;return null}async getIndexByClass(e){for(let[t,n]of this.cachedSelectorMap.entries())if(n.attributes&&(n.attributes.class||"").split(" ").includes(e))return t;return null}isFileInput(e){return e.nodeName?.toUpperCase()==="INPUT"&&e.attributes?.type?.toLowerCase()==="file"}async clickElement(e){return this.eventBus.dispatch(q.CLICK_ELEMENT,{node:e},te.CLICK_ELEMENT)}async typeText(e,t){return this.eventBus.dispatch(q.TYPE_TEXT,{text:e,node:t},te.TYPE_TEXT)}async scroll(e,t,n){return this.eventBus.dispatch(q.SCROLL,{direction:e,amount:t||500},te.SCROLL)}async getTargetIdFromTabId(e){let t=await this.getAllTabs();for(let n of t)if(n.targetId.endsWith(e))return n.targetId;throw new Error(`No tab found with ID ending in: ${e}`)}async switchTab(e){let t=e.length===4?await this.getTargetIdFromTabId(e):e;this.currentPageId=t}async closeTab(e){let t=e.length===4?await this.getTargetIdFromTabId(e):e,n=this.pages.get(t);if(n)try{await n.close(),this.pages.delete(t),this.pageSelectorMaps.delete(t);let s=this.pageCdpSessions.get(t);if(s&&(s.detach().catch(()=>{}),this.pageCdpSessions.delete(t)),this.currentPageId===t){let r=Array.from(this.pages.keys());this.currentPageId=r.length>0?r[0]:void 0,b.log("🔄 [BrowserSession] Switched to another tab after closing current")}return b.log(`🗑️ [BrowserSession] Closed tab ${e}. Remaining tabs: ${this.pages.size}`),!0}catch(s){return console.error(`❌ [BrowserSession] Error closing tab ${e}: ${s.message}`),!1}return!1}async uploadFile(e,t){let n=await this.getElementByIndex(e);if(!n)throw new Error(`Element at index ${e} not found`);if(!this.isFileInput(n))throw new Error(`Element at index ${e} is not a file input`);return this.eventBus.dispatch(q.UPLOAD_FILE,{node:n,filePath:t},te.UPLOAD_FILE||3e4)}async getDropdownOptions(e){let t=await this.getElementByIndex(e);if(!t)throw new Error(`Element at index ${e} not found`);return this.eventBus.dispatch(q.GET_DROPDOWN_OPTIONS,{node:t},te.GET_DROPDOWN_OPTIONS||15e3)}async selectDropdownOption(e,t){let n=await this.getElementByIndex(e);if(!n)throw new Error(`Element at index ${e} not found`);return this.eventBus.dispatch(q.SELECT_DROPDOWN_OPTION,{node:n,text:t},te.SELECT_DROPDOWN_OPTION||8e3)}async sendKeys(e){return this.eventBus.dispatch(q.SEND_KEYS,{keys:e.join("")},te.SEND_KEYS)}async evaluate(e){return(await this.ensurePage()).evaluate(e)}get page(){return this.getCurrentPage()}get downloadedFiles(){return[...this._downloadedFiles]}async getCdpSession(){let e=await this.ensurePage();if(this.cdpSession)try{return await this.cdpSession.send("Runtime.evaluate",{expression:"1",returnByValue:!0}),this.cdpSession}catch(t){b.debug("CDP session stale, creating new one:",t.message);try{await this.cdpSession.detach()}catch{}this.cdpSession=null}return this.cdpSession=await e.context().newCDPSession(e),this.cdpSession}async getCdpSessionForPage(e){let t=this.pages.get(e);if(!t)throw new Error(`Page ${e} not found`);let n=this.pageCdpSessions.get(e);if(n)try{return await n.send("Runtime.evaluate",{expression:"1",returnByValue:!0}),n}catch(r){b.debug(`CDP session for page ${e} stale, creating new one:`,r.message);try{await n.detach()}catch{}this.pageCdpSessions.delete(e)}let s=await t.context().newCDPSession(t);return this.pageCdpSessions.set(e,s),s}async closeCdpSession(){this.cdpSession&&(await this.cdpSession.detach(),this.cdpSession=null)}async closeCdpSessionForPage(e){let t=this.pageCdpSessions.get(e);if(t){try{await t.detach()}catch{}this.pageCdpSessions.delete(e)}}async cookies(e){if(!this.context)throw new Error("Browser context not initialized");return this.context.cookies(e)}async setCookies(e){if(!this.context)throw new Error("Browser context not initialized");await this.context.addCookies(e)}async clearCookies(){if(!this.context)throw new Error("Browser context not initialized");await this.context.clearCookies()}async exportStorageState(e){if(!this.context)throw new Error("Browser context not initialized");return e?this.context.storageState({path:e}):this.context.storageState()}async importStorageState(e){console.warn("Storage state import is only supported during browser session initialization")}async getAllFrames(e=!0){let t=new Map,n=new Map;try{let s=await this.ensurePage(),r=await s.context().newCDPSession(s),c=((await r.send("Target.getTargets")).targetInfos||[]).filter(l=>!!(l.type==="page"||l.type==="iframe"&&e));for(let l of c){let d=l.targetId;try{let g;try{g=(await r.send("Target.attachToTarget",{targetId:d,flatten:!0})).sessionId}catch(m){b.debug(`Could not attach to target ${d}:`,m);continue}if(g){n.set(d,g),await r.send("Page.enable",void 0,g);let p=(await r.send("Page.getFrameTree",void 0,g)).frameTree;if(p){let h=(f,y=null)=>{let T=f.frame||{},C=T.id;if(C){let w=T.parentId||y,E={...T,frameTargetId:d,parentFrameId:w,childFrameIds:[],isCrossOrigin:l.type==="iframe"},v=T.crossOriginIsolatedContextType;v&&v!=="NotIsolated"&&(E.isCrossOrigin=!0);let x=f.childFrames||[];for(let S of x){let I=S.frame||{};I.id&&E.childFrameIds.push(I.id)}if(t.has(C)){let S=t.get(C);l.type==="iframe"&&(S.frameTargetId=d,S.isCrossOrigin=!0)}else t.set(C,E);for(let S of x)h(S,C)}};h(p)}}}catch(g){b.debug(`Failed to get frame tree for target ${d}:`,g)}}}catch(s){b.debug("Failed to get frames via CDP, falling back to Playwright:",s);let o=(await this.ensurePage()).mainFrame(),a=(c,l)=>{let d=c.name()||`frame_${t.size}`;t.set(d,{id:d,url:c.url(),name:c.name(),parentFrameId:l,isCrossOrigin:!1});for(let g of c.childFrames())a(g,d)};a(o,null)}return{frames:t,targetSessions:n}}async findFrameById(e){let{frames:t}=await this.getAllFrames();return t.get(e)||null}async getFrameByUrl(e){let n=(await this.ensurePage()).frames();for(let s of n)if(s.url()===e||s.url().includes(e))return s;return null}async removeHighlights(){if(this.highlightsAdded)try{await(await this.ensurePage()).evaluate(()=>{let t=document.getElementById("browser-use-debug-highlights");t&&t.remove();let n=document.getElementById("browser-use-highlights");n&&n.remove(),document.querySelectorAll("[data-browser-use-highlight]").forEach(o=>{o.remove()}),document.querySelectorAll("[data-browser-use-interaction-highlight]").forEach(o=>{o.remove()})}),this.highlightsAdded=!1}catch(e){b.debug(`Failed to remove highlights: ${e.message}`)}}async addHighlights(e){try{let t=await this.ensurePage();await this.removeHighlights(),await new Promise(s=>setTimeout(s,50));let n=[];for(let[s,r]of e.entries())if(r.absolutePosition){let{x:o,y:a,width:c,height:l}=r.absolutePosition;c>0&&l>0&&n.push({index:s,x:o,y:a,width:c,height:l,elementName:r.nodeName||"div",backendNodeId:r.backendNodeId||s})}if(n.length===0){b.debug("No valid elements to highlight");return}await t.evaluate(s=>{let r=document.getElementById("browser-use-debug-highlights");r&&r.remove(),document.querySelectorAll("[data-browser-use-highlight]").forEach(d=>d.remove());let a=2147483647,c=document.createElement("div");c.id="browser-use-debug-highlights",c.setAttribute("data-browser-use-highlight","container"),c.style.cssText=`
568
568
  position: absolute;
569
569
  top: 0;
570
570
  left: 0;
@@ -610,10 +610,10 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
610
610
  z-index: ${a+1};
611
611
  margin: 0;
612
612
  line-height: 1.4;
613
- `,m.appendChild(p),c.appendChild(m)}document.body.appendChild(c)},n),this.highlightsAdded=!0}catch(t){b.debug(`Failed to add highlights: ${t.message}`)}}async highlightInteractionElement(e,t){try{let n=await this.getElementCoordinatesByBackendNodeId(e.backendNodeId,t);if(!n){b.debug(`No coordinates found for backend node ${e.backendNodeId}`);return}let s=t?this.getPageOrCurrent(t):await this.ensurePage(),{x:r,y:o,width:a,height:c}=n;await s.evaluate(({x:g,y:m,width:p,height:h,color:f,duration:y})=>{let x=!window.matchMedia("(prefers-reduced-motion: reduce)").matches,w=window.pageXOffset||document.documentElement.scrollLeft||0,C=window.pageYOffset||document.documentElement.scrollTop||0,v=document.querySelector("[data-browser-use-interaction-highlight]");v&&v.remove();let E=document.createElement("div");E.setAttribute("data-browser-use-interaction-highlight","true"),E.style.cssText=`
613
+ `,m.appendChild(p),c.appendChild(m)}document.body.appendChild(c)},n),this.highlightsAdded=!0}catch(t){b.debug(`Failed to add highlights: ${t.message}`)}}async highlightInteractionElement(e,t){try{let n=await this.getElementCoordinatesByBackendNodeId(e.backendNodeId,t);if(!n){b.debug(`No coordinates found for backend node ${e.backendNodeId}`);return}let s=t?this.getPageOrCurrent(t):await this.ensurePage(),{x:r,y:o,width:a,height:c}=n;await s.evaluate(({x:g,y:m,width:p,height:h,color:f,duration:y})=>{let C=!window.matchMedia("(prefers-reduced-motion: reduce)").matches,w=window.pageXOffset||document.documentElement.scrollLeft||0,E=window.pageYOffset||document.documentElement.scrollTop||0,v=document.querySelector("[data-browser-use-interaction-highlight]");v&&v.remove();let x=document.createElement("div");x.setAttribute("data-browser-use-interaction-highlight","true"),x.style.cssText=`
614
614
  position: absolute;
615
615
  left: ${g+w}px;
616
- top: ${m+C}px;
616
+ top: ${m+E}px;
617
617
  width: ${p}px;
618
618
  height: ${h}px;
619
619
  background: transparent;
@@ -622,10 +622,10 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
622
622
  pointer-events: none;
623
623
  z-index: 2147483647;
624
624
  box-sizing: border-box;
625
- transform: ${x?"scale(0.95)":"scale(1)"};
626
- opacity: ${x?"0":"1"};
627
- transition: ${x?"all 0.25s cubic-bezier(0.34, 1.56, 0.64, 1)":"none"};
628
- `,document.body.appendChild(E),x&&requestAnimationFrame(()=>{setTimeout(()=>{E.style.transform="scale(1)",E.style.opacity="1"},10)}),setTimeout(()=>{x?(E.style.transform="scale(1.05)",E.style.opacity="0",E.style.transition="all 0.3s cubic-bezier(0.4, 0.0, 0.2, 1)",setTimeout(()=>E.remove(),300)):E.remove()},y)},{x:r,y:o,width:a||0,height:c||0,color:"rgb(156, 173, 184)",duration:2e3})}catch(n){b.debug(`Failed to highlight interaction element: ${n.message}`)}}async getElementCoordinates(e){try{let n=await(await this.ensurePage()).$(e);if(!n)return null;let s=await n.boundingBox();return s?{x:s.x,y:s.y,width:s.width,height:s.height}:null}catch(t){return b.debug(`Failed to get element coordinates: ${t.message}`),null}}async getElementCoordinatesByBackendNodeId(e,t){try{let n=t?await this.getCdpSessionForPage(t):await this.getCdpSession(),s=[];try{let r=await n.send("DOM.getContentQuads",{backendNodeId:e});r.quads&&r.quads.length>0&&(s=r.quads,b.debug(`Got ${s.length} quads from DOM.getContentQuads`))}catch(r){b.debug(`DOM.getContentQuads failed: ${r.message}`)}if(s.length===0)try{let r=await n.send("DOM.getBoxModel",{backendNodeId:e});if(r.model&&r.model.content&&r.model.content.length>=8){let o=r.model.content;s=[[o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7]]],b.debug("Got quad from DOM.getBoxModel")}}catch(r){b.debug(`DOM.getBoxModel failed: ${r.message}`)}if(s.length===0)try{let r=await n.send("DOM.resolveNode",{backendNodeId:e});if(r.object&&r.object.objectId){let o=await n.send("Runtime.callFunctionOn",{objectId:r.object.objectId,functionDeclaration:`
625
+ transform: ${C?"scale(0.95)":"scale(1)"};
626
+ opacity: ${C?"0":"1"};
627
+ transition: ${C?"all 0.25s cubic-bezier(0.34, 1.56, 0.64, 1)":"none"};
628
+ `,document.body.appendChild(x),C&&requestAnimationFrame(()=>{setTimeout(()=>{x.style.transform="scale(1)",x.style.opacity="1"},10)}),setTimeout(()=>{C?(x.style.transform="scale(1.05)",x.style.opacity="0",x.style.transition="all 0.3s cubic-bezier(0.4, 0.0, 0.2, 1)",setTimeout(()=>x.remove(),300)):x.remove()},y)},{x:r,y:o,width:a||0,height:c||0,color:"rgb(156, 173, 184)",duration:2e3})}catch(n){b.debug(`Failed to highlight interaction element: ${n.message}`)}}async getElementCoordinates(e){try{let n=await(await this.ensurePage()).$(e);if(!n)return null;let s=await n.boundingBox();return s?{x:s.x,y:s.y,width:s.width,height:s.height}:null}catch(t){return b.debug(`Failed to get element coordinates: ${t.message}`),null}}async getElementCoordinatesByBackendNodeId(e,t){try{let n=t?await this.getCdpSessionForPage(t):await this.getCdpSession(),s=[];try{let r=await n.send("DOM.getContentQuads",{backendNodeId:e});r.quads&&r.quads.length>0&&(s=r.quads,b.debug(`Got ${s.length} quads from DOM.getContentQuads`))}catch(r){b.debug(`DOM.getContentQuads failed: ${r.message}`)}if(s.length===0)try{let r=await n.send("DOM.getBoxModel",{backendNodeId:e});if(r.model&&r.model.content&&r.model.content.length>=8){let o=r.model.content;s=[[o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7]]],b.debug("Got quad from DOM.getBoxModel")}}catch(r){b.debug(`DOM.getBoxModel failed: ${r.message}`)}if(s.length===0)try{let r=await n.send("DOM.resolveNode",{backendNodeId:e});if(r.object&&r.object.objectId){let o=await n.send("Runtime.callFunctionOn",{objectId:r.object.objectId,functionDeclaration:`
629
629
  function() {
630
630
  const rect = this.getBoundingClientRect();
631
631
  return {
@@ -636,21 +636,21 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
636
636
  };
637
637
  }
638
638
  `,returnByValue:!0});if(o.result&&o.result.value){let a=o.result.value;if(a.width>0&&a.height>0)return a}}}catch(r){b.debug(`JavaScript getBoundingClientRect failed: ${r.message}`)}if(s.length>0){let r=s[0];if(r.length>=8){let o=[r[0],r[2],r[4],r[6]],a=[r[1],r[3],r[5],r[7]],c=Math.min(...o),l=Math.min(...a),d=Math.max(...o),g=Math.max(...a),m=d-c,p=g-l;if(m>0&&p>0)return{x:c,y:l,width:m,height:p}}}return null}catch(n){return b.debug(`Failed to get element coordinates by backendNodeId: ${n.message}`),null}}async newPage(e){if(!this.context)throw new Error("Browser context not initialized");let t=await this.context.newPage(),n=this.generatePageId();return this.pages.set(n,t),await this.injectStealthScripts(t),this.setupPageListeners(t,n),this.currentPageId=n,e&&await t.goto(e),t}async getCurrentPageUrl(){return(await this.ensurePage()).url()}async getCurrentPageTitle(){return(await this.ensurePage()).title()}async getPages(){return Array.from(this.pages.values())}async closePage(e){let t,n;if(typeof e=="string")t=e,n=this.pages.get(t);else for(let[s,r]of this.pages.entries())if(r===e){t=s,n=r;break}if(n&&t&&(await n.close(),this.pages.delete(t),this.currentPageId===t)){let s=Array.from(this.pages.keys());this.currentPageId=s[0]}}async grantPermissions(e,t){if(!this.context)throw new Error("Browser context not initialized");await this.context.grantPermissions(e,{origin:t})}async setGeolocation(e,t,n=100){if(!this.context)throw new Error("Browser context not initialized");await this.context.setGeolocation({latitude:e,longitude:t,accuracy:n})}async clearGeolocation(){if(!this.context)throw new Error("Browser context not initialized");await this.context.clearPermissions()}async setExtraHTTPHeaders(e){if(!this.context)throw new Error("Browser context not initialized");await this.context.setExtraHTTPHeaders(e)}async addInitScript(e){if(!this.context)throw new Error("Browser context not initialized");await this.context.addInitScript(e)}async setViewport(e,t){await(await this.ensurePage()).setViewportSize({width:e,height:t})}async getViewport(){return(await this.ensurePage()).viewportSize()}async takeScreenshot(e){return(await this.ensurePage()).screenshot({fullPage:e?.fullPage??!1,path:e?.path,type:e?.type??"png",quality:e?.quality,clip:e?.clip})}async screenshotElement(e,t){try{let s=await(await this.ensurePage()).$(e);return s?s.screenshot({path:t?.path,type:t?.type??"png",quality:t?.quality}):null}catch(n){return b.debug(`Failed to screenshot element: ${n.message}`),null}}async getStateAsText(){let e=await this.getState(),t=[];t.push(`URL: ${e.url}`),t.push(`Title: ${e.title}`),t.push(`Tabs: ${e.tabs.length}`);for(let n of e.tabs)t.push(` - [${n.targetId.slice(-4)}] ${n.title}: ${n.url}`);return t.join(`
639
- `)}async reset(){this.cachedSelectorMap.clear(),this.cachedBrowserStateSummary=null,this._downloadedFiles=[],await this.removeHighlights();let e=Array.from(this.pages.keys());for(let t=1;t<e.length;t++){let n=this.pages.get(e[t]);n&&(await n.close(),this.pages.delete(e[t]))}if(e.length>0){let t=this.pages.get(e[0]);t&&await t.goto("about:blank")}await this.clearCookies()}}});import{z as qi}from"zod";var ao,Kl=F(()=>{"use strict";ao=class{actions=new Map;register(e){this.actions.set(e.name,e)}getActions(){return this.actions}getAction(e){return this.actions.get(e)}async execute(e,t,n){let s=this.actions.get(e);if(!s)throw new Error(`Action ${e} not found`);let r=s.paramSchema.parse(t);return s.function(r,n)}getPromptDescription(e){let t=[];for(let n of this.actions.values()){if(e&&n.domains){if(!this.matchDomains(n.domains,e))continue}else{if(e&&!n.domains)continue;if(!e&&n.domains)continue}t.push(this.formatActionDescription(n))}return t.join(`
640
- `)}formatActionDescription(e){let t=e.paramSchema,n=[];if(t._def&&t._def.shape){let s=t._def.shape();for(let[r,o]of Object.entries(s)){let a=o,c=r;a._def.typeName&&(c+=`=${a._def.typeName.replace("Zod","").toLowerCase()}`),a._def.description&&(c+=` (${a._def.description})`),n.push(c)}}return n.length>0?`${e.name}: ${e.description}. (${n.join(", ")})`:`${e.name}: ${e.description}`}matchDomains(e,t){if(!e||e.length===0)return!0;try{let s=new URL(t).hostname;for(let r of e)if(new RegExp("^"+r.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(s))return!0}catch{return!1}return!1}getActionsSchema(){let e={};for(let[t,n]of this.actions.entries())e[t]={description:n.description,parameters:n.paramSchema};return e}createActionModel(e,t){let n=[];for(let[r,o]of this.actions.entries())if(!(e&&!e.includes(r))){if(!t){o.domains||n.push(o);continue}(!o.domains||this.matchDomains(o.domains,t))&&n.push(o)}let s=[];for(let r of n){let o=qi.object({[r.name]:r.paramSchema}).describe(r.description);s.push(o)}return s.length===0?qi.object({}):s.length===1?s[0]:qi.union(s)}}});import{z as U}from"zod";async function ts(i,e){return i.pageId?i.browserSession.getElementByIndexForPage(i.pageId,e):i.browserSession.getElementByIndex(e)}async function Xl(i){return i.pageId?i.browserSession.getSelectorMapForPage(i.pageId):await i.browserSession.getSelectorMap()}function yh(i,e){if(!e||!i)return null;for(let[t,n]of Object.entries(e))if(typeof n=="object"&&n!==null){for(let[s,r]of Object.entries(n))if(r&&r===i)return s}else if(n&&n===i)return t;return null}function Vl(i){let e=i;return e=e.replace(/\\"/g,'"'),e=e.replace(/\\\\([dDsSwWbBnrtfv])/g,"\\$1"),e=e.replace(/\\\\([.*+?^${}()|[\]])/g,"\\$1"),e=e.replace(/document\.evaluate\s*\(\s*"([^"]*'[^"]*)"/g,(t,n)=>`document.evaluate(\`${n}\`,`),e=e.replace(/(querySelector(?:All)?)\s*\(\s*"([^"]*'[^"]*)"/g,(t,n,s)=>`${n}(\`${s}\`)`),e=e.replace(/\.closest\s*\(\s*"([^"]*'[^"]*)"/g,(t,n)=>`.closest(\`${n}\`)`),e=e.replace(/\.matches\s*\(\s*"([^"]*'[^"]*)"/g,(t,n)=>`.matches(\`${n}\`)`),e}async function Wh(i,e){try{return await e.browserSession.eventBus.dispatch(z.NAVIGATE_TO_URL,{...i,pageId:e.pageId},ee.NAVIGATE_TO_URL),{longTermMemory:i.new_tab?`Opened new tab with URL ${i.url}`:`Navigated to ${i.url}`}}catch(t){let n=t.message||String(t);return n.includes("CDP client not initialized")?{error:`Browser connection error: ${n}`}:["ERR_NAME_NOT_RESOLVED","ERR_INTERNET_DISCONNECTED","ERR_CONNECTION_REFUSED","ERR_TIMED_OUT","net::"].some(r=>n.includes(r))?{error:`Navigation failed - site unavailable: ${i.url}`}:{error:`Navigation failed: ${n}`}}}async function Hh(i,e){try{if(i.index===0)return{error:"Cannot click on element with index 0. If there are no interactive elements use scroll(), wait(), refresh(), etc. to troubleshoot"};let t=await ts(e,i.index);if(b.log(`🔍 [click] Looking up element index ${i.index}${e.pageId?` (page: ${e.pageId})`:""}`),b.log(`🔍 [click] Element found: ${t?"yes":"no"}`),t&&(b.log(`🔍 [click] Element tag: ${t.nodeName}, text: ${t.text?.substring(0,50)}`),b.log(`🔍 [click] Element position: ${JSON.stringify(t.absolutePosition)}`),b.log(`🔍 [click] Element backendNodeId: ${t.backendNodeId}`)),!t){let n=await Xl(e);b.log(`🔍 [click] Available indices in selectorMap: ${n?Array.from(n.keys()).slice(0,20).join(", "):"empty"}`);let s=`Element index ${i.index} not available - page may have changed. Try refreshing browser state.`;return console.warn(`⚠️ ${s}`),{extractedContent:s}}return e.browserSession.highlightInteractionElement(t,e.pageId).catch(()=>{}),await e.browserSession.eventBus.dispatch(z.CLICK_ELEMENT,{node:t,button:i.button,pageId:e.pageId},ee.CLICK_ELEMENT),{longTermMemory:`Clicked element ${i.index}`}}catch(t){let n=t.message||String(t);if(n.includes("Cannot click on <select>")||n.includes("select element"))try{return await Yl({index:i.index},e)}catch{return{error:"Cannot click on select elements. Use dropdown_options or select_dropdown instead."}}return{error:`Failed to click element ${i.index}: ${n}`}}}async function Gh(i,e){try{let t=await ts(e,i.index);if(!t){let a=`Element index ${i.index} not available - page may have changed. Try refreshing browser state.`;return console.warn(`⚠️ ${a}`),{extractedContent:a}}e.browserSession.highlightInteractionElement(t,e.pageId).catch(()=>{});let n=e.hasSensitiveData||!1,s=e.sensitiveData,r=null;n&&s&&(r=yh(i.text,s)),await e.browserSession.eventBus.dispatch(z.TYPE_TEXT,{node:t,text:i.text,clear:i.clear,isSensitive:n,sensitiveKeyName:r,pageId:e.pageId},ee.TYPE_TEXT);let o;return n?r?o=`Input ${r} into element ${i.index}`:o=`Input sensitive data into element ${i.index}`:o=`Input '${i.text}' into element ${i.index}`,{longTermMemory:o}}catch(t){return{error:`Failed to type text: ${t.message}`}}}async function jh(i,e){try{let t=i.pages??1,n=i.down?"down":"up",s=null;if(i.index!==void 0&&i.index!==0&&(s=await ts(e,i.index),!s))return{error:`Element index ${i.index} not found in browser state`};let r=i.index!==void 0&&i.index!==0?`element ${i.index}`:"page",o=1e3;try{let a=await e.browserSession.getCdpSession();if(a){let c=await a.send("Page.getLayoutMetrics"),l=c?.cssVisualViewport||c?.cssLayoutViewport;l?.clientHeight&&(o=Math.floor(l.clientHeight))}}catch{}if(t>=1){let a=Math.floor(t),c=t-a,l=0;for(let g=0;g<a;g++)try{let m=o;await e.browserSession.eventBus.dispatch(z.SCROLL,{direction:n,amount:m,node:s,pageId:e.pageId},ee.SCROLL),l++,await new Promise(p=>setTimeout(p,300))}catch{}if(c>0)try{let g=Math.floor(c*o);await e.browserSession.eventBus.dispatch(z.SCROLL,{direction:n,amount:g,node:s,pageId:e.pageId},ee.SCROLL),l+=c}catch{}return{longTermMemory:(t===1?`Scrolled ${n} ${r} ${o}px`:`Scrolled ${n} ${r} ${l.toFixed(1)} pages`).replace(" "," ")}}else{let a=Math.floor(t*o);return await e.browserSession.eventBus.dispatch(z.SCROLL,{direction:n,amount:a,node:s,pageId:e.pageId},ee.SCROLL),{longTermMemory:`Scrolled ${n} ${r} ${t} pages`.replace(" "," ")}}}catch(t){return{error:`Failed to scroll: ${t.message}`}}}async function zh(i,e){try{return await e.browserSession.eventBus.dispatch(z.GO_BACK,{pageId:e.pageId},ee.GO_BACK),{longTermMemory:"Navigated back"}}catch(t){return{error:`Failed to go back: ${t.message}`}}}async function qh(i,e){try{return await e.browserSession.eventBus.dispatch(z.GO_FORWARD,{pageId:e.pageId},ee.GO_FORWARD),{longTermMemory:"Navigated forward"}}catch(t){return{error:`Failed to go forward: ${t.message}`}}}async function Kh(i,e){try{return await e.browserSession.eventBus.dispatch(z.REFRESH,{pageId:e.pageId},ee.REFRESH),{longTermMemory:"Refreshed page"}}catch(t){return{error:`Failed to refresh: ${t.message}`}}}async function Vh(i,e){try{return await e.browserSession.eventBus.dispatch(z.WAIT,{seconds:i.seconds,pageId:e.pageId},ee.WAIT),{longTermMemory:`Waited ${i.seconds} seconds`}}catch(t){return{error:`Failed to wait: ${t.message}`}}}async function Xh(i,e){try{return await e.browserSession.eventBus.dispatch(z.SEND_KEYS,{...i,pageId:e.pageId},ee.SEND_KEYS),{longTermMemory:`Sent keys: ${i.keys}`}}catch(t){return{error:`Failed to send keys: ${t.message}`}}}async function Yh(i,e){try{let t=await e.browserSession.eventBus.dispatch(z.SCREENSHOT,{...i,pageId:e.pageId},ee.SCREENSHOT);return{extractedContent:`Screenshot captured (${t.length} bytes)`,metadata:{screenshot:t}}}catch(t){return{error:`Failed to take screenshot: ${t.message}`}}}async function Qh(i,e){return{isDone:!0,success:i.success??!0,extractedContent:i.text,attachments:i.files_to_display||[]}}async function Jh(i,e){try{let t=i.engine||"google",n=encodeURIComponent(i.query),r={google:`https://www.google.com/search?q=${n}&udm=14`,bing:`https://www.bing.com/search?q=${n}`,duckduckgo:`https://duckduckgo.com/?q=${n}`}[t];if(!r)return{error:`Unsupported search engine: ${t}. Options: google, bing, duckduckgo`};await e.browserSession.eventBus.dispatch(z.NAVIGATE_TO_URL,{url:r,newTab:!1,pageId:e.pageId},ee.NAVIGATE_TO_URL);let o=`Searched ${t} for '${i.query}'`;return{extractedContent:o,longTermMemory:o}}catch(t){return{error:`Failed to search: ${t.message}`}}}async function Zh(i,e){try{let n=(await e.browserSession.getState()).tabs.find(r=>r.targetId.endsWith(i.tab_id));if(!n)return{error:`Tab with ID ${i.tab_id} not found`};await e.browserSession.eventBus.dispatch(z.SWITCH_TAB,{targetId:n.targetId},ee.SWITCH_TAB);let s=`Switched to tab #${i.tab_id}`;return{extractedContent:s,longTermMemory:s}}catch(t){return{error:`Failed to switch tab: ${t.message}`}}}async function ef(i,e){try{let n=(await e.browserSession.getState()).tabs.find(r=>r.targetId.endsWith(i.tab_id));if(!n)return{extractedContent:`Tab #${i.tab_id} closed (was already closed or invalid)`,longTermMemory:`Tab #${i.tab_id} closed`};await e.browserSession.eventBus.dispatch(z.CLOSE_TAB,{targetId:n.targetId},ee.CLOSE_TAB);let s=`Closed tab #${i.tab_id}`;return{extractedContent:s,longTermMemory:s}}catch(t){return{error:`Failed to close tab: ${t.message}`}}}async function tf(i,e){try{await e.browserSession.eventBus.dispatch(z.SCROLL_TO_TEXT,{text:i.text,pageId:e.pageId},ee.SCROLL_TO_TEXT);let t=`Scrolled to text: ${i.text}`;return{extractedContent:t,longTermMemory:t}}catch{return{extractedContent:`Text '${i.text}' not found or not visible on page`,longTermMemory:`Tried scrolling to text '${i.text}' but it was not found`}}}async function Yl(i,e){try{let t=await ts(e,i.index);if(!t)return{error:`Element with index ${i.index} not found`};let n=await e.browserSession.eventBus.dispatch(z.GET_DROPDOWN_OPTIONS,{node:t,pageId:e.pageId},ee.GET_DROPDOWN_OPTIONS);return n?{extractedContent:n.shortTermMemory||JSON.stringify(n),longTermMemory:n.longTermMemory||`Got dropdown options for element ${i.index}`,includeExtractedContentOnlyOnce:!0}:{error:"Failed to get dropdown options - no data returned"}}catch(t){return{error:`Failed to get dropdown options: ${t.message}`}}}async function nf(i,e){try{let t=await ts(e,i.index);if(!t){let s=`Element index ${i.index} not available - page may have changed. Try refreshing browser state.`;return console.warn(`⚠️ ${s}`),{extractedContent:s}}let n=await e.browserSession.eventBus.dispatch(z.SELECT_DROPDOWN_OPTION,{node:t,text:i.text,pageId:e.pageId},ee.SELECT_DROPDOWN_OPTION);return n?n.success==="true"||n.success===!0?{extractedContent:n.message||`Selected option: ${i.text}`,longTermMemory:`Selected dropdown option '${i.text}' at index ${i.index}`}:{error:n.error||`Failed to select option: ${i.text}`}:{error:"Failed to select dropdown option - no data returned"}}catch(t){return{error:`Failed to select dropdown option: ${t.message}`}}}async function sf(i,e){try{let t=await ts(e,i.index),n=await Xl(e);if(!t)return{error:`Element with index ${i.index} not found`};if(e.availableFilePaths&&!e.availableFilePaths.includes(i.path)&&!(e.browserSession.downloadedFiles||[]).includes(i.path))if(e.fileSystem){if(!await e.fileSystem.getFile?.(i.path))return{error:`File path ${i.path} is not available. Upload files must be in available_file_paths, downloaded_files, or file_system.`}}else return{error:`File path ${i.path} is not available. Upload files must be in available_file_paths or downloaded_files.`};let s=l=>{if(!l)return!1;let d=(l.tagName||l.nodeName||"").toLowerCase(),g=(l.attributes?.type||"").toLowerCase();return d==="input"&&g==="file"},o=((l,d=3)=>{if(s(l))return l;let g=l.childrenNodes||l.children||[];for(let p of g)if(s(p))return p;let m=l;for(let p=0;p<d;p++){let h=m.parentNode||m.parent;if(!h)break;let f=h.childrenNodes||h.children||[];for(let y of f){if(y===m)continue;if(s(y))return y;let T=y.childrenNodes||y.children||[];for(let x of T)if(s(x))return x}m=h}return null})(t);if(!o&&n){let l=null,d=1/0,g=0;try{let m=e.browserSession.page;m&&(g=await m.evaluate(()=>window.scrollY||0))}catch{}for(let[m,p]of n.entries())if(s(p)){let h=p.absolutePosition?.y||0,f=Math.abs(h-g);f<d&&(d=f,l=p)}l&&(o=l)}let a=o||t;await e.browserSession.eventBus.dispatch(z.UPLOAD_FILE,{node:a,filePath:i.path,pageId:e.pageId},ee.UPLOAD_FILE);let c=`Uploaded file ${i.path} to element ${i.index}`;return{extractedContent:`Successfully uploaded file to index ${i.index}`,longTermMemory:c}}catch(t){return{error:`Failed to upload file: ${t.message}`}}}async function rf(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to execute JavaScript"};let n=Vl(i.code),s=await t.evaluate(n),r;if(s===void 0)r="undefined";else if(s===null)r="null";else if(typeof s=="object")try{r=JSON.stringify(s,null,2)}catch{r=String(s)}else r=String(s);let o=2e4;return r.length>o&&(r=r.substring(0,o-50)+`
639
+ `)}async reset(){this.cachedSelectorMap.clear(),this.cachedBrowserStateSummary=null,this._downloadedFiles=[],await this.removeHighlights();let e=Array.from(this.pages.keys());for(let t=1;t<e.length;t++){let n=this.pages.get(e[t]);n&&(await n.close(),this.pages.delete(e[t]))}if(e.length>0){let t=this.pages.get(e[0]);t&&await t.goto("about:blank")}await this.clearCookies()}}});import{z as qi}from"zod";var ao,Kl=$(()=>{"use strict";ao=class{actions=new Map;register(e){this.actions.set(e.name,e)}getActions(){return this.actions}getAction(e){return this.actions.get(e)}async execute(e,t,n){let s=this.actions.get(e);if(!s)throw new Error(`Action ${e} not found`);let r=s.paramSchema.parse(t);return s.function(r,n)}getPromptDescription(e){let t=[];for(let n of this.actions.values()){if(e&&n.domains){if(!this.matchDomains(n.domains,e))continue}else{if(e&&!n.domains)continue;if(!e&&n.domains)continue}t.push(this.formatActionDescription(n))}return t.join(`
640
+ `)}formatActionDescription(e){let t=e.paramSchema,n=[];if(t._def&&t._def.shape){let s=t._def.shape();for(let[r,o]of Object.entries(s)){let a=o,c=r;a._def.typeName&&(c+=`=${a._def.typeName.replace("Zod","").toLowerCase()}`),a._def.description&&(c+=` (${a._def.description})`),n.push(c)}}return n.length>0?`${e.name}: ${e.description}. (${n.join(", ")})`:`${e.name}: ${e.description}`}matchDomains(e,t){if(!e||e.length===0)return!0;try{let s=new URL(t).hostname;for(let r of e)if(new RegExp("^"+r.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(s))return!0}catch{return!1}return!1}getActionsSchema(){let e={};for(let[t,n]of this.actions.entries())e[t]={description:n.description,parameters:n.paramSchema};return e}createActionModel(e,t){let n=[];for(let[r,o]of this.actions.entries())if(!(e&&!e.includes(r))){if(!t){o.domains||n.push(o);continue}(!o.domains||this.matchDomains(o.domains,t))&&n.push(o)}let s=[];for(let r of n){let o=qi.object({[r.name]:r.paramSchema}).describe(r.description);s.push(o)}return s.length===0?qi.object({}):s.length===1?s[0]:qi.union(s)}}});import{z as U}from"zod";async function ss(i,e){return i.pageId?i.browserSession.getElementByIndexForPage(i.pageId,e):i.browserSession.getElementByIndex(e)}async function Xl(i){return i.pageId?i.browserSession.getSelectorMapForPage(i.pageId):await i.browserSession.getSelectorMap()}function yh(i,e){if(!e||!i)return null;for(let[t,n]of Object.entries(e))if(typeof n=="object"&&n!==null){for(let[s,r]of Object.entries(n))if(r&&r===i)return s}else if(n&&n===i)return t;return null}function Vl(i){let e=i;return e=e.replace(/\\"/g,'"'),e=e.replace(/\\\\([dDsSwWbBnrtfv])/g,"\\$1"),e=e.replace(/\\\\([.*+?^${}()|[\]])/g,"\\$1"),e=e.replace(/document\.evaluate\s*\(\s*"([^"]*'[^"]*)"/g,(t,n)=>`document.evaluate(\`${n}\`,`),e=e.replace(/(querySelector(?:All)?)\s*\(\s*"([^"]*'[^"]*)"/g,(t,n,s)=>`${n}(\`${s}\`)`),e=e.replace(/\.closest\s*\(\s*"([^"]*'[^"]*)"/g,(t,n)=>`.closest(\`${n}\`)`),e=e.replace(/\.matches\s*\(\s*"([^"]*'[^"]*)"/g,(t,n)=>`.matches(\`${n}\`)`),e}async function Wh(i,e){try{return await e.browserSession.eventBus.dispatch(q.NAVIGATE_TO_URL,{...i,pageId:e.pageId},te.NAVIGATE_TO_URL),{longTermMemory:i.new_tab?`Opened new tab with URL ${i.url}`:`Navigated to ${i.url}`}}catch(t){let n=t.message||String(t);return n.includes("CDP client not initialized")?{error:`Browser connection error: ${n}`}:["ERR_NAME_NOT_RESOLVED","ERR_INTERNET_DISCONNECTED","ERR_CONNECTION_REFUSED","ERR_TIMED_OUT","net::"].some(r=>n.includes(r))?{error:`Navigation failed - site unavailable: ${i.url}`}:{error:`Navigation failed: ${n}`}}}async function Hh(i,e){try{if(i.index===0)return{error:"Cannot click on element with index 0. If there are no interactive elements use scroll(), wait(), refresh(), etc. to troubleshoot"};let t=await ss(e,i.index);if(b.log(`🔍 [click] Looking up element index ${i.index}${e.pageId?` (page: ${e.pageId})`:""}`),b.log(`🔍 [click] Element found: ${t?"yes":"no"}`),t&&(b.log(`🔍 [click] Element tag: ${t.nodeName}, text: ${t.text?.substring(0,50)}`),b.log(`🔍 [click] Element position: ${JSON.stringify(t.absolutePosition)}`),b.log(`🔍 [click] Element backendNodeId: ${t.backendNodeId}`)),!t){let n=await Xl(e);b.log(`🔍 [click] Available indices in selectorMap: ${n?Array.from(n.keys()).slice(0,20).join(", "):"empty"}`);let s=`Element index ${i.index} not available - page may have changed. Try refreshing browser state.`;return console.warn(`⚠️ ${s}`),{extractedContent:s}}return e.browserSession.highlightInteractionElement(t,e.pageId).catch(()=>{}),await e.browserSession.eventBus.dispatch(q.CLICK_ELEMENT,{node:t,button:i.button,pageId:e.pageId},te.CLICK_ELEMENT),{longTermMemory:`Clicked element ${i.index}`}}catch(t){let n=t.message||String(t);if(n.includes("Cannot click on <select>")||n.includes("select element"))try{return await Yl({index:i.index},e)}catch{return{error:"Cannot click on select elements. Use dropdown_options or select_dropdown instead."}}return{error:`Failed to click element ${i.index}: ${n}`}}}async function Gh(i,e){try{let t=await ss(e,i.index);if(!t){let a=`Element index ${i.index} not available - page may have changed. Try refreshing browser state.`;return console.warn(`⚠️ ${a}`),{extractedContent:a}}e.browserSession.highlightInteractionElement(t,e.pageId).catch(()=>{});let n=e.hasSensitiveData||!1,s=e.sensitiveData,r=null;n&&s&&(r=yh(i.text,s)),await e.browserSession.eventBus.dispatch(q.TYPE_TEXT,{node:t,text:i.text,clear:i.clear,isSensitive:n,sensitiveKeyName:r,pageId:e.pageId},te.TYPE_TEXT);let o;return n?r?o=`Input ${r} into element ${i.index}`:o=`Input sensitive data into element ${i.index}`:o=`Input '${i.text}' into element ${i.index}`,{longTermMemory:o}}catch(t){return{error:`Failed to type text: ${t.message}`}}}async function jh(i,e){try{let t=i.pages??1,n=i.down?"down":"up",s=null;if(i.index!==void 0&&i.index!==0&&(s=await ss(e,i.index),!s))return{error:`Element index ${i.index} not found in browser state`};let r=i.index!==void 0&&i.index!==0?`element ${i.index}`:"page",o=1e3;try{let a=await e.browserSession.getCdpSession();if(a){let c=await a.send("Page.getLayoutMetrics"),l=c?.cssVisualViewport||c?.cssLayoutViewport;l?.clientHeight&&(o=Math.floor(l.clientHeight))}}catch{}if(t>=1){let a=Math.floor(t),c=t-a,l=0;for(let g=0;g<a;g++)try{let m=o;await e.browserSession.eventBus.dispatch(q.SCROLL,{direction:n,amount:m,node:s,pageId:e.pageId},te.SCROLL),l++,await new Promise(p=>setTimeout(p,300))}catch{}if(c>0)try{let g=Math.floor(c*o);await e.browserSession.eventBus.dispatch(q.SCROLL,{direction:n,amount:g,node:s,pageId:e.pageId},te.SCROLL),l+=c}catch{}return{longTermMemory:(t===1?`Scrolled ${n} ${r} ${o}px`:`Scrolled ${n} ${r} ${l.toFixed(1)} pages`).replace(" "," ")}}else{let a=Math.floor(t*o);return await e.browserSession.eventBus.dispatch(q.SCROLL,{direction:n,amount:a,node:s,pageId:e.pageId},te.SCROLL),{longTermMemory:`Scrolled ${n} ${r} ${t} pages`.replace(" "," ")}}}catch(t){return{error:`Failed to scroll: ${t.message}`}}}async function zh(i,e){try{return await e.browserSession.eventBus.dispatch(q.GO_BACK,{pageId:e.pageId},te.GO_BACK),{longTermMemory:"Navigated back"}}catch(t){return{error:`Failed to go back: ${t.message}`}}}async function qh(i,e){try{return await e.browserSession.eventBus.dispatch(q.GO_FORWARD,{pageId:e.pageId},te.GO_FORWARD),{longTermMemory:"Navigated forward"}}catch(t){return{error:`Failed to go forward: ${t.message}`}}}async function Kh(i,e){try{return await e.browserSession.eventBus.dispatch(q.REFRESH,{pageId:e.pageId},te.REFRESH),{longTermMemory:"Refreshed page"}}catch(t){return{error:`Failed to refresh: ${t.message}`}}}async function Vh(i,e){try{return await e.browserSession.eventBus.dispatch(q.WAIT,{seconds:i.seconds,pageId:e.pageId},te.WAIT),{longTermMemory:`Waited ${i.seconds} seconds`}}catch(t){return{error:`Failed to wait: ${t.message}`}}}async function Xh(i,e){try{return await e.browserSession.eventBus.dispatch(q.SEND_KEYS,{...i,pageId:e.pageId},te.SEND_KEYS),{longTermMemory:`Sent keys: ${i.keys}`}}catch(t){return{error:`Failed to send keys: ${t.message}`}}}async function Yh(i,e){try{let t=await e.browserSession.eventBus.dispatch(q.SCREENSHOT,{...i,pageId:e.pageId},te.SCREENSHOT);return{extractedContent:`Screenshot captured (${t.length} bytes)`,metadata:{screenshot:t}}}catch(t){return{error:`Failed to take screenshot: ${t.message}`}}}async function Qh(i,e){return{isDone:!0,success:i.success??!0,extractedContent:i.text,attachments:i.files_to_display||[]}}async function Jh(i,e){try{let t=i.engine||"google",n=encodeURIComponent(i.query),r={google:`https://www.google.com/search?q=${n}&udm=14`,bing:`https://www.bing.com/search?q=${n}`,duckduckgo:`https://duckduckgo.com/?q=${n}`}[t];if(!r)return{error:`Unsupported search engine: ${t}. Options: google, bing, duckduckgo`};await e.browserSession.eventBus.dispatch(q.NAVIGATE_TO_URL,{url:r,newTab:!1,pageId:e.pageId},te.NAVIGATE_TO_URL);let o=`Searched ${t} for '${i.query}'`;return{extractedContent:o,longTermMemory:o}}catch(t){return{error:`Failed to search: ${t.message}`}}}async function Zh(i,e){try{let n=(await e.browserSession.getState()).tabs.find(r=>r.targetId.endsWith(i.tab_id));if(!n)return{error:`Tab with ID ${i.tab_id} not found`};await e.browserSession.eventBus.dispatch(q.SWITCH_TAB,{targetId:n.targetId},te.SWITCH_TAB);let s=`Switched to tab #${i.tab_id}`;return{extractedContent:s,longTermMemory:s}}catch(t){return{error:`Failed to switch tab: ${t.message}`}}}async function ef(i,e){try{let n=(await e.browserSession.getState()).tabs.find(r=>r.targetId.endsWith(i.tab_id));if(!n)return{extractedContent:`Tab #${i.tab_id} closed (was already closed or invalid)`,longTermMemory:`Tab #${i.tab_id} closed`};await e.browserSession.eventBus.dispatch(q.CLOSE_TAB,{targetId:n.targetId},te.CLOSE_TAB);let s=`Closed tab #${i.tab_id}`;return{extractedContent:s,longTermMemory:s}}catch(t){return{error:`Failed to close tab: ${t.message}`}}}async function tf(i,e){try{await e.browserSession.eventBus.dispatch(q.SCROLL_TO_TEXT,{text:i.text,pageId:e.pageId},te.SCROLL_TO_TEXT);let t=`Scrolled to text: ${i.text}`;return{extractedContent:t,longTermMemory:t}}catch{return{extractedContent:`Text '${i.text}' not found or not visible on page`,longTermMemory:`Tried scrolling to text '${i.text}' but it was not found`}}}async function Yl(i,e){try{let t=await ss(e,i.index);if(!t)return{error:`Element with index ${i.index} not found`};let n=await e.browserSession.eventBus.dispatch(q.GET_DROPDOWN_OPTIONS,{node:t,pageId:e.pageId},te.GET_DROPDOWN_OPTIONS);return n?{extractedContent:n.shortTermMemory||JSON.stringify(n),longTermMemory:n.longTermMemory||`Got dropdown options for element ${i.index}`,includeExtractedContentOnlyOnce:!0}:{error:"Failed to get dropdown options - no data returned"}}catch(t){return{error:`Failed to get dropdown options: ${t.message}`}}}async function nf(i,e){try{let t=await ss(e,i.index);if(!t){let s=`Element index ${i.index} not available - page may have changed. Try refreshing browser state.`;return console.warn(`⚠️ ${s}`),{extractedContent:s}}let n=await e.browserSession.eventBus.dispatch(q.SELECT_DROPDOWN_OPTION,{node:t,text:i.text,pageId:e.pageId},te.SELECT_DROPDOWN_OPTION);return n?n.success==="true"||n.success===!0?{extractedContent:n.message||`Selected option: ${i.text}`,longTermMemory:`Selected dropdown option '${i.text}' at index ${i.index}`}:{error:n.error||`Failed to select option: ${i.text}`}:{error:"Failed to select dropdown option - no data returned"}}catch(t){return{error:`Failed to select dropdown option: ${t.message}`}}}async function sf(i,e){try{let t=await ss(e,i.index),n=await Xl(e);if(!t)return{error:`Element with index ${i.index} not found`};if(e.availableFilePaths&&!e.availableFilePaths.includes(i.path)&&!(e.browserSession.downloadedFiles||[]).includes(i.path))if(e.fileSystem){if(!await e.fileSystem.getFile?.(i.path))return{error:`File path ${i.path} is not available. Upload files must be in available_file_paths, downloaded_files, or file_system.`}}else return{error:`File path ${i.path} is not available. Upload files must be in available_file_paths or downloaded_files.`};let s=l=>{if(!l)return!1;let d=(l.tagName||l.nodeName||"").toLowerCase(),g=(l.attributes?.type||"").toLowerCase();return d==="input"&&g==="file"},o=((l,d=3)=>{if(s(l))return l;let g=l.childrenNodes||l.children||[];for(let p of g)if(s(p))return p;let m=l;for(let p=0;p<d;p++){let h=m.parentNode||m.parent;if(!h)break;let f=h.childrenNodes||h.children||[];for(let y of f){if(y===m)continue;if(s(y))return y;let T=y.childrenNodes||y.children||[];for(let C of T)if(s(C))return C}m=h}return null})(t);if(!o&&n){let l=null,d=1/0,g=0;try{let m=e.browserSession.page;m&&(g=await m.evaluate(()=>window.scrollY||0))}catch{}for(let[m,p]of n.entries())if(s(p)){let h=p.absolutePosition?.y||0,f=Math.abs(h-g);f<d&&(d=f,l=p)}l&&(o=l)}let a=o||t;await e.browserSession.eventBus.dispatch(q.UPLOAD_FILE,{node:a,filePath:i.path,pageId:e.pageId},te.UPLOAD_FILE);let c=`Uploaded file ${i.path} to element ${i.index}`;return{extractedContent:`Successfully uploaded file to index ${i.index}`,longTermMemory:c}}catch(t){return{error:`Failed to upload file: ${t.message}`}}}async function rf(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to execute JavaScript"};let n=Vl(i.code),s=await t.evaluate(n),r;if(s===void 0)r="undefined";else if(s===null)r="null";else if(typeof s=="object")try{r=JSON.stringify(s,null,2)}catch{r=String(s)}else r=String(s);let o=2e4;return r.length>o&&(r=r.substring(0,o-50)+`
641
641
  ... [Truncated after 20000 characters]`),{extractedContent:r}}catch(t){return{error:`JavaScript Execution Failed:
642
642
  ${t.message||String(t)}
643
643
 
644
644
  Validated Code (after quote fixing):
645
- ${Vl(i.code).substring(0,500)}${i.code.length>500?"...":""}`}}}async function of(i,e){try{let s=e.pageExtractionLlm||e.llm;if(b.log(`📤 [Extract] LLM available: ${!!s}, pageExtractionLlm: ${!!e.pageExtractionLlm}, mainLlm: ${!!e.llm}`),!s)return console.error("❌ [Extract] No LLM available for extraction"),{error:"No LLM available for extraction. Neither pageExtractionLlm nor main llm configured."};let r=e.browserSession.page;if(b.log(`📄 [Extract] Page available: ${!!r}`),!r)return{error:"No active page to extract content from"};let o=r.url(),a,c;try{let f=i.extract_links||!1,y=await r.evaluate(T=>{function x(E,S=0){if(S>20)return"";let I=E.tagName?.toLowerCase();if(["script","style","noscript","svg","path","iframe"].includes(I))return"";try{let R=window.getComputedStyle(E);if(R.display==="none"||R.visibility==="hidden")return""}catch{}let P="";if(["h1","h2","h3","h4","h5","h6"].includes(I)){let R=parseInt(I[1]),$="#".repeat(R)+" ";return P+=`
646
- `+$+E.innerText.trim()+`
647
- `,P}if(I==="p"){let R=E.innerText.trim();return R&&(P+=`
648
- `+R+`
649
- `),P}if(I==="a"&&T){let R=E.getAttribute("href"),$=E.innerText.trim();if(R&&$&&!R.startsWith("javascript:"))return`[${$}](${R})`}if(I==="li")return P+="- "+E.innerText.trim()+`
650
- `,P;if(["div","span","section","article","main"].includes(I)){for(let R of Array.from(E.children))P+=x(R,S+1);if(P===""&&E.innerText){let R=E.innerText.trim();R.length>2&&(P=R+`
651
- `)}return P}for(let R of Array.from(E.children))P+=x(R,S+1);return P}let w=document.documentElement.outerHTML,C=x(document.body),v=C.replace(/\n{3,}/g,`
645
+ ${Vl(i.code).substring(0,500)}${i.code.length>500?"...":""}`}}}async function of(i,e){try{let s=e.pageExtractionLlm||e.llm;if(b.log(`📤 [Extract] LLM available: ${!!s}, pageExtractionLlm: ${!!e.pageExtractionLlm}, mainLlm: ${!!e.llm}`),!s)return console.error("❌ [Extract] No LLM available for extraction"),{error:"No LLM available for extraction. Neither pageExtractionLlm nor main llm configured."};let r=e.browserSession.page;if(b.log(`📄 [Extract] Page available: ${!!r}`),!r)return{error:"No active page to extract content from"};let o=r.url(),a,c;try{let f=i.extract_links||!1,y=await r.evaluate(T=>{function C(x,S=0){if(S>20)return"";let I=x.tagName?.toLowerCase();if(["script","style","noscript","svg","path","iframe"].includes(I))return"";try{let M=window.getComputedStyle(x);if(M.display==="none"||M.visibility==="hidden")return""}catch{}let D="";if(["h1","h2","h3","h4","h5","h6"].includes(I)){let M=parseInt(I[1]),_="#".repeat(M)+" ";return D+=`
646
+ `+_+x.innerText.trim()+`
647
+ `,D}if(I==="p"){let M=x.innerText.trim();return M&&(D+=`
648
+ `+M+`
649
+ `),D}if(I==="a"&&T){let M=x.getAttribute("href"),_=x.innerText.trim();if(M&&_&&!M.startsWith("javascript:"))return`[${_}](${M})`}if(I==="li")return D+="- "+x.innerText.trim()+`
650
+ `,D;if(["div","span","section","article","main"].includes(I)){for(let M of Array.from(x.children))D+=C(M,S+1);if(D===""&&x.innerText){let M=x.innerText.trim();M.length>2&&(D=M+`
651
+ `)}return D}for(let M of Array.from(x.children))D+=C(M,S+1);return D}let w=document.documentElement.outerHTML,E=C(document.body),v=E.replace(/\n{3,}/g,`
652
652
 
653
- `).replace(/[ \t]+/g," ").replace(/%[0-9A-Fa-f]{2}/g,"").trim();return{content:v,originalHtmlChars:w.length,initialMarkdownChars:C.length,finalFilteredChars:v.length}},f);a=y.content,c={originalHtmlChars:y.originalHtmlChars,initialMarkdownChars:y.initialMarkdownChars,filteredCharsRemoved:y.initialMarkdownChars-y.finalFilteredChars,finalFilteredChars:y.finalFilteredChars}}catch(f){return{error:`Failed to extract page content: ${f.message}`}}let l=i.start_from_char||0;if(l>0){if(l>=a.length)return{error:`startFromChar (${l}) exceeds content length (${a.length}).`};a=a.substring(l)}let d=!1,g=0;if(a.length>3e4){let f=3e4,y=a.lastIndexOf(`
653
+ `).replace(/[ \t]+/g," ").replace(/%[0-9A-Fa-f]{2}/g,"").trim();return{content:v,originalHtmlChars:w.length,initialMarkdownChars:E.length,finalFilteredChars:v.length}},f);a=y.content,c={originalHtmlChars:y.originalHtmlChars,initialMarkdownChars:y.initialMarkdownChars,filteredCharsRemoved:y.initialMarkdownChars-y.finalFilteredChars,finalFilteredChars:y.finalFilteredChars}}catch(f){return{error:`Failed to extract page content: ${f.message}`}}let l=i.start_from_char||0;if(l>0){if(l>=a.length)return{error:`startFromChar (${l}) exceeds content length (${a.length}).`};a=a.substring(l)}let d=!1,g=0;if(a.length>3e4){let f=3e4,y=a.lastIndexOf(`
654
654
 
655
655
  `,3e4);if(y>29500)f=y;else{let T=a.lastIndexOf(".",3e4);T>29800&&(f=T+1)}a=a.substring(0,f),d=!0,g=l+f}let m=`Content: ${c.originalHtmlChars.toLocaleString()} HTML → ${c.finalFilteredChars.toLocaleString()} markdown chars`;l>0&&(m+=` (from char ${l.toLocaleString()})`),d&&(m+=` → ${a.length.toLocaleString()} chars (truncated, use startFromChar=${g} to continue)`);let p=`You are an expert at extracting data from the markdown of a webpage.
656
656
 
@@ -675,7 +675,7 @@ ${m}
675
675
 
676
676
  <webpage_content>
677
677
  ${a}
678
- </webpage_content>`;b.log(`🤖 [Extract] Calling LLM with ${a.length} chars of content...`);try{let f=await Promise.race([s.ainvoke([{role:"system",content:p},{role:"user",content:h}]),new Promise((C,v)=>setTimeout(()=>v(new Error("LLM extraction timeout")),12e4))]);b.log("✅ [Extract] LLM response received");let y=typeof f.completion=="string"?f.completion:JSON.stringify(f.completion);b.log(`📝 [Extract] Extracted ${y.length} chars`);let T=`<url>
678
+ </webpage_content>`;b.log(`🤖 [Extract] Calling LLM with ${a.length} chars of content...`);try{let f=await Promise.race([s.ainvoke([{role:"system",content:p},{role:"user",content:h}]),new Promise((E,v)=>setTimeout(()=>v(new Error("LLM extraction timeout")),12e4))]);b.log("✅ [Extract] LLM response received");let y=typeof f.completion=="string"?f.completion:JSON.stringify(f.completion);b.log(`📝 [Extract] Extracted ${y.length} chars`);let T=`<url>
679
679
  ${o}
680
680
  </url>
681
681
  <query>
@@ -683,24 +683,24 @@ ${i.query}
683
683
  </query>
684
684
  <result>
685
685
  ${y}
686
- </result>`,x,w=!1;if(T.length<1e3)x=T;else if(e.fileSystem)try{let C=await e.fileSystem.saveExtractedContent(T);x=`Query: ${i.query}
687
- Content saved to ${C}`,w=!0}catch{x=`Query: ${i.query}
688
- Extracted ${y.length} chars (see extracted_content)`,w=!0}else x=`Query: ${i.query}
689
- Extracted ${y.length} chars`,w=!0;return{extractedContent:T,longTermMemory:x,includeExtractedContentOnlyOnce:w}}catch(f){return console.error("❌ [Extract] LLM call failed:",f.message),{error:`LLM extraction failed: ${f.message}`}}}catch(s){return console.error("❌ [Extract] Action failed:",s.message),{error:`Extract action failed: ${s.message}`}}}async function af(i,e){try{if(!e.fileSystem)return{error:"No file system available. FileSystem must be configured in agent settings."};let t=i.content,n=i.trailing_newline!==!1,s=i.leading_newline===!0;n&&!t.endsWith(`
686
+ </result>`,C,w=!1;if(T.length<1e3)C=T;else if(e.fileSystem)try{let E=await e.fileSystem.saveExtractedContent(T);C=`Query: ${i.query}
687
+ Content saved to ${E}`,w=!0}catch{C=`Query: ${i.query}
688
+ Extracted ${y.length} chars (see extracted_content)`,w=!0}else C=`Query: ${i.query}
689
+ Extracted ${y.length} chars`,w=!0;return{extractedContent:T,longTermMemory:C,includeExtractedContentOnlyOnce:w}}catch(f){return console.error("❌ [Extract] LLM call failed:",f.message),{error:`LLM extraction failed: ${f.message}`}}}catch(s){return console.error("❌ [Extract] Action failed:",s.message),{error:`Extract action failed: ${s.message}`}}}async function af(i,e){try{if(!e.fileSystem)return{error:"No file system available. FileSystem must be configured in agent settings."};let t=i.content,n=i.trailing_newline!==!1,s=i.leading_newline===!0;n&&!t.endsWith(`
690
690
  `)&&(t+=`
691
691
  `),s&&!t.startsWith(`
692
692
  `)&&(t=`
693
693
  `+t);let r;return i.append?r=await e.fileSystem.appendFile(i.file_name,t):r=await e.fileSystem.writeFile(i.file_name,t),{extractedContent:r,longTermMemory:r}}catch(t){return{error:`Failed to write file: ${t.message}`}}}async function cf(i,e){try{if(!e.fileSystem)return{error:"No file system available. FileSystem must be configured in agent settings."};let t=e.availableFilePaths?.includes(i.file_name)??!1,n=await e.fileSystem.readFile(i.file_name,t),s=1e3,r;if(n.length>s){let o=n.split(`
694
694
  `),a="",c=0;for(let d of o)if(a.length+d.length<s)a+=d+`
695
- `,c++;else break;let l=o.length-c;r=l>0?`${a}${l} more lines...`:a}else r=n;return{extractedContent:n,longTermMemory:r,includeExtractedContentOnlyOnce:!0}}catch(t){return{error:`Failed to read file: ${t.message}`}}}async function lf(i,e){try{if(!e.fileSystem)return{error:"No file system available. FileSystem must be configured in agent settings."};let t=await e.fileSystem.replaceFileStr(i.file_name,i.old_str,i.new_str);return{extractedContent:t,longTermMemory:t}}catch(t){return{error:`Failed to replace in file: ${t.message}`}}}async function uf(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to search"};let n=i.pattern,s=i.regex??!1,r=i.case_sensitive??!1,o=i.context_chars??150,a=i.css_scope??null,c=i.max_results??25,l=await t.evaluate(({pattern:f,isRegex:y,caseSensitive:T,contextChars:x,cssScope:w,maxResults:C})=>{function v(E){let S=[],I=E;for(;I&&I!==document.body&&I!==document.documentElement;){let P=I.tagName?I.tagName.toLowerCase():"";if(!P)break;if(I.id)P+="#"+I.id;else if(I.className&&typeof I.className=="string"){let R=I.className.trim().split(/\s+/).slice(0,2).join(".");R&&(P+="."+R)}S.unshift(P),I=I.parentElement}return S.join(" > ")}try{let E=w?document.querySelector(w):document.body;if(!E)return{error:"CSS scope selector not found: "+w,matches:[],total:0};let S=document.createTreeWalker(E,NodeFilter.SHOW_TEXT),I="",P=[];for(;S.nextNode();){let N=S.currentNode,k=N.textContent;k&&k.trim()&&(P.push({offset:I.length,length:k.length,node:N}),I+=k)}let R;try{let N=T?"g":"gi";y?R=new RegExp(f,N):R=new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N)}catch(N){return{error:"Invalid regex pattern: "+N.message,matches:[],total:0}}let $=[],D,_=0;for(;(D=R.exec(I))!==null;){if(_++,$.length<C){let N=Math.max(0,D.index-x),k=Math.min(I.length,D.index+D[0].length+x),M=I.slice(N,k),L="";for(let B=0;B<P.length;B++){let H=P[B];if(H.offset<=D.index&&H.offset+H.length>D.index){L=v(H.node.parentElement);break}}$.push({match_text:D[0],context:(N>0?"...":"")+M+(k<I.length?"...":""),element_path:L,char_position:D.index})}D[0].length===0&&R.lastIndex++}return{matches:$,total:_,has_more:_>C}}catch(E){return{error:"search_page error: "+E.message,matches:[],total:0}}},{pattern:n,isRegex:s,caseSensitive:r,contextChars:o,cssScope:a,maxResults:c});if(l.error)return{error:l.error};let{matches:d,total:g,has_more:m}=l;if(g===0)return{extractedContent:`No matches found for "${n}" on page.`,longTermMemory:`Searched page for "${n}" - no matches found`};let p=[`Found ${g} match${g!==1?"es":""} for "${n}" on page:`,""];for(let f=0;f<d.length;f++){let y=d[f],T=y.element_path?` (in ${y.element_path})`:"";p.push(`[${f+1}] ${y.context}${T}`)}return m&&p.push(`
695
+ `,c++;else break;let l=o.length-c;r=l>0?`${a}${l} more lines...`:a}else r=n;return{extractedContent:n,longTermMemory:r,includeExtractedContentOnlyOnce:!0}}catch(t){return{error:`Failed to read file: ${t.message}`}}}async function lf(i,e){try{if(!e.fileSystem)return{error:"No file system available. FileSystem must be configured in agent settings."};let t=await e.fileSystem.replaceFileStr(i.file_name,i.old_str,i.new_str);return{extractedContent:t,longTermMemory:t}}catch(t){return{error:`Failed to replace in file: ${t.message}`}}}async function uf(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to search"};let n=i.pattern,s=i.regex??!1,r=i.case_sensitive??!1,o=i.context_chars??150,a=i.css_scope??null,c=i.max_results??25,l=await t.evaluate(({pattern:f,isRegex:y,caseSensitive:T,contextChars:C,cssScope:w,maxResults:E})=>{function v(x){let S=[],I=x;for(;I&&I!==document.body&&I!==document.documentElement;){let D=I.tagName?I.tagName.toLowerCase():"";if(!D)break;if(I.id)D+="#"+I.id;else if(I.className&&typeof I.className=="string"){let M=I.className.trim().split(/\s+/).slice(0,2).join(".");M&&(D+="."+M)}S.unshift(D),I=I.parentElement}return S.join(" > ")}try{let x=w?document.querySelector(w):document.body;if(!x)return{error:"CSS scope selector not found: "+w,matches:[],total:0};let S=document.createTreeWalker(x,NodeFilter.SHOW_TEXT),I="",D=[];for(;S.nextNode();){let N=S.currentNode,k=N.textContent;k&&k.trim()&&(D.push({offset:I.length,length:k.length,node:N}),I+=k)}let M;try{let N=T?"g":"gi";y?M=new RegExp(f,N):M=new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N)}catch(N){return{error:"Invalid regex pattern: "+N.message,matches:[],total:0}}let _=[],F,R=0;for(;(F=M.exec(I))!==null;){if(R++,_.length<E){let N=Math.max(0,F.index-C),k=Math.min(I.length,F.index+F[0].length+C),P=I.slice(N,k),B="";for(let L=0;L<D.length;L++){let W=D[L];if(W.offset<=F.index&&W.offset+W.length>F.index){B=v(W.node.parentElement);break}}_.push({match_text:F[0],context:(N>0?"...":"")+P+(k<I.length?"...":""),element_path:B,char_position:F.index})}F[0].length===0&&M.lastIndex++}return{matches:_,total:R,has_more:R>E}}catch(x){return{error:"search_page error: "+x.message,matches:[],total:0}}},{pattern:n,isRegex:s,caseSensitive:r,contextChars:o,cssScope:a,maxResults:c});if(l.error)return{error:l.error};let{matches:d,total:g,has_more:m}=l;if(g===0)return{extractedContent:`No matches found for "${n}" on page.`,longTermMemory:`Searched page for "${n}" - no matches found`};let p=[`Found ${g} match${g!==1?"es":""} for "${n}" on page:`,""];for(let f=0;f<d.length;f++){let y=d[f],T=y.element_path?` (in ${y.element_path})`:"";p.push(`[${f+1}] ${y.context}${T}`)}return m&&p.push(`
696
696
  ... showing ${d.length} of ${g} total matches. Increase max_results to see more.`),{extractedContent:p.join(`
697
- `),longTermMemory:`Searched page for "${n}" - found ${g} matches`}}catch(t){return{error:`search_page failed: ${t.message}`}}}async function df(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to query"};let n=i.selector,s=i.attributes??null,r=i.max_results??50,o=i.include_text??!0,a=await t.evaluate(({selector:h,attributes:f,maxResults:y,includeText:T})=>{try{let x;try{x=document.querySelectorAll(h)}catch(E){return{error:"Invalid CSS selector: "+E.message,elements:[],total:0}}let w=x.length,C=Math.min(w,y),v=[];for(let E=0;E<C;E++){let S=x[E],I={index:E,tag:S.tagName.toLowerCase(),children_count:S.children.length};if(T){let P=(S.textContent||"").trim();I.text=P.length>300?P.slice(0,300)+"...":P}if(f&&f.length>0){I.attrs={};for(let P=0;P<f.length;P++){let R=S.getAttribute(f[P]);R!==null&&(I.attrs[f[P]]=R.length>500?R.slice(0,500)+"...":R)}}v.push(I)}return{elements:v,total:w,showing:C}}catch(x){return{error:"find_elements error: "+x.message,elements:[],total:0}}},{selector:n,attributes:s,maxResults:r,includeText:o});if(a.error)return{error:a.error};let{elements:c,total:l,showing:d}=a,g=d??c.length;if(l===0)return{extractedContent:`No elements found matching "${n}".`,longTermMemory:`Queried DOM for "${n}" - no elements found`};let m=[`Found ${l} element${l!==1?"s":""} matching "${n}":`,""];for(let h of c){let f=[`[${h.index}] <${h.tag}>`];if(h.text){let y=h.text.split(/\s+/).join(" ");y.length>120&&(y=y.slice(0,120)+"..."),f.push(`"${y}"`)}if(h.attrs&&Object.keys(h.attrs).length>0){let y=Object.entries(h.attrs).map(([T,x])=>`${T}="${x}"`);f.push("{"+y.join(", ")+"}")}f.push(`(${h.children_count} children)`),m.push(f.join(" "))}return g<l&&m.push(`
697
+ `),longTermMemory:`Searched page for "${n}" - found ${g} matches`}}catch(t){return{error:`search_page failed: ${t.message}`}}}async function df(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to query"};let n=i.selector,s=i.attributes??null,r=i.max_results??50,o=i.include_text??!0,a=await t.evaluate(({selector:h,attributes:f,maxResults:y,includeText:T})=>{try{let C;try{C=document.querySelectorAll(h)}catch(x){return{error:"Invalid CSS selector: "+x.message,elements:[],total:0}}let w=C.length,E=Math.min(w,y),v=[];for(let x=0;x<E;x++){let S=C[x],I={index:x,tag:S.tagName.toLowerCase(),children_count:S.children.length};if(T){let D=(S.textContent||"").trim();I.text=D.length>300?D.slice(0,300)+"...":D}if(f&&f.length>0){I.attrs={};for(let D=0;D<f.length;D++){let M=S.getAttribute(f[D]);M!==null&&(I.attrs[f[D]]=M.length>500?M.slice(0,500)+"...":M)}}v.push(I)}return{elements:v,total:w,showing:E}}catch(C){return{error:"find_elements error: "+C.message,elements:[],total:0}}},{selector:n,attributes:s,maxResults:r,includeText:o});if(a.error)return{error:a.error};let{elements:c,total:l,showing:d}=a,g=d??c.length;if(l===0)return{extractedContent:`No elements found matching "${n}".`,longTermMemory:`Queried DOM for "${n}" - no elements found`};let m=[`Found ${l} element${l!==1?"s":""} matching "${n}":`,""];for(let h of c){let f=[`[${h.index}] <${h.tag}>`];if(h.text){let y=h.text.split(/\s+/).join(" ");y.length>120&&(y=y.slice(0,120)+"..."),f.push(`"${y}"`)}if(h.attrs&&Object.keys(h.attrs).length>0){let y=Object.entries(h.attrs).map(([T,C])=>`${T}="${C}"`);f.push("{"+y.join(", ")+"}")}f.push(`(${h.children_count} children)`),m.push(f.join(" "))}return g<l&&m.push(`
698
698
  Showing ${g} of ${l} total elements. Increase max_results to see more.`),{extractedContent:m.join(`
699
- `),longTermMemory:`Queried DOM for "${n}" - found ${l} elements`}}catch(t){return{error:`find_elements failed: ${t.message}`}}}function Ql(i){i.register({name:"navigate",description:"Navigate to a URL",function:Wh,paramSchema:vh}),i.register({name:"click",description:"Click an element by index",function:Hh,paramSchema:Sh}),i.register({name:"input",description:"Type text into an element",function:Gh,paramSchema:wh}),i.register({name:"scroll",description:"Scroll by pages (down=true/false, pages=0.5-10.0, default 1.0). Use index for scroll containers. High pages (10) reaches bottom. Multi-page scrolls sequentially. Viewport-based height, fallback 1000px.",function:jh,paramSchema:Th}),i.register({name:"go_back",description:"Navigate back in browser history",function:zh,paramSchema:U.object({})}),i.register({name:"go_forward",description:"Navigate forward in browser history",function:qh,paramSchema:U.object({})}),i.register({name:"refresh",description:"Refresh the current page",function:Kh,paramSchema:U.object({})}),i.register({name:"wait",description:"Wait for a specified number of seconds",function:Vh,paramSchema:Ch}),i.register({name:"send_keys",description:"Send keyboard keys or shortcuts",function:Xh,paramSchema:Eh}),i.register({name:"screenshot",description:"Take a screenshot of the current page",function:Yh,paramSchema:Ih}),i.register({name:"done",description:"Mark the task as complete",function:Qh,paramSchema:xh}),i.register({name:"search",description:"Search the web using Google, Bing, or DuckDuckGo",function:Jh,paramSchema:kh}),i.register({name:"switch",description:"Switch to another open tab by tab_id. Tab IDs are shown in browser state tabs list (last 4 chars of target_id).",function:Zh,paramSchema:Ph}),i.register({name:"close",description:"Close a tab by tab_id. Tab IDs are shown in browser state tabs list (last 4 chars of target_id).",function:ef,paramSchema:Ah}),i.register({name:"find_text",description:"Find and scroll to specific text on the page",function:tf,paramSchema:Dh}),i.register({name:"dropdown_options",description:"Get all options from a native dropdown or ARIA menu",function:Yl,paramSchema:Mh}),i.register({name:"select_dropdown",description:"Select a dropdown option by the text of the option you want to select",function:nf,paramSchema:Rh}),i.register({name:"upload_file",description:"Upload a file to a file input element",function:sf,paramSchema:Oh}),i.register({name:"evaluate",description:"Execute JavaScript code in the browser context. Use for hover, drag, zoom, custom selectors, or analyzing page structure.",function:rf,paramSchema:Nh}),i.register({name:"extract",description:"LLM extracts structured data from page content. Use when: on the right page, know what to extract, haven't called before on same page+query. Can't get interactive elements. Set extractLinks=true for URLs. Use startFromChar if truncated. If fails, use find_text/scroll instead.",function:of,paramSchema:_h}),i.register({name:"write_file",description:"Write content to a file in the agent's file system. Supports md, txt, json, jsonl, csv, pdf extensions.",function:af,paramSchema:$h}),i.register({name:"read_file",description:"Read content from a file in the agent's file system or from available_file_paths.",function:cf,paramSchema:Fh}),i.register({name:"replace_file",description:"Replace all occurrences of a string in a file with another string.",function:lf,paramSchema:Lh}),i.register({name:"search_page",description:"Search page text for a pattern (like grep). Zero LLM cost, instant. Returns matches with surrounding context. Use to find specific text, verify content exists, or locate data on the page. Set regex=true for regex patterns. Use css_scope to search within a specific section.",function:uf,paramSchema:Uh}),i.register({name:"find_elements",description:"Query DOM elements by CSS selector. Zero LLM cost, instant. Returns element tag, text, and optional attributes. Use to find all links, extract table data, or analyze page structure without LLM.",function:df,paramSchema:Bh})}var vh,Sh,wh,Th,xh,Ch,Eh,Ih,kh,Ph,Ah,Dh,Mh,Rh,Oh,Nh,_h,$h,Fh,Lh,Uh,Bh,Jl=F(()=>{"use strict";dt();Wi();Bi();vh=U.object({url:U.string().describe("The URL to navigate to"),new_tab:U.boolean().optional().default(!1).describe("Open in a new tab")}),Sh=U.object({index:U.number().min(1).describe("The element index to click (must be >= 1)"),button:U.enum(["left","right","middle"]).optional().describe("Mouse button to use")}),wh=U.object({index:U.number().min(0).describe("The element index to type into (>= 0)"),text:U.string().describe("The text to type"),clear:U.boolean().optional().default(!0).describe("Clear existing text first")}),Th=U.object({down:U.boolean().describe("Scroll direction: true=down, false=up"),pages:U.number().optional().default(1).describe("Pages to scroll (0.5=half, 1=full, 10=to bottom/top)"),index:U.number().optional().describe("Optional element index for scrollable container")}),xh=U.object({text:U.string().describe("Summary of what was accomplished"),success:U.boolean().optional().default(!0).describe("Whether the task was successful"),files_to_display:U.array(U.string()).optional().default([]).describe("File paths to include")}),Ch=U.object({seconds:U.number().describe("Number of seconds to wait")}),Eh=U.object({keys:U.string().describe('Keys to send (e.g., "Enter", "Control+A")')}),Ih=U.object({full_page:U.boolean().optional().describe("Capture full page")}),kh=U.object({query:U.string().describe("The search query"),engine:U.enum(["google","bing","duckduckgo"]).optional().default("duckduckgo").describe("Search engine to use")}),Ph=U.object({tab_id:U.string().length(4).describe("The tab ID to switch to (exactly 4 chars from target_id)")}),Ah=U.object({tab_id:U.string().length(4).describe("The tab ID to close (exactly 4 chars from target_id)")}),Dh=U.object({text:U.string().describe("The text to find and scroll to")}),Mh=U.object({index:U.number().describe("The element index of the dropdown/select")}),Rh=U.object({index:U.number().describe("The element index of the dropdown/select"),text:U.string().describe("The text of the option to select")}),Oh=U.object({index:U.number().describe("The element index of the file input"),path:U.string().describe("The path of the file to upload")}),Nh=U.object({code:U.string().describe("JavaScript code to execute in the browser context")}),_h=U.object({query:U.string().describe("What information to extract from the page"),extract_links:U.boolean().optional().default(!1).describe("Whether to include URLs in extraction"),start_from_char:U.number().optional().default(0).describe("Character offset to start from (for pagination)")}),$h=U.object({file_name:U.string().describe("The filename with extension (e.g., notes.md, data.json)"),content:U.string().describe("The content to write to the file"),append:U.boolean().optional().default(!1).describe("Append to existing file instead of overwriting"),trailing_newline:U.boolean().optional().default(!0).describe("Add trailing newline"),leading_newline:U.boolean().optional().default(!1).describe("Add leading newline")}),Fh=U.object({file_name:U.string().describe("The filename to read")}),Lh=U.object({file_name:U.string().describe("The filename to modify"),old_str:U.string().describe("The string to find and replace"),new_str:U.string().describe("The replacement string")}),Uh=U.object({pattern:U.string().describe("Text or regex pattern to search for in page content"),regex:U.boolean().optional().default(!1).describe("Treat pattern as regex (default: literal text match)"),case_sensitive:U.boolean().optional().default(!1).describe("Case-sensitive search (default: case-insensitive)"),context_chars:U.number().optional().default(150).describe("Characters of surrounding context per match"),css_scope:U.string().optional().describe('CSS selector to limit search scope (e.g. "div#main")'),max_results:U.number().optional().default(25).describe("Maximum matches to return")}),Bh=U.object({selector:U.string().describe('CSS selector to query elements (e.g. "table tr", "a.link", "div.product")'),attributes:U.array(U.string()).optional().describe('Specific attributes to extract (e.g. ["href", "src", "class"])'),max_results:U.number().optional().default(50).describe("Maximum elements to return"),include_text:U.boolean().optional().default(!0).describe("Include text content of each element")})});import{z as Ie}from"zod";import{v4 as gf}from"uuid";function Ki(i){return i.stepNumber>=i.maxSteps-1}function eu(i,e){let t=[];for(let n of i.action){let s=n.getIndex?.()??null;if(s!==null&&e.has(s)){let r=e.get(s);t.push(Bl(r))}else t.push(null)}return t}function tu(i,e){if(!e)return i;let t={};for(let[s,r]of Object.entries(e))if(typeof r=="object")for(let[o,a]of Object.entries(r))a&&(t[o]=a);else r&&(t[s]=r);if(Object.keys(t).length===0)return i;let n=i;for(let[s,r]of Object.entries(t))n=n.replace(new RegExp(r,"g"),`<secret>${s}</secret>`);return n}var Zl,mf,Ik,kk,Pk,Vi=F(()=>{"use strict";oo();Zl={useVision:"auto",visionDetailLevel:"auto",saveConversationPath:null,saveConversationPathEncoding:"utf-8",maxFailures:3,generateGif:!1,overrideSystemMessage:null,extendSystemMessage:null,includeAttributes:Ul,maxActionsPerStep:10,useThinking:!0,flashMode:!1,maxHistoryItems:null,pageExtractionLlm:null,calculateCost:!1,includeToolCallExamples:!1,llmTimeout:60,stepTimeout:120,finalResponseAfterFailure:!0,directlyOpenUrl:!0,includeRecentEvents:!1,sampleImages:null,availableFilePaths:null,waitBetweenActions:.1},mf={messages:[]},Ik={agentId:gf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1,messageManagerState:mf,fileSystemState:null};kk=Ie.object({isDone:Ie.boolean().nullable().optional(),success:Ie.boolean().nullable().optional(),error:Ie.string().nullable().optional(),attachments:Ie.array(Ie.string()).nullable().optional(),longTermMemory:Ie.string().nullable().optional(),extractedContent:Ie.string().nullable().optional(),includeExtractedContentOnlyOnce:Ie.boolean().optional(),metadata:Ie.record(Ie.any()).nullable().optional(),includeInMemory:Ie.boolean().optional()}).refine(i=>!(i.success===!0&&i.isDone!==!0),{message:"success=True can only be set when isDone=True. For regular actions that succeed, leave success as None. Use success=False only for actions that fail."}),Pk=Ie.object({thinking:Ie.string().nullable().optional(),evaluationPreviousGoal:Ie.string().nullable().optional(),memory:Ie.string().nullable().optional(),nextGoal:Ie.string().nullable().optional(),action:Ie.array(Ie.any()).min(1)})});var Qi={};Fe(Qi,{ActionResultSchema:()=>Cf,AgentOutputSchema:()=>co,DEFAULT_AGENT_SETTINGS:()=>hf,createAgentHistoryList:()=>Yi,createAgentOutputSchema:()=>lo,createAgentState:()=>Xi,getAgentBrain:()=>vf,getDurationSeconds:()=>yf,getFinalResult:()=>wf,isLastStep:()=>ff,isSuccessful:()=>Sf,loadHistoryFromFile:()=>xf,saveHistoryToFile:()=>Tf,validateActionResult:()=>bf});import{v4 as pf}from"uuid";import{z as me}from"zod";function Xi(){return{agentId:pf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1}}function ff(i){return i.stepNumber>=i.maxSteps-1}function bf(i){if(i.success===!0&&i.isDone!==!0)throw new Error("success=true can only be set when isDone=true. For regular actions that succeed, leave success as undefined/null. Use success=false only for actions that fail.")}function yf(i){return(i.stepEndTime-i.stepStartTime)/1e3}function vf(i){return{thinking:i.thinking,evaluationPreviousGoal:i.evaluationPreviousGoal||"",memory:i.memory||"",nextGoal:i.nextGoal||""}}function Yi(i,e){return{history:[],agentId:i,task:e,createdAt:Date.now(),finalResult:null}}function Sf(i){if(i.history&&i.history.length>0){let e=i.history[i.history.length-1];if(e.result&&e.result.length>0){let t=e.result[e.result.length-1];if(t.isDone===!0)return t.success??null}}return i.finalResult?.success!==void 0?i.finalResult.success:null}function wf(i){if(i.history&&i.history.length>0){let e=i.history[i.history.length-1];if(e.result&&e.result.length>0){let t=e.result[e.result.length-1];if(t.extractedContent)return t.extractedContent}}return i.finalResult?.extractedContent||null}async function Tf(i,e="AgentHistory.json",t){let n=await import("fs/promises"),s=JSON.parse(JSON.stringify(i));if(t){let r=o=>{if(typeof o=="string"){let a=o;for(let[c,l]of Object.entries(t))l&&(a=a.replace(new RegExp(l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),`[FILTERED:${c}]`));return a}if(Array.isArray(o))return o.map(r);if(o&&typeof o=="object"){let a={};for(let[c,l]of Object.entries(o))a[c]=r(l);return a}return o};s=r(s)}await n.writeFile(e,JSON.stringify(s,null,2),"utf-8")}async function xf(i="AgentHistory.json"){let t=await(await import("fs/promises")).readFile(i,"utf-8");return JSON.parse(t)}function lo(i){return me.object({thinking:me.string().nullable().optional(),evaluationPreviousGoal:me.string().nullable().optional(),memory:me.string().nullable().optional(),nextGoal:me.string().nullable().optional(),action:me.array(i).min(1)})}var hf,Cf,co,uo=F(()=>{"use strict";hf={saveConversationPath:null,saveConversationPathEncoding:"utf-8",useVision:"auto",visionDetailLevel:"auto",maxFailures:3,maxActionsPerStep:4,useThinking:!0,flashMode:!1,calculateCost:!1,includeToolCallExamples:!1,llmTimeout:60,stepTimeout:180,finalResponseAfterFailure:!0};Cf=me.object({isDone:me.boolean().optional(),success:me.boolean().nullable().optional(),error:me.string().nullable().optional(),attachments:me.array(me.string()).nullable().optional(),longTermMemory:me.string().nullable().optional(),extractedContent:me.string().nullable().optional(),includeExtractedContentOnlyOnce:me.boolean().optional(),metadata:me.record(me.any()).nullable().optional(),includeInMemory:me.boolean().optional()}).refine(i=>!(i.success===!0&&i.isDone!==!0),{message:"success=true can only be set when isDone=true"}),co=me.object({thinking:me.string().nullable().optional(),evaluationPreviousGoal:me.string().nullable().optional(),memory:me.string().nullable().optional(),nextGoal:me.string().nullable().optional(),action:me.array(me.any()).min(1)})});function nu(i){return i.content?typeof i.content=="string"?i.content:Array.isArray(i.content)?i.content.filter(e=>e.type==="text").map(e=>e.text).join(`
700
- `):"":""}function Pn(i,e){return{role:"user",content:i,name:e}}function Ji(i,e){return{role:"system",content:i,name:e}}var Zi=F(()=>{"use strict"});import{z as Re}from"zod";function qs(i){let e=i.stepNumber!==null&&i.stepNumber!==void 0?"step":"step_unknown";if(i.error)return`<${e}>
699
+ `),longTermMemory:`Queried DOM for "${n}" - found ${l} elements`}}catch(t){return{error:`find_elements failed: ${t.message}`}}}function Ql(i){i.register({name:"navigate",description:"Navigate to a URL",function:Wh,paramSchema:vh}),i.register({name:"click",description:"Click an element by index",function:Hh,paramSchema:Sh}),i.register({name:"input",description:"Type text into an element",function:Gh,paramSchema:wh}),i.register({name:"scroll",description:"Scroll by pages (down=true/false, pages=0.5-10.0, default 1.0). Use index for scroll containers. High pages (10) reaches bottom. Multi-page scrolls sequentially. Viewport-based height, fallback 1000px.",function:jh,paramSchema:Th}),i.register({name:"go_back",description:"Navigate back in browser history",function:zh,paramSchema:U.object({})}),i.register({name:"go_forward",description:"Navigate forward in browser history",function:qh,paramSchema:U.object({})}),i.register({name:"refresh",description:"Refresh the current page",function:Kh,paramSchema:U.object({})}),i.register({name:"wait",description:"Wait for a specified number of seconds",function:Vh,paramSchema:Ch}),i.register({name:"send_keys",description:"Send keyboard keys or shortcuts",function:Xh,paramSchema:Eh}),i.register({name:"screenshot",description:"Take a screenshot of the current page",function:Yh,paramSchema:Ih}),i.register({name:"done",description:"Mark the task as complete",function:Qh,paramSchema:xh}),i.register({name:"search",description:"Search the web using Google, Bing, or DuckDuckGo",function:Jh,paramSchema:kh}),i.register({name:"switch",description:"Switch to another open tab by tab_id. Tab IDs are shown in browser state tabs list (last 4 chars of target_id).",function:Zh,paramSchema:Ph}),i.register({name:"close",description:"Close a tab by tab_id. Tab IDs are shown in browser state tabs list (last 4 chars of target_id).",function:ef,paramSchema:Ah}),i.register({name:"find_text",description:"Find and scroll to specific text on the page",function:tf,paramSchema:Dh}),i.register({name:"dropdown_options",description:"Get all options from a native dropdown or ARIA menu",function:Yl,paramSchema:Mh}),i.register({name:"select_dropdown",description:"Select a dropdown option by the text of the option you want to select",function:nf,paramSchema:Rh}),i.register({name:"upload_file",description:"Upload a file to a file input element",function:sf,paramSchema:Oh}),i.register({name:"evaluate",description:"Execute JavaScript code in the browser context. Use for hover, drag, zoom, custom selectors, or analyzing page structure.",function:rf,paramSchema:Nh}),i.register({name:"extract",description:"LLM extracts structured data from page content. Use when: on the right page, know what to extract, haven't called before on same page+query. Can't get interactive elements. Set extractLinks=true for URLs. Use startFromChar if truncated. If fails, use find_text/scroll instead.",function:of,paramSchema:_h}),i.register({name:"write_file",description:"Write content to a file in the agent's file system. Supports md, txt, json, jsonl, csv, pdf extensions.",function:af,paramSchema:$h}),i.register({name:"read_file",description:"Read content from a file in the agent's file system or from available_file_paths.",function:cf,paramSchema:Fh}),i.register({name:"replace_file",description:"Replace all occurrences of a string in a file with another string.",function:lf,paramSchema:Lh}),i.register({name:"search_page",description:"Search page text for a pattern (like grep). Zero LLM cost, instant. Returns matches with surrounding context. Use to find specific text, verify content exists, or locate data on the page. Set regex=true for regex patterns. Use css_scope to search within a specific section.",function:uf,paramSchema:Uh}),i.register({name:"find_elements",description:"Query DOM elements by CSS selector. Zero LLM cost, instant. Returns element tag, text, and optional attributes. Use to find all links, extract table data, or analyze page structure without LLM.",function:df,paramSchema:Bh})}var vh,Sh,wh,Th,xh,Ch,Eh,Ih,kh,Ph,Ah,Dh,Mh,Rh,Oh,Nh,_h,$h,Fh,Lh,Uh,Bh,Jl=$(()=>{"use strict";dt();Wi();Bi();vh=U.object({url:U.string().describe("The URL to navigate to"),new_tab:U.boolean().optional().default(!1).describe("Open in a new tab")}),Sh=U.object({index:U.number().min(1).describe("The element index to click (must be >= 1)"),button:U.enum(["left","right","middle"]).optional().describe("Mouse button to use")}),wh=U.object({index:U.number().min(0).describe("The element index to type into (>= 0)"),text:U.string().describe("The text to type"),clear:U.boolean().optional().default(!0).describe("Clear existing text first")}),Th=U.object({down:U.boolean().describe("Scroll direction: true=down, false=up"),pages:U.number().optional().default(1).describe("Pages to scroll (0.5=half, 1=full, 10=to bottom/top)"),index:U.number().optional().describe("Optional element index for scrollable container")}),xh=U.object({text:U.string().describe("Summary of what was accomplished"),success:U.boolean().optional().default(!0).describe("Whether the task was successful"),files_to_display:U.array(U.string()).optional().default([]).describe("File paths to include")}),Ch=U.object({seconds:U.number().describe("Number of seconds to wait")}),Eh=U.object({keys:U.string().describe('Keys to send (e.g., "Enter", "Control+A")')}),Ih=U.object({full_page:U.boolean().optional().describe("Capture full page")}),kh=U.object({query:U.string().describe("The search query"),engine:U.enum(["google","bing","duckduckgo"]).optional().default("duckduckgo").describe("Search engine to use")}),Ph=U.object({tab_id:U.string().length(4).describe("The tab ID to switch to (exactly 4 chars from target_id)")}),Ah=U.object({tab_id:U.string().length(4).describe("The tab ID to close (exactly 4 chars from target_id)")}),Dh=U.object({text:U.string().describe("The text to find and scroll to")}),Mh=U.object({index:U.number().describe("The element index of the dropdown/select")}),Rh=U.object({index:U.number().describe("The element index of the dropdown/select"),text:U.string().describe("The text of the option to select")}),Oh=U.object({index:U.number().describe("The element index of the file input"),path:U.string().describe("The path of the file to upload")}),Nh=U.object({code:U.string().describe("JavaScript code to execute in the browser context")}),_h=U.object({query:U.string().describe("What information to extract from the page"),extract_links:U.boolean().optional().default(!1).describe("Whether to include URLs in extraction"),start_from_char:U.number().optional().default(0).describe("Character offset to start from (for pagination)")}),$h=U.object({file_name:U.string().describe("The filename with extension (e.g., notes.md, data.json)"),content:U.string().describe("The content to write to the file"),append:U.boolean().optional().default(!1).describe("Append to existing file instead of overwriting"),trailing_newline:U.boolean().optional().default(!0).describe("Add trailing newline"),leading_newline:U.boolean().optional().default(!1).describe("Add leading newline")}),Fh=U.object({file_name:U.string().describe("The filename to read")}),Lh=U.object({file_name:U.string().describe("The filename to modify"),old_str:U.string().describe("The string to find and replace"),new_str:U.string().describe("The replacement string")}),Uh=U.object({pattern:U.string().describe("Text or regex pattern to search for in page content"),regex:U.boolean().optional().default(!1).describe("Treat pattern as regex (default: literal text match)"),case_sensitive:U.boolean().optional().default(!1).describe("Case-sensitive search (default: case-insensitive)"),context_chars:U.number().optional().default(150).describe("Characters of surrounding context per match"),css_scope:U.string().optional().describe('CSS selector to limit search scope (e.g. "div#main")'),max_results:U.number().optional().default(25).describe("Maximum matches to return")}),Bh=U.object({selector:U.string().describe('CSS selector to query elements (e.g. "table tr", "a.link", "div.product")'),attributes:U.array(U.string()).optional().describe('Specific attributes to extract (e.g. ["href", "src", "class"])'),max_results:U.number().optional().default(50).describe("Maximum elements to return"),include_text:U.boolean().optional().default(!0).describe("Include text content of each element")})});import{z as ke}from"zod";import{v4 as gf}from"uuid";function Ki(i){return i.stepNumber>=i.maxSteps-1}function eu(i,e){let t=[];for(let n of i.action){let s=n.getIndex?.()??null;if(s!==null&&e.has(s)){let r=e.get(s);t.push(Bl(r))}else t.push(null)}return t}function tu(i,e){if(!e)return i;let t={};for(let[s,r]of Object.entries(e))if(typeof r=="object")for(let[o,a]of Object.entries(r))a&&(t[o]=a);else r&&(t[s]=r);if(Object.keys(t).length===0)return i;let n=i;for(let[s,r]of Object.entries(t))n=n.replace(new RegExp(r,"g"),`<secret>${s}</secret>`);return n}var Zl,mf,Ik,kk,Pk,Vi=$(()=>{"use strict";oo();Zl={useVision:"auto",visionDetailLevel:"auto",saveConversationPath:null,saveConversationPathEncoding:"utf-8",maxFailures:3,generateGif:!1,overrideSystemMessage:null,extendSystemMessage:null,includeAttributes:Ul,maxActionsPerStep:10,useThinking:!0,flashMode:!1,maxHistoryItems:null,pageExtractionLlm:null,calculateCost:!1,includeToolCallExamples:!1,llmTimeout:60,stepTimeout:120,finalResponseAfterFailure:!0,directlyOpenUrl:!0,includeRecentEvents:!1,sampleImages:null,availableFilePaths:null,waitBetweenActions:.1},mf={messages:[]},Ik={agentId:gf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1,messageManagerState:mf,fileSystemState:null};kk=ke.object({isDone:ke.boolean().nullable().optional(),success:ke.boolean().nullable().optional(),error:ke.string().nullable().optional(),attachments:ke.array(ke.string()).nullable().optional(),longTermMemory:ke.string().nullable().optional(),extractedContent:ke.string().nullable().optional(),includeExtractedContentOnlyOnce:ke.boolean().optional(),metadata:ke.record(ke.any()).nullable().optional(),includeInMemory:ke.boolean().optional()}).refine(i=>!(i.success===!0&&i.isDone!==!0),{message:"success=True can only be set when isDone=True. For regular actions that succeed, leave success as None. Use success=False only for actions that fail."}),Pk=ke.object({thinking:ke.string().nullable().optional(),evaluationPreviousGoal:ke.string().nullable().optional(),memory:ke.string().nullable().optional(),nextGoal:ke.string().nullable().optional(),action:ke.array(ke.any()).min(1)})});var Qi={};Le(Qi,{ActionResultSchema:()=>Cf,AgentOutputSchema:()=>co,DEFAULT_AGENT_SETTINGS:()=>hf,createAgentHistoryList:()=>Yi,createAgentOutputSchema:()=>lo,createAgentState:()=>Xi,getAgentBrain:()=>vf,getDurationSeconds:()=>yf,getFinalResult:()=>wf,isLastStep:()=>ff,isSuccessful:()=>Sf,loadHistoryFromFile:()=>xf,saveHistoryToFile:()=>Tf,validateActionResult:()=>bf});import{v4 as pf}from"uuid";import{z as me}from"zod";function Xi(){return{agentId:pf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1}}function ff(i){return i.stepNumber>=i.maxSteps-1}function bf(i){if(i.success===!0&&i.isDone!==!0)throw new Error("success=true can only be set when isDone=true. For regular actions that succeed, leave success as undefined/null. Use success=false only for actions that fail.")}function yf(i){return(i.stepEndTime-i.stepStartTime)/1e3}function vf(i){return{thinking:i.thinking,evaluationPreviousGoal:i.evaluationPreviousGoal||"",memory:i.memory||"",nextGoal:i.nextGoal||""}}function Yi(i,e){return{history:[],agentId:i,task:e,createdAt:Date.now(),finalResult:null}}function Sf(i){if(i.history&&i.history.length>0){let e=i.history[i.history.length-1];if(e.result&&e.result.length>0){let t=e.result[e.result.length-1];if(t.isDone===!0)return t.success??null}}return i.finalResult?.success!==void 0?i.finalResult.success:null}function wf(i){if(i.history&&i.history.length>0){let e=i.history[i.history.length-1];if(e.result&&e.result.length>0){let t=e.result[e.result.length-1];if(t.extractedContent)return t.extractedContent}}return i.finalResult?.extractedContent||null}async function Tf(i,e="AgentHistory.json",t){let n=await import("fs/promises"),s=JSON.parse(JSON.stringify(i));if(t){let r=o=>{if(typeof o=="string"){let a=o;for(let[c,l]of Object.entries(t))l&&(a=a.replace(new RegExp(l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),`[FILTERED:${c}]`));return a}if(Array.isArray(o))return o.map(r);if(o&&typeof o=="object"){let a={};for(let[c,l]of Object.entries(o))a[c]=r(l);return a}return o};s=r(s)}await n.writeFile(e,JSON.stringify(s,null,2),"utf-8")}async function xf(i="AgentHistory.json"){let t=await(await import("fs/promises")).readFile(i,"utf-8");return JSON.parse(t)}function lo(i){return me.object({thinking:me.string().nullable().optional(),evaluationPreviousGoal:me.string().nullable().optional(),memory:me.string().nullable().optional(),nextGoal:me.string().nullable().optional(),action:me.array(i).min(1)})}var hf,Cf,co,uo=$(()=>{"use strict";hf={saveConversationPath:null,saveConversationPathEncoding:"utf-8",useVision:"auto",visionDetailLevel:"auto",maxFailures:3,maxActionsPerStep:4,useThinking:!0,flashMode:!1,calculateCost:!1,includeToolCallExamples:!1,llmTimeout:60,stepTimeout:180,finalResponseAfterFailure:!0};Cf=me.object({isDone:me.boolean().optional(),success:me.boolean().nullable().optional(),error:me.string().nullable().optional(),attachments:me.array(me.string()).nullable().optional(),longTermMemory:me.string().nullable().optional(),extractedContent:me.string().nullable().optional(),includeExtractedContentOnlyOnce:me.boolean().optional(),metadata:me.record(me.any()).nullable().optional(),includeInMemory:me.boolean().optional()}).refine(i=>!(i.success===!0&&i.isDone!==!0),{message:"success=true can only be set when isDone=true"}),co=me.object({thinking:me.string().nullable().optional(),evaluationPreviousGoal:me.string().nullable().optional(),memory:me.string().nullable().optional(),nextGoal:me.string().nullable().optional(),action:me.array(me.any()).min(1)})});function nu(i){return i.content?typeof i.content=="string"?i.content:Array.isArray(i.content)?i.content.filter(e=>e.type==="text").map(e=>e.text).join(`
700
+ `):"":""}function Dn(i,e){return{role:"user",content:i,name:e}}function Ji(i,e){return{role:"system",content:i,name:e}}var Zi=$(()=>{"use strict"});import{z as Oe}from"zod";function Ks(i){let e=i.stepNumber!==null&&i.stepNumber!==void 0?"step":"step_unknown";if(i.error)return`<${e}>
701
701
  ${i.error}`;if(i.systemMessage)return i.systemMessage;{let t=[];i.evaluationPreviousGoal&&t.push(i.evaluationPreviousGoal),i.memory&&t.push(i.memory),i.nextGoal&&t.push(i.nextGoal),i.actionResults&&t.push(i.actionResults);let n=t.join(`
702
702
  `);return`<${e}>
703
- ${n}`}}function ea(i){let e=[];return i.systemMessage&&e.push(i.systemMessage),i.stateMessage&&e.push(i.stateMessage),e.push(...i.contextMessages),e}function su(){return{history:{systemMessage:null,stateMessage:null,contextMessages:[]},toolId:1,agentHistoryItems:[{stepNumber:0,systemMessage:"Agent initialized"}],readStateDescription:""}}var Ef,If,Nk,ru=F(()=>{"use strict";Ef=Re.object({stepNumber:Re.number().nullable().optional(),evaluationPreviousGoal:Re.string().nullable().optional(),memory:Re.string().nullable().optional(),nextGoal:Re.string().nullable().optional(),actionResults:Re.string().nullable().optional(),error:Re.string().nullable().optional(),systemMessage:Re.string().nullable().optional()}).refine(i=>!(i.error&&i.systemMessage),{message:"Cannot have both error and systemMessage at the same time"});If=Re.object({systemMessage:Re.any().nullable().optional(),stateMessage:Re.any().nullable().optional(),contextMessages:Re.array(Re.any()).default([])});Nk=Re.object({history:If,toolId:Re.number().default(1),agentHistoryItems:Re.array(Ef).default([{stepNumber:0,systemMessage:"Agent initialized"}]),readStateDescription:Re.string().default("")})});import{minimatch as ta}from"minimatch";function na(i){return["about:blank","chrome://new-tab-page/","chrome://new-tab-page","chrome://newtab/","chrome://newtab"].includes(i)}function ou(i,e,t=!1){try{if(na(i))return!1;let n=new URL(i),s=n.protocol.replace(":","").toLowerCase(),r=n.hostname.toLowerCase();if(!s||!r)return!1;e=e.toLowerCase();let o,a;if(e.includes("://")?[o,a]=e.split("://",2):(o="https",a=e),a.includes(":")&&!a.startsWith(":")&&([a]=a.split(":",2)),!ta(s,o))return!1;if(a==="*"||r===a)return!0;if(a.includes("*")){let c=(a.match(/\*\./g)||[]).length,l=(a.match(/\.\*/g)||[]).length;if(c>1||l>1)return t&&console.error(`⛔️ Multiple wildcards in pattern=[${e}] are not supported`),!1;if(a.endsWith(".*"))return t&&console.error(`⛔️ Wildcard TLDs like in pattern=[${e}] are not supported for security`),!1;if(a.replace(/\*\./g,"").includes("*"))return t&&console.error(`⛔️ Only *.domain style patterns are supported, ignoring pattern=[${e}]`),!1;if(a.startsWith("*.")){let g=a.substring(2);if(r===g||ta(r,g))return!0}if(ta(r,a))return!0}return!1}catch(n){return console.error(`⛔️ Error matching URL ${i} with pattern ${e}: ${n?.name}: ${n?.message}`),!1}}var sa=F(()=>{"use strict";dt()});import iu from"fs";import au from"path";import{fileURLToPath as kf}from"url";var go,mo,ra=F(()=>{"use strict";oo();sa();go=class{maxActionsPerStep;useThinking;flashMode;promptTemplate="";systemMessage;constructor(e=10,t,n,s=!0,r=!1){this.maxActionsPerStep=e,this.useThinking=s,this.flashMode=r;let o="";t?o=t:(this.loadPromptTemplate(),o=this.promptTemplate.replace("{max_actions}",String(this.maxActionsPerStep))),n&&(o+=`
703
+ ${n}`}}function ea(i){let e=[];return i.systemMessage&&e.push(i.systemMessage),i.stateMessage&&e.push(i.stateMessage),e.push(...i.contextMessages),e}function su(){return{history:{systemMessage:null,stateMessage:null,contextMessages:[]},toolId:1,agentHistoryItems:[{stepNumber:0,systemMessage:"Agent initialized"}],readStateDescription:""}}var Ef,If,Nk,ru=$(()=>{"use strict";Ef=Oe.object({stepNumber:Oe.number().nullable().optional(),evaluationPreviousGoal:Oe.string().nullable().optional(),memory:Oe.string().nullable().optional(),nextGoal:Oe.string().nullable().optional(),actionResults:Oe.string().nullable().optional(),error:Oe.string().nullable().optional(),systemMessage:Oe.string().nullable().optional()}).refine(i=>!(i.error&&i.systemMessage),{message:"Cannot have both error and systemMessage at the same time"});If=Oe.object({systemMessage:Oe.any().nullable().optional(),stateMessage:Oe.any().nullable().optional(),contextMessages:Oe.array(Oe.any()).default([])});Nk=Oe.object({history:If,toolId:Oe.number().default(1),agentHistoryItems:Oe.array(Ef).default([{stepNumber:0,systemMessage:"Agent initialized"}]),readStateDescription:Oe.string().default("")})});import{minimatch as ta}from"minimatch";function na(i){return["about:blank","chrome://new-tab-page/","chrome://new-tab-page","chrome://newtab/","chrome://newtab"].includes(i)}function ou(i,e,t=!1){try{if(na(i))return!1;let n=new URL(i),s=n.protocol.replace(":","").toLowerCase(),r=n.hostname.toLowerCase();if(!s||!r)return!1;e=e.toLowerCase();let o,a;if(e.includes("://")?[o,a]=e.split("://",2):(o="https",a=e),a.includes(":")&&!a.startsWith(":")&&([a]=a.split(":",2)),!ta(s,o))return!1;if(a==="*"||r===a)return!0;if(a.includes("*")){let c=(a.match(/\*\./g)||[]).length,l=(a.match(/\.\*/g)||[]).length;if(c>1||l>1)return t&&console.error(`⛔️ Multiple wildcards in pattern=[${e}] are not supported`),!1;if(a.endsWith(".*"))return t&&console.error(`⛔️ Wildcard TLDs like in pattern=[${e}] are not supported for security`),!1;if(a.replace(/\*\./g,"").includes("*"))return t&&console.error(`⛔️ Only *.domain style patterns are supported, ignoring pattern=[${e}]`),!1;if(a.startsWith("*.")){let g=a.substring(2);if(r===g||ta(r,g))return!0}if(ta(r,a))return!0}return!1}catch(n){return console.error(`⛔️ Error matching URL ${i} with pattern ${e}: ${n?.name}: ${n?.message}`),!1}}var sa=$(()=>{"use strict";dt()});import iu from"fs";import au from"path";import{fileURLToPath as kf}from"url";var go,mo,ra=$(()=>{"use strict";oo();sa();go=class{maxActionsPerStep;useThinking;flashMode;promptTemplate="";systemMessage;constructor(e=10,t,n,s=!0,r=!1){this.maxActionsPerStep=e,this.useThinking=s,this.flashMode=r;let o="";t?o=t:(this.loadPromptTemplate(),o=this.promptTemplate.replace("{max_actions}",String(this.maxActionsPerStep))),n&&(o+=`
704
704
  ${n}`),this.systemMessage={role:"system",content:o,cache:!0}}loadPromptTemplate(){try{let e;this.flashMode?e="system_prompt_flash.md":this.useThinking?e="system_prompt.md":e="system_prompt_no_thinking.md";let t=import.meta.url,n=kf(t),s=au.dirname(n),r=au.join(s,e);iu.existsSync(r)?this.promptTemplate=iu.readFileSync(r,"utf-8"):(console.warn(`System prompt template not found at ${r}, using fallback`),this.promptTemplate=this.getFallbackTemplate())}catch(e){console.warn(`Failed to load system prompt template: ${e.message}, using fallback`),this.promptTemplate=this.getFallbackTemplate()}}getFallbackTemplate(){return`You are an AI agent designed to operate in an iterative loop to automate browser tasks.
705
705
  Your ultimate goal is accomplishing the task provided by the user.
706
706
 
@@ -750,7 +750,7 @@ You must respond with a valid JSON in this format:
750
750
  "action": [{"action_name": {"param": "value"}}]
751
751
  }
752
752
  </output>`}getSystemMessage(){return this.systemMessage}},mo=class{browserState;fileSystem;agentHistoryDescription;readStateDescription;task;includeAttributes;stepInfo;pageFilteredActions;maxClickableElementsLength;sensitiveData;availableFilePaths;screenshots;visionDetailLevel;includeRecentEvents;sampleImages;constructor(e){this.browserState=e.browserStateSummary,this.fileSystem=e.fileSystem,this.agentHistoryDescription=e.agentHistoryDescription||null,this.readStateDescription=e.readStateDescription||null,this.task=e.task||null,this.includeAttributes=e.includeAttributes||null,this.stepInfo=e.stepInfo||null,this.pageFilteredActions=e.pageFilteredActions||null,this.maxClickableElementsLength=e.maxClickableElementsLength||4e4,this.sensitiveData=e.sensitiveData||null,this.availableFilePaths=e.availableFilePaths||null,this.screenshots=e.screenshots||[],this.visionDetailLevel=e.visionDetailLevel||"auto",this.includeRecentEvents=e.includeRecentEvents||!1,this.sampleImages=e.sampleImages||[]}extractPageStatistics(){let e={links:0,iframes:0,shadow_open:0,shadow_closed:0,scroll_containers:0,images:0,interactive_elements:0,total_elements:0},t=this.browserState.domState?.selectorMap;if(t&&t instanceof Map){e.interactive_elements=t.size;for(let n of Array.from(t.values())){let s=(n.nodeName||"").toLowerCase();s==="a"?e.links+=1:s==="iframe"||s==="frame"?e.iframes+=1:s==="img"&&(e.images+=1),n.isScrollable&&(e.scroll_containers+=1)}}if(this.browserState.domState?.root){let n=s=>{if(!s)return 0;let r=1;if(s.children&&Array.isArray(s.children))for(let o of s.children)r+=n(o);return r};e.total_elements=n(this.browserState.domState.root)}else t&&(e.total_elements=t.size);if(this.browserState.domState?.root){let n=s=>{if(!s||!s.originalNode)return;let r=s.originalNode;s.isShadowHost&&(s.children.some(a=>a.originalNode.nodeType===11&&a.originalNode.shadowRootType&&a.originalNode.shadowRootType.toLowerCase()==="closed")?e.shadow_closed+=1:e.shadow_open+=1);for(let o of s.children)n(o)};n(this.browserState.domState.root)}return e}getBrowserStateDescription(){let e=this.extractPageStatistics(),t="<page_stats>";e.total_elements<10&&(t+="Page appears empty (SPA not loaded?) - "),t+=`${e.links} links, ${e.interactive_elements} interactive, `,t+=`${e.iframes} iframes, ${e.scroll_containers} scroll containers`,(e.shadow_open>0||e.shadow_closed>0)&&(t+=`, ${e.shadow_open} shadow(open), ${e.shadow_closed} shadow(closed)`),e.images>0&&(t+=`, ${e.images} images`),t+=`, ${e.total_elements} total elements`,t+=`</page_stats>
753
- `;let n=this.browserState.domState?.llmRepresentation?.(this.includeAttributes||[])||"",s="";n.length>this.maxClickableElementsLength&&(n=n.substring(0,this.maxClickableElementsLength),s=` (truncated to ${this.maxClickableElementsLength} characters)`);let r=!1,o=!1,a="";if(this.browserState.pageInfo){let f=this.browserState.pageInfo,y=f.viewportHeight>0?f.pixelsAbove/f.viewportHeight:0,T=f.viewportHeight>0?f.pixelsBelow/f.viewportHeight:0;r=y>0,o=T>0;let x=f.viewportHeight>0?f.pageHeight/f.viewportHeight:0;a="<page_info>",a+=`${y.toFixed(1)} pages above, `,a+=`${T.toFixed(1)} pages below, `,a+=`${x.toFixed(1)} total pages`,a+=`</page_info>
753
+ `;let n=this.browserState.domState?.llmRepresentation?.(this.includeAttributes||[])||"",s="";n.length>this.maxClickableElementsLength&&(n=n.substring(0,this.maxClickableElementsLength),s=` (truncated to ${this.maxClickableElementsLength} characters)`);let r=!1,o=!1,a="";if(this.browserState.pageInfo){let f=this.browserState.pageInfo,y=f.viewportHeight>0?f.pixelsAbove/f.viewportHeight:0,T=f.viewportHeight>0?f.pixelsBelow/f.viewportHeight:0;r=y>0,o=T>0;let C=f.viewportHeight>0?f.pageHeight/f.viewportHeight:0;a="<page_info>",a+=`${y.toFixed(1)} pages above, `,a+=`${T.toFixed(1)} pages below, `,a+=`${C.toFixed(1)} total pages`,a+=`</page_info>
754
754
  `}if(n!==""){if(r&&this.browserState.pageInfo){let f=this.browserState.pageInfo;n=`... ${(f.viewportHeight>0?f.pixelsAbove/f.viewportHeight:0).toFixed(1)} pages above - scroll to see more or extract structured data if you are looking for specific information ...
755
755
  ${n}`}else n=`[Start of page]
756
756
  ${n}`;if(o&&this.browserState.pageInfo){let f=this.browserState.pageInfo,y=f.viewportHeight>0?f.pixelsBelow/f.viewportHeight:0;n=`${n}
@@ -797,9 +797,9 @@ Use with absolute paths</available_file_paths>
797
797
  `),this.pageFilteredActions&&(t+=`<page_specific_actions>
798
798
  `,t+=this.pageFilteredActions+`
799
799
  `,t+=`</page_specific_actions>
800
- `),e&&this.screenshots.length>0){let s=[{type:"text",text:t}];s.push(...this.sampleImages);for(let r=0;r<this.screenshots.length;r++){let o=this.screenshots[r],a=r===this.screenshots.length-1?"Current screenshot:":"Previous screenshot:";s.push({type:"text",text:a}),s.push({type:"image_url",imageUrl:{url:`data:image/jpeg;base64,${o}`,mediaType:"image/jpeg",detail:this.visionDetailLevel}})}return{role:"user",content:s,cache:!0}}return{role:"user",content:t,cache:!0}}}});var po,cu=F(()=>{"use strict";ru();ra();Zi();sa();po=class{task;state;systemPrompt;fileSystem;sensitiveDataDescription="";useThinking;maxHistoryItems;visionDetailLevel;includeToolCallExamples;includeRecentEvents;sampleImages;includeAttributes;sensitiveData;lastInputMessages=[];lastStateMessageText;constructor(e){if(this.task=e.task,this.state=e.state||su(),this.systemPrompt=e.systemMessage,this.fileSystem=e.fileSystem,this.useThinking=e.useThinking??!0,this.maxHistoryItems=e.maxHistoryItems??null,this.visionDetailLevel=e.visionDetailLevel||"auto",this.includeToolCallExamples=e.includeToolCallExamples||!1,this.includeRecentEvents=e.includeRecentEvents||!1,this.sampleImages=e.sampleImages,this.includeAttributes=e.includeAttributes||[],this.sensitiveData=e.sensitiveData,this.maxHistoryItems!==null&&this.maxHistoryItems<=5)throw new Error("maxHistoryItems must be null or greater than 5");ea(this.state.history).length===0&&this.setMessageWithType(this.systemPrompt,"system")}get agentHistoryDescription(){if(this.maxHistoryItems===null)return this.state.agentHistoryItems.map(qs).join(`
801
- `);let e=this.state.agentHistoryItems.length;if(e<=this.maxHistoryItems)return this.state.agentHistoryItems.map(qs).join(`
802
- `);let t=e-this.maxHistoryItems,n=this.maxHistoryItems-1,s=[qs(this.state.agentHistoryItems[0]),`<sys>[... ${t} previous steps omitted...]</sys>`],r=this.state.agentHistoryItems.slice(-n);return s.push(...r.map(qs)),s.join(`
800
+ `),e&&this.screenshots.length>0){let s=[{type:"text",text:t}];s.push(...this.sampleImages);for(let r=0;r<this.screenshots.length;r++){let o=this.screenshots[r],a=r===this.screenshots.length-1?"Current screenshot:":"Previous screenshot:";s.push({type:"text",text:a}),s.push({type:"image_url",imageUrl:{url:`data:image/jpeg;base64,${o}`,mediaType:"image/jpeg",detail:this.visionDetailLevel}})}return{role:"user",content:s,cache:!0}}return{role:"user",content:t,cache:!0}}}});var po,cu=$(()=>{"use strict";ru();ra();Zi();sa();po=class{task;state;systemPrompt;fileSystem;sensitiveDataDescription="";useThinking;maxHistoryItems;visionDetailLevel;includeToolCallExamples;includeRecentEvents;sampleImages;includeAttributes;sensitiveData;lastInputMessages=[];lastStateMessageText;constructor(e){if(this.task=e.task,this.state=e.state||su(),this.systemPrompt=e.systemMessage,this.fileSystem=e.fileSystem,this.useThinking=e.useThinking??!0,this.maxHistoryItems=e.maxHistoryItems??null,this.visionDetailLevel=e.visionDetailLevel||"auto",this.includeToolCallExamples=e.includeToolCallExamples||!1,this.includeRecentEvents=e.includeRecentEvents||!1,this.sampleImages=e.sampleImages,this.includeAttributes=e.includeAttributes||[],this.sensitiveData=e.sensitiveData,this.maxHistoryItems!==null&&this.maxHistoryItems<=5)throw new Error("maxHistoryItems must be null or greater than 5");ea(this.state.history).length===0&&this.setMessageWithType(this.systemPrompt,"system")}get agentHistoryDescription(){if(this.maxHistoryItems===null)return this.state.agentHistoryItems.map(Ks).join(`
801
+ `);let e=this.state.agentHistoryItems.length;if(e<=this.maxHistoryItems)return this.state.agentHistoryItems.map(Ks).join(`
802
+ `);let t=e-this.maxHistoryItems,n=this.maxHistoryItems-1,s=[Ks(this.state.agentHistoryItems[0]),`<sys>[... ${t} previous steps omitted...]</sys>`],r=this.state.agentHistoryItems.slice(-n);return s.push(...r.map(Ks)),s.join(`
803
803
  `)}addNewTask(e){let t=`<follow_up_user_request> ${e.trim()} </follow_up_user_request>`;this.task.includes("<initial_user_request>")||(this.task=`<initial_user_request>${this.task}</initial_user_request>`),this.task+=`
804
804
  `+t;let n={systemMessage:t};this.state.agentHistoryItems.push(n)}updateAgentHistoryDescription(e,t,n){let s=t||[],r=n?.stepNumber;this.state.readStateDescription="";let o="",a=0;for(let l=0;l<s.length;l++){let d=s[l];if(d.includeExtractedContentOnlyOnce&&d.extractedContent&&(this.state.readStateDescription+=`<read_state_${a}>
805
805
  ${d.extractedContent}
@@ -812,15 +812,15 @@ ${d.extractedContent}
812
812
  ${o}`),o=o?o.trim():"",o&&o.length>c&&(o=o.substring(0,c)+`
813
813
  ... [Content truncated at 60k characters]`),e){let l={evaluationPreviousGoal:e.evaluationPreviousGoal||"",memory:e.memory||"",nextGoal:e.nextGoal||""},d={stepNumber:r,evaluationPreviousGoal:l.evaluationPreviousGoal,memory:l.memory,nextGoal:l.nextGoal,actionResults:o||void 0};this.state.agentHistoryItems.push(d)}else if(r!=null){if(r===0&&o){let l={stepNumber:r,actionResults:o||void 0};this.state.agentHistoryItems.push(l)}else if(r>0){let l={stepNumber:r,error:"Agent failed to output in the right format."};this.state.agentHistoryItems.push(l)}}}getSensitiveDataDescription(e){if(!this.sensitiveData)return"";let t=new Set;for(let[n,s]of Object.entries(this.sensitiveData))typeof s=="object"?e&&ou(e,n)&&Object.keys(s).forEach(r=>t.add(r)):t.add(n);if(t.size>0){let n=Array.from(t).sort(),s=`Here are placeholders for sensitive data:
814
814
  ${JSON.stringify(n)}
815
- `;return s+="To use them, write <secret>the placeholder name</secret>",s}return""}createStateMessages(e,t){this.state.history.contextMessages=[],this.updateAgentHistoryDescription(t?.modelOutput,t?.result,t?.stepInfo);let n=t?.sensitiveData??this.sensitiveData;n&&(this.sensitiveData=n,this.sensitiveDataDescription=this.getSensitiveDataDescription(e.url));let s=[],r=!1;if(t?.result){for(let d of t.result)if(d.metadata?.includeScreenshot){r=!0;break}}let o=t?.useVision??"auto",a=!1;o===!0?a=!0:o==="auto"&&(a=r),a&&e.screenshot&&s.push(e.screenshot);let c=s.length>0,l=new mo({browserStateSummary:e,fileSystem:this.fileSystem,agentHistoryDescription:this.agentHistoryDescription,readStateDescription:this.state.readStateDescription,task:this.task,includeAttributes:this.includeAttributes,stepInfo:t?.stepInfo,pageFilteredActions:t?.pageFilteredActions,sensitiveData:this.sensitiveDataDescription,availableFilePaths:t?.availableFilePaths,screenshots:s,visionDetailLevel:this.visionDetailLevel,includeRecentEvents:this.includeRecentEvents,sampleImages:this.sampleImages}).getUserMessage(c);this.lastStateMessageText=nu(l),this.setMessageWithType(l,"state")}getMessages(){return this.lastInputMessages=ea(this.state.history),this.lastInputMessages}setMessageWithType(e,t){if(t==="system")this.state.history.systemMessage=e;else if(t==="state")this.state.history.stateMessage=e;else throw new Error(`Invalid state message type: ${t}`)}addContextMessage(e){this.state.history.contextMessages.push(e)}filterSensitiveData(e){if(!this.sensitiveData)return e;let t=s=>{if(!this.sensitiveData)return s;let r={};for(let[o,a]of Object.entries(this.sensitiveData))if(typeof a=="object"&&a!==null)for(let[c,l]of Object.entries(a))l&&(r[c]=l);else a&&(r[o]=a);for(let[o,a]of Object.entries(r)){let c=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(c,"g"),`<secret>${o}</secret>`)}return s},n={...e};return typeof n.content=="string"?n.content=t(n.content):Array.isArray(n.content)&&(n.content=n.content.map(s=>s.type==="text"&&s.text?{...s,text:t(s.text)}:s)),n}getFilteredMessages(){return this.getMessages().map(t=>this.filterSensitiveData(t))}}});import fo from"fs/promises";import Zt from"fs";import Vs from"path";var ho,Pf,An,en,Ks,bo,yo,vo,So,wo,To,lu=F(()=>{"use strict";dt();zs();ho="Error: Invalid filename format. Must be alphanumeric with supported extension.",Pf="browseruse_agent_data",An=class extends Error{constructor(e){super(e),this.name="FileSystemError"}},en=class{name;content;constructor(e,t=""){this.name=e,this.content=t}get fullName(){return`${this.name}.${this.extension}`}get size(){return this.content.length}get lineCount(){return this.content.split(`
816
- `).length}writeFileContent(e){this.updateContent(e)}appendFileContent(e){this.updateContent(this.content+e)}updateContent(e){this.content=e}async syncToDisk(e){let t=Vs.join(e,this.fullName);await fo.writeFile(t,this.content,"utf-8")}syncToDiskSync(e){let t=Vs.join(e,this.fullName);Zt.writeFileSync(t,this.content,"utf-8")}async write(e,t){this.writeFileContent(e),await this.syncToDisk(t)}async append(e,t){this.appendFileContent(e),await this.syncToDisk(t)}read(){return this.content}},Ks=class extends en{get extension(){return"md"}},bo=class extends en{get extension(){return"txt"}},yo=class extends en{get extension(){return"json"}},vo=class extends en{get extension(){return"csv"}},So=class extends en{get extension(){return"jsonl"}},wo=class extends en{get extension(){return"pdf"}async syncToDisk(e){let t=Vs.join(e,this.fullName);try{let n=await import("pdfkit").catch(()=>null);if(n&&n.default){let s=new n.default,r=[];s.on("data",l=>r.push(l));let o=new Promise(l=>{s.on("end",()=>l(Buffer.concat(r)))});s.fontSize(js.sm);let a=this.content.split(`
817
- `);for(let l of a)l.trim()&&(s.text(l.trim(),{align:"left"}),s.moveDown(.5));s.end();let c=await o;await fo.writeFile(t,c);return}}catch(n){b.debug("PDFKit not available, writing text file with .pdf extension:",n)}await fo.writeFile(t,this.content,"utf-8")}syncToDiskSync(e){let t=Vs.join(e,this.fullName);Zt.writeFileSync(t,this.content,"utf-8")}},To=class i{baseDir;dataDir;files=new Map;extractedContentCount=0;defaultFiles=["todo.md"];fileTypes={md:Ks,txt:bo,json:yo,jsonl:So,csv:vo,pdf:wo};constructor(e,t=!0){this.baseDir=e,this.dataDir=Vs.join(e,Pf);try{Zt.existsSync(this.baseDir)||Zt.mkdirSync(this.baseDir,{recursive:!0}),Zt.existsSync(this.dataDir)&&Zt.rmSync(this.dataDir,{recursive:!0,force:!0}),Zt.mkdirSync(this.dataDir,{recursive:!0})}catch(n){throw new An(`Failed to create file system directories: ${n.message}`)}t&&this.createDefaultFiles()}getAllowedExtensions(){return Object.keys(this.fileTypes)}getFileTypeClass(e){return this.fileTypes[e.toLowerCase()]||null}createDefaultFiles(){for(let e of this.defaultFiles){let[t,n]=this.parseFilename(e),s=this.getFileTypeClass(n);if(!s)throw new Error(`Error: Invalid file extension '${n}' for file '${e}'.`);let r=new s(t);this.files.set(e,r),r.syncToDiskSync(this.dataDir)}}isValidFilename(e){let t=Object.keys(this.fileTypes).join("|");return new RegExp(`^[a-zA-Z0-9_\\-]+\\.(${t})$`).test(e)}parseFilename(e){let t=e.lastIndexOf(".");if(t===-1)throw new Error("Invalid filename: no extension found");let n=e.substring(0,t),s=e.substring(t+1).toLowerCase();return[n,s]}getDir(){return this.dataDir}getFile(e){return this.isValidFilename(e)&&this.files.get(e)||null}async listFiles(){return Array.from(this.files.values()).map(e=>e.fullName)}displayFile(e){if(!this.isValidFilename(e))return null;let t=this.getFile(e);return t?t.read():null}async readFile(e,t=!1){if(t)try{let s;try{[,s]=this.parseFilename(e)}catch{return`Error: Invalid filename format ${e}. Must be alphanumeric with a supported extension.`}if(["md","txt","json","jsonl","csv"].includes(s)){let r=await fo.readFile(e,"utf-8");return`Read from file ${e}.
815
+ `;return s+="To use them, write <secret>the placeholder name</secret>",s}return""}createStateMessages(e,t){this.state.history.contextMessages=[],this.updateAgentHistoryDescription(t?.modelOutput,t?.result,t?.stepInfo);let n=t?.sensitiveData??this.sensitiveData;n&&(this.sensitiveData=n,this.sensitiveDataDescription=this.getSensitiveDataDescription(e.url));let s=[],r=!1;if(t?.result){for(let d of t.result)if(d.metadata?.includeScreenshot){r=!0;break}}let o=t?.useVision??"auto",a=!1;o===!0?a=!0:o==="auto"&&(a=r),a&&e.screenshot&&s.push(e.screenshot);let c=s.length>0,l=new mo({browserStateSummary:e,fileSystem:this.fileSystem,agentHistoryDescription:this.agentHistoryDescription,readStateDescription:this.state.readStateDescription,task:this.task,includeAttributes:this.includeAttributes,stepInfo:t?.stepInfo,pageFilteredActions:t?.pageFilteredActions,sensitiveData:this.sensitiveDataDescription,availableFilePaths:t?.availableFilePaths,screenshots:s,visionDetailLevel:this.visionDetailLevel,includeRecentEvents:this.includeRecentEvents,sampleImages:this.sampleImages}).getUserMessage(c);this.lastStateMessageText=nu(l),this.setMessageWithType(l,"state")}getMessages(){return this.lastInputMessages=ea(this.state.history),this.lastInputMessages}setMessageWithType(e,t){if(t==="system")this.state.history.systemMessage=e;else if(t==="state")this.state.history.stateMessage=e;else throw new Error(`Invalid state message type: ${t}`)}addContextMessage(e){this.state.history.contextMessages.push(e)}filterSensitiveData(e){if(!this.sensitiveData)return e;let t=s=>{if(!this.sensitiveData)return s;let r={};for(let[o,a]of Object.entries(this.sensitiveData))if(typeof a=="object"&&a!==null)for(let[c,l]of Object.entries(a))l&&(r[c]=l);else a&&(r[o]=a);for(let[o,a]of Object.entries(r)){let c=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(c,"g"),`<secret>${o}</secret>`)}return s},n={...e};return typeof n.content=="string"?n.content=t(n.content):Array.isArray(n.content)&&(n.content=n.content.map(s=>s.type==="text"&&s.text?{...s,text:t(s.text)}:s)),n}getFilteredMessages(){return this.getMessages().map(t=>this.filterSensitiveData(t))}}});import fo from"fs/promises";import tn from"fs";import Xs from"path";var ho,Pf,Mn,nn,Vs,bo,yo,vo,So,wo,To,lu=$(()=>{"use strict";dt();qs();ho="Error: Invalid filename format. Must be alphanumeric with supported extension.",Pf="browseruse_agent_data",Mn=class extends Error{constructor(e){super(e),this.name="FileSystemError"}},nn=class{name;content;constructor(e,t=""){this.name=e,this.content=t}get fullName(){return`${this.name}.${this.extension}`}get size(){return this.content.length}get lineCount(){return this.content.split(`
816
+ `).length}writeFileContent(e){this.updateContent(e)}appendFileContent(e){this.updateContent(this.content+e)}updateContent(e){this.content=e}async syncToDisk(e){let t=Xs.join(e,this.fullName);await fo.writeFile(t,this.content,"utf-8")}syncToDiskSync(e){let t=Xs.join(e,this.fullName);tn.writeFileSync(t,this.content,"utf-8")}async write(e,t){this.writeFileContent(e),await this.syncToDisk(t)}async append(e,t){this.appendFileContent(e),await this.syncToDisk(t)}read(){return this.content}},Vs=class extends nn{get extension(){return"md"}},bo=class extends nn{get extension(){return"txt"}},yo=class extends nn{get extension(){return"json"}},vo=class extends nn{get extension(){return"csv"}},So=class extends nn{get extension(){return"jsonl"}},wo=class extends nn{get extension(){return"pdf"}async syncToDisk(e){let t=Xs.join(e,this.fullName);try{let n=await import("pdfkit").catch(()=>null);if(n&&n.default){let s=new n.default,r=[];s.on("data",l=>r.push(l));let o=new Promise(l=>{s.on("end",()=>l(Buffer.concat(r)))});s.fontSize(zs.sm);let a=this.content.split(`
817
+ `);for(let l of a)l.trim()&&(s.text(l.trim(),{align:"left"}),s.moveDown(.5));s.end();let c=await o;await fo.writeFile(t,c);return}}catch(n){b.debug("PDFKit not available, writing text file with .pdf extension:",n)}await fo.writeFile(t,this.content,"utf-8")}syncToDiskSync(e){let t=Xs.join(e,this.fullName);tn.writeFileSync(t,this.content,"utf-8")}},To=class i{baseDir;dataDir;files=new Map;extractedContentCount=0;defaultFiles=["todo.md"];fileTypes={md:Vs,txt:bo,json:yo,jsonl:So,csv:vo,pdf:wo};constructor(e,t=!0){this.baseDir=e,this.dataDir=Xs.join(e,Pf);try{tn.existsSync(this.baseDir)||tn.mkdirSync(this.baseDir,{recursive:!0}),tn.existsSync(this.dataDir)&&tn.rmSync(this.dataDir,{recursive:!0,force:!0}),tn.mkdirSync(this.dataDir,{recursive:!0})}catch(n){throw new Mn(`Failed to create file system directories: ${n.message}`)}t&&this.createDefaultFiles()}getAllowedExtensions(){return Object.keys(this.fileTypes)}getFileTypeClass(e){return this.fileTypes[e.toLowerCase()]||null}createDefaultFiles(){for(let e of this.defaultFiles){let[t,n]=this.parseFilename(e),s=this.getFileTypeClass(n);if(!s)throw new Error(`Error: Invalid file extension '${n}' for file '${e}'.`);let r=new s(t);this.files.set(e,r),r.syncToDiskSync(this.dataDir)}}isValidFilename(e){let t=Object.keys(this.fileTypes).join("|");return new RegExp(`^[a-zA-Z0-9_\\-]+\\.(${t})$`).test(e)}parseFilename(e){let t=e.lastIndexOf(".");if(t===-1)throw new Error("Invalid filename: no extension found");let n=e.substring(0,t),s=e.substring(t+1).toLowerCase();return[n,s]}getDir(){return this.dataDir}getFile(e){return this.isValidFilename(e)&&this.files.get(e)||null}async listFiles(){return Array.from(this.files.values()).map(e=>e.fullName)}displayFile(e){if(!this.isValidFilename(e))return null;let t=this.getFile(e);return t?t.read():null}async readFile(e,t=!1){if(t)try{let s;try{[,s]=this.parseFilename(e)}catch{return`Error: Invalid filename format ${e}. Must be alphanumeric with a supported extension.`}if(["md","txt","json","jsonl","csv"].includes(s)){let r=await fo.readFile(e,"utf-8");return`Read from file ${e}.
818
818
  <content>
819
819
  ${r}
820
820
  </content>`}else return s==="pdf"?"Error: PDF reading not yet implemented for external files.":`Error: Cannot read file ${e} as ${s} extension is not supported.`}catch(s){return s.code==="ENOENT"?`Error: File '${e}' not found.`:s.code==="EACCES"?`Error: Permission denied to read file '${e}'.`:`Error: Could not read file '${e}'.`}if(!this.isValidFilename(e))return ho;let n=this.getFile(e);if(!n)return`File '${e}' not found.`;try{let s=n.read();return`Read from file ${e}.
821
821
  <content>
822
822
  ${s}
823
- </content>`}catch(s){return s instanceof An?s.message:`Error: Could not read file '${e}'.`}}async writeFile(e,t){if(!this.isValidFilename(e))return ho;try{let[n,s]=this.parseFilename(e),r=this.getFileTypeClass(s);if(!r)throw new Error(`Error: Invalid file extension '${s}' for file '${e}'.`);let o=this.files.get(e);if(!o){let a=new r(n);this.files.set(e,a),o=a}return await o.write(t,this.dataDir),`Data written to file ${e} successfully.`}catch(n){return n instanceof An?n.message:`Error: Could not write to file '${e}'. ${n.message}`}}async appendFile(e,t){if(!this.isValidFilename(e))return ho;let n=this.getFile(e);if(!n)return`File '${e}' not found.`;try{return await n.append(t,this.dataDir),`Data appended to file ${e} successfully.`}catch(s){return s instanceof An?s.message:`Error: Could not append to file '${e}'. ${s.message}`}}async replaceFileStr(e,t,n){if(!this.isValidFilename(e))return ho;if(!t)return"Error: Cannot replace empty string. Please provide a non-empty string to replace.";let s=this.getFile(e);if(!s)return`File '${e}' not found.`;try{let r=s.read();return r=r.replace(new RegExp(t,"g"),n),await s.write(r,this.dataDir),`Successfully replaced all occurrences of "${t}" with "${n}" in file ${e}`}catch(r){return r instanceof An?r.message:`Error: Could not replace string in file '${e}'. ${r.message}`}}async saveExtractedContent(e){let t=`extracted_content_${this.extractedContentCount}`,n=`${t}.md`,s=new Ks(t);return await s.write(e,this.dataDir),this.files.set(n,s),this.extractedContentCount+=1,n}describe(){let t="";for(let n of this.files.values()){if(n.fullName==="todo.md")continue;let s=n.read();if(!s){t+=`<file>
823
+ </content>`}catch(s){return s instanceof Mn?s.message:`Error: Could not read file '${e}'.`}}async writeFile(e,t){if(!this.isValidFilename(e))return ho;try{let[n,s]=this.parseFilename(e),r=this.getFileTypeClass(s);if(!r)throw new Error(`Error: Invalid file extension '${s}' for file '${e}'.`);let o=this.files.get(e);if(!o){let a=new r(n);this.files.set(e,a),o=a}return await o.write(t,this.dataDir),`Data written to file ${e} successfully.`}catch(n){return n instanceof Mn?n.message:`Error: Could not write to file '${e}'. ${n.message}`}}async appendFile(e,t){if(!this.isValidFilename(e))return ho;let n=this.getFile(e);if(!n)return`File '${e}' not found.`;try{return await n.append(t,this.dataDir),`Data appended to file ${e} successfully.`}catch(s){return s instanceof Mn?s.message:`Error: Could not append to file '${e}'. ${s.message}`}}async replaceFileStr(e,t,n){if(!this.isValidFilename(e))return ho;if(!t)return"Error: Cannot replace empty string. Please provide a non-empty string to replace.";let s=this.getFile(e);if(!s)return`File '${e}' not found.`;try{let r=s.read();return r=r.replace(new RegExp(t,"g"),n),await s.write(r,this.dataDir),`Successfully replaced all occurrences of "${t}" with "${n}" in file ${e}`}catch(r){return r instanceof Mn?r.message:`Error: Could not replace string in file '${e}'. ${r.message}`}}async saveExtractedContent(e){let t=`extracted_content_${this.extractedContentCount}`,n=`${t}.md`,s=new Vs(t);return await s.write(e,this.dataDir),this.files.set(n,s),this.extractedContentCount+=1,n}describe(){let t="";for(let n of this.files.values()){if(n.fullName==="todo.md")continue;let s=n.read();if(!s){t+=`<file>
824
824
  ${n.fullName} - [empty file]
825
825
  </file>
826
826
  `;continue}let r=s.split(`
@@ -846,7 +846,7 @@ ${l}
846
846
  `,t+=`${m}
847
847
  `,t+=`</content>
848
848
  </file>
849
- `)}return t.trim()}getTodoContents(){let e=this.getFile("todo.md");return e?e.read():""}getState(){let e={};for(let[t,n]of this.files.entries())e[t]={type:n.constructor.name,data:{name:n.name,content:n.content}};return{files:e,baseDir:this.baseDir,extractedContentCount:this.extractedContentCount}}nuke(){Zt.rmSync(this.dataDir,{recursive:!0,force:!0})}static fromState(e){let t=new i(e.baseDir,!1);t.extractedContentCount=e.extractedContentCount;for(let[n,s]of Object.entries(e.files)){let r=s.type,o=s.data,a;switch(r){case"MarkdownFile":a=new Ks(o.name,o.content);break;case"TxtFile":a=new bo(o.name,o.content);break;case"JsonFile":a=new yo(o.name,o.content);break;case"JsonlFile":a=new So(o.name,o.content);break;case"CsvFile":a=new vo(o.name,o.content);break;case"PdfFile":a=new wo(o.name,o.content);break;default:continue}t.files.set(n,a),a.syncToDiskSync(t.dataDir)}return t}}});import*as tn from"fs/promises";import*as oa from"path";var xo,uu=F(()=>{"use strict";xo=class{agentDirectory;screenshotsDir;constructor(e){this.agentDirectory=e,this.screenshotsDir=oa.join(this.agentDirectory,"screenshots")}async initialize(){await tn.mkdir(this.screenshotsDir,{recursive:!0})}async storeScreenshot(e,t){let n=`step_${t}.png`,s=oa.join(this.screenshotsDir,n),r=Buffer.from(e,"base64");return await tn.writeFile(s,r),s}async getScreenshot(e){if(!e)return null;try{return await tn.access(e),(await tn.readFile(e)).toString("base64")}catch{return null}}}});import{z as q}from"zod";async function gu(i){if(!i)return null;try{let e=await import("fs/promises"),t=await import("path");return await e.access(i).then(()=>!0).catch(()=>!1)?(await e.readFile(i)).toString("base64"):null}catch{return null}}var Co,du,Af,Df,Mf,gP,mP,mu=F(()=>{"use strict";Co="iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAFElEQVR4nGP8//8/AwwwMSAB3BwAlm4DBfIlvvkAAAAASUVORK5CYII=",du=q.object({url:q.string(),title:q.string(),targetId:q.string(),parentTargetId:q.string().nullable().optional()}),Af=q.object({viewportWidth:q.number(),viewportHeight:q.number(),pageWidth:q.number(),pageHeight:q.number(),scrollX:q.number(),scrollY:q.number(),pixelsAbove:q.number(),pixelsBelow:q.number(),pixelsLeft:q.number(),pixelsRight:q.number()}),Df=q.object({url:q.string(),method:q.string().default("GET"),loadingDurationMs:q.number().default(0),resourceType:q.string().nullable().optional()}),Mf=q.object({buttonType:q.string(),backendNodeId:q.number(),text:q.string(),selector:q.string(),isDisabled:q.boolean().default(!1)}),gP=q.object({domState:q.any(),url:q.string(),title:q.string(),tabs:q.array(du),screenshot:q.string().nullable().optional(),pageInfo:Af.nullable().optional(),pixelsAbove:q.number().default(0),pixelsBelow:q.number().default(0),browserErrors:q.array(q.string()).default([]),isPdfViewer:q.boolean().default(!1),recentEvents:q.string().nullable().optional(),pendingNetworkRequests:q.array(Df).default([]),paginationButtons:q.array(Mf).default([])}),mP=q.object({url:q.string(),title:q.string(),tabs:q.array(du),interactedElement:q.array(q.any().nullable()),screenshotPath:q.string().nullable().optional()})});import*as ia from"fs";async function pu(i){try{return await import(i)}catch{throw new Error(`Module '${i}' not available. Install with: npm install ${i}`)}}function hu(i){return i?["about:blank","chrome://newtab","chrome://new-tab-page","edge://newtab","about:newtab","about:home"].some(t=>i.toLowerCase().startsWith(t.toLowerCase())):!1}function fu(i){if(!i.includes("\\u"))return i;try{return i.replace(/\\u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}catch{return i}}async function Rf(i,e=!1){let t=[];for(let n of i.history){let s=n.state,r=s.screenshotPath,o=s.screenshot;if(r){let a=await gu(r);t.push(a)}else o?t.push(o):e&&t.push(null)}return t}async function bu(i){let{task:e,history:t,outputPath:n="agent_history.gif",duration:s=3e3,showGoals:r=!0,showTask:o=!0,showLogo:a=!1,fontSize:c=io.text,titleFontSize:l=io.title,goalFontSize:d=io.goal,margin:g=40,lineSpacing:m=1.5}=i;if(!t.history||t.history.length===0){console.warn("[GIF] No history to create GIF from");return}let p=await Rf(t,!0);if(!p||p.length===0){console.warn("[GIF] No screenshots found in history");return}let h=null;for(let f of p)if(f&&f!==Co){h=f;break}if(!h){console.warn("[GIF] No valid screenshots found (all are placeholders or from new tab pages)");return}try{await Of({task:e,history:t,screenshots:p,firstRealScreenshot:h,outputPath:n,duration:s,showGoals:r,showTask:o,showLogo:a,fontSize:c,titleFontSize:l,goalFontSize:d,margin:g,lineSpacing:m}),console.info(`[GIF] Created GIF at ${n}`)}catch(f){console.warn(`[GIF] Native GIF generation failed: ${f.message}`),console.info("[GIF] Falling back to HTML viewer"),await Ff({task:e,history:t,screenshots:p,outputPath:n.replace(".gif",".html"),duration:s,showGoals:r,showTask:o})}}async function Of(i){let{task:e,history:t,screenshots:n,firstRealScreenshot:s,outputPath:r,duration:o,showGoals:a,showTask:c,fontSize:l,titleFontSize:d,margin:g,lineSpacing:m}=i,p;try{let S=await pu("sharp");p=S.default||S}catch(S){throw new Error(`sharp library not available: ${S.message}`)}let h;try{let S=await pu("gif-encoder-2");h=S.default||S}catch(S){throw new Error(`gif-encoder-2 library not available: ${S.message}`)}let f=Buffer.from(s,"base64"),y=await p(f).metadata(),T=y.width||1920,x=y.height||1080,w=new h(T,x,"neuquant",!0);w.setDelay(o),w.setRepeat(0),w.setQuality(10),w.start();let C=[];if(c&&e){let S=await Nf(p,e,s,T,x,l,g);C.push(S)}let v=0;for(let S=0;S<t.history.length;S++){let I=t.history[S],P=n[S];if(!P)continue;if(P===Co){b.debug(`[GIF] Skipping placeholder screenshot from about:blank page at step ${S+1}`);continue}if(hu(I.state.url)){b.debug(`[GIF] Skipping screenshot from new tab page (${I.state.url}) at step ${S+1}`);continue}v++;let R=Buffer.from(P,"base64");if(a&&I.modelOutput){let $=I.modelOutput.currentState?.nextGoal||I.modelOutput.nextGoal||"",D=await _f(p,R,v,$,T,x,l,d,g);C.push(D)}else{let $=await p(R).resize(T,x,{fit:"fill"}).raw().toBuffer();C.push($)}}if(C.length===0){console.warn("[GIF] No valid frames to create GIF");return}for(let S of C)w.addFrame(S);w.finish();let E=w.out.getData();ia.writeFileSync(r,E)}async function Nf(i,e,t,n,s,r,o){return await i({create:{width:n,height:s,channels:4,background:{r:0,g:0,b:0,alpha:1}}}).raw().toBuffer()}async function _f(i,e,t,n,s,r,o,a,c){let l=fu(n),d=`
849
+ `)}return t.trim()}getTodoContents(){let e=this.getFile("todo.md");return e?e.read():""}getState(){let e={};for(let[t,n]of this.files.entries())e[t]={type:n.constructor.name,data:{name:n.name,content:n.content}};return{files:e,baseDir:this.baseDir,extractedContentCount:this.extractedContentCount}}nuke(){tn.rmSync(this.dataDir,{recursive:!0,force:!0})}static fromState(e){let t=new i(e.baseDir,!1);t.extractedContentCount=e.extractedContentCount;for(let[n,s]of Object.entries(e.files)){let r=s.type,o=s.data,a;switch(r){case"MarkdownFile":a=new Vs(o.name,o.content);break;case"TxtFile":a=new bo(o.name,o.content);break;case"JsonFile":a=new yo(o.name,o.content);break;case"JsonlFile":a=new So(o.name,o.content);break;case"CsvFile":a=new vo(o.name,o.content);break;case"PdfFile":a=new wo(o.name,o.content);break;default:continue}t.files.set(n,a),a.syncToDiskSync(t.dataDir)}return t}}});import*as sn from"fs/promises";import*as oa from"path";var xo,uu=$(()=>{"use strict";xo=class{agentDirectory;screenshotsDir;constructor(e){this.agentDirectory=e,this.screenshotsDir=oa.join(this.agentDirectory,"screenshots")}async initialize(){await sn.mkdir(this.screenshotsDir,{recursive:!0})}async storeScreenshot(e,t){let n=`step_${t}.png`,s=oa.join(this.screenshotsDir,n),r=Buffer.from(e,"base64");return await sn.writeFile(s,r),s}async getScreenshot(e){if(!e)return null;try{return await sn.access(e),(await sn.readFile(e)).toString("base64")}catch{return null}}}});import{z as K}from"zod";async function gu(i){if(!i)return null;try{let e=await import("fs/promises"),t=await import("path");return await e.access(i).then(()=>!0).catch(()=>!1)?(await e.readFile(i)).toString("base64"):null}catch{return null}}var Co,du,Af,Df,Mf,gP,mP,mu=$(()=>{"use strict";Co="iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAFElEQVR4nGP8//8/AwwwMSAB3BwAlm4DBfIlvvkAAAAASUVORK5CYII=",du=K.object({url:K.string(),title:K.string(),targetId:K.string(),parentTargetId:K.string().nullable().optional()}),Af=K.object({viewportWidth:K.number(),viewportHeight:K.number(),pageWidth:K.number(),pageHeight:K.number(),scrollX:K.number(),scrollY:K.number(),pixelsAbove:K.number(),pixelsBelow:K.number(),pixelsLeft:K.number(),pixelsRight:K.number()}),Df=K.object({url:K.string(),method:K.string().default("GET"),loadingDurationMs:K.number().default(0),resourceType:K.string().nullable().optional()}),Mf=K.object({buttonType:K.string(),backendNodeId:K.number(),text:K.string(),selector:K.string(),isDisabled:K.boolean().default(!1)}),gP=K.object({domState:K.any(),url:K.string(),title:K.string(),tabs:K.array(du),screenshot:K.string().nullable().optional(),pageInfo:Af.nullable().optional(),pixelsAbove:K.number().default(0),pixelsBelow:K.number().default(0),browserErrors:K.array(K.string()).default([]),isPdfViewer:K.boolean().default(!1),recentEvents:K.string().nullable().optional(),pendingNetworkRequests:K.array(Df).default([]),paginationButtons:K.array(Mf).default([])}),mP=K.object({url:K.string(),title:K.string(),tabs:K.array(du),interactedElement:K.array(K.any().nullable()),screenshotPath:K.string().nullable().optional()})});import*as ia from"fs";async function pu(i){try{return await import(i)}catch{throw new Error(`Module '${i}' not available. Install with: npm install ${i}`)}}function hu(i){return i?["about:blank","chrome://newtab","chrome://new-tab-page","edge://newtab","about:newtab","about:home"].some(t=>i.toLowerCase().startsWith(t.toLowerCase())):!1}function fu(i){if(!i.includes("\\u"))return i;try{return i.replace(/\\u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}catch{return i}}async function Rf(i,e=!1){let t=[];for(let n of i.history){let s=n.state,r=s.screenshotPath,o=s.screenshot;if(r){let a=await gu(r);t.push(a)}else o?t.push(o):e&&t.push(null)}return t}async function bu(i){let{task:e,history:t,outputPath:n="agent_history.gif",duration:s=3e3,showGoals:r=!0,showTask:o=!0,showLogo:a=!1,fontSize:c=io.text,titleFontSize:l=io.title,goalFontSize:d=io.goal,margin:g=40,lineSpacing:m=1.5}=i;if(!t.history||t.history.length===0){console.warn("[GIF] No history to create GIF from");return}let p=await Rf(t,!0);if(!p||p.length===0){console.warn("[GIF] No screenshots found in history");return}let h=null;for(let f of p)if(f&&f!==Co){h=f;break}if(!h){console.warn("[GIF] No valid screenshots found (all are placeholders or from new tab pages)");return}try{await Of({task:e,history:t,screenshots:p,firstRealScreenshot:h,outputPath:n,duration:s,showGoals:r,showTask:o,showLogo:a,fontSize:c,titleFontSize:l,goalFontSize:d,margin:g,lineSpacing:m}),console.info(`[GIF] Created GIF at ${n}`)}catch(f){console.warn(`[GIF] Native GIF generation failed: ${f.message}`),console.info("[GIF] Falling back to HTML viewer"),await Ff({task:e,history:t,screenshots:p,outputPath:n.replace(".gif",".html"),duration:s,showGoals:r,showTask:o})}}async function Of(i){let{task:e,history:t,screenshots:n,firstRealScreenshot:s,outputPath:r,duration:o,showGoals:a,showTask:c,fontSize:l,titleFontSize:d,margin:g,lineSpacing:m}=i,p;try{let S=await pu("sharp");p=S.default||S}catch(S){throw new Error(`sharp library not available: ${S.message}`)}let h;try{let S=await pu("gif-encoder-2");h=S.default||S}catch(S){throw new Error(`gif-encoder-2 library not available: ${S.message}`)}let f=Buffer.from(s,"base64"),y=await p(f).metadata(),T=y.width||1920,C=y.height||1080,w=new h(T,C,"neuquant",!0);w.setDelay(o),w.setRepeat(0),w.setQuality(10),w.start();let E=[];if(c&&e){let S=await Nf(p,e,s,T,C,l,g);E.push(S)}let v=0;for(let S=0;S<t.history.length;S++){let I=t.history[S],D=n[S];if(!D)continue;if(D===Co){b.debug(`[GIF] Skipping placeholder screenshot from about:blank page at step ${S+1}`);continue}if(hu(I.state.url)){b.debug(`[GIF] Skipping screenshot from new tab page (${I.state.url}) at step ${S+1}`);continue}v++;let M=Buffer.from(D,"base64");if(a&&I.modelOutput){let _=I.modelOutput.currentState?.nextGoal||I.modelOutput.nextGoal||"",F=await _f(p,M,v,_,T,C,l,d,g);E.push(F)}else{let _=await p(M).resize(T,C,{fit:"fill"}).raw().toBuffer();E.push(_)}}if(E.length===0){console.warn("[GIF] No valid frames to create GIF");return}for(let S of E)w.addFrame(S);w.finish();let x=w.out.getData();ia.writeFileSync(r,x)}async function Nf(i,e,t,n,s,r,o){return await i({create:{width:n,height:s,channels:4,background:{r:0,g:0,b:0,alpha:1}}}).raw().toBuffer()}async function _f(i,e,t,n,s,r,o,a,c){let l=fu(n),d=`
850
850
  <svg width="${s}" height="${r}" xmlns="http://www.w3.org/2000/svg">
851
851
  <defs>
852
852
  <filter id="shadow" x="-10%" y="-10%" width="120%" height="120%">
@@ -869,15 +869,15 @@ ${l}
869
869
  font-family="Arial, sans-serif" font-size="${o}"
870
870
  fill="white" text-anchor="middle" dominant-baseline="middle"
871
871
  filter="url(#shadow)">
872
- ${Xs($f(l,80))}
872
+ ${Ys($f(l,80))}
873
873
  </text>
874
874
  </svg>
875
- `;return await i(e).resize(s,r,{fit:"fill"}).composite([{input:Buffer.from(d),top:0,left:0}]).raw().toBuffer()}function Xs(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function $f(i,e){return i.length<=e?i:i.substring(0,e-3)+"..."}async function Ff(i){let{task:e,history:t,screenshots:n,outputPath:s,duration:r,showGoals:o,showTask:a}=i,c=[],l=0;for(let g=0;g<t.history.length;g++){let m=t.history[g],p=n[g];if(!p||p===Co||hu(m.state.url))continue;l++;let h=o&&m.modelOutput&&(m.modelOutput.currentState?.nextGoal||m.modelOutput.nextGoal)||"";c.push({screenshot:p,stepNumber:l,goal:fu(h),url:m.state.url})}let d=`<!DOCTYPE html>
875
+ `;return await i(e).resize(s,r,{fit:"fill"}).composite([{input:Buffer.from(d),top:0,left:0}]).raw().toBuffer()}function Ys(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function $f(i,e){return i.length<=e?i:i.substring(0,e-3)+"..."}async function Ff(i){let{task:e,history:t,screenshots:n,outputPath:s,duration:r,showGoals:o,showTask:a}=i,c=[],l=0;for(let g=0;g<t.history.length;g++){let m=t.history[g],p=n[g];if(!p||p===Co||hu(m.state.url))continue;l++;let h=o&&m.modelOutput&&(m.modelOutput.currentState?.nextGoal||m.modelOutput.nextGoal)||"";c.push({screenshot:p,stepNumber:l,goal:fu(h),url:m.state.url})}let d=`<!DOCTYPE html>
876
876
  <html lang="en">
877
877
  <head>
878
878
  <meta charset="UTF-8">
879
879
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
880
- <title>Agent History - ${Xs(e)}</title>
880
+ <title>Agent History - ${Ys(e)}</title>
881
881
  <style>
882
882
  * {
883
883
  margin: 0;
@@ -1040,7 +1040,7 @@ ${l}
1040
1040
  <body>
1041
1041
  <div class="header">
1042
1042
  <h1>Agent History Viewer</h1>
1043
- <p class="task">${Xs(e)}</p>
1043
+ <p class="task">${Ys(e)}</p>
1044
1044
  </div>
1045
1045
 
1046
1046
  <div class="container">
@@ -1050,8 +1050,8 @@ ${l}
1050
1050
  <img src="data:image/png;base64,${g.screenshot}" alt="Step ${g.stepNumber}">
1051
1051
  <div class="overlay">
1052
1052
  <div class="step-badge">Step ${g.stepNumber}</div>
1053
- ${g.goal?`<div class="goal">${Xs(g.goal)}</div>`:""}
1054
- <div class="url">${Xs(g.url)}</div>
1053
+ ${g.goal?`<div class="goal">${Ys(g.goal)}</div>`:""}
1054
+ <div class="url">${Ys(g.url)}</div>
1055
1055
  </div>
1056
1056
  </div>
1057
1057
  `).join("")}
@@ -1140,7 +1140,7 @@ ${l}
1140
1140
  });
1141
1141
  </script>
1142
1142
  </body>
1143
- </html>`;ia.writeFileSync(s,d),console.info(`[GIF] Created HTML viewer at ${s}`)}var yu=F(()=>{"use strict";dt();Vi();mu();zs()});import{v4 as Lf}from"uuid";import vu from"fs/promises";import Eo from"path";import Uf from"os";import Bf from"crypto";import{spawnSync as Wf}from"child_process";import{zodToJsonSchema as Hf}from"zod-to-json-schema";var Ys,Su=F(()=>{"use strict";dt();zi();so();Kl();Jl();Vi();uo();Zi();cu();ra();lu();uu();yu();Ys=class{id;task;llm;browserSession;actionRegistry;settings;maxSteps;pageId;state;history;outputSchema;dynamicAgentOutputSchema;doneAgentOutputSchema;ownsBrowserSession=!1;messageManager;fileSystem;screenshotService;sensitiveData;agentDirectory;registerNewStepCallback;registerDoneCallback;registerShouldStopCallback;registerExternalAgentStatusRaiseErrorCallback;initialUrl=null;initialActions=null;pauseResolve=null;pausePromise=null;constructor(e){if(this.id=Lf(),this.task=e.task,this.llm=e.llm,this.maxSteps=e.maxSteps||100,this.outputSchema=e.outputSchema,this.settings={...Zl,...e.settings},e.browserSession)this.browserSession=e.browserSession,this.ownsBrowserSession=!1;else{let a={headless:!1};if(es())try{let c=Ws();c&&c.cookies&&c.cookies.length>0&&(a.storageState=c,b.log(`🍪 [Agent] Auto-loaded profile with ${c.cookies.length} cookies`))}catch(c){console.warn(`⚠️ [Agent] Failed to load profile: ${c.message}`)}this.browserSession=new kn(a),this.ownsBrowserSession=!0}this.pageId=e.pageId,this.pageId&&b.log(`🔀 [Agent] Multi-agent mode: Agent ${this.id.substring(0,8)} assigned to tab ${this.pageId}`),e.actionRegistry?this.actionRegistry=e.actionRegistry:(this.actionRegistry=new ao,Ql(this.actionRegistry));let t=this.actionRegistry.createActionModel();this.dynamicAgentOutputSchema=lo(t);let n=this.actionRegistry.createActionModel(["done"]);this.doneAgentOutputSchema=lo(n),this.state=Xi(),this.history=Yi(this.id,this.task);let s=Uf.tmpdir();this.agentDirectory=Eo.join(s,`browser_use_agent_${this.id}`),this.fileSystem=new To(this.agentDirectory),this.screenshotService=new xo(this.agentDirectory),this.settings.directlyOpenUrl&&(this.initialUrl=this._extractStartUrl(this.task),this.initialUrl&&(b.log(`🔗 Found URL in task: ${this.initialUrl}, adding as initial action...`),this.initialActions=[{navigate:{url:this.initialUrl,new_tab:!1}}]));let o=new go(this.settings.maxActionsPerStep,this.settings.overrideSystemMessage,this.settings.extendSystemMessage,this.settings.useThinking,this.settings.flashMode).getSystemMessage();this.messageManager=new po({task:this.task,systemMessage:o,fileSystem:this.fileSystem,useThinking:this.settings.useThinking,includeAttributes:this.settings.includeAttributes??void 0,sensitiveData:this.sensitiveData,maxHistoryItems:this.settings.maxHistoryItems??void 0,visionDetailLevel:this.settings.visionDetailLevel,includeToolCallExamples:this.settings.includeToolCallExamples,includeRecentEvents:this.settings.includeRecentEvents,sampleImages:this.settings.sampleImages??void 0}),this.registerNewStepCallback=e.registerNewStepCallback,this.registerDoneCallback=e.registerDoneCallback,this.registerShouldStopCallback=e.registerShouldStopCallback,this.registerExternalAgentStatusRaiseErrorCallback=e.registerExternalAgentStatusRaiseErrorCallback,this.sensitiveData=e.sensitiveData}async run(e=100){let t=null;try{b.log(`🤖 Starting agent ${this.id.substring(0,8)} with task: ${this.task}`),b.log(`🔧 Agent setup: Session ID ${this.id.substring(this.id.length-4)}, max_steps: ${e}`);let n=Date.now();await this.screenshotService.initialize(),await this.browserSession.start();try{await this._executeInitialActions()}catch(s){if(!(s instanceof Error&&s.message==="Interrupted"))throw s}b.log(`🔄 Starting main execution loop with max ${e} steps...`);for(let s=0;s<e;s++){if(this.state.consecutiveFailures>=this.settings.maxFailures+(this.settings.finalResponseAfterFailure?1:0)){console.error(`❌ Stopping due to ${this.settings.maxFailures} consecutive failures`),t=`Stopped due to ${this.settings.maxFailures} consecutive failures`;break}if(this.state.stopped){b.log("🛑 Agent stopped"),t="Agent stopped programmatically";break}if(this.state.paused){for(b.log("⏸️ Agent paused, waiting for resume...");this.state.paused;)this.pausePromise?await this.pausePromise:await new Promise(a=>setTimeout(a,100));b.log("▶️ Agent resumed, continuing...")}let r={stepNumber:s,maxSteps:e};if(await this._executeStep(s,e,r)){b.log("✅ Task completed successfully"),this.registerDoneCallback&&await this.registerDoneCallback(this.history);break}}return this.state.nSteps>=e&&!this.state.stopped&&(t="Failed to complete task in maximum steps",b.log(`❌ ${t}`),this.history.push({modelOutput:null,result:[{error:t,includeInMemory:!0}],state:{url:"",title:"",tabs:[],interactedElement:[],screenshot:null,downloadedFiles:[],selectorMap:{}}})),this.history}catch(n){throw console.error("Agent run failed with exception:",n),t=n instanceof Error?n.message:String(n),n}finally{if(b.log("🧹 Cleaning up agent resources..."),this.settings.generateGif)try{let n=typeof this.settings.generateGif=="string"?this.settings.generateGif:Eo.join(this.agentDirectory,"agent_history.gif");b.log("📹 Generating GIF..."),await bu({task:this.task,history:this.history,outputPath:n,duration:3e3,showGoals:!0,showTask:!0}),b.log(`📹 GIF saved to ${n}`)}catch(n){console.error(`📹 GIF generation failed: ${n.message}`)}this.ownsBrowserSession&&await this.browserSession.stop()}}async step(e=null){let t=Date.now(),n=null;try{n=await this._prepareContext(e),await this._getNextAction(n),await this._executeActions(),await this._postProcess()}catch(s){await this._handleStepError(s)}finally{await this._finalize(n,t)}}async getBrowserState(){let e=this.pageId?await this.browserSession.getStateForPage(this.pageId):await this.browserSession.getState();return{url:e.url,title:e.title,domTree:[],selectorMap:new Map,screenshot:e.screenshot}}async buildMessages(e,t){let n=[],s=this.buildSystemPrompt(t);n.push(Ji(s));for(let o of this.history.history){let a=this.formatBrowserState(o.state);if(n.push(Pn(a)),o.modelOutput){let c=JSON.stringify(o.modelOutput);n.push({role:"assistant",content:c})}}let r=this.formatCurrentState(e,t);return n.push(Pn(r)),n}buildSystemPrompt(e){let t=this.actionRegistry.getPromptDescription();return`You are an AI agent designed to operate in an iterative loop to automate browser tasks.
1143
+ </html>`;ia.writeFileSync(s,d),console.info(`[GIF] Created HTML viewer at ${s}`)}var yu=$(()=>{"use strict";dt();Vi();mu();qs()});import{v4 as Lf}from"uuid";import vu from"fs/promises";import Eo from"path";import Uf from"os";import Bf from"crypto";import{spawnSync as Wf}from"child_process";import{zodToJsonSchema as Hf}from"zod-to-json-schema";var Qs,Su=$(()=>{"use strict";dt();zi();so();Kl();Jl();Vi();uo();Zi();cu();ra();lu();uu();yu();Qs=class{id;task;llm;browserSession;actionRegistry;settings;maxSteps;pageId;state;history;outputSchema;dynamicAgentOutputSchema;doneAgentOutputSchema;ownsBrowserSession=!1;messageManager;fileSystem;screenshotService;sensitiveData;agentDirectory;registerNewStepCallback;registerDoneCallback;registerShouldStopCallback;registerExternalAgentStatusRaiseErrorCallback;initialUrl=null;initialActions=null;pauseResolve=null;pausePromise=null;constructor(e){if(this.id=Lf(),this.task=e.task,this.llm=e.llm,this.maxSteps=e.maxSteps||100,this.outputSchema=e.outputSchema,this.settings={...Zl,...e.settings},e.browserSession)this.browserSession=e.browserSession,this.ownsBrowserSession=!1;else{let a={headless:!1};if(Pn())try{let c=ns();c&&c.cookies&&c.cookies.length>0&&(a.storageState=c,b.log(`🍪 [Agent] Auto-loaded profile with ${c.cookies.length} cookies`))}catch(c){console.warn(`⚠️ [Agent] Failed to load profile: ${c.message}`)}this.browserSession=new en(a),this.ownsBrowserSession=!0}this.pageId=e.pageId,this.pageId&&b.log(`🔀 [Agent] Multi-agent mode: Agent ${this.id.substring(0,8)} assigned to tab ${this.pageId}`),e.actionRegistry?this.actionRegistry=e.actionRegistry:(this.actionRegistry=new ao,Ql(this.actionRegistry));let t=this.actionRegistry.createActionModel();this.dynamicAgentOutputSchema=lo(t);let n=this.actionRegistry.createActionModel(["done"]);this.doneAgentOutputSchema=lo(n),this.state=Xi(),this.history=Yi(this.id,this.task);let s=Uf.tmpdir();this.agentDirectory=Eo.join(s,`browser_use_agent_${this.id}`),this.fileSystem=new To(this.agentDirectory),this.screenshotService=new xo(this.agentDirectory),this.settings.directlyOpenUrl&&(this.initialUrl=this._extractStartUrl(this.task),this.initialUrl&&(b.log(`🔗 Found URL in task: ${this.initialUrl}, adding as initial action...`),this.initialActions=[{navigate:{url:this.initialUrl,new_tab:!1}}]));let o=new go(this.settings.maxActionsPerStep,this.settings.overrideSystemMessage,this.settings.extendSystemMessage,this.settings.useThinking,this.settings.flashMode).getSystemMessage();this.messageManager=new po({task:this.task,systemMessage:o,fileSystem:this.fileSystem,useThinking:this.settings.useThinking,includeAttributes:this.settings.includeAttributes??void 0,sensitiveData:this.sensitiveData,maxHistoryItems:this.settings.maxHistoryItems??void 0,visionDetailLevel:this.settings.visionDetailLevel,includeToolCallExamples:this.settings.includeToolCallExamples,includeRecentEvents:this.settings.includeRecentEvents,sampleImages:this.settings.sampleImages??void 0}),this.registerNewStepCallback=e.registerNewStepCallback,this.registerDoneCallback=e.registerDoneCallback,this.registerShouldStopCallback=e.registerShouldStopCallback,this.registerExternalAgentStatusRaiseErrorCallback=e.registerExternalAgentStatusRaiseErrorCallback,this.sensitiveData=e.sensitiveData}async run(e=100){let t=null;try{b.log(`🤖 Starting agent ${this.id.substring(0,8)} with task: ${this.task}`),b.log(`🔧 Agent setup: Session ID ${this.id.substring(this.id.length-4)}, max_steps: ${e}`);let n=Date.now();await this.screenshotService.initialize(),await this.browserSession.start();try{await this._executeInitialActions()}catch(s){if(!(s instanceof Error&&s.message==="Interrupted"))throw s}b.log(`🔄 Starting main execution loop with max ${e} steps...`);for(let s=0;s<e;s++){if(this.state.consecutiveFailures>=this.settings.maxFailures+(this.settings.finalResponseAfterFailure?1:0)){console.error(`❌ Stopping due to ${this.settings.maxFailures} consecutive failures`),t=`Stopped due to ${this.settings.maxFailures} consecutive failures`;break}if(this.state.stopped){b.log("🛑 Agent stopped"),t="Agent stopped programmatically";break}if(this.state.paused){for(b.log("⏸️ Agent paused, waiting for resume...");this.state.paused;)this.pausePromise?await this.pausePromise:await new Promise(a=>setTimeout(a,100));b.log("▶️ Agent resumed, continuing...")}let r={stepNumber:s,maxSteps:e};if(await this._executeStep(s,e,r)){b.log("✅ Task completed successfully"),this.registerDoneCallback&&await this.registerDoneCallback(this.history);break}}return this.state.nSteps>=e&&!this.state.stopped&&(t="Failed to complete task in maximum steps",b.log(`❌ ${t}`),this.history.push({modelOutput:null,result:[{error:t,includeInMemory:!0}],state:{url:"",title:"",tabs:[],interactedElement:[],screenshot:null,downloadedFiles:[],selectorMap:{}}})),this.history}catch(n){throw console.error("Agent run failed with exception:",n),t=n instanceof Error?n.message:String(n),n}finally{if(b.log("🧹 Cleaning up agent resources..."),this.settings.generateGif)try{let n=typeof this.settings.generateGif=="string"?this.settings.generateGif:Eo.join(this.agentDirectory,"agent_history.gif");b.log("📹 Generating GIF..."),await bu({task:this.task,history:this.history,outputPath:n,duration:3e3,showGoals:!0,showTask:!0}),b.log(`📹 GIF saved to ${n}`)}catch(n){console.error(`📹 GIF generation failed: ${n.message}`)}this.ownsBrowserSession&&await this.browserSession.stop()}}async step(e=null){let t=Date.now(),n=null;try{n=await this._prepareContext(e),await this._getNextAction(n),await this._executeActions(),await this._postProcess()}catch(s){await this._handleStepError(s)}finally{await this._finalize(n,t)}}async getBrowserState(){let e=this.pageId?await this.browserSession.getStateForPage(this.pageId):await this.browserSession.getState();return{url:e.url,title:e.title,domTree:[],selectorMap:new Map,screenshot:e.screenshot}}async buildMessages(e,t){let n=[],s=this.buildSystemPrompt(t);n.push(Ji(s));for(let o of this.history.history){let a=this.formatBrowserState(o.state);if(n.push(Dn(a)),o.modelOutput){let c=JSON.stringify(o.modelOutput);n.push({role:"assistant",content:c})}}let r=this.formatCurrentState(e,t);return n.push(Dn(r)),n}buildSystemPrompt(e){let t=this.actionRegistry.getPromptDescription();return`You are an AI agent designed to operate in an iterative loop to automate browser tasks.
1144
1144
 
1145
1145
  Your ultimate goal is accomplishing the task: ${this.task}
1146
1146
 
@@ -1170,7 +1170,7 @@ Current URL: ${e.url}
1170
1170
  Title: ${e.title}
1171
1171
 
1172
1172
  What is your next action?`}async callLLM(e){if(this.outputSchema)return(await this.llm.ainvoke(e,this.outputSchema)).completion;let t=this.dynamicAgentOutputSchema||co;return(await this.llm.ainvoke(e,t)).completion}async executeActions(e){let t=[];for(let n=0;n<Math.min(e.length,this.settings.maxActionsPerStep);n++){let s=e[n],r=Object.keys(s)[0],o=s[r];b.log(` ⚡ Executing action ${n+1}/${e.length}: ${r}`);try{let a=this._createActionContext(),c=await this.actionRegistry.execute(r,o,a);if(t.push(c),c.isDone)break;if(c.error){console.error(` ❌ Error: ${c.error}`);break}}catch(a){console.error(` ❌ Failed to execute ${r}:`,a.message),t.push({error:`Failed to execute ${r}: ${a.message}`});break}}return t}logModelOutput(e){if(e.thinking&&this.settings.useThinking&&b.log(` 💡 Thinking: ${e.thinking.substring(0,100)}...`),e.evaluationPreviousGoal){let t=e.evaluationPreviousGoal;t.toLowerCase().includes("success")?b.log(` ✅ Eval: ${t}`):t.toLowerCase().includes("failure")?b.log(` ❌ Eval: ${t}`):b.log(` ❔ Eval: ${t}`)}e.memory&&b.log(` 🧠 Memory: ${e.memory}`),e.nextGoal&&b.log(` 🎯 Next goal: ${e.nextGoal}`)}browserStateToHistory(e){return{url:e.url,title:e.title,tabs:[],screenshot:e.screenshot}}async attemptFinalRecovery(){b.log("🔄 Attempting final recovery...");try{let e=[];e.push(Ji("You have exceeded the maximum number of failures. Provide a final summary of what was accomplished and what could not be completed."));let t=await this.llm.ainvoke(e);return{isDone:!0,success:!1,longTermMemory:typeof t.completion=="string"?t.completion:JSON.stringify(t.completion)}}catch{return{isDone:!0,success:!1,error:"Failed to generate final recovery response"}}}async saveConversationStep(e){if(!(!this.settings.saveConversationPath||!this.state.lastModelOutput))try{let t=Eo.resolve(this.settings.saveConversationPath),n=`conversation_${this.id}_${this.state.nSteps}.txt`,s=Eo.join(t,n);await vu.mkdir(t,{recursive:!0});let r=this._formatConversation(e,this.state.lastModelOutput),o=this.settings.saveConversationPathEncoding||"utf-8";await vu.writeFile(s,r,o),b.log(`💾 Saved conversation step ${this.state.nSteps} to ${s}`)}catch(t){console.error("Failed to save conversation:",t)}}_formatConversation(e,t){let n=[];for(let s of e)n.push(` ${s.role} `),n.push(s.text||""),n.push("");n.push(" RESPONSE");try{n.push(JSON.stringify(t,null,2))}catch{n.push(String(t))}return n.join(`
1173
- `)}getHistory(){return this.history}getState(){return this.state}addNewTask(e){this.task=e,this.messageManager.addNewTask(e),this.state.followUpTask=!0,this.state.stopped=!1,this.state.paused=!1}pause(){b.log("⏸️ Pausing agent..."),this.state.paused=!0,this.pausePromise||(this.pausePromise=new Promise(e=>{this.pauseResolve=e}))}resume(){b.log("▶️ Resuming agent..."),this.state.paused=!1,this.pauseResolve&&(this.pauseResolve(),this.pauseResolve=null,this.pausePromise=null)}stop(){b.log("🛑 Stopping agent..."),this.state.stopped=!0}async multiAct(e){let t=[],n=0,s=e.length;if(!this.browserSession)throw new Error("BrowserSession is not set up");let r="";try{r=await this.browserSession.getCurrentPageUrl()}catch{}for(let o=0;o<e.length;o++){let a=e[o];if(o>0&&a.done!==void 0){let l=`Done action is allowed only as a single action - stopped after action ${o} / ${s}.`;b.log(l);break}if(o>0){let c=this.settings.waitBetweenActions;await new Promise(l=>setTimeout(l,c*1e3))}try{await this._checkStopOrPause();let c=a,l=Object.keys(c)[0]||"unknown";this._logAction(a,l,o+1,s);let d=Date.now(),g=c[l]||{},m=this._createActionContext(),p=await this.actionRegistry.execute(l,g,m);if(n=(Date.now()-d)/1e3,t.push(p),(["click","navigate","send_keys","go_back","go_forward","evaluate"].includes(l)||l==="send_keys"&&(g.keys?.toLowerCase().includes("enter")||g.keys?.toLowerCase().includes("return")))&&o<s-1)try{let T=await this.browserSession.getCurrentPageUrl();if(T!==r&&T!==""&&r!==""){let x=s-o-1;b.log(`🔄 Page navigation detected: ${r} → ${T}`),b.log(`📍 Interrupting remaining ${x} actions (element indices now stale)`),this.browserSession.clearCachedState(),x>0&&t.push({extractedContent:`Page navigated to ${T}. Skipped ${x} remaining action(s) because element indices are now stale.`});break}r=T}catch{}if(t[t.length-1].isDone||t[t.length-1].error||o===s-1)break}catch(c){let l=c.message||String(c);console.error(`❌ Executing action ${o+1} failed: ${l}`),t.push({error:`Action failed: ${l}`});break}}return t}_logAction(e,t,n,s){let r="\x1B[34m",o="\x1B[35m",a="\x1B[0m",c;s>1?c=`▶️ [${n}/${s}] ${r}${t}${a}:`:c=`▶️ ${r}${t}${a}:`;let d=e[t],g=[];if(d&&typeof d=="object")for(let[m,p]of Object.entries(d)){let h=p;typeof p=="string"&&p.length>150?h=p.substring(0,150)+"...":Array.isArray(p)&&JSON.stringify(p).length>200&&(h=JSON.stringify(p).substring(0,200)+"..."),typeof h=="string"&&this.sensitiveData&&(h=tu(h,this.sensitiveData)),g.push(`${o}${m}${a}: ${h}`)}if(g.length>0){let m=g.join(", ");b.log(` ${c} ${m}`)}else b.log(` ${c}`)}_logStepContext(e){let t=e?.url||"",n=t.length>50?t.substring(0,50)+"...":t,s=e?.domState?.selectorMap?.size||0;b.log(`
1173
+ `)}getHistory(){return this.history}getState(){return this.state}addNewTask(e){this.task=e,this.messageManager.addNewTask(e),this.state.followUpTask=!0,this.state.stopped=!1,this.state.paused=!1}pause(){b.log("⏸️ Pausing agent..."),this.state.paused=!0,this.pausePromise||(this.pausePromise=new Promise(e=>{this.pauseResolve=e}))}resume(){b.log("▶️ Resuming agent..."),this.state.paused=!1,this.pauseResolve&&(this.pauseResolve(),this.pauseResolve=null,this.pausePromise=null)}stop(){b.log("🛑 Stopping agent..."),this.state.stopped=!0}async multiAct(e){let t=[],n=0,s=e.length;if(!this.browserSession)throw new Error("BrowserSession is not set up");let r="";try{r=await this.browserSession.getCurrentPageUrl()}catch{}for(let o=0;o<e.length;o++){let a=e[o];if(o>0&&a.done!==void 0){let l=`Done action is allowed only as a single action - stopped after action ${o} / ${s}.`;b.log(l);break}if(o>0){let c=this.settings.waitBetweenActions;await new Promise(l=>setTimeout(l,c*1e3))}try{await this._checkStopOrPause();let c=a,l=Object.keys(c)[0]||"unknown";this._logAction(a,l,o+1,s);let d=Date.now(),g=c[l]||{},m=this._createActionContext(),p=await this.actionRegistry.execute(l,g,m);if(n=(Date.now()-d)/1e3,t.push(p),(["click","navigate","send_keys","go_back","go_forward","evaluate"].includes(l)||l==="send_keys"&&(g.keys?.toLowerCase().includes("enter")||g.keys?.toLowerCase().includes("return")))&&o<s-1)try{let T=await this.browserSession.getCurrentPageUrl();if(T!==r&&T!==""&&r!==""){let C=s-o-1;b.log(`🔄 Page navigation detected: ${r} → ${T}`),b.log(`📍 Interrupting remaining ${C} actions (element indices now stale)`),this.browserSession.clearCachedState(),C>0&&t.push({extractedContent:`Page navigated to ${T}. Skipped ${C} remaining action(s) because element indices are now stale.`});break}r=T}catch{}if(t[t.length-1].isDone||t[t.length-1].error||o===s-1)break}catch(c){let l=c.message||String(c);console.error(`❌ Executing action ${o+1} failed: ${l}`),t.push({error:`Action failed: ${l}`});break}}return t}_logAction(e,t,n,s){let r="\x1B[34m",o="\x1B[35m",a="\x1B[0m",c;s>1?c=`▶️ [${n}/${s}] ${r}${t}${a}:`:c=`▶️ ${r}${t}${a}:`;let d=e[t],g=[];if(d&&typeof d=="object")for(let[m,p]of Object.entries(d)){let h=p;typeof p=="string"&&p.length>150?h=p.substring(0,150)+"...":Array.isArray(p)&&JSON.stringify(p).length>200&&(h=JSON.stringify(p).substring(0,200)+"..."),typeof h=="string"&&this.sensitiveData&&(h=tu(h,this.sensitiveData)),g.push(`${o}${m}${a}: ${h}`)}if(g.length>0){let m=g.join(", ");b.log(` ${c} ${m}`)}else b.log(` ${c}`)}_logStepContext(e){let t=e?.url||"",n=t.length>50?t.substring(0,50)+"...":t,s=e?.domState?.selectorMap?.size||0;b.log(`
1174
1174
  `),b.log(`📍 Step ${this.state.nSteps}:`),b.log(`Evaluating page with ${s} interactive elements on: ${n}`)}_logStepCompletionSummary(e,t){if(!t||t.length===0)return;let n=(Date.now()-e)/1e3,s=t.length,r=t.filter(g=>!g.error).length,o=s-r,a=r>0?`✅ ${r}`:"",c=o>0?`❌ ${o}`:"",l=[a,c].filter(g=>g),d=l.length>0?l.join(" | "):"✅ 0";b.log(`📍 Step ${this.state.nSteps}: Ran ${s} action${s===1?"":"s"} in ${n.toFixed(2)}s: ${d}`)}_createActionContext(){let e=this.settings.pageExtractionLlm??this.llm;return{browserSession:this.browserSession,pageId:this.pageId,fileSystem:this.fileSystem,sensitiveData:this.sensitiveData,availableFilePaths:this.settings.availableFilePaths??void 0,pageExtractionLlm:e,llm:this.llm}}async _executeInitialActions(){if(this.state.followUpTask||!this.initialActions||this.initialActions.length===0)return;b.log(`🚀 Executing ${this.initialActions.length} initial action(s)...`);let e=Date.now(),t=await this.multiAct(this.initialActions);t&&this.initialUrl&&t[0]?.longTermMemory&&(t[0].longTermMemory=`Found initial url and automatically loaded it. ${t[0].longTermMemory}`),this.state.lastResult=t;let n=this.settings.flashMode?{evaluationPreviousGoal:null,memory:"Initial navigation",nextGoal:null,action:this.initialActions}:{evaluationPreviousGoal:"Start",memory:null,nextGoal:"Initial navigation",action:this.initialActions},s=Date.now(),r={stepNumber:0,stepStartTime:e,stepEndTime:s},o={url:this.initialUrl||"",title:"Initial Actions",tabs:[],screenshot:void 0},a={modelOutput:n,result:t,state:o,metadata:r};this.history.history.push(a),b.log("📝 Saved initial actions to history as step 0"),b.log("Initial actions completed")}_extractStartUrl(e){let t=e.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,""),n=new Set(["pdf","doc","docx","xls","xlsx","ppt","pptx","odt","ods","odp","txt","md","rtf","csv","json","xml","yaml","yml","jpg","jpeg","png","gif","bmp","svg","webp","ico","tiff","mp3","wav","ogg","mp4","avi","mov","wmv","flv","mkv","zip","rar","tar","gz","7z","bz2","py","js","ts","jsx","tsx","java","c","cpp","h","cs","go","rb","php","swift","kt","ini","cfg","conf","log","sql","env"]),s=[/https?:\/\/[^\s<>"']+/g,/(?:www\.)?[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}(?:\/[^\s<>"']*)?/g],r=[];for(let o of s){let a=t.match(o);if(a)for(let c of a){let l=c.replace(/[.,;:!?)'"]+$/,""),d=l.split(".").pop()?.toLowerCase();d&&n.has(d)||(!l.startsWith("http://")&&!l.startsWith("https://")&&(l="https://"+l),r.push(l))}}return r.length>1?(b.log(`Multiple URLs found (${r.length}), skipping directlyOpenUrl to avoid ambiguity`),null):r.length===1?r[0]:null}async _executeStep(e,t,n){try{let s=(this.settings.stepTimeout??180)*1e3;if(await Promise.race([this.step(n),new Promise((r,o)=>setTimeout(()=>o(new Error(`Step ${e} timed out after ${this.settings.stepTimeout??180}s`)),s))]),this.state.lastResult&&this.state.lastResult.length>0){let r=this.state.lastResult[this.state.lastResult.length-1];if(r.isDone)return r.success??!1?b.log(`
1175
1175
  📄 \x1B[32m Final Result:\x1B[0m
1176
1176
  ${r.extractedContent}
@@ -1190,19 +1190,19 @@ ${e.extractedContent}
1190
1190
  `),e.attachments&&e.attachments.length>0)for(let n=0;n<e.attachments.length;n++)b.log(`👉 Attachment ${n+1}: ${e.attachments[n]}`)}}BASE_RETRY_DELAY=5;MAX_RETRY_DELAY=30;async _handleStepError(e){if(e instanceof Error&&e.message==="Interrupted"){console.error("The agent was interrupted mid-step");return}let t=e instanceof Error?e.message:String(e),n=`❌ Result failed ${this.state.consecutiveFailures+1}/${this.settings.maxFailures+(this.settings.finalResponseAfterFailure?1:0)} times:
1191
1191
  `;if(this.state.consecutiveFailures++,console.error(`${n}${t}`),this.state.lastResult=[{error:t}],this.state.consecutiveFailures<this.settings.maxFailures){let s=Math.min(this.BASE_RETRY_DELAY*Math.pow(2,this.state.consecutiveFailures-1),this.MAX_RETRY_DELAY);b.log(`⏳ Waiting ${s.toFixed(1)}s before retry (exponential backoff)`),await new Promise(r=>setTimeout(r,s*1e3))}}async _makeHistoryItem(e,t,n,s=null,r=null){let o=[];if(e){let d=t.domState?.selectorMap||new Map;o=eu(e,d)}else o=[null];let a=null;t.screenshot?(b.log(`📸 Storing screenshot for step ${this.state.nSteps}, screenshot length: ${t.screenshot.length}`),a=await this.screenshotService.storeScreenshot(t.screenshot,this.state.nSteps),b.log(`📸 Screenshot stored at: ${a}`)):b.log(`📸 No screenshot in browser_state_summary for step ${this.state.nSteps}`);let c={url:t.url,title:t.title,tabs:t.tabs,interactedElement:o,screenshotPath:a},l={modelOutput:e,result:n,state:c,metadata:s??null,stateMessage:r??null};this.history.history.push(l)}async _finalize(e,t){let n=Date.now();if(this.state.lastResult){if(e&&this.state.lastModelOutput){let s={stepStartTime:t,stepEndTime:n,stepNumber:this.state.nSteps};await this._makeHistoryItem(this.state.lastModelOutput,e,this.state.lastResult,s,null),this._logStepCompletionSummary(t,this.state.lastResult||[])}this.state.nSteps++}}async _forceDoneAfterLastStep(e=null){if(e&&Ki(e)){let t=`You reached max_steps - this is your last step. Your only tool available is the "done" tool. No other tool is available. All other tools which you see in history or examples are not available.
1192
1192
  If the task is not yet fully finished as requested by the user, set success in "done" to false! E.g. if not all steps are fully completed. Else success to true.
1193
- Include everything you found out for the ultimate task in the done text.`;b.log("Last step finishing up"),this.messageManager.addContextMessage(Pn(t)),this.doneAgentOutputSchema&&(this.dynamicAgentOutputSchema=this.doneAgentOutputSchema)}}async _forceDoneAfterFailure(){if(this.state.consecutiveFailures>=this.settings.maxFailures&&this.settings.finalResponseAfterFailure){let e=`You failed ${this.settings.maxFailures} times. Therefore we terminate the agent.
1193
+ Include everything you found out for the ultimate task in the done text.`;b.log("Last step finishing up"),this.messageManager.addContextMessage(Dn(t)),this.doneAgentOutputSchema&&(this.dynamicAgentOutputSchema=this.doneAgentOutputSchema)}}async _forceDoneAfterFailure(){if(this.state.consecutiveFailures>=this.settings.maxFailures&&this.settings.finalResponseAfterFailure){let e=`You failed ${this.settings.maxFailures} times. Therefore we terminate the agent.
1194
1194
  Your only tool available is the "done" tool. No other tool is available. All other tools which you see in history or examples are not available.
1195
1195
  If the task is not yet fully finished as requested by the user, set success in "done" to false! E.g. if not all steps are fully completed. Else success to true.
1196
- Include everything you found out for the ultimate task in the done text.`;b.log("Force done action, because we reached max_failures."),this.messageManager.addContextMessage(Pn(e)),this.doneAgentOutputSchema&&(this.dynamicAgentOutputSchema=this.doneAgentOutputSchema)}}async _injectBudgetWarning(e=null){if(!e)return;let t=e.stepNumber+1,n=t/e.maxSteps;if(n>=.75&&!Ki(e)){let s=e.maxSteps-t,r=Math.floor(n*100),o=`BUDGET WARNING: You have used ${t}/${e.maxSteps} steps (${r}%). ${s} steps remaining. If the task cannot be completed in the remaining steps, prioritize: (1) consolidate your results (save to files if the file system is in use), (2) call done with what you have. Partial results are far more valuable than exhausting all steps with nothing saved.`;b.log(`Step budget warning: ${t}/${e.maxSteps} (${r}%)`),this.messageManager.addContextMessage(Pn(o))}}async _getModelOutputWithRetry(e){let t=this.dynamicAgentOutputSchema||co,n=this._processMessagesAndReplaceLongUrls(e),r=(await this.llm.ainvoke(e,t)).completion;Object.keys(n).length>0&&this._restoreShortenedUrlsInAgentOutput(r,n),b.log(`✅ Step ${this.state.nSteps}: Got LLM response with ${r.action?.length??0} actions`);let o=a=>!a||!Array.isArray(a)||a.length===0?!0:a.every(c=>!c||typeof c!="object"?!0:Object.keys(c).length===0);if(o(r.action)){console.warn("Model returned empty action. Retrying...");let a=Pn("You forgot to return an action. Please respond with a valid JSON action according to the expected schema with your assessment and next actions."),c=[...e,a];r=(await this.llm.ainvoke(c,t)).completion,o(r.action)&&(console.warn("Model still returned empty after retry. Inserting safe done action."),r={...r,action:[{done:{success:!1,text:"No next action returned by LLM!"}}]})}return r.action&&r.action.length>this.settings.maxActionsPerStep&&(b.log(`✂️ Limiting actions from ${r.action.length} to ${this.settings.maxActionsPerStep}`),r.action=r.action.slice(0,this.settings.maxActionsPerStep)),r}async _handlePostLLMProcessing(e,t){this.registerNewStepCallback&&this.state.lastModelOutput&&await this.registerNewStepCallback(e,this.state.lastModelOutput,this.state.nSteps),this.settings.saveConversationPath&&this.state.lastModelOutput&&await this.saveConversationStep(t)}async _checkStopOrPause(){if(this.registerShouldStopCallback&&await this.registerShouldStopCallback())throw b.log("External callback requested stop"),this.state.stopped=!0,new Error("Interrupted");if(this.registerExternalAgentStatusRaiseErrorCallback&&await this.registerExternalAgentStatusRaiseErrorCallback())throw new Error("Interrupted");if(this.state.stopped)throw new Error("Interrupted");if(this.state.paused)throw new Error("Interrupted")}async saveHistory(e="AgentHistory.json"){let{saveHistoryToFile:t}=await Promise.resolve().then(()=>(uo(),Qi));await t(this.history,e,this.sensitiveData),b.log(`📝 Saved agent history to ${e}`)}async loadAndRerun(e="AgentHistory.json",t){let{loadHistoryFromFile:n}=await Promise.resolve().then(()=>(uo(),Qi)),s=await n(e);return this.rerunHistory(s,t)}async rerunHistory(e,t={}){let{maxRetries:n=3,skipFailures:s=!0,delayBetweenActions:r=2}=t;await this.browserSession.start();let o=[];for(let a=0;a<e.history.length;a++){let c=e.history[a],l=c.modelOutput?.nextGoal||"",d=c.metadata?.stepNumber??a,g=d===0?"Initial actions":`Step ${d}`;if(b.log(`Replaying ${g} (${a+1}/${e.history.length}): ${l}`),!c.modelOutput?.action||c.modelOutput.action.length===0){console.warn(`${g}: No action to replay, skipping`),o.push({error:"No action to replay"});continue}let m=0;for(;m<n;)try{let p=await this._executeHistoryStep(c,r);o.push(...p);break}catch(p){if(m++,m===n){let h=`${g} failed after ${n} attempts: ${p.message}`;if(console.error(h),!s)throw o.push({error:h}),new Error(h)}else console.warn(`${g} failed (attempt ${m}/${n}), retrying...`),await this._sleep(r*1e3)}}return this.ownsBrowserSession&&await this.browserSession.stop(),o}async _executeHistoryStep(e,t){if(!e.modelOutput?.action)throw new Error("Invalid model output");let n=await this.multiAct(e.modelOutput.action);return await this._sleep(t*1e3),n}_sleep(e){return new Promise(t=>setTimeout(t,e))}URL_SHORTENING_LIMIT=25;_replaceUrlsInText(e){let t={},n=/https?:\/\/[^\s<>"']+|www\.[^\s<>"']+/gi;return{text:e.replace(n,r=>{let o=r.indexOf("?"),a=r.indexOf("#"),c=r.length;o!==-1&&(c=Math.min(c,o)),a!==-1&&(c=Math.min(c,a));let l=r.substring(0,c),d=r.substring(c);if(d.length<=this.URL_SHORTENING_LIMIT)return r;if(d){let g=d.substring(0,this.URL_SHORTENING_LIMIT),m=Bf.createHash("md5").update(d).digest("hex").substring(0,7),p=`${l}${g}...${m}`;if(p.length<r.length)return t[p]=r,p}return r}),urlMap:t}}_processMessagesAndReplaceLongUrls(e){let t={};for(let n of e)if(typeof n.content=="string"){let{text:s,urlMap:r}=this._replaceUrlsInText(n.content);n.content=s,Object.assign(t,r)}else if(Array.isArray(n.content)){for(let s of n.content)if(s.type==="text"&&s.text){let{text:r,urlMap:o}=this._replaceUrlsInText(s.text);s.text=r,Object.assign(t,o)}}return t}_replaceShortenedUrlsInString(e,t){let n=e;for(let[s,r]of Object.entries(t))n=n.split(s).join(r);return n}_restoreShortenedUrlsInAgentOutput(e,t){let n=s=>{if(typeof s=="string")return this._replaceShortenedUrlsInString(s,t);if(Array.isArray(s))return s.map(r=>n(r));if(s!==null&&typeof s=="object")for(let r of Object.keys(s))s[r]=n(s[r]);return s};if(e.current_state?.evaluation&&(e.current_state.evaluation=this._replaceShortenedUrlsInString(e.current_state.evaluation,t)),e.current_state?.memory&&(e.current_state.memory=this._replaceShortenedUrlsInString(e.current_state.memory,t)),e.current_state?.next_goal&&(e.current_state.next_goal=this._replaceShortenedUrlsInString(e.current_state.next_goal,t)),e.action&&Array.isArray(e.action))for(let s of e.action)for(let r of Object.keys(s))s[r]=n(s[r])}lastKnownDownloads=[];availableFilePaths=[];async _checkAndUpdateDownloads(e=""){if(this.browserSession)try{let t=this.browserSession.downloadedFiles||[];JSON.stringify(t)!==JSON.stringify(this.lastKnownDownloads)&&(this._updateAvailableFilePaths(t),this.lastKnownDownloads=[...t],e&&b.debug(`📁 ${e}: Updated available files`))}catch(t){let n=e?` ${e}`:"";b.debug(`📁 Failed to check for downloads${n}: ${t.message}`)}}_updateAvailableFilePaths(e){let t=new Set(this.availableFilePaths),n=e.filter(s=>!t.has(s));if(n.length>0){this.availableFilePaths=[...t,...n],console.info(`📁 Added ${n.length} downloaded files to available_file_paths (total: ${this.availableFilePaths.length} files)`);for(let s of n)console.info(`📄 New file available: ${s}`)}}saveFileSystemState(){if(this.fileSystem)this.state.fileSystemState=this.fileSystem.getState();else throw console.error("💾 File system is not set up. Cannot save state."),new Error("File system is not set up. Cannot save state.")}_removeThinkTags(e){let t=e.replace(/<think>[\s\S]*?<\/think>/g,"");return t=t.replace(/[\s\S]*?<\/think>/g,""),t.trim()}_enhanceTaskWithSchema(e,t){if(!t)return e;try{let n=Hf(t),r=`
1196
+ Include everything you found out for the ultimate task in the done text.`;b.log("Force done action, because we reached max_failures."),this.messageManager.addContextMessage(Dn(e)),this.doneAgentOutputSchema&&(this.dynamicAgentOutputSchema=this.doneAgentOutputSchema)}}async _injectBudgetWarning(e=null){if(!e)return;let t=e.stepNumber+1,n=t/e.maxSteps;if(n>=.75&&!Ki(e)){let s=e.maxSteps-t,r=Math.floor(n*100),o=`BUDGET WARNING: You have used ${t}/${e.maxSteps} steps (${r}%). ${s} steps remaining. If the task cannot be completed in the remaining steps, prioritize: (1) consolidate your results (save to files if the file system is in use), (2) call done with what you have. Partial results are far more valuable than exhausting all steps with nothing saved.`;b.log(`Step budget warning: ${t}/${e.maxSteps} (${r}%)`),this.messageManager.addContextMessage(Dn(o))}}async _getModelOutputWithRetry(e){let t=this.dynamicAgentOutputSchema||co,n=this._processMessagesAndReplaceLongUrls(e),r=(await this.llm.ainvoke(e,t)).completion;Object.keys(n).length>0&&this._restoreShortenedUrlsInAgentOutput(r,n),b.log(`✅ Step ${this.state.nSteps}: Got LLM response with ${r.action?.length??0} actions`);let o=a=>!a||!Array.isArray(a)||a.length===0?!0:a.every(c=>!c||typeof c!="object"?!0:Object.keys(c).length===0);if(o(r.action)){console.warn("Model returned empty action. Retrying...");let a=Dn("You forgot to return an action. Please respond with a valid JSON action according to the expected schema with your assessment and next actions."),c=[...e,a];r=(await this.llm.ainvoke(c,t)).completion,o(r.action)&&(console.warn("Model still returned empty after retry. Inserting safe done action."),r={...r,action:[{done:{success:!1,text:"No next action returned by LLM!"}}]})}return r.action&&r.action.length>this.settings.maxActionsPerStep&&(b.log(`✂️ Limiting actions from ${r.action.length} to ${this.settings.maxActionsPerStep}`),r.action=r.action.slice(0,this.settings.maxActionsPerStep)),r}async _handlePostLLMProcessing(e,t){this.registerNewStepCallback&&this.state.lastModelOutput&&await this.registerNewStepCallback(e,this.state.lastModelOutput,this.state.nSteps),this.settings.saveConversationPath&&this.state.lastModelOutput&&await this.saveConversationStep(t)}async _checkStopOrPause(){if(this.registerShouldStopCallback&&await this.registerShouldStopCallback())throw b.log("External callback requested stop"),this.state.stopped=!0,new Error("Interrupted");if(this.registerExternalAgentStatusRaiseErrorCallback&&await this.registerExternalAgentStatusRaiseErrorCallback())throw new Error("Interrupted");if(this.state.stopped)throw new Error("Interrupted");if(this.state.paused)throw new Error("Interrupted")}async saveHistory(e="AgentHistory.json"){let{saveHistoryToFile:t}=await Promise.resolve().then(()=>(uo(),Qi));await t(this.history,e,this.sensitiveData),b.log(`📝 Saved agent history to ${e}`)}async loadAndRerun(e="AgentHistory.json",t){let{loadHistoryFromFile:n}=await Promise.resolve().then(()=>(uo(),Qi)),s=await n(e);return this.rerunHistory(s,t)}async rerunHistory(e,t={}){let{maxRetries:n=3,skipFailures:s=!0,delayBetweenActions:r=2}=t;await this.browserSession.start();let o=[];for(let a=0;a<e.history.length;a++){let c=e.history[a],l=c.modelOutput?.nextGoal||"",d=c.metadata?.stepNumber??a,g=d===0?"Initial actions":`Step ${d}`;if(b.log(`Replaying ${g} (${a+1}/${e.history.length}): ${l}`),!c.modelOutput?.action||c.modelOutput.action.length===0){console.warn(`${g}: No action to replay, skipping`),o.push({error:"No action to replay"});continue}let m=0;for(;m<n;)try{let p=await this._executeHistoryStep(c,r);o.push(...p);break}catch(p){if(m++,m===n){let h=`${g} failed after ${n} attempts: ${p.message}`;if(console.error(h),!s)throw o.push({error:h}),new Error(h)}else console.warn(`${g} failed (attempt ${m}/${n}), retrying...`),await this._sleep(r*1e3)}}return this.ownsBrowserSession&&await this.browserSession.stop(),o}async _executeHistoryStep(e,t){if(!e.modelOutput?.action)throw new Error("Invalid model output");let n=await this.multiAct(e.modelOutput.action);return await this._sleep(t*1e3),n}_sleep(e){return new Promise(t=>setTimeout(t,e))}URL_SHORTENING_LIMIT=25;_replaceUrlsInText(e){let t={},n=/https?:\/\/[^\s<>"']+|www\.[^\s<>"']+/gi;return{text:e.replace(n,r=>{let o=r.indexOf("?"),a=r.indexOf("#"),c=r.length;o!==-1&&(c=Math.min(c,o)),a!==-1&&(c=Math.min(c,a));let l=r.substring(0,c),d=r.substring(c);if(d.length<=this.URL_SHORTENING_LIMIT)return r;if(d){let g=d.substring(0,this.URL_SHORTENING_LIMIT),m=Bf.createHash("md5").update(d).digest("hex").substring(0,7),p=`${l}${g}...${m}`;if(p.length<r.length)return t[p]=r,p}return r}),urlMap:t}}_processMessagesAndReplaceLongUrls(e){let t={};for(let n of e)if(typeof n.content=="string"){let{text:s,urlMap:r}=this._replaceUrlsInText(n.content);n.content=s,Object.assign(t,r)}else if(Array.isArray(n.content)){for(let s of n.content)if(s.type==="text"&&s.text){let{text:r,urlMap:o}=this._replaceUrlsInText(s.text);s.text=r,Object.assign(t,o)}}return t}_replaceShortenedUrlsInString(e,t){let n=e;for(let[s,r]of Object.entries(t))n=n.split(s).join(r);return n}_restoreShortenedUrlsInAgentOutput(e,t){let n=s=>{if(typeof s=="string")return this._replaceShortenedUrlsInString(s,t);if(Array.isArray(s))return s.map(r=>n(r));if(s!==null&&typeof s=="object")for(let r of Object.keys(s))s[r]=n(s[r]);return s};if(e.current_state?.evaluation&&(e.current_state.evaluation=this._replaceShortenedUrlsInString(e.current_state.evaluation,t)),e.current_state?.memory&&(e.current_state.memory=this._replaceShortenedUrlsInString(e.current_state.memory,t)),e.current_state?.next_goal&&(e.current_state.next_goal=this._replaceShortenedUrlsInString(e.current_state.next_goal,t)),e.action&&Array.isArray(e.action))for(let s of e.action)for(let r of Object.keys(s))s[r]=n(s[r])}lastKnownDownloads=[];availableFilePaths=[];async _checkAndUpdateDownloads(e=""){if(this.browserSession)try{let t=this.browserSession.downloadedFiles||[];JSON.stringify(t)!==JSON.stringify(this.lastKnownDownloads)&&(this._updateAvailableFilePaths(t),this.lastKnownDownloads=[...t],e&&b.debug(`📁 ${e}: Updated available files`))}catch(t){let n=e?` ${e}`:"";b.debug(`📁 Failed to check for downloads${n}: ${t.message}`)}}_updateAvailableFilePaths(e){let t=new Set(this.availableFilePaths),n=e.filter(s=>!t.has(s));if(n.length>0){this.availableFilePaths=[...t,...n],console.info(`📁 Added ${n.length} downloaded files to available_file_paths (total: ${this.availableFilePaths.length} files)`);for(let s of n)console.info(`📄 New file available: ${s}`)}}saveFileSystemState(){if(this.fileSystem)this.state.fileSystemState=this.fileSystem.getState();else throw console.error("💾 File system is not set up. Cannot save state."),new Error("File system is not set up. Cannot save state.")}_removeThinkTags(e){let t=e.replace(/<think>[\s\S]*?<\/think>/g,"");return t=t.replace(/[\s\S]*?<\/think>/g,""),t.trim()}_enhanceTaskWithSchema(e,t){if(!t)return e;try{let n=Hf(t),r=`
1197
1197
  Expected output format:
1198
- ${JSON.stringify(n,null,2)}`;return e+r}catch(n){b.debug(`Could not parse output schema: ${n.message}`)}return e}_convertInitialActions(e){let t=[];for(let n of e){let s=Object.keys(n)[0],r=n[s],o=this.actionRegistry.getAction(s);if(o&&o.paramSchema)try{let a=o.paramSchema.parse(r);t.push({[s]:a})}catch{t.push(n)}else t.push(n)}return t}_getCompleteHistoryWithoutScreenshots(){let e=JSON.parse(JSON.stringify(this.history));if(e.history)for(let t of e.history)t.state&&t.state.screenshot&&(t.state.screenshot=null);return JSON.stringify(e)}static extractTaskWebsite(e){let t=/https?:\/\/[^\s<>"']+|www\.[^\s<>"']+|[^\s<>"']+\.[a-z]{2,}(?:\/[^\s<>"']*)?/i,n=e.match(t);return n?n[0]:null}async authenticateCloudSync(e=!0){return console.warn("Cloud sync has been removed and is no longer available"),!1}_logAgentRun(){let e=this.browserSession?.id?.slice(-4)||"----";b.log(`🤖 Agent ${this.id.slice(-4)} started with browser session ${e}`)}_logFirstStepStartup(){b.log(`📋 Task: ${this.task}`),b.log(`🔧 Settings: maxSteps=${this.maxSteps}, useVision=${this.settings.useVision}`)}_logFinalOutcomeMessages(){let e=this.history.finalResult;e&&(e.success?b.log("✅ Task completed successfully"):b.log("❌ Task failed"),e.extractedContent&&b.log(`📄 Result: ${e.extractedContent.slice(0,200)}...`))}_logNextActionSummary(e){if(e.nextGoal&&b.log(`🎯 Next goal: ${e.nextGoal}`),e.action&&e.action.length>0){let t=e.action.map(n=>Object.keys(n)[0]).join(", ");b.log(`⚡ Actions: ${t}`)}}_logAgentEvent(e,t=null){let n={type:"agent_run",agentId:this.id,task:this.task,maxSteps:e,stepsCompleted:this.state.nSteps,success:this.history.finalResult?.success??!1,error:t,timestamp:new Date().toISOString()};b.debug("📊 Agent event:",JSON.stringify(n))}runSync(e,t,n){let s=this.run(e),r,o,a=!1;for(s.then(c=>{r=c,a=!0}).catch(c=>{o=c,a=!0});!a;)Wf("sleep",["0.01"]);if(o)throw o;return r}}});import{zodToJsonSchema as Gf}from"zod-to-json-schema";var Io,wu=F(()=>{"use strict";Io=class{static createOptimizedJsonSchema(e){let t=Gf(e,{$refStrategy:"none"}),n=t.$defs||{},s=(c,l,d=!1)=>{if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let g={},m=null,p=["additionalProperties","$defs","$schema"];for(let[h,f]of Object.entries(c))if(!p.includes(h)&&!(h==="title"&&!d))if(h==="description")f&&(g[h]=f);else if(h==="type")g[h]=f;else if(h==="$ref"&&l){let y=f.split("/").pop();if(y&&l[y]){let T=l[y];m=s(T,l)}}else h==="anyOf"&&Array.isArray(f)?g[h]=f.map(y=>s(y,l)):h==="properties"||h==="items"?g[h]=s(f,l,h==="properties"):["type","required","minimum","maximum","minItems","maxItems","pattern","default"].includes(h)?g[h]=typeof f=="object"&&f!==null?s(f,l):f:g[h]=typeof f=="object"&&f!==null||Array.isArray(f)?s(f,l):f;if(m!==null){let h={...m};for(let[f,y]of Object.entries(g))(f==="description"&&!("description"in h)||f!=="description")&&(h[f]=y);return h}else return g.type==="object"&&(g.additionalProperties=!1),g}else if(Array.isArray(c))return c.map(g=>s(g,l,d));return c},r=s(t,n);if(typeof r!="object"||r===null)throw new Error("Optimized schema result is not a dictionary");let o=r,a=c=>{if(typeof c=="object"&&c!==null&&!Array.isArray(c)){c.type==="object"&&(c.additionalProperties=!1);for(let l of Object.values(c))typeof l=="object"&&l!==null&&a(l)}else if(Array.isArray(c))for(let l of c)typeof l=="object"&&l!==null&&a(l)};return a(o),this.ensureArraysHaveItems(o),this.makeStrictCompatible(o),o}static ensureArraysHaveItems(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){e.type==="array"&&!("items"in e)&&(e.items={});for(let t of Object.values(e))typeof t=="object"&&t!==null&&this.ensureArraysHaveItems(t)}else if(Array.isArray(e))for(let t of e)typeof t=="object"&&t!==null&&this.ensureArraysHaveItems(t)}static makeStrictCompatible(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&t!=="required"&&this.makeStrictCompatible(n);if(e.type==="object"){"properties"in e||(e.properties={});let t=Object.keys(e.properties);e.required=t}}else if(Array.isArray(e))for(let t of e)this.makeStrictCompatible(t)}static createGeminiOptimizedSchema(e){let t=this.createOptimizedJsonSchema(e),n=s=>{if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let r={};for(let[o,a]of Object.entries(s))o!=="required"&&(r[o]=n(a));return r}else if(Array.isArray(s))return s.map(n);return s};return n(t)}}});import jf from"openai";var zf,aa,Qs,Tu=F(()=>{"use strict";wu();zf=["o4-mini","o3","o3-mini","o1","o1-pro","gpt-5","gpt-5-mini","gpt-5-nano"],aa=class{static serializeMessages(e){return e.map(t=>{if(t.role==="user")return typeof t.content=="string"?{role:"user",content:t.content,...t.name&&{name:t.name}}:{role:"user",content:t.content.map(s=>{if(s.type==="text")return{type:"text",text:s.text};if(s.type==="image_url")return{type:"image_url",image_url:{url:s.imageUrl.url,detail:s.imageUrl.detail||"auto"}};throw new Error(`Unsupported content part type: ${s.type}`)}),...t.name&&{name:t.name}};if(t.role==="system")return{role:"system",content:typeof t.content=="string"?t.content:t.content.map(n=>n.text).join(`
1198
+ ${JSON.stringify(n,null,2)}`;return e+r}catch(n){b.debug(`Could not parse output schema: ${n.message}`)}return e}_convertInitialActions(e){let t=[];for(let n of e){let s=Object.keys(n)[0],r=n[s],o=this.actionRegistry.getAction(s);if(o&&o.paramSchema)try{let a=o.paramSchema.parse(r);t.push({[s]:a})}catch{t.push(n)}else t.push(n)}return t}_getCompleteHistoryWithoutScreenshots(){let e=JSON.parse(JSON.stringify(this.history));if(e.history)for(let t of e.history)t.state&&t.state.screenshot&&(t.state.screenshot=null);return JSON.stringify(e)}static extractTaskWebsite(e){let t=/https?:\/\/[^\s<>"']+|www\.[^\s<>"']+|[^\s<>"']+\.[a-z]{2,}(?:\/[^\s<>"']*)?/i,n=e.match(t);return n?n[0]:null}async authenticateCloudSync(e=!0){return console.warn("Cloud sync has been removed and is no longer available"),!1}_logAgentRun(){let e=this.browserSession?.id?.slice(-4)||"----";b.log(`🤖 Agent ${this.id.slice(-4)} started with browser session ${e}`)}_logFirstStepStartup(){b.log(`📋 Task: ${this.task}`),b.log(`🔧 Settings: maxSteps=${this.maxSteps}, useVision=${this.settings.useVision}`)}_logFinalOutcomeMessages(){let e=this.history.finalResult;e&&(e.success?b.log("✅ Task completed successfully"):b.log("❌ Task failed"),e.extractedContent&&b.log(`📄 Result: ${e.extractedContent.slice(0,200)}...`))}_logNextActionSummary(e){if(e.nextGoal&&b.log(`🎯 Next goal: ${e.nextGoal}`),e.action&&e.action.length>0){let t=e.action.map(n=>Object.keys(n)[0]).join(", ");b.log(`⚡ Actions: ${t}`)}}_logAgentEvent(e,t=null){let n={type:"agent_run",agentId:this.id,task:this.task,maxSteps:e,stepsCompleted:this.state.nSteps,success:this.history.finalResult?.success??!1,error:t,timestamp:new Date().toISOString()};b.debug("📊 Agent event:",JSON.stringify(n))}runSync(e,t,n){let s=this.run(e),r,o,a=!1;for(s.then(c=>{r=c,a=!0}).catch(c=>{o=c,a=!0});!a;)Wf("sleep",["0.01"]);if(o)throw o;return r}}});import{zodToJsonSchema as Gf}from"zod-to-json-schema";var Io,wu=$(()=>{"use strict";Io=class{static createOptimizedJsonSchema(e){let t=Gf(e,{$refStrategy:"none"}),n=t.$defs||{},s=(c,l,d=!1)=>{if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let g={},m=null,p=["additionalProperties","$defs","$schema"];for(let[h,f]of Object.entries(c))if(!p.includes(h)&&!(h==="title"&&!d))if(h==="description")f&&(g[h]=f);else if(h==="type")g[h]=f;else if(h==="$ref"&&l){let y=f.split("/").pop();if(y&&l[y]){let T=l[y];m=s(T,l)}}else h==="anyOf"&&Array.isArray(f)?g[h]=f.map(y=>s(y,l)):h==="properties"||h==="items"?g[h]=s(f,l,h==="properties"):["type","required","minimum","maximum","minItems","maxItems","pattern","default"].includes(h)?g[h]=typeof f=="object"&&f!==null?s(f,l):f:g[h]=typeof f=="object"&&f!==null||Array.isArray(f)?s(f,l):f;if(m!==null){let h={...m};for(let[f,y]of Object.entries(g))(f==="description"&&!("description"in h)||f!=="description")&&(h[f]=y);return h}else return g.type==="object"&&(g.additionalProperties=!1),g}else if(Array.isArray(c))return c.map(g=>s(g,l,d));return c},r=s(t,n);if(typeof r!="object"||r===null)throw new Error("Optimized schema result is not a dictionary");let o=r,a=c=>{if(typeof c=="object"&&c!==null&&!Array.isArray(c)){c.type==="object"&&(c.additionalProperties=!1);for(let l of Object.values(c))typeof l=="object"&&l!==null&&a(l)}else if(Array.isArray(c))for(let l of c)typeof l=="object"&&l!==null&&a(l)};return a(o),this.ensureArraysHaveItems(o),this.makeStrictCompatible(o),o}static ensureArraysHaveItems(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){e.type==="array"&&!("items"in e)&&(e.items={});for(let t of Object.values(e))typeof t=="object"&&t!==null&&this.ensureArraysHaveItems(t)}else if(Array.isArray(e))for(let t of e)typeof t=="object"&&t!==null&&this.ensureArraysHaveItems(t)}static makeStrictCompatible(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&t!=="required"&&this.makeStrictCompatible(n);if(e.type==="object"){"properties"in e||(e.properties={});let t=Object.keys(e.properties);e.required=t}}else if(Array.isArray(e))for(let t of e)this.makeStrictCompatible(t)}static createGeminiOptimizedSchema(e){let t=this.createOptimizedJsonSchema(e),n=s=>{if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let r={};for(let[o,a]of Object.entries(s))o!=="required"&&(r[o]=n(a));return r}else if(Array.isArray(s))return s.map(n);return s};return n(t)}}});import jf from"openai";var zf,aa,Js,Tu=$(()=>{"use strict";wu();zf=["o4-mini","o3","o3-mini","o1","o1-pro","gpt-5","gpt-5-mini","gpt-5-nano"],aa=class{static serializeMessages(e){return e.map(t=>{if(t.role==="user")return typeof t.content=="string"?{role:"user",content:t.content,...t.name&&{name:t.name}}:{role:"user",content:t.content.map(s=>{if(s.type==="text")return{type:"text",text:s.text};if(s.type==="image_url")return{type:"image_url",image_url:{url:s.imageUrl.url,detail:s.imageUrl.detail||"auto"}};throw new Error(`Unsupported content part type: ${s.type}`)}),...t.name&&{name:t.name}};if(t.role==="system")return{role:"system",content:typeof t.content=="string"?t.content:t.content.map(n=>n.text).join(`
1199
1199
  `),...t.name&&{name:t.name}};if(t.role==="assistant")return{role:"assistant",content:typeof t.content=="string"?t.content:t.content?t.content.map(s=>s.type==="text"?s.text:"").join(`
1200
- `):null,...t.toolCalls&&{tool_calls:t.toolCalls.map(s=>({id:s.id,type:"function",function:{name:s.function.name,arguments:s.function.arguments}}))},...t.name&&{name:t.name}};throw new Error(`Unknown message role: ${t.role}`)})}},Qs=class{model;client;temperature;frequencyPenalty;maxCompletionTokens;topP;seed;maxRetries;reasoningEffort;isReasoningModel;constructor(e){this.model=e.model,this.temperature=e.temperature??.2,this.frequencyPenalty=e.frequencyPenalty??.3,this.maxCompletionTokens=e.maxCompletionTokens,this.topP=e.topP,this.seed=e.seed,this.maxRetries=e.maxRetries??5,this.reasoningEffort=e.reasoningEffort??"low";let t=e.model.toLowerCase();this.isReasoningModel=zf.some(n=>t.includes(n.toLowerCase())),this.client=new jf({apiKey:e.apiKey,organization:e.organization,project:e.project,baseURL:e.baseURL,timeout:e.timeout,maxRetries:this.maxRetries,defaultHeaders:e.defaultHeaders})}get provider(){return"openai"}get name(){return this.model}getUsage(e){if(!e.usage)return null;let t=e.usage.completion_tokens;return e.usage.completion_tokens_details?.reasoning_tokens&&(t+=e.usage.completion_tokens_details.reasoning_tokens),{promptTokens:e.usage.prompt_tokens,promptCachedTokens:e.usage.prompt_tokens_details?.cached_tokens??null,promptCacheCreationTokens:null,promptImageTokens:null,completionTokens:t,totalTokens:e.usage.total_tokens}}async ainvoke(e,t){let n=aa.serializeMessages(e),s={model:this.model,messages:n};this.isReasoningModel?s.reasoning_effort=this.reasoningEffort:(s.temperature=this.temperature,s.frequency_penalty=this.frequencyPenalty),this.topP!==void 0&&(s.top_p=this.topP),this.seed!==void 0&&(s.seed=this.seed);try{if(t){let r=Io.createOptimizedJsonSchema(t),o=await this.client.chat.completions.create({...s,response_format:{type:"json_schema",json_schema:{name:"response",strict:!0,schema:r}}}),a=this.getUsage(o),c=o.choices[0]?.message?.content||"{}",l=JSON.parse(c);return{completion:t.parse(l),usage:a,stopReason:o.choices[0]?.finish_reason??null}}else{let r=await this.client.chat.completions.create(s),o=this.getUsage(r);return{completion:r.choices[0]?.message?.content||"",usage:o,stopReason:r.choices[0]?.finish_reason??null}}}catch(r){throw r.status===429?new Error(`Rate limit exceeded for model ${this.model}. Error: ${r.message}`):r.status?new Error(`OpenAI API error (${r.status}): ${r.message}`):new Error(`OpenAI invocation failed: ${r.message}`)}}}});import qf from"@anthropic-ai/sdk";import{zodToJsonSchema as Kf}from"zod-to-json-schema";var ca,ko,xu=F(()=>{"use strict";ca=class{static serializeMessages(e){let t=[],n=[];for(let s of e)if(s.role==="system"){let r=typeof s.content=="string"?s.content:s.content.map(o=>o.text).join(`
1200
+ `):null,...t.toolCalls&&{tool_calls:t.toolCalls.map(s=>({id:s.id,type:"function",function:{name:s.function.name,arguments:s.function.arguments}}))},...t.name&&{name:t.name}};throw new Error(`Unknown message role: ${t.role}`)})}},Js=class{model;client;temperature;frequencyPenalty;maxCompletionTokens;topP;seed;maxRetries;reasoningEffort;isReasoningModel;constructor(e){this.model=e.model,this.temperature=e.temperature??.2,this.frequencyPenalty=e.frequencyPenalty??.3,this.maxCompletionTokens=e.maxCompletionTokens,this.topP=e.topP,this.seed=e.seed,this.maxRetries=e.maxRetries??5,this.reasoningEffort=e.reasoningEffort??"low";let t=e.model.toLowerCase();this.isReasoningModel=zf.some(n=>t.includes(n.toLowerCase())),this.client=new jf({apiKey:e.apiKey,organization:e.organization,project:e.project,baseURL:e.baseURL,timeout:e.timeout,maxRetries:this.maxRetries,defaultHeaders:e.defaultHeaders})}get provider(){return"openai"}get name(){return this.model}getUsage(e){if(!e.usage)return null;let t=e.usage.completion_tokens;return e.usage.completion_tokens_details?.reasoning_tokens&&(t+=e.usage.completion_tokens_details.reasoning_tokens),{promptTokens:e.usage.prompt_tokens,promptCachedTokens:e.usage.prompt_tokens_details?.cached_tokens??null,promptCacheCreationTokens:null,promptImageTokens:null,completionTokens:t,totalTokens:e.usage.total_tokens}}async ainvoke(e,t){let n=aa.serializeMessages(e),s={model:this.model,messages:n};this.isReasoningModel?s.reasoning_effort=this.reasoningEffort:(s.temperature=this.temperature,s.frequency_penalty=this.frequencyPenalty),this.topP!==void 0&&(s.top_p=this.topP),this.seed!==void 0&&(s.seed=this.seed);try{if(t){let r=Io.createOptimizedJsonSchema(t),o=await this.client.chat.completions.create({...s,response_format:{type:"json_schema",json_schema:{name:"response",strict:!0,schema:r}}}),a=this.getUsage(o),c=o.choices[0]?.message?.content||"{}",l=JSON.parse(c);return{completion:t.parse(l),usage:a,stopReason:o.choices[0]?.finish_reason??null}}else{let r=await this.client.chat.completions.create(s),o=this.getUsage(r);return{completion:r.choices[0]?.message?.content||"",usage:o,stopReason:r.choices[0]?.finish_reason??null}}}catch(r){throw r.status===429?new Error(`Rate limit exceeded for model ${this.model}. Error: ${r.message}`):r.status?new Error(`OpenAI API error (${r.status}): ${r.message}`):new Error(`OpenAI invocation failed: ${r.message}`)}}}});import qf from"@anthropic-ai/sdk";import{zodToJsonSchema as Kf}from"zod-to-json-schema";var ca,ko,xu=$(()=>{"use strict";ca=class{static serializeMessages(e){let t=[],n=[];for(let s of e)if(s.role==="system"){let r=typeof s.content=="string"?s.content:s.content.map(o=>o.text).join(`
1201
1201
  `);t.push(r)}else if(s.role==="user")if(typeof s.content=="string")n.push({role:"user",content:s.content});else{let r=s.content.map(o=>{if(o.type==="text")return{type:"text",text:o.text};if(o.type==="image_url"){let a=o.imageUrl.url;if(a.startsWith("data:")){let[c,l]=a.split(",");return{type:"image",source:{type:"base64",media_type:c.split(";")[0].split(":")[1],data:l}}}else throw new Error("URL images not yet supported for Anthropic, use base64")}throw new Error(`Unsupported content part type: ${o.type}`)});n.push({role:"user",content:r})}else if(s.role==="assistant"){let r=typeof s.content=="string"?s.content:s.content?s.content.map(o=>o.type==="text"?o.text:"").join(`
1202
1202
  `):"";n.push({role:"assistant",content:r||""})}return{messages:n,systemPrompt:t.length>0?t.join(`
1203
1203
 
1204
- `):void 0}}},ko=class{model;client;maxTokens;temperature;topP;seed;constructor(e){this.model=e.model,this.maxTokens=e.maxTokens??8192,this.temperature=e.temperature,this.topP=e.topP,this.seed=e.seed,this.client=new qf({apiKey:e.apiKey,authToken:e.authToken,baseURL:e.baseURL,timeout:e.timeout,maxRetries:e.maxRetries??10,defaultHeaders:e.defaultHeaders})}get provider(){return"anthropic"}get name(){return this.model}getUsage(e){let t=e.usage;return{promptTokens:t.input_tokens+(t.cache_read_input_tokens||0),completionTokens:t.output_tokens,totalTokens:t.input_tokens+t.output_tokens,promptCachedTokens:t.cache_read_input_tokens??null,promptCacheCreationTokens:t.cache_creation_input_tokens??null,promptImageTokens:null}}async ainvoke(e,t){let{messages:n,systemPrompt:s}=ca.serializeMessages(e),r={model:this.model,messages:n,max_tokens:this.maxTokens,...s&&{system:s},...this.temperature!==void 0&&{temperature:this.temperature},...this.topP!==void 0&&{top_p:this.topP}};try{if(t){let o="extract_data",c={...Kf(t)};"title"in c&&delete c.title;let l={name:o,description:"Extract information in structured format",input_schema:{type:"object",...c}},d=await this.client.messages.create({...r,tools:[l],tool_choice:{type:"tool",name:o}}),g=this.getUsage(d),m=d.content.find(h=>h.type==="tool_use");if(!m||m.type!=="tool_use")throw new Error("No tool use found in response");return{completion:t.parse(m.input),usage:g,stopReason:d.stop_reason??null}}else{let o=await this.client.messages.create(r),a=this.getUsage(o),c=o.content[0];return{completion:c&&c.type==="text"?c.text:"",usage:a,stopReason:o.stop_reason??null}}}catch(o){throw o.status===429?new Error(`Rate limit exceeded for model ${this.model}. Error: ${o.message}`):o.status?new Error(`Anthropic API error (${o.status}): ${o.message}`):new Error(`Anthropic invocation failed: ${o.message}`)}}}});import{spawn as Vf}from"child_process";import{existsSync as Cu}from"fs";import{homedir as Eu}from"os";import{join as Iu}from"path";import{EventEmitter as Xf}from"events";var la,te,Po=F(()=>{"use strict";dt();Su();zi();Tu();xu();so();la=class i{static instance=null;browserSession=null;currentAgent=null;initState="idle";initPromise=null;initError=null;browsersInstalled=!1;systemChromePath=null;isExecuting=!1;stopRequested=!1;sessionLastActivity=0;sessionHeadlessMode=!1;executionLock=null;progressCallback=null;currentStep=0;currentMaxSteps=0;currentAction="";executionStartTime=0;agentTabs=new Map;runningAgents=new Map;static MAX_CONCURRENT_AGENTS=5;multiAgentMode=!1;browserSessionInitLock=null;static PLAYWRIGHT_INSTALL_TIMEOUT=300*1e3;tools=[{name:"browser_use_agent",description:"Execute a browser automation task using AI agent. The agent can navigate websites, fill forms, click buttons, extract data, and perform complex multi-step tasks.",inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to perform in the browser (e.g., "Go to google.com and search for AI news")'},model:{type:"string",description:'LLM model to use (e.g., "gpt-4o", "claude-sonnet-4-20250514", "o3")',default:"gpt-4o"},use_vision:{type:"boolean",description:"Whether to use vision/screenshots for the agent",default:!0},max_steps:{type:"number",description:"Maximum number of steps the agent can take",default:100},headless:{type:"boolean",description:"Run browser in headless mode",default:!1},keep_alive:{type:"boolean",description:"Keep browser open after task completion",default:!1}},required:["task"]}},{name:"retry_with_browser_use_agent",description:"Retry/execute a browser automation task (alias for browser_use_agent with additional parameters)",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task to perform in the browser"},firebase_token:{type:"string",description:"Firebase authentication token for API access"},model:{type:"string",description:"LLM model to use",default:"o3"},use_vision:{type:"boolean",description:"Whether to use vision/screenshots",default:!0},max_steps:{type:"number",description:"Maximum steps",default:100},keep_alive:{type:"boolean",description:"Keep browser open after completion",default:!0}},required:["task"]}}];statusEmitter=new Xf;constructor(){this.statusEmitter.setMaxListeners(20)}emitStatusChange(){try{let e=this.getStatus();this.statusEmitter.emit("status-changed",e)}catch{}}onStatusChange(e){return this.statusEmitter.on("status-changed",e),()=>{this.statusEmitter.off("status-changed",e)}}findSystemChrome(){let e=process.platform,t=[];e==="darwin"?t.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium",Iu(Eu(),"Applications/Google Chrome.app/Contents/MacOS/Google Chrome")):e==="win32"?t.push("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",Iu(Eu(),"AppData\\Local\\Google\\Chrome\\Application\\chrome.exe")):t.push("/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium");for(let n of t)if(Cu(n))return n;return null}async checkPatchrightBrowsers(){try{let{chromium:e}=await import("patchright"),t=e.executablePath();if(Cu(t))return!0}catch{}return!1}async installPlaywrightBrowsers(){return b.log("📦 [BrowserUse] Installing Patchright browsers..."),b.log(`⏳ [BrowserUse] This may take a few minutes (timeout: ${i.PLAYWRIGHT_INSTALL_TIMEOUT/1e3}s)...`),new Promise(e=>{let t=!1,n=null,s=setTimeout(()=>{if(!t){if(t=!0,console.error(`❌ [BrowserUse] Patchright install timed out after ${i.PLAYWRIGHT_INSTALL_TIMEOUT/1e3}s`),n)try{n.kill("SIGTERM")}catch{}e(!1)}},i.PLAYWRIGHT_INSTALL_TIMEOUT);try{let r=process.platform==="win32"?"npx.cmd":"npx";n=Vf(r,["patchright","install","chromium"],{stdio:"pipe",shell:!0});let o="";n.stdout?.on("data",a=>{o+=a.toString(),b.log(`[Patchright] ${a.toString().trim()}`)}),n.stderr?.on("data",a=>{o+=a.toString(),b.log(`[Patchright] ${a.toString().trim()}`)}),n.on("close",a=>{t||(t=!0,clearTimeout(s),a===0?(b.log("✅ [BrowserUse] Patchright browsers installed successfully!"),e(!0)):(console.error(`❌ [BrowserUse] Patchright install failed with code ${a}`),e(!1)))}),n.on("error",a=>{t||(t=!0,clearTimeout(s),console.error("❌ [BrowserUse] Failed to run patchright install:",a),e(!1))})}catch(r){t||(t=!0,clearTimeout(s),console.error("❌ [BrowserUse] Error installing Patchright browsers:",r),e(!1))}})}async ensureBrowsersAvailable(){if(this.systemChromePath=this.findSystemChrome(),this.systemChromePath){this.browsersInstalled=!0;return}if(await this.checkPatchrightBrowsers()){this.browsersInstalled=!0;return}if(await this.installPlaywrightBrowsers()){this.browsersInstalled=!0;return}throw this.browsersInstalled=!1,console.error("❌ [BrowserUse] No browsers available. Browser automation will not work."),console.error("❌ [BrowserUse] Please install Google Chrome or run: npx patchright install chromium"),new Error("No browser available. Please install Google Chrome.")}static shared(){return i.instance||(i.instance=new i),i.instance}async initialize(){switch(this.initState){case"initializing":if(this.initPromise)return this.initPromise;this.initState="idle",this.emitStatusChange();break;case"ready":return;case"error":this.initError=null;break;case"idle":break}this.initState="initializing",this.emitStatusChange(),this.initPromise=this._doInitialize();try{await this.initPromise}finally{this.initPromise=null}}async _doInitialize(){try{await this.ensureBrowsersAvailable(),this.initState="ready",this.initError=null,this.emitStatusChange()}catch(e){throw console.error("❌ [BrowserUse] Initialization failed:",e),this.initState="error",this.initError=e instanceof Error?e:new Error(String(e)),this.browsersInstalled=!1,this.emitStatusChange(),e}}getStatus(){let e=this.initState==="ready"&&this.browsersInstalled,t=es()?no():null,n=this.browserSession&&this.sessionLastActivity>0?Math.round((Date.now()-this.sessionLastActivity)/1e3):void 0;return{isRunning:e,isInitialized:e,isInitializing:this.initState==="initializing",initState:this.initState,toolCount:this.tools.length,hasBrowser:this.browsersInstalled,browserPath:this.systemChromePath||"patchright",error:this.initError?.message,hasProfile:t?.exists??!1,profileCookies:t?.cookieCount??0,hasActiveSession:this.browserSession!==null,sessionIdleSeconds:n,isExecuting:this.isExecuting||this.runningAgents.size>0,multiAgentMode:this.multiAgentMode,runningAgentCount:this.runningAgents.size,maxConcurrentAgents:i.MAX_CONCURRENT_AGENTS,tabCount:this.browserSession?.getTabCount?.()??0}}async listTools(){if(this.initState!=="ready")throw new Error("BrowserUseManager not initialized");return this.tools}async executeTool(e,t){switch(b.log(`🔧 [BrowserUse] Executing tool '${e}'...`),b.log("🔧 [BrowserUse] Arguments:",JSON.stringify(t,null,2)),this.initState){case"initializing":if(b.log("⏳ [BrowserUse] Waiting for initialization to complete..."),this.initPromise)try{await this.initPromise}catch{return{content:[{type:"text",text:"Browser automation initialization failed. Please try again."}],isError:!0}}break;case"error":return{content:[{type:"text",text:`Browser automation failed to initialize: ${this.initError?.message||"Unknown error"}`}],isError:!0};case"idle":return{content:[{type:"text",text:"Browser automation not initialized. Please wait for initialization to complete."}],isError:!0};case"ready":break}if(this.initState!=="ready")return{content:[{type:"text",text:"Browser automation not ready"}],isError:!0};if(this.stopRequested)return b.log("🛑 [BrowserUse] Stop was requested, not starting execution"),this.stopRequested=!1,{content:[{type:"text",text:"Execution cancelled by user"}],isError:!0};if(e!=="browser_use_agent"&&e!=="retry_with_browser_use_agent")return{content:[{type:"text",text:`Unknown tool: ${e}`}],isError:!0};if(this.isExecuting&&(b.log("⚠️ [BrowserUse] Another task is already executing, waiting for it to finish..."),this.executionLock))try{await Promise.race([this.executionLock,new Promise((s,r)=>setTimeout(()=>r(new Error("Timeout waiting for previous task")),5e3))])}catch{if(this.isExecuting)return console.warn("⚠️ [BrowserUse] Previous task still running, cannot start new task"),{content:[{type:"text",text:"Another task is currently running. Please stop it first or wait for it to complete."}],isError:!0}}let n=null;this.executionLock=new Promise(s=>{n=s}),this.isExecuting=!0;try{return{content:[{type:"text",text:await this.runBrowserAgent(t)}]}}catch(s){return this.stopRequested||s.message==="Interrupted"||s.message==="Agent stopped by user"?(b.log("🛑 [BrowserUse] Execution stopped by user"),{content:[{type:"text",text:"Task stopped by user"}],isError:!1}):(console.error("❌ [BrowserUse] Tool execution failed:",s),{content:[{type:"text",text:`Error: ${s.message}`}],isError:!0})}finally{n&&n(),this.executionLock=null,this.isExecuting=!1,this.stopRequested=!1,this.currentAgent=null}}async executeToolForSubAgent(e,t,n){if(b.log(`🔀 [BrowserUse] Multi-agent execution for sub-agent ${e}`),b.log(`🔧 [BrowserUse] Tool: ${t}`),this.initState==="initializing"&&this.initPromise){b.log("⏳ [BrowserUse] Waiting for initialization...");try{await this.initPromise}catch{return{content:[{type:"text",text:"Browser automation initialization failed"}],isError:!0}}}if(this.initState!=="ready")return{content:[{type:"text",text:`Browser automation not ready (state: ${this.initState})`}],isError:!0};if(this.runningAgents.size>=i.MAX_CONCURRENT_AGENTS)return console.warn(`⚠️ [BrowserUse] Max concurrent agents (${i.MAX_CONCURRENT_AGENTS}) reached`),{content:[{type:"text",text:`Maximum concurrent browser agents (${i.MAX_CONCURRENT_AGENTS}) reached. Please wait for other agents to complete.`}],isError:!0};this.multiAgentMode=!0;try{return{content:[{type:"text",text:await this.runBrowserAgentForSubAgent(e,n)}]}}catch(s){return console.error(`❌ [BrowserUse] Sub-agent ${e} execution failed:`,s),{content:[{type:"text",text:`Error: ${s.message}`}],isError:!0}}finally{this.runningAgents.delete(e),this.runningAgents.size===0&&(this.multiAgentMode=!1,b.log("🔀 [BrowserUse] All sub-agents completed, exiting multi-agent mode"))}}async ensureBrowserSessionForMultiAgent(e){if(this.browserSession){this.sessionHeadlessMode!==e&&(b.log(`⚠️ [BrowserUse] Headless mode mismatch (current: ${this.sessionHeadlessMode}, requested: ${e})`),b.log(`⚠️ [BrowserUse] Continuing with existing session (headless: ${this.sessionHeadlessMode})`));return}if(this.browserSessionInitLock){if(b.log("⏳ [BrowserUse] Waiting for browser session init (another sub-agent is creating)..."),await this.browserSessionInitLock,this.browserSession)return;console.warn("⚠️ [BrowserUse] Browser session still null after waiting, creating now...")}let t=null;this.browserSessionInitLock=new Promise(n=>{t=n});try{b.log("🌐 [BrowserUse] Creating browser session for multi-agent mode...");let n={headless:e};if(this.systemChromePath&&(b.log(`🌐 [BrowserUse] Using system Chrome: ${this.systemChromePath}`),n.executablePath=this.systemChromePath,n.channel=void 0),es()){let s=no();b.log(`🍪 [BrowserUse] Found imported profile: ${s.cookieCount} cookies, ${s.originCount} origins`);try{let r=Ws();r&&r.cookies&&r.cookies.length>0&&(n.storageState=r,b.log("✅ [BrowserUse] Profile loaded - browser will start authenticated"))}catch(r){console.error(`❌ [BrowserUse] Failed to load profile: ${r.message}`)}}this.browserSession=new kn(n),await this.browserSession.start(),this.sessionHeadlessMode=e,this.sessionLastActivity=Date.now(),b.log("✅ [BrowserUse] Browser session started for multi-agent mode")}finally{t&&t(),this.browserSessionInitLock=null}}async runBrowserAgentForSubAgent(e,t){let{task:n,model:s="gpt-4o",use_vision:r=!0,max_steps:o=100,headless:a=!1,keep_alive:c=!0,firebase_token:l}=t;b.log(`🤖 [BrowserUse] Starting sub-agent ${e}...`),b.log(`📝 [BrowserUse] Task: ${n}`),await this.ensureBrowserSessionForMultiAgent(a);let d=this.agentTabs.get(e);if(d)b.log(`🔄 [BrowserUse] Reusing tab ${d} for sub-agent ${e}`);else{let{pageId:f}=await this.browserSession.createTabForAgent(e);d=f,this.agentTabs.set(e,d),b.log(`🆕 [BrowserUse] Created tab ${d} for sub-agent ${e}`)}this.sessionLastActivity=Date.now();let g=this.createLLM(s,l),m=new Ys({task:n,llm:g,browserSession:this.browserSession,pageId:d,settings:{useVision:r??!0},maxSteps:o,registerShouldStopCallback:()=>this.stopRequested,registerNewStepCallback:async(f,y,T)=>{b.log(`📊 [BrowserUse] Sub-agent ${e} step ${T}/${o}`)}});this.runningAgents.set(e,m),b.log(`📊 [BrowserUse] Running agents: ${this.runningAgents.size}/${i.MAX_CONCURRENT_AGENTS}`);let p=await m.run();this.sessionLastActivity=Date.now();let h=this.extractResult(p);return c||await this.cleanupSubAgent(e),h}async cleanupSubAgent(e){let t=this.agentTabs.get(e);t&&this.browserSession&&(await this.browserSession.closeTab(t),this.agentTabs.delete(e),b.log(`🗑️ [BrowserUse] Cleaned up tab for sub-agent ${e}`)),this.runningAgents.delete(e)}async cleanupAllSubAgents(){b.log(`🗑️ [BrowserUse] Cleaning up all ${this.agentTabs.size} sub-agent tabs...`);for(let[e,t]of this.agentTabs.entries())this.browserSession&&await this.browserSession.closeTab(t),this.runningAgents.delete(e);this.agentTabs.clear(),this.multiAgentMode=!1,b.log("✅ [BrowserUse] All sub-agent tabs cleaned up")}getSubAgentStatus(){return{count:this.runningAgents.size,maxAllowed:i.MAX_CONCURRENT_AGENTS,agents:Array.from(this.agentTabs.entries()).map(([e,t])=>({subAgentId:e,pageId:t}))}}async stopSubAgent(e){let t=this.runningAgents.get(e);return t?(t.stop(),await this.cleanupSubAgent(e),b.log(`🛑 [BrowserUse] Stopped sub-agent ${e}`),!0):!1}async stopAllSubAgents(){b.log(`🛑 [BrowserUse] Stopping all ${this.runningAgents.size} sub-agents...`);for(let[e,t]of this.runningAgents.entries())t.stop();await this.cleanupAllSubAgents(),b.log("✅ [BrowserUse] All sub-agents stopped")}async runBrowserAgent(e){let{task:t,model:n="gpt-4o",use_vision:s=!0,max_steps:r=100,headless:o=!1,keep_alive:a=!1,firebase_token:c}=e;b.log("🤖 [BrowserUse] Starting browser agent..."),b.log(`📝 [BrowserUse] Task: ${t}`),b.log(`🧠 [BrowserUse] Model: ${n}`),b.log(`👁️ [BrowserUse] Vision: ${s}`),b.log(`🔢 [BrowserUse] Max steps: ${r}`),b.log(`🖥️ [BrowserUse] Headless: ${o}`);try{if(this.browserSession&&this.sessionHeadlessMode!==o&&(b.log(`⚠️ [BrowserUse] Headless mode mismatch (current: ${this.sessionHeadlessMode}, requested: ${o}), closing existing session`),await this.closeBrowserSession()),this.browserSession&&(await this.validateBrowserSession()||(b.log("⚠️ [BrowserUse] Existing browser session is no longer valid, creating new one"),await this.closeBrowserSession())),this.browserSession)b.log("🔄 [BrowserUse] Reusing existing browser session");else{b.log("🌐 [BrowserUse] Creating new browser session...");let m={headless:o};if(this.systemChromePath&&(b.log(`🌐 [BrowserUse] Using system Chrome: ${this.systemChromePath}`),m.executablePath=this.systemChromePath,m.channel=void 0),es()){let p=no();b.log(`🍪 [BrowserUse] Found imported profile: ${p.cookieCount} cookies, ${p.originCount} origins`);try{let h=Ws();h&&h.cookies&&h.cookies.length>0?(m.storageState=h,b.log("✅ [BrowserUse] Profile loaded - browser will start authenticated")):console.warn("⚠️ [BrowserUse] Profile file exists but contains no cookies - starting fresh")}catch(h){console.error(`❌ [BrowserUse] Failed to load profile: ${h.message} - starting fresh browser`)}}else b.log("ℹ️ [BrowserUse] No imported profile found - starting fresh browser");if(this.stopRequested)throw new Error("Agent stopped by user");if(this.browserSession=new kn(m),await this.browserSession.start(),this.sessionHeadlessMode=o,b.log("✅ [BrowserUse] Browser session started"),this.stopRequested)throw new Error("Agent stopped by user")}this.sessionLastActivity=Date.now();let l=this.createLLM(n,c);if(b.log(`✅ [BrowserUse] Created LLM: ${n}`),this.executionStartTime=Date.now(),this.currentStep=0,this.currentMaxSteps=r,this.currentAction="",this.emitProgress({type:"step_start",step:0,maxSteps:r,message:"Starting browser automation..."}),b.log("🤖 [BrowserUse] Creating agent..."),this.currentAgent=new Ys({task:t,llm:l,browserSession:this.browserSession,settings:{useVision:s??!0},maxSteps:r,registerShouldStopCallback:()=>this.stopRequested?(b.log("🛑 [BrowserUse] Stop requested via callback"),!0):!1,registerNewStepCallback:async(m,p,h)=>{let f=p.action?.[0]?Object.keys(p.action[0])[0]:void 0,y=m?.url||void 0;this.emitProgress({type:"step_complete",step:h,maxSteps:r,action:f,message:p.currentState?.summary||p.nextGoal,url:y}),f&&h<r-1&&this.emitProgress({type:"action_executing",step:h+1,maxSteps:r,action:f,message:`Executing: ${f}`,url:y})},registerDoneCallback:async m=>{let p=m.history?.length||r;this.emitProgress({type:"done",step:p,maxSteps:r,message:"Task completed"})}}),this.stopRequested)throw new Error("Agent stopped by user");b.log("▶️ [BrowserUse] Running agent...");let d=await this.currentAgent.run();b.log("✅ [BrowserUse] Agent completed"),this.sessionLastActivity=Date.now();let g=this.extractResult(d);return a?b.log("🌐 [BrowserUse] Browser session kept alive (keep_alive=true)"):(b.log("🧹 [BrowserUse] Cleaning up browser session (keep_alive=false)..."),await this.closeBrowserSession()),g}catch(l){throw console.error("❌ [BrowserUse] Agent execution failed:",l),this.sessionLastActivity=Date.now(),a?b.log("🌐 [BrowserUse] Browser session kept alive after error for reuse"):(b.log("🧹 [BrowserUse] Cleaning up browser session after error (keep_alive=false)..."),await this.closeBrowserSession()),l}}createLLM(e,t){let n=e.toLowerCase();if(n.includes("claude")||n.includes("anthropic"))return b.log("🧠 [BrowserUse] Using Anthropic provider"),new ko({model:e,apiKey:process.env.ANTHROPIC_API_KEY});if(t){let s=n.includes("o3")?"o3":"gpt-4o",o=`${process.env.SNOWX_API_URL||"https://snowx.ai/api-beta/api"}/browser-use/${s}/v1`;return b.log(`🧠 [BrowserUse] Using SnowX API (ChatOpenAI) with model: ${e}`),b.log(`🔒 [BrowserUse] Using SnowX API proxy at ${o}/chat/completions`),b.log(`🔐 [BrowserUse] Firebase token preview: ${t.substring(0,50)}...`),b.log(`🔐 [BrowserUse] Firebase token length: ${t.length}`),new Qs({model:e,apiKey:t,baseURL:o,temperature:.7})}return b.log("🧠 [BrowserUse] Using OpenAI provider (requires OPENAI_API_KEY)"),new Qs({model:e,apiKey:process.env.OPENAI_API_KEY})}extractResult(e){try{if(e.finalResult){let n=e.finalResult;if(n.extractedContent)return n.extractedContent;if(n.success!==void 0)return n.success?"Task completed successfully":"Task completed with errors"}if(e.history&&e.history.length>0){let n=e.history[e.history.length-1];if(n.result&&n.result.length>0){let s=n.result[n.result.length-1];if(s.extractedContent)return s.extractedContent;if(s.isDone)return s.success?"Task completed successfully":"Task completed with errors"}}let t=[];if(e.history){for(let n of e.history)if(n.result)for(let s of n.result)s.extractedContent&&t.push(s.extractedContent)}return t.length>0?t.join(`
1205
- `):"Task execution finished (no specific result)"}catch(t){return console.error("❌ [BrowserUse] Error extracting result:",t),"Task completed (result extraction failed)"}}emitProgress(e){let t={...e,timestamp:Date.now()};if(this.currentStep=e.step,this.currentMaxSteps=e.maxSteps,e.action&&(this.currentAction=e.action),this.sessionLastActivity=Date.now(),b.log(`📊 [BrowserUse] Progress: Step ${e.step}/${e.maxSteps} - ${e.type}${e.action?`: ${e.action}`:""}`),this.progressCallback)try{this.progressCallback(t)}catch(n){console.warn("⚠️ [BrowserUse] Progress callback error:",n)}}onProgress(e){this.progressCallback=e}setProgressCallback(e){this.progressCallback=e}async closeBrowserSession(){if(this.browserSession){try{await this.browserSession.stop(),b.log("✅ [BrowserUse] Browser session closed")}catch(e){console.warn("⚠️ [BrowserUse] Error closing browser session:",e)}this.browserSession=null,this.sessionLastActivity=0,this.sessionHeadlessMode=!1}this.currentAgent=null}async closeBrowser(){b.log("🔒 [BrowserUse] Explicitly closing browser session..."),await this.closeBrowserSession(),b.log("✅ [BrowserUse] Browser closed by user request")}isBrowserSessionAlive(){return this.browserSession!==null}getSessionIdleSeconds(){if(this.browserSession&&this.sessionLastActivity>0)return Math.round((Date.now()-this.sessionLastActivity)/1e3)}async validateBrowserSession(){if(!this.browserSession)return!1;try{let e=this.browserSession.getState(),t=new Promise((n,s)=>setTimeout(()=>s(new Error("Browser validation timeout (3s)")),3e3));return await Promise.race([e,t]),b.log("✅ [BrowserUse] Browser session validated - still responsive"),!0}catch(e){return console.warn(`⚠️ [BrowserUse] Browser session validation failed: ${e.message}`),console.warn("⚠️ [BrowserUse] Browser may have been closed externally or crashed"),!1}}requestStop(){b.log("🛑 [BrowserUse] Stop requested"),this.stopRequested=!0}async stop(){if(!this.isExecuting&&!this.currentAgent&&!this.stopRequested){b.log("🛑 [BrowserUse] Stop called but nothing to stop (already stopped or not running)"),this.browserSession&&(this.sessionLastActivity=Date.now());return}if(b.log("🛑 [BrowserUse] Stopping current execution (keeping browser session alive)..."),this.stopRequested=!0,b.log("🛑 [BrowserUse] Stop flag set, agent will stop at next checkpoint"),this.currentAgent)try{this.currentAgent.stop(),b.log("🛑 [BrowserUse] Agent stop() called")}catch(e){console.warn("⚠️ [BrowserUse] Error stopping agent:",e)}if(this.browserSession){try{await this.browserSession.saveStorageState(),b.log("💾 [BrowserUse] Browser state saved")}catch(e){console.warn("⚠️ [BrowserUse] Could not save browser state:",e)}b.log("🌐 [BrowserUse] Browser session kept alive for reuse"),this.sessionLastActivity=Date.now()}b.log("✅ [BrowserUse] Stop signal sent, waiting for execution to finish...")}async forceKill(){if(b.log("💀 [BrowserUse] Force killing and resetting all state..."),this.stopRequested=!0,this.isExecuting=!1,this.currentAgent){try{this.currentAgent.stop()}catch{}this.currentAgent=null}for(let[e,t]of this.runningAgents.entries())try{t.stop(),b.log(`💀 [BrowserUse] Force stopped sub-agent ${e}`)}catch{}if(this.runningAgents.clear(),this.agentTabs.clear(),this.multiAgentMode=!1,this.browserSession){try{await this.browserSession.stop()}catch{}this.browserSession=null}this.initState="idle",this.initPromise=null,this.initError=null,this.browsersInstalled=!1,this.systemChromePath=null,this.stopRequested=!1,this.sessionLastActivity=0,this.sessionHeadlessMode=!1,this.executionLock=null,this.emitStatusChange(),b.log("💀 [BrowserUse] Force kill completed - must call initialize() again")}async restart(){b.log("🔄 [BrowserUse] Restarting..."),await this.forceKill(),await this.initialize(),b.log("✅ [BrowserUse] Restarted")}isRunning(){return this.isExecuting}getExecutionStatus(){return{isExecuting:this.isExecuting,currentStep:this.currentStep,maxSteps:this.currentMaxSteps,currentAction:this.currentAction,startTime:this.executionStartTime,lastActivityTime:this.sessionLastActivity,hasActiveSession:this.browserSession!==null,sessionIdleSeconds:this.getSessionIdleSeconds()}}async cleanup(){if(b.log("🧹 [BrowserUse] Cleaning up internal state (browser stays open)..."),this.stopRequested=!0,this.currentAgent){try{this.currentAgent.stop()}catch{}this.currentAgent=null}this.browserSession&&b.log("🌐 [BrowserUse] Browser session left open for user"),this.browserSession=null,this.isExecuting=!1,this.stopRequested=!1,this.sessionLastActivity=0,this.sessionHeadlessMode=!1,this.executionLock=null,b.log("✅ [BrowserUse] Cleanup completed (browser still running)")}},te=la.shared()});var Js,IA,ku=F(()=>{"use strict";dt();Po();Te();Js=class{toolNames=["browser_automation","BrowserAutomation","browser_use_agent","BrowserUseAgent","browser_use","BrowserUse","retry_with_browser_use_agent"];initialized=!1;lastProgressTime=0;progressHistory=[];MAX_PROGRESS_HISTORY=200;async ensureInitialized(){if(!this.initialized)try{await te.initialize(),this.initialized=!0}catch(e){throw console.error("❌ [BrowserAutomation] Failed to initialize browser-use manager:",e),e}}async initialize(){try{return await this.ensureInitialized(),{success:!0}}catch(e){return console.error("❌ [BrowserAutomation] Initialization failed:",e),{success:!1}}}async listTools(){return te.listTools()}async executeTool(e,t){return await this.ensureInitialized(),te.executeTool(e,t)}async executeToolStream(e,t,n){await this.ensureInitialized(),te.setProgressCallback(n);try{return await te.executeTool(e,t)}finally{te.setProgressCallback(null)}}async execute(e,t,n,s){let r=n.task;if(!r)return[{type:"text",text:"Missing task argument"}];b.log("🌐 [BrowserAutomation] ==================== BROWSER AUTOMATION STARTED ===================="),b.log("📋 [BrowserAutomation] Task:",r),this.lastProgressTime=Date.now(),this.progressHistory=[];try{await this.ensureInitialized(),b.log("🔐 [BrowserAutomation] Getting Firebase authentication token...");let o=null;try{o=await X.getInstance().getFirebaseIdToken(),o&&b.log("✅ [BrowserAutomation] Got Firebase ID token")}catch{console.warn("⚠️ [BrowserAutomation] Could not get Firebase token, continuing without auth")}let a={task:r,firebase_token:o,model:n.model||"o3",use_vision:n.use_vision!==!1,max_steps:n.max_steps||100,keep_alive:n.keep_alive!==!1,headless:n.headless||!1};b.log("🔧 [BrowserAutomation] Executing with streaming progress..."),te.onProgress(d=>{this.handleProgress(d)});let c=await te.executeTool("browser_use_agent",a),l=[];if(c.content&&c.content.length>0)for(let d of c.content)d.type==="text"&&l.push({type:"text",text:d.text});return c.isError?console.error("❌ [BrowserAutomation] Execution failed"):b.log("✅ [BrowserAutomation] Execution completed successfully"),l.length===0&&l.push({type:"text",text:c.isError?"Browser automation task failed":"Browser automation task completed"}),b.log("✅ [BrowserAutomation] Task completed successfully"),b.log(`📊 [BrowserAutomation] Output length: ${l.reduce((d,g)=>d+(g.text?.length||0),0)} characters`),b.log(`📊 [BrowserAutomation] Steps executed: ${this.progressHistory.length}`),l}catch(o){return console.error("❌ [BrowserAutomation] Error:",o),[{type:"text",text:`Browser automation error: ${o.message}`}]}}handleProgress(e){this.lastProgressTime=Date.now(),this.progressHistory.length>=this.MAX_PROGRESS_HISTORY&&this.progressHistory.shift(),this.progressHistory.push(e);let t=`Step ${e.step}/${e.maxSteps}`;switch(e.type){case"step_start":b.log(`🚀 [BrowserAutomation] ${t} - Starting...`);break;case"step_complete":b.log(`✅ [BrowserAutomation] ${t} - ${e.action||"Complete"}`),e.message&&b.log(` 📝 ${e.message}`),e.url&&b.log(` 🌐 URL: ${e.url}`);break;case"action_executing":b.log(`⚡ [BrowserAutomation] ${t} - Executing: ${e.action}`);break;case"error":console.error(`❌ [BrowserAutomation] ${t} - Error: ${e.message}`);break;case"done":b.log(`🎉 [BrowserAutomation] Task completed at step ${e.step}`);break}}getStatus(){return te.getStatus()}async closeBrowser(){await te.closeBrowser()}requestStop(){te.requestStop()}async executeToolForSubAgent(e,t,n){let s=null;try{s=await X.getInstance().getFirebaseIdToken()}catch{console.warn("⚠️ [BrowserAutomation] Could not get Firebase token for sub-agent")}let r={...n,firebase_token:s||n.firebase_token};return te.executeToolForSubAgent(e,t,r)}getSubAgentStatus(){return te.getSubAgentStatus()}async stopSubAgent(e){return te.stopSubAgent(e)}async stopAllSubAgents(){return te.stopAllSubAgents()}async cleanupAllSubAgents(){return te.cleanupAllSubAgents()}async stop(){return te.stop()}async forceKill(){return te.forceKill()}async restart(){return te.restart()}isRunning(){return te.isRunning()}getExecutionStatus(){return te.getExecutionStatus()}isBrowserSessionAlive(){return te.isBrowserSessionAlive()}getSessionIdleSeconds(){return te.getSessionIdleSeconds()}setProgressCallback(e){te.setProgressCallback(e)}async cleanup(){return te.cleanup()}},IA=new Js});function Pu(i){i.register(new Dr),i.register(new Rr),i.register(new Or),i.register(new Nr),i.register(new _r),i.register(new $r),i.register(new Fr),i.register(new Br),i.register(new Wr),i.register(new Hr),i.register(new Gr),i.register(new jr),i.register(new zr),i.register(new qr),i.register(new Yr),i.register(new Qr),i.register(new Jr),i.register(new eo),i.register(new Js)}var Au=F(()=>{"use strict";rl();ol();il();al();cl();ll();ul();yl();vl();Sl();wl();Tl();xl();Cl();Al();Dl();Ml();Nl();ku()});var Zs,Du=F(()=>{"use strict";Zs=class{constructor(e,t,n,s,r,o){this.userId=e;this.sessionId=t;this.toolCallId=n;this.runningProcesses=s;this.activeWebViewURLs=r;this.workingDirectory=o}workingDirectory}});var Mu=F(()=>{"use strict"});import Xe from"fs";import nn from"path";import Yf from"os";var Qf,ua,Ot,Ru=F(()=>{"use strict";j();Qf=/[/\\:*?"<>|]/g,ua=class i{static instance;skillsPath;constructor(){this.skillsPath=nn.join(Yf.homedir(),".orion","skills")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.skillsPath}ensureFolder(){try{return Xe.existsSync(this.skillsPath)||(Xe.mkdirSync(this.skillsPath,{recursive:!0}),u.debug(`[Skills] Created skills folder: ${this.skillsPath}`)),!0}catch(e){return u.error(`[Skills] Failed to create skills folder: ${e.message}`),!1}}validateFilename(e){if(!e||typeof e!="string")return{valid:!1,error:"Skill name is required"};let t=e.trim();return t===""?{valid:!1,error:"Skill name cannot be empty"}:Qf.test(t)?{valid:!1,error:"Skill name contains invalid characters"}:nn.join(this.skillsPath,`${t}.md`).startsWith(this.skillsPath)?{valid:!0}:{valid:!1,error:"Invalid skill name (path traversal detected)"}}scanFolder(){try{this.ensureFolder();let e=Xe.readdirSync(this.skillsPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=nn.join(this.skillsPath,n);try{if(!Xe.statSync(s).isFile())continue;let o=Xe.readFileSync(s,"utf-8"),a=n.replace(/\.md$/,"");t.push({id:a,name:a,content:o})}catch(r){u.warn(`[Skills] Failed to read skill file ${n}: ${r.message}`)}}return u.debug(`[Skills] Scanned folder, found ${t.length} skills`),t}catch(e){return u.error(`[Skills] Failed to scan skills folder: ${e.message}`),[]}}createFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=e.trim(),r=nn.join(this.skillsPath,`${s}.md`);try{return this.ensureFolder(),Xe.existsSync(r)?{success:!1,error:"A skill with this name already exists"}:(Xe.writeFileSync(r,t,"utf-8"),u.debug(`[Skills] Created skill file: ${s}`),{success:!0,id:s})}catch(o){return u.error(`[Skills] Failed to create skill file: ${o.message}`),{success:!1,error:o.message}}}updateFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=nn.join(this.skillsPath,`${e}.md`);try{return Xe.existsSync(s)?(Xe.writeFileSync(s,t,"utf-8"),u.debug(`[Skills] Updated skill file: ${e}`),{success:!0}):{success:!1,error:"Skill not found"}}catch(r){return u.error(`[Skills] Failed to update skill file: ${r.message}`),{success:!1,error:r.message}}}deleteFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=nn.join(this.skillsPath,`${e}.md`);try{return Xe.existsSync(n)?(Xe.unlinkSync(n),u.debug(`[Skills] Deleted skill file: ${e}`),{success:!0}):{success:!1,error:"Skill not found"}}catch(s){return u.error(`[Skills] Failed to delete skill file: ${s.message}`),{success:!1,error:s.message}}}readFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=nn.join(this.skillsPath,`${e}.md`);try{return Xe.existsSync(n)?{success:!0,content:Xe.readFileSync(n,"utf-8")}:{success:!1,error:"Skill not found"}}catch(s){return u.error(`[Skills] Failed to read skill file: ${s.message}`),{success:!1,error:s.message}}}exists(e){if(!this.validateFilename(e).valid)return!1;let n=nn.join(this.skillsPath,`${e}.md`);return Xe.existsSync(n)}},Ot=ua.getInstance()});var Jf,Zf,eb,tb,nb,sb,rb,da,Ou=F(()=>{"use strict";Jf=[{id:"wacli",name:"WhatsApp",emoji:"📱",description:"Send WhatsApp messages to other people or search/sync WhatsApp history via the wacli CLI.",tags:["whatsapp","messaging","wacli"],content:`# wacli
1204
+ `):void 0}}},ko=class{model;client;maxTokens;temperature;topP;seed;constructor(e){this.model=e.model,this.maxTokens=e.maxTokens??8192,this.temperature=e.temperature,this.topP=e.topP,this.seed=e.seed,this.client=new qf({apiKey:e.apiKey,authToken:e.authToken,baseURL:e.baseURL,timeout:e.timeout,maxRetries:e.maxRetries??10,defaultHeaders:e.defaultHeaders})}get provider(){return"anthropic"}get name(){return this.model}getUsage(e){let t=e.usage;return{promptTokens:t.input_tokens+(t.cache_read_input_tokens||0),completionTokens:t.output_tokens,totalTokens:t.input_tokens+t.output_tokens,promptCachedTokens:t.cache_read_input_tokens??null,promptCacheCreationTokens:t.cache_creation_input_tokens??null,promptImageTokens:null}}async ainvoke(e,t){let{messages:n,systemPrompt:s}=ca.serializeMessages(e),r={model:this.model,messages:n,max_tokens:this.maxTokens,...s&&{system:s},...this.temperature!==void 0&&{temperature:this.temperature},...this.topP!==void 0&&{top_p:this.topP}};try{if(t){let o="extract_data",c={...Kf(t)};"title"in c&&delete c.title;let l={name:o,description:"Extract information in structured format",input_schema:{type:"object",...c}},d=await this.client.messages.create({...r,tools:[l],tool_choice:{type:"tool",name:o}}),g=this.getUsage(d),m=d.content.find(h=>h.type==="tool_use");if(!m||m.type!=="tool_use")throw new Error("No tool use found in response");return{completion:t.parse(m.input),usage:g,stopReason:d.stop_reason??null}}else{let o=await this.client.messages.create(r),a=this.getUsage(o),c=o.content[0];return{completion:c&&c.type==="text"?c.text:"",usage:a,stopReason:o.stop_reason??null}}}catch(o){throw o.status===429?new Error(`Rate limit exceeded for model ${this.model}. Error: ${o.message}`):o.status?new Error(`Anthropic API error (${o.status}): ${o.message}`):new Error(`Anthropic invocation failed: ${o.message}`)}}}});import{spawn as Vf}from"child_process";import{existsSync as Cu}from"fs";import{homedir as Eu}from"os";import{join as Iu}from"path";import{EventEmitter as Xf}from"events";var la,ne,Po=$(()=>{"use strict";dt();Su();zi();Tu();xu();so();la=class i{static instance=null;browserSession=null;currentAgent=null;initState="idle";initPromise=null;initError=null;browsersInstalled=!1;systemChromePath=null;isExecuting=!1;stopRequested=!1;sessionLastActivity=0;sessionHeadlessMode=!1;prewarmTriggered=!1;executionLock=null;progressCallback=null;currentStep=0;currentMaxSteps=0;currentAction="";executionStartTime=0;agentTabs=new Map;runningAgents=new Map;static MAX_CONCURRENT_AGENTS=5;multiAgentMode=!1;browserSessionInitLock=null;static PLAYWRIGHT_INSTALL_TIMEOUT=300*1e3;tools=[{name:"browser_use_agent",description:"Execute a browser automation task using AI agent. The agent can navigate websites, fill forms, click buttons, extract data, and perform complex multi-step tasks.",inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to perform in the browser (e.g., "Go to google.com and search for AI news")'},model:{type:"string",description:'LLM model to use (e.g., "gpt-4o", "claude-sonnet-4-20250514", "o3")',default:"gpt-4o"},use_vision:{type:"boolean",description:"Whether to use vision/screenshots for the agent",default:!0},max_steps:{type:"number",description:"Maximum number of steps the agent can take",default:100},headless:{type:"boolean",description:"Run browser in headless mode",default:!1},keep_alive:{type:"boolean",description:"Keep browser open after task completion",default:!1}},required:["task"]}},{name:"retry_with_browser_use_agent",description:"Retry/execute a browser automation task (alias for browser_use_agent with additional parameters)",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task to perform in the browser"},firebase_token:{type:"string",description:"Firebase authentication token for API access"},model:{type:"string",description:"LLM model to use",default:"o3"},use_vision:{type:"boolean",description:"Whether to use vision/screenshots",default:!0},max_steps:{type:"number",description:"Maximum steps",default:100},keep_alive:{type:"boolean",description:"Keep browser open after completion",default:!0}},required:["task"]}}];statusEmitter=new Xf;constructor(){this.statusEmitter.setMaxListeners(20)}emitStatusChange(){try{let e=this.getStatus();this.statusEmitter.emit("status-changed",e)}catch{}}onStatusChange(e){return this.statusEmitter.on("status-changed",e),()=>{this.statusEmitter.off("status-changed",e)}}findSystemChrome(){let e=process.platform,t=[];e==="darwin"?t.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium",Iu(Eu(),"Applications/Google Chrome.app/Contents/MacOS/Google Chrome")):e==="win32"?t.push("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",Iu(Eu(),"AppData\\Local\\Google\\Chrome\\Application\\chrome.exe")):t.push("/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium");for(let n of t)if(Cu(n))return n;return null}async checkPatchrightBrowsers(){try{let{chromium:e}=await import("patchright"),t=e.executablePath();if(Cu(t))return!0}catch{}return!1}async installPlaywrightBrowsers(){return b.log("📦 [BrowserUse] Installing Patchright browsers..."),b.log(`⏳ [BrowserUse] This may take a few minutes (timeout: ${i.PLAYWRIGHT_INSTALL_TIMEOUT/1e3}s)...`),new Promise(e=>{let t=!1,n=null,s=setTimeout(()=>{if(!t){if(t=!0,console.error(`❌ [BrowserUse] Patchright install timed out after ${i.PLAYWRIGHT_INSTALL_TIMEOUT/1e3}s`),n)try{n.kill("SIGTERM")}catch{}e(!1)}},i.PLAYWRIGHT_INSTALL_TIMEOUT);try{let r=process.platform==="win32"?"npx.cmd":"npx";n=Vf(r,["patchright","install","chromium"],{stdio:"pipe",shell:!0});let o="";n.stdout?.on("data",a=>{o+=a.toString(),b.log(`[Patchright] ${a.toString().trim()}`)}),n.stderr?.on("data",a=>{o+=a.toString(),b.log(`[Patchright] ${a.toString().trim()}`)}),n.on("close",a=>{t||(t=!0,clearTimeout(s),a===0?(b.log("✅ [BrowserUse] Patchright browsers installed successfully!"),e(!0)):(console.error(`❌ [BrowserUse] Patchright install failed with code ${a}`),e(!1)))}),n.on("error",a=>{t||(t=!0,clearTimeout(s),console.error("❌ [BrowserUse] Failed to run patchright install:",a),e(!1))})}catch(r){t||(t=!0,clearTimeout(s),console.error("❌ [BrowserUse] Error installing Patchright browsers:",r),e(!1))}})}async ensureBrowsersAvailable(){if(this.systemChromePath=this.findSystemChrome(),this.systemChromePath){this.browsersInstalled=!0;return}if(await this.checkPatchrightBrowsers()){this.browsersInstalled=!0;return}if(await this.installPlaywrightBrowsers()){this.browsersInstalled=!0;return}throw this.browsersInstalled=!1,console.error("❌ [BrowserUse] No browsers available. Browser automation will not work."),console.error("❌ [BrowserUse] Please install Google Chrome or run: npx patchright install chromium"),new Error("No browser available. Please install Google Chrome.")}static shared(){return i.instance||(i.instance=new i),i.instance}async initialize(){switch(this.initState){case"initializing":if(this.initPromise)return this.initPromise;this.initState="idle",this.emitStatusChange();break;case"ready":return;case"error":this.initError=null;break;case"idle":break}this.initState="initializing",this.emitStatusChange(),this.initPromise=this._doInitialize();try{await this.initPromise}finally{this.initPromise=null}}async _doInitialize(){try{await this.ensureBrowsersAvailable(),this.initState="ready",this.initError=null,this.emitStatusChange()}catch(e){throw console.error("❌ [BrowserUse] Initialization failed:",e),this.initState="error",this.initError=e instanceof Error?e:new Error(String(e)),this.browsersInstalled=!1,this.emitStatusChange(),e}}async prewarmBrowserSession(){if(this.browserSession){b.log("🔄 [BrowserUse] Browser session already exists, skipping pre-warm");return}b.log("🔥 [BrowserUse] Pre-warming browser session...");let e=Date.now();try{let n={headless:!1};if(this.systemChromePath&&(b.log(`🌐 [BrowserUse] Using system Chrome: ${this.systemChromePath}`),n.executablePath=this.systemChromePath,n.channel=void 0),Pn()){let r=Hs();b.log(`🍪 [BrowserUse] Found imported profile: ${r.cookieCount} cookies, ${r.originCount} origins`);try{let o=ns();o&&o.cookies&&o.cookies.length>0&&(n.storageState=o,b.log("✅ [BrowserUse] Profile loaded - browser will start authenticated"))}catch(o){b.log(`⚠️ [BrowserUse] Failed to load profile: ${o.message}`)}}this.browserSession=new en(n),await this.browserSession.start(),this.sessionHeadlessMode=!1,this.sessionLastActivity=Date.now();let s=Date.now()-e;b.log(`✅ [BrowserUse] Browser session pre-warmed in ${s}ms`)}catch(t){b.log(`⚠️ [BrowserUse] Pre-warm failed (will retry on first task): ${t.message}`),this.browserSession=null}}getStatus(){this.initState==="ready"&&!this.browserSession&&!this.prewarmTriggered&&(this.prewarmTriggered=!0,b.log("🔥 [BrowserUse] Triggering lazy pre-warm (first status check)"),this.prewarmBrowserSession().catch(s=>{b.log(`⚠️ [BrowserUse] Lazy pre-warm failed: ${s.message}`)}));let e=this.initState==="ready"&&this.browsersInstalled,t=Pn()?Hs():null,n=this.browserSession&&this.sessionLastActivity>0?Math.round((Date.now()-this.sessionLastActivity)/1e3):void 0;return{isRunning:e,isInitialized:e,isInitializing:this.initState==="initializing",initState:this.initState,toolCount:this.tools.length,hasBrowser:this.browsersInstalled,browserPath:this.systemChromePath||"patchright",error:this.initError?.message,hasProfile:t?.exists??!1,profileCookies:t?.cookieCount??0,hasActiveSession:this.browserSession!==null,sessionIdleSeconds:n,isExecuting:this.isExecuting||this.runningAgents.size>0,multiAgentMode:this.multiAgentMode,runningAgentCount:this.runningAgents.size,maxConcurrentAgents:i.MAX_CONCURRENT_AGENTS,tabCount:this.browserSession?.getTabCount?.()??0}}async listTools(){if(this.initState!=="ready")throw new Error("BrowserUseManager not initialized");return this.tools}async executeTool(e,t){switch(b.log(`🔧 [BrowserUse] Executing tool '${e}'...`),b.log("🔧 [BrowserUse] Arguments:",JSON.stringify(t,null,2)),this.initState){case"initializing":if(b.log("⏳ [BrowserUse] Waiting for initialization to complete..."),this.initPromise)try{await this.initPromise}catch{return{content:[{type:"text",text:"Browser automation initialization failed. Please try again."}],isError:!0}}break;case"error":return{content:[{type:"text",text:`Browser automation failed to initialize: ${this.initError?.message||"Unknown error"}`}],isError:!0};case"idle":return{content:[{type:"text",text:"Browser automation not initialized. Please wait for initialization to complete."}],isError:!0};case"ready":break}if(this.initState!=="ready")return{content:[{type:"text",text:"Browser automation not ready"}],isError:!0};if(this.stopRequested)return b.log("🛑 [BrowserUse] Stop was requested, not starting execution"),this.stopRequested=!1,{content:[{type:"text",text:"Execution cancelled by user"}],isError:!0};if(e!=="browser_use_agent"&&e!=="retry_with_browser_use_agent")return{content:[{type:"text",text:`Unknown tool: ${e}`}],isError:!0};if(this.isExecuting&&(b.log("⚠️ [BrowserUse] Another task is already executing, waiting for it to finish..."),this.executionLock))try{await Promise.race([this.executionLock,new Promise((s,r)=>setTimeout(()=>r(new Error("Timeout waiting for previous task")),5e3))])}catch{if(this.isExecuting)return console.warn("⚠️ [BrowserUse] Previous task still running, cannot start new task"),{content:[{type:"text",text:"Another task is currently running. Please stop it first or wait for it to complete."}],isError:!0}}let n=null;this.executionLock=new Promise(s=>{n=s}),this.isExecuting=!0;try{return{content:[{type:"text",text:await this.runBrowserAgent(t)}]}}catch(s){return this.stopRequested||s.message==="Interrupted"||s.message==="Agent stopped by user"?(b.log("🛑 [BrowserUse] Execution stopped by user"),{content:[{type:"text",text:"Task stopped by user"}],isError:!1}):(console.error("❌ [BrowserUse] Tool execution failed:",s),{content:[{type:"text",text:`Error: ${s.message}`}],isError:!0})}finally{n&&n(),this.executionLock=null,this.isExecuting=!1,this.stopRequested=!1,this.currentAgent=null}}async executeToolForSubAgent(e,t,n){if(b.log(`🔀 [BrowserUse] Multi-agent execution for sub-agent ${e}`),b.log(`🔧 [BrowserUse] Tool: ${t}`),this.initState==="initializing"&&this.initPromise){b.log("⏳ [BrowserUse] Waiting for initialization...");try{await this.initPromise}catch{return{content:[{type:"text",text:"Browser automation initialization failed"}],isError:!0}}}if(this.initState!=="ready")return{content:[{type:"text",text:`Browser automation not ready (state: ${this.initState})`}],isError:!0};if(this.runningAgents.size>=i.MAX_CONCURRENT_AGENTS)return console.warn(`⚠️ [BrowserUse] Max concurrent agents (${i.MAX_CONCURRENT_AGENTS}) reached`),{content:[{type:"text",text:`Maximum concurrent browser agents (${i.MAX_CONCURRENT_AGENTS}) reached. Please wait for other agents to complete.`}],isError:!0};this.multiAgentMode=!0;try{return{content:[{type:"text",text:await this.runBrowserAgentForSubAgent(e,n)}]}}catch(s){return console.error(`❌ [BrowserUse] Sub-agent ${e} execution failed:`,s),{content:[{type:"text",text:`Error: ${s.message}`}],isError:!0}}finally{this.runningAgents.delete(e),this.runningAgents.size===0&&(this.multiAgentMode=!1,b.log("🔀 [BrowserUse] All sub-agents completed, exiting multi-agent mode"))}}async ensureBrowserSessionForMultiAgent(e){if(this.browserSession){this.sessionHeadlessMode!==e&&(b.log(`⚠️ [BrowserUse] Headless mode mismatch (current: ${this.sessionHeadlessMode}, requested: ${e})`),b.log(`⚠️ [BrowserUse] Continuing with existing session (headless: ${this.sessionHeadlessMode})`));return}if(this.browserSessionInitLock){if(b.log("⏳ [BrowserUse] Waiting for browser session init (another sub-agent is creating)..."),await this.browserSessionInitLock,this.browserSession)return;console.warn("⚠️ [BrowserUse] Browser session still null after waiting, creating now...")}let t=null;this.browserSessionInitLock=new Promise(n=>{t=n});try{b.log("🌐 [BrowserUse] Creating browser session for multi-agent mode...");let n={headless:e};if(this.systemChromePath&&(b.log(`🌐 [BrowserUse] Using system Chrome: ${this.systemChromePath}`),n.executablePath=this.systemChromePath,n.channel=void 0),Pn()){let s=Hs();b.log(`🍪 [BrowserUse] Found imported profile: ${s.cookieCount} cookies, ${s.originCount} origins`);try{let r=ns();r&&r.cookies&&r.cookies.length>0&&(n.storageState=r,b.log("✅ [BrowserUse] Profile loaded - browser will start authenticated"))}catch(r){console.error(`❌ [BrowserUse] Failed to load profile: ${r.message}`)}}this.browserSession=new en(n),await this.browserSession.start(),this.sessionHeadlessMode=e,this.sessionLastActivity=Date.now(),b.log("✅ [BrowserUse] Browser session started for multi-agent mode")}finally{t&&t(),this.browserSessionInitLock=null}}async runBrowserAgentForSubAgent(e,t){let{task:n,model:s="gpt-4o",use_vision:r=!0,max_steps:o=100,headless:a=!1,keep_alive:c=!0,firebase_token:l}=t;b.log(`🤖 [BrowserUse] Starting sub-agent ${e}...`),b.log(`📝 [BrowserUse] Task: ${n}`),await this.ensureBrowserSessionForMultiAgent(a);let d=this.agentTabs.get(e);if(d)b.log(`🔄 [BrowserUse] Reusing tab ${d} for sub-agent ${e}`);else{let{pageId:f}=await this.browserSession.createTabForAgent(e);d=f,this.agentTabs.set(e,d),b.log(`🆕 [BrowserUse] Created tab ${d} for sub-agent ${e}`)}this.sessionLastActivity=Date.now();let g=this.createLLM(s,l),m=new Qs({task:n,llm:g,browserSession:this.browserSession,pageId:d,settings:{useVision:r??!0},maxSteps:o,registerShouldStopCallback:()=>this.stopRequested,registerNewStepCallback:async(f,y,T)=>{b.log(`📊 [BrowserUse] Sub-agent ${e} step ${T}/${o}`)}});this.runningAgents.set(e,m),b.log(`📊 [BrowserUse] Running agents: ${this.runningAgents.size}/${i.MAX_CONCURRENT_AGENTS}`);let p=await m.run();this.sessionLastActivity=Date.now();let h=this.extractResult(p);return c||await this.cleanupSubAgent(e),h}async cleanupSubAgent(e){let t=this.agentTabs.get(e);t&&this.browserSession&&(await this.browserSession.closeTab(t),this.agentTabs.delete(e),b.log(`🗑️ [BrowserUse] Cleaned up tab for sub-agent ${e}`)),this.runningAgents.delete(e)}async cleanupAllSubAgents(){b.log(`🗑️ [BrowserUse] Cleaning up all ${this.agentTabs.size} sub-agent tabs...`);for(let[e,t]of this.agentTabs.entries())this.browserSession&&await this.browserSession.closeTab(t),this.runningAgents.delete(e);this.agentTabs.clear(),this.multiAgentMode=!1,b.log("✅ [BrowserUse] All sub-agent tabs cleaned up")}getSubAgentStatus(){return{count:this.runningAgents.size,maxAllowed:i.MAX_CONCURRENT_AGENTS,agents:Array.from(this.agentTabs.entries()).map(([e,t])=>({subAgentId:e,pageId:t}))}}async stopSubAgent(e){let t=this.runningAgents.get(e);return t?(t.stop(),await this.cleanupSubAgent(e),b.log(`🛑 [BrowserUse] Stopped sub-agent ${e}`),!0):!1}async stopAllSubAgents(){b.log(`🛑 [BrowserUse] Stopping all ${this.runningAgents.size} sub-agents...`);for(let[e,t]of this.runningAgents.entries())t.stop();await this.cleanupAllSubAgents(),b.log("✅ [BrowserUse] All sub-agents stopped")}async runBrowserAgent(e){let{task:t,model:n="gpt-4o",use_vision:s=!0,max_steps:r=100,headless:o=!1,keep_alive:a=!1,firebase_token:c}=e;b.log("🤖 [BrowserUse] Starting browser agent..."),b.log(`📝 [BrowserUse] Task: ${t}`),b.log(`🧠 [BrowserUse] Model: ${n}`),b.log(`👁️ [BrowserUse] Vision: ${s}`),b.log(`🔢 [BrowserUse] Max steps: ${r}`),b.log(`🖥️ [BrowserUse] Headless: ${o}`);try{if(this.browserSession&&this.sessionHeadlessMode!==o&&(b.log(`⚠️ [BrowserUse] Headless mode mismatch (current: ${this.sessionHeadlessMode}, requested: ${o}), closing existing session`),await this.closeBrowserSession()),this.browserSession&&(await this.validateBrowserSession()||(b.log("⚠️ [BrowserUse] Existing browser session is no longer valid, creating new one"),await this.closeBrowserSession())),this.browserSession)b.log("🔄 [BrowserUse] Reusing existing browser session");else{b.log("🌐 [BrowserUse] Creating new browser session...");let m={headless:o};if(this.systemChromePath&&(b.log(`🌐 [BrowserUse] Using system Chrome: ${this.systemChromePath}`),m.executablePath=this.systemChromePath,m.channel=void 0),Pn()){let p=Hs();b.log(`🍪 [BrowserUse] Found imported profile: ${p.cookieCount} cookies, ${p.originCount} origins`);try{let h=ns();h&&h.cookies&&h.cookies.length>0?(m.storageState=h,b.log("✅ [BrowserUse] Profile loaded - browser will start authenticated")):console.warn("⚠️ [BrowserUse] Profile file exists but contains no cookies - starting fresh")}catch(h){console.error(`❌ [BrowserUse] Failed to load profile: ${h.message} - starting fresh browser`)}}else b.log("ℹ️ [BrowserUse] No imported profile found - starting fresh browser");if(this.stopRequested)throw new Error("Agent stopped by user");if(this.browserSession=new en(m),await this.browserSession.start(),this.sessionHeadlessMode=o,b.log("✅ [BrowserUse] Browser session started"),this.stopRequested)throw new Error("Agent stopped by user")}this.sessionLastActivity=Date.now();let l=this.createLLM(n,c);if(b.log(`✅ [BrowserUse] Created LLM: ${n}`),this.executionStartTime=Date.now(),this.currentStep=0,this.currentMaxSteps=r,this.currentAction="",this.emitProgress({type:"step_start",step:0,maxSteps:r,message:"Starting browser automation..."}),b.log("🤖 [BrowserUse] Creating agent..."),this.currentAgent=new Qs({task:t,llm:l,browserSession:this.browserSession,settings:{useVision:s??!0},maxSteps:r,registerShouldStopCallback:()=>this.stopRequested?(b.log("🛑 [BrowserUse] Stop requested via callback"),!0):!1,registerNewStepCallback:async(m,p,h)=>{let f=p.action?.[0]?Object.keys(p.action[0])[0]:void 0,y=m?.url||void 0;this.emitProgress({type:"step_complete",step:h,maxSteps:r,action:f,message:p.currentState?.summary||p.nextGoal,url:y}),f&&h<r-1&&this.emitProgress({type:"action_executing",step:h+1,maxSteps:r,action:f,message:`Executing: ${f}`,url:y})},registerDoneCallback:async m=>{let p=m.history?.length||r;this.emitProgress({type:"done",step:p,maxSteps:r,message:"Task completed"})}}),this.stopRequested)throw new Error("Agent stopped by user");b.log("▶️ [BrowserUse] Running agent...");let d=await this.currentAgent.run();b.log("✅ [BrowserUse] Agent completed"),this.sessionLastActivity=Date.now();let g=this.extractResult(d);return a?b.log("🌐 [BrowserUse] Browser session kept alive (keep_alive=true)"):(b.log("🧹 [BrowserUse] Cleaning up browser session (keep_alive=false)..."),await this.closeBrowserSession()),g}catch(l){throw console.error("❌ [BrowserUse] Agent execution failed:",l),this.sessionLastActivity=Date.now(),a?b.log("🌐 [BrowserUse] Browser session kept alive after error for reuse"):(b.log("🧹 [BrowserUse] Cleaning up browser session after error (keep_alive=false)..."),await this.closeBrowserSession()),l}}createLLM(e,t){let n=e.toLowerCase();if(n.includes("claude")||n.includes("anthropic"))return b.log("🧠 [BrowserUse] Using Anthropic provider"),new ko({model:e,apiKey:process.env.ANTHROPIC_API_KEY});if(t){let s=n.includes("o3")?"o3":"gpt-4o",o=`${process.env.SNOWX_API_URL||"https://snowx.ai/api-beta/api"}/browser-use/${s}/v1`;return b.log(`🧠 [BrowserUse] Using SnowX API (ChatOpenAI) with model: ${e}`),b.log(`🔒 [BrowserUse] Using SnowX API proxy at ${o}/chat/completions`),b.log(`🔐 [BrowserUse] Firebase token preview: ${t.substring(0,50)}...`),b.log(`🔐 [BrowserUse] Firebase token length: ${t.length}`),new Js({model:e,apiKey:t,baseURL:o,temperature:.7})}return b.log("🧠 [BrowserUse] Using OpenAI provider (requires OPENAI_API_KEY)"),new Js({model:e,apiKey:process.env.OPENAI_API_KEY})}extractResult(e){try{if(e.finalResult){let n=e.finalResult;if(n.extractedContent)return n.extractedContent;if(n.success!==void 0)return n.success?"Task completed successfully":"Task completed with errors"}if(e.history&&e.history.length>0){let n=e.history[e.history.length-1];if(n.result&&n.result.length>0){let s=n.result[n.result.length-1];if(s.extractedContent)return s.extractedContent;if(s.isDone)return s.success?"Task completed successfully":"Task completed with errors"}}let t=[];if(e.history){for(let n of e.history)if(n.result)for(let s of n.result)s.extractedContent&&t.push(s.extractedContent)}return t.length>0?t.join(`
1205
+ `):"Task execution finished (no specific result)"}catch(t){return console.error("❌ [BrowserUse] Error extracting result:",t),"Task completed (result extraction failed)"}}emitProgress(e){let t={...e,timestamp:Date.now()};if(this.currentStep=e.step,this.currentMaxSteps=e.maxSteps,e.action&&(this.currentAction=e.action),this.sessionLastActivity=Date.now(),b.log(`📊 [BrowserUse] Progress: Step ${e.step}/${e.maxSteps} - ${e.type}${e.action?`: ${e.action}`:""}`),this.progressCallback)try{this.progressCallback(t)}catch(n){console.warn("⚠️ [BrowserUse] Progress callback error:",n)}}onProgress(e){this.progressCallback=e}setProgressCallback(e){this.progressCallback=e}async closeBrowserSession(){if(this.browserSession){try{await this.browserSession.stop(),b.log("✅ [BrowserUse] Browser session closed")}catch(e){console.warn("⚠️ [BrowserUse] Error closing browser session:",e)}this.browserSession=null,this.sessionLastActivity=0,this.sessionHeadlessMode=!1}this.currentAgent=null}async closeBrowser(){b.log("🔒 [BrowserUse] Explicitly closing browser session..."),await this.closeBrowserSession(),b.log("✅ [BrowserUse] Browser closed by user request")}isBrowserSessionAlive(){return this.browserSession!==null}getSessionIdleSeconds(){if(this.browserSession&&this.sessionLastActivity>0)return Math.round((Date.now()-this.sessionLastActivity)/1e3)}async validateBrowserSession(){if(!this.browserSession)return!1;try{let e=this.browserSession.getState(),t=new Promise((n,s)=>setTimeout(()=>s(new Error("Browser validation timeout (3s)")),3e3));return await Promise.race([e,t]),b.log("✅ [BrowserUse] Browser session validated - still responsive"),!0}catch(e){return console.warn(`⚠️ [BrowserUse] Browser session validation failed: ${e.message}`),console.warn("⚠️ [BrowserUse] Browser may have been closed externally or crashed"),!1}}requestStop(){b.log("🛑 [BrowserUse] Stop requested"),this.stopRequested=!0}async stop(){if(!this.isExecuting&&!this.currentAgent&&!this.stopRequested){b.log("🛑 [BrowserUse] Stop called but nothing to stop (already stopped or not running)"),this.browserSession&&(this.sessionLastActivity=Date.now());return}if(b.log("🛑 [BrowserUse] Stopping current execution (keeping browser session alive)..."),this.stopRequested=!0,b.log("🛑 [BrowserUse] Stop flag set, agent will stop at next checkpoint"),this.currentAgent)try{this.currentAgent.stop(),b.log("🛑 [BrowserUse] Agent stop() called")}catch(e){console.warn("⚠️ [BrowserUse] Error stopping agent:",e)}if(this.browserSession){try{await this.browserSession.saveStorageState(),b.log("💾 [BrowserUse] Browser state saved")}catch(e){console.warn("⚠️ [BrowserUse] Could not save browser state:",e)}b.log("🌐 [BrowserUse] Browser session kept alive for reuse"),this.sessionLastActivity=Date.now()}b.log("✅ [BrowserUse] Stop signal sent, waiting for execution to finish...")}async forceKill(){if(b.log("💀 [BrowserUse] Force killing and resetting all state..."),this.stopRequested=!0,this.isExecuting=!1,this.currentAgent){try{this.currentAgent.stop()}catch{}this.currentAgent=null}for(let[e,t]of this.runningAgents.entries())try{t.stop(),b.log(`💀 [BrowserUse] Force stopped sub-agent ${e}`)}catch{}if(this.runningAgents.clear(),this.agentTabs.clear(),this.multiAgentMode=!1,this.browserSession){try{await this.browserSession.stop()}catch{}this.browserSession=null}this.initState="idle",this.initPromise=null,this.initError=null,this.browsersInstalled=!1,this.systemChromePath=null,this.stopRequested=!1,this.sessionLastActivity=0,this.sessionHeadlessMode=!1,this.executionLock=null,this.emitStatusChange(),b.log("💀 [BrowserUse] Force kill completed - must call initialize() again")}async restart(){b.log("🔄 [BrowserUse] Restarting..."),await this.forceKill(),await this.initialize(),b.log("✅ [BrowserUse] Restarted")}isRunning(){return this.isExecuting}getExecutionStatus(){return{isExecuting:this.isExecuting,currentStep:this.currentStep,maxSteps:this.currentMaxSteps,currentAction:this.currentAction,startTime:this.executionStartTime,lastActivityTime:this.sessionLastActivity,hasActiveSession:this.browserSession!==null,sessionIdleSeconds:this.getSessionIdleSeconds()}}async cleanup(){if(b.log("🧹 [BrowserUse] Cleaning up internal state (browser stays open)..."),this.stopRequested=!0,this.currentAgent){try{this.currentAgent.stop()}catch{}this.currentAgent=null}this.browserSession&&b.log("🌐 [BrowserUse] Browser session left open for user"),this.browserSession=null,this.isExecuting=!1,this.stopRequested=!1,this.sessionLastActivity=0,this.sessionHeadlessMode=!1,this.executionLock=null,b.log("✅ [BrowserUse] Cleanup completed (browser still running)")}},ne=la.shared()});var Zs,IA,ku=$(()=>{"use strict";dt();Po();xe();Zs=class{toolNames=["browser_automation","BrowserAutomation","browser_use_agent","BrowserUseAgent","browser_use","BrowserUse","retry_with_browser_use_agent"];initialized=!1;lastProgressTime=0;progressHistory=[];MAX_PROGRESS_HISTORY=200;async ensureInitialized(){if(!this.initialized)try{await ne.initialize(),this.initialized=!0}catch(e){throw console.error("❌ [BrowserAutomation] Failed to initialize browser-use manager:",e),e}}async initialize(){try{return await this.ensureInitialized(),{success:!0}}catch(e){return console.error("❌ [BrowserAutomation] Initialization failed:",e),{success:!1}}}async listTools(){return ne.listTools()}async executeTool(e,t){return await this.ensureInitialized(),ne.executeTool(e,t)}async executeToolStream(e,t,n){await this.ensureInitialized(),ne.setProgressCallback(n);try{return await ne.executeTool(e,t)}finally{ne.setProgressCallback(null)}}async execute(e,t,n,s){let r=n.task;if(!r)return[{type:"text",text:"Missing task argument"}];b.log("🌐 [BrowserAutomation] ==================== BROWSER AUTOMATION STARTED ===================="),b.log("📋 [BrowserAutomation] Task:",r),this.lastProgressTime=Date.now(),this.progressHistory=[];try{await this.ensureInitialized(),b.log("🔐 [BrowserAutomation] Getting Firebase authentication token...");let o=null;try{o=await X.getInstance().getFirebaseIdToken(),o&&b.log("✅ [BrowserAutomation] Got Firebase ID token")}catch{console.warn("⚠️ [BrowserAutomation] Could not get Firebase token, continuing without auth")}let a={task:r,firebase_token:o,model:n.model||"o3",use_vision:n.use_vision!==!1,max_steps:n.max_steps||100,keep_alive:n.keep_alive!==!1,headless:n.headless||!1};b.log("🔧 [BrowserAutomation] Executing with streaming progress..."),ne.onProgress(d=>{this.handleProgress(d)});let c=await ne.executeTool("browser_use_agent",a),l=[];if(c.content&&c.content.length>0)for(let d of c.content)d.type==="text"&&l.push({type:"text",text:d.text});return c.isError?console.error("❌ [BrowserAutomation] Execution failed"):b.log("✅ [BrowserAutomation] Execution completed successfully"),l.length===0&&l.push({type:"text",text:c.isError?"Browser automation task failed":"Browser automation task completed"}),b.log("✅ [BrowserAutomation] Task completed successfully"),b.log(`📊 [BrowserAutomation] Output length: ${l.reduce((d,g)=>d+(g.text?.length||0),0)} characters`),b.log(`📊 [BrowserAutomation] Steps executed: ${this.progressHistory.length}`),l}catch(o){return console.error("❌ [BrowserAutomation] Error:",o),[{type:"text",text:`Browser automation error: ${o.message}`}]}}handleProgress(e){this.lastProgressTime=Date.now(),this.progressHistory.length>=this.MAX_PROGRESS_HISTORY&&this.progressHistory.shift(),this.progressHistory.push(e);let t=`Step ${e.step}/${e.maxSteps}`;switch(e.type){case"step_start":b.log(`🚀 [BrowserAutomation] ${t} - Starting...`);break;case"step_complete":b.log(`✅ [BrowserAutomation] ${t} - ${e.action||"Complete"}`),e.message&&b.log(` 📝 ${e.message}`),e.url&&b.log(` 🌐 URL: ${e.url}`);break;case"action_executing":b.log(`⚡ [BrowserAutomation] ${t} - Executing: ${e.action}`);break;case"error":console.error(`❌ [BrowserAutomation] ${t} - Error: ${e.message}`);break;case"done":b.log(`🎉 [BrowserAutomation] Task completed at step ${e.step}`);break}}getStatus(){return ne.getStatus()}async closeBrowser(){await ne.closeBrowser()}requestStop(){ne.requestStop()}async executeToolForSubAgent(e,t,n){let s=null;try{s=await X.getInstance().getFirebaseIdToken()}catch{console.warn("⚠️ [BrowserAutomation] Could not get Firebase token for sub-agent")}let r={...n,firebase_token:s||n.firebase_token};return ne.executeToolForSubAgent(e,t,r)}getSubAgentStatus(){return ne.getSubAgentStatus()}async stopSubAgent(e){return ne.stopSubAgent(e)}async stopAllSubAgents(){return ne.stopAllSubAgents()}async cleanupAllSubAgents(){return ne.cleanupAllSubAgents()}async stop(){return ne.stop()}async forceKill(){return ne.forceKill()}async restart(){return ne.restart()}isRunning(){return ne.isRunning()}getExecutionStatus(){return ne.getExecutionStatus()}isBrowserSessionAlive(){return ne.isBrowserSessionAlive()}getSessionIdleSeconds(){return ne.getSessionIdleSeconds()}setProgressCallback(e){ne.setProgressCallback(e)}async cleanup(){return ne.cleanup()}},IA=new Zs});function Pu(i){i.register(new Mr),i.register(new Or),i.register(new Nr),i.register(new _r),i.register(new $r),i.register(new Fr),i.register(new Lr),i.register(new Wr),i.register(new Hr),i.register(new Gr),i.register(new jr),i.register(new zr),i.register(new qr),i.register(new Kr),i.register(new Qr),i.register(new Jr),i.register(new Zr),i.register(new to),i.register(new Zs)}var Au=$(()=>{"use strict";rl();ol();il();al();cl();ll();ul();yl();vl();Sl();wl();Tl();xl();Cl();Al();Dl();Ml();Nl();ku()});var er,Du=$(()=>{"use strict";er=class{constructor(e,t,n,s,r,o){this.userId=e;this.sessionId=t;this.toolCallId=n;this.runningProcesses=s;this.activeWebViewURLs=r;this.workingDirectory=o}workingDirectory}});var Mu=$(()=>{"use strict"});import Ye from"fs";import rn from"path";import Yf from"os";var Qf,ua,Ot,Ru=$(()=>{"use strict";z();Qf=/[/\\:*?"<>|]/g,ua=class i{static instance;skillsPath;constructor(){this.skillsPath=rn.join(Yf.homedir(),".orion","skills")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.skillsPath}ensureFolder(){try{return Ye.existsSync(this.skillsPath)||(Ye.mkdirSync(this.skillsPath,{recursive:!0}),u.debug(`[Skills] Created skills folder: ${this.skillsPath}`)),!0}catch(e){return u.error(`[Skills] Failed to create skills folder: ${e.message}`),!1}}validateFilename(e){if(!e||typeof e!="string")return{valid:!1,error:"Skill name is required"};let t=e.trim();return t===""?{valid:!1,error:"Skill name cannot be empty"}:Qf.test(t)?{valid:!1,error:"Skill name contains invalid characters"}:rn.join(this.skillsPath,`${t}.md`).startsWith(this.skillsPath)?{valid:!0}:{valid:!1,error:"Invalid skill name (path traversal detected)"}}scanFolder(){try{this.ensureFolder();let e=Ye.readdirSync(this.skillsPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=rn.join(this.skillsPath,n);try{if(!Ye.statSync(s).isFile())continue;let o=Ye.readFileSync(s,"utf-8"),a=n.replace(/\.md$/,"");t.push({id:a,name:a,content:o})}catch(r){u.warn(`[Skills] Failed to read skill file ${n}: ${r.message}`)}}return u.debug(`[Skills] Scanned folder, found ${t.length} skills`),t}catch(e){return u.error(`[Skills] Failed to scan skills folder: ${e.message}`),[]}}createFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=e.trim(),r=rn.join(this.skillsPath,`${s}.md`);try{return this.ensureFolder(),Ye.existsSync(r)?{success:!1,error:"A skill with this name already exists"}:(Ye.writeFileSync(r,t,"utf-8"),u.debug(`[Skills] Created skill file: ${s}`),{success:!0,id:s})}catch(o){return u.error(`[Skills] Failed to create skill file: ${o.message}`),{success:!1,error:o.message}}}updateFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=rn.join(this.skillsPath,`${e}.md`);try{return Ye.existsSync(s)?(Ye.writeFileSync(s,t,"utf-8"),u.debug(`[Skills] Updated skill file: ${e}`),{success:!0}):{success:!1,error:"Skill not found"}}catch(r){return u.error(`[Skills] Failed to update skill file: ${r.message}`),{success:!1,error:r.message}}}deleteFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=rn.join(this.skillsPath,`${e}.md`);try{return Ye.existsSync(n)?(Ye.unlinkSync(n),u.debug(`[Skills] Deleted skill file: ${e}`),{success:!0}):{success:!1,error:"Skill not found"}}catch(s){return u.error(`[Skills] Failed to delete skill file: ${s.message}`),{success:!1,error:s.message}}}readFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=rn.join(this.skillsPath,`${e}.md`);try{return Ye.existsSync(n)?{success:!0,content:Ye.readFileSync(n,"utf-8")}:{success:!1,error:"Skill not found"}}catch(s){return u.error(`[Skills] Failed to read skill file: ${s.message}`),{success:!1,error:s.message}}}exists(e){if(!this.validateFilename(e).valid)return!1;let n=rn.join(this.skillsPath,`${e}.md`);return Ye.existsSync(n)}},Ot=ua.getInstance()});var Jf,Zf,eb,tb,nb,sb,rb,da,Ou=$(()=>{"use strict";Jf=[{id:"wacli",name:"WhatsApp",emoji:"📱",description:"Send WhatsApp messages to other people or search/sync WhatsApp history via the wacli CLI.",tags:["whatsapp","messaging","wacli"],content:`# wacli
1206
1206
 
1207
1207
  Use \`wacli\` to message someone on WhatsApp or sync/search WhatsApp history.
1208
1208
 
@@ -1761,7 +1761,7 @@ Docs
1761
1761
  Notes
1762
1762
  - Set \`GOG_ACCOUNT=you@gmail.com\` to avoid repeating \`--account\`.
1763
1763
  - Confirm before sending mail or creating events.
1764
- `}],rb=[{id:"messaging",name:"Messaging",icon:"MessageCircle",description:"WhatsApp, iMessage, Slack, and social platforms",skills:Jf},{id:"productivity",name:"Productivity",icon:"CheckSquare",description:"Notion, Trello, Things, Reminders, Obsidian",skills:Zf},{id:"development",name:"Development",icon:"Code",description:"GitHub and developer tools",skills:eb},{id:"smart-home",name:"Smart Home",icon:"Home",description:"Philips Hue, Sonos, BluOS, Eight Sleep",skills:tb},{id:"media",name:"Media & Utilities",icon:"Music",description:"Spotify, GIFs, PDFs, audio visualization, macOS automation",skills:nb},{id:"google",name:"Google Workspace",icon:"Mail",description:"Gmail, Calendar, Drive, Sheets, Docs",skills:sb}],da=()=>rb.flatMap(i=>i.skills)});var $u={};Fe($u,{skillsStore:()=>Dn});import{EventEmitter as ob}from"events";var Nu,ha,ib,_u,ab,cb,ma,pa,Dn,fa=F(()=>{"use strict";Mu();Ru();Le();j();Ou();Nu="orion-skills-selected",ha="orion-installed-skill-templates",ib=()=>{try{let i=de.string(ha);if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}},_u=i=>{de.set(ha,JSON.stringify(i))},ab=i=>{let e="orion-skills-initialized";if(de.string(e)&&!de.string(ha)){let n=da(),s=i.map(o=>o.toLowerCase()),r=n.filter(o=>s.includes(o.name.toLowerCase())||s.includes(o.id.toLowerCase())).map(o=>o.id);_u(r),de.remove(e),u.debug(`[Skills] Migrated to version-based system. Found ${r.length} existing template skills.`)}},cb=async i=>{ab(i);let e=da(),t=ib(),n=i.map(a=>a.toLowerCase()),s=e.filter(a=>!t.includes(a.id));if(s.length===0)return!1;u.debug(`[Skills] Found ${s.length} new skill template(s) to install...`);let r=0,o=[];for(let a of s){if(n.includes(a.name.toLowerCase())||n.includes(a.id.toLowerCase())){u.debug(`[Skills] Skipping "${a.name}" - user already has this skill`),o.push(a.id);continue}try{Ot.createFile(a.name,a.content).success&&(u.debug(`[Skills] Installed new skill: ${a.name}`),o.push(a.id),r++)}catch(c){u.error(`[Skills] Failed to install skill ${a.name}: ${c.message}`)}}return _u([...t,...o]),u.info(`[Skills] Sync complete: installed ${r} new skill(s)`),r>0},ma=(i,e)=>{if(!e||e.trim()==="")return i;let t=e.split(`
1764
+ `}],rb=[{id:"messaging",name:"Messaging",icon:"MessageCircle",description:"WhatsApp, iMessage, Slack, and social platforms",skills:Jf},{id:"productivity",name:"Productivity",icon:"CheckSquare",description:"Notion, Trello, Things, Reminders, Obsidian",skills:Zf},{id:"development",name:"Development",icon:"Code",description:"GitHub and developer tools",skills:eb},{id:"smart-home",name:"Smart Home",icon:"Home",description:"Philips Hue, Sonos, BluOS, Eight Sleep",skills:tb},{id:"media",name:"Media & Utilities",icon:"Music",description:"Spotify, GIFs, PDFs, audio visualization, macOS automation",skills:nb},{id:"google",name:"Google Workspace",icon:"Mail",description:"Gmail, Calendar, Drive, Sheets, Docs",skills:sb}],da=()=>rb.flatMap(i=>i.skills)});var $u={};Le($u,{skillsStore:()=>Rn});import{EventEmitter as ob}from"events";var Nu,ha,ib,_u,ab,cb,ma,pa,Rn,fa=$(()=>{"use strict";Mu();Ru();Ue();z();Ou();Nu="orion-skills-selected",ha="orion-installed-skill-templates",ib=()=>{try{let i=de.string(ha);if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}},_u=i=>{de.set(ha,JSON.stringify(i))},ab=i=>{let e="orion-skills-initialized";if(de.string(e)&&!de.string(ha)){let n=da(),s=i.map(o=>o.toLowerCase()),r=n.filter(o=>s.includes(o.name.toLowerCase())||s.includes(o.id.toLowerCase())).map(o=>o.id);_u(r),de.remove(e),u.debug(`[Skills] Migrated to version-based system. Found ${r.length} existing template skills.`)}},cb=async i=>{ab(i);let e=da(),t=ib(),n=i.map(a=>a.toLowerCase()),s=e.filter(a=>!t.includes(a.id));if(s.length===0)return!1;u.debug(`[Skills] Found ${s.length} new skill template(s) to install...`);let r=0,o=[];for(let a of s){if(n.includes(a.name.toLowerCase())||n.includes(a.id.toLowerCase())){u.debug(`[Skills] Skipping "${a.name}" - user already has this skill`),o.push(a.id);continue}try{Ot.createFile(a.name,a.content).success&&(u.debug(`[Skills] Installed new skill: ${a.name}`),o.push(a.id),r++)}catch(c){u.error(`[Skills] Failed to install skill ${a.name}: ${c.message}`)}}return _u([...t,...o]),u.info(`[Skills] Sync complete: installed ${r} new skill(s)`),r>0},ma=(i,e)=>{if(!e||e.trim()==="")return i;let t=e.split(`
1765
1765
  `);for(let n of t){let s=n.trim();if(!s||s.startsWith("#")||s.startsWith("```"))continue;let r=s.substring(0,150);return r.length<s.length?r+"...":r}return i},pa=class i extends ob{static instance;state;constructor(){super(),this.state={skills:[],selectedSkillIds:this.loadSelectedIds(),isLoading:!1,isDeleting:null,isCreating:!1,isUpdating:null,lastSynced:null}}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadSelectedIds(){try{let e=de.string(Nu);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}saveSelectedIds(e){de.set(Nu,JSON.stringify(e))}getState(){return{...this.state}}async loadSkills(){this.state.isLoading=!0,this.emit("change",this.state);try{u.debug("[Skills] Loading skills from file system..."),Ot.ensureFolder();let e=Ot.scanFolder(),t=e.map(c=>c.name);await cb(t)&&(e=Ot.scanFolder());let s=new Date().toISOString(),r=e.map(c=>({id:c.id,name:c.name,description:ma(c.name,c.content),content:c.content,createdAt:s,updatedAt:s,isSelected:this.state.selectedSkillIds.includes(c.id)})),o=r.map(c=>c.id),a=this.state.selectedSkillIds.filter(c=>o.includes(c));this.state={...this.state,skills:r,selectedSkillIds:a,lastSynced:s,isLoading:!1},this.saveSelectedIds(a),this.emit("change",this.state),u.debug(`[Skills] Loaded ${r.length} skills from file system`)}catch(e){u.error(`[Skills] Failed to load skills: ${e.message}`),this.state.isLoading=!1,this.emit("change",this.state)}}async refreshSkills(){u.debug("[Skills] Refreshing skills..."),await this.loadSkills()}async toggleSkillSelection(e){if(!this.state.skills.find(r=>r.id===e))return;let n;if(this.state.selectedSkillIds.includes(e))n=this.state.selectedSkillIds.filter(r=>r!==e);else{if(this.state.selectedSkillIds.length>=3){u.warn(`[Skills] Cannot select more than ${3} skills`);return}n=[...this.state.selectedSkillIds,e]}let s=this.state.skills.map(r=>({...r,isSelected:n.includes(r.id)}));this.state={...this.state,skills:s,selectedSkillIds:n},this.saveSelectedIds(n),this.emit("change",this.state),u.debug(`[Skills] Selected skills: ${n.join(", ")||"none"}`)}async createSkill(e,t,n){if(!e||e.trim()==="")return{success:!1,error:"Skill name is required"};let s=e.trim(),r=t?.trim()||"";if(this.state.isCreating)return{success:!1,error:"Another operation in progress"};if(this.state.skills.some(o=>o.name.toLowerCase()===s.toLowerCase()))return{success:!1,error:"A skill with this name already exists"};this.state.isCreating=!0,this.emit("change",this.state);try{let o=Ot.createFile(s,r);if(!o.success)return this.state.isCreating=!1,this.emit("change",this.state),{success:!1,error:o.error};let a=new Date().toISOString(),c=s,l={id:c,name:s,description:n?.trim()||ma(s,r),content:r,createdAt:a,updatedAt:a,isSelected:!1};return this.state={...this.state,skills:[...this.state.skills,l],isCreating:!1,lastSynced:a},this.emit("change",this.state),u.debug(`[Skills] Created skill: ${s}`),{success:!0,id:c}}catch(o){return u.error(`[Skills] Failed to create skill: ${o.message}`),this.state.isCreating=!1,this.emit("change",this.state),{success:!1,error:o.message}}}async updateSkill(e,t,n,s){if(!e)return{success:!1,error:"Invalid skill ID"};if(this.state.isUpdating!==null)return{success:!1,error:"Another operation in progress"};let r=this.state.skills.find(c=>c.id===e);if(!r)return{success:!1,error:"Skill not found"};let o=t?.trim()||r.name,a=n?.trim()||r.content;this.state.isUpdating=e,this.emit("change",this.state);try{let c=new Date().toISOString();if(o!==r.name){Ot.deleteFile(e);let m=Ot.createFile(o,a);if(!m.success)return this.state.isUpdating=null,this.emit("change",this.state),{success:!1,error:m.error}}else{let m=Ot.updateFile(e,a);if(!m.success)return this.state.isUpdating=null,this.emit("change",this.state),{success:!1,error:m.error}}let l=o!==r.name?o:e,d=this.state.selectedSkillIds;l!==e&&this.state.selectedSkillIds.includes(e)&&(d=this.state.selectedSkillIds.map(m=>m===e?l:m));let g=this.state.skills.map(m=>m.id===e?{...m,id:l,name:o,description:s?.trim()||ma(o,a),content:a,updatedAt:c,isSelected:d.includes(l)}:m);return this.state={...this.state,skills:g,selectedSkillIds:d,isUpdating:null,lastSynced:c},this.saveSelectedIds(d),this.emit("change",this.state),u.debug(`[Skills] Updated skill: ${e}${l!==e?` -> ${l}`:""}`),{success:!0}}catch(c){return u.error(`[Skills] Failed to update skill: ${c.message}`),this.state.isUpdating=null,this.emit("change",this.state),{success:!1,error:c.message}}}async deleteSkill(e){if(!e)return{success:!1,error:"Invalid skill ID"};if(this.state.isDeleting!==null)return{success:!1,error:"Another delete in progress"};if(!this.state.skills.find(n=>n.id===e))return{success:!1,error:"Skill not found"};this.state.isDeleting=e,this.emit("change",this.state);try{let n=Ot.deleteFile(e);if(!n.success)return this.state.isDeleting=null,this.emit("change",this.state),{success:!1,error:n.error};let s=this.state.skills.filter(a=>a.id!==e),r=this.state.selectedSkillIds.includes(e),o=r?this.state.selectedSkillIds.filter(a=>a!==e):this.state.selectedSkillIds;return this.state={...this.state,skills:s,selectedSkillIds:o,isDeleting:null,lastSynced:new Date().toISOString()},this.saveSelectedIds(o),this.emit("change",this.state),u.debug(`[Skills] Deleted skill: ${e}${r?" (was selected)":""}`),{success:!0}}catch(n){return u.error(`[Skills] Failed to delete skill: ${n.message}`),this.state.isDeleting=null,this.emit("change",this.state),{success:!1,error:n.message}}}getSelectedSkills(){return this.state.skills.filter(e=>this.state.selectedSkillIds.includes(e.id))}getSelectedSkillsContent(){let e=this.getSelectedSkills();return e.length===0?"":e.map((t,n)=>`═══════════════════════════════════════════════════════════════
1766
1766
  SKILL ${n+1}: ${t.name.toUpperCase()}
1767
1767
  ═══════════════════════════════════════════════════════════════
@@ -1775,11 +1775,11 @@ ${e.map(n=>` <skill>
1775
1775
  <description>${n.description}</description>
1776
1776
  </skill>`).join(`
1777
1777
  `)}
1778
- </available_skills>`}getSkillsContentMap(){return Object.fromEntries(this.state.skills.map(e=>[e.id,e.content]))}getSkillContentById(e){return this.state.skills.find(n=>n.id===e)?.content??null}reset(){this.state={skills:[],selectedSkillIds:[],isLoading:!1,isDeleting:null,isCreating:!1,isUpdating:null,lastSynced:null},this.saveSelectedIds([]),this.emit("change",this.state),u.debug("[Skills] Reset store state (files preserved)")}},Dn=pa.getInstance()});var Uu={};Fe(Uu,{toolPermissionsStore:()=>Lu,useToolPermissionsStore:()=>Sa});import{EventEmitter as lb}from"events";import er from"fs";import Fu from"path";import ub from"os";function db(){try{if(!er.existsSync(Ao))return null;let i=er.readFileSync(Ao,"utf-8");return JSON.parse(i)}catch(i){return u.error(`[ToolPermissions] Failed to load permissions: ${i}`),null}}function gb(i){try{let e=Fu.dirname(Ao);er.existsSync(e)||er.mkdirSync(e,{recursive:!0}),er.writeFileSync(Ao,JSON.stringify(i,null,2)),u.debug("[ToolPermissions] Saved permissions to file")}catch(e){u.error(`[ToolPermissions] Failed to save permissions: ${e}`)}}var ba,ya,Ao,va,Lu,Sa,wa=F(()=>{"use strict";j();ba={Read:!0,Write:!0,Edit:!0,Glob:!0,Grep:!0,UploadFile:!0,Bash:!0,KillShell:!0,TakeScreenshot:!0,OpenUrl:!0,TodoWrite:!0,WebSearch:!0,WebFetch:!0},ya={ListCalls:!0,GetCallRecordings:!0,GetRecentMessages:!0,SendMessage:!0,ScheduleMessage:!0,GetContacts:!0,RunOperatorTask:!0,SearchMemory:!0,StoreMemory:!0,TelegramSend:!0,DiscordSend:!0},Ao=Fu.join(ub.homedir(),".orion","tool-permissions.json");va=class i extends lb{static instance;onDeviceTools;backendTools;lastSyncedAt=null;constructor(){super();let e=db();e?(this.onDeviceTools={...ba,...e.onDeviceTools},this.backendTools={...ya,...e.backendTools},this.lastSyncedAt=e.lastModified,u.debug("[ToolPermissions] Loaded permissions from file")):(this.onDeviceTools={...ba},this.backendTools={...ya},u.debug("[ToolPermissions] Using default permissions"))}static getInstance(){return i.instance||(i.instance=new i),i.instance}isToolEnabled(e){return e in this.onDeviceTools?this.onDeviceTools[e]??!0:e in this.backendTools?this.backendTools[e]??!0:!0}setToolPermission(e,t){e in this.onDeviceTools?this.onDeviceTools[e]=t:e in this.backendTools?this.backendTools[e]=t:this.onDeviceTools[e]=t,this.save(),this.emit("permission_changed",{toolName:e,enabled:t})}getEnabledTools(){let e=[];for(let[t,n]of Object.entries(this.onDeviceTools))n&&e.push(t);for(let[t,n]of Object.entries(this.backendTools))n&&e.push(t);return e}getDisabledTools(){let e=[];for(let[t,n]of Object.entries(this.onDeviceTools))n||e.push(t);for(let[t,n]of Object.entries(this.backendTools))n||e.push(t);return e}toggleAllTools(e){for(let t of Object.keys(this.onDeviceTools))this.onDeviceTools[t]=e;for(let t of Object.keys(this.backendTools))this.backendTools[t]=e;this.save(),this.emit("all_permissions_changed",{enabled:e})}resetToDefaults(){this.onDeviceTools={...ba},this.backendTools={...ya},this.save(),this.emit("permissions_reset")}save(){let e={onDeviceTools:this.onDeviceTools,backendTools:this.backendTools,lastModified:new Date().toISOString()};this.lastSyncedAt=e.lastModified,gb(e)}getState(){return this}},Lu=va.getInstance(),Sa={getState:()=>Lu}});var Wu={};Fe(Wu,{TelegramToolConnectionService:()=>Do,telegramToolConnectionService:()=>ns});import{ref as Bu,onChildAdded as mb,onChildChanged as pb,update as hb,off as fb}from"firebase/database";import{io as bb}from"socket.io-client";import{EventEmitter as yb}from"events";var Do,ns,Ta=F(()=>{"use strict";j();Rs();At();Te();Do=class i extends yb{static instance;database=null;unsubscribe=null;listenerRef=null;currentUserId=null;currentDeviceId=null;activeSessions=new Map;onToolExecutionCallback=null;processedRequestIds=new Map;MAX_PROCESSED_IDS=50;PROCESSED_ID_TTL_MS=300*1e3;SESSION_MAX_AGE_MS=1800*1e3;SESSION_CLEANUP_INTERVAL_MS=60*1e3;sessionCleanupInterval=null;firebaseAPI;constructor(){super(),this.firebaseAPI=Pt.getInstance(),this.setupLogoutListener(),u.debug("[TelegramToolConnection] Service initialized")}setupLogoutListener(){X.getInstance().on("SnowXSignOut",()=>{u.debug("[TelegramToolConnection] Sign out detected, stopping listeners"),this.stopListening(),this.disconnectAllSessions(),this.currentUserId=null,this.currentDeviceId=null,this.processedRequestIds.clear(),this.sessionCleanupInterval&&(clearInterval(this.sessionCleanupInterval),this.sessionCleanupInterval=null)})}static getInstance(){return i.instance||(i.instance=new i),i.instance}setFirebaseDatabase(e){this.database=e,u.debug("[TelegramToolConnection] Firebase database set")}setToolExecutionCallback(e){this.onToolExecutionCallback=e,u.debug("[TelegramToolConnection] Tool execution callback registered")}isCallbackRegistered(){return this.onToolExecutionCallback!==null}async startListening(e,t){let n=t||Pe.getInstance().getCurrentDeviceId();if(!n){u.error("[TelegramToolConnection] No device ID available - cannot start listening");return}if(!this.database){u.error("[TelegramToolConnection] Firebase database not set - cannot start listening");return}this.onToolExecutionCallback||(u.warn("[TelegramToolConnection] Callback not yet registered, waiting..."),await this.waitForCallbackRegistration(5e3,50)||u.error("[TelegramToolConnection] Cannot start listener - callback not registered after 5s")),this.currentUserId=e,this.currentDeviceId=n,u.info("[TelegramToolConnection] Starting listener"),u.debug(` User: ${e}`),u.debug(` Device: ${n}`),u.debug(` Callback registered: ${this.onToolExecutionCallback!==null}`),this.stopListening(),this.setupFirebaseListener(e,n)}async waitForCallbackRegistration(e=5e3,t=50){if(this.onToolExecutionCallback)return!0;let n=Date.now();for(;Date.now()-n<e;)if(await new Promise(s=>setTimeout(s,t)),this.onToolExecutionCallback)return u.debug(`[TelegramToolConnection] Callback registered after ${Date.now()-n}ms`),!0;return!1}stopListening(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.listenerRef&&(fb(this.listenerRef),this.listenerRef=null),u.debug("[TelegramToolConnection] Listeners stopped")}isListening(){return this.unsubscribe!==null}setupFirebaseListener(e,t){if(!this.database){u.error("[TelegramToolConnection] Database not available");return}let n=`users/${e}/devices/${t}/connections`;u.debug(`[TelegramToolConnection] Setting up Firebase listener at: ${n}`);let s=Bu(this.database,n);this.listenerRef=s;let r=(c,l)=>{if(!l)return;let d={...l,sessionId:l.sessionId||c};this.handleConnectionRequest(d)},o=mb(s,c=>{let l=c.key||"",d=c.val();u.debug(`[TelegramToolConnection] New connection request: ${l}`),r(l,d)},c=>{u.error(`[TelegramToolConnection] Firebase onChildAdded error: ${c.message}`)}),a=pb(s,c=>{let l=c.key||"",d=c.val();u.debug(`[TelegramToolConnection] Connection status changed: ${l}`),r(l,d)},c=>{u.error(`[TelegramToolConnection] Firebase onChildChanged error: ${c.message}`)});this.unsubscribe=()=>{o(),a()},u.info("[TelegramToolConnection] Firebase listener active")}async handleConnectionRequest(e){let{sessionId:t,status:n,conversationId:s,createdAt:r,source:o}=e,a=`${t}_${n}_${r}`;if(this.processedRequestIds.has(a))return;let c=Date.now()-r;if(c>6e4){u.debug(`[TelegramToolConnection] Ignoring stale request (age: ${c}ms)`);return}switch(u.debug(`[TelegramToolConnection] Received request - status: ${n}, session: ${t}, source: ${o||"unknown"}`),n){case"wake_up":this.processedRequestIds.set(a,Date.now()),this.cleanupProcessedIds(),await this.handleWakeUp(e);break;case"timed_out":u.warn("[TelegramToolConnection] Request timed out by backend"),this.activeSessions.has(t)&&await this.handleCompleted(t);break;case"completed":this.processedRequestIds.set(a,Date.now()),await this.handleCompleted(t);break;case"connecting":case"connected":break;case"error":u.error("[TelegramToolConnection] Error status received"),await this.handleCompleted(t);break}}cleanupProcessedIds(){let e=Date.now(),t=0;for(let[n,s]of this.processedRequestIds)e-s>this.PROCESSED_ID_TTL_MS&&(this.processedRequestIds.delete(n),t++);if(this.processedRequestIds.size>this.MAX_PROCESSED_IDS){let n=Array.from(this.processedRequestIds.entries()).sort((s,r)=>r[1]-s[1]).slice(0,25);this.processedRequestIds=new Map(n)}(t>0||this.processedRequestIds.size>25)&&u.debug(`[TelegramToolConnection] Cleaned up processed IDs (expired: ${t}, current: ${this.processedRequestIds.size})`)}async handleWakeUp(e){let{sessionId:t,conversationId:n,source:s="telegram"}=e;if(this.activeSessions.has(t)&&(this.activeSessions.get(t).socket.connected?(u.debug(`[TelegramToolConnection] Session ${t} already active, re-confirming connected status`),await this.updateStatus("connected",t),u.debug(`[TelegramToolConnection] Re-confirmed connected status for session: ${t}`)):(u.debug(`[TelegramToolConnection] Session ${t} socket disconnected, cleaning up and reconnecting`),this.activeSessions.delete(t)),this.activeSessions.has(t)))return;u.info(`[TelegramToolConnection] Wake-up received, connecting WebSocket for session: ${t}`),await this.updateStatus("connecting",t);let r=null;try{let{url:o,token:a}=await this.buildSocketIOURL();if(r=bb(o,{path:"/frontend-tools",query:{deviceId:this.currentDeviceId||"",sessionId:t,token:a},transports:["websocket","polling"],reconnection:!1,timeout:3e4,forceNew:!0}),this.setupSocketEventHandlers(r,t),this.activeSessions.set(t,{sessionId:t,socket:r,conversationId:n,source:s,createdAt:Date.now()}),this.ensureSessionCleanupRunning(),await this.waitForSocketConnection(r,3e4))await this.registerDevice(r),await this.updateStatus("connected",t),u.info(`[TelegramToolConnection] WebSocket connected for session: ${t}`);else throw new Error("WebSocket connection timeout")}catch(o){if(u.error(`[TelegramToolConnection] Failed to connect: ${o.message}`),r)try{r.removeAllListeners(),r.disconnect()}catch{}await this.updateStatus("error",t),this.activeSessions.delete(t)}}async handleCompleted(e){u.debug(`[TelegramToolConnection] Completion received, disconnecting session: ${e}`),this.disconnectSession(e)}disconnectSession(e){let t=this.activeSessions.get(e);if(t){try{t.socket.removeAllListeners(),t.socket.disconnect()}catch{}this.activeSessions.delete(e),u.debug(`[TelegramToolConnection] Session ${e} disconnected`),this.stopSessionCleanupIfEmpty()}}disconnectAllSessions(){for(let[e,t]of this.activeSessions)try{t.socket.removeAllListeners(),t.socket.disconnect()}catch{}this.activeSessions.clear(),this.stopSessionCleanupIfEmpty()}ensureSessionCleanupRunning(){this.sessionCleanupInterval||(this.sessionCleanupInterval=setInterval(()=>{this.cleanupExpiredSessions()},this.SESSION_CLEANUP_INTERVAL_MS))}stopSessionCleanupIfEmpty(){this.activeSessions.size===0&&this.sessionCleanupInterval&&(clearInterval(this.sessionCleanupInterval),this.sessionCleanupInterval=null)}cleanupExpiredSessions(){let e=Date.now();for(let[t,n]of this.activeSessions)e-n.createdAt>this.SESSION_MAX_AGE_MS&&(u.debug(`[TelegramToolConnection] Expiring stale session ${t}`),this.disconnectSession(t))}async buildSocketIOURL(){let e="ws.snowx.ai",t="";try{t=await X.getInstance().getFirebaseIdToken()||""}catch{u.warn("[TelegramToolConnection] Failed to get Firebase token")}return{url:`wss://${e}`,token:t}}setupSocketEventHandlers(e,t){e.on("connect",()=>{u.debug(`[TelegramToolConnection] Socket connected for session: ${t}`)}),e.on("disconnect",n=>{u.debug(`[TelegramToolConnection] Socket disconnected for session: ${t}, reason: ${n}`);let s=this.activeSessions.get(t),r=s?.conversationId,o=s?.source||"telegram";this.activeSessions.delete(t),r&&this.emit("external_session_ended",{source:o,conversationId:r,error:!0,timestamp:Date.now()})}),e.on("connect_error",n=>{u.error(`[TelegramToolConnection] Connection error for session: ${t}: ${n.message}`)}),e.on("connection_established",n=>{u.debug(`[TelegramToolConnection] Connection established for session: ${t}`)}),e.on("tool_execution_request",async n=>{let s=n?.data?.tool_name||"tool",o=this.activeSessions.get(t)?.source||"telegram";u.debug(`[TelegramToolConnection] Tool execution request: ${s} (session: ${t}, source: ${o})`),this.emit("remote_task_status",{status:"start",toolName:s,source:o,timestamp:Date.now()});try{await this.handleToolExecutionRequest(e,n,t)}finally{this.emit("remote_task_status",{status:"end",toolName:s,source:o,timestamp:Date.now()})}}),e.on("external_session_started",n=>{u.info(`[TelegramToolConnection] External session started - source: ${n.source}, session: ${t}`),this.emit("external_session_started",n)}),e.on("external_session_ended",n=>{u.info(`[TelegramToolConnection] External session ended - source: ${n.source}, session: ${t}`),this.emit("external_session_ended",n)})}waitForSocketConnection(e,t){return new Promise(n=>{let s=!1,r=()=>{s||(s=!0,e.off("connection_established",o),e.off("connect_error",a))},o=()=>{clearTimeout(c),r(),n(!0)},a=()=>{clearTimeout(c),r(),n(!1)},c=setTimeout(()=>{r(),n(!1)},t);e.once("connection_established",o),e.once("connect_error",a)})}async registerDevice(e){e.emit("device_registration",{deviceId:this.currentDeviceId,userId:this.currentUserId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url","browser_navigate","browser_click","browser_type"]}),u.debug("[TelegramToolConnection] Device registered")}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"macOS"}async handleToolExecutionRequest(e,t,n,s=0){let l={id:t.data?.id||"",name:t.data?.tool_name||"",arguments:t.data?.arguments||{},timestamp:t.metadata?.timestamp||new Date().toISOString()},d=t.metadata?.tool_call_id||l.id,g=Date.now(),p=this.activeSessions.get(n)?.source||"telegram";if(u.debug(`[TelegramToolConnection] Executing tool: ${l.name} (session: ${n}, source: ${p})`),!this.onToolExecutionCallback&&s<3)return u.warn(`[TelegramToolConnection] Callback not ready, retry ${s+1}/3`),await new Promise(f=>setTimeout(f,200)),this.handleToolExecutionRequest(e,t,n,s+1);let h=f=>{e.connected&&e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:[{type:"text",text:`Error: ${f}`}],success:!1,error:f})};try{let f,y=!0;this.onToolExecutionCallback?(f=await Promise.race([this.onToolExecutionCallback(l),new Promise((C,v)=>setTimeout(()=>v(new Error(`Tool execution timed out after ${3e5/1e3}s`)),3e5))]),!f||typeof f!="object"?(y=!1,f={error:"Invalid tool result"}):(f.success===!1||f.error)&&(y=!1)):(u.error("[TelegramToolConnection] No tool execution callback registered!"),f={error:"Tool execution not available"},y=!1);let T=this.formatResultAsContentBlocks(f);if(!e.connected){u.warn("[TelegramToolConnection] Socket disconnected before sending response");return}let x=JSON.stringify(T);if(x.length>1048576){u.warn(`[TelegramToolConnection] Result too large (${x.length} bytes), truncating...`);let C=T.map(v=>v.type==="text"&&v.text&&v.text.length>5e4?{...v,text:v.text.slice(0,5e4)+`
1778
+ </available_skills>`}getSkillsContentMap(){return Object.fromEntries(this.state.skills.map(e=>[e.id,e.content]))}getSkillContentById(e){return this.state.skills.find(n=>n.id===e)?.content??null}reset(){this.state={skills:[],selectedSkillIds:[],isLoading:!1,isDeleting:null,isCreating:!1,isUpdating:null,lastSynced:null},this.saveSelectedIds([]),this.emit("change",this.state),u.debug("[Skills] Reset store state (files preserved)")}},Rn=pa.getInstance()});var Uu={};Le(Uu,{toolPermissionsStore:()=>Lu,useToolPermissionsStore:()=>Sa});import{EventEmitter as lb}from"events";import tr from"fs";import Fu from"path";import ub from"os";function db(){try{if(!tr.existsSync(Ao))return null;let i=tr.readFileSync(Ao,"utf-8");return JSON.parse(i)}catch(i){return u.error(`[ToolPermissions] Failed to load permissions: ${i}`),null}}function gb(i){try{let e=Fu.dirname(Ao);tr.existsSync(e)||tr.mkdirSync(e,{recursive:!0}),tr.writeFileSync(Ao,JSON.stringify(i,null,2)),u.debug("[ToolPermissions] Saved permissions to file")}catch(e){u.error(`[ToolPermissions] Failed to save permissions: ${e}`)}}var ba,ya,Ao,va,Lu,Sa,wa=$(()=>{"use strict";z();ba={Read:!0,Write:!0,Edit:!0,Glob:!0,Grep:!0,UploadFile:!0,Bash:!0,KillShell:!0,TakeScreenshot:!0,OpenUrl:!0,TodoWrite:!0,WebSearch:!0,WebFetch:!0},ya={ListCalls:!0,GetCallRecordings:!0,GetRecentMessages:!0,SendMessage:!0,ScheduleMessage:!0,GetContacts:!0,RunOperatorTask:!0,SearchMemory:!0,StoreMemory:!0,TelegramSend:!0,DiscordSend:!0},Ao=Fu.join(ub.homedir(),".orion","tool-permissions.json");va=class i extends lb{static instance;onDeviceTools;backendTools;lastSyncedAt=null;constructor(){super();let e=db();e?(this.onDeviceTools={...ba,...e.onDeviceTools},this.backendTools={...ya,...e.backendTools},this.lastSyncedAt=e.lastModified,u.debug("[ToolPermissions] Loaded permissions from file")):(this.onDeviceTools={...ba},this.backendTools={...ya},u.debug("[ToolPermissions] Using default permissions"))}static getInstance(){return i.instance||(i.instance=new i),i.instance}isToolEnabled(e){return e in this.onDeviceTools?this.onDeviceTools[e]??!0:e in this.backendTools?this.backendTools[e]??!0:!0}setToolPermission(e,t){e in this.onDeviceTools?this.onDeviceTools[e]=t:e in this.backendTools?this.backendTools[e]=t:this.onDeviceTools[e]=t,this.save(),this.emit("permission_changed",{toolName:e,enabled:t})}getEnabledTools(){let e=[];for(let[t,n]of Object.entries(this.onDeviceTools))n&&e.push(t);for(let[t,n]of Object.entries(this.backendTools))n&&e.push(t);return e}getDisabledTools(){let e=[];for(let[t,n]of Object.entries(this.onDeviceTools))n||e.push(t);for(let[t,n]of Object.entries(this.backendTools))n||e.push(t);return e}toggleAllTools(e){for(let t of Object.keys(this.onDeviceTools))this.onDeviceTools[t]=e;for(let t of Object.keys(this.backendTools))this.backendTools[t]=e;this.save(),this.emit("all_permissions_changed",{enabled:e})}resetToDefaults(){this.onDeviceTools={...ba},this.backendTools={...ya},this.save(),this.emit("permissions_reset")}save(){let e={onDeviceTools:this.onDeviceTools,backendTools:this.backendTools,lastModified:new Date().toISOString()};this.lastSyncedAt=e.lastModified,gb(e)}getState(){return this}},Lu=va.getInstance(),Sa={getState:()=>Lu}});var Wu={};Le(Wu,{TelegramToolConnectionService:()=>Do,telegramToolConnectionService:()=>rs});import{ref as Bu,onChildAdded as mb,onChildChanged as pb,update as hb,off as fb}from"firebase/database";import{io as bb}from"socket.io-client";import{EventEmitter as yb}from"events";var Do,rs,Ta=$(()=>{"use strict";z();Os();At();xe();Do=class i extends yb{static instance;database=null;unsubscribe=null;listenerRef=null;currentUserId=null;currentDeviceId=null;activeSessions=new Map;onToolExecutionCallback=null;processedRequestIds=new Map;MAX_PROCESSED_IDS=50;PROCESSED_ID_TTL_MS=300*1e3;SESSION_MAX_AGE_MS=1800*1e3;SESSION_CLEANUP_INTERVAL_MS=60*1e3;sessionCleanupInterval=null;firebaseAPI;constructor(){super(),this.firebaseAPI=Pt.getInstance(),this.setupLogoutListener(),u.debug("[TelegramToolConnection] Service initialized")}setupLogoutListener(){X.getInstance().on("SnowXSignOut",()=>{u.debug("[TelegramToolConnection] Sign out detected, stopping listeners"),this.stopListening(),this.disconnectAllSessions(),this.currentUserId=null,this.currentDeviceId=null,this.processedRequestIds.clear(),this.sessionCleanupInterval&&(clearInterval(this.sessionCleanupInterval),this.sessionCleanupInterval=null)})}static getInstance(){return i.instance||(i.instance=new i),i.instance}setFirebaseDatabase(e){this.database=e,u.debug("[TelegramToolConnection] Firebase database set")}setToolExecutionCallback(e){this.onToolExecutionCallback=e,u.debug("[TelegramToolConnection] Tool execution callback registered")}isCallbackRegistered(){return this.onToolExecutionCallback!==null}async startListening(e,t){let n=t||Ae.getInstance().getCurrentDeviceId();if(!n){u.error("[TelegramToolConnection] No device ID available - cannot start listening");return}if(!this.database){u.error("[TelegramToolConnection] Firebase database not set - cannot start listening");return}this.onToolExecutionCallback||(u.warn("[TelegramToolConnection] Callback not yet registered, waiting..."),await this.waitForCallbackRegistration(5e3,50)||u.error("[TelegramToolConnection] Cannot start listener - callback not registered after 5s")),this.currentUserId=e,this.currentDeviceId=n,u.info("[TelegramToolConnection] Starting listener"),u.debug(` User: ${e}`),u.debug(` Device: ${n}`),u.debug(` Callback registered: ${this.onToolExecutionCallback!==null}`),this.stopListening(),this.setupFirebaseListener(e,n)}async waitForCallbackRegistration(e=5e3,t=50){if(this.onToolExecutionCallback)return!0;let n=Date.now();for(;Date.now()-n<e;)if(await new Promise(s=>setTimeout(s,t)),this.onToolExecutionCallback)return u.debug(`[TelegramToolConnection] Callback registered after ${Date.now()-n}ms`),!0;return!1}stopListening(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.listenerRef&&(fb(this.listenerRef),this.listenerRef=null),u.debug("[TelegramToolConnection] Listeners stopped")}isListening(){return this.unsubscribe!==null}setupFirebaseListener(e,t){if(!this.database){u.error("[TelegramToolConnection] Database not available");return}let n=`users/${e}/devices/${t}/connections`;u.debug(`[TelegramToolConnection] Setting up Firebase listener at: ${n}`);let s=Bu(this.database,n);this.listenerRef=s;let r=(c,l)=>{if(!l)return;let d={...l,sessionId:l.sessionId||c};this.handleConnectionRequest(d)},o=mb(s,c=>{let l=c.key||"",d=c.val();u.debug(`[TelegramToolConnection] New connection request: ${l}`),r(l,d)},c=>{u.error(`[TelegramToolConnection] Firebase onChildAdded error: ${c.message}`)}),a=pb(s,c=>{let l=c.key||"",d=c.val();u.debug(`[TelegramToolConnection] Connection status changed: ${l}`),r(l,d)},c=>{u.error(`[TelegramToolConnection] Firebase onChildChanged error: ${c.message}`)});this.unsubscribe=()=>{o(),a()},u.info("[TelegramToolConnection] Firebase listener active")}async handleConnectionRequest(e){let{sessionId:t,status:n,conversationId:s,createdAt:r,source:o}=e,a=`${t}_${n}_${r}`;if(this.processedRequestIds.has(a))return;let c=Date.now()-r;if(c>6e4){u.debug(`[TelegramToolConnection] Ignoring stale request (age: ${c}ms)`);return}switch(u.debug(`[TelegramToolConnection] Received request - status: ${n}, session: ${t}, source: ${o||"unknown"}`),n){case"wake_up":this.processedRequestIds.set(a,Date.now()),this.cleanupProcessedIds(),await this.handleWakeUp(e);break;case"timed_out":u.warn("[TelegramToolConnection] Request timed out by backend"),this.activeSessions.has(t)&&await this.handleCompleted(t);break;case"completed":this.processedRequestIds.set(a,Date.now()),await this.handleCompleted(t);break;case"connecting":case"connected":break;case"error":u.error("[TelegramToolConnection] Error status received"),await this.handleCompleted(t);break}}cleanupProcessedIds(){let e=Date.now(),t=0;for(let[n,s]of this.processedRequestIds)e-s>this.PROCESSED_ID_TTL_MS&&(this.processedRequestIds.delete(n),t++);if(this.processedRequestIds.size>this.MAX_PROCESSED_IDS){let n=Array.from(this.processedRequestIds.entries()).sort((s,r)=>r[1]-s[1]).slice(0,25);this.processedRequestIds=new Map(n)}(t>0||this.processedRequestIds.size>25)&&u.debug(`[TelegramToolConnection] Cleaned up processed IDs (expired: ${t}, current: ${this.processedRequestIds.size})`)}async handleWakeUp(e){let{sessionId:t,conversationId:n,source:s="telegram"}=e;if(this.activeSessions.has(t)&&(this.activeSessions.get(t).socket.connected?(u.debug(`[TelegramToolConnection] Session ${t} already active, re-confirming connected status`),await this.updateStatus("connected",t),u.debug(`[TelegramToolConnection] Re-confirmed connected status for session: ${t}`)):(u.debug(`[TelegramToolConnection] Session ${t} socket disconnected, cleaning up and reconnecting`),this.activeSessions.delete(t)),this.activeSessions.has(t)))return;u.info(`[TelegramToolConnection] Wake-up received, connecting WebSocket for session: ${t}`),await this.updateStatus("connecting",t);let r=null;try{let{url:o,token:a}=await this.buildSocketIOURL();if(r=bb(o,{path:"/frontend-tools",query:{deviceId:this.currentDeviceId||"",sessionId:t,token:a},transports:["websocket","polling"],reconnection:!1,timeout:3e4,forceNew:!0}),this.setupSocketEventHandlers(r,t),this.activeSessions.set(t,{sessionId:t,socket:r,conversationId:n,source:s,createdAt:Date.now()}),this.ensureSessionCleanupRunning(),await this.waitForSocketConnection(r,3e4))await this.registerDevice(r),await this.updateStatus("connected",t),u.info(`[TelegramToolConnection] WebSocket connected for session: ${t}`);else throw new Error("WebSocket connection timeout")}catch(o){if(u.error(`[TelegramToolConnection] Failed to connect: ${o.message}`),r)try{r.removeAllListeners(),r.disconnect()}catch{}await this.updateStatus("error",t),this.activeSessions.delete(t)}}async handleCompleted(e){u.debug(`[TelegramToolConnection] Completion received, disconnecting session: ${e}`),this.disconnectSession(e)}disconnectSession(e){let t=this.activeSessions.get(e);if(t){try{t.socket.removeAllListeners(),t.socket.disconnect()}catch{}this.activeSessions.delete(e),u.debug(`[TelegramToolConnection] Session ${e} disconnected`),this.stopSessionCleanupIfEmpty()}}disconnectAllSessions(){for(let[e,t]of this.activeSessions)try{t.socket.removeAllListeners(),t.socket.disconnect()}catch{}this.activeSessions.clear(),this.stopSessionCleanupIfEmpty()}ensureSessionCleanupRunning(){this.sessionCleanupInterval||(this.sessionCleanupInterval=setInterval(()=>{this.cleanupExpiredSessions()},this.SESSION_CLEANUP_INTERVAL_MS))}stopSessionCleanupIfEmpty(){this.activeSessions.size===0&&this.sessionCleanupInterval&&(clearInterval(this.sessionCleanupInterval),this.sessionCleanupInterval=null)}cleanupExpiredSessions(){let e=Date.now();for(let[t,n]of this.activeSessions)e-n.createdAt>this.SESSION_MAX_AGE_MS&&(u.debug(`[TelegramToolConnection] Expiring stale session ${t}`),this.disconnectSession(t))}async buildSocketIOURL(){let e="ws.snowx.ai",t="";try{t=await X.getInstance().getFirebaseIdToken()||""}catch{u.warn("[TelegramToolConnection] Failed to get Firebase token")}return{url:`wss://${e}`,token:t}}setupSocketEventHandlers(e,t){e.on("connect",()=>{u.debug(`[TelegramToolConnection] Socket connected for session: ${t}`)}),e.on("disconnect",n=>{u.debug(`[TelegramToolConnection] Socket disconnected for session: ${t}, reason: ${n}`);let s=this.activeSessions.get(t),r=s?.conversationId,o=s?.source||"telegram";this.activeSessions.delete(t),r&&this.emit("external_session_ended",{source:o,conversationId:r,error:!0,timestamp:Date.now()})}),e.on("connect_error",n=>{u.error(`[TelegramToolConnection] Connection error for session: ${t}: ${n.message}`)}),e.on("connection_established",n=>{u.debug(`[TelegramToolConnection] Connection established for session: ${t}`)}),e.on("tool_execution_request",async n=>{let s=n?.data?.tool_name||"tool",o=this.activeSessions.get(t)?.source||"telegram";u.debug(`[TelegramToolConnection] Tool execution request: ${s} (session: ${t}, source: ${o})`),this.emit("remote_task_status",{status:"start",toolName:s,source:o,timestamp:Date.now()});try{await this.handleToolExecutionRequest(e,n,t)}finally{this.emit("remote_task_status",{status:"end",toolName:s,source:o,timestamp:Date.now()})}}),e.on("external_session_started",n=>{u.info(`[TelegramToolConnection] External session started - source: ${n.source}, session: ${t}`),this.emit("external_session_started",n)}),e.on("external_session_ended",n=>{u.info(`[TelegramToolConnection] External session ended - source: ${n.source}, session: ${t}`),this.emit("external_session_ended",n)})}waitForSocketConnection(e,t){return new Promise(n=>{let s=!1,r=()=>{s||(s=!0,e.off("connection_established",o),e.off("connect_error",a))},o=()=>{clearTimeout(c),r(),n(!0)},a=()=>{clearTimeout(c),r(),n(!1)},c=setTimeout(()=>{r(),n(!1)},t);e.once("connection_established",o),e.once("connect_error",a)})}async registerDevice(e){e.emit("device_registration",{deviceId:this.currentDeviceId,userId:this.currentUserId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url","browser_navigate","browser_click","browser_type"]}),u.debug("[TelegramToolConnection] Device registered")}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"macOS"}async handleToolExecutionRequest(e,t,n,s=0){let l={id:t.data?.id||"",name:t.data?.tool_name||"",arguments:t.data?.arguments||{},timestamp:t.metadata?.timestamp||new Date().toISOString()},d=t.metadata?.tool_call_id||l.id,g=Date.now(),p=this.activeSessions.get(n)?.source||"telegram";if(u.debug(`[TelegramToolConnection] Executing tool: ${l.name} (session: ${n}, source: ${p})`),!this.onToolExecutionCallback&&s<3)return u.warn(`[TelegramToolConnection] Callback not ready, retry ${s+1}/3`),await new Promise(f=>setTimeout(f,200)),this.handleToolExecutionRequest(e,t,n,s+1);let h=f=>{e.connected&&e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:[{type:"text",text:`Error: ${f}`}],success:!1,error:f})};try{let f,y=!0;this.onToolExecutionCallback?(f=await Promise.race([this.onToolExecutionCallback(l),new Promise((E,v)=>setTimeout(()=>v(new Error(`Tool execution timed out after ${3e5/1e3}s`)),3e5))]),!f||typeof f!="object"?(y=!1,f={error:"Invalid tool result"}):(f.success===!1||f.error)&&(y=!1)):(u.error("[TelegramToolConnection] No tool execution callback registered!"),f={error:"Tool execution not available"},y=!1);let T=this.formatResultAsContentBlocks(f);if(!e.connected){u.warn("[TelegramToolConnection] Socket disconnected before sending response");return}let C=JSON.stringify(T);if(C.length>1048576){u.warn(`[TelegramToolConnection] Result too large (${C.length} bytes), truncating...`);let E=T.map(v=>v.type==="text"&&v.text&&v.text.length>5e4?{...v,text:v.text.slice(0,5e4)+`
1779
1779
 
1780
- ... [TRUNCATED - result too large]`}:v);e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:C,success:y,error:y?null:f?.error||"Tool execution failed"})}else e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:T,success:y,error:y?null:f?.error||"Tool execution failed"});let w=Date.now()-g;u.debug(`[TelegramToolConnection] Tool ${l.name} completed in ${w}ms`)}catch(f){let y=Date.now()-g;u.error(`[TelegramToolConnection] Tool ${l.name} failed after ${y}ms: ${f.message}`),h(f.message)}}formatResultAsContentBlocks(e){return e?Array.isArray(e)?e:e.content?Array.isArray(e.content)?e.content:[{type:"text",text:String(e.content)}]:e.output||e.text?[{type:"text",text:String(e.output||e.text)}]:e.error?[{type:"text",text:`Error: ${e.error}`}]:[{type:"text",text:JSON.stringify(e)}]:[{type:"text",text:"No result"}]}async updateStatus(e,t){if(!this.currentUserId||!this.currentDeviceId){u.warn("[TelegramToolConnection] Cannot update status - no user/device ID");return}if(!t){u.warn("[TelegramToolConnection] Cannot update status - no sessionId");return}let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/connections/${t}`,s={status:e,updatedAt:Date.now()};if(e==="connected"){s.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone;try{let{skillsStore:r}=await Promise.resolve().then(()=>(fa(),$u)),o=r.getSelectedSkillsContent();o&&(s.skills_instruction=o,u.debug(`[TelegramToolConnection] Including skills in Firebase, length: ${o.length}`))}catch(r){u.warn(`[TelegramToolConnection] Failed to load skills: ${r.message}`)}try{let{DeviceKnowledgeService:r}=await Promise.resolve().then(()=>(Xr(),Pl)),o=r.getInstance(),a=o.readDeviceKnowledge();if(a){let c=o.getKnowledgeFilePath();s.device_knowledge_instruction=`Current device knowledge (${c}): ${a}
1780
+ ... [TRUNCATED - result too large]`}:v);e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:E,success:y,error:y?null:f?.error||"Tool execution failed"})}else e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:T,success:y,error:y?null:f?.error||"Tool execution failed"});let w=Date.now()-g;u.debug(`[TelegramToolConnection] Tool ${l.name} completed in ${w}ms`)}catch(f){let y=Date.now()-g;u.error(`[TelegramToolConnection] Tool ${l.name} failed after ${y}ms: ${f.message}`),h(f.message)}}formatResultAsContentBlocks(e){return e?Array.isArray(e)?e:e.content?Array.isArray(e.content)?e.content:[{type:"text",text:String(e.content)}]:e.output||e.text?[{type:"text",text:String(e.output||e.text)}]:e.error?[{type:"text",text:`Error: ${e.error}`}]:[{type:"text",text:JSON.stringify(e)}]:[{type:"text",text:"No result"}]}async updateStatus(e,t){if(!this.currentUserId||!this.currentDeviceId){u.warn("[TelegramToolConnection] Cannot update status - no user/device ID");return}if(!t){u.warn("[TelegramToolConnection] Cannot update status - no sessionId");return}let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/connections/${t}`,s={status:e,updatedAt:Date.now()};if(e==="connected"){s.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone;try{let{skillsStore:r}=await Promise.resolve().then(()=>(fa(),$u)),o=r.getSelectedSkillsContent();o&&(s.skills_instruction=o,u.debug(`[TelegramToolConnection] Including skills in Firebase, length: ${o.length}`))}catch(r){u.warn(`[TelegramToolConnection] Failed to load skills: ${r.message}`)}try{let{DeviceKnowledgeService:r}=await Promise.resolve().then(()=>(Yr(),Pl)),o=r.getInstance(),a=o.readDeviceKnowledge();if(a){let c=o.getKnowledgeFilePath();s.device_knowledge_instruction=`Current device knowledge (${c}): ${a}
1781
1781
 
1782
- Remember to update memory about device if any new information is learned during conversation.`,u.debug(`[TelegramToolConnection] Including device knowledge in Firebase, length: ${a.length}`)}}catch(r){u.warn(`[TelegramToolConnection] Failed to load device knowledge: ${r.message}`)}try{let{toolPermissionsStore:r}=await Promise.resolve().then(()=>(wa(),Uu)),o=r.getDisabledTools();o.length>0&&(s.disabled_tools=o,u.debug(`[TelegramToolConnection] Including disabled tools in Firebase: ${o.join(", ")}`))}catch(r){u.warn(`[TelegramToolConnection] Failed to load disabled tools: ${r.message}`)}}try{await this.firebaseAPI.updateRealtimeData(n,s),u.debug(`[TelegramToolConnection] Status updated to '${e}' via API`)}catch(r){if(u.warn(`[TelegramToolConnection] API update failed: ${r.message}`),this.database)try{let o=Bu(this.database,n);await hb(o,s),u.debug(`[TelegramToolConnection] Status updated to '${e}' via SDK`)}catch(o){u.error(`[TelegramToolConnection] Failed to update status: ${o.message}`)}}}getActiveSessionCount(){return this.activeSessions.size}isSessionActive(e){return this.activeSessions.has(e)}destroy(){u.debug("[TelegramToolConnection] Destroying service"),this.sessionCleanupInterval&&(clearInterval(this.sessionCleanupInterval),this.sessionCleanupInterval=null),this.stopListening(),this.disconnectAllSessions(),this.currentUserId=null,this.currentDeviceId=null,this.processedRequestIds.clear(),this.onToolExecutionCallback=null}},ns=Do.getInstance()});var $i={};Fe($i,{FrontendWebSocketService:()=>be});import{EventEmitter as vb}from"events";import{io as Sb}from"socket.io-client";import Hu from"os";import Gu from"path";import Nt from"fs";import wb from"axios";var Lt,be,Jn=F(()=>{"use strict";j();At();Te();zn();Kn();Ei();el();Au();Du();Lt=Gu.join(Hu.homedir(),".orion","pending-tool-results.json"),be=class i extends vb{static instance;socket=null;_connectionState="disconnected";connectionError=null;isConversationActive=!1;serverHost;deviceId=null;userId=null;sessionId=null;deviceRegistrationService;authService;toolRegistry;runningProcesses=new Map;activeWebViewURLs=[];reconnectAttempts=0;heartbeatTimer=null;baseHeartbeatInterval=2e4;lastHeartbeat=null;lastPongReceived=new Date;connectionQuality="excellent";connectionMetrics={totalConnections:0,totalDisconnections:0,disconnectionReasons:{},qualityDegradations:0,proactiveRecoveries:0,successfulRecoveries:0,failedRecoveries:0,pingResponseTimes:[],lastMetricsReset:new Date};tokenRefreshTimer=null;TOKEN_REFRESH_INTERVAL=2700*1e3;consecutivePoorQualityChecks=0;keepaliveWatchdog=null;lastKeepaliveTime=null;baseKeepaliveTimeout=12e4;extendedKeepaliveTimeout=6e5;aggressiveHeartbeatTimer=null;baseAggressiveHeartbeatInterval=5e3;toolProgressTimer=null;baseToolProgressInterval=15e3;activeToolExecutions=new Set;lastHeartbeatSent=null;superAggressiveMode=!1;connectionHealthCheckTimer=null;POOR_QUALITY_THRESHOLD=2;CONNECTION_HEALTH_CHECK_INTERVAL=1e4;toolExecutionQueue=[];activeToolCount=0;MAX_CONCURRENT_TOOLS=5;MAX_QUEUED_TOOLS=50;pendingToolResults=[];MAX_PENDING_RESULTS=100;TOOL_RESULTS_HTTP_ENDPOINT="https://snowx.ai/api-beta/api/tool-results";capturedScreenshots=[];MAX_CAPTURED_SCREENSHOTS=10;pingLatencies=[];MAX_PING_SAMPLES=10;tokenCounter=new lt;wsConnectionStartTime=null;pendingDeleteConfirmations=new Map;DELETE_CONFIRMATION_TIMEOUT=5e4;_hasElectronFrontend=!1;onConnectionStateChangeCallbacks=new Set;connectionPromise=null;constructor(e="ws.snowx.ai",t,n="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=Pe.getInstance(),this.authService=X.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,n),this.toolRegistry=new kr,Pu(this.toolRegistry),u.debug(`[FRONTEND WS] Tool registry initialized with ${this.toolRegistry.getToolCount()} frontend tools`),this.setupTelegramToolExecutionCallback(),this.deviceId?u.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):u.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication"),process.on("beforeExit",()=>{u.debug("[FRONTEND WS] Process exiting - cleaning up resources"),this.forceCleanup()}),process.on("SIGINT",()=>{this.forceCleanup()}),process.on("SIGTERM",()=>{this.forceCleanup()})}static getInstance(){return i.instance||(i.instance=new i),i.instance}isConnected(){return this._connectionState==="connected"&&this.socket?.connected===!0}hasElectronFrontend(){return this._hasElectronFrontend}setElectronFrontendAvailable(e){this._hasElectronFrontend=e,u.debug(`[FRONTEND WS] Electron frontend availability set to: ${e}`)}isWebSocketConnected(){return this.isConnected()}getConnectionState(){return this._connectionState}isConversationInProgress(){return this.isConversationActive&&this.isConnected()}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected(),isConnecting:this._connectionState==="connecting",error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}get currentDeviceId(){return this.deviceId}onConnectionStateChange(e){return this.onConnectionStateChangeCallbacks.add(e),e(this._connectionState),()=>{this.onConnectionStateChangeCallbacks.delete(e)}}notifyConnectionStateChange(){for(let e of this.onConnectionStateChangeCallbacks)e(this._connectionState);this.emit("connectionStateChange",this._connectionState)}generateUniqueDeviceId(e,t="node"){if(e){let n=this.deviceRegistrationService.getCurrentDeviceId();if(n)return n}return u.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}setupTelegramToolExecutionCallback(){Promise.resolve().then(()=>(Ta(),Wu)).then(({telegramToolConnectionService:e})=>{e.setToolExecutionCallback(async t=>{u.debug(`[FRONTEND WS/Telegram] Tool execution requested: ${t.name}`),u.debug(`[FRONTEND WS/Telegram] Request ID: ${t.id}`);try{let n=new Zs(this.userId||"",this.sessionId||"",t.id,this.runningProcesses,this.activeWebViewURLs),s=await this.toolRegistry.executeTool(t.name,t.id,t.arguments||{},n);return u.debug(`[FRONTEND WS/Telegram] Tool ${t.name} completed successfully`),{success:s.success,output:s.output,error:s.error}}catch(n){return u.error(`[FRONTEND WS/Telegram] Tool ${t.name} failed: ${n.message}`),{success:!1,error:n.message}}}),u.debug("[FRONTEND WS] TelegramToolConnectionService callback registered")}).catch(e=>{u.warn(`[FRONTEND WS] Failed to setup TelegramToolConnectionService: ${e.message}`)})}async connectForConversation(e,t){if(!t)return u.error("[FRONTEND WS] No sessionId provided! Connection will fail."),!1;if(u.debug("[FRONTEND WS] connectForConversation called"),u.debug(`[FRONTEND WS] New sessionId: ${t}`),u.debug(`[FRONTEND WS] Old sessionId: ${this.sessionId}`),u.debug(`[FRONTEND WS] isConnected(): ${this.isConnected()}`),this.sessionId&&this.sessionId!==t){let n=this.sessionId;this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0?(u.debug("[FRONTEND WS] Session ID changing but active work exists"),u.debug(`[FRONTEND WS] Active tools: ${this.activeToolExecutions.size}`),u.debug(`[FRONTEND WS] Queued tools: ${this.toolExecutionQueue.length}`),u.debug(`[FRONTEND WS] Pending results: ${this.pendingToolResults.length}`),this.scheduleOldSessionCleanup(n)):(u.debug("[FRONTEND WS] Session ID changed! Disconnecting old connection..."),this.disconnect("session_id_changed",!1))}if(this.sessionId=t,e&&e!==this.userId&&(this.userId=e),this.userId){let n=this.generateUniqueDeviceId(this.userId,"node");if(n&&this.deviceId!==n)u.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${n}`),this.deviceId=n;else if(!n)return u.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}return this.isConversationActive=!0,this.isConnected()?(u.debug("[FRONTEND WS] Already connected with same sessionId, reusing connection"),!0):(await this.connect(),await this.waitForConnection(3e4))}disconnectAfterConversation(){u.debug("[FRONTEND WS] Disconnecting after conversation (permanent)"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],u.debug("[FRONTEND WS] Cleared active WebView URLs"),this.capturedScreenshots=[],u.debug("[FRONTEND WS] Cleared captured screenshots"),(this.isConnected()||this.socket)&&this.disconnect("conversation_ended",!0)}handleConversationComplete(){u.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}async connect(){if(u.debug("[FRONTEND WS] connect() called"),this.socket?.connected){u.debug("[FRONTEND WS] Socket.IO already connected, skipping");return}this.socket&&(u.debug("[FRONTEND WS] Cleaning up old socket"),this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._connectionState="connecting",this.notifyConnectionStateChange(),u.debug("[FRONTEND WS] Creating Socket.IO connection...");try{let e="";try{e=await this.authService.getFirebaseIdToken()||""}catch(n){throw new Error(`Failed to get authentication token: ${n}`)}let t=`wss://${this.serverHost}`;u.debug(`[FRONTEND WS] Connecting to ${t}`),u.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),u.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),u.debug(`[FRONTEND WS] User ID: ${this.userId||"anonymous"}`),this.wsConnectionStartTime=new Date,this.socket=Sb(t,{path:"/frontend-tools",query:{deviceId:this.deviceId||"",sessionId:this.sessionId||"",token:e},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.1,timeout:45e3,autoConnect:!0,forceNew:!0}),this.setupSocketEventHandlers()}catch(e){u.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){u.debug(`[FRONTEND WS] DISCONNECT - Reason: ${e}, Permanent: ${t}`),this.connectionMetrics.totalDisconnections++,this.connectionMetrics.disconnectionReasons[e]=(this.connectionMetrics.disconnectionReasons[e]||0)+1,this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.stopTokenRefreshTimer(),this.stopConnectionHealthCheck(),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,u.debug("[FRONTEND WS] Socket.IO disconnected")),this.connectionError=null,this._connectionState="disconnected",this.notifyConnectionStateChange(),t&&(this.isConversationActive=!1,this.reconnectAttempts=0,this.pendingToolResults.length>0&&(u.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),u.debug("[FRONTEND WS] Connection state FULLY reset (permanent disconnect)")),this.emit("disconnected")}async waitForConnection(e){return this.isConnected()?!0:new Promise((t,n)=>{let s=setTimeout(()=>{this.connectionPromise=null,n(new Error("WebSocket connection timeout"))},e);this.connectionPromise={resolve:r=>{clearTimeout(s),this.connectionPromise=null,t(r)},reject:r=>{clearTimeout(s),this.connectionPromise=null,n(r)},timeoutId:s}})}resolveConnectionPromise(e){this.connectionPromise&&this.connectionPromise.resolve(e)}rejectConnectionPromise(e){this.connectionPromise&&this.connectionPromise.reject(e)}setupSocketEventHandlers(){this.socket&&(this.socket.on("connect",()=>{u.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{u.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{u.error(`[FRONTEND WS] Socket.IO connect_error: ${e.message}`),this.connectionError=e.message,this.rejectConnectionPromise(e)}),this.socket.io.on("reconnect_attempt",e=>{this.reconnectAttempts=e,u.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{u.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{u.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{u.error("[FRONTEND WS] All reconnection attempts failed"),this.connectionError="Connection failed after multiple attempts.",this._connectionState="disconnected",this.notifyConnectionStateChange()}),this.socket.on("connection_established",e=>{this.handleConnectionEstablished(e)}),this.socket.on("tool_execution_request",e=>{u.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{u.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{u.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{u.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("ping_request",e=>{u.debug(`[FRONTEND WS] Server ping_request received: ${e.reason||"heartbeat"}`),this.socket?.connected&&this.socket.emit("ping_response",{timestamp:Date.now(),originalTimestamp:e.timestamp,hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size,isWindowVisible:!0}),this.lastPongReceived=new Date,this.consecutivePoorQualityChecks=0,this.updateConnectionQuality()}),this.socket.on("connection_quality_warning",e=>{u.debug(`[FRONTEND WS] Connection quality warning: ${e.quality} - ${e.reason}`),this.connectionMetrics.qualityDegradations++,this.socket?.connected&&this.socket.emit("ping",{timestamp:new Date().toISOString(),reason:"quality_warning_response"}),e.quality==="critical"&&this.handleConnectionQualityDegradation()}),this.socket.on("ping_ack",e=>{u.debug(`[FRONTEND WS] Ping acknowledged: health=${e.connectionHealth}, latency=${e.latency}ms`),this.lastPongReceived=new Date,e.latency!==void 0&&(this.connectionMetrics.pingResponseTimes.length>=this.MAX_PING_SAMPLES&&this.connectionMetrics.pingResponseTimes.shift(),this.connectionMetrics.pingResponseTimes.push(e.latency)),this.updateConnectionQuality()}),this.socket.on("tool_execution_dropped",e=>{let t=e.executionId||e.toolId,n=e.toolName||"unknown",s=e.message||e.reason;u.debug(`[FRONTEND WS] Tool execution dropped: ${n} (${t}) - ${s}`),t&&this.activeToolExecutions.has(t)&&(this.activeToolExecutions.delete(t),this.activeToolCount=Math.max(0,this.activeToolCount-1),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat()),this.emit("tool_dropped",{executionId:t,toolId:t,toolName:n,reason:e.reason,message:s})}),this.socket.on("long_operation_start",e=>{u.debug("[FRONTEND WS] Backend requested long operation mode"),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat()}),this.socket.on("stop_signal",e=>{this.handleStopSignal(e)}),this.socket.on("stop_all_tools",e=>{u.debug("[FRONTEND WS] Stop all tools request received"),this.handleStopAllTools(e)}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{u.debug("[FRONTEND WS] Shell cleanup request received"),this.handleShellCleanup(e)}),this.socket.on("checkpoint_request",e=>{this.handleCheckpointRequest(e)}),this.socket.on("messages_saved",e=>{this.handleMessagesSaved(e)}),this.socket.on("auto_prompt",e=>{this.handleAutoPrompt(e)}),this.socket.on("reconnection_requested",e=>{u.debug(`[FRONTEND WS] Reconnection requested by server: ${e.reason||"unknown"}`),this.handleReconnectionRequest(e)}),this.socket.on("sub_agent_event",e=>{u.debug(`[FRONTEND WS] Sub-agent event received: ${e.type}`),this.handleSubAgentEvent(e)}),this.socket.on("external_session_started",e=>{u.debug(`[FRONTEND WS] External session started: ${e.source} - ${e.message}`),this.emit("external_session_started",e)}),this.socket.on("external_session_ended",e=>{u.debug(`[FRONTEND WS] External session ended: ${e.source}${e.error?" (with error)":""}`),this.emit("external_session_ended",e)}),this.socket.on("get_image_for_annotation",e=>{u.debug(`[FRONTEND WS] Image for annotation request received - ID: ${e.id}, Path: ${e.image_path}`),this.handleImageForAnnotationRequest(e)}),this.socket.on("delete_confirmation_response",e=>{this.handleDeleteConfirmationResponse(e)}),this.socket.on("error",e=>{console.error("[FRONTEND WS] Socket.IO error:",e)}))}handleConnect(){u.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.connectionMetrics.totalConnections++,this.startHeartbeat(),this.startKeepaliveWatchdog(),this.startConnectionHealthCheck(),this.startTokenRefreshTimer(),this.activeToolExecutions.size>0&&(u.debug(`[FRONTEND WS] Restarting aggressive heartbeat - ${this.activeToolExecutions.size} tools still active`),this.startAggressiveHeartbeat())}handleConnectionEstablished(e){if(this.wsConnectionStartTime){let t=Date.now()-this.wsConnectionStartTime.getTime();u.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else u.debug("[FRONTEND WS] Connection established!");this.registerDevice(),this._connectionState="connected",this.notifyConnectionStateChange(),this.isConversationActive=!0,this.loadPersistedToolResults(),this.flushPendingToolResultsWithFallback(),this.resolveConnectionPromise(!0),this.emit("connected")}handleDisconnect(e){u.debug(`[FRONTEND WS] Handling disconnect: ${e}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.rejectConnectionPromise(new Error(`WebSocket disconnected: ${e}`)),this.isConversationActive||u.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){u.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,n=t?.type||t?.stop_type||"all";switch(u.debug(`[FRONTEND WS] Stop type: ${n}`),n){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:u.debug(`[FRONTEND WS] Unknown stop type: ${n}`)}}handleStopAllTools(e){let t=e.session_id,n=e.reason||"backend_stop";if(u.debug(`[FRONTEND WS] Stopping all tools - Session: ${t}, Reason: ${n}`),t&&this.sessionId&&t!==this.sessionId){u.debug(`[FRONTEND WS] Ignoring stop_all_tools for different session (theirs: ${t}, ours: ${this.sessionId})`);return}this.stopAllActiveTools(n)}stopAllActiveTools(e){u.debug(`[FRONTEND WS] Stopping all active tools - Reason: ${e}`),u.debug(`[FRONTEND WS] - Active tools: ${this.activeToolExecutions.size}`),u.debug(`[FRONTEND WS] - Queued tools: ${this.toolExecutionQueue.length}`),u.debug(`[FRONTEND WS] - Pending results: ${this.pendingToolResults.length}`),this.toolExecutionQueue.length>0&&(u.debug(`[FRONTEND WS] Clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]),this.activeToolExecutions.size>0&&(u.debug(`[FRONTEND WS] Marking ${this.activeToolExecutions.size} active tools as cancelled`),this.activeToolExecutions.clear(),this.activeToolCount=0),this.pendingToolResults.length>0&&(u.debug(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending results`),this.pendingToolResults=[]),this.stopAggressiveHeartbeat(),this.terminateAllRunningProcesses(),u.debug(`[FRONTEND WS] All tools stopped for reason: ${e}`)}frameFeedbackForLLM(e,t,n){return`<user_feedback priority="high" requires_response="true">
1782
+ Remember to update memory about device if any new information is learned during conversation.`,u.debug(`[TelegramToolConnection] Including device knowledge in Firebase, length: ${a.length}`)}}catch(r){u.warn(`[TelegramToolConnection] Failed to load device knowledge: ${r.message}`)}try{let{toolPermissionsStore:r}=await Promise.resolve().then(()=>(wa(),Uu)),o=r.getDisabledTools();o.length>0&&(s.disabled_tools=o,u.debug(`[TelegramToolConnection] Including disabled tools in Firebase: ${o.join(", ")}`))}catch(r){u.warn(`[TelegramToolConnection] Failed to load disabled tools: ${r.message}`)}}try{await this.firebaseAPI.updateRealtimeData(n,s),u.debug(`[TelegramToolConnection] Status updated to '${e}' via API`)}catch(r){if(u.warn(`[TelegramToolConnection] API update failed: ${r.message}`),this.database)try{let o=Bu(this.database,n);await hb(o,s),u.debug(`[TelegramToolConnection] Status updated to '${e}' via SDK`)}catch(o){u.error(`[TelegramToolConnection] Failed to update status: ${o.message}`)}}}getActiveSessionCount(){return this.activeSessions.size}isSessionActive(e){return this.activeSessions.has(e)}destroy(){u.debug("[TelegramToolConnection] Destroying service"),this.sessionCleanupInterval&&(clearInterval(this.sessionCleanupInterval),this.sessionCleanupInterval=null),this.stopListening(),this.disconnectAllSessions(),this.currentUserId=null,this.currentDeviceId=null,this.processedRequestIds.clear(),this.onToolExecutionCallback=null}},rs=Do.getInstance()});var $i={};Le($i,{FrontendWebSocketService:()=>be});import{EventEmitter as vb}from"events";import{io as Sb}from"socket.io-client";import Hu from"os";import Gu from"path";import Nt from"fs";import wb from"axios";var Ut,be,es=$(()=>{"use strict";z();At();xe();Kn();Xn();Ei();el();Au();Du();Ut=Gu.join(Hu.homedir(),".orion","pending-tool-results.json"),be=class i extends vb{static instance;socket=null;_connectionState="disconnected";connectionError=null;isConversationActive=!1;serverHost;deviceId=null;userId=null;sessionId=null;deviceRegistrationService;authService;toolRegistry;runningProcesses=new Map;activeWebViewURLs=[];reconnectAttempts=0;heartbeatTimer=null;baseHeartbeatInterval=2e4;lastHeartbeat=null;lastPongReceived=new Date;connectionQuality="excellent";connectionMetrics={totalConnections:0,totalDisconnections:0,disconnectionReasons:{},qualityDegradations:0,proactiveRecoveries:0,successfulRecoveries:0,failedRecoveries:0,pingResponseTimes:[],lastMetricsReset:new Date};tokenRefreshTimer=null;TOKEN_REFRESH_INTERVAL=2700*1e3;consecutivePoorQualityChecks=0;keepaliveWatchdog=null;lastKeepaliveTime=null;baseKeepaliveTimeout=12e4;extendedKeepaliveTimeout=6e5;aggressiveHeartbeatTimer=null;baseAggressiveHeartbeatInterval=5e3;toolProgressTimer=null;baseToolProgressInterval=15e3;activeToolExecutions=new Set;lastHeartbeatSent=null;superAggressiveMode=!1;connectionHealthCheckTimer=null;POOR_QUALITY_THRESHOLD=2;CONNECTION_HEALTH_CHECK_INTERVAL=1e4;toolExecutionQueue=[];activeToolCount=0;MAX_CONCURRENT_TOOLS=5;MAX_QUEUED_TOOLS=50;pendingToolResults=[];MAX_PENDING_RESULTS=100;TOOL_RESULTS_HTTP_ENDPOINT="https://snowx.ai/api-beta/api/tool-results";capturedScreenshots=[];MAX_CAPTURED_SCREENSHOTS=10;pingLatencies=[];MAX_PING_SAMPLES=10;tokenCounter=new lt;wsConnectionStartTime=null;pendingDeleteConfirmations=new Map;DELETE_CONFIRMATION_TIMEOUT=5e4;_hasElectronFrontend=!1;onConnectionStateChangeCallbacks=new Set;connectionPromise=null;constructor(e="ws.snowx.ai",t,n="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=Ae.getInstance(),this.authService=X.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,n),this.toolRegistry=new Pr,Pu(this.toolRegistry),u.debug(`[FRONTEND WS] Tool registry initialized with ${this.toolRegistry.getToolCount()} frontend tools`),this.setupTelegramToolExecutionCallback(),this.deviceId?u.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):u.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication"),process.on("beforeExit",()=>{u.debug("[FRONTEND WS] Process exiting - cleaning up resources"),this.forceCleanup()}),process.on("SIGINT",()=>{this.forceCleanup()}),process.on("SIGTERM",()=>{this.forceCleanup()})}static getInstance(){return i.instance||(i.instance=new i),i.instance}isConnected(){return this._connectionState==="connected"&&this.socket?.connected===!0}hasElectronFrontend(){return this._hasElectronFrontend}setElectronFrontendAvailable(e){this._hasElectronFrontend=e,u.debug(`[FRONTEND WS] Electron frontend availability set to: ${e}`)}isWebSocketConnected(){return this.isConnected()}getConnectionState(){return this._connectionState}isConversationInProgress(){return this.isConversationActive&&this.isConnected()}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected(),isConnecting:this._connectionState==="connecting",error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}get currentDeviceId(){return this.deviceId}onConnectionStateChange(e){return this.onConnectionStateChangeCallbacks.add(e),e(this._connectionState),()=>{this.onConnectionStateChangeCallbacks.delete(e)}}notifyConnectionStateChange(){for(let e of this.onConnectionStateChangeCallbacks)e(this._connectionState);this.emit("connectionStateChange",this._connectionState)}generateUniqueDeviceId(e,t="node"){if(e){let n=this.deviceRegistrationService.getCurrentDeviceId();if(n)return n}return u.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}setupTelegramToolExecutionCallback(){Promise.resolve().then(()=>(Ta(),Wu)).then(({telegramToolConnectionService:e})=>{e.setToolExecutionCallback(async t=>{u.debug(`[FRONTEND WS/Telegram] Tool execution requested: ${t.name}`),u.debug(`[FRONTEND WS/Telegram] Request ID: ${t.id}`);try{let n=new er(this.userId||"",this.sessionId||"",t.id,this.runningProcesses,this.activeWebViewURLs),s=await this.toolRegistry.executeTool(t.name,t.id,t.arguments||{},n);return u.debug(`[FRONTEND WS/Telegram] Tool ${t.name} completed successfully`),{success:s.success,output:s.output,error:s.error}}catch(n){return u.error(`[FRONTEND WS/Telegram] Tool ${t.name} failed: ${n.message}`),{success:!1,error:n.message}}}),u.debug("[FRONTEND WS] TelegramToolConnectionService callback registered")}).catch(e=>{u.warn(`[FRONTEND WS] Failed to setup TelegramToolConnectionService: ${e.message}`)})}async connectForConversation(e,t){if(!t)return u.error("[FRONTEND WS] No sessionId provided! Connection will fail."),!1;if(u.debug("[FRONTEND WS] connectForConversation called"),u.debug(`[FRONTEND WS] New sessionId: ${t}`),u.debug(`[FRONTEND WS] Old sessionId: ${this.sessionId}`),u.debug(`[FRONTEND WS] isConnected(): ${this.isConnected()}`),this.sessionId&&this.sessionId!==t){let n=this.sessionId;this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0?(u.debug("[FRONTEND WS] Session ID changing but active work exists"),u.debug(`[FRONTEND WS] Active tools: ${this.activeToolExecutions.size}`),u.debug(`[FRONTEND WS] Queued tools: ${this.toolExecutionQueue.length}`),u.debug(`[FRONTEND WS] Pending results: ${this.pendingToolResults.length}`),this.scheduleOldSessionCleanup(n)):(u.debug("[FRONTEND WS] Session ID changed! Disconnecting old connection..."),this.disconnect("session_id_changed",!1))}if(this.sessionId=t,e&&e!==this.userId&&(this.userId=e),this.userId){let n=this.generateUniqueDeviceId(this.userId,"node");if(n&&this.deviceId!==n)u.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${n}`),this.deviceId=n;else if(!n)return u.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}return this.isConversationActive=!0,this.isConnected()?(u.debug("[FRONTEND WS] Already connected with same sessionId, reusing connection"),!0):(await this.connect(),await this.waitForConnection(3e4))}disconnectAfterConversation(){u.debug("[FRONTEND WS] Disconnecting after conversation (permanent)"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],u.debug("[FRONTEND WS] Cleared active WebView URLs"),this.capturedScreenshots=[],u.debug("[FRONTEND WS] Cleared captured screenshots"),(this.isConnected()||this.socket)&&this.disconnect("conversation_ended",!0)}handleConversationComplete(){u.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}async connect(){if(u.debug("[FRONTEND WS] connect() called"),this.socket?.connected){u.debug("[FRONTEND WS] Socket.IO already connected, skipping");return}this.socket&&(u.debug("[FRONTEND WS] Cleaning up old socket"),this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._connectionState="connecting",this.notifyConnectionStateChange(),u.debug("[FRONTEND WS] Creating Socket.IO connection...");try{let e="";try{e=await this.authService.getFirebaseIdToken()||""}catch(n){throw new Error(`Failed to get authentication token: ${n}`)}let t=`wss://${this.serverHost}`;u.debug(`[FRONTEND WS] Connecting to ${t}`),u.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),u.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),u.debug(`[FRONTEND WS] User ID: ${this.userId||"anonymous"}`),this.wsConnectionStartTime=new Date,this.socket=Sb(t,{path:"/frontend-tools",query:{deviceId:this.deviceId||"",sessionId:this.sessionId||"",token:e},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.1,timeout:45e3,autoConnect:!0,forceNew:!0}),this.setupSocketEventHandlers()}catch(e){u.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){u.debug(`[FRONTEND WS] DISCONNECT - Reason: ${e}, Permanent: ${t}`),this.connectionMetrics.totalDisconnections++,this.connectionMetrics.disconnectionReasons[e]=(this.connectionMetrics.disconnectionReasons[e]||0)+1,this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.stopTokenRefreshTimer(),this.stopConnectionHealthCheck(),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,u.debug("[FRONTEND WS] Socket.IO disconnected")),this.connectionError=null,this._connectionState="disconnected",this.notifyConnectionStateChange(),t&&(this.isConversationActive=!1,this.reconnectAttempts=0,this.pendingToolResults.length>0&&(u.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),u.debug("[FRONTEND WS] Connection state FULLY reset (permanent disconnect)")),this.emit("disconnected")}async waitForConnection(e){return this.isConnected()?!0:new Promise((t,n)=>{let s=setTimeout(()=>{this.connectionPromise=null,n(new Error("WebSocket connection timeout"))},e);this.connectionPromise={resolve:r=>{clearTimeout(s),this.connectionPromise=null,t(r)},reject:r=>{clearTimeout(s),this.connectionPromise=null,n(r)},timeoutId:s}})}resolveConnectionPromise(e){this.connectionPromise&&this.connectionPromise.resolve(e)}rejectConnectionPromise(e){this.connectionPromise&&this.connectionPromise.reject(e)}setupSocketEventHandlers(){this.socket&&(this.socket.on("connect",()=>{u.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{u.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{u.error(`[FRONTEND WS] Socket.IO connect_error: ${e.message}`),this.connectionError=e.message,this.rejectConnectionPromise(e)}),this.socket.io.on("reconnect_attempt",e=>{this.reconnectAttempts=e,u.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{u.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{u.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{u.error("[FRONTEND WS] All reconnection attempts failed"),this.connectionError="Connection failed after multiple attempts.",this._connectionState="disconnected",this.notifyConnectionStateChange()}),this.socket.on("connection_established",e=>{this.handleConnectionEstablished(e)}),this.socket.on("tool_execution_request",e=>{u.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{u.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{u.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{u.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("ping_request",e=>{u.debug(`[FRONTEND WS] Server ping_request received: ${e.reason||"heartbeat"}`),this.socket?.connected&&this.socket.emit("ping_response",{timestamp:Date.now(),originalTimestamp:e.timestamp,hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size,isWindowVisible:!0}),this.lastPongReceived=new Date,this.consecutivePoorQualityChecks=0,this.updateConnectionQuality()}),this.socket.on("connection_quality_warning",e=>{u.debug(`[FRONTEND WS] Connection quality warning: ${e.quality} - ${e.reason}`),this.connectionMetrics.qualityDegradations++,this.socket?.connected&&this.socket.emit("ping",{timestamp:new Date().toISOString(),reason:"quality_warning_response"}),e.quality==="critical"&&this.handleConnectionQualityDegradation()}),this.socket.on("ping_ack",e=>{u.debug(`[FRONTEND WS] Ping acknowledged: health=${e.connectionHealth}, latency=${e.latency}ms`),this.lastPongReceived=new Date,e.latency!==void 0&&(this.connectionMetrics.pingResponseTimes.length>=this.MAX_PING_SAMPLES&&this.connectionMetrics.pingResponseTimes.shift(),this.connectionMetrics.pingResponseTimes.push(e.latency)),this.updateConnectionQuality()}),this.socket.on("tool_execution_dropped",e=>{let t=e.executionId||e.toolId,n=e.toolName||"unknown",s=e.message||e.reason;u.debug(`[FRONTEND WS] Tool execution dropped: ${n} (${t}) - ${s}`),t&&this.activeToolExecutions.has(t)&&(this.activeToolExecutions.delete(t),this.activeToolCount=Math.max(0,this.activeToolCount-1),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat()),this.emit("tool_dropped",{executionId:t,toolId:t,toolName:n,reason:e.reason,message:s})}),this.socket.on("long_operation_start",e=>{u.debug("[FRONTEND WS] Backend requested long operation mode"),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat()}),this.socket.on("stop_signal",e=>{this.handleStopSignal(e)}),this.socket.on("stop_all_tools",e=>{u.debug("[FRONTEND WS] Stop all tools request received"),this.handleStopAllTools(e)}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{u.debug("[FRONTEND WS] Shell cleanup request received"),this.handleShellCleanup(e)}),this.socket.on("checkpoint_request",e=>{this.handleCheckpointRequest(e)}),this.socket.on("messages_saved",e=>{this.handleMessagesSaved(e)}),this.socket.on("auto_prompt",e=>{this.handleAutoPrompt(e)}),this.socket.on("reconnection_requested",e=>{u.debug(`[FRONTEND WS] Reconnection requested by server: ${e.reason||"unknown"}`),this.handleReconnectionRequest(e)}),this.socket.on("sub_agent_event",e=>{u.debug(`[FRONTEND WS] Sub-agent event received: ${e.type}`),this.handleSubAgentEvent(e)}),this.socket.on("external_session_started",e=>{u.debug(`[FRONTEND WS] External session started: ${e.source} - ${e.message}`),this.emit("external_session_started",e)}),this.socket.on("external_session_ended",e=>{u.debug(`[FRONTEND WS] External session ended: ${e.source}${e.error?" (with error)":""}`),this.emit("external_session_ended",e)}),this.socket.on("get_image_for_annotation",e=>{u.debug(`[FRONTEND WS] Image for annotation request received - ID: ${e.id}, Path: ${e.image_path}`),this.handleImageForAnnotationRequest(e)}),this.socket.on("delete_confirmation_response",e=>{this.handleDeleteConfirmationResponse(e)}),this.socket.on("error",e=>{console.error("[FRONTEND WS] Socket.IO error:",e)}))}handleConnect(){u.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.connectionMetrics.totalConnections++,this.startHeartbeat(),this.startKeepaliveWatchdog(),this.startConnectionHealthCheck(),this.startTokenRefreshTimer(),this.activeToolExecutions.size>0&&(u.debug(`[FRONTEND WS] Restarting aggressive heartbeat - ${this.activeToolExecutions.size} tools still active`),this.startAggressiveHeartbeat())}handleConnectionEstablished(e){if(this.wsConnectionStartTime){let t=Date.now()-this.wsConnectionStartTime.getTime();u.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else u.debug("[FRONTEND WS] Connection established!");this.registerDevice(),this._connectionState="connected",this.notifyConnectionStateChange(),this.isConversationActive=!0,this.loadPersistedToolResults(),this.flushPendingToolResultsWithFallback(),this.resolveConnectionPromise(!0),this.emit("connected")}handleDisconnect(e){u.debug(`[FRONTEND WS] Handling disconnect: ${e}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.rejectConnectionPromise(new Error(`WebSocket disconnected: ${e}`)),this.isConversationActive||u.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){u.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,n=t?.type||t?.stop_type||"all";switch(u.debug(`[FRONTEND WS] Stop type: ${n}`),n){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:u.debug(`[FRONTEND WS] Unknown stop type: ${n}`)}}handleStopAllTools(e){let t=e.session_id,n=e.reason||"backend_stop";if(u.debug(`[FRONTEND WS] Stopping all tools - Session: ${t}, Reason: ${n}`),t&&this.sessionId&&t!==this.sessionId){u.debug(`[FRONTEND WS] Ignoring stop_all_tools for different session (theirs: ${t}, ours: ${this.sessionId})`);return}this.stopAllActiveTools(n)}stopAllActiveTools(e){u.debug(`[FRONTEND WS] Stopping all active tools - Reason: ${e}`),u.debug(`[FRONTEND WS] - Active tools: ${this.activeToolExecutions.size}`),u.debug(`[FRONTEND WS] - Queued tools: ${this.toolExecutionQueue.length}`),u.debug(`[FRONTEND WS] - Pending results: ${this.pendingToolResults.length}`),this.toolExecutionQueue.length>0&&(u.debug(`[FRONTEND WS] Clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]),this.activeToolExecutions.size>0&&(u.debug(`[FRONTEND WS] Marking ${this.activeToolExecutions.size} active tools as cancelled`),this.activeToolExecutions.clear(),this.activeToolCount=0),this.pendingToolResults.length>0&&(u.debug(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending results`),this.pendingToolResults=[]),this.stopAggressiveHeartbeat(),this.terminateAllRunningProcesses(),u.debug(`[FRONTEND WS] All tools stopped for reason: ${e}`)}frameFeedbackForLLM(e,t,n){return`<user_feedback priority="high" requires_response="true">
1783
1783
  ${n>1?`[Mid-Task User Feedback ${t}/${n}]`:"[Mid-Task User Feedback]"}
1784
1784
  The user has provided the following feedback while you were working. This feedback was sent DURING your task execution and represents updated instructions or corrections from the user.
1785
1785
 
@@ -1793,16 +1793,16 @@ ${e}
1793
1793
  - If this feedback contradicts your current direction, STOP and address the user's concern first
1794
1794
  - Do NOT continue with your previous plan if it conflicts with this feedback
1795
1795
  </instructions>
1796
- </user_feedback>`}handleCheckpointRequest(e){u.debug("[FRONTEND WS] Handling checkpoint request");let t=e.data||e,n=t.checkpoint_id,s=t.session_id,r=t.iteration;if(!n||!s||r===void 0){u.warn("[FRONTEND WS] Invalid checkpoint request format");return}u.debug(`[FRONTEND WS] Checkpoint request - ID: ${n}, Session: ${s}, Iteration: ${r}`);let o=ct.getInstance(),a=o.getQueuedMessages(),c=a.map((d,g)=>({content:this.frameFeedbackForLLM(d.content,g+1,a.length),timestamp:Math.floor(d.timestamp.getTime()),imageUrls:d.imageUrls||[],is_mid_task_feedback:!0,requires_acknowledgment:!0})),l=c.length>0;u.debug(`[FRONTEND WS] Sending checkpoint response with ${c.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:n,session_id:s,has_feedback:l,feedback:c}),l&&(u.info(`Sent ${c.length} feedback message(s) to AI`),this.emit("feedback:sent",a),o.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,n=e.isNew;if(!t||n===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:n})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){u.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){u.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}u.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),u.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}async handleReconnectionRequest(e){let t=e.reason||"unknown",n=e.lastPingAge||0;if(u.debug(`[FRONTEND WS] Server requested reconnection - Reason: ${t}`),u.debug(`[FRONTEND WS] Connection was degraded (last ping: ${Math.round(n/1e3)}s ago)`),this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0){u.debug(`[FRONTEND WS] Deferring reconnection - ${this.activeToolExecutions.size} active, ${this.toolExecutionQueue.length} queued tools`),this.sendAggressiveHeartbeat();return}if(this.pendingToolResults.length>0){u.debug(`[FRONTEND WS] Deferring reconnection - ${this.pendingToolResults.length} pending results to send`),this.sendAggressiveHeartbeat();return}if(this.socket&&this.isConversationActive&&this.sessionId&&this.userId){u.debug("[FRONTEND WS] Initiating forced reconnection...");let s=this.sessionId,r=this.userId,o=this.deviceId;this.disconnect("reconnection_requested",!1),await new Promise(a=>setTimeout(a,500));try{await this.connectForConversation(r,s)?(u.debug("[FRONTEND WS] Reconnection successful!"),u.debug(`[FRONTEND WS] Composite key: ${o}_${s}`)):u.error("[FRONTEND WS] Reconnection failed")}catch(a){u.error(`[FRONTEND WS] Reconnection error: ${a}`)}}else u.debug("[FRONTEND WS] Cannot reconnect - missing session info or conversation not active")}handleSubAgentEvent(e){let t=e.sessionId;if(t&&this.sessionId&&t!==this.sessionId){u.debug(`[FRONTEND WS] Ignoring sub_agent_event for different session (theirs: ${t}, ours: ${this.sessionId})`);return}let{type:n,data:s}=e;u.debug(`[FRONTEND WS] Sub-agent event: ${n}`,s);try{Zc.handleEvent({type:n,...s}),u.debug("[FRONTEND WS] Sub-agent event forwarded to SubAgentManager")}catch(r){u.debug(`[FRONTEND WS] Failed to forward to SubAgentManager: ${r}`)}this.emit("subAgentEvent",{type:n,...s,timestamp:new Date().toISOString()})}async handleImageForAnnotationRequest(e){let{id:t,image_path:n,timeout:s=3e4}=e;u.debug(`[FRONTEND WS] Processing image for annotation: ${n}`);try{let r=await import("fs/promises"),o=await import("path");try{await r.access(n)}catch{u.error(`[FRONTEND WS] Image file not found: ${n}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Image file not found: ${n}`});return}let c=(await r.readFile(n)).toString("base64"),l=o.extname(n).toLowerCase(),d="image/png";l===".jpg"||l===".jpeg"?d="image/jpeg":l===".gif"?d="image/gif":l===".webp"&&(d="image/webp"),this.socket?.emit("image_for_annotation_response",{id:t,success:!0,image_data:`data:${d};base64,${c}`,mime_type:d,file_path:n}),u.debug(`[FRONTEND WS] Image sent for annotation: ${n}`)}catch(r){u.error(`[FRONTEND WS] Failed to read image for annotation: ${r.message}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Failed to read image: ${r.message}`})}}async handleToolExecutionRequest(e){let t=e.metadata?.session_id;if(t&&this.sessionId&&t!==this.sessionId){u.debug(`[FRONTEND WS] Ignoring tool_execution_request for different session (theirs: ${t}, ours: ${this.sessionId})`);return}let n={id:e.data?.id||"",name:e.data?.tool_name||"",arguments:e.data?.arguments||{},timestamp:e.metadata?.timestamp||new Date().toISOString()},s=e.metadata?.tool_call_id||n.id;this.toolExecutionQueue.length>=this.MAX_QUEUED_TOOLS&&(u.warn("[FRONTEND WS] Tool execution queue full, dropping oldest tool"),this.toolExecutionQueue.shift()),this.toolExecutionQueue.push(async()=>{await this.executeToolWithTracking(n,s)}),this.processNextTool()}processNextTool(){if(this.activeToolCount>=this.MAX_CONCURRENT_TOOLS){u.debug(`[FRONTEND WS] Max concurrent tools reached (${this.activeToolCount}/${this.MAX_CONCURRENT_TOOLS}), queuing...`);return}if(this.toolExecutionQueue.length===0)return;let e=this.toolExecutionQueue.shift();u.debug(`[FRONTEND WS] Starting tool (${this.activeToolCount+1}/${this.MAX_CONCURRENT_TOOLS} active)`),e()}async executeToolWithTracking(e,t){this.activeToolCount++;let n=Date.now();this.activeToolExecutions.add(e.id),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat(),u.debug("[FRONTEND WS] === EXECUTING TOOL ==="),u.debug(`[FRONTEND WS] Tool name: ${e.name}`),u.debug(`[FRONTEND WS] Tool ID: ${e.id}`),u.debug(`[FRONTEND WS] Tool call ID: ${t}`),u.debug("[FRONTEND WS] Tool arguments:",JSON.stringify(e.arguments).substring(0,200)),this.emit("toolExecuting",{toolCallId:e.id,name:e.name,arguments:e.arguments,startTime:new Date}),u.debug(`[FRONTEND WS] Emitted toolExecuting for ${e.name}`);let s=new Zs(this.userId,this.sessionId,t,this.runningProcesses,this.activeWebViewURLs);try{let r=await this.toolRegistry.executeTool(e.name,e.id,e.arguments,s);(e.name==="take_current_screenshot"||e.name==="TakeCurrentScreenshot"||e.name==="take_screenshot")&&r.success&&this.captureScreenshotFromResult(e.id,r.output),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.output,success:r.success,arguments:e.arguments});let o=typeof r=="string"?!0:r?.success??!0;await this.handleLargeResponse(e.id,t,e.name,r,o,e.arguments)}catch(r){u.error(`[FRONTEND WS] Tool execution failed: ${r.message}`),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.message,success:!1,error:r.message,arguments:e.arguments}),this.sendToolError(e.id,t,e.name,r)}finally{this.activeToolCount--,this.activeToolExecutions.delete(e.id),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat();let r=((Date.now()-n)/1e3).toFixed(2);u.debug(`[FRONTEND WS] Tool completed for ${e.id} (took ${r}s)`),this.processNextTool(),await this.captureFrontendToolResultForHistory(e.name,[],!0,void 0)}}sendMessage(e,t){if(!this.isConnected()){if(e==="tool_execution_response"){u.debug(`[FRONTEND WS] Not connected - trying HTTP fallback for tool result: ${t?.id}`),this.submitToolResultViaHttp(t).then(n=>{n||this.queuePendingToolResult(e,t)});return}u.warn("[FRONTEND WS] Not connected, cannot send message");return}try{if(e==="tool_execution_response"){let s=!1,r=setTimeout(()=>{s||(u.warn(`[FRONTEND WS] No acknowledgment for tool result ${t?.id} after 10000ms - trying HTTP fallback`),this.submitToolResultViaHttp(t).then(o=>{o||this.queuePendingToolResult(e,t)}))},1e4);this.socket?.emit(e,t,o=>{s=!0,clearTimeout(r),o?.received?u.debug(`[FRONTEND WS] ✅ Tool result ${t?.id} acknowledged by server`):(u.warn(`[FRONTEND WS] Tool result ${t?.id} - server did not acknowledge, trying HTTP fallback`),this.submitToolResultViaHttp(t).then(a=>{a||this.queuePendingToolResult(e,t)}))})}else this.socket?.emit(e,t)}catch(n){u.error(`[FRONTEND WS] Failed to send message: ${n}`),e==="tool_execution_response"&&(u.debug(`[FRONTEND WS] WebSocket emit failed - trying HTTP fallback for tool result: ${t?.id}`),this.submitToolResultViaHttp(t).then(s=>{s||this.queuePendingToolResult(e,t)}))}}queuePendingToolResult(e,t){this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&(u.warn("[FRONTEND WS] Pending results queue full, dropping oldest"),this.pendingToolResults.shift()),u.debug("[FRONTEND WS] Queuing tool result for later delivery"),this.pendingToolResults.push({type:e,data:t}),this.persistPendingToolResults()}async submitToolResultViaHttp(e){if(!this.sessionId||!this.deviceId)return u.warn("[FRONTEND WS] Cannot submit via HTTP - missing sessionId or deviceId"),!1;try{u.debug(`[FRONTEND WS] 📡 Attempting HTTP fallback for tool result: ${e?.id}`);let t=await this.authService.getFirebaseIdToken();if(!t)return u.error("[FRONTEND WS] Cannot submit via HTTP - no auth token"),!1;let n=await wb.post(this.TOOL_RESULTS_HTTP_ENDPOINT,{executionId:e.id,deviceId:this.deviceId,sessionId:this.sessionId,result:{id:e.id,success:e.success??!0,content:e.content||[],error:e.error||null}},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},timeout:15e3});return n.status===200?(u.debug(`[FRONTEND WS] ✅ HTTP fallback successful for tool result: ${e?.id}`),!0):(u.error(`[FRONTEND WS] HTTP fallback failed (${n.status}): ${n.data?.error}`),!1)}catch(t){return u.error(`[FRONTEND WS] HTTP fallback error: ${t.message}`),!1}}persistPendingToolResults(){if(this.pendingToolResults.length===0){try{Nt.existsSync(Lt)&&Nt.unlinkSync(Lt)}catch{}return}try{let e={sessionId:this.sessionId,deviceId:this.deviceId,results:this.pendingToolResults,timestamp:new Date().toISOString()},t=Gu.dirname(Lt);Nt.existsSync(t)||Nt.mkdirSync(t,{recursive:!0}),Nt.writeFileSync(Lt,JSON.stringify(e,null,2)),u.debug(`[FRONTEND WS] 💾 Persisted ${this.pendingToolResults.length} pending tool results to file`)}catch(e){u.error(`[FRONTEND WS] Failed to persist pending tool results: ${e}`)}}loadPersistedToolResults(){try{if(!Nt.existsSync(Lt))return;let e=Nt.readFileSync(Lt,"utf-8"),t=JSON.parse(e);if(t.sessionId===this.sessionId&&t.deviceId===this.deviceId){let n=t.results?.length||0;if(n>0){u.debug(`[FRONTEND WS] 📥 Restoring ${n} persisted tool results`);let s=new Set(this.pendingToolResults.map(r=>r.data?.id));for(let r of t.results)s.has(r.data?.id)||this.pendingToolResults.push(r)}}else u.debug("[FRONTEND WS] Clearing stale persisted tool results (different session)");Nt.unlinkSync(Lt)}catch(e){u.error(`[FRONTEND WS] Failed to load persisted tool results: ${e}`);try{Nt.existsSync(Lt)&&Nt.unlinkSync(Lt)}catch{}}}flushPendingToolResults(){if(this.pendingToolResults.length===0)return;u.debug(`[FRONTEND WS] Flushing ${this.pendingToolResults.length} queued tool results`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e)try{this.socket?.connected?(this.socket.emit(t.type,t.data),u.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(n){u.error(`[FRONTEND WS] Failed to send queued tool result: ${n}`),this.pendingToolResults.push(t)}this.persistPendingToolResults()}async flushPendingToolResultsWithFallback(){if(this.pendingToolResults.length===0)return;u.debug(`[FRONTEND WS] 🔄 Flushing ${this.pendingToolResults.length} pending tool results with HTTP fallback`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e){let n=!1;try{this.socket?.connected&&(this.socket.emit(t.type,t.data),u.debug(`[FRONTEND WS] ✅ Sent queued tool result via WebSocket: ${t.data?.id}`),n=!0)}catch(s){u.error(`[FRONTEND WS] Failed to send via WebSocket: ${s}`)}n||await this.submitToolResultViaHttp(t.data)&&(n=!0),n||(u.warn(`[FRONTEND WS] ⚠️ Both WebSocket and HTTP failed for result: ${t.data?.id}`),this.pendingToolResults.push(t))}this.persistPendingToolResults()}registerDevice(){if(!this.userId||!this.deviceId){console.warn("[FRONTEND WS] Cannot register device - missing userId or deviceId");return}let e=["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url"];this.socket?.emit("device_registration",{deviceId:this.deviceId,userId:this.userId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:e})}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"Unknown"}captureScreenshotFromResult(e,t){try{let n=JSON.parse(t);if(Array.isArray(n))for(let s of n)s.type==="image_url"&&s.image_url?.url&&(u.debug("[FRONTEND WS] 📸 Storing screenshot for assistant message attachment"),this.capturedScreenshots.push({toolCallId:e,base64Data:s.image_url.url}),this.capturedScreenshots.length>this.MAX_CAPTURED_SCREENSHOTS&&(u.debug(`[FRONTEND WS] 🧹 Dropping oldest screenshot (limit: ${this.MAX_CAPTURED_SCREENSHOTS})`),this.capturedScreenshots.shift()))}catch(n){u.warn(`[FRONTEND WS] ⚠️ Failed to parse screenshot tool output: ${n}`)}}getCapturedScreenshots(){return[...this.capturedScreenshots]}clearCapturedScreenshots(){this.capturedScreenshots=[]}async sendToolResult(e,t,n,s,r){let o;typeof s=="string"?o=s:s&&typeof s=="object"&&"output"in s?o=s.output||s.error||"":o=JSON.stringify(s);let a=this.createContentBlocks(o,r,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:a,success:!0,error:null})}sendToolError(e,t,n,s){let r=this.createContentBlocks(s.message,!1,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:r,success:!0,error:null})}createContentBlocks(e,t,n){let s=e.trim();s.length===0&&(t?s=`Command '${n}' executed successfully.
1796
+ </user_feedback>`}handleCheckpointRequest(e){u.debug("[FRONTEND WS] Handling checkpoint request");let t=e.data||e,n=t.checkpoint_id,s=t.session_id,r=t.iteration;if(!n||!s||r===void 0){u.warn("[FRONTEND WS] Invalid checkpoint request format");return}u.debug(`[FRONTEND WS] Checkpoint request - ID: ${n}, Session: ${s}, Iteration: ${r}`);let o=ct.getInstance(),a=o.getQueuedMessages(),c=a.map((d,g)=>({content:this.frameFeedbackForLLM(d.content,g+1,a.length),timestamp:Math.floor(d.timestamp.getTime()),imageUrls:d.imageUrls||[],is_mid_task_feedback:!0,requires_acknowledgment:!0})),l=c.length>0;u.debug(`[FRONTEND WS] Sending checkpoint response with ${c.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:n,session_id:s,has_feedback:l,feedback:c}),l&&(u.info(`Sent ${c.length} feedback message(s) to AI`),this.emit("feedback:sent",a),o.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,n=e.isNew;if(!t||n===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:n})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){u.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){u.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}u.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),u.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}async handleReconnectionRequest(e){let t=e.reason||"unknown",n=e.lastPingAge||0;if(u.debug(`[FRONTEND WS] Server requested reconnection - Reason: ${t}`),u.debug(`[FRONTEND WS] Connection was degraded (last ping: ${Math.round(n/1e3)}s ago)`),this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0){u.debug(`[FRONTEND WS] Deferring reconnection - ${this.activeToolExecutions.size} active, ${this.toolExecutionQueue.length} queued tools`),this.sendAggressiveHeartbeat();return}if(this.pendingToolResults.length>0){u.debug(`[FRONTEND WS] Deferring reconnection - ${this.pendingToolResults.length} pending results to send`),this.sendAggressiveHeartbeat();return}if(this.socket&&this.isConversationActive&&this.sessionId&&this.userId){u.debug("[FRONTEND WS] Initiating forced reconnection...");let s=this.sessionId,r=this.userId,o=this.deviceId;this.disconnect("reconnection_requested",!1),await new Promise(a=>setTimeout(a,500));try{await this.connectForConversation(r,s)?(u.debug("[FRONTEND WS] Reconnection successful!"),u.debug(`[FRONTEND WS] Composite key: ${o}_${s}`)):u.error("[FRONTEND WS] Reconnection failed")}catch(a){u.error(`[FRONTEND WS] Reconnection error: ${a}`)}}else u.debug("[FRONTEND WS] Cannot reconnect - missing session info or conversation not active")}handleSubAgentEvent(e){let t=e.sessionId;if(t&&this.sessionId&&t!==this.sessionId){u.debug(`[FRONTEND WS] Ignoring sub_agent_event for different session (theirs: ${t}, ours: ${this.sessionId})`);return}let{type:n,data:s}=e;u.debug(`[FRONTEND WS] Sub-agent event: ${n}`,s);try{Zc.handleEvent({type:n,...s}),u.debug("[FRONTEND WS] Sub-agent event forwarded to SubAgentManager")}catch(r){u.debug(`[FRONTEND WS] Failed to forward to SubAgentManager: ${r}`)}this.emit("subAgentEvent",{type:n,...s,timestamp:new Date().toISOString()})}async handleImageForAnnotationRequest(e){let{id:t,image_path:n,timeout:s=3e4}=e;u.debug(`[FRONTEND WS] Processing image for annotation: ${n}`);try{let r=await import("fs/promises"),o=await import("path");try{await r.access(n)}catch{u.error(`[FRONTEND WS] Image file not found: ${n}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Image file not found: ${n}`});return}let c=(await r.readFile(n)).toString("base64"),l=o.extname(n).toLowerCase(),d="image/png";l===".jpg"||l===".jpeg"?d="image/jpeg":l===".gif"?d="image/gif":l===".webp"&&(d="image/webp"),this.socket?.emit("image_for_annotation_response",{id:t,success:!0,image_data:`data:${d};base64,${c}`,mime_type:d,file_path:n}),u.debug(`[FRONTEND WS] Image sent for annotation: ${n}`)}catch(r){u.error(`[FRONTEND WS] Failed to read image for annotation: ${r.message}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Failed to read image: ${r.message}`})}}async handleToolExecutionRequest(e){let t=e.metadata?.session_id;if(t&&this.sessionId&&t!==this.sessionId){u.debug(`[FRONTEND WS] Ignoring tool_execution_request for different session (theirs: ${t}, ours: ${this.sessionId})`);return}let n={id:e.data?.id||"",name:e.data?.tool_name||"",arguments:e.data?.arguments||{},timestamp:e.metadata?.timestamp||new Date().toISOString()},s=e.metadata?.tool_call_id||n.id;this.toolExecutionQueue.length>=this.MAX_QUEUED_TOOLS&&(u.warn("[FRONTEND WS] Tool execution queue full, dropping oldest tool"),this.toolExecutionQueue.shift()),this.toolExecutionQueue.push(async()=>{await this.executeToolWithTracking(n,s)}),this.processNextTool()}processNextTool(){if(this.activeToolCount>=this.MAX_CONCURRENT_TOOLS){u.debug(`[FRONTEND WS] Max concurrent tools reached (${this.activeToolCount}/${this.MAX_CONCURRENT_TOOLS}), queuing...`);return}if(this.toolExecutionQueue.length===0)return;let e=this.toolExecutionQueue.shift();u.debug(`[FRONTEND WS] Starting tool (${this.activeToolCount+1}/${this.MAX_CONCURRENT_TOOLS} active)`),e()}async executeToolWithTracking(e,t){this.activeToolCount++;let n=Date.now();this.activeToolExecutions.add(e.id),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat(),u.debug("[FRONTEND WS] === EXECUTING TOOL ==="),u.debug(`[FRONTEND WS] Tool name: ${e.name}`),u.debug(`[FRONTEND WS] Tool ID: ${e.id}`),u.debug(`[FRONTEND WS] Tool call ID: ${t}`),u.debug("[FRONTEND WS] Tool arguments:",JSON.stringify(e.arguments).substring(0,200)),this.emit("toolExecuting",{toolCallId:e.id,name:e.name,arguments:e.arguments,startTime:new Date}),u.debug(`[FRONTEND WS] Emitted toolExecuting for ${e.name}`);let s=new er(this.userId,this.sessionId,t,this.runningProcesses,this.activeWebViewURLs);try{let r=await this.toolRegistry.executeTool(e.name,e.id,e.arguments,s);(e.name==="take_current_screenshot"||e.name==="TakeCurrentScreenshot"||e.name==="take_screenshot")&&r.success&&this.captureScreenshotFromResult(e.id,r.output),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.output,success:r.success,arguments:e.arguments});let o=typeof r=="string"?!0:r?.success??!0;await this.handleLargeResponse(e.id,t,e.name,r,o,e.arguments)}catch(r){u.error(`[FRONTEND WS] Tool execution failed: ${r.message}`),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.message,success:!1,error:r.message,arguments:e.arguments}),this.sendToolError(e.id,t,e.name,r)}finally{this.activeToolCount--,this.activeToolExecutions.delete(e.id),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat();let r=((Date.now()-n)/1e3).toFixed(2);u.debug(`[FRONTEND WS] Tool completed for ${e.id} (took ${r}s)`),this.processNextTool(),await this.captureFrontendToolResultForHistory(e.name,[],!0,void 0)}}sendMessage(e,t){if(!this.isConnected()){if(e==="tool_execution_response"){u.debug(`[FRONTEND WS] Not connected - trying HTTP fallback for tool result: ${t?.id}`),this.submitToolResultViaHttp(t).then(n=>{n||this.queuePendingToolResult(e,t)});return}u.warn("[FRONTEND WS] Not connected, cannot send message");return}try{if(e==="tool_execution_response"){let s=!1,r=setTimeout(()=>{s||(u.warn(`[FRONTEND WS] No acknowledgment for tool result ${t?.id} after 10000ms - trying HTTP fallback`),this.submitToolResultViaHttp(t).then(o=>{o||this.queuePendingToolResult(e,t)}))},1e4);this.socket?.emit(e,t,o=>{s=!0,clearTimeout(r),o?.received?u.debug(`[FRONTEND WS] ✅ Tool result ${t?.id} acknowledged by server`):(u.warn(`[FRONTEND WS] Tool result ${t?.id} - server did not acknowledge, trying HTTP fallback`),this.submitToolResultViaHttp(t).then(a=>{a||this.queuePendingToolResult(e,t)}))})}else this.socket?.emit(e,t)}catch(n){u.error(`[FRONTEND WS] Failed to send message: ${n}`),e==="tool_execution_response"&&(u.debug(`[FRONTEND WS] WebSocket emit failed - trying HTTP fallback for tool result: ${t?.id}`),this.submitToolResultViaHttp(t).then(s=>{s||this.queuePendingToolResult(e,t)}))}}queuePendingToolResult(e,t){this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&(u.warn("[FRONTEND WS] Pending results queue full, dropping oldest"),this.pendingToolResults.shift()),u.debug("[FRONTEND WS] Queuing tool result for later delivery"),this.pendingToolResults.push({type:e,data:t}),this.persistPendingToolResults()}async submitToolResultViaHttp(e){if(!this.sessionId||!this.deviceId)return u.warn("[FRONTEND WS] Cannot submit via HTTP - missing sessionId or deviceId"),!1;try{u.debug(`[FRONTEND WS] 📡 Attempting HTTP fallback for tool result: ${e?.id}`);let t=await this.authService.getFirebaseIdToken();if(!t)return u.error("[FRONTEND WS] Cannot submit via HTTP - no auth token"),!1;let n=await wb.post(this.TOOL_RESULTS_HTTP_ENDPOINT,{executionId:e.id,deviceId:this.deviceId,sessionId:this.sessionId,result:{id:e.id,success:e.success??!0,content:e.content||[],error:e.error||null}},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},timeout:15e3});return n.status===200?(u.debug(`[FRONTEND WS] ✅ HTTP fallback successful for tool result: ${e?.id}`),!0):(u.error(`[FRONTEND WS] HTTP fallback failed (${n.status}): ${n.data?.error}`),!1)}catch(t){return u.error(`[FRONTEND WS] HTTP fallback error: ${t.message}`),!1}}persistPendingToolResults(){if(this.pendingToolResults.length===0){try{Nt.existsSync(Ut)&&Nt.unlinkSync(Ut)}catch{}return}try{let e={sessionId:this.sessionId,deviceId:this.deviceId,results:this.pendingToolResults,timestamp:new Date().toISOString()},t=Gu.dirname(Ut);Nt.existsSync(t)||Nt.mkdirSync(t,{recursive:!0}),Nt.writeFileSync(Ut,JSON.stringify(e,null,2)),u.debug(`[FRONTEND WS] 💾 Persisted ${this.pendingToolResults.length} pending tool results to file`)}catch(e){u.error(`[FRONTEND WS] Failed to persist pending tool results: ${e}`)}}loadPersistedToolResults(){try{if(!Nt.existsSync(Ut))return;let e=Nt.readFileSync(Ut,"utf-8"),t=JSON.parse(e);if(t.sessionId===this.sessionId&&t.deviceId===this.deviceId){let n=t.results?.length||0;if(n>0){u.debug(`[FRONTEND WS] 📥 Restoring ${n} persisted tool results`);let s=new Set(this.pendingToolResults.map(r=>r.data?.id));for(let r of t.results)s.has(r.data?.id)||this.pendingToolResults.push(r)}}else u.debug("[FRONTEND WS] Clearing stale persisted tool results (different session)");Nt.unlinkSync(Ut)}catch(e){u.error(`[FRONTEND WS] Failed to load persisted tool results: ${e}`);try{Nt.existsSync(Ut)&&Nt.unlinkSync(Ut)}catch{}}}flushPendingToolResults(){if(this.pendingToolResults.length===0)return;u.debug(`[FRONTEND WS] Flushing ${this.pendingToolResults.length} queued tool results`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e)try{this.socket?.connected?(this.socket.emit(t.type,t.data),u.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(n){u.error(`[FRONTEND WS] Failed to send queued tool result: ${n}`),this.pendingToolResults.push(t)}this.persistPendingToolResults()}async flushPendingToolResultsWithFallback(){if(this.pendingToolResults.length===0)return;u.debug(`[FRONTEND WS] 🔄 Flushing ${this.pendingToolResults.length} pending tool results with HTTP fallback`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e){let n=!1;try{this.socket?.connected&&(this.socket.emit(t.type,t.data),u.debug(`[FRONTEND WS] ✅ Sent queued tool result via WebSocket: ${t.data?.id}`),n=!0)}catch(s){u.error(`[FRONTEND WS] Failed to send via WebSocket: ${s}`)}n||await this.submitToolResultViaHttp(t.data)&&(n=!0),n||(u.warn(`[FRONTEND WS] ⚠️ Both WebSocket and HTTP failed for result: ${t.data?.id}`),this.pendingToolResults.push(t))}this.persistPendingToolResults()}registerDevice(){if(!this.userId||!this.deviceId){console.warn("[FRONTEND WS] Cannot register device - missing userId or deviceId");return}let e=["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url"];this.socket?.emit("device_registration",{deviceId:this.deviceId,userId:this.userId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:e})}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"Unknown"}captureScreenshotFromResult(e,t){try{let n=JSON.parse(t);if(Array.isArray(n))for(let s of n)s.type==="image_url"&&s.image_url?.url&&(u.debug("[FRONTEND WS] 📸 Storing screenshot for assistant message attachment"),this.capturedScreenshots.push({toolCallId:e,base64Data:s.image_url.url}),this.capturedScreenshots.length>this.MAX_CAPTURED_SCREENSHOTS&&(u.debug(`[FRONTEND WS] 🧹 Dropping oldest screenshot (limit: ${this.MAX_CAPTURED_SCREENSHOTS})`),this.capturedScreenshots.shift()))}catch(n){u.warn(`[FRONTEND WS] ⚠️ Failed to parse screenshot tool output: ${n}`)}}getCapturedScreenshots(){return[...this.capturedScreenshots]}clearCapturedScreenshots(){this.capturedScreenshots=[]}async sendToolResult(e,t,n,s,r){let o;typeof s=="string"?o=s:s&&typeof s=="object"&&"output"in s?o=s.output||s.error||"":o=JSON.stringify(s);let a=this.createContentBlocks(o,r,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:a,success:!0,error:null})}sendToolError(e,t,n,s){let r=this.createContentBlocks(s.message,!1,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:r,success:!0,error:null})}createContentBlocks(e,t,n){let s=e.trim();s.length===0&&(t?s=`Command '${n}' executed successfully.
1797
1797
 
1798
1798
  No output was produced, which may be expected for this operation.`:s=`Command '${n}' failed but no error message was provided.`);try{let r=JSON.parse(s);if(Array.isArray(r)){let o=[];for(let a of r)a&&typeof a=="object"&&a.type&&(a.type==="text"&&typeof a.text=="string"?o.push({type:"text",text:a.text}):a.type==="image_url"&&a.image_url?.url&&o.push({type:"image_url",image_url:{url:String(a.image_url.url)}}));if(o.length>0)return o}}catch{}return[{type:"text",text:s}]}async handleLargeResponse(e,t,n,s,r,o){let a;if(typeof s=="string"?a=s:s&&typeof s=="object"&&"output"in s?a=s.output||s.error||"":a=JSON.stringify(s),n==="take_screenshot"||n==="take_current_screenshot"){await this.sendToolResult(e,t,n,s,r);return}if(["read","read_special_file","read_file","readspecialfile"].includes(n.toLowerCase())&&s?.metadata?.isImage===!0){u.debug(`[FRONTEND WS] Image file detected from ${n} tool, bypassing token limit`),await this.sendToolResult(e,t,n,s,r);return}if(this.tokenCounter.exceedsResponseLimit(a)){let l=this.tokenCounter.count(a);if(u.debug(`[FRONTEND WS] Response too large (${l} tokens), creating temp file`),n.toLowerCase()==="read"&&o?.file_path){let p=o.file_path,h=this.tokenCounter.formatLargeFileMessage(a,p);await this.sendToolResult(e,t,n,h,r);return}let g=await this.createTempFile(a,n);if(!g){u.error("[FRONTEND WS] Failed to create temp file, using truncated response"),await this.sendToolResult(e,t,n,this.tokenCounter.truncateOutput(a),r);return}let m=this.tokenCounter.formatLargeResponsePreview(a,g);await this.sendToolResult(e,t,n,m,r)}else await this.sendToolResult(e,t,n,a,r)}async createTempFile(e,t){try{let n=await import("fs/promises"),s=await import("path"),r=Math.floor(Date.now()/1e3),o=Math.random().toString(36).substring(2,10),a=`${t}_${r}_${o}.txt`,c=Hu.homedir(),l=s.join(c,".orion","tool_outputs");await n.mkdir(l,{recursive:!0});let d=s.join(l,a);return await n.writeFile(d,e,"utf-8"),u.debug(`[FRONTEND WS] Created temp file: ${d}`),d}catch(n){return u.error(`[FRONTEND WS] Failed to create temp file: ${n}`),null}}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeatPing()},this.baseHeartbeatInterval),u.debug(`[FRONTEND WS] Started heartbeat (${this.baseHeartbeatInterval/1e3}s interval)`)}sendHeartbeatPing(){this.socket?.connected&&(this.socket.emit("ping",{timestamp:new Date().toISOString()}),this.lastHeartbeat=new Date)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}startAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&clearInterval(this.aggressiveHeartbeatTimer);let e=this.superAggressiveMode?2e3:this.baseAggressiveHeartbeatInterval;this.aggressiveHeartbeatTimer=setInterval(()=>{this.sendAggressiveHeartbeat()},e);let t=this.superAggressiveMode?"SUPER-AGGRESSIVE":"aggressive";u.debug(`[FRONTEND WS] Started ${t} heartbeat (${e/1e3}s interval)`),this.startToolProgressReporting()}stopAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),this.superAggressiveMode=!1,u.debug("[FRONTEND WS] Stopped aggressive heartbeat"),this.stopToolProgressReporting()}enterSuperAggressiveMode(){this.superAggressiveMode||this.activeToolExecutions.size>0&&(u.debug("[FRONTEND WS] Entering SUPER-AGGRESSIVE heartbeat mode due to connection quality degradation"),this.superAggressiveMode=!0,this.startAggressiveHeartbeat())}sendAggressiveHeartbeat(){if(this.lastHeartbeatSent=new Date,this.socket?.connected){this.socket.emit("heartbeat",{timestamp:new Date().toISOString(),hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size,superAggressive:this.superAggressiveMode});let e=this.superAggressiveMode?"SUPER-":"";u.debug(`[FRONTEND WS] Sent ${e}aggressive heartbeat (${this.activeToolExecutions.size} active tools)`)}this.updateConnectionQuality()}updateConnectionQuality(){let e=(Date.now()-this.lastPongReceived.getTime())/1e3,t=this.connectionQuality;e<10?(this.connectionQuality="excellent",this.consecutivePoorQualityChecks=0):e<30?(this.connectionQuality="good",this.consecutivePoorQualityChecks=0):e<60?(this.connectionQuality="fair",this.consecutivePoorQualityChecks=0):e<90?(this.connectionQuality="poor",this.consecutivePoorQualityChecks++):(this.connectionQuality="critical",this.consecutivePoorQualityChecks++),t!==this.connectionQuality&&u.debug(`[FRONTEND WS] Connection quality: ${t} -> ${this.connectionQuality}`),this.consecutivePoorQualityChecks>=this.POOR_QUALITY_THRESHOLD&&(this.connectionQuality==="poor"||this.connectionQuality==="critical")&&this.handleConnectionQualityDegradation()}handleConnectionQualityDegradation(){if(u.debug(`[FRONTEND WS] Proactive recovery - quality: ${this.connectionQuality}, checks: ${this.consecutivePoorQualityChecks}`),this.connectionMetrics.proactiveRecoveries++,this.activeToolExecutions.size>0&&this.enterSuperAggressiveMode(),this.socket?.connected)for(let e=0;e<3;e++)setTimeout(()=>{this.socket?.connected&&this.socket.emit("heartbeat",{timestamp:new Date().toISOString(),hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size,reason:"quality_recovery"})},e*500);setTimeout(()=>{if(this.connectionQuality==="critical"&&this.isConversationActive){if(this.activeToolExecutions.size>0){u.debug("[FRONTEND WS] Deferring reconnect - active tools in progress"),this.connectionMetrics.failedRecoveries++;return}u.debug("[FRONTEND WS] Recovery failed - attempting soft reconnect"),this.attemptSoftReconnect()}else this.connectionMetrics.successfulRecoveries++},5e3)}async attemptSoftReconnect(){if(!this.sessionId||!this.userId){u.debug("[FRONTEND WS] Cannot soft reconnect - missing session info");return}let e=this.sessionId,t=this.userId;this.disconnect("soft_reconnect",!1),await new Promise(n=>setTimeout(n,1e3));try{await this.connectForConversation(t,e)?(u.debug("[FRONTEND WS] Soft reconnect successful"),this.connectionMetrics.successfulRecoveries++):(u.debug("[FRONTEND WS] Soft reconnect failed"),this.connectionMetrics.failedRecoveries++)}catch(n){u.error(`[FRONTEND WS] Soft reconnect error: ${n}`),this.connectionMetrics.failedRecoveries++}}startToolProgressReporting(){this.toolProgressTimer&&clearInterval(this.toolProgressTimer),this.toolProgressTimer=setInterval(()=>{this.sendToolProgress()},this.baseToolProgressInterval),u.debug(`[FRONTEND WS] Started tool progress reporting (${this.baseToolProgressInterval/1e3}s interval)`)}stopToolProgressReporting(){this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),u.debug("[FRONTEND WS] Stopped tool progress reporting")}sendToolProgress(){if(this.activeToolExecutions.size!==0&&this.socket?.connected){for(let e of this.activeToolExecutions)this.socket.emit("tool_progress",{toolId:e,status:"running",timestamp:new Date().toISOString()});u.debug(`[FRONTEND WS] Sent progress update for ${this.activeToolExecutions.size} active tools`)}}getKeepaliveTimeout(){return this.activeToolExecutions.size>0?this.extendedKeepaliveTimeout:this.baseKeepaliveTimeout}startKeepaliveWatchdog(){this.lastKeepaliveTime=new Date,this.stopKeepaliveWatchdog(),this.keepaliveWatchdog=setInterval(()=>{if(!this.lastKeepaliveTime)return;let e=this.getKeepaliveTimeout(),t=Date.now()-this.lastKeepaliveTime.getTime();u.debug(`[FRONTEND WS] Keepalive check - ${Math.round(t/1e3)}s since last, timeout: ${e/1e3}s, active tools: ${this.activeToolExecutions.size}`),t>e&&(u.error(`[FRONTEND WS] KEEPALIVE TIMEOUT - No activity for ${Math.round(t/1e3)}s`),this.handleKeepaliveTimeout())},1e4),u.debug("[FRONTEND WS] Started keepalive watchdog (check every 10s)")}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}handleKeepaliveTimeout(){u.debug("[FRONTEND WS] Handling keepalive timeout"),this.emit("keepalive_timeout",{lastKeepaliveTime:this.lastKeepaliveTime,activeTools:this.activeToolExecutions.size}),this.activeToolExecutions.size>0&&(u.debug("[FRONTEND WS] Tools still active, not disconnecting"),this.sendAggressiveHeartbeat())}updateKeepalive(){this.lastKeepaliveTime=new Date}startConnectionHealthCheck(){this.connectionHealthCheckTimer&&clearInterval(this.connectionHealthCheckTimer),this.connectionHealthCheckTimer=setInterval(()=>{this.updateConnectionQuality(),(this.connectionQuality==="fair"||this.connectionQuality==="poor")&&this.socket?.connected&&this.socket.emit("ping",{timestamp:Date.now()})},this.CONNECTION_HEALTH_CHECK_INTERVAL),u.debug(`[FRONTEND WS] Started connection health check (${this.CONNECTION_HEALTH_CHECK_INTERVAL/1e3}s interval)`)}stopConnectionHealthCheck(){this.connectionHealthCheckTimer&&(clearInterval(this.connectionHealthCheckTimer),this.connectionHealthCheckTimer=null)}startTokenRefreshTimer(){this.stopTokenRefreshTimer(),this.tokenRefreshTimer=setInterval(async()=>{await this.refreshAuthToken()},this.TOKEN_REFRESH_INTERVAL),u.debug(`[FRONTEND WS] Started token refresh timer (${this.TOKEN_REFRESH_INTERVAL/6e4} min interval)`)}stopTokenRefreshTimer(){this.tokenRefreshTimer&&(clearInterval(this.tokenRefreshTimer),this.tokenRefreshTimer=null)}async refreshAuthToken(){if(!this.isConnected()){u.debug("[FRONTEND WS] Not connected, skipping token refresh");return}try{u.debug("[FRONTEND WS] Refreshing Firebase token...");let e=await this.authService.getFirebaseIdToken();e&&this.socket?(this.socket.io.opts.query={...this.socket.io.opts.query,token:e},u.debug("[FRONTEND WS] Firebase token refreshed successfully"),this.socket?.connected&&(this.socket.emit("token_refreshed",{timestamp:Date.now()}),u.debug("[FRONTEND WS] Notified server of token refresh"))):u.warn("[FRONTEND WS] No Firebase token available for refresh")}catch(e){u.error(`[FRONTEND WS] Token refresh failed: ${e}`)}}getConnectionMetrics(){let e=this.connectionMetrics.pingResponseTimes.length>0?this.connectionMetrics.pingResponseTimes.reduce((t,n)=>t+n,0)/this.connectionMetrics.pingResponseTimes.length:0;return{...this.connectionMetrics,avgPingRTT:Math.round(e),currentQuality:this.connectionQuality}}resetConnectionMetrics(){this.connectionMetrics={totalConnections:0,totalDisconnections:0,disconnectionReasons:{},qualityDegradations:0,proactiveRecoveries:0,successfulRecoveries:0,failedRecoveries:0,pingResponseTimes:[],lastMetricsReset:new Date},u.debug("[FRONTEND WS] Connection metrics reset")}terminateAllRunningProcesses(){u.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),u.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(n){u.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${n.message}`)}this.runningProcesses.clear()}async sendStopSignal(e,t="all"){if(!this.isConnected()){u.warn("[FRONTEND WS] Not connected, cannot send stop signal");return}this.socket?.emit("stop_request",{user_id:e,stop_type:t,timestamp:new Date().toISOString()}),u.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async registerSession(e,t){if(!this.isConnected()){u.debug("[FRONTEND WS] Not connected, cannot register session");return}u.debug(`[FRONTEND WS] Registering session: ${e}`),this.socket?.emit("register",{traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()}),u.debug(`[FRONTEND WS] Session registered: ${e}`)}async sendToolRequest(e){if(!this.isConnected())throw u.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()}};u.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),this.socket?.emit("tool_execution_request",t)}async requestDeleteConfirmation(e,t){if(!this.isConnected())return u.debug("[FRONTEND WS] Not connected, cannot request delete confirmation"),"error";let n=`delete-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return u.debug(`[FRONTEND WS] Requesting delete confirmation: ${n}`),u.debug(`[FRONTEND WS] Command: ${e.substring(0,100)}${e.length>100?"...":""}`),new Promise(s=>{let r=setTimeout(()=>{this.pendingDeleteConfirmations.get(n)&&(u.debug(`[FRONTEND WS] Delete confirmation timed out: ${n}`),this.pendingDeleteConfirmations.delete(n),s("timeout"))},this.DELETE_CONFIRMATION_TIMEOUT);this.pendingDeleteConfirmations.set(n,{resolve:s,timeoutId:r}),this.socket?.emit("delete_confirmation_request",{confirmationId:n,command:e,description:t,timeout:this.DELETE_CONFIRMATION_TIMEOUT,timestamp:new Date().toISOString()}),u.debug(`[FRONTEND WS] Delete confirmation request sent: ${n}`)})}handleDeleteConfirmationResponse(e){let{confirmationId:t,response:n}=e;u.debug(`[FRONTEND WS] Delete confirmation response received: ${t} = ${n}`);let s=this.pendingDeleteConfirmations.get(t);if(!s){u.debug(`[FRONTEND WS] No pending confirmation for: ${t}`);return}clearTimeout(s.timeoutId),this.pendingDeleteConfirmations.delete(t);let r=n;s.resolve(["confirmed","declined","timeout","error"].includes(n)?r:"error")}async captureFrontendToolResultForHistory(e,t,n,s){let r=t.map(o=>o.text||"").join(`
1799
- `);try{let{PersonalAgentService:o}=await Promise.resolve().then(()=>(xt(),Cn)),a=o.getInstance(),c=s?`Error: ${s}`:r;a.captureFrontendToolResult(e,c,n),u.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}catch(o){u.debug(`[FRONTEND WS] Could not capture tool result: ${o}`)}}scheduleOldSessionCleanup(e){let s=Date.now(),r=()=>{if(!(this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0)){u.debug(`[FRONTEND WS] Old session ${e} work completed, cleanup done`);return}if(Date.now()-s>6e4){u.debug(`[FRONTEND WS] Cleanup timeout exceeded for session ${e}, forcing clear`),this.toolExecutionQueue.length>0&&(u.debug(`[FRONTEND WS] Force clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]);return}setTimeout(r,2e3)};u.debug(`[FRONTEND WS] Scheduling cleanup for old session ${e}`),setTimeout(r,2e3)}forceCleanup(){u.debug("[FRONTEND WS] Force cleanup"),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null),this.tokenRefreshTimer&&(clearInterval(this.tokenRefreshTimer),this.tokenRefreshTimer=null),this.connectionHealthCheckTimer&&(clearInterval(this.connectionHealthCheckTimer),this.connectionHealthCheckTimer=null);for(let[,e]of this.pendingDeleteConfirmations)clearTimeout(e.timeoutId);if(this.pendingDeleteConfirmations.clear(),this.runningProcesses.clear(),this.activeToolExecutions.clear(),this.toolExecutionQueue=[],this.pendingToolResults=[],this.capturedScreenshots=[],this.pingLatencies=[],this.onConnectionStateChangeCallbacks.clear(),this.activeWebViewURLs=[],this.activeToolCount=0,this.consecutivePoorQualityChecks=0,this.superAggressiveMode=!1,this.socket){try{this.socket.removeAllListeners(),this.socket.disconnect()}catch{}this.socket=null}u.debug("[FRONTEND WS] Force cleanup complete")}destroy(){u.debug("[FRONTEND WS] Destroying WebSocket service"),this.terminateAllRunningProcesses(),this.forceCleanup(),this.removeAllListeners(),this.connectionPromise&&(clearTimeout(this.connectionPromise.timeoutId),this.connectionPromise=null)}}});var sn,ju=F(()=>{"use strict";sn=class{static contextRegex=/<context>[\s\S]*?<\/context>/gi;static toolContextRegex=/<tool_context[^>]*>[\s\S]*?<\/tool_context>/gi;static guestContextRegex=/<guest-context>[\s\S]*?<\/guest-context>/gi;static agentSystemReminderRegex=/<agent_system_reminder>[\s\S]*?<\/agent_system_reminder>/gi;static systemReminderRegex=/<system-reminder>[\s\S]*?<\/system-reminder>/gi;static multipleNewlinesRegex=/\n{3,}/g;static incompleteContextRegex=/<context>[\s\S]*$/gi;static incompleteToolContextRegex=/<tool_context[^>]*>[\s\S]*$/gi;static incompleteGuestContextRegex=/<guest-context>[\s\S]*$/gi;static incompleteAgentSystemReminderRegex=/<agent_system_reminder>[\s\S]*$/gi;static incompleteSystemReminderRegex=/<system-reminder>[\s\S]*$/gi;static cache=new Map;static MAX_CACHE_SIZE=50;static lastInput="";static lastOutput="";static quickHash(e){let t=e.length;if(t===0)return"0";if(t<100)return`${t}:${e.slice(0,20)}`;let n=Math.floor(t/2);return`${t}:${e.charCodeAt(0)}:${e.charCodeAt(n)}:${e.charCodeAt(t-1)}`}static remove(e){if(!e)return e;if(e===this.lastInput)return this.lastOutput;if(!(e.includes("<context>")||e.includes("<tool_context")||e.includes("<guest-context>")||e.includes("<agent_system_reminder>")||e.includes("<system-reminder>")))return this.lastInput=e,this.lastOutput=e,e;let n=this.quickHash(e),s=this.cache.get(n);if(s!==void 0)return this.lastInput=e,this.lastOutput=s,s;let r=e;if(e.includes("<context>")&&(r=r.replace(this.contextRegex,""),r=r.replace(this.incompleteContextRegex,"")),e.includes("<tool_context")&&(r=r.replace(this.toolContextRegex,""),r=r.replace(this.incompleteToolContextRegex,"")),e.includes("<guest-context>")&&(r=r.replace(this.guestContextRegex,""),r=r.replace(this.incompleteGuestContextRegex,"")),e.includes("<agent_system_reminder>")&&(r=r.replace(this.agentSystemReminderRegex,""),r=r.replace(this.incompleteAgentSystemReminderRegex,"")),e.includes("<system-reminder>")&&(r=r.replace(this.systemReminderRegex,""),r=r.replace(this.incompleteSystemReminderRegex,"")),r=r.replace(this.multipleNewlinesRegex,`
1799
+ `);try{let{PersonalAgentService:o}=await Promise.resolve().then(()=>(xt(),In)),a=o.getInstance(),c=s?`Error: ${s}`:r;a.captureFrontendToolResult(e,c,n),u.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}catch(o){u.debug(`[FRONTEND WS] Could not capture tool result: ${o}`)}}scheduleOldSessionCleanup(e){let s=Date.now(),r=()=>{if(!(this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0)){u.debug(`[FRONTEND WS] Old session ${e} work completed, cleanup done`);return}if(Date.now()-s>6e4){u.debug(`[FRONTEND WS] Cleanup timeout exceeded for session ${e}, forcing clear`),this.toolExecutionQueue.length>0&&(u.debug(`[FRONTEND WS] Force clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]);return}setTimeout(r,2e3)};u.debug(`[FRONTEND WS] Scheduling cleanup for old session ${e}`),setTimeout(r,2e3)}forceCleanup(){u.debug("[FRONTEND WS] Force cleanup"),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null),this.tokenRefreshTimer&&(clearInterval(this.tokenRefreshTimer),this.tokenRefreshTimer=null),this.connectionHealthCheckTimer&&(clearInterval(this.connectionHealthCheckTimer),this.connectionHealthCheckTimer=null);for(let[,e]of this.pendingDeleteConfirmations)clearTimeout(e.timeoutId);if(this.pendingDeleteConfirmations.clear(),this.runningProcesses.clear(),this.activeToolExecutions.clear(),this.toolExecutionQueue=[],this.pendingToolResults=[],this.capturedScreenshots=[],this.pingLatencies=[],this.onConnectionStateChangeCallbacks.clear(),this.activeWebViewURLs=[],this.activeToolCount=0,this.consecutivePoorQualityChecks=0,this.superAggressiveMode=!1,this.socket){try{this.socket.removeAllListeners(),this.socket.disconnect()}catch{}this.socket=null}u.debug("[FRONTEND WS] Force cleanup complete")}destroy(){u.debug("[FRONTEND WS] Destroying WebSocket service"),this.terminateAllRunningProcesses(),this.forceCleanup(),this.removeAllListeners(),this.connectionPromise&&(clearTimeout(this.connectionPromise.timeoutId),this.connectionPromise=null)}}});var on,ju=$(()=>{"use strict";on=class{static contextRegex=/<context>[\s\S]*?<\/context>/gi;static toolContextRegex=/<tool_context[^>]*>[\s\S]*?<\/tool_context>/gi;static guestContextRegex=/<guest-context>[\s\S]*?<\/guest-context>/gi;static agentSystemReminderRegex=/<agent_system_reminder>[\s\S]*?<\/agent_system_reminder>/gi;static systemReminderRegex=/<system-reminder>[\s\S]*?<\/system-reminder>/gi;static multipleNewlinesRegex=/\n{3,}/g;static incompleteContextRegex=/<context>[\s\S]*$/gi;static incompleteToolContextRegex=/<tool_context[^>]*>[\s\S]*$/gi;static incompleteGuestContextRegex=/<guest-context>[\s\S]*$/gi;static incompleteAgentSystemReminderRegex=/<agent_system_reminder>[\s\S]*$/gi;static incompleteSystemReminderRegex=/<system-reminder>[\s\S]*$/gi;static cache=new Map;static MAX_CACHE_SIZE=50;static lastInput="";static lastOutput="";static quickHash(e){let t=e.length;if(t===0)return"0";if(t<100)return`${t}:${e.slice(0,20)}`;let n=Math.floor(t/2);return`${t}:${e.charCodeAt(0)}:${e.charCodeAt(n)}:${e.charCodeAt(t-1)}`}static remove(e){if(!e)return e;if(e===this.lastInput)return this.lastOutput;if(!(e.includes("<context>")||e.includes("<tool_context")||e.includes("<guest-context>")||e.includes("<agent_system_reminder>")||e.includes("<system-reminder>")))return this.lastInput=e,this.lastOutput=e,e;let n=this.quickHash(e),s=this.cache.get(n);if(s!==void 0)return this.lastInput=e,this.lastOutput=s,s;let r=e;if(e.includes("<context>")&&(r=r.replace(this.contextRegex,""),r=r.replace(this.incompleteContextRegex,"")),e.includes("<tool_context")&&(r=r.replace(this.toolContextRegex,""),r=r.replace(this.incompleteToolContextRegex,"")),e.includes("<guest-context>")&&(r=r.replace(this.guestContextRegex,""),r=r.replace(this.incompleteGuestContextRegex,"")),e.includes("<agent_system_reminder>")&&(r=r.replace(this.agentSystemReminderRegex,""),r=r.replace(this.incompleteAgentSystemReminderRegex,"")),e.includes("<system-reminder>")&&(r=r.replace(this.systemReminderRegex,""),r=r.replace(this.incompleteSystemReminderRegex,"")),r=r.replace(this.multipleNewlinesRegex,`
1800
1800
 
1801
- `),r=r.trim(),this.cache.size>=this.MAX_CACHE_SIZE){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}return this.cache.set(n,r),this.lastInput=e,this.lastOutput=r,r}static hasContextBlocks(e){return e.includes("<context>")||e.includes("<tool_context")||e.includes("<guest-context>")||e.includes("<agent_system_reminder>")||e.includes("<system-reminder>")}}});import{EventEmitter as Tb}from"events";import{promises as Mo}from"fs";import{join as zu}from"path";import{homedir as xb}from"os";var xa,tr,Ca=F(()=>{"use strict";xa=class i extends Tb{static instance;settings;configDir;configPath;constructor(){super(),this.configDir=zu(xb(),".orion-cli"),this.configPath=zu(this.configDir,"settings.json"),this.settings={isPrivacyModeEnabled:!0,defaultModel:"snowx-c5",temperature:.7,maxTokens:4096,enableMarkdownFormatting:!0,showThinkingBlocks:!0,compactMode:!1,enableColors:!0,enableToolCalling:!0,enableCrossDevice:!0,enableWebSocket:!0,enableFirebase:!0,customUserPreferences:{instructions:"",lastModified:new Date,isEnabled:!0},logLevel:"info",autoSaveHistory:!0,maxHistoryEntries:1e3},this.loadSettings()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async loadSettings(){try{await Mo.mkdir(this.configDir,{recursive:!0});try{let e=await Mo.readFile(this.configPath,"utf-8"),t=JSON.parse(e);this.settings={...this.settings,...t},this.settings.customUserPreferences.lastModified&&(this.settings.customUserPreferences.lastModified=new Date(this.settings.customUserPreferences.lastModified))}catch{await this.saveSettings()}}catch(e){console.warn("⚠️ Failed to load settings:",e)}this.emit("settingsLoaded",this.settings)}async saveSettings(){try{await Mo.mkdir(this.configDir,{recursive:!0}),await Mo.writeFile(this.configPath,JSON.stringify(this.settings,null,2)),this.emit("settingsSaved",this.settings)}catch(e){throw console.error("❌ Failed to save settings:",e),e}}async setWorkingDirectory(e){this.settings.currentWorkingDirectory=e,await this.saveSettings(),this.emit("workingDirectoryChanged",e)}getWorkingDirectory(){return this.settings.currentWorkingDirectory}async setPrivacyMode(e){this.settings.isPrivacyModeEnabled=e,await this.saveSettings(),this.emit("privacyModeChanged",e)}isPrivacyModeEnabled(){return this.settings.isPrivacyModeEnabled}async setDefaultModel(e){this.settings.defaultModel=e,await this.saveSettings(),this.emit("defaultModelChanged",e)}getDefaultModel(){return this.settings.defaultModel}async setTemperature(e){this.settings.temperature=Math.max(0,Math.min(2,e)),await this.saveSettings(),this.emit("temperatureChanged",this.settings.temperature)}getTemperature(){return this.settings.temperature}async setMarkdownFormatting(e){this.settings.enableMarkdownFormatting=e,await this.saveSettings(),this.emit("markdownFormattingChanged",e)}async setShowThinkingBlocks(e){this.settings.showThinkingBlocks=e,await this.saveSettings(),this.emit("thinkingBlocksChanged",e)}async setCompactMode(e){this.settings.compactMode=e,await this.saveSettings(),this.emit("compactModeChanged",e)}async setEnableColors(e){this.settings.enableColors=e,await this.saveSettings(),this.emit("colorsChanged",e)}async setEnableToolCalling(e){this.settings.enableToolCalling=e,await this.saveSettings(),this.emit("toolCallingChanged",e)}async setEnableCrossDevice(e){this.settings.enableCrossDevice=e,await this.saveSettings(),this.emit("crossDeviceChanged",e)}async setEnableWebSocket(e){this.settings.enableWebSocket=e,await this.saveSettings(),this.emit("webSocketChanged",e)}async setEnableFirebase(e){this.settings.enableFirebase=e,await this.saveSettings(),this.emit("firebaseChanged",e)}async updateCustomUserPreferences(e){this.settings.customUserPreferences={...this.settings.customUserPreferences,...e,lastModified:new Date},await this.saveSettings(),this.emit("customPreferencesChanged",this.settings.customUserPreferences)}getFormattedCustomPreferences(){let e=this.settings.customUserPreferences;return!e.isEnabled||!e.instructions.trim()?"":`
1801
+ `),r=r.trim(),this.cache.size>=this.MAX_CACHE_SIZE){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}return this.cache.set(n,r),this.lastInput=e,this.lastOutput=r,r}static hasContextBlocks(e){return e.includes("<context>")||e.includes("<tool_context")||e.includes("<guest-context>")||e.includes("<agent_system_reminder>")||e.includes("<system-reminder>")}}});import{EventEmitter as Tb}from"events";import{promises as Mo}from"fs";import{join as zu}from"path";import{homedir as xb}from"os";var xa,nr,Ca=$(()=>{"use strict";xa=class i extends Tb{static instance;settings;configDir;configPath;constructor(){super(),this.configDir=zu(xb(),".orion-cli"),this.configPath=zu(this.configDir,"settings.json"),this.settings={isPrivacyModeEnabled:!0,defaultModel:"snowx-c5",temperature:.7,maxTokens:4096,enableMarkdownFormatting:!0,showThinkingBlocks:!0,compactMode:!1,enableColors:!0,enableToolCalling:!0,enableCrossDevice:!0,enableWebSocket:!0,enableFirebase:!0,customUserPreferences:{instructions:"",lastModified:new Date,isEnabled:!0},logLevel:"info",autoSaveHistory:!0,maxHistoryEntries:1e3},this.loadSettings()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async loadSettings(){try{await Mo.mkdir(this.configDir,{recursive:!0});try{let e=await Mo.readFile(this.configPath,"utf-8"),t=JSON.parse(e);this.settings={...this.settings,...t},this.settings.customUserPreferences.lastModified&&(this.settings.customUserPreferences.lastModified=new Date(this.settings.customUserPreferences.lastModified))}catch{await this.saveSettings()}}catch(e){console.warn("⚠️ Failed to load settings:",e)}this.emit("settingsLoaded",this.settings)}async saveSettings(){try{await Mo.mkdir(this.configDir,{recursive:!0}),await Mo.writeFile(this.configPath,JSON.stringify(this.settings,null,2)),this.emit("settingsSaved",this.settings)}catch(e){throw console.error("❌ Failed to save settings:",e),e}}async setWorkingDirectory(e){this.settings.currentWorkingDirectory=e,await this.saveSettings(),this.emit("workingDirectoryChanged",e)}getWorkingDirectory(){return this.settings.currentWorkingDirectory}async setPrivacyMode(e){this.settings.isPrivacyModeEnabled=e,await this.saveSettings(),this.emit("privacyModeChanged",e)}isPrivacyModeEnabled(){return this.settings.isPrivacyModeEnabled}async setDefaultModel(e){this.settings.defaultModel=e,await this.saveSettings(),this.emit("defaultModelChanged",e)}getDefaultModel(){return this.settings.defaultModel}async setTemperature(e){this.settings.temperature=Math.max(0,Math.min(2,e)),await this.saveSettings(),this.emit("temperatureChanged",this.settings.temperature)}getTemperature(){return this.settings.temperature}async setMarkdownFormatting(e){this.settings.enableMarkdownFormatting=e,await this.saveSettings(),this.emit("markdownFormattingChanged",e)}async setShowThinkingBlocks(e){this.settings.showThinkingBlocks=e,await this.saveSettings(),this.emit("thinkingBlocksChanged",e)}async setCompactMode(e){this.settings.compactMode=e,await this.saveSettings(),this.emit("compactModeChanged",e)}async setEnableColors(e){this.settings.enableColors=e,await this.saveSettings(),this.emit("colorsChanged",e)}async setEnableToolCalling(e){this.settings.enableToolCalling=e,await this.saveSettings(),this.emit("toolCallingChanged",e)}async setEnableCrossDevice(e){this.settings.enableCrossDevice=e,await this.saveSettings(),this.emit("crossDeviceChanged",e)}async setEnableWebSocket(e){this.settings.enableWebSocket=e,await this.saveSettings(),this.emit("webSocketChanged",e)}async setEnableFirebase(e){this.settings.enableFirebase=e,await this.saveSettings(),this.emit("firebaseChanged",e)}async updateCustomUserPreferences(e){this.settings.customUserPreferences={...this.settings.customUserPreferences,...e,lastModified:new Date},await this.saveSettings(),this.emit("customPreferencesChanged",this.settings.customUserPreferences)}getFormattedCustomPreferences(){let e=this.settings.customUserPreferences;return!e.isEnabled||!e.instructions.trim()?"":`
1802
1802
  --- User Instructions ---
1803
1803
  ${e.instructions}
1804
1804
  --- End Instructions ---
1805
- `}getCustomPreferencesSummary(){let e=this.settings.customUserPreferences;if(!e.instructions.trim())return"No instructions set";let t=e.instructions.trim().split(/\s+/).length;return t<=10?e.instructions.trim():`${t} words of custom instructions`}async setLogLevel(e){this.settings.logLevel=e,await this.saveSettings(),this.emit("logLevelChanged",e)}getLogLevel(){return this.settings.logLevel}getAllSettings(){return{...this.settings}}getDisplayPreferences(){return{enableMarkdownFormatting:this.settings.enableMarkdownFormatting,showThinkingBlocks:this.settings.showThinkingBlocks,compactMode:this.settings.compactMode,enableColors:this.settings.enableColors}}getFeatureToggles(){return{enableToolCalling:this.settings.enableToolCalling,enableCrossDevice:this.settings.enableCrossDevice,enableWebSocket:this.settings.enableWebSocket,enableFirebase:this.settings.enableFirebase}}async resetToDefaults(){let e=this.settings.currentWorkingDirectory;this.settings={currentWorkingDirectory:e,isPrivacyModeEnabled:!0,defaultModel:"snowx-c5",temperature:.7,maxTokens:4096,enableMarkdownFormatting:!0,showThinkingBlocks:!0,compactMode:!1,enableColors:!0,enableToolCalling:!0,enableCrossDevice:!0,enableWebSocket:!0,enableFirebase:!0,customUserPreferences:{instructions:"",lastModified:new Date,isEnabled:!0},logLevel:"info",autoSaveHistory:!0,maxHistoryEntries:1e3},await this.saveSettings(),this.emit("settingsReset")}exportSettings(){return JSON.stringify(this.settings,null,2)}async importSettings(e){try{let t=JSON.parse(e);this.settings={...this.settings,...t},this.settings.customUserPreferences.lastModified&&(this.settings.customUserPreferences.lastModified=new Date(this.settings.customUserPreferences.lastModified)),await this.saveSettings(),this.emit("settingsImported")}catch{throw new Error("Invalid settings format")}}},tr=xa});var qu=F(()=>{"use strict"});import Ye from"fs";import rn from"path";import Cb from"os";var Eb,Ea,_t,Ku=F(()=>{"use strict";j();Eb=/[/\\:*?"<>|]/g,Ea=class i{static instance;guardrailsPath;constructor(){this.guardrailsPath=rn.join(Cb.homedir(),".orion","guardrails")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.guardrailsPath}ensureFolder(){try{return Ye.existsSync(this.guardrailsPath)||(Ye.mkdirSync(this.guardrailsPath,{recursive:!0}),u.debug(`[Guardrails] Created guardrails folder: ${this.guardrailsPath}`)),!0}catch(e){return u.error(`[Guardrails] Failed to create guardrails folder: ${e.message}`),!1}}validateFilename(e){if(!e||typeof e!="string")return{valid:!1,error:"Guardrail name is required"};let t=e.trim();return t===""?{valid:!1,error:"Guardrail name cannot be empty"}:Eb.test(t)?{valid:!1,error:"Guardrail name contains invalid characters"}:rn.join(this.guardrailsPath,`${t}.md`).startsWith(this.guardrailsPath)?{valid:!0}:{valid:!1,error:"Invalid guardrail name (path traversal detected)"}}scanFolder(){try{this.ensureFolder();let e=Ye.readdirSync(this.guardrailsPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=rn.join(this.guardrailsPath,n);try{if(!Ye.statSync(s).isFile())continue;let o=Ye.readFileSync(s,"utf-8"),a=n.replace(/\.md$/,"");t.push({id:a,name:a,content:o})}catch(r){u.warn(`[Guardrails] Failed to read guardrail file ${n}: ${r.message}`)}}return u.debug(`[Guardrails] Scanned folder, found ${t.length} guardrails`),t}catch(e){return u.error(`[Guardrails] Failed to scan guardrails folder: ${e.message}`),[]}}createFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=e.trim(),r=rn.join(this.guardrailsPath,`${s}.md`);try{return this.ensureFolder(),Ye.existsSync(r)?{success:!1,error:"A guardrail with this name already exists"}:(Ye.writeFileSync(r,t,"utf-8"),u.debug(`[Guardrails] Created guardrail file: ${s}`),{success:!0,id:s})}catch(o){return u.error(`[Guardrails] Failed to create guardrail file: ${o.message}`),{success:!1,error:o.message}}}updateFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=rn.join(this.guardrailsPath,`${e}.md`);try{return Ye.existsSync(s)?(Ye.writeFileSync(s,t,"utf-8"),u.debug(`[Guardrails] Updated guardrail file: ${e}`),{success:!0}):{success:!1,error:"Guardrail not found"}}catch(r){return u.error(`[Guardrails] Failed to update guardrail file: ${r.message}`),{success:!1,error:r.message}}}deleteFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=rn.join(this.guardrailsPath,`${e}.md`);try{return Ye.existsSync(n)?(Ye.unlinkSync(n),u.debug(`[Guardrails] Deleted guardrail file: ${e}`),{success:!0}):{success:!1,error:"Guardrail not found"}}catch(s){return u.error(`[Guardrails] Failed to delete guardrail file: ${s.message}`),{success:!1,error:s.message}}}readFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=rn.join(this.guardrailsPath,`${e}.md`);try{return Ye.existsSync(n)?{success:!0,content:Ye.readFileSync(n,"utf-8")}:{success:!1,error:"Guardrail not found"}}catch(s){return u.error(`[Guardrails] Failed to read guardrail file: ${s.message}`),{success:!1,error:s.message}}}exists(e){if(!this.validateFilename(e).valid)return!1;let n=rn.join(this.guardrailsPath,`${e}.md`);return Ye.existsSync(n)}},_t=Ea.getInstance()});var Ib,kb,Pb,Ab,Db,Mb,Vu,Xu=F(()=>{"use strict";Ib=[{id:"no-hardcoded-secrets",name:"No Hardcoded Secrets",description:"Never hardcode API keys, passwords, tokens, or other secrets in code",category:"security",severity:"critical",tags:["security","secrets","credentials","api-keys"],content:`# No Hardcoded Secrets
1805
+ `}getCustomPreferencesSummary(){let e=this.settings.customUserPreferences;if(!e.instructions.trim())return"No instructions set";let t=e.instructions.trim().split(/\s+/).length;return t<=10?e.instructions.trim():`${t} words of custom instructions`}async setLogLevel(e){this.settings.logLevel=e,await this.saveSettings(),this.emit("logLevelChanged",e)}getLogLevel(){return this.settings.logLevel}getAllSettings(){return{...this.settings}}getDisplayPreferences(){return{enableMarkdownFormatting:this.settings.enableMarkdownFormatting,showThinkingBlocks:this.settings.showThinkingBlocks,compactMode:this.settings.compactMode,enableColors:this.settings.enableColors}}getFeatureToggles(){return{enableToolCalling:this.settings.enableToolCalling,enableCrossDevice:this.settings.enableCrossDevice,enableWebSocket:this.settings.enableWebSocket,enableFirebase:this.settings.enableFirebase}}async resetToDefaults(){let e=this.settings.currentWorkingDirectory;this.settings={currentWorkingDirectory:e,isPrivacyModeEnabled:!0,defaultModel:"snowx-c5",temperature:.7,maxTokens:4096,enableMarkdownFormatting:!0,showThinkingBlocks:!0,compactMode:!1,enableColors:!0,enableToolCalling:!0,enableCrossDevice:!0,enableWebSocket:!0,enableFirebase:!0,customUserPreferences:{instructions:"",lastModified:new Date,isEnabled:!0},logLevel:"info",autoSaveHistory:!0,maxHistoryEntries:1e3},await this.saveSettings(),this.emit("settingsReset")}exportSettings(){return JSON.stringify(this.settings,null,2)}async importSettings(e){try{let t=JSON.parse(e);this.settings={...this.settings,...t},this.settings.customUserPreferences.lastModified&&(this.settings.customUserPreferences.lastModified=new Date(this.settings.customUserPreferences.lastModified)),await this.saveSettings(),this.emit("settingsImported")}catch{throw new Error("Invalid settings format")}}},nr=xa});var qu=$(()=>{"use strict"});import Qe from"fs";import an from"path";import Cb from"os";var Eb,Ea,_t,Ku=$(()=>{"use strict";z();Eb=/[/\\:*?"<>|]/g,Ea=class i{static instance;guardrailsPath;constructor(){this.guardrailsPath=an.join(Cb.homedir(),".orion","guardrails")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.guardrailsPath}ensureFolder(){try{return Qe.existsSync(this.guardrailsPath)||(Qe.mkdirSync(this.guardrailsPath,{recursive:!0}),u.debug(`[Guardrails] Created guardrails folder: ${this.guardrailsPath}`)),!0}catch(e){return u.error(`[Guardrails] Failed to create guardrails folder: ${e.message}`),!1}}validateFilename(e){if(!e||typeof e!="string")return{valid:!1,error:"Guardrail name is required"};let t=e.trim();return t===""?{valid:!1,error:"Guardrail name cannot be empty"}:Eb.test(t)?{valid:!1,error:"Guardrail name contains invalid characters"}:an.join(this.guardrailsPath,`${t}.md`).startsWith(this.guardrailsPath)?{valid:!0}:{valid:!1,error:"Invalid guardrail name (path traversal detected)"}}scanFolder(){try{this.ensureFolder();let e=Qe.readdirSync(this.guardrailsPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=an.join(this.guardrailsPath,n);try{if(!Qe.statSync(s).isFile())continue;let o=Qe.readFileSync(s,"utf-8"),a=n.replace(/\.md$/,"");t.push({id:a,name:a,content:o})}catch(r){u.warn(`[Guardrails] Failed to read guardrail file ${n}: ${r.message}`)}}return u.debug(`[Guardrails] Scanned folder, found ${t.length} guardrails`),t}catch(e){return u.error(`[Guardrails] Failed to scan guardrails folder: ${e.message}`),[]}}createFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=e.trim(),r=an.join(this.guardrailsPath,`${s}.md`);try{return this.ensureFolder(),Qe.existsSync(r)?{success:!1,error:"A guardrail with this name already exists"}:(Qe.writeFileSync(r,t,"utf-8"),u.debug(`[Guardrails] Created guardrail file: ${s}`),{success:!0,id:s})}catch(o){return u.error(`[Guardrails] Failed to create guardrail file: ${o.message}`),{success:!1,error:o.message}}}updateFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=an.join(this.guardrailsPath,`${e}.md`);try{return Qe.existsSync(s)?(Qe.writeFileSync(s,t,"utf-8"),u.debug(`[Guardrails] Updated guardrail file: ${e}`),{success:!0}):{success:!1,error:"Guardrail not found"}}catch(r){return u.error(`[Guardrails] Failed to update guardrail file: ${r.message}`),{success:!1,error:r.message}}}deleteFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=an.join(this.guardrailsPath,`${e}.md`);try{return Qe.existsSync(n)?(Qe.unlinkSync(n),u.debug(`[Guardrails] Deleted guardrail file: ${e}`),{success:!0}):{success:!1,error:"Guardrail not found"}}catch(s){return u.error(`[Guardrails] Failed to delete guardrail file: ${s.message}`),{success:!1,error:s.message}}}readFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=an.join(this.guardrailsPath,`${e}.md`);try{return Qe.existsSync(n)?{success:!0,content:Qe.readFileSync(n,"utf-8")}:{success:!1,error:"Guardrail not found"}}catch(s){return u.error(`[Guardrails] Failed to read guardrail file: ${s.message}`),{success:!1,error:s.message}}}exists(e){if(!this.validateFilename(e).valid)return!1;let n=an.join(this.guardrailsPath,`${e}.md`);return Qe.existsSync(n)}},_t=Ea.getInstance()});var Ib,kb,Pb,Ab,Db,Mb,Vu,Xu=$(()=>{"use strict";Ib=[{id:"no-hardcoded-secrets",name:"No Hardcoded Secrets",description:"Never hardcode API keys, passwords, tokens, or other secrets in code",category:"security",severity:"critical",tags:["security","secrets","credentials","api-keys"],content:`# No Hardcoded Secrets
1806
1806
 
1807
1807
  Never hardcode API keys, passwords, tokens, or other secrets in code.
1808
1808
 
@@ -2349,7 +2349,7 @@ chmod -R 777 /
2349
2349
  - When in doubt, ask before running
2350
2350
  - Test on non-production data first
2351
2351
  - Keep command history for audit trail
2352
- `}],Mb=[{id:"security",name:"Security",description:"Prevent security vulnerabilities",guardrails:Ib},{id:"code_quality",name:"Code Quality",description:"Maintain code quality standards",guardrails:kb},{id:"git",name:"Git",description:"Prevent git-related mistakes",guardrails:Pb},{id:"data",name:"Data",description:"Protect data integrity",guardrails:Ab},{id:"tool_misuse",name:"Tool Misuse",description:"Prevent tool misuse errors",guardrails:Db}],Vu=()=>Mb.flatMap(i=>i.guardrails)});import{EventEmitter as Rb}from"events";var Yu,Qu,Ob,Nb,ka,Pa,Aa,_b,Da,ss,Ju=F(()=>{"use strict";qu();Ku();Le();j();Xu();Yu="orion-guardrails-selected",Qu="orion-installed-guardrail-templates",Ob=()=>{try{let i=de.string(Qu);if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}},Nb=i=>{de.set(Qu,JSON.stringify(i))},ka=i=>{let e=i.match(/##\s*Category\s*\n+[-*]?\s*(security|code_quality|data|git|architecture|tool_misuse)/i);return e?e[1].toLowerCase():"code_quality"},Pa=i=>{let e=i.match(/##\s*Severity\s*\n+[-*]?\s*(critical|high|medium|low)/i);return e?e[1].toLowerCase():"medium"},Aa=(i,e)=>{if(!e||e.trim()==="")return i;let t=e.split(`
2352
+ `}],Mb=[{id:"security",name:"Security",description:"Prevent security vulnerabilities",guardrails:Ib},{id:"code_quality",name:"Code Quality",description:"Maintain code quality standards",guardrails:kb},{id:"git",name:"Git",description:"Prevent git-related mistakes",guardrails:Pb},{id:"data",name:"Data",description:"Protect data integrity",guardrails:Ab},{id:"tool_misuse",name:"Tool Misuse",description:"Prevent tool misuse errors",guardrails:Db}],Vu=()=>Mb.flatMap(i=>i.guardrails)});import{EventEmitter as Rb}from"events";var Yu,Qu,Ob,Nb,ka,Pa,Aa,_b,Da,os,Ju=$(()=>{"use strict";qu();Ku();Ue();z();Xu();Yu="orion-guardrails-selected",Qu="orion-installed-guardrail-templates",Ob=()=>{try{let i=de.string(Qu);if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}},Nb=i=>{de.set(Qu,JSON.stringify(i))},ka=i=>{let e=i.match(/##\s*Category\s*\n+[-*]?\s*(security|code_quality|data|git|architecture|tool_misuse)/i);return e?e[1].toLowerCase():"code_quality"},Pa=i=>{let e=i.match(/##\s*Severity\s*\n+[-*]?\s*(critical|high|medium|low)/i);return e?e[1].toLowerCase():"medium"},Aa=(i,e)=>{if(!e||e.trim()==="")return i;let t=e.split(`
2353
2353
  `);for(let n of t){let s=n.trim();if(!s||s.startsWith("#")||s.startsWith("```")||s.match(/^[-*]?\s*(security|code_quality|data|git|architecture|tool_misuse|critical|high|medium|low)/i))continue;let r=s.substring(0,150);return r.length<s.length?r+"...":r}return i},_b=async i=>{let e=Vu(),t=Ob(),n=i.map(a=>a.toLowerCase()),s=e.filter(a=>!t.includes(a.id));if(s.length===0)return!1;u.debug(`[Guardrails] Found ${s.length} new guardrail template(s) to install...`);let r=0,o=[];for(let a of s){if(n.includes(a.name.toLowerCase())||n.includes(a.id.toLowerCase())){u.debug(`[Guardrails] Skipping "${a.name}" - user already has this guardrail`),o.push(a.id);continue}try{_t.createFile(a.name,a.content).success&&(u.debug(`[Guardrails] Installed new guardrail: ${a.name}`),o.push(a.id),r++)}catch(c){u.error(`[Guardrails] Failed to install guardrail ${a.name}: ${c.message}`)}}return Nb([...t,...o]),u.info(`[Guardrails] Sync complete: installed ${r} new guardrail(s)`),r>0},Da=class i extends Rb{static instance;state;constructor(){super(),this.state={guardrails:[],selectedGuardrailIds:this.loadSelectedIds(),isLoading:!1,isDeleting:null,isCreating:!1,isUpdating:null,lastSynced:null}}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadSelectedIds(){try{let e=de.string(Yu);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}saveSelectedIds(e){de.set(Yu,JSON.stringify(e))}getState(){return{...this.state}}async loadGuardrails(){this.state.isLoading=!0,this.emit("change",this.state);try{u.debug("[Guardrails] Loading guardrails from file system..."),_t.ensureFolder();let e=_t.scanFolder(),t=e.map(c=>c.name);await _b(t)&&(e=_t.scanFolder());let s=new Date().toISOString(),r=e.map(c=>({id:c.id,name:c.name,description:Aa(c.name,c.content),content:c.content,category:ka(c.content),severity:Pa(c.content),createdAt:s,updatedAt:s,isSelected:this.state.selectedGuardrailIds.includes(c.id)})),o=r.map(c=>c.id),a=this.state.selectedGuardrailIds.filter(c=>o.includes(c));this.state={...this.state,guardrails:r,selectedGuardrailIds:a,lastSynced:s,isLoading:!1},this.saveSelectedIds(a),this.emit("change",this.state),u.debug(`[Guardrails] Loaded ${r.length} guardrails from file system`)}catch(e){u.error(`[Guardrails] Failed to load guardrails: ${e.message}`),this.state.isLoading=!1,this.emit("change",this.state)}}async refreshGuardrails(){u.debug("[Guardrails] Refreshing guardrails..."),await this.loadGuardrails()}async toggleGuardrailSelection(e){if(!this.state.guardrails.find(r=>r.id===e))return;let n;if(this.state.selectedGuardrailIds.includes(e))n=this.state.selectedGuardrailIds.filter(r=>r!==e);else{if(this.state.selectedGuardrailIds.length>=10){u.warn(`[Guardrails] Cannot select more than ${10} guardrails`);return}n=[...this.state.selectedGuardrailIds,e]}let s=this.state.guardrails.map(r=>({...r,isSelected:n.includes(r.id)}));this.state={...this.state,guardrails:s,selectedGuardrailIds:n},this.saveSelectedIds(n),this.emit("change",this.state),u.debug(`[Guardrails] Selected guardrails: ${n.join(", ")||"none"}`)}async createGuardrail(e,t,n,s,r){if(!e||e.trim()==="")return{success:!1,error:"Guardrail name is required"};let o=e.trim(),a=t?.trim()||"";if(this.state.isCreating)return{success:!1,error:"Another operation in progress"};if(this.state.guardrails.some(c=>c.name.toLowerCase()===o.toLowerCase()))return{success:!1,error:"A guardrail with this name already exists"};this.state.isCreating=!0,this.emit("change",this.state);try{let c=_t.createFile(o,a);if(!c.success)return this.state.isCreating=!1,this.emit("change",this.state),{success:!1,error:c.error};let l=new Date().toISOString(),d=o,g={id:d,name:o,description:n?.trim()||Aa(o,a),content:a,category:s||ka(a),severity:r||Pa(a),createdAt:l,updatedAt:l,isSelected:!1};return this.state={...this.state,guardrails:[...this.state.guardrails,g],isCreating:!1,lastSynced:l},this.emit("change",this.state),u.debug(`[Guardrails] Created guardrail: ${o}`),{success:!0,id:d}}catch(c){return u.error(`[Guardrails] Failed to create guardrail: ${c.message}`),this.state.isCreating=!1,this.emit("change",this.state),{success:!1,error:c.message}}}async updateGuardrail(e,t,n,s,r,o){if(!e)return{success:!1,error:"Invalid guardrail ID"};if(this.state.isUpdating!==null)return{success:!1,error:"Another operation in progress"};let a=this.state.guardrails.find(d=>d.id===e);if(!a)return{success:!1,error:"Guardrail not found"};let c=t?.trim()||a.name,l=n?.trim()||a.content;this.state.isUpdating=e,this.emit("change",this.state);try{let d=new Date().toISOString();if(c!==a.name){_t.deleteFile(e);let h=_t.createFile(c,l);if(!h.success)return this.state.isUpdating=null,this.emit("change",this.state),{success:!1,error:h.error}}else{let h=_t.updateFile(e,l);if(!h.success)return this.state.isUpdating=null,this.emit("change",this.state),{success:!1,error:h.error}}let g=c!==a.name?c:e,m=this.state.selectedGuardrailIds;g!==e&&this.state.selectedGuardrailIds.includes(e)&&(m=this.state.selectedGuardrailIds.map(h=>h===e?g:h));let p=this.state.guardrails.map(h=>h.id===e?{...h,id:g,name:c,description:s?.trim()||Aa(c,l),content:l,category:r||ka(l),severity:o||Pa(l),updatedAt:d,isSelected:m.includes(g)}:h);return this.state={...this.state,guardrails:p,selectedGuardrailIds:m,isUpdating:null,lastSynced:d},this.saveSelectedIds(m),this.emit("change",this.state),u.debug(`[Guardrails] Updated guardrail: ${e}${g!==e?` -> ${g}`:""}`),{success:!0}}catch(d){return u.error(`[Guardrails] Failed to update guardrail: ${d.message}`),this.state.isUpdating=null,this.emit("change",this.state),{success:!1,error:d.message}}}async deleteGuardrail(e){if(!e)return{success:!1,error:"Invalid guardrail ID"};if(this.state.isDeleting!==null)return{success:!1,error:"Another delete in progress"};if(!this.state.guardrails.find(n=>n.id===e))return{success:!1,error:"Guardrail not found"};this.state.isDeleting=e,this.emit("change",this.state);try{let n=_t.deleteFile(e);if(!n.success)return this.state.isDeleting=null,this.emit("change",this.state),{success:!1,error:n.error};let s=this.state.guardrails.filter(a=>a.id!==e),r=this.state.selectedGuardrailIds.includes(e),o=r?this.state.selectedGuardrailIds.filter(a=>a!==e):this.state.selectedGuardrailIds;return this.state={...this.state,guardrails:s,selectedGuardrailIds:o,isDeleting:null,lastSynced:new Date().toISOString()},this.saveSelectedIds(o),this.emit("change",this.state),u.debug(`[Guardrails] Deleted guardrail: ${e}${r?" (was selected)":""}`),{success:!0}}catch(n){return u.error(`[Guardrails] Failed to delete guardrail: ${n.message}`),this.state.isDeleting=null,this.emit("change",this.state),{success:!1,error:n.message}}}getSelectedGuardrails(){return this.state.guardrails.filter(e=>this.state.selectedGuardrailIds.includes(e.id))}getSelectedGuardrailsContent(){let e=this.getSelectedGuardrails();return e.length===0?"":e.map((t,n)=>`═══════════════════════════════════════════════════════════════
2354
2354
  GUARDRAIL ${n+1}: ${t.name.toUpperCase()} [${t.severity.toUpperCase()}]
2355
2355
  ═══════════════════════════════════════════════════════════════
@@ -2371,43 +2371,43 @@ ${e.map(n=>` <guardrail>
2371
2371
  <severity>${n.severity}</severity>
2372
2372
  </guardrail>`).join(`
2373
2373
  `)}
2374
- </available_guardrails>`}getGuardrailsContentMap(){return Object.fromEntries(this.state.guardrails.map(e=>[e.id,e.content]))}getGuardrailContentById(e){return this.state.guardrails.find(n=>n.id===e)?.content??null}reset(){this.state={guardrails:[],selectedGuardrailIds:[],isLoading:!1,isDeleting:null,isCreating:!1,isUpdating:null,lastSynced:null},this.saveSelectedIds([]),this.emit("change",this.state),u.debug("[Guardrails] Reset store state (files preserved)")}},ss=Da.getInstance()});import Qe from"fs";import on from"path";import $b from"os";var Fb,Ma,an,Zu=F(()=>{"use strict";j();Fb=/[/\\:*?"<>|]/g,Ma=class i{static instance;charactersPath;constructor(){this.charactersPath=on.join($b.homedir(),".orion","characters")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.charactersPath}ensureFolder(){try{return Qe.existsSync(this.charactersPath)||(Qe.mkdirSync(this.charactersPath,{recursive:!0}),u.debug(`[Characters] Created characters folder: ${this.charactersPath}`)),!0}catch(e){return u.error(`[Characters] Failed to create characters folder: ${e.message}`),!1}}validateFilename(e){if(!e||typeof e!="string")return{valid:!1,error:"Character name is required"};let t=e.trim();return t===""?{valid:!1,error:"Character name cannot be empty"}:Fb.test(t)?{valid:!1,error:"Character name contains invalid characters"}:on.join(this.charactersPath,`${t}.md`).startsWith(this.charactersPath)?{valid:!0}:{valid:!1,error:"Invalid character name (path traversal detected)"}}scanFolder(){try{this.ensureFolder();let e=Qe.readdirSync(this.charactersPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=on.join(this.charactersPath,n);try{if(!Qe.statSync(s).isFile())continue;let o=Qe.readFileSync(s,"utf-8"),a=n.replace(/\.md$/,"");t.push({id:a,name:a,content:o})}catch(r){u.warn(`[Characters] Failed to read character file ${n}: ${r.message}`)}}return u.debug(`[Characters] Scanned folder, found ${t.length} characters`),t}catch(e){return u.error(`[Characters] Failed to scan characters folder: ${e.message}`),[]}}createFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=e.trim(),r=on.join(this.charactersPath,`${s}.md`);try{return this.ensureFolder(),Qe.existsSync(r)?{success:!1,error:"A character with this name already exists"}:(Qe.writeFileSync(r,t,"utf-8"),u.debug(`[Characters] Created character file: ${s}`),{success:!0,id:s})}catch(o){return u.error(`[Characters] Failed to create character file: ${o.message}`),{success:!1,error:o.message}}}updateFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=on.join(this.charactersPath,`${e}.md`);try{return Qe.existsSync(s)?(Qe.writeFileSync(s,t,"utf-8"),u.debug(`[Characters] Updated character file: ${e}`),{success:!0}):{success:!1,error:"Character not found"}}catch(r){return u.error(`[Characters] Failed to update character file: ${r.message}`),{success:!1,error:r.message}}}deleteFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=on.join(this.charactersPath,`${e}.md`);try{return Qe.existsSync(n)?(Qe.unlinkSync(n),u.debug(`[Characters] Deleted character file: ${e}`),{success:!0}):{success:!1,error:"Character not found"}}catch(s){return u.error(`[Characters] Failed to delete character file: ${s.message}`),{success:!1,error:s.message}}}readFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=on.join(this.charactersPath,`${e}.md`);try{return Qe.existsSync(n)?{success:!0,content:Qe.readFileSync(n,"utf-8")}:{success:!1,error:"Character not found"}}catch(s){return u.error(`[Characters] Failed to read character file: ${s.message}`),{success:!1,error:s.message}}}exists(e){if(!this.validateFilename(e).valid)return!1;let n=on.join(this.charactersPath,`${e}.md`);return Qe.existsSync(n)}},an=Ma.getInstance()});import{EventEmitter as Lb}from"events";var Ra,Oa,Ro,ed=F(()=>{"use strict";Zu();Le();j();Ra="orion-characters-active",Oa=class i extends Lb{static instance;state;constructor(){super(),this.state={characters:[],activeCharacterId:this.loadActiveId(),isLoading:!1,isSaving:!1,isDeleting:null,lastSynced:null}}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadActiveId(){return de.string(Ra)||null}saveActiveId(e){e?de.set(Ra,e):de.remove(Ra)}getState(){return{...this.state}}async loadCharacters(){this.state.isLoading=!0,this.emit("change",this.state);try{u.debug("[Characters] Loading characters from file system..."),an.ensureFolder();let e=an.scanFolder(),t=new Date().toISOString(),n=e.map(o=>({id:o.id,name:o.name,content:o.content,createdAt:t,updatedAt:t})),s=n.map(o=>o.id),r=this.state.activeCharacterId&&s.includes(this.state.activeCharacterId)?this.state.activeCharacterId:null;this.state={...this.state,characters:n,activeCharacterId:r,lastSynced:t,isLoading:!1},this.saveActiveId(r),this.emit("change",this.state),u.debug(`[Characters] Loaded ${n.length} characters from file system`)}catch(e){u.error(`[Characters] Failed to load characters: ${e.message}`),this.state.isLoading=!1,this.emit("change",this.state)}}async createCharacter(e,t){if(!e||e.trim()==="")return{success:!1,error:"Name is required"};if(!t||t.trim()==="")return{success:!1,error:"Content is required"};let n=e.trim(),s=t.trim();if(this.state.characters.some(r=>r.name.toLowerCase()===n.toLowerCase()))return{success:!1,error:"A character with this name already exists"};if(this.state.isSaving)return{success:!1,error:"Another operation in progress"};this.state.isSaving=!0,this.emit("change",this.state);try{let r=an.createFile(n,s);if(!r.success)return this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:r.error};let o=new Date().toISOString(),a=n,c={id:a,name:n,content:s,createdAt:o,updatedAt:o};return this.state={...this.state,characters:[...this.state.characters,c],activeCharacterId:a,isSaving:!1,lastSynced:o},this.saveActiveId(a),this.emit("change",this.state),u.debug(`[Characters] Created character: ${n}`),{success:!0,id:a}}catch(r){return u.error(`[Characters] Failed to create character: ${r.message}`),this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:r.message}}}async updateCharacter(e,t){if(!e)return{success:!1,error:"Invalid character ID"};let n=this.state.characters.find(o=>o.id===e);if(!n)return{success:!1,error:"Character not found"};let s=t.name!==void 0?t.name.trim():n.name;if(t.name!==void 0&&!s)return{success:!1,error:"Name cannot be empty"};if(s!==n.name&&this.state.characters.some(o=>o.id!==e&&o.name.toLowerCase()===s.toLowerCase()))return{success:!1,error:"A character with this name already exists"};let r=t.content!==void 0?t.content.trim():n.content;if(t.content!==void 0&&!r)return{success:!1,error:"Content cannot be empty"};if(this.state.isSaving)return{success:!1,error:"Another operation in progress"};this.state.isSaving=!0,this.emit("change",this.state);try{let o=new Date().toISOString();if(s!==n.name){an.deleteFile(e);let d=an.createFile(s,r);if(!d.success)return this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:d.error}}else{let d=an.updateFile(e,r);if(!d.success)return this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:d.error}}let a=s!==n.name?s:e,c=this.state.activeCharacterId;a!==e&&this.state.activeCharacterId===e&&(c=a);let l=this.state.characters.map(d=>d.id===e?{...d,id:a,name:s,content:r,updatedAt:o}:d);return this.state={...this.state,characters:l,activeCharacterId:c,isSaving:!1,lastSynced:o},this.saveActiveId(c),this.emit("change",this.state),u.debug(`[Characters] Updated character: ${e}${a!==e?` -> ${a}`:""}`),{success:!0}}catch(o){return u.error(`[Characters] Failed to update character: ${o.message}`),this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:o.message}}}async deleteCharacter(e){if(!e)return{success:!1,error:"Invalid character ID"};if(this.state.isDeleting!==null)return{success:!1,error:"Another delete operation in progress"};let t=this.state.characters.find(n=>n.id===e);if(!t)return{success:!1,error:"Character not found"};this.state.isDeleting=e,this.emit("change",this.state);try{let n=an.deleteFile(e);if(!n.success)return this.state.isDeleting=null,this.emit("change",this.state),{success:!1,error:n.error};let s=this.state.characters.filter(o=>o.id!==e),r=this.state.activeCharacterId===e?null:this.state.activeCharacterId;return this.state={...this.state,characters:s,activeCharacterId:r,isDeleting:null,lastSynced:new Date().toISOString()},this.saveActiveId(r),this.emit("change",this.state),u.debug(`[Characters] Deleted character: ${t.name}`),{success:!0}}catch(n){return u.error(`[Characters] Failed to delete character: ${n.message}`),this.state.isDeleting=null,this.emit("change",this.state),{success:!1,error:n.message}}}async setActiveCharacter(e){if(e===this.state.activeCharacterId){this.state.activeCharacterId=null,this.saveActiveId(null),this.emit("change",this.state),u.debug("[Characters] Deselected active character");return}if(e!==null&&!this.state.characters.find(s=>s.id===e))return;this.state.activeCharacterId=e,this.saveActiveId(e),this.emit("change",this.state);let t=e?this.state.characters.find(n=>n.id===e)?.name:"none";u.debug(`[Characters] Set active character: ${t}`)}reorderCharacters(e){let t=e.map(n=>this.state.characters.find(s=>s.id===n)).filter(n=>n!==void 0);this.state.characters=t,this.emit("change",this.state)}getActiveCharacter(){return this.state.activeCharacterId&&this.state.characters.find(e=>e.id===this.state.activeCharacterId)||null}getActiveCharacterContent(){let e=this.getActiveCharacter();return e?e.content:""}getAllCharacters(){return this.state.characters}formatCharactersForPrompt(){let{characters:e}=this.state;return e.length===0?"":`<available_characters>
2374
+ </available_guardrails>`}getGuardrailsContentMap(){return Object.fromEntries(this.state.guardrails.map(e=>[e.id,e.content]))}getGuardrailContentById(e){return this.state.guardrails.find(n=>n.id===e)?.content??null}reset(){this.state={guardrails:[],selectedGuardrailIds:[],isLoading:!1,isDeleting:null,isCreating:!1,isUpdating:null,lastSynced:null},this.saveSelectedIds([]),this.emit("change",this.state),u.debug("[Guardrails] Reset store state (files preserved)")}},os=Da.getInstance()});import Je from"fs";import cn from"path";import $b from"os";var Fb,Ma,ln,Zu=$(()=>{"use strict";z();Fb=/[/\\:*?"<>|]/g,Ma=class i{static instance;charactersPath;constructor(){this.charactersPath=cn.join($b.homedir(),".orion","characters")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.charactersPath}ensureFolder(){try{return Je.existsSync(this.charactersPath)||(Je.mkdirSync(this.charactersPath,{recursive:!0}),u.debug(`[Characters] Created characters folder: ${this.charactersPath}`)),!0}catch(e){return u.error(`[Characters] Failed to create characters folder: ${e.message}`),!1}}validateFilename(e){if(!e||typeof e!="string")return{valid:!1,error:"Character name is required"};let t=e.trim();return t===""?{valid:!1,error:"Character name cannot be empty"}:Fb.test(t)?{valid:!1,error:"Character name contains invalid characters"}:cn.join(this.charactersPath,`${t}.md`).startsWith(this.charactersPath)?{valid:!0}:{valid:!1,error:"Invalid character name (path traversal detected)"}}scanFolder(){try{this.ensureFolder();let e=Je.readdirSync(this.charactersPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=cn.join(this.charactersPath,n);try{if(!Je.statSync(s).isFile())continue;let o=Je.readFileSync(s,"utf-8"),a=n.replace(/\.md$/,"");t.push({id:a,name:a,content:o})}catch(r){u.warn(`[Characters] Failed to read character file ${n}: ${r.message}`)}}return u.debug(`[Characters] Scanned folder, found ${t.length} characters`),t}catch(e){return u.error(`[Characters] Failed to scan characters folder: ${e.message}`),[]}}createFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=e.trim(),r=cn.join(this.charactersPath,`${s}.md`);try{return this.ensureFolder(),Je.existsSync(r)?{success:!1,error:"A character with this name already exists"}:(Je.writeFileSync(r,t,"utf-8"),u.debug(`[Characters] Created character file: ${s}`),{success:!0,id:s})}catch(o){return u.error(`[Characters] Failed to create character file: ${o.message}`),{success:!1,error:o.message}}}updateFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=cn.join(this.charactersPath,`${e}.md`);try{return Je.existsSync(s)?(Je.writeFileSync(s,t,"utf-8"),u.debug(`[Characters] Updated character file: ${e}`),{success:!0}):{success:!1,error:"Character not found"}}catch(r){return u.error(`[Characters] Failed to update character file: ${r.message}`),{success:!1,error:r.message}}}deleteFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=cn.join(this.charactersPath,`${e}.md`);try{return Je.existsSync(n)?(Je.unlinkSync(n),u.debug(`[Characters] Deleted character file: ${e}`),{success:!0}):{success:!1,error:"Character not found"}}catch(s){return u.error(`[Characters] Failed to delete character file: ${s.message}`),{success:!1,error:s.message}}}readFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=cn.join(this.charactersPath,`${e}.md`);try{return Je.existsSync(n)?{success:!0,content:Je.readFileSync(n,"utf-8")}:{success:!1,error:"Character not found"}}catch(s){return u.error(`[Characters] Failed to read character file: ${s.message}`),{success:!1,error:s.message}}}exists(e){if(!this.validateFilename(e).valid)return!1;let n=cn.join(this.charactersPath,`${e}.md`);return Je.existsSync(n)}},ln=Ma.getInstance()});import{EventEmitter as Lb}from"events";var Ra,Oa,Ro,ed=$(()=>{"use strict";Zu();Ue();z();Ra="orion-characters-active",Oa=class i extends Lb{static instance;state;constructor(){super(),this.state={characters:[],activeCharacterId:this.loadActiveId(),isLoading:!1,isSaving:!1,isDeleting:null,lastSynced:null}}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadActiveId(){return de.string(Ra)||null}saveActiveId(e){e?de.set(Ra,e):de.remove(Ra)}getState(){return{...this.state}}async loadCharacters(){this.state.isLoading=!0,this.emit("change",this.state);try{u.debug("[Characters] Loading characters from file system..."),ln.ensureFolder();let e=ln.scanFolder(),t=new Date().toISOString(),n=e.map(o=>({id:o.id,name:o.name,content:o.content,createdAt:t,updatedAt:t})),s=n.map(o=>o.id),r=this.state.activeCharacterId&&s.includes(this.state.activeCharacterId)?this.state.activeCharacterId:null;this.state={...this.state,characters:n,activeCharacterId:r,lastSynced:t,isLoading:!1},this.saveActiveId(r),this.emit("change",this.state),u.debug(`[Characters] Loaded ${n.length} characters from file system`)}catch(e){u.error(`[Characters] Failed to load characters: ${e.message}`),this.state.isLoading=!1,this.emit("change",this.state)}}async createCharacter(e,t){if(!e||e.trim()==="")return{success:!1,error:"Name is required"};if(!t||t.trim()==="")return{success:!1,error:"Content is required"};let n=e.trim(),s=t.trim();if(this.state.characters.some(r=>r.name.toLowerCase()===n.toLowerCase()))return{success:!1,error:"A character with this name already exists"};if(this.state.isSaving)return{success:!1,error:"Another operation in progress"};this.state.isSaving=!0,this.emit("change",this.state);try{let r=ln.createFile(n,s);if(!r.success)return this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:r.error};let o=new Date().toISOString(),a=n,c={id:a,name:n,content:s,createdAt:o,updatedAt:o};return this.state={...this.state,characters:[...this.state.characters,c],activeCharacterId:a,isSaving:!1,lastSynced:o},this.saveActiveId(a),this.emit("change",this.state),u.debug(`[Characters] Created character: ${n}`),{success:!0,id:a}}catch(r){return u.error(`[Characters] Failed to create character: ${r.message}`),this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:r.message}}}async updateCharacter(e,t){if(!e)return{success:!1,error:"Invalid character ID"};let n=this.state.characters.find(o=>o.id===e);if(!n)return{success:!1,error:"Character not found"};let s=t.name!==void 0?t.name.trim():n.name;if(t.name!==void 0&&!s)return{success:!1,error:"Name cannot be empty"};if(s!==n.name&&this.state.characters.some(o=>o.id!==e&&o.name.toLowerCase()===s.toLowerCase()))return{success:!1,error:"A character with this name already exists"};let r=t.content!==void 0?t.content.trim():n.content;if(t.content!==void 0&&!r)return{success:!1,error:"Content cannot be empty"};if(this.state.isSaving)return{success:!1,error:"Another operation in progress"};this.state.isSaving=!0,this.emit("change",this.state);try{let o=new Date().toISOString();if(s!==n.name){ln.deleteFile(e);let d=ln.createFile(s,r);if(!d.success)return this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:d.error}}else{let d=ln.updateFile(e,r);if(!d.success)return this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:d.error}}let a=s!==n.name?s:e,c=this.state.activeCharacterId;a!==e&&this.state.activeCharacterId===e&&(c=a);let l=this.state.characters.map(d=>d.id===e?{...d,id:a,name:s,content:r,updatedAt:o}:d);return this.state={...this.state,characters:l,activeCharacterId:c,isSaving:!1,lastSynced:o},this.saveActiveId(c),this.emit("change",this.state),u.debug(`[Characters] Updated character: ${e}${a!==e?` -> ${a}`:""}`),{success:!0}}catch(o){return u.error(`[Characters] Failed to update character: ${o.message}`),this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:o.message}}}async deleteCharacter(e){if(!e)return{success:!1,error:"Invalid character ID"};if(this.state.isDeleting!==null)return{success:!1,error:"Another delete operation in progress"};let t=this.state.characters.find(n=>n.id===e);if(!t)return{success:!1,error:"Character not found"};this.state.isDeleting=e,this.emit("change",this.state);try{let n=ln.deleteFile(e);if(!n.success)return this.state.isDeleting=null,this.emit("change",this.state),{success:!1,error:n.error};let s=this.state.characters.filter(o=>o.id!==e),r=this.state.activeCharacterId===e?null:this.state.activeCharacterId;return this.state={...this.state,characters:s,activeCharacterId:r,isDeleting:null,lastSynced:new Date().toISOString()},this.saveActiveId(r),this.emit("change",this.state),u.debug(`[Characters] Deleted character: ${t.name}`),{success:!0}}catch(n){return u.error(`[Characters] Failed to delete character: ${n.message}`),this.state.isDeleting=null,this.emit("change",this.state),{success:!1,error:n.message}}}async setActiveCharacter(e){if(e===this.state.activeCharacterId){this.state.activeCharacterId=null,this.saveActiveId(null),this.emit("change",this.state),u.debug("[Characters] Deselected active character");return}if(e!==null&&!this.state.characters.find(s=>s.id===e))return;this.state.activeCharacterId=e,this.saveActiveId(e),this.emit("change",this.state);let t=e?this.state.characters.find(n=>n.id===e)?.name:"none";u.debug(`[Characters] Set active character: ${t}`)}reorderCharacters(e){let t=e.map(n=>this.state.characters.find(s=>s.id===n)).filter(n=>n!==void 0);this.state.characters=t,this.emit("change",this.state)}getActiveCharacter(){return this.state.activeCharacterId&&this.state.characters.find(e=>e.id===this.state.activeCharacterId)||null}getActiveCharacterContent(){let e=this.getActiveCharacter();return e?e.content:""}getAllCharacters(){return this.state.characters}formatCharactersForPrompt(){let{characters:e}=this.state;return e.length===0?"":`<available_characters>
2375
2375
  ${e.map(n=>` <character>
2376
2376
  <id>${n.id}</id>
2377
2377
  <name>${n.name}</name>
2378
2378
  <personality>${n.content}</personality>
2379
2379
  </character>`).join(`
2380
2380
  `)}
2381
- </available_characters>`}getCharacterById(e){return this.state.characters.find(t=>t.id===e)||null}reset(){this.state={characters:[],activeCharacterId:null,isLoading:!1,isSaving:!1,isDeleting:null,lastSynced:null},this.saveActiveId(null),this.emit("change",this.state),u.debug("[Characters] Reset store state (files preserved)")}},Ro=Oa.getInstance()});var Cn={};Fe(Cn,{PersonalAgentService:()=>je});import{EventEmitter as Ub}from"events";import Na from"axios";import Bb from"http";import Wb from"https";import{v4 as cn}from"uuid";import ln from"fs";import nr from"path";import Oo from"os";var sr,je,xt=F(()=>{"use strict";Vt();Te();Jn();zn();At();j();ju();Ca();fa();Ju();ed();wa();Po();Xr();sr=class{static PARSING_ERROR_REGEX=/json|parsing|decode|format|invalid response|malformed|serialization|unexpected token/i;static NETWORK_ERROR_REGEX=/network|connection|timeout/i;static AUTH_ERROR_REGEX=/unauthorized|authentication|forbidden/i;static NETWORK_ERROR_CODES=new Set(["ECONNREFUSED","ENOTFOUND","ETIMEDOUT","ECONNRESET","ERR_NETWORK","EPIPE","EHOSTUNREACH"]);static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",n=e?.code,s=e?.status||e?.statusCode||e?.response?.status,r=String(n||""),o=Number(s);return this.PARSING_ERROR_REGEX.test(t)?"parsing":this.NETWORK_ERROR_CODES.has(r)||this.NETWORK_ERROR_REGEX.test(t)||this.AUTH_ERROR_REGEX.test(t)||o===401||o===403||r==="401"||r==="403"?"critical":"parsing"}},je=class i extends Ub{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;isStreamingActive=!1;static MAX_TOOL_CACHE_SIZE=100;static MAX_PROCESSED_IDS_SIZE=500;accumulatedToolCalls=new Map;processedToolCallIds=new Set;activeToolNames=new Set;toolArgumentsCache=new Map;baseKeepaliveTimeout=12e4;extendedKeepaliveTimeout=6e5;lastKeepaliveTime=null;keepaliveWatchdog=null;lastRequestHash=null;lastRequestTime=0;inflightRequests=new Set;storesInitialized=!1;constructor(){super(),this.authService=X.getInstance(),this.httpAgent=new Bb.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Wb.Agent({keepAlive:!0,timeout:36e5}),u.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout");let e=be.getInstance();e.on("toolExecuting",t=>{u.debug("[PERSONAL AGENT] Forwarding toolExecuting:",t.name,"args:",t.arguments?Object.keys(t.arguments):"none"),this.emit("toolExecuting",t)}),e.on("tool_completed",t=>{this.emit("tool_completed",t)}),this.initializeStores()}async initializeStores(){if(!this.storesInitialized)try{u.debug("[PERSONAL AGENT] Initializing skills, guardrails and characters stores..."),await Promise.all([Dn.loadSkills(),ss.loadGuardrails(),Ro.loadCharacters()]),this.storesInitialized=!0,u.debug("[PERSONAL AGENT] Skills, guardrails and characters stores initialized")}catch(e){u.error(`[PERSONAL AGENT] Failed to initialize stores: ${e.message}`)}}async ensureStoresLoaded(){this.storesInitialized||await this.initializeStores()}getAuthToken(){let e=this.authService.getAuthToken();return e?.token?e.token:(u.warn("[PersonalAgent] No auth token available - user may not be authenticated"),"")}async getFirebaseIdToken(){return await this.authService.getFirebaseIdToken()}getDeviceInfo(){let e=process.platform;if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux"){try{if(ln.existsSync("/etc/os-release")){let n=ln.readFileSync("/etc/os-release","utf8").match(/^ID=["']?([^"'\n]+)["']?/m);if(n)return n[1].toLowerCase()}}catch{}return"linux"}return(e||"unknown").toLowerCase()}getAppStorageInfo(){let e=Oo.homedir(),n=tr.getInstance().getWorkingDirectory()||process.cwd();return{userData:nr.join(e,".orion-cli"),downloads:n,temp:Oo.tmpdir()}}async getDeviceKnowledgeInstruction(){try{let e=Se.getKnowledgeFilePath();this.migrateDeviceKnowledgeIfNeeded(e);let t=Se.readDeviceKnowledge();return t||(u.debug("[DeviceKnowledge] File not found, creating initial knowledge file..."),await Se.initializeDeviceKnowledge(),u.debug(`[DeviceKnowledge] Initial knowledge file created at: ${e}`),t=Se.readDeviceKnowledge()||""),u.debug(`[DeviceKnowledge] Loaded device knowledge, length: ${t.length} characters`),`Current device knowledge (${e}): ${t}
2381
+ </available_characters>`}getCharacterById(e){return this.state.characters.find(t=>t.id===e)||null}reset(){this.state={characters:[],activeCharacterId:null,isLoading:!1,isSaving:!1,isDeleting:null,lastSynced:null},this.saveActiveId(null),this.emit("change",this.state),u.debug("[Characters] Reset store state (files preserved)")}},Ro=Oa.getInstance()});var In={};Le(In,{PersonalAgentService:()=>ze});import{EventEmitter as Ub}from"events";import Na from"axios";import Bb from"http";import Wb from"https";import{v4 as un}from"uuid";import dn from"fs";import sr from"path";import Oo from"os";var rr,ze,xt=$(()=>{"use strict";Xt();xe();es();Kn();At();z();ju();Ca();fa();Ju();ed();wa();Po();Yr();rr=class{static PARSING_ERROR_REGEX=/json|parsing|decode|format|invalid response|malformed|serialization|unexpected token/i;static NETWORK_ERROR_REGEX=/network|connection|timeout/i;static AUTH_ERROR_REGEX=/unauthorized|authentication|forbidden/i;static NETWORK_ERROR_CODES=new Set(["ECONNREFUSED","ENOTFOUND","ETIMEDOUT","ECONNRESET","ERR_NETWORK","EPIPE","EHOSTUNREACH"]);static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",n=e?.code,s=e?.status||e?.statusCode||e?.response?.status,r=String(n||""),o=Number(s);return this.PARSING_ERROR_REGEX.test(t)?"parsing":this.NETWORK_ERROR_CODES.has(r)||this.NETWORK_ERROR_REGEX.test(t)||this.AUTH_ERROR_REGEX.test(t)||o===401||o===403||r==="401"||r==="403"?"critical":"parsing"}},ze=class i extends Ub{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;isStreamingActive=!1;static MAX_TOOL_CACHE_SIZE=100;static MAX_PROCESSED_IDS_SIZE=500;accumulatedToolCalls=new Map;processedToolCallIds=new Set;activeToolNames=new Set;toolArgumentsCache=new Map;baseKeepaliveTimeout=12e4;extendedKeepaliveTimeout=6e5;lastKeepaliveTime=null;keepaliveWatchdog=null;lastRequestHash=null;lastRequestTime=0;inflightRequests=new Set;storesInitialized=!1;constructor(){super(),this.authService=X.getInstance(),this.httpAgent=new Bb.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Wb.Agent({keepAlive:!0,timeout:36e5}),u.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout");let e=be.getInstance();e.on("toolExecuting",t=>{u.debug("[PERSONAL AGENT] Forwarding toolExecuting:",t.name,"args:",t.arguments?Object.keys(t.arguments):"none"),this.emit("toolExecuting",t)}),e.on("tool_completed",t=>{this.emit("tool_completed",t)}),this.initializeStores()}async initializeStores(){if(!this.storesInitialized)try{u.debug("[PERSONAL AGENT] Initializing skills, guardrails and characters stores..."),await Promise.all([Rn.loadSkills(),os.loadGuardrails(),Ro.loadCharacters()]),this.storesInitialized=!0,u.debug("[PERSONAL AGENT] Skills, guardrails and characters stores initialized")}catch(e){u.error(`[PERSONAL AGENT] Failed to initialize stores: ${e.message}`)}}async ensureStoresLoaded(){this.storesInitialized||await this.initializeStores()}getAuthToken(){let e=this.authService.getAuthToken();return e?.token?e.token:(u.warn("[PersonalAgent] No auth token available - user may not be authenticated"),"")}async getFirebaseIdToken(){return await this.authService.getFirebaseIdToken()}getDeviceInfo(){let e=process.platform;if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux"){try{if(dn.existsSync("/etc/os-release")){let n=dn.readFileSync("/etc/os-release","utf8").match(/^ID=["']?([^"'\n]+)["']?/m);if(n)return n[1].toLowerCase()}}catch{}return"linux"}return(e||"unknown").toLowerCase()}getAppStorageInfo(){let e=Oo.homedir(),n=nr.getInstance().getWorkingDirectory()||process.cwd();return{userData:sr.join(e,".orion-cli"),downloads:n,temp:Oo.tmpdir()}}async getDeviceKnowledgeInstruction(){try{let e=Se.getKnowledgeFilePath();this.migrateDeviceKnowledgeIfNeeded(e);let t=Se.readDeviceKnowledge();return t||(u.debug("[DeviceKnowledge] File not found, creating initial knowledge file..."),await Se.initializeDeviceKnowledge(),u.debug(`[DeviceKnowledge] Initial knowledge file created at: ${e}`),t=Se.readDeviceKnowledge()||""),u.debug(`[DeviceKnowledge] Loaded device knowledge, length: ${t.length} characters`),`Current device knowledge (${e}): ${t}
2382
2382
 
2383
2383
  Remember to update memory about device if any new information is learned during conversation.`}catch{return`Current device knowledge (${Se.getKnowledgeFilePath()}): No specific device knowledge available.
2384
2384
 
2385
2385
  Remember to update memory about device if any new information is learned during conversation.`}}getProjectPathContext(){return`<context>
2386
- Current project path in this session: ${tr.getInstance().getWorkingDirectory()||process.cwd()}
2387
- </context>`}getDeviceKnowledgePath(){let e=nr.join(Oo.homedir(),".orion");return nr.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(ln.existsSync(e))return;let t=nr.join(Oo.homedir(),"Documents","orion","orion-device-knowledge.md");if(ln.existsSync(t)){u.info("📦 Migrating device knowledge to cross-platform location...");let n=nr.dirname(e);ln.existsSync(n)||ln.mkdirSync(n,{recursive:!0});let s=ln.readFileSync(t,"utf8");ln.writeFileSync(e,s,"utf8"),u.info(`✅ Device knowledge migrated to: ${e}`),u.info(` Old location: ${t} (can be safely deleted)`)}}catch(t){u.debug(`Migration skipped: ${t.message}`)}}static getInstance(){return i.instance||(i.instance=new i),i.instance}setToolArgsCache(e,t){let n=this.currentSessionId?`${this.currentSessionId}:${e}`:e;if(this.toolArgumentsCache.size>=i.MAX_TOOL_CACHE_SIZE){let s=this.toolArgumentsCache.keys().next().value;s&&this.toolArgumentsCache.delete(s)}this.toolArgumentsCache.set(n,t)}getToolArgsCache(e){let t=this.currentSessionId?`${this.currentSessionId}:${e}`:e;return this.toolArgumentsCache.get(t)}generateRequestHash(e,t){let n=`${e}:${t}:${Date.now()}`,s=0;for(let r=0;r<n.length;r++){let o=n.charCodeAt(r);s=(s<<5)-s+o,s=s&s}return s.toString(16)}isDuplicateRequest(e){let t=Date.now();return!!(this.lastRequestHash===e&&t-this.lastRequestTime<2e3||this.inflightRequests.has(e))}async sendMessageWithToolCalling(e,t,n,s=.7,r=!0,o,a,c){await this.ensureStoresLoaded();let l=this.generateRequestHash(e,t.length);if(this.isDuplicateRequest(l))return u.debug("[PERSONAL AGENT] Duplicate request detected, ignoring"),"";this.inflightRequests.add(l),this.lastRequestHash=l,this.lastRequestTime=Date.now(),this.currentPromptId=cn(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=n;let d=c?.crossDeviceTaskId;d&&u.debug(`[PERSONAL AGENT] Executing cross-device task: ${d}`),c?.mode==="new"&&(t=[],u.debug("[PERSONAL AGENT] Starting new conversation (cross-device mode: new)")),this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear();let g=o||this.authService.getUserId(),m=Pe.getInstance().getCurrentDeviceId();if(!m)throw u.error("No device ID available - device registration may have failed"),new Error("Device not registered - cannot submit prompt");try{if(g){let P=`tc-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;this.currentSessionId=P,u.debug("🔌 [PRE-CONNECT] ==================== WEBSOCKET PRE-CONNECT ===================="),u.debug("🔌 [PRE-CONNECT] Connecting WebSocket BEFORE HTTP request"),u.debug(`🔌 [PRE-CONNECT] - User ID: ${g}`),u.debug(`🔌 [PRE-CONNECT] - Device ID: ${m}`),u.debug(`🔌 [PRE-CONNECT] - Session ID: ${P}`),u.debug(`🔌 [PRE-CONNECT] - Composite Key: ${m}_${P}`),await be.getInstance().connectForConversation(g,P)?u.debug("✅ [PRE-CONNECT] WebSocket pre-connected successfully!"):u.warn("⚠️ [PRE-CONNECT] WebSocket pre-connect failed, will retry after HTTP response"),u.debug("🔌 [PRE-CONNECT] ==================== END PRE-CONNECT ====================")}else u.warn("⚠️ [PRE-CONNECT] No userId found, skipping WebSocket pre-connect")}catch(P){u.error(`❌ [PRE-CONNECT] WebSocket pre-connect error: ${P}`)}let h=`${this.getProjectPathContext()}
2386
+ Current project path in this session: ${nr.getInstance().getWorkingDirectory()||process.cwd()}
2387
+ </context>`}getDeviceKnowledgePath(){let e=sr.join(Oo.homedir(),".orion");return sr.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(dn.existsSync(e))return;let t=sr.join(Oo.homedir(),"Documents","orion","orion-device-knowledge.md");if(dn.existsSync(t)){u.info("📦 Migrating device knowledge to cross-platform location...");let n=sr.dirname(e);dn.existsSync(n)||dn.mkdirSync(n,{recursive:!0});let s=dn.readFileSync(t,"utf8");dn.writeFileSync(e,s,"utf8"),u.info(`✅ Device knowledge migrated to: ${e}`),u.info(` Old location: ${t} (can be safely deleted)`)}}catch(t){u.debug(`Migration skipped: ${t.message}`)}}static getInstance(){return i.instance||(i.instance=new i),i.instance}setToolArgsCache(e,t){let n=this.currentSessionId?`${this.currentSessionId}:${e}`:e;if(this.toolArgumentsCache.size>=i.MAX_TOOL_CACHE_SIZE){let s=this.toolArgumentsCache.keys().next().value;s&&this.toolArgumentsCache.delete(s)}this.toolArgumentsCache.set(n,t)}getToolArgsCache(e){let t=this.currentSessionId?`${this.currentSessionId}:${e}`:e;return this.toolArgumentsCache.get(t)}generateRequestHash(e,t){let n=`${e}:${t}:${Date.now()}`,s=0;for(let r=0;r<n.length;r++){let o=n.charCodeAt(r);s=(s<<5)-s+o,s=s&s}return s.toString(16)}isDuplicateRequest(e){let t=Date.now();return!!(this.lastRequestHash===e&&t-this.lastRequestTime<2e3||this.inflightRequests.has(e))}async sendMessageWithToolCalling(e,t,n,s=.7,r=!0,o,a,c){await this.ensureStoresLoaded();let l=this.generateRequestHash(e,t.length);if(this.isDuplicateRequest(l))return u.debug("[PERSONAL AGENT] Duplicate request detected, ignoring"),"";this.inflightRequests.add(l),this.lastRequestHash=l,this.lastRequestTime=Date.now(),this.currentPromptId=un(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=n;let d=c?.crossDeviceTaskId;d&&u.debug(`[PERSONAL AGENT] Executing cross-device task: ${d}`),c?.mode==="new"&&(t=[],u.debug("[PERSONAL AGENT] Starting new conversation (cross-device mode: new)")),this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear();let g=o||this.authService.getUserId(),m=Ae.getInstance().getCurrentDeviceId();if(!m)throw u.error("No device ID available - device registration may have failed"),new Error("Device not registered - cannot submit prompt");try{if(g){let D=`tc-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;this.currentSessionId=D,u.debug("🔌 [PRE-CONNECT] ==================== WEBSOCKET PRE-CONNECT ===================="),u.debug("🔌 [PRE-CONNECT] Connecting WebSocket BEFORE HTTP request"),u.debug(`🔌 [PRE-CONNECT] - User ID: ${g}`),u.debug(`🔌 [PRE-CONNECT] - Device ID: ${m}`),u.debug(`🔌 [PRE-CONNECT] - Session ID: ${D}`),u.debug(`🔌 [PRE-CONNECT] - Composite Key: ${m}_${D}`),await be.getInstance().connectForConversation(g,D)?u.debug("✅ [PRE-CONNECT] WebSocket pre-connected successfully!"):u.warn("⚠️ [PRE-CONNECT] WebSocket pre-connect failed, will retry after HTTP response"),u.debug("🔌 [PRE-CONNECT] ==================== END PRE-CONNECT ====================")}else u.warn("⚠️ [PRE-CONNECT] No userId found, skipping WebSocket pre-connect")}catch(D){u.error(`❌ [PRE-CONNECT] WebSocket pre-connect error: ${D}`)}let h=`${this.getProjectPathContext()}
2388
2388
 
2389
- My main prompt: ${e}`,f={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:h},...a.map(P=>({type:"image_url",image_url:{url:P}}))]:[{type:"text",text:h}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:m,model:n.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:await this.getDeviceKnowledgeInstruction(),shell_timeout_config:{activity_timeout:300,max_timeout:18e3,initial_timeout:60},timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,app_storage_info:this.getAppStorageInfo(),disabled_tools:Sa.getState().getDisabledTools(),isFocusedMode:!1,browseruse:!0,dictation:!1},y=Dn.getState(),T=Dn.formatSkillsIndexForPrompt(),x=Dn.getSkillsContentMap();if(T){f.skills_index=T,f.skills_content=x;let P=Dn.getSelectedSkillsContent();P&&(f.skills_instruction=P),u.debug(`[PERSONAL AGENT] 📚 Including ${y.skills.length} skills in request`)}let w=ss.getState(),C=ss.formatGuardrailsIndexForPrompt(),v=ss.getGuardrailsContentMap();C&&(f.guardrails_index=C,f.guardrails_content=v,u.debug(`[PERSONAL AGENT] 🛡️ Including ${w.guardrails.length} guardrails in request`));let E=ss.getAllGuardrailsContent();E&&(f.guardrails_instruction=E);let S=Ro.getActiveCharacter(),I=Ro.getActiveCharacterContent();if(S&&I&&(f.character_instruction=I,f.custom_instructions=I,u.debug(`[PERSONAL AGENT] 🎭 Including active character "${S.name}" in request`)),this.currentSessionId?(f.session_id=this.currentSessionId,u.debug(`[PERSONAL AGENT] 🔗 Including existing session_id in request: ${this.currentSessionId}`)):u.debug("[PERSONAL AGENT] 🆕 No existing session_id - backend will generate new one"),c?.conversationId)f.conversationId=c.conversationId,u.debug(`[PERSONAL AGENT] Sending request with conversationId: ${c.conversationId}`),u.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let P=t.map(R=>{let $,D=R;D.metadata?.toolResults?$=D.metadata.toolResults:D.originalContent?$=D.originalContent:$=typeof R.content=="string"?R.content:JSON.stringify(R.content);let _=[{type:"text",text:$}];return D.imageUrls&&D.imageUrls.length>0&&_.push(...D.imageUrls.map(N=>({type:"image_url",image_url:{url:N}}))),{role:R.role,content:_}});for(let R=0;R<P.length;R++)P[R].role;f.messages=P,u.debug(`[PERSONAL AGENT] Sending request with ${P.length} messages (new conversation)`)}else u.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return r?this.performStreamingToolCall(f,l):this.performNonStreamingToolCall(f,l)}async performStreamingToolCall(e,t){let n=await this.getFirebaseIdToken();return n||u.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401"),new Promise((s,r)=>{this.currentAbortController=new AbortController,this.isStreamingActive=!0;let o=[],a=Buffer.alloc(0),c="",l="",d=[],g=null,m=!1,p="";this.currentOutput="",this.completeOutputWithToolResults="";let h=new Map,f=new Set,y=new Map,T=this.authService.getUserId();Na.post(this.apiEndpoint,e,{responseType:"stream",signal:this.currentAbortController.signal,timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n||this.getAuthToken()}`}}).then(async x=>{let w=x.data;this.startKeepaliveWatchdog();let C=x.headers["x-session-id"]||x.headers["session-id"]||x.headers["X-Session-Id"];u.debug("🔍 [SESSION-ID] ==================== SESSION ID VERIFICATION ===================="),u.debug(`🔍 [SESSION-ID] Pre-connected sessionId: ${this.currentSessionId}`),u.debug(`🔍 [SESSION-ID] Backend X-Session-Id header: ${C}`),C?(g=C,this.currentSessionId&&C!==this.currentSessionId?(u.warn("⚠️ [SESSION-ID] Backend returned different sessionId!"),u.warn(`⚠️ [SESSION-ID] - We sent: ${this.currentSessionId}`),u.warn(`⚠️ [SESSION-ID] - Backend returned: ${C}`),u.warn("⚠️ [SESSION-ID] Using backend sessionId and reconnecting WebSocket..."),this.currentSessionId=C,await be.getInstance().connectForConversation(T||"",C)?u.debug("✅ [WEBSOCKET] Reconnected with backend sessionId"):u.error("❌ [WEBSOCKET] Failed to reconnect with backend sessionId")):this.currentSessionId?u.debug("✅ [SESSION-ID] Backend confirmed our sessionId - WebSocket already connected!"):(u.debug("🔌 [WEBSOCKET] No pre-connect, connecting now with backend sessionId"),this.currentSessionId=C,await be.getInstance().connectForConversation(T||"",C)?u.debug("✅ [WEBSOCKET] Connected with backend sessionId"):u.error("❌ [WEBSOCKET] Failed to connect with backend sessionId"))):(u.error("❌ [SESSION-ID] ==================== ERROR ===================="),u.error("❌ [SESSION-ID] ✗ No X-Session-Id header found in response!"),this.currentSessionId?u.debug(`ℹ️ [SESSION-ID] Using pre-connected sessionId: ${this.currentSessionId}`):u.error("❌ [SESSION-ID] No sessionId available - tools may fail!")),u.debug("🔍 [SESSION-ID] ==================== END SESSION ID CHECK ===================="),w.on("data",v=>{this.updateKeepaliveTimer("stream chunk");try{a=Buffer.concat([a,v]);let P=a.length,R=Math.max(0,a.length-3);for(let $=a.length-1;$>=R;$--){let D=a[$];if((D&192)===128)continue;let _=D,N=1;(_&128)===0?N=1:(_&224)===192?N=2:(_&240)===224?N=3:(_&248)===240&&(N=4),a.length-$<N&&(P=$);break}if(P>0){let $=a.slice(0,P);a=a.slice(P),o.push($.toString("utf8"))}}catch{o.push(v.toString())}let E=o.join("");o.length=0;let S=E.split(/\r?\n/),I=S.pop()||"";I&&o.push(I);for(let P of S){let R=P.trim();if(R){if(R.startsWith(":")){R.includes("keepalive")&&this.updateKeepaliveTimer("SSE comment keepalive");continue}if(R.startsWith("event: keepalive")){this.updateKeepaliveTimer("explicit keepalive event"),this.emit("keepalive");continue}if(R.startsWith("data: ")){let $=R.slice(6).trim();if($==="[DONE]"){this.stopKeepaliveWatchdog(),this.handleConversationComplete(),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),this.emit("done"),this.emit("BotResponseCompleted",c),s(c);return}try{let D=JSON.parse($);if(D.type==="session_start"&&D.conversationId){let _=D.conversationId,N=D.isNewConversation||!1,k=D.title;u.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),u.debug(`[PERSONAL AGENT] conversationId: ${_}`),u.debug(`[PERSONAL AGENT] isNewConversation: ${N}`),k&&u.debug(`[PERSONAL AGENT] title: "${k}"`),D.sessionId&&!this.currentSessionId&&this.isStreamingActive&&(u.debug("🔍 [SESSION-ID] ==================== SESSION ID FROM SSE ===================="),u.debug(`🔍 [SESSION-ID] Found sessionId in session_start event: ${D.sessionId}`),u.debug("🔍 [SESSION-ID] This is a fallback for clients when header is not accessible"),this.currentSessionId=D.sessionId,be.getInstance().connectForConversation(T||"",D.sessionId).then(L=>{L?u.debug("✅ [WEBSOCKET] Connected via SSE fallback sessionId"):u.error("❌ [WEBSOCKET] Failed to connect via SSE fallback sessionId")}).catch(L=>{u.error(`❌ [WEBSOCKET] Connection error via SSE fallback: ${L}`)}),u.debug("🔍 [SESSION-ID] ==================== END SSE FALLBACK ====================")),this.emit("conversation_id_received",{conversationId:_,isNew:N,title:k||void 0});continue}if(D.type==="title_generated"&&D.title&&D.conversationId){let _=D.title,N=D.conversationId;u.debug("[PERSONAL AGENT] Received title_generated event!"),u.debug(`[PERSONAL AGENT] conversationId: ${N}`),u.debug(`[PERSONAL AGENT] title: "${_}"`),this.emit("conversation_title_updated",{conversationId:N,title:_});continue}if(D.type==="error"||D.error){let _=D.error||D,N=_.message||"Unknown error occurred",k=_.status||500,M=_.provider||"unknown";u.debug(`[PERSONAL AGENT] API Error - Status: ${k}, Provider: ${M}`),u.debug(`[PERSONAL AGENT] Error Message: ${N}`);let L=N;try{let H=JSON.parse(N);H.error?.message&&(L=H.error.message)}catch{}let B;k===503?B=`Service Temporarily Unavailable: The AI model is currently experiencing high demand. Please try again in a few moments.
2389
+ My main prompt: ${e}`,f={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:h},...a.map(D=>({type:"image_url",image_url:{url:D}}))]:[{type:"text",text:h}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:m,model:n.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:await this.getDeviceKnowledgeInstruction(),shell_timeout_config:{activity_timeout:300,max_timeout:18e3,initial_timeout:60},timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,app_storage_info:this.getAppStorageInfo(),disabled_tools:Sa.getState().getDisabledTools(),isFocusedMode:!1,browseruse:!0,dictation:!1},y=Rn.getState(),T=Rn.formatSkillsIndexForPrompt(),C=Rn.getSkillsContentMap();if(T){f.skills_index=T,f.skills_content=C;let D=Rn.getSelectedSkillsContent();D&&(f.skills_instruction=D),u.debug(`[PERSONAL AGENT] 📚 Including ${y.skills.length} skills in request`)}let w=os.getState(),E=os.formatGuardrailsIndexForPrompt(),v=os.getGuardrailsContentMap();E&&(f.guardrails_index=E,f.guardrails_content=v,u.debug(`[PERSONAL AGENT] 🛡️ Including ${w.guardrails.length} guardrails in request`));let x=os.getAllGuardrailsContent();x&&(f.guardrails_instruction=x);let S=Ro.getActiveCharacter(),I=Ro.getActiveCharacterContent();if(S&&I&&(f.character_instruction=I,f.custom_instructions=I,u.debug(`[PERSONAL AGENT] 🎭 Including active character "${S.name}" in request`)),this.currentSessionId?(f.session_id=this.currentSessionId,u.debug(`[PERSONAL AGENT] 🔗 Including existing session_id in request: ${this.currentSessionId}`)):u.debug("[PERSONAL AGENT] 🆕 No existing session_id - backend will generate new one"),c?.conversationId)f.conversationId=c.conversationId,u.debug(`[PERSONAL AGENT] Sending request with conversationId: ${c.conversationId}`),u.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let D=t.map(M=>{let _,F=M;F.metadata?.toolResults?_=F.metadata.toolResults:F.originalContent?_=F.originalContent:_=typeof M.content=="string"?M.content:JSON.stringify(M.content);let R=[{type:"text",text:_}];return F.imageUrls&&F.imageUrls.length>0&&R.push(...F.imageUrls.map(N=>({type:"image_url",image_url:{url:N}}))),{role:M.role,content:R}});for(let M=0;M<D.length;M++)D[M].role;f.messages=D,u.debug(`[PERSONAL AGENT] Sending request with ${D.length} messages (new conversation)`)}else u.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return r?this.performStreamingToolCall(f,l):this.performNonStreamingToolCall(f,l)}async performStreamingToolCall(e,t){let n=await this.getFirebaseIdToken();return n||u.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401"),new Promise((s,r)=>{this.currentAbortController=new AbortController,this.isStreamingActive=!0;let o=[],a=[],c=0,l="",d="",g=[],m=null,p=!1,h="";this.currentOutput="",this.completeOutputWithToolResults="";let f=new Map,y=new Set,T=new Map,C=this.authService.getUserId();Na.post(this.apiEndpoint,e,{responseType:"stream",signal:this.currentAbortController.signal,timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n||this.getAuthToken()}`}}).then(async w=>{let E=w.data;this.startKeepaliveWatchdog();let v=w.headers["x-session-id"]||w.headers["session-id"]||w.headers["X-Session-Id"];u.debug("🔍 [SESSION-ID] ==================== SESSION ID VERIFICATION ===================="),u.debug(`🔍 [SESSION-ID] Pre-connected sessionId: ${this.currentSessionId}`),u.debug(`🔍 [SESSION-ID] Backend X-Session-Id header: ${v}`),v?(m=v,this.currentSessionId&&v!==this.currentSessionId?(u.warn("⚠️ [SESSION-ID] Backend returned different sessionId!"),u.warn(`⚠️ [SESSION-ID] - We sent: ${this.currentSessionId}`),u.warn(`⚠️ [SESSION-ID] - Backend returned: ${v}`),u.warn("⚠️ [SESSION-ID] Using backend sessionId and reconnecting WebSocket..."),this.currentSessionId=v,await be.getInstance().connectForConversation(C||"",v)?u.debug("✅ [WEBSOCKET] Reconnected with backend sessionId"):u.error("❌ [WEBSOCKET] Failed to reconnect with backend sessionId")):this.currentSessionId?u.debug("✅ [SESSION-ID] Backend confirmed our sessionId - WebSocket already connected!"):(u.debug("🔌 [WEBSOCKET] No pre-connect, connecting now with backend sessionId"),this.currentSessionId=v,await be.getInstance().connectForConversation(C||"",v)?u.debug("✅ [WEBSOCKET] Connected with backend sessionId"):u.error("❌ [WEBSOCKET] Failed to connect with backend sessionId"))):(u.error("❌ [SESSION-ID] ==================== ERROR ===================="),u.error("❌ [SESSION-ID] ✗ No X-Session-Id header found in response!"),this.currentSessionId?u.debug(`ℹ️ [SESSION-ID] Using pre-connected sessionId: ${this.currentSessionId}`):u.error("❌ [SESSION-ID] No sessionId available - tools may fail!")),u.debug("🔍 [SESSION-ID] ==================== END SESSION ID CHECK ===================="),E.on("data",x=>{this.updateKeepaliveTimer("stream chunk");try{a.push(x),c+=x.length;let M=c>0?Buffer.concat(a):Buffer.alloc(0);a=[],c=0;let _=M.length,F=Math.max(0,M.length-3);for(let R=M.length-1;R>=F;R--){let N=M[R];if((N&192)===128)continue;let k=N,P=1;(k&128)===0?P=1:(k&224)===192?P=2:(k&240)===224?P=3:(k&248)===240&&(P=4),M.length-R<P&&(_=R);break}if(_>0){let R=M.slice(0,_);_<M.length&&(a.push(M.slice(_)),c=M.length-_),o.push(R.toString("utf8"))}}catch{o.push(x.toString())}let S=o.join("");o.length=0;let I=S.split(/\r?\n/),D=I.pop()||"";D&&o.push(D);for(let M of I){let _=M.trim();if(_){if(_.startsWith(":")){_.includes("keepalive")&&this.updateKeepaliveTimer("SSE comment keepalive");continue}if(_.startsWith("event: keepalive")){this.updateKeepaliveTimer("explicit keepalive event"),this.emit("keepalive");continue}if(_.startsWith("data: ")){let F=_.slice(6).trim();if(F==="[DONE]"){this.stopKeepaliveWatchdog(),this.handleConversationComplete(),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),this.emit("done"),this.emit("BotResponseCompleted",l),s(l);return}try{let R=JSON.parse(F);if(R.type==="session_start"&&R.conversationId){let N=R.conversationId,k=R.isNewConversation||!1,P=R.title;u.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),u.debug(`[PERSONAL AGENT] conversationId: ${N}`),u.debug(`[PERSONAL AGENT] isNewConversation: ${k}`),P&&u.debug(`[PERSONAL AGENT] title: "${P}"`),R.sessionId&&!this.currentSessionId&&this.isStreamingActive&&(u.debug("🔍 [SESSION-ID] ==================== SESSION ID FROM SSE ===================="),u.debug(`🔍 [SESSION-ID] Found sessionId in session_start event: ${R.sessionId}`),u.debug("🔍 [SESSION-ID] This is a fallback for clients when header is not accessible"),this.currentSessionId=R.sessionId,be.getInstance().connectForConversation(C||"",R.sessionId).then(L=>{L?u.debug("✅ [WEBSOCKET] Connected via SSE fallback sessionId"):u.error("❌ [WEBSOCKET] Failed to connect via SSE fallback sessionId")}).catch(L=>{u.error(`❌ [WEBSOCKET] Connection error via SSE fallback: ${L}`)}),u.debug("🔍 [SESSION-ID] ==================== END SSE FALLBACK ====================")),this.emit("conversation_id_received",{conversationId:N,isNew:k,title:P||void 0});continue}if(R.type==="title_generated"&&R.title&&R.conversationId){let N=R.title,k=R.conversationId;u.debug("[PERSONAL AGENT] Received title_generated event!"),u.debug(`[PERSONAL AGENT] conversationId: ${k}`),u.debug(`[PERSONAL AGENT] title: "${N}"`),this.emit("conversation_title_updated",{conversationId:k,title:N});continue}if(R.type==="error"||R.error){let N=R.error||R,k=N.message||"Unknown error occurred",P=N.status||500,B=N.provider||"unknown";u.debug(`[PERSONAL AGENT] API Error - Status: ${P}, Provider: ${B}`),u.debug(`[PERSONAL AGENT] Error Message: ${k}`);let L=k;try{let G=JSON.parse(k);G.error?.message&&(L=G.error.message)}catch{}let W;P===503?W=`Service Temporarily Unavailable: The AI model is currently experiencing high demand. Please try again in a few moments.
2390
2390
 
2391
- Details: ${L}`:k>=500?B=`Server Error (${k}): The AI service encountered an internal error. Please try again.
2391
+ Details: ${L}`:P>=500?W=`Server Error (${P}): The AI service encountered an internal error. Please try again.
2392
2392
 
2393
- Details: ${L}`:k===429?B="Rate Limit Exceeded: You've made too many requests. Please wait a moment before trying again.":B=`Error: ${L}`,this.emit("api_error",{status:k,provider:M,message:B,originalMessage:N}),l+=B+`
2394
- `,this.currentOutput+=B+`
2395
- `;continue}if(D.tool_response&&D.tool_response.content){this.updateKeepaliveTimer("tool_response event (top-level)");let _=D.tool_response.content,N=D.tool_response.id||"unknown",k=D.tool_response.name||"unknown",M=this.getToolArgsCache(N);if(this.emit("tool_completed",{toolName:k,toolId:N,result:_,todos:D.tool_response.todos||null,arguments:M}),this.emit("toolComplete",k),u.debug("[TODO-DEBUG] Checking tool_response for todos..."),u.debug("[TODO-DEBUG] Tool name:",k),u.debug("[TODO-DEBUG] tool_response keys:",Object.keys(D.tool_response).sort()),D.tool_response.todos&&Array.isArray(D.tool_response.todos))u.debug("[TODO-DEBUG] ✅ Found todos in tool_response:",D.tool_response.todos.length,"items"),this.handleTodoUpdate({items:D.tool_response.todos});else if(u.debug("[TODO-DEBUG] ❌ No todos key in tool_response"),k.toLowerCase()==="todowrite"||k.toLowerCase()==="todo_write"){u.debug("[TODO-DEBUG] This is a TodoWrite tool, checking content for todos...");try{let H=null;if(typeof _=="string"){let V=JSON.parse(_);H=V.todos||V}else if(Array.isArray(_)){let V=_[0];V&&(V.content||V.text||V.status)&&(H=_)}H&&Array.isArray(H)&&(u.debug("[TODO-DEBUG] ✅ Extracted todos from content:",H.length,"items"),this.handleTodoUpdate({items:H}))}catch(H){u.debug("[TODO-DEBUG] Could not parse todos from content:",H)}}let L="";Array.isArray(_)?L=_.map(H=>typeof H=="string"?H:H&&typeof H=="object"&&(H.text||H.content)||"").join(""):typeof _=="string"?L=_:L=JSON.stringify(_),(!L||L.trim().length===0)&&(L="(empty tool result)");let B=`<context>
2393
+ Details: ${L}`:P===429?W="Rate Limit Exceeded: You've made too many requests. Please wait a moment before trying again.":W=`Error: ${L}`,this.emit("api_error",{status:P,provider:B,message:W,originalMessage:k}),d+=W+`
2394
+ `,this.currentOutput+=W+`
2395
+ `;continue}if(R.tool_response&&R.tool_response.content){this.updateKeepaliveTimer("tool_response event (top-level)");let N=R.tool_response.content,k=R.tool_response.id||"unknown",P=R.tool_response.name||"unknown",B=this.getToolArgsCache(k);if(this.emit("tool_completed",{toolName:P,toolId:k,result:N,todos:R.tool_response.todos||null,arguments:B}),this.emit("toolComplete",P),u.debug("[TODO-DEBUG] Checking tool_response for todos..."),u.debug("[TODO-DEBUG] Tool name:",P),u.debug("[TODO-DEBUG] tool_response keys:",Object.keys(R.tool_response).sort()),R.tool_response.todos&&Array.isArray(R.tool_response.todos))u.debug("[TODO-DEBUG] ✅ Found todos in tool_response:",R.tool_response.todos.length,"items"),this.handleTodoUpdate({items:R.tool_response.todos});else if(u.debug("[TODO-DEBUG] ❌ No todos key in tool_response"),P.toLowerCase()==="todowrite"||P.toLowerCase()==="todo_write"){u.debug("[TODO-DEBUG] This is a TodoWrite tool, checking content for todos...");try{let G=null;if(typeof N=="string"){let Y=JSON.parse(N);G=Y.todos||Y}else if(Array.isArray(N)){let Y=N[0];Y&&(Y.content||Y.text||Y.status)&&(G=N)}G&&Array.isArray(G)&&(u.debug("[TODO-DEBUG] ✅ Extracted todos from content:",G.length,"items"),this.handleTodoUpdate({items:G}))}catch(G){u.debug("[TODO-DEBUG] Could not parse todos from content:",G)}}let L="";Array.isArray(N)?L=N.map(G=>typeof G=="string"?G:G&&typeof G=="object"&&(G.text||G.content)||"").join(""):typeof N=="string"?L=N:L=JSON.stringify(N),(!L||L.trim().length===0)&&(L="(empty tool result)");let W=`<context>
2396
2396
  ${L}
2397
- </context>`;d.push(B),c+=B+`
2398
- `,this.completeOutputWithToolResults+=B+`
2399
- `,this.currentOutput+=B+`
2400
- `;continue}if(D.tool_calls){this.updateKeepaliveTimer("tool_calls event"),u.debug("Processing tool calls:",D.tool_calls.length,"items");for(let[_,N]of D.tool_calls.entries()){u.debug("Tool call ["+_+"]:");let k=N.id,M=N.index??_;if(k&&M!==void 0?(y.set(M,k),u.debug(`Mapped index ${M} -> id ${k}`)):!k&&M!==void 0&&(k=y.get(M),k&&u.debug(`Resolved index ${M} -> id ${k}`)),k){u.debug("Processing tool call ID:",k);let L=h.get(k)||{};for(let[B,H]of Object.entries(N))if(B==="function"&&typeof H=="object"&&H!==null){let V=L.function||{},le=H;for(let[W,G]of Object.entries(le))if(W==="arguments"&&typeof G=="string"){let tt=V.arguments||"";V.arguments=tt+G}else V[W]=G;L.function=V}else L[B]=H;if(h.set(k,L),L.function?.name&&!f.has(k)){let B=L.function.name;f.add(k),this.activeToolNames.add(B),u.debug("[TOOL-DISPLAY] Tool started:",B,"ID:",k);let H;if(L.function?.arguments)try{H=JSON.parse(L.function.arguments),this.setToolArgsCache(k,H)}catch{}this.emit("toolExecuting",{toolCallId:k,name:B,arguments:H,startTime:new Date})}if(L.function?.name&&L.function?.arguments){let B=L.function.arguments,H=`args-${k}`;if((B.endsWith("}")||B.endsWith('"}'))&&!f.has(H))try{let V=JSON.parse(B);f.add(H),this.setToolArgsCache(k,V),u.debug("[TOOL-DISPLAY] Args complete for:",L.function.name,"ID:",k),this.emit("tool_args_update",{toolCallId:k,arguments:V})}catch{}}if(L.function?.arguments&&L.function?.name){let B=L.function.arguments;B.endsWith("}")||B.endsWith('"}')?(u.debug("Complete tool call accumulated:",k,"-",L.function.name),u.debug("Arguments:",B.substring(0,100)+(B.length>100?"...":"")),f.has(k)||(f.add(k),this.handleCompleteToolCall(L))):u.debug("Partial tool call:",k,"-",L.function.name)}}}}else if(D.tool_response&&D.tool_response.content){this.updateKeepaliveTimer("tool_response event");let _=D.tool_response.content,N=D.tool_response.id||"unknown",k=D.tool_response.name||"unknown",M=D.tool_response.role||"unknown";u.debug("[PERSONAL AGENT] TOOL RESPONSE RECEIVED:"),u.debug(" Tool ID:",N),u.debug(" Tool Name:",k),u.debug(" Tool Role:",M),u.debug(" Content Length:",_.length),u.debug(" Content Preview:",_.substring(0,200)+"..."),this.activeToolNames.delete(k);let L=this.getToolArgsCache(N);this.emit("tool_completed",{toolName:k,toolId:N,result:_,todos:D.tool_response.todos||null,arguments:L}),this.emit("toolComplete",k),D.tool_response.todos&&Array.isArray(D.tool_response.todos)&&(u.debug("[PERSONAL AGENT] Tool response contains",D.tool_response.todos.length,"todo items"),this.handleTodoUpdate({items:D.tool_response.todos}));let B=`<context>
2401
- ${_}
2402
- </context>`;d.push(B),c+=B+`
2403
- `,this.completeOutputWithToolResults+=B+`
2404
- `,this.currentOutput+=B+`
2405
- `,u.debug("[PERSONAL AGENT] Stored tool result (hidden from user) - Total tool results:",d.length)}else if(D.content!==void 0){let _=D.content;if(_&&_.length>0&&u.debug(`[STREAMING] Received content chunk: "${_}" (length: ${_.length})`),_&&_.includes('{"tool_response"'))try{let N,k=!1;try{N=JSON.parse(_),k=!0}catch{let M=_.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(M){let L=M[0];N=JSON.parse(L),k=!1}}if(N&&N.tool_response&&N.tool_response.content){let M=N.tool_response.content,L=N.tool_response.id||"unknown",B=N.tool_response.name||"unknown",H=this.getToolArgsCache(L);this.emit("tool_completed",{toolName:B,toolId:L,result:M,todos:N.tool_response.todos||null,arguments:H}),this.emit("toolComplete",B),N.tool_response.todos&&Array.isArray(N.tool_response.todos)&&this.handleTodoUpdate({items:N.tool_response.todos});let V="";Array.isArray(M)?V=M.map(W=>W.text||"").join(""):typeof M=="string"?V=M:V=JSON.stringify(M);let le=`<context>
2406
- ${V}
2407
- </context>`;if(d.push(le),c+=le+`
2408
- `,this.completeOutputWithToolResults+=le+`
2409
- `,this.currentOutput+=le+`
2410
- `,!k){let W=_.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(W){let G=_.replace(W[0],"").trim();if(G.length>0){c+=G,l+=G,this.currentOutput+=G,this.completeOutputWithToolResults+=G;let tt=sn.remove(G);this.emit("data",tt)}}}continue}}catch{}if(_.includes("<think>")){m=!0;let N=_.split("<think>")[0];if(N){c+=N,l+=N,this.currentOutput+=N,this.completeOutputWithToolResults+=N;let k=sn.remove(N);this.emit("data",k)}}else if(_.includes("</think>")){m=!1,p+=_.split("</think>")[0],this.emit("thinking",p),p="";let N=_.split("</think>")[1]||"";if(N){c+=N,l+=N,this.currentOutput+=N,this.completeOutputWithToolResults+=N;let k=sn.remove(N);this.emit("data",k)}}else if(m)p+=_,this.emit("thinking",p);else{c+=_,l+=_,this.currentOutput+=_,this.completeOutputWithToolResults+=_;let N=sn.remove(_);this.emit("data",N)}}else if(D.type==="checkpoint_reached"||D.event==="checkpoint_reached")u.debug("[CHECKPOINT] Backend reached checkpoint, processing queued messages as feedback"),this.handleCheckpointReached();else if(D.type==="todo_update")this.handleTodoUpdate(D.data);else if(D.type==="todo_list")this.handleTodoUpdate({items:D.todos});else if(D.type==="webview_update")this.handleWebViewUpdate(D.data);else if(D.type==="operator_progress")this.handleOperatorProgress(D.data);else if(D.type==="context_compaction_starting"||D.type==="manual_compaction_starting")u.debug("[COMPACTION] Starting:",D.message),this.emit("compaction_status",{status:"starting",conversationPercentage:D.conversationPercentage||D.percentage,message:D.message});else if(D.type==="context_compaction_complete"||D.type==="manual_compaction_complete")u.debug("[COMPACTION] Complete:",D.message),this.emit("compaction_status",{status:"complete",originalTokens:D.originalTokens,compactedTokens:D.compactedTokens,compressionRatio:D.compressionRatio,message:D.message});else if(D.type==="compaction_failed")u.debug("[COMPACTION] Failed:",D.message),this.emit("compaction_status",{status:"failed",error:D.error,message:D.message});else if(D.type==="stop"){this.handleStop(D.data),this.stopKeepaliveWatchdog(),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),this.emit("done"),s(c);return}}catch{u.debug("Treating as plain text"),c+=$,l+=$,this.currentOutput+=$,this.completeOutputWithToolResults+=$;let _=sn.remove($);this.emit("data",_)}}}}}),w.on("end",()=>{this.stopKeepaliveWatchdog(),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),this.emit("done"),s(c)}),w.on("error",v=>{switch(this.stopKeepaliveWatchdog(),u.debug("Streaming error, disconnecting WebSocket and cleaning up"),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),sr.classify(v)){case"parsing":let S={type:"tool_result",tool_call_id:`error_${cn()}`,error:!0,content:`Streaming parsing error occurred: ${v.message}. Please check response format and retry.`};u.debug("🔄 [PERSONAL AGENT] Parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(S)),be.getInstance().handleConversationComplete(),s(c);return;case"critical":be.getInstance().handleConversationComplete(),this.emit("error",v),r(v);break}})}).catch(x=>{if(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),x.code==="ERR_CANCELED")u.debug("Task was cancelled, disconnecting WebSocket"),be.getInstance().handleConversationComplete(),this.emit("canceled"),s(c);else switch(sr.classify(x)){case"parsing":let C={type:"tool_result",tool_call_id:`error_${cn()}`,error:!0,content:`Request parsing error: ${x.message}. Please check request format and retry.`};u.debug("🔄 [PERSONAL AGENT] Request parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(C)),be.getInstance().handleConversationComplete(),s(c);break;case"critical":u.debug("Request failed, disconnecting WebSocket"),be.getInstance().handleConversationComplete(),r(x);break}})})}async performNonStreamingToolCall(e,t){try{let n=await this.getFirebaseIdToken();n||u.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401");let s=await Na.post(this.apiEndpoint,e,{timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n||this.getAuthToken()}`}});if(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),s.data?.content){if(this.currentOutput=s.data.content,this.completeOutputWithToolResults=s.data.completeOutput||s.data.content,s.data.toolResults)for(let r of s.data.toolResults)this.handleToolResult(r.tool,r.result);return s.data.content}throw new Error("No response content received")}catch(n){switch(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),sr.classify(n)){case"parsing":let r={type:"tool_result",tool_call_id:`error_${cn()}`,error:!0,content:`Non-streaming API parsing error: ${n.message}. Please check request format and retry.`};return u.debug("🔄 [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",n),new Error(`Tool calling API Error: ${n.message}`)}}}handleCompleteToolCall(e){this.emit("tool_use",e);let t=e.function?.name||"unknown",n=null;if(e.function?.arguments)try{n=JSON.parse(e.function.arguments)}catch{u.debug("[PERSONAL AGENT] Failed to parse tool arguments:",e.function.arguments);return}n&&this.setToolArgsCache(e.id,n),this.emit("toolExecuting",{toolCallId:e.id,name:t,arguments:n,startTime:new Date}),this.executeToolViaWebSocket(e.id,t,n)}async executeToolViaWebSocket(e,t,n){try{let s=be.getInstance(),r={id:e,tool_name:t,arguments:n||{},tool_call_id:e};await s.sendToolRequest(r)}catch(s){u.debug(`Failed to execute tool via WebSocket: ${s.message}`)}}handleToolResult(e,t){this.emit("tool_result",{tool:e,result:t}),u.debug(`Tool Result: ${e.name}`),t&&u.debug(` Result: ${JSON.stringify(t,null,2)}`)}handleWebSocketToolResponse(e){let{tool_name:t,content:n,success:s,error:r}=e;if(u.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",s),s&&n){let a=`<context>
2397
+ </context>`;g.push(W),l+=W+`
2398
+ `,this.completeOutputWithToolResults+=W+`
2399
+ `,this.currentOutput+=W+`
2400
+ `;continue}if(R.tool_calls){this.updateKeepaliveTimer("tool_calls event"),u.debug("Processing tool calls:",R.tool_calls.length,"items");for(let[N,k]of R.tool_calls.entries()){u.debug("Tool call ["+N+"]:");let P=k.id,B=k.index??N;if(P&&B!==void 0?(T.set(B,P),u.debug(`Mapped index ${B} -> id ${P}`)):!P&&B!==void 0&&(P=T.get(B),P&&u.debug(`Resolved index ${B} -> id ${P}`)),P){u.debug("Processing tool call ID:",P);let L=f.get(P)||{};for(let[W,G]of Object.entries(k))if(W==="function"&&typeof G=="object"&&G!==null){let Y=L.function||{},H=G;for(let[j,Te]of Object.entries(H))if(j==="arguments"&&typeof Te=="string"){let Ft=Y.arguments||"";Y.arguments=Ft+Te}else Y[j]=Te;L.function=Y}else L[W]=G;if(f.set(P,L),L.function?.name&&!y.has(P)){let W=L.function.name;y.add(P),this.activeToolNames.add(W),u.debug("[TOOL-DISPLAY] Tool started:",W,"ID:",P);let G;if(L.function?.arguments)try{G=JSON.parse(L.function.arguments),this.setToolArgsCache(P,G)}catch{}this.emit("toolExecuting",{toolCallId:P,name:W,arguments:G,startTime:new Date})}if(L.function?.name&&L.function?.arguments){let W=L.function.arguments,G=`args-${P}`;if((W.endsWith("}")||W.endsWith('"}'))&&!y.has(G))try{let Y=JSON.parse(W);y.add(G),this.setToolArgsCache(P,Y),u.debug("[TOOL-DISPLAY] Args complete for:",L.function.name,"ID:",P),this.emit("tool_args_update",{toolCallId:P,arguments:Y})}catch{}}if(L.function?.arguments&&L.function?.name){let W=L.function.arguments;W.endsWith("}")||W.endsWith('"}')?(u.debug("Complete tool call accumulated:",P,"-",L.function.name),u.debug("Arguments:",W.substring(0,100)+(W.length>100?"...":"")),y.has(P)||(y.add(P),this.handleCompleteToolCall(L))):u.debug("Partial tool call:",P,"-",L.function.name)}}}}else if(R.tool_response&&R.tool_response.content){this.updateKeepaliveTimer("tool_response event");let N=R.tool_response.content,k=R.tool_response.id||"unknown",P=R.tool_response.name||"unknown",B=R.tool_response.role||"unknown";u.debug("[PERSONAL AGENT] TOOL RESPONSE RECEIVED:"),u.debug(" Tool ID:",k),u.debug(" Tool Name:",P),u.debug(" Tool Role:",B),u.debug(" Content Length:",N.length),u.debug(" Content Preview:",N.substring(0,200)+"..."),this.activeToolNames.delete(P);let L=this.getToolArgsCache(k);this.emit("tool_completed",{toolName:P,toolId:k,result:N,todos:R.tool_response.todos||null,arguments:L}),this.emit("toolComplete",P),R.tool_response.todos&&Array.isArray(R.tool_response.todos)&&(u.debug("[PERSONAL AGENT] Tool response contains",R.tool_response.todos.length,"todo items"),this.handleTodoUpdate({items:R.tool_response.todos}));let W=`<context>
2401
+ ${N}
2402
+ </context>`;g.push(W),l+=W+`
2403
+ `,this.completeOutputWithToolResults+=W+`
2404
+ `,this.currentOutput+=W+`
2405
+ `,u.debug("[PERSONAL AGENT] Stored tool result (hidden from user) - Total tool results:",g.length)}else if(R.content!==void 0){let N=R.content;if(N&&N.length>0&&u.debug(`[STREAMING] Received content chunk: "${N}" (length: ${N.length})`),N&&N.includes('{"tool_response"'))try{let k,P=!1;try{k=JSON.parse(N),P=!0}catch{let B=N.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(B){let L=B[0];k=JSON.parse(L),P=!1}}if(k&&k.tool_response&&k.tool_response.content){let B=k.tool_response.content,L=k.tool_response.id||"unknown",W=k.tool_response.name||"unknown",G=this.getToolArgsCache(L);this.emit("tool_completed",{toolName:W,toolId:L,result:B,todos:k.tool_response.todos||null,arguments:G}),this.emit("toolComplete",W),k.tool_response.todos&&Array.isArray(k.tool_response.todos)&&this.handleTodoUpdate({items:k.tool_response.todos});let Y="";Array.isArray(B)?Y=B.map(j=>j.text||"").join(""):typeof B=="string"?Y=B:Y=JSON.stringify(B);let H=`<context>
2406
+ ${Y}
2407
+ </context>`;if(g.push(H),l+=H+`
2408
+ `,this.completeOutputWithToolResults+=H+`
2409
+ `,this.currentOutput+=H+`
2410
+ `,!P){let j=N.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(j){let Te=N.replace(j[0],"").trim();if(Te.length>0){l+=Te,d+=Te,this.currentOutput+=Te,this.completeOutputWithToolResults+=Te;let Ft=on.remove(Te);this.emit("data",Ft)}}}continue}}catch{}if(N.includes("<think>")){p=!0;let k=N.split("<think>")[0];if(k){l+=k,d+=k,this.currentOutput+=k,this.completeOutputWithToolResults+=k;let P=on.remove(k);this.emit("data",P)}}else if(N.includes("</think>")){p=!1,h+=N.split("</think>")[0],this.emit("thinking",h),h="";let k=N.split("</think>")[1]||"";if(k){l+=k,d+=k,this.currentOutput+=k,this.completeOutputWithToolResults+=k;let P=on.remove(k);this.emit("data",P)}}else if(p)h+=N,this.emit("thinking",h);else{l+=N,d+=N,this.currentOutput+=N,this.completeOutputWithToolResults+=N;let k=on.remove(N);this.emit("data",k)}}else if(R.type==="checkpoint_reached"||R.event==="checkpoint_reached")u.debug("[CHECKPOINT] Backend reached checkpoint, processing queued messages as feedback"),this.handleCheckpointReached();else if(R.type==="todo_update")this.handleTodoUpdate(R.data);else if(R.type==="todo_list")this.handleTodoUpdate({items:R.todos});else if(R.type==="webview_update")this.handleWebViewUpdate(R.data);else if(R.type==="operator_progress")this.handleOperatorProgress(R.data);else if(R.type==="context_compaction_starting"||R.type==="manual_compaction_starting")u.debug("[COMPACTION] Starting:",R.message),this.emit("compaction_status",{status:"starting",conversationPercentage:R.conversationPercentage||R.percentage,message:R.message});else if(R.type==="context_compaction_complete"||R.type==="manual_compaction_complete")u.debug("[COMPACTION] Complete:",R.message),this.emit("compaction_status",{status:"complete",originalTokens:R.originalTokens,compactedTokens:R.compactedTokens,compressionRatio:R.compressionRatio,message:R.message});else if(R.type==="compaction_failed")u.debug("[COMPACTION] Failed:",R.message),this.emit("compaction_status",{status:"failed",error:R.error,message:R.message});else if(R.type==="stop"){this.handleStop(R.data),this.stopKeepaliveWatchdog(),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),this.emit("done"),s(l);return}}catch{u.debug("Treating as plain text"),l+=F,d+=F,this.currentOutput+=F,this.completeOutputWithToolResults+=F;let N=on.remove(F);this.emit("data",N)}}}}}),E.on("end",()=>{this.stopKeepaliveWatchdog(),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),this.emit("done"),s(l)}),E.on("error",x=>{switch(this.stopKeepaliveWatchdog(),u.debug("Streaming error, disconnecting WebSocket and cleaning up"),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),rr.classify(x)){case"parsing":let I={type:"tool_result",tool_call_id:`error_${un()}`,error:!0,content:`Streaming parsing error occurred: ${x.message}. Please check response format and retry.`};u.debug("🔄 [PERSONAL AGENT] Parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(I)),be.getInstance().handleConversationComplete(),s(l);return;case"critical":be.getInstance().handleConversationComplete(),this.emit("error",x),r(x);break}})}).catch(w=>{if(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),w.code==="ERR_CANCELED")u.debug("Task was cancelled, disconnecting WebSocket"),be.getInstance().handleConversationComplete(),this.emit("canceled"),s(l);else switch(rr.classify(w)){case"parsing":let v={type:"tool_result",tool_call_id:`error_${un()}`,error:!0,content:`Request parsing error: ${w.message}. Please check request format and retry.`};u.debug("🔄 [PERSONAL AGENT] Request parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(v)),be.getInstance().handleConversationComplete(),s(l);break;case"critical":u.debug("Request failed, disconnecting WebSocket"),be.getInstance().handleConversationComplete(),r(w);break}})})}async performNonStreamingToolCall(e,t){try{let n=await this.getFirebaseIdToken();n||u.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401");let s=await Na.post(this.apiEndpoint,e,{timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n||this.getAuthToken()}`}});if(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),s.data?.content){if(this.currentOutput=s.data.content,this.completeOutputWithToolResults=s.data.completeOutput||s.data.content,s.data.toolResults)for(let r of s.data.toolResults)this.handleToolResult(r.tool,r.result);return s.data.content}throw new Error("No response content received")}catch(n){switch(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),rr.classify(n)){case"parsing":let r={type:"tool_result",tool_call_id:`error_${un()}`,error:!0,content:`Non-streaming API parsing error: ${n.message}. Please check request format and retry.`};return u.debug("🔄 [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",n),new Error(`Tool calling API Error: ${n.message}`)}}}handleCompleteToolCall(e){this.emit("tool_use",e);let t=e.function?.name||"unknown",n=null;if(e.function?.arguments)try{n=JSON.parse(e.function.arguments)}catch{u.debug("[PERSONAL AGENT] Failed to parse tool arguments:",e.function.arguments);return}n&&this.setToolArgsCache(e.id,n),this.emit("toolExecuting",{toolCallId:e.id,name:t,arguments:n,startTime:new Date}),this.executeToolViaWebSocket(e.id,t,n)}async executeToolViaWebSocket(e,t,n){try{let s=be.getInstance(),r={id:e,tool_name:t,arguments:n||{},tool_call_id:e};await s.sendToolRequest(r)}catch(s){u.debug(`Failed to execute tool via WebSocket: ${s.message}`)}}handleToolResult(e,t){this.emit("tool_result",{tool:e,result:t}),u.debug(`Tool Result: ${e.name}`),t&&u.debug(` Result: ${JSON.stringify(t,null,2)}`)}handleWebSocketToolResponse(e){let{tool_name:t,content:n,success:s,error:r}=e;if(u.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",s),s&&n){let a=`<context>
2411
2411
  ${n.map(c=>c.text||"").join("")}
2412
2412
  </context>`;this.completeOutputWithToolResults+=a+`
2413
2413
  `,this.currentOutput+=a+`
@@ -2421,31 +2421,31 @@ Output:
2421
2421
  ${t}
2422
2422
  </context>`;this.completeOutputWithToolResults+=r+`
2423
2423
  `,this.currentOutput+=r+`
2424
- `,u.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${n}`),u.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:n,toolId:s,wrappedContent:r})}handleCheckpointReached(){let e=ct.getInstance(),t=e.getQueuedMessages();if(t.length===0){u.debug("[CHECKPOINT] No queued messages to convert");return}let n=[],s=[];for(let r of t)(r.isCrossDeviceTask?s:n).push(r);if(u.debug(`[CHECKPOINT] Found ${t.length} queued messages:`),u.debug(` - ${n.length} user messages -> convert to feedback`),u.debug(` - ${s.length} cross-device tasks -> keep in queue`),n.length>0){let r=n.map(o=>({id:o.id,content:o.content,timestamp:o.timestamp,isFeedbackMessage:!0}));this.emit("feedback:messages",r),u.info(`[CHECKPOINT] Converted ${n.length} user messages to feedback`),n.forEach(o=>{e.removeFromQueueById(o.id)})}s.length>0&&u.debug(`[CHECKPOINT] Kept ${s.length} cross-device tasks in queue for execution`)}handleTodoUpdate(e){u.debug("[TODO-DEBUG] handleTodoUpdate called with:",JSON.stringify(e).substring(0,500));let t=e.items||e.todos||[];u.debug("[TODO-DEBUG] Extracted items count:",t.length),this.currentTodoList={todos:t.map(n=>{let s=n.content||n.text||"";return u.debug("[TODO-DEBUG] Processing todo item:",{id:n.id,text:s,status:n.status}),{id:n.id||cn(),content:s,text:s,completed:n.completed||!1,priority:n.priority,status:n.status||(n.completed?"completed":"pending"),activeForm:n.activeForm||s}}),timestamp:new Date(e.timestamp||Date.now())},u.debug("[TODO-DEBUG] Emitting todo_update with",this.currentTodoList.todos.length,"todos"),this.emit("todo_update",this.currentTodoList)}handleWebViewUpdate(e){Array.isArray(e)?this.activeWebViewURLs=e:e.urls?this.activeWebViewURLs=e.urls:e.url&&(this.activeWebViewURLs=[e.url]),this.emit("webview_update",this.activeWebViewURLs)}handleOperatorProgress(e){this.operatorTaskState={id:e.id||cn(),taskId:e.taskId||e.id||cn(),sessionId:e.sessionId||cn(),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(this.isStreamingActive=!1,u.debug("[PERSONAL AGENT] Disconnecting WebSocket after conversation completion..."),be.getInstance().handleConversationComplete(),u.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};u.debug(`[PERSONAL AGENT] Emitting conversation_complete with content length: ${this.currentOutput.length}`),u.debug(`[PERSONAL AGENT] Content preview: "${this.currentOutput.substring(0,100)}..."`),this.emit("conversation_complete",t),u.debug("[PERSONAL AGENT] Conversation saving handled by AdvancedChatCommand (like SnowX OverlayManager)")}this.resetState()}calculateTokensUsed(e){return e.reduce((t,n)=>typeof n.content=="string"?t+Math.ceil(n.content.length/4):t,0)}stopCurrentOperation(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.emit("stopped"),this.resetState()}async submitPrompt(e,t){let n=t?.selectedPersonalModel||this.currentModel?.name||"snowx-c5",s=pe.find(o=>o.name===n)||{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},r=t?.mode==="new"?[]:[];return this.sendMessageWithToolCalling(e,r,s,.7,!0,void 0,void 0,{mode:t?.mode,crossDeviceTaskId:t?.crossDeviceTaskId,conversationId:t?.conversationId})}getCurrentOutput(){return this.currentOutput||this.completeOutputWithToolResults}async stopStreaming(){u.debug("[PERSONAL AGENT] Starting comprehensive stop operation (like SnowX stopStreaming)"),this.stopKeepaliveWatchdog(),this.stopLocalOperationsOnly(),await this.stopAllRunningTools(),be.getInstance().stopAllActiveTools("user_manual_stop"),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,n;if(t&&t.trim().length>0?n=t+`
2424
+ `,u.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${n}`),u.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:n,toolId:s,wrappedContent:r})}handleCheckpointReached(){let e=ct.getInstance(),t=e.getQueuedMessages();if(t.length===0){u.debug("[CHECKPOINT] No queued messages to convert");return}let n=[],s=[];for(let r of t)(r.isCrossDeviceTask?s:n).push(r);if(u.debug(`[CHECKPOINT] Found ${t.length} queued messages:`),u.debug(` - ${n.length} user messages -> convert to feedback`),u.debug(` - ${s.length} cross-device tasks -> keep in queue`),n.length>0){let r=n.map(o=>({id:o.id,content:o.content,timestamp:o.timestamp,isFeedbackMessage:!0}));this.emit("feedback:messages",r),u.info(`[CHECKPOINT] Converted ${n.length} user messages to feedback`),n.forEach(o=>{e.removeFromQueueById(o.id)})}s.length>0&&u.debug(`[CHECKPOINT] Kept ${s.length} cross-device tasks in queue for execution`)}handleTodoUpdate(e){u.debug("[TODO-DEBUG] handleTodoUpdate called with:",JSON.stringify(e).substring(0,500));let t=e.items||e.todos||[];u.debug("[TODO-DEBUG] Extracted items count:",t.length),this.currentTodoList={todos:t.map(n=>{let s=n.content||n.text||"";return u.debug("[TODO-DEBUG] Processing todo item:",{id:n.id,text:s,status:n.status}),{id:n.id||un(),content:s,text:s,completed:n.completed||!1,priority:n.priority,status:n.status||(n.completed?"completed":"pending"),activeForm:n.activeForm||s}}),timestamp:new Date(e.timestamp||Date.now())},u.debug("[TODO-DEBUG] Emitting todo_update with",this.currentTodoList.todos.length,"todos"),this.emit("todo_update",this.currentTodoList)}handleWebViewUpdate(e){Array.isArray(e)?this.activeWebViewURLs=e:e.urls?this.activeWebViewURLs=e.urls:e.url&&(this.activeWebViewURLs=[e.url]),this.emit("webview_update",this.activeWebViewURLs)}handleOperatorProgress(e){this.operatorTaskState={id:e.id||un(),taskId:e.taskId||e.id||un(),sessionId:e.sessionId||un(),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(this.isStreamingActive=!1,u.debug("[PERSONAL AGENT] Disconnecting WebSocket after conversation completion..."),be.getInstance().handleConversationComplete(),u.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};u.debug(`[PERSONAL AGENT] Emitting conversation_complete with content length: ${this.currentOutput.length}`),u.debug(`[PERSONAL AGENT] Content preview: "${this.currentOutput.substring(0,100)}..."`),this.emit("conversation_complete",t),u.debug("[PERSONAL AGENT] Conversation saving handled by AdvancedChatCommand (like SnowX OverlayManager)")}this.resetState()}calculateTokensUsed(e){return e.reduce((t,n)=>typeof n.content=="string"?t+Math.ceil(n.content.length/4):t,0)}stopCurrentOperation(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.emit("stopped"),this.resetState()}async submitPrompt(e,t){let n=t?.selectedPersonalModel||this.currentModel?.name||"snowx-c5",s=pe.find(o=>o.name===n)||{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},r=t?.mode==="new"?[]:[];return this.sendMessageWithToolCalling(e,r,s,.7,!0,void 0,void 0,{mode:t?.mode,crossDeviceTaskId:t?.crossDeviceTaskId,conversationId:t?.conversationId})}getCurrentOutput(){return this.currentOutput||this.completeOutputWithToolResults}async stopStreaming(){u.debug("[PERSONAL AGENT] Starting comprehensive stop operation (like SnowX stopStreaming)"),this.stopKeepaliveWatchdog(),this.stopLocalOperationsOnly(),await this.stopAllRunningTools(),be.getInstance().stopAllActiveTools("user_manual_stop"),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,n;if(t&&t.trim().length>0?n=t+`
2425
2425
 
2426
- [STOPPED] - Task was stopped by user`:n="Task was stopped by user before any response was generated.",this.currentPromptId)try{u.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(s){u.debug("[PERSONAL AGENT] Firebase update failed for STOP:",s)}await this.completeConversation(n,"STOP"),u.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),u.debug("[PERSONAL AGENT] Local operations stopped (sessionId preserved for backend stop)")}async stopAllRunningTools(){try{u.debug("[PERSONAL AGENT] 🛑 Stopping browser-use agent..."),await te.stop(),u.debug("[PERSONAL AGENT] ✅ Browser-use agent stopped successfully")}catch(e){u.error("[PERSONAL AGENT] ❌ Failed to stop browser-use agent:",e)}try{await te.stopAllSubAgents(),u.debug("[PERSONAL AGENT] ✅ All browser sub-agents stopped")}catch(e){u.error("[PERSONAL AGENT] ❌ Failed to stop browser sub-agents:",e)}}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",n={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(n.session_id=this.currentSessionId,u.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):u.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let s=Pe.getInstance().getCurrentDeviceId();s?(n.device_id=s,u.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${s}`)):u.debug("[PERSONAL AGENT] No device_id available for stop request"),u.debug("[PERSONAL AGENT] Sending backend stop request");let r=await this.getFirebaseIdToken();r||u.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let o=await Na.post(t,n,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r||this.getAuthToken()}`}});o.status===200&&(u.debug("[PERSONAL AGENT] Backend stop successful:",o.data),o.data.stopped_sessions&&u.debug("[PERSONAL AGENT] Stopped sessions:",o.data.stopped_sessions),o.data.stopped_tools&&u.debug("[PERSONAL AGENT] Stopped tools:",o.data.stopped_tools))}catch(e){u.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){u.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`);let n=this.currentSessionId;this.currentSessionId=null,u.debug(`[PERSONAL AGENT] 🆔 SESSION ID CLEARED FIRST on conversation completion (was: ${n})`),be.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(),u.debug(`[PERSONAL AGENT] Conversation completion finished for: ${t}`)}resetState(){this.currentOutput="",this.completeOutputWithToolResults="",this.currentPromptId=null,this.currentModel=null,this.currentTodoList=null,this.activeWebViewURLs=[],this.operatorTaskState=null,this.currentSessionId=null,this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear(),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),this.stopKeepaliveWatchdog()}getKeepaliveTimeout(){return this.activeToolNames.size>0?this.extendedKeepaliveTimeout:this.baseKeepaliveTimeout}startKeepaliveWatchdog(){this.stopKeepaliveWatchdog(),this.lastKeepaliveTime=new Date;let e=this.getKeepaliveTimeout();u.debug(`[KEEPALIVE] Watchdog started (timeout: ${e}ms = ${e/1e3}s)`),this.keepaliveWatchdog=setInterval(()=>{if(!this.lastKeepaliveTime)return;let t=this.getKeepaliveTimeout(),n=Date.now()-this.lastKeepaliveTime.getTime(),s=Math.floor(n/1e3),r=Math.floor(t/1e3);u.debug(`[KEEPALIVE] Check: ${s}s / ${r}s | Active tools: ${this.activeToolNames.size} | Processing: ${this.isProcessing}`),n>t&&(u.error("[KEEPALIVE-TIMEOUT] TIMEOUT TRIGGERED"),u.error(`[KEEPALIVE-TIMEOUT] Time since last keepalive: ${n}ms (${s}s)`),u.error(`[KEEPALIVE-TIMEOUT] Timeout limit: ${t}ms (${r}s)`),u.error(`[KEEPALIVE-TIMEOUT] Active tools: ${Array.from(this.activeToolNames).join(", ")||"none"}`),u.error(`[KEEPALIVE-TIMEOUT] Is processing: ${this.isProcessing}`),u.error(`[KEEPALIVE-TIMEOUT] Session ID: ${this.currentSessionId||"none"}`),u.error("[KEEPALIVE-TIMEOUT] Terminating stream and calling stopStreaming()..."),this.stopStreaming().catch(o=>{u.error(`[KEEPALIVE-TIMEOUT] Error stopping stream: ${o.message}`)}),this.emit("keepalive_timeout",{timeSinceLastKeepalive:n,activeTools:Array.from(this.activeToolNames),sessionId:this.currentSessionId}))},1e4)}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null,u.debug("[KEEPALIVE] Watchdog stopped")),this.lastKeepaliveTime=null}updateKeepaliveTimer(e="unknown"){this.lastKeepaliveTime=new Date,u.debug(`[KEEPALIVE] Updated timer on ${e}`)}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 td={};Fe(td,{FirebaseNativeService:()=>rr,TaskMode:()=>Fa,TaskStatus:()=>La});import{getDatabase as jb,ref as $a,onChildAdded as zb,update as qb,set as Kb,serverTimestamp as Vb}from"firebase/database";import{EventEmitter as Xb}from"events";var Fa,La,rr,Ua=F(()=>{"use strict";j();Rs();Fa=(t=>(t.NEW="new",t.EXISTING="existing",t))(Fa||{}),La=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s.QUEUE_FULL="queue_full",s))(La||{}),rr=class i extends Xb{static instance;app=null;database=null;auth=null;listenerHandle=null;currentUserId=null;currentDeviceId=null;currentTaskId=null;processedTaskIds=new Set;MAX_PROCESSED_IDS=50;firebaseAPI;get databaseInstance(){return this.database}completedObserver=null;errorObserver=null;stopObserver=null;constructor(){super(),u.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=Pt.getInstance()}setFirebaseInstances(e,t){u.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=jb(e),u.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(u.error("[Firebase Native] Firebase not initialized. Call setFirebaseInstances first."),!1):!0}static getInstance(){return i.instance||(i.instance=new i),i.instance}async startListening(e,t){if(u.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){u.error("[Firebase Native] Firebase not initialized properly");return}u.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let n=`users/${e}/devices/${t}/tasks`;u.debug("[Firebase Native] Creating Firebase reference",{taskPath:n});let s=$a(this.database,n),r=this.auth?.currentUser;u.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!r,uid:r?.uid||"none",email:r?.email||"none"}),this.listenerHandle=zb(s,o=>{let a=o.key,c=o.val();if(u.debug("[Firebase Native] Child added event received",{taskId:a,status:c?.status,exists:o.exists()}),!a||!c){u.debug("[Firebase Native] Invalid task snapshot - skipping");return}if(this.processedTaskIds.has(a)){u.debug("[Firebase Native] Task already processed - skipping duplicate",{taskId:a});return}if(c.status!=="pending"){u.debug("[Firebase Native] Task not pending - skipping",{taskId:a,status:c.status});return}if(this.processedTaskIds.add(a),this.processedTaskIds.size>this.MAX_PROCESSED_IDS){let l=Array.from(this.processedTaskIds);l.slice(0,l.length-this.MAX_PROCESSED_IDS).forEach(g=>this.processedTaskIds.delete(g))}u.debug("[Firebase Native] Processing new PENDING task",{taskId:a}),this.handleIncomingTask(a,c)},o=>{u.error("[Firebase Native] Firebase listener error",{code:o.code||"unknown",message:o.message,authState:this.auth?.currentUser?.uid||"null"})}),u.debug("[Firebase Native] Firebase onChildAdded listener established",{taskPath:n,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}async handleIncomingTask(e,t){u.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,u.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),u.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),u.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(n){u.error("[Firebase Native] Error processing task",{taskId:e,error:n.message,stack:n.stack}),await this.updateTaskStatus(e,"completed",`Error: ${n.message}`)}}async executeTask(e,t,n){u.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${n}`),u.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),u.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(xt(),Cn))).PersonalAgentService.getInstance()){u.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}u.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),n==="new"?u.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):u.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),u.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:n==="new"?"new":"existing"}),u.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(s){u.error("[FIREBASE-NATIVE] Task execution failed:",s.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(xt(),Cn)),n=t.getInstance();await this.cleanupObservers(),this.completedObserver=s=>{this.currentTaskId===e&&(u.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},n.on("BotResponseCompleted",this.completedObserver),this.errorObserver=s=>{if(this.currentTaskId!==e)return;let r=s?.message||s||"Unknown error occurred";u.debug(`[RESULT MONITOR] Task ${e} failed: ${r}`),this.cleanupObservers()},n.on("BotResponseError",this.errorObserver),this.stopObserver=s=>{if(this.currentTaskId!==e)return;let r=s?.reason;u.debug(`[RESULT MONITOR] Task ${e} stopped: ${r}`),setTimeout(()=>{this.cleanupObservers()},100)},n.on("BotResponseStopped",this.stopObserver),u.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(xt(),Cn)),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),u.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,n){if(!this.currentUserId||!this.currentDeviceId){u.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,r={status:t,updatedAt:"firebase_timestamp"};n&&(r.result=n),u.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:s,status:t,hasResult:!!n});try{u.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(s,r),u.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(o){u.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:s,error:o.message}),u.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=$a(this.database,s),c={status:t,updatedAt:Vb()};n&&(c.result=n),await qb(a,c),u.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else u.error("[Firebase Native] Database not available for fallback")}catch(a){u.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,n,s){let r=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;u.debug("[Firebase Native] Sending task to device",{taskId:r,targetDeviceId:t,mode:s});try{let o=$a(this.database,`users/${e}/devices/${t}/tasks/${r}`),a={taskId:r,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:n,mode:s,timestamp:Date.now(),status:"pending"};return await Kb(o,a),u.debug("[Firebase Native] Task sent successfully",{taskId:r,targetDeviceId:t}),r}catch(o){throw o}}stopListening(){if(u.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,u.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){u.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,this.processedTaskIds.clear(),u.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as Yb}from"events";var rs,Ba=F(()=>{"use strict";At();Te();Rs();Ua();xt();zn();j();rs=class i extends Yb{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];incomingTaskQueue=[];isProcessingIncoming=!1;currentlyExecutingTaskId=null;overlayManager=null;constructor(){super(),this.deviceRegistrationService=Pe.getInstance(),this.authService=X.getInstance(),this.firebaseAPI=Pt.getInstance(),this.firebaseNative=rr.getInstance(),this.firebaseNative.on("taskReceived",e=>{this.handleNativeTaskReceived(e)}),this.authService.on("SnowXSignOut",()=>{this.stopListening()}),this.setupTaskCompletionListener()}static getInstance(){return i.instance||(i.instance=new i),i.instance}setupTaskCompletionListener(){let e=je.getInstance();e.on("BotResponseCompleted",()=>{this.handleTaskCompletion()}),e.on("BotResponseStopped",()=>{this.handleTaskCompletion()}),e.on("BotResponseError",()=>{this.handleTaskCompletion()})}async handleTaskCompletion(){u.debug("✅ [CrossDevice] Task completion event received"),this.currentlyExecutingTaskId&&(u.debug("✅ [CrossDevice] Marking task completed:",this.currentlyExecutingTaskId),await this.markTaskCompletedById(this.currentlyExecutingTaskId),this.currentlyExecutingTaskId=null),this.incomingTaskQueue.length>0&&!this.isProcessingIncoming?(u.debug(`🔵 [CrossDevice] Task completed, processing next from incoming queue (${this.incomingTaskQueue.length} waiting)`),this.processIncomingTaskQueue()):this.processNextQueuedTask()}async markTaskCompletedById(e){u.debug("🔵 [CrossDevice] Marking task complete:",e),await this.updateTaskStatus(e,"completed")}processNextQueuedTask(){if(je.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){u.debug("⏸️ [CrossDevice] System still busy, waiting for completion");return}if(this.pendingTasksQueue.length===0){u.debug("✅ [CrossDevice] No pending tasks in queue");return}let n=this.pendingTasksQueue.shift();u.debug(`📤 [CrossDevice] Processing next task from queue: ${n.taskId}`),this.executeTaskImmediately(n.taskId,n.prompt,n.mode)}async startListening(e,t){let n=t||this.deviceRegistrationService.getCurrentDeviceId();if(!n){u.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=n,u.debug(`Starting listener - User: ${e}, Device: ${n}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let s=this.authService.getFirebaseAuth();if(!s?.currentUser){u.error("No authenticated Firebase user - cannot start listeners");return}if(s.currentUser.uid!==e){u.error("SECURITY: User ID mismatch! Firebase UID:",s.currentUser.uid,"Requested:",e),u.error("Refusing to start listener for different user");return}u.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,n)}catch(s){throw u.error("Failed to start listener:",s.message),s}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),u.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){u.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){u.error("No stored user ID found - cannot authenticate Firebase for listeners");return}u.debug("Found stored user ID, getting custom token from API...");try{let n=await this.authService.getCustomTokenFromAPI(e);if(t){let s=await this.authService.signInWithCustomToken(n);u.debug("Firebase authenticated successfully - UID:",s.user.uid)}}catch(n){u.warn("Firebase authentication failed:",n.message),u.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){u.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){u.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),u.warn("🚨 [SECURITY] Task ID:",e.taskId),u.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),u.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}u.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,u.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}),u.debug("Cross-device task UI flow triggered successfully")}catch(t){u.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){u.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(n){u.error("Failed to process task:",n.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),u.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let n=e.split("_");if(n.length!==3||n[0]!=="task")return!1;let s=n[1],r=n[2];return s.length!==13||!Number.isInteger(Number(s))||r.length!==9?!1:/^[a-z0-9]+$/.test(r)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let n=t.id,s=t.prompt,r=t.status;if(!n||!s){u.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(r!=="pending"){u.debug("⏭️ [CrossDevice] Skipping non-pending task:",n,"Status:",r);return}this.incomingTaskQueue.push({taskId:n,prompt:s,snapshot:e}),u.debug(`📨 [CrossDevice] Task queued for processing: ${n}`),u.debug(` Incoming queue size: ${this.incomingTaskQueue.length}`),this.isProcessingIncoming||this.processIncomingTaskQueue()}catch(t){u.error("❌ [CrossDevice] Error in handleIncomingTask:",t.message)}}async processIncomingTaskQueue(){if(this.incomingTaskQueue.length===0){this.isProcessingIncoming=!1,u.debug("✅ [CrossDevice] Incoming queue empty, processing complete");return}this.isProcessingIncoming=!0;let{taskId:e,prompt:t,snapshot:n}=this.incomingTaskQueue.shift();u.debug(`🔵 [CrossDevice] Processing task: ${e}`),u.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let s=n.val();if(u.debug("🔵 [CrossDevice] Task received, updating status to processing immediately"),await this.updateTaskStatus(e,"processing"),!this.validateTaskId(e)){u.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),u.warn("🚨 [SECURITY] Task ID:",e),u.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),u.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access"),await this.updateTaskStatus(e,"completed"),this.processIncomingTaskQueue();return}if(u.debug("✅ [SECURITY] Task ID validation passed:",e),!this.canAcceptTask()){u.warn("⚠️ [CrossDevice] Cannot accept task - execution queue is full"),await this.updateTaskStatus(e,"queue_full"),this.processIncomingTaskQueue();return}u.debug("✅ [CrossDevice] Task accepted:",e),u.debug(" Prompt:",t),this.currentlyExecutingTaskId=e,this.currentTaskId=e;let o="existing";await this.executeTask(e,t,o),this.isProcessingIncoming=!1,u.debug("✅ [CrossDevice] Task dispatched for execution, waiting for completion")}canAcceptTask(){if(je.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let n=ct.getInstance(),s=n.getQueueCount(),r=n.canAddToQueue();if(u.debug(`🔍 [CrossDevice] Queue capacity check: ${s}/5 used, hasSpace: ${r}`),!r)return!1}return!0}async executeTask(e,t,n){if(u.debug(`Executing task: ${e} with mode: ${n}`),u.debug(`Prompt to execute: ${t}`),je.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){u.debug(`System is busy - queueing cross-device task: ${e}`);let o={taskId:e,prompt:t,mode:n};this.pendingTasksQueue.push(o),u.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}u.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,n)}async executeTaskImmediately(e,t,n){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{u.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",n),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:n})})}catch(s){u.error("Task execution failed:",s.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,s={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(n,s)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){this.cleanupObservers();let t=()=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)},n=r=>{this.currentTaskId===e&&this.cleanupObservers()},s=r=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)};this.once("BotResponseCompleted",t),this.once("BotResponseError",n),this.once("BotResponseStopped",s)}cleanupObservers(){this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),this.currentTaskId=null}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,n="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let s=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,r={taskId:s,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:n,timestamp:Yt,status:"pending"},o=`users/${this.currentUserId}/devices/${e}/tasks/${s}`;try{await this.firebaseAPI.writeRealtimeData(o,r),u.debug("Task submitted to device:",e)}catch(a){throw u.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([n,s])=>({id:n,...s})).filter(n=>n.isOnline&&n.id!==this.currentDeviceId)}catch(e){return u.error("Failed to get available devices:",e.message),[]}}enable(){u.debug("[CROSS DEVICE] Service enabled")}disable(){u.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){u.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var Tm={};Fe(Tm,{SnowXStreamHandlerService:()=>kc});import{EventEmitter as pT}from"events";var kc,xm=F(()=>{"use strict";kc=class extends pT{buffer="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteChunks=[];byteChunksLength=0;thinkingContentParts=[];regularContentParts=[];isInThinkingBlock=!1;thinkingBuffer="";accumulatedToolCalls=new Map;toolCallIndexToId=new Map;processedToolCallIds=new Set;isCancelled=!1;lastActivityTime=new Date;keepaliveWatchdog=null;KEEPALIVE_TIMEOUT=3e4;constructor(){super()}updateActivityTime(){this.lastActivityTime=new Date}startKeepaliveWatchdog(){this.stopKeepaliveWatchdog(),this.updateActivityTime(),this.keepaliveWatchdog=setInterval(()=>{let e=Date.now()-this.lastActivityTime.getTime();e>this.KEEPALIVE_TIMEOUT&&this.emit("keepalive_timeout",{lastActivityTime:this.lastActivityTime,timeSinceLastActivity:e})},5e3)}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}async processStreamingResponse(e,t,n,s,r){let o=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,c)=>{this.startKeepaliveWatchdog(),e.on("data",l=>{if(this.isCancelled){this.stopKeepaliveWatchdog(),a();return}this.updateActivityTime(),this.totalBytesReceived+=l.length,this.byteChunks.push(l),this.byteChunksLength+=l.length;let d=this.byteChunksLength>0?Buffer.concat(this.byteChunks):Buffer.alloc(0);this.byteChunks=[],this.byteChunksLength=0;let g=d.length,m=Math.max(0,d.length-3);for(let p=d.length-1;p>=m;p--){let h=d[p];if((h&192)===128)continue;let f=1;(h&128)===0?f=1:(h&224)===192?f=2:(h&240)===224?f=3:(h&248)===240&&(f=4),d.length-p<f&&(g=p);break}if(g>0){let p=d.slice(0,g);g<d.length&&(this.byteChunks.push(d.slice(g)),this.byteChunksLength=d.length-g);let h=p.toString("utf8");this.buffer+=h,this.rawDataReceived+=h,this.processBufferedLines(n,s,r)}}),e.on("end",()=>{if(this.stopKeepaliveWatchdog(),this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(n,s,r),this.printFinalStatistics(),this.regularContentParts.length===0&&!r){c(new Error("No response received"));return}a()}),e.on("error",l=>{this.stopKeepaliveWatchdog(),c(l)})})}processBufferedLines(e,t,n){if(this.isCancelled)return;let s,r=this.buffer.indexOf(`\r
2426
+ [STOPPED] - Task was stopped by user`:n="Task was stopped by user before any response was generated.",this.currentPromptId)try{u.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(s){u.debug("[PERSONAL AGENT] Firebase update failed for STOP:",s)}await this.completeConversation(n,"STOP"),u.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),u.debug("[PERSONAL AGENT] Local operations stopped (sessionId preserved for backend stop)")}async stopAllRunningTools(){try{u.debug("[PERSONAL AGENT] 🛑 Stopping browser-use agent..."),await ne.stop(),u.debug("[PERSONAL AGENT] ✅ Browser-use agent stopped successfully")}catch(e){u.error("[PERSONAL AGENT] ❌ Failed to stop browser-use agent:",e)}try{await ne.stopAllSubAgents(),u.debug("[PERSONAL AGENT] ✅ All browser sub-agents stopped")}catch(e){u.error("[PERSONAL AGENT] ❌ Failed to stop browser sub-agents:",e)}}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",n={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(n.session_id=this.currentSessionId,u.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):u.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let s=Ae.getInstance().getCurrentDeviceId();s?(n.device_id=s,u.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${s}`)):u.debug("[PERSONAL AGENT] No device_id available for stop request"),u.debug("[PERSONAL AGENT] Sending backend stop request");let r=await this.getFirebaseIdToken();r||u.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let o=await Na.post(t,n,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r||this.getAuthToken()}`}});o.status===200&&(u.debug("[PERSONAL AGENT] Backend stop successful:",o.data),o.data.stopped_sessions&&u.debug("[PERSONAL AGENT] Stopped sessions:",o.data.stopped_sessions),o.data.stopped_tools&&u.debug("[PERSONAL AGENT] Stopped tools:",o.data.stopped_tools))}catch(e){u.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){u.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`);let n=this.currentSessionId;this.currentSessionId=null,u.debug(`[PERSONAL AGENT] 🆔 SESSION ID CLEARED FIRST on conversation completion (was: ${n})`),be.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(),u.debug(`[PERSONAL AGENT] Conversation completion finished for: ${t}`)}resetState(){this.currentOutput="",this.completeOutputWithToolResults="",this.currentPromptId=null,this.currentModel=null,this.currentTodoList=null,this.activeWebViewURLs=[],this.operatorTaskState=null,this.currentSessionId=null,this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear(),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),this.stopKeepaliveWatchdog()}getKeepaliveTimeout(){return this.activeToolNames.size>0?this.extendedKeepaliveTimeout:this.baseKeepaliveTimeout}startKeepaliveWatchdog(){this.stopKeepaliveWatchdog(),this.lastKeepaliveTime=new Date;let e=this.getKeepaliveTimeout();u.debug(`[KEEPALIVE] Watchdog started (timeout: ${e}ms = ${e/1e3}s)`),this.keepaliveWatchdog=setInterval(()=>{if(!this.lastKeepaliveTime)return;let t=this.getKeepaliveTimeout(),n=Date.now()-this.lastKeepaliveTime.getTime(),s=Math.floor(n/1e3),r=Math.floor(t/1e3);u.debug(`[KEEPALIVE] Check: ${s}s / ${r}s | Active tools: ${this.activeToolNames.size} | Processing: ${this.isProcessing}`),n>t&&(u.error("[KEEPALIVE-TIMEOUT] TIMEOUT TRIGGERED"),u.error(`[KEEPALIVE-TIMEOUT] Time since last keepalive: ${n}ms (${s}s)`),u.error(`[KEEPALIVE-TIMEOUT] Timeout limit: ${t}ms (${r}s)`),u.error(`[KEEPALIVE-TIMEOUT] Active tools: ${Array.from(this.activeToolNames).join(", ")||"none"}`),u.error(`[KEEPALIVE-TIMEOUT] Is processing: ${this.isProcessing}`),u.error(`[KEEPALIVE-TIMEOUT] Session ID: ${this.currentSessionId||"none"}`),u.error("[KEEPALIVE-TIMEOUT] Terminating stream and calling stopStreaming()..."),this.stopStreaming().catch(o=>{u.error(`[KEEPALIVE-TIMEOUT] Error stopping stream: ${o.message}`)}),this.emit("keepalive_timeout",{timeSinceLastKeepalive:n,activeTools:Array.from(this.activeToolNames),sessionId:this.currentSessionId}))},1e4)}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null,u.debug("[KEEPALIVE] Watchdog stopped")),this.lastKeepaliveTime=null}updateKeepaliveTimer(e="unknown"){this.lastKeepaliveTime=new Date,u.debug(`[KEEPALIVE] Updated timer on ${e}`)}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 td={};Le(td,{FirebaseNativeService:()=>or,TaskMode:()=>Fa,TaskStatus:()=>La});import{getDatabase as jb,ref as $a,onChildAdded as zb,update as qb,set as Kb,serverTimestamp as Vb}from"firebase/database";import{EventEmitter as Xb}from"events";var Fa,La,or,Ua=$(()=>{"use strict";z();Os();Fa=(t=>(t.NEW="new",t.EXISTING="existing",t))(Fa||{}),La=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s.QUEUE_FULL="queue_full",s))(La||{}),or=class i extends Xb{static instance;app=null;database=null;auth=null;listenerHandle=null;currentUserId=null;currentDeviceId=null;currentTaskId=null;processedTaskIds=new Set;MAX_PROCESSED_IDS=50;firebaseAPI;get databaseInstance(){return this.database}completedObserver=null;errorObserver=null;stopObserver=null;constructor(){super(),u.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=Pt.getInstance()}setFirebaseInstances(e,t){u.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=jb(e),u.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(u.error("[Firebase Native] Firebase not initialized. Call setFirebaseInstances first."),!1):!0}static getInstance(){return i.instance||(i.instance=new i),i.instance}async startListening(e,t){if(u.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){u.error("[Firebase Native] Firebase not initialized properly");return}u.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let n=`users/${e}/devices/${t}/tasks`;u.debug("[Firebase Native] Creating Firebase reference",{taskPath:n});let s=$a(this.database,n),r=this.auth?.currentUser;u.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!r,uid:r?.uid||"none",email:r?.email||"none"}),this.listenerHandle=zb(s,o=>{let a=o.key,c=o.val();if(u.debug("[Firebase Native] Child added event received",{taskId:a,status:c?.status,exists:o.exists()}),!a||!c){u.debug("[Firebase Native] Invalid task snapshot - skipping");return}if(this.processedTaskIds.has(a)){u.debug("[Firebase Native] Task already processed - skipping duplicate",{taskId:a});return}if(c.status!=="pending"){u.debug("[Firebase Native] Task not pending - skipping",{taskId:a,status:c.status});return}if(this.processedTaskIds.add(a),this.processedTaskIds.size>this.MAX_PROCESSED_IDS){let l=Array.from(this.processedTaskIds);l.slice(0,l.length-this.MAX_PROCESSED_IDS).forEach(g=>this.processedTaskIds.delete(g))}u.debug("[Firebase Native] Processing new PENDING task",{taskId:a}),this.handleIncomingTask(a,c)},o=>{u.error("[Firebase Native] Firebase listener error",{code:o.code||"unknown",message:o.message,authState:this.auth?.currentUser?.uid||"null"})}),u.debug("[Firebase Native] Firebase onChildAdded listener established",{taskPath:n,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}async handleIncomingTask(e,t){u.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,u.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),u.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),u.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(n){u.error("[Firebase Native] Error processing task",{taskId:e,error:n.message,stack:n.stack}),await this.updateTaskStatus(e,"completed",`Error: ${n.message}`)}}async executeTask(e,t,n){u.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${n}`),u.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),u.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(xt(),In))).PersonalAgentService.getInstance()){u.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}u.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),n==="new"?u.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):u.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),u.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:n==="new"?"new":"existing"}),u.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(s){u.error("[FIREBASE-NATIVE] Task execution failed:",s.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(xt(),In)),n=t.getInstance();await this.cleanupObservers(),this.completedObserver=s=>{this.currentTaskId===e&&(u.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},n.on("BotResponseCompleted",this.completedObserver),this.errorObserver=s=>{if(this.currentTaskId!==e)return;let r=s?.message||s||"Unknown error occurred";u.debug(`[RESULT MONITOR] Task ${e} failed: ${r}`),this.cleanupObservers()},n.on("BotResponseError",this.errorObserver),this.stopObserver=s=>{if(this.currentTaskId!==e)return;let r=s?.reason;u.debug(`[RESULT MONITOR] Task ${e} stopped: ${r}`),setTimeout(()=>{this.cleanupObservers()},100)},n.on("BotResponseStopped",this.stopObserver),u.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(xt(),In)),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),u.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,n){if(!this.currentUserId||!this.currentDeviceId){u.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,r={status:t,updatedAt:"firebase_timestamp"};n&&(r.result=n),u.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:s,status:t,hasResult:!!n});try{u.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(s,r),u.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(o){u.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:s,error:o.message}),u.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=$a(this.database,s),c={status:t,updatedAt:Vb()};n&&(c.result=n),await qb(a,c),u.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else u.error("[Firebase Native] Database not available for fallback")}catch(a){u.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,n,s){let r=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;u.debug("[Firebase Native] Sending task to device",{taskId:r,targetDeviceId:t,mode:s});try{let o=$a(this.database,`users/${e}/devices/${t}/tasks/${r}`),a={taskId:r,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:n,mode:s,timestamp:Date.now(),status:"pending"};return await Kb(o,a),u.debug("[Firebase Native] Task sent successfully",{taskId:r,targetDeviceId:t}),r}catch(o){throw o}}stopListening(){if(u.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,u.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){u.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,this.processedTaskIds.clear(),u.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as Yb}from"events";var is,Ba=$(()=>{"use strict";At();xe();Os();Ua();xt();Kn();z();is=class i extends Yb{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];incomingTaskQueue=[];isProcessingIncoming=!1;currentlyExecutingTaskId=null;overlayManager=null;constructor(){super(),this.deviceRegistrationService=Ae.getInstance(),this.authService=X.getInstance(),this.firebaseAPI=Pt.getInstance(),this.firebaseNative=or.getInstance(),this.firebaseNative.on("taskReceived",e=>{this.handleNativeTaskReceived(e)}),this.authService.on("SnowXSignOut",()=>{this.stopListening()}),this.setupTaskCompletionListener()}static getInstance(){return i.instance||(i.instance=new i),i.instance}setupTaskCompletionListener(){let e=ze.getInstance();e.on("BotResponseCompleted",()=>{this.handleTaskCompletion()}),e.on("BotResponseStopped",()=>{this.handleTaskCompletion()}),e.on("BotResponseError",()=>{this.handleTaskCompletion()})}async handleTaskCompletion(){u.debug("✅ [CrossDevice] Task completion event received"),this.currentlyExecutingTaskId&&(u.debug("✅ [CrossDevice] Marking task completed:",this.currentlyExecutingTaskId),await this.markTaskCompletedById(this.currentlyExecutingTaskId),this.currentlyExecutingTaskId=null),this.incomingTaskQueue.length>0&&!this.isProcessingIncoming?(u.debug(`🔵 [CrossDevice] Task completed, processing next from incoming queue (${this.incomingTaskQueue.length} waiting)`),this.processIncomingTaskQueue()):this.processNextQueuedTask()}async markTaskCompletedById(e){u.debug("🔵 [CrossDevice] Marking task complete:",e),await this.updateTaskStatus(e,"completed")}processNextQueuedTask(){if(ze.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){u.debug("⏸️ [CrossDevice] System still busy, waiting for completion");return}if(this.pendingTasksQueue.length===0){u.debug("✅ [CrossDevice] No pending tasks in queue");return}let n=this.pendingTasksQueue.shift();u.debug(`📤 [CrossDevice] Processing next task from queue: ${n.taskId}`),this.executeTaskImmediately(n.taskId,n.prompt,n.mode)}async startListening(e,t){let n=t||this.deviceRegistrationService.getCurrentDeviceId();if(!n){u.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=n,u.debug(`Starting listener - User: ${e}, Device: ${n}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let s=this.authService.getFirebaseAuth();if(!s?.currentUser){u.error("No authenticated Firebase user - cannot start listeners");return}if(s.currentUser.uid!==e){u.error("SECURITY: User ID mismatch! Firebase UID:",s.currentUser.uid,"Requested:",e),u.error("Refusing to start listener for different user");return}u.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,n)}catch(s){throw u.error("Failed to start listener:",s.message),s}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),u.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){u.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){u.error("No stored user ID found - cannot authenticate Firebase for listeners");return}u.debug("Found stored user ID, getting custom token from API...");try{let n=await this.authService.getCustomTokenFromAPI(e);if(t){let s=await this.authService.signInWithCustomToken(n);u.debug("Firebase authenticated successfully - UID:",s.user.uid)}}catch(n){u.warn("Firebase authentication failed:",n.message),u.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){u.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){u.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),u.warn("🚨 [SECURITY] Task ID:",e.taskId),u.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),u.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}u.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,u.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}),u.debug("Cross-device task UI flow triggered successfully")}catch(t){u.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){u.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(n){u.error("Failed to process task:",n.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),u.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let n=e.split("_");if(n.length!==3||n[0]!=="task")return!1;let s=n[1],r=n[2];return s.length!==13||!Number.isInteger(Number(s))||r.length!==9?!1:/^[a-z0-9]+$/.test(r)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let n=t.id,s=t.prompt,r=t.status;if(!n||!s){u.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(r!=="pending"){u.debug("⏭️ [CrossDevice] Skipping non-pending task:",n,"Status:",r);return}this.incomingTaskQueue.push({taskId:n,prompt:s,snapshot:e}),u.debug(`📨 [CrossDevice] Task queued for processing: ${n}`),u.debug(` Incoming queue size: ${this.incomingTaskQueue.length}`),this.isProcessingIncoming||this.processIncomingTaskQueue()}catch(t){u.error("❌ [CrossDevice] Error in handleIncomingTask:",t.message)}}async processIncomingTaskQueue(){if(this.incomingTaskQueue.length===0){this.isProcessingIncoming=!1,u.debug("✅ [CrossDevice] Incoming queue empty, processing complete");return}this.isProcessingIncoming=!0;let{taskId:e,prompt:t,snapshot:n}=this.incomingTaskQueue.shift();u.debug(`🔵 [CrossDevice] Processing task: ${e}`),u.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let s=n.val();if(u.debug("🔵 [CrossDevice] Task received, updating status to processing immediately"),await this.updateTaskStatus(e,"processing"),!this.validateTaskId(e)){u.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),u.warn("🚨 [SECURITY] Task ID:",e),u.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),u.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access"),await this.updateTaskStatus(e,"completed"),this.processIncomingTaskQueue();return}if(u.debug("✅ [SECURITY] Task ID validation passed:",e),!this.canAcceptTask()){u.warn("⚠️ [CrossDevice] Cannot accept task - execution queue is full"),await this.updateTaskStatus(e,"queue_full"),this.processIncomingTaskQueue();return}u.debug("✅ [CrossDevice] Task accepted:",e),u.debug(" Prompt:",t),this.currentlyExecutingTaskId=e,this.currentTaskId=e;let o="existing";await this.executeTask(e,t,o),this.isProcessingIncoming=!1,u.debug("✅ [CrossDevice] Task dispatched for execution, waiting for completion")}canAcceptTask(){if(ze.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let n=ct.getInstance(),s=n.getQueueCount(),r=n.canAddToQueue();if(u.debug(`🔍 [CrossDevice] Queue capacity check: ${s}/5 used, hasSpace: ${r}`),!r)return!1}return!0}async executeTask(e,t,n){if(u.debug(`Executing task: ${e} with mode: ${n}`),u.debug(`Prompt to execute: ${t}`),ze.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){u.debug(`System is busy - queueing cross-device task: ${e}`);let o={taskId:e,prompt:t,mode:n};this.pendingTasksQueue.push(o),u.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}u.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,n)}async executeTaskImmediately(e,t,n){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{u.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",n),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:n})})}catch(s){u.error("Task execution failed:",s.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,s={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(n,s)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){this.cleanupObservers();let t=()=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)},n=r=>{this.currentTaskId===e&&this.cleanupObservers()},s=r=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)};this.once("BotResponseCompleted",t),this.once("BotResponseError",n),this.once("BotResponseStopped",s)}cleanupObservers(){this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),this.currentTaskId=null}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,n="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let s=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,r={taskId:s,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:n,timestamp:Qt,status:"pending"},o=`users/${this.currentUserId}/devices/${e}/tasks/${s}`;try{await this.firebaseAPI.writeRealtimeData(o,r),u.debug("Task submitted to device:",e)}catch(a){throw u.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([n,s])=>({id:n,...s})).filter(n=>n.isOnline&&n.id!==this.currentDeviceId)}catch(e){return u.error("Failed to get available devices:",e.message),[]}}enable(){u.debug("[CROSS DEVICE] Service enabled")}disable(){u.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){u.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var Tm={};Le(Tm,{SnowXStreamHandlerService:()=>kc});import{EventEmitter as pT}from"events";var kc,xm=$(()=>{"use strict";kc=class extends pT{buffer="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteChunks=[];byteChunksLength=0;thinkingContentParts=[];regularContentParts=[];isInThinkingBlock=!1;thinkingBuffer="";accumulatedToolCalls=new Map;toolCallIndexToId=new Map;processedToolCallIds=new Set;isCancelled=!1;lastActivityTime=new Date;keepaliveWatchdog=null;KEEPALIVE_TIMEOUT=3e4;constructor(){super()}updateActivityTime(){this.lastActivityTime=new Date}startKeepaliveWatchdog(){this.stopKeepaliveWatchdog(),this.updateActivityTime(),this.keepaliveWatchdog=setInterval(()=>{let e=Date.now()-this.lastActivityTime.getTime();e>this.KEEPALIVE_TIMEOUT&&this.emit("keepalive_timeout",{lastActivityTime:this.lastActivityTime,timeSinceLastActivity:e})},5e3)}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}async processStreamingResponse(e,t,n,s,r){let o=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,c)=>{this.startKeepaliveWatchdog(),e.on("data",l=>{if(this.isCancelled){this.stopKeepaliveWatchdog(),a();return}this.updateActivityTime(),this.totalBytesReceived+=l.length,this.byteChunks.push(l),this.byteChunksLength+=l.length;let d=this.byteChunksLength>0?Buffer.concat(this.byteChunks):Buffer.alloc(0);this.byteChunks=[],this.byteChunksLength=0;let g=d.length,m=Math.max(0,d.length-3);for(let p=d.length-1;p>=m;p--){let h=d[p];if((h&192)===128)continue;let f=1;(h&128)===0?f=1:(h&224)===192?f=2:(h&240)===224?f=3:(h&248)===240&&(f=4),d.length-p<f&&(g=p);break}if(g>0){let p=d.slice(0,g);g<d.length&&(this.byteChunks.push(d.slice(g)),this.byteChunksLength=d.length-g);let h=p.toString("utf8");this.buffer+=h,this.rawDataReceived+=h,this.processBufferedLines(n,s,r)}}),e.on("end",()=>{if(this.stopKeepaliveWatchdog(),this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(n,s,r),this.printFinalStatistics(),this.regularContentParts.length===0&&!r){c(new Error("No response received"));return}a()}),e.on("error",l=>{this.stopKeepaliveWatchdog(),c(l)})})}processBufferedLines(e,t,n){if(this.isCancelled)return;let s,r=this.buffer.indexOf(`\r
2427
2427
  `);if(r!==-1)s=r;else{let o=this.buffer.indexOf(`
2428
2428
  `);if(o!==-1)s=o;else{let a=this.buffer.indexOf("\r");if(a!==-1)s=a;else return}}for(;s!==-1;){if(this.isCancelled)return;let o=this.buffer.substring(0,s);this.linesProcessed++,this.buffer.substring(s,s+2)===`\r
2429
2429
  `?this.buffer=this.buffer.substring(s+2):this.buffer=this.buffer.substring(s+1);let a=o.trim();if(!a){s=this.findNextLineEnd();continue}if(a.startsWith(":")){a.toLowerCase().includes("keepalive")&&(this.updateActivityTime(),this.emit("keepalive_received")),s=this.findNextLineEnd();continue}a.startsWith("data: ")&&this.processDataLine(a,e,t,n),s=this.findNextLineEnd()}}processDataLine(e,t,n,s){if(this.isCancelled)return;this.dataLinesFound++;let r=e.substring(6).trim();if(r==="[DONE]"){this.emit("streamEnd");return}if(r)try{let o=JSON.parse(r);if(o.session_start){let a=o.session_start;this.emit("session_start",{sessionId:a.session_id,conversationId:a.conversation_id,title:a.title});return}if(o.title_generated){this.emit("title_generated",{title:o.title_generated});return}if(o.todo_list){this.emit("todo_list",o.todo_list);return}if(o.tool_response){let a=o.tool_response,c="";typeof a.content=="string"?c=a.content:Array.isArray(a.content)&&(c=a.content.filter(d=>d.type==="text"&&d.text).map(d=>d.text).join(`
2430
2430
  `)),this.emit("tool_response",{toolCallId:a.tool_call_id,content:c,name:a.name});return}if(o.checkpoint_reached){this.emit("checkpoint_reached",o.checkpoint_reached);return}if(o.context_compaction_starting||o.manual_compaction_starting){this.emit("compaction_starting");return}if(o.context_compaction_complete||o.manual_compaction_complete){this.emit("compaction_complete");return}if(o.compaction_failed){this.emit("compaction_failed",o.compaction_failed);return}if(o.error){this.emit("error",o.error);return}if(o.choices&&o.choices.length>0){let a=o.choices[0];if(a.delta.tool_calls&&a.delta.tool_calls.length>0)for(let c of a.delta.tool_calls){let l=c.id,d=c.index;if(l&&d!==void 0?this.toolCallIndexToId.set(d,l):!l&&d!==void 0&&(l=this.toolCallIndexToId.get(d)),!l)continue;let g=this.accumulatedToolCalls.get(l)||{id:l,type:c.type||"function",function:{name:"",arguments:""}};c.function&&(c.function.name&&(g.function.name=c.function.name),c.function.arguments&&(g.function.arguments+=c.function.arguments)),this.accumulatedToolCalls.set(l,g),s?.(g)}a.delta.content&&(this.contentChunksReceived++,this.processThinkingContent(a.delta.content,t,n))}}catch{}}processThinkingContent(e,t,n){if(!this.isCancelled)for(this.thinkingBuffer+=e;;)if(this.isInThinkingBlock){let s=this.thinkingBuffer.indexOf("</think>");if(s!==-1){let r=this.thinkingBuffer.substring(0,s);r&&(this.thinkingContentParts.push(r),n?.(this.thinkingContentParts.join(""))),this.thinkingBuffer=this.thinkingBuffer.substring(s+8),this.isInThinkingBlock=!1;continue}this.thinkingBuffer&&(this.thinkingContentParts.push(this.thinkingBuffer),this.thinkingBuffer="",n?.(this.thinkingContentParts.join("")));break}else{let s=this.thinkingBuffer.indexOf("<think>");if(s!==-1){let r=this.thinkingBuffer.substring(0,s);r&&(this.regularContentParts.push(r),t(this.regularContentParts.join(""))),this.thinkingBuffer=this.thinkingBuffer.substring(s+7),this.isInThinkingBlock=!0;continue}this.thinkingBuffer&&(this.regularContentParts.push(this.thinkingBuffer),this.thinkingBuffer="",t(this.regularContentParts.join("")));break}}handleNonSSEResponse(e,t,n){if(this.rawDataReceived.startsWith("data: ")){let s=this.rawDataReceived.substring(6).trim();try{let r=JSON.parse(s);r.choices&&r.choices.length>0&&r.choices[0].delta.content&&this.processThinkingContent(r.choices[0].delta.content,e,t)}catch{}}else try{let s=JSON.parse(this.rawDataReceived);s.choices?.[0]?.message?.content&&this.processThinkingContent(s.choices[0].message.content,e,t)}catch{this.processThinkingContent(this.rawDataReceived,e,t)}}findNextLineEnd(){let e=this.buffer.indexOf(`\r
2431
2431
  `);if(e!==-1)return e;let t=this.buffer.indexOf(`
2432
- `);if(t!==-1)return t;let n=this.buffer.indexOf("\r");return n!==-1?n:-1}printFinalStatistics(){this.regularContentParts.length}cancel(){this.isCancelled=!0,this.emit("cancelled")}reset(){this.buffer="",this.totalBytesReceived=0,this.linesProcessed=0,this.dataLinesFound=0,this.contentChunksReceived=0,this.rawDataReceived="",this.byteChunks=[],this.byteChunksLength=0,this.thinkingContentParts=[],this.regularContentParts=[],this.isInThinkingBlock=!1,this.thinkingBuffer="",this.accumulatedToolCalls.clear(),this.toolCallIndexToId.clear(),this.processedToolCallIds.clear(),this.isCancelled=!1}getStats(){return{totalBytesReceived:this.totalBytesReceived,linesProcessed:this.linesProcessed,dataLinesFound:this.dataLinesFound,contentChunksReceived:this.contentChunksReceived}}getFinalResponse(){return this.regularContentParts.join("")}getThinkingContent(){return this.thinkingContentParts.join("")}getAccumulatedToolCalls(){return this.accumulatedToolCalls}isToolCallProcessed(e){return this.processedToolCallIds.has(e)}markToolCallProcessed(e){this.processedToolCallIds.add(e)}}});import hT from"axios";import{EventEmitter as fT}from"events";import bT from"http";import yT from"https";var di,Cm=F(()=>{"use strict";Te();j();di=class extends fT{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new bT.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new yT.Agent({keepAlive:!0,timeout:36e5}),this.client=hT.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=X.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let n=0;n<t;n++)try{return await e()}catch(s){let r=s.response?.status,o=s.code,a=r===429||r>=500&&r<600||o==="ECONNABORTED"||o==="ETIMEDOUT"||o==="ECONNREFUSED"||o==="ENOTFOUND"||o==="ERR_NETWORK";if(r===401||r===403||r===404)throw s;if(a&&n<t-1){let l=Math.pow(2,n+1)*1e3;u.debug(`[NETWORK] Retryable error (${o||r}), attempt ${n+1}/${t}, waiting ${l/1e3}s`),await new Promise(d=>setTimeout(d,l));continue}throw r===429?new Error("Rate limit exceeded. Please try again later."):s}throw new Error("Max retries exceeded")}buildRequest(e,t,n,s=.7,r=.9,o,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:n,temperature:t.name.includes("o4-mini")?void 0:s,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:r,reasoning_effort:t.reasoningEffort,tools:o,tool_choice:a}}async performNonStreamingRequest(e,t,n=.7,s=.9,r,o){let a=this.buildRequest(e,t,!1,n,s,r,o);try{let l=(await this.executeWithRetry(async()=>{let{data:d}=await this.client.post("/chat/completions",a,{headers:this.getAuthHeaders()});return d})).choices[0];return{content:l.message.content||"",toolCalls:l.message.tool_calls}}catch(c){throw this.emit("error",c),new Error(`API Error: ${c.message}`)}}async performStreamingRequest(e,t,n=.7,s=.9,r,o,a,c,l){let{SnowXStreamHandlerService:d}=await Promise.resolve().then(()=>(xm(),Tm)),g=this.buildRequest(e,t,!0,n,s,r,o);return new Promise((m,p)=>{this.currentAbortController=new AbortController;let h=[],f=new Map,y=new d;this.client.post("/chat/completions",g,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async T=>{let x=T.data,w=T.headers["content-type"]||"",C=v=>{if(v?.index!==void 0){let E=v.index;f.has(E)||f.set(E,{});let S=f.get(E);v.id&&(S.id=v.id,S.type="function"),v.function&&(S.function||(S.function={name:"",arguments:""}),v.function.name&&(S.function.name=v.function.name),v.function.arguments&&(S.function.arguments+=v.function.arguments))}l?.(v),this.emit("tool_call_delta",v)};y.on("streamEnd",()=>{f.forEach((v,E)=>{v.id&&v.function?.name&&h.push(v)}),this.emit("done"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})}),y.on("cancelled",()=>{this.emit("canceled"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})});try{await y.processStreamingResponse(x,w,a||(()=>{}),c,C),f.forEach((v,E)=>{v.id&&v.function?.name&&h.push(v)}),this.emit("done"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})}catch(v){this.emit("error",v),p(v)}}).catch(T=>{T.code==="ERR_CANCELED"?(this.emit("canceled"),m({content:"",toolCalls:h.length>0?h:void 0})):p(T)})})}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 vT}from"socket.io-client";import{EventEmitter as ST}from"events";var gi,Em=F(()=>{"use strict";At();gi=class i extends ST{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=Pe.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let n={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=vT(t,n),this.setupEventHandlers(),new Promise((s,r)=>{let o=setTimeout(()=>{r(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(o),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),s(!0)}),this.socket?.on("connect_error",a=>{clearTimeout(o),console.error("❌ WebSocket connection error:",a),r(a)})})}catch(n){return console.error("❌ Failed to connect WebSocket:",n),!1}}setupEventHandlers(){this.socket&&(this.socket.on("connect",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),this.registerDevice()}),this.socket.on("disconnect",e=>{this.isConnected=!1,this.emit("disconnected",e),e==="io server disconnect"&&this.attemptReconnect()}),this.socket.on("connect_error",e=>{console.error("❌ WebSocket connection error:",e),this.emit("connection_error",e),this.attemptReconnect()}),this.socket.on("reconnect",e=>{this.isConnected=!0,this.emit("reconnected",e)}),this.socket.on("reconnect_error",e=>{console.error("❌ WebSocket reconnection error:",e),this.emit("reconnection_error",e)}),this.socket.on("reconnect_failed",()=>{console.error("❌ WebSocket reconnection failed after max attempts"),this.emit("reconnection_failed")}),this.socket.on("cross_device_message",e=>{this.emit("cross_device_message",e),this.handleCrossDeviceMessage(e)}),this.socket.on("conversation_sync",e=>{this.emit("conversation_sync",e),this.handleConversationSync(e)}),this.socket.on("device_status_update",e=>{this.emit("device_status_update",e),this.handleDeviceStatusUpdate(e)}),this.socket.on("typing_indicator",e=>{this.emit("typing_indicator",e)}),this.socket.on("notification",e=>{this.emit("notification",e),this.handleNotification(e)}),this.socket.on("user_activity",e=>{this.emit("user_activity",e)}),this.socket.on("tool_execution",e=>{this.emit("tool_execution",e)}),this.socket.on("operator_progress",e=>{this.emit("operator_progress",e)}),this.socket.on("webview_update",e=>{this.emit("webview_update",e)}),this.socket.on("todo_update",e=>{this.emit("todo_update",e)}))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("❌ Max reconnection attempts reached");return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.socket&&!this.isConnected&&this.socket.connect()},e)}registerDevice(){if(!this.deviceId){console.error("Cannot register device without device ID");return}let e={id:this.deviceId,name:"Orion CLI",type:"cli",platform:process.platform,lastSeen:new Date,isOnline:!0};this.send("register_device",e)}handleCrossDeviceMessage(e){}handleConversationSync(e){}handleDeviceStatusUpdate(e){}handleNotification(e){}send(e,t){if(!this.isConnected||!this.socket)return;let n={type:e,data:t,timestamp:Date.now(),userId:this.userId||void 0,deviceId:this.deviceId||void 0};this.socket.emit(e,n)}sendCrossDeviceMessage(e,t,n){this.send("cross_device_message",{targetDeviceId:e,messageType:t,data:n,sourceDevice:this.deviceId})}shareConversation(e,t){this.sendCrossDeviceMessage(t||null,"conversation_shared",{conversationId:e,action:"share"})}syncModel(e,t){this.sendCrossDeviceMessage(t||null,"model_sync",{model:e,action:"sync"})}sendTypingIndicator(e){this.send("typing_indicator",{isTyping:e,deviceId:this.deviceId})}syncConversation(e,t,n){this.send("conversation_sync",{conversationId:e,action:t,data:n,timestamp:Date.now()})}syncToolExecution(e,t,n){this.send("tool_execution",{toolName:e,status:t,result:n,deviceId:this.deviceId})}sendUserActivity(e){this.send("user_activity",{activity:e,timestamp:Date.now()})}isWebSocketConnected(){return this.isConnected}getDeviceId(){return this.deviceId}getConnectionStatus(){return{connected:this.isConnected,attempts:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.socket&&(this.socket.disconnect(),this.socket=null),this.isConnected=!1,this.emit("disconnected","manual")}destroy(){this.disconnect(),this.removeAllListeners()}}});var Im,km=F(()=>{"use strict";Im={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 Am={};Fe(Am,{ServiceManager:()=>wr});import{EventEmitter as wT}from"events";import{initializeApp as TT,getApps as Pm}from"firebase/app";import{getAuth as xT}from"firebase/auth";var wr,Pc=F(()=>{"use strict";xt();Cm();Te();At();Em();Jn();Ba();Ur();Vt();j();km();wr=class i extends wT{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=je.getInstance(),this.networkClient=new di,this.authService=X.getInstance(),this.deviceRegistration=Pe.getInstance(),this.webSocketService=gi.getInstance(),this.frontendWebSocketService=be.getInstance(),this.crossDeviceService=rs.getInstance(),this.toolCalling=Us.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}isInitialized(){return this.initialized}async initialize(e={}){if(!this.initialized){this.options={...this.options,...e};try{this.options.enableFirebase&&await this.initializeFirebase(),this.options.enableWebSocket&&await this.initializeWebSocket(),this.options.enableCrossDevice&&this.options.enableWebSocket&&await this.initializeCrossDevice(),this.options.enableToolCalling&&await this.initializeToolCalling(),this.setupServiceConnections(),this.initialized=!0,this.emit("initialized")}catch(t){throw t}}}async initializeFirebase(){try{let e=this.options.firebaseConfig||Im;if(Pm().length===0?(this.firebaseApp=TT(e),u.debug("Firebase app initialized")):(this.firebaseApp=Pm()[0],u.debug("Using existing Firebase app")),this.firebaseAuth=xT(this.firebaseApp),u.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),u.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(Ua(),td));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),u.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{u.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){u.debug("Firebase initialization failed - using access token authentication:",e)}}async initializeWebSocket(){}async ensureWebSocketConnection(){if(this.webSocketService.isWebSocketConnected())return!0;let e=this.authService.getUserId();if(!e)return!1;try{return await this.webSocketService.connect(e)}catch{return!1}}async initializeCrossDevice(){this.crossDeviceService.enable()}async initializeToolCalling(){["web_search","calculate","get_current_time","http_request"].forEach(t=>this.toolCalling.enableTool(t))}setupServiceConnections(){this.personalAgent.on("conversation_complete",e=>{this.emit("conversation_complete",e)}),this.personalAgent.on("todo_update",e=>{this.emit("todo_update",e),this.webSocketService.isWebSocketConnected()&&this.webSocketService.send("todo_update",e)}),this.personalAgent.on("tool_use",e=>{this.emit("tool_use",e),this.options.enableToolCalling&&(this.isFrontendTool(e.name)?this.executeFrontendTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}).catch(t=>{this.emit("tool_error",{toolCall:e,error:t})}):this.toolCalling.executeTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}))}),this.authService.on("authenticated",e=>{this.emit("authenticated",e),this.options.enableWebSocket&&!this.webSocketService.isWebSocketConnected()&&this.initializeWebSocket()}),this.webSocketService.on("connected",()=>{this.emit("websocket_connected")}),this.webSocketService.on("cross_device_message",e=>{this.emit("cross_device_message",e)}),this.toolCalling.on("tool_execution_complete",e=>{this.emit("tool_execution_complete",e)})}async sendMessage(e,t=pe[0],n={}){let{usePersonalAgent:s=!0,enableToolCalling:r=this.options.enableToolCalling,temperature:o=.7,stream:a=!0}=n;try{let c=[];if(s)return await this.personalAgent.sendMessageWithToolCalling(e,c,t,o,a,this.authService.getUserId()||void 0);{let l=r?this.toolCalling.getAvailableTools():void 0;return a?new Promise((d,g)=>{let m="";this.networkClient.on("data",p=>{m+=p}),this.networkClient.on("done",()=>{d(m)}),this.networkClient.on("error",g),this.networkClient.performStreamingRequest([...c,{role:"user",content:e}],t,o,.9,l)}):(await this.networkClient.performNonStreamingRequest([...c,{role:"user",content:e}],t,o,.9,l)).content}}catch(c){throw c}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:n}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return pe.filter(e=>this.authService.canAccessModel(e.name))}enableService(e){switch(e){case"firebase":this.options.enableFirebase=!0,this.initialized&&this.initializeFirebase();break;case"websocket":this.options.enableWebSocket=!0,this.initialized&&this.initializeWebSocket();break;case"crossDevice":this.options.enableCrossDevice=!0,this.crossDeviceService.enable();break;case"toolCalling":this.options.enableToolCalling=!0;break}}disableService(e){switch(e){case"firebase":this.options.enableFirebase=!1;break;case"websocket":this.options.enableWebSocket=!1,this.webSocketService.disconnect();break;case"crossDevice":this.options.enableCrossDevice=!1,this.crossDeviceService.disable();break;case"toolCalling":this.options.enableToolCalling=!1;break}}async shutdown(){try{this.personalAgent.stopCurrentOperation(),this.options.enableToolCalling&&this.toolCalling.stopAllRunningTools?.(),this.webSocketService.disconnect(),this.crossDeviceService.destroy(),await this.authService.signOut(),this.initialized=!1,this.emit("shutdown")}catch{}}async waitForDeviceRegistration(e=1e4){if(!this.deviceRegistration.getCurrentDeviceId())return new Promise((n,s)=>{let r=setTimeout(()=>{s(new Error(`Device registration timeout after ${e}ms`))},e),o=c=>{clearTimeout(r),this.deviceRegistration.off("DeviceRegistrationComplete",o),n()};this.deviceRegistration.on("DeviceRegistrationComplete",o),this.deviceRegistration.getCurrentDeviceId()&&(clearTimeout(r),this.deviceRegistration.off("DeviceRegistrationComplete",o),n())})}}});import*as Rc from"@sentry/node";Rc.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as AT}from"commander";import IT from"react";import{render as kT}from"@jrichman/ink";import Z,{useCallback as uT,useState as dT,useEffect as Ic,useMemo as ym,useRef as vm}from"react";import{Box as He,Text as Sm}from"@jrichman/ink";import gT from"ink-spinner";import hi from"terminal-link";import{homedir as Nm}from"os";function Oc(i){let e=i.trim();return e.startsWith("~")&&(e=e.replace("~",Nm())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function _m(i){return i.startsWith("http://")||i.startsWith("https://")||i.startsWith("mailto:")}function Cr(i){let e=i;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,n,s)=>{let r=s;return!_m(s)&&!s.startsWith("file://")&&(s.startsWith("/")||s.startsWith("~")||/\.[a-z]{2,4}$/i.test(s))&&(r=Oc(s)),hi(n,r,{fallback:(o,a)=>`${o} (${a})`})}),e=e.replace(/(https?:\/\/[^\s\)]+)/g,t=>{let n=/\x1b\]8;;/,s=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));return n.test(s)?t:hi(t,t,{fallback:(r,o)=>o})}),e=e.replace(/([/~][^\s:,\)]+\.[a-z]{2,4})/gi,t=>{let n=/\x1b\]8;;/,s=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));if(n.test(s)||s.includes("http"))return t;let r=Oc(t);return hi(t,r,{fallback:(o,a)=>o})}),e}function Er(i){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],n;for(;(n=e.exec(i))!==null;){let o=n[1].split(`
2433
- `).map(a=>a.trim()).filter(a=>a.length>0).map(a=>a.replace(/^Option\s+\d+:\s*/i,"").trim());o.length>0&&t.push({options:o})}let s=i.replace(/<suggestion>[\s\S]*?<\/suggestion>/g,"");return s=s.replace(/<suggestion>[\s\S]*$/g,""),{suggestions:t,cleanedContent:s}}function Nc(i){let e=/<working-files>([\s\S]*?)<\/working-files>/g,t=[],n=new Set,s;for(;(s=e.exec(i))!==null;){let o=s[1],a=/\[([^\]]+)\]\(<?([^>)]+)>?\)/g,c;for(;(c=a.exec(o))!==null;){let l=c[1],d=c[2];n.has(d)||(n.add(d),t.push({name:l,path:d}))}}let r=i.replace(/<working-files>[\s\S]*?<\/working-files>/g,"");return r=r.replace(/<working-files>[\s\S]*$/g,""),{workingFiles:t,cleanedContent:r}}function _c(i){let e=/<conversation_history>([\s\S]*?)<\/conversation_history>/g,t=[],n;for(;(n=e.exec(i))!==null;){let r=n[1],o=/^\s*(.+?)\s*\(<([^>]+)>\)\s*$/gm,a;for(;(a=o.exec(r))!==null;){let c=a[1].trim(),l=a[2].trim();c&&l&&t.push({title:c,id:l})}}let s=i.replace(/<conversation_history>[\s\S]*?<\/conversation_history>/g,"");return s=s.replace(/<conversation_history>[\s\S]*$/g,""),{conversationHistory:t,cleanedContent:s}}function fi(i){let e=i;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=Cr(e),e}function $c(i){return i.replace(/\[TOOL:[^\]]+\]/g,"").trim()}import Fn from"react";Te();import cs,{createContext as ds,useContext as $t,useState as fd,useCallback as Ga,useRef as On,useEffect as Ut,useMemo as ls}from"react";import{useApp as yy}from"@jrichman/ink";xt();Li();import pt from"chalk";import Hb from"ora";var ke=class{static spinner=null;static formatUserMessage(e){return pt.cyan("You: ")+e}static formatAssistantMessage(e){return pt.green("Assistant: ")+e}static formatError(e){return pt.red("Error: ")+e}static formatWarning(e){return pt.yellow("Warning: ")+e}static formatInfo(e){return pt.blue("Info: ")+e}static formatSuccess(e){return pt.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=Hb(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(pt.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(pt.bold.cyan(e)),console.log(pt.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return pt.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return pt.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(pt.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};j();zn();Kn();import{EventEmitter as Gb}from"events";import _a from"chalk";var No=class extends Gb{delegate=null;personalAgentService=je.getInstance();currentStreamingTask=null;constructor(e){super(),this.delegate=e||null,this.setupPersonalAgentService()}setupPersonalAgentService(){let e=!0,t="",n=console.log;this.delegate?.usesCustomUI||(console.log=(...s)=>{let r=String(s[0]||"");(r.includes("▸")||r.includes("→")||r.includes("✎"))&&t&&(e&&(e=!1),t=""),n.apply(console,s)}),this.personalAgentService.on("data",s=>{if(t+=s,this.delegate){let r=this.delegate.messages[this.delegate.messages.length-1],o=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];r&&r.isStreaming&&(!r.content||r.content===""?r.content=s:r.content+=s),o&&o.isStreaming&&(!o.content||o.content===""?o.content=s:o.content+=s)}}),this.personalAgentService.on("thinking",s=>{}),this.personalAgentService.on("toolExecuting",s=>{this.delegate?.usesCustomUI||console.log(`
2432
+ `);if(t!==-1)return t;let n=this.buffer.indexOf("\r");return n!==-1?n:-1}printFinalStatistics(){this.regularContentParts.length}cancel(){this.isCancelled=!0,this.emit("cancelled")}reset(){this.buffer="",this.totalBytesReceived=0,this.linesProcessed=0,this.dataLinesFound=0,this.contentChunksReceived=0,this.rawDataReceived="",this.byteChunks=[],this.byteChunksLength=0,this.thinkingContentParts=[],this.regularContentParts=[],this.isInThinkingBlock=!1,this.thinkingBuffer="",this.accumulatedToolCalls.clear(),this.toolCallIndexToId.clear(),this.processedToolCallIds.clear(),this.isCancelled=!1}getStats(){return{totalBytesReceived:this.totalBytesReceived,linesProcessed:this.linesProcessed,dataLinesFound:this.dataLinesFound,contentChunksReceived:this.contentChunksReceived}}getFinalResponse(){return this.regularContentParts.join("")}getThinkingContent(){return this.thinkingContentParts.join("")}getAccumulatedToolCalls(){return this.accumulatedToolCalls}isToolCallProcessed(e){return this.processedToolCallIds.has(e)}markToolCallProcessed(e){this.processedToolCallIds.add(e)}}});import hT from"axios";import{EventEmitter as fT}from"events";import bT from"http";import yT from"https";var di,Cm=$(()=>{"use strict";xe();z();di=class extends fT{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new bT.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new yT.Agent({keepAlive:!0,timeout:36e5}),this.client=hT.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=X.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let n=0;n<t;n++)try{return await e()}catch(s){let r=s.response?.status,o=s.code,a=r===429||r>=500&&r<600||o==="ECONNABORTED"||o==="ETIMEDOUT"||o==="ECONNREFUSED"||o==="ENOTFOUND"||o==="ERR_NETWORK";if(r===401||r===403||r===404)throw s;if(a&&n<t-1){let l=Math.pow(2,n+1)*1e3;u.debug(`[NETWORK] Retryable error (${o||r}), attempt ${n+1}/${t}, waiting ${l/1e3}s`),await new Promise(d=>setTimeout(d,l));continue}throw r===429?new Error("Rate limit exceeded. Please try again later."):s}throw new Error("Max retries exceeded")}buildRequest(e,t,n,s=.7,r=.9,o,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:n,temperature:t.name.includes("o4-mini")?void 0:s,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:r,reasoning_effort:t.reasoningEffort,tools:o,tool_choice:a}}async performNonStreamingRequest(e,t,n=.7,s=.9,r,o){let a=this.buildRequest(e,t,!1,n,s,r,o);try{let l=(await this.executeWithRetry(async()=>{let{data:d}=await this.client.post("/chat/completions",a,{headers:this.getAuthHeaders()});return d})).choices[0];return{content:l.message.content||"",toolCalls:l.message.tool_calls}}catch(c){throw this.emit("error",c),new Error(`API Error: ${c.message}`)}}async performStreamingRequest(e,t,n=.7,s=.9,r,o,a,c,l){let{SnowXStreamHandlerService:d}=await Promise.resolve().then(()=>(xm(),Tm)),g=this.buildRequest(e,t,!0,n,s,r,o);return new Promise((m,p)=>{this.currentAbortController=new AbortController;let h=[],f=new Map,y=new d;this.client.post("/chat/completions",g,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async T=>{let C=T.data,w=T.headers["content-type"]||"",E=v=>{if(v?.index!==void 0){let x=v.index;f.has(x)||f.set(x,{});let S=f.get(x);v.id&&(S.id=v.id,S.type="function"),v.function&&(S.function||(S.function={name:"",arguments:""}),v.function.name&&(S.function.name=v.function.name),v.function.arguments&&(S.function.arguments+=v.function.arguments))}l?.(v),this.emit("tool_call_delta",v)};y.on("streamEnd",()=>{f.forEach((v,x)=>{v.id&&v.function?.name&&h.push(v)}),this.emit("done"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})}),y.on("cancelled",()=>{this.emit("canceled"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})});try{await y.processStreamingResponse(C,w,a||(()=>{}),c,E),f.forEach((v,x)=>{v.id&&v.function?.name&&h.push(v)}),this.emit("done"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})}catch(v){this.emit("error",v),p(v)}}).catch(T=>{T.code==="ERR_CANCELED"?(this.emit("canceled"),m({content:"",toolCalls:h.length>0?h:void 0})):p(T)})})}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 vT}from"socket.io-client";import{EventEmitter as ST}from"events";var gi,Em=$(()=>{"use strict";At();gi=class i extends ST{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=Ae.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let n={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=vT(t,n),this.setupEventHandlers(),new Promise((s,r)=>{let o=setTimeout(()=>{r(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(o),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),s(!0)}),this.socket?.on("connect_error",a=>{clearTimeout(o),console.error("❌ WebSocket connection error:",a),r(a)})})}catch(n){return console.error("❌ Failed to connect WebSocket:",n),!1}}setupEventHandlers(){this.socket&&(this.socket.on("connect",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),this.registerDevice()}),this.socket.on("disconnect",e=>{this.isConnected=!1,this.emit("disconnected",e),e==="io server disconnect"&&this.attemptReconnect()}),this.socket.on("connect_error",e=>{console.error("❌ WebSocket connection error:",e),this.emit("connection_error",e),this.attemptReconnect()}),this.socket.on("reconnect",e=>{this.isConnected=!0,this.emit("reconnected",e)}),this.socket.on("reconnect_error",e=>{console.error("❌ WebSocket reconnection error:",e),this.emit("reconnection_error",e)}),this.socket.on("reconnect_failed",()=>{console.error("❌ WebSocket reconnection failed after max attempts"),this.emit("reconnection_failed")}),this.socket.on("cross_device_message",e=>{this.emit("cross_device_message",e),this.handleCrossDeviceMessage(e)}),this.socket.on("conversation_sync",e=>{this.emit("conversation_sync",e),this.handleConversationSync(e)}),this.socket.on("device_status_update",e=>{this.emit("device_status_update",e),this.handleDeviceStatusUpdate(e)}),this.socket.on("typing_indicator",e=>{this.emit("typing_indicator",e)}),this.socket.on("notification",e=>{this.emit("notification",e),this.handleNotification(e)}),this.socket.on("user_activity",e=>{this.emit("user_activity",e)}),this.socket.on("tool_execution",e=>{this.emit("tool_execution",e)}),this.socket.on("operator_progress",e=>{this.emit("operator_progress",e)}),this.socket.on("webview_update",e=>{this.emit("webview_update",e)}),this.socket.on("todo_update",e=>{this.emit("todo_update",e)}))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("❌ Max reconnection attempts reached");return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.socket&&!this.isConnected&&this.socket.connect()},e)}registerDevice(){if(!this.deviceId){console.error("Cannot register device without device ID");return}let e={id:this.deviceId,name:"Orion CLI",type:"cli",platform:process.platform,lastSeen:new Date,isOnline:!0};this.send("register_device",e)}handleCrossDeviceMessage(e){}handleConversationSync(e){}handleDeviceStatusUpdate(e){}handleNotification(e){}send(e,t){if(!this.isConnected||!this.socket)return;let n={type:e,data:t,timestamp:Date.now(),userId:this.userId||void 0,deviceId:this.deviceId||void 0};this.socket.emit(e,n)}sendCrossDeviceMessage(e,t,n){this.send("cross_device_message",{targetDeviceId:e,messageType:t,data:n,sourceDevice:this.deviceId})}shareConversation(e,t){this.sendCrossDeviceMessage(t||null,"conversation_shared",{conversationId:e,action:"share"})}syncModel(e,t){this.sendCrossDeviceMessage(t||null,"model_sync",{model:e,action:"sync"})}sendTypingIndicator(e){this.send("typing_indicator",{isTyping:e,deviceId:this.deviceId})}syncConversation(e,t,n){this.send("conversation_sync",{conversationId:e,action:t,data:n,timestamp:Date.now()})}syncToolExecution(e,t,n){this.send("tool_execution",{toolName:e,status:t,result:n,deviceId:this.deviceId})}sendUserActivity(e){this.send("user_activity",{activity:e,timestamp:Date.now()})}isWebSocketConnected(){return this.isConnected}getDeviceId(){return this.deviceId}getConnectionStatus(){return{connected:this.isConnected,attempts:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.socket&&(this.socket.disconnect(),this.socket=null),this.isConnected=!1,this.emit("disconnected","manual")}destroy(){this.disconnect(),this.removeAllListeners()}}});var Im,km=$(()=>{"use strict";Im={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 Am={};Le(Am,{ServiceManager:()=>Tr});import{EventEmitter as wT}from"events";import{initializeApp as TT,getApps as Pm}from"firebase/app";import{getAuth as xT}from"firebase/auth";var Tr,Pc=$(()=>{"use strict";xt();Cm();xe();At();Em();es();Ba();Br();Xt();z();km();Tr=class i extends wT{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=ze.getInstance(),this.networkClient=new di,this.authService=X.getInstance(),this.deviceRegistration=Ae.getInstance(),this.webSocketService=gi.getInstance(),this.frontendWebSocketService=be.getInstance(),this.crossDeviceService=is.getInstance(),this.toolCalling=Bs.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}isInitialized(){return this.initialized}async initialize(e={}){if(!this.initialized){this.options={...this.options,...e};try{this.options.enableFirebase&&await this.initializeFirebase(),this.options.enableWebSocket&&await this.initializeWebSocket(),this.options.enableCrossDevice&&this.options.enableWebSocket&&await this.initializeCrossDevice(),this.options.enableToolCalling&&await this.initializeToolCalling(),this.setupServiceConnections(),this.initialized=!0,this.emit("initialized")}catch(t){throw t}}}async initializeFirebase(){try{let e=this.options.firebaseConfig||Im;if(Pm().length===0?(this.firebaseApp=TT(e),u.debug("Firebase app initialized")):(this.firebaseApp=Pm()[0],u.debug("Using existing Firebase app")),this.firebaseAuth=xT(this.firebaseApp),u.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),u.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(Ua(),td));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),u.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{u.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){u.debug("Firebase initialization failed - using access token authentication:",e)}}async initializeWebSocket(){}async ensureWebSocketConnection(){if(this.webSocketService.isWebSocketConnected())return!0;let e=this.authService.getUserId();if(!e)return!1;try{return await this.webSocketService.connect(e)}catch{return!1}}async initializeCrossDevice(){this.crossDeviceService.enable()}async initializeToolCalling(){["web_search","calculate","get_current_time","http_request"].forEach(t=>this.toolCalling.enableTool(t))}setupServiceConnections(){this.personalAgent.on("conversation_complete",e=>{this.emit("conversation_complete",e)}),this.personalAgent.on("todo_update",e=>{this.emit("todo_update",e),this.webSocketService.isWebSocketConnected()&&this.webSocketService.send("todo_update",e)}),this.personalAgent.on("tool_use",e=>{this.emit("tool_use",e),this.options.enableToolCalling&&(this.isFrontendTool(e.name)?this.executeFrontendTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}).catch(t=>{this.emit("tool_error",{toolCall:e,error:t})}):this.toolCalling.executeTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}))}),this.authService.on("authenticated",e=>{this.emit("authenticated",e),this.options.enableWebSocket&&!this.webSocketService.isWebSocketConnected()&&this.initializeWebSocket()}),this.webSocketService.on("connected",()=>{this.emit("websocket_connected")}),this.webSocketService.on("cross_device_message",e=>{this.emit("cross_device_message",e)}),this.toolCalling.on("tool_execution_complete",e=>{this.emit("tool_execution_complete",e)})}async sendMessage(e,t=pe[0],n={}){let{usePersonalAgent:s=!0,enableToolCalling:r=this.options.enableToolCalling,temperature:o=.7,stream:a=!0}=n;try{let c=[];if(s)return await this.personalAgent.sendMessageWithToolCalling(e,c,t,o,a,this.authService.getUserId()||void 0);{let l=r?this.toolCalling.getAvailableTools():void 0;return a?new Promise((d,g)=>{let m="";this.networkClient.on("data",p=>{m+=p}),this.networkClient.on("done",()=>{d(m)}),this.networkClient.on("error",g),this.networkClient.performStreamingRequest([...c,{role:"user",content:e}],t,o,.9,l)}):(await this.networkClient.performNonStreamingRequest([...c,{role:"user",content:e}],t,o,.9,l)).content}}catch(c){throw c}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:n}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return pe.filter(e=>this.authService.canAccessModel(e.name))}enableService(e){switch(e){case"firebase":this.options.enableFirebase=!0,this.initialized&&this.initializeFirebase();break;case"websocket":this.options.enableWebSocket=!0,this.initialized&&this.initializeWebSocket();break;case"crossDevice":this.options.enableCrossDevice=!0,this.crossDeviceService.enable();break;case"toolCalling":this.options.enableToolCalling=!0;break}}disableService(e){switch(e){case"firebase":this.options.enableFirebase=!1;break;case"websocket":this.options.enableWebSocket=!1,this.webSocketService.disconnect();break;case"crossDevice":this.options.enableCrossDevice=!1,this.crossDeviceService.disable();break;case"toolCalling":this.options.enableToolCalling=!1;break}}async shutdown(){try{this.personalAgent.stopCurrentOperation(),this.options.enableToolCalling&&this.toolCalling.stopAllRunningTools?.(),this.webSocketService.disconnect(),this.crossDeviceService.destroy(),await this.authService.signOut(),this.initialized=!1,this.emit("shutdown")}catch{}}async waitForDeviceRegistration(e=1e4){if(!this.deviceRegistration.getCurrentDeviceId())return new Promise((n,s)=>{let r=setTimeout(()=>{s(new Error(`Device registration timeout after ${e}ms`))},e),o=c=>{clearTimeout(r),this.deviceRegistration.off("DeviceRegistrationComplete",o),n()};this.deviceRegistration.on("DeviceRegistrationComplete",o),this.deviceRegistration.getCurrentDeviceId()&&(clearTimeout(r),this.deviceRegistration.off("DeviceRegistrationComplete",o),n())})}}});import*as Rc from"@sentry/node";Rc.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as AT}from"commander";import IT from"react";import{render as kT}from"@jrichman/ink";import ee,{useCallback as uT,useState as dT,useEffect as Ic,useMemo as ym,useRef as vm}from"react";import{Box as Ge,Text as Sm}from"@jrichman/ink";import gT from"ink-spinner";import hi from"terminal-link";import{homedir as Nm}from"os";function Oc(i){let e=i.trim();return e.startsWith("~")&&(e=e.replace("~",Nm())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function _m(i){return i.startsWith("http://")||i.startsWith("https://")||i.startsWith("mailto:")}function Er(i){let e=i;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,n,s)=>{let r=s;return!_m(s)&&!s.startsWith("file://")&&(s.startsWith("/")||s.startsWith("~")||/\.[a-z]{2,4}$/i.test(s))&&(r=Oc(s)),hi(n,r,{fallback:(o,a)=>`${o} (${a})`})}),e=e.replace(/(https?:\/\/[^\s\)]+)/g,t=>{let n=/\x1b\]8;;/,s=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));return n.test(s)?t:hi(t,t,{fallback:(r,o)=>o})}),e=e.replace(/([/~][^\s:,\)]+\.[a-z]{2,4})/gi,t=>{let n=/\x1b\]8;;/,s=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));if(n.test(s)||s.includes("http"))return t;let r=Oc(t);return hi(t,r,{fallback:(o,a)=>o})}),e}function Ir(i){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],n;for(;(n=e.exec(i))!==null;){let o=n[1].split(`
2433
+ `).map(a=>a.trim()).filter(a=>a.length>0).map(a=>a.replace(/^Option\s+\d+:\s*/i,"").trim());o.length>0&&t.push({options:o})}let s=i.replace(/<suggestion>[\s\S]*?<\/suggestion>/g,"");return s=s.replace(/<suggestion>[\s\S]*$/g,""),{suggestions:t,cleanedContent:s}}function Nc(i){let e=/<working-files>([\s\S]*?)<\/working-files>/g,t=[],n=new Set,s;for(;(s=e.exec(i))!==null;){let o=s[1],a=/\[([^\]]+)\]\(<?([^>)]+)>?\)/g,c;for(;(c=a.exec(o))!==null;){let l=c[1],d=c[2];n.has(d)||(n.add(d),t.push({name:l,path:d}))}}let r=i.replace(/<working-files>[\s\S]*?<\/working-files>/g,"");return r=r.replace(/<working-files>[\s\S]*$/g,""),{workingFiles:t,cleanedContent:r}}function _c(i){let e=/<conversation_history>([\s\S]*?)<\/conversation_history>/g,t=[],n;for(;(n=e.exec(i))!==null;){let r=n[1],o=/^\s*(.+?)\s*\(<([^>]+)>\)\s*$/gm,a;for(;(a=o.exec(r))!==null;){let c=a[1].trim(),l=a[2].trim();c&&l&&t.push({title:c,id:l})}}let s=i.replace(/<conversation_history>[\s\S]*?<\/conversation_history>/g,"");return s=s.replace(/<conversation_history>[\s\S]*$/g,""),{conversationHistory:t,cleanedContent:s}}function fi(i){let e=i;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=Er(e),e}function $c(i){return i.replace(/\[TOOL:[^\]]+\]/g,"").trim()}import Un from"react";xe();import us,{createContext as ms,useContext as $t,useState as fd,useCallback as Ga,useRef as _n,useEffect as Bt,useMemo as ds}from"react";import{useApp as yy}from"@jrichman/ink";xt();Li();import pt from"chalk";import Hb from"ora";var Pe=class{static spinner=null;static formatUserMessage(e){return pt.cyan("You: ")+e}static formatAssistantMessage(e){return pt.green("Assistant: ")+e}static formatError(e){return pt.red("Error: ")+e}static formatWarning(e){return pt.yellow("Warning: ")+e}static formatInfo(e){return pt.blue("Info: ")+e}static formatSuccess(e){return pt.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=Hb(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(pt.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(pt.bold.cyan(e)),console.log(pt.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return pt.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return pt.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(pt.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};z();Kn();Xn();import{EventEmitter as Gb}from"events";import _a from"chalk";var No=class extends Gb{delegate=null;personalAgentService=ze.getInstance();currentStreamingTask=null;constructor(e){super(),this.delegate=e||null,this.setupPersonalAgentService()}setupPersonalAgentService(){let e=!0,t="",n=console.log;this.delegate?.usesCustomUI||(console.log=(...s)=>{let r=String(s[0]||"");(r.includes("▸")||r.includes("→")||r.includes("✎"))&&t&&(e&&(e=!1),t=""),n.apply(console,s)}),this.personalAgentService.on("data",s=>{if(t+=s,this.delegate){let r=this.delegate.messages[this.delegate.messages.length-1],o=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];r&&r.isStreaming&&(!r.content||r.content===""?r.content=s:r.content+=s),o&&o.isStreaming&&(!o.content||o.content===""?o.content=s:o.content+=s)}}),this.personalAgentService.on("thinking",s=>{}),this.personalAgentService.on("toolExecuting",s=>{this.delegate?.usesCustomUI||console.log(`
2434
2434
  ▸ ${s}`)}),this.personalAgentService.on("tool_completed",s=>{if(!this.delegate?.usesCustomUI){let{toolName:r,success:o,error:a}=s;console.log(o!==!1?`✓ ${r}`:`✗ ${r} failed${a?": "+a.substring(0,50):""}`)}}),this.personalAgentService.on("toolComplete",s=>{}),this.personalAgentService.on("todo_update",s=>{}),this.personalAgentService.on("operator_progress",s=>{}),this.personalAgentService.on("webview_update",s=>{}),this.personalAgentService.on("done",()=>{if(e&&(e=!1),t&&(t=""),e=!0,this.delegate){let s=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];s&&s.isStreaming&&(s.isStreaming=!1),r&&r.isStreaming&&(r.isStreaming=!1),this.delegate.isLoading=!1}}),this.personalAgentService.on("error",s=>{console.error(`
2435
- ❌ Error:`,s.message||s),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",s=>{if(u.debug("[PERSONAL AGENT] Conversation completed"),this.delegate){let r=this.delegate.messages[this.delegate.messages.length-1],o=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];r&&r.isStreaming&&(s.content&&s.content.trim()?(u.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${s.content.substring(0,50)}..."`),r.content=s.content,r.originalContent=s.content):u.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),s.completeWithTools&&(r.metadata={toolResults:s.completeWithTools}),r.isStreaming=!1,u.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),o&&o.isStreaming&&(s.content&&s.content.trim()?(u.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${s.content.substring(0,50)}..."`),o.content=s.content,o.originalContent=s.content):u.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),s.completeWithTools&&(o.metadata={toolResults:s.completeWithTools}),o.isStreaming=!1),this.delegate.isLoading=!1,this.delegate.updateCurrentConversation()}})}setDelegate(e){this.delegate=e}async sendMessage(e,t,n=!0){if(!this.delegate||!e.trim())return;let s=new lt,r=e.trim(),o=s.count(r);if(o>qn){console.log(ke.formatError(`Prompt too large (${o.toLocaleString()} tokens). Please reduce it to ${qn.toLocaleString()} tokens or less.`));return}if(this.delegate.isLoading){let l=ct.getInstance();l.addToQueue({content:r,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(_a.blue(`⚡ Message queued (${l.getQueueCount()} in queue)`)),console.log(_a.dim(" Your feedback will be sent when AI completes current task"))):console.log(_a.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let a=null;this.delegate.isVisionEnabled&&(a=await Zn.getInstance().captureScreen(),a?u.debug(`[MESSAGE HANDLER] Captured screenshot for vision mode: ${a.length} chars`):u.debug("[MESSAGE HANDLER] Failed to capture screenshot, sending message without vision"));let c=[];t&&t.length>0&&(c.push(...t),u.debug(`[MESSAGE HANDLER] Received ${t.length} image attachments`)),a&&c.push(a),this.delegate.currentInput="";try{n?await this.processStreamingMessage(c.length>0?c:void 0):await this.processNonStreamingMessage(c.length>0?c:void 0)}catch(l){console.error(ke.formatError(`Message failed: ${l.message}`)),this.delegate.isLoading=!1,this.emit("BotResponseError",l.message)}}async processStreamingMessage(e){if(this.delegate)try{u.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(r=>!(r.isStreaming||r.role==="system"||!r.content||typeof r.content=="string"&&r.content.trim().length===0)).map(r=>({role:r.role,content:r.content})),n=this.delegate.fullConversationHistory.filter(r=>r.role==="user"),s=n[n.length-1];if(s)try{let r={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(s.content,t,this.delegate.selectedModel,.7,!0,void 0,e,r),u.debug("[MESSAGE HANDLER] PersonalAgentService processing complete")}catch(r){throw u.debug(`[MESSAGE HANDLER] PersonalAgentService error: ${r.message}`),r}}async processNonStreamingMessage(e){throw new Error("processNonStreamingMessage is deprecated - PersonalAgentService handles all conversations")}stopStreaming(){if(this.currentStreamingTask&&(this.currentStreamingTask.abort(),this.currentStreamingTask=null),this.delegate){let e="",t=this.delegate.messages.find(s=>s.isStreaming);if(t){if(e=t.content,!t.content.includes("[STOPPED]")&&!t.content.includes("[DONE]")){let r=t.content;r.trim().length>0&&(r+=`
2435
+ ❌ Error:`,s.message||s),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",s=>{if(u.debug("[PERSONAL AGENT] Conversation completed"),this.delegate){let r=this.delegate.messages[this.delegate.messages.length-1],o=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];r&&r.isStreaming&&(s.content&&s.content.trim()?(u.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${s.content.substring(0,50)}..."`),r.content=s.content,r.originalContent=s.content):u.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),s.completeWithTools&&(r.metadata={toolResults:s.completeWithTools}),r.isStreaming=!1,u.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),o&&o.isStreaming&&(s.content&&s.content.trim()?(u.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${s.content.substring(0,50)}..."`),o.content=s.content,o.originalContent=s.content):u.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),s.completeWithTools&&(o.metadata={toolResults:s.completeWithTools}),o.isStreaming=!1),this.delegate.isLoading=!1,this.delegate.updateCurrentConversation()}})}setDelegate(e){this.delegate=e}async sendMessage(e,t,n=!0){if(!this.delegate||!e.trim())return;let s=new lt,r=e.trim(),o=s.count(r);if(o>Vn){console.log(Pe.formatError(`Prompt too large (${o.toLocaleString()} tokens). Please reduce it to ${Vn.toLocaleString()} tokens or less.`));return}if(this.delegate.isLoading){let l=ct.getInstance();l.addToQueue({content:r,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(_a.blue(`⚡ Message queued (${l.getQueueCount()} in queue)`)),console.log(_a.dim(" Your feedback will be sent when AI completes current task"))):console.log(_a.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let a=null;this.delegate.isVisionEnabled&&(a=await ts.getInstance().captureScreen(),a?u.debug(`[MESSAGE HANDLER] Captured screenshot for vision mode: ${a.length} chars`):u.debug("[MESSAGE HANDLER] Failed to capture screenshot, sending message without vision"));let c=[];t&&t.length>0&&(c.push(...t),u.debug(`[MESSAGE HANDLER] Received ${t.length} image attachments`)),a&&c.push(a),this.delegate.currentInput="";try{n?await this.processStreamingMessage(c.length>0?c:void 0):await this.processNonStreamingMessage(c.length>0?c:void 0)}catch(l){console.error(Pe.formatError(`Message failed: ${l.message}`)),this.delegate.isLoading=!1,this.emit("BotResponseError",l.message)}}async processStreamingMessage(e){if(this.delegate)try{u.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(r=>!(r.isStreaming||r.role==="system"||!r.content||typeof r.content=="string"&&r.content.trim().length===0)).map(r=>({role:r.role,content:r.content})),n=this.delegate.fullConversationHistory.filter(r=>r.role==="user"),s=n[n.length-1];if(s)try{let r={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(s.content,t,this.delegate.selectedModel,.7,!0,void 0,e,r),u.debug("[MESSAGE HANDLER] PersonalAgentService processing complete")}catch(r){throw u.debug(`[MESSAGE HANDLER] PersonalAgentService error: ${r.message}`),r}}async processNonStreamingMessage(e){throw new Error("processNonStreamingMessage is deprecated - PersonalAgentService handles all conversations")}stopStreaming(){if(this.currentStreamingTask&&(this.currentStreamingTask.abort(),this.currentStreamingTask=null),this.delegate){let e="",t=this.delegate.messages.find(s=>s.isStreaming);if(t){if(e=t.content,!t.content.includes("[STOPPED]")&&!t.content.includes("[DONE]")){let r=t.content;r.trim().length>0&&(r+=`
2436
2436
 
2437
- `),r+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=r}t.isStreaming=!1;let s=this.delegate.fullConversationHistory.find(r=>r.isStreaming);s&&(s.content=t.content,s.isStreaming=!1)}this.delegate.isLoading=!1,je.getInstance().stopStreaming().catch(s=>{u.error("[MESSAGE HANDLER] Error in comprehensive stop:",s)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};xt();zn();Jn();Ba();Ei();j();import{EventEmitter as Qb}from"events";import Jb from"axios";import{spawn as Zb,execSync as ey}from"child_process";import _o from"chalk";import Mn from"fs";import Rn from"path";import os from"os";import{getUserAgent as ty}from"package-manager-detector/detect";import{resolveCommand as ny}from"package-manager-detector/commands";var sy={enabled:!0,checkIntervalMs:1440*60*1e3},nd=/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.-]+))?(?:\+([a-zA-Z0-9.-]+))?$/,is=class i extends Qb{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;config;cacheFilePath;updateCompleted=!1;constructor(e,t){super(),this.currentVersion=e,this.config={...sy,...t},this.cacheFilePath=Rn.join(os.homedir(),".orion","update-cache.json")}static getInstance(e,t){return i.instance||(i.instance=new i(e,t)),i.instance}static getExistingInstance(){return i.instance||null}static resetInstance(){i.instance=void 0}isEnabled(){return this.config.enabled}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}async checkAndUpdate(){if(!this.config.enabled){u.debug("Auto-update is disabled");return}if(!this.isChecking){if(!this.shouldCheckForUpdates()){u.debug("Skipping update check - within cooldown period");return}this.isChecking=!0;try{let e=await this.fetchLatestVersion();if(!this.isValidVersion(e)){u.debug(`Invalid version format from registry: ${e}`);return}this.saveCache({lastCheck:Date.now(),latestVersion:e}),this.isNewerVersion(e,this.currentVersion)?await this.performUpdate(e):u.debug(`Already on latest version: ${this.currentVersion}`)}catch(e){u.debug("Update check failed:",e)}finally{this.isChecking=!1}}}shouldCheckForUpdates(){let e=this.loadCache();return e?Date.now()-e.lastCheck>=this.config.checkIntervalMs:!0}loadCache(){try{if(Mn.existsSync(this.cacheFilePath)){let e=Mn.readFileSync(this.cacheFilePath,"utf8");return JSON.parse(e)}}catch(e){u.debug("Failed to load update cache:",e)}return null}saveCache(e){try{let t=Rn.dirname(this.cacheFilePath);Mn.existsSync(t)||Mn.mkdirSync(t,{recursive:!0}),Mn.writeFileSync(this.cacheFilePath,JSON.stringify(e,null,2))}catch(t){u.debug("Failed to save update cache:",t)}}isValidVersion(e){return!e||typeof e!="string"?!1:nd.test(e)}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`,n=(await Jb.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"]?.latest;if(!n)throw new Error("No latest version found in registry response");return n}isNewerVersion(e,t){let n=this.parseVersion(e),s=this.parseVersion(t);if(!n||!s)return u.debug("Failed to parse versions for comparison",{latest:e,current:t}),!1;for(let r=0;r<3;r++){if(n.numbers[r]>s.numbers[r])return!0;if(n.numbers[r]<s.numbers[r])return!1}return!n.prerelease&&s.prerelease?!0:n.prerelease&&!s.prerelease?!1:n.prerelease&&s.prerelease?this.comparePrerelease(n.prerelease,s.prerelease)>0:!1}parseVersion(e){let t=e.match(nd);return t?{numbers:[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)],prerelease:t[4]||null}:null}comparePrerelease(e,t){let n=e.split("."),s=t.split(".");for(let r=0;r<Math.max(n.length,s.length);r++){let o=n[r],a=s[r];if(o===void 0)return-1;if(a===void 0)return 1;let c=parseInt(o,10),l=parseInt(a,10);if(!isNaN(c)&&!isNaN(l)){if(c!==l)return c-l;continue}if(!isNaN(c))return-1;if(!isNaN(l))return 1;if(o!==a)return o.localeCompare(a)}return 0}detectGlobalPackageManager(){let e=ty();if(e)return u.debug(`Detected package manager from user agent: ${e}`),e;let t=process.argv[1]||"";return[process.env.PNPM_HOME,Rn.join(os.homedir(),".local","share","pnpm"),Rn.join(os.homedir(),"Library","pnpm")].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected pnpm from installation path"),"pnpm"):[Rn.join(os.homedir(),".yarn"),Rn.join(os.homedir(),".config","yarn"),process.env.YARN_GLOBAL_FOLDER].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected yarn from installation path"),"yarn"):[Rn.join(os.homedir(),".bun"),process.env.BUN_INSTALL].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected bun from installation path"),"bun"):(u.debug("Defaulting to npm"),"npm")}isCommandAvailable(e){try{let t=process.platform==="win32"?"where":"which";return ey(`${t} ${e}`,{stdio:"ignore"}),!0}catch{return!1}}async getInstallCommand(){let e=`${this.packageName}@latest`,t=this.detectGlobalPackageManager(),n=this.isCommandAvailable(t)?t:["npm","pnpm","yarn","bun"].find(r=>r!==t&&this.isCommandAvailable(r))||"npm";n!==t&&u.debug(`Detected ${t} not available, falling back to ${n}`);let s=ny(n,"global",[e]);return s?(u.debug(`Using package manager: ${n} -> ${s.command} ${s.args.join(" ")}`),{command:s.command,args:s.args}):(u.debug("Falling back to npm install -g"),{command:"npm",args:["install","-g",e]})}async performUpdate(e){try{let{command:t,args:n}=await this.getInstallCommand();return u.debug(`Auto-updating from ${this.currentVersion} to ${e} using ${t}`),new Promise(s=>{let r=Zb(t,n,{stdio:"pipe",shell:process.platform==="win32",detached:!1}),o="";r.stderr?.on("data",a=>{o+=a.toString()}),r.on("close",a=>{a===0?(this.updateCompleted=!0,this.emit("updated",{from:this.currentVersion,to:e}),setImmediate(()=>{this.isUserInteracting()?this.emit("update_notification_pending",{from:this.currentVersion,to:e}):console.log(_o.green(`
2437
+ `),r+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=r}t.isStreaming=!1;let s=this.delegate.fullConversationHistory.find(r=>r.isStreaming);s&&(s.content=t.content,s.isStreaming=!1)}this.delegate.isLoading=!1,ze.getInstance().stopStreaming().catch(s=>{u.error("[MESSAGE HANDLER] Error in comprehensive stop:",s)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};xt();Kn();es();Ba();Ei();z();import{EventEmitter as Qb}from"events";import Jb from"axios";import{spawn as Zb,execSync as ey}from"child_process";import _o from"chalk";import On from"fs";import Nn from"path";import as from"os";import{getUserAgent as ty}from"package-manager-detector/detect";import{resolveCommand as ny}from"package-manager-detector/commands";var sy={enabled:!0,checkIntervalMs:1440*60*1e3},nd=/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.-]+))?(?:\+([a-zA-Z0-9.-]+))?$/,cs=class i extends Qb{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;config;cacheFilePath;updateCompleted=!1;constructor(e,t){super(),this.currentVersion=e,this.config={...sy,...t},this.cacheFilePath=Nn.join(as.homedir(),".orion","update-cache.json")}static getInstance(e,t){return i.instance||(i.instance=new i(e,t)),i.instance}static getExistingInstance(){return i.instance||null}static resetInstance(){i.instance=void 0}isEnabled(){return this.config.enabled}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}async checkAndUpdate(){if(!this.config.enabled){u.debug("Auto-update is disabled");return}if(!this.isChecking){if(!this.shouldCheckForUpdates()){u.debug("Skipping update check - within cooldown period");return}this.isChecking=!0;try{let e=await this.fetchLatestVersion();if(!this.isValidVersion(e)){u.debug(`Invalid version format from registry: ${e}`);return}this.saveCache({lastCheck:Date.now(),latestVersion:e}),this.isNewerVersion(e,this.currentVersion)?await this.performUpdate(e):u.debug(`Already on latest version: ${this.currentVersion}`)}catch(e){u.debug("Update check failed:",e)}finally{this.isChecking=!1}}}shouldCheckForUpdates(){let e=this.loadCache();return e?Date.now()-e.lastCheck>=this.config.checkIntervalMs:!0}loadCache(){try{if(On.existsSync(this.cacheFilePath)){let e=On.readFileSync(this.cacheFilePath,"utf8");return JSON.parse(e)}}catch(e){u.debug("Failed to load update cache:",e)}return null}saveCache(e){try{let t=Nn.dirname(this.cacheFilePath);On.existsSync(t)||On.mkdirSync(t,{recursive:!0}),On.writeFileSync(this.cacheFilePath,JSON.stringify(e,null,2))}catch(t){u.debug("Failed to save update cache:",t)}}isValidVersion(e){return!e||typeof e!="string"?!1:nd.test(e)}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`,n=(await Jb.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"]?.latest;if(!n)throw new Error("No latest version found in registry response");return n}isNewerVersion(e,t){let n=this.parseVersion(e),s=this.parseVersion(t);if(!n||!s)return u.debug("Failed to parse versions for comparison",{latest:e,current:t}),!1;for(let r=0;r<3;r++){if(n.numbers[r]>s.numbers[r])return!0;if(n.numbers[r]<s.numbers[r])return!1}return!n.prerelease&&s.prerelease?!0:n.prerelease&&!s.prerelease?!1:n.prerelease&&s.prerelease?this.comparePrerelease(n.prerelease,s.prerelease)>0:!1}parseVersion(e){let t=e.match(nd);return t?{numbers:[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)],prerelease:t[4]||null}:null}comparePrerelease(e,t){let n=e.split("."),s=t.split(".");for(let r=0;r<Math.max(n.length,s.length);r++){let o=n[r],a=s[r];if(o===void 0)return-1;if(a===void 0)return 1;let c=parseInt(o,10),l=parseInt(a,10);if(!isNaN(c)&&!isNaN(l)){if(c!==l)return c-l;continue}if(!isNaN(c))return-1;if(!isNaN(l))return 1;if(o!==a)return o.localeCompare(a)}return 0}detectGlobalPackageManager(){let e=ty();if(e)return u.debug(`Detected package manager from user agent: ${e}`),e;let t=process.argv[1]||"";return[process.env.PNPM_HOME,Nn.join(as.homedir(),".local","share","pnpm"),Nn.join(as.homedir(),"Library","pnpm")].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected pnpm from installation path"),"pnpm"):[Nn.join(as.homedir(),".yarn"),Nn.join(as.homedir(),".config","yarn"),process.env.YARN_GLOBAL_FOLDER].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected yarn from installation path"),"yarn"):[Nn.join(as.homedir(),".bun"),process.env.BUN_INSTALL].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected bun from installation path"),"bun"):(u.debug("Defaulting to npm"),"npm")}isCommandAvailable(e){try{let t=process.platform==="win32"?"where":"which";return ey(`${t} ${e}`,{stdio:"ignore"}),!0}catch{return!1}}async getInstallCommand(){let e=`${this.packageName}@latest`,t=this.detectGlobalPackageManager(),n=this.isCommandAvailable(t)?t:["npm","pnpm","yarn","bun"].find(r=>r!==t&&this.isCommandAvailable(r))||"npm";n!==t&&u.debug(`Detected ${t} not available, falling back to ${n}`);let s=ny(n,"global",[e]);return s?(u.debug(`Using package manager: ${n} -> ${s.command} ${s.args.join(" ")}`),{command:s.command,args:s.args}):(u.debug("Falling back to npm install -g"),{command:"npm",args:["install","-g",e]})}async performUpdate(e){try{let{command:t,args:n}=await this.getInstallCommand();return u.debug(`Auto-updating from ${this.currentVersion} to ${e} using ${t}`),new Promise(s=>{let r=Zb(t,n,{stdio:"pipe",shell:process.platform==="win32",detached:!1}),o="";r.stderr?.on("data",a=>{o+=a.toString()}),r.on("close",a=>{a===0?(this.updateCompleted=!0,this.emit("updated",{from:this.currentVersion,to:e}),setImmediate(()=>{this.isUserInteracting()?this.emit("update_notification_pending",{from:this.currentVersion,to:e}):console.log(_o.green(`
2438
2438
  ✓ Updated to v${e}`)+_o.gray(` - restart CLI to use new version
2439
2439
  `))}),u.debug(`Successfully updated to ${e}`)):u.debug(`Update failed with code ${a}: ${o}`),s()}),r.on("error",a=>{u.debug("Auto-update spawn error:",a),s()}),setTimeout(()=>{this.updateCompleted||(r.kill(),u.debug("Update timed out"),s())},6e4)})}catch(t){u.debug("Auto-update failed:",t)}}isUserInteracting(){return process.stdin.isRaw?!0:process.stdin.listenerCount("keypress")>0}showPendingNotification(){if(this.updateCompleted){let e=this.loadCache();e?.latestVersion&&console.log(_o.green(`
2440
2440
  ✓ Updated to v${e.latestVersion}`)+_o.gray(` - restart CLI to use new version
2441
- `))}}wasUpdated(){return this.updateCompleted}async checkForUpdates(){try{let e=this.loadCache();if(e&&Date.now()-e.lastCheck<this.config.checkIntervalMs)return{hasUpdate:this.isNewerVersion(e.latestVersion,this.currentVersion),latestVersion:e.latestVersion};let t=await this.fetchLatestVersion();return this.isValidVersion(t)?(this.saveCache({lastCheck:Date.now(),latestVersion:t}),{hasUpdate:this.isNewerVersion(t,this.currentVersion),latestVersion:t}):{hasUpdate:!1}}catch(e){return u.debug("Update check failed:",e),{hasUpdate:!1}}}async forceCheckAndUpdate(){try{Mn.existsSync(this.cacheFilePath)&&Mn.unlinkSync(this.cacheFilePath)}catch(e){u.debug("Failed to clear update cache:",e)}return this.checkAndUpdate()}getConfig(){return{...this.config}}setConfig(e){this.config={...this.config,...e}}};function sd(){if(process.env.ORION_DEV==="true"||process.env.ORION_DEV==="1"||process.argv[1]?.includes("tsx")||process.argv[1]?.endsWith(".ts"))return!0;let i=process.argv[1]||"";if(i.includes("/src/")&&!i.includes("node_modules"))return!0;let e=["/orion-cli/dist/","/orion-cli/src/"];for(let n of e)if(i.includes(n)&&!i.includes("node_modules"))return!0;return!1}Vt();Le();Tt();j();import un from"fs";import $o from"path";import ry from"os";import rd from"crypto";var Wa=200,oy=100,iy=500,as=class i{static instance;storagePath;state;saveTimeout=null;isDirty=!1;constructor(){let e=$o.join(ry.homedir(),".orion-cli");this.storagePath=$o.join(e,"conversations.json"),this.state=this.loadState()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadState(){try{if(un.existsSync(this.storagePath)){let e=un.readFileSync(this.storagePath,"utf8"),t=JSON.parse(e);return u.debug(`[STORAGE] Loaded ${t.conversations?.length||0} conversations`),{conversations:t.conversations||[],currentConversationId:t.currentConversationId||null,messages:t.messages||{},version:t.version||1}}}catch{u.debug("[STORAGE] Failed to load conversations, starting fresh")}return{conversations:[],currentConversationId:null,messages:{},version:1}}saveStateDebounced(){this.isDirty=!0,this.saveTimeout&&clearTimeout(this.saveTimeout),this.saveTimeout=setTimeout(()=>{this.saveStateImmediate()},iy)}flushPendingSaves(){this.isDirty&&(this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveTimeout=null),this.saveStateImmediate())}saveStateImmediate(){try{let e=$o.dirname(this.storagePath);un.existsSync(e)||un.mkdirSync(e,{recursive:!0});let t={conversations:this.state.conversations.slice(0,20),currentConversationId:this.state.currentConversationId,messages:{},version:this.state.version};for(let n of t.conversations)this.state.messages[n.id]&&(t.messages[n.id]=this.state.messages[n.id]);un.writeFileSync(this.storagePath,JSON.stringify(t,null,2)),this.isDirty=!1,u.debug(`[STORAGE] Saved ${t.conversations.length} conversations`)}catch(e){u.debug(`[STORAGE] Failed to save: ${e.message}`)}}createConversation(e="New Conversation"){let t=new Date().toISOString(),n={id:rd.randomUUID(),title:e,createdAt:t,updatedAt:t,messageCount:0};if(this.state.conversations.length>=oy){let s=this.state.conversations.findIndex(r=>!r.isPinned);if(s!==-1){let r=this.state.conversations.splice(s,1)[0];delete this.state.messages[r.id]}}return this.state.conversations.unshift(n),this.state.messages[n.id]=[],this.state.currentConversationId=n.id,this.saveStateDebounced(),u.debug(`[STORAGE] Created conversation: ${n.id}`),n}getConversations(){return[...this.state.conversations]}getCurrentConversation(){return this.state.currentConversationId&&this.state.conversations.find(e=>e.id===this.state.currentConversationId)||null}setCurrentConversation(e){this.state.currentConversationId=e,this.saveStateDebounced()}updateConversationTitle(e,t){let n=this.state.conversations.find(s=>s.id===e);n&&(n.title=t,this.saveStateDebounced(),u.debug(`[STORAGE] Updated title for ${e}: ${t}`))}pinConversation(e,t){let n=this.state.conversations.find(s=>s.id===e);n&&(n.isPinned=t,n.pinnedAt=t?new Date().toISOString():void 0,this.saveStateDebounced())}deleteConversation(e){let t=this.state.conversations.findIndex(n=>n.id===e);t!==-1&&(this.state.conversations.splice(t,1),delete this.state.messages[e],this.state.currentConversationId===e&&(this.state.currentConversationId=this.state.conversations[0]?.id||null),this.saveStateDebounced(),u.debug(`[STORAGE] Deleted conversation: ${e}`))}getMessages(e){return this.state.messages[e]||[]}addMessage(e,t){this.state.messages[e]||(this.state.messages[e]=[]);let n=this.state.messages[e];n.push(t),n.length>Wa&&(this.state.messages[e]=n.slice(-Wa),u.debug(`[STORAGE] Trimmed messages to ${Wa} for ${e}`));let s=this.state.conversations.find(r=>r.id===e);if(s){s.messageCount=this.state.messages[e].length,s.lastMessage=t.content.substring(0,100),s.updatedAt=new Date().toISOString();let r=this.state.conversations.indexOf(s);r>0&&(this.state.conversations.splice(r,1),this.state.conversations.unshift(s))}this.saveStateDebounced()}updateMessage(e,t,n){let s=this.state.messages[e];if(!s)return;let r=s.findIndex(o=>o.id===t);r!==-1&&(s[r]={...s[r],...n},this.saveStateDebounced())}clearMessages(e){this.state.messages[e]=[];let t=this.state.conversations.find(n=>n.id===e);t&&(t.messageCount=0,t.lastMessage=void 0),this.saveStateDebounced()}static toStoredMessage(e){return{id:e.id||rd.randomUUID(),role:e.role,content:e.content,timestamp:e.timestamp?.toISOString()||new Date().toISOString(),sender:e.sender,thinkingContent:e.thinkingContent||void 0,hasThinking:e.hasThinking||void 0,toolCallId:e.toolCallId,name:e.name,metadata:e.metadata}}static fromStoredMessage(e){return{id:e.id,role:e.role,content:e.content,timestamp:new Date(e.timestamp),sender:e.sender,isStreaming:!1,thinkingContent:e.thinkingContent||"",isThinkingStreaming:!1,hasThinking:e.hasThinking||!1,showInlineTodos:!1,showInlineWebView:!1,showInlineOperatorProgress:!1,activeWebViewURLs:[],isFeedbackMessage:!1,isRemoteTask:!1,toolCallId:e.toolCallId,name:e.name,metadata:e.metadata}}getStats(){let e=0;for(let t of Object.values(this.state.messages))e+=t.length;return{conversationCount:this.state.conversations.length,totalMessages:e}}clearAll(){this.state={conversations:[],currentConversationId:null,messages:{},version:1},this.saveStateImmediate(),u.debug("[STORAGE] Cleared all conversation data")}exportAsMarkdown(e){let t=this.state.conversations.find(r=>r.id===e);if(!t)return null;let n=this.state.messages[e]||[];if(n.length===0)return null;let s=[`# ${t.title}`,"",`**Created:** ${new Date(t.createdAt).toLocaleString()}`,`**Messages:** ${n.length}`,"","---",""];for(let r of n){let o=new Date(r.timestamp).toLocaleString(),a=r.role==="user"?"👤 **User**":r.role==="assistant"?"🤖 **Assistant**":r.role==="system"?"⚙️ **System**":`**${r.role}**`;s.push(`### ${a}`),s.push(`*${o}*`),s.push(""),r.thinkingContent&&(s.push("<details>"),s.push("<summary>💭 Thinking</summary>"),s.push(""),s.push(r.thinkingContent),s.push(""),s.push("</details>"),s.push("")),s.push(r.content),s.push(""),s.push("---"),s.push("")}return s.join(`
2441
+ `))}}wasUpdated(){return this.updateCompleted}async checkForUpdates(){try{let e=this.loadCache();if(e&&Date.now()-e.lastCheck<this.config.checkIntervalMs)return{hasUpdate:this.isNewerVersion(e.latestVersion,this.currentVersion),latestVersion:e.latestVersion};let t=await this.fetchLatestVersion();return this.isValidVersion(t)?(this.saveCache({lastCheck:Date.now(),latestVersion:t}),{hasUpdate:this.isNewerVersion(t,this.currentVersion),latestVersion:t}):{hasUpdate:!1}}catch(e){return u.debug("Update check failed:",e),{hasUpdate:!1}}}async forceCheckAndUpdate(){try{On.existsSync(this.cacheFilePath)&&On.unlinkSync(this.cacheFilePath)}catch(e){u.debug("Failed to clear update cache:",e)}return this.checkAndUpdate()}getConfig(){return{...this.config}}setConfig(e){this.config={...this.config,...e}}};function sd(){if(process.env.ORION_DEV==="true"||process.env.ORION_DEV==="1"||process.argv[1]?.includes("tsx")||process.argv[1]?.endsWith(".ts"))return!0;let i=process.argv[1]||"";if(i.includes("/src/")&&!i.includes("node_modules"))return!0;let e=["/orion-cli/dist/","/orion-cli/src/"];for(let n of e)if(i.includes(n)&&!i.includes("node_modules"))return!0;return!1}Xt();Ue();Tt();z();import gn from"fs";import $o from"path";import ry from"os";import rd from"crypto";var Wa=200,oy=100,iy=500,ls=class i{static instance;storagePath;state;saveTimeout=null;isDirty=!1;constructor(){let e=$o.join(ry.homedir(),".orion-cli");this.storagePath=$o.join(e,"conversations.json"),this.state=this.loadState()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadState(){try{if(gn.existsSync(this.storagePath)){let e=gn.readFileSync(this.storagePath,"utf8"),t=JSON.parse(e);return u.debug(`[STORAGE] Loaded ${t.conversations?.length||0} conversations`),{conversations:t.conversations||[],currentConversationId:t.currentConversationId||null,messages:t.messages||{},version:t.version||1}}}catch{u.debug("[STORAGE] Failed to load conversations, starting fresh")}return{conversations:[],currentConversationId:null,messages:{},version:1}}saveStateDebounced(){this.isDirty=!0,this.saveTimeout&&clearTimeout(this.saveTimeout),this.saveTimeout=setTimeout(()=>{this.saveStateImmediate()},iy)}flushPendingSaves(){this.isDirty&&(this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveTimeout=null),this.saveStateImmediate())}saveStateImmediate(){try{let e=$o.dirname(this.storagePath);gn.existsSync(e)||gn.mkdirSync(e,{recursive:!0});let t={conversations:this.state.conversations.slice(0,20),currentConversationId:this.state.currentConversationId,messages:{},version:this.state.version};for(let n of t.conversations)this.state.messages[n.id]&&(t.messages[n.id]=this.state.messages[n.id]);gn.writeFileSync(this.storagePath,JSON.stringify(t,null,2)),this.isDirty=!1,u.debug(`[STORAGE] Saved ${t.conversations.length} conversations`)}catch(e){u.debug(`[STORAGE] Failed to save: ${e.message}`)}}createConversation(e="New Conversation"){let t=new Date().toISOString(),n={id:rd.randomUUID(),title:e,createdAt:t,updatedAt:t,messageCount:0};if(this.state.conversations.length>=oy){let s=this.state.conversations.findIndex(r=>!r.isPinned);if(s!==-1){let r=this.state.conversations.splice(s,1)[0];delete this.state.messages[r.id]}}return this.state.conversations.unshift(n),this.state.messages[n.id]=[],this.state.currentConversationId=n.id,this.saveStateDebounced(),u.debug(`[STORAGE] Created conversation: ${n.id}`),n}getConversations(){return[...this.state.conversations]}getCurrentConversation(){return this.state.currentConversationId&&this.state.conversations.find(e=>e.id===this.state.currentConversationId)||null}setCurrentConversation(e){this.state.currentConversationId=e,this.saveStateDebounced()}updateConversationTitle(e,t){let n=this.state.conversations.find(s=>s.id===e);n&&(n.title=t,this.saveStateDebounced(),u.debug(`[STORAGE] Updated title for ${e}: ${t}`))}pinConversation(e,t){let n=this.state.conversations.find(s=>s.id===e);n&&(n.isPinned=t,n.pinnedAt=t?new Date().toISOString():void 0,this.saveStateDebounced())}deleteConversation(e){let t=this.state.conversations.findIndex(n=>n.id===e);t!==-1&&(this.state.conversations.splice(t,1),delete this.state.messages[e],this.state.currentConversationId===e&&(this.state.currentConversationId=this.state.conversations[0]?.id||null),this.saveStateDebounced(),u.debug(`[STORAGE] Deleted conversation: ${e}`))}getMessages(e){return this.state.messages[e]||[]}addMessage(e,t){this.state.messages[e]||(this.state.messages[e]=[]);let n=this.state.messages[e];n.push(t),n.length>Wa&&(this.state.messages[e]=n.slice(-Wa),u.debug(`[STORAGE] Trimmed messages to ${Wa} for ${e}`));let s=this.state.conversations.find(r=>r.id===e);if(s){s.messageCount=this.state.messages[e].length,s.lastMessage=t.content.substring(0,100),s.updatedAt=new Date().toISOString();let r=this.state.conversations.indexOf(s);r>0&&(this.state.conversations.splice(r,1),this.state.conversations.unshift(s))}this.saveStateDebounced()}updateMessage(e,t,n){let s=this.state.messages[e];if(!s)return;let r=s.findIndex(o=>o.id===t);r!==-1&&(s[r]={...s[r],...n},this.saveStateDebounced())}clearMessages(e){this.state.messages[e]=[];let t=this.state.conversations.find(n=>n.id===e);t&&(t.messageCount=0,t.lastMessage=void 0),this.saveStateDebounced()}static toStoredMessage(e){return{id:e.id||rd.randomUUID(),role:e.role,content:e.content,timestamp:e.timestamp?.toISOString()||new Date().toISOString(),sender:e.sender,thinkingContent:e.thinkingContent||void 0,hasThinking:e.hasThinking||void 0,toolCallId:e.toolCallId,name:e.name,metadata:e.metadata}}static fromStoredMessage(e){return{id:e.id,role:e.role,content:e.content,timestamp:new Date(e.timestamp),sender:e.sender,isStreaming:!1,thinkingContent:e.thinkingContent||"",isThinkingStreaming:!1,hasThinking:e.hasThinking||!1,showInlineTodos:!1,showInlineWebView:!1,showInlineOperatorProgress:!1,activeWebViewURLs:[],isFeedbackMessage:!1,isRemoteTask:!1,toolCallId:e.toolCallId,name:e.name,metadata:e.metadata}}getStats(){let e=0;for(let t of Object.values(this.state.messages))e+=t.length;return{conversationCount:this.state.conversations.length,totalMessages:e}}clearAll(){this.state={conversations:[],currentConversationId:null,messages:{},version:1},this.saveStateImmediate(),u.debug("[STORAGE] Cleared all conversation data")}exportAsMarkdown(e){let t=this.state.conversations.find(r=>r.id===e);if(!t)return null;let n=this.state.messages[e]||[];if(n.length===0)return null;let s=[`# ${t.title}`,"",`**Created:** ${new Date(t.createdAt).toLocaleString()}`,`**Messages:** ${n.length}`,"","---",""];for(let r of n){let o=new Date(r.timestamp).toLocaleString(),a=r.role==="user"?"👤 **User**":r.role==="assistant"?"🤖 **Assistant**":r.role==="system"?"⚙️ **System**":`**${r.role}**`;s.push(`### ${a}`),s.push(`*${o}*`),s.push(""),r.thinkingContent&&(s.push("<details>"),s.push("<summary>💭 Thinking</summary>"),s.push(""),s.push(r.thinkingContent),s.push(""),s.push("</details>"),s.push("")),s.push(r.content),s.push(""),s.push("---"),s.push("")}return s.join(`
2442
2442
  `)}exportAsJSON(e){let t=this.state.conversations.find(r=>r.id===e);if(!t)return null;let n=this.state.messages[e]||[],s={exportedAt:new Date().toISOString(),exportVersion:1,conversation:t,messages:n};return JSON.stringify(s,null,2)}exportAsText(e){let t=this.state.conversations.find(r=>r.id===e);if(!t)return null;let n=this.state.messages[e]||[];if(n.length===0)return null;let s=[t.title,"=".repeat(t.title.length),"",`Created: ${new Date(t.createdAt).toLocaleString()}`,`Messages: ${n.length}`,"","-".repeat(40),""];for(let r of n){let o=new Date(r.timestamp).toLocaleString(),a=r.role==="user"?"User":r.role==="assistant"?"Assistant":r.role==="system"?"System":r.role;s.push(`[${a}] - ${o}`),s.push(""),s.push(r.content),s.push(""),s.push("-".repeat(40)),s.push("")}return s.join(`
2443
- `)}saveExportToFile(e,t,n){try{let s=null;switch(t){case"markdown":s=this.exportAsMarkdown(e);break;case"json":s=this.exportAsJSON(e);break;case"text":s=this.exportAsText(e);break}if(!s)return{success:!1,error:"Conversation not found or empty"};let r=$o.dirname(n);return un.existsSync(r)||un.mkdirSync(r,{recursive:!0}),un.writeFileSync(n,s,"utf8"),u.debug(`[STORAGE] Exported conversation to ${n}`),{success:!0}}catch(s){return{success:!1,error:s.message}}}},Je=as.getInstance();import ay from"crypto";function ye(){return ay.randomUUID()}function od(i){return i.content||i.text||"Untitled task"}import{useEffect as cy,useRef as or,useCallback as id}from"react";function ad({personalAgent:i,frontendWS:e,handlers:t}){let n=or(""),s=or(!0),r=or(!1),o=or(!1),a=or(null),c=100,l=id(()=>{if(a.current=null,o.current=!1,!r.current||!s.current)return;r.current=!1;let g=n.current;t.onMessagesUpdate(m=>m.map((p,h)=>p.role==="assistant"&&!m.slice(h+1).some(y=>y.role==="assistant")?{...p,content:g}:p))},[t]);return cy(()=>{s.current=!0,n.current="";let g=v=>{t.onConversationIdReceived(v)},m=()=>{t.onLoadingMessageChange("Processing")},p=v=>{n.current+=v,r.current=!0,o.current||(o.current=!0,a.current=setTimeout(l,c))},h=v=>{let E=typeof v=="string"?v:v.name,S=typeof v=="string"?`tool-${Date.now()}`:v.toolCallId,I=typeof v=="string"?void 0:v.arguments,R=E.toLowerCase().replace(/_/g,"")==="todowrite";t.onActiveToolsUpdate($=>{let D=new Map($);return D.set(S,{toolCallId:S,name:E,arguments:I,startTime:new Date,state:"running"}),D}),R||t.onLoadingMessageChange("Processing")},f=v=>{if(!v||!v.toolName)return;let E=v.toolId||`tool-${v.toolName}-${Date.now()}`,S=v.success===!1||v.error,I=v.error||v.result?.error||"",P=v.arguments,R="";v.result&&(typeof v.result=="string"?R=v.result:Array.isArray(v.result)?R=v.result.map(N=>typeof N=="string"?N:N&&typeof N=="object"?N.text||N.content||JSON.stringify(N):"").join(""):v.result.output?R=typeof v.result.output=="string"?v.result.output:JSON.stringify(v.result.output,null,2):v.result.content?R=v.result.content:R=JSON.stringify(v.result,null,2));let $=R.length>500?R.substring(0,500)+`
2444
- ...(truncated)`:R,D=`<context>
2445
- ${R}
2446
- </context>`,_=S?"failed":"completed";t.onActiveToolsUpdate(N=>{let k=new Map(N),M=E;if(!k.has(E)){for(let[L,B]of k.entries())if(B.name===v.toolName&&B.state==="running"){M=L;break}}if(k.has(M)){let L=k.get(M);k.set(M,{...L,arguments:L.arguments||P,state:_,output:$,error:S?I:void 0})}else k.set(M,{toolCallId:M,name:v.toolName,arguments:P,startTime:new Date,state:_,output:$,error:S?I:void 0});return k}),t.onMessagesUpdate(N=>N.map((k,M)=>{if(k.role==="assistant"&&!N.slice(M+1).some(B=>B.role==="assistant")){let B=k.metadata?.toolResults;return{...k,metadata:{...k.metadata,toolResults:B?B+`
2447
- `+D:D}}}return k}))},y=v=>{!v||!v.toolCallId||t.onActiveToolsUpdate(E=>{let S=new Map(E),I=S.get(v.toolCallId);return I&&S.set(v.toolCallId,{...I,arguments:v.arguments}),S})},T=()=>{if(r.current){r.current=!1,o.current=!1;let v=n.current;t.onMessagesUpdate(E=>E.map((S,I)=>S.role==="assistant"&&!E.slice(I+1).some(R=>R.role==="assistant")?{...S,content:v}:S))}t.onLoadingChange(!1),t.onActiveToolsUpdate(()=>new Map),n.current=""},x=v=>{t.onError(v.message||"Unknown error"),t.onLoadingChange(!1),t.onActiveToolsUpdate(()=>new Map),n.current=""},w=v=>{t.onConfirmationRequest({id:v.confirmationId,type:v.type,title:v.title,message:v.message,command:v.command,targets:v.targets,isDestructive:v.isDestructive,timeout:v.isDestructive?v.timeout||3e4:void 0})},C=v=>{t.onTodoUpdate(v)};return i.on("conversation_id_received",g),i.on("thinking",m),i.on("data",p),i.on("toolExecuting",h),i.on("tool_completed",f),i.on("tool_args_update",y),i.on("done",T),i.on("error",x),i.on("confirmation_request",w),i.on("todo_update",C),e&&(e.on("toolExecuting",h),e.on("tool_completed",f)),()=>{s.current=!1,a.current&&(clearTimeout(a.current),a.current=null),i.off("conversation_id_received",g),i.off("thinking",m),i.off("data",p),i.off("toolExecuting",h),i.off("tool_completed",f),i.off("tool_args_update",y),i.off("done",T),i.off("error",x),i.off("confirmation_request",w),i.off("todo_update",C),e&&(e.off("toolExecuting",h),e.off("tool_completed",f))}},[i,e,t,l]),{resetContent:id(()=>{n.current=""},[])}}import{useState as ly,useEffect as cd,useCallback as ld,useMemo as ud,useRef as Ha}from"react";function dd({queueManager:i,frontendWS:e,crossDevice:t,isLoading:n,selectedModel:s,onCrossDeviceTask:r}){let[o,a]=ly([]),c=Ha(n),l=Ha(s),d=Ha(r);cd(()=>{c.current=n,l.current=s,d.current=r},[n,s,r]);let g=ud(()=>o.filter(y=>!y.isCrossDeviceTask),[o]),m=ud(()=>o.filter(y=>y.isCrossDeviceTask),[o]),p=o.length>0,h=ld((y,T=[])=>i.addToQueue({content:y,imageUrls:T,attachments:[],model:l.current.name}),[i]),f=ld(()=>{if(!i.hasQueuedMessages())return null;let y=i.processNextMessage();return y&&i.startProcessing(),y},[i]);return cd(()=>{let y=w=>{a(w)},T=()=>{},x=w=>{if(c.current){i.addToQueue({content:w.prompt,imageUrls:[],attachments:[],model:l.current.name,isCrossDeviceTask:!0,crossDeviceTaskId:w.taskId})||d.current(w.taskId,"");return}d.current(w.taskId,w.prompt)};return i.on("queue:updated",y),e.on("feedback:sent",T),t.on("CrossDeviceTaskSendMessage",x),()=>{i.off("queue:updated",y),e.off("feedback:sent",T),t.off("CrossDeviceTaskSendMessage",x)}},[i,e,t]),{queuedMessages:o,regularQueuedMessages:g,crossDeviceTasks:m,addToQueue:h,processNextMessage:f,hasQueuedMessages:p}}import{useState as uy,useEffect as dy}from"react";function gd({subAgentManager:i}){let[e,t]=uy(new Map);return dy(()=>{let n=()=>{let s=i.getOperations();t(new Map(s))};return i.on("spawn_started",n),i.on("agent_started",n),i.on("agent_streaming",n),i.on("agent_completed",n),i.on("spawn_completed",n),i.on("progress",n),()=>{i.off("spawn_started",n),i.off("agent_started",n),i.off("agent_streaming",n),i.off("agent_completed",n),i.off("spawn_completed",n),i.off("progress",n)}},[i]),{subAgentOperations:e}}Ta();import{useEffect as gy,useState as my,useRef as py,useCallback as hy}from"react";function md({frontendWS:i}){let[e,t]=my(null),n=py(null);gy(()=>{let r=a=>{n.current={conversationId:a.conversationId,source:a.source};let c=a.message?a.message.length>80?a.message.substring(0,80)+"...":a.message:"Processing request";t({source:a.source,message:c,conversationId:a.conversationId,timestamp:a.timestamp})},o=a=>{n.current?.conversationId===a.conversationId&&(n.current=null,t(null))};return i.on("external_session_started",r),i.on("external_session_ended",o),ns.on("external_session_started",r),ns.on("external_session_ended",o),()=>{i.off("external_session_started",r),i.off("external_session_ended",o),ns.off("external_session_started",r),ns.off("external_session_ended",o),n.current=null}},[i]);let s=hy(()=>{n.current=null,t(null)},[]);return{externalSession:e,clearSession:s,hasActiveSession:e!==null}}import{useState as fy,useEffect as pd,useRef as by}from"react";function hd(){let[i,e]=fy(null),t=by(null);return pd(()=>{t.current=i},[i]),pd(()=>{if(!i||i.todos.length===0)return;let n=i.todos.filter(o=>o.status==="completed").length,s=i.todos.length;if(n===s&&s>0){let o=setTimeout(()=>{e(null),t.current=null},3e3);return()=>clearTimeout(o)}},[i]),{todoList:i,setTodoList:e,todoListRef:t}}var bd=ds(null),yd=ds(null),vd=ds(null),Sd=ds(null),wd=ds(null),Bt=ds(null),us={main:i=>`Orion ready
2448
- 📁 ${i}`,clear:()=>"Fresh start",newConversation:()=>"New conversation",continueConversation:()=>"Welcome back",deleted:()=>"Conversation cleared"};function ja({children:i,initialProjectPath:e}){let t=e||process.cwd(),{exit:n}=yy(),s=ls(()=>({authService:X.getInstance(),personalAgent:je.getInstance(),queueManager:ct.getInstance(),frontendWS:be.getInstance(),crossDevice:rs.getInstance(),subAgentManager:_s.getInstance()}),[]);Ut(()=>(Y.enableCustomUI(),()=>Y.disableCustomUI()),[]);let r=ls(()=>pe.find(k=>k.name===de.string("selectedPersonalModel"))||pe.find(k=>k.name==="snowx-c5")||pe[0],[]),[o,a]=fd(()=>{let k=Je.getConversations(),M=Je.getCurrentConversation();return{messages:[{id:ye(),role:"system",content:us.main(t),timestamp:Date.now()}],conversationId:M?.id||null,conversationTitleGenerated:!1,isLoading:!1,loadingMessage:"Processing",activeTools:new Map,subAgentOperations:new Map,externalSession:null,pendingConfirmation:null,todoList:null,conversations:k,staticRemountKey:0}}),c=On(o.isLoading),l=On(o.messages),d=On(o.conversationId),g=On(o.pendingConfirmation),m=On(r),p=On(!1);Ut(()=>{c.current=o.isLoading,l.current=o.messages,d.current=o.conversationId,g.current=o.pendingConfirmation},[o.isLoading,o.messages,o.conversationId,o.pendingConfirmation]);let{todoList:h,setTodoList:f}=hd();Ut(()=>{a(k=>({...k,todoList:h}))},[h]),Ut(()=>{if(process.env.MOCK_MESSAGES!=="true")return;let k=setTimeout(()=>{let L=[{id:ye(),role:"system",content:us.main("/mock/project"),timestamp:Date.now()},{id:ye(),role:"user",content:"Show me all UI components for testing the chatbox",timestamp:Date.now()+100},{id:ye(),role:"assistant",content:`## Heading Level 2
2443
+ `)}saveExportToFile(e,t,n){try{let s=null;switch(t){case"markdown":s=this.exportAsMarkdown(e);break;case"json":s=this.exportAsJSON(e);break;case"text":s=this.exportAsText(e);break}if(!s)return{success:!1,error:"Conversation not found or empty"};let r=$o.dirname(n);return gn.existsSync(r)||gn.mkdirSync(r,{recursive:!0}),gn.writeFileSync(n,s,"utf8"),u.debug(`[STORAGE] Exported conversation to ${n}`),{success:!0}}catch(s){return{success:!1,error:s.message}}}},Ze=ls.getInstance();import ay from"crypto";function ye(){return ay.randomUUID()}function od(i){return i.content||i.text||"Untitled task"}import{useEffect as cy,useRef as ir,useCallback as id}from"react";function ad({personalAgent:i,frontendWS:e,handlers:t}){let n=ir(""),s=ir(!0),r=ir(!1),o=ir(!1),a=ir(null),c=100,l=id(()=>{if(a.current=null,o.current=!1,!r.current||!s.current)return;r.current=!1;let g=n.current;t.onMessagesUpdate(m=>m.map((p,h)=>p.role==="assistant"&&!m.slice(h+1).some(y=>y.role==="assistant")?{...p,content:g}:p))},[t]);return cy(()=>{s.current=!0,n.current="";let g=v=>{t.onConversationIdReceived(v)},m=()=>{t.onLoadingMessageChange("Processing")},p=v=>{n.current+=v,r.current=!0,o.current||(o.current=!0,a.current=setTimeout(l,c))},h=v=>{let x=typeof v=="string"?v:v.name,S=typeof v=="string"?`tool-${Date.now()}`:v.toolCallId,I=typeof v=="string"?void 0:v.arguments,M=x.toLowerCase().replace(/_/g,"")==="todowrite";t.onActiveToolsUpdate(_=>{let F=new Map(_);return F.set(S,{toolCallId:S,name:x,arguments:I,startTime:new Date,state:"running"}),F}),M||t.onLoadingMessageChange("Processing")},f=v=>{if(!v||!v.toolName)return;let x=v.toolId||`tool-${v.toolName}-${Date.now()}`,S=v.success===!1||v.error,I=v.error||v.result?.error||"",D=v.arguments,M="";v.result&&(typeof v.result=="string"?M=v.result:Array.isArray(v.result)?M=v.result.map(N=>typeof N=="string"?N:N&&typeof N=="object"?N.text||N.content||JSON.stringify(N):"").join(""):v.result.output?M=typeof v.result.output=="string"?v.result.output:JSON.stringify(v.result.output,null,2):v.result.content?M=v.result.content:M=JSON.stringify(v.result,null,2));let _=M.length>500?M.substring(0,500)+`
2444
+ ...(truncated)`:M,F=`<context>
2445
+ ${M}
2446
+ </context>`,R=S?"failed":"completed";t.onActiveToolsUpdate(N=>{let k=new Map(N),P=x;if(!k.has(x)){for(let[B,L]of k.entries())if(L.name===v.toolName&&L.state==="running"){P=B;break}}if(k.has(P)){let B=k.get(P);k.set(P,{...B,arguments:B.arguments||D,state:R,output:_,error:S?I:void 0})}else k.set(P,{toolCallId:P,name:v.toolName,arguments:D,startTime:new Date,state:R,output:_,error:S?I:void 0});return k}),t.onMessagesUpdate(N=>N.map((k,P)=>{if(k.role==="assistant"&&!N.slice(P+1).some(L=>L.role==="assistant")){let L=k.metadata?.toolResults;return{...k,metadata:{...k.metadata,toolResults:L?L+`
2447
+ `+F:F}}}return k}))},y=v=>{!v||!v.toolCallId||t.onActiveToolsUpdate(x=>{let S=new Map(x),I=S.get(v.toolCallId);return I&&S.set(v.toolCallId,{...I,arguments:v.arguments}),S})},T=()=>{if(r.current){r.current=!1,o.current=!1;let v=n.current;t.onMessagesUpdate(x=>x.map((S,I)=>S.role==="assistant"&&!x.slice(I+1).some(M=>M.role==="assistant")?{...S,content:v}:S))}t.onLoadingChange(!1),t.onActiveToolsUpdate(()=>new Map),n.current=""},C=v=>{t.onError(v.message||"Unknown error"),t.onLoadingChange(!1),t.onActiveToolsUpdate(()=>new Map),n.current=""},w=v=>{t.onConfirmationRequest({id:v.confirmationId,type:v.type,title:v.title,message:v.message,command:v.command,targets:v.targets,isDestructive:v.isDestructive,timeout:v.isDestructive?v.timeout||3e4:void 0})},E=v=>{t.onTodoUpdate(v)};return i.on("conversation_id_received",g),i.on("thinking",m),i.on("data",p),i.on("toolExecuting",h),i.on("tool_completed",f),i.on("tool_args_update",y),i.on("done",T),i.on("error",C),i.on("confirmation_request",w),i.on("todo_update",E),e&&(e.on("toolExecuting",h),e.on("tool_completed",f)),()=>{s.current=!1,a.current&&(clearTimeout(a.current),a.current=null),i.off("conversation_id_received",g),i.off("thinking",m),i.off("data",p),i.off("toolExecuting",h),i.off("tool_completed",f),i.off("tool_args_update",y),i.off("done",T),i.off("error",C),i.off("confirmation_request",w),i.off("todo_update",E),e&&(e.off("toolExecuting",h),e.off("tool_completed",f))}},[i,e,t,l]),{resetContent:id(()=>{n.current=""},[])}}import{useState as ly,useEffect as cd,useCallback as ld,useMemo as ud,useRef as Ha}from"react";function dd({queueManager:i,frontendWS:e,crossDevice:t,isLoading:n,selectedModel:s,onCrossDeviceTask:r}){let[o,a]=ly([]),c=Ha(n),l=Ha(s),d=Ha(r);cd(()=>{c.current=n,l.current=s,d.current=r},[n,s,r]);let g=ud(()=>o.filter(y=>!y.isCrossDeviceTask),[o]),m=ud(()=>o.filter(y=>y.isCrossDeviceTask),[o]),p=o.length>0,h=ld((y,T=[])=>i.addToQueue({content:y,imageUrls:T,attachments:[],model:l.current.name}),[i]),f=ld(()=>{if(!i.hasQueuedMessages())return null;let y=i.processNextMessage();return y&&i.startProcessing(),y},[i]);return cd(()=>{let y=w=>{a(w)},T=()=>{},C=w=>{if(c.current){i.addToQueue({content:w.prompt,imageUrls:[],attachments:[],model:l.current.name,isCrossDeviceTask:!0,crossDeviceTaskId:w.taskId})||d.current(w.taskId,"");return}d.current(w.taskId,w.prompt)};return i.on("queue:updated",y),e.on("feedback:sent",T),t.on("CrossDeviceTaskSendMessage",C),()=>{i.off("queue:updated",y),e.off("feedback:sent",T),t.off("CrossDeviceTaskSendMessage",C)}},[i,e,t]),{queuedMessages:o,regularQueuedMessages:g,crossDeviceTasks:m,addToQueue:h,processNextMessage:f,hasQueuedMessages:p}}import{useState as uy,useEffect as dy}from"react";function gd({subAgentManager:i}){let[e,t]=uy(new Map);return dy(()=>{let n=()=>{let s=i.getOperations();t(new Map(s))};return i.on("spawn_started",n),i.on("agent_started",n),i.on("agent_streaming",n),i.on("agent_completed",n),i.on("spawn_completed",n),i.on("progress",n),()=>{i.off("spawn_started",n),i.off("agent_started",n),i.off("agent_streaming",n),i.off("agent_completed",n),i.off("spawn_completed",n),i.off("progress",n)}},[i]),{subAgentOperations:e}}Ta();import{useEffect as gy,useState as my,useRef as py,useCallback as hy}from"react";function md({frontendWS:i}){let[e,t]=my(null),n=py(null);gy(()=>{let r=a=>{n.current={conversationId:a.conversationId,source:a.source};let c=a.message?a.message.length>80?a.message.substring(0,80)+"...":a.message:"Processing request";t({source:a.source,message:c,conversationId:a.conversationId,timestamp:a.timestamp})},o=a=>{n.current?.conversationId===a.conversationId&&(n.current=null,t(null))};return i.on("external_session_started",r),i.on("external_session_ended",o),rs.on("external_session_started",r),rs.on("external_session_ended",o),()=>{i.off("external_session_started",r),i.off("external_session_ended",o),rs.off("external_session_started",r),rs.off("external_session_ended",o),n.current=null}},[i]);let s=hy(()=>{n.current=null,t(null)},[]);return{externalSession:e,clearSession:s,hasActiveSession:e!==null}}import{useState as fy,useEffect as pd,useRef as by}from"react";function hd(){let[i,e]=fy(null),t=by(null);return pd(()=>{t.current=i},[i]),pd(()=>{if(!i||i.todos.length===0)return;let n=i.todos.filter(o=>o.status==="completed").length,s=i.todos.length;if(n===s&&s>0){let o=setTimeout(()=>{e(null),t.current=null},3e3);return()=>clearTimeout(o)}},[i]),{todoList:i,setTodoList:e,todoListRef:t}}var bd=ms(null),yd=ms(null),vd=ms(null),Sd=ms(null),wd=ms(null),Wt=ms(null),gs={main:i=>`Orion ready
2448
+ 📁 ${i}`,clear:()=>"Fresh start",newConversation:()=>"New conversation",continueConversation:()=>"Welcome back",deleted:()=>"Conversation cleared"};function ja({children:i,initialProjectPath:e}){let t=e||process.cwd(),{exit:n}=yy(),s=ds(()=>({authService:X.getInstance(),personalAgent:ze.getInstance(),queueManager:ct.getInstance(),frontendWS:be.getInstance(),crossDevice:is.getInstance(),subAgentManager:$s.getInstance()}),[]);Bt(()=>(Q.enableCustomUI(),()=>Q.disableCustomUI()),[]);let r=ds(()=>pe.find(k=>k.name===de.string("selectedPersonalModel"))||pe.find(k=>k.name==="snowx-c5")||pe[0],[]),[o,a]=fd(()=>{let k=Ze.getConversations(),P=Ze.getCurrentConversation();return{messages:[{id:ye(),role:"system",content:gs.main(t),timestamp:Date.now()}],conversationId:P?.id||null,conversationTitleGenerated:!1,isLoading:!1,loadingMessage:"Processing",activeTools:new Map,subAgentOperations:new Map,externalSession:null,pendingConfirmation:null,todoList:null,conversations:k,staticRemountKey:0}}),c=_n(o.isLoading),l=_n(o.messages),d=_n(o.conversationId),g=_n(o.pendingConfirmation),m=_n(r),p=_n(!1);Bt(()=>{c.current=o.isLoading,l.current=o.messages,d.current=o.conversationId,g.current=o.pendingConfirmation},[o.isLoading,o.messages,o.conversationId,o.pendingConfirmation]);let{todoList:h,setTodoList:f}=hd();Bt(()=>{a(k=>({...k,todoList:h}))},[h]),Bt(()=>{if(process.env.MOCK_MESSAGES!=="true")return;let k=setTimeout(()=>{let B=[{id:ye(),role:"system",content:gs.main("/mock/project"),timestamp:Date.now()},{id:ye(),role:"user",content:"Show me all UI components for testing the chatbox",timestamp:Date.now()+100},{id:ye(),role:"assistant",content:`## Heading Level 2
2449
2449
 
2450
2450
  ### Heading Level 3
2451
2451
 
@@ -2514,18 +2514,18 @@ Check build
2514
2514
  Deploy to staging
2515
2515
  </suggestions>`,timestamp:Date.now()+200},{id:ye(),role:"system",content:"[!] This is an error/warning system message",timestamp:Date.now()+300},{id:ye(),role:"user",content:`Another user message with
2516
2516
  multiple lines
2517
- to test multiline rendering`,timestamp:Date.now()+400},{id:ye(),role:"assistant",content:"Short assistant response with `code` and **bold**.",timestamp:Date.now()+500},...Array.from({length:20},(V,le)=>({id:ye(),role:le%2===0?"user":"assistant",content:le%2===0?`User message #${le+1}: This is a test message to fill up the chat for scroll testing.`:`Assistant response #${le+1}: Here's a longer response with some **markdown** and \`code\` to make it more realistic.
2517
+ to test multiline rendering`,timestamp:Date.now()+400},{id:ye(),role:"assistant",content:"Short assistant response with `code` and **bold**.",timestamp:Date.now()+500},...Array.from({length:20},(G,Y)=>({id:ye(),role:Y%2===0?"user":"assistant",content:Y%2===0?`User message #${Y+1}: This is a test message to fill up the chat for scroll testing.`:`Assistant response #${Y+1}: Here's a longer response with some **markdown** and \`code\` to make it more realistic.
2518
2518
 
2519
2519
  This response has multiple paragraphs to take up more space.
2520
2520
 
2521
2521
  - Item 1
2522
2522
  - Item 2
2523
- - Item 3`,timestamp:Date.now()+600+le*100}))],B={todos:[{id:"todo-1",content:"Setup project structure",status:"completed",activeForm:"Setting up project structure"},{id:"todo-2",content:"Implement core features",status:"completed",activeForm:"Implementing core features"},{id:"todo-3",content:"Add authentication",status:"in_progress",activeForm:"Adding authentication"},{id:"todo-4",content:"Write unit tests",status:"pending",activeForm:"Writing unit tests"},{id:"todo-5",content:"Setup CI/CD pipeline",status:"pending",activeForm:"Setting up CI/CD"},{id:"todo-6",content:"Deploy to production",status:"pending",activeForm:"Deploying to production"}],timestamp:new Date},H=new Map([["tool-1",{toolCallId:"tool-1",name:"Bash",arguments:{command:"npm install",description:"Install dependencies"},startTime:new Date,state:"running"}],["tool-2",{toolCallId:"tool-2",name:"Read",arguments:{file_path:"/src/index.ts"},startTime:new Date(Date.now()-5e3),state:"completed",output:"File content..."}],["tool-3",{toolCallId:"tool-3",name:"Grep",arguments:{pattern:"TODO",path:"src/"},startTime:new Date(Date.now()-3e3),state:"completed"}],["tool-4",{toolCallId:"tool-4",name:"Write",arguments:{file_path:"/src/new-file.ts"},startTime:new Date(Date.now()-1e3),state:"failed",error:"Permission denied"}],["tool-5",{toolCallId:"tool-5",name:"WebFetch",arguments:{url:"https://api.example.com/data"},startTime:new Date,state:"running"}]]);a(V=>({...V,messages:L,todoList:B,activeTools:H,isLoading:!0,loadingMessage:"Processing mock request..."}))},500);return()=>clearTimeout(k)},[]);let[y]=fd(()=>{let k={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:r,isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new No(k)});Ut(()=>{let k=o.messages.map(M=>({role:M.role,content:M.content,timestamp:new Date(M.timestamp||Date.now()),...M.tool&&{tool:M.tool},...M.toolOutput&&{toolOutput:M.toolOutput}}));y.setDelegate({messages:k,fullConversationHistory:k,isLoading:o.isLoading,currentInput:"",selectedModel:m.current,isVisionEnabled:p.current,conversationId:o.conversationId,usesCustomUI:!0,updateCurrentConversation:()=>{}})},[o.messages,o.isLoading,o.conversationId,y]);let T=On(null),x=Ga(async(k,M=[])=>{if(is.getExistingInstance()?.checkAndUpdate().catch(()=>{}),c.current){s.queueManager.addToQueue({content:k,imageUrls:M,attachments:[],model:m.current.name})||a(G=>({...G,messages:[...G.messages,{id:ye(),role:"system",content:"[!] Queue is full (max 5 messages). Your input was not saved.",timestamp:Date.now()}]}));return}let L=Date.now(),B={id:ye(),role:"user",content:k,timestamp:L},H={id:ye(),role:"assistant",content:"",timestamp:L+1},V=[...l.current,B,H];a(W=>({...W,messages:V,isLoading:!0,loadingMessage:"Processing"}));let le=V.map(W=>({role:W.role,content:W.content,timestamp:new Date(W.timestamp||Date.now()),...W.tool&&{tool:W.tool},...W.toolOutput&&{toolOutput:W.toolOutput}}));y.setDelegate({messages:le,fullConversationHistory:le,isLoading:!1,currentInput:"",selectedModel:m.current,isVisionEnabled:p.current,conversationId:d.current,usesCustomUI:!0,updateCurrentConversation:()=>{}});try{await y.sendMessage(k,M.length>0?M:void 0)}catch(W){a(G=>({...G,messages:[...G.messages,{id:ye(),role:"system",content:`Error: ${W.message}`,timestamp:Date.now()}],isLoading:!1}))}},[s.queueManager,y]);T.current=x;let w=ls(()=>({onConversationIdReceived:k=>{a(M=>({...M,conversationId:k.conversationId,conversationTitleGenerated:!!k.title}))},onMessagesUpdate:k=>{a(M=>({...M,messages:k(M.messages)}))},onActiveToolsUpdate:k=>{a(M=>({...M,activeTools:k(M.activeTools)}))},onLoadingChange:k=>{a(M=>({...M,isLoading:k,activeTools:k?M.activeTools:new Map,subAgentOperations:k?M.subAgentOperations:new Map}))},onLoadingMessageChange:k=>{a(M=>({...M,loadingMessage:k}))},onTodoUpdate:k=>{f(k)},onConfirmationRequest:k=>{a(M=>({...M,pendingConfirmation:k}))},onError:k=>{a(M=>({...M,messages:[...M.messages,{id:ye(),role:"system",content:`Error: ${k}`,timestamp:Date.now()}],isLoading:!1,activeTools:new Map,subAgentOperations:new Map}))}}),[f]);ad({personalAgent:s.personalAgent,frontendWS:s.frontendWS,handlers:w});let{regularQueuedMessages:C,crossDeviceTasks:v,processNextMessage:E,hasQueuedMessages:S}=dd({queueManager:s.queueManager,frontendWS:s.frontendWS,crossDevice:s.crossDevice,isLoading:o.isLoading,selectedModel:m.current,onCrossDeviceTask:(k,M)=>{M&&T.current?.(M)}}),{subAgentOperations:I}=gd({subAgentManager:s.subAgentManager});Ut(()=>{a(k=>({...k,subAgentOperations:I}))},[I]);let{externalSession:P}=md({frontendWS:s.frontendWS});Ut(()=>{a(k=>({...k,externalSession:P}))},[P]),Ut(()=>{if(!o.isLoading&&S){let k=E();k&&T.current?.(k.content)}},[o.isLoading,S,E]);let R=ls(()=>({addMessage:k=>{a(M=>({...M,messages:[...M.messages,k]}))},addSystemMessage:k=>{a(M=>({...M,messages:[...M.messages,{id:ye(),role:"system",content:k,timestamp:Date.now()}]}))},updateMessages:k=>{a(M=>({...M,messages:k(M.messages)}))},setLoading:(k,M)=>{a(L=>({...L,isLoading:k,loadingMessage:M||L.loadingMessage}))},setConversationId:(k,M)=>{a(L=>({...L,conversationId:k,conversationTitleGenerated:!!M}))},clearChat:()=>{a(k=>({...k,messages:[{id:ye(),role:"system",content:us.clear(),timestamp:Date.now()}],todoList:null,conversationId:null,conversationTitleGenerated:!1,staticRemountKey:k.staticRemountKey+1}))},handleSubmit:x,handleConfirmationConfirm:k=>{let M=g.current?.id;M&&(a(L=>({...L,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:M,response:k,confirmed:!0}))},handleConfirmationDecline:()=>{let k=g.current?.id;k&&(a(M=>({...M,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:k,response:"n",confirmed:!1}),a(M=>({...M,messages:[...M.messages,{id:ye(),role:"system",content:"[!] Action declined by user",timestamp:Date.now()}]})))},handleConfirmationTimeout:()=>{let k=g.current?.id;k&&(a(M=>({...M,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:k,response:"n",confirmed:!1,timedOut:!0}),a(M=>({...M,messages:[...M.messages,{id:ye(),role:"system",content:"[!] Confirmation timed out - action declined",timestamp:Date.now()}]})))},stopStreaming:async()=>{await s.personalAgent.stopStreaming(),a(k=>({...k,isLoading:!1,activeTools:new Map,subAgentOperations:new Map,pendingConfirmation:null,messages:[...k.messages,{id:ye(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))},createConversation:k=>{let M=Je.createConversation(k);return a(L=>({...L,conversations:Je.getConversations(),conversationId:M.id,conversationTitleGenerated:!1,messages:[{id:ye(),role:"system",content:us.newConversation(),timestamp:Date.now()}],todoList:null,staticRemountKey:L.staticRemountKey+1})),M},switchConversation:k=>{let M=d.current,L=l.current;if(M&&L.length>1)for(let H of L)H.role!=="system"&&Je.addMessage(M,as.toStoredMessage(H));Je.setCurrentConversation(k);let B=Je.getMessages(k);a(H=>({...H,conversationId:k,messages:B.length>0?B.map(V=>as.fromStoredMessage(V)):[{id:ye(),role:"system",content:us.continueConversation(),timestamp:Date.now()}],staticRemountKey:H.staticRemountKey+1}))},deleteConversation:k=>{Je.deleteConversation(k),a(M=>({...M,conversations:Je.getConversations(),...M.conversationId===k?{conversationId:null,messages:[{id:ye(),role:"system",content:us.deleted(),timestamp:Date.now()}],staticRemountKey:M.staticRemountKey+1}:{}}))},updateConversationTitle:(k,M)=>{Je.updateConversationTitle(k,M),a(L=>({...L,conversations:Je.getConversations(),conversationTitleGenerated:!0}))}}),[x,s.personalAgent]),$=ls(()=>({regularQueuedMessages:C,crossDeviceTasks:v,hasQueuedMessages:S}),[C,v,S]),D=Ga(k=>{m.current=k},[]),_=Ga(k=>{p.current=k},[]),N=ls(()=>({state:o,actions:R,services:s,queue:$,projectPath:t}),[o,R,s,$,t]);return Ut(()=>{Bt._updateModelRef=D,Bt._updateVisionRef=_},[D,_]),cs.createElement(Bt.Provider,{value:N},cs.createElement(bd.Provider,{value:o},cs.createElement(yd.Provider,{value:R},cs.createElement(vd.Provider,{value:s},cs.createElement(Sd.Provider,{value:$},cs.createElement(wd.Provider,{value:t},i))))))}function Nn(){let i=$t(bd);if(i)return i;let e=$t(Bt);if(!e)throw new Error("useChatState must be used within ChatProvider");return e.state}function Ct(){let i=$t(yd);if(i)return i;let e=$t(Bt);if(!e)throw new Error("useChatActions must be used within ChatProvider");return e.actions}function za(){let i=$t(vd);if(i)return i;let e=$t(Bt);if(!e)throw new Error("useChatServices must be used within ChatProvider");return e.services}function qa(){let i=$t(Sd);if(i)return i;let e=$t(Bt);if(!e)throw new Error("useChatQueue must be used within ChatProvider");return e.queue}function Ka(){let i=$t(wd);if(i)return i;let e=$t(Bt);if(!e)throw new Error("useProjectPath must be used within ChatProvider");return e.projectPath}function Td(){return Bt}Vt();Le();wn();Te();import Fo,{createContext as Uo,useContext as gs,useState as vy,useMemo as Lo,useEffect as Sy,useRef as wy}from"react";var xd=Uo(null),Cd=Uo(null),Ed=Uo(null),Bo=Uo(null);function Va({children:i}){let e=Lo(()=>pe.find(l=>l.name===de.string("selectedPersonalModel"))||pe.find(l=>l.name==="snowx-c5")||pe[0],[]),t=wy(0),[n,s]=vy({showHelp:!1,showModelMenu:!1,showCommandMenu:!1,selectedModel:e,isVisionEnabled:!1,showWizard:!1,wizard:{type:null,step:1,data:{}},operationalMode:"normal",toasts:[],isReverseSearchActive:!1}),r=Ct();Sy(()=>{let l=Td();l._updateModelRef&&l._updateModelRef(n.selectedModel),l._updateVisionRef&&l._updateVisionRef(n.isVisionEnabled)},[n.selectedModel,n.isVisionEnabled]);let o=Lo(()=>({email:X.getInstance().getUserEmail()||"User",tier:xe.getDisplayName(xe.getCurrentUserTier()),userTier:xe.getCurrentUserTier()}),[]),a=Lo(()=>({toggleHelp:()=>s(l=>({...l,showHelp:!l.showHelp})),showHelp:()=>s(l=>({...l,showHelp:!0})),hideHelp:()=>s(l=>({...l,showHelp:!1})),toggleModelMenu:()=>s(l=>({...l,showModelMenu:!l.showModelMenu})),showModelMenu:()=>s(l=>({...l,showModelMenu:!0})),hideModelMenu:()=>s(l=>({...l,showModelMenu:!1})),toggleCommandMenu:()=>s(l=>({...l,showCommandMenu:!l.showCommandMenu})),showCommandMenu:()=>s(l=>({...l,showCommandMenu:!0})),hideCommandMenu:()=>s(l=>({...l,showCommandMenu:!1})),setModel:l=>{de.set("selectedPersonalModel",l.name),s(d=>({...d,selectedModel:l,showModelMenu:!1})),r.addSystemMessage(`Switched to ${l.displayName}`)},toggleVision:()=>{s(l=>{let d=!l.isVisionEnabled;return r.addSystemMessage(`Vision mode ${d?"enabled":"disabled"}`),{...l,isVisionEnabled:d}})},closeAllModals:()=>s(l=>({...l,showHelp:!1,showModelMenu:!1,showCommandMenu:!1,showWizard:!1})),showDiscordWizard:()=>s(l=>({...l,showWizard:!0,showCommandMenu:!1,wizard:{type:"discord",step:1,data:{}}})),showTelegramWizard:()=>s(l=>({...l,showWizard:!0,showCommandMenu:!1,wizard:{type:"telegram",step:1,data:{}}})),hideWizard:()=>s(l=>({...l,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setWizardStep:l=>s(d=>({...d,wizard:{...d.wizard,step:l}})),setWizardData:(l,d)=>s(g=>({...g,wizard:{...g.wizard,data:{...g.wizard.data,[l]:d}}})),resetWizard:()=>s(l=>({...l,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setMode:l=>{s(d=>({...d,operationalMode:l})),l!=="normal"&&r.addSystemMessage(`Switched to ${l.toUpperCase()} mode`)},toggleYoloMode:()=>{s(l=>{let d=l.operationalMode==="yolo"?"normal":"yolo";return d==="yolo"?r.addSystemMessage("YOLO mode enabled - all actions will be auto-approved"):r.addSystemMessage("YOLO mode disabled"),{...l,operationalMode:d}})},togglePlanMode:()=>{s(l=>{let d=l.operationalMode==="plan"?"normal":"plan";return d==="plan"?r.addSystemMessage("PLAN mode enabled - planning only, no execution"):r.addSystemMessage("PLAN mode disabled"),{...l,operationalMode:d}})},showToast:(l,d="info",g)=>{let m=`toast-${Date.now()}-${t.current++}`;s(p=>({...p,toasts:[...p.toasts,{id:m,message:l,type:d,duration:g}]}))},removeToast:l=>{s(d=>({...d,toasts:d.toasts.filter(g=>g.id!==l)}))},clearToasts:()=>{s(l=>({...l,toasts:[]}))},startReverseSearch:()=>{s(l=>({...l,isReverseSearchActive:!0,showHelp:!1,showModelMenu:!1,showCommandMenu:!1}))},stopReverseSearch:()=>{s(l=>({...l,isReverseSearchActive:!1}))}}),[r]),c=Lo(()=>({state:n,actions:a,info:o}),[n,a,o]);return Fo.createElement(Cd.Provider,{value:a},Fo.createElement(xd.Provider,{value:n},Fo.createElement(Ed.Provider,{value:o},Fo.createElement(Bo.Provider,{value:c},i))))}function ms(){let i=gs(xd);if(i)return i;let e=gs(Bo);if(!e)throw new Error("useUIState must be used within UIProvider");return e.state}function Wt(){let i=gs(Cd);if(i)return i;let e=gs(Bo);if(!e)throw new Error("useUIActions must be used within UIProvider");return e.actions}function ir(){let i=gs(Ed);if(i)return i;let e=gs(Bo);if(!e)throw new Error("useUIInfo must be used within UIProvider");return e.info}function Xa(){let i=ms();return{...i.wizard,isOpen:i.showWizard}}import Ey,{createContext as Iy,useContext as _d,useState as ky,useMemo as Od,useRef as Nd}from"react";import Ho from"path";import Ya from"fs";import _n from"path";import Ty from"os";var Pd={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".ico":"image/x-icon",".tiff":"image/tiff",".tif":"image/tiff",".avif":"image/avif",".heic":"image/heic",".heif":"image/heif"},Ad=Object.keys(Pd),xy=[...Ad,".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".mp3",".mp4",".wav",".avi",".mov",".mkv",".ttf",".otf",".woff",".woff2",".bin",".dat",".db",".sqlite"],Id=20*1024*1024,kd=1*1024*1024;function dn(i){return i<1024?`${i}B`:i<1024*1024?`${(i/1024).toFixed(1)}KB`:`${(i/(1024*1024)).toFixed(1)}MB`}function Qa(i,e=30){if(i.length<=e)return i;let t=_n.extname(i);return _n.basename(i,t).slice(0,e-t.length-3)+"..."+t}function Dd(i){let e=i.trim();if(e.startsWith("file://")){e=e.replace("file://","");try{e=decodeURIComponent(e)}catch{}}if((e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1)),e=e.replace(/\\ /g," "),e.includes(`
2524
- `))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let t=e.startsWith("/"),n=/^[A-Za-z]:[\\\/]/.test(e),s=e.startsWith("./")||e.startsWith("../"),r=e.startsWith("~/");if(!(t||n||s||r))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let a=e.toLowerCase(),c=_n.extname(a),l=Ad.includes(c),d=xy.includes(c);return{isFilePath:!0,isImage:l,isBinary:d,path:e}}function Cy(i){return i.startsWith("~/")?_n.join(Ty.homedir(),i.slice(2)):i}function Ja(i){let e=Cy(i);return _n.isAbsolute(e)?e:_n.resolve(process.cwd(),e)}function Wo(i){try{let e=Ja(i),t=Ya.statSync(e);return t.isFile()?{exists:!0,size:t.size}:{exists:!1,size:0,error:"Not a file"}}catch(e){return e.code==="ENOENT"?{exists:!1,size:0,error:"File not found"}:e.code==="EACCES"?{exists:!1,size:0,error:"Permission denied"}:{exists:!1,size:0,error:e.message}}}async function Md(i){try{let e=Ja(i),t=Wo(i);if(!t.exists)return{data:null,error:t.error};if(t.size>Id)return{data:null,error:`Image too large (${dn(t.size)}, max ${dn(Id)})`};let n=Ya.readFileSync(e),s=_n.extname(i).toLowerCase(),r=Pd[s]||"image/png",o=n.toString("base64");return{data:`data:${r};base64,${o}`}}catch(e){return{data:null,error:e.message}}}function Rd(i){try{let e=Ja(i),t=Wo(i);return t.exists?t.size>kd?{content:null,error:`File too large (${dn(t.size)}, max ${dn(kd)})`}:{content:Ya.readFileSync(e,"utf8")}:{content:null,error:t.error}}catch(e){return{content:null,error:e.message}}}var Py=100,Ay=50,Za=Iy(null);function ec({children:i}){let[e,t]=ky({input:"",cursorPosition:0,pastedTexts:[],isProcessingFiles:!1,suggestion:null,history:[],historyIndex:-1,tempInput:"",undoStack:[],redoStack:[]}),n=Nd(0),s=Nd(null),r=Od(()=>({setInput:a=>{t(c=>({...c,input:a,cursorPosition:a.length}))},setCursor:a=>{t(c=>({...c,cursorPosition:Math.max(0,Math.min(a,c.input.length))}))},insertAtCursor:a=>{t(c=>{let l=c.input.slice(0,c.cursorPosition)+a+c.input.slice(c.cursorPosition);return{...c,input:l,cursorPosition:c.cursorPosition+a.length}})},deleteAtCursor:()=>{t(a=>{if(a.input===""&&a.pastedTexts.length>0)return{...a,pastedTexts:a.pastedTexts.slice(0,-1)};if(a.cursorPosition===0)return a;let c=a.input.slice(0,a.cursorPosition-1)+a.input.slice(a.cursorPosition);return{...a,input:c,cursorPosition:a.cursorPosition-1}})},clearInput:()=>{t(a=>({...a,input:"",cursorPosition:0,pastedTexts:[],suggestion:null}))},moveCursorLeft:()=>{t(a=>({...a,cursorPosition:Math.max(0,a.cursorPosition-1)}))},moveCursorRight:()=>{t(a=>({...a,cursorPosition:Math.min(a.input.length,a.cursorPosition+1)}))},moveCursorToStart:()=>{t(a=>({...a,cursorPosition:0}))},moveCursorToEnd:()=>{t(a=>({...a,cursorPosition:a.input.length}))},addPastedContent:a=>{let c=Dd(a),l=a.split(`
2525
- `);n.current+=1;let d="text",g,m;if(c.isFilePath){c.isImage?d="image_path":c.isBinary?(d="file_path",m="Binary file - cannot read as text"):d="file_path";let p=Wo(c.path);p.exists?g=p.size:m=p.error}t(p=>({...p,pastedTexts:[...p.pastedTexts,{id:n.current,content:a,lineCount:l.length,type:d,filePath:c.isFilePath?c.path:void 0,fileSize:g,error:m}]}))},addClipboardImage:(a,c)=>{n.current+=1,t(l=>({...l,pastedTexts:[...l.pastedTexts,{id:n.current,content:"Clipboard image",lineCount:1,type:"clipboard_image",imageData:a,fileSize:c}]}))},clearPastedTexts:()=>{t(a=>({...a,pastedTexts:[]}))},removeLastPaste:()=>{t(a=>({...a,pastedTexts:a.pastedTexts.slice(0,-1)}))},processFilesForSubmit:async()=>{t(a=>({...a,isProcessingFiles:!0}));try{let a=e,c=a.pastedTexts.filter(w=>w.type==="image_path"&&w.filePath),l=a.pastedTexts.filter(w=>w.type==="clipboard_image"&&w.imageData),d=a.pastedTexts.filter(w=>w.type==="file_path"&&w.filePath),g=a.pastedTexts.filter(w=>w.type==="text"),m=[],p=[],h=[];for(let w of d)if(w.filePath&&!w.error){let C=Rd(w.filePath);if(C.content){let v=Ho.basename(w.filePath),E=Ho.extname(v).slice(1)||"text";p.push(`[File: ${v}]
2526
- \`\`\`${E}
2527
- ${C.content}
2528
- \`\`\``)}else C.error&&h.push(`${Ho.basename(w.filePath)}: ${C.error}`)}for(let w of c)if(w.filePath&&!w.error){let C=await Md(w.filePath);C.data?m.push(C.data):C.error&&h.push(`${Ho.basename(w.filePath)}: ${C.error}`)}for(let w of l)w.imageData&&!w.error&&m.push(w.imageData);let f=g.map(w=>w.content).join(`
2523
+ - Item 3`,timestamp:Date.now()+600+Y*100}))],L={todos:[{id:"todo-1",content:"Setup project structure",status:"completed",activeForm:"Setting up project structure"},{id:"todo-2",content:"Implement core features",status:"completed",activeForm:"Implementing core features"},{id:"todo-3",content:"Add authentication",status:"in_progress",activeForm:"Adding authentication"},{id:"todo-4",content:"Write unit tests",status:"pending",activeForm:"Writing unit tests"},{id:"todo-5",content:"Setup CI/CD pipeline",status:"pending",activeForm:"Setting up CI/CD"},{id:"todo-6",content:"Deploy to production",status:"pending",activeForm:"Deploying to production"}],timestamp:new Date},W=new Map([["tool-1",{toolCallId:"tool-1",name:"Bash",arguments:{command:"npm install",description:"Install dependencies"},startTime:new Date,state:"running"}],["tool-2",{toolCallId:"tool-2",name:"Read",arguments:{file_path:"/src/index.ts"},startTime:new Date(Date.now()-5e3),state:"completed",output:"File content..."}],["tool-3",{toolCallId:"tool-3",name:"Grep",arguments:{pattern:"TODO",path:"src/"},startTime:new Date(Date.now()-3e3),state:"completed"}],["tool-4",{toolCallId:"tool-4",name:"Write",arguments:{file_path:"/src/new-file.ts"},startTime:new Date(Date.now()-1e3),state:"failed",error:"Permission denied"}],["tool-5",{toolCallId:"tool-5",name:"WebFetch",arguments:{url:"https://api.example.com/data"},startTime:new Date,state:"running"}]]);a(G=>({...G,messages:B,todoList:L,activeTools:W,isLoading:!0,loadingMessage:"Processing mock request..."}))},500);return()=>clearTimeout(k)},[]);let[y]=fd(()=>{let k={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:r,isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new No(k)});Bt(()=>{let k=o.messages.map(P=>({role:P.role,content:P.content,timestamp:new Date(P.timestamp||Date.now()),...P.tool&&{tool:P.tool},...P.toolOutput&&{toolOutput:P.toolOutput}}));y.setDelegate({messages:k,fullConversationHistory:k,isLoading:o.isLoading,currentInput:"",selectedModel:m.current,isVisionEnabled:p.current,conversationId:o.conversationId,usesCustomUI:!0,updateCurrentConversation:()=>{}})},[o.messages,o.isLoading,o.conversationId,y]);let T=_n(null),C=Ga(async(k,P=[])=>{if(cs.getExistingInstance()?.checkAndUpdate().catch(()=>{}),c.current){s.queueManager.addToQueue({content:k,imageUrls:P,attachments:[],model:m.current.name})||a(j=>({...j,messages:[...j.messages,{id:ye(),role:"system",content:"[!] Queue is full (max 5 messages). Your input was not saved.",timestamp:Date.now()}]}));return}let B=Date.now(),L={id:ye(),role:"user",content:k,timestamp:B},W={id:ye(),role:"assistant",content:"",timestamp:B+1},G=[...l.current,L,W];a(H=>({...H,messages:G,isLoading:!0,loadingMessage:"Processing"}));let Y=G.map(H=>({role:H.role,content:H.content,timestamp:new Date(H.timestamp||Date.now()),...H.tool&&{tool:H.tool},...H.toolOutput&&{toolOutput:H.toolOutput}}));y.setDelegate({messages:Y,fullConversationHistory:Y,isLoading:!1,currentInput:"",selectedModel:m.current,isVisionEnabled:p.current,conversationId:d.current,usesCustomUI:!0,updateCurrentConversation:()=>{}});try{await y.sendMessage(k,P.length>0?P:void 0)}catch(H){a(j=>({...j,messages:[...j.messages,{id:ye(),role:"system",content:`Error: ${H.message}`,timestamp:Date.now()}],isLoading:!1}))}},[s.queueManager,y]);T.current=C;let w=ds(()=>({onConversationIdReceived:k=>{a(P=>({...P,conversationId:k.conversationId,conversationTitleGenerated:!!k.title}))},onMessagesUpdate:k=>{a(P=>({...P,messages:k(P.messages)}))},onActiveToolsUpdate:k=>{a(P=>({...P,activeTools:k(P.activeTools)}))},onLoadingChange:k=>{a(P=>({...P,isLoading:k,activeTools:k?P.activeTools:new Map,subAgentOperations:k?P.subAgentOperations:new Map}))},onLoadingMessageChange:k=>{a(P=>({...P,loadingMessage:k}))},onTodoUpdate:k=>{f(k)},onConfirmationRequest:k=>{a(P=>({...P,pendingConfirmation:k}))},onError:k=>{a(P=>({...P,messages:[...P.messages,{id:ye(),role:"system",content:`Error: ${k}`,timestamp:Date.now()}],isLoading:!1,activeTools:new Map,subAgentOperations:new Map}))}}),[f]);ad({personalAgent:s.personalAgent,frontendWS:s.frontendWS,handlers:w});let{regularQueuedMessages:E,crossDeviceTasks:v,processNextMessage:x,hasQueuedMessages:S}=dd({queueManager:s.queueManager,frontendWS:s.frontendWS,crossDevice:s.crossDevice,isLoading:o.isLoading,selectedModel:m.current,onCrossDeviceTask:(k,P)=>{P&&T.current?.(P)}}),{subAgentOperations:I}=gd({subAgentManager:s.subAgentManager});Bt(()=>{a(k=>({...k,subAgentOperations:I}))},[I]);let{externalSession:D}=md({frontendWS:s.frontendWS});Bt(()=>{a(k=>({...k,externalSession:D}))},[D]),Bt(()=>{if(!o.isLoading&&S){let k=x();k&&T.current?.(k.content)}},[o.isLoading,S,x]);let M=ds(()=>({addMessage:k=>{a(P=>({...P,messages:[...P.messages,k]}))},addSystemMessage:k=>{a(P=>({...P,messages:[...P.messages,{id:ye(),role:"system",content:k,timestamp:Date.now()}]}))},updateMessages:k=>{a(P=>({...P,messages:k(P.messages)}))},setLoading:(k,P)=>{a(B=>({...B,isLoading:k,loadingMessage:P||B.loadingMessage}))},setConversationId:(k,P)=>{a(B=>({...B,conversationId:k,conversationTitleGenerated:!!P}))},clearChat:()=>{a(k=>({...k,messages:[{id:ye(),role:"system",content:gs.clear(),timestamp:Date.now()}],todoList:null,conversationId:null,conversationTitleGenerated:!1,staticRemountKey:k.staticRemountKey+1}))},handleSubmit:C,handleConfirmationConfirm:k=>{let P=g.current?.id;P&&(a(B=>({...B,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:P,response:k,confirmed:!0}))},handleConfirmationDecline:()=>{let k=g.current?.id;k&&(a(P=>({...P,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:k,response:"n",confirmed:!1}),a(P=>({...P,messages:[...P.messages,{id:ye(),role:"system",content:"[!] Action declined by user",timestamp:Date.now()}]})))},handleConfirmationTimeout:()=>{let k=g.current?.id;k&&(a(P=>({...P,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:k,response:"n",confirmed:!1,timedOut:!0}),a(P=>({...P,messages:[...P.messages,{id:ye(),role:"system",content:"[!] Confirmation timed out - action declined",timestamp:Date.now()}]})))},stopStreaming:async()=>{await s.personalAgent.stopStreaming(),a(k=>({...k,isLoading:!1,activeTools:new Map,subAgentOperations:new Map,pendingConfirmation:null,messages:[...k.messages,{id:ye(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))},createConversation:k=>{let P=Ze.createConversation(k);return a(B=>({...B,conversations:Ze.getConversations(),conversationId:P.id,conversationTitleGenerated:!1,messages:[{id:ye(),role:"system",content:gs.newConversation(),timestamp:Date.now()}],todoList:null,staticRemountKey:B.staticRemountKey+1})),P},switchConversation:k=>{let P=d.current,B=l.current;if(P&&B.length>1)for(let W of B)W.role!=="system"&&Ze.addMessage(P,ls.toStoredMessage(W));Ze.setCurrentConversation(k);let L=Ze.getMessages(k);a(W=>({...W,conversationId:k,messages:L.length>0?L.map(G=>ls.fromStoredMessage(G)):[{id:ye(),role:"system",content:gs.continueConversation(),timestamp:Date.now()}],staticRemountKey:W.staticRemountKey+1}))},deleteConversation:k=>{Ze.deleteConversation(k),a(P=>({...P,conversations:Ze.getConversations(),...P.conversationId===k?{conversationId:null,messages:[{id:ye(),role:"system",content:gs.deleted(),timestamp:Date.now()}],staticRemountKey:P.staticRemountKey+1}:{}}))},updateConversationTitle:(k,P)=>{Ze.updateConversationTitle(k,P),a(B=>({...B,conversations:Ze.getConversations(),conversationTitleGenerated:!0}))}}),[C,s.personalAgent]),_=ds(()=>({regularQueuedMessages:E,crossDeviceTasks:v,hasQueuedMessages:S}),[E,v,S]),F=Ga(k=>{m.current=k},[]),R=Ga(k=>{p.current=k},[]),N=ds(()=>({state:o,actions:M,services:s,queue:_,projectPath:t}),[o,M,s,_,t]);return Bt(()=>{Wt._updateModelRef=F,Wt._updateVisionRef=R},[F,R]),us.createElement(Wt.Provider,{value:N},us.createElement(bd.Provider,{value:o},us.createElement(yd.Provider,{value:M},us.createElement(vd.Provider,{value:s},us.createElement(Sd.Provider,{value:_},us.createElement(wd.Provider,{value:t},i))))))}function $n(){let i=$t(bd);if(i)return i;let e=$t(Wt);if(!e)throw new Error("useChatState must be used within ChatProvider");return e.state}function Ct(){let i=$t(yd);if(i)return i;let e=$t(Wt);if(!e)throw new Error("useChatActions must be used within ChatProvider");return e.actions}function za(){let i=$t(vd);if(i)return i;let e=$t(Wt);if(!e)throw new Error("useChatServices must be used within ChatProvider");return e.services}function qa(){let i=$t(Sd);if(i)return i;let e=$t(Wt);if(!e)throw new Error("useChatQueue must be used within ChatProvider");return e.queue}function Ka(){let i=$t(wd);if(i)return i;let e=$t(Wt);if(!e)throw new Error("useProjectPath must be used within ChatProvider");return e.projectPath}function Td(){return Wt}Xt();Ue();xn();xe();import Fo,{createContext as Uo,useContext as ps,useState as vy,useMemo as Lo,useEffect as Sy,useRef as wy}from"react";var xd=Uo(null),Cd=Uo(null),Ed=Uo(null),Bo=Uo(null);function Va({children:i}){let e=Lo(()=>pe.find(l=>l.name===de.string("selectedPersonalModel"))||pe.find(l=>l.name==="snowx-c5")||pe[0],[]),t=wy(0),[n,s]=vy({showHelp:!1,showModelMenu:!1,showCommandMenu:!1,selectedModel:e,isVisionEnabled:!1,showWizard:!1,wizard:{type:null,step:1,data:{}},operationalMode:"normal",toasts:[],isReverseSearchActive:!1}),r=Ct();Sy(()=>{let l=Td();l._updateModelRef&&l._updateModelRef(n.selectedModel),l._updateVisionRef&&l._updateVisionRef(n.isVisionEnabled)},[n.selectedModel,n.isVisionEnabled]);let o=Lo(()=>({email:X.getInstance().getUserEmail()||"User",tier:Ce.getDisplayName(Ce.getCurrentUserTier()),userTier:Ce.getCurrentUserTier()}),[]),a=Lo(()=>({toggleHelp:()=>s(l=>({...l,showHelp:!l.showHelp})),showHelp:()=>s(l=>({...l,showHelp:!0})),hideHelp:()=>s(l=>({...l,showHelp:!1})),toggleModelMenu:()=>s(l=>({...l,showModelMenu:!l.showModelMenu})),showModelMenu:()=>s(l=>({...l,showModelMenu:!0})),hideModelMenu:()=>s(l=>({...l,showModelMenu:!1})),toggleCommandMenu:()=>s(l=>({...l,showCommandMenu:!l.showCommandMenu})),showCommandMenu:()=>s(l=>({...l,showCommandMenu:!0})),hideCommandMenu:()=>s(l=>({...l,showCommandMenu:!1})),setModel:l=>{de.set("selectedPersonalModel",l.name),s(d=>({...d,selectedModel:l,showModelMenu:!1})),r.addSystemMessage(`Switched to ${l.displayName}`)},toggleVision:()=>{s(l=>{let d=!l.isVisionEnabled;return r.addSystemMessage(`Vision mode ${d?"enabled":"disabled"}`),{...l,isVisionEnabled:d}})},closeAllModals:()=>s(l=>({...l,showHelp:!1,showModelMenu:!1,showCommandMenu:!1,showWizard:!1})),showDiscordWizard:()=>s(l=>({...l,showWizard:!0,showCommandMenu:!1,wizard:{type:"discord",step:1,data:{}}})),showTelegramWizard:()=>s(l=>({...l,showWizard:!0,showCommandMenu:!1,wizard:{type:"telegram",step:1,data:{}}})),hideWizard:()=>s(l=>({...l,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setWizardStep:l=>s(d=>({...d,wizard:{...d.wizard,step:l}})),setWizardData:(l,d)=>s(g=>({...g,wizard:{...g.wizard,data:{...g.wizard.data,[l]:d}}})),resetWizard:()=>s(l=>({...l,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setMode:l=>{s(d=>({...d,operationalMode:l})),l!=="normal"&&r.addSystemMessage(`Switched to ${l.toUpperCase()} mode`)},toggleYoloMode:()=>{s(l=>{let d=l.operationalMode==="yolo"?"normal":"yolo";return d==="yolo"?r.addSystemMessage("YOLO mode enabled - all actions will be auto-approved"):r.addSystemMessage("YOLO mode disabled"),{...l,operationalMode:d}})},togglePlanMode:()=>{s(l=>{let d=l.operationalMode==="plan"?"normal":"plan";return d==="plan"?r.addSystemMessage("PLAN mode enabled - planning only, no execution"):r.addSystemMessage("PLAN mode disabled"),{...l,operationalMode:d}})},showToast:(l,d="info",g)=>{let m=`toast-${Date.now()}-${t.current++}`;s(p=>({...p,toasts:[...p.toasts,{id:m,message:l,type:d,duration:g}]}))},removeToast:l=>{s(d=>({...d,toasts:d.toasts.filter(g=>g.id!==l)}))},clearToasts:()=>{s(l=>({...l,toasts:[]}))},startReverseSearch:()=>{s(l=>({...l,isReverseSearchActive:!0,showHelp:!1,showModelMenu:!1,showCommandMenu:!1}))},stopReverseSearch:()=>{s(l=>({...l,isReverseSearchActive:!1}))}}),[r]),c=Lo(()=>({state:n,actions:a,info:o}),[n,a,o]);return Fo.createElement(Cd.Provider,{value:a},Fo.createElement(xd.Provider,{value:n},Fo.createElement(Ed.Provider,{value:o},Fo.createElement(Bo.Provider,{value:c},i))))}function hs(){let i=ps(xd);if(i)return i;let e=ps(Bo);if(!e)throw new Error("useUIState must be used within UIProvider");return e.state}function Ht(){let i=ps(Cd);if(i)return i;let e=ps(Bo);if(!e)throw new Error("useUIActions must be used within UIProvider");return e.actions}function ar(){let i=ps(Ed);if(i)return i;let e=ps(Bo);if(!e)throw new Error("useUIInfo must be used within UIProvider");return e.info}function Xa(){let i=hs();return{...i.wizard,isOpen:i.showWizard}}import Ey,{createContext as Iy,useContext as _d,useState as ky,useMemo as Od,useRef as Nd}from"react";import Ho from"path";import Ya from"fs";import Fn from"path";import Ty from"os";var Pd={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".ico":"image/x-icon",".tiff":"image/tiff",".tif":"image/tiff",".avif":"image/avif",".heic":"image/heic",".heif":"image/heif"},Ad=Object.keys(Pd),xy=[...Ad,".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".mp3",".mp4",".wav",".avi",".mov",".mkv",".ttf",".otf",".woff",".woff2",".bin",".dat",".db",".sqlite"],Id=20*1024*1024,kd=1*1024*1024;function mn(i){return i<1024?`${i}B`:i<1024*1024?`${(i/1024).toFixed(1)}KB`:`${(i/(1024*1024)).toFixed(1)}MB`}function Qa(i,e=30){if(i.length<=e)return i;let t=Fn.extname(i);return Fn.basename(i,t).slice(0,e-t.length-3)+"..."+t}function Dd(i){let e=i.trim();if(e.startsWith("file://")){e=e.replace("file://","");try{e=decodeURIComponent(e)}catch{}}if((e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1)),e=e.replace(/\\ /g," "),e.includes(`
2524
+ `))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let t=e.startsWith("/"),n=/^[A-Za-z]:[\\\/]/.test(e),s=e.startsWith("./")||e.startsWith("../"),r=e.startsWith("~/");if(!(t||n||s||r))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let a=e.toLowerCase(),c=Fn.extname(a),l=Ad.includes(c),d=xy.includes(c);return{isFilePath:!0,isImage:l,isBinary:d,path:e}}function Cy(i){return i.startsWith("~/")?Fn.join(Ty.homedir(),i.slice(2)):i}function Ja(i){let e=Cy(i);return Fn.isAbsolute(e)?e:Fn.resolve(process.cwd(),e)}function Wo(i){try{let e=Ja(i),t=Ya.statSync(e);return t.isFile()?{exists:!0,size:t.size}:{exists:!1,size:0,error:"Not a file"}}catch(e){return e.code==="ENOENT"?{exists:!1,size:0,error:"File not found"}:e.code==="EACCES"?{exists:!1,size:0,error:"Permission denied"}:{exists:!1,size:0,error:e.message}}}async function Md(i){try{let e=Ja(i),t=Wo(i);if(!t.exists)return{data:null,error:t.error};if(t.size>Id)return{data:null,error:`Image too large (${mn(t.size)}, max ${mn(Id)})`};let n=Ya.readFileSync(e),s=Fn.extname(i).toLowerCase(),r=Pd[s]||"image/png",o=n.toString("base64");return{data:`data:${r};base64,${o}`}}catch(e){return{data:null,error:e.message}}}function Rd(i){try{let e=Ja(i),t=Wo(i);return t.exists?t.size>kd?{content:null,error:`File too large (${mn(t.size)}, max ${mn(kd)})`}:{content:Ya.readFileSync(e,"utf8")}:{content:null,error:t.error}}catch(e){return{content:null,error:e.message}}}var Py=100,Ay=50,Za=Iy(null);function ec({children:i}){let[e,t]=ky({input:"",cursorPosition:0,pastedTexts:[],isProcessingFiles:!1,suggestion:null,history:[],historyIndex:-1,tempInput:"",undoStack:[],redoStack:[]}),n=Nd(0),s=Nd(null),r=Od(()=>({setInput:a=>{t(c=>({...c,input:a,cursorPosition:a.length}))},setCursor:a=>{t(c=>({...c,cursorPosition:Math.max(0,Math.min(a,c.input.length))}))},insertAtCursor:a=>{t(c=>{let l=c.input.slice(0,c.cursorPosition)+a+c.input.slice(c.cursorPosition);return{...c,input:l,cursorPosition:c.cursorPosition+a.length}})},deleteAtCursor:()=>{t(a=>{if(a.input===""&&a.pastedTexts.length>0)return{...a,pastedTexts:a.pastedTexts.slice(0,-1)};if(a.cursorPosition===0)return a;let c=a.input.slice(0,a.cursorPosition-1)+a.input.slice(a.cursorPosition);return{...a,input:c,cursorPosition:a.cursorPosition-1}})},clearInput:()=>{t(a=>({...a,input:"",cursorPosition:0,pastedTexts:[],suggestion:null}))},moveCursorLeft:()=>{t(a=>({...a,cursorPosition:Math.max(0,a.cursorPosition-1)}))},moveCursorRight:()=>{t(a=>({...a,cursorPosition:Math.min(a.input.length,a.cursorPosition+1)}))},moveCursorToStart:()=>{t(a=>({...a,cursorPosition:0}))},moveCursorToEnd:()=>{t(a=>({...a,cursorPosition:a.input.length}))},addPastedContent:a=>{let c=Dd(a),l=a.split(`
2525
+ `);n.current+=1;let d="text",g,m;if(c.isFilePath){c.isImage?d="image_path":c.isBinary?(d="file_path",m="Binary file - cannot read as text"):d="file_path";let p=Wo(c.path);p.exists?g=p.size:m=p.error}t(p=>({...p,pastedTexts:[...p.pastedTexts,{id:n.current,content:a,lineCount:l.length,type:d,filePath:c.isFilePath?c.path:void 0,fileSize:g,error:m}]}))},addClipboardImage:(a,c)=>{n.current+=1,t(l=>({...l,pastedTexts:[...l.pastedTexts,{id:n.current,content:"Clipboard image",lineCount:1,type:"clipboard_image",imageData:a,fileSize:c}]}))},clearPastedTexts:()=>{t(a=>({...a,pastedTexts:[]}))},removeLastPaste:()=>{t(a=>({...a,pastedTexts:a.pastedTexts.slice(0,-1)}))},processFilesForSubmit:async()=>{t(a=>({...a,isProcessingFiles:!0}));try{let a=e,c=a.pastedTexts.filter(w=>w.type==="image_path"&&w.filePath),l=a.pastedTexts.filter(w=>w.type==="clipboard_image"&&w.imageData),d=a.pastedTexts.filter(w=>w.type==="file_path"&&w.filePath),g=a.pastedTexts.filter(w=>w.type==="text"),m=[],p=[],h=[];for(let w of d)if(w.filePath&&!w.error){let E=Rd(w.filePath);if(E.content){let v=Ho.basename(w.filePath),x=Ho.extname(v).slice(1)||"text";p.push(`[File: ${v}]
2526
+ \`\`\`${x}
2527
+ ${E.content}
2528
+ \`\`\``)}else E.error&&h.push(`${Ho.basename(w.filePath)}: ${E.error}`)}for(let w of c)if(w.filePath&&!w.error){let E=await Md(w.filePath);E.data?m.push(E.data):E.error&&h.push(`${Ho.basename(w.filePath)}: ${E.error}`)}for(let w of l)w.imageData&&!w.error&&m.push(w.imageData);let f=g.map(w=>w.content).join(`
2529
2529
 
2530
2530
  `),y=p.join(`
2531
2531
 
@@ -2533,7 +2533,7 @@ ${C.content}
2533
2533
 
2534
2534
  `);return{fullInput:T?a.input.trim()?`${T}
2535
2535
 
2536
- ${a.input}`:T:a.input,imageUrls:m,errors:h}}finally{t(a=>({...a,isProcessingFiles:!1}))}},setSuggestion:a=>{t(c=>({...c,suggestion:a}))},acceptSuggestion:()=>{t(a=>{if(!a.suggestion)return a;let c=a.suggestion.startsWith(a.input)?a.suggestion.slice(a.input.length):a.suggestion,l=a.input+c;return{...a,input:l,cursorPosition:l.length,suggestion:null}})},addToHistory:a=>{a.trim()&&t(c=>{if(c.history.length>0&&c.history[c.history.length-1]===a)return c;let l=[...c.history,a];return l.length>Py&&l.shift(),{...c,history:l,historyIndex:-1,tempInput:""}})},navigateHistoryUp:()=>{let a=!1;return t(c=>{if(c.history.length===0)return c;if(c.historyIndex===-1){let l=c.history.length-1;return a=!0,{...c,tempInput:c.input,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}if(c.historyIndex>0){let l=c.historyIndex-1;return a=!0,{...c,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}return c}),a},navigateHistoryDown:()=>{let a=!1;return t(c=>{if(c.historyIndex===-1)return c;if(c.historyIndex>=c.history.length-1)return a=!0,{...c,historyIndex:-1,input:c.tempInput,cursorPosition:c.tempInput.length,tempInput:""};let l=c.historyIndex+1;return a=!0,{...c,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}),a},resetHistoryNavigation:()=>{t(a=>({...a,historyIndex:-1,tempInput:""}))},saveUndoState:()=>{t(a=>{let c={input:a.input,cursorPosition:a.cursorPosition};if(s.current&&s.current.input===c.input)return a;s.current=c;let l=[...a.undoStack,c];return l.length>Ay&&l.shift(),{...a,undoStack:l,redoStack:[]}})},undo:()=>{let a=!1;return t(c=>{if(c.undoStack.length===0)return c;let l={input:c.input,cursorPosition:c.cursorPosition},d=[...c.undoStack],g=d.pop();return a=!0,{...c,input:g.input,cursorPosition:g.cursorPosition,undoStack:d,redoStack:[...c.redoStack,l]}}),a},redo:()=>{let a=!1;return t(c=>{if(c.redoStack.length===0)return c;let l={input:c.input,cursorPosition:c.cursorPosition},d=[...c.redoStack],g=d.pop();return a=!0,{...c,input:g.input,cursorPosition:g.cursorPosition,undoStack:[...c.undoStack,l],redoStack:d}}),a}}),[e]),o=Od(()=>({state:e,actions:r}),[e,r]);return Ey.createElement(Za.Provider,{value:o},i)}function ar(){let i=_d(Za);if(!i)throw new Error("useInputState must be used within InputProvider");return i.state}function $n(){let i=_d(Za);if(!i)throw new Error("useInputActions must be used within InputProvider");return i.actions}import Ry,{createContext as Oy,useContext as dO,useCallback as jo,useRef as Fd,useEffect as Ny}from"react";import{EventEmitter as My}from"events";function $d(){process.stdout.write("\x1B[?1006l\x1B[?1002l")}var Go=new My;Go.setMaxListeners(50);var _y=Oy(null);function tc({children:i,enableMouse:e=!0}){let t=Fd(new Set),n=Fd(new Set),s=jo(c=>{t.current.add(c)},[]),r=jo(c=>{t.current.delete(c)},[]),o=jo(c=>{n.current.add(c)},[]),a=jo(c=>{n.current.delete(c)},[]);return Ny(()=>{if(!e)return;let c=l=>{for(let d of t.current)d(l);if(l.name==="scroll-up")for(let d of n.current)d("up");else if(l.name==="scroll-down")for(let d of n.current)d("down")};return Go.on("mouse",c),()=>{Go.off("mouse",c)}},[e]),Ry.createElement(_y.Provider,{value:{subscribe:s,unsubscribe:r,subscribeScroll:o,unsubscribeScroll:a,isMouseEnabled:e}},i)}import Ld,{createContext as Bd,useContext as hO,useState as $y,useCallback as zo,useMemo as Ud}from"react";var Fy=Bd(null),Ly=Bd(null);function nc({children:i}){let[e,t]=$y(new Set),n=zo(l=>{t(d=>{if(d.has(l))return d;let g=new Set(d);return g.add(l),g})},[]),s=zo(l=>{t(d=>{if(!d.has(l))return d;let g=new Set(d);return g.delete(l),g})},[]),r=zo(()=>{t(new Set)},[]),o=zo(l=>e.has(l),[e]),a=Ud(()=>({overflowingIds:e,hasOverflow:e.size>0}),[e]),c=Ud(()=>({markOverflowing:n,clearOverflowing:s,clearAll:r,isOverflowing:o}),[n,s,r,o]);return Ld.createElement(Ly.Provider,{value:c},Ld.createElement(Fy.Provider,{value:a},i))}import Wd,{createContext as Gd,useContext as yO,useState as Uy,useCallback as qo,useMemo as By,useRef as Wy}from"react";function Hy(i,e){return i.modelName===e.modelName&&i.requestCount===e.requestCount&&i.totalTokens===e.totalTokens&&Math.abs(i.averageLatency-e.averageLatency)<.01}function Gy(i,e){return i.toolName===e.toolName&&i.callCount===e.callCount&&i.successCount===e.successCount&&i.failureCount===e.failureCount&&Math.abs(i.averageDuration-e.averageDuration)<.01}function Ko(i,e){if(i.promptCount!==e.promptCount||i.lastPromptTokenCount!==e.lastPromptTokenCount||i.totalInputTokens!==e.totalInputTokens||i.totalOutputTokens!==e.totalOutputTokens||i.modelMetrics.size!==e.modelMetrics.size)return!1;for(let[t,n]of i.modelMetrics){let s=e.modelMetrics.get(t);if(!s||!Hy(n,s))return!1}if(i.toolCallStats.size!==e.toolCallStats.size)return!1;for(let[t,n]of i.toolCallStats){let s=e.toolCallStats.get(t);if(!s||!Gy(n,s))return!1}return!0}var jy=Gd(null),zy=Gd(null);function Hd(){let i=Date.now();return{promptCount:0,lastPromptTokenCount:0,totalInputTokens:0,totalOutputTokens:0,sessionStartTime:i,lastActivityTime:i,modelMetrics:new Map,toolCallStats:new Map}}function sc({children:i}){let[e,t]=Uy(Hd),n=Wy(e),s=qo(l=>{t(d=>{let g={...d,promptCount:d.promptCount+1,lastPromptTokenCount:l,lastActivityTime:Date.now()};return Ko(d,g)?d:g})},[]),r=qo((l,d,g,m)=>{t(p=>{let h=new Map(p.modelMetrics),f=h.get(l);if(f){let T=f.requestCount+1,x=f.totalTokens+d+g,w=(f.averageLatency*f.requestCount+m)/T;h.set(l,{modelName:l,requestCount:T,totalTokens:x,averageLatency:w})}else h.set(l,{modelName:l,requestCount:1,totalTokens:d+g,averageLatency:m});let y={...p,totalInputTokens:p.totalInputTokens+d,totalOutputTokens:p.totalOutputTokens+g,lastActivityTime:Date.now(),modelMetrics:h};return Ko(p,y)?p:y})},[]),o=qo((l,d,g)=>{t(m=>{let p=new Map(m.toolCallStats),h=p.get(l);if(h){let y=h.callCount+1,T=(h.averageDuration*h.callCount+g)/y;p.set(l,{toolName:l,callCount:y,successCount:h.successCount+(d?1:0),failureCount:h.failureCount+(d?0:1),averageDuration:T})}else p.set(l,{toolName:l,callCount:1,successCount:d?1:0,failureCount:d?0:1,averageDuration:g});let f={...m,lastActivityTime:Date.now(),toolCallStats:p};return Ko(m,f)?m:f})},[]),a=qo(()=>{t(Hd())},[]),c=By(()=>({recordPrompt:s,recordModelUsage:r,recordToolCall:o,resetSession:a}),[s,r,o,a]);return Wd.createElement(zy.Provider,{value:c},Wd.createElement(jy.Provider,{value:e},i))}import qy,{createContext as Ky,useContext as TO,useState as jd,useEffect as zd,useCallback as cr,useMemo as qd,useRef as rc}from"react";var lr={high:{enableAnimations:!0,enableSyntaxHighlighting:!0,enableSmoothScrolling:!0,maxVisibleMessages:100,inputDebounceMs:16,suggestionDelayMs:150,enableVirtualization:!1},medium:{enableAnimations:!0,enableSyntaxHighlighting:!0,enableSmoothScrolling:!0,maxVisibleMessages:50,inputDebounceMs:32,suggestionDelayMs:250,enableVirtualization:!0},low:{enableAnimations:!1,enableSyntaxHighlighting:!0,enableSmoothScrolling:!1,maxVisibleMessages:30,inputDebounceMs:50,suggestionDelayMs:400,enableVirtualization:!0},minimal:{enableAnimations:!1,enableSyntaxHighlighting:!1,enableSmoothScrolling:!1,maxVisibleMessages:20,inputDebounceMs:100,suggestionDelayMs:500,enableVirtualization:!0}},Kd={fps:60,frameTime:16.67,memoryUsageMB:0,memoryPressure:"normal",totalRenders:0,avgRenderTime:0,peakRenderTime:0,isDegraded:!1,performanceLevel:"high"},Vy=Ky(null);function oc({children:i,initialLevel:e,enableAdaptive:t=!0,memoryWarningMB:n=150,memoryCriticalMB:s=250}){let[r,o]=jd(Kd),[a,c]=jd(lr[e||"high"]),l=rc([]),d=rc([]),g=rc(0),m=cr(w=>{let C=Date.now();l.current.push(w),l.current.length>100&&l.current.shift(),d.current.push(C);let v=C-1e3;d.current=d.current.filter(E=>E>v),o(E=>{let S=l.current,I=S.length>0?S.reduce((D,_)=>D+_,0)/S.length:0,P=Math.max(E.peakRenderTime,w),R=d.current.length,$=R>0?1e3/R:16.67;return{...E,totalRenders:E.totalRenders+1,avgRenderTime:I,peakRenderTime:P,fps:R,frameTime:$,isDegraded:I>16||R<30}})},[]);zd(()=>{let w=()=>{if(typeof process<"u"&&process.memoryUsage){let E=process.memoryUsage().heapUsed/1024/1024,S="normal";E>=s?S="critical":E>=n&&(S="warning"),o(I=>({...I,memoryUsageMB:E,memoryPressure:S}))}};w();let C=setInterval(w,5e3);return()=>clearInterval(C)},[n,s]),zd(()=>{if(!t)return;let w=r.performanceLevel;r.memoryPressure==="critical"||r.fps<15?w="minimal":r.memoryPressure==="warning"||r.fps<30||r.avgRenderTime>32?w="low":r.fps<45||r.avgRenderTime>20?w="medium":r.fps>=55&&r.avgRenderTime<12&&r.memoryPressure==="normal"&&(w="high"),w!==r.performanceLevel&&(o(C=>({...C,performanceLevel:w})),c(lr[w]))},[t,r.fps,r.avgRenderTime,r.memoryPressure,r.performanceLevel]);let p=cr(w=>{o(C=>({...C,performanceLevel:w})),c(lr[w])},[]),h=cr(()=>{l.current=[],d.current=[],o(w=>({...Kd,performanceLevel:w.performanceLevel}))},[]),f=cr((w,C)=>{c(v=>({...v,[w]:C}))},[]),y=cr(w=>{c(lr[w])},[]),T=qd(()=>({recordRender:m,setPerformanceLevel:p,resetMetrics:h,updateSetting:f,applyPreset:y}),[m,p,h,f,y]),x=qd(()=>({state:{metrics:r,settings:a},actions:T}),[r,a,T]);return qy.createElement(Vy.Provider,{value:x},i)}function Vd({children:i,initialProjectPath:e}){return Fn.createElement(oc,{enableAdaptive:!0,memoryWarningMB:150,memoryCriticalMB:250},Fn.createElement(sc,null,Fn.createElement(tc,{enableMouse:!1},Fn.createElement(nc,null,Fn.createElement(ja,{initialProjectPath:e},Fn.createElement(Va,null,Fn.createElement(ec,null,i)))))))}import NO,{createContext as Xy,useContext as _O,useCallback as $O,useState as FO,useEffect as LO,useMemo as UO}from"react";var BO=Xy(null);import GO,{createContext as Xd,useContext as jO,useCallback as zO,useState as qO,useMemo as KO,useRef as VO}from"react";var XO=Xd(null),YO=Xd(null);import ZO,{createContext as Yy,useCallback as eN,useContext as tN,useEffect as nN,useMemo as sN,useRef as rN,useState as oN}from"react";var iN=Yy(null);import uN,{createContext as yv,useContext as dN,useEffect as gN,useState as mN,useMemo as pN,useCallback as hN}from"react";import*as ac from"node:fs";var Qy="\x1B[?u",Yd="\x1B]11;?\x1B\\",Jy="\x1B[>q",Zy="\x1B[c",ev="\x1B[>4;?m",tv="\x1B[8m",nv="\x1B[2K\r",sv="\x1B[0m",rv="\x1B[>u",ov="\x1B[<u",iv="\x1B[?2004h",av="\x1B[?2004l",cv="\x1B[>4;2m",lv="\x1B[>4;0m",uv="\x1B[<u\x1B[>4;0m\x1B[?2004l",dv=/\x1b\[\?(\d+)u/,gv=/\x1bP>\|(.+?)(\x1b\\|\x07)/,mv=/\x1b\[\?(\d+)(;\d+)*c/,pv=/\x1b\]11;rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})(\x1b\\|\x07)/,hv=/\x1b\[>4;(\d+)m/;function fv(i,e,t){let n=s=>s.length===4?s.substring(0,2):s.length===2?s:s.length===1?s+s:s.substring(0,2);return`#${n(i)}${n(e)}${n(t)}`.toLowerCase()}function ps(){try{if(process.stdout?.fd!==void 0){ac.writeSync(process.stdout.fd,uv);return}}catch{}try{process.stdout.write(ov),process.stdout.write(lv),process.stdout.write(av)}catch{}}var ic=class i{static instance;detectionComplete=!1;terminalBackgroundColor;kittySupported=!1;kittyEnabled=!1;modifyOtherKeysSupported=!1;terminalName;constructor(){}static getInstance(){return this.instance||(this.instance=new i),this.instance}static resetInstanceForTesting(){this.instance=void 0}static queryBackgroundColor(e){e.write(Yd)}async detectCapabilities(){if(!this.detectionComplete){if(!process.stdin.isTTY||!process.stdout.isTTY){this.detectionComplete=!0;return}return process.off("exit",ps),process.off("SIGTERM",ps),process.off("SIGINT",ps),process.on("exit",ps),process.on("SIGTERM",ps),process.on("SIGINT",ps),new Promise(e=>{let t=process.stdin.isRaw;t||process.stdin.setRawMode(!0);let n="",s=!1,r=!1,o=!1,a=!1,c=!1,l,d=()=>{l&&clearTimeout(l),process.stdin.removeListener("data",g),t||process.stdin.setRawMode(!1),this.detectionComplete=!0,this.enableSupportedModes(),e()};l=setTimeout(d,1e3);let g=m=>{if(n+=m.toString(),!a){let p=n.match(pv);p&&(a=!0,this.terminalBackgroundColor=fv(p[1],p[2],p[3]))}if(!s&&dv.test(n)&&(s=!0,this.kittySupported=!0),!c){let p=n.match(hv);if(p){c=!0;let h=parseInt(p[1],10);this.modifyOtherKeysSupported=h>=2}}if(!r){let p=n.match(gv);p&&(r=!0,this.terminalName=p[1])}o||n.match(mv)&&(o=!0,d())};process.stdin.on("data",g);try{ac.writeSync(process.stdout.fd,tv+Qy+Yd+Jy+ev+Zy+nv+sv)}catch{d()}})}}enableSupportedModes(){try{this.kittySupported?(process.stdout.write(rv),this.kittyEnabled=!0):this.modifyOtherKeysSupported&&process.stdout.write(cv),process.stdout.write(iv)}catch{}}getTerminalBackgroundColor(){return this.terminalBackgroundColor}getTerminalName(){return this.terminalName}isKittyProtocolEnabled(){return this.kittyEnabled}supportsOsc9Notifications(e=process.env){return e.WT_SESSION?!1:this.hasOsc9TerminalSignature(this.getTerminalName())||this.hasOsc9TerminalSignature(e.TERM_PROGRAM)||this.hasOsc9TerminalSignature(e.TERM)}hasOsc9TerminalSignature(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("wezterm")||t.includes("ghostty")||t.includes("iterm")||t.includes("kitty")}getCapabilities(){return{kittySupported:this.kittySupported,kittyEnabled:this.kittyEnabled,modifyOtherKeysSupported:this.modifyOtherKeysSupported,backgroundColor:this.terminalBackgroundColor,terminalName:this.terminalName,detectionComplete:this.detectionComplete}}},bv=ic.getInstance();var bN=yv(null);import SN,{createContext as vv,useContext as wN,useState as TN,useCallback as xN,useMemo as CN,useRef as EN,useEffect as IN}from"react";var kN=vv(null);import DN,{createContext as Sv,useContext as MN,useState as RN,useCallback as ON,useMemo as NN,useEffect as _N}from"react";var $N=Sv(null);import UN,{createContext as wv,useContext as BN,useState as WN,useCallback as HN,useMemo as GN,useEffect as jN}from"react";var zN=wv(null);import VN,{createContext as Tv,useContext as XN,useState as YN,useCallback as QN,useMemo as JN,useRef as ZN,useEffect as e_}from"react";var t_=Tv(null);import{useRef as dc,useEffect as Rv,useCallback as Ov}from"react";import{useInput as Nv,useApp as _v}from"@jrichman/ink";import{useCallback as tg}from"react";import{useApp as kv}from"@jrichman/ink";import{execSync as Qd}from"child_process";import Jd from"os";import Ht from"fs";function Vo(){if(Jd.platform()!=="darwin")return!1;try{let i=Qd('osascript -e "clipboard info"',{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]});return i.includes("PNGf")||i.includes("TIFF")||i.includes("JPEG")||i.includes("jp2")||i.includes("GIF")||i.includes("BMP")}catch{return!1}}async function Xo(){if(Jd.platform()!=="darwin")return{data:null,size:0,error:"Clipboard image not supported on this platform"};let i=Date.now(),e=`/tmp/clipboard-image-${i}.png`,t=`/tmp/clipboard-script-${i}.scpt`;try{let n=`use framework "AppKit"
2536
+ ${a.input}`:T:a.input,imageUrls:m,errors:h}}finally{t(a=>({...a,isProcessingFiles:!1}))}},setSuggestion:a=>{t(c=>({...c,suggestion:a}))},acceptSuggestion:()=>{t(a=>{if(!a.suggestion)return a;let c=a.suggestion.startsWith(a.input)?a.suggestion.slice(a.input.length):a.suggestion,l=a.input+c;return{...a,input:l,cursorPosition:l.length,suggestion:null}})},addToHistory:a=>{a.trim()&&t(c=>{if(c.history.length>0&&c.history[c.history.length-1]===a)return c;let l=[...c.history,a];return l.length>Py&&l.shift(),{...c,history:l,historyIndex:-1,tempInput:""}})},navigateHistoryUp:()=>{let a=!1;return t(c=>{if(c.history.length===0)return c;if(c.historyIndex===-1){let l=c.history.length-1;return a=!0,{...c,tempInput:c.input,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}if(c.historyIndex>0){let l=c.historyIndex-1;return a=!0,{...c,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}return c}),a},navigateHistoryDown:()=>{let a=!1;return t(c=>{if(c.historyIndex===-1)return c;if(c.historyIndex>=c.history.length-1)return a=!0,{...c,historyIndex:-1,input:c.tempInput,cursorPosition:c.tempInput.length,tempInput:""};let l=c.historyIndex+1;return a=!0,{...c,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}),a},resetHistoryNavigation:()=>{t(a=>({...a,historyIndex:-1,tempInput:""}))},saveUndoState:()=>{t(a=>{let c={input:a.input,cursorPosition:a.cursorPosition};if(s.current&&s.current.input===c.input)return a;s.current=c;let l=[...a.undoStack,c];return l.length>Ay&&l.shift(),{...a,undoStack:l,redoStack:[]}})},undo:()=>{let a=!1;return t(c=>{if(c.undoStack.length===0)return c;let l={input:c.input,cursorPosition:c.cursorPosition},d=[...c.undoStack],g=d.pop();return a=!0,{...c,input:g.input,cursorPosition:g.cursorPosition,undoStack:d,redoStack:[...c.redoStack,l]}}),a},redo:()=>{let a=!1;return t(c=>{if(c.redoStack.length===0)return c;let l={input:c.input,cursorPosition:c.cursorPosition},d=[...c.redoStack],g=d.pop();return a=!0,{...c,input:g.input,cursorPosition:g.cursorPosition,undoStack:[...c.undoStack,l],redoStack:d}}),a}}),[e]),o=Od(()=>({state:e,actions:r}),[e,r]);return Ey.createElement(Za.Provider,{value:o},i)}function cr(){let i=_d(Za);if(!i)throw new Error("useInputState must be used within InputProvider");return i.state}function Ln(){let i=_d(Za);if(!i)throw new Error("useInputActions must be used within InputProvider");return i.actions}import Ry,{createContext as Oy,useContext as dO,useCallback as jo,useRef as Fd,useEffect as Ny}from"react";import{EventEmitter as My}from"events";function $d(){process.stdout.write("\x1B[?1006l\x1B[?1002l")}var Go=new My;Go.setMaxListeners(50);var _y=Oy(null);function tc({children:i,enableMouse:e=!0}){let t=Fd(new Set),n=Fd(new Set),s=jo(c=>{t.current.add(c)},[]),r=jo(c=>{t.current.delete(c)},[]),o=jo(c=>{n.current.add(c)},[]),a=jo(c=>{n.current.delete(c)},[]);return Ny(()=>{if(!e)return;let c=l=>{for(let d of t.current)d(l);if(l.name==="scroll-up")for(let d of n.current)d("up");else if(l.name==="scroll-down")for(let d of n.current)d("down")};return Go.on("mouse",c),()=>{Go.off("mouse",c)}},[e]),Ry.createElement(_y.Provider,{value:{subscribe:s,unsubscribe:r,subscribeScroll:o,unsubscribeScroll:a,isMouseEnabled:e}},i)}import Ld,{createContext as Bd,useContext as hO,useState as $y,useCallback as zo,useMemo as Ud}from"react";var Fy=Bd(null),Ly=Bd(null);function nc({children:i}){let[e,t]=$y(new Set),n=zo(l=>{t(d=>{if(d.has(l))return d;let g=new Set(d);return g.add(l),g})},[]),s=zo(l=>{t(d=>{if(!d.has(l))return d;let g=new Set(d);return g.delete(l),g})},[]),r=zo(()=>{t(new Set)},[]),o=zo(l=>e.has(l),[e]),a=Ud(()=>({overflowingIds:e,hasOverflow:e.size>0}),[e]),c=Ud(()=>({markOverflowing:n,clearOverflowing:s,clearAll:r,isOverflowing:o}),[n,s,r,o]);return Ld.createElement(Ly.Provider,{value:c},Ld.createElement(Fy.Provider,{value:a},i))}import Wd,{createContext as Gd,useContext as yO,useState as Uy,useCallback as qo,useMemo as By,useRef as Wy}from"react";function Hy(i,e){return i.modelName===e.modelName&&i.requestCount===e.requestCount&&i.totalTokens===e.totalTokens&&Math.abs(i.averageLatency-e.averageLatency)<.01}function Gy(i,e){return i.toolName===e.toolName&&i.callCount===e.callCount&&i.successCount===e.successCount&&i.failureCount===e.failureCount&&Math.abs(i.averageDuration-e.averageDuration)<.01}function Ko(i,e){if(i.promptCount!==e.promptCount||i.lastPromptTokenCount!==e.lastPromptTokenCount||i.totalInputTokens!==e.totalInputTokens||i.totalOutputTokens!==e.totalOutputTokens||i.modelMetrics.size!==e.modelMetrics.size)return!1;for(let[t,n]of i.modelMetrics){let s=e.modelMetrics.get(t);if(!s||!Hy(n,s))return!1}if(i.toolCallStats.size!==e.toolCallStats.size)return!1;for(let[t,n]of i.toolCallStats){let s=e.toolCallStats.get(t);if(!s||!Gy(n,s))return!1}return!0}var jy=Gd(null),zy=Gd(null);function Hd(){let i=Date.now();return{promptCount:0,lastPromptTokenCount:0,totalInputTokens:0,totalOutputTokens:0,sessionStartTime:i,lastActivityTime:i,modelMetrics:new Map,toolCallStats:new Map}}function sc({children:i}){let[e,t]=Uy(Hd),n=Wy(e),s=qo(l=>{t(d=>{let g={...d,promptCount:d.promptCount+1,lastPromptTokenCount:l,lastActivityTime:Date.now()};return Ko(d,g)?d:g})},[]),r=qo((l,d,g,m)=>{t(p=>{let h=new Map(p.modelMetrics),f=h.get(l);if(f){let T=f.requestCount+1,C=f.totalTokens+d+g,w=(f.averageLatency*f.requestCount+m)/T;h.set(l,{modelName:l,requestCount:T,totalTokens:C,averageLatency:w})}else h.set(l,{modelName:l,requestCount:1,totalTokens:d+g,averageLatency:m});let y={...p,totalInputTokens:p.totalInputTokens+d,totalOutputTokens:p.totalOutputTokens+g,lastActivityTime:Date.now(),modelMetrics:h};return Ko(p,y)?p:y})},[]),o=qo((l,d,g)=>{t(m=>{let p=new Map(m.toolCallStats),h=p.get(l);if(h){let y=h.callCount+1,T=(h.averageDuration*h.callCount+g)/y;p.set(l,{toolName:l,callCount:y,successCount:h.successCount+(d?1:0),failureCount:h.failureCount+(d?0:1),averageDuration:T})}else p.set(l,{toolName:l,callCount:1,successCount:d?1:0,failureCount:d?0:1,averageDuration:g});let f={...m,lastActivityTime:Date.now(),toolCallStats:p};return Ko(m,f)?m:f})},[]),a=qo(()=>{t(Hd())},[]),c=By(()=>({recordPrompt:s,recordModelUsage:r,recordToolCall:o,resetSession:a}),[s,r,o,a]);return Wd.createElement(zy.Provider,{value:c},Wd.createElement(jy.Provider,{value:e},i))}import qy,{createContext as Ky,useContext as TO,useState as jd,useEffect as zd,useCallback as lr,useMemo as qd,useRef as rc}from"react";var ur={high:{enableAnimations:!0,enableSyntaxHighlighting:!0,enableSmoothScrolling:!0,maxVisibleMessages:100,inputDebounceMs:16,suggestionDelayMs:150,enableVirtualization:!1},medium:{enableAnimations:!0,enableSyntaxHighlighting:!0,enableSmoothScrolling:!0,maxVisibleMessages:50,inputDebounceMs:32,suggestionDelayMs:250,enableVirtualization:!0},low:{enableAnimations:!1,enableSyntaxHighlighting:!0,enableSmoothScrolling:!1,maxVisibleMessages:30,inputDebounceMs:50,suggestionDelayMs:400,enableVirtualization:!0},minimal:{enableAnimations:!1,enableSyntaxHighlighting:!1,enableSmoothScrolling:!1,maxVisibleMessages:20,inputDebounceMs:100,suggestionDelayMs:500,enableVirtualization:!0}},Kd={fps:60,frameTime:16.67,memoryUsageMB:0,memoryPressure:"normal",totalRenders:0,avgRenderTime:0,peakRenderTime:0,isDegraded:!1,performanceLevel:"high"},Vy=Ky(null);function oc({children:i,initialLevel:e,enableAdaptive:t=!0,memoryWarningMB:n=150,memoryCriticalMB:s=250}){let[r,o]=jd(Kd),[a,c]=jd(ur[e||"high"]),l=rc([]),d=rc([]),g=rc(0),m=lr(w=>{let E=Date.now();l.current.push(w),l.current.length>100&&l.current.shift(),d.current.push(E);let v=E-1e3;d.current=d.current.filter(x=>x>v),o(x=>{let S=l.current,I=S.length>0?S.reduce((F,R)=>F+R,0)/S.length:0,D=Math.max(x.peakRenderTime,w),M=d.current.length,_=M>0?1e3/M:16.67;return{...x,totalRenders:x.totalRenders+1,avgRenderTime:I,peakRenderTime:D,fps:M,frameTime:_,isDegraded:I>16||M<30}})},[]);zd(()=>{let w=()=>{if(typeof process<"u"&&process.memoryUsage){let x=process.memoryUsage().heapUsed/1024/1024,S="normal";x>=s?S="critical":x>=n&&(S="warning"),o(I=>({...I,memoryUsageMB:x,memoryPressure:S}))}};w();let E=setInterval(w,5e3);return()=>clearInterval(E)},[n,s]),zd(()=>{if(!t)return;let w=r.performanceLevel;r.memoryPressure==="critical"||r.fps<15?w="minimal":r.memoryPressure==="warning"||r.fps<30||r.avgRenderTime>32?w="low":r.fps<45||r.avgRenderTime>20?w="medium":r.fps>=55&&r.avgRenderTime<12&&r.memoryPressure==="normal"&&(w="high"),w!==r.performanceLevel&&(o(E=>({...E,performanceLevel:w})),c(ur[w]))},[t,r.fps,r.avgRenderTime,r.memoryPressure,r.performanceLevel]);let p=lr(w=>{o(E=>({...E,performanceLevel:w})),c(ur[w])},[]),h=lr(()=>{l.current=[],d.current=[],o(w=>({...Kd,performanceLevel:w.performanceLevel}))},[]),f=lr((w,E)=>{c(v=>({...v,[w]:E}))},[]),y=lr(w=>{c(ur[w])},[]),T=qd(()=>({recordRender:m,setPerformanceLevel:p,resetMetrics:h,updateSetting:f,applyPreset:y}),[m,p,h,f,y]),C=qd(()=>({state:{metrics:r,settings:a},actions:T}),[r,a,T]);return qy.createElement(Vy.Provider,{value:C},i)}function Vd({children:i,initialProjectPath:e}){return Un.createElement(oc,{enableAdaptive:!0,memoryWarningMB:150,memoryCriticalMB:250},Un.createElement(sc,null,Un.createElement(tc,{enableMouse:!1},Un.createElement(nc,null,Un.createElement(ja,{initialProjectPath:e},Un.createElement(Va,null,Un.createElement(ec,null,i)))))))}import NO,{createContext as Xy,useContext as _O,useCallback as $O,useState as FO,useEffect as LO,useMemo as UO}from"react";var BO=Xy(null);import GO,{createContext as Xd,useContext as jO,useCallback as zO,useState as qO,useMemo as KO,useRef as VO}from"react";var XO=Xd(null),YO=Xd(null);import ZO,{createContext as Yy,useCallback as eN,useContext as tN,useEffect as nN,useMemo as sN,useRef as rN,useState as oN}from"react";var iN=Yy(null);import uN,{createContext as yv,useContext as dN,useEffect as gN,useState as mN,useMemo as pN,useCallback as hN}from"react";import*as ac from"node:fs";var Qy="\x1B[?u",Yd="\x1B]11;?\x1B\\",Jy="\x1B[>q",Zy="\x1B[c",ev="\x1B[>4;?m",tv="\x1B[8m",nv="\x1B[2K\r",sv="\x1B[0m",rv="\x1B[>u",ov="\x1B[<u",iv="\x1B[?2004h",av="\x1B[?2004l",cv="\x1B[>4;2m",lv="\x1B[>4;0m",uv="\x1B[<u\x1B[>4;0m\x1B[?2004l",dv=/\x1b\[\?(\d+)u/,gv=/\x1bP>\|(.+?)(\x1b\\|\x07)/,mv=/\x1b\[\?(\d+)(;\d+)*c/,pv=/\x1b\]11;rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})(\x1b\\|\x07)/,hv=/\x1b\[>4;(\d+)m/;function fv(i,e,t){let n=s=>s.length===4?s.substring(0,2):s.length===2?s:s.length===1?s+s:s.substring(0,2);return`#${n(i)}${n(e)}${n(t)}`.toLowerCase()}function fs(){try{if(process.stdout?.fd!==void 0){ac.writeSync(process.stdout.fd,uv);return}}catch{}try{process.stdout.write(ov),process.stdout.write(lv),process.stdout.write(av)}catch{}}var ic=class i{static instance;detectionComplete=!1;terminalBackgroundColor;kittySupported=!1;kittyEnabled=!1;modifyOtherKeysSupported=!1;terminalName;constructor(){}static getInstance(){return this.instance||(this.instance=new i),this.instance}static resetInstanceForTesting(){this.instance=void 0}static queryBackgroundColor(e){e.write(Yd)}async detectCapabilities(){if(!this.detectionComplete){if(!process.stdin.isTTY||!process.stdout.isTTY){this.detectionComplete=!0;return}return process.off("exit",fs),process.off("SIGTERM",fs),process.off("SIGINT",fs),process.on("exit",fs),process.on("SIGTERM",fs),process.on("SIGINT",fs),new Promise(e=>{let t=process.stdin.isRaw;t||process.stdin.setRawMode(!0);let n="",s=!1,r=!1,o=!1,a=!1,c=!1,l,d=()=>{l&&clearTimeout(l),process.stdin.removeListener("data",g),t||process.stdin.setRawMode(!1),this.detectionComplete=!0,this.enableSupportedModes(),e()};l=setTimeout(d,1e3);let g=m=>{if(n+=m.toString(),!a){let p=n.match(pv);p&&(a=!0,this.terminalBackgroundColor=fv(p[1],p[2],p[3]))}if(!s&&dv.test(n)&&(s=!0,this.kittySupported=!0),!c){let p=n.match(hv);if(p){c=!0;let h=parseInt(p[1],10);this.modifyOtherKeysSupported=h>=2}}if(!r){let p=n.match(gv);p&&(r=!0,this.terminalName=p[1])}o||n.match(mv)&&(o=!0,d())};process.stdin.on("data",g);try{ac.writeSync(process.stdout.fd,tv+Qy+Yd+Jy+ev+Zy+nv+sv)}catch{d()}})}}enableSupportedModes(){try{this.kittySupported?(process.stdout.write(rv),this.kittyEnabled=!0):this.modifyOtherKeysSupported&&process.stdout.write(cv),process.stdout.write(iv)}catch{}}getTerminalBackgroundColor(){return this.terminalBackgroundColor}getTerminalName(){return this.terminalName}isKittyProtocolEnabled(){return this.kittyEnabled}supportsOsc9Notifications(e=process.env){return e.WT_SESSION?!1:this.hasOsc9TerminalSignature(this.getTerminalName())||this.hasOsc9TerminalSignature(e.TERM_PROGRAM)||this.hasOsc9TerminalSignature(e.TERM)}hasOsc9TerminalSignature(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("wezterm")||t.includes("ghostty")||t.includes("iterm")||t.includes("kitty")}getCapabilities(){return{kittySupported:this.kittySupported,kittyEnabled:this.kittyEnabled,modifyOtherKeysSupported:this.modifyOtherKeysSupported,backgroundColor:this.terminalBackgroundColor,terminalName:this.terminalName,detectionComplete:this.detectionComplete}}},bv=ic.getInstance();var bN=yv(null);import SN,{createContext as vv,useContext as wN,useState as TN,useCallback as xN,useMemo as CN,useRef as EN,useEffect as IN}from"react";var kN=vv(null);import DN,{createContext as Sv,useContext as MN,useState as RN,useCallback as ON,useMemo as NN,useEffect as _N}from"react";var $N=Sv(null);import UN,{createContext as wv,useContext as BN,useState as WN,useCallback as HN,useMemo as GN,useEffect as jN}from"react";var zN=wv(null);import VN,{createContext as Tv,useContext as XN,useState as YN,useCallback as QN,useMemo as JN,useRef as ZN,useEffect as e_}from"react";var t_=Tv(null);import{useRef as dc,useEffect as Rv,useCallback as Ov}from"react";import{useInput as Nv,useApp as _v}from"@jrichman/ink";import{useCallback as tg}from"react";import{useApp as kv}from"@jrichman/ink";import{execSync as Qd}from"child_process";import Jd from"os";import Gt from"fs";function Vo(){if(Jd.platform()!=="darwin")return!1;try{let i=Qd('osascript -e "clipboard info"',{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]});return i.includes("PNGf")||i.includes("TIFF")||i.includes("JPEG")||i.includes("jp2")||i.includes("GIF")||i.includes("BMP")}catch{return!1}}async function Xo(){if(Jd.platform()!=="darwin")return{data:null,size:0,error:"Clipboard image not supported on this platform"};let i=Date.now(),e=`/tmp/clipboard-image-${i}.png`,t=`/tmp/clipboard-script-${i}.scpt`;try{let n=`use framework "AppKit"
2537
2537
  use scripting additions
2538
2538
 
2539
2539
  set theClipboard to current application's NSPasteboard's generalPasteboard()
@@ -2546,121 +2546,121 @@ if imageData is not missing value then
2546
2546
  else
2547
2547
  return "error:No PNG image in clipboard"
2548
2548
  end if
2549
- `;Ht.writeFileSync(t,n);let s;try{s=Qd(`osascript "${t}"`,{encoding:"utf8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim()}finally{try{Ht.unlinkSync(t)}catch{}}if(s.startsWith("error:"))return{data:null,size:0,error:s.replace("error:","")};if(!Ht.existsSync(e))return{data:null,size:0,error:"Failed to save clipboard image"};let r=Ht.readFileSync(e),o=r.length,c=`data:image/png;base64,${r.toString("base64")}`;try{Ht.unlinkSync(e)}catch{}return{data:c,size:o}}catch(n){try{Ht.existsSync(e)&&Ht.unlinkSync(e),Ht.existsSync(t)&&Ht.unlinkSync(t)}catch{}return{data:null,size:0,error:n.message||"Failed to read clipboard image"}}}Te();At();import gn from"axios";var Gt=class i{static instance;authService;deviceRegistration;baseURL="https://snowx.ai/api-beta/api";constructor(){this.authService=X.getInstance(),this.deviceRegistration=Pe.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async getAuthHeaders(){let e=await this.authService.getAccessToken();if(!e)throw new Error('Not authenticated. Run "orion auth login" first.');return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}async getDeviceId(){if(!this.authService.getUserId())throw new Error('Not authenticated. Run "orion auth login" first.');let t=this.deviceRegistration.getCurrentDeviceId();if(!t)throw new Error("Device not registered. Please wait a moment and try again.");return t}generateDiscordInviteUrl(e){return`https://discord.com/api/oauth2/authorize?client_id=${e}&permissions=274877975552&scope=bot%20applications.commands`}validateDiscordToken(e){return/^[A-Za-z0-9_-]{24,}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27,}$/.test(e.trim())}async connectDiscord(e){try{let t=await this.getAuthHeaders(),n=await this.getDeviceId(),s=await gn.post(`${this.baseURL}/integrations/discord`,{bot_token:e.botToken,device_id:n,owner_user_ids:e.ownerUserIds.join(","),guest_user_ids:e.guestUserIds?.join(",")||"",allow_guild_chat:e.allowGuildChat||!1},{headers:t});return{success:!0,botUsername:s.data.botUsername,botId:s.data.botId,webhookUrl:s.data.webhookUrl}}catch(t){return{success:!1,error:t.response?.data?.error||t.message}}}async getDiscordStatus(){try{let e=await this.getAuthHeaders(),t=await this.getDeviceId(),n=this.authService.getUserId(),s=await gn.get(`${this.baseURL}/integrations/discord/status`,{headers:e,params:{device_id:t,user_id:n}});return{connected:s.data.connected||!1,botUsername:s.data.bot_username,botId:s.data.bot_id,ownerUserIds:s.data.owner_user_ids||[],guestUserIds:s.data.guest_user_ids||[],allowGuildChat:s.data.allow_guild_chat||!1,webhookUrl:s.data.webhook_url,botTokenHash:s.data.bot_token_hash}}catch{return{connected:!1}}}async updateDiscord(e){try{let t=await this.getAuthHeaders(),s={device_id:await this.getDeviceId()};return e.ownerUserIds&&(s.owner_user_ids=e.ownerUserIds.join(",")),e.guestUserIds!==void 0&&(s.guest_user_ids=e.guestUserIds.join(",")),e.allowGuildChat!==void 0&&(s.allow_guild_chat=e.allowGuildChat),await gn.patch(`${this.baseURL}/integrations/discord`,s,{headers:t}),{success:!0}}catch(t){return{success:!1,error:t.response?.data?.error||t.message}}}async disconnectDiscord(){try{let e=await this.getAuthHeaders(),t=await this.getDeviceId(),n=this.authService.getUserId();return await gn.delete(`${this.baseURL}/integrations/discord`,{headers:e,data:{device_id:t,user_id:n}}),!0}catch{return!1}}validateTelegramToken(e){return/^\d{6,15}:[A-Za-z0-9_-]{35,50}$/.test(e.trim())}getTelegramChatUrl(e){return`https://t.me/${e.replace(/^@/,"")}`}async connectTelegram(e){try{let t=await this.getAuthHeaders(),n=await this.getDeviceId();return{success:!0,botUsername:(await gn.post(`${this.baseURL}/integrations/telegram`,{bot_token:e.botToken,device_id:n,owner_usernames:e.ownerUsernames.join(","),guest_usernames:e.guestUsernames?.join(",")||"",allow_group_chat:e.allowGroupChat||!1,route_to_dm:e.routeToDM||!1},{headers:t})).data.botUsername}}catch(t){return{success:!1,error:t.response?.data?.error||t.message}}}async getTelegramStatus(){try{let e=await this.getAuthHeaders(),t=await this.getDeviceId(),n=this.authService.getUserId(),s=await gn.get(`${this.baseURL}/integrations/telegram/status`,{headers:e,params:{device_id:t,user_id:n}});return{connected:s.data.connected||!1,botUsername:s.data.bot_username,ownerUsernames:s.data.owner_usernames||[],guestUsernames:s.data.guest_usernames||[],allowGroupChat:s.data.allow_group_chat||!1,routeToDM:s.data.route_to_dm||!1}}catch{return{connected:!1}}}async updateTelegram(e){try{let t=await this.getAuthHeaders(),s={device_id:await this.getDeviceId()};return e.ownerUsernames&&(s.owner_usernames=e.ownerUsernames.join(",")),e.guestUsernames!==void 0&&(s.guest_usernames=e.guestUsernames.join(",")),e.allowGroupChat!==void 0&&(s.allow_group_chat=e.allowGroupChat),e.routeToDM!==void 0&&(s.route_to_dm=e.routeToDM),await gn.patch(`${this.baseURL}/integrations/telegram`,s,{headers:t}),{success:!0}}catch(t){return{success:!1,error:t.response?.data?.error||t.message}}}async disconnectTelegram(){try{let e=await this.getAuthHeaders(),t=await this.getDeviceId(),n=this.authService.getUserId();return await gn.delete(`${this.baseURL}/integrations/telegram`,{headers:e,data:{device_id:t,user_id:n}}),!0}catch{return!1}}};Te();j();import{EventEmitter as xv}from"events";import Cv from"axios";var Ev="https://snowx.ai/api-beta/api/users/me/quota",Zd=50,Iv=300*1e3,cc=class i extends xv{static instance;authService;cachedQuota=null;lastFetchTime=0;pollTimer=null;constructor(){super(),this.authService=X.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async fetchQuotaStatus(e=!1){let t=Date.now();if(!e&&this.cachedQuota&&t-this.lastFetchTime<6e4)return this.cachedQuota;try{let n=this.authService.getAccessToken();if(n||(n=await this.authService.getAccessTokenFromStorage()),!n)return u.debug("[QuotaService] No auth token available"),null;let s=await Cv.get(Ev,{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},timeout:1e4});return s.data.success&&s.data.data?(this.cachedQuota=s.data.data,this.lastFetchTime=t,this.emit("quotaUpdated",this.cachedQuota),this.cachedQuota):(s.data.error&&u.debug("[QuotaService] API error:",s.data.error),null)}catch(n){return u.debug("[QuotaService] Fetch error:",n),null}}async getUsageDisplayData(){let e=await this.fetchQuotaStatus();if(!e?.token)return null;let{weekly:t,hourly:n}=e.token;return t?.percentUsed>=Zd?{percent:Math.round(t.percentUsed),type:"weekly",resetsAt:t.resetsAt,resetsInSeconds:t.resetsInSeconds}:n?.percentUsed>=Zd?{percent:Math.round(n.percentUsed),type:"hourly",resetsAt:n.resetsAt,resetsInSeconds:n.resetsInSeconds}:null}getCachedQuota(){return this.cachedQuota}startPolling(){this.pollTimer||(this.fetchQuotaStatus(),this.pollTimer=setInterval(()=>{this.fetchQuotaStatus(!0)},Iv))}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}clearCache(){this.cachedQuota=null,this.lastFetchTime=0}},ur=cc.getInstance();function eg(i){return i>=95?"critical":i>=90?"high":i>=70?"warning":i>=50?"notice":"normal"}function dr(i,e){if(!i&&(!e||e<=0))return"";let t=i?new Date(i):new Date(Date.now()+e*1e3),n=Date.now(),s=t.getTime()-n,r=Math.floor(s/(1e3*60*60)),o=Math.floor(s%(1e3*60*60)/(1e3*60));return s<0?"now":r<24?r>0?`${r}h ${o}m`:`${o}m`:t.toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}import Pv from"os";import ng from"path";function Yo(){let{exit:i}=kv(),e=Nn(),t=Ct(),n=za(),s=Wt(),r=$n(),o=tg(c=>c.startsWith("/"),[]);return{handleCommand:tg(async c=>{if(!c.startsWith("/"))return{handled:!1};let l=c.toLowerCase().trim();if(l==="/help"||l==="/?")return s.showCommandMenu(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/model")return s.showModelMenu(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/clear"||l==="/new")return t.clearChat(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/vision")return s.toggleVision(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/exit"||l==="/quit")return i(),{handled:!0};if(l==="/stop")return t.stopStreaming(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/img"||l==="/image"||l==="/paste"){if(r.clearInput(),!Vo())return t.addSystemMessage("[!] No image found in clipboard"),{handled:!0,clearInput:!0};try{let d=await Xo();d.data?(r.addClipboardImage(d.data,d.size),t.addSystemMessage("[OK] Image added from clipboard")):t.addSystemMessage(`[!] Failed to read clipboard image: ${d.error||"Unknown error"}`)}catch(d){t.addSystemMessage(`[!] Error reading clipboard: ${d.message}`)}return{handled:!0,clearInput:!0}}if(l==="/signout"){t.addSystemMessage("[...] Signing out..."),r.clearInput();try{await n.authService.signOut()&&(t.addSystemMessage("[OK] Successfully signed out. Goodbye!"),setTimeout(()=>i(),1e3))}catch(d){t.addSystemMessage(`[ERROR] ${d.message}`)}return{handled:!0,clearInput:!0}}if(l.startsWith("/export")){r.clearInput();let g=l.split(/\s+/)[1]?.toLowerCase()||"markdown";if(!["markdown","md","json","text","txt"].includes(g))return t.addSystemMessage(`[!] Invalid format: ${g}
2549
+ `;Gt.writeFileSync(t,n);let s;try{s=Qd(`osascript "${t}"`,{encoding:"utf8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim()}finally{try{Gt.unlinkSync(t)}catch{}}if(s.startsWith("error:"))return{data:null,size:0,error:s.replace("error:","")};if(!Gt.existsSync(e))return{data:null,size:0,error:"Failed to save clipboard image"};let r=Gt.readFileSync(e),o=r.length,c=`data:image/png;base64,${r.toString("base64")}`;try{Gt.unlinkSync(e)}catch{}return{data:c,size:o}}catch(n){try{Gt.existsSync(e)&&Gt.unlinkSync(e),Gt.existsSync(t)&&Gt.unlinkSync(t)}catch{}return{data:null,size:0,error:n.message||"Failed to read clipboard image"}}}xe();At();import pn from"axios";var jt=class i{static instance;authService;deviceRegistration;baseURL="https://snowx.ai/api-beta/api";constructor(){this.authService=X.getInstance(),this.deviceRegistration=Ae.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async getAuthHeaders(){let e=await this.authService.getAccessToken();if(!e)throw new Error('Not authenticated. Run "orion auth login" first.');return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}async getDeviceId(){if(!this.authService.getUserId())throw new Error('Not authenticated. Run "orion auth login" first.');let t=this.deviceRegistration.getCurrentDeviceId();if(!t)throw new Error("Device not registered. Please wait a moment and try again.");return t}generateDiscordInviteUrl(e){return`https://discord.com/api/oauth2/authorize?client_id=${e}&permissions=274877975552&scope=bot%20applications.commands`}validateDiscordToken(e){return/^[A-Za-z0-9_-]{24,}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27,}$/.test(e.trim())}async connectDiscord(e){try{let t=await this.getAuthHeaders(),n=await this.getDeviceId(),s=await pn.post(`${this.baseURL}/integrations/discord`,{bot_token:e.botToken,device_id:n,owner_user_ids:e.ownerUserIds.join(","),guest_user_ids:e.guestUserIds?.join(",")||"",allow_guild_chat:e.allowGuildChat||!1},{headers:t});return{success:!0,botUsername:s.data.botUsername,botId:s.data.botId,webhookUrl:s.data.webhookUrl}}catch(t){return{success:!1,error:t.response?.data?.error||t.message}}}async getDiscordStatus(){try{let e=await this.getAuthHeaders(),t=await this.getDeviceId(),n=this.authService.getUserId(),s=await pn.get(`${this.baseURL}/integrations/discord/status`,{headers:e,params:{device_id:t,user_id:n}});return{connected:s.data.connected||!1,botUsername:s.data.bot_username,botId:s.data.bot_id,ownerUserIds:s.data.owner_user_ids||[],guestUserIds:s.data.guest_user_ids||[],allowGuildChat:s.data.allow_guild_chat||!1,webhookUrl:s.data.webhook_url,botTokenHash:s.data.bot_token_hash}}catch{return{connected:!1}}}async updateDiscord(e){try{let t=await this.getAuthHeaders(),s={device_id:await this.getDeviceId()};return e.ownerUserIds&&(s.owner_user_ids=e.ownerUserIds.join(",")),e.guestUserIds!==void 0&&(s.guest_user_ids=e.guestUserIds.join(",")),e.allowGuildChat!==void 0&&(s.allow_guild_chat=e.allowGuildChat),await pn.patch(`${this.baseURL}/integrations/discord`,s,{headers:t}),{success:!0}}catch(t){return{success:!1,error:t.response?.data?.error||t.message}}}async disconnectDiscord(){try{let e=await this.getAuthHeaders(),t=await this.getDeviceId(),n=this.authService.getUserId();return await pn.delete(`${this.baseURL}/integrations/discord`,{headers:e,data:{device_id:t,user_id:n}}),!0}catch{return!1}}validateTelegramToken(e){return/^\d{6,15}:[A-Za-z0-9_-]{35,50}$/.test(e.trim())}getTelegramChatUrl(e){return`https://t.me/${e.replace(/^@/,"")}`}async connectTelegram(e){try{let t=await this.getAuthHeaders(),n=await this.getDeviceId();return{success:!0,botUsername:(await pn.post(`${this.baseURL}/integrations/telegram`,{bot_token:e.botToken,device_id:n,owner_usernames:e.ownerUsernames.join(","),guest_usernames:e.guestUsernames?.join(",")||"",allow_group_chat:e.allowGroupChat||!1,route_to_dm:e.routeToDM||!1},{headers:t})).data.botUsername}}catch(t){return{success:!1,error:t.response?.data?.error||t.message}}}async getTelegramStatus(){try{let e=await this.getAuthHeaders(),t=await this.getDeviceId(),n=this.authService.getUserId(),s=await pn.get(`${this.baseURL}/integrations/telegram/status`,{headers:e,params:{device_id:t,user_id:n}});return{connected:s.data.connected||!1,botUsername:s.data.bot_username,ownerUsernames:s.data.owner_usernames||[],guestUsernames:s.data.guest_usernames||[],allowGroupChat:s.data.allow_group_chat||!1,routeToDM:s.data.route_to_dm||!1}}catch{return{connected:!1}}}async updateTelegram(e){try{let t=await this.getAuthHeaders(),s={device_id:await this.getDeviceId()};return e.ownerUsernames&&(s.owner_usernames=e.ownerUsernames.join(",")),e.guestUsernames!==void 0&&(s.guest_usernames=e.guestUsernames.join(",")),e.allowGroupChat!==void 0&&(s.allow_group_chat=e.allowGroupChat),e.routeToDM!==void 0&&(s.route_to_dm=e.routeToDM),await pn.patch(`${this.baseURL}/integrations/telegram`,s,{headers:t}),{success:!0}}catch(t){return{success:!1,error:t.response?.data?.error||t.message}}}async disconnectTelegram(){try{let e=await this.getAuthHeaders(),t=await this.getDeviceId(),n=this.authService.getUserId();return await pn.delete(`${this.baseURL}/integrations/telegram`,{headers:e,data:{device_id:t,user_id:n}}),!0}catch{return!1}}};xe();z();import{EventEmitter as xv}from"events";import Cv from"axios";var Ev="https://snowx.ai/api-beta/api/users/me/quota",Zd=50,Iv=300*1e3,cc=class i extends xv{static instance;authService;cachedQuota=null;lastFetchTime=0;pollTimer=null;constructor(){super(),this.authService=X.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async fetchQuotaStatus(e=!1){let t=Date.now();if(!e&&this.cachedQuota&&t-this.lastFetchTime<6e4)return this.cachedQuota;try{let n=this.authService.getAccessToken();if(n||(n=await this.authService.getAccessTokenFromStorage()),!n)return u.debug("[QuotaService] No auth token available"),null;let s=await Cv.get(Ev,{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},timeout:1e4});return s.data.success&&s.data.data?(this.cachedQuota=s.data.data,this.lastFetchTime=t,this.emit("quotaUpdated",this.cachedQuota),this.cachedQuota):(s.data.error&&u.debug("[QuotaService] API error:",s.data.error),null)}catch(n){return u.debug("[QuotaService] Fetch error:",n),null}}async getUsageDisplayData(){let e=await this.fetchQuotaStatus();if(!e?.token)return null;let{weekly:t,hourly:n}=e.token;return t?.percentUsed>=Zd?{percent:Math.round(t.percentUsed),type:"weekly",resetsAt:t.resetsAt,resetsInSeconds:t.resetsInSeconds}:n?.percentUsed>=Zd?{percent:Math.round(n.percentUsed),type:"hourly",resetsAt:n.resetsAt,resetsInSeconds:n.resetsInSeconds}:null}getCachedQuota(){return this.cachedQuota}startPolling(){this.pollTimer||(this.fetchQuotaStatus(),this.pollTimer=setInterval(()=>{this.fetchQuotaStatus(!0)},Iv))}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}clearCache(){this.cachedQuota=null,this.lastFetchTime=0}},dr=cc.getInstance();function eg(i){return i>=95?"critical":i>=90?"high":i>=70?"warning":i>=50?"notice":"normal"}function gr(i,e){if(!i&&(!e||e<=0))return"";let t=i?new Date(i):new Date(Date.now()+e*1e3),n=Date.now(),s=t.getTime()-n,r=Math.floor(s/(1e3*60*60)),o=Math.floor(s%(1e3*60*60)/(1e3*60));return s<0?"now":r<24?r>0?`${r}h ${o}m`:`${o}m`:t.toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}import Pv from"os";import ng from"path";function Yo(){let{exit:i}=kv(),e=$n(),t=Ct(),n=za(),s=Ht(),r=Ln(),o=tg(c=>c.startsWith("/"),[]);return{handleCommand:tg(async c=>{if(!c.startsWith("/"))return{handled:!1};let l=c.toLowerCase().trim();if(l==="/help"||l==="/?")return s.showCommandMenu(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/model")return s.showModelMenu(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/clear"||l==="/new")return t.clearChat(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/vision")return s.toggleVision(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/exit"||l==="/quit")return i(),{handled:!0};if(l==="/stop")return t.stopStreaming(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/img"||l==="/image"||l==="/paste"){if(r.clearInput(),!Vo())return t.addSystemMessage("[!] No image found in clipboard"),{handled:!0,clearInput:!0};try{let d=await Xo();d.data?(r.addClipboardImage(d.data,d.size),t.addSystemMessage("[OK] Image added from clipboard")):t.addSystemMessage(`[!] Failed to read clipboard image: ${d.error||"Unknown error"}`)}catch(d){t.addSystemMessage(`[!] Error reading clipboard: ${d.message}`)}return{handled:!0,clearInput:!0}}if(l==="/signout"){t.addSystemMessage("[...] Signing out..."),r.clearInput();try{await n.authService.signOut()&&(t.addSystemMessage("[OK] Successfully signed out. Goodbye!"),setTimeout(()=>i(),1e3))}catch(d){t.addSystemMessage(`[ERROR] ${d.message}`)}return{handled:!0,clearInput:!0}}if(l.startsWith("/export")){r.clearInput();let g=l.split(/\s+/)[1]?.toLowerCase()||"markdown";if(!["markdown","md","json","text","txt"].includes(g))return t.addSystemMessage(`[!] Invalid format: ${g}
2550
2550
 
2551
2551
  Usage: /export [markdown|json|text]
2552
2552
  - markdown (default): Export as .md file
2553
2553
  - json: Export as .json file
2554
- - text: Export as .txt file`),{handled:!0,clearInput:!0};let p=g==="md"?"markdown":g==="txt"?"text":g,h=p==="markdown"?"md":p==="json"?"json":"txt",f=e.conversationId;if(!f)return t.addSystemMessage("[!] No active conversation to export"),{handled:!0,clearInput:!0};let T=`orion-chat-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}.${h}`,x=ng.join(Pv.homedir(),"Downloads"),w=ng.join(x,T),C=Je.saveExportToFile(f,p,w);return C.success?t.addSystemMessage(`[OK] Conversation exported to:
2555
- ${w}`):t.addSystemMessage(`[!] Export failed: ${C.error}`),{handled:!0,clearInput:!0}}if(l==="/discord"||l==="/discord reconnect"||l==="/discord setup"){r.clearInput();let d=l.includes("reconnect")||l.includes("setup");try{let g=Gt.getInstance(),m=await g.getDiscordStatus();if(m.connected&&!d){let p=m.botId?g.generateDiscordInviteUrl(m.botId):"";t.addSystemMessage(`Discord: Connected
2554
+ - text: Export as .txt file`),{handled:!0,clearInput:!0};let p=g==="md"?"markdown":g==="txt"?"text":g,h=p==="markdown"?"md":p==="json"?"json":"txt",f=e.conversationId;if(!f)return t.addSystemMessage("[!] No active conversation to export"),{handled:!0,clearInput:!0};let T=`orion-chat-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}.${h}`,C=ng.join(Pv.homedir(),"Downloads"),w=ng.join(C,T),E=Ze.saveExportToFile(f,p,w);return E.success?t.addSystemMessage(`[OK] Conversation exported to:
2555
+ ${w}`):t.addSystemMessage(`[!] Export failed: ${E.error}`),{handled:!0,clearInput:!0}}if(l==="/discord"||l==="/discord reconnect"||l==="/discord setup"){r.clearInput();let d=l.includes("reconnect")||l.includes("setup");try{let g=jt.getInstance(),m=await g.getDiscordStatus();if(m.connected&&!d){let p=m.botId?g.generateDiscordInviteUrl(m.botId):"";t.addSystemMessage(`Discord: Connected
2556
2556
  Bot: ${m.botUsername}
2557
2557
  Owners: ${m.ownerUserIds?.join(", ")||"None"}
2558
2558
  Server chat: ${m.allowGuildChat?"Enabled":"Disabled"}
2559
2559
  `+(p?`Invite: ${p}
2560
2560
  `:"")+`
2561
- Reconfigure: /discord reconnect`)}else s.showDiscordWizard()}catch{s.showDiscordWizard()}return{handled:!0,clearInput:!0}}if(l==="/telegram"||l==="/telegram reconnect"||l==="/telegram setup"){r.clearInput();let d=l.includes("reconnect")||l.includes("setup");try{let g=Gt.getInstance(),m=await g.getTelegramStatus();if(m.connected&&!d){let p=g.getTelegramChatUrl(m.botUsername||"");t.addSystemMessage(`Telegram: Connected
2561
+ Reconfigure: /discord reconnect`)}else s.showDiscordWizard()}catch{s.showDiscordWizard()}return{handled:!0,clearInput:!0}}if(l==="/telegram"||l==="/telegram reconnect"||l==="/telegram setup"){r.clearInput();let d=l.includes("reconnect")||l.includes("setup");try{let g=jt.getInstance(),m=await g.getTelegramStatus();if(m.connected&&!d){let p=g.getTelegramChatUrl(m.botUsername||"");t.addSystemMessage(`Telegram: Connected
2562
2562
  Bot: @${m.botUsername}
2563
2563
  Chat: ${p}
2564
2564
  Owners: ${m.ownerUsernames?.map(h=>`@${h}`).join(", ")||"None"}
2565
2565
  Group chat: ${m.allowGroupChat?"Enabled":"Disabled"}
2566
2566
 
2567
- Reconfigure: /telegram reconnect`)}else s.showTelegramWizard()}catch{s.showTelegramWizard()}return{handled:!0,clearInput:!0}}if(l==="/usage"||l==="/quota"){r.clearInput(),t.addSystemMessage("[...] Fetching usage data...");try{let d=await ur.fetchQuotaStatus(!0);if(!d)return t.addSystemMessage("[!] Unable to fetch usage data. Please try again."),{handled:!0,clearInput:!0};let{token:g,tierName:m}=d,{hourly:p,weekly:h}=g,f=w=>{let C=Math.round(w/5),v=20-C;return`${w>=90?"🔴":w>=70?"🟡":"🟢"} [${"█".repeat(C)}${"░".repeat(v)}]`},y=`
2567
+ Reconfigure: /telegram reconnect`)}else s.showTelegramWizard()}catch{s.showTelegramWizard()}return{handled:!0,clearInput:!0}}if(l==="/usage"||l==="/quota"){r.clearInput(),t.addSystemMessage("[...] Fetching usage data...");try{let d=await dr.fetchQuotaStatus(!0);if(!d)return t.addSystemMessage("[!] Unable to fetch usage data. Please try again."),{handled:!0,clearInput:!0};let{token:g,tierName:m}=d,{hourly:p,weekly:h}=g,f=w=>{let E=Math.round(w/5),v=20-E;return`${w>=90?"🔴":w>=70?"🟡":"🟢"} [${"█".repeat(E)}${"░".repeat(v)}]`},y=`
2568
2568
  📊 Usage Status (${m})
2569
2569
  ${"─".repeat(30)}
2570
2570
 
2571
2571
  `,T=Math.round(p.percentUsed);y+=`5-Hour: ${f(T)} ${T}%`,T>=50&&p.resetsInSeconds&&(y+=`
2572
- Resets in ${dr(p.resetsAt,p.resetsInSeconds)}`),y+=`
2572
+ Resets in ${gr(p.resetsAt,p.resetsInSeconds)}`),y+=`
2573
2573
 
2574
- `;let x=Math.round(h.percentUsed);y+=`Weekly: ${f(x)} ${x}%`,x>=50&&h.resetsInSeconds&&(y+=`
2575
- Resets in ${dr(h.resetsAt,h.resetsInSeconds)}`),y+=`
2574
+ `;let C=Math.round(h.percentUsed);y+=`Weekly: ${f(C)} ${C}%`,C>=50&&h.resetsInSeconds&&(y+=`
2575
+ Resets in ${gr(h.resetsAt,h.resetsInSeconds)}`),y+=`
2576
2576
  `,t.addSystemMessage(y)}catch(d){t.addSystemMessage(`[!] Error fetching usage: ${d.message}`)}return{handled:!0,clearInput:!0}}return t.addSystemMessage(`Unknown command: ${c}
2577
2577
 
2578
- Type /help to see available commands.`),r.clearInput(),{handled:!0,clearInput:!0}},[i,e,t,n.authService,s,r]),isCommand:o}}import{useRef as mn,useCallback as jt,useEffect as Av}from"react";var lc=typeof requestAnimationFrame<"u"?requestAnimationFrame:i=>setImmediate(i),hs=typeof cancelAnimationFrame<"u"?cancelAnimationFrame:i=>clearImmediate(i);var Dv={flushInterval:16,maxBufferSize:32,detectPaste:!0,pasteThreshold:50,immediateFlushChars:[`
2579
- `,"\r"," "]};function sg(i,e){let t={...Dv,...e},n=mn(""),s=mn(0),r=mn(0),o=mn(0),a=mn(0),c=mn(null),l=mn(null),d=mn(i);d.current=i;let g=jt(()=>{if(n.current===""&&s.current===0)return null;let v=Date.now()-r.current,E=t.detectPaste&&a.current>3&&v<t.pasteThreshold*a.current;return{chars:n.current,backspaces:s.current,isPaste:E,startTime:r.current}},[t.detectPaste,t.pasteThreshold]),m=jt(()=>{let C=g();C&&(n.current="",s.current=0,a.current=0,r.current=0,d.current(C)),c.current!==null&&(hs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null)},[g]),p=jt(()=>{c.current===null&&(c.current=lc(()=>{c.current=null,l.current&&clearTimeout(l.current),l.current=setTimeout(m,t.flushInterval)}))},[m,t.flushInterval]),h=jt(C=>{let v=Date.now();r.current===0&&(r.current=v),o.current=v,a.current++,n.current+=C,t.immediateFlushChars.includes(C)||n.current.length>=t.maxBufferSize?m():p()},[m,p,t.immediateFlushChars,t.maxBufferSize]),f=jt(()=>{let C=Date.now();r.current===0&&(r.current=C),a.current++,n.current.length>0?n.current=n.current.slice(0,-1):s.current++,p()},[p]),y=jt(()=>{let C=g();return C&&(n.current="",s.current=0,a.current=0,r.current=0),c.current!==null&&(hs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),C},[g]),T=jt(()=>g(),[g]),x=jt(()=>{n.current="",s.current=0,a.current=0,r.current=0,c.current!==null&&(hs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null)},[]),w=jt(()=>n.current===""&&s.current===0,[]);return Av(()=>()=>{c.current!==null&&hs(c.current),l.current&&clearTimeout(l.current)},[]),{pushChar:h,pushBackspace:f,flush:y,peek:T,clear:x,isEmpty:w}}import{useRef as pn,useEffect as uc,useCallback as fs,useState as Mv,useMemo as rg}from"react";function og(i){let e=pn(0),t=pn([]),n=pn(0),s=pn(0),r=pn([]);return uc(()=>{let a=performance.now();return()=>{let l=performance.now()-a;e.current++,n.current=l,s.current=Math.max(s.current,l),t.current.push(l),t.current.length>100&&t.current.shift(),r.current.push(Date.now());let d=Date.now()-1e3;r.current=r.current.filter(g=>g>d)}}),rg(()=>{let a=t.current,c=a.length>0?a.reduce((g,m)=>g+m,0)/a.length:0,l=r.current.length,d=c>16||l>60;return{renderCount:e.current,avgRenderTime:c,lastRenderTime:n.current,peakRenderTime:s.current,rendersPerSecond:l,isPerformanceDegraded:d}},[])}function ig(i){let{targetFrameTime:e=16.67,warningThreshold:t=.8,criticalThreshold:n=1}=i||{},s=pn(0),r=pn(0),o=fs(()=>{s.current=performance.now(),r.current=0},[]),a=fs(()=>performance.now()-s.current+r.current<e*n,[e,n]),c=fs(d=>{r.current+=d;let g=e-r.current;return Math.max(0,g)},[e]),l=fs(()=>{let g=(performance.now()-s.current+r.current)/e;return g>=n?"critical":g>=t?"warning":"ok"},[e,t,n]);return uc(()=>{o()}),{hasBudget:a,useBudget:c,resetBudget:o,getBudgetStatus:l}}function ag(i){let{warningThresholdMB:e=100,criticalThresholdMB:t=200,checkInterval:n=5e3}=i||{},[s,r]=Mv(0);uc(()=>{let c=()=>{if(typeof process<"u"&&process.memoryUsage){let d=process.memoryUsage();r(d.heapUsed/1024/1024)}};c();let l=setInterval(c,n);return()=>clearInterval(l)},[n]);let o=rg(()=>s>=t?"critical":s>=e?"warning":"normal",[s,e,t]),a=fs(()=>{typeof global<"u"&&global.gc&&global.gc()},[]);return{heapUsedMB:s,pressure:o,requestGC:a}}function cg(i){let e=pn(i);return e.current=i,fs(((...t)=>e.current(...t)),[])}function lg({onSubmit:i,enableProfiling:e=!1,bufferFlushInterval:t=16}){let{exit:n}=_v(),s=Nn(),r=Ct(),o=ms(),a=Wt(),c=ar(),l=$n(),{handleCommand:d,isCommand:g}=Yo(),m=ig({targetFrameTime:16.67}),{pressure:p}=ag({warningThresholdMB:150,criticalThresholdMB:250}),h=e?og("OptimizedKeyboardInput"):void 0,f=dc(!1),y=dc(0),T=dc(0),x=500,w=cg(i),C=Ov(E=>{if(E.isPaste)l.addPastedContent(E.chars);else{for(let S=0;S<E.backspaces;S++)l.deleteAtCursor();E.chars&&(l.insertAtCursor(E.chars),c.input.slice(0,c.cursorPosition)+E.chars+c.input.slice(c.cursorPosition)==="/"&&!o.showCommandMenu&&a.showCommandMenu())}},[l,c.input,c.cursorPosition,o.showCommandMenu,a]),v=sg(C,{flushInterval:t,maxBufferSize:64,detectPaste:!0,pasteThreshold:50});return Nv((E,S)=>{let I=Date.now(),P=I-y.current;if(y.current=I,!(E.startsWith("[<")||E.startsWith("[M")||/^\[<?\d+;\d+;\d+[mM]?/.test(E)||/^\d+[mM]/.test(E)||/^;\d+;\d+[mM]/.test(E)||/^\d+;\d+[mM]/.test(E))){if(S.escape){v.flush();let R=Date.now(),$=R-T.current;if(T.current=R,$<x){s.isLoading&&r.stopStreaming(),a.closeAllModals(),a.stopReverseSearch(),l.clearInput(),l.clearPastedTexts();return}if(s.isLoading){r.stopStreaming();return}if(o.isReverseSearchActive){a.stopReverseSearch();return}if(o.showWizard)return;if(o.showModelMenu||o.showCommandMenu){a.closeAllModals(),o.showCommandMenu&&c.input==="/"&&l.clearInput();return}if(o.showHelp){a.hideHelp();return}if(c.pastedTexts.length>0){l.clearPastedTexts();return}return}if(!o.showModelMenu&&!o.showWizard&&!(o.showCommandMenu&&(S.upArrow||S.downArrow||S.return))){if(S.ctrl&&E==="l"){v.flush(),process.stdout.write("\x1B[2J\x1B[H");return}if(S.ctrl&&E==="c"){v.flush(),s.isLoading?r.stopStreaming():n();return}if(S.ctrl&&E==="r"){v.flush(),o.isReverseSearchActive||a.startReverseSearch();return}if(S.ctrl&&E==="z"){v.flush(),l.undo();return}if(S.ctrl&&(E==="y"||E==="Z")){v.flush(),l.redo();return}if(E===""||S.ctrl&&E==="v"){if(f.current)return;if(Vo()){f.current=!0,Xo().then(R=>{f.current=!1,R.data&&(v.flush(),l.addClipboardImage(R.data,R.size))}).catch(()=>{f.current=!1});return}return}if(S.tab){v.flush(),c.suggestion&&l.acceptSuggestion();return}if(E==="?"&&c.input===""&&!o.showCommandMenu){v.flush(),a.toggleHelp();return}if(S.return&&!o.isReverseSearchActive){v.flush();let R=c.pastedTexts.filter(D=>!D.error||D.type==="text");(c.input.trim()||R.length>0)&&w();return}if(S.upArrow&&!o.showCommandMenu&&!o.isReverseSearchActive){v.flush(),l.navigateHistoryUp();return}if(S.downArrow&&!o.showCommandMenu&&!o.isReverseSearchActive){v.flush(),l.navigateHistoryDown();return}if(S.leftArrow){v.flush(),l.moveCursorLeft();return}if(S.rightArrow){v.flush(),l.moveCursorRight();return}if(S.ctrl&&E==="a"){v.flush(),l.moveCursorToStart();return}if(S.ctrl&&E==="e"){v.flush(),l.moveCursorToEnd();return}if(S.delete||S.backspace){v.flush(),l.deleteAtCursor(),o.showCommandMenu&&((c.input.slice(0,c.cursorPosition-1)+c.input.slice(c.cursorPosition)).startsWith("/")||a.hideCommandMenu());return}if(!S.ctrl&&!S.meta&&E){let R=E.includes(`
2580
- `),$=E.length>50;if(R||$){v.flush(),l.addPastedContent(E);return}v.pushChar(E)}}}}),Rv(()=>()=>{v.clear()},[v]),{handleCommand:d,isCommand:g,renderProfile:h,memoryPressure:p,frameBudgetStatus:m.getBudgetStatus()}}import{useState as gr,useCallback as Et,useMemo as Wv,useRef as dg,useEffect as gg}from"react";import{useEffect as $v,useRef as gc}from"react";import{useInput as jF}from"@jrichman/ink";var Fv=0,Qo=[];function Lv(){return`keypress-${++Fv}`}function Uv(i,e,t){let n=Lv();return Qo.push({id:n,handler:i,priority:e,isActive:t}),Qo.sort((s,r)=>r.priority-s.priority),n}function Bv(i){let e=Qo.findIndex(t=>t.id===i);e!==-1&&Qo.splice(e,1)}function ug(i,e={}){let{priority:t=0,isActive:n=!0}=e,s=gc(i),r=gc(n),o=gc(null);s.current=i,r.current=n,$v(()=>(o.current=Uv((a,c)=>s.current(a,c),t,()=>r.current),()=>{o.current&&(Bv(o.current),o.current=null)}),[t])}function mg(i){let{items:e,getSearchText:t,direction:n="forward",caseSensitive:s=!1,useRegex:r=!1,initialQuery:o="",onSearchChange:a,onMatchSelect:c,isActive:l=!0,maxHistory:d=50}=i,[g,m]=gr(o),[p,h]=gr(!1),[f,y]=gr(0),[T,x]=gr([]),[w,C]=gr(-1),v=dg(a),E=dg(c);v.current=a,E.current=c;let S=Wv(()=>{if(!g)return[];let W=[],G;try{if(r)G=new RegExp(g,s?"g":"gi");else{let tt=g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");G=new RegExp(tt,s?"g":"gi")}}catch{return[]}return e.forEach((tt,Es)=>{let vt=t(tt),Sn=G.exec(vt);Sn&&W.push({item:tt,index:Es,matchStart:Sn.index,matchEnd:Sn.index+Sn[0].length}),G.lastIndex=0}),n==="backward"&&W.reverse(),W},[e,g,t,n,s,r]),I=S.length>0&&S[f]||null,P=S.length,R=P>0,$=Et(W=>{m(W),y(0),C(-1)},[]);gg(()=>{v.current?.(g,S)},[g,S]),gg(()=>{I&&E.current?.(I)},[I]);let D=Et(()=>{P!==0&&y(W=>(W+1)%P)},[P]),_=Et(()=>{P!==0&&y(W=>(W-1+P)%P)},[P]),N=Et(W=>{W>=0&&W<P&&y(W)},[P]),k=Et(()=>{g&&x(W=>{let G=W.filter(tt=>tt!==g);return[g,...G].slice(0,d)}),m(""),y(0),C(-1)},[g,d]),M=Et(()=>{h(!0),$("")},[$]),L=Et(()=>{k(),h(!1)},[k]),B=Et(()=>{T.length!==0&&C(W=>{let G=Math.min(W+1,T.length-1);return m(T[G]||""),G})},[T]),H=Et(()=>{w<0||C(W=>{let G=W-1;return G<0?m(""):m(T[G]||""),G})},[T,w]),V=Et(W=>{m(G=>G+W),y(0),C(-1)},[]),le=Et(()=>{m(W=>W.slice(0,-1)),y(0),C(-1)},[]);return ug((W,G)=>{if(p){if(G.downArrow||G.ctrl&&W==="n")return D(),!0;if(G.upArrow||G.ctrl&&W==="p")return _(),!0;if(G.ctrl&&G.upArrow)return B(),!0;if(G.ctrl&&G.downArrow)return H(),!0;if(G.escape)return L(),!0;if(G.return)return k(),h(!1),!0;if(G.backspace||G.delete)return le(),!0;if(W&&W.length===1&&!G.ctrl&&!G.meta)return V(W),!0}},{isActive:l&&p,priority:100}),{query:g,setQuery:$,matches:S,currentMatchIndex:f,currentMatch:I,nextMatch:D,prevMatch:_,goToMatch:N,clear:k,isSearching:p,startSearch:M,stopSearch:L,history:T,historyUp:B,historyDown:H,append:V,backspace:le,matchCount:P,hasMatches:R}}function pg(i,e,t=!1){if(!e)return[{text:i,isMatch:!1}];let n=[],s=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t?"g":"gi"),r=0,o;for(;(o=s.exec(i))!==null;)o.index>r&&n.push({text:i.slice(r,o.index),isMatch:!1}),n.push({text:o[0],isMatch:!0}),r=o.index+o[0].length;return r<i.length&&n.push({text:i.slice(r),isMatch:!1}),n.length>0?n:[{text:i,isMatch:!1}]}import fe,{memo as hg,useMemo as jv}from"react";import{Box as mr,Text as ht}from"@jrichman/ink";import zv from"ink-spinner";var ze={Foreground:"#D4D4D4",Background:"#1E1E1E",AccentBlue:"#6B9FD4",AccentPurple:"#B48EAD",AccentCyan:"#88C0D0",AccentGreen:"#A3BE8C",AccentYellow:"#EBCB8B",AccentRed:"#BF616A",Gray:"#808080",DarkGray:"#5C5C5C",LightGray:"#A0A0A0",Comment:"#6A737D"},Hv={text:{primary:ze.Foreground,secondary:ze.LightGray,accent:ze.Foreground,link:ze.AccentBlue,response:ze.Foreground},background:{primary:ze.Background,secondary:"#252526"},border:{default:"#3C3C3C",focused:ze.AccentBlue},ui:{comment:ze.Comment,symbol:ze.Gray,muted:ze.DarkGray},status:{success:ze.AccentGreen,warning:ze.AccentYellow,error:ze.AccentRed,info:ze.Gray}},mc={name:"Default Dark",type:"dark",colors:ze,semantic:Hv};var Gv=mc;function bs(){return Gv}var A={get text(){return bs().semantic.text},get background(){return bs().semantic.background},get border(){return bs().semantic.border},get ui(){return bs().semantic.ui},get status(){return bs().semantic.status},get colors(){return bs().colors}};function qv(i,e){let t=i.toLowerCase();if(t==="read"||t==="readfile")return{displayName:"Read",mainArg:e?.file_path};if(t==="write"||t==="writefile")return{displayName:"Write",mainArg:e?.file_path};if(t==="edit"||t==="editfile")return{displayName:"Edit",mainArg:e?.file_path};if(t==="grep")return{displayName:"Grep",mainArg:e?.pattern};if(t==="glob")return{displayName:"Glob",mainArg:e?.pattern};if(t==="bash"||t==="command"||t==="run_command"){let r=e?.command;return{displayName:"Bash",mainArg:r?r.length>40?r.substring(0,37)+"...":r:void 0}}if(t==="webfetch"||t==="web_fetch")return{displayName:"WebFetch",mainArg:e?.url};if(t==="websearch"||t==="web_search")return{displayName:"WebSearch",mainArg:e?.query};if(t==="task")return{displayName:"Task",mainArg:e?.subagent_type||e?.description};if(t==="todowrite"||t==="todo_write")return{displayName:"",mainArg:void 0};let n=i.charAt(0).toUpperCase()+i.slice(1).replace(/_/g,""),s=e?.description||e?.query||e?.path||e?.url;return{displayName:n,mainArg:s}}function Kv(i){if(!i)return"";let e=i.split("/");return e.length<=2?i:e.slice(-2).join("/")}var pc=hg(function({tool:e}){let{displayName:t,mainArg:n}=qv(e.name,e.arguments);if(!t)return null;let s=e.state==="running",r=e.state==="completed",o=e.state==="failed",a=n?Kv(n):void 0;return fe.createElement(mr,{flexDirection:"column"},fe.createElement(mr,null,s&&fe.createElement(ht,{color:A.status.warning},fe.createElement(zv,{type:"dots"})),r&&fe.createElement(ht,{color:A.status.success},"●"),o&&fe.createElement(ht,{color:A.status.error},"●"),fe.createElement(ht,null," "),fe.createElement(ht,{color:A.text.primary,bold:!0},t),a&&fe.createElement(fe.Fragment,null,fe.createElement(ht,{color:A.ui.muted},"("),fe.createElement(ht,{color:A.text.secondary},a),fe.createElement(ht,{color:A.ui.muted},")"))),r&&e.output&&fe.createElement(mr,{paddingLeft:2},fe.createElement(ht,{color:A.ui.muted},"└ "),fe.createElement(ht,{color:A.ui.muted},Vv(e.output))),o&&e.error&&fe.createElement(mr,{paddingLeft:2},fe.createElement(ht,{color:A.ui.muted},"└ "),fe.createElement(ht,{color:A.status.error},e.error.substring(0,60))))});function Vv(i){if(!i)return"";let e=i.split(`
2581
- `).length;return e>1?`${e} lines`:i.length>50?i.substring(0,47)+"...":i}function Xv({activeTools:i}){let{running:e,completed:t,failed:n}=jv(()=>{if(i.size===0)return{running:[],completed:[],failed:[]};let s=Array.from(i.values()).filter(r=>r.name.toLowerCase().replace(/_/g,"")!=="todowrite");return{running:s.filter(r=>r.state==="running"),completed:s.filter(r=>r.state==="completed").slice(-3),failed:s.filter(r=>r.state==="failed")}},[i]);return e.length===0&&t.length===0&&n.length===0?null:fe.createElement(mr,{flexDirection:"column",paddingX:1,marginY:1},e.map(s=>fe.createElement(pc,{key:s.toolCallId,tool:s})),t.map(s=>fe.createElement(pc,{key:s.toolCallId,tool:s})),n.map(s=>fe.createElement(pc,{key:s.toolCallId,tool:s})))}var fg=hg(Xv);import oe,{memo as hc,useMemo as bg}from"react";import{Box as zt,Text as Oe}from"@jrichman/ink";import yg from"ink-spinner";function Yv(i,e=60){return i?i.length<=e?i:i.substring(0,e-3)+"...":"Processing..."}var Qv=hc(function({agent:e}){let t=Yv(e.task||"Working..."),n=o=>{switch(o){case"running":return"cyan";case"completed":return"#5AD8A6";case"failed":return"#F5716C";case"timeout":return"#FBBF24";default:return"#6B7280"}},s=()=>e.status==="running"?oe.createElement(Oe,{color:"cyan"},oe.createElement(yg,{type:"dots"})):e.status==="completed"?oe.createElement(Oe,{color:"#5AD8A6"},"[done]"):e.status==="failed"?oe.createElement(Oe,{color:"#F5716C"},"[fail]"):e.status==="timeout"?oe.createElement(Oe,{color:"#FBBF24"},"[time]"):oe.createElement(Oe,{color:"#6B7280"},"[ ]"),r=n(e.status);return oe.createElement(zt,{flexDirection:"column",marginLeft:2},oe.createElement(zt,null,s(),oe.createElement(Oe,{color:r,bold:!0}," Agent #",e.agentNumber)),oe.createElement(zt,{marginLeft:2},oe.createElement(Oe,{color:"#9CA3AF"},t)),e.error&&oe.createElement(zt,{marginLeft:2},oe.createElement(Oe,{color:"#F5716C"},"Error: ",e.error.substring(0,60),e.error.length>60?"...":"")),e.streamingContent&&e.status==="running"&&oe.createElement(zt,{marginLeft:2},oe.createElement(Oe,{color:"#6B7280"},e.streamingContent.split(`
2582
- `)[0]?.substring(0,50),"...")))}),Jv=hc(function({operation:e}){let{agents:t,completed:n,failed:s,running:r,total:o}=bg(()=>{let d=Array.from(e.agents.values()).sort((g,m)=>g.agentNumber-m.agentNumber);return{agents:d,completed:d.filter(g=>g.status==="completed").length,failed:d.filter(g=>g.status==="failed").length,running:d.filter(g=>g.status==="running").length,total:e.totalAgents}},[e.agents,e.totalAgents]),a=()=>e.status==="starting"||e.status==="running"?`Spawning ${o} agents`:e.status==="completed"?`${o} agents completed`:"Operation failed",c=()=>e.status==="running"||e.status==="starting"?oe.createElement(Oe,{color:"cyan"},oe.createElement(yg,{type:"dots"})):e.status==="completed"?oe.createElement(Oe,{color:"#5AD8A6"},"[done]"):oe.createElement(Oe,{color:"#F5716C"},"[fail]"),l=e.status==="completed"?"#5AD8A6":e.status==="failed"?"#F5716C":"cyan";return oe.createElement(zt,{flexDirection:"column"},oe.createElement(zt,null,c(),oe.createElement(Oe,{color:l,bold:!0}," ",a()),oe.createElement(Oe,{color:"#6B7280"}," "),oe.createElement(Oe,{backgroundColor:"#3F3F46",color:"whiteBright"}," ",n,"/",o," "),r>0&&oe.createElement(Oe,{color:"cyan"}," (",r," running)"),s>0&&oe.createElement(Oe,{color:"#F5716C"}," [",s," failed]")),oe.createElement(zt,{flexDirection:"column",marginTop:1},t.map(d=>oe.createElement(Qv,{key:d.agentNumber,agent:d}))))});function Zv({operations:i}){let e=bg(()=>i.size===0?[]:Array.from(i.entries()).filter(([t,n])=>n.status==="running"||n.status==="starting"?!0:n.endTime?Date.now()-n.endTime.getTime()<1e4:!0),[i]);return e.length===0?null:oe.createElement(zt,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},e.map(([t,n])=>oe.createElement(Jv,{key:t,operation:n})))}var vg=hc(Zv);import Ln,{memo as eS}from"react";import{Box as tS,Text as pr}from"@jrichman/ink";import nS from"ink-spinner";function sS(i){switch(i.toLowerCase()){case"vapi":return"Phone";case"cron":return"Scheduler";case"telegram":return"Telegram";case"discord":return"Discord";default:return i.charAt(0).toUpperCase()+i.slice(1)}}function rS(i,e=60){return i?i.length<=e?i:i.substring(0,e-3)+"...":"Processing request..."}function oS({session:i}){if(!i)return null;let e=sS(i.source),t=rS(i.message);return Ln.createElement(tS,{flexDirection:"row",paddingX:1,marginY:1,borderStyle:"round",borderColor:A.ui.border},Ln.createElement(pr,{color:A.status.warning},Ln.createElement(nS,{type:"dots"})),Ln.createElement(pr,null," "),Ln.createElement(pr,{color:A.text.primary,bold:!0},e),Ln.createElement(pr,{color:A.ui.muted},": "),Ln.createElement(pr,{color:A.text.secondary},t))}var Sg=eS(oS);import It,{useState as iS,useEffect as aS,useRef as wg,memo as cS,useMemo as lS,useCallback as uS}from"react";import{Box as hr,Text as fr}from"@jrichman/ink";import dS from"ink-select-input";var gS=[{label:"Yes, proceed",value:"confirm"},{label:"No, cancel",value:"decline"}];function mS({request:i,onConfirm:e,onDecline:t,onTimeout:n}){let[s,r]=iS(i.timeout?Math.ceil(i.timeout/1e3):null),o=wg(null),a=wg(0);aS(()=>{if(i.timeout)return a.current=Date.now(),r(Math.ceil(i.timeout/1e3)),o.current=setInterval(()=>{let g=Date.now()-a.current,m=Math.max(0,i.timeout-g),p=Math.ceil(m/1e3);r(p),m<=0&&(o.current&&clearInterval(o.current),n?.())},1e3),()=>{o.current&&clearInterval(o.current)}},[i.timeout,n]);let c=uS(g=>{o.current&&(clearInterval(o.current),o.current=null),g.value==="confirm"?e("y"):t()},[e,t]),{actualTargets:l,displayCommand:d}=lS(()=>{let g=i.targets?.filter(p=>p.startsWith("/")||p.startsWith("./")||p.startsWith("~/")).slice(0,3)||[],m=i.command&&i.command.length>60?i.command.substring(0,57)+"...":i.command;return{actualTargets:g,displayCommand:m}},[i.targets,i.command]);return It.createElement(hr,{flexDirection:"column",borderStyle:"round",borderColor:"#525252",paddingX:2,paddingY:1},It.createElement(fr,{color:"white",bold:!0},i.title),d&&It.createElement(hr,{marginTop:1},It.createElement(fr,{color:"gray"},"$ "),It.createElement(fr,{color:"white"},d)),l.length>0&&It.createElement(hr,{marginTop:1,flexDirection:"column"},l.map((g,m)=>It.createElement(fr,{key:m,color:"gray"}," ",g))),s!==null&&It.createElement(hr,{marginTop:1},It.createElement(fr,{color:"yellow"},"Auto-cancel in ",s,"s")),It.createElement(hr,{marginTop:1},It.createElement(dS,{items:gS,onSelect:c})))}var Tg=cS(mS,(i,e)=>i.request.id===e.request.id&&i.request.timeout===e.request.timeout);import ft,{memo as pS,useMemo as hS}from"react";import{Box as br,Text as Un}from"@jrichman/ink";var fS=8;function bS({todoList:i}){let{incompleteTodos:e,completedTodos:t,allComplete:n,visibleTodos:s,hiddenCount:r}=hS(()=>{if(!i||i.todos.length===0)return{incompleteTodos:[],completedTodos:[],allComplete:!1,visibleTodos:[],hiddenCount:0};let o=i.todos.filter(g=>g.status!=="completed"),a=i.todos.filter(g=>g.status==="completed"),c=o.length===0&&a.length>0,l=[...o,...a.slice(-2)].slice(0,fS),d=i.todos.length-l.length;return{incompleteTodos:o,completedTodos:a,allComplete:c,visibleTodos:l,hiddenCount:d}},[i]);return!i||i.todos.length===0?null:ft.createElement(br,{paddingX:2,marginBottom:1,flexShrink:0},ft.createElement(br,{borderStyle:"round",borderColor:n?A.status.success:A.border.default,paddingX:2,paddingY:1,flexDirection:"column"},ft.createElement(br,{marginBottom:1},ft.createElement(Un,{color:A.text.primary,bold:!0},"Tasks"),ft.createElement(Un,{color:A.ui.muted}," - "),ft.createElement(Un,{color:n?A.status.success:A.text.secondary},t.length,"/",i.todos.length,n&&" ✓")),s.map((o,a)=>{let c=o.status==="completed"?"[done]":o.status==="in_progress"?"[..]":"[ ]",l=o.status==="completed"?A.status.success:o.status==="in_progress"?A.text.accent:A.ui.muted,d=o.status==="in_progress"&&o.activeForm?o.activeForm:od(o);return ft.createElement(br,{key:o.id||`todo-${a}`},ft.createElement(Un,{color:l},c),ft.createElement(Un,{color:A.ui.muted}," "),ft.createElement(Un,{color:o.status==="completed"?A.ui.muted:A.text.primary},d))}),r>0&&ft.createElement(br,{marginTop:0},ft.createElement(Un,{color:A.ui.muted}," +",r," more tasks"))))}var xg=pS(bS);import Ne,{memo as yS}from"react";import{Box as fc,Text as Ze}from"@jrichman/ink";function vS(){return Ne.createElement(fc,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},Ne.createElement(Ze,{bold:!0,color:"whiteBright"},"Keyboard Shortcuts"),Ne.createElement(fc,{marginTop:1,flexDirection:"column"},Ne.createElement(Ze,{color:"#9CA3AF"},"• ",Ne.createElement(Ze,{color:"whiteBright",bold:!0},"Enter")," ",Ne.createElement(Ze,{color:"#9CA3AF"},"Submit message")),Ne.createElement(Ze,{color:"#9CA3AF"},"• ",Ne.createElement(Ze,{color:"whiteBright",bold:!0},"?")," ",Ne.createElement(Ze,{color:"#9CA3AF"},"Toggle this help")),Ne.createElement(Ze,{color:"#9CA3AF"},"• ",Ne.createElement(Ze,{color:"whiteBright",bold:!0},"Esc")," ",Ne.createElement(Ze,{color:"#9CA3AF"},"Stop generation / Close menus")),Ne.createElement(Ze,{color:"#9CA3AF"},"• ",Ne.createElement(Ze,{color:"whiteBright",bold:!0},"Ctrl+C")," ",Ne.createElement(Ze,{color:"#9CA3AF"},"Stop generation / Exit"))),Ne.createElement(fc,{marginTop:1},Ne.createElement(Ze,{color:"#6B7280"},"Press Esc to close")))}var Cg=yS(vS);import Ae,{memo as ES,useMemo as IS,useCallback as kS}from"react";import{Box as Zo,Text as nt}from"@jrichman/ink";import ys,{useState as SS,useEffect as wS,memo as Eg}from"react";import{Box as bc,Text as Ig,useInput as TS}from"@jrichman/ink";var xS=Eg(function({item:e,isSelected:t,highlightColor:n}){return ys.createElement(Ig,{color:t?"#000":"#fff",backgroundColor:t?n:void 0},e.label)});function CS({items:i,onSelect:e,onHighlight:t,isFocused:n=!0,highlightColor:s="#D97706",itemComponent:r=xS}){let[o,a]=SS(0);return wS(()=>{a(0)},[i.length]),TS((c,l)=>{if(n){if(l.upArrow){let d=o>0?o-1:i.length-1;a(d),t?.(i[d])}if(l.downArrow){let d=o<i.length-1?o+1:0;a(d),t?.(i[d])}if(l.return){let d=i[o];d&&e(d)}}},{isActive:n}),i.length===0?ys.createElement(bc,null,ys.createElement(Ig,{color:"#6B7280"},"No items")):ys.createElement(bc,{flexDirection:"column"},i.map((c,l)=>{let d=l===o;return ys.createElement(bc,{key:c.value||l},ys.createElement(r,{item:c,isSelected:d,highlightColor:s}))}))}var Jo=Eg(CS);Vt();wn();function PS({userTier:i,onSelect:e,onAccessDenied:t}){let n=a=>{switch(a){case .5:return"[0.5x]";case 1:return"[1x]";case 1.25:return"[1.25x]";case 1.5:return"[1.5x]";case 2:return"[2x]";case 2.5:return"[2.5x]";default:return`[${a}x]`}},{allItems:s,selectableItems:r}=IS(()=>{let a=pe.filter(p=>p.name.startsWith("snowx-o4")||p.name.startsWith("snowx-c")||p.name.startsWith("snowx-h")),c=pe.filter(p=>p.name.startsWith("snowx-5")||p.name.startsWith("snowx-o3")||p.name.startsWith("snowx-4")),l=pe.filter(p=>p.name.startsWith("snowx-g")),d=p=>p.map(h=>{let f=xe.isModelAccessible(h.name,i),y=n(h.creditMultiplier);return{label:`${f?"":"[LOCKED] "}${h.displayName} ${y}`,value:h.name,isAccessible:f,creditMultiplier:h.creditMultiplier,isHeader:!1}}),g=[{label:"-- Claude --",value:"_claude_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(a),{label:"-- GPT --",value:"_gpt_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(c),{label:"-- Gemini --",value:"_gemini_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(l)],m=g.filter(p=>!p.isHeader);return{allItems:g,selectableItems:m}},[i]),o=kS(a=>{if(a.value.startsWith("_"))return;if(!s.find(d=>d.value===a.value)?.isAccessible){t(a.value);return}let l=pe.find(d=>d.name===a.value);l&&e(l)},[s,t,e]);return Ae.createElement(Zo,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},Ae.createElement(nt,{bold:!0,color:"whiteBright"},"Select Model"),Ae.createElement(Zo,null,Ae.createElement(nt,{color:"#6B7280"},"Tier: ",xe.getDisplayName(i)," - "),Ae.createElement(nt,{color:"#5AD8A6"},"[0.5x]"),Ae.createElement(nt,{color:"#6B7280"}," "),Ae.createElement(nt,{color:"#9CA3AF"},"[1x]"),Ae.createElement(nt,{color:"#6B7280"}," "),Ae.createElement(nt,{color:"#60A5FA"},"[1.5x]"),Ae.createElement(nt,{color:"#6B7280"}," "),Ae.createElement(nt,{color:"#FBBF24"},"[2x]"),Ae.createElement(nt,{color:"#6B7280"}," "),Ae.createElement(nt,{color:"#F472B6"},"[2.5x]"),Ae.createElement(nt,{color:"#6B7280"}," credits")),Ae.createElement(Zo,{marginTop:1},Ae.createElement(Jo,{items:r.map(a=>({label:a.label,value:a.value})),onSelect:o,isFocused:!0,highlightColor:"#D97706"})),Ae.createElement(Zo,{marginTop:1},Ae.createElement(nt,{color:"#6B7280"},"Esc to cancel")))}var kg=ES(PS);import vs,{memo as Dg,useMemo as AS,useCallback as DS}from"react";import{Box as yc,Text as Pg}from"@jrichman/ink";var Ag=[{command:"/model",description:"change AI model",value:"model"},{command:"/usage",description:"view usage & limits",value:"usage"},{command:"/new",description:"start new conversation",value:"new"},{command:"/clear",description:"clear conversation",value:"clear"},{command:"/stop",description:"stop current generation",value:"stop"},{command:"/vision",description:"toggle vision mode",value:"vision"},{command:"/img",description:"paste image from clipboard",value:"img"},{command:"/export",description:"export conversation (md/json/txt)",value:"export"},{command:"/discord",description:"discord integration",value:"discord"},{command:"/telegram",description:"telegram integration",value:"telegram"},{command:"/signout",description:"sign out and exit",value:"signout"},{command:"/help",description:"show help",value:"help"},{command:"/exit",description:"exit the app",value:"exit"}],MS=Dg(function({item:e,isSelected:t,highlightColor:n}){let[s,r]=e.label.split(" ");return vs.createElement(yc,{width:50,backgroundColor:t?n:void 0},vs.createElement(yc,{width:14},vs.createElement(Pg,{color:t?"#1a1a1a":"whiteBright",bold:!0},s)),vs.createElement(Pg,{color:t?"#1a1a1a":"#6B7280"},r))});function RS({filterText:i,onSelect:e}){let t=AS(()=>(i?Ag.filter(r=>r.value.toLowerCase().includes(i)):Ag).map(r=>({label:`${r.command} ${r.description}`,value:r.value})),[i]),n=DS(s=>{s.value&&e(s.value)},[e]);return vs.createElement(yc,{flexDirection:"column",paddingX:1,paddingY:1,width:"100%",borderStyle:"single",borderColor:"#3F3F46",backgroundColor:"#18181B"},vs.createElement(Jo,{items:t.length>0?t:[{label:"No matching commands",value:""}],onSelect:n,itemComponent:MS,isFocused:!0,highlightColor:"#D97706"}))}var Mg=Dg(RS);import ne,{useState as ei,useEffect as OS,useCallback as ti,memo as NS}from"react";import{Box as qe,Text as _e,useInput as _S}from"@jrichman/ink";import $S from"ink-spinner";import{exec as FS}from"child_process";var ce={brand:"#A78BFA",text:"#F8FAFC",muted:"#94A3B8",dim:"#64748B",border:"#334155",error:"#EF4444",success:"#22C55E"},LS=[{id:1,title:"Bot Token",type:"input",field:"botToken",required:!0,help:"Paste your Discord bot token",hint:"Get it from discord.com/developers → Your App → Bot → Token",placeholder:"e.g., MTIzNDU2Nzg5MDEy..."},{id:2,title:"Owner IDs",type:"input",field:"ownerIds",required:!0,help:"Your Discord User ID (has full access)",hint:"Enable Developer Mode → Right-click your name → Copy User ID",placeholder:"e.g., 123456789012345678"},{id:3,title:"Guest IDs",type:"input",field:"guestIds",required:!1,help:"Guest User IDs (limited access, optional)",hint:"Comma-separated. Press Enter to skip",placeholder:"e.g., 111111111, 222222222"},{id:4,title:"Server Channels",type:"confirm",field:"allowGuildChat",help:"Allow bot to respond in server channels?",hint:"If No, bot only responds in DMs"},{id:5,title:"Connecting",type:"loading"}],US=[{id:1,title:"Bot Token",type:"input",field:"botToken",required:!0,help:"Paste your Telegram bot token",hint:"Get it from @BotFather → /newbot or /token",placeholder:"e.g., 123456789:ABCdefGHI..."},{id:2,title:"Owner Username",type:"input",field:"ownerUsernames",required:!0,help:"Your Telegram username (has full access)",hint:"Without @ symbol",placeholder:"e.g., johndoe"},{id:3,title:"Guest Usernames",type:"input",field:"guestUsernames",required:!1,help:"Guest usernames (limited access, optional)",hint:"Comma-separated. Press Enter to skip",placeholder:"e.g., alice, bob"},{id:4,title:"Group Chats",type:"confirm",field:"allowGroupChat",help:"Allow bot to respond in group chats?",hint:"If No, bot only responds in private chats"},{id:5,title:"Route to DM",type:"confirm",field:"routeToDM",help:"Send group responses to your private DM instead?",hint:"Keeps group chat clean, responses go to you privately"},{id:6,title:"Connecting",type:"loading"}];function BS({type:i}){let e=Wt(),t=Ct(),n=Xa(),[s,r]=ei(""),[o,a]=ei(null),[c,l]=ei(!1),[d,g]=ei(0),m=Gt.getInstance(),p=i==="discord"?LS:US,h=p.find(S=>S.id===n.step),f=p.length-1,y=ti(S=>{let I=process.platform,P;I==="darwin"?P=`open "${S}"`:I==="win32"?P=`start "" "${S}"`:P=`xdg-open "${S}"`,FS(P,()=>{})},[]);_S((S,I)=>{if(n.isOpen){if(I.escape){e.hideWizard();return}if(h?.type==="input"){if(I.return){T();return}if(I.backspace||I.delete){r(P=>P.slice(0,-1)),a(null);return}S&&!I.ctrl&&!I.meta&&!I.leftArrow&&!I.rightArrow&&!I.upArrow&&!I.downArrow&&!I.tab&&(r(P=>P+S),a(null))}else if(h?.type==="confirm"){if(I.leftArrow||I.rightArrow||S==="y"||S==="n"){g(S==="y"?1:S==="n"?0:P=>P===0?1:0);return}if(I.return){x();return}}}},{isActive:n.isOpen});let T=ti(()=>{let S=n.step,I=s.trim();if(i==="discord"){if(S===1){if(!I){a("Bot token is required");return}if(!m.validateDiscordToken(I)){a("Invalid token format. Should be like: MTIz...xxx.Yyy...zzz");return}e.setWizardData("botToken",I)}else if(S===2){if(!I){a("At least one owner ID is required");return}if(I.split(",").map(R=>R.trim()).some(R=>!/^\d{17,19}$/.test(R))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("ownerIds",I)}else if(S===3){if(I&&I.split(",").map(R=>R.trim()).filter(Boolean).some(R=>!/^\d{17,19}$/.test(R))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("guestIds",I)}}else if(S===1){if(!I){a("Bot token is required");return}if(!m.validateTelegramToken(I)){a("Invalid token format. Should be like: 123456789:ABCdef...");return}e.setWizardData("botToken",I)}else if(S===2){if(!I){a("At least one owner username is required");return}e.setWizardData("ownerUsernames",I)}else S===3&&e.setWizardData("guestUsernames",I);r(""),a(null),e.setWizardStep(S+1)},[n.step,i,s,m,e]),x=ti(()=>{let S=n.step,I=d===1;i==="discord"?S===4&&(e.setWizardData("allowGuildChat",I),e.setWizardStep(5)):S===4?(e.setWizardData("allowGroupChat",I),I?e.setWizardStep(5):(e.setWizardData("routeToDM",!1),e.setWizardStep(6))):S===5&&(e.setWizardData("routeToDM",I),e.setWizardStep(6)),g(0)},[n.step,i,d,e]),w=ti(async S=>{try{if(i==="discord"){let I=await m.connectDiscord({botToken:S.botToken,ownerUserIds:S.ownerIds.split(",").map(P=>P.trim()).filter(Boolean),guestUserIds:S.guestIds?S.guestIds.split(",").map(P=>P.trim()).filter(Boolean):[],allowGuildChat:S.allowGuildChat||!1});if(I.success){let P=I.botId?m.generateDiscordInviteUrl(I.botId):"";t.addSystemMessage(`✓ Discord connected!
2578
+ Type /help to see available commands.`),r.clearInput(),{handled:!0,clearInput:!0}},[i,e,t,n.authService,s,r]),isCommand:o}}import{useRef as hn,useCallback as zt,useEffect as Av}from"react";var lc=typeof requestAnimationFrame<"u"?requestAnimationFrame:i=>setImmediate(i),bs=typeof cancelAnimationFrame<"u"?cancelAnimationFrame:i=>clearImmediate(i);var Dv={flushInterval:16,maxBufferSize:32,detectPaste:!0,pasteThreshold:50,immediateFlushChars:[`
2579
+ `,"\r"," "]};function sg(i,e){let t={...Dv,...e},n=hn(""),s=hn(0),r=hn(0),o=hn(0),a=hn(0),c=hn(null),l=hn(null),d=hn(i);d.current=i;let g=zt(()=>{if(n.current===""&&s.current===0)return null;let v=Date.now()-r.current,x=t.detectPaste&&a.current>3&&v<t.pasteThreshold*a.current;return{chars:n.current,backspaces:s.current,isPaste:x,startTime:r.current}},[t.detectPaste,t.pasteThreshold]),m=zt(()=>{let E=g();E&&(n.current="",s.current=0,a.current=0,r.current=0,d.current(E)),c.current!==null&&(bs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null)},[g]),p=zt(()=>{c.current===null&&(c.current=lc(()=>{c.current=null,l.current&&clearTimeout(l.current),l.current=setTimeout(m,t.flushInterval)}))},[m,t.flushInterval]),h=zt(E=>{let v=Date.now();r.current===0&&(r.current=v),o.current=v,a.current++,n.current+=E,t.immediateFlushChars.includes(E)||n.current.length>=t.maxBufferSize?m():p()},[m,p,t.immediateFlushChars,t.maxBufferSize]),f=zt(()=>{let E=Date.now();r.current===0&&(r.current=E),a.current++,n.current.length>0?n.current=n.current.slice(0,-1):s.current++,p()},[p]),y=zt(()=>{let E=g();return E&&(n.current="",s.current=0,a.current=0,r.current=0),c.current!==null&&(bs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),E},[g]),T=zt(()=>g(),[g]),C=zt(()=>{n.current="",s.current=0,a.current=0,r.current=0,c.current!==null&&(bs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null)},[]),w=zt(()=>n.current===""&&s.current===0,[]);return Av(()=>()=>{c.current!==null&&bs(c.current),l.current&&clearTimeout(l.current)},[]),{pushChar:h,pushBackspace:f,flush:y,peek:T,clear:C,isEmpty:w}}import{useRef as fn,useEffect as uc,useCallback as ys,useState as Mv,useMemo as rg}from"react";function og(i){let e=fn(0),t=fn([]),n=fn(0),s=fn(0),r=fn([]);return uc(()=>{let a=performance.now();return()=>{let l=performance.now()-a;e.current++,n.current=l,s.current=Math.max(s.current,l),t.current.push(l),t.current.length>100&&t.current.shift(),r.current.push(Date.now());let d=Date.now()-1e3;r.current=r.current.filter(g=>g>d)}}),rg(()=>{let a=t.current,c=a.length>0?a.reduce((g,m)=>g+m,0)/a.length:0,l=r.current.length,d=c>16||l>60;return{renderCount:e.current,avgRenderTime:c,lastRenderTime:n.current,peakRenderTime:s.current,rendersPerSecond:l,isPerformanceDegraded:d}},[])}function ig(i){let{targetFrameTime:e=16.67,warningThreshold:t=.8,criticalThreshold:n=1}=i||{},s=fn(0),r=fn(0),o=ys(()=>{s.current=performance.now(),r.current=0},[]),a=ys(()=>performance.now()-s.current+r.current<e*n,[e,n]),c=ys(d=>{r.current+=d;let g=e-r.current;return Math.max(0,g)},[e]),l=ys(()=>{let g=(performance.now()-s.current+r.current)/e;return g>=n?"critical":g>=t?"warning":"ok"},[e,t,n]);return uc(()=>{o()}),{hasBudget:a,useBudget:c,resetBudget:o,getBudgetStatus:l}}function ag(i){let{warningThresholdMB:e=100,criticalThresholdMB:t=200,checkInterval:n=5e3}=i||{},[s,r]=Mv(0);uc(()=>{let c=()=>{if(typeof process<"u"&&process.memoryUsage){let d=process.memoryUsage();r(d.heapUsed/1024/1024)}};c();let l=setInterval(c,n);return()=>clearInterval(l)},[n]);let o=rg(()=>s>=t?"critical":s>=e?"warning":"normal",[s,e,t]),a=ys(()=>{typeof global<"u"&&global.gc&&global.gc()},[]);return{heapUsedMB:s,pressure:o,requestGC:a}}function cg(i){let e=fn(i);return e.current=i,ys(((...t)=>e.current(...t)),[])}function lg({onSubmit:i,enableProfiling:e=!1,bufferFlushInterval:t=16}){let{exit:n}=_v(),s=$n(),r=Ct(),o=hs(),a=Ht(),c=cr(),l=Ln(),{handleCommand:d,isCommand:g}=Yo(),m=ig({targetFrameTime:16.67}),{pressure:p}=ag({warningThresholdMB:150,criticalThresholdMB:250}),h=e?og("OptimizedKeyboardInput"):void 0,f=dc(!1),y=dc(0),T=dc(0),C=500,w=cg(i),E=Ov(x=>{if(x.isPaste)l.addPastedContent(x.chars);else{for(let S=0;S<x.backspaces;S++)l.deleteAtCursor();x.chars&&(l.insertAtCursor(x.chars),c.input.slice(0,c.cursorPosition)+x.chars+c.input.slice(c.cursorPosition)==="/"&&!o.showCommandMenu&&a.showCommandMenu())}},[l,c.input,c.cursorPosition,o.showCommandMenu,a]),v=sg(E,{flushInterval:t,maxBufferSize:64,detectPaste:!0,pasteThreshold:50});return Nv((x,S)=>{let I=Date.now(),D=I-y.current;if(y.current=I,!(x.startsWith("[<")||x.startsWith("[M")||/^\[<?\d+;\d+;\d+[mM]?/.test(x)||/^\d+[mM]/.test(x)||/^;\d+;\d+[mM]/.test(x)||/^\d+;\d+[mM]/.test(x))){if(S.escape){v.flush();let M=Date.now(),_=M-T.current;if(T.current=M,_<C){s.isLoading&&r.stopStreaming(),a.closeAllModals(),a.stopReverseSearch(),l.clearInput(),l.clearPastedTexts();return}if(s.isLoading){r.stopStreaming();return}if(o.isReverseSearchActive){a.stopReverseSearch();return}if(o.showWizard)return;if(o.showModelMenu||o.showCommandMenu){a.closeAllModals(),o.showCommandMenu&&c.input==="/"&&l.clearInput();return}if(o.showHelp){a.hideHelp();return}if(c.pastedTexts.length>0){l.clearPastedTexts();return}return}if(!o.showModelMenu&&!o.showWizard&&!(o.showCommandMenu&&(S.upArrow||S.downArrow||S.return))){if(S.ctrl&&x==="l"){v.flush(),process.stdout.write("\x1B[2J\x1B[H");return}if(S.ctrl&&x==="c"){v.flush(),s.isLoading?r.stopStreaming():n();return}if(S.ctrl&&x==="r"){v.flush(),o.isReverseSearchActive||a.startReverseSearch();return}if(S.ctrl&&x==="z"){v.flush(),l.undo();return}if(S.ctrl&&(x==="y"||x==="Z")){v.flush(),l.redo();return}if(x===""||S.ctrl&&x==="v"){if(f.current)return;if(Vo()){f.current=!0,Xo().then(M=>{f.current=!1,M.data&&(v.flush(),l.addClipboardImage(M.data,M.size))}).catch(()=>{f.current=!1});return}return}if(S.tab){v.flush(),c.suggestion&&l.acceptSuggestion();return}if(x==="?"&&c.input===""&&!o.showCommandMenu){v.flush(),a.toggleHelp();return}if(S.return&&!o.isReverseSearchActive){v.flush();let M=c.pastedTexts.filter(F=>!F.error||F.type==="text");(c.input.trim()||M.length>0)&&w();return}if(S.upArrow&&!o.showCommandMenu&&!o.isReverseSearchActive){v.flush(),l.navigateHistoryUp();return}if(S.downArrow&&!o.showCommandMenu&&!o.isReverseSearchActive){v.flush(),l.navigateHistoryDown();return}if(S.leftArrow){v.flush(),l.moveCursorLeft();return}if(S.rightArrow){v.flush(),l.moveCursorRight();return}if(S.ctrl&&x==="a"){v.flush(),l.moveCursorToStart();return}if(S.ctrl&&x==="e"){v.flush(),l.moveCursorToEnd();return}if(S.delete||S.backspace){v.flush(),l.deleteAtCursor(),o.showCommandMenu&&((c.input.slice(0,c.cursorPosition-1)+c.input.slice(c.cursorPosition)).startsWith("/")||a.hideCommandMenu());return}if(!S.ctrl&&!S.meta&&x){let M=x.includes(`
2580
+ `),_=x.length>50;if(M||_){v.flush(),l.addPastedContent(x);return}v.pushChar(x)}}}}),Rv(()=>()=>{v.clear()},[v]),{handleCommand:d,isCommand:g,renderProfile:h,memoryPressure:p,frameBudgetStatus:m.getBudgetStatus()}}import{useState as mr,useCallback as Et,useMemo as Wv,useRef as dg,useEffect as gg}from"react";import{useEffect as $v,useRef as gc}from"react";import{useInput as jF}from"@jrichman/ink";var Fv=0,Qo=[];function Lv(){return`keypress-${++Fv}`}function Uv(i,e,t){let n=Lv();return Qo.push({id:n,handler:i,priority:e,isActive:t}),Qo.sort((s,r)=>r.priority-s.priority),n}function Bv(i){let e=Qo.findIndex(t=>t.id===i);e!==-1&&Qo.splice(e,1)}function ug(i,e={}){let{priority:t=0,isActive:n=!0}=e,s=gc(i),r=gc(n),o=gc(null);s.current=i,r.current=n,$v(()=>(o.current=Uv((a,c)=>s.current(a,c),t,()=>r.current),()=>{o.current&&(Bv(o.current),o.current=null)}),[t])}function mg(i){let{items:e,getSearchText:t,direction:n="forward",caseSensitive:s=!1,useRegex:r=!1,initialQuery:o="",onSearchChange:a,onMatchSelect:c,isActive:l=!0,maxHistory:d=50}=i,[g,m]=mr(o),[p,h]=mr(!1),[f,y]=mr(0),[T,C]=mr([]),[w,E]=mr(-1),v=dg(a),x=dg(c);v.current=a,x.current=c;let S=Wv(()=>{if(!g)return[];let H=[],j;try{if(r)j=new RegExp(g,s?"g":"gi");else{let Te=g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");j=new RegExp(Te,s?"g":"gi")}}catch{return[]}return e.forEach((Te,Ft)=>{let vt=t(Te),Tn=j.exec(vt);Tn&&H.push({item:Te,index:Ft,matchStart:Tn.index,matchEnd:Tn.index+Tn[0].length}),j.lastIndex=0}),n==="backward"&&H.reverse(),H},[e,g,t,n,s,r]),I=S.length>0&&S[f]||null,D=S.length,M=D>0,_=Et(H=>{m(H),y(0),E(-1)},[]);gg(()=>{v.current?.(g,S)},[g,S]),gg(()=>{I&&x.current?.(I)},[I]);let F=Et(()=>{D!==0&&y(H=>(H+1)%D)},[D]),R=Et(()=>{D!==0&&y(H=>(H-1+D)%D)},[D]),N=Et(H=>{H>=0&&H<D&&y(H)},[D]),k=Et(()=>{g&&C(H=>{let j=H.filter(Te=>Te!==g);return[g,...j].slice(0,d)}),m(""),y(0),E(-1)},[g,d]),P=Et(()=>{h(!0),_("")},[_]),B=Et(()=>{k(),h(!1)},[k]),L=Et(()=>{T.length!==0&&E(H=>{let j=Math.min(H+1,T.length-1);return m(T[j]||""),j})},[T]),W=Et(()=>{w<0||E(H=>{let j=H-1;return j<0?m(""):m(T[j]||""),j})},[T,w]),G=Et(H=>{m(j=>j+H),y(0),E(-1)},[]),Y=Et(()=>{m(H=>H.slice(0,-1)),y(0),E(-1)},[]);return ug((H,j)=>{if(p){if(j.downArrow||j.ctrl&&H==="n")return F(),!0;if(j.upArrow||j.ctrl&&H==="p")return R(),!0;if(j.ctrl&&j.upArrow)return L(),!0;if(j.ctrl&&j.downArrow)return W(),!0;if(j.escape)return B(),!0;if(j.return)return k(),h(!1),!0;if(j.backspace||j.delete)return Y(),!0;if(H&&H.length===1&&!j.ctrl&&!j.meta)return G(H),!0}},{isActive:l&&p,priority:100}),{query:g,setQuery:_,matches:S,currentMatchIndex:f,currentMatch:I,nextMatch:F,prevMatch:R,goToMatch:N,clear:k,isSearching:p,startSearch:P,stopSearch:B,history:T,historyUp:L,historyDown:W,append:G,backspace:Y,matchCount:D,hasMatches:M}}function pg(i,e,t=!1){if(!e)return[{text:i,isMatch:!1}];let n=[],s=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t?"g":"gi"),r=0,o;for(;(o=s.exec(i))!==null;)o.index>r&&n.push({text:i.slice(r,o.index),isMatch:!1}),n.push({text:o[0],isMatch:!0}),r=o.index+o[0].length;return r<i.length&&n.push({text:i.slice(r),isMatch:!1}),n.length>0?n:[{text:i,isMatch:!1}]}import fe,{memo as hg,useMemo as jv}from"react";import{Box as pr,Text as ht}from"@jrichman/ink";import zv from"ink-spinner";var qe={Foreground:"#D4D4D4",Background:"#1E1E1E",AccentBlue:"#6B9FD4",AccentPurple:"#B48EAD",AccentCyan:"#88C0D0",AccentGreen:"#A3BE8C",AccentYellow:"#EBCB8B",AccentRed:"#BF616A",Gray:"#808080",DarkGray:"#5C5C5C",LightGray:"#A0A0A0",Comment:"#6A737D"},Hv={text:{primary:qe.Foreground,secondary:qe.LightGray,accent:qe.Foreground,link:qe.AccentBlue,response:qe.Foreground},background:{primary:qe.Background,secondary:"#252526"},border:{default:"#3C3C3C",focused:qe.AccentBlue},ui:{comment:qe.Comment,symbol:qe.Gray,muted:qe.DarkGray},status:{success:qe.AccentGreen,warning:qe.AccentYellow,error:qe.AccentRed,info:qe.Gray}},mc={name:"Default Dark",type:"dark",colors:qe,semantic:Hv};var Gv=mc;function vs(){return Gv}var A={get text(){return vs().semantic.text},get background(){return vs().semantic.background},get border(){return vs().semantic.border},get ui(){return vs().semantic.ui},get status(){return vs().semantic.status},get colors(){return vs().colors}};function qv(i,e){let t=i.toLowerCase();if(t==="read"||t==="readfile")return{displayName:"Read",mainArg:e?.file_path};if(t==="write"||t==="writefile")return{displayName:"Write",mainArg:e?.file_path};if(t==="edit"||t==="editfile")return{displayName:"Edit",mainArg:e?.file_path};if(t==="grep")return{displayName:"Grep",mainArg:e?.pattern};if(t==="glob")return{displayName:"Glob",mainArg:e?.pattern};if(t==="bash"||t==="command"||t==="run_command"){let r=e?.command;return{displayName:"Bash",mainArg:r?r.length>40?r.substring(0,37)+"...":r:void 0}}if(t==="webfetch"||t==="web_fetch")return{displayName:"WebFetch",mainArg:e?.url};if(t==="websearch"||t==="web_search")return{displayName:"WebSearch",mainArg:e?.query};if(t==="task")return{displayName:"Task",mainArg:e?.subagent_type||e?.description};if(t==="todowrite"||t==="todo_write")return{displayName:"",mainArg:void 0};let n=i.charAt(0).toUpperCase()+i.slice(1).replace(/_/g,""),s=e?.description||e?.query||e?.path||e?.url;return{displayName:n,mainArg:s}}function Kv(i){if(!i)return"";let e=i.split("/");return e.length<=2?i:e.slice(-2).join("/")}var pc=hg(function({tool:e}){let{displayName:t,mainArg:n}=qv(e.name,e.arguments);if(!t)return null;let s=e.state==="running",r=e.state==="completed",o=e.state==="failed",a=n?Kv(n):void 0;return fe.createElement(pr,{flexDirection:"column"},fe.createElement(pr,null,s&&fe.createElement(ht,{color:A.status.warning},fe.createElement(zv,{type:"dots"})),r&&fe.createElement(ht,{color:A.status.success},"●"),o&&fe.createElement(ht,{color:A.status.error},"●"),fe.createElement(ht,null," "),fe.createElement(ht,{color:A.text.primary,bold:!0},t),a&&fe.createElement(fe.Fragment,null,fe.createElement(ht,{color:A.ui.muted},"("),fe.createElement(ht,{color:A.text.secondary},a),fe.createElement(ht,{color:A.ui.muted},")"))),r&&e.output&&fe.createElement(pr,{paddingLeft:2},fe.createElement(ht,{color:A.ui.muted},"└ "),fe.createElement(ht,{color:A.ui.muted},Vv(e.output))),o&&e.error&&fe.createElement(pr,{paddingLeft:2},fe.createElement(ht,{color:A.ui.muted},"└ "),fe.createElement(ht,{color:A.status.error},e.error.substring(0,60))))});function Vv(i){if(!i)return"";let e=i.split(`
2581
+ `).length;return e>1?`${e} lines`:i.length>50?i.substring(0,47)+"...":i}function Xv({activeTools:i}){let{running:e,completed:t,failed:n}=jv(()=>{if(i.size===0)return{running:[],completed:[],failed:[]};let s=Array.from(i.values()).filter(r=>r.name.toLowerCase().replace(/_/g,"")!=="todowrite");return{running:s.filter(r=>r.state==="running"),completed:s.filter(r=>r.state==="completed").slice(-3),failed:s.filter(r=>r.state==="failed")}},[i]);return e.length===0&&t.length===0&&n.length===0?null:fe.createElement(pr,{flexDirection:"column",paddingX:1,marginY:1},e.map(s=>fe.createElement(pc,{key:s.toolCallId,tool:s})),t.map(s=>fe.createElement(pc,{key:s.toolCallId,tool:s})),n.map(s=>fe.createElement(pc,{key:s.toolCallId,tool:s})))}var fg=hg(Xv);import ie,{memo as hc,useMemo as bg}from"react";import{Box as qt,Text as Ne}from"@jrichman/ink";import yg from"ink-spinner";function Yv(i,e=60){return i?i.length<=e?i:i.substring(0,e-3)+"...":"Processing..."}var Qv=hc(function({agent:e}){let t=Yv(e.task||"Working..."),n=o=>{switch(o){case"running":return"cyan";case"completed":return"#5AD8A6";case"failed":return"#F5716C";case"timeout":return"#FBBF24";default:return"#6B7280"}},s=()=>e.status==="running"?ie.createElement(Ne,{color:"cyan"},ie.createElement(yg,{type:"dots"})):e.status==="completed"?ie.createElement(Ne,{color:"#5AD8A6"},"[done]"):e.status==="failed"?ie.createElement(Ne,{color:"#F5716C"},"[fail]"):e.status==="timeout"?ie.createElement(Ne,{color:"#FBBF24"},"[time]"):ie.createElement(Ne,{color:"#6B7280"},"[ ]"),r=n(e.status);return ie.createElement(qt,{flexDirection:"column",marginLeft:2},ie.createElement(qt,null,s(),ie.createElement(Ne,{color:r,bold:!0}," Agent #",e.agentNumber)),ie.createElement(qt,{marginLeft:2},ie.createElement(Ne,{color:"#9CA3AF"},t)),e.error&&ie.createElement(qt,{marginLeft:2},ie.createElement(Ne,{color:"#F5716C"},"Error: ",e.error.substring(0,60),e.error.length>60?"...":"")),e.streamingContent&&e.status==="running"&&ie.createElement(qt,{marginLeft:2},ie.createElement(Ne,{color:"#6B7280"},e.streamingContent.split(`
2582
+ `)[0]?.substring(0,50),"...")))}),Jv=hc(function({operation:e}){let{agents:t,completed:n,failed:s,running:r,total:o}=bg(()=>{let d=Array.from(e.agents.values()).sort((g,m)=>g.agentNumber-m.agentNumber);return{agents:d,completed:d.filter(g=>g.status==="completed").length,failed:d.filter(g=>g.status==="failed").length,running:d.filter(g=>g.status==="running").length,total:e.totalAgents}},[e.agents,e.totalAgents]),a=()=>e.status==="starting"||e.status==="running"?`Spawning ${o} agents`:e.status==="completed"?`${o} agents completed`:"Operation failed",c=()=>e.status==="running"||e.status==="starting"?ie.createElement(Ne,{color:"cyan"},ie.createElement(yg,{type:"dots"})):e.status==="completed"?ie.createElement(Ne,{color:"#5AD8A6"},"[done]"):ie.createElement(Ne,{color:"#F5716C"},"[fail]"),l=e.status==="completed"?"#5AD8A6":e.status==="failed"?"#F5716C":"cyan";return ie.createElement(qt,{flexDirection:"column"},ie.createElement(qt,null,c(),ie.createElement(Ne,{color:l,bold:!0}," ",a()),ie.createElement(Ne,{color:"#6B7280"}," "),ie.createElement(Ne,{backgroundColor:"#3F3F46",color:"whiteBright"}," ",n,"/",o," "),r>0&&ie.createElement(Ne,{color:"cyan"}," (",r," running)"),s>0&&ie.createElement(Ne,{color:"#F5716C"}," [",s," failed]")),ie.createElement(qt,{flexDirection:"column",marginTop:1},t.map(d=>ie.createElement(Qv,{key:d.agentNumber,agent:d}))))});function Zv({operations:i}){let e=bg(()=>i.size===0?[]:Array.from(i.entries()).filter(([t,n])=>n.status==="running"||n.status==="starting"?!0:n.endTime?Date.now()-n.endTime.getTime()<1e4:!0),[i]);return e.length===0?null:ie.createElement(qt,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},e.map(([t,n])=>ie.createElement(Jv,{key:t,operation:n})))}var vg=hc(Zv);import Bn,{memo as eS}from"react";import{Box as tS,Text as hr}from"@jrichman/ink";import nS from"ink-spinner";function sS(i){switch(i.toLowerCase()){case"vapi":return"Phone";case"cron":return"Scheduler";case"telegram":return"Telegram";case"discord":return"Discord";default:return i.charAt(0).toUpperCase()+i.slice(1)}}function rS(i,e=60){return i?i.length<=e?i:i.substring(0,e-3)+"...":"Processing request..."}function oS({session:i}){if(!i)return null;let e=sS(i.source),t=rS(i.message);return Bn.createElement(tS,{flexDirection:"row",paddingX:1,marginY:1,borderStyle:"round",borderColor:A.ui.border},Bn.createElement(hr,{color:A.status.warning},Bn.createElement(nS,{type:"dots"})),Bn.createElement(hr,null," "),Bn.createElement(hr,{color:A.text.primary,bold:!0},e),Bn.createElement(hr,{color:A.ui.muted},": "),Bn.createElement(hr,{color:A.text.secondary},t))}var Sg=eS(oS);import It,{useState as iS,useEffect as aS,useRef as wg,memo as cS,useMemo as lS,useCallback as uS}from"react";import{Box as fr,Text as br}from"@jrichman/ink";import dS from"ink-select-input";var gS=[{label:"Yes, proceed",value:"confirm"},{label:"No, cancel",value:"decline"}];function mS({request:i,onConfirm:e,onDecline:t,onTimeout:n}){let[s,r]=iS(i.timeout?Math.ceil(i.timeout/1e3):null),o=wg(null),a=wg(0);aS(()=>{if(i.timeout)return a.current=Date.now(),r(Math.ceil(i.timeout/1e3)),o.current=setInterval(()=>{let g=Date.now()-a.current,m=Math.max(0,i.timeout-g),p=Math.ceil(m/1e3);r(p),m<=0&&(o.current&&clearInterval(o.current),n?.())},1e3),()=>{o.current&&clearInterval(o.current)}},[i.timeout,n]);let c=uS(g=>{o.current&&(clearInterval(o.current),o.current=null),g.value==="confirm"?e("y"):t()},[e,t]),{actualTargets:l,displayCommand:d}=lS(()=>{let g=i.targets?.filter(p=>p.startsWith("/")||p.startsWith("./")||p.startsWith("~/")).slice(0,3)||[],m=i.command&&i.command.length>60?i.command.substring(0,57)+"...":i.command;return{actualTargets:g,displayCommand:m}},[i.targets,i.command]);return It.createElement(fr,{flexDirection:"column",borderStyle:"round",borderColor:"#525252",paddingX:2,paddingY:1},It.createElement(br,{color:"white",bold:!0},i.title),d&&It.createElement(fr,{marginTop:1},It.createElement(br,{color:"gray"},"$ "),It.createElement(br,{color:"white"},d)),l.length>0&&It.createElement(fr,{marginTop:1,flexDirection:"column"},l.map((g,m)=>It.createElement(br,{key:m,color:"gray"}," ",g))),s!==null&&It.createElement(fr,{marginTop:1},It.createElement(br,{color:"yellow"},"Auto-cancel in ",s,"s")),It.createElement(fr,{marginTop:1},It.createElement(dS,{items:gS,onSelect:c})))}var Tg=cS(mS,(i,e)=>i.request.id===e.request.id&&i.request.timeout===e.request.timeout);import ft,{memo as pS,useMemo as hS}from"react";import{Box as yr,Text as Wn}from"@jrichman/ink";var fS=8;function bS({todoList:i}){let{incompleteTodos:e,completedTodos:t,allComplete:n,visibleTodos:s,hiddenCount:r}=hS(()=>{if(!i||i.todos.length===0)return{incompleteTodos:[],completedTodos:[],allComplete:!1,visibleTodos:[],hiddenCount:0};let o=i.todos.filter(g=>g.status!=="completed"),a=i.todos.filter(g=>g.status==="completed"),c=o.length===0&&a.length>0,l=[...o,...a.slice(-2)].slice(0,fS),d=i.todos.length-l.length;return{incompleteTodos:o,completedTodos:a,allComplete:c,visibleTodos:l,hiddenCount:d}},[i]);return!i||i.todos.length===0?null:ft.createElement(yr,{paddingX:2,marginBottom:1,flexShrink:0},ft.createElement(yr,{borderStyle:"round",borderColor:n?A.status.success:A.border.default,paddingX:2,paddingY:1,flexDirection:"column"},ft.createElement(yr,{marginBottom:1},ft.createElement(Wn,{color:A.text.primary,bold:!0},"Tasks"),ft.createElement(Wn,{color:A.ui.muted}," - "),ft.createElement(Wn,{color:n?A.status.success:A.text.secondary},t.length,"/",i.todos.length,n&&" ✓")),s.map((o,a)=>{let c=o.status==="completed"?"[done]":o.status==="in_progress"?"[..]":"[ ]",l=o.status==="completed"?A.status.success:o.status==="in_progress"?A.text.accent:A.ui.muted,d=o.status==="in_progress"&&o.activeForm?o.activeForm:od(o);return ft.createElement(yr,{key:o.id||`todo-${a}`},ft.createElement(Wn,{color:l},c),ft.createElement(Wn,{color:A.ui.muted}," "),ft.createElement(Wn,{color:o.status==="completed"?A.ui.muted:A.text.primary},d))}),r>0&&ft.createElement(yr,{marginTop:0},ft.createElement(Wn,{color:A.ui.muted}," +",r," more tasks"))))}var xg=pS(bS);import _e,{memo as yS}from"react";import{Box as fc,Text as et}from"@jrichman/ink";function vS(){return _e.createElement(fc,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},_e.createElement(et,{bold:!0,color:"whiteBright"},"Keyboard Shortcuts"),_e.createElement(fc,{marginTop:1,flexDirection:"column"},_e.createElement(et,{color:"#9CA3AF"},"• ",_e.createElement(et,{color:"whiteBright",bold:!0},"Enter")," ",_e.createElement(et,{color:"#9CA3AF"},"Submit message")),_e.createElement(et,{color:"#9CA3AF"},"• ",_e.createElement(et,{color:"whiteBright",bold:!0},"?")," ",_e.createElement(et,{color:"#9CA3AF"},"Toggle this help")),_e.createElement(et,{color:"#9CA3AF"},"• ",_e.createElement(et,{color:"whiteBright",bold:!0},"Esc")," ",_e.createElement(et,{color:"#9CA3AF"},"Stop generation / Close menus")),_e.createElement(et,{color:"#9CA3AF"},"• ",_e.createElement(et,{color:"whiteBright",bold:!0},"Ctrl+C")," ",_e.createElement(et,{color:"#9CA3AF"},"Stop generation / Exit"))),_e.createElement(fc,{marginTop:1},_e.createElement(et,{color:"#6B7280"},"Press Esc to close")))}var Cg=yS(vS);import De,{memo as ES,useMemo as IS,useCallback as kS}from"react";import{Box as Zo,Text as nt}from"@jrichman/ink";import Ss,{useState as SS,useEffect as wS,memo as Eg}from"react";import{Box as bc,Text as Ig,useInput as TS}from"@jrichman/ink";var xS=Eg(function({item:e,isSelected:t,highlightColor:n}){return Ss.createElement(Ig,{color:t?"#000":"#fff",backgroundColor:t?n:void 0},e.label)});function CS({items:i,onSelect:e,onHighlight:t,isFocused:n=!0,highlightColor:s="#D97706",itemComponent:r=xS}){let[o,a]=SS(0);return wS(()=>{a(0)},[i.length]),TS((c,l)=>{if(n){if(l.upArrow){let d=o>0?o-1:i.length-1;a(d),t?.(i[d])}if(l.downArrow){let d=o<i.length-1?o+1:0;a(d),t?.(i[d])}if(l.return){let d=i[o];d&&e(d)}}},{isActive:n}),i.length===0?Ss.createElement(bc,null,Ss.createElement(Ig,{color:"#6B7280"},"No items")):Ss.createElement(bc,{flexDirection:"column"},i.map((c,l)=>{let d=l===o;return Ss.createElement(bc,{key:c.value||l},Ss.createElement(r,{item:c,isSelected:d,highlightColor:s}))}))}var Jo=Eg(CS);Xt();xn();function PS({userTier:i,onSelect:e,onAccessDenied:t}){let n=a=>{switch(a){case .5:return"[0.5x]";case 1:return"[1x]";case 1.25:return"[1.25x]";case 1.5:return"[1.5x]";case 2:return"[2x]";case 2.5:return"[2.5x]";default:return`[${a}x]`}},{allItems:s,selectableItems:r}=IS(()=>{let a=pe.filter(p=>p.name.startsWith("snowx-o4")||p.name.startsWith("snowx-c")||p.name.startsWith("snowx-h")),c=pe.filter(p=>p.name.startsWith("snowx-5")||p.name.startsWith("snowx-o3")||p.name.startsWith("snowx-4")),l=pe.filter(p=>p.name.startsWith("snowx-g")),d=p=>p.map(h=>{let f=Ce.isModelAccessible(h.name,i),y=n(h.creditMultiplier);return{label:`${f?"":"[LOCKED] "}${h.displayName} ${y}`,value:h.name,isAccessible:f,creditMultiplier:h.creditMultiplier,isHeader:!1}}),g=[{label:"-- Claude --",value:"_claude_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(a),{label:"-- GPT --",value:"_gpt_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(c),{label:"-- Gemini --",value:"_gemini_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(l)],m=g.filter(p=>!p.isHeader);return{allItems:g,selectableItems:m}},[i]),o=kS(a=>{if(a.value.startsWith("_"))return;if(!s.find(d=>d.value===a.value)?.isAccessible){t(a.value);return}let l=pe.find(d=>d.name===a.value);l&&e(l)},[s,t,e]);return De.createElement(Zo,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},De.createElement(nt,{bold:!0,color:"whiteBright"},"Select Model"),De.createElement(Zo,null,De.createElement(nt,{color:"#6B7280"},"Tier: ",Ce.getDisplayName(i)," - "),De.createElement(nt,{color:"#5AD8A6"},"[0.5x]"),De.createElement(nt,{color:"#6B7280"}," "),De.createElement(nt,{color:"#9CA3AF"},"[1x]"),De.createElement(nt,{color:"#6B7280"}," "),De.createElement(nt,{color:"#60A5FA"},"[1.5x]"),De.createElement(nt,{color:"#6B7280"}," "),De.createElement(nt,{color:"#FBBF24"},"[2x]"),De.createElement(nt,{color:"#6B7280"}," "),De.createElement(nt,{color:"#F472B6"},"[2.5x]"),De.createElement(nt,{color:"#6B7280"}," credits")),De.createElement(Zo,{marginTop:1},De.createElement(Jo,{items:r.map(a=>({label:a.label,value:a.value})),onSelect:o,isFocused:!0,highlightColor:"#D97706"})),De.createElement(Zo,{marginTop:1},De.createElement(nt,{color:"#6B7280"},"Esc to cancel")))}var kg=ES(PS);import ws,{memo as Dg,useMemo as AS,useCallback as DS}from"react";import{Box as yc,Text as Pg}from"@jrichman/ink";var Ag=[{command:"/model",description:"change AI model",value:"model"},{command:"/usage",description:"view usage & limits",value:"usage"},{command:"/new",description:"start new conversation",value:"new"},{command:"/clear",description:"clear conversation",value:"clear"},{command:"/stop",description:"stop current generation",value:"stop"},{command:"/vision",description:"toggle vision mode",value:"vision"},{command:"/img",description:"paste image from clipboard",value:"img"},{command:"/export",description:"export conversation (md/json/txt)",value:"export"},{command:"/discord",description:"discord integration",value:"discord"},{command:"/telegram",description:"telegram integration",value:"telegram"},{command:"/signout",description:"sign out and exit",value:"signout"},{command:"/help",description:"show help",value:"help"},{command:"/exit",description:"exit the app",value:"exit"}],MS=Dg(function({item:e,isSelected:t,highlightColor:n}){let[s,r]=e.label.split(" ");return ws.createElement(yc,{width:50,backgroundColor:t?n:void 0},ws.createElement(yc,{width:14},ws.createElement(Pg,{color:t?"#1a1a1a":"whiteBright",bold:!0},s)),ws.createElement(Pg,{color:t?"#1a1a1a":"#6B7280"},r))});function RS({filterText:i,onSelect:e}){let t=AS(()=>(i?Ag.filter(r=>r.value.toLowerCase().includes(i)):Ag).map(r=>({label:`${r.command} ${r.description}`,value:r.value})),[i]),n=DS(s=>{s.value&&e(s.value)},[e]);return ws.createElement(yc,{flexDirection:"column",paddingX:1,paddingY:1,width:"100%",borderStyle:"single",borderColor:"#3F3F46",backgroundColor:"#18181B"},ws.createElement(Jo,{items:t.length>0?t:[{label:"No matching commands",value:""}],onSelect:n,itemComponent:MS,isFocused:!0,highlightColor:"#D97706"}))}var Mg=Dg(RS);import se,{useState as ei,useEffect as OS,useCallback as ti,memo as NS}from"react";import{Box as Ke,Text as $e,useInput as _S}from"@jrichman/ink";import $S from"ink-spinner";import{exec as FS}from"child_process";var le={brand:"#A78BFA",text:"#F8FAFC",muted:"#94A3B8",dim:"#64748B",border:"#334155",error:"#EF4444",success:"#22C55E"},LS=[{id:1,title:"Bot Token",type:"input",field:"botToken",required:!0,help:"Paste your Discord bot token",hint:"Get it from discord.com/developers → Your App → Bot → Token",placeholder:"e.g., MTIzNDU2Nzg5MDEy..."},{id:2,title:"Owner IDs",type:"input",field:"ownerIds",required:!0,help:"Your Discord User ID (has full access)",hint:"Enable Developer Mode → Right-click your name → Copy User ID",placeholder:"e.g., 123456789012345678"},{id:3,title:"Guest IDs",type:"input",field:"guestIds",required:!1,help:"Guest User IDs (limited access, optional)",hint:"Comma-separated. Press Enter to skip",placeholder:"e.g., 111111111, 222222222"},{id:4,title:"Server Channels",type:"confirm",field:"allowGuildChat",help:"Allow bot to respond in server channels?",hint:"If No, bot only responds in DMs"},{id:5,title:"Connecting",type:"loading"}],US=[{id:1,title:"Bot Token",type:"input",field:"botToken",required:!0,help:"Paste your Telegram bot token",hint:"Get it from @BotFather → /newbot or /token",placeholder:"e.g., 123456789:ABCdefGHI..."},{id:2,title:"Owner Username",type:"input",field:"ownerUsernames",required:!0,help:"Your Telegram username (has full access)",hint:"Without @ symbol",placeholder:"e.g., johndoe"},{id:3,title:"Guest Usernames",type:"input",field:"guestUsernames",required:!1,help:"Guest usernames (limited access, optional)",hint:"Comma-separated. Press Enter to skip",placeholder:"e.g., alice, bob"},{id:4,title:"Group Chats",type:"confirm",field:"allowGroupChat",help:"Allow bot to respond in group chats?",hint:"If No, bot only responds in private chats"},{id:5,title:"Route to DM",type:"confirm",field:"routeToDM",help:"Send group responses to your private DM instead?",hint:"Keeps group chat clean, responses go to you privately"},{id:6,title:"Connecting",type:"loading"}];function BS({type:i}){let e=Ht(),t=Ct(),n=Xa(),[s,r]=ei(""),[o,a]=ei(null),[c,l]=ei(!1),[d,g]=ei(0),m=jt.getInstance(),p=i==="discord"?LS:US,h=p.find(S=>S.id===n.step),f=p.length-1,y=ti(S=>{let I=process.platform,D;I==="darwin"?D=`open "${S}"`:I==="win32"?D=`start "" "${S}"`:D=`xdg-open "${S}"`,FS(D,()=>{})},[]);_S((S,I)=>{if(n.isOpen){if(I.escape){e.hideWizard();return}if(h?.type==="input"){if(I.return){T();return}if(I.backspace||I.delete){r(D=>D.slice(0,-1)),a(null);return}S&&!I.ctrl&&!I.meta&&!I.leftArrow&&!I.rightArrow&&!I.upArrow&&!I.downArrow&&!I.tab&&(r(D=>D+S),a(null))}else if(h?.type==="confirm"){if(I.leftArrow||I.rightArrow||S==="y"||S==="n"){g(S==="y"?1:S==="n"?0:D=>D===0?1:0);return}if(I.return){C();return}}}},{isActive:n.isOpen});let T=ti(()=>{let S=n.step,I=s.trim();if(i==="discord"){if(S===1){if(!I){a("Bot token is required");return}if(!m.validateDiscordToken(I)){a("Invalid token format. Should be like: MTIz...xxx.Yyy...zzz");return}e.setWizardData("botToken",I)}else if(S===2){if(!I){a("At least one owner ID is required");return}if(I.split(",").map(M=>M.trim()).some(M=>!/^\d{17,19}$/.test(M))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("ownerIds",I)}else if(S===3){if(I&&I.split(",").map(M=>M.trim()).filter(Boolean).some(M=>!/^\d{17,19}$/.test(M))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("guestIds",I)}}else if(S===1){if(!I){a("Bot token is required");return}if(!m.validateTelegramToken(I)){a("Invalid token format. Should be like: 123456789:ABCdef...");return}e.setWizardData("botToken",I)}else if(S===2){if(!I){a("At least one owner username is required");return}e.setWizardData("ownerUsernames",I)}else S===3&&e.setWizardData("guestUsernames",I);r(""),a(null),e.setWizardStep(S+1)},[n.step,i,s,m,e]),C=ti(()=>{let S=n.step,I=d===1;i==="discord"?S===4&&(e.setWizardData("allowGuildChat",I),e.setWizardStep(5)):S===4?(e.setWizardData("allowGroupChat",I),I?e.setWizardStep(5):(e.setWizardData("routeToDM",!1),e.setWizardStep(6))):S===5&&(e.setWizardData("routeToDM",I),e.setWizardStep(6)),g(0)},[n.step,i,d,e]),w=ti(async S=>{try{if(i==="discord"){let I=await m.connectDiscord({botToken:S.botToken,ownerUserIds:S.ownerIds.split(",").map(D=>D.trim()).filter(Boolean),guestUserIds:S.guestIds?S.guestIds.split(",").map(D=>D.trim()).filter(Boolean):[],allowGuildChat:S.allowGuildChat||!1});if(I.success){let D=I.botId?m.generateDiscordInviteUrl(I.botId):"";t.addSystemMessage(`✓ Discord connected!
2583
2583
 
2584
2584
  Bot: ${I.botUsername}
2585
- `+(P?`Invite URL: ${P}
2585
+ `+(D?`Invite URL: ${D}
2586
2586
  `:"")+`
2587
- Commands: /ask, /new, /clear`),P&&y(P)}else t.addSystemMessage(`✗ Discord setup failed: ${I.error}`)}else{let I=await m.connectTelegram({botToken:S.botToken,ownerUsernames:S.ownerUsernames.split(",").map(P=>P.trim().replace(/^@/,"")).filter(Boolean),guestUsernames:S.guestUsernames?S.guestUsernames.split(",").map(P=>P.trim().replace(/^@/,"")).filter(Boolean):[],allowGroupChat:S.allowGroupChat||!1,routeToDM:S.routeToDM||!1});if(I.success){let P=m.getTelegramChatUrl(I.botUsername||"");t.addSystemMessage(`✓ Telegram connected!
2587
+ Commands: /ask, /new, /clear`),D&&y(D)}else t.addSystemMessage(`✗ Discord setup failed: ${I.error}`)}else{let I=await m.connectTelegram({botToken:S.botToken,ownerUsernames:S.ownerUsernames.split(",").map(D=>D.trim().replace(/^@/,"")).filter(Boolean),guestUsernames:S.guestUsernames?S.guestUsernames.split(",").map(D=>D.trim().replace(/^@/,"")).filter(Boolean):[],allowGroupChat:S.allowGroupChat||!1,routeToDM:S.routeToDM||!1});if(I.success){let D=m.getTelegramChatUrl(I.botUsername||"");t.addSystemMessage(`✓ Telegram connected!
2588
2588
 
2589
2589
  Bot: @${I.botUsername}
2590
- Chat: ${P}
2590
+ Chat: ${D}
2591
2591
 
2592
- Send /new to start`),y(P)}else t.addSystemMessage(`✗ Telegram setup failed: ${I.error}`)}}catch(I){t.addSystemMessage(`✗ Connection error: ${I.message}`)}e.resetWizard()},[i,m,t,y,e]);OS(()=>{(i==="discord"&&n.step===5||i==="telegram"&&n.step===6)&&!c&&(l(!0),w(n.data))},[n.step,n.data,i,c,w]);let C=()=>{let S=Math.min(n.step,f),I="━".repeat(S),P="─".repeat(f-S);return ne.createElement(qe,null,ne.createElement(_e,{color:ce.brand},I),ne.createElement(_e,{color:ce.dim},P),ne.createElement(_e,{color:ce.muted}," ",S,"/",f))},v=()=>h?h.type==="loading"?ne.createElement(qe,{flexDirection:"column",paddingY:1},ne.createElement(qe,null,ne.createElement(_e,{color:ce.brand},ne.createElement($S,{type:"dots"})),ne.createElement(_e,{color:ce.muted}," Connecting to ",i==="discord"?"Discord":"Telegram","..."))):h.type==="input"?ne.createElement(qe,{flexDirection:"column"},ne.createElement(_e,{color:ce.text},h.help),ne.createElement(_e,{color:ce.dim},h.hint),ne.createElement(qe,{marginTop:1,flexDirection:"column"},ne.createElement(qe,{paddingX:1,borderStyle:"round",borderColor:o?ce.error:ce.brand},ne.createElement(_e,{color:s?ce.text:ce.dim},s||h.placeholder||"Type here..."),ne.createElement(_e,{color:ce.brand},"▎")),o&&ne.createElement(qe,{marginTop:1},ne.createElement(_e,{color:ce.error},"✗ ",o)))):h.type==="confirm"?ne.createElement(qe,{flexDirection:"column"},ne.createElement(_e,{color:ce.text},h.help),ne.createElement(_e,{color:ce.dim},h.hint),ne.createElement(qe,{marginTop:1,gap:2},ne.createElement(qe,{paddingX:2,borderStyle:"round",borderColor:d===0?ce.brand:ce.border},ne.createElement(_e,{color:d===0?ce.brand:ce.muted},"No")),ne.createElement(qe,{paddingX:2,borderStyle:"round",borderColor:d===1?ce.brand:ce.border},ne.createElement(_e,{color:d===1?ce.brand:ce.muted},"Yes")))):null:null,E=i==="discord"?"Discord Setup":"Telegram Setup";return ne.createElement(qe,{flexDirection:"column",borderStyle:"round",borderColor:ce.border,paddingX:2,paddingY:1,width:60},ne.createElement(qe,{marginBottom:1,justifyContent:"space-between"},ne.createElement(_e,{bold:!0,color:ce.brand},E),C()),ne.createElement(qe,{marginBottom:1},ne.createElement(_e,{bold:!0,color:ce.text},h?.title)),v(),ne.createElement(qe,{marginTop:1,borderStyle:"single",borderTop:!0,borderColor:ce.border,paddingTop:1},ne.createElement(_e,{color:ce.dim},h?.type==="confirm"?"← → or y/n to select • enter to confirm • esc to cancel":h?.type==="loading"?"Please wait...":"enter to continue • esc to cancel")))}var Rg=NS(BS);import De,{memo as WS,useMemo as ni}from"react";import{Box as hn,Text as fn}from"@jrichman/ink";var Og=(i,e=60)=>i.length>e?i.substring(0,e)+"...":i;function HS({regularQueuedMessages:i,crossDeviceTasks:e}){let t=ni(()=>i.length===0?null:i.map((o,a)=>De.createElement(hn,{key:o.id,borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,marginBottom:1},De.createElement(hn,null,De.createElement(fn,{color:"whiteBright",bold:!0},a+1),De.createElement(fn,{color:"#6B7280"}," • "),De.createElement(fn,{color:"#9CA3AF"},Og(o.content))))),[i]),n=ni(()=>e.length===0?null:e.map((o,a)=>De.createElement(hn,{key:`cross-${o.id}`,borderStyle:"round",borderColor:"#0E7490",paddingX:2,paddingY:0,marginBottom:1},De.createElement(hn,null,De.createElement(fn,{color:"#22D3EE",bold:!0},"[M] ",a+1),De.createElement(fn,{color:"#6B7280"}," - "),De.createElement(fn,{color:"#9CA3AF"},Og(o.content))))),[e]),s=ni(()=>{let o=i.length;return`${o} message${o>1?"s":""} queued`},[i.length]),r=ni(()=>{let o=e.length;return`${o} cross-device task${o>1?"s":""} waiting`},[e.length]);return De.createElement(De.Fragment,null,t&&De.createElement(hn,{flexDirection:"column",paddingX:2,marginBottom:1},t,De.createElement(hn,null,De.createElement(fn,{color:"#9CA3AF"},s))),n&&De.createElement(hn,{flexDirection:"column",paddingX:2,marginBottom:1},n,De.createElement(hn,null,De.createElement(fn,{color:"#22D3EE"},r))))}var Ng=WS(HS,(i,e)=>i.regularQueuedMessages.length===e.regularQueuedMessages.length&&i.crossDeviceTasks.length===e.crossDeviceTasks.length&&i.regularQueuedMessages.every((t,n)=>t.id===e.regularQueuedMessages[n]?.id)&&i.crossDeviceTasks.every((t,n)=>t.id===e.crossDeviceTasks[n]?.id));import Q,{memo as GS,useMemo as $g}from"react";import{Box as st,Text as ge}from"@jrichman/ink";import Fg from"path";import et,{memo as si}from"react";import{Box as yr,Text as qt}from"@jrichman/ink";var ri={normal:{symbol:"",label:"",color:A.text.primary,description:"Normal mode"},yolo:{symbol:"*",label:"YOLO",color:A.status.error,description:"Auto-approve all actions"},plan:{symbol:">",label:"PLAN",color:A.status.success,description:"Planning mode - no execution"},shell:{symbol:"!",label:"SHELL",color:A.status.warning,description:"Shell command mode"},auto:{symbol:">",label:"AUTO",color:A.status.warning,description:"Auto-accept suggestions"}},aU=si(function({mode:e,showLabel:t=!1,size:n="normal"}){if(e==="normal")return null;let s=ri[e];return n==="compact"?et.createElement(qt,{color:s.color,bold:!0},s.symbol):et.createElement(yr,{flexDirection:"row",alignItems:"center"},et.createElement(qt,{color:s.color,bold:!0},s.symbol),t&&et.createElement(yr,{marginLeft:1},et.createElement(qt,{color:s.color,bold:!0},s.label)))}),cU=si(function({mode:e,isActive:t=!0}){if(e==="normal")return null;let n=ri[e],s=t?n.color:A.ui.muted;return et.createElement(qt,{color:s,bold:t},"[",n.label,"]")}),lU=si(function({selectedMode:e,availableModes:t=["normal","yolo","plan","auto"],isFocused:n=!1}){return et.createElement(yr,{flexDirection:"row",alignItems:"center"},et.createElement(qt,{color:A.text.secondary},"Mode: "),t.map((s,r)=>{let o=ri[s],a=s===e,c=s==="normal"?"NORMAL":o.label;return et.createElement(yr,{key:s,flexDirection:"row"},r>0&&et.createElement(qt,{color:A.ui.muted}," | "),et.createElement(qt,{color:a?o.color:A.ui.muted,bold:a,inverse:a&&n},c))}))}),_g=si(function({mode:e,promptSymbol:t="❯",isFocused:n=!0}){let s=ri[e],r=e!=="normal",o=r?s.color:n?A.text.accent:A.ui.muted;return et.createElement(yr,{flexDirection:"row",alignItems:"center"},r&&et.createElement(qt,{color:s.color,bold:!0},s.symbol),et.createElement(qt,{color:o},t))});var jS=" Type your message or @path/to/file";function zS({input:i,isLoading:e,pastedTexts:t,cursorPosition:n,suggestion:s,mode:r="normal"}){let{hasContent:o,ghostText:a}=$g(()=>{let l=i.length>0||t.length>0,d=s&&s.toLowerCase().startsWith(i.toLowerCase())&&i.length>0?s.slice(i.length):null;return{hasContent:l,ghostText:d}},[i,t.length,s]),c=$g(()=>t.length===0?null:t.map((l,d)=>{if(l.type==="clipboard_image"){let p=l.fileSize?` ${dn(l.fileSize)}`:"",h=!!l.error;return Q.createElement(st,{key:`pasted-${l.id}`,flexDirection:"column"},Q.createElement(st,null,Q.createElement(ge,{color:h?A.status.error:A.status.info}," ","[CLIPBOARD] "),Q.createElement(ge,{color:h?A.status.error:A.text.secondary},"Image"),p&&Q.createElement(ge,{color:A.ui.muted},p)),h&&Q.createElement(st,{marginLeft:4},Q.createElement(ge,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}if(l.type==="image_path"&&l.filePath){let p=Qa(Fg.basename(l.filePath)),h=l.fileSize?` ${dn(l.fileSize)}`:"",f=!!l.error;return Q.createElement(st,{key:`pasted-${l.id}`,flexDirection:"column"},Q.createElement(st,null,Q.createElement(ge,{color:f?A.status.error:A.status.info}," ","[IMG] "),Q.createElement(ge,{color:f?A.status.error:A.text.secondary},p),h&&Q.createElement(ge,{color:A.ui.muted},h)),f&&Q.createElement(st,{marginLeft:4},Q.createElement(ge,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}if(l.type==="file_path"&&l.filePath){let p=Qa(Fg.basename(l.filePath)),h=l.fileSize?` ${dn(l.fileSize)}`:"",f=!!l.error;return Q.createElement(st,{key:`pasted-${l.id}`,flexDirection:"column"},Q.createElement(st,null,Q.createElement(ge,{color:f?A.status.error:A.status.info}," ","[FILE] "),Q.createElement(ge,{color:f?A.status.error:A.text.secondary},p),h&&Q.createElement(ge,{color:A.ui.muted},h)),f&&Q.createElement(st,{marginLeft:4},Q.createElement(ge,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}let g=l.lineCount-1,m=g>0?`+${g} lines`:"1 line";return Q.createElement(st,{key:`pasted-${l.id}`},Q.createElement(ge,{color:A.ui.muted}," ","[TEXT] "),Q.createElement(ge,{color:A.text.secondary},"Pasted text #",d+1),Q.createElement(ge,{color:A.ui.muted}," (",m,")"))}),[t]);return Q.createElement(st,{borderStyle:"round",borderColor:o?A.border.focused:A.border.default,paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},c&&Q.createElement(st,{flexDirection:"column",marginBottom:0},c),Q.createElement(st,null,Q.createElement(_g,{mode:r,isFocused:!e}),Q.createElement(ge,null," "),i.length===0&&!e?s?Q.createElement(ge,null,Q.createElement(ge,{inverse:!0}," "),Q.createElement(ge,{color:A.ui.muted},s),Q.createElement(ge,{color:A.ui.muted,dimColor:!0}," (Tab to accept)")):Q.createElement(ge,{color:A.ui.muted},jS):Q.createElement(ge,null,Q.createElement(ge,{color:A.text.primary},i.slice(0,n)),!e&&Q.createElement(ge,{inverse:!0}," "),Q.createElement(ge,{color:A.text.primary},i.slice(n)),a&&Q.createElement(ge,{color:A.ui.muted},a))))}var Lg=GS(zS,(i,e)=>i.input===e.input&&i.isLoading===e.isLoading&&i.cursorPosition===e.cursorPosition&&i.suggestion===e.suggestion&&i.mode===e.mode&&i.pastedTexts.length===e.pastedTexts.length&&i.pastedTexts.every((t,n)=>t.id===e.pastedTexts[n]?.id));import vr,{useState as qS,useEffect as KS,useRef as VS,memo as XS}from"react";import{Box as YS,Text as vc}from"@jrichman/ink";import QS from"ink-spinner";function JS(i){if(i<60)return`${i}s`;let e=Math.floor(i/60),t=i%60;return`${e}m ${t}s`}function ZS({isLoading:i,phrase:e="Processing",startTime:t}){let[n,s]=qS(0),r=VS(null);return KS(()=>{if(r.current&&(clearInterval(r.current),r.current=null),!i){s(0);return}let o=t||Date.now();return r.current=setInterval(()=>{let a=Date.now(),c=Math.floor((a-o)/1e3);s(c)},1e3),()=>{r.current&&(clearInterval(r.current),r.current=null)}},[i,t]),i?vr.createElement(YS,{flexDirection:"row",alignItems:"center",paddingX:2,marginBottom:1,flexShrink:0},vr.createElement(vc,{color:A.text.accent},vr.createElement(QS,{type:"dots"})),vr.createElement(vc,{color:A.text.primary}," ",e,"... "),vr.createElement(vc,{color:A.text.secondary},"(esc to cancel",n>0?`, ${JS(n)}`:"",")")):null}var Ug=XS(ZS);import we,{memo as aw,useMemo as Kg}from"react";import{Box as Ts,Text as rt}from"@jrichman/ink";import{useState as Bg,useEffect as Wg,useCallback as ew,useRef as Hg}from"react";import{useStdout as tw}from"@jrichman/ink";var Ss=80,ws=24,nw=100;function oi(i){let{debounceMs:e=nw}=i||{},{stdout:t}=tw(),[n,s]=Bg({width:t?.columns||Ss,height:t?.rows||ws,rows:t?.rows||ws,columns:t?.columns||Ss}),[r,o]=Bg(!1),a=Hg(null),c=Hg(null);Wg(()=>{function d(){o(!0),a.current&&clearTimeout(a.current),c.current&&clearTimeout(c.current),a.current=setTimeout(()=>{let g=process.stdout.columns||Ss,m=process.stdout.rows||ws;s(p=>p.width!==g||p.height!==m?{width:g,height:m,rows:m,columns:g}:p),c.current=setTimeout(()=>{o(!1)},50)},e)}return process.stdout.on("resize",d),()=>{process.stdout.off("resize",d),a.current&&clearTimeout(a.current),c.current&&clearTimeout(c.current)}},[e]),Wg(()=>{if(t){let d=t.columns||Ss,g=t.rows||ws;(d!==n.width||g!==n.height)&&s({width:d,height:g,rows:g,columns:d})}},[t?.columns,t?.rows]);let l=ew(()=>{s({width:process.stdout.columns||Ss,height:process.stdout.rows||ws,rows:process.stdout.rows||ws,columns:process.stdout.columns||Ss})},[]);return{...n,isResizing:r,refresh:l}}Po();import{useState as bn,useEffect as Gg,useRef as sw,useCallback as rw}from"react";function jg(i=1e4){let[e,t]=bn("not-ready"),[n,s]=bn(!1),[r,o]=bn(!1),[a,c]=bn(0),[l,d]=bn(5),[g,m]=bn(0),[p,h]=bn(!1),[f,y]=bn(!1),T=sw(!1),x=rw(w=>{w.isInitializing||w.initState==="initializing"?t("initializing"):w.isRunning&&w.isInitialized?t("ready"):t("not-ready"),s(w.hasBrowser??!1),o(w.multiAgentMode??!1),c(w.runningAgentCount??0),d(w.maxConcurrentAgents??5),m(w.tabCount??0),h(w.isExecuting??!1),y(w.hasActiveSession??!1)},[]);return Gg(()=>{let w=te.onStatusChange(C=>{x(C)});return()=>w()},[x]),Gg(()=>{let w=()=>{let v=te.getStatus();v.initState==="idle"&&!T.current&&(T.current=!0,te.initialize().catch(E=>{console.debug("[useBrowserStatus] Auto-init failed:",E.message)}),v=te.getStatus()),x(v)};w();let C=setInterval(w,i);return()=>clearInterval(C)},[i,x]),{status:e,hasBrowser:n,multiAgentMode:r,runningAgentCount:a,maxConcurrentAgents:l,tabCount:g,isExecuting:p,hasActiveSession:f}}import{useState as ii,useEffect as ow,useCallback as zg}from"react";var iw=300*1e3;function qg(){let[i,e]=ii(null),[t,n]=ii(null),[s,r]=ii(!1),[o,a]=ii(null),c=zg(async(m=!1)=>{r(!0),a(null);try{let p=await ur.fetchQuotaStatus(m);e(p);let h=await ur.getUsageDisplayData();n(h)}catch(p){a(p instanceof Error?p.message:"Failed to fetch quota")}finally{r(!1)}},[]),l=zg(async()=>{await c(!0)},[c]);ow(()=>{c();let m=setInterval(()=>{c(!0)},iw);return()=>clearInterval(m)},[c]);let d=t?eg(t.percent):"normal",g=t?dr(t.resetsAt,t.resetsInSeconds):"";return{quota:i,usageDisplay:t,severity:d,resetTimeDisplay:g,isLoading:s,error:o,refresh:l}}wn();import{createRequire as cw}from"module";var lw=cw(import.meta.url),uw=lw("../package.json"),dw=uw.version,gw={3:"#FFD700",2:"#A78BFA",1:"#60A5FA",0:A.ui.muted},mw={ready:"#10B981",initializing:"#F59E0B","not-ready":"#F97316"},pw={normal:A.ui.muted,notice:"#60A5FA",warning:"#FBBF24",high:"#F97316",critical:"#EF4444"};function hw(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function fw(i,e){if(i.length<=e)return i;let t=i.split("/");if(t.length<=2)return i.slice(0,e-3)+"...";let n=t[0]+"/.../"+t[t.length-1];return n.length>e&&(n=".../"+t[t.length-1]),n.length>e&&(n=n.slice(0,e-3)+"..."),n}function bw({cwd:i,selectedModel:e,showScrollHint:t=!1,tier:n=0}){let{width:s}=oi(),{status:r}=jg(),{usageDisplay:o,severity:a,resetTimeDisplay:c}=qg(),l=xe.getDisplayName(n),d=gw[n]||A.ui.muted,{displayPath:g,shortcuts:m}=Kg(()=>{let h=`${e.displayName} /model`,f=" ● browser",y=t?"? help · Shift+↑↓ scroll":"? help",x=h.length+f.length+y.length+" ".length*2+4,w=Math.max(15,Math.floor((s-x)*.4));return{displayPath:fw(hw(i),w),shortcuts:y}},[i,e.displayName,t,s]),p=Kg(()=>{if(!o)return null;let{percent:h,type:f}=o,y=f==="weekly"?"weekly":"5-hour";return h>=100?`You've hit your ${y} limit`:h>=90?`${h}% of ${y} limit used`:`${h}% ${y} usage`},[o]);return we.createElement(Ts,{flexDirection:"column",width:"100%"},o&&we.createElement(Ts,{paddingX:2,justifyContent:"center"},we.createElement(rt,{color:pw[a]},p),c&&we.createElement(we.Fragment,null,we.createElement(rt,{color:A.ui.muted}," · "),we.createElement(rt,{color:A.ui.muted},"Resets in ",c))),we.createElement(Ts,{paddingX:2,paddingY:0,width:"100%",justifyContent:"space-between",flexDirection:"row"},we.createElement(Ts,null,we.createElement(rt,{color:A.text.link},g),we.createElement(rt,{color:A.ui.muted}," v",dw),we.createElement(rt,{color:A.ui.muted}," · "),we.createElement(rt,{color:d,bold:!0},l)),we.createElement(Ts,null,we.createElement(rt,{color:A.text.accent},e.displayName),we.createElement(rt,{color:A.text.secondary}," /model"),we.createElement(rt,{color:A.text.secondary}," "),we.createElement(rt,{color:mw[r]},"●"),we.createElement(rt,{color:A.text.secondary}," browser")),we.createElement(Ts,null,we.createElement(rt,{color:A.text.secondary},m))))}var Vg=aw(bw);import xc,{memo as Cc}from"react";import{Box as Vw}from"@jrichman/ink";import ie,{memo as Hw,useMemo as om}from"react";import{Box as at,Text as bt}from"@jrichman/ink";import xs,{memo as yw}from"react";import{Box as ai,Text as Xg}from"@jrichman/ink";function vw({suggestions:i,onSelect:e}){return i.length===0?null:xs.createElement(ai,{flexDirection:"column",marginTop:1,width:"100%"},i.map((t,n)=>xs.createElement(ai,{key:`sug-block-${n}`,flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},t.options.map((s,r)=>xs.createElement(ai,{key:`sug-opt-${n}-${r}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},xs.createElement(Xg,{color:"#22D3EE"},s))))),e&&xs.createElement(ai,{marginTop:0,width:"100%"},xs.createElement(Xg,{color:"#6B7280"},"Type a suggestion to use it")))}var Yg=yw(vw,(i,e)=>i.suggestions===e.suggestions?!0:i.suggestions.length!==e.suggestions.length?!1:i.suggestions.every((t,n)=>{let s=e.suggestions[n];return t.options.length===s.options.length&&t.options.every((r,o)=>r===s.options[o])}));import Bn,{memo as Sw}from"react";import{Box as ci,Text as Sc}from"@jrichman/ink";function ww({workingFiles:i}){return i.length===0?null:Bn.createElement(ci,{flexDirection:"column",marginTop:1,width:"100%"},Bn.createElement(ci,{marginBottom:0,width:"100%"},Bn.createElement(Sc,{color:"#9CA3AF",bold:!0},"Working Files"),Bn.createElement(Sc,{color:"#6B7280"}," (",i.length,")")),Bn.createElement(ci,{flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},i.map(e=>Bn.createElement(ci,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},Bn.createElement(Sc,{color:"white"},e.name)))))}var Qg=Sw(ww,(i,e)=>i.workingFiles===e.workingFiles?!0:i.workingFiles.length!==e.workingFiles.length?!1:i.workingFiles.every((t,n)=>t.path===e.workingFiles[n].path));import ot,{memo as Tw,useMemo as xw,useState as Cw}from"react";import{Box as Sr,Text as yn}from"@jrichman/ink";var wc=5;function Ew({conversationHistory:i,onSelect:e}){let[t,n]=Cw(!1),{displayedItems:s,hiddenCount:r}=xw(()=>i.length<=wc||t?{displayedItems:i,hiddenCount:0}:{displayedItems:i.slice(0,wc),hiddenCount:i.length-wc},[i,t]);return i.length===0?null:ot.createElement(Sr,{flexDirection:"column",marginTop:1},ot.createElement(Sr,{marginBottom:0},ot.createElement(yn,{color:A.text.secondary},"💬 "),ot.createElement(yn,{color:A.text.secondary,bold:!0},i.length," conversation",i.length!==1?"s":""," found")),ot.createElement(Sr,{flexDirection:"column",paddingLeft:2},s.map((o,a)=>ot.createElement(Sr,{key:`conv-${o.id}-${a}`},ot.createElement(yn,{color:A.ui.muted},"• "),ot.createElement(yn,{color:A.text.primary},o.title),ot.createElement(yn,{color:A.ui.muted}," ("),ot.createElement(yn,{color:A.text.link},Iw(o.id)),ot.createElement(yn,{color:A.ui.muted},")"))),r>0&&ot.createElement(Sr,{marginTop:0},ot.createElement(yn,{color:A.text.accent},"+",r," more conversation",r!==1?"s":""))))}function Iw(i,e=20){return i.length<=e?i:i.slice(0,e-3)+"..."}var Jg=Tw(Ew);import K,{memo as kw,useMemo as Pw}from"react";import{Box as it,Text as re}from"@jrichman/ink";wn();import{createRequire as Aw}from"module";var Dw=Aw(import.meta.url),Mw=Dw("../package.json"),Rw=Mw.version;function Ow(i){switch(i){case 3:return"#FFD700";case 2:return"#A78BFA";case 1:return"#60A5FA";default:return A.ui.muted}}function Nw(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function _w(){let i="#E8B4B8",e="#B8E4E8",t="#4A4A4A";return K.createElement(it,{flexDirection:"column"},K.createElement(it,null,K.createElement(re,{color:i},"██"),K.createElement(re,null," "),K.createElement(re,{color:i},"██"),K.createElement(re,null," "),K.createElement(re,{color:i},"██")),K.createElement(it,null,K.createElement(re,{color:i},"██████████")),K.createElement(it,null,K.createElement(re,{color:i},"██"),K.createElement(re,{color:e},"██████"),K.createElement(re,{color:i},"██")),K.createElement(it,null,K.createElement(re,{color:i},"██"),K.createElement(re,{color:t},"██"),K.createElement(re,{color:e},"██"),K.createElement(re,{color:t},"██"),K.createElement(re,{color:i},"██")),K.createElement(it,null,K.createElement(re,{color:i},"██"),K.createElement(re,{color:e},"██████"),K.createElement(re,{color:i},"██")),K.createElement(it,null,K.createElement(re,{color:i},"████"),K.createElement(re,{color:t},"██"),K.createElement(re,{color:i},"████")),K.createElement(it,null,K.createElement(re,{color:i}," ██████ ")))}function $w({projectPath:i,variant:e="main",tier:t=0}){let n=Pw(()=>i?Nw(i):null,[i]),s=xe.getDisplayName(t),r=Ow(t);return e==="main"?K.createElement(it,{flexDirection:"row",paddingX:1,marginY:1,gap:2},K.createElement(_w,null),K.createElement(it,{flexDirection:"column",justifyContent:"center"},K.createElement(it,null,K.createElement(re,{color:A.colors.AccentPurple,bold:!0},"Orion"),K.createElement(re,{color:A.ui.muted}," v",Rw),K.createElement(re,{color:A.ui.muted}," · "),K.createElement(re,{color:r,bold:!0},"Orion ",s)),K.createElement(re,{color:A.text.secondary},"Your partner in getting things done."),K.createElement(re,{color:A.text.secondary,dimColor:!0},"More done, more sleep."),n&&K.createElement(it,{marginTop:1},K.createElement(re,{color:A.ui.muted},n)))):K.createElement(it,{paddingX:1,marginY:1},K.createElement(re,{color:A.colors.AccentPurple},"● "),e==="fresh"&&K.createElement(re,{color:A.text.secondary},"Ready when you are."),e==="continue"&&K.createElement(re,{color:A.text.secondary},"Picking up where we left off."),e==="new"&&K.createElement(re,{color:A.text.secondary},"New conversation started."))}var Zg=kw($w);function em(i){return i.includes("Orion ready")||i.includes("Fresh start")||i.includes("Welcome back")||i.includes("New conversation")||i.includes("Conversation cleared")}function tm(i){let e=i.match(/📁\s*(.+)/),t=e?e[1].trim():void 0;return i.includes("Fresh start")||i.includes("Conversation cleared")?{variant:"fresh",projectPath:t}:i.includes("Welcome back")?{variant:"continue",projectPath:t}:i.includes("New conversation")?{variant:"new",projectPath:t}:{variant:"main",projectPath:t}}import Ke,{memo as li,useMemo as Fw}from"react";import{Box as Cs,Text as Wn}from"@jrichman/ink";var he={javascript:{keywords:["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","new","class","extends","import","export","default","from","async","await","yield","static","get","set","typeof","instanceof","in","of","delete","void","this","super","with","debugger"],types:["Array","Object","String","Number","Boolean","Function","Promise","Map","Set","Date","RegExp","Error","Symbol","BigInt","null","undefined","true","false","NaN","Infinity"],stringDelimiters:["'",'"',"`"],commentSingle:"//",commentMultiStart:"/*",commentMultiEnd:"*/"},typescript:{keywords:["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","new","class","extends","import","export","default","from","async","await","yield","static","get","set","typeof","instanceof","in","of","delete","void","this","super","type","interface","enum","namespace","module","declare","abstract","implements","private","protected","public","readonly","as","is","keyof","infer","never","unknown","any"],types:["Array","Object","String","Number","Boolean","Function","Promise","Map","Set","Date","RegExp","Error","Symbol","BigInt","null","undefined","true","false","void","Partial","Required","Readonly","Record","Pick","Omit","Exclude","Extract","NonNullable","ReturnType","InstanceType","Parameters"],stringDelimiters:["'",'"',"`"],commentSingle:"//",commentMultiStart:"/*",commentMultiEnd:"*/"},python:{keywords:["def","class","return","if","elif","else","for","while","break","continue","try","except","finally","raise","import","from","as","with","assert","yield","lambda","pass","del","global","nonlocal","and","or","not","in","is","async","await","match","case"],types:["None","True","False","int","float","str","list","dict","tuple","set","bool","bytes","object","type","Exception"],builtins:["print","len","range","enumerate","zip","map","filter","sorted","reversed","sum","min","max","abs","round","open","input","isinstance","hasattr","getattr","setattr","super","property","staticmethod","classmethod"],stringDelimiters:["'",'"',"'''",'"""'],commentSingle:"#"},bash:{keywords:["if","then","else","elif","fi","for","while","do","done","case","esac","in","function","return","exit","break","continue","export","local","readonly","declare","unset","shift","source","eval","exec","trap","set","shopt"],builtins:["echo","cd","pwd","ls","cat","grep","sed","awk","find","xargs","sort","uniq","head","tail","wc","cut","tr","mkdir","rm","cp","mv","touch","chmod","chown","curl","wget","git","npm","yarn","pnpm","node","python","pip"],stringDelimiters:["'",'"'],commentSingle:"#"},rust:{keywords:["fn","let","mut","const","static","if","else","match","for","while","loop","break","continue","return","struct","enum","impl","trait","type","where","use","mod","pub","crate","self","super","as","in","ref","move","async","await","dyn","unsafe","extern"],types:["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","bool","char","str","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","true","false","Some","None","Ok","Err","Self"],stringDelimiters:['"'],commentSingle:"//",commentMultiStart:"/*",commentMultiEnd:"*/"},go:{keywords:["func","return","if","else","for","range","switch","case","default","break","continue","goto","fallthrough","defer","go","select","chan","var","const","type","struct","interface","map","package","import"],types:["int","int8","int16","int32","int64","uint","uint8","uint16","uint32","uint64","uintptr","float32","float64","complex64","complex128","bool","byte","rune","string","error","nil","true","false","iota"],builtins:["make","new","len","cap","append","copy","delete","close","panic","recover","print","println"],stringDelimiters:['"',"'","`"],commentSingle:"//",commentMultiStart:"/*",commentMultiEnd:"*/"},json:{keywords:[],types:["true","false","null"],stringDelimiters:['"']},yaml:{keywords:[],types:["true","false","null","yes","no","on","off"],stringDelimiters:["'",'"'],commentSingle:"#"},sql:{keywords:["SELECT","FROM","WHERE","AND","OR","NOT","IN","LIKE","BETWEEN","IS","NULL","ORDER","BY","ASC","DESC","LIMIT","OFFSET","JOIN","LEFT","RIGHT","INNER","OUTER","ON","AS","GROUP","HAVING","DISTINCT","COUNT","SUM","AVG","MIN","MAX","INSERT","INTO","VALUES","UPDATE","SET","DELETE","CREATE","TABLE","DROP","ALTER","INDEX","PRIMARY","KEY","FOREIGN","REFERENCES","CONSTRAINT","UNIQUE","DEFAULT","CASCADE","UNION","ALL","EXISTS","CASE","WHEN","THEN","ELSE","END","COALESCE","NULLIF","CAST"],types:["INT","INTEGER","VARCHAR","TEXT","BOOLEAN","DATE","TIMESTAMP","FLOAT","DOUBLE","DECIMAL","BIGINT","SMALLINT","CHAR","BLOB","JSON","UUID"],stringDelimiters:["'"],commentSingle:"--",commentMultiStart:"/*",commentMultiEnd:"*/"}};he.ts=he.typescript;he.js=he.javascript;he.jsx=he.javascript;he.tsx=he.typescript;he.py=he.python;he.sh=he.bash;he.shell=he.bash;he.zsh=he.bash;he.rs=he.rust;he.golang=he.go;he.yml=he.yaml;function Lw(i,e){let t=[],n=0;for(;n<i.length;){if(e.commentSingle&&i.slice(n).startsWith(e.commentSingle)){t.push({type:"comment",value:i.slice(n)});break}let s=!1;for(let c of e.stringDelimiters)if(i.slice(n).startsWith(c)){let l=i.indexOf(c,n+c.length);if(l!==-1){t.push({type:"string",value:i.slice(n,l+c.length)}),n=l+c.length,s=!0;break}else{t.push({type:"string",value:i.slice(n)}),n=i.length,s=!0;break}}if(s)continue;let r=i.slice(n).match(/^-?\d+(\.\d+)?([eE][+-]?\d+)?/);if(r&&(n===0||/[\s\(\[\{,;:=<>!&|+\-*/%]/.test(i[n-1]))){t.push({type:"number",value:r[0]}),n+=r[0].length;continue}let o=i.slice(n).match(/^[a-zA-Z_$][a-zA-Z0-9_$]*/);if(o){let c=o[0],l="plain";e.keywords.includes(c)?l="keyword":e.types?.includes(c)?l="type":(e.builtins?.includes(c)||i[n+c.length]==="(")&&(l="function"),t.push({type:l,value:c}),n+=c.length;continue}let a=i.slice(n).match(/^(===|!==|==|!=|<=|>=|=>|->|&&|\|\||<<|>>|\+\+|--|[+\-*/%=<>!&|^~?:])/);if(a){t.push({type:"operator",value:a[0]}),n+=a[0].length;continue}if(/^[(){}\[\];,.]/.test(i[n])){t.push({type:"punctuation",value:i[n]}),n++;continue}t.push({type:"plain",value:i[n]}),n++}return t}var Uw={keyword:A.status.warning,string:A.status.success,comment:A.ui.comment,number:A.text.link,function:A.text.link,operator:A.text.primary,punctuation:A.ui.muted,type:A.status.info,plain:A.text.primary},Bw=li(function({line:e,language:t}){if(!t)return Ke.createElement(Wn,{color:A.text.primary},e);let n=Lw(e,t);return Ke.createElement(Wn,null,n.map((s,r)=>Ke.createElement(Wn,{key:r,color:Uw[s.type]},s.value)))}),Ww=li(function({code:e,language:t,showLineNumbers:n=!1,startLineNumber:s=1,maxLines:r}){let{lines:o,langDef:a,truncated:c}=Fw(()=>{let d=e.split(`
2593
- `),g=t?he[t.toLowerCase()]:void 0;return r&&d.length>r?{lines:d.slice(0,r),langDef:g,truncated:d.length-r}:{lines:d,langDef:g,truncated:0}},[e,t,r]),l=n?String(s+o.length-1).length:0;return Ke.createElement(Cs,{flexDirection:"column"},o.map((d,g)=>Ke.createElement(Cs,{key:g,flexDirection:"row"},n&&Ke.createElement(Cs,{width:l+2,flexShrink:0},Ke.createElement(Wn,{color:A.ui.muted},String(s+g).padStart(l," ")," │")),Ke.createElement(Cs,{flexGrow:1},Ke.createElement(Bw,{line:d,language:a})))),c>0&&Ke.createElement(Wn,{color:A.ui.muted}," ... ",c," more lines"))}),nm=li(function({code:e,language:t,showLanguageLabel:n=!0,showLineNumbers:s=!1,maxLines:r,showBorder:o=!0}){let a=t?.toLowerCase(),c=a&&he[a]?a:void 0;return Ke.createElement(Cs,{flexDirection:"column",borderStyle:o?"round":void 0,borderColor:o?A.border.default:void 0,paddingX:o?1:0},n&&c&&Ke.createElement(Cs,{marginBottom:0},Ke.createElement(Wn,{color:A.ui.muted,dimColor:!0},c)),Ke.createElement(Ww,{code:e,language:c,showLineNumbers:s,maxLines:r}))}),dB=li(function({children:e}){return Ke.createElement(Wn,{color:A.status.warning,bold:!1},"`",e,"`")});function sm(i){let e=[],t=/```(\w*)\n?([\s\S]*?)```/g,n=0,s;for(;(s=t.exec(i))!==null;)s.index>n&&e.push({type:"text",content:i.slice(n,s.index)}),e.push({type:"code",content:s[2].trim(),language:s[1]||void 0}),n=s.index+s[0].length;return n<i.length&&e.push({type:"text",content:i.slice(n)}),e}function rm(i){return/```[\s\S]*?```/.test(i)}var Gw=150;function im(i,e){return i.length<=e?{lines:i,truncated:!1}:{lines:i.slice(0,e),truncated:!0}}function jw({message:i,onSuggestionClick:e,maxLines:t=Gw}){let{role:n,content:s}=i,{userTier:r}=ir(),o=om(()=>{if(n!=="assistant")return null;let{suggestions:c,cleanedContent:l}=Er(s),{workingFiles:d,cleanedContent:g}=Nc(l),{conversationHistory:m,cleanedContent:p}=_c(g),f=$c(p).split(`
2592
+ Send /new to start`),y(D)}else t.addSystemMessage(`✗ Telegram setup failed: ${I.error}`)}}catch(I){t.addSystemMessage(`✗ Connection error: ${I.message}`)}e.resetWizard()},[i,m,t,y,e]);OS(()=>{(i==="discord"&&n.step===5||i==="telegram"&&n.step===6)&&!c&&(l(!0),w(n.data))},[n.step,n.data,i,c,w]);let E=()=>{let S=Math.min(n.step,f),I="━".repeat(S),D="─".repeat(f-S);return se.createElement(Ke,null,se.createElement($e,{color:le.brand},I),se.createElement($e,{color:le.dim},D),se.createElement($e,{color:le.muted}," ",S,"/",f))},v=()=>h?h.type==="loading"?se.createElement(Ke,{flexDirection:"column",paddingY:1},se.createElement(Ke,null,se.createElement($e,{color:le.brand},se.createElement($S,{type:"dots"})),se.createElement($e,{color:le.muted}," Connecting to ",i==="discord"?"Discord":"Telegram","..."))):h.type==="input"?se.createElement(Ke,{flexDirection:"column"},se.createElement($e,{color:le.text},h.help),se.createElement($e,{color:le.dim},h.hint),se.createElement(Ke,{marginTop:1,flexDirection:"column"},se.createElement(Ke,{paddingX:1,borderStyle:"round",borderColor:o?le.error:le.brand},se.createElement($e,{color:s?le.text:le.dim},s||h.placeholder||"Type here..."),se.createElement($e,{color:le.brand},"▎")),o&&se.createElement(Ke,{marginTop:1},se.createElement($e,{color:le.error},"✗ ",o)))):h.type==="confirm"?se.createElement(Ke,{flexDirection:"column"},se.createElement($e,{color:le.text},h.help),se.createElement($e,{color:le.dim},h.hint),se.createElement(Ke,{marginTop:1,gap:2},se.createElement(Ke,{paddingX:2,borderStyle:"round",borderColor:d===0?le.brand:le.border},se.createElement($e,{color:d===0?le.brand:le.muted},"No")),se.createElement(Ke,{paddingX:2,borderStyle:"round",borderColor:d===1?le.brand:le.border},se.createElement($e,{color:d===1?le.brand:le.muted},"Yes")))):null:null,x=i==="discord"?"Discord Setup":"Telegram Setup";return se.createElement(Ke,{flexDirection:"column",borderStyle:"round",borderColor:le.border,paddingX:2,paddingY:1,width:60},se.createElement(Ke,{marginBottom:1,justifyContent:"space-between"},se.createElement($e,{bold:!0,color:le.brand},x),E()),se.createElement(Ke,{marginBottom:1},se.createElement($e,{bold:!0,color:le.text},h?.title)),v(),se.createElement(Ke,{marginTop:1,borderStyle:"single",borderTop:!0,borderColor:le.border,paddingTop:1},se.createElement($e,{color:le.dim},h?.type==="confirm"?"← → or y/n to select • enter to confirm • esc to cancel":h?.type==="loading"?"Please wait...":"enter to continue • esc to cancel")))}var Rg=NS(BS);import Me,{memo as WS,useMemo as ni}from"react";import{Box as bn,Text as yn}from"@jrichman/ink";var Og=(i,e=60)=>i.length>e?i.substring(0,e)+"...":i;function HS({regularQueuedMessages:i,crossDeviceTasks:e}){let t=ni(()=>i.length===0?null:i.map((o,a)=>Me.createElement(bn,{key:o.id,borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,marginBottom:1},Me.createElement(bn,null,Me.createElement(yn,{color:"whiteBright",bold:!0},a+1),Me.createElement(yn,{color:"#6B7280"}," • "),Me.createElement(yn,{color:"#9CA3AF"},Og(o.content))))),[i]),n=ni(()=>e.length===0?null:e.map((o,a)=>Me.createElement(bn,{key:`cross-${o.id}`,borderStyle:"round",borderColor:"#0E7490",paddingX:2,paddingY:0,marginBottom:1},Me.createElement(bn,null,Me.createElement(yn,{color:"#22D3EE",bold:!0},"[M] ",a+1),Me.createElement(yn,{color:"#6B7280"}," - "),Me.createElement(yn,{color:"#9CA3AF"},Og(o.content))))),[e]),s=ni(()=>{let o=i.length;return`${o} message${o>1?"s":""} queued`},[i.length]),r=ni(()=>{let o=e.length;return`${o} cross-device task${o>1?"s":""} waiting`},[e.length]);return Me.createElement(Me.Fragment,null,t&&Me.createElement(bn,{flexDirection:"column",paddingX:2,marginBottom:1},t,Me.createElement(bn,null,Me.createElement(yn,{color:"#9CA3AF"},s))),n&&Me.createElement(bn,{flexDirection:"column",paddingX:2,marginBottom:1},n,Me.createElement(bn,null,Me.createElement(yn,{color:"#22D3EE"},r))))}var Ng=WS(HS,(i,e)=>i.regularQueuedMessages.length===e.regularQueuedMessages.length&&i.crossDeviceTasks.length===e.crossDeviceTasks.length&&i.regularQueuedMessages.every((t,n)=>t.id===e.regularQueuedMessages[n]?.id)&&i.crossDeviceTasks.every((t,n)=>t.id===e.crossDeviceTasks[n]?.id));import J,{memo as GS,useMemo as $g}from"react";import{Box as st,Text as ge}from"@jrichman/ink";import Fg from"path";import tt,{memo as si}from"react";import{Box as vr,Text as Kt}from"@jrichman/ink";var ri={normal:{symbol:"",label:"",color:A.text.primary,description:"Normal mode"},yolo:{symbol:"*",label:"YOLO",color:A.status.error,description:"Auto-approve all actions"},plan:{symbol:">",label:"PLAN",color:A.status.success,description:"Planning mode - no execution"},shell:{symbol:"!",label:"SHELL",color:A.status.warning,description:"Shell command mode"},auto:{symbol:">",label:"AUTO",color:A.status.warning,description:"Auto-accept suggestions"}},aU=si(function({mode:e,showLabel:t=!1,size:n="normal"}){if(e==="normal")return null;let s=ri[e];return n==="compact"?tt.createElement(Kt,{color:s.color,bold:!0},s.symbol):tt.createElement(vr,{flexDirection:"row",alignItems:"center"},tt.createElement(Kt,{color:s.color,bold:!0},s.symbol),t&&tt.createElement(vr,{marginLeft:1},tt.createElement(Kt,{color:s.color,bold:!0},s.label)))}),cU=si(function({mode:e,isActive:t=!0}){if(e==="normal")return null;let n=ri[e],s=t?n.color:A.ui.muted;return tt.createElement(Kt,{color:s,bold:t},"[",n.label,"]")}),lU=si(function({selectedMode:e,availableModes:t=["normal","yolo","plan","auto"],isFocused:n=!1}){return tt.createElement(vr,{flexDirection:"row",alignItems:"center"},tt.createElement(Kt,{color:A.text.secondary},"Mode: "),t.map((s,r)=>{let o=ri[s],a=s===e,c=s==="normal"?"NORMAL":o.label;return tt.createElement(vr,{key:s,flexDirection:"row"},r>0&&tt.createElement(Kt,{color:A.ui.muted}," | "),tt.createElement(Kt,{color:a?o.color:A.ui.muted,bold:a,inverse:a&&n},c))}))}),_g=si(function({mode:e,promptSymbol:t="❯",isFocused:n=!0}){let s=ri[e],r=e!=="normal",o=r?s.color:n?A.text.accent:A.ui.muted;return tt.createElement(vr,{flexDirection:"row",alignItems:"center"},r&&tt.createElement(Kt,{color:s.color,bold:!0},s.symbol),tt.createElement(Kt,{color:o},t))});var jS=" Type your message or @path/to/file";function zS({input:i,isLoading:e,pastedTexts:t,cursorPosition:n,suggestion:s,mode:r="normal"}){let{hasContent:o,ghostText:a}=$g(()=>{let l=i.length>0||t.length>0,d=s&&s.toLowerCase().startsWith(i.toLowerCase())&&i.length>0?s.slice(i.length):null;return{hasContent:l,ghostText:d}},[i,t.length,s]),c=$g(()=>t.length===0?null:t.map((l,d)=>{if(l.type==="clipboard_image"){let p=l.fileSize?` ${mn(l.fileSize)}`:"",h=!!l.error;return J.createElement(st,{key:`pasted-${l.id}`,flexDirection:"column"},J.createElement(st,null,J.createElement(ge,{color:h?A.status.error:A.status.info}," ","[CLIPBOARD] "),J.createElement(ge,{color:h?A.status.error:A.text.secondary},"Image"),p&&J.createElement(ge,{color:A.ui.muted},p)),h&&J.createElement(st,{marginLeft:4},J.createElement(ge,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}if(l.type==="image_path"&&l.filePath){let p=Qa(Fg.basename(l.filePath)),h=l.fileSize?` ${mn(l.fileSize)}`:"",f=!!l.error;return J.createElement(st,{key:`pasted-${l.id}`,flexDirection:"column"},J.createElement(st,null,J.createElement(ge,{color:f?A.status.error:A.status.info}," ","[IMG] "),J.createElement(ge,{color:f?A.status.error:A.text.secondary},p),h&&J.createElement(ge,{color:A.ui.muted},h)),f&&J.createElement(st,{marginLeft:4},J.createElement(ge,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}if(l.type==="file_path"&&l.filePath){let p=Qa(Fg.basename(l.filePath)),h=l.fileSize?` ${mn(l.fileSize)}`:"",f=!!l.error;return J.createElement(st,{key:`pasted-${l.id}`,flexDirection:"column"},J.createElement(st,null,J.createElement(ge,{color:f?A.status.error:A.status.info}," ","[FILE] "),J.createElement(ge,{color:f?A.status.error:A.text.secondary},p),h&&J.createElement(ge,{color:A.ui.muted},h)),f&&J.createElement(st,{marginLeft:4},J.createElement(ge,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}let g=l.lineCount-1,m=g>0?`+${g} lines`:"1 line";return J.createElement(st,{key:`pasted-${l.id}`},J.createElement(ge,{color:A.ui.muted}," ","[TEXT] "),J.createElement(ge,{color:A.text.secondary},"Pasted text #",d+1),J.createElement(ge,{color:A.ui.muted}," (",m,")"))}),[t]);return J.createElement(st,{borderStyle:"round",borderColor:o?A.border.focused:A.border.default,paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},c&&J.createElement(st,{flexDirection:"column",marginBottom:0},c),J.createElement(st,null,J.createElement(_g,{mode:r,isFocused:!e}),J.createElement(ge,null," "),i.length===0&&!e?s?J.createElement(ge,null,J.createElement(ge,{inverse:!0}," "),J.createElement(ge,{color:A.ui.muted},s),J.createElement(ge,{color:A.ui.muted,dimColor:!0}," (Tab to accept)")):J.createElement(ge,{color:A.ui.muted},jS):J.createElement(ge,null,J.createElement(ge,{color:A.text.primary},i.slice(0,n)),!e&&J.createElement(ge,{inverse:!0}," "),J.createElement(ge,{color:A.text.primary},i.slice(n)),a&&J.createElement(ge,{color:A.ui.muted},a))))}var Lg=GS(zS,(i,e)=>i.input===e.input&&i.isLoading===e.isLoading&&i.cursorPosition===e.cursorPosition&&i.suggestion===e.suggestion&&i.mode===e.mode&&i.pastedTexts.length===e.pastedTexts.length&&i.pastedTexts.every((t,n)=>t.id===e.pastedTexts[n]?.id));import Sr,{useState as qS,useEffect as KS,useRef as VS,memo as XS}from"react";import{Box as YS,Text as vc}from"@jrichman/ink";import QS from"ink-spinner";function JS(i){if(i<60)return`${i}s`;let e=Math.floor(i/60),t=i%60;return`${e}m ${t}s`}function ZS({isLoading:i,phrase:e="Processing",startTime:t}){let[n,s]=qS(0),r=VS(null);return KS(()=>{if(r.current&&(clearInterval(r.current),r.current=null),!i){s(0);return}let o=t||Date.now();return r.current=setInterval(()=>{let a=Date.now(),c=Math.floor((a-o)/1e3);s(c)},1e3),()=>{r.current&&(clearInterval(r.current),r.current=null)}},[i,t]),i?Sr.createElement(YS,{flexDirection:"row",alignItems:"center",paddingX:2,marginBottom:1,flexShrink:0},Sr.createElement(vc,{color:A.text.accent},Sr.createElement(QS,{type:"dots"})),Sr.createElement(vc,{color:A.text.primary}," ",e,"... "),Sr.createElement(vc,{color:A.text.secondary},"(esc to cancel",n>0?`, ${JS(n)}`:"",")")):null}var Ug=XS(ZS);import we,{memo as aw,useMemo as Kg}from"react";import{Box as Cs,Text as rt}from"@jrichman/ink";import{useState as Bg,useEffect as Wg,useCallback as ew,useRef as Hg}from"react";import{useStdout as tw}from"@jrichman/ink";var Ts=80,xs=24,nw=100;function oi(i){let{debounceMs:e=nw}=i||{},{stdout:t}=tw(),[n,s]=Bg({width:t?.columns||Ts,height:t?.rows||xs,rows:t?.rows||xs,columns:t?.columns||Ts}),[r,o]=Bg(!1),a=Hg(null),c=Hg(null);Wg(()=>{function d(){o(!0),a.current&&clearTimeout(a.current),c.current&&clearTimeout(c.current),a.current=setTimeout(()=>{let g=process.stdout.columns||Ts,m=process.stdout.rows||xs;s(p=>p.width!==g||p.height!==m?{width:g,height:m,rows:m,columns:g}:p),c.current=setTimeout(()=>{o(!1)},50)},e)}return process.stdout.on("resize",d),()=>{process.stdout.off("resize",d),a.current&&clearTimeout(a.current),c.current&&clearTimeout(c.current)}},[e]),Wg(()=>{if(t){let d=t.columns||Ts,g=t.rows||xs;(d!==n.width||g!==n.height)&&s({width:d,height:g,rows:g,columns:d})}},[t?.columns,t?.rows]);let l=ew(()=>{s({width:process.stdout.columns||Ts,height:process.stdout.rows||xs,rows:process.stdout.rows||xs,columns:process.stdout.columns||Ts})},[]);return{...n,isResizing:r,refresh:l}}Po();import{useState as vn,useEffect as Gg,useRef as sw,useCallback as rw}from"react";function jg(i=1e4){let[e,t]=vn("not-ready"),[n,s]=vn(!1),[r,o]=vn(!1),[a,c]=vn(0),[l,d]=vn(5),[g,m]=vn(0),[p,h]=vn(!1),[f,y]=vn(!1),T=sw(!1),C=rw(w=>{w.isInitializing||w.initState==="initializing"?t("initializing"):w.isRunning&&w.isInitialized?t("ready"):t("not-ready"),s(w.hasBrowser??!1),o(w.multiAgentMode??!1),c(w.runningAgentCount??0),d(w.maxConcurrentAgents??5),m(w.tabCount??0),h(w.isExecuting??!1),y(w.hasActiveSession??!1)},[]);return Gg(()=>{let w=ne.onStatusChange(E=>{C(E)});return()=>w()},[C]),Gg(()=>{let w=()=>{let v=ne.getStatus();v.initState==="idle"&&!T.current&&(T.current=!0,ne.initialize().catch(x=>{console.debug("[useBrowserStatus] Auto-init failed:",x.message)}),v=ne.getStatus()),C(v)};w();let E=setInterval(w,i);return()=>clearInterval(E)},[i,C]),{status:e,hasBrowser:n,multiAgentMode:r,runningAgentCount:a,maxConcurrentAgents:l,tabCount:g,isExecuting:p,hasActiveSession:f}}import{useState as ii,useEffect as ow,useCallback as zg}from"react";var iw=300*1e3;function qg(){let[i,e]=ii(null),[t,n]=ii(null),[s,r]=ii(!1),[o,a]=ii(null),c=zg(async(m=!1)=>{r(!0),a(null);try{let p=await dr.fetchQuotaStatus(m);e(p);let h=await dr.getUsageDisplayData();n(h)}catch(p){a(p instanceof Error?p.message:"Failed to fetch quota")}finally{r(!1)}},[]),l=zg(async()=>{await c(!0)},[c]);ow(()=>{c();let m=setInterval(()=>{c(!0)},iw);return()=>clearInterval(m)},[c]);let d=t?eg(t.percent):"normal",g=t?gr(t.resetsAt,t.resetsInSeconds):"";return{quota:i,usageDisplay:t,severity:d,resetTimeDisplay:g,isLoading:s,error:o,refresh:l}}xn();import{createRequire as cw}from"module";var lw=cw(import.meta.url),uw=lw("../package.json"),dw=uw.version,gw={3:"#FFD700",2:"#A78BFA",1:"#60A5FA",0:A.ui.muted},mw={ready:"#10B981",initializing:"#F59E0B","not-ready":"#F97316"},pw={normal:A.ui.muted,notice:"#60A5FA",warning:"#FBBF24",high:"#F97316",critical:"#EF4444"};function hw(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function fw(i,e){if(i.length<=e)return i;let t=i.split("/");if(t.length<=2)return i.slice(0,e-3)+"...";let n=t[0]+"/.../"+t[t.length-1];return n.length>e&&(n=".../"+t[t.length-1]),n.length>e&&(n=n.slice(0,e-3)+"..."),n}function bw({cwd:i,selectedModel:e,showScrollHint:t=!1,tier:n=0}){let{width:s}=oi(),{status:r}=jg(),{usageDisplay:o,severity:a,resetTimeDisplay:c}=qg(),l=Ce.getDisplayName(n),d=gw[n]||A.ui.muted,{displayPath:g,shortcuts:m}=Kg(()=>{let h=`${e.displayName} /model`,f=" ● browser",y=t?"? help · Shift+↑↓ scroll":"? help",C=h.length+f.length+y.length+" ".length*2+4,w=Math.max(15,Math.floor((s-C)*.4));return{displayPath:fw(hw(i),w),shortcuts:y}},[i,e.displayName,t,s]),p=Kg(()=>{if(!o)return null;let{percent:h,type:f}=o,y=f==="weekly"?"weekly":"5-hour";return h>=100?`You've hit your ${y} limit`:h>=90?`${h}% of ${y} limit used`:`${h}% ${y} usage`},[o]);return we.createElement(Cs,{flexDirection:"column",width:"100%"},o&&we.createElement(Cs,{paddingX:2,justifyContent:"center"},we.createElement(rt,{color:pw[a]},p),c&&we.createElement(we.Fragment,null,we.createElement(rt,{color:A.ui.muted}," · "),we.createElement(rt,{color:A.ui.muted},"Resets in ",c))),we.createElement(Cs,{paddingX:2,paddingY:0,width:"100%",justifyContent:"space-between",flexDirection:"row"},we.createElement(Cs,null,we.createElement(rt,{color:A.text.link},g),we.createElement(rt,{color:A.ui.muted}," v",dw),we.createElement(rt,{color:A.ui.muted}," · "),we.createElement(rt,{color:d,bold:!0},l)),we.createElement(Cs,null,we.createElement(rt,{color:A.text.accent},e.displayName),we.createElement(rt,{color:A.text.secondary}," /model"),we.createElement(rt,{color:A.text.secondary}," "),we.createElement(rt,{color:mw[r]},"●"),we.createElement(rt,{color:A.text.secondary}," browser")),we.createElement(Cs,null,we.createElement(rt,{color:A.text.secondary},m))))}var Vg=aw(bw);import xc,{memo as Cc}from"react";import{Box as Vw}from"@jrichman/ink";import ae,{memo as Hw,useMemo as om}from"react";import{Box as at,Text as bt}from"@jrichman/ink";import Es,{memo as yw}from"react";import{Box as ai,Text as Xg}from"@jrichman/ink";function vw({suggestions:i,onSelect:e}){return i.length===0?null:Es.createElement(ai,{flexDirection:"column",marginTop:1,width:"100%"},i.map((t,n)=>Es.createElement(ai,{key:`sug-block-${n}`,flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},t.options.map((s,r)=>Es.createElement(ai,{key:`sug-opt-${n}-${r}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},Es.createElement(Xg,{color:"#22D3EE"},s))))),e&&Es.createElement(ai,{marginTop:0,width:"100%"},Es.createElement(Xg,{color:"#6B7280"},"Type a suggestion to use it")))}var Yg=yw(vw,(i,e)=>i.suggestions===e.suggestions?!0:i.suggestions.length!==e.suggestions.length?!1:i.suggestions.every((t,n)=>{let s=e.suggestions[n];return t.options.length===s.options.length&&t.options.every((r,o)=>r===s.options[o])}));import Hn,{memo as Sw}from"react";import{Box as ci,Text as Sc}from"@jrichman/ink";function ww({workingFiles:i}){return i.length===0?null:Hn.createElement(ci,{flexDirection:"column",marginTop:1,width:"100%"},Hn.createElement(ci,{marginBottom:0,width:"100%"},Hn.createElement(Sc,{color:"#9CA3AF",bold:!0},"Working Files"),Hn.createElement(Sc,{color:"#6B7280"}," (",i.length,")")),Hn.createElement(ci,{flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},i.map(e=>Hn.createElement(ci,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},Hn.createElement(Sc,{color:"white"},e.name)))))}var Qg=Sw(ww,(i,e)=>i.workingFiles===e.workingFiles?!0:i.workingFiles.length!==e.workingFiles.length?!1:i.workingFiles.every((t,n)=>t.path===e.workingFiles[n].path));import ot,{memo as Tw,useMemo as xw,useState as Cw}from"react";import{Box as wr,Text as Sn}from"@jrichman/ink";var wc=5;function Ew({conversationHistory:i,onSelect:e}){let[t,n]=Cw(!1),{displayedItems:s,hiddenCount:r}=xw(()=>i.length<=wc||t?{displayedItems:i,hiddenCount:0}:{displayedItems:i.slice(0,wc),hiddenCount:i.length-wc},[i,t]);return i.length===0?null:ot.createElement(wr,{flexDirection:"column",marginTop:1},ot.createElement(wr,{marginBottom:0},ot.createElement(Sn,{color:A.text.secondary},"💬 "),ot.createElement(Sn,{color:A.text.secondary,bold:!0},i.length," conversation",i.length!==1?"s":""," found")),ot.createElement(wr,{flexDirection:"column",paddingLeft:2},s.map((o,a)=>ot.createElement(wr,{key:`conv-${o.id}-${a}`},ot.createElement(Sn,{color:A.ui.muted},"• "),ot.createElement(Sn,{color:A.text.primary},o.title),ot.createElement(Sn,{color:A.ui.muted}," ("),ot.createElement(Sn,{color:A.text.link},Iw(o.id)),ot.createElement(Sn,{color:A.ui.muted},")"))),r>0&&ot.createElement(wr,{marginTop:0},ot.createElement(Sn,{color:A.text.accent},"+",r," more conversation",r!==1?"s":""))))}function Iw(i,e=20){return i.length<=e?i:i.slice(0,e-3)+"..."}var Jg=Tw(Ew);import V,{memo as kw,useMemo as Pw}from"react";import{Box as it,Text as oe}from"@jrichman/ink";xn();import{createRequire as Aw}from"module";var Dw=Aw(import.meta.url),Mw=Dw("../package.json"),Rw=Mw.version;function Ow(i){switch(i){case 3:return"#FFD700";case 2:return"#A78BFA";case 1:return"#60A5FA";default:return A.ui.muted}}function Nw(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function _w(){let i="#E8B4B8",e="#B8E4E8",t="#4A4A4A";return V.createElement(it,{flexDirection:"column"},V.createElement(it,null,V.createElement(oe,{color:i},"██"),V.createElement(oe,null," "),V.createElement(oe,{color:i},"██"),V.createElement(oe,null," "),V.createElement(oe,{color:i},"██")),V.createElement(it,null,V.createElement(oe,{color:i},"██████████")),V.createElement(it,null,V.createElement(oe,{color:i},"██"),V.createElement(oe,{color:e},"██████"),V.createElement(oe,{color:i},"██")),V.createElement(it,null,V.createElement(oe,{color:i},"██"),V.createElement(oe,{color:t},"██"),V.createElement(oe,{color:e},"██"),V.createElement(oe,{color:t},"██"),V.createElement(oe,{color:i},"██")),V.createElement(it,null,V.createElement(oe,{color:i},"██"),V.createElement(oe,{color:e},"██████"),V.createElement(oe,{color:i},"██")),V.createElement(it,null,V.createElement(oe,{color:i},"████"),V.createElement(oe,{color:t},"██"),V.createElement(oe,{color:i},"████")),V.createElement(it,null,V.createElement(oe,{color:i}," ██████ ")))}function $w({projectPath:i,variant:e="main",tier:t=0}){let n=Pw(()=>i?Nw(i):null,[i]),s=Ce.getDisplayName(t),r=Ow(t);return e==="main"?V.createElement(it,{flexDirection:"row",paddingX:1,marginY:1,gap:2},V.createElement(_w,null),V.createElement(it,{flexDirection:"column",justifyContent:"center"},V.createElement(it,null,V.createElement(oe,{color:A.colors.AccentPurple,bold:!0},"Orion"),V.createElement(oe,{color:A.ui.muted}," v",Rw),V.createElement(oe,{color:A.ui.muted}," · "),V.createElement(oe,{color:r,bold:!0},"Orion ",s)),V.createElement(oe,{color:A.text.secondary},"Your partner in getting things done."),V.createElement(oe,{color:A.text.secondary,dimColor:!0},"More done, more sleep."),n&&V.createElement(it,{marginTop:1},V.createElement(oe,{color:A.ui.muted},n)))):V.createElement(it,{paddingX:1,marginY:1},V.createElement(oe,{color:A.colors.AccentPurple},"● "),e==="fresh"&&V.createElement(oe,{color:A.text.secondary},"Ready when you are."),e==="continue"&&V.createElement(oe,{color:A.text.secondary},"Picking up where we left off."),e==="new"&&V.createElement(oe,{color:A.text.secondary},"New conversation started."))}var Zg=kw($w);function em(i){return i.includes("Orion ready")||i.includes("Fresh start")||i.includes("Welcome back")||i.includes("New conversation")||i.includes("Conversation cleared")}function tm(i){let e=i.match(/📁\s*(.+)/),t=e?e[1].trim():void 0;return i.includes("Fresh start")||i.includes("Conversation cleared")?{variant:"fresh",projectPath:t}:i.includes("Welcome back")?{variant:"continue",projectPath:t}:i.includes("New conversation")?{variant:"new",projectPath:t}:{variant:"main",projectPath:t}}import Ve,{memo as li,useMemo as Fw}from"react";import{Box as Is,Text as Gn}from"@jrichman/ink";var he={javascript:{keywords:["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","new","class","extends","import","export","default","from","async","await","yield","static","get","set","typeof","instanceof","in","of","delete","void","this","super","with","debugger"],types:["Array","Object","String","Number","Boolean","Function","Promise","Map","Set","Date","RegExp","Error","Symbol","BigInt","null","undefined","true","false","NaN","Infinity"],stringDelimiters:["'",'"',"`"],commentSingle:"//",commentMultiStart:"/*",commentMultiEnd:"*/"},typescript:{keywords:["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","new","class","extends","import","export","default","from","async","await","yield","static","get","set","typeof","instanceof","in","of","delete","void","this","super","type","interface","enum","namespace","module","declare","abstract","implements","private","protected","public","readonly","as","is","keyof","infer","never","unknown","any"],types:["Array","Object","String","Number","Boolean","Function","Promise","Map","Set","Date","RegExp","Error","Symbol","BigInt","null","undefined","true","false","void","Partial","Required","Readonly","Record","Pick","Omit","Exclude","Extract","NonNullable","ReturnType","InstanceType","Parameters"],stringDelimiters:["'",'"',"`"],commentSingle:"//",commentMultiStart:"/*",commentMultiEnd:"*/"},python:{keywords:["def","class","return","if","elif","else","for","while","break","continue","try","except","finally","raise","import","from","as","with","assert","yield","lambda","pass","del","global","nonlocal","and","or","not","in","is","async","await","match","case"],types:["None","True","False","int","float","str","list","dict","tuple","set","bool","bytes","object","type","Exception"],builtins:["print","len","range","enumerate","zip","map","filter","sorted","reversed","sum","min","max","abs","round","open","input","isinstance","hasattr","getattr","setattr","super","property","staticmethod","classmethod"],stringDelimiters:["'",'"',"'''",'"""'],commentSingle:"#"},bash:{keywords:["if","then","else","elif","fi","for","while","do","done","case","esac","in","function","return","exit","break","continue","export","local","readonly","declare","unset","shift","source","eval","exec","trap","set","shopt"],builtins:["echo","cd","pwd","ls","cat","grep","sed","awk","find","xargs","sort","uniq","head","tail","wc","cut","tr","mkdir","rm","cp","mv","touch","chmod","chown","curl","wget","git","npm","yarn","pnpm","node","python","pip"],stringDelimiters:["'",'"'],commentSingle:"#"},rust:{keywords:["fn","let","mut","const","static","if","else","match","for","while","loop","break","continue","return","struct","enum","impl","trait","type","where","use","mod","pub","crate","self","super","as","in","ref","move","async","await","dyn","unsafe","extern"],types:["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","bool","char","str","String","Vec","Option","Result","Box","Rc","Arc","Cell","RefCell","true","false","Some","None","Ok","Err","Self"],stringDelimiters:['"'],commentSingle:"//",commentMultiStart:"/*",commentMultiEnd:"*/"},go:{keywords:["func","return","if","else","for","range","switch","case","default","break","continue","goto","fallthrough","defer","go","select","chan","var","const","type","struct","interface","map","package","import"],types:["int","int8","int16","int32","int64","uint","uint8","uint16","uint32","uint64","uintptr","float32","float64","complex64","complex128","bool","byte","rune","string","error","nil","true","false","iota"],builtins:["make","new","len","cap","append","copy","delete","close","panic","recover","print","println"],stringDelimiters:['"',"'","`"],commentSingle:"//",commentMultiStart:"/*",commentMultiEnd:"*/"},json:{keywords:[],types:["true","false","null"],stringDelimiters:['"']},yaml:{keywords:[],types:["true","false","null","yes","no","on","off"],stringDelimiters:["'",'"'],commentSingle:"#"},sql:{keywords:["SELECT","FROM","WHERE","AND","OR","NOT","IN","LIKE","BETWEEN","IS","NULL","ORDER","BY","ASC","DESC","LIMIT","OFFSET","JOIN","LEFT","RIGHT","INNER","OUTER","ON","AS","GROUP","HAVING","DISTINCT","COUNT","SUM","AVG","MIN","MAX","INSERT","INTO","VALUES","UPDATE","SET","DELETE","CREATE","TABLE","DROP","ALTER","INDEX","PRIMARY","KEY","FOREIGN","REFERENCES","CONSTRAINT","UNIQUE","DEFAULT","CASCADE","UNION","ALL","EXISTS","CASE","WHEN","THEN","ELSE","END","COALESCE","NULLIF","CAST"],types:["INT","INTEGER","VARCHAR","TEXT","BOOLEAN","DATE","TIMESTAMP","FLOAT","DOUBLE","DECIMAL","BIGINT","SMALLINT","CHAR","BLOB","JSON","UUID"],stringDelimiters:["'"],commentSingle:"--",commentMultiStart:"/*",commentMultiEnd:"*/"}};he.ts=he.typescript;he.js=he.javascript;he.jsx=he.javascript;he.tsx=he.typescript;he.py=he.python;he.sh=he.bash;he.shell=he.bash;he.zsh=he.bash;he.rs=he.rust;he.golang=he.go;he.yml=he.yaml;function Lw(i,e){let t=[],n=0;for(;n<i.length;){if(e.commentSingle&&i.slice(n).startsWith(e.commentSingle)){t.push({type:"comment",value:i.slice(n)});break}let s=!1;for(let c of e.stringDelimiters)if(i.slice(n).startsWith(c)){let l=i.indexOf(c,n+c.length);if(l!==-1){t.push({type:"string",value:i.slice(n,l+c.length)}),n=l+c.length,s=!0;break}else{t.push({type:"string",value:i.slice(n)}),n=i.length,s=!0;break}}if(s)continue;let r=i.slice(n).match(/^-?\d+(\.\d+)?([eE][+-]?\d+)?/);if(r&&(n===0||/[\s\(\[\{,;:=<>!&|+\-*/%]/.test(i[n-1]))){t.push({type:"number",value:r[0]}),n+=r[0].length;continue}let o=i.slice(n).match(/^[a-zA-Z_$][a-zA-Z0-9_$]*/);if(o){let c=o[0],l="plain";e.keywords.includes(c)?l="keyword":e.types?.includes(c)?l="type":(e.builtins?.includes(c)||i[n+c.length]==="(")&&(l="function"),t.push({type:l,value:c}),n+=c.length;continue}let a=i.slice(n).match(/^(===|!==|==|!=|<=|>=|=>|->|&&|\|\||<<|>>|\+\+|--|[+\-*/%=<>!&|^~?:])/);if(a){t.push({type:"operator",value:a[0]}),n+=a[0].length;continue}if(/^[(){}\[\];,.]/.test(i[n])){t.push({type:"punctuation",value:i[n]}),n++;continue}t.push({type:"plain",value:i[n]}),n++}return t}var Uw={keyword:A.status.warning,string:A.status.success,comment:A.ui.comment,number:A.text.link,function:A.text.link,operator:A.text.primary,punctuation:A.ui.muted,type:A.status.info,plain:A.text.primary},Bw=li(function({line:e,language:t}){if(!t)return Ve.createElement(Gn,{color:A.text.primary},e);let n=Lw(e,t);return Ve.createElement(Gn,null,n.map((s,r)=>Ve.createElement(Gn,{key:r,color:Uw[s.type]},s.value)))}),Ww=li(function({code:e,language:t,showLineNumbers:n=!1,startLineNumber:s=1,maxLines:r}){let{lines:o,langDef:a,truncated:c}=Fw(()=>{let d=e.split(`
2593
+ `),g=t?he[t.toLowerCase()]:void 0;return r&&d.length>r?{lines:d.slice(0,r),langDef:g,truncated:d.length-r}:{lines:d,langDef:g,truncated:0}},[e,t,r]),l=n?String(s+o.length-1).length:0;return Ve.createElement(Is,{flexDirection:"column"},o.map((d,g)=>Ve.createElement(Is,{key:g,flexDirection:"row"},n&&Ve.createElement(Is,{width:l+2,flexShrink:0},Ve.createElement(Gn,{color:A.ui.muted},String(s+g).padStart(l," ")," │")),Ve.createElement(Is,{flexGrow:1},Ve.createElement(Bw,{line:d,language:a})))),c>0&&Ve.createElement(Gn,{color:A.ui.muted}," ... ",c," more lines"))}),nm=li(function({code:e,language:t,showLanguageLabel:n=!0,showLineNumbers:s=!1,maxLines:r,showBorder:o=!0}){let a=t?.toLowerCase(),c=a&&he[a]?a:void 0;return Ve.createElement(Is,{flexDirection:"column",borderStyle:o?"round":void 0,borderColor:o?A.border.default:void 0,paddingX:o?1:0},n&&c&&Ve.createElement(Is,{marginBottom:0},Ve.createElement(Gn,{color:A.ui.muted,dimColor:!0},c)),Ve.createElement(Ww,{code:e,language:c,showLineNumbers:s,maxLines:r}))}),dB=li(function({children:e}){return Ve.createElement(Gn,{color:A.status.warning,bold:!1},"`",e,"`")});function sm(i){let e=[],t=/```(\w*)\n?([\s\S]*?)```/g,n=0,s;for(;(s=t.exec(i))!==null;)s.index>n&&e.push({type:"text",content:i.slice(n,s.index)}),e.push({type:"code",content:s[2].trim(),language:s[1]||void 0}),n=s.index+s[0].length;return n<i.length&&e.push({type:"text",content:i.slice(n)}),e}function rm(i){return/```[\s\S]*?```/.test(i)}var Gw=150;function im(i,e){return i.length<=e?{lines:i,truncated:!1}:{lines:i.slice(0,e),truncated:!0}}function jw({message:i,onSuggestionClick:e,maxLines:t=Gw}){let{role:n,content:s}=i,{userTier:r}=ar(),o=om(()=>{if(n!=="assistant")return null;let{suggestions:c,cleanedContent:l}=Ir(s),{workingFiles:d,cleanedContent:g}=Nc(l),{conversationHistory:m,cleanedContent:p}=_c(g),f=$c(p).split(`
2594
2594
  `),{lines:y,truncated:T}=im(f,t);return{suggestions:c,workingFiles:d,conversationHistory:m,lines:y,truncated:T,totalLines:f.length}},[s,n,t]),a=om(()=>{if(n==="assistant")return null;let c=s.split(`
2595
- `);return im(c,t)},[s,n,t]);if(n==="system"&&a){if(em(s)){let{variant:g,projectPath:m}=tm(s);return ie.createElement(Zg,{variant:g,projectPath:m,tier:r})}let{lines:c,truncated:l}=a,d=s.split(`
2596
- `);return ie.createElement(at,{marginY:0,flexDirection:"column",paddingX:1},ie.createElement(at,{flexDirection:"row"},ie.createElement(bt,{color:A.ui.muted},"● "),ie.createElement(at,{flexDirection:"column",flexGrow:1},c.map((g,m)=>ie.createElement(bt,{key:`sys-${m}`,color:A.ui.muted},g)),l&&ie.createElement(bt,{color:A.ui.muted}," ... (",d.length-t," more)"))))}if(n==="user"&&a){let{lines:c,truncated:l}=a,d=s.split(`
2597
- `);return ie.createElement(at,{marginY:1,flexDirection:"column",paddingX:1},ie.createElement(at,{flexDirection:"row"},ie.createElement(bt,{color:A.text.primary},"❯ "),ie.createElement(at,{flexDirection:"column",flexGrow:1},c.map((g,m)=>ie.createElement(bt,{key:`user-${m}`,color:A.text.primary},g)),l&&ie.createElement(bt,{color:A.ui.muted}," ... (",d.length-t," more)"))))}if(n==="assistant"&&o){let{suggestions:c,workingFiles:l,conversationHistory:d,lines:g,truncated:m,totalLines:p}=o,h=g.join(`
2598
- `),f=rm(h);return ie.createElement(at,{marginY:1,flexDirection:"column",paddingX:1},ie.createElement(at,{flexDirection:"row"},ie.createElement(bt,{color:A.text.primary},"● "),ie.createElement(at,{flexDirection:"column",flexGrow:1},f?sm(h).map((y,T)=>y.type==="code"?ie.createElement(at,{key:`code-${T}`,marginY:1},ie.createElement(nm,{code:y.content,language:y.language,showBorder:!0,maxLines:50})):y.content.split(`
2599
- `).map((x,w)=>x.trim()===""?ie.createElement(bt,{key:`text-${T}-${w}`}," "):ie.createElement(bt,{key:`text-${T}-${w}`,color:A.text.primary},fi(x)))):g.map((y,T)=>y.trim()===""?ie.createElement(bt,{key:`asst-${T}`}," "):ie.createElement(bt,{key:`asst-${T}`,color:A.text.primary},fi(y))),m&&ie.createElement(bt,{color:A.ui.muted}," ... (",p-t," more)"))),d.length>0&&ie.createElement(at,{paddingLeft:2},ie.createElement(Jg,{conversationHistory:d})),l.length>0&&ie.createElement(at,{paddingLeft:2},ie.createElement(Qg,{workingFiles:l})),c.length>0&&ie.createElement(at,{paddingLeft:2},ie.createElement(Yg,{suggestions:c,onSelect:e})))}return null}var am=Hw(jw,(i,e)=>i.message.id===e.message.id&&i.message.content===e.message.content&&i.maxLines===e.maxLines);import Tc,{memo as zw}from"react";import{Box as qw,Text as cm}from"@jrichman/ink";function Kw({version:i,showDetails:e=!0}){return e?Tc.createElement(qw,{marginBottom:1,paddingX:1},Tc.createElement(cm,{color:A.text.primary,bold:!0},"Orion"),i&&Tc.createElement(cm,{color:A.ui.muted,dimColor:!0}," v",i)):null}var lm=zw(Kw);var Xw=Cc(am),Yw=Cc(lm),Qw=150;function Jw({messages:i,version:e,showHeader:t=!1,hasFocus:n=!0,onSuggestionClick:s,staticRemountKey:r=0}){return xc.createElement(Vw,{flexDirection:"column",key:r},t&&xc.createElement(Yw,{version:e,showDetails:!0}),i.map(o=>xc.createElement(Xw,{key:o.id,message:o,maxLines:Qw,onSuggestionClick:s})))}var um=Cc(Jw);import dm,{memo as Zw}from"react";import{Box as eT,Text as tT}from"@jrichman/ink";function nT({width:i,color:e=A.border.default,char:t="─"}){let{width:n}=oi(),s=typeof i=="number"?i:typeof i=="string"&&i.endsWith("%")?Math.floor(parseInt(i)/100*n):n-4,r=t.repeat(s);return dm.createElement(eT,null,dm.createElement(tT,{color:e},r))}var gm=Zw(nT);import Hn,{memo as pm,useState as UB,useEffect as sT,useRef as rT,useCallback as BB}from"react";import{Box as ui,Text as mm}from"@jrichman/ink";var oT={success:{icon:"✓",color:A.status.success,borderColor:A.status.success},error:{icon:"✕",color:A.status.error,borderColor:A.status.error},warning:{icon:"⚠",color:A.status.warning,borderColor:A.status.warning},info:{icon:"ℹ",color:A.status.info,borderColor:A.border.default}},iT=pm(function({message:e,type:t="info",duration:n=3e3,onDismiss:s,icon:r,showBorder:o=!0}){let a=oT[t],c=r??a.icon,l=rT(null);return sT(()=>{if(n>0&&s)return l.current=setTimeout(s,n),()=>{l.current&&clearTimeout(l.current)}},[n,s]),Hn.createElement(ui,{borderStyle:o?"round":void 0,borderColor:o?a.borderColor:void 0,paddingX:o?1:0,paddingY:0,flexDirection:"row",alignItems:"center"},Hn.createElement(mm,{color:a.color},c),Hn.createElement(ui,{marginLeft:1},Hn.createElement(mm,{color:A.text.primary},e)))}),hm=pm(function({toasts:e,onRemove:t,maxToasts:n=3,position:s="bottom"}){let r=e.slice(-n);return r.length===0?null:Hn.createElement(ui,{flexDirection:"column",marginTop:s==="bottom"?1:0,marginBottom:s==="top"?1:0},r.map(o=>Hn.createElement(ui,{key:o.id,marginBottom:1},Hn.createElement(iT,{message:o.message,type:o.type,duration:o.duration??3e3,onDismiss:()=>t(o.id)}))))});import Me,{memo as fm,useMemo as aT}from"react";import{Box as Ec,Text as yt}from"@jrichman/ink";var cT=fm(function({text:e,query:t}){let n=aT(()=>pg(e,t,!1),[e,t]),s=70,r=0,o=[],a=!1;for(let c of n){if(r>=s){a=!0;break}let l=s-r;if(c.text.length>l){o.push({text:c.text.slice(0,l),isMatch:c.isMatch}),a=!0;break}o.push(c),r+=c.text.length}return Me.createElement(Me.Fragment,null,o.map((c,l)=>Me.createElement(yt,{key:l,color:c.isMatch?A.status.warning:A.text.primary,bold:c.isMatch,inverse:c.isMatch},c.text)),a&&Me.createElement(yt,{color:A.ui.muted},"..."))});function lT({query:i,history:e,currentMatchIndex:t,matchCount:n,matchedEntry:s,isActive:r}){return r?Me.createElement(Ec,{flexDirection:"column",paddingX:1,borderStyle:"single",borderColor:A.border.default},Me.createElement(Ec,{flexDirection:"row"},Me.createElement(yt,{color:A.text.accent},"(reverse-i-search)"),Me.createElement(yt,{color:A.text.primary},"`"),Me.createElement(yt,{color:A.status.warning},i),Me.createElement(yt,{color:A.text.primary},"'"),Me.createElement(yt,{color:A.ui.muted},": "),s?Me.createElement(cT,{text:s,query:i}):i?Me.createElement(yt,{color:A.ui.muted,italic:!0},"no match"):Me.createElement(yt,{color:A.ui.muted,italic:!0},"type to search history")),i&&Me.createElement(Ec,{flexDirection:"row",marginTop:0},Me.createElement(yt,{color:A.ui.muted},n>0?`[${t+1}/${n}]`:"[0/0]"),Me.createElement(yt,{color:A.ui.muted}," "),Me.createElement(yt,{color:A.ui.muted,italic:!0},n>0?"Up/Down to navigate, Enter to select, Esc to cancel":"No matches found"))):null}var bm=fm(lT);wn();function mT(){let i=Nn(),e=Ct(),{regularQueuedMessages:t,crossDeviceTasks:n}=qa(),s=ms(),r=Wt(),{userTier:o}=ir(),a=ar(),c=$n(),{handleCommand:l}=Yo(),d=Ka(),[g,m]=dT();Ic(()=>{i.isLoading&&!g?m(Date.now()):i.isLoading||m(void 0)},[i.isLoading,g]);let p=ym(()=>{let v=null;for(let S=i.messages.length-1;S>=0;S--){let I=i.messages[S];if(I.role==="assistant"&&I.content){v=I;break}}if(!v)return null;let{suggestions:E}=Er(v.content);return E.length>0&&E[0].options.length>0?E[0].options[0]:null},[i.messages]),h=vm(null);Ic(()=>{let v=null;i.isLoading?v=null:a.input===""||p&&p.toLowerCase().startsWith(a.input.toLowerCase())?v=p:v=null,h.current!==v&&(h.current=v,c.setSuggestion(v))},[p,i.isLoading,a.input]);let f=uT(async()=>{let v=a.pastedTexts.filter(E=>!E.error||E.type==="text");if(a.input.startsWith("/")){await l(a.input);return}if(c.clearPastedTexts(),v.length>0){let{fullInput:E,imageUrls:S,errors:I}=await c.processFilesForSubmit();if(I.length>0&&!E.trim()&&S.length===0){e.addSystemMessage(`Failed to read files:
2600
- ${I.map(P=>` - ${P}`).join(`
2601
- `)}`);return}a.input.trim()&&c.addToHistory(a.input.trim()),e.handleSubmit(E.trim()||"Please analyze this image.",S)}else a.input.trim()&&c.addToHistory(a.input.trim()),e.handleSubmit(a.input.trim());c.clearInput()},[a.input,a.pastedTexts,c,e,l]),{memoryPressure:y,frameBudgetStatus:T}=lg({onSubmit:f,enableProfiling:process.env.DEBUG_PERF==="true",bufferFlushInterval:16}),x=mg({items:a.history,getSearchText:v=>v,direction:"backward",isActive:s.isReverseSearchActive,onMatchSelect:v=>{c.setInput(v.item)}}),w=vm(!1);Ic(()=>{s.isReverseSearchActive&&!x.isSearching?x.startSearch():!s.isReverseSearchActive&&x.isSearching&&x.stopSearch(),w.current&&!x.isSearching&&s.isReverseSearchActive&&(x.currentMatch&&c.setInput(x.currentMatch.item),r.stopReverseSearch()),w.current=x.isSearching},[s.isReverseSearchActive,x.isSearching,x.startSearch,x.stopSearch,x.currentMatch,c,r]);let C=ym(()=>s.showHelp||s.showModelMenu||s.showCommandMenu||s.showWizard||s.isReverseSearchActive,[s.showHelp,s.showModelMenu,s.showCommandMenu,s.showWizard,s.isReverseSearchActive]);return Z.createElement(He,{flexDirection:"column",width:"100%"},Z.createElement(um,{messages:i.messages,showHeader:!1,hasFocus:!C,onSuggestionClick:v=>c.setInput(v),staticRemountKey:i.staticRemountKey}),Z.createElement(He,{paddingX:2,flexShrink:0},Z.createElement(gm,null)),i.todoList&&i.todoList.todos.length>0&&Z.createElement(He,{flexShrink:0},Z.createElement(xg,{todoList:i.todoList})),i.externalSession&&Z.createElement(He,{paddingX:2,marginBottom:1,flexShrink:0},Z.createElement(Sg,{session:i.externalSession})),i.activeTools.size>0&&Z.createElement(He,{paddingX:2,marginBottom:1,flexShrink:0},Z.createElement(fg,{activeTools:i.activeTools})),i.subAgentOperations.size>0&&Z.createElement(He,{paddingX:2,marginBottom:1,flexShrink:0},Z.createElement(vg,{operations:i.subAgentOperations})),i.pendingConfirmation&&Z.createElement(He,{paddingX:2,marginBottom:1,flexShrink:0},Z.createElement(Tg,{request:i.pendingConfirmation,onConfirm:e.handleConfirmationConfirm,onDecline:e.handleConfirmationDecline,onTimeout:e.handleConfirmationTimeout})),a.isProcessingFiles&&Z.createElement(He,{paddingX:2,marginBottom:1,flexShrink:0},Z.createElement(Sm,{color:A.text.accent},Z.createElement(gT,{type:"dots"})),Z.createElement(Sm,{color:A.text.primary}," Reading files...")),!a.isProcessingFiles&&Z.createElement(Ug,{isLoading:i.isLoading,phrase:i.loadingMessage||"Processing",startTime:g}),(t.length>0||n.length>0)&&Z.createElement(He,{flexShrink:0},Z.createElement(Ng,{regularQueuedMessages:t,crossDeviceTasks:n})),s.showWizard&&s.wizard.type&&Z.createElement(He,{flexShrink:0,paddingX:2,marginBottom:1},Z.createElement(Rg,{type:s.wizard.type})),s.showCommandMenu&&Z.createElement(He,{flexShrink:0,paddingX:2,marginBottom:0},Z.createElement(Mg,{filterText:a.input.startsWith("/")?a.input.substring(1).toLowerCase():"",onSelect:v=>{r.hideCommandMenu(),l(`/${v}`)}})),s.showModelMenu&&Z.createElement(He,{flexShrink:0,paddingX:2,marginBottom:1},Z.createElement(kg,{userTier:o,onSelect:v=>{r.setModel(v),r.hideModelMenu()},onAccessDenied:v=>{e.addSystemMessage(xe.getAccessDeniedMessage(v)),r.hideModelMenu()}})),s.showHelp&&Z.createElement(He,{flexShrink:0,paddingX:2,marginBottom:1},Z.createElement(Cg,null)),s.isReverseSearchActive&&Z.createElement(He,{flexShrink:0,paddingX:2,marginBottom:1},Z.createElement(bm,{query:x.query,history:a.history,currentMatchIndex:x.currentMatchIndex,matchCount:x.matchCount,matchedEntry:x.currentMatch?.item||null,isActive:s.isReverseSearchActive})),!s.showWizard&&Z.createElement(He,{flexShrink:0,paddingX:2},Z.createElement(Lg,{input:a.input,isLoading:i.isLoading,pastedTexts:a.pastedTexts,cursorPosition:a.cursorPosition,suggestion:a.suggestion,mode:s.operationalMode})),s.toasts.length>0&&Z.createElement(He,{flexShrink:0,paddingX:2},Z.createElement(hm,{toasts:s.toasts,onRemove:r.removeToast,maxToasts:3})),Z.createElement(Vg,{cwd:d,selectedModel:s.selectedModel,showScrollHint:!1,tier:o}))}function wm({initialProjectPath:i}={}){return Z.createElement(Vd,{initialProjectPath:i},Z.createElement(mT,null))}Pc();Te();Te();import se from"chalk";import CT from"inquirer";import{exec as ET}from"child_process";var vn=class{authService;constructor(){this.authService=X.getInstance()}openBrowser(e){return new Promise(t=>{let n=process.platform,s;n==="darwin"?s=`open "${e}"`:n==="win32"?s=`start "" "${e}"`:s=`xdg-open "${e}"`,ET(s,r=>{r&&console.log(se.yellow("⚠️ Could not auto-open browser. Please open the URL manually.")),t()})})}async login(){console.log(se.blue(`
2602
- 🔐 Orion Authentication`)),console.log(se.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(se.yellow(`
2603
- 📋 Opening browser for authentication...`)),console.log(se.cyan.underline(` ${e}`)),await this.openBrowser(e),console.log(se.white(`
2604
- 1. Log in with your Orion account in the browser`)),console.log(se.white("2. Copy the access token shown after login")),console.log(se.white("3. Paste the token below")),console.log(se.yellow(`
2605
- Paste your access token here:`));let{accessToken:t}=await CT.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:n=>!n||n.trim().length===0?"Access token is required":!0}]);console.log(se.gray(`
2606
- Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let s=await this.authService.getUserInfo();console.log(se.green(`
2607
- ✅ Authentication successful!`)),s&&(console.log(se.gray(`Logged in as: ${s.email||s.username||"User"}`)),console.log(se.gray(`Subscription: ${this.getSubscriptionDisplay(s.subscription?.tier)}`)))}else console.log(se.red(`
2608
- ❌ Authentication failed. Please try again.`))}catch(n){console.log(se.red(`
2609
- ❌ Authentication error: ${n.message}`))}}async logout(){console.log(se.yellow(`
2610
- 🔄 Signing out...`)),console.log(se.gray("This will clear all stored data and device registrations.")),await this.authService.signOut()?(console.log(se.green(`
2611
- ✅ Successfully signed out`)),console.log(se.gray("All authentication data and settings have been cleared.")),console.log(se.gray('Run "orion auth login" to sign in again.'))):(console.log(se.red(`
2612
- ❌ Logout failed`)),console.log(se.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(se.green(`
2613
- ✅ Authenticated`)),t){console.log(se.gray("─".repeat(50))),console.log(se.white("User:",t.name||t.username||"N/A")),console.log(se.white("Email:",t.email||"N/A"));let n=this.getSubscriptionDisplay(t.subscription?.tier);console.log(se.white("Subscription:",n)),t.usage&&(console.log(se.gray(`
2614
- Usage:`)),console.log(se.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(se.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(se.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(se.yellow(`
2615
- ⚠️ Not authenticated`)),console.log(se.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"}}};Tt();Ca();var Dm=!1;async function Ac(){let i=process.cwd();if(Dm){console.log("Already running...");return}Dm=!0,Y.enableCustomUI();let e=wr.getInstance(),t=X.getInstance();if(!e.isInitialized()){console.log("🔧 Initializing Orion services...");try{await e.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(o){console.error(`
2595
+ `);return im(c,t)},[s,n,t]);if(n==="system"&&a){if(em(s)){let{variant:g,projectPath:m}=tm(s);return ae.createElement(Zg,{variant:g,projectPath:m,tier:r})}let{lines:c,truncated:l}=a,d=s.split(`
2596
+ `);return ae.createElement(at,{marginY:0,flexDirection:"column",paddingX:1},ae.createElement(at,{flexDirection:"row"},ae.createElement(bt,{color:A.ui.muted},"● "),ae.createElement(at,{flexDirection:"column",flexGrow:1},c.map((g,m)=>ae.createElement(bt,{key:`sys-${m}`,color:A.ui.muted},g)),l&&ae.createElement(bt,{color:A.ui.muted}," ... (",d.length-t," more)"))))}if(n==="user"&&a){let{lines:c,truncated:l}=a,d=s.split(`
2597
+ `);return ae.createElement(at,{marginY:1,flexDirection:"column",paddingX:1},ae.createElement(at,{flexDirection:"row"},ae.createElement(bt,{color:A.text.primary},"❯ "),ae.createElement(at,{flexDirection:"column",flexGrow:1},c.map((g,m)=>ae.createElement(bt,{key:`user-${m}`,color:A.text.primary},g)),l&&ae.createElement(bt,{color:A.ui.muted}," ... (",d.length-t," more)"))))}if(n==="assistant"&&o){let{suggestions:c,workingFiles:l,conversationHistory:d,lines:g,truncated:m,totalLines:p}=o,h=g.join(`
2598
+ `),f=rm(h);return ae.createElement(at,{marginY:1,flexDirection:"column",paddingX:1},ae.createElement(at,{flexDirection:"row"},ae.createElement(bt,{color:A.text.primary},"● "),ae.createElement(at,{flexDirection:"column",flexGrow:1},f?sm(h).map((y,T)=>y.type==="code"?ae.createElement(at,{key:`code-${T}`,marginY:1},ae.createElement(nm,{code:y.content,language:y.language,showBorder:!0,maxLines:50})):y.content.split(`
2599
+ `).map((C,w)=>C.trim()===""?ae.createElement(bt,{key:`text-${T}-${w}`}," "):ae.createElement(bt,{key:`text-${T}-${w}`,color:A.text.primary},fi(C)))):g.map((y,T)=>y.trim()===""?ae.createElement(bt,{key:`asst-${T}`}," "):ae.createElement(bt,{key:`asst-${T}`,color:A.text.primary},fi(y))),m&&ae.createElement(bt,{color:A.ui.muted}," ... (",p-t," more)"))),d.length>0&&ae.createElement(at,{paddingLeft:2},ae.createElement(Jg,{conversationHistory:d})),l.length>0&&ae.createElement(at,{paddingLeft:2},ae.createElement(Qg,{workingFiles:l})),c.length>0&&ae.createElement(at,{paddingLeft:2},ae.createElement(Yg,{suggestions:c,onSelect:e})))}return null}var am=Hw(jw,(i,e)=>i.message.id===e.message.id&&i.message.content===e.message.content&&i.maxLines===e.maxLines);import Tc,{memo as zw}from"react";import{Box as qw,Text as cm}from"@jrichman/ink";function Kw({version:i,showDetails:e=!0}){return e?Tc.createElement(qw,{marginBottom:1,paddingX:1},Tc.createElement(cm,{color:A.text.primary,bold:!0},"Orion"),i&&Tc.createElement(cm,{color:A.ui.muted,dimColor:!0}," v",i)):null}var lm=zw(Kw);var Xw=Cc(am),Yw=Cc(lm),Qw=150;function Jw({messages:i,version:e,showHeader:t=!1,hasFocus:n=!0,onSuggestionClick:s,staticRemountKey:r=0}){return xc.createElement(Vw,{flexDirection:"column",key:r},t&&xc.createElement(Yw,{version:e,showDetails:!0}),i.map(o=>xc.createElement(Xw,{key:o.id,message:o,maxLines:Qw,onSuggestionClick:s})))}var um=Cc(Jw);import dm,{memo as Zw}from"react";import{Box as eT,Text as tT}from"@jrichman/ink";function nT({width:i,color:e=A.border.default,char:t="─"}){let{width:n}=oi(),s=typeof i=="number"?i:typeof i=="string"&&i.endsWith("%")?Math.floor(parseInt(i)/100*n):n-4,r=t.repeat(s);return dm.createElement(eT,null,dm.createElement(tT,{color:e},r))}var gm=Zw(nT);import jn,{memo as pm,useState as UB,useEffect as sT,useRef as rT,useCallback as BB}from"react";import{Box as ui,Text as mm}from"@jrichman/ink";var oT={success:{icon:"✓",color:A.status.success,borderColor:A.status.success},error:{icon:"✕",color:A.status.error,borderColor:A.status.error},warning:{icon:"⚠",color:A.status.warning,borderColor:A.status.warning},info:{icon:"ℹ",color:A.status.info,borderColor:A.border.default}},iT=pm(function({message:e,type:t="info",duration:n=3e3,onDismiss:s,icon:r,showBorder:o=!0}){let a=oT[t],c=r??a.icon,l=rT(null);return sT(()=>{if(n>0&&s)return l.current=setTimeout(s,n),()=>{l.current&&clearTimeout(l.current)}},[n,s]),jn.createElement(ui,{borderStyle:o?"round":void 0,borderColor:o?a.borderColor:void 0,paddingX:o?1:0,paddingY:0,flexDirection:"row",alignItems:"center"},jn.createElement(mm,{color:a.color},c),jn.createElement(ui,{marginLeft:1},jn.createElement(mm,{color:A.text.primary},e)))}),hm=pm(function({toasts:e,onRemove:t,maxToasts:n=3,position:s="bottom"}){let r=e.slice(-n);return r.length===0?null:jn.createElement(ui,{flexDirection:"column",marginTop:s==="bottom"?1:0,marginBottom:s==="top"?1:0},r.map(o=>jn.createElement(ui,{key:o.id,marginBottom:1},jn.createElement(iT,{message:o.message,type:o.type,duration:o.duration??3e3,onDismiss:()=>t(o.id)}))))});import Re,{memo as fm,useMemo as aT}from"react";import{Box as Ec,Text as yt}from"@jrichman/ink";var cT=fm(function({text:e,query:t}){let n=aT(()=>pg(e,t,!1),[e,t]),s=70,r=0,o=[],a=!1;for(let c of n){if(r>=s){a=!0;break}let l=s-r;if(c.text.length>l){o.push({text:c.text.slice(0,l),isMatch:c.isMatch}),a=!0;break}o.push(c),r+=c.text.length}return Re.createElement(Re.Fragment,null,o.map((c,l)=>Re.createElement(yt,{key:l,color:c.isMatch?A.status.warning:A.text.primary,bold:c.isMatch,inverse:c.isMatch},c.text)),a&&Re.createElement(yt,{color:A.ui.muted},"..."))});function lT({query:i,history:e,currentMatchIndex:t,matchCount:n,matchedEntry:s,isActive:r}){return r?Re.createElement(Ec,{flexDirection:"column",paddingX:1,borderStyle:"single",borderColor:A.border.default},Re.createElement(Ec,{flexDirection:"row"},Re.createElement(yt,{color:A.text.accent},"(reverse-i-search)"),Re.createElement(yt,{color:A.text.primary},"`"),Re.createElement(yt,{color:A.status.warning},i),Re.createElement(yt,{color:A.text.primary},"'"),Re.createElement(yt,{color:A.ui.muted},": "),s?Re.createElement(cT,{text:s,query:i}):i?Re.createElement(yt,{color:A.ui.muted,italic:!0},"no match"):Re.createElement(yt,{color:A.ui.muted,italic:!0},"type to search history")),i&&Re.createElement(Ec,{flexDirection:"row",marginTop:0},Re.createElement(yt,{color:A.ui.muted},n>0?`[${t+1}/${n}]`:"[0/0]"),Re.createElement(yt,{color:A.ui.muted}," "),Re.createElement(yt,{color:A.ui.muted,italic:!0},n>0?"Up/Down to navigate, Enter to select, Esc to cancel":"No matches found"))):null}var bm=fm(lT);xn();function mT(){let i=$n(),e=Ct(),{regularQueuedMessages:t,crossDeviceTasks:n}=qa(),s=hs(),r=Ht(),{userTier:o}=ar(),a=cr(),c=Ln(),{handleCommand:l}=Yo(),d=Ka(),[g,m]=dT();Ic(()=>{i.isLoading&&!g?m(Date.now()):i.isLoading||m(void 0)},[i.isLoading,g]);let p=ym(()=>{let v=null;for(let S=i.messages.length-1;S>=0;S--){let I=i.messages[S];if(I.role==="assistant"&&I.content){v=I;break}}if(!v)return null;let{suggestions:x}=Ir(v.content);return x.length>0&&x[0].options.length>0?x[0].options[0]:null},[i.messages]),h=vm(null);Ic(()=>{let v=null;i.isLoading?v=null:a.input===""||p&&p.toLowerCase().startsWith(a.input.toLowerCase())?v=p:v=null,h.current!==v&&(h.current=v,c.setSuggestion(v))},[p,i.isLoading,a.input]);let f=uT(async()=>{let v=a.pastedTexts.filter(x=>!x.error||x.type==="text");if(a.input.startsWith("/")){await l(a.input);return}if(c.clearPastedTexts(),v.length>0){let{fullInput:x,imageUrls:S,errors:I}=await c.processFilesForSubmit();if(I.length>0&&!x.trim()&&S.length===0){e.addSystemMessage(`Failed to read files:
2600
+ ${I.map(D=>` - ${D}`).join(`
2601
+ `)}`);return}a.input.trim()&&c.addToHistory(a.input.trim()),e.handleSubmit(x.trim()||"Please analyze this image.",S)}else a.input.trim()&&c.addToHistory(a.input.trim()),e.handleSubmit(a.input.trim());c.clearInput()},[a.input,a.pastedTexts,c,e,l]),{memoryPressure:y,frameBudgetStatus:T}=lg({onSubmit:f,enableProfiling:process.env.DEBUG_PERF==="true",bufferFlushInterval:16}),C=mg({items:a.history,getSearchText:v=>v,direction:"backward",isActive:s.isReverseSearchActive,onMatchSelect:v=>{c.setInput(v.item)}}),w=vm(!1);Ic(()=>{s.isReverseSearchActive&&!C.isSearching?C.startSearch():!s.isReverseSearchActive&&C.isSearching&&C.stopSearch(),w.current&&!C.isSearching&&s.isReverseSearchActive&&(C.currentMatch&&c.setInput(C.currentMatch.item),r.stopReverseSearch()),w.current=C.isSearching},[s.isReverseSearchActive,C.isSearching,C.startSearch,C.stopSearch,C.currentMatch,c,r]);let E=ym(()=>s.showHelp||s.showModelMenu||s.showCommandMenu||s.showWizard||s.isReverseSearchActive,[s.showHelp,s.showModelMenu,s.showCommandMenu,s.showWizard,s.isReverseSearchActive]);return ee.createElement(Ge,{flexDirection:"column",width:"100%"},ee.createElement(um,{messages:i.messages,showHeader:!1,hasFocus:!E,onSuggestionClick:v=>c.setInput(v),staticRemountKey:i.staticRemountKey}),ee.createElement(Ge,{paddingX:2,flexShrink:0},ee.createElement(gm,null)),i.todoList&&i.todoList.todos.length>0&&ee.createElement(Ge,{flexShrink:0},ee.createElement(xg,{todoList:i.todoList})),i.externalSession&&ee.createElement(Ge,{paddingX:2,marginBottom:1,flexShrink:0},ee.createElement(Sg,{session:i.externalSession})),i.activeTools.size>0&&ee.createElement(Ge,{paddingX:2,marginBottom:1,flexShrink:0},ee.createElement(fg,{activeTools:i.activeTools})),i.subAgentOperations.size>0&&ee.createElement(Ge,{paddingX:2,marginBottom:1,flexShrink:0},ee.createElement(vg,{operations:i.subAgentOperations})),i.pendingConfirmation&&ee.createElement(Ge,{paddingX:2,marginBottom:1,flexShrink:0},ee.createElement(Tg,{request:i.pendingConfirmation,onConfirm:e.handleConfirmationConfirm,onDecline:e.handleConfirmationDecline,onTimeout:e.handleConfirmationTimeout})),a.isProcessingFiles&&ee.createElement(Ge,{paddingX:2,marginBottom:1,flexShrink:0},ee.createElement(Sm,{color:A.text.accent},ee.createElement(gT,{type:"dots"})),ee.createElement(Sm,{color:A.text.primary}," Reading files...")),!a.isProcessingFiles&&ee.createElement(Ug,{isLoading:i.isLoading,phrase:i.loadingMessage||"Processing",startTime:g}),(t.length>0||n.length>0)&&ee.createElement(Ge,{flexShrink:0},ee.createElement(Ng,{regularQueuedMessages:t,crossDeviceTasks:n})),s.showWizard&&s.wizard.type&&ee.createElement(Ge,{flexShrink:0,paddingX:2,marginBottom:1},ee.createElement(Rg,{type:s.wizard.type})),s.showCommandMenu&&ee.createElement(Ge,{flexShrink:0,paddingX:2,marginBottom:0},ee.createElement(Mg,{filterText:a.input.startsWith("/")?a.input.substring(1).toLowerCase():"",onSelect:v=>{r.hideCommandMenu(),l(`/${v}`)}})),s.showModelMenu&&ee.createElement(Ge,{flexShrink:0,paddingX:2,marginBottom:1},ee.createElement(kg,{userTier:o,onSelect:v=>{r.setModel(v),r.hideModelMenu()},onAccessDenied:v=>{e.addSystemMessage(Ce.getAccessDeniedMessage(v)),r.hideModelMenu()}})),s.showHelp&&ee.createElement(Ge,{flexShrink:0,paddingX:2,marginBottom:1},ee.createElement(Cg,null)),s.isReverseSearchActive&&ee.createElement(Ge,{flexShrink:0,paddingX:2,marginBottom:1},ee.createElement(bm,{query:C.query,history:a.history,currentMatchIndex:C.currentMatchIndex,matchCount:C.matchCount,matchedEntry:C.currentMatch?.item||null,isActive:s.isReverseSearchActive})),!s.showWizard&&ee.createElement(Ge,{flexShrink:0,paddingX:2},ee.createElement(Lg,{input:a.input,isLoading:i.isLoading,pastedTexts:a.pastedTexts,cursorPosition:a.cursorPosition,suggestion:a.suggestion,mode:s.operationalMode})),s.toasts.length>0&&ee.createElement(Ge,{flexShrink:0,paddingX:2},ee.createElement(hm,{toasts:s.toasts,onRemove:r.removeToast,maxToasts:3})),ee.createElement(Vg,{cwd:d,selectedModel:s.selectedModel,showScrollHint:!1,tier:o}))}function wm({initialProjectPath:i}={}){return ee.createElement(Vd,{initialProjectPath:i},ee.createElement(mT,null))}Pc();xe();xe();import re from"chalk";import CT from"inquirer";import{exec as ET}from"child_process";var wn=class{authService;constructor(){this.authService=X.getInstance()}openBrowser(e){return new Promise(t=>{let n=process.platform,s;n==="darwin"?s=`open "${e}"`:n==="win32"?s=`start "" "${e}"`:s=`xdg-open "${e}"`,ET(s,r=>{r&&console.log(re.yellow("⚠️ Could not auto-open browser. Please open the URL manually.")),t()})})}async login(){console.log(re.blue(`
2602
+ 🔐 Orion Authentication`)),console.log(re.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(re.yellow(`
2603
+ 📋 Opening browser for authentication...`)),console.log(re.cyan.underline(` ${e}`)),await this.openBrowser(e),console.log(re.white(`
2604
+ 1. Log in with your Orion account in the browser`)),console.log(re.white("2. Copy the access token shown after login")),console.log(re.white("3. Paste the token below")),console.log(re.yellow(`
2605
+ Paste your access token here:`));let{accessToken:t}=await CT.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:n=>!n||n.trim().length===0?"Access token is required":!0}]);console.log(re.gray(`
2606
+ Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let s=await this.authService.getUserInfo();console.log(re.green(`
2607
+ ✅ Authentication successful!`)),s&&(console.log(re.gray(`Logged in as: ${s.email||s.username||"User"}`)),console.log(re.gray(`Subscription: ${this.getSubscriptionDisplay(s.subscription?.tier)}`)))}else console.log(re.red(`
2608
+ ❌ Authentication failed. Please try again.`))}catch(n){console.log(re.red(`
2609
+ ❌ Authentication error: ${n.message}`))}}async logout(){console.log(re.yellow(`
2610
+ 🔄 Signing out...`)),console.log(re.gray("This will clear all stored data and device registrations.")),await this.authService.signOut()?(console.log(re.green(`
2611
+ ✅ Successfully signed out`)),console.log(re.gray("All authentication data and settings have been cleared.")),console.log(re.gray('Run "orion auth login" to sign in again.'))):(console.log(re.red(`
2612
+ ❌ Logout failed`)),console.log(re.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(re.green(`
2613
+ ✅ Authenticated`)),t){console.log(re.gray("─".repeat(50))),console.log(re.white("User:",t.name||t.username||"N/A")),console.log(re.white("Email:",t.email||"N/A"));let n=this.getSubscriptionDisplay(t.subscription?.tier);console.log(re.white("Subscription:",n)),t.usage&&(console.log(re.gray(`
2614
+ Usage:`)),console.log(re.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(re.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(re.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(re.yellow(`
2615
+ ⚠️ Not authenticated`)),console.log(re.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"}}};Tt();Ca();var Dm=!1;async function Ac(){let i=process.cwd();if(Dm){console.log("Already running...");return}Dm=!0,Q.enableCustomUI();let e=Tr.getInstance(),t=X.getInstance();if(!e.isInitialized()){console.log("🔧 Initializing Orion services...");try{await e.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(o){console.error(`
2616
2616
  ❌ Failed to initialize services:`,o.message),console.error(`
2617
2617
  💡 Tip: Check your internet connection and Firebase configuration.
2618
2618
  `),process.exit(1)}}(!await t.autoAuthenticate()||!t.isAuthenticated())&&(console.log(`🔐 Authentication required to use Orion CLI
2619
- `),await new vn().login(),t.isAuthenticated()||(console.error(`
2619
+ `),await new wn().login(),t.isAuthenticated()||(console.error(`
2620
2620
  ❌ Authentication failed. Please try again.`),process.exit(1)),console.log(`
2621
2621
  ✨ Starting Orion CLI...
2622
2622
  `)),t.isFirebaseAuthenticated()||(console.error(`
2623
2623
  ❌ Firebase authentication failed.`),console.error("This may be due to:"),console.error(" 1. Network connectivity issues"),console.error(" 2. Firewall blocking Firebase services (firebaseio.com)"),console.error(" 3. Temporary server issues"),console.error(`
2624
2624
  Please check your connection and try again.
2625
- `),process.exit(1)),console.log("✅ Authentication verified"),tr.getInstance().setWorkingDirectory(i),process.stdout.write("\x1B[2J\x1B[H");let{waitUntilExit:r}=kT(IT.createElement(wm,{initialProjectPath:i}),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:!1});await r(),$d()}import O from"chalk";import ae from"inquirer";import Ve from"ora";import{exec as PT}from"child_process";Te();var Gn=class{integrationsService;authService;constructor(){this.integrationsService=Gt.getInstance(),this.authService=X.getInstance()}async ensureAuthenticated(){let e=Ve("Checking authentication...").start();return await this.authService.autoAuthenticate(),this.authService.isAuthenticated()?(e.stop(),!0):(e.fail("Not authenticated"),console.log(O.gray('Run "orion auth login" first.')),!1)}openBrowser(e){let t=process.platform,n;t==="darwin"?n=`open "${e}"`:t==="win32"?n=`start "" "${e}"`:n=`xdg-open "${e}"`,PT(n,()=>{})}async discord(){if(!await this.ensureAuthenticated())return;console.log(O.blue(`
2626
- 🎮 Discord Integration`)),console.log(O.gray("─".repeat(50)));let e=Ve("Checking connection status...").start(),t=await this.integrationsService.getDiscordStatus();e.stop(),t.connected?await this.manageDiscord(t):await this.setupDiscord()}async manageDiscord(e){if(console.log(O.green(`
2625
+ `),process.exit(1)),console.log("✅ Authentication verified"),nr.getInstance().setWorkingDirectory(i),process.stdout.write("\x1B[2J\x1B[H");let{waitUntilExit:r}=kT(IT.createElement(wm,{initialProjectPath:i}),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:!1});await r(),$d()}import O from"chalk";import ce from"inquirer";import Xe from"ora";import{exec as PT}from"child_process";xe();var zn=class{integrationsService;authService;constructor(){this.integrationsService=jt.getInstance(),this.authService=X.getInstance()}async ensureAuthenticated(){let e=Xe("Checking authentication...").start();return await this.authService.autoAuthenticate(),this.authService.isAuthenticated()?(e.stop(),!0):(e.fail("Not authenticated"),console.log(O.gray('Run "orion auth login" first.')),!1)}openBrowser(e){let t=process.platform,n;t==="darwin"?n=`open "${e}"`:t==="win32"?n=`start "" "${e}"`:n=`xdg-open "${e}"`,PT(n,()=>{})}async discord(){if(!await this.ensureAuthenticated())return;console.log(O.blue(`
2626
+ 🎮 Discord Integration`)),console.log(O.gray("─".repeat(50)));let e=Xe("Checking connection status...").start(),t=await this.integrationsService.getDiscordStatus();e.stop(),t.connected?await this.manageDiscord(t):await this.setupDiscord()}async manageDiscord(e){if(console.log(O.green(`
2627
2627
  ✓ Connected`)),console.log(O.white(" Bot:"),O.cyan(e.botUsername||"Unknown")),console.log(O.gray(`
2628
2628
  ─ Setup Info ─`)),e.webhookUrl&&(console.log(O.white(" Webhook URL:"),O.cyan(e.webhookUrl)),console.log(O.gray(" (Add this to Discord Developer Portal → Interactions Endpoint URL)"))),e.botId){let n=this.integrationsService.generateDiscordInviteUrl(e.botId);console.log(O.white(" Invite URL:"),O.cyan(n))}console.log(O.gray(" Commands: /ask, /new, /clear")),console.log(O.gray(`
2629
2629
  ─ Access Control ─`)),console.log(O.white(" Owners:"),e.ownerUserIds?.length?e.ownerUserIds.join(", "):O.gray("None")),console.log(O.white(" Guests:"),e.guestUserIds?.length?e.guestUserIds.join(", "):O.gray("None")),console.log(O.gray(`
2630
- ─ Chat Mode ─`)),console.log(O.white(" Server chat:"),e.allowGuildChat?O.green("Enabled"):O.gray("Disabled (DM only)"));let{action:t}=await ae.prompt([{type:"list",name:"action",message:`
2631
- What would you like to do?`,choices:[{name:"📋 Copy webhook URL",value:"copy_webhook"},{name:"🔗 Open bot invite link",value:"invite"},{name:"👥 Update owners/guests",value:"update_users"},{name:e.allowGuildChat?"🔒 Disable server chat":"🌐 Enable server chat",value:"toggle_guild"},{name:"🔄 Reconnect with new token",value:"reconnect"},new ae.Separator,{name:O.red("🗑️ Disconnect"),value:"disconnect"},{name:"Cancel",value:"cancel"}]}]);switch(t){case"copy_webhook":e.webhookUrl&&(console.log(O.cyan(`
2630
+ ─ Chat Mode ─`)),console.log(O.white(" Server chat:"),e.allowGuildChat?O.green("Enabled"):O.gray("Disabled (DM only)"));let{action:t}=await ce.prompt([{type:"list",name:"action",message:`
2631
+ What would you like to do?`,choices:[{name:"📋 Copy webhook URL",value:"copy_webhook"},{name:"🔗 Open bot invite link",value:"invite"},{name:"👥 Update owners/guests",value:"update_users"},{name:e.allowGuildChat?"🔒 Disable server chat":"🌐 Enable server chat",value:"toggle_guild"},{name:"🔄 Reconnect with new token",value:"reconnect"},new ce.Separator,{name:O.red("🗑️ Disconnect"),value:"disconnect"},{name:"Cancel",value:"cancel"}]}]);switch(t){case"copy_webhook":e.webhookUrl&&(console.log(O.cyan(`
2632
2632
  ${e.webhookUrl}`)),console.log(O.green("(Copy the URL above)")));break;case"invite":if(e.botId){let n=this.integrationsService.generateDiscordInviteUrl(e.botId);console.log(O.gray(`
2633
2633
  Opening invite link...`)),this.openBrowser(n),console.log(O.cyan(n))}break;case"update_users":await this.updateDiscordUsers(e);break;case"toggle_guild":await this.toggleDiscordGuild(e,!e.allowGuildChat);break;case"reconnect":await this.disconnectDiscordQuiet(),await this.setupDiscord();break;case"disconnect":await this.disconnectDiscordConfirm();break}}async setupDiscord(){console.log(O.white(`
2634
- ─ Step 1: Create a Discord Bot ─`)),console.log(O.gray(" 1. Go to https://discord.com/developers/applications")),console.log(O.gray(' 2. Click "New Application" and name it')),console.log(O.gray(' 3. Go to "Bot" section in the sidebar')),console.log(O.gray(' 4. Click "Reset Token" to generate a new token')),console.log(O.gray(' 5. Enable "Message Content Intent" under Privileged Gateway Intents')),console.log(O.gray(" 6. Copy the bot token"));let{openPortal:e}=await ae.prompt([{type:"confirm",name:"openPortal",message:"Open Discord Developer Portal in browser?",default:!0}]);e&&this.openBrowser("https://discord.com/developers/applications"),console.log(O.white(`
2635
- ─ Step 2: Enter Bot Token ─`));let{botToken:t}=await ae.prompt([{type:"password",name:"botToken",message:"Bot Token:",mask:"*",validate:l=>l?.trim()?this.integrationsService.validateDiscordToken(l)?!0:"Invalid token format. Discord tokens look like: NzE2MjE0....":"Bot token is required"}]);console.log(O.white(`
2634
+ ─ Step 1: Create a Discord Bot ─`)),console.log(O.gray(" 1. Go to https://discord.com/developers/applications")),console.log(O.gray(' 2. Click "New Application" and name it')),console.log(O.gray(' 3. Go to "Bot" section in the sidebar')),console.log(O.gray(' 4. Click "Reset Token" to generate a new token')),console.log(O.gray(' 5. Enable "Message Content Intent" under Privileged Gateway Intents')),console.log(O.gray(" 6. Copy the bot token"));let{openPortal:e}=await ce.prompt([{type:"confirm",name:"openPortal",message:"Open Discord Developer Portal in browser?",default:!0}]);e&&this.openBrowser("https://discord.com/developers/applications"),console.log(O.white(`
2635
+ ─ Step 2: Enter Bot Token ─`));let{botToken:t}=await ce.prompt([{type:"password",name:"botToken",message:"Bot Token:",mask:"*",validate:l=>l?.trim()?this.integrationsService.validateDiscordToken(l)?!0:"Invalid token format. Discord tokens look like: NzE2MjE0....":"Bot token is required"}]);console.log(O.white(`
2636
2636
  ─ Step 3: Access Control ─`)),console.log(O.gray(" Owners: Full access including device tools (files, browser, apps)")),console.log(O.gray(" Guests: Cloud-only tools, sandboxed conversations")),console.log(O.yellow(` ⚠️ Only add people you fully trust as owners.
2637
- `));let{ownerIds:n}=await ae.prompt([{type:"input",name:"ownerIds",message:"Owner Discord User IDs (comma-separated):",validate:l=>l?.trim()?!0:"At least one owner is required"}]),{guestIds:s}=await ae.prompt([{type:"input",name:"guestIds",message:"Guest Discord User IDs (optional, press Enter to skip):"}]),r=!1,{allowGuild:o}=await ae.prompt([{type:"confirm",name:"allowGuild",message:"Allow server/guild chat? (or DM only)",default:!1}]);if(o){console.log(O.yellow(`
2638
- ⚠️ Warning: Server chat means others in the server can see bot responses.`));let{confirmGuild:l}=await ae.prompt([{type:"confirm",name:"confirmGuild",message:"Are you sure you want to enable server chat?",default:!1}]);l?r=!0:console.log(O.gray("Server chat will be disabled."))}let a=Ve("Connecting to Discord...").start(),c=await this.integrationsService.connectDiscord({botToken:t.trim(),ownerUserIds:n.split(",").map(l=>l.trim()).filter(Boolean),guestUserIds:s?s.split(",").map(l=>l.trim()).filter(Boolean):[],allowGuildChat:r});if(c.success){if(a.succeed("Discord bot connected!"),console.log(O.white(`
2637
+ `));let{ownerIds:n}=await ce.prompt([{type:"input",name:"ownerIds",message:"Owner Discord User IDs (comma-separated):",validate:l=>l?.trim()?!0:"At least one owner is required"}]),{guestIds:s}=await ce.prompt([{type:"input",name:"guestIds",message:"Guest Discord User IDs (optional, press Enter to skip):"}]),r=!1,{allowGuild:o}=await ce.prompt([{type:"confirm",name:"allowGuild",message:"Allow server/guild chat? (or DM only)",default:!1}]);if(o){console.log(O.yellow(`
2638
+ ⚠️ Warning: Server chat means others in the server can see bot responses.`));let{confirmGuild:l}=await ce.prompt([{type:"confirm",name:"confirmGuild",message:"Are you sure you want to enable server chat?",default:!1}]);l?r=!0:console.log(O.gray("Server chat will be disabled."))}let a=Xe("Connecting to Discord...").start(),c=await this.integrationsService.connectDiscord({botToken:t.trim(),ownerUserIds:n.split(",").map(l=>l.trim()).filter(Boolean),guestUserIds:s?s.split(",").map(l=>l.trim()).filter(Boolean):[],allowGuildChat:r});if(c.success){if(a.succeed("Discord bot connected!"),console.log(O.white(`
2639
2639
  ─ Finish Setup ─`)),console.log(O.white(" Bot:"),O.cyan(c.botUsername)),c.webhookUrl&&(console.log(O.white(`
2640
2640
  1. Set Interactions Endpoint URL:`)),console.log(O.cyan(` ${c.webhookUrl}`)),console.log(O.gray(" (Copy this to Discord Developer Portal → Your App → General Information)"))),c.botId){let l=this.integrationsService.generateDiscordInviteUrl(c.botId);console.log(O.white(`
2641
- 2. Invite bot to your server:`)),console.log(O.cyan(` ${l}`));let{openInvite:d}=await ae.prompt([{type:"confirm",name:"openInvite",message:"Open invite link now?",default:!0}]);d&&this.openBrowser(l)}console.log(O.white(`
2641
+ 2. Invite bot to your server:`)),console.log(O.cyan(` ${l}`));let{openInvite:d}=await ce.prompt([{type:"confirm",name:"openInvite",message:"Open invite link now?",default:!0}]);d&&this.openBrowser(l)}console.log(O.white(`
2642
2642
  3. Start chatting!`)),console.log(O.gray(" Use /ask, /new, or /clear commands in Discord"))}else a.fail(`Connection failed: ${c.error}`)}async updateDiscordUsers(e){console.log(O.gray(`
2643
- Current owners:`),e.ownerUserIds?.join(", ")||"None"),console.log(O.gray("Current guests:"),e.guestUserIds?.join(", ")||"None");let{ownerIds:t}=await ae.prompt([{type:"input",name:"ownerIds",message:"Owner User IDs (comma-separated):",default:e.ownerUserIds?.join(", ")||"",validate:o=>o?.trim()?!0:"At least one owner required"}]),{guestIds:n}=await ae.prompt([{type:"input",name:"guestIds",message:"Guest User IDs (optional):",default:e.guestUserIds?.join(", ")||""}]),s=Ve("Updating...").start(),r=await this.integrationsService.updateDiscord({ownerUserIds:t.split(",").map(o=>o.trim()).filter(Boolean),guestUserIds:n?n.split(",").map(o=>o.trim()).filter(Boolean):[]});r.success?s.succeed("Updated successfully."):s.fail(`Update failed: ${r.error}`)}async toggleDiscordGuild(e,t){if(t){console.log(O.yellow(`
2644
- ⚠️ Warning: Enabling server chat means:`)),console.log(O.gray(" - Bot will respond in server channels (not just DMs)")),console.log(O.gray(" - Others in the server can see bot responses"));let{confirm:r}=await ae.prompt([{type:"confirm",name:"confirm",message:"Enable server chat?",default:!1}]);if(!r){console.log(O.gray("Cancelled."));return}}let n=Ve(`${t?"Enabling":"Disabling"} server chat...`).start(),s=await this.integrationsService.updateDiscord({allowGuildChat:t});s.success?n.succeed(`Server chat ${t?"enabled":"disabled"}.`):n.fail(`Failed: ${s.error}`)}async disconnectDiscordConfirm(){let{confirm:e}=await ae.prompt([{type:"confirm",name:"confirm",message:O.red("Disconnect Discord bot? This cannot be undone."),default:!1}]);if(!e){console.log(O.gray("Cancelled."));return}let t=Ve("Disconnecting...").start();await this.integrationsService.disconnectDiscord()?t.succeed("Discord disconnected."):t.fail("Failed to disconnect.")}async disconnectDiscordQuiet(){await this.integrationsService.disconnectDiscord()}async telegram(){if(!await this.ensureAuthenticated())return;console.log(O.blue(`
2645
- 📱 Telegram Integration`)),console.log(O.gray("─".repeat(50)));let e=Ve("Checking connection status...").start(),t=await this.integrationsService.getTelegramStatus();e.stop(),t.connected?await this.manageTelegram(t):await this.setupTelegram()}async manageTelegram(e){console.log(O.green(`
2643
+ Current owners:`),e.ownerUserIds?.join(", ")||"None"),console.log(O.gray("Current guests:"),e.guestUserIds?.join(", ")||"None");let{ownerIds:t}=await ce.prompt([{type:"input",name:"ownerIds",message:"Owner User IDs (comma-separated):",default:e.ownerUserIds?.join(", ")||"",validate:o=>o?.trim()?!0:"At least one owner required"}]),{guestIds:n}=await ce.prompt([{type:"input",name:"guestIds",message:"Guest User IDs (optional):",default:e.guestUserIds?.join(", ")||""}]),s=Xe("Updating...").start(),r=await this.integrationsService.updateDiscord({ownerUserIds:t.split(",").map(o=>o.trim()).filter(Boolean),guestUserIds:n?n.split(",").map(o=>o.trim()).filter(Boolean):[]});r.success?s.succeed("Updated successfully."):s.fail(`Update failed: ${r.error}`)}async toggleDiscordGuild(e,t){if(t){console.log(O.yellow(`
2644
+ ⚠️ Warning: Enabling server chat means:`)),console.log(O.gray(" - Bot will respond in server channels (not just DMs)")),console.log(O.gray(" - Others in the server can see bot responses"));let{confirm:r}=await ce.prompt([{type:"confirm",name:"confirm",message:"Enable server chat?",default:!1}]);if(!r){console.log(O.gray("Cancelled."));return}}let n=Xe(`${t?"Enabling":"Disabling"} server chat...`).start(),s=await this.integrationsService.updateDiscord({allowGuildChat:t});s.success?n.succeed(`Server chat ${t?"enabled":"disabled"}.`):n.fail(`Failed: ${s.error}`)}async disconnectDiscordConfirm(){let{confirm:e}=await ce.prompt([{type:"confirm",name:"confirm",message:O.red("Disconnect Discord bot? This cannot be undone."),default:!1}]);if(!e){console.log(O.gray("Cancelled."));return}let t=Xe("Disconnecting...").start();await this.integrationsService.disconnectDiscord()?t.succeed("Discord disconnected."):t.fail("Failed to disconnect.")}async disconnectDiscordQuiet(){await this.integrationsService.disconnectDiscord()}async telegram(){if(!await this.ensureAuthenticated())return;console.log(O.blue(`
2645
+ 📱 Telegram Integration`)),console.log(O.gray("─".repeat(50)));let e=Xe("Checking connection status...").start(),t=await this.integrationsService.getTelegramStatus();e.stop(),t.connected?await this.manageTelegram(t):await this.setupTelegram()}async manageTelegram(e){console.log(O.green(`
2646
2646
  ✓ Connected`)),console.log(O.white(" Bot:"),O.cyan(`@${e.botUsername}`));let t=this.integrationsService.getTelegramChatUrl(e.botUsername||"");console.log(O.white(" Chat:"),O.cyan(t)),console.log(O.gray(" 💡 Send /new to start a fresh conversation. Memory persists.")),console.log(O.gray(`
2647
2647
  ─ Access Control ─`)),console.log(O.white(" Owners:"),e.ownerUsernames?.length?e.ownerUsernames.map(r=>`@${r}`).join(", "):O.gray("None")),console.log(O.white(" Guests:"),e.guestUsernames?.length?e.guestUsernames.map(r=>`@${r}`).join(", "):O.gray("None")),console.log(O.gray(`
2648
- ─ Chat Mode ─`)),console.log(O.white(" Group chat:"),e.allowGroupChat?O.green("Enabled"):O.gray("Disabled (DM only)")),e.allowGroupChat&&console.log(O.white(" Route to DM:"),e.routeToDM?O.green("Enabled"):O.gray("Disabled"));let n=[{name:"💬 Open chat in Telegram",value:"open_chat"},{name:"👥 Update owners/guests",value:"update_users"},{name:e.allowGroupChat?"🔒 Disable group chat":"🌐 Enable group chat",value:"toggle_group"}];e.allowGroupChat&&n.push({name:e.routeToDM?"📥 Disable route to DM":"📤 Enable route to DM",value:"toggle_route_dm"}),n.push({name:"🔄 Reconnect with new token",value:"reconnect"},new ae.Separator,{name:O.red("🗑️ Disconnect"),value:"disconnect"},{name:"Cancel",value:"cancel"});let{action:s}=await ae.prompt([{type:"list",name:"action",message:`
2648
+ ─ Chat Mode ─`)),console.log(O.white(" Group chat:"),e.allowGroupChat?O.green("Enabled"):O.gray("Disabled (DM only)")),e.allowGroupChat&&console.log(O.white(" Route to DM:"),e.routeToDM?O.green("Enabled"):O.gray("Disabled"));let n=[{name:"💬 Open chat in Telegram",value:"open_chat"},{name:"👥 Update owners/guests",value:"update_users"},{name:e.allowGroupChat?"🔒 Disable group chat":"🌐 Enable group chat",value:"toggle_group"}];e.allowGroupChat&&n.push({name:e.routeToDM?"📥 Disable route to DM":"📤 Enable route to DM",value:"toggle_route_dm"}),n.push({name:"🔄 Reconnect with new token",value:"reconnect"},new ce.Separator,{name:O.red("🗑️ Disconnect"),value:"disconnect"},{name:"Cancel",value:"cancel"});let{action:s}=await ce.prompt([{type:"list",name:"action",message:`
2649
2649
  What would you like to do?`,choices:n}]);switch(s){case"open_chat":console.log(O.gray(`
2650
2650
  Opening Telegram...`)),this.openBrowser(t);break;case"update_users":await this.updateTelegramUsers(e);break;case"toggle_group":await this.toggleTelegramGroup(e,!e.allowGroupChat);break;case"toggle_route_dm":await this.toggleTelegramRouteDM(e,!e.routeToDM);break;case"reconnect":await this.disconnectTelegramQuiet(),await this.setupTelegram();break;case"disconnect":await this.disconnectTelegramConfirm();break}}async setupTelegram(){console.log(O.white(`
2651
- ─ Step 1: Create a Telegram Bot ─`)),console.log(O.gray(" 1. Open Telegram and search for @BotFather")),console.log(O.gray(" 2. Send /newbot command")),console.log(O.gray(" 3. Choose a name and username for your bot")),console.log(O.gray(" 4. Copy the bot token"));let{openBotFather:e}=await ae.prompt([{type:"confirm",name:"openBotFather",message:"Open @BotFather in Telegram?",default:!0}]);e&&this.openBrowser("https://t.me/BotFather"),console.log(O.white(`
2652
- ─ Step 2: Enter Bot Token ─`));let{botToken:t}=await ae.prompt([{type:"password",name:"botToken",message:"Bot Token:",mask:"*",validate:d=>d?.trim()?this.integrationsService.validateTelegramToken(d)?!0:"Invalid token format. Telegram tokens look like: 123456789:ABCdef...":"Bot token is required"}]);console.log(O.white(`
2651
+ ─ Step 1: Create a Telegram Bot ─`)),console.log(O.gray(" 1. Open Telegram and search for @BotFather")),console.log(O.gray(" 2. Send /newbot command")),console.log(O.gray(" 3. Choose a name and username for your bot")),console.log(O.gray(" 4. Copy the bot token"));let{openBotFather:e}=await ce.prompt([{type:"confirm",name:"openBotFather",message:"Open @BotFather in Telegram?",default:!0}]);e&&this.openBrowser("https://t.me/BotFather"),console.log(O.white(`
2652
+ ─ Step 2: Enter Bot Token ─`));let{botToken:t}=await ce.prompt([{type:"password",name:"botToken",message:"Bot Token:",mask:"*",validate:d=>d?.trim()?this.integrationsService.validateTelegramToken(d)?!0:"Invalid token format. Telegram tokens look like: 123456789:ABCdef...":"Bot token is required"}]);console.log(O.white(`
2653
2653
  ─ Step 3: Access Control ─`)),console.log(O.gray(" Owners: Full access including device tools (files, browser, apps)")),console.log(O.gray(" Guests: Cloud-only tools, sandboxed conversations")),console.log(O.yellow(` ⚠️ Only add people you fully trust as owners.
2654
- `));let{ownerUsernames:n}=await ae.prompt([{type:"input",name:"ownerUsernames",message:"Owner Telegram usernames (with @, comma-separated):",validate:d=>d?.trim()?!0:"At least one owner is required"}]),{guestUsernames:s}=await ae.prompt([{type:"input",name:"guestUsernames",message:"Guest usernames (optional, press Enter to skip):"}]);console.log(O.white(`
2655
- ─ Step 4: Chat Settings ─`));let r=!1,o=!1,{allowGroup:a}=await ae.prompt([{type:"confirm",name:"allowGroup",message:"Allow group chat? (or DM only)",default:!1}]);if(a){console.log(O.yellow(`
2654
+ `));let{ownerUsernames:n}=await ce.prompt([{type:"input",name:"ownerUsernames",message:"Owner Telegram usernames (with @, comma-separated):",validate:d=>d?.trim()?!0:"At least one owner is required"}]),{guestUsernames:s}=await ce.prompt([{type:"input",name:"guestUsernames",message:"Guest usernames (optional, press Enter to skip):"}]);console.log(O.white(`
2655
+ ─ Step 4: Chat Settings ─`));let r=!1,o=!1,{allowGroup:a}=await ce.prompt([{type:"confirm",name:"allowGroup",message:"Allow group chat? (or DM only)",default:!1}]);if(a){console.log(O.yellow(`
2656
2656
  ⚠️ For group chat, you need to disable Privacy Mode:`)),console.log(O.gray(" 1. Open @BotFather")),console.log(O.gray(" 2. Send /setprivacy")),console.log(O.gray(" 3. Select your bot")),console.log(O.gray(' 4. Choose "Disable"')),console.log(O.gray(` Without this, the bot only responds to /commands in groups.
2657
- `));let{confirmGroup:d}=await ae.prompt([{type:"confirm",name:"confirmGroup",message:"I understand. Enable group chat?",default:!0}]);if(d){r=!0;let{enableRouteDM:g}=await ae.prompt([{type:"confirm",name:"enableRouteDM",message:"Route group responses to DM? (keeps group chat clean)",default:!1}]);o=g}else console.log(O.gray("Group chat will be disabled."))}let c=Ve("Connecting to Telegram...").start(),l=await this.integrationsService.connectTelegram({botToken:t.trim(),ownerUsernames:n.split(",").map(d=>d.trim().replace(/^@/,"")).filter(Boolean),guestUsernames:s?s.split(",").map(d=>d.trim().replace(/^@/,"")).filter(Boolean):[],allowGroupChat:r,routeToDM:o});if(l.success){c.succeed("Telegram bot connected!");let d=this.integrationsService.getTelegramChatUrl(l.botUsername||"");console.log(O.white(`
2657
+ `));let{confirmGroup:d}=await ce.prompt([{type:"confirm",name:"confirmGroup",message:"I understand. Enable group chat?",default:!0}]);if(d){r=!0;let{enableRouteDM:g}=await ce.prompt([{type:"confirm",name:"enableRouteDM",message:"Route group responses to DM? (keeps group chat clean)",default:!1}]);o=g}else console.log(O.gray("Group chat will be disabled."))}let c=Xe("Connecting to Telegram...").start(),l=await this.integrationsService.connectTelegram({botToken:t.trim(),ownerUsernames:n.split(",").map(d=>d.trim().replace(/^@/,"")).filter(Boolean),guestUsernames:s?s.split(",").map(d=>d.trim().replace(/^@/,"")).filter(Boolean):[],allowGroupChat:r,routeToDM:o});if(l.success){c.succeed("Telegram bot connected!");let d=this.integrationsService.getTelegramChatUrl(l.botUsername||"");console.log(O.white(`
2658
2658
  Bot:`),O.cyan(`@${l.botUsername}`)),console.log(O.white(" Chat:"),O.cyan(d)),console.log(O.gray(`
2659
- 💡 Send /new to start a fresh conversation.`));let{openChat:g}=await ae.prompt([{type:"confirm",name:"openChat",message:"Open chat in Telegram?",default:!0}]);g&&this.openBrowser(d)}else c.fail(`Connection failed: ${l.error}`)}async updateTelegramUsers(e){console.log(O.gray(`
2660
- Current owners:`),e.ownerUsernames?.map(o=>`@${o}`).join(", ")||"None"),console.log(O.gray("Current guests:"),e.guestUsernames?.map(o=>`@${o}`).join(", ")||"None");let{ownerUsernames:t}=await ae.prompt([{type:"input",name:"ownerUsernames",message:"Owner usernames (with @, comma-separated):",default:e.ownerUsernames?.map(o=>`@${o}`).join(", ")||"",validate:o=>o?.trim()?!0:"At least one owner required"}]),{guestUsernames:n}=await ae.prompt([{type:"input",name:"guestUsernames",message:"Guest usernames (optional):",default:e.guestUsernames?.map(o=>`@${o}`).join(", ")||""}]),s=Ve("Updating...").start(),r=await this.integrationsService.updateTelegram({ownerUsernames:t.split(",").map(o=>o.trim().replace(/^@/,"")).filter(Boolean),guestUsernames:n?n.split(",").map(o=>o.trim().replace(/^@/,"")).filter(Boolean):[]});r.success?s.succeed("Updated successfully."):s.fail(`Update failed: ${r.error}`)}async toggleTelegramGroup(e,t){if(t){console.log(O.yellow(`
2659
+ 💡 Send /new to start a fresh conversation.`));let{openChat:g}=await ce.prompt([{type:"confirm",name:"openChat",message:"Open chat in Telegram?",default:!0}]);g&&this.openBrowser(d)}else c.fail(`Connection failed: ${l.error}`)}async updateTelegramUsers(e){console.log(O.gray(`
2660
+ Current owners:`),e.ownerUsernames?.map(o=>`@${o}`).join(", ")||"None"),console.log(O.gray("Current guests:"),e.guestUsernames?.map(o=>`@${o}`).join(", ")||"None");let{ownerUsernames:t}=await ce.prompt([{type:"input",name:"ownerUsernames",message:"Owner usernames (with @, comma-separated):",default:e.ownerUsernames?.map(o=>`@${o}`).join(", ")||"",validate:o=>o?.trim()?!0:"At least one owner required"}]),{guestUsernames:n}=await ce.prompt([{type:"input",name:"guestUsernames",message:"Guest usernames (optional):",default:e.guestUsernames?.map(o=>`@${o}`).join(", ")||""}]),s=Xe("Updating...").start(),r=await this.integrationsService.updateTelegram({ownerUsernames:t.split(",").map(o=>o.trim().replace(/^@/,"")).filter(Boolean),guestUsernames:n?n.split(",").map(o=>o.trim().replace(/^@/,"")).filter(Boolean):[]});r.success?s.succeed("Updated successfully."):s.fail(`Update failed: ${r.error}`)}async toggleTelegramGroup(e,t){if(t){console.log(O.yellow(`
2661
2661
  ⚠️ To use group chat, disable Privacy Mode in @BotFather:`)),console.log(O.gray(" /setprivacy → Select your bot → Disable")),console.log(O.gray(` Without this, the bot only responds to /commands in groups.
2662
- `));let{confirm:r}=await ae.prompt([{type:"confirm",name:"confirm",message:"Enable group chat?",default:!1}]);if(!r){console.log(O.gray("Cancelled."));return}}let n=Ve(`${t?"Enabling":"Disabling"} group chat...`).start(),s=await this.integrationsService.updateTelegram({allowGroupChat:t,routeToDM:t?e.routeToDM:!1});s.success?n.succeed(`Group chat ${t?"enabled":"disabled"}.`):n.fail(`Failed: ${s.error}`)}async toggleTelegramRouteDM(e,t){let n=Ve(`${t?"Enabling":"Disabling"} route to DM...`).start(),s=await this.integrationsService.updateTelegram({routeToDM:t});s.success?(n.succeed(`Route to DM ${t?"enabled":"disabled"}.`),t&&console.log(O.gray(" Group responses will be sent via private DM."))):n.fail(`Failed: ${s.error}`)}async disconnectTelegramConfirm(){let{confirm:e}=await ae.prompt([{type:"confirm",name:"confirm",message:O.red("Disconnect Telegram bot? This cannot be undone."),default:!1}]);if(!e){console.log(O.gray("Cancelled."));return}let t=Ve("Disconnecting...").start();await this.integrationsService.disconnectTelegram()?t.succeed("Telegram disconnected."):t.fail("Failed to disconnect.")}async disconnectTelegramQuiet(){await this.integrationsService.disconnectTelegram()}async status(){if(!await this.ensureAuthenticated())return;console.log(O.blue(`
2663
- 🔌 Integration Status`)),console.log(O.gray("─".repeat(50)));let e=Ve("Checking...").start(),[t,n]=await Promise.all([this.integrationsService.getDiscordStatus(),this.integrationsService.getTelegramStatus()]);e.stop(),console.log(O.white(`
2662
+ `));let{confirm:r}=await ce.prompt([{type:"confirm",name:"confirm",message:"Enable group chat?",default:!1}]);if(!r){console.log(O.gray("Cancelled."));return}}let n=Xe(`${t?"Enabling":"Disabling"} group chat...`).start(),s=await this.integrationsService.updateTelegram({allowGroupChat:t,routeToDM:t?e.routeToDM:!1});s.success?n.succeed(`Group chat ${t?"enabled":"disabled"}.`):n.fail(`Failed: ${s.error}`)}async toggleTelegramRouteDM(e,t){let n=Xe(`${t?"Enabling":"Disabling"} route to DM...`).start(),s=await this.integrationsService.updateTelegram({routeToDM:t});s.success?(n.succeed(`Route to DM ${t?"enabled":"disabled"}.`),t&&console.log(O.gray(" Group responses will be sent via private DM."))):n.fail(`Failed: ${s.error}`)}async disconnectTelegramConfirm(){let{confirm:e}=await ce.prompt([{type:"confirm",name:"confirm",message:O.red("Disconnect Telegram bot? This cannot be undone."),default:!1}]);if(!e){console.log(O.gray("Cancelled."));return}let t=Xe("Disconnecting...").start();await this.integrationsService.disconnectTelegram()?t.succeed("Telegram disconnected."):t.fail("Failed to disconnect.")}async disconnectTelegramQuiet(){await this.integrationsService.disconnectTelegram()}async status(){if(!await this.ensureAuthenticated())return;console.log(O.blue(`
2663
+ 🔌 Integration Status`)),console.log(O.gray("─".repeat(50)));let e=Xe("Checking...").start(),[t,n]=await Promise.all([this.integrationsService.getDiscordStatus(),this.integrationsService.getTelegramStatus()]);e.stop(),console.log(O.white(`
2664
2664
  Discord`)),t.connected?(console.log(O.green(" ✓ Connected")),console.log(O.gray(` Bot: ${t.botUsername}`)),console.log(O.gray(` Owners: ${t.ownerUserIds?.join(", ")||"None"}`)),console.log(O.gray(` Guests: ${t.guestUserIds?.length?t.guestUserIds.join(", "):"None"}`)),console.log(O.gray(` Server chat: ${t.allowGuildChat?"Enabled":"Disabled"}`))):(console.log(O.gray(" Not connected")),console.log(O.gray(" Run: orion integrations discord"))),console.log(O.white(`
2665
- Telegram`)),n.connected?(console.log(O.green(" ✓ Connected")),console.log(O.gray(` Bot: @${n.botUsername}`)),console.log(O.gray(` Owners: ${n.ownerUsernames?.map(s=>`@${s}`).join(", ")||"None"}`)),console.log(O.gray(` Guests: ${n.guestUsernames?.length?n.guestUsernames.map(s=>`@${s}`).join(", "):"None"}`)),console.log(O.gray(` Group chat: ${n.allowGroupChat?"Enabled":"Disabled"}`)),n.allowGroupChat&&console.log(O.gray(` Route to DM: ${n.routeToDM?"Enabled":"Disabled"}`))):(console.log(O.gray(" Not connected")),console.log(O.gray(" Run: orion integrations telegram")))}async disconnect(){if(!await this.ensureAuthenticated())return;let e=Ve("Checking connections...").start(),[t,n]=await Promise.all([this.integrationsService.getDiscordStatus(),this.integrationsService.getTelegramStatus()]);e.stop();let s=[];if(t.connected&&s.push({name:`🎮 Discord (${t.botUsername})`,value:"discord"}),n.connected&&s.push({name:`📱 Telegram (@${n.botUsername})`,value:"telegram"}),s.length===0){console.log(O.yellow(`
2666
- ⚠️ No integrations connected.`));return}s.push(new ae.Separator,{name:"Cancel",value:"cancel"});let{platform:r}=await ae.prompt([{type:"list",name:"platform",message:"Which integration to disconnect?",choices:s}]);if(r==="cancel")return;let{confirm:o}=await ae.prompt([{type:"confirm",name:"confirm",message:O.red(`Disconnect ${r}? This cannot be undone.`),default:!1}]);if(!o){console.log(O.gray("Cancelled."));return}let a=Ve("Disconnecting...").start();(r==="discord"?await this.integrationsService.disconnectDiscord():await this.integrationsService.disconnectTelegram())?a.succeed(`${r.charAt(0).toUpperCase()+r.slice(1)} disconnected.`):a.fail("Failed to disconnect.")}};Vt();import DT from"dotenv";import{fileURLToPath as MT}from"url";import{dirname as RT,join as OT}from"path";import{readFileSync as NT}from"fs";DT.config();var _T=MT(import.meta.url),$T=RT(_T),Mm=JSON.parse(NT(OT($T,"..","package.json"),"utf8")),FT=process.argv.includes("--no-update")||process.env.ORION_NO_UPDATE==="true";!sd()&&!FT&&is.getInstance(Mm.version).checkAndUpdate().catch(()=>{});var jn=new AT;jn.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(Mm.version).option("--no-update","Disable automatic update check");jn.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await Ac()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});jn.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(i,e)=>{try{let{ServiceManager:t}=await Promise.resolve().then(()=>(Pc(),Am)),n=t.getInstance();console.log("🔧 Initializing Orion services..."),await n.initialize(),await n.waitForDeviceRegistration();let s=pe.find(o=>o.name===e.model)||pe[0];console.log("💭 Sending message...");let r=await n.sendMessage(i,s,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(Cr(r))}catch(t){ke.stopSpinner(!1),console.error(ke.formatError(t.message)),process.exit(1)}});var Dc=jn.command("auth").description("Authentication commands");Dc.command("login").description("Login to Orion").action(async()=>{try{await new vn().login()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});Dc.command("logout").description("Logout from Orion").action(async()=>{try{await new vn().logout()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});Dc.command("status").description("Check authentication status").action(async()=>{try{await new vn().status()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});var mi=jn.command("integrations").description("Manage Discord and Telegram integrations");mi.command("discord").description("Setup Discord bot integration").action(async()=>{try{await new Gn().discord()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});mi.command("telegram").description("Setup Telegram bot integration").action(async()=>{try{await new Gn().telegram()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});mi.command("status").description("Show integration status").action(async()=>{try{await new Gn().status()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});mi.command("disconnect").description("Disconnect an integration").action(async()=>{try{await new Gn().disconnect()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});jn.command("models").description("List available AI models").action(()=>{ke.printHeader("Available Models");for(let i of pe)console.log(`${ke.formatModelName(i.name)} - ${i.displayName}`)});process.argv.length===2?Ac().catch(i=>{console.error(ke.formatError(i.message)),process.exit(1)}):jn.parse(process.argv);
2665
+ Telegram`)),n.connected?(console.log(O.green(" ✓ Connected")),console.log(O.gray(` Bot: @${n.botUsername}`)),console.log(O.gray(` Owners: ${n.ownerUsernames?.map(s=>`@${s}`).join(", ")||"None"}`)),console.log(O.gray(` Guests: ${n.guestUsernames?.length?n.guestUsernames.map(s=>`@${s}`).join(", "):"None"}`)),console.log(O.gray(` Group chat: ${n.allowGroupChat?"Enabled":"Disabled"}`)),n.allowGroupChat&&console.log(O.gray(` Route to DM: ${n.routeToDM?"Enabled":"Disabled"}`))):(console.log(O.gray(" Not connected")),console.log(O.gray(" Run: orion integrations telegram")))}async disconnect(){if(!await this.ensureAuthenticated())return;let e=Xe("Checking connections...").start(),[t,n]=await Promise.all([this.integrationsService.getDiscordStatus(),this.integrationsService.getTelegramStatus()]);e.stop();let s=[];if(t.connected&&s.push({name:`🎮 Discord (${t.botUsername})`,value:"discord"}),n.connected&&s.push({name:`📱 Telegram (@${n.botUsername})`,value:"telegram"}),s.length===0){console.log(O.yellow(`
2666
+ ⚠️ No integrations connected.`));return}s.push(new ce.Separator,{name:"Cancel",value:"cancel"});let{platform:r}=await ce.prompt([{type:"list",name:"platform",message:"Which integration to disconnect?",choices:s}]);if(r==="cancel")return;let{confirm:o}=await ce.prompt([{type:"confirm",name:"confirm",message:O.red(`Disconnect ${r}? This cannot be undone.`),default:!1}]);if(!o){console.log(O.gray("Cancelled."));return}let a=Xe("Disconnecting...").start();(r==="discord"?await this.integrationsService.disconnectDiscord():await this.integrationsService.disconnectTelegram())?a.succeed(`${r.charAt(0).toUpperCase()+r.slice(1)} disconnected.`):a.fail("Failed to disconnect.")}};Xt();import DT from"dotenv";import{fileURLToPath as MT}from"url";import{dirname as RT,join as OT}from"path";import{readFileSync as NT}from"fs";DT.config();var _T=MT(import.meta.url),$T=RT(_T),Mm=JSON.parse(NT(OT($T,"..","package.json"),"utf8")),FT=process.argv.includes("--no-update")||process.env.ORION_NO_UPDATE==="true";!sd()&&!FT&&cs.getInstance(Mm.version).checkAndUpdate().catch(()=>{});var qn=new AT;qn.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(Mm.version).option("--no-update","Disable automatic update check");qn.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await Ac()}catch(i){console.error(Pe.formatError(i.message)),process.exit(1)}});qn.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(i,e)=>{try{let{ServiceManager:t}=await Promise.resolve().then(()=>(Pc(),Am)),n=t.getInstance();console.log("🔧 Initializing Orion services..."),await n.initialize(),await n.waitForDeviceRegistration();let s=pe.find(o=>o.name===e.model)||pe[0];console.log("💭 Sending message...");let r=await n.sendMessage(i,s,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(Er(r))}catch(t){Pe.stopSpinner(!1),console.error(Pe.formatError(t.message)),process.exit(1)}});var Dc=qn.command("auth").description("Authentication commands");Dc.command("login").description("Login to Orion").action(async()=>{try{await new wn().login()}catch(i){console.error(Pe.formatError(i.message)),process.exit(1)}});Dc.command("logout").description("Logout from Orion").action(async()=>{try{await new wn().logout()}catch(i){console.error(Pe.formatError(i.message)),process.exit(1)}});Dc.command("status").description("Check authentication status").action(async()=>{try{await new wn().status()}catch(i){console.error(Pe.formatError(i.message)),process.exit(1)}});var mi=qn.command("integrations").description("Manage Discord and Telegram integrations");mi.command("discord").description("Setup Discord bot integration").action(async()=>{try{await new zn().discord()}catch(i){console.error(Pe.formatError(i.message)),process.exit(1)}});mi.command("telegram").description("Setup Telegram bot integration").action(async()=>{try{await new zn().telegram()}catch(i){console.error(Pe.formatError(i.message)),process.exit(1)}});mi.command("status").description("Show integration status").action(async()=>{try{await new zn().status()}catch(i){console.error(Pe.formatError(i.message)),process.exit(1)}});mi.command("disconnect").description("Disconnect an integration").action(async()=>{try{await new zn().disconnect()}catch(i){console.error(Pe.formatError(i.message)),process.exit(1)}});qn.command("models").description("List available AI models").action(()=>{Pe.printHeader("Available Models");for(let i of pe)console.log(`${Pe.formatModelName(i.name)} - ${i.displayName}`)});process.argv.length===2?Ac().catch(i=>{console.error(Pe.formatError(i.message)),process.exit(1)}):qn.parse(process.argv);