@zinley/orion 1.2.36 → 1.2.37

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 +122 -122
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- var ap=Object.defineProperty;var L=(i,e)=>()=>(i&&(e=i(i=0)),e);var Ue=(i,e)=>{for(var t in e)ap(i,t,{get:e[t],enumerable:!0})};var ye,en=L(()=>{"use strict";ye=[{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 Ai,u,V=L(()=>{"use strict";Ai=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=Ai.getInstance()});var Rt={};Ue(Rt,{UserDefaults:()=>fe});import _s from"fs";import Di from"path";import up from"os";var Mi,fe,ze=L(()=>{"use strict";V();Mi=class i{static instance;preferencesPath;preferences={};constructor(){let e=Di.join(up.homedir(),".orion");this.preferencesPath=Di.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadPreferences(){try{if(_s.existsSync(this.preferencesPath)){let e=_s.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=Di.dirname(this.preferencesPath);_s.existsSync(e)||_s.mkdirSync(e,{recursive:!0}),_s.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)}},fe=Mi.getInstance()});var Pe,Pn=L(()=>{"use strict";en();ze();V();Pe=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=fe.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=3?e:0}static setUserTier(e){fe.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 ye.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 Ae from"@sentry/node";var Ri,Ni,el=L(()=>{"use strict";V();Ri=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&&Ae.setUser({id:e,email:t,subscription:n})}setDevice(e){this.deviceId=e,this.isEnabled&&Ae.setTag("device_id",e)}clearUser(){this.userId=null,this.userEmail=null,this.isEnabled&&Ae.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 Ae.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=Ae.captureException(e);return u.debug(`[SENTRY] Captured exception: ${s}`),s})}captureMessage(e,t="info",n){return this.isEnabled?Ae.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=Ae.captureMessage(e,t);return u.debug(`[SENTRY] Captured message: ${r}`),r}):null}addBreadcrumb(e,t,n,s="info"){this.isEnabled&&Ae.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&&Ae.setTag(e,t)}setExtra(e,t){this.isEnabled&&Ae.setExtra(e,t)}startTransaction(e,t){return this.isEnabled?Ae.startInactiveSpan({name:e,op:t}):null}},Ni=Ri.getInstance()});var Us={};Ue(Us,{SecureStorageService:()=>$r,secureStorage:()=>fp});import $s from"crypto";import tn from"os";import An from"fs";import Oi from"path";import{execSync as dp}from"child_process";var tl,Fs,nl,gp,mp,pp,Ls,hp,$r,fp,Bs=L(()=>{"use strict";V();tl="aes-256-gcm",Fs=16,nl=16,gp=32,mp=32,pp=1e5,Ls="__enc__",hp=["snowx_auth_token","snowx_access_token","snowx_user_data","snowx_device_id","orion_device_id","firebase_custom_token"],$r=class i{static instance;storagePath;storage={};encryptionKey=null;salt=null;isProduction;constructor(){let e=Oi.join(tn.homedir(),".orion-cli");this.storagePath=Oi.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(An.existsSync(this.storagePath)){let e=An.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=Oi.dirname(this.storagePath);An.existsSync(e)||An.mkdirSync(e,{recursive:!0});let t={data:this.storage,salt:this.salt?.toString("base64")};An.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=$s.randomBytes(gp));let e=this.generateDeviceSeed();this.encryptionKey=$s.pbkdf2Sync(e,this.salt,pp,mp,"sha256"),u.debug("[SECURE] Encryption initialized")}generateDeviceSeed(){return[tn.hostname(),tn.platform(),tn.arch(),tn.cpus()[0]?.model||"unknown-cpu",tn.userInfo().username,this.getMachineId()].join("|")}getMachineId(){try{if(process.platform==="linux"&&An.existsSync("/etc/machine-id"))return An.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let t=dp("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID" = "([^"]+)"/);if(t)return t[1]}}catch{}return tn.hostname()+tn.userInfo().uid}shouldEncrypt(e){return!this.isProduction&&process.env.ORION_SKIP_ENCRYPTION==="true"?!1:hp.some(t=>e.includes(t))}encrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");let t=$s.randomBytes(Fs),n=$s.createCipheriv(tl,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 Ls+o.toString("base64")}decrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");if(!e.startsWith(Ls))return e;let t=Buffer.from(e.slice(Ls.length),"base64"),n=t.subarray(0,Fs),s=t.subarray(Fs,Fs+nl),r=t.subarray(Fs+nl),o=$s.createDecipheriv(tl,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(Ls)?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(Ls)&&(this.storage[t]=this.encrypt(n),e++)}e>0&&(this.saveStorage(),u.debug(`[SECURE] Migrated ${e} values to encrypted storage`))}},fp=$r.getInstance()});import bp from"axios";import{EventEmitter as yp}from"events";var nn,Nt,Ws=L(()=>{"use strict";nn="firebase_timestamp",Nt=class i extends yp{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=bp.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(()=>(ze(),Rt));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(ke(),sl));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 _i={};Ue(_i,{DeviceRegistrationService:()=>Ne});import{EventEmitter as vp}from"events";import{v4 as rl}from"uuid";import Hs from"os";import ol from"fs/promises";import Sp from"path";import{execSync as Gs}from"child_process";import wp from"crypto";var Ne,Ot=L(()=>{"use strict";Ws();ke();V();Ne=class i extends vp{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=Nt.getInstance(),this.authService=Z.getInstance(),this.configDir=Sp.join(Hs.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=Hs.platform();if(e==="darwin")try{let s=Gs("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=Gs('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=Hs.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}`),Hs.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=Hs.platform();try{let t=null;switch(e){case"darwin":try{let a=Gs("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=Gs("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 ol.readFile("/etc/machine-id","utf-8").then(o=>o.trim()),u.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await ol.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=Gs("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=wp.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(()=>(ze(),Rt)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${r}`):(r=rl(),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(()=>(ze(),Rt)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${r}`):(r=rl(),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:nn,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:nn,lastSeenAt:nn};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:nn,lastSeenAt:nn}],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 sl={};Ue(sl,{AuthService:()=>Z});import{EventEmitter as Tp}from"events";import{signInAnonymously as xp,signInWithEmailAndPassword as Cp,createUserWithEmailAndPassword as Ep,signOut as Ip,onAuthStateChanged as il,updateProfile as kp,signInWithCustomToken as Pp}from"firebase/auth";import sn from"axios";import $i from"fs/promises";import al from"path";import Ap from"os";function cl(i,e,t){return Promise.race([i,new Promise((n,s)=>setTimeout(()=>s(new Error(t)),e))])}var Z,ke=L(()=>{"use strict";Pn();V();el();Z=class i extends Tp{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=al.join(Ap.homedir(),".orion-cli","auth.json")}static getInstance(){return i.instance||(i.instance=new i),i.instance}async initializeTokenFile(){try{let e=al.dirname(this.tokenFilePath);await $i.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{secureStorage:e}=await Promise.resolve().then(()=>(Bs(),Us)),{UserDefaults:t}=await Promise.resolve().then(()=>(ze(),Rt)),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 $i.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 $i.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(()=>(Bs(),Us));t.setItem("snowx_auth_token",e.userId),t.setItem("snowx_access_token",e.token);let{UserDefaults:n}=await Promise.resolve().then(()=>(ze(),Rt));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";Ni.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(()=>(Bs(),Us)),{UserDefaults:t}=await Promise.resolve().then(()=>(ze(),Rt));e.removeItem("snowx_auth_token"),e.removeItem("snowx_access_token"),t.remove("snowx_auth_token"),t.remove("snowx_access_token"),this.authToken=null,Ni.clearUser()}catch(e){console.error("❌ Failed to clear auth token:",e)}}setFirebaseAuth(e){this.auth=e,il(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}Pe.setUserTier(t);let{UserDefaults:n}=await Promise.resolve().then(()=>(ze(),Rt));n.set("userSubscriptionTier",e.tier||0),n.set("isTrialUser",!1),u.debug(`User tier updated: ${Pe.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 xp(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 Cp(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 Ep(this.auth,e,t);return this.currentUser=s.user,n&&await kp(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(()=>(Ot(),_i));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Ip(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(()=>(Ot(),_i));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ze(),Rt)),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 sn.post(`${this.snowxAuthEndpoint}/login`,e):t=await sn.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 sn.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(()=>(Bs(),Us)),t=e.getItem("snowx_access_token");if(t)return t;let{UserDefaults:n}=await Promise.resolve().then(()=>(ze(),Rt));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=il(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.isFirebaseIdToken(this.authToken.token)?!!this.authToken.userId:this.authToken.expiresAt>Date.now():!1}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(){await this.initializeTokenFile();let e=!!this.authToken,t=this.getUserId();if(!e||!t)return!1;let n=this.authToken?.token;if(!n)return!1;u.debug("[AuthService] Attempting auto-authenticate for userId:",t);try{if(this.isFirebaseIdToken(n)){let s=this.parseFirebaseIdToken(n);return s&&Date.now()<=s.exp*1e3?(u.debug("Firebase ID Token is still valid, using directly"),this.emit("AuthenticationComplete",t),!0):(u.debug("Firebase ID Token expired - re-authenticating via custom token API"),await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",t),!0)}return this.isAuthenticated()?(await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",t),!0):(u.error("Regular access token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}catch(s){return u.error("Failed to authenticate with Firebase during auto-authenticate:",s.message),s.response?.status===401||s.response?.status===403||s.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}}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 cl(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 cl(Pp(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 sn.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 sn.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 sn.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 sn.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){if(e.response?.status===401)throw console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken(),e;return e.response?.status===404?console.warn("⚠️ User profile not found (404) - new account, profile not provisioned yet"):console.warn(`⚠️ Failed to fetch user info: ${e.message}`),null}}async canAccessModel(e){let t=await this.getUserTier(),n=t===1?1:t===2?2:0;return Pe.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 sn.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 Dp}from"events";import Mp from"crypto";var pt,ns=L(()=>{"use strict";V();pt=class i extends Dp{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 Mp.randomUUID()}}});import{encode as ul,decode as dl,isWithinTokenLimit as gl,countTokens as Rp}from"gpt-tokenizer/encoding/cl100k_base";var ss,Np,Op,ht,rs=L(()=>{"use strict";ss=25e3,Np=1400,Op=17e3,ht=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??ss,this.previewTokens=e?.previewTokens??Np,this.maxContentTokens=e?.maxContentTokens??Op}count(e){return e?Rp(e):0}encode(e){return e?ul(e):[]}decode(e){return!e||e.length===0?"":dl(e)}isWithinLimit(e,t){return e?gl(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=gl(e,n);if(s!==!1)return{text:e,tokens:s,truncated:!1};let o=ul(e).slice(0,n);return{text:dl(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 lp=Object.defineProperty;var L=(i,e)=>()=>(i&&(e=i(i=0)),e);var Ue=(i,e)=>{for(var t in e)lp(i,t,{get:e[t],enumerable:!0})};var ye,en=L(()=>{"use strict";ye=[{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 Ai,u,V=L(()=>{"use strict";Ai=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=Ai.getInstance()});var Rt={};Ue(Rt,{UserDefaults:()=>fe});import _s from"fs";import Di from"path";import gp from"os";var Mi,fe,ze=L(()=>{"use strict";V();Mi=class i{static instance;preferencesPath;preferences={};constructor(){let e=Di.join(gp.homedir(),".orion");this.preferencesPath=Di.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadPreferences(){try{if(_s.existsSync(this.preferencesPath)){let e=_s.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=Di.dirname(this.preferencesPath);_s.existsSync(e)||_s.mkdirSync(e,{recursive:!0}),_s.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)}},fe=Mi.getInstance()});var Pe,Pn=L(()=>{"use strict";en();ze();V();Pe=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=fe.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=3?e:0}static setUserTier(e){fe.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 ye.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 Ae from"@sentry/node";var Ri,Ni,tl=L(()=>{"use strict";V();Ri=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&&Ae.setUser({id:e,email:t,subscription:n})}setDevice(e){this.deviceId=e,this.isEnabled&&Ae.setTag("device_id",e)}clearUser(){this.userId=null,this.userEmail=null,this.isEnabled&&Ae.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 Ae.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=Ae.captureException(e);return u.debug(`[SENTRY] Captured exception: ${s}`),s})}captureMessage(e,t="info",n){return this.isEnabled?Ae.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=Ae.captureMessage(e,t);return u.debug(`[SENTRY] Captured message: ${r}`),r}):null}addBreadcrumb(e,t,n,s="info"){this.isEnabled&&Ae.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&&Ae.setTag(e,t)}setExtra(e,t){this.isEnabled&&Ae.setExtra(e,t)}startTransaction(e,t){return this.isEnabled?Ae.startInactiveSpan({name:e,op:t}):null}},Ni=Ri.getInstance()});var Us={};Ue(Us,{SecureStorageService:()=>$r,secureStorage:()=>yp});import $s from"crypto";import tn from"os";import An from"fs";import Oi from"path";import{execSync as mp}from"child_process";var nl,Fs,sl,pp,hp,fp,Ls,bp,$r,yp,Bs=L(()=>{"use strict";V();nl="aes-256-gcm",Fs=16,sl=16,pp=32,hp=32,fp=1e5,Ls="__enc__",bp=["snowx_auth_token","snowx_access_token","snowx_user_data","snowx_device_id","orion_device_id","firebase_custom_token"],$r=class i{static instance;storagePath;storage={};encryptionKey=null;salt=null;isProduction;constructor(){let e=Oi.join(tn.homedir(),".orion-cli");this.storagePath=Oi.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(An.existsSync(this.storagePath)){let e=An.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=Oi.dirname(this.storagePath);An.existsSync(e)||An.mkdirSync(e,{recursive:!0});let t={data:this.storage,salt:this.salt?.toString("base64")};An.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=$s.randomBytes(pp));let e=this.generateDeviceSeed();this.encryptionKey=$s.pbkdf2Sync(e,this.salt,fp,hp,"sha256"),u.debug("[SECURE] Encryption initialized")}generateDeviceSeed(){return[tn.hostname(),tn.platform(),tn.arch(),tn.cpus()[0]?.model||"unknown-cpu",tn.userInfo().username,this.getMachineId()].join("|")}getMachineId(){try{if(process.platform==="linux"&&An.existsSync("/etc/machine-id"))return An.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let t=mp("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID" = "([^"]+)"/);if(t)return t[1]}}catch{}return tn.hostname()+tn.userInfo().uid}shouldEncrypt(e){return!this.isProduction&&process.env.ORION_SKIP_ENCRYPTION==="true"?!1:bp.some(t=>e.includes(t))}encrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");let t=$s.randomBytes(Fs),n=$s.createCipheriv(nl,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 Ls+o.toString("base64")}decrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");if(!e.startsWith(Ls))return e;let t=Buffer.from(e.slice(Ls.length),"base64"),n=t.subarray(0,Fs),s=t.subarray(Fs,Fs+sl),r=t.subarray(Fs+sl),o=$s.createDecipheriv(nl,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(Ls)?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(Ls)&&(this.storage[t]=this.encrypt(n),e++)}e>0&&(this.saveStorage(),u.debug(`[SECURE] Migrated ${e} values to encrypted storage`))}},yp=$r.getInstance()});import vp from"axios";import{EventEmitter as Sp}from"events";var nn,Nt,Ws=L(()=>{"use strict";nn="firebase_timestamp",Nt=class i extends Sp{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=vp.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(()=>(ze(),Rt));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(ke(),rl));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 _i={};Ue(_i,{DeviceRegistrationService:()=>Ne});import{EventEmitter as wp}from"events";import{v4 as ol}from"uuid";import Hs from"os";import il from"fs/promises";import Tp from"path";import{execSync as Gs}from"child_process";import xp from"crypto";var Ne,Ot=L(()=>{"use strict";Ws();ke();V();Ne=class i extends wp{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=Nt.getInstance(),this.authService=Z.getInstance(),this.configDir=Tp.join(Hs.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=Hs.platform();if(e==="darwin")try{let s=Gs("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=Gs('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=Hs.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}`),Hs.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=Hs.platform();try{let t=null;switch(e){case"darwin":try{let a=Gs("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=Gs("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 il.readFile("/etc/machine-id","utf-8").then(o=>o.trim()),u.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await il.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=Gs("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=xp.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(()=>(ze(),Rt)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${r}`):(r=ol(),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(()=>(ze(),Rt)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${r}`):(r=ol(),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:nn,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:nn,lastSeenAt:nn};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:nn,lastSeenAt:nn}],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 rl={};Ue(rl,{AuthService:()=>Z});import{EventEmitter as Cp}from"events";import{signInAnonymously as Ep,signInWithEmailAndPassword as Ip,createUserWithEmailAndPassword as kp,signOut as Pp,onAuthStateChanged as al,updateProfile as Ap,signInWithCustomToken as Dp}from"firebase/auth";import sn from"axios";import $i from"fs/promises";import cl from"path";import Mp from"os";function ll(i,e,t){return Promise.race([i,new Promise((n,s)=>setTimeout(()=>s(new Error(t)),e))])}var Z,ke=L(()=>{"use strict";Pn();V();tl();Z=class i extends Cp{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=cl.join(Mp.homedir(),".orion-cli","auth.json")}static getInstance(){return i.instance||(i.instance=new i),i.instance}async initializeTokenFile(){try{let e=cl.dirname(this.tokenFilePath);await $i.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{secureStorage:e}=await Promise.resolve().then(()=>(Bs(),Us)),{UserDefaults:t}=await Promise.resolve().then(()=>(ze(),Rt)),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 $i.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 $i.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(()=>(Bs(),Us));t.setItem("snowx_auth_token",e.userId),t.setItem("snowx_access_token",e.token);let{UserDefaults:n}=await Promise.resolve().then(()=>(ze(),Rt));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";Ni.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(()=>(Bs(),Us)),{UserDefaults:t}=await Promise.resolve().then(()=>(ze(),Rt));e.removeItem("snowx_auth_token"),e.removeItem("snowx_access_token"),t.remove("snowx_auth_token"),t.remove("snowx_access_token"),this.authToken=null,Ni.clearUser()}catch(e){console.error("❌ Failed to clear auth token:",e)}}setFirebaseAuth(e){this.auth=e,al(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}Pe.setUserTier(t);let{UserDefaults:n}=await Promise.resolve().then(()=>(ze(),Rt));n.set("userSubscriptionTier",e.tier||0),n.set("isTrialUser",!1),u.debug(`User tier updated: ${Pe.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 Ep(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 Ip(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 kp(this.auth,e,t);return this.currentUser=s.user,n&&await Ap(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(()=>(Ot(),_i));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Pp(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(()=>(Ot(),_i));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ze(),Rt)),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 sn.post(`${this.snowxAuthEndpoint}/login`,e):t=await sn.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 sn.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(()=>(Bs(),Us)),t=e.getItem("snowx_access_token");if(t)return t;let{UserDefaults:n}=await Promise.resolve().then(()=>(ze(),Rt));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=al(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.isFirebaseIdToken(this.authToken.token)?!!this.authToken.userId:this.authToken.expiresAt>Date.now():!1}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(){await this.initializeTokenFile();let e=!!this.authToken,t=this.getUserId();if(!e||!t)return!1;let n=this.authToken?.token;if(!n)return!1;u.debug("[AuthService] Attempting auto-authenticate for userId:",t);try{if(this.isFirebaseIdToken(n)){let s=this.parseFirebaseIdToken(n);return s&&Date.now()<=s.exp*1e3?(u.debug("Firebase ID Token is still valid, using directly"),this.emit("AuthenticationComplete",t),!0):(u.debug("Firebase ID Token expired - re-authenticating via custom token API"),await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",t),!0)}return this.isAuthenticated()?(await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",t),!0):(u.error("Regular access token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}catch(s){return u.error("Failed to authenticate with Firebase during auto-authenticate:",s.message),s.response?.status===401||s.response?.status===403||s.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}}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 ll(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 ll(Dp(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 sn.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 sn.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 sn.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 sn.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){if(e.response?.status===401)throw console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken(),e;return e.response?.status===404?console.warn("⚠️ User profile not found (404) - new account, profile not provisioned yet"):console.warn(`⚠️ Failed to fetch user info: ${e.message}`),null}}async canAccessModel(e){let t=await this.getUserTier(),n=t===1?1:t===2?2:0;return Pe.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 sn.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 Rp}from"events";import Np from"crypto";var pt,ns=L(()=>{"use strict";V();pt=class i extends Rp{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 Np.randomUUID()}}});import{encode as dl,decode as gl,isWithinTokenLimit as ml,countTokens as Op}from"gpt-tokenizer/encoding/cl100k_base";var ss,_p,$p,ht,rs=L(()=>{"use strict";ss=25e3,_p=1400,$p=17e3,ht=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??ss,this.previewTokens=e?.previewTokens??_p,this.maxContentTokens=e?.maxContentTokens??$p}count(e){return e?Op(e):0}encode(e){return e?dl(e):[]}decode(e){return!e||e.length===0?"":gl(e)}isWithinLimit(e,t){return e?ml(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=ml(e,n);if(s!==!1)return{text:e,tokens:s,truncated:!1};let o=dl(e).slice(0,n);return{text:gl(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 _p}from"events";var ml,pl,$p,hl,Fp,js,fl,Fi=L(()=>{"use strict";V();ml=10,pl=2e3,$p=5e3,hl=200,Fp=3e3,js=class i extends _p{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,hl),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||"",hl);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>pl?o.streamingContent=c.slice(-pl):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||"",$p),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<ml)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-ml+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}`)},Fp);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")}},fl=js.getInstance()});var Fr,bl=L(()=>{"use strict";V();Fr=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 yl={};Ue(yl,{ToolDisplay:()=>ee});import he from"chalk";var ee,Et=L(()=>{"use strict";ee=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(he.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 Fp}from"events";var pl,hl,Lp,fl,Up,js,bl,Fi=L(()=>{"use strict";V();pl=10,hl=2e3,Lp=5e3,fl=200,Up=3e3,js=class i extends Fp{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,fl),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||"",fl);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>hl?o.streamingContent=c.slice(-hl):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||"",Lp),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<pl)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-pl+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}`)},Up);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")}},bl=js.getInstance()});var Fr,yl=L(()=>{"use strict";V();Fr=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 vl={};Ue(vl,{ToolDisplay:()=>ee});import he from"chalk";var ee,Et=L(()=>{"use strict";ee=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(he.cyan(`
30
30
  ${s} ${he.bold(e)}`)),t&&console.log(he.gray(` ${t}`)),n){let r=n.length>120?n.substring(0,120)+he.gray("..."):n;console.log(he.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?he.green("✓"):he.red("✗"),l=s?he.green("SUCCESS"):he.red("FAILED"),d=r?he.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=>he.gray(" ")+d).join(`
@@ -40,12 +40,12 @@ ${s} ${he.bold(e)}`)),t&&console.log(he.gray(` ${t}`)),n){let r=n.length>120?n
40
40
  `);let r=n.slice(0,t).map(o=>he.gray(" ")+he.dim(o)).join(`
41
41
  `);return r+=`
42
42
  `+he.gray(` ... (${n.length-t} more lines)`),r}static error(e,t){i.customUIMode||(console.log(`
43
- ${he.red("✗")} ${he.red.bold(e)} ${he.red("ERROR")}`),console.log(he.gray(" ")+he.white(t)),console.log(""))}}});import vl from"os";import Li from"path";function Lr(){return process.platform==="win32"}function Dn(i){if(!i)return i;let e=i.trim();return e.startsWith("~")&&(e=e.replace(/^~/,vl.homedir())),Lr()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,vl.homedir())),!Lr()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),Lr()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function os(i){if(!i||typeof i!="string")return{valid:!1,error:"File path is required"};let e=Dn(i);if(Lr()){let n=Li.basename(e).split(".")[0].toUpperCase();if(Lp.includes(n))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${n}`}}return Li.isAbsolute(e)?Li.resolve(e).includes("..")?{valid:!1,error:`Security Error: Path traversal not allowed: ${i}`}:{valid:!0}:{valid:!1,error:`Invalid path format: "${i}"
43
+ ${he.red("✗")} ${he.red.bold(e)} ${he.red("ERROR")}`),console.log(he.gray(" ")+he.white(t)),console.log(""))}}});import Sl from"os";import Li from"path";function Lr(){return process.platform==="win32"}function Dn(i){if(!i)return i;let e=i.trim();return e.startsWith("~")&&(e=e.replace(/^~/,Sl.homedir())),Lr()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,Sl.homedir())),!Lr()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),Lr()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function os(i){if(!i||typeof i!="string")return{valid:!1,error:"File path is required"};let e=Dn(i);if(Lr()){let n=Li.basename(e).split(".")[0].toUpperCase();if(Bp.includes(n))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${n}`}}return Li.isAbsolute(e)?Li.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 Lp,Ur=L(()=>{"use strict";Lp=["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 Up,Bp,Br,wl=L(()=>{"use strict";V();Et();Ur();rs();Up=["png","jpg","jpeg","gif","bmp","webp","ico","tiff","tif"],Bp={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"},Br=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=Dn(r),l=os(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();ee.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(Up.includes(p)){u.debug(`[ReadFileTool] Image file detected: ${c}`);let O=(await g.readFile(c)).toString("base64"),U=Bp[p]||"application/octet-stream",D=Sl.basename(c);u.debug(`[ReadFileTool] Image converted to base64: ${D} (${O.length} chars)`);let $=Date.now()-d;return ee.result({toolName:"Read",filePath:c,output:`Image loaded: ${D}`,success:!0,executionTime:$}),[{type:"image_url",image_url:{url:`data:${U};base64,${O}`}}]}let f=await g.readFile(c,"utf-8"),y=f.length,v=f.split(`
48
+ Correct: /Users/username/Downloads/file.pdf`}}var Bp,Ur=L(()=>{"use strict";Bp=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});import wl from"path";var Wp,Hp,Br,Tl=L(()=>{"use strict";V();Et();Ur();rs();Wp=["png","jpg","jpeg","gif","bmp","webp","ico","tiff","tif"],Hp={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"},Br=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=Dn(r),l=os(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();ee.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=wl.extname(c).substring(1).toLowerCase();if(Wp.includes(p)){u.debug(`[ReadFileTool] Image file detected: ${c}`);let O=(await g.readFile(c)).toString("base64"),U=Hp[p]||"application/octet-stream",D=wl.basename(c);u.debug(`[ReadFileTool] Image converted to base64: ${D} (${O.length} chars)`);let $=Date.now()-d;return ee.result({toolName:"Read",filePath:c,output:`Image loaded: ${D}`,success:!0,executionTime:$}),[{type:"image_url",image_url:{url:`data:${U};base64,${O}`}}]}let f=await g.readFile(c,"utf-8"),y=f.length,v=f.split(`
49
49
  `),T=v.length,C=Math.max(o??0,0),I=new ht;if(o===void 0&&a===void 0&&I.exceedsResponseLimit(f)){let A=I.count(f),O=m.size/1024,U=O/1024,D=U>=1?`${U.toFixed(2)} MB`:`${O.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
50
50
 
51
51
  File Information:
@@ -69,7 +69,7 @@ Suggested Solutions:
69
69
  The file has ${T.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(T===0||f.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(C>=T)return[{type:"text",text:`Error: Offset ${C} is beyond file length. File has ${T} total lines. Try a smaller offset (0 to ${T-1}).`}];let E=a!==void 0?Math.min(C+a,T):T,w=v.slice(C,E),S=w.map((A,O)=>`${(C+O+1).toString().padStart(6," ")} ${A}`).join(`
70
70
  `),P=S;if(o!==void 0||a!==void 0){let A=`
71
71
 
72
- [Read ${w.length} lines (${C+1}-${E}) of ${T} total lines]`;P=S+A}let x=Date.now()-d;return ee.result({toolName:"Read",filePath:c,output:P,success:!0,executionTime:x}),[{type:"text",text:P}]}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 ee.result({toolName:"Read",filePath:c,output:m,success:!1,executionTime:p}),[{type:"text",text:m}]}}}});import Wr from"fs/promises";import Wp from"form-data";import Ui from"axios";import Bi from"path";var Hr,Tl=L(()=>{"use strict";V();Et();ke();Hr=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();ee.start("ReadSpecialFile",n.description,r);try{try{await Wr.access(r)}catch{return[{type:"text",text:`Error: File does not exist at path: ${r}`}]}let a=Bi.extname(r).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let C=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 ${w.length} lines (${C+1}-${E}) of ${T} total lines]`;P=S+A}let x=Date.now()-d;return ee.result({toolName:"Read",filePath:c,output:P,success:!0,executionTime:x}),[{type:"text",text:P}]}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 ee.result({toolName:"Read",filePath:c,output:m,success:!1,executionTime:p}),[{type:"text",text:m}]}}}});import Wr from"fs/promises";import Gp from"form-data";import Ui from"axios";import Bi from"path";var Hr,xl=L(()=>{"use strict";V();Et();ke();Hr=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();ee.start("ReadSpecialFile",n.description,r);try{try{await Wr.access(r)}catch{return[{type:"text",text:`Error: File does not exist at path: ${r}`}]}let a=Bi.extname(r).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let C=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
74
  Supported file types: ${C}`}]}let c=await Wr.stat(r),l=Bi.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 I=(await Wr.readFile(r)).toString("base64"),E=this.imageMimeTypes[a]||"application/octet-stream";u.debug(`[ReadSpecialFileTool] Image converted to base64: ${l} (${I.length} chars)`);let w=Date.now()-o;return ee.result({toolName:"ReadSpecialFile",filePath:r,output:`Image loaded: ${l}`,success:!0,executionTime:w}),[{type:"image_url",image_url:{url:`data:${E};base64,${I}`}}]}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 C=m?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${C}`}]}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`,v=`# File: ${l}
75
75
  **Type:** ${a.toUpperCase()}
@@ -86,7 +86,7 @@ This could be due to:
86
86
  • Unsupported document structure
87
87
  • File is password-protected or encrypted
88
88
 
89
- For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,l=Date.now()-o;return ee.result({toolName:"ReadSpecialFile",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}async uploadToBatchAPI(e,t){let n=await Wr.readFile(e),s=Bi.extname(t).substring(1).toLowerCase(),o=await Z.getInstance().getFirebaseIdToken(),a=new Wp;a.append("files",n,{filename:t,contentType:this.getMimeType(s)});try{let c={...a.getHeaders()};o&&(c.Authorization=`Bearer ${o}`);let l=await Ui.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 Z.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);for(let r=1;r<=this.maxPollAttempts;r++)try{let a=(await Ui.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 Z.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);try{let r=await Ui.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 Gr,xl=L(()=>{"use strict";V();Et();Ur();Gr=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=Dn(r),l=os(c);if(!l.valid)return[{type:"text",text:`Error: ${l.error}`}];let d=Date.now();return ee.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 ee.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 ee.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 ee.result({toolName:"ReadSpecialFile",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}async uploadToBatchAPI(e,t){let n=await Wr.readFile(e),s=Bi.extname(t).substring(1).toLowerCase(),o=await Z.getInstance().getFirebaseIdToken(),a=new Gp;a.append("files",n,{filename:t,contentType:this.getMimeType(s)});try{let c={...a.getHeaders()};o&&(c.Authorization=`Bearer ${o}`);let l=await Ui.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 Z.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);for(let r=1;r<=this.maxPollAttempts;r++)try{let a=(await Ui.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 Z.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);try{let r=await Ui.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 Gr,Cl=L(()=>{"use strict";V();Et();Ur();Gr=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=Dn(r),l=os(c);if(!l.valid)return[{type:"text",text:`Error: ${l.error}`}];let d=Date.now();return ee.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 ee.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 ee.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
 
@@ -98,14 +98,14 @@ For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'ca
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 jr,Cl=L(()=>{"use strict";V();Et();Ur();jr=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=Dn(r),d=os(l);if(!d.valid)return[{type:"text",text:`Error: ${d.error}`}];u.debug(`[EditFileTool] Editing file: ${l}`);let g=Date.now();ee.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 I=`No matches found for the specified old_string in file: ${l}`,E=Date.now()-g;return ee.result({toolName:"Edit",filePath:l,output:I,success:!1,executionTime:E}),[{type:"text",text:I}]}await m.writeFile(l,h,"utf-8");let y=`Successfully edited file: Replaced ${f} occurrence(s)`;u.debug(`[EditFileTool] ${y}`);let v=Date.now()-g,T=(await import("chalk")).default,C=`${T.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 jr,El=L(()=>{"use strict";V();Et();Ur();jr=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=Dn(r),d=os(l);if(!d.valid)return[{type:"text",text:`Error: ${d.error}`}];u.debug(`[EditFileTool] Editing file: ${l}`);let g=Date.now();ee.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 I=`No matches found for the specified old_string in file: ${l}`,E=Date.now()-g;return ee.result({toolName:"Edit",filePath:l,output:I,success:!1,executionTime:E}),[{type:"text",text:I}]}await m.writeFile(l,h,"utf-8");let y=`Successfully edited file: Replaced ${f} occurrence(s)`;u.debug(`[EditFileTool] ${y}`);let v=Date.now()-g,T=(await import("chalk")).default,C=`${T.red("- "+o.split(`
102
102
  `).slice(0,5).join(`
103
103
  - `))}
104
104
  ${T.green("+ "+a.split(`
105
105
  `).slice(0,5).join(`
106
106
  + `))}
107
107
 
108
- Replaced ${f} occurrence(s)`;return ee.result({toolName:"Edit",filePath:l,output:C,success:!0,executionTime:v}),[{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 ee.result({toolName:"Edit",filePath:l,output:p,success:!1,executionTime:h}),[{type:"text",text:p}]}}}});var zr,El=L(()=>{"use strict";V();zr=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 Wi from"fs/promises";import Hp from"path";import Gp from"form-data";import jp from"axios";var qr,Il=L(()=>{"use strict";V();Et();ke();qr=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();ee.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 Wi.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 Wi.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 Wi.readFile(r),g=Hp.basename(r).replace(/[\r\n\t"']/g,"_");u.debug(`[DeployZipHTML] File: ${g}, Size: ${c.size} bytes`);let p=await Z.getInstance().getFirebaseIdToken();if(!p)throw new Error("User must be authenticated to deploy projects");let h=new Gp;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 jp.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 v=y.data;u.debug("[DeployZipHTML] Deployed successfully"),u.debug(`[DeployZipHTML] Response: ${JSON.stringify(v,null,2)}`);let T=v.data?.deployUrl||v.deployUrl||v.url||v.deploymentUrl||v.site_url||v.siteUrl||v.website_url,C=v.data?.deployId||v.deployId||v.projectId||v.deploymentId,I=v.data?.siteId||v.siteId;this.deployCount++;let E=`# HTML Project Deployed Successfully!
108
+ Replaced ${f} occurrence(s)`;return ee.result({toolName:"Edit",filePath:l,output:C,success:!0,executionTime:v}),[{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 ee.result({toolName:"Edit",filePath:l,output:p,success:!1,executionTime:h}),[{type:"text",text:p}]}}}});var zr,Il=L(()=>{"use strict";V();zr=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 Wi from"fs/promises";import jp from"path";import zp from"form-data";import qp from"axios";var qr,kl=L(()=>{"use strict";V();Et();ke();qr=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();ee.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 Wi.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 Wi.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 Wi.readFile(r),g=jp.basename(r).replace(/[\r\n\t"']/g,"_");u.debug(`[DeployZipHTML] File: ${g}, Size: ${c.size} bytes`);let p=await Z.getInstance().getFirebaseIdToken();if(!p)throw new Error("User must be authenticated to deploy projects");let h=new zp;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 qp.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 v=y.data;u.debug("[DeployZipHTML] Deployed successfully"),u.debug(`[DeployZipHTML] Response: ${JSON.stringify(v,null,2)}`);let T=v.data?.deployUrl||v.deployUrl||v.url||v.deploymentUrl||v.site_url||v.siteUrl||v.website_url,C=v.data?.deployId||v.deployId||v.projectId||v.deploymentId,I=v.data?.siteId||v.siteId;this.deployCount++;let E=`# HTML Project Deployed Successfully!
109
109
 
110
110
  **Deployment URL**: ${T}
111
111
 
@@ -127,7 +127,7 @@ Troubleshooting:
127
127
  4. Check network connectivity
128
128
  5. Ensure ZIP file is under 100MB
129
129
 
130
- If the issue persists, contact support.`,l=Date.now()-o;return ee.result({toolName:"DeployZipHTML",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});import Hi from"fs/promises";import zp from"path";import qp from"form-data";import Kp from"axios";var Kr,kl=L(()=>{"use strict";V();Et();ke();Kr=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();ee.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 Hi.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 Hi.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 Hi.readFile(r),g=zp.basename(r).replace(/[\r\n\t"']/g,"_");u.debug(`[DeployZipReact] File: ${g}, Size: ${c.size} bytes`);let p=await Z.getInstance().getFirebaseIdToken();if(!p)throw new Error("User must be authenticated to deploy projects");let h=new qp;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 Kp.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 v=y.data;u.debug("[DeployZipReact] Deployed successfully"),u.debug(`[DeployZipReact] Response: ${JSON.stringify(v,null,2)}`);let T=v.data?.deployUrl||v.deployUrl||v.url||v.deploymentUrl||v.site_url||v.siteUrl||v.website_url,C=v.data?.deployId||v.deployId||v.projectId||v.deploymentId,I=v.data?.siteId||v.siteId;this.deployCount++;let E=`# React Project Deployed Successfully!
130
+ If the issue persists, contact support.`,l=Date.now()-o;return ee.result({toolName:"DeployZipHTML",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});import Hi from"fs/promises";import Kp from"path";import Vp from"form-data";import Xp from"axios";var Kr,Pl=L(()=>{"use strict";V();Et();ke();Kr=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();ee.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 Hi.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 Hi.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 Hi.readFile(r),g=Kp.basename(r).replace(/[\r\n\t"']/g,"_");u.debug(`[DeployZipReact] File: ${g}, Size: ${c.size} bytes`);let p=await Z.getInstance().getFirebaseIdToken();if(!p)throw new Error("User must be authenticated to deploy projects");let h=new Vp;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 Xp.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 v=y.data;u.debug("[DeployZipReact] Deployed successfully"),u.debug(`[DeployZipReact] Response: ${JSON.stringify(v,null,2)}`);let T=v.data?.deployUrl||v.deployUrl||v.url||v.deploymentUrl||v.site_url||v.siteUrl||v.website_url,C=v.data?.deployId||v.deployId||v.projectId||v.deploymentId,I=v.data?.siteId||v.siteId;this.deployCount++;let E=`# React Project Deployed Successfully!
131
131
 
132
132
  **Deployment URL**: ${T}
133
133
 
@@ -149,9 +149,9 @@ Troubleshooting:
149
149
  4. Check network connectivity
150
150
  5. Ensure ZIP file is under 100MB
151
151
 
152
- If the issue persists, contact support.`,l=Date.now()-o;return ee.result({toolName:"DeployZipReact",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});var Pl=L(()=>{"use strict"});function Vp(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 zs(i){let e=i.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(Vp(i))return ft.pipedWithTerminator;if(i.includes("<<")&&(i.includes("EOF")||i.includes("'EOF'")||i.includes('"EOF"')||i.includes("END")||i.includes("SCRIPT")||i.includes("DOC")))return ft.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 ft.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 ft.extended;return(i.match(/\n/g)||[]).length>5?ft.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)?ft.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?ft.fast:ft.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)?ft.extended:i.includes("|")?ft.default:i.length<30?ft.fast:ft.default}var ft,Gi=L(()=>{"use strict";Pl();ft={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 Xp,exec as Yp,execSync as Qp}from"child_process";import{promisify as Jp}from"util";function qi(){return process.platform}function jt(){return process.platform==="win32"}function th(){return process.platform==="darwin"}function is(i,e="SIGTERM"){if(i)try{if(jt())try{Qp(`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 nh(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(jt()&&(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 Al(){return jt()?"PowerShell or Command Prompt":(th(),"Terminal")}function ji(i,e,t="max",n){let s=f=>{if(f>=6e4){let v=Math.round(f/6e4);return`${v} minute${v>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
- `)}function sh(i,e){let t=Al();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
152
+ If the issue persists, contact support.`,l=Date.now()-o;return ee.result({toolName:"DeployZipReact",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});var Al=L(()=>{"use strict"});function Yp(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 zs(i){let e=i.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(Yp(i))return ft.pipedWithTerminator;if(i.includes("<<")&&(i.includes("EOF")||i.includes("'EOF'")||i.includes('"EOF"')||i.includes("END")||i.includes("SCRIPT")||i.includes("DOC")))return ft.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 ft.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 ft.extended;return(i.match(/\n/g)||[]).length>5?ft.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)?ft.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?ft.fast:ft.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)?ft.extended:i.includes("|")?ft.default:i.length<30?ft.fast:ft.default}var ft,Gi=L(()=>{"use strict";Al();ft={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 Qp,exec as Jp,execSync as Zp}from"child_process";import{promisify as eh}from"util";function qi(){return process.platform}function jt(){return process.platform==="win32"}function sh(){return process.platform==="darwin"}function is(i,e="SIGTERM"){if(i)try{if(jt())try{Zp(`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 rh(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(jt()&&(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 Dl(){return jt()?"PowerShell or Command Prompt":(sh(),"Terminal")}function ji(i,e,t="max",n){let s=f=>{if(f>=6e4){let v=Math.round(f/6e4);return`${v} minute${v>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
+ `)}function oh(i,e){let t=Dl();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
155
155
 
156
156
  Reason: ${e}
157
157
 
@@ -165,7 +165,7 @@ To run this command:
165
165
  2. Run the command manually: ${i}
166
166
  3. Enter your password when prompted
167
167
 
168
- Alternative: Break down the task into non-privileged commands if possible.`}function rh(i){let e=i.trim().toLowerCase(),t=e.split(/\s+/)[0]||"",n=[{cmd:"npm login",reason:"npm login requires interactive authentication"},{cmd:"npm adduser",reason:"npm adduser requires interactive authentication"},{cmd:"yarn login",reason:"yarn login requires interactive authentication"},{cmd:"docker login",reason:"docker login requires interactive password input"},{cmd:"docker logout",reason:"docker logout may require confirmation"},{cmd:"gh auth login",reason:"GitHub CLI login requires interactive browser/token input"},{cmd:"firebase login",reason:"Firebase login requires interactive browser authentication"},{cmd:"heroku login",reason:"Heroku login requires interactive browser authentication"},{cmd:"aws configure",reason:"AWS configure requires interactive credential input"},{cmd:"gcloud auth login",reason:"Google Cloud login requires interactive browser authentication"},{cmd:"az login",reason:"Azure CLI login requires interactive browser authentication"},{cmd:"netlify login",reason:"Netlify login requires interactive authentication"},{cmd:"vercel login",reason:"Vercel login requires interactive authentication"},{cmd:"supabase login",reason:"Supabase login requires interactive authentication"},{cmd:"wrangler login",reason:"Cloudflare Wrangler login requires interactive authentication"},{cmd:"flyctl auth login",reason:"Fly.io login requires interactive authentication"},{cmd:"railway login",reason:"Railway login requires interactive authentication"}];for(let{cmd:l,reason:d}of n)if(e.startsWith(l)||e.includes(`&& ${l}`)||e.includes(`; ${l}`))return{isInteractive:!0,reason:d};let s=[{cmd:"npm init",except:["npm init -y","npm init --yes"],reason:"npm init requires interactive prompts (use npm init -y for non-interactive)"},{cmd:"yarn init",except:["yarn init -y","yarn init --yes"],reason:"yarn init requires interactive prompts (use yarn init -y for non-interactive)"},{cmd:"pnpm init",except:["pnpm init -y","pnpm init --yes"],reason:"pnpm init requires interactive prompts"}];for(let{cmd:l,except:d,reason:g}of s)if(e.startsWith(l)&&!d?.some(p=>e.startsWith(p)))return{isInteractive:!0,reason:g};if(["vim","vi","nano","emacs","pico","ed","less","more","most"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive editor/pager that requires a TTY`};if(["top","htop","btop","atop","iotop","nmon","glances"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive monitor that requires a TTY`};if((t==="python"||t==="python3"||t==="node")&&e.includes(" -i"))return{isInteractive:!0,reason:`${t} -i starts an interactive REPL`};let a=["irb","pry","iex","erl","ghci","scala","sbt console"];for(let l of a)if(e.startsWith(l))return{isInteractive:!0,reason:`${l} is an interactive REPL`};if(t==="ssh"&&!e.includes("-o batchmode")&&!e.includes("-o passwordauthentication=no")&&!e.includes("-i ")&&!e.includes("-o identityfile"))return{isInteractive:!0,reason:"ssh may require interactive password input (use -o BatchMode=yes for non-interactive)"};if(t==="read"||e.includes("| read")||e.includes("; read"))return{isInteractive:!0,reason:"read command waits for user input"};if(t==="passwd")return{isInteractive:!0,reason:"passwd requires interactive password input"};let c=["git push","git pull","git fetch","git clone"];for(let l of c)e.startsWith(l);return t==="mysql"&&!e.includes("-p")&&!e.includes("--password")?{isInteractive:!0,reason:"mysql without -p flag may prompt for password"}:(t==="psql"&&!e.includes("PGPASSWORD")&&e.includes("--no-password"),{isInteractive:!1})}function oh(i,e){let t=Al();return`This command requires interactive input and cannot run in the Bash tool.
168
+ Alternative: Break down the task into non-privileged commands if possible.`}function ih(i){let e=i.trim().toLowerCase(),t=e.split(/\s+/)[0]||"",n=[{cmd:"npm login",reason:"npm login requires interactive authentication"},{cmd:"npm adduser",reason:"npm adduser requires interactive authentication"},{cmd:"yarn login",reason:"yarn login requires interactive authentication"},{cmd:"docker login",reason:"docker login requires interactive password input"},{cmd:"docker logout",reason:"docker logout may require confirmation"},{cmd:"gh auth login",reason:"GitHub CLI login requires interactive browser/token input"},{cmd:"firebase login",reason:"Firebase login requires interactive browser authentication"},{cmd:"heroku login",reason:"Heroku login requires interactive browser authentication"},{cmd:"aws configure",reason:"AWS configure requires interactive credential input"},{cmd:"gcloud auth login",reason:"Google Cloud login requires interactive browser authentication"},{cmd:"az login",reason:"Azure CLI login requires interactive browser authentication"},{cmd:"netlify login",reason:"Netlify login requires interactive authentication"},{cmd:"vercel login",reason:"Vercel login requires interactive authentication"},{cmd:"supabase login",reason:"Supabase login requires interactive authentication"},{cmd:"wrangler login",reason:"Cloudflare Wrangler login requires interactive authentication"},{cmd:"flyctl auth login",reason:"Fly.io login requires interactive authentication"},{cmd:"railway login",reason:"Railway login requires interactive authentication"}];for(let{cmd:l,reason:d}of n)if(e.startsWith(l)||e.includes(`&& ${l}`)||e.includes(`; ${l}`))return{isInteractive:!0,reason:d};let s=[{cmd:"npm init",except:["npm init -y","npm init --yes"],reason:"npm init requires interactive prompts (use npm init -y for non-interactive)"},{cmd:"yarn init",except:["yarn init -y","yarn init --yes"],reason:"yarn init requires interactive prompts (use yarn init -y for non-interactive)"},{cmd:"pnpm init",except:["pnpm init -y","pnpm init --yes"],reason:"pnpm init requires interactive prompts"}];for(let{cmd:l,except:d,reason:g}of s)if(e.startsWith(l)&&!d?.some(p=>e.startsWith(p)))return{isInteractive:!0,reason:g};if(["vim","vi","nano","emacs","pico","ed","less","more","most"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive editor/pager that requires a TTY`};if(["top","htop","btop","atop","iotop","nmon","glances"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive monitor that requires a TTY`};if((t==="python"||t==="python3"||t==="node")&&e.includes(" -i"))return{isInteractive:!0,reason:`${t} -i starts an interactive REPL`};let a=["irb","pry","iex","erl","ghci","scala","sbt console"];for(let l of a)if(e.startsWith(l))return{isInteractive:!0,reason:`${l} is an interactive REPL`};if(t==="ssh"&&!e.includes("-o batchmode")&&!e.includes("-o passwordauthentication=no")&&!e.includes("-i ")&&!e.includes("-o identityfile"))return{isInteractive:!0,reason:"ssh may require interactive password input (use -o BatchMode=yes for non-interactive)"};if(t==="read"||e.includes("| read")||e.includes("; read"))return{isInteractive:!0,reason:"read command waits for user input"};if(t==="passwd")return{isInteractive:!0,reason:"passwd requires interactive password input"};let c=["git push","git pull","git fetch","git clone"];for(let l of c)e.startsWith(l);return t==="mysql"&&!e.includes("-p")&&!e.includes("--password")?{isInteractive:!0,reason:"mysql without -p flag may prompt for password"}:(t==="psql"&&!e.includes("PGPASSWORD")&&e.includes("--no-password"),{isInteractive:!1})}function ah(i,e){let t=Dl();return`This command requires interactive input and cannot run in the Bash tool.
169
169
 
170
170
  Reason: ${e}
171
171
 
@@ -179,7 +179,7 @@ To run this command:
179
179
  2. Run the command manually: ${i}
180
180
  3. Follow the interactive prompts
181
181
 
182
- Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive) or environment variables for authentication.`}function ah(i){for(let e of ih){let t=e.pattern.exec(i);if(t)return{isCatastrophic:!0,pattern:e,matchedText:t[0]}}return{isCatastrophic:!1}}function ch(i,e){return!e.isCatastrophic||!e.pattern?"Unknown catastrophic command error":`🛑 BLOCKED: Catastrophic command detected!
182
+ Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive) or environment variables for authentication.`}function lh(i){for(let e of ch){let t=e.pattern.exec(i);if(t)return{isCatastrophic:!0,pattern:e,matchedText:t[0]}}return{isCatastrophic:!1}}function uh(i,e){return!e.isCatastrophic||!e.pattern?"Unknown catastrophic command error":`🛑 BLOCKED: Catastrophic command detected!
183
183
 
184
184
  Category: ${{filesystem_destruction:"Filesystem Destruction",disk_destruction:"Disk/Device Destruction",filesystem_formatting:"Filesystem Formatting",fork_bomb:"Fork Bomb / System Crash",permission_destruction:"Permission Destruction",root_modification:"Root Directory Modification",kernel_panic:"Kernel Panic Trigger",environment_destruction:"System Environment Destruction",partition_destruction:"Partition Table Destruction"}[e.pattern.category]||"Unknown Category"}
185
185
  Reason: ${e.pattern.description}
@@ -195,7 +195,7 @@ 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 Dl(i){let e=ah(i);if(e.isCatastrophic)return ch(i,e);let t=nh(i);if(t.isPrivileged)return sh(i,t.reason||"Privileged command detected");let n=rh(i);return n.isInteractive?oh(i,n.reason||"Interactive command detected"):null}function Ml(i){let e=i.trim();for(let t of lh)if(t.test(e))return{isDelete:!0,paths:uh(e),category:dh(e)};return{isDelete:!1,paths:[]}}function uh(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 dh(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 Zp,eh,qs,zi,qe,Ks,ih,lh,as=L(()=>{"use strict";Gi();rs();V();Zp=Jp(Yp),eh=8500,qs=new ht({maxResponseTokens:eh});zi=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")}},qe=new zi;Ks=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||zs(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(jt())await Zp(`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=qi(),o,a;jt()?(o="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(o="/bin/bash",a=["-c",e]);let c=Xp(o,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!jt()}),l="",d="",g=!1,m="",p="max",h=!1,f=!1,y=Date.now(),v=null,T=null,C=null,I=null,E=null,w=null,S=()=>{v&&(clearTimeout(v),v=null),T&&(clearTimeout(T),T=null),C&&(clearTimeout(C),C=null),I&&(clearTimeout(I),I=null),E&&(clearTimeout(E),E=null),w&&(clearTimeout(w),w=null)},P=O=>{h||(h=!0,S(),n(O))},x=async(O,U="max")=>{h||(g=!0,m=O,p=U,T&&(clearTimeout(T),T=null),C&&(clearTimeout(C),C=null),c.pid&&await this.killProcessTree(c.pid,"SIGTERM"),this.cleanupStreams(c),I=setTimeout(async()=>{h||(c.pid&&await this.killProcessTree(c.pid,"SIGKILL"),E=setTimeout(()=>{if(h)return;let D=Date.now()-s,$=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,_=ji(e,$,p,m);P({output:l+d+_,exitCode:-9,isSuccess:!1,duration:D,platform:r})},500))},1e3))};v=setTimeout(()=>{x(`Max timeout reached (${t.maxTimeout}ms)`,"max")},t.maxTimeout),t.initialTimeout>0&&(C=setTimeout(()=>{!f&&!h&&x(`No output received within initial timeout (${t.initialTimeout}ms)`,"initial")},t.initialTimeout));let A=()=>{y=Date.now(),t.useActivityTimeout&&(T&&clearTimeout(T),T=setTimeout(()=>{if(!h){let O=Date.now()-y;x(`No output for ${O}ms (activity timeout: ${t.activityTimeout}ms)`,"activity")}},t.activityTimeout))};t.useActivityTimeout&&A(),c.stdout?.on("data",O=>{f=!0,A(),C&&(clearTimeout(C),C=null),l+=O.toString()}),c.stderr?.on("data",O=>{f=!0,A(),C&&(clearTimeout(C),C=null),d+=O.toString()}),c.on("exit",(O,U)=>{U&&!g&&(d+=`
198
+ 3. Consider breaking down the operation into safer steps`}function Ml(i){let e=lh(i);if(e.isCatastrophic)return uh(i,e);let t=rh(i);if(t.isPrivileged)return oh(i,t.reason||"Privileged command detected");let n=ih(i);return n.isInteractive?ah(i,n.reason||"Interactive command detected"):null}function Rl(i){let e=i.trim();for(let t of dh)if(t.test(e))return{isDelete:!0,paths:gh(e),category:mh(e)};return{isDelete:!1,paths:[]}}function gh(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 mh(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 th,nh,qs,zi,qe,Ks,ch,dh,as=L(()=>{"use strict";Gi();rs();V();th=eh(Jp),nh=8500,qs=new ht({maxResponseTokens:nh});zi=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")}},qe=new zi;Ks=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||zs(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(jt())await th(`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=qi(),o,a;jt()?(o="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(o="/bin/bash",a=["-c",e]);let c=Qp(o,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!jt()}),l="",d="",g=!1,m="",p="max",h=!1,f=!1,y=Date.now(),v=null,T=null,C=null,I=null,E=null,w=null,S=()=>{v&&(clearTimeout(v),v=null),T&&(clearTimeout(T),T=null),C&&(clearTimeout(C),C=null),I&&(clearTimeout(I),I=null),E&&(clearTimeout(E),E=null),w&&(clearTimeout(w),w=null)},P=O=>{h||(h=!0,S(),n(O))},x=async(O,U="max")=>{h||(g=!0,m=O,p=U,T&&(clearTimeout(T),T=null),C&&(clearTimeout(C),C=null),c.pid&&await this.killProcessTree(c.pid,"SIGTERM"),this.cleanupStreams(c),I=setTimeout(async()=>{h||(c.pid&&await this.killProcessTree(c.pid,"SIGKILL"),E=setTimeout(()=>{if(h)return;let D=Date.now()-s,$=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,_=ji(e,$,p,m);P({output:l+d+_,exitCode:-9,isSuccess:!1,duration:D,platform:r})},500))},1e3))};v=setTimeout(()=>{x(`Max timeout reached (${t.maxTimeout}ms)`,"max")},t.maxTimeout),t.initialTimeout>0&&(C=setTimeout(()=>{!f&&!h&&x(`No output received within initial timeout (${t.initialTimeout}ms)`,"initial")},t.initialTimeout));let A=()=>{y=Date.now(),t.useActivityTimeout&&(T&&clearTimeout(T),T=setTimeout(()=>{if(!h){let O=Date.now()-y;x(`No output for ${O}ms (activity timeout: ${t.activityTimeout}ms)`,"activity")}},t.activityTimeout))};t.useActivityTimeout&&A(),c.stdout?.on("data",O=>{f=!0,A(),C&&(clearTimeout(C),C=null),l+=O.toString()}),c.stderr?.on("data",O=>{f=!0,A(),C&&(clearTimeout(C),C=null),d+=O.toString()}),c.on("exit",(O,U)=>{U&&!g&&(d+=`
199
199
  [Process terminated by signal: ${U}]`),w=setTimeout(()=>{if(h)return;S(),this.cleanupStreams(c);let D=Date.now()-s,$=(l+d).trim();if(qs.exceedsResponseLimit($)){let _=qs.truncate($),F=_.text.split(`
200
200
  `);$=_.text+`
201
201
 
@@ -205,7 +205,7 @@ If you believe this is a false positive, please:
205
205
 
206
206
  [Output truncated at `+_.tokens.toLocaleString()+` tokens]
207
207
  [Showing first `+z+` lines of output]
208
- [Total output was `+$.toLocaleString()+" tokens]"}if(g){let $=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,_=ji(e,$,p,m);P({output:D+_,exitCode:-15,isSuccess:!1,duration:U,platform:r})}else P({output:D,exitCode:O||0,isSuccess:(O||0)===0,duration:U,platform:r})}),c.on("error",O=>{if(h)return;S();let U=Date.now()-s;P({output:"Process execution failed: "+O.message,exitCode:-1,isSuccess:!1,duration:U,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`)}};ih=[{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"}];lh=[/^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 Ki={};Ue(Ki,{ToolCallingService:()=>Vs});import{EventEmitter as gh}from"events";import Rl from"axios";import{exec as mh,spawn as Nl}from"child_process";import{promisify as ph}from"util";import Ke from"fs/promises";import _t from"fs";import cs from"path";import hh from"os";var jE,Vr,Ol,fh,Vs,Xr=L(()=>{"use strict";as();Gi();rs();jE=ph(mh),Vr=5,Ol=20,fh=new Set(["Bash","execute_command","read_file","write_file","Edit","Grep","Glob"]),Vs=class i extends gh{static instance;tools=new Map;executionHistory=[];tokenCounter=new ht;shellSessionManager=Ks.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<Vr&&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}/${Vr})`),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(!fh.has(e))return t();if(this.activeToolExecutions<Vr){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>=Ol)throw console.warn(`⚠️ [ToolQueue] Queue full (${Ol}), 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}/${Vr})`),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.
208
+ [Total output was `+$.toLocaleString()+" tokens]"}if(g){let $=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,_=ji(e,$,p,m);P({output:D+_,exitCode:-15,isSuccess:!1,duration:U,platform:r})}else P({output:D,exitCode:O||0,isSuccess:(O||0)===0,duration:U,platform:r})}),c.on("error",O=>{if(h)return;S();let U=Date.now()-s;P({output:"Process execution failed: "+O.message,exitCode:-1,isSuccess:!1,duration:U,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`)}};ch=[{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"}];dh=[/^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 Ki={};Ue(Ki,{ToolCallingService:()=>Vs});import{EventEmitter as ph}from"events";import Nl from"axios";import{exec as hh,spawn as Ol}from"child_process";import{promisify as fh}from"util";import Ke from"fs/promises";import _t from"fs";import cs from"path";import bh from"os";var qE,Vr,_l,yh,Vs,Xr=L(()=>{"use strict";as();Gi();rs();qE=fh(hh),Vr=5,_l=20,yh=new Set(["Bash","execute_command","read_file","write_file","Edit","Grep","Glob"]),Vs=class i extends ph{static instance;tools=new Map;executionHistory=[];tokenCounter=new ht;shellSessionManager=Ks.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<Vr&&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}/${Vr})`),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(!yh.has(e))return t();if(this.activeToolExecutions<Vr){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>=_l)throw console.warn(`⚠️ [ToolQueue] Queue full (${_l}), 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}/${Vr})`),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(()=>(Et(),yl));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(()=>(It(),Mn)),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 Rl.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 Ke.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(()=>(Et(),vl));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(()=>(It(),Mn)),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 Nl.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 Ke.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")&&_t.existsSync(t)){let o=await Ke.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 Ke.writeFile(t,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{file_path:t,bytes_written:n.length,message:"Notebook cell written successfully"}}}}_t.existsSync(t)&&s!=="append"&&await this.validateFileNotModified(t);let r=cs.dirname(t);return await Ke.mkdir(r,{recursive:!0}),s==="append"?await Ke.appendFile(t,n):await Ke.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 Ke.readdir(e.directory_path,{withFileTypes:!0}),n=[];for(let s of t){if(!e.include_hidden&&s.name.startsWith("."))continue;let r=await Ke.stat(cs.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=Ks.parseSessionMode(e.session),n=zs(e.command),s={activityTimeout:e.timeout||n.activityTimeout,maxTimeout:e.timeout||n.maxTimeout,initialTimeout:n.initialTimeout,useActivityTimeout:n.useActivityTimeout},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 Rl({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=Nl("/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 v=m-y.stdout.length;y.stdout+=f.substring(0,v),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 v=m-y.stderr.length;y.stderr+=f.substring(0,v),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")&&_t.existsSync(t)){let o=await Ke.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 Ke.writeFile(t,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{file_path:t,bytes_written:n.length,message:"Notebook cell written successfully"}}}}_t.existsSync(t)&&s!=="append"&&await this.validateFileNotModified(t);let r=cs.dirname(t);return await Ke.mkdir(r,{recursive:!0}),s==="append"?await Ke.appendFile(t,n):await Ke.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 Ke.readdir(e.directory_path,{withFileTypes:!0}),n=[];for(let s of t){if(!e.include_hidden&&s.name.startsWith("."))continue;let r=await Ke.stat(cs.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=Ks.parseSessionMode(e.session),n=zs(e.command),s={activityTimeout:e.timeout||n.activityTimeout,maxTimeout:e.timeout||n.maxTimeout,initialTimeout:n.initialTimeout,useActivityTimeout:n.useActivityTimeout},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 Nl({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=Ol("/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 v=m-y.stdout.length;y.stdout+=f.substring(0,v),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 v=m-y.stderr.length;y.stderr+=f.substring(0,v),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,useActivityTimeout:!1}:zs(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")&&_t.existsSync(t)){let c=await Ke.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 Ke.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 Ke.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 Ke.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(v=>{let T=Nl("rg",y,{stdio:["ignore","pipe","pipe"]}),C="",I="";T.stdout.on("data",E=>{C+=E.toString()}),T.stderr.on("data",E=>{I+=E.toString()}),T.on("close",E=>{if(E!==0&&E!==1){v({success:!1,error:`ripgrep failed: ${I||"Unknown error"}`});return}let w=C.trim().split(`
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,useActivityTimeout:!1}:zs(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")&&_t.existsSync(t)){let c=await Ke.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 Ke.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 Ke.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 Ke.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(v=>{let T=Ol("rg",y,{stdio:["ignore","pipe","pipe"]}),C="",I="";T.stdout.on("data",E=>{C+=E.toString()}),T.stderr.on("data",E=>{I+=E.toString()}),T.on("close",E=>{if(E!==0&&E!==1){v({success:!1,error:`ripgrep failed: ${I||"Unknown error"}`});return}let w=C.trim().split(`
251
251
  `).filter(P=>P);p>0&&(w=w.slice(p)),m>0&&(w=w.slice(0,m));let S=w.length;v({success:!0,result:{pattern:t,num_files:S,files:w,output:w.join(`
252
- `)}})}),T.on("error",E=>{v({success:!1,error:`Failed to execute ripgrep: ${E.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 Ke.readdir(a,{withFileTypes:!0});for(let l of c){if(l.name.startsWith("."))continue;let d=cs.join(a,l.name),g=cs.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(!_t.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 Ke.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 Ke.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=_t.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(_t.existsSync(e)){let s=await Ke.readFile(e,"utf-8");this.cacheFileState(e,s)}return}if(_t.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=hh.tmpdir(),s=cs.join(n,"orion_tool_responses");_t.existsSync(s)||_t.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=cs.join(s,a);return _t.writeFileSync(c,e,"utf8"),c}catch{return null}}stopAllRunningTools(){}}});import{spawn as bh}from"child_process";var Yr,_l=L(()=>{"use strict";V();as();Yr=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 v=Number(n.timeout);if(Number.isNaN(v))throw new Error(`Timeout must be a valid number. Received string: "${n.timeout}"`);a=v}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=Dl(r);if(d)return u.debug("[RunCommandTool] Command blocked by security check"),[{type:"text",text:d}];let g=Ml(r);if(g.isDelete){u.debug("[RunCommandTool] Delete command detected, requesting confirmation"),u.debug(`[RunCommandTool] Affected targets: ${g.paths.join(", ")}`);let{FrontendWebSocketService:v}=await Promise.resolve().then(()=>(ls(),Vi)),T=v.getInstance(),C;if(T.hasElectronFrontend())C=await T.requestDeleteConfirmation(r,c);else{let{PersonalAgentService:I}=await Promise.resolve().then(()=>(It(),Mn)),E=I.getInstance();C=await this.requestCliConfirmation(E,r,g.paths,c)}if(C==="declined")return u.debug("[RunCommandTool] User declined delete command"),[{type:"text",text:`User declined the delete. Command NOT executed: ${r}
252
+ `)}})}),T.on("error",E=>{v({success:!1,error:`Failed to execute ripgrep: ${E.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 Ke.readdir(a,{withFileTypes:!0});for(let l of c){if(l.name.startsWith("."))continue;let d=cs.join(a,l.name),g=cs.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(!_t.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 Ke.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 Ke.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=_t.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(_t.existsSync(e)){let s=await Ke.readFile(e,"utf-8");this.cacheFileState(e,s)}return}if(_t.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=bh.tmpdir(),s=cs.join(n,"orion_tool_responses");_t.existsSync(s)||_t.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=cs.join(s,a);return _t.writeFileSync(c,e,"utf8"),c}catch{return null}}stopAllRunningTools(){}}});import{spawn as vh}from"child_process";var Yr,$l=L(()=>{"use strict";V();as();Yr=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 v=Number(n.timeout);if(Number.isNaN(v))throw new Error(`Timeout must be a valid number. Received string: "${n.timeout}"`);a=v}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=Rl(r);if(g.isDelete){u.debug("[RunCommandTool] Delete command detected, requesting confirmation"),u.debug(`[RunCommandTool] Affected targets: ${g.paths.join(", ")}`);let{FrontendWebSocketService:v}=await Promise.resolve().then(()=>(ls(),Vi)),T=v.getInstance(),C;if(T.hasElectronFrontend())C=await T.requestDeleteConfirmation(r,c);else{let{PersonalAgentService:I}=await Promise.resolve().then(()=>(It(),Mn)),E=I.getInstance();C=await this.requestCliConfirmation(E,r,g.paths,c)}if(C==="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
@@ -297,7 +297,7 @@ Options:
297
297
 
298
298
  `,I+=`Error:
299
299
  ${E}`,[{type:"text",text:I}]}}catch(v){return u.debug(`[RunCommandTool] Failed to execute bash command: ${v.message}`),[{type:"text",text:`Command: ${r}
300
- Error: ${v.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;jt()?(a="powershell.exe",c=["-ExecutionPolicy","Bypass","-Command",t]):(a="/bin/bash",c=["-c",t]);let l=bh(a,c,{cwd:o,env:process.env,stdio:["ignore","pipe","pipe"],detached:!jt()});l.unref();let d={id:r,command:t,startTime:new Date,status:"running",output:[],error:[],pid:l.pid};qe.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}`),qe.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),qe.updateProcess(r,{endTime:new Date,status:"failed"})}),n&&setTimeout(()=>{let h=qe.getProcess(r);h&&h.status==="running"&&(u.debug(`[RunCommandTool] Background process ${r} timed out, killing...`),is(l.pid,"SIGTERM"),setTimeout(()=>{let f=qe.getProcess(r);f&&f.status==="running"&&is(l.pid,"SIGKILL")},3e3),qe.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}
300
+ Error: ${v.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;jt()?(a="powershell.exe",c=["-ExecutionPolicy","Bypass","-Command",t]):(a="/bin/bash",c=["-c",t]);let l=vh(a,c,{cwd:o,env:process.env,stdio:["ignore","pipe","pipe"],detached:!jt()});l.unref();let d={id:r,command:t,startTime:new Date,status:"running",output:[],error:[],pid:l.pid};qe.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}`),qe.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),qe.updateProcess(r,{endTime:new Date,status:"failed"})}),n&&setTimeout(()=>{let h=qe.getProcess(r);h&&h.status==="running"&&(u.debug(`[RunCommandTool] Background process ${r} timed out, killing...`),is(l.pid,"SIGTERM"),setTimeout(()=>{let f=qe.getProcess(r);f&&f.status==="running"&&is(l.pid,"SIGKILL")},3e3),qe.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 Qr,$l=L(()=>{"use strict";V();as();Qr=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=qe.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 Qr,Fl=L(()=>{"use strict";V();as();Qr=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=qe.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 Jr,Fl=L(()=>{"use strict";V();as();Jr=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=qe.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){is(o.pid,"SIGTERM");let a=o.pid;setTimeout(()=>{let d=qe.getProcess(r);d&&d.status==="running"&&is(a,"SIGKILL")},3e3).unref(),qe.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 Xi,yh,Zr,Ll=L(()=>{"use strict";V();as();Xi=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=qe.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=qe.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(()=>(ls(),Vi)),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 Jr,Ll=L(()=>{"use strict";V();as();Jr=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=qe.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){is(o.pid,"SIGTERM");let a=o.pid;setTimeout(()=>{let d=qe.getProcess(r);d&&d.status==="running"&&is(a,"SIGKILL")},3e3).unref(),qe.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 Xi,Sh,Zr,Ul=L(()=>{"use strict";V();as();Xi=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=qe.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=qe.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(()=>(ls(),Vi)),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,19 +350,19 @@ 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")}},yh=Xi.getInstance(),Zr=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=yh.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")}},Sh=Xi.getInstance(),Zr=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=Sh.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 eo,Ul=L(()=>{"use strict";V();eo=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:v}=await import("child_process"),{promisify:T}=await import("util"),C=T(v),I="rg",E=!0;try{await C("which rg",{timeout:5e3})}catch{u.debug("[GrepTool] ripgrep not found, falling back to grep"),I="grep -r",E=!1}if(E){switch(d&&(I+=" -i"),g&&(I+=" -n"),o){case"files_with_matches":I+=" -l";break;case"count":I+=" -c";break;case"content":default:break}h!==void 0?I+=` -C ${h}`:(m!==void 0&&(I+=` -A ${m}`),p!==void 0&&(I+=` -B ${p}`)),f&&(I+=" -U --multiline-dotall"),I+=` "${r.replace(/"/g,'\\"')}"`,c&&(I+=` --glob="${c}"`),l&&(I+=` --type=${l}`),I+=` "${a}"`}else{switch(d&&(I+=" -i"),g&&(I+=" -n"),o){case"files_with_matches":I+=" -l";break;case"count":I+=" -c";break}h!==void 0?I+=` -C ${h}`:(m!==void 0&&(I+=` -A ${m}`),p!==void 0&&(I+=` -B ${p}`)),I+=` "${r.replace(/"/g,'\\"')}"`,c&&(I+=` --include="${c}"`),I+=` "${a}"`}y!==void 0&&y>0&&(I+=` | head -n ${y}`),u.debug(`[GrepTool] Executing: ${I}`);let{stdout:w,stderr:S}=await C(I,{maxBuffer:10*1024*1024,timeout:3e4});if(!w&&!S)return[{type:"text",text:"No matches found"}];let P=w||S;if(o==="content"&&P){let A=`
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 eo,Bl=L(()=>{"use strict";V();eo=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:v}=await import("child_process"),{promisify:T}=await import("util"),C=T(v),I="rg",E=!0;try{await C("which rg",{timeout:5e3})}catch{u.debug("[GrepTool] ripgrep not found, falling back to grep"),I="grep -r",E=!1}if(E){switch(d&&(I+=" -i"),g&&(I+=" -n"),o){case"files_with_matches":I+=" -l";break;case"count":I+=" -c";break;case"content":default:break}h!==void 0?I+=` -C ${h}`:(m!==void 0&&(I+=` -A ${m}`),p!==void 0&&(I+=` -B ${p}`)),f&&(I+=" -U --multiline-dotall"),I+=` "${r.replace(/"/g,'\\"')}"`,c&&(I+=` --glob="${c}"`),l&&(I+=` --type=${l}`),I+=` "${a}"`}else{switch(d&&(I+=" -i"),g&&(I+=" -n"),o){case"files_with_matches":I+=" -l";break;case"count":I+=" -c";break}h!==void 0?I+=` -C ${h}`:(m!==void 0&&(I+=` -A ${m}`),p!==void 0&&(I+=` -B ${p}`)),I+=` "${r.replace(/"/g,'\\"')}"`,c&&(I+=` --include="${c}"`),I+=` "${a}"`}y!==void 0&&y>0&&(I+=` | head -n ${y}`),u.debug(`[GrepTool] Executing: ${I}`);let{stdout:w,stderr:S}=await C(I,{maxBuffer:10*1024*1024,timeout:3e4});if(!w&&!S)return[{type:"text",text:"No matches found"}];let P=w||S;if(o==="content"&&P){let A=`
360
360
 
361
361
  [Found ${P.trim().split(`
362
- `).length} matching line(s)]`;return[{type:"text",text:P+A}]}return[{type:"text",text:P}]}catch(v){return v.code===1?[{type:"text",text:"No matches found"}]:(u.debug(`[GrepTool] Grep failed: ${v.message}`),v.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 to,Bl=L(()=>{"use strict";V();to=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:P+A}]}return[{type:"text",text:P}]}catch(v){return v.code===1?[{type:"text",text:"No matches found"}]:(u.debug(`[GrepTool] Grep failed: ${v.message}`),v.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 to,Wl=L(()=>{"use strict";V();to=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 no,Wl=L(()=>{"use strict";V();no=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 vh,execSync as vI}from"child_process";import{promisify as Sh}from"util";function so(){return process.platform==="win32"}function Hl(){return process.platform==="darwin"}function Gl(){return process.platform==="linux"}var wI,jl=L(()=>{"use strict";wI=Sh(vh)});var zl={};Ue(zl,{DeviceKnowledgeService:()=>ro,deviceKnowledgeService:()=>Ce});import*as Xe from"fs";import*as rn from"path";import*as xe from"os";import{exec as wh}from"child_process";var ro,Ce,oo=L(()=>{"use strict";jl();ro=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 rn.join(xe.homedir(),".orion")}getKnowledgeFilePath(){return rn.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!Xe.existsSync(this.orionDirectory))try{Xe.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),so()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{wh(`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 Xe.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return Xe.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),Xe.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 no,Hl=L(()=>{"use strict";V();no=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 wh,execSync as wI}from"child_process";import{promisify as Th}from"util";function so(){return process.platform==="win32"}function Gl(){return process.platform==="darwin"}function jl(){return process.platform==="linux"}var xI,zl=L(()=>{"use strict";xI=Th(wh)});var ql={};Ue(ql,{DeviceKnowledgeService:()=>ro,deviceKnowledgeService:()=>Ce});import*as Xe from"fs";import*as rn from"path";import*as xe from"os";import{exec as xh}from"child_process";var ro,Ce,oo=L(()=>{"use strict";zl();ro=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 rn.join(xe.homedir(),".orion")}getKnowledgeFilePath(){return rn.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!Xe.existsSync(this.orionDirectory))try{Xe.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),so()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{xh(`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 Xe.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return Xe.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),Xe.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
367
  `+e;return this.writeDeviceKnowledge(n)}getKnowledgeFileSize(){try{return Xe.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
368
368
 
@@ -385,10 +385,10 @@ ${p.join(`
385
385
  `,e+=`- **Desktop**: ${rn.join(xe.homedir(),"Desktop")}
386
386
  `,e+=`- **Documents**: ${rn.join(xe.homedir(),"Documents")}
387
387
  `,e+=`- **Downloads**: ${rn.join(xe.homedir(),"Downloads")}
388
- `,Hl()?e+=`- **Applications**: /Applications
388
+ `,Gl()?e+=`- **Applications**: /Applications
389
389
  `:so()?(e+=`- **Program Files**: C:\\Program Files
390
390
  `,e+=`- **AppData**: ${rn.join(xe.homedir(),"AppData")}
391
- `):Gl()&&(e+=`- **Config**: ${rn.join(xe.homedir(),".config")}
391
+ `):jl()&&(e+=`- **Config**: ${rn.join(xe.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 Xe.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return Xe.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=Xe.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}},Ce=ro.shared()});var io,ql=L(()=>{"use strict";V();Et();oo();io=class{toolNames=["manage_device_knowledge"];async execute(e,t,n,s){let r=n.action,o=Date.now();u.debug(`[ManageDeviceKnowledgeTool] Executing action: ${r}`),ee.start("ManageDeviceKnowledge",r);try{let a,c=!0;switch(r){case"read":{let d=Ce.readDeviceKnowledge();d?a=d:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await Ce.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${Ce.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",c=!1);break}case"write":{let d=n.content;d?Ce.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?Ce.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):Ce.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):Ce.addNote(d,g,m)?a=`Note "${d}" added to ${m} successfully.`:(a=`Failed to add note "${d}".`,c=!1);break}case"delete":{Ce.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",c=!1);break}case"path":{a=Ce.getKnowledgeFilePath();break}case"exists":{a=Ce.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${Ce.getKnowledgeFileSize()} bytes`;break}case"export":{let d=n.destination;d?Ce.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?Ce.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 ee.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 ee.result({toolName:"ManageDeviceKnowledge",output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});var ao,Kl=L(()=>{"use strict";V();ao=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 co,Vl=L(()=>{"use strict";V();co=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(()=>(Xr(),Ki))).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 Th}from"child_process";import{promisify as xh}from"util";import*as lo from"fs/promises";import*as Xl from"path";import*as Yl from"os";var Ch,us,Yi=L(()=>{"use strict";V();Ch=xh(Th),us=class i{static instance;constructor(){}static getInstance(){return i.instance||(i.instance=new i),i.instance}async captureScreen(){try{let e=Xl.join(Yl.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 Xe.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return Xe.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=Xe.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}},Ce=ro.shared()});var io,Kl=L(()=>{"use strict";V();Et();oo();io=class{toolNames=["manage_device_knowledge"];async execute(e,t,n,s){let r=n.action,o=Date.now();u.debug(`[ManageDeviceKnowledgeTool] Executing action: ${r}`),ee.start("ManageDeviceKnowledge",r);try{let a,c=!0;switch(r){case"read":{let d=Ce.readDeviceKnowledge();d?a=d:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await Ce.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${Ce.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",c=!1);break}case"write":{let d=n.content;d?Ce.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?Ce.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):Ce.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):Ce.addNote(d,g,m)?a=`Note "${d}" added to ${m} successfully.`:(a=`Failed to add note "${d}".`,c=!1);break}case"delete":{Ce.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",c=!1);break}case"path":{a=Ce.getKnowledgeFilePath();break}case"exists":{a=Ce.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${Ce.getKnowledgeFileSize()} bytes`;break}case"export":{let d=n.destination;d?Ce.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?Ce.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 ee.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 ee.result({toolName:"ManageDeviceKnowledge",output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});var ao,Vl=L(()=>{"use strict";V();ao=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 co,Xl=L(()=>{"use strict";V();co=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(()=>(Xr(),Ki))).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 Ch}from"child_process";import{promisify as Eh}from"util";import*as lo from"fs/promises";import*as Yl from"path";import*as Ql from"os";var Ih,us,Yi=L(()=>{"use strict";V();Ih=Eh(Ch),us=class i{static instance;constructor(){}static getInstance(){return i.instance||(i.instance=new i),i.instance}async captureScreen(){try{let e=Yl.join(Ql.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 Ch(t);let n=await lo.readFile(e),s=n.toString("base64");return await lo.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 Ih(t);let n=await lo.readFile(e),s=n.toString("base64");return await lo.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 uo,Ql=L(()=>{"use strict";V();Yi();uo=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,n,s){u.debug("[TakeScreenshotTool] Capturing screenshot...");try{let o=await us.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 Qi,Eh,b,bt=L(()=>{"use strict";Qi=process.env.BROWSER_USE_DEBUG==="1"||"false"?.includes("browser-use"),Eh={log:Qi?console.log.bind(console):()=>{},debug:Qi?console.debug.bind(console):()=>{},info:Qi?console.info.bind(console):()=>{}},b=Eh});import{EventEmitter as Ih}from"eventemitter3";function De(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 go,se,Ji=L(()=>{"use strict";go=class extends Ih{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))}};se={NAVIGATE_TO_URL:De("TIMEOUT_NavigateToUrlEvent",15),CLICK_ELEMENT:De("TIMEOUT_ClickElementEvent",15),TYPE_TEXT:De("TIMEOUT_TypeTextEvent",60),SCROLL:De("TIMEOUT_ScrollEvent",8),SWITCH_TAB:De("TIMEOUT_SwitchTabEvent",10),CLOSE_TAB:De("TIMEOUT_CloseTabEvent",10),SCREENSHOT:De("TIMEOUT_ScreenshotEvent",15),BROWSER_STATE_REQUEST:De("TIMEOUT_BrowserStateRequestEvent",30),GO_BACK:De("TIMEOUT_GoBackEvent",15),GO_FORWARD:De("TIMEOUT_GoForwardEvent",15),REFRESH:De("TIMEOUT_RefreshEvent",15),WAIT:De("TIMEOUT_WaitEvent",60),SEND_KEYS:De("TIMEOUT_SendKeysEvent",60),UPLOAD_FILE:De("TIMEOUT_UploadFileEvent",30),GET_DROPDOWN_OPTIONS:De("TIMEOUT_GetDropdownOptionsEvent",15),SELECT_DROPDOWN_OPTION:De("TIMEOUT_SelectDropdownOptionEvent",8),SCROLL_TO_TEXT:De("TIMEOUT_ScrollToTextEvent",15),BROWSER_START:De("TIMEOUT_BrowserStartEvent",30),BROWSER_STOP:De("TIMEOUT_BrowserStopEvent",45)}});var X,Zi=L(()=>{"use strict";X={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 Jl,zI,Xs,Zl=L(()=>{"use strict";bt();Jl=["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"],zI=["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(", "),Xs=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 v=a.isClickable?.index||[];f.isClickable=v.includes(h)}let y=g.get(h);if(y!==void 0){let v=c.bounds||[];if(y<v.length){let w=v[y];w&&w.length>=4&&(f.bounds={x:w[0]/t,y:w[1]/t,width:w[2]/t,height:w[3]/t})}let T=c.styles||[];if(y<T.length){let w=T[y]||[],S={};for(let P=0;P<w.length&&P<r.length;P++){let x=w[P];x>=0&&x<s.length&&(S[r[P]]=s[x])}Object.keys(S).length>0&&(f.computedStyles=S,f.cursorStyle=S.cursor)}let C=c.paintOrders||[];y<C.length&&(f.paintOrder=C[y]);let I=c.clientRects||[];if(y<I.length){let w=I[y];w&&w.length>=4&&(f.clientRects={x:w[0],y:w[1],width:w[2],height:w[3]})}let E=c.scrollRects||[];if(y<E.length){let w=E[y];w&&w.length>=4&&(f.scrollRects={x:w[0],y:w[1],width:w[2],height:w[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(v=>y.toLowerCase().includes(v)))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,v=c.x-g.x,T=c.y-g.y;if(!(v<f&&v+c.width>0&&T<y+2e3&&T+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 v=["modal","overlay","dialog","popup","drawer","backdrop","lightbox"];for(let T of v)if(f.includes(T)||y.includes(T)){m.push(`class/id contains "${T}"`);break}if(c&&l){let T=(c.position||"").toLowerCase(),I=l.width*l.height/s;if((T==="fixed"||T==="absolute")&&I>=r&&m.push(`${T} position, covers ${(I*100).toFixed(0)}% of viewport`),I>=.8){let E=parseFloat(c.opacity||"1");((c["background-color"]||"").includes("rgba")||E<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 uo,Jl=L(()=>{"use strict";V();Yi();uo=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,n,s){u.debug("[TakeScreenshotTool] Capturing screenshot...");try{let o=await us.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 Qi,kh,b,bt=L(()=>{"use strict";Qi=process.env.BROWSER_USE_DEBUG==="1"||"false"?.includes("browser-use"),kh={log:Qi?console.log.bind(console):()=>{},debug:Qi?console.debug.bind(console):()=>{},info:Qi?console.info.bind(console):()=>{}},b=kh});import{EventEmitter as Ph}from"eventemitter3";function De(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 go,se,Ji=L(()=>{"use strict";go=class extends Ph{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))}};se={NAVIGATE_TO_URL:De("TIMEOUT_NavigateToUrlEvent",15),CLICK_ELEMENT:De("TIMEOUT_ClickElementEvent",15),TYPE_TEXT:De("TIMEOUT_TypeTextEvent",60),SCROLL:De("TIMEOUT_ScrollEvent",8),SWITCH_TAB:De("TIMEOUT_SwitchTabEvent",10),CLOSE_TAB:De("TIMEOUT_CloseTabEvent",10),SCREENSHOT:De("TIMEOUT_ScreenshotEvent",15),BROWSER_STATE_REQUEST:De("TIMEOUT_BrowserStateRequestEvent",30),GO_BACK:De("TIMEOUT_GoBackEvent",15),GO_FORWARD:De("TIMEOUT_GoForwardEvent",15),REFRESH:De("TIMEOUT_RefreshEvent",15),WAIT:De("TIMEOUT_WaitEvent",60),SEND_KEYS:De("TIMEOUT_SendKeysEvent",60),UPLOAD_FILE:De("TIMEOUT_UploadFileEvent",30),GET_DROPDOWN_OPTIONS:De("TIMEOUT_GetDropdownOptionsEvent",15),SELECT_DROPDOWN_OPTION:De("TIMEOUT_SelectDropdownOptionEvent",8),SCROLL_TO_TEXT:De("TIMEOUT_ScrollToTextEvent",15),BROWSER_START:De("TIMEOUT_BrowserStartEvent",30),BROWSER_STOP:De("TIMEOUT_BrowserStopEvent",45)}});var X,Zi=L(()=>{"use strict";X={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 Zl,KI,Xs,eu=L(()=>{"use strict";bt();Zl=["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"],KI=["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(", "),Xs=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 v=a.isClickable?.index||[];f.isClickable=v.includes(h)}let y=g.get(h);if(y!==void 0){let v=c.bounds||[];if(y<v.length){let w=v[y];w&&w.length>=4&&(f.bounds={x:w[0]/t,y:w[1]/t,width:w[2]/t,height:w[3]/t})}let T=c.styles||[];if(y<T.length){let w=T[y]||[],S={};for(let P=0;P<w.length&&P<r.length;P++){let x=w[P];x>=0&&x<s.length&&(S[r[P]]=s[x])}Object.keys(S).length>0&&(f.computedStyles=S,f.cursorStyle=S.cursor)}let C=c.paintOrders||[];y<C.length&&(f.paintOrder=C[y]);let I=c.clientRects||[];if(y<I.length){let w=I[y];w&&w.length>=4&&(f.clientRects={x:w[0],y:w[1],width:w[2],height:w[3]})}let E=c.scrollRects||[];if(y<E.length){let w=E[y];w&&w.length>=4&&(f.scrollRects={x:w[0],y:w[1],width:w[2],height:w[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(v=>y.toLowerCase().includes(v)))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,v=c.x-g.x,T=c.y-g.y;if(!(v<f&&v+c.width>0&&T<y+2e3&&T+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 v=["modal","overlay","dialog","popup","drawer","backdrop","lightbox"];for(let T of v)if(f.includes(T)||y.includes(T)){m.push(`class/id contains "${T}"`);break}if(c&&l){let T=(c.position||"").toLowerCase(),I=l.width*l.height/s;if((T==="fixed"||T==="absolute")&&I>=r&&m.push(`${T} position, covers ${(I*100).toFixed(0)}% of viewport`),I>=.8){let E=parseFloat(c.opacity||"1");((c["background-color"]||"").includes("rgba")||E<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') {
@@ -428,7 +428,7 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
428
428
 
429
429
  return elementsWithListeners;
430
430
  })()
431
- `,includeCommandLineAPI:!0,returnByValue:!1})).result?.objectId;if(s){let r=await e.send("Runtime.getProperties",{objectId:s,ownProperties:!0}),o=[];for(let l of r.result||[]){let d=l?.name||"";if(typeof d=="string"&&/^\d+$/.test(d)){let g=l?.value?.objectId;g&&typeof g=="string"&&o.push(g)}}let a=o.map(async l=>{try{return(await e.send("DOM.describeNode",{objectId:l})).node?.backendNodeId}catch{return null}}),c=await Promise.all(a);for(let l of c)l!=null&&t.add(l);try{await e.send("Runtime.releaseObject",{objectId:s})}catch{}b.debug(`🔍 Detected ${t.size} elements with JS click listeners`)}}catch(n){b.debug("Failed to detect JS event listeners:",n)}return t}async getPageState(e={}){let t=e.includeAttributes||Jl,n=await this.getCDPSession();try{let S=await n.send("Runtime.evaluate",{expression:"document.readyState"});b.debug(`📄 Document readyState: ${S.result?.value}`)}catch(S){b.debug("Failed to get document readyState:",S)}let s=await this.detectJsClickListeners(n),r=await this.getViewportInfo(),o=await this.getAccessibilityTree(),a;try{a=(await n.send("DOM.getDocument",{depth:-1,pierce:!0})).root}catch(S){throw console.error("Failed to get DOM via CDP:",S),S}let c=new Map;try{let P=(await n.send("Runtime.evaluate",{expression:`
431
+ `,includeCommandLineAPI:!0,returnByValue:!1})).result?.objectId;if(s){let r=await e.send("Runtime.getProperties",{objectId:s,ownProperties:!0}),o=[];for(let l of r.result||[]){let d=l?.name||"";if(typeof d=="string"&&/^\d+$/.test(d)){let g=l?.value?.objectId;g&&typeof g=="string"&&o.push(g)}}let a=o.map(async l=>{try{return(await e.send("DOM.describeNode",{objectId:l})).node?.backendNodeId}catch{return null}}),c=await Promise.all(a);for(let l of c)l!=null&&t.add(l);try{await e.send("Runtime.releaseObject",{objectId:s})}catch{}b.debug(`🔍 Detected ${t.size} elements with JS click listeners`)}}catch(n){b.debug("Failed to detect JS event listeners:",n)}return t}async getPageState(e={}){let t=e.includeAttributes||Zl,n=await this.getCDPSession();try{let S=await n.send("Runtime.evaluate",{expression:"document.readyState"});b.debug(`📄 Document readyState: ${S.result?.value}`)}catch(S){b.debug("Failed to get document readyState:",S)}let s=await this.detectJsClickListeners(n),r=await this.getViewportInfo(),o=await this.getAccessibilityTree(),a;try{a=(await n.send("DOM.getDocument",{depth:-1,pierce:!0})).root}catch(S){throw console.error("Failed to get DOM via CDP:",S),S}let c=new Map;try{let P=(await n.send("Runtime.evaluate",{expression:`
432
432
  (() => {
433
433
  const scrollData = {};
434
434
  const iframes = document.querySelectorAll('iframe');
@@ -448,7 +448,7 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
448
448
  return scrollData;
449
449
  })()
450
450
  `,returnByValue:!0})).result?.value;if(P)for(let[x,A]of Object.entries(P)){let O=A;c.set(parseInt(x),O),b.debug(`Iframe ${x} scroll position - scrollTop=${O.scrollTop}, scrollLeft=${O.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,P,x,A=0)=>{P===null&&(P=[]),x===null?x={x:0,y:0}:x={x:x.x,y:x.y};let O=S.backendNodeId,U=S.nodeName?.toLowerCase()||"",D=S.nodeType;if(D===9||D===11){let te=[];if(S.children)for(let je of S.children){let xt=h(je,P,x,A);xt&&te.push(xt)}return te.length===1?te[0]:te.length>0?{index:-1,tagName:U,children:te,isInteractive:!1,position:void 0}:null}if(D!==1)return null;let $={};if(S.attributes)for(let te=0;te<S.attributes.length;te+=2){let je=S.attributes[te],xt=S.attributes[te+1];je&&($[je]=xt||"")}let _={};for(let te of t)$[te]&&(_[te]=$[te]);let F=l.get(O),z=F?.isClickable??!1,G=F?.bounds,M=F?.cursorStyle,R=o.get(O),H;G&&(H={x:G.x+x.x,y:G.y+x.y,width:G.width,height:G.height});let B=[...P];D===1&&U==="html"&&S.frameId&&(B.push({nodeName:"HTML",frameId:S.frameId,snapshotData:F}),F?.scrollRects&&(x.x-=F.scrollRects.x,x.y-=F.scrollRects.y)),(U==="iframe"||U==="frame")&&G&&(B.push({nodeName:U.toUpperCase(),frameId:S.frameId,snapshotData:F}),x.x+=G.x,x.y+=G.y);let j=this.isElementVisibleAccordingToAllParents(F,B),ne=s.has(O),pe=this.isInteractiveNode(U,$,z,R,G,M,ne),ue={index:pe?O:-1,tagName:U,children:[],isInteractive:pe,isVisible:j,position:H||G};if(pe&&j){m.add(O);let te="",je=_.role;if(R&&(te=R.name||"",je=R.role||je),!te&&S.children){let Ct=Zt=>{let Ii=[];if(Zt.nodeType===3&&Zt.nodeValue){let Nr=Zt.nodeValue.trim();Nr.length>1&&Ii.push(Nr)}if(Zt.children)for(let Nr of Zt.children)Ii.push(...Ct(Nr));return Ii};te=Ct(S).join(`
451
- `).trim()}!te&&S.nodeValue&&(te=S.nodeValue.trim().substring(0,200)),ue.text=te,ue.role=je;let xt={..._};if(R&&R.properties)for(let Ct of R.properties)try{if(Jl.includes(Ct.name)&&Ct.value!==null&&Ct.value!==void 0){let Rr=Ct.value?.value!==void 0?Ct.value.value:Ct.value;if(typeof Rr=="boolean")xt[Ct.name]=Rr.toString().toLowerCase();else{let Zt=String(Rr).trim();Zt&&(xt[Ct.name]=Zt)}}}catch{continue}R?.name&&!xt.ax_name&&(xt.ax_name=R.name),ue.attributes=xt;let Vc=!this.previousElements.has(O.toString());ue.isNew=Vc;let ip={nodeId:S.nodeId,backendNodeId:O,sessionId:"",frameId:S.frameId||"",targetId:"",nodeType:"element",nodeName:U,attributes:xt,isVisible:j,absolutePosition:H||G,text:te,role:je,isNew:Vc,hasJsClickListener:ne,snapshotNode:F?{isClickable:F.isClickable,cursorStyle:F.cursorStyle,bounds:F.bounds,clientRects:F.clientRects,scrollRects:F.scrollRects,computedStyles:F.computedStyles,paintOrder:F.paintOrder}:null};d.set(O,ip)}let ct=new Set;if(S.shadowRoots)for(let te of S.shadowRoots)te.nodeId&&ct.add(te.nodeId);if(S.children)for(let te of S.children){if(te.nodeId&&ct.has(te.nodeId))continue;let je=h(te,B,x,A+1);je&&ue.children.push(je)}if(S.contentDocument){let te=h(S.contentDocument,B,x,A+1);te&&ue.children.push(te)}else if((U==="iframe"||U==="frame")&&this.crossOriginIframes&&A<this.maxIframeDepth&&S.frameId){let te=G||F?.bounds;j&&te&&te.width>=50&&te.height>=50&&p.push({treeNode:ue,frameId:S.frameId,htmlFrames:B,totalFrameOffset:{...x},depth:A+1})}if(S.shadowRoots)for(let te of S.shadowRoots){let je=h(te,B,x,A+1);je&&ue.children.push(je)}return ue},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 P=(await n.send("Target.getTargets")).targetInfos||[];await n.send("Page.enable");let A=(await n.send("Page.getFrameTree")).frameTree,O=new Map,U=D=>{let $=D.frame||{};if($.id){let _=P.find(F=>F.type==="iframe"&&F.url&&$.url&&F.url===$.url);_&&O.set($.id,_.targetId)}for(let _ of D.childFrames||[])U(_)};A&&U(A);for(let D of p){let $=O.get(D.frameId);if(!$){b.debug(`No target found for cross-origin iframe ${D.frameId}`);continue}try{b.debug(`Found cross-origin iframe target: ${$} for frame ${D.frameId}`);let F=this.page.frames().find(z=>z.url().includes(D.frameId)||z.name()===D.frameId);if(F)try{let z=await F.content();z&&b.debug(`Got content from cross-origin frame ${D.frameId} (${z.length} chars)`)}catch{}}catch(_){b.debug(`Failed to process cross-origin iframe ${D.frameId}:`,_)}}}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 v=d,T=d.size;e.paintOrderFiltering!==!1&&(v=this.applyPaintOrderFiltering(d));let C=v.size;e.bboxFiltering!==!1&&(v=this.applyBoundingBoxFiltering(v));let I={url:this.page.url(),title:await this.page.title(),domTree:g,selectorMap:v,viewportInfo:r};if(e.includeScreenshot!==!1){let S=await this.page.screenshot({type:"png"});I.screenshot=S.toString("base64")}let E=T-C,w=C-v.size;return b.log(`📋 [DOM] Extracted ${v.size} interactive elements with real backendNodeIds (${E} filtered by paint order, ${w} filtered by bbox)`),I}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 v of f)o.attributes[v]!==void 0&&o.attributes[v]!==""&&(h[v]=String(o.attributes[v]).trim());if(Object.keys(h).length>1){let v={},T=[];for(let C of f)if(h[C]){let I=h[C];I.length>5&&(v[I]?T.push(C):v[I]=C)}for(let C of T)delete h[C]}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 v of["aria-label","placeholder","title"])h[v]?.trim().toLowerCase()===y&&delete h[v];for(let v of f)if(h[v]){let T=h[v];T.length>100&&(T=T.substring(0,100)+"..."),p.push(`${v}=${T}`)}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+=`
451
+ `).trim()}!te&&S.nodeValue&&(te=S.nodeValue.trim().substring(0,200)),ue.text=te,ue.role=je;let xt={..._};if(R&&R.properties)for(let Ct of R.properties)try{if(Zl.includes(Ct.name)&&Ct.value!==null&&Ct.value!==void 0){let Rr=Ct.value?.value!==void 0?Ct.value.value:Ct.value;if(typeof Rr=="boolean")xt[Ct.name]=Rr.toString().toLowerCase();else{let Zt=String(Rr).trim();Zt&&(xt[Ct.name]=Zt)}}}catch{continue}R?.name&&!xt.ax_name&&(xt.ax_name=R.name),ue.attributes=xt;let Xc=!this.previousElements.has(O.toString());ue.isNew=Xc;let cp={nodeId:S.nodeId,backendNodeId:O,sessionId:"",frameId:S.frameId||"",targetId:"",nodeType:"element",nodeName:U,attributes:xt,isVisible:j,absolutePosition:H||G,text:te,role:je,isNew:Xc,hasJsClickListener:ne,snapshotNode:F?{isClickable:F.isClickable,cursorStyle:F.cursorStyle,bounds:F.bounds,clientRects:F.clientRects,scrollRects:F.scrollRects,computedStyles:F.computedStyles,paintOrder:F.paintOrder}:null};d.set(O,cp)}let ct=new Set;if(S.shadowRoots)for(let te of S.shadowRoots)te.nodeId&&ct.add(te.nodeId);if(S.children)for(let te of S.children){if(te.nodeId&&ct.has(te.nodeId))continue;let je=h(te,B,x,A+1);je&&ue.children.push(je)}if(S.contentDocument){let te=h(S.contentDocument,B,x,A+1);te&&ue.children.push(te)}else if((U==="iframe"||U==="frame")&&this.crossOriginIframes&&A<this.maxIframeDepth&&S.frameId){let te=G||F?.bounds;j&&te&&te.width>=50&&te.height>=50&&p.push({treeNode:ue,frameId:S.frameId,htmlFrames:B,totalFrameOffset:{...x},depth:A+1})}if(S.shadowRoots)for(let te of S.shadowRoots){let je=h(te,B,x,A+1);je&&ue.children.push(je)}return ue},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 P=(await n.send("Target.getTargets")).targetInfos||[];await n.send("Page.enable");let A=(await n.send("Page.getFrameTree")).frameTree,O=new Map,U=D=>{let $=D.frame||{};if($.id){let _=P.find(F=>F.type==="iframe"&&F.url&&$.url&&F.url===$.url);_&&O.set($.id,_.targetId)}for(let _ of D.childFrames||[])U(_)};A&&U(A);for(let D of p){let $=O.get(D.frameId);if(!$){b.debug(`No target found for cross-origin iframe ${D.frameId}`);continue}try{b.debug(`Found cross-origin iframe target: ${$} for frame ${D.frameId}`);let F=this.page.frames().find(z=>z.url().includes(D.frameId)||z.name()===D.frameId);if(F)try{let z=await F.content();z&&b.debug(`Got content from cross-origin frame ${D.frameId} (${z.length} chars)`)}catch{}}catch(_){b.debug(`Failed to process cross-origin iframe ${D.frameId}:`,_)}}}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 v=d,T=d.size;e.paintOrderFiltering!==!1&&(v=this.applyPaintOrderFiltering(d));let C=v.size;e.bboxFiltering!==!1&&(v=this.applyBoundingBoxFiltering(v));let I={url:this.page.url(),title:await this.page.title(),domTree:g,selectorMap:v,viewportInfo:r};if(e.includeScreenshot!==!1){let S=await this.page.screenshot({type:"png"});I.screenshot=S.toString("base64")}let E=T-C,w=C-v.size;return b.log(`📋 [DOM] Extracted ${v.size} interactive elements with real backendNodeIds (${E} filtered by paint order, ${w} filtered by bbox)`),I}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 v of f)o.attributes[v]!==void 0&&o.attributes[v]!==""&&(h[v]=String(o.attributes[v]).trim());if(Object.keys(h).length>1){let v={},T=[];for(let C of f)if(h[C]){let I=h[C];I.length>5&&(v[I]?T.push(C):v[I]=C)}for(let C of T)delete h[C]}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 v of["aria-label","placeholder","title"])h[v]?.trim().toLowerCase()===y&&delete h[v];for(let v of f)if(h[v]){let T=h[v];T.length>100&&(T=T.substring(0,100)+"..."),p.push(`${v}=${T}`)}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,7 +457,7 @@ ${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 XI}from"patchright";import yt from"fs";import ea from"path";import kh from"os";function Rn(){return ea.join(Ph,Ah)}async function eu(i,e=Rn(),t=!0){let n=ea.dirname(e);yt.existsSync(n)||yt.mkdirSync(n,{recursive:!0});let s=i;if(t&&yt.existsSync(e))try{let o=JSON.parse(yt.readFileSync(e,"utf-8"));s=Mh(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(yt.writeFileSync(r,JSON.stringify(s,null,2)),yt.existsSync(e)){let o=e+".bak";yt.renameSync(e,o)}yt.renameSync(r,e),b.log(`[ProfileImport] Saved profile to ${e}`),b.log(`[ProfileImport] Total: ${s.cookieCount} cookies, ${s.originCount} origins`)}function tu(i=Rn()){if(!yt.existsSync(i))return null;try{return JSON.parse(yt.readFileSync(i,"utf-8"))}catch(e){return console.error(`[ProfileImport] Failed to load profile: ${e.message}`),null}}function Nn(i=Rn()){return yt.existsSync(i)}function Dh(i){return i?{cookies:i.cookies,origins:i.origins}:null}function ds(i=Rn()){let e=tu(i);return Dh(e)}function Mh(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 Ys(i=Rn()){if(!yt.existsSync(i))return{exists:!1,cookieCount:0,originCount:0,importedAt:null,path:i};try{let t=tu(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 Ph,Ah,mo=L(()=>{"use strict";bt();Ph=ea.join(kh.homedir(),".orion"),Ah="browser-profile.json"});import Rh from"crypto";import{z as Ve}from"zod";function Qs(i){return i.nodeName.toLowerCase()}function _h(i){let e=[],t=i;for(;t&&(t.nodeType===1||t.nodeType===11);){if(t.nodeType===11){t=t.parentNode;continue}if(t.parentNode&&Qs(t.parentNode)==="iframe")break;let n=$h(t),s=Qs(t),r=n>0?`[${n}]`:"";e.unshift(`${s}${r}`),t=t.parentNode}return e.join("/")}function $h(i){if(!i.parentNode||!i.parentNode.childrenNodes)return 0;let e=i.parentNode.childrenNodes.filter(n=>n.nodeType===1&&Qs(n)===Qs(i));if(e.length<=1)return 0;let t=e.indexOf(i);return t>=0?t+1:0}function Fh(i){let t=Lh(i).join("/"),n=Object.entries(i.attributes).filter(([o])=>Nh.has(o)).sort().map(([o,a])=>`${o}=${a}`).join(""),s=`${t}|${n}`,r=Rh.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=>Qs(n))}function su(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:_h(i),elementHash:Fh(i)}}var nu,Nh,po,Oh,sk,ho=L(()=>{"use strict";nu=["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"],Nh=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"]),po=(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))(po||{}),Oh=Ve.object({x:Ve.number(),y:Ve.number(),width:Ve.number(),height:Ve.number()}),sk=Ve.object({nodeId:Ve.number(),backendNodeId:Ve.number(),frameId:Ve.string().nullable().optional(),nodeType:Ve.nativeEnum(po),nodeValue:Ve.string(),nodeName:Ve.string(),attributes:Ve.record(Ve.string()).nullable().optional(),bounds:Oh.nullable().optional(),xPath:Ve.string(),elementHash:Ve.number()})});import*as $t from"path";import*as ou from"os";import*as vt from"fs";import{v4 as ik}from"uuid";function Uh(){if(On!==null)return On;try{if(vt.existsSync("/.dockerenv"))return On=!0,!0}catch{}try{if(vt.readFileSync("/proc/1/cgroup","utf-8").toLowerCase().includes("docker"))return On=!0,!0}catch{}try{let i=vt.readFileSync("/proc/1/cmdline","utf-8").replace(/\0/g," ");if(/\b(node|python|py|uv|app)\b/i.test(i))return On=!0,!0}catch{}try{if(vt.readdirSync("/proc").filter(t=>/^\d+$/.test(t)).length<10)return On=!0,!0}catch{}return On=!1,!1}function Js(i,e){if(!i)return e;let t=i.toLowerCase().charAt(0);return t==="t"||t==="y"||t==="1"}function ta(i){return i.startsWith("~")?$t.join(ou.homedir(),i.slice(1)):i}function Bh(i){if(!ru)try{vt.mkdirSync(i,{recursive:!0}),vt.mkdirSync($t.join(i,"profiles"),{recursive:!0}),vt.mkdirSync($t.join(i,"extensions"),{recursive:!0}),ru=!0}catch{}}function iu(){let i=ta(process.env.XDG_CACHE_HOME||"~/.cache"),e=ta(process.env.XDG_CONFIG_HOME||"~/.config"),t=ta(process.env.BROWSER_USE_CONFIG_DIR||$t.join(e,"browseruse"));Bh(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:$t.join(t,"config.json"),BROWSER_USE_CONFIG_PATH:process.env.BROWSER_USE_CONFIG_PATH||null,BROWSER_USE_PROFILES_DIR:$t.join(t,"profiles"),BROWSER_USE_DEFAULT_USER_DATA_DIR:$t.join(t,"profiles","default"),BROWSER_USE_EXTENSIONS_DIR:$t.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 On,ru,au=L(()=>{"use strict";On=null;ru=!1});var Ft,Zs,fo,er=L(()=>{"use strict";Ft={"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},fo={text:40,title:56,goal:44}});function Wh(i,e){return i.toLowerCase()==="input"&&e&&(e==="button"||e==="submit")?na.button:na[i.toLowerCase()]||na.default}function Hh(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 cu(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),v=Math.floor((h.x+(h.width||0))*t),T=Math.floor((h.y+(h.height||0))*t),C=Math.max(0,Math.min(f,a)),I=Math.max(0,Math.min(y,c)),E=Math.max(C,Math.min(v,a)),w=Math.max(I,Math.min(T,c)),S={x:C,y:I,width:E-C,height:w-I};if(S.width<2||S.height<2)continue;let P="";if(p.attributes){let A=["value","aria-label","title","placeholder","alt"];for(let O of A)if(p.attributes[O]){P=p.attributes[O];break}}P||(P=p.text||""),P=P.trim();let x=n?P.length<3:!0;l.push({index:m,bbox:S,tagName:p.nodeName||"div",elementType:p.attributes?.type,text:x?String(m):void 0,backendNodeId:m})}if(l.length===0)return i;let d=Gh(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 Gh(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,v,T){let C="";if(m===h){let I=Math.min(p,f),E=Math.max(p,f);for(;I<E;){let w=Math.min(I+c,E);C+=`<line x1="${m}" y1="${I}" x2="${m}" y2="${w}" stroke="${y}" stroke-width="${T}"/>`,I+=c+l}}else{let I=Math.min(m,h),E=Math.max(m,h);for(;I<E;){let w=Math.min(I+c,E);C+=`<line x1="${I}" y1="${p}" x2="${w}" y2="${p}" stroke="${y}" stroke-width="${T}"/>`,I+=c+l}}return C}for(let m of i){let{bbox:p,tagName:h,elementType:f,text:y}=m,v=Wh(h,f),T=Math.max(0,Math.floor(p.x)),C=Math.max(0,Math.floor(p.y)),I=Math.min(Math.floor(p.x+p.width),e),E=Math.min(Math.floor(p.y+p.height),t);if(I-T<=0||E-C<=0)continue;a+=g(T,C,I,C,v,void 0,d),a+=g(I,C,I,E,v,void 0,d),a+=g(I,E,T,E,v,void 0,d),a+=g(T,E,T,C,v,void 0,d);let w=I-T,S=E-C;if(y){let P=y.length*(r*.6),x=r,A=P+o*2,O=x+o*2,D=Hh({x:T,y:C,width:w,height:S},P,x,o,e,t),$=D.x,_=D.y;a+=`
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 QI}from"patchright";import yt from"fs";import ea from"path";import Ah from"os";function Rn(){return ea.join(Dh,Mh)}async function tu(i,e=Rn(),t=!0){let n=ea.dirname(e);yt.existsSync(n)||yt.mkdirSync(n,{recursive:!0});let s=i;if(t&&yt.existsSync(e))try{let o=JSON.parse(yt.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(yt.writeFileSync(r,JSON.stringify(s,null,2)),yt.existsSync(e)){let o=e+".bak";yt.renameSync(e,o)}yt.renameSync(r,e),b.log(`[ProfileImport] Saved profile to ${e}`),b.log(`[ProfileImport] Total: ${s.cookieCount} cookies, ${s.originCount} origins`)}function nu(i=Rn()){if(!yt.existsSync(i))return null;try{return JSON.parse(yt.readFileSync(i,"utf-8"))}catch(e){return console.error(`[ProfileImport] Failed to load profile: ${e.message}`),null}}function Nn(i=Rn()){return yt.existsSync(i)}function Rh(i){return i?{cookies:i.cookies,origins:i.origins}:null}function ds(i=Rn()){let e=nu(i);return Rh(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 Ys(i=Rn()){if(!yt.existsSync(i))return{exists:!1,cookieCount:0,originCount:0,importedAt:null,path:i};try{let t=nu(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 Dh,Mh,mo=L(()=>{"use strict";bt();Dh=ea.join(Ah.homedir(),".orion"),Mh="browser-profile.json"});import Oh from"crypto";import{z as Ve}from"zod";function Qs(i){return i.nodeName.toLowerCase()}function Fh(i){let e=[],t=i;for(;t&&(t.nodeType===1||t.nodeType===11);){if(t.nodeType===11){t=t.parentNode;continue}if(t.parentNode&&Qs(t.parentNode)==="iframe")break;let n=Lh(t),s=Qs(t),r=n>0?`[${n}]`:"";e.unshift(`${s}${r}`),t=t.parentNode}return e.join("/")}function Lh(i){if(!i.parentNode||!i.parentNode.childrenNodes)return 0;let e=i.parentNode.childrenNodes.filter(n=>n.nodeType===1&&Qs(n)===Qs(i));if(e.length<=1)return 0;let t=e.indexOf(i);return t>=0?t+1:0}function Uh(i){let t=Bh(i).join("/"),n=Object.entries(i.attributes).filter(([o])=>_h.has(o)).sort().map(([o,a])=>`${o}=${a}`).join(""),s=`${t}|${n}`,r=Oh.createHash("sha256").update(s).digest("hex");return parseInt(r.substring(0,16),16)}function Bh(i){let e=[],t=i;for(;t;)t.nodeType===1&&e.push(t),t=t.parentNode;return e.reverse(),e.map(n=>Qs(n))}function ru(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:Fh(i),elementHash:Uh(i)}}var su,_h,po,$h,ok,ho=L(()=>{"use strict";su=["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"],_h=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"]),po=(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))(po||{}),$h=Ve.object({x:Ve.number(),y:Ve.number(),width:Ve.number(),height:Ve.number()}),ok=Ve.object({nodeId:Ve.number(),backendNodeId:Ve.number(),frameId:Ve.string().nullable().optional(),nodeType:Ve.nativeEnum(po),nodeValue:Ve.string(),nodeName:Ve.string(),attributes:Ve.record(Ve.string()).nullable().optional(),bounds:$h.nullable().optional(),xPath:Ve.string(),elementHash:Ve.number()})});import*as $t from"path";import*as iu from"os";import*as vt from"fs";import{v4 as ck}from"uuid";function Wh(){if(On!==null)return On;try{if(vt.existsSync("/.dockerenv"))return On=!0,!0}catch{}try{if(vt.readFileSync("/proc/1/cgroup","utf-8").toLowerCase().includes("docker"))return On=!0,!0}catch{}try{let i=vt.readFileSync("/proc/1/cmdline","utf-8").replace(/\0/g," ");if(/\b(node|python|py|uv|app)\b/i.test(i))return On=!0,!0}catch{}try{if(vt.readdirSync("/proc").filter(t=>/^\d+$/.test(t)).length<10)return On=!0,!0}catch{}return On=!1,!1}function Js(i,e){if(!i)return e;let t=i.toLowerCase().charAt(0);return t==="t"||t==="y"||t==="1"}function ta(i){return i.startsWith("~")?$t.join(iu.homedir(),i.slice(1)):i}function Hh(i){if(!ou)try{vt.mkdirSync(i,{recursive:!0}),vt.mkdirSync($t.join(i,"profiles"),{recursive:!0}),vt.mkdirSync($t.join(i,"extensions"),{recursive:!0}),ou=!0}catch{}}function au(){let i=ta(process.env.XDG_CACHE_HOME||"~/.cache"),e=ta(process.env.XDG_CONFIG_HOME||"~/.config"),t=ta(process.env.BROWSER_USE_CONFIG_DIR||$t.join(e,"browseruse"));Hh(t);let n=Js(process.env.ANONYMIZED_TELEMETRY,!0),s=process.env.IN_DOCKER,r=s!==void 0?Js(s,!1):Wh();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:$t.join(t,"config.json"),BROWSER_USE_CONFIG_PATH:process.env.BROWSER_USE_CONFIG_PATH||null,BROWSER_USE_PROFILES_DIR:$t.join(t,"profiles"),BROWSER_USE_DEFAULT_USER_DATA_DIR:$t.join(t,"profiles","default"),BROWSER_USE_EXTENSIONS_DIR:$t.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 On,ou,cu=L(()=>{"use strict";On=null;ou=!1});var Ft,Zs,fo,er=L(()=>{"use strict";Ft={"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},fo={text:40,title:56,goal:44}});function Gh(i,e){return i.toLowerCase()==="input"&&e&&(e==="button"||e==="submit")?na.button:na[i.toLowerCase()]||na.default}function jh(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 lu(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),v=Math.floor((h.x+(h.width||0))*t),T=Math.floor((h.y+(h.height||0))*t),C=Math.max(0,Math.min(f,a)),I=Math.max(0,Math.min(y,c)),E=Math.max(C,Math.min(v,a)),w=Math.max(I,Math.min(T,c)),S={x:C,y:I,width:E-C,height:w-I};if(S.width<2||S.height<2)continue;let P="";if(p.attributes){let A=["value","aria-label","title","placeholder","alt"];for(let O of A)if(p.attributes[O]){P=p.attributes[O];break}}P||(P=p.text||""),P=P.trim();let x=n?P.length<3:!0;l.push({index:m,bbox:S,tagName:p.nodeName||"div",elementType:p.attributes?.type,text:x?String(m):void 0,backendNodeId:m})}if(l.length===0)return i;let d=zh(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 zh(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,v,T){let C="";if(m===h){let I=Math.min(p,f),E=Math.max(p,f);for(;I<E;){let w=Math.min(I+c,E);C+=`<line x1="${m}" y1="${I}" x2="${m}" y2="${w}" stroke="${y}" stroke-width="${T}"/>`,I+=c+l}}else{let I=Math.min(m,h),E=Math.max(m,h);for(;I<E;){let w=Math.min(I+c,E);C+=`<line x1="${I}" y1="${p}" x2="${w}" y2="${p}" stroke="${y}" stroke-width="${T}"/>`,I+=c+l}}return C}for(let m of i){let{bbox:p,tagName:h,elementType:f,text:y}=m,v=Gh(h,f),T=Math.max(0,Math.floor(p.x)),C=Math.max(0,Math.floor(p.y)),I=Math.min(Math.floor(p.x+p.width),e),E=Math.min(Math.floor(p.y+p.height),t);if(I-T<=0||E-C<=0)continue;a+=g(T,C,I,C,v,void 0,d),a+=g(I,C,I,E,v,void 0,d),a+=g(I,E,T,E,v,void 0,d),a+=g(T,E,T,C,v,void 0,d);let w=I-T,S=E-C;if(y){let P=y.length*(r*.6),x=r,A=P+o*2,O=x+o*2,D=jh({x:T,y:C,width:w,height:S},P,x,o,e,t),$=D.x,_=D.y;a+=`
461
461
  <rect x="${$}" y="${_}" width="${A}" height="${O}"
462
462
  fill="${v}" rx="3"/>
463
463
  `;let F=$+Math.floor((A-P)/2),z=_+Math.floor((O+x*.7)/2);a+=`
@@ -470,7 +470,7 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
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 na,lu=L(()=>{"use strict";bt();er();na={button:"#8FA3B8",input:"#A0B4C8",select:"#B8C5D0",a:"#7A92A8",textarea:"#C0CCD8",default:"#9CADB8"}});import{chromium as jh}from"patchright";import{v4 as zh}from"uuid";function qh(){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 on,sa=L(()=>{"use strict";bt();Ji();Zi();Zl();mo();ho();au();er();lu();on=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||zh(),this.options=e,this.eventBus=new go,this.registerEventHandlers()}registerEventHandlers(){this.eventBus.on(X.NAVIGATE_TO_URL,async e=>{await this.handleNavigateToUrl(e)}),this.eventBus.on(X.CLICK_ELEMENT,async e=>{await this.handleClickElement(e)}),this.eventBus.on(X.TYPE_TEXT,async e=>{await this.handleTypeText(e)}),this.eventBus.on(X.SCROLL,async e=>{await this.handleScroll(e)}),this.eventBus.on(X.BROWSER_STATE_REQUEST,async e=>{await this.handleBrowserStateRequest(e)}),this.eventBus.on(X.SCREENSHOT,async e=>{await this.handleScreenshot(e)}),this.eventBus.on(X.GO_BACK,async e=>{await this.handleGoBack(e)}),this.eventBus.on(X.GO_FORWARD,async e=>{await this.handleGoForward(e)}),this.eventBus.on(X.REFRESH,async e=>{await this.handleRefresh(e)}),this.eventBus.on(X.WAIT,async e=>{await this.handleWait(e)}),this.eventBus.on(X.SEND_KEYS,async e=>{await this.handleSendKeys(e)}),this.eventBus.on(X.UPLOAD_FILE,async e=>{await this.handleUploadFile(e)}),this.eventBus.on(X.GET_DROPDOWN_OPTIONS,async e=>{await this.handleGetDropdownOptions(e)}),this.eventBus.on(X.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=iu(),r;this.options.useRealChromeProfile?(r=qh(),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 jh.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 eu(t,Rn(),!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(T=>T.responseEnd===0||T.transferSize===0&&T.decodedBodySize===0&&!T.name.startsWith("data:")).length,y=document.querySelectorAll('a, button, input, select, textarea, [role="button"], [onclick], [tabindex]').length,v=!!(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:v}});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 Xs(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 I=(await c.send("Page.getLayoutMetrics")).layoutViewport||{};l={width:I.clientWidth||n.viewportSize()?.width||1280,height:I.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 C=null,I=[];try{let E=await c.send("DOM.getContentQuads",{backendNodeId:d});E?.quads?.length>0&&(I=E.quads,b.debug(`Got ${I.length} quads from DOM.getContentQuads`))}catch(E){b.debug("getContentQuads failed:",E.message)}if(I.length===0)try{let E=await c.send("DOM.getBoxModel",{backendNodeId:d});if(E?.model?.content){let w=E.model.content;w.length>=8&&(I=[[w[0],w[1],w[2],w[3],w[4],w[5],w[6],w[7]]],b.debug("Got quad from DOM.getBoxModel"))}}catch(E){b.debug("getBoxModel failed:",E.message)}if(I.length===0)try{let w=(await c.send("DOM.resolveNode",{backendNodeId:d}))?.object?.objectId;if(w){let P=(await c.send("Runtime.callFunctionOn",{objectId:w,functionDeclaration:`function() {
473
+ `}}return a+="</svg>",a}var na,uu=L(()=>{"use strict";bt();er();na={button:"#8FA3B8",input:"#A0B4C8",select:"#B8C5D0",a:"#7A92A8",textarea:"#C0CCD8",default:"#9CADB8"}});import{chromium as qh}from"patchright";import{v4 as Kh}from"uuid";function Vh(){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 on,sa=L(()=>{"use strict";bt();Ji();Zi();eu();mo();ho();cu();er();uu();on=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||Kh(),this.options=e,this.eventBus=new go,this.registerEventHandlers()}registerEventHandlers(){this.eventBus.on(X.NAVIGATE_TO_URL,async e=>{await this.handleNavigateToUrl(e)}),this.eventBus.on(X.CLICK_ELEMENT,async e=>{await this.handleClickElement(e)}),this.eventBus.on(X.TYPE_TEXT,async e=>{await this.handleTypeText(e)}),this.eventBus.on(X.SCROLL,async e=>{await this.handleScroll(e)}),this.eventBus.on(X.BROWSER_STATE_REQUEST,async e=>{await this.handleBrowserStateRequest(e)}),this.eventBus.on(X.SCREENSHOT,async e=>{await this.handleScreenshot(e)}),this.eventBus.on(X.GO_BACK,async e=>{await this.handleGoBack(e)}),this.eventBus.on(X.GO_FORWARD,async e=>{await this.handleGoForward(e)}),this.eventBus.on(X.REFRESH,async e=>{await this.handleRefresh(e)}),this.eventBus.on(X.WAIT,async e=>{await this.handleWait(e)}),this.eventBus.on(X.SEND_KEYS,async e=>{await this.handleSendKeys(e)}),this.eventBus.on(X.UPLOAD_FILE,async e=>{await this.handleUploadFile(e)}),this.eventBus.on(X.GET_DROPDOWN_OPTIONS,async e=>{await this.handleGetDropdownOptions(e)}),this.eventBus.on(X.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=au(),r;this.options.useRealChromeProfile?(r=Vh(),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 qh.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 tu(t,Rn(),!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(T=>T.responseEnd===0||T.transferSize===0&&T.decodedBodySize===0&&!T.name.startsWith("data:")).length,y=document.querySelectorAll('a, button, input, select, textarea, [role="button"], [onclick], [tabindex]').length,v=!!(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:v}});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 Xs(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 I=(await c.send("Page.getLayoutMetrics")).layoutViewport||{};l={width:I.clientWidth||n.viewportSize()?.width||1280,height:I.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 C=null,I=[];try{let E=await c.send("DOM.getContentQuads",{backendNodeId:d});E?.quads?.length>0&&(I=E.quads,b.debug(`Got ${I.length} quads from DOM.getContentQuads`))}catch(E){b.debug("getContentQuads failed:",E.message)}if(I.length===0)try{let E=await c.send("DOM.getBoxModel",{backendNodeId:d});if(E?.model?.content){let w=E.model.content;w.length>=8&&(I=[[w[0],w[1],w[2],w[3],w[4],w[5],w[6],w[7]]],b.debug("Got quad from DOM.getBoxModel"))}}catch(E){b.debug("getBoxModel failed:",E.message)}if(I.length===0)try{let w=(await c.send("DOM.resolveNode",{backendNodeId:d}))?.object?.objectId;if(w){let P=(await c.send("Runtime.callFunctionOn",{objectId:w,functionDeclaration:`function() {
474
474
  const rect = this.getBoundingClientRect();
475
475
  return { x: rect.left, y: rect.top, width: rect.width, height: rect.height };
476
476
  }`,returnByValue:!0}))?.result?.value;if(P){let x=P.x,A=P.y,O=P.width,U=P.height;I=[[x,A,x+O,A,x+O,A+U,x,A+U]],b.debug("Got quad from getBoundingClientRect")}}}catch(E){b.debug("JS getBoundingClientRect failed:",E.message)}if(I.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(E){b.debug("JS click for no-quads case failed:",E.message)}}if(I.length>0){let E=null,w=0;for(let x of I){if(x.length<8)continue;let A=[x[0],x[2],x[4],x[6]],O=[x[1],x[3],x[5],x[7]],U=Math.min(...A),D=Math.max(...A),$=Math.min(...O),_=Math.max(...O);if(D<0||_<0||U>l.width||$>l.height)continue;let F=Math.max(0,U),z=Math.min(l.width,D),G=Math.max(0,$),M=Math.min(l.height,_),R=z-F,H=M-G,B=R*H;B>w&&(w=B,E=x)}if(!E){b.debug("🔄 [click] No visible quad found, scrolling element into view first...");try{await c.send("DOM.scrollIntoViewIfNeeded",{backendNodeId:d}),await new Promise(x=>setTimeout(x,100))}catch{}try{let x=await c.send("DOM.getContentQuads",{backendNodeId:d});if(x?.quads?.length>0){I=x.quads;for(let A of I){if(A.length<8)continue;let O=[A[0],A[2],A[4],A[6]],U=[A[1],A[3],A[5],A[7]],D=Math.min(...O),$=Math.max(...O),_=Math.min(...U),F=Math.max(...U);if($<0||F<0||D>l.width||_>l.height)continue;let z=Math.max(0,D),G=Math.min(l.width,$),M=Math.max(0,_),R=Math.min(l.height,F),H=(G-z)*(R-M);H>w&&(w=H,E=A)}}}catch{}if(!E){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=(E[0]+E[2]+E[4]+E[6])/4,P=(E[1]+E[3]+E[5]+E[7])/4;S=Math.max(0,Math.min(l.width-1,S)),P=Math.max(0,Math.min(l.height-1,P)),C={x:S,y:P},b.log(`🖱️ [click] Calculated center: (${S.toFixed(1)}, ${P.toFixed(1)})`)}if(C)try{await c.send("DOM.scrollIntoViewIfNeeded",{backendNodeId:d}),await new Promise(E=>setTimeout(E,50));try{let E=await c.send("DOM.getContentQuads",{backendNodeId:d});if(E?.quads?.length>0){let w=E.quads[0];if(w.length>=8){let S=(w[0]+w[2]+w[4]+w[6])/4,P=(w[1]+w[3]+w[5]+w[7])/4;S>=0&&S<=l.width&&P>=0&&P<=l.height?(C={x:S,y:P},b.debug(`📍 [click] Updated coordinates after scroll: (${S.toFixed(1)}, ${P.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(C){if(await this.checkElementOcclusionCDP(c,d,C.x,C.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:C.x,y:C.y}),await new Promise(S=>setTimeout(S,50));let w=!1;try{await Promise.race([c.send("Input.dispatchMouseEvent",{type:"mousePressed",x:C.x,y:C.y,button:r,clickCount:1}),new Promise((S,P)=>setTimeout(()=>P(new Error("mousePressed timeout")),3e3))]),w=!0}catch(S){b.debug("mousePressed timed out (possibly dialog):",S.message)}w&&await new Promise(S=>setTimeout(S,80));try{await Promise.race([c.send("Input.dispatchMouseEvent",{type:"mouseReleased",x:C.x,y:C.y,button:r,clickCount:1}),new Promise((S,P)=>setTimeout(()=>P(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:C});return}}catch(C){b.debug("CDP click failed, falling back to JavaScript click:",C.message);try{await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_cdp_error"});return}catch(I){b.debug("JS click also failed:",I.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 C=Math.max(0,m-l.height/2);await n.evaluate(E=>window.scrollTo(0,E),C),await new Promise(E=>setTimeout(E,100));let I=await n.evaluate(()=>({x:window.scrollX,y:window.scrollY}));y=m-I.y+(h||0)/2,f=g-I.x+(p||0)/2}catch(C){b.debug("Failed to scroll element into view:",C)}}f=Math.max(1,Math.min(l.width-1,f)),y=Math.max(1,Math.min(l.height-1,y));let T=!1;if(d&&d>0&&(T=await this.checkElementOcclusionCDP(c,d,f,y)),T){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(C=>setTimeout(C,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:`
@@ -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 Xs(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 cu(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 v of Array.from(m)){let T=v,C=(T.innerText?.trim()||"").toLowerCase(),I=(T.getAttribute("data-value")||"").toLowerCase();if(!(!C&&!I)&&(C&&f.push(T.innerText?.trim()||""),!(T.getAttribute("aria-disabled")==="true"||T.hasAttribute("disabled")))){if(C===g||I===g){p=T;break}!h&&(C.includes(g)||I.includes(g))&&(h=T)}}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(X.BROWSER_STATE_REQUEST,{includeScreenshot:e.includeScreenshot??!0,includeDom:e.includeDom??!0,includeRecentEvents:e.includeRecentEvents??!1},se.BROWSER_STATE_REQUEST)}async navigate(e,t={}){return this.eventBus.dispatch(X.NAVIGATE_TO_URL,{url:e,...t},se.NAVIGATE_TO_URL)}async screenshot(e={}){return this.eventBus.dispatch(X.SCREENSHOT,e,se.SCREENSHOT)}async goBack(){return this.eventBus.dispatch(X.GO_BACK,{},se.GO_BACK)}async goForward(){return this.eventBus.dispatch(X.GO_FORWARD,{},se.GO_FORWARD)}async refresh(){return this.eventBus.dispatch(X.REFRESH,{},se.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(X.CLICK_ELEMENT,{node:e},se.CLICK_ELEMENT)}async typeText(e,t){return this.eventBus.dispatch(X.TYPE_TEXT,{text:e,node:t},se.TYPE_TEXT)}async scroll(e,t,n){return this.eventBus.dispatch(X.SCROLL,{direction:e,amount:t||500},se.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(X.UPLOAD_FILE,{node:n,filePath:t},se.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(X.GET_DROPDOWN_OPTIONS,{node:t},se.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(X.SELECT_DROPDOWN_OPTION,{node:n,text:t},se.SELECT_DROPDOWN_OPTION||8e3)}async sendKeys(e){return this.eventBus.dispatch(X.SEND_KEYS,{keys:e.join("")},se.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 v=f.frame||{},T=v.id;if(T){let C=v.parentId||y,I={...v,frameTargetId:d,parentFrameId:C,childFrameIds:[],isCrossOrigin:l.type==="iframe"},E=v.crossOriginIsolatedContextType;E&&E!=="NotIsolated"&&(I.isCrossOrigin=!0);let w=f.childFrames||[];for(let S of w){let P=S.frame||{};P.id&&I.childFrameIds.push(P.id)}if(t.has(T)){let S=t.get(T);l.type==="iframe"&&(S.frameTargetId=d,S.isCrossOrigin=!0)}else t.set(T,I);for(let S of w)h(S,T)}};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 Xs(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 lu(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 v of Array.from(m)){let T=v,C=(T.innerText?.trim()||"").toLowerCase(),I=(T.getAttribute("data-value")||"").toLowerCase();if(!(!C&&!I)&&(C&&f.push(T.innerText?.trim()||""),!(T.getAttribute("aria-disabled")==="true"||T.hasAttribute("disabled")))){if(C===g||I===g){p=T;break}!h&&(C.includes(g)||I.includes(g))&&(h=T)}}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(X.BROWSER_STATE_REQUEST,{includeScreenshot:e.includeScreenshot??!0,includeDom:e.includeDom??!0,includeRecentEvents:e.includeRecentEvents??!1},se.BROWSER_STATE_REQUEST)}async navigate(e,t={}){return this.eventBus.dispatch(X.NAVIGATE_TO_URL,{url:e,...t},se.NAVIGATE_TO_URL)}async screenshot(e={}){return this.eventBus.dispatch(X.SCREENSHOT,e,se.SCREENSHOT)}async goBack(){return this.eventBus.dispatch(X.GO_BACK,{},se.GO_BACK)}async goForward(){return this.eventBus.dispatch(X.GO_FORWARD,{},se.GO_FORWARD)}async refresh(){return this.eventBus.dispatch(X.REFRESH,{},se.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(X.CLICK_ELEMENT,{node:e},se.CLICK_ELEMENT)}async typeText(e,t){return this.eventBus.dispatch(X.TYPE_TEXT,{text:e,node:t},se.TYPE_TEXT)}async scroll(e,t,n){return this.eventBus.dispatch(X.SCROLL,{direction:e,amount:t||500},se.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(X.UPLOAD_FILE,{node:n,filePath:t},se.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(X.GET_DROPDOWN_OPTIONS,{node:t},se.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(X.SELECT_DROPDOWN_OPTION,{node:n,text:t},se.SELECT_DROPDOWN_OPTION||8e3)}async sendKeys(e){return this.eventBus.dispatch(X.SEND_KEYS,{keys:e.join("")},se.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 v=f.frame||{},T=v.id;if(T){let C=v.parentId||y,I={...v,frameTargetId:d,parentFrameId:C,childFrameIds:[],isCrossOrigin:l.type==="iframe"},E=v.crossOriginIsolatedContextType;E&&E!=="NotIsolated"&&(I.isCrossOrigin=!0);let w=f.childFrames||[];for(let S of w){let P=S.frame||{};P.id&&I.childFrameIds.push(P.id)}if(t.has(T)){let S=t.get(T);l.type==="iframe"&&(S.frameTargetId=d,S.isCrossOrigin=!0)}else t.set(T,I);for(let S of w)h(S,T)}};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;
@@ -636,13 +636,13 @@ ${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 ra}from"zod";var bo,uu=L(()=>{"use strict";bo=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=ra.object({[r.name]:r.paramSchema}).describe(r.description);s.push(o)}return s.length===0?ra.object({}):s.length===1?s[0]:ra.union(s)}}});import{z as W}from"zod";async function gs(i,e){return i.pageId?i.browserSession.getElementByIndexForPage(i.pageId,e):i.browserSession.getElementByIndex(e)}async function gu(i){return i.pageId?i.browserSession.getSelectorMapForPage(i.pageId):await i.browserSession.getSelectorMap()}function Kh(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 du(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 bf(i,e){try{return await e.browserSession.eventBus.dispatch(X.NAVIGATE_TO_URL,{...i,pageId:e.pageId},se.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 yf(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 gs(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 gu(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(X.CLICK_ELEMENT,{node:t,button:i.button,pageId:e.pageId},se.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 mu({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 vf(i,e){try{let t=await gs(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=Kh(i.text,s)),await e.browserSession.eventBus.dispatch(X.TYPE_TEXT,{node:t,text:i.text,clear:i.clear,isSensitive:n,sensitiveKeyName:r,pageId:e.pageId},se.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 Sf(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 gs(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(X.SCROLL,{direction:n,amount:m,node:s,pageId:e.pageId},se.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(X.SCROLL,{direction:n,amount:g,node:s,pageId:e.pageId},se.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(X.SCROLL,{direction:n,amount:a,node:s,pageId:e.pageId},se.SCROLL),{longTermMemory:`Scrolled ${n} ${r} ${t} pages`.replace(" "," ")}}}catch(t){return{error:`Failed to scroll: ${t.message}`}}}async function wf(i,e){try{return await e.browserSession.eventBus.dispatch(X.GO_BACK,{pageId:e.pageId},se.GO_BACK),{longTermMemory:"Navigated back"}}catch(t){return{error:`Failed to go back: ${t.message}`}}}async function Tf(i,e){try{return await e.browserSession.eventBus.dispatch(X.GO_FORWARD,{pageId:e.pageId},se.GO_FORWARD),{longTermMemory:"Navigated forward"}}catch(t){return{error:`Failed to go forward: ${t.message}`}}}async function xf(i,e){try{return await e.browserSession.eventBus.dispatch(X.REFRESH,{pageId:e.pageId},se.REFRESH),{longTermMemory:"Refreshed page"}}catch(t){return{error:`Failed to refresh: ${t.message}`}}}async function Cf(i,e){try{return await e.browserSession.eventBus.dispatch(X.WAIT,{seconds:i.seconds,pageId:e.pageId},se.WAIT),{longTermMemory:`Waited ${i.seconds} seconds`}}catch(t){return{error:`Failed to wait: ${t.message}`}}}async function Ef(i,e){try{return await e.browserSession.eventBus.dispatch(X.SEND_KEYS,{...i,pageId:e.pageId},se.SEND_KEYS),{longTermMemory:`Sent keys: ${i.keys}`}}catch(t){return{error:`Failed to send keys: ${t.message}`}}}async function If(i,e){try{let t=await e.browserSession.eventBus.dispatch(X.SCREENSHOT,{...i,pageId:e.pageId},se.SCREENSHOT);return{extractedContent:`Screenshot captured (${t.length} bytes)`,metadata:{screenshot:t}}}catch(t){return{error:`Failed to take screenshot: ${t.message}`}}}async function kf(i,e){return{isDone:!0,success:i.success??!0,extractedContent:i.text,attachments:i.files_to_display||[]}}async function Pf(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(X.NAVIGATE_TO_URL,{url:r,newTab:!1,pageId:e.pageId},se.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 Af(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(X.SWITCH_TAB,{targetId:n.targetId},se.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 Df(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(X.CLOSE_TAB,{targetId:n.targetId},se.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 Mf(i,e){try{await e.browserSession.eventBus.dispatch(X.SCROLL_TO_TEXT,{text:i.text,pageId:e.pageId},se.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 mu(i,e){try{let t=await gs(e,i.index);if(!t)return{error:`Element with index ${i.index} not found`};let n=await e.browserSession.eventBus.dispatch(X.GET_DROPDOWN_OPTIONS,{node:t,pageId:e.pageId},se.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 Rf(i,e){try{let t=await gs(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(X.SELECT_DROPDOWN_OPTION,{node:t,text:i.text,pageId:e.pageId},se.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 Nf(i,e){try{let t=await gs(e,i.index),n=await gu(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 v=y.childrenNodes||y.children||[];for(let T of v)if(s(T))return T}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(X.UPLOAD_FILE,{node:a,filePath:i.path,pageId:e.pageId},se.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 Of(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to execute JavaScript"};let n=du(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 ra}from"zod";var bo,du=L(()=>{"use strict";bo=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=ra.object({[r.name]:r.paramSchema}).describe(r.description);s.push(o)}return s.length===0?ra.object({}):s.length===1?s[0]:ra.union(s)}}});import{z as W}from"zod";async function gs(i,e){return i.pageId?i.browserSession.getElementByIndexForPage(i.pageId,e):i.browserSession.getElementByIndex(e)}async function mu(i){return i.pageId?i.browserSession.getSelectorMapForPage(i.pageId):await i.browserSession.getSelectorMap()}function Xh(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 gu(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 vf(i,e){try{return await e.browserSession.eventBus.dispatch(X.NAVIGATE_TO_URL,{...i,pageId:e.pageId},se.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 Sf(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 gs(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 mu(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(X.CLICK_ELEMENT,{node:t,button:i.button,pageId:e.pageId},se.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 pu({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 wf(i,e){try{let t=await gs(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=Xh(i.text,s)),await e.browserSession.eventBus.dispatch(X.TYPE_TEXT,{node:t,text:i.text,clear:i.clear,isSensitive:n,sensitiveKeyName:r,pageId:e.pageId},se.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 Tf(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 gs(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(X.SCROLL,{direction:n,amount:m,node:s,pageId:e.pageId},se.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(X.SCROLL,{direction:n,amount:g,node:s,pageId:e.pageId},se.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(X.SCROLL,{direction:n,amount:a,node:s,pageId:e.pageId},se.SCROLL),{longTermMemory:`Scrolled ${n} ${r} ${t} pages`.replace(" "," ")}}}catch(t){return{error:`Failed to scroll: ${t.message}`}}}async function xf(i,e){try{return await e.browserSession.eventBus.dispatch(X.GO_BACK,{pageId:e.pageId},se.GO_BACK),{longTermMemory:"Navigated back"}}catch(t){return{error:`Failed to go back: ${t.message}`}}}async function Cf(i,e){try{return await e.browserSession.eventBus.dispatch(X.GO_FORWARD,{pageId:e.pageId},se.GO_FORWARD),{longTermMemory:"Navigated forward"}}catch(t){return{error:`Failed to go forward: ${t.message}`}}}async function Ef(i,e){try{return await e.browserSession.eventBus.dispatch(X.REFRESH,{pageId:e.pageId},se.REFRESH),{longTermMemory:"Refreshed page"}}catch(t){return{error:`Failed to refresh: ${t.message}`}}}async function If(i,e){try{return await e.browserSession.eventBus.dispatch(X.WAIT,{seconds:i.seconds,pageId:e.pageId},se.WAIT),{longTermMemory:`Waited ${i.seconds} seconds`}}catch(t){return{error:`Failed to wait: ${t.message}`}}}async function kf(i,e){try{return await e.browserSession.eventBus.dispatch(X.SEND_KEYS,{...i,pageId:e.pageId},se.SEND_KEYS),{longTermMemory:`Sent keys: ${i.keys}`}}catch(t){return{error:`Failed to send keys: ${t.message}`}}}async function Pf(i,e){try{let t=await e.browserSession.eventBus.dispatch(X.SCREENSHOT,{...i,pageId:e.pageId},se.SCREENSHOT);return{extractedContent:`Screenshot captured (${t.length} bytes)`,metadata:{screenshot:t}}}catch(t){return{error:`Failed to take screenshot: ${t.message}`}}}async function Af(i,e){return{isDone:!0,success:i.success??!0,extractedContent:i.text,attachments:i.files_to_display||[]}}async function Df(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(X.NAVIGATE_TO_URL,{url:r,newTab:!1,pageId:e.pageId},se.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 Mf(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(X.SWITCH_TAB,{targetId:n.targetId},se.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 Rf(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(X.CLOSE_TAB,{targetId:n.targetId},se.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 Nf(i,e){try{await e.browserSession.eventBus.dispatch(X.SCROLL_TO_TEXT,{text:i.text,pageId:e.pageId},se.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 pu(i,e){try{let t=await gs(e,i.index);if(!t)return{error:`Element with index ${i.index} not found`};let n=await e.browserSession.eventBus.dispatch(X.GET_DROPDOWN_OPTIONS,{node:t,pageId:e.pageId},se.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 Of(i,e){try{let t=await gs(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(X.SELECT_DROPDOWN_OPTION,{node:t,text:i.text,pageId:e.pageId},se.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 _f(i,e){try{let t=await gs(e,i.index),n=await mu(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 v=y.childrenNodes||y.children||[];for(let T of v)if(s(T))return T}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(X.UPLOAD_FILE,{node:a,filePath:i.path,pageId:e.pageId},se.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 $f(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to execute JavaScript"};let n=gu(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
- ${du(i.code).substring(0,500)}${i.code.length>500?"...":""}`}}}async function _f(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(v=>{function T(w,S=0){if(S>20)return"";let P=w.tagName?.toLowerCase();if(["script","style","noscript","svg","path","iframe"].includes(P))return"";try{let A=window.getComputedStyle(w);if(A.display==="none"||A.visibility==="hidden")return""}catch{}let x="";if(["h1","h2","h3","h4","h5","h6"].includes(P)){let A=parseInt(P[1]),O="#".repeat(A)+" ";return x+=`
645
+ ${gu(i.code).substring(0,500)}${i.code.length>500?"...":""}`}}}async function Ff(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(v=>{function T(w,S=0){if(S>20)return"";let P=w.tagName?.toLowerCase();if(["script","style","noscript","svg","path","iframe"].includes(P))return"";try{let A=window.getComputedStyle(w);if(A.display==="none"||A.visibility==="hidden")return""}catch{}let x="";if(["h1","h2","h3","h4","h5","h6"].includes(P)){let A=parseInt(P[1]),O="#".repeat(A)+" ";return x+=`
646
646
  `+O+w.innerText.trim()+`
647
647
  `,x}if(P==="p"){let A=w.innerText.trim();return A&&(x+=`
648
648
  `+A+`
@@ -686,22 +686,22 @@ ${y}
686
686
  </result>`,T,C=!1;if(v.length<1e3)T=v;else if(e.fileSystem)try{let I=await e.fileSystem.saveExtractedContent(v);T=`Query: ${i.query}
687
687
  Content saved to ${I}`,C=!0}catch{T=`Query: ${i.query}
688
688
  Extracted ${y.length} chars (see extracted_content)`,C=!0}else T=`Query: ${i.query}
689
- Extracted ${y.length} chars`,C=!0;return{extractedContent:v,longTermMemory:T,includeExtractedContentOnlyOnce:C}}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 $f(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(`
689
+ Extracted ${y.length} chars`,C=!0;return{extractedContent:v,longTermMemory:T,includeExtractedContentOnlyOnce:C}}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 Lf(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
- `+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 Ff(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(`
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 Uf(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:v,contextChars:T,cssScope:C,maxResults:I})=>{function E(w){let S=[],P=w;for(;P&&P!==document.body&&P!==document.documentElement;){let x=P.tagName?P.tagName.toLowerCase():"";if(!x)break;if(P.id)x+="#"+P.id;else if(P.className&&typeof P.className=="string"){let A=P.className.trim().split(/\s+/).slice(0,2).join(".");A&&(x+="."+A)}S.unshift(x),P=P.parentElement}return S.join(" > ")}try{let w=C?document.querySelector(C):document.body;if(!w)return{error:"CSS scope selector not found: "+C,matches:[],total:0};let S=document.createTreeWalker(w,NodeFilter.SHOW_TEXT),P="",x=[];for(;S.nextNode();){let $=S.currentNode,_=$.textContent;_&&_.trim()&&(x.push({offset:P.length,length:_.length,node:$}),P+=_)}let A;try{let $=v?"g":"gi";y?A=new RegExp(f,$):A=new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),$)}catch($){return{error:"Invalid regex pattern: "+$.message,matches:[],total:0}}let O=[],U,D=0;for(;(U=A.exec(P))!==null;){if(D++,O.length<I){let $=Math.max(0,U.index-T),_=Math.min(P.length,U.index+U[0].length+T),F=P.slice($,_),z="";for(let G=0;G<x.length;G++){let M=x[G];if(M.offset<=U.index&&M.offset+M.length>U.index){z=E(M.node.parentElement);break}}O.push({match_text:U[0],context:($>0?"...":"")+F+(_<P.length?"...":""),element_path:z,char_position:U.index})}U[0].length===0&&A.lastIndex++}return{matches:O,total:D,has_more:D>I}}catch(w){return{error:"search_page error: "+w.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],v=y.element_path?` (in ${y.element_path})`:"";p.push(`[${f+1}] ${y.context}${v}`)}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 Bf(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 Wf(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:v,contextChars:T,cssScope:C,maxResults:I})=>{function E(w){let S=[],P=w;for(;P&&P!==document.body&&P!==document.documentElement;){let x=P.tagName?P.tagName.toLowerCase():"";if(!x)break;if(P.id)x+="#"+P.id;else if(P.className&&typeof P.className=="string"){let A=P.className.trim().split(/\s+/).slice(0,2).join(".");A&&(x+="."+A)}S.unshift(x),P=P.parentElement}return S.join(" > ")}try{let w=C?document.querySelector(C):document.body;if(!w)return{error:"CSS scope selector not found: "+C,matches:[],total:0};let S=document.createTreeWalker(w,NodeFilter.SHOW_TEXT),P="",x=[];for(;S.nextNode();){let $=S.currentNode,_=$.textContent;_&&_.trim()&&(x.push({offset:P.length,length:_.length,node:$}),P+=_)}let A;try{let $=v?"g":"gi";y?A=new RegExp(f,$):A=new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),$)}catch($){return{error:"Invalid regex pattern: "+$.message,matches:[],total:0}}let O=[],U,D=0;for(;(U=A.exec(P))!==null;){if(D++,O.length<I){let $=Math.max(0,U.index-T),_=Math.min(P.length,U.index+U[0].length+T),F=P.slice($,_),z="";for(let G=0;G<x.length;G++){let M=x[G];if(M.offset<=U.index&&M.offset+M.length>U.index){z=E(M.node.parentElement);break}}O.push({match_text:U[0],context:($>0?"...":"")+F+(_<P.length?"...":""),element_path:z,char_position:U.index})}U[0].length===0&&A.lastIndex++}return{matches:O,total:D,has_more:D>I}}catch(w){return{error:"search_page error: "+w.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],v=y.element_path?` (in ${y.element_path})`:"";p.push(`[${f+1}] ${y.context}${v}`)}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 Bf(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:v})=>{try{let T;try{T=document.querySelectorAll(h)}catch(w){return{error:"Invalid CSS selector: "+w.message,elements:[],total:0}}let C=T.length,I=Math.min(C,y),E=[];for(let w=0;w<I;w++){let S=T[w],P={index:w,tag:S.tagName.toLowerCase(),children_count:S.children.length};if(v){let x=(S.textContent||"").trim();P.text=x.length>300?x.slice(0,300)+"...":x}if(f&&f.length>0){P.attrs={};for(let x=0;x<f.length;x++){let A=S.getAttribute(f[x]);A!==null&&(P.attrs[f[x]]=A.length>500?A.slice(0,500)+"...":A)}}E.push(P)}return{elements:E,total:C,showing:I}}catch(T){return{error:"find_elements error: "+T.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(([v,T])=>`${v}="${T}"`);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 Hf(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:v})=>{try{let T;try{T=document.querySelectorAll(h)}catch(w){return{error:"Invalid CSS selector: "+w.message,elements:[],total:0}}let C=T.length,I=Math.min(C,y),E=[];for(let w=0;w<I;w++){let S=T[w],P={index:w,tag:S.tagName.toLowerCase(),children_count:S.children.length};if(v){let x=(S.textContent||"").trim();P.text=x.length>300?x.slice(0,300)+"...":x}if(f&&f.length>0){P.attrs={};for(let x=0;x<f.length;x++){let A=S.getAttribute(f[x]);A!==null&&(P.attrs[f[x]]=A.length>500?A.slice(0,500)+"...":A)}}E.push(P)}return{elements:E,total:C,showing:I}}catch(T){return{error:"find_elements error: "+T.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(([v,T])=>`${v}="${T}"`);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 pu(i){i.register({name:"navigate",description:"Navigate to a URL",function:bf,paramSchema:Vh}),i.register({name:"click",description:"Click an element by index",function:yf,paramSchema:Xh}),i.register({name:"input",description:"Type text into an element",function:vf,paramSchema:Yh}),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:Sf,paramSchema:Qh}),i.register({name:"go_back",description:"Navigate back in browser history",function:wf,paramSchema:W.object({})}),i.register({name:"go_forward",description:"Navigate forward in browser history",function:Tf,paramSchema:W.object({})}),i.register({name:"refresh",description:"Refresh the current page",function:xf,paramSchema:W.object({})}),i.register({name:"wait",description:"Wait for a specified number of seconds",function:Cf,paramSchema:Zh}),i.register({name:"send_keys",description:"Send keyboard keys or shortcuts",function:Ef,paramSchema:ef}),i.register({name:"screenshot",description:"Take a screenshot of the current page",function:If,paramSchema:tf}),i.register({name:"done",description:"Mark the task as complete",function:kf,paramSchema:Jh}),i.register({name:"search",description:"Search the web using Google, Bing, or DuckDuckGo",function:Pf,paramSchema:nf}),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:Af,paramSchema:sf}),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:Df,paramSchema:rf}),i.register({name:"find_text",description:"Find and scroll to specific text on the page",function:Mf,paramSchema:of}),i.register({name:"dropdown_options",description:"Get all options from a native dropdown or ARIA menu",function:mu,paramSchema:af}),i.register({name:"select_dropdown",description:"Select a dropdown option by the text of the option you want to select",function:Rf,paramSchema:cf}),i.register({name:"upload_file",description:"Upload a file to a file input element",function:Nf,paramSchema:lf}),i.register({name:"evaluate",description:"Execute JavaScript code in the browser context. Use for hover, drag, zoom, custom selectors, or analyzing page structure.",function:Of,paramSchema:uf}),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:_f,paramSchema:df}),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:$f,paramSchema:gf}),i.register({name:"read_file",description:"Read content from a file in the agent's file system or from available_file_paths.",function:Ff,paramSchema:mf}),i.register({name:"replace_file",description:"Replace all occurrences of a string in a file with another string.",function:Lf,paramSchema:pf}),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:hf}),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:Bf,paramSchema:ff})}var Vh,Xh,Yh,Qh,Jh,Zh,ef,tf,nf,sf,rf,of,af,cf,lf,uf,df,gf,mf,pf,hf,ff,hu=L(()=>{"use strict";bt();Zi();Ji();Vh=W.object({url:W.string().describe("The URL to navigate to"),new_tab:W.boolean().optional().default(!1).describe("Open in a new tab")}),Xh=W.object({index:W.number().min(1).describe("The element index to click (must be >= 1)"),button:W.enum(["left","right","middle"]).optional().describe("Mouse button to use")}),Yh=W.object({index:W.number().min(0).describe("The element index to type into (>= 0)"),text:W.string().describe("The text to type"),clear:W.boolean().optional().default(!0).describe("Clear existing text first")}),Qh=W.object({down:W.boolean().describe("Scroll direction: true=down, false=up"),pages:W.number().optional().default(1).describe("Pages to scroll (0.5=half, 1=full, 10=to bottom/top)"),index:W.number().optional().describe("Optional element index for scrollable container")}),Jh=W.object({text:W.string().describe("Summary of what was accomplished"),success:W.boolean().optional().default(!0).describe("Whether the task was successful"),files_to_display:W.array(W.string()).optional().default([]).describe("File paths to include")}),Zh=W.object({seconds:W.number().describe("Number of seconds to wait")}),ef=W.object({keys:W.string().describe('Keys to send (e.g., "Enter", "Control+A")')}),tf=W.object({full_page:W.boolean().optional().describe("Capture full page")}),nf=W.object({query:W.string().describe("The search query"),engine:W.enum(["google","bing","duckduckgo"]).optional().default("duckduckgo").describe("Search engine to use")}),sf=W.object({tab_id:W.string().length(4).describe("The tab ID to switch to (exactly 4 chars from target_id)")}),rf=W.object({tab_id:W.string().length(4).describe("The tab ID to close (exactly 4 chars from target_id)")}),of=W.object({text:W.string().describe("The text to find and scroll to")}),af=W.object({index:W.number().describe("The element index of the dropdown/select")}),cf=W.object({index:W.number().describe("The element index of the dropdown/select"),text:W.string().describe("The text of the option to select")}),lf=W.object({index:W.number().describe("The element index of the file input"),path:W.string().describe("The path of the file to upload")}),uf=W.object({code:W.string().describe("JavaScript code to execute in the browser context")}),df=W.object({query:W.string().describe("What information to extract from the page"),extract_links:W.boolean().optional().default(!1).describe("Whether to include URLs in extraction"),start_from_char:W.number().optional().default(0).describe("Character offset to start from (for pagination)")}),gf=W.object({file_name:W.string().describe("The filename with extension (e.g., notes.md, data.json)"),content:W.string().describe("The content to write to the file"),append:W.boolean().optional().default(!1).describe("Append to existing file instead of overwriting"),trailing_newline:W.boolean().optional().default(!0).describe("Add trailing newline"),leading_newline:W.boolean().optional().default(!1).describe("Add leading newline")}),mf=W.object({file_name:W.string().describe("The filename to read")}),pf=W.object({file_name:W.string().describe("The filename to modify"),old_str:W.string().describe("The string to find and replace"),new_str:W.string().describe("The replacement string")}),hf=W.object({pattern:W.string().describe("Text or regex pattern to search for in page content"),regex:W.boolean().optional().default(!1).describe("Treat pattern as regex (default: literal text match)"),case_sensitive:W.boolean().optional().default(!1).describe("Case-sensitive search (default: case-insensitive)"),context_chars:W.number().optional().default(150).describe("Characters of surrounding context per match"),css_scope:W.string().optional().describe('CSS selector to limit search scope (e.g. "div#main")'),max_results:W.number().optional().default(25).describe("Maximum matches to return")}),ff=W.object({selector:W.string().describe('CSS selector to query elements (e.g. "table tr", "a.link", "div.product")'),attributes:W.array(W.string()).optional().describe('Specific attributes to extract (e.g. ["href", "src", "class"])'),max_results:W.number().optional().default(50).describe("Maximum elements to return"),include_text:W.boolean().optional().default(!0).describe("Include text content of each element")})});import{z as Me}from"zod";import{v4 as Wf}from"uuid";function oa(i){return i.stepNumber>=i.maxSteps-1}function bu(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(su(r))}else t.push(null)}return t}function yu(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 fu,Hf,aP,cP,lP,ia=L(()=>{"use strict";ho();fu={useVision:"auto",visionDetailLevel:"auto",saveConversationPath:null,saveConversationPathEncoding:"utf-8",maxFailures:3,generateGif:!1,overrideSystemMessage:null,extendSystemMessage:null,includeAttributes:nu,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},Hf={messages:[]},aP={agentId:Wf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1,messageManagerState:Hf,fileSystemState:null};cP=Me.object({isDone:Me.boolean().nullable().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. For regular actions that succeed, leave success as None. Use success=False only for actions that fail."}),lP=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)})});var la={};Ue(la,{ActionResultSchema:()=>Zf,AgentOutputSchema:()=>yo,DEFAULT_AGENT_SETTINGS:()=>jf,createAgentHistoryList:()=>ca,createAgentOutputSchema:()=>vo,createAgentState:()=>aa,getAgentBrain:()=>Vf,getDurationSeconds:()=>Kf,getFinalResult:()=>Yf,isLastStep:()=>zf,isSuccessful:()=>Xf,loadHistoryFromFile:()=>Jf,saveHistoryToFile:()=>Qf,validateActionResult:()=>qf});import{v4 as Gf}from"uuid";import{z as be}from"zod";function aa(){return{agentId:Gf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1}}function zf(i){return i.stepNumber>=i.maxSteps-1}function qf(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 Kf(i){return(i.stepEndTime-i.stepStartTime)/1e3}function Vf(i){return{thinking:i.thinking,evaluationPreviousGoal:i.evaluationPreviousGoal||"",memory:i.memory||"",nextGoal:i.nextGoal||""}}function ca(i,e){return{history:[],agentId:i,task:e,createdAt:Date.now(),finalResult:null}}function Xf(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 Yf(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 Qf(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 Jf(i="AgentHistory.json"){let t=await(await import("fs/promises")).readFile(i,"utf-8");return JSON.parse(t)}function vo(i){return be.object({thinking:be.string().nullable().optional(),evaluationPreviousGoal:be.string().nullable().optional(),memory:be.string().nullable().optional(),nextGoal:be.string().nullable().optional(),action:be.array(i).min(1)})}var jf,Zf,yo,So=L(()=>{"use strict";jf={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};Zf=be.object({isDone:be.boolean().optional(),success:be.boolean().nullable().optional(),error:be.string().nullable().optional(),attachments:be.array(be.string()).nullable().optional(),longTermMemory:be.string().nullable().optional(),extractedContent:be.string().nullable().optional(),includeExtractedContentOnlyOnce:be.boolean().optional(),metadata:be.record(be.any()).nullable().optional(),includeInMemory:be.boolean().optional()}).refine(i=>!(i.success===!0&&i.isDone!==!0),{message:"success=true can only be set when isDone=true"}),yo=be.object({thinking:be.string().nullable().optional(),evaluationPreviousGoal:be.string().nullable().optional(),memory:be.string().nullable().optional(),nextGoal:be.string().nullable().optional(),action:be.array(be.any()).min(1)})});function vu(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(`
699
+ `),longTermMemory:`Queried DOM for "${n}" - found ${l} elements`}}catch(t){return{error:`find_elements failed: ${t.message}`}}}function hu(i){i.register({name:"navigate",description:"Navigate to a URL",function:vf,paramSchema:Yh}),i.register({name:"click",description:"Click an element by index",function:Sf,paramSchema:Qh}),i.register({name:"input",description:"Type text into an element",function:wf,paramSchema:Jh}),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:Tf,paramSchema:Zh}),i.register({name:"go_back",description:"Navigate back in browser history",function:xf,paramSchema:W.object({})}),i.register({name:"go_forward",description:"Navigate forward in browser history",function:Cf,paramSchema:W.object({})}),i.register({name:"refresh",description:"Refresh the current page",function:Ef,paramSchema:W.object({})}),i.register({name:"wait",description:"Wait for a specified number of seconds",function:If,paramSchema:tf}),i.register({name:"send_keys",description:"Send keyboard keys or shortcuts",function:kf,paramSchema:nf}),i.register({name:"screenshot",description:"Take a screenshot of the current page",function:Pf,paramSchema:sf}),i.register({name:"done",description:"Mark the task as complete",function:Af,paramSchema:ef}),i.register({name:"search",description:"Search the web using Google, Bing, or DuckDuckGo",function:Df,paramSchema:rf}),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:Mf,paramSchema:of}),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:Rf,paramSchema:af}),i.register({name:"find_text",description:"Find and scroll to specific text on the page",function:Nf,paramSchema:cf}),i.register({name:"dropdown_options",description:"Get all options from a native dropdown or ARIA menu",function:pu,paramSchema:lf}),i.register({name:"select_dropdown",description:"Select a dropdown option by the text of the option you want to select",function:Of,paramSchema:uf}),i.register({name:"upload_file",description:"Upload a file to a file input element",function:_f,paramSchema:df}),i.register({name:"evaluate",description:"Execute JavaScript code in the browser context. Use for hover, drag, zoom, custom selectors, or analyzing page structure.",function:$f,paramSchema:gf}),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:Ff,paramSchema:mf}),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:Lf,paramSchema:pf}),i.register({name:"read_file",description:"Read content from a file in the agent's file system or from available_file_paths.",function:Uf,paramSchema:hf}),i.register({name:"replace_file",description:"Replace all occurrences of a string in a file with another string.",function:Bf,paramSchema:ff}),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:Wf,paramSchema:bf}),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:Hf,paramSchema:yf})}var Yh,Qh,Jh,Zh,ef,tf,nf,sf,rf,of,af,cf,lf,uf,df,gf,mf,pf,hf,ff,bf,yf,fu=L(()=>{"use strict";bt();Zi();Ji();Yh=W.object({url:W.string().describe("The URL to navigate to"),new_tab:W.boolean().optional().default(!1).describe("Open in a new tab")}),Qh=W.object({index:W.number().min(1).describe("The element index to click (must be >= 1)"),button:W.enum(["left","right","middle"]).optional().describe("Mouse button to use")}),Jh=W.object({index:W.number().min(0).describe("The element index to type into (>= 0)"),text:W.string().describe("The text to type"),clear:W.boolean().optional().default(!0).describe("Clear existing text first")}),Zh=W.object({down:W.boolean().describe("Scroll direction: true=down, false=up"),pages:W.number().optional().default(1).describe("Pages to scroll (0.5=half, 1=full, 10=to bottom/top)"),index:W.number().optional().describe("Optional element index for scrollable container")}),ef=W.object({text:W.string().describe("Summary of what was accomplished"),success:W.boolean().optional().default(!0).describe("Whether the task was successful"),files_to_display:W.array(W.string()).optional().default([]).describe("File paths to include")}),tf=W.object({seconds:W.number().describe("Number of seconds to wait")}),nf=W.object({keys:W.string().describe('Keys to send (e.g., "Enter", "Control+A")')}),sf=W.object({full_page:W.boolean().optional().describe("Capture full page")}),rf=W.object({query:W.string().describe("The search query"),engine:W.enum(["google","bing","duckduckgo"]).optional().default("duckduckgo").describe("Search engine to use")}),of=W.object({tab_id:W.string().length(4).describe("The tab ID to switch to (exactly 4 chars from target_id)")}),af=W.object({tab_id:W.string().length(4).describe("The tab ID to close (exactly 4 chars from target_id)")}),cf=W.object({text:W.string().describe("The text to find and scroll to")}),lf=W.object({index:W.number().describe("The element index of the dropdown/select")}),uf=W.object({index:W.number().describe("The element index of the dropdown/select"),text:W.string().describe("The text of the option to select")}),df=W.object({index:W.number().describe("The element index of the file input"),path:W.string().describe("The path of the file to upload")}),gf=W.object({code:W.string().describe("JavaScript code to execute in the browser context")}),mf=W.object({query:W.string().describe("What information to extract from the page"),extract_links:W.boolean().optional().default(!1).describe("Whether to include URLs in extraction"),start_from_char:W.number().optional().default(0).describe("Character offset to start from (for pagination)")}),pf=W.object({file_name:W.string().describe("The filename with extension (e.g., notes.md, data.json)"),content:W.string().describe("The content to write to the file"),append:W.boolean().optional().default(!1).describe("Append to existing file instead of overwriting"),trailing_newline:W.boolean().optional().default(!0).describe("Add trailing newline"),leading_newline:W.boolean().optional().default(!1).describe("Add leading newline")}),hf=W.object({file_name:W.string().describe("The filename to read")}),ff=W.object({file_name:W.string().describe("The filename to modify"),old_str:W.string().describe("The string to find and replace"),new_str:W.string().describe("The replacement string")}),bf=W.object({pattern:W.string().describe("Text or regex pattern to search for in page content"),regex:W.boolean().optional().default(!1).describe("Treat pattern as regex (default: literal text match)"),case_sensitive:W.boolean().optional().default(!1).describe("Case-sensitive search (default: case-insensitive)"),context_chars:W.number().optional().default(150).describe("Characters of surrounding context per match"),css_scope:W.string().optional().describe('CSS selector to limit search scope (e.g. "div#main")'),max_results:W.number().optional().default(25).describe("Maximum matches to return")}),yf=W.object({selector:W.string().describe('CSS selector to query elements (e.g. "table tr", "a.link", "div.product")'),attributes:W.array(W.string()).optional().describe('Specific attributes to extract (e.g. ["href", "src", "class"])'),max_results:W.number().optional().default(50).describe("Maximum elements to return"),include_text:W.boolean().optional().default(!0).describe("Include text content of each element")})});import{z as Me}from"zod";import{v4 as Gf}from"uuid";function oa(i){return i.stepNumber>=i.maxSteps-1}function yu(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(ru(r))}else t.push(null)}return t}function vu(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 bu,jf,lP,uP,dP,ia=L(()=>{"use strict";ho();bu={useVision:"auto",visionDetailLevel:"auto",saveConversationPath:null,saveConversationPathEncoding:"utf-8",maxFailures:3,generateGif:!1,overrideSystemMessage:null,extendSystemMessage:null,includeAttributes:su,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},jf={messages:[]},lP={agentId:Gf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1,messageManagerState:jf,fileSystemState:null};uP=Me.object({isDone:Me.boolean().nullable().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. For regular actions that succeed, leave success as None. Use success=False only for actions that fail."}),dP=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)})});var la={};Ue(la,{ActionResultSchema:()=>tb,AgentOutputSchema:()=>yo,DEFAULT_AGENT_SETTINGS:()=>qf,createAgentHistoryList:()=>ca,createAgentOutputSchema:()=>vo,createAgentState:()=>aa,getAgentBrain:()=>Yf,getDurationSeconds:()=>Xf,getFinalResult:()=>Jf,isLastStep:()=>Kf,isSuccessful:()=>Qf,loadHistoryFromFile:()=>eb,saveHistoryToFile:()=>Zf,validateActionResult:()=>Vf});import{v4 as zf}from"uuid";import{z as be}from"zod";function aa(){return{agentId:zf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1}}function Kf(i){return i.stepNumber>=i.maxSteps-1}function Vf(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 Xf(i){return(i.stepEndTime-i.stepStartTime)/1e3}function Yf(i){return{thinking:i.thinking,evaluationPreviousGoal:i.evaluationPreviousGoal||"",memory:i.memory||"",nextGoal:i.nextGoal||""}}function ca(i,e){return{history:[],agentId:i,task:e,createdAt:Date.now(),finalResult:null}}function Qf(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 Jf(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 Zf(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 eb(i="AgentHistory.json"){let t=await(await import("fs/promises")).readFile(i,"utf-8");return JSON.parse(t)}function vo(i){return be.object({thinking:be.string().nullable().optional(),evaluationPreviousGoal:be.string().nullable().optional(),memory:be.string().nullable().optional(),nextGoal:be.string().nullable().optional(),action:be.array(i).min(1)})}var qf,tb,yo,So=L(()=>{"use strict";qf={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};tb=be.object({isDone:be.boolean().optional(),success:be.boolean().nullable().optional(),error:be.string().nullable().optional(),attachments:be.array(be.string()).nullable().optional(),longTermMemory:be.string().nullable().optional(),extractedContent:be.string().nullable().optional(),includeExtractedContentOnlyOnce:be.boolean().optional(),metadata:be.record(be.any()).nullable().optional(),includeInMemory:be.boolean().optional()}).refine(i=>!(i.success===!0&&i.isDone!==!0),{message:"success=true can only be set when isDone=true"}),yo=be.object({thinking:be.string().nullable().optional(),evaluationPreviousGoal:be.string().nullable().optional(),memory:be.string().nullable().optional(),nextGoal:be.string().nullable().optional(),action:be.array(be.any()).min(1)})});function Su(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
700
  `):"":""}function _n(i,e){return{role:"user",content:i,name:e}}function ua(i,e){return{role:"system",content:i,name:e}}var da=L(()=>{"use strict"});import{z as Be}from"zod";function tr(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 ga(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 eb,tb,hP,wu=L(()=>{"use strict";eb=Be.object({stepNumber:Be.number().nullable().optional(),evaluationPreviousGoal:Be.string().nullable().optional(),memory:Be.string().nullable().optional(),nextGoal:Be.string().nullable().optional(),actionResults:Be.string().nullable().optional(),error:Be.string().nullable().optional(),systemMessage:Be.string().nullable().optional()}).refine(i=>!(i.error&&i.systemMessage),{message:"Cannot have both error and systemMessage at the same time"});tb=Be.object({systemMessage:Be.any().nullable().optional(),stateMessage:Be.any().nullable().optional(),contextMessages:Be.array(Be.any()).default([])});hP=Be.object({history:tb,toolId:Be.number().default(1),agentHistoryItems:Be.array(eb).default([{stepNumber:0,systemMessage:"Agent initialized"}]),readStateDescription:Be.string().default("")})});import{minimatch as ma}from"minimatch";function pa(i){return["about:blank","chrome://new-tab-page/","chrome://new-tab-page","chrome://newtab/","chrome://newtab"].includes(i)}function Tu(i,e,t=!1){try{if(pa(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)),!ma(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||ma(r,g))return!0}if(ma(r,a))return!0}return!1}catch(n){return console.error(`⛔️ Error matching URL ${i} with pattern ${e}: ${n?.name}: ${n?.message}`),!1}}var ha=L(()=>{"use strict";bt()});import xu from"fs";import Cu from"path";import{fileURLToPath as nb}from"url";var wo,To,fa=L(()=>{"use strict";ho();ha();wo=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
- ${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=nb(t),s=Cu.dirname(n),r=Cu.join(s,e);xu.existsSync(r)?this.promptTemplate=xu.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.
703
+ ${n}`}}function ga(i){let e=[];return i.systemMessage&&e.push(i.systemMessage),i.stateMessage&&e.push(i.stateMessage),e.push(...i.contextMessages),e}function wu(){return{history:{systemMessage:null,stateMessage:null,contextMessages:[]},toolId:1,agentHistoryItems:[{stepNumber:0,systemMessage:"Agent initialized"}],readStateDescription:""}}var nb,sb,bP,Tu=L(()=>{"use strict";nb=Be.object({stepNumber:Be.number().nullable().optional(),evaluationPreviousGoal:Be.string().nullable().optional(),memory:Be.string().nullable().optional(),nextGoal:Be.string().nullable().optional(),actionResults:Be.string().nullable().optional(),error:Be.string().nullable().optional(),systemMessage:Be.string().nullable().optional()}).refine(i=>!(i.error&&i.systemMessage),{message:"Cannot have both error and systemMessage at the same time"});sb=Be.object({systemMessage:Be.any().nullable().optional(),stateMessage:Be.any().nullable().optional(),contextMessages:Be.array(Be.any()).default([])});bP=Be.object({history:sb,toolId:Be.number().default(1),agentHistoryItems:Be.array(nb).default([{stepNumber:0,systemMessage:"Agent initialized"}]),readStateDescription:Be.string().default("")})});import{minimatch as ma}from"minimatch";function pa(i){return["about:blank","chrome://new-tab-page/","chrome://new-tab-page","chrome://newtab/","chrome://newtab"].includes(i)}function xu(i,e,t=!1){try{if(pa(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)),!ma(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||ma(r,g))return!0}if(ma(r,a))return!0}return!1}catch(n){return console.error(`⛔️ Error matching URL ${i} with pattern ${e}: ${n?.name}: ${n?.message}`),!1}}var ha=L(()=>{"use strict";bt()});import Cu from"fs";import Eu from"path";import{fileURLToPath as rb}from"url";var wo,To,fa=L(()=>{"use strict";ho();ha();wo=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
+ ${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=rb(t),s=Eu.dirname(n),r=Eu.join(s,e);Cu.existsSync(r)?this.promptTemplate=Cu.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
 
707
707
  <proactive_mindset>
@@ -797,7 +797,7 @@ 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 xo,Eu=L(()=>{"use strict";wu();fa();da();ha();xo=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");ga(this.state.history).length===0&&this.setMessageWithType(this.systemPrompt,"system")}get agentHistoryDescription(){if(this.maxHistoryItems===null)return this.state.agentHistoryItems.map(tr).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 xo,Iu=L(()=>{"use strict";Tu();fa();da();ha();xo=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||wu(),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");ga(this.state.history).length===0&&this.setMessageWithType(this.systemPrompt,"system")}get agentHistoryDescription(){if(this.maxHistoryItems===null)return this.state.agentHistoryItems.map(tr).join(`
801
801
  `);let e=this.state.agentHistoryItems.length;if(e<=this.maxHistoryItems)return this.state.agentHistoryItems.map(tr).join(`
802
802
  `);let t=e-this.maxHistoryItems,n=this.maxHistoryItems-1,s=[tr(this.state.agentHistoryItems[0]),`<sys>[... ${t} previous steps omitted...]</sys>`],r=this.state.agentHistoryItems.slice(-n);return s.push(...r.map(tr)),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+=`
@@ -810,11 +810,11 @@ ${d.extractedContent}
810
810
  `}}let c=6e4;if(this.state.readStateDescription.length>c&&(this.state.readStateDescription=this.state.readStateDescription.substring(0,c)+`
811
811
  ... [Content truncated at 60k characters]`),this.state.readStateDescription=this.state.readStateDescription.trim(),o&&(o=`Result
812
812
  ${o}`),o=o?o.trim():"",o&&o.length>c&&(o=o.substring(0,c)+`
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&&Tu(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:
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&&xu(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 To({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=vu(l),this.setMessageWithType(l,"state")}getMessages(){return this.lastInputMessages=ga(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 Eo from"fs/promises";import an from"fs";import sr from"path";var Co,sb,$n,cn,nr,Io,ko,Po,Ao,Do,Mo,Iu=L(()=>{"use strict";bt();er();Co="Error: Invalid filename format. Must be alphanumeric with supported extension.",sb="browseruse_agent_data",$n=class extends Error{constructor(e){super(e),this.name="FileSystemError"}},cn=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(`
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 To({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=Su(l),this.setMessageWithType(l,"state")}getMessages(){return this.lastInputMessages=ga(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 Eo from"fs/promises";import an from"fs";import sr from"path";var Co,ob,$n,cn,nr,Io,ko,Po,Ao,Do,Mo,ku=L(()=>{"use strict";bt();er();Co="Error: Invalid filename format. Must be alphanumeric with supported extension.",ob="browseruse_agent_data",$n=class extends Error{constructor(e){super(e),this.name="FileSystemError"}},cn=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
816
  `).length}writeFileContent(e){this.updateContent(e)}appendFileContent(e){this.updateContent(this.content+e)}updateContent(e){this.content=e}async syncToDisk(e){let t=sr.join(e,this.fullName);await Eo.writeFile(t,this.content,"utf-8")}syncToDiskSync(e){let t=sr.join(e,this.fullName);an.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}},nr=class extends cn{get extension(){return"md"}},Io=class extends cn{get extension(){return"txt"}},ko=class extends cn{get extension(){return"json"}},Po=class extends cn{get extension(){return"csv"}},Ao=class extends cn{get extension(){return"jsonl"}},Do=class extends cn{get extension(){return"pdf"}async syncToDisk(e){let t=sr.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 Eo.writeFile(t,c);return}}catch(n){b.debug("PDFKit not available, writing text file with .pdf extension:",n)}await Eo.writeFile(t,this.content,"utf-8")}syncToDiskSync(e){let t=sr.join(e,this.fullName);an.writeFileSync(t,this.content,"utf-8")}},Mo=class i{baseDir;dataDir;files=new Map;extractedContentCount=0;defaultFiles=["todo.md"];fileTypes={md:nr,txt:Io,json:ko,jsonl:Ao,csv:Po,pdf:Do};constructor(e,t=!0){this.baseDir=e,this.dataDir=sr.join(e,sb);try{an.existsSync(this.baseDir)||an.mkdirSync(this.baseDir,{recursive:!0}),an.existsSync(this.dataDir)&&an.rmSync(this.dataDir,{recursive:!0,force:!0}),an.mkdirSync(this.dataDir,{recursive:!0})}catch(n){throw new $n(`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 Eo.readFile(e,"utf-8");return`Read from file ${e}.
817
+ `);for(let l of a)l.trim()&&(s.text(l.trim(),{align:"left"}),s.moveDown(.5));s.end();let c=await o;await Eo.writeFile(t,c);return}}catch(n){b.debug("PDFKit not available, writing text file with .pdf extension:",n)}await Eo.writeFile(t,this.content,"utf-8")}syncToDiskSync(e){let t=sr.join(e,this.fullName);an.writeFileSync(t,this.content,"utf-8")}},Mo=class i{baseDir;dataDir;files=new Map;extractedContentCount=0;defaultFiles=["todo.md"];fileTypes={md:nr,txt:Io,json:ko,jsonl:Ao,csv:Po,pdf:Do};constructor(e,t=!0){this.baseDir=e,this.dataDir=sr.join(e,ob);try{an.existsSync(this.baseDir)||an.mkdirSync(this.baseDir,{recursive:!0}),an.existsSync(this.dataDir)&&an.rmSync(this.dataDir,{recursive:!0,force:!0}),an.mkdirSync(this.dataDir,{recursive:!0})}catch(n){throw new $n(`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 Eo.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 Co;let n=this.getFile(e);if(!n)return`File '${e}' not found.`;try{let s=n.read();return`Read from file ${e}.
@@ -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(){an.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 nr(o.name,o.content);break;case"TxtFile":a=new Io(o.name,o.content);break;case"JsonFile":a=new ko(o.name,o.content);break;case"JsonlFile":a=new Ao(o.name,o.content);break;case"CsvFile":a=new Po(o.name,o.content);break;case"PdfFile":a=new Do(o.name,o.content);break;default:continue}t.files.set(n,a),a.syncToDiskSync(t.dataDir)}return t}}});import*as ln from"fs/promises";import*as ba from"path";var Ro,ku=L(()=>{"use strict";Ro=class{agentDirectory;screenshotsDir;constructor(e){this.agentDirectory=e,this.screenshotsDir=ba.join(this.agentDirectory,"screenshots")}async initialize(){await ln.mkdir(this.screenshotsDir,{recursive:!0})}async storeScreenshot(e,t){let n=`step_${t}.png`,s=ba.join(this.screenshotsDir,n),r=Buffer.from(e,"base64");return await ln.writeFile(s,r),s}async getScreenshot(e){if(!e)return null;try{return await ln.access(e),(await ln.readFile(e)).toString("base64")}catch{return null}}}});import{z as Y}from"zod";async function Au(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 No,Pu,rb,ob,ib,KP,VP,Du=L(()=>{"use strict";No="iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAFElEQVR4nGP8//8/AwwwMSAB3BwAlm4DBfIlvvkAAAAASUVORK5CYII=",Pu=Y.object({url:Y.string(),title:Y.string(),targetId:Y.string(),parentTargetId:Y.string().nullable().optional()}),rb=Y.object({viewportWidth:Y.number(),viewportHeight:Y.number(),pageWidth:Y.number(),pageHeight:Y.number(),scrollX:Y.number(),scrollY:Y.number(),pixelsAbove:Y.number(),pixelsBelow:Y.number(),pixelsLeft:Y.number(),pixelsRight:Y.number()}),ob=Y.object({url:Y.string(),method:Y.string().default("GET"),loadingDurationMs:Y.number().default(0),resourceType:Y.string().nullable().optional()}),ib=Y.object({buttonType:Y.string(),backendNodeId:Y.number(),text:Y.string(),selector:Y.string(),isDisabled:Y.boolean().default(!1)}),KP=Y.object({domState:Y.any(),url:Y.string(),title:Y.string(),tabs:Y.array(Pu),screenshot:Y.string().nullable().optional(),pageInfo:rb.nullable().optional(),pixelsAbove:Y.number().default(0),pixelsBelow:Y.number().default(0),browserErrors:Y.array(Y.string()).default([]),isPdfViewer:Y.boolean().default(!1),recentEvents:Y.string().nullable().optional(),pendingNetworkRequests:Y.array(ob).default([]),paginationButtons:Y.array(ib).default([])}),VP=Y.object({url:Y.string(),title:Y.string(),tabs:Y.array(Pu),interactedElement:Y.array(Y.any().nullable()),screenshotPath:Y.string().nullable().optional()})});import*as ya from"fs";async function Mu(i){try{return await import(i)}catch{throw new Error(`Module '${i}' not available. Install with: npm install ${i}`)}}function Ru(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 Nu(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 ab(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 Au(r);t.push(a)}else o?t.push(o):e&&t.push(null)}return t}async function Ou(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=fo.text,titleFontSize:l=fo.title,goalFontSize:d=fo.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 ab(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!==No){h=f;break}if(!h){console.warn("[GIF] No valid screenshots found (all are placeholders or from new tab pages)");return}try{await cb({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 gb({task:e,history:t,screenshots:p,outputPath:n.replace(".gif",".html"),duration:s,showGoals:r,showTask:o})}}async function cb(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 Mu("sharp");p=S.default||S}catch(S){throw new Error(`sharp library not available: ${S.message}`)}let h;try{let S=await Mu("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(),v=y.width||1920,T=y.height||1080,C=new h(v,T,"neuquant",!0);C.setDelay(o),C.setRepeat(0),C.setQuality(10),C.start();let I=[];if(c&&e){let S=await lb(p,e,s,v,T,l,g);I.push(S)}let E=0;for(let S=0;S<t.history.length;S++){let P=t.history[S],x=n[S];if(!x)continue;if(x===No){b.debug(`[GIF] Skipping placeholder screenshot from about:blank page at step ${S+1}`);continue}if(Ru(P.state.url)){b.debug(`[GIF] Skipping screenshot from new tab page (${P.state.url}) at step ${S+1}`);continue}E++;let A=Buffer.from(x,"base64");if(a&&P.modelOutput){let O=P.modelOutput.currentState?.nextGoal||P.modelOutput.nextGoal||"",U=await ub(p,A,E,O,v,T,l,d,g);I.push(U)}else{let O=await p(A).resize(v,T,{fit:"fill"}).raw().toBuffer();I.push(O)}}if(I.length===0){console.warn("[GIF] No valid frames to create GIF");return}for(let S of I)C.addFrame(S);C.finish();let w=C.out.getData();ya.writeFileSync(r,w)}async function lb(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 ub(i,e,t,n,s,r,o,a,c){let l=Nu(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(){an.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 nr(o.name,o.content);break;case"TxtFile":a=new Io(o.name,o.content);break;case"JsonFile":a=new ko(o.name,o.content);break;case"JsonlFile":a=new Ao(o.name,o.content);break;case"CsvFile":a=new Po(o.name,o.content);break;case"PdfFile":a=new Do(o.name,o.content);break;default:continue}t.files.set(n,a),a.syncToDiskSync(t.dataDir)}return t}}});import*as ln from"fs/promises";import*as ba from"path";var Ro,Pu=L(()=>{"use strict";Ro=class{agentDirectory;screenshotsDir;constructor(e){this.agentDirectory=e,this.screenshotsDir=ba.join(this.agentDirectory,"screenshots")}async initialize(){await ln.mkdir(this.screenshotsDir,{recursive:!0})}async storeScreenshot(e,t){let n=`step_${t}.png`,s=ba.join(this.screenshotsDir,n),r=Buffer.from(e,"base64");return await ln.writeFile(s,r),s}async getScreenshot(e){if(!e)return null;try{return await ln.access(e),(await ln.readFile(e)).toString("base64")}catch{return null}}}});import{z as Y}from"zod";async function Du(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 No,Au,ib,ab,cb,XP,YP,Mu=L(()=>{"use strict";No="iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAFElEQVR4nGP8//8/AwwwMSAB3BwAlm4DBfIlvvkAAAAASUVORK5CYII=",Au=Y.object({url:Y.string(),title:Y.string(),targetId:Y.string(),parentTargetId:Y.string().nullable().optional()}),ib=Y.object({viewportWidth:Y.number(),viewportHeight:Y.number(),pageWidth:Y.number(),pageHeight:Y.number(),scrollX:Y.number(),scrollY:Y.number(),pixelsAbove:Y.number(),pixelsBelow:Y.number(),pixelsLeft:Y.number(),pixelsRight:Y.number()}),ab=Y.object({url:Y.string(),method:Y.string().default("GET"),loadingDurationMs:Y.number().default(0),resourceType:Y.string().nullable().optional()}),cb=Y.object({buttonType:Y.string(),backendNodeId:Y.number(),text:Y.string(),selector:Y.string(),isDisabled:Y.boolean().default(!1)}),XP=Y.object({domState:Y.any(),url:Y.string(),title:Y.string(),tabs:Y.array(Au),screenshot:Y.string().nullable().optional(),pageInfo:ib.nullable().optional(),pixelsAbove:Y.number().default(0),pixelsBelow:Y.number().default(0),browserErrors:Y.array(Y.string()).default([]),isPdfViewer:Y.boolean().default(!1),recentEvents:Y.string().nullable().optional(),pendingNetworkRequests:Y.array(ab).default([]),paginationButtons:Y.array(cb).default([])}),YP=Y.object({url:Y.string(),title:Y.string(),tabs:Y.array(Au),interactedElement:Y.array(Y.any().nullable()),screenshotPath:Y.string().nullable().optional()})});import*as ya from"fs";async function Ru(i){try{return await import(i)}catch{throw new Error(`Module '${i}' not available. Install with: npm install ${i}`)}}function Nu(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 Ou(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 lb(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 Du(r);t.push(a)}else o?t.push(o):e&&t.push(null)}return t}async function _u(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=fo.text,titleFontSize:l=fo.title,goalFontSize:d=fo.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 lb(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!==No){h=f;break}if(!h){console.warn("[GIF] No valid screenshots found (all are placeholders or from new tab pages)");return}try{await ub({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 pb({task:e,history:t,screenshots:p,outputPath:n.replace(".gif",".html"),duration:s,showGoals:r,showTask:o})}}async function ub(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 Ru("sharp");p=S.default||S}catch(S){throw new Error(`sharp library not available: ${S.message}`)}let h;try{let S=await Ru("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(),v=y.width||1920,T=y.height||1080,C=new h(v,T,"neuquant",!0);C.setDelay(o),C.setRepeat(0),C.setQuality(10),C.start();let I=[];if(c&&e){let S=await db(p,e,s,v,T,l,g);I.push(S)}let E=0;for(let S=0;S<t.history.length;S++){let P=t.history[S],x=n[S];if(!x)continue;if(x===No){b.debug(`[GIF] Skipping placeholder screenshot from about:blank page at step ${S+1}`);continue}if(Nu(P.state.url)){b.debug(`[GIF] Skipping screenshot from new tab page (${P.state.url}) at step ${S+1}`);continue}E++;let A=Buffer.from(x,"base64");if(a&&P.modelOutput){let O=P.modelOutput.currentState?.nextGoal||P.modelOutput.nextGoal||"",U=await gb(p,A,E,O,v,T,l,d,g);I.push(U)}else{let O=await p(A).resize(v,T,{fit:"fill"}).raw().toBuffer();I.push(O)}}if(I.length===0){console.warn("[GIF] No valid frames to create GIF");return}for(let S of I)C.addFrame(S);C.finish();let w=C.out.getData();ya.writeFileSync(r,w)}async function db(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 gb(i,e,t,n,s,r,o,a,c){let l=Ou(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,10 +869,10 @@ ${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
- ${rr(db(l,80))}
872
+ ${rr(mb(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 rr(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function db(i,e){return i.length<=e?i:i.substring(0,e-3)+"..."}async function gb(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===No||Ru(m.state.url))continue;l++;let h=o&&m.modelOutput&&(m.modelOutput.currentState?.nextGoal||m.modelOutput.nextGoal)||"";c.push({screenshot:p,stepNumber:l,goal:Nu(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 rr(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function mb(i,e){return i.length<=e?i:i.substring(0,e-3)+"..."}async function pb(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===No||Nu(m.state.url))continue;l++;let h=o&&m.modelOutput&&(m.modelOutput.currentState?.nextGoal||m.modelOutput.nextGoal)||"";c.push({screenshot:p,stepNumber:l,goal:Ou(h),url:m.state.url})}let d=`<!DOCTYPE html>
876
876
  <html lang="en">
877
877
  <head>
878
878
  <meta charset="UTF-8">
@@ -1140,7 +1140,7 @@ ${l}
1140
1140
  });
1141
1141
  </script>
1142
1142
  </body>
1143
- </html>`;ya.writeFileSync(s,d),console.info(`[GIF] Created HTML viewer at ${s}`)}var _u=L(()=>{"use strict";bt();ia();Du();er()});import{v4 as mb}from"uuid";import $u from"fs/promises";import Oo from"path";import pb from"os";import hb from"crypto";import{spawnSync as fb}from"child_process";import{zodToJsonSchema as bb}from"zod-to-json-schema";var or,Fu=L(()=>{"use strict";bt();sa();mo();uu();hu();ia();So();da();Eu();fa();Iu();ku();_u();or=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=mb(),this.task=e.task,this.llm=e.llm,this.maxSteps=e.maxSteps||100,this.outputSchema=e.outputSchema,this.settings={...fu,...e.settings},e.browserSession)this.browserSession=e.browserSession,this.ownsBrowserSession=!1;else{let a={headless:!1};if(Nn())try{let c=ds();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 on(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 bo,pu(this.actionRegistry));let t=this.actionRegistry.createActionModel();this.dynamicAgentOutputSchema=vo(t);let n=this.actionRegistry.createActionModel(["done"]);this.doneAgentOutputSchema=vo(n),this.state=aa(),this.history=ca(this.id,this.task);let s=pb.tmpdir();this.agentDirectory=Oo.join(s,`browser_use_agent_${this.id}`),this.fileSystem=new Mo(this.agentDirectory),this.screenshotService=new Ro(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 wo(this.settings.maxActionsPerStep,this.settings.overrideSystemMessage,this.settings.extendSystemMessage,this.settings.useThinking,this.settings.flashMode).getSystemMessage();this.messageManager=new xo({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:Oo.join(this.agentDirectory,"agent_history.gif");b.log("📹 Generating GIF..."),await Ou({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(ua(s));for(let o of this.history.history){let a=this.formatBrowserState(o.state);if(n.push(_n(a)),o.modelOutput){let c=JSON.stringify(o.modelOutput);n.push({role:"assistant",content:c})}}let r=this.formatCurrentState(e,t);return n.push(_n(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>`;ya.writeFileSync(s,d),console.info(`[GIF] Created HTML viewer at ${s}`)}var $u=L(()=>{"use strict";bt();ia();Mu();er()});import{v4 as hb}from"uuid";import Fu from"fs/promises";import Oo from"path";import fb from"os";import bb from"crypto";import{spawnSync as yb}from"child_process";import{zodToJsonSchema as vb}from"zod-to-json-schema";var or,Lu=L(()=>{"use strict";bt();sa();mo();du();fu();ia();So();da();Iu();fa();ku();Pu();$u();or=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=hb(),this.task=e.task,this.llm=e.llm,this.maxSteps=e.maxSteps||100,this.outputSchema=e.outputSchema,this.settings={...bu,...e.settings},e.browserSession)this.browserSession=e.browserSession,this.ownsBrowserSession=!1;else{let a={headless:!1};if(Nn())try{let c=ds();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 on(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 bo,hu(this.actionRegistry));let t=this.actionRegistry.createActionModel();this.dynamicAgentOutputSchema=vo(t);let n=this.actionRegistry.createActionModel(["done"]);this.doneAgentOutputSchema=vo(n),this.state=aa(),this.history=ca(this.id,this.task);let s=fb.tmpdir();this.agentDirectory=Oo.join(s,`browser_use_agent_${this.id}`),this.fileSystem=new Mo(this.agentDirectory),this.screenshotService=new Ro(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 wo(this.settings.maxActionsPerStep,this.settings.overrideSystemMessage,this.settings.extendSystemMessage,this.settings.useThinking,this.settings.flashMode).getSystemMessage();this.messageManager=new xo({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:Oo.join(this.agentDirectory,"agent_history.gif");b.log("📹 Generating GIF..."),await _u({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(ua(s));for(let o of this.history.history){let a=this.formatBrowserState(o.state);if(n.push(_n(a)),o.modelOutput){let c=JSON.stringify(o.modelOutput);n.push({role:"assistant",content:c})}}let r=this.formatCurrentState(e,t);return n.push(_n(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
 
@@ -1169,8 +1169,8 @@ Tabs: ${e.tabs.length} open`}formatCurrentState(e,t){return`Step ${t.stepNumber}
1169
1169
  Current URL: ${e.url}
1170
1170
  Title: ${e.title}
1171
1171
 
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||yo;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(ua("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=Oo.resolve(this.settings.saveConversationPath),n=`conversation_${this.id}_${this.state.nSteps}.txt`,s=Oo.join(t,n);await $u.mkdir(t,{recursive:!0});let r=this._formatConversation(e,this.state.lastModelOutput),o=this.settings.saveConversationPathEncoding||"utf-8";await $u.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 v=await this.browserSession.getCurrentPageUrl();if(v!==r&&v!==""&&r!==""){let T=s-o-1;b.log(`🔄 Page navigation detected: ${r} → ${v}`),b.log(`📍 Interrupting remaining ${T} actions (element indices now stale)`),this.browserSession.clearCachedState(),T>0&&t.push({extractedContent:`Page navigated to ${v}. Skipped ${T} remaining action(s) because element indices are now stale.`});break}r=v}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=yu(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(`
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||yo;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(ua("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=Oo.resolve(this.settings.saveConversationPath),n=`conversation_${this.id}_${this.state.nSteps}.txt`,s=Oo.join(t,n);await Fu.mkdir(t,{recursive:!0});let r=this._formatConversation(e,this.state.lastModelOutput),o=this.settings.saveConversationPathEncoding||"utf-8";await Fu.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 v=await this.browserSession.getCurrentPageUrl();if(v!==r&&v!==""&&r!==""){let T=s-o-1;b.log(`🔄 Page navigation detected: ${r} → ${v}`),b.log(`📍 Interrupting remaining ${T} actions (element indices now stale)`),this.browserSession.clearCachedState(),T>0&&t.push({extractedContent:`Page navigated to ${v}. Skipped ${T} remaining action(s) because element indices are now stale.`});break}r=v}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=vu(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}
@@ -1188,21 +1188,21 @@ ${e.extractedContent}
1188
1188
  ${e.extractedContent}
1189
1189
 
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
- `;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=bu(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&&oa(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.
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=yu(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&&oa(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
1193
  Include everything you found out for the ultimate task in the done text.`;b.log("Last step finishing up"),this.messageManager.addContextMessage(_n(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(_n(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&&!oa(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(_n(o))}}async _getModelOutputWithRetry(e){let t=this.dynamicAgentOutputSchema||yo,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=_n("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(()=>(So(),la));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(()=>(So(),la)),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=hb.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=bb(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(_n(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&&!oa(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(_n(o))}}async _getModelOutputWithRetry(e){let t=this.dynamicAgentOutputSchema||yo,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=_n("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(()=>(So(),la));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(()=>(So(),la)),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=bb.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=vb(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;)fb("sleep",["0.01"]);if(o)throw o;return r}}});import{zodToJsonSchema as yb}from"zod-to-json-schema";var _o,Lu=L(()=>{"use strict";_o=class{static createOptimizedJsonSchema(e){let t=yb(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 v=l[y];m=s(v,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 vb from"openai";var Sb,va,ir,Uu=L(()=>{"use strict";Lu();Sb=["o4-mini","o3","o3-mini","o1","o1-pro","gpt-5","gpt-5-mini","gpt-5-nano"],va=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;)yb("sleep",["0.01"]);if(o)throw o;return r}}});import{zodToJsonSchema as Sb}from"zod-to-json-schema";var _o,Uu=L(()=>{"use strict";_o=class{static createOptimizedJsonSchema(e){let t=Sb(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 v=l[y];m=s(v,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 wb from"openai";var Tb,va,ir,Bu=L(()=>{"use strict";Uu();Tb=["o4-mini","o3","o3-mini","o1","o1-pro","gpt-5","gpt-5-mini","gpt-5-nano"],va=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}`)})}},ir=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=Sb.some(n=>t.includes(n.toLowerCase())),this.client=new vb({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=va.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=_o.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 wb from"@anthropic-ai/sdk";import{zodToJsonSchema as Tb}from"zod-to-json-schema";var Sa,$o,Bu=L(()=>{"use strict";Sa=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}`)})}},ir=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=Tb.some(n=>t.includes(n.toLowerCase())),this.client=new wb({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=va.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=_o.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 xb from"@anthropic-ai/sdk";import{zodToJsonSchema as Cb}from"zod-to-json-schema";var Sa,$o,Wu=L(()=>{"use strict";Sa=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}}},$o=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 wb({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}=Sa.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={...Tb(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 xb}from"child_process";import{existsSync as Wu}from"fs";import{homedir as Hu}from"os";import{join as Gu}from"path";import{EventEmitter as Cb}from"events";var wa,re,Fo=L(()=>{"use strict";bt();Fu();sa();Uu();Bu();mo();wa=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 Cb;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",Gu(Hu(),"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",Gu(Hu(),"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(Wu(n))return n;return null}async checkPatchrightBrowsers(){try{let{chromium:e}=await import("patchright"),t=e.executablePath();if(Wu(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=xb(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:!0};if(this.systemChromePath&&(b.log(`🌐 [BrowserUse] Using system Chrome: ${this.systemChromePath}`),n.executablePath=this.systemChromePath,n.channel=void 0),Nn()){let r=Ys();b.log(`🍪 [BrowserUse] Found imported profile: ${r.cookieCount} cookies, ${r.originCount} origins`);try{let o=ds();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 on(n),await this.browserSession.start(),this.sessionHeadlessMode=!0,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(){let e=this.initState==="ready"&&this.browsersInstalled,t=Nn()?Ys():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),Nn()){let s=Ys();b.log(`🍪 [BrowserUse] Found imported profile: ${s.cookieCount} cookies, ${s.originCount} origins`);try{let r=ds();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 on(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 or({task:n,llm:g,browserSession:this.browserSession,pageId:d,settings:{useVision:r??!0},maxSteps:o,registerShouldStopCallback:()=>this.stopRequested,registerNewStepCallback:async(f,y,v)=>{b.log(`📊 [BrowserUse] Sub-agent ${e} step ${v}/${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),Nn()){let p=Ys();b.log(`🍪 [BrowserUse] Found imported profile: ${p.cookieCount} cookies, ${p.originCount} origins`);try{let h=ds();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 on(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 or({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 $o({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 ir({model:e,apiKey:t,baseURL:o,temperature:.7})}return b.log("🧠 [BrowserUse] Using OpenAI provider (requires OPENAI_API_KEY)"),new ir({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.prewarmTriggered=!1,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)")}},re=wa.shared()});var ar,a0,ju=L(()=>{"use strict";bt();Fo();ke();ar=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 re.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 re.listTools()}async executeTool(e,t){return await this.ensureInitialized(),re.executeTool(e,t)}async executeToolStream(e,t,n){await this.ensureInitialized(),re.setProgressCallback(n);try{return await re.executeTool(e,t)}finally{re.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 Z.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..."),re.onProgress(d=>{this.handleProgress(d)});let c=await re.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 re.getStatus()}async closeBrowser(){await re.closeBrowser()}requestStop(){re.requestStop()}async executeToolForSubAgent(e,t,n){let s=null;try{s=await Z.getInstance().getFirebaseIdToken()}catch{console.warn("⚠️ [BrowserAutomation] Could not get Firebase token for sub-agent")}let r={...n,firebase_token:s||n.firebase_token};return re.executeToolForSubAgent(e,t,r)}getSubAgentStatus(){return re.getSubAgentStatus()}async stopSubAgent(e){return re.stopSubAgent(e)}async stopAllSubAgents(){return re.stopAllSubAgents()}async cleanupAllSubAgents(){return re.cleanupAllSubAgents()}async stop(){return re.stop()}async forceKill(){return re.forceKill()}async restart(){return re.restart()}isRunning(){return re.isRunning()}getExecutionStatus(){return re.getExecutionStatus()}isBrowserSessionAlive(){return re.isBrowserSessionAlive()}getSessionIdleSeconds(){return re.getSessionIdleSeconds()}setProgressCallback(e){re.setProgressCallback(e)}async cleanup(){return re.cleanup()}},a0=new ar});function zu(i){i.register(new Br),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 Yr),i.register(new Qr),i.register(new Jr),i.register(new Zr),i.register(new eo),i.register(new to),i.register(new no),i.register(new io),i.register(new ao),i.register(new co),i.register(new uo),i.register(new ar)}var qu=L(()=>{"use strict";wl();Tl();xl();Cl();El();Il();kl();_l();$l();Fl();Ll();Ul();Bl();Wl();ql();Kl();Vl();Ql();ju()});var cr,Ku=L(()=>{"use strict";cr=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 Vu=L(()=>{"use strict"});import nt from"fs";import un from"path";import Eb from"os";var Ib,Ta,Lt,Xu=L(()=>{"use strict";V();Ib=/[/\\:*?"<>|]/g,Ta=class i{static instance;skillsPath;constructor(){this.skillsPath=un.join(Eb.homedir(),".orion","skills")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.skillsPath}ensureFolder(){try{return nt.existsSync(this.skillsPath)||(nt.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"}:Ib.test(t)?{valid:!1,error:"Skill name contains invalid characters"}:un.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=nt.readdirSync(this.skillsPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=un.join(this.skillsPath,n);try{if(!nt.statSync(s).isFile())continue;let o=nt.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=un.join(this.skillsPath,`${s}.md`);try{return this.ensureFolder(),nt.existsSync(r)?{success:!1,error:"A skill with this name already exists"}:(nt.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=un.join(this.skillsPath,`${e}.md`);try{return nt.existsSync(s)?(nt.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=un.join(this.skillsPath,`${e}.md`);try{return nt.existsSync(n)?(nt.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=un.join(this.skillsPath,`${e}.md`);try{return nt.existsSync(n)?{success:!0,content:nt.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=un.join(this.skillsPath,`${e}.md`);return nt.existsSync(n)}},Lt=Ta.getInstance()});var kb,Pb,Ab,Db,Mb,Rb,Nb,xa,Yu=L(()=>{"use strict";kb=[{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}}},$o=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 xb({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}=Sa.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={...Cb(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 Eb}from"child_process";import{existsSync as Hu}from"fs";import{homedir as Gu}from"os";import{join as ju}from"path";import{EventEmitter as Ib}from"events";var wa,re,Fo=L(()=>{"use strict";bt();Lu();sa();Bu();Wu();mo();wa=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 Ib;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",ju(Gu(),"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",ju(Gu(),"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(Hu(n))return n;return null}async checkPatchrightBrowsers(){try{let{chromium:e}=await import("patchright"),t=e.executablePath();if(Hu(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=Eb(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:!0};if(this.systemChromePath&&(b.log(`🌐 [BrowserUse] Using system Chrome: ${this.systemChromePath}`),n.executablePath=this.systemChromePath,n.channel=void 0),Nn()){let r=Ys();b.log(`🍪 [BrowserUse] Found imported profile: ${r.cookieCount} cookies, ${r.originCount} origins`);try{let o=ds();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 on(n),await this.browserSession.start(),this.sessionHeadlessMode=!0,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(){let e=this.initState==="ready"&&this.browsersInstalled,t=Nn()?Ys():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),Nn()){let s=Ys();b.log(`🍪 [BrowserUse] Found imported profile: ${s.cookieCount} cookies, ${s.originCount} origins`);try{let r=ds();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 on(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 or({task:n,llm:g,browserSession:this.browserSession,pageId:d,settings:{useVision:r??!0},maxSteps:o,registerShouldStopCallback:()=>this.stopRequested,registerNewStepCallback:async(f,y,v)=>{b.log(`📊 [BrowserUse] Sub-agent ${e} step ${v}/${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),Nn()){let p=Ys();b.log(`🍪 [BrowserUse] Found imported profile: ${p.cookieCount} cookies, ${p.originCount} origins`);try{let h=ds();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 on(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 or({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 $o({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 ir({model:e,apiKey:t,baseURL:o,temperature:.7})}return b.log("🧠 [BrowserUse] Using OpenAI provider (requires OPENAI_API_KEY)"),new ir({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.prewarmTriggered=!1,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)")}},re=wa.shared()});var ar,l0,zu=L(()=>{"use strict";bt();Fo();ke();ar=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 re.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 re.listTools()}async executeTool(e,t){return await this.ensureInitialized(),re.executeTool(e,t)}async executeToolStream(e,t,n){await this.ensureInitialized(),re.setProgressCallback(n);try{return await re.executeTool(e,t)}finally{re.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 Z.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..."),re.onProgress(d=>{this.handleProgress(d)});let c=await re.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 re.getStatus()}async closeBrowser(){await re.closeBrowser()}requestStop(){re.requestStop()}async executeToolForSubAgent(e,t,n){let s=null;try{s=await Z.getInstance().getFirebaseIdToken()}catch{console.warn("⚠️ [BrowserAutomation] Could not get Firebase token for sub-agent")}let r={...n,firebase_token:s||n.firebase_token};return re.executeToolForSubAgent(e,t,r)}getSubAgentStatus(){return re.getSubAgentStatus()}async stopSubAgent(e){return re.stopSubAgent(e)}async stopAllSubAgents(){return re.stopAllSubAgents()}async cleanupAllSubAgents(){return re.cleanupAllSubAgents()}async stop(){return re.stop()}async forceKill(){return re.forceKill()}async restart(){return re.restart()}isRunning(){return re.isRunning()}getExecutionStatus(){return re.getExecutionStatus()}isBrowserSessionAlive(){return re.isBrowserSessionAlive()}getSessionIdleSeconds(){return re.getSessionIdleSeconds()}setProgressCallback(e){re.setProgressCallback(e)}async cleanup(){return re.cleanup()}},l0=new ar});function qu(i){i.register(new Br),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 Yr),i.register(new Qr),i.register(new Jr),i.register(new Zr),i.register(new eo),i.register(new to),i.register(new no),i.register(new io),i.register(new ao),i.register(new co),i.register(new uo),i.register(new ar)}var Ku=L(()=>{"use strict";Tl();xl();Cl();El();Il();kl();Pl();$l();Fl();Ll();Ul();Bl();Wl();Hl();Kl();Vl();Xl();Jl();zu()});var cr,Vu=L(()=>{"use strict";cr=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 Xu=L(()=>{"use strict"});import nt from"fs";import un from"path";import kb from"os";var Pb,Ta,Lt,Yu=L(()=>{"use strict";V();Pb=/[/\\:*?"<>|]/g,Ta=class i{static instance;skillsPath;constructor(){this.skillsPath=un.join(kb.homedir(),".orion","skills")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.skillsPath}ensureFolder(){try{return nt.existsSync(this.skillsPath)||(nt.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"}:Pb.test(t)?{valid:!1,error:"Skill name contains invalid characters"}:un.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=nt.readdirSync(this.skillsPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=un.join(this.skillsPath,n);try{if(!nt.statSync(s).isFile())continue;let o=nt.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=un.join(this.skillsPath,`${s}.md`);try{return this.ensureFolder(),nt.existsSync(r)?{success:!1,error:"A skill with this name already exists"}:(nt.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=un.join(this.skillsPath,`${e}.md`);try{return nt.existsSync(s)?(nt.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=un.join(this.skillsPath,`${e}.md`);try{return nt.existsSync(n)?(nt.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=un.join(this.skillsPath,`${e}.md`);try{return nt.existsSync(n)?{success:!0,content:nt.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=un.join(this.skillsPath,`${e}.md`);return nt.existsSync(n)}},Lt=Ta.getInstance()});var Ab,Db,Mb,Rb,Nb,Ob,_b,xa,Qu=L(()=>{"use strict";Ab=[{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
 
@@ -1283,7 +1283,7 @@ bird tweet "check this out" --media image.png --alt "description"
1283
1283
  \`\`\`
1284
1284
 
1285
1285
  ⚠️ Posting is more likely to be rate limited.
1286
- `}],Pb=[{id:"notion",name:"Notion",emoji:"📝",description:"Notion API for creating and managing pages, databases, and blocks.",tags:["notion","productivity","notes"],content:`# Notion API
1286
+ `}],Db=[{id:"notion",name:"Notion",emoji:"📝",description:"Notion API for creating and managing pages, databases, and blocks.",tags:["notion","productivity","notes"],content:`# Notion API
1287
1287
 
1288
1288
  Create/read/update pages, databases, and blocks via Notion API.
1289
1289
 
@@ -1389,7 +1389,7 @@ obsidian-cli delete "path/note"
1389
1389
 
1390
1390
  Notes
1391
1391
  - Prefer direct edits: open the .md file and Obsidian will pick it up.
1392
- `}],Ab=[{id:"coding",name:"Coding Standards",emoji:"📐",description:"Enforces universal code quality rules when the agent writes or modifies code in any language. Covers file limits, style, structure, and refactoring.",tags:["coding","standards","guidelines","development"],content:`# Coding Standards
1392
+ `}],Mb=[{id:"coding",name:"Coding Standards",emoji:"📐",description:"Enforces universal code quality rules when the agent writes or modifies code in any language. Covers file limits, style, structure, and refactoring.",tags:["coding","standards","guidelines","development"],content:`# Coding Standards
1393
1393
 
1394
1394
  Universal rules for writing code in any language.
1395
1395
 
@@ -1673,7 +1673,7 @@ Tell user: "Installed '<name>' skill - [what it does]"
1673
1673
  1. Do NOT install
1674
1674
  2. Try next skill from search results
1675
1675
  3. If all fail, tell user what's missing
1676
- `}],Db=[{id:"openhue",name:"Philips Hue",emoji:"💡",description:"Control Philips Hue lights/scenes via the OpenHue CLI.",tags:["hue","lights","smarthome"],content:'# OpenHue CLI\n\nUse `openhue` to control Hue lights and scenes via a Hue Bridge.\n\nSetup\n- Discover bridges: `openhue discover`\n- Guided setup: `openhue setup`\n\nRead\n- `openhue get light --json`\n- `openhue get room --json`\n- `openhue get scene --json`\n\nWrite\n- Turn on: `openhue set light <id-or-name> --on`\n- Turn off: `openhue set light <id-or-name> --off`\n- Brightness: `openhue set light <id> --on --brightness 50`\n- Color: `openhue set light <id> --on --rgb #3399FF`\n- Scene: `openhue set scene <scene-id>`\n\nNotes\n- You may need to press the Hue Bridge button during setup.\n- Use `--room "Room Name"` when light names are ambiguous.\n'},{id:"sonoscli",name:"Sonos",emoji:"🔊",description:"Control Sonos speakers (discover/status/play/volume/group).",tags:["sonos","speakers","audio"],content:'# Sonos CLI\n\nUse `sonos` to control Sonos speakers on the local network.\n\nQuick start\n- `sonos discover`\n- `sonos status --name "Kitchen"`\n- `sonos play|pause|stop --name "Kitchen"`\n- `sonos volume set 15 --name "Kitchen"`\n\nCommon tasks\n- Grouping: `sonos group status|join|unjoin|party|solo`\n- Favorites: `sonos favorites list|open`\n- Queue: `sonos queue list|play|clear`\n- Spotify search: `sonos smapi search --service "Spotify" --category tracks "query"`\n\nNotes\n- If SSDP fails, specify `--ip <speaker-ip>`.\n'},{id:"blucli",name:"BluOS",emoji:"🫐",description:"BluOS CLI (blu) for discovery, playback, grouping, and volume.",tags:["bluos","speakers","audio"],content:'# blucli (blu)\n\nUse `blu` to control Bluesound/NAD players.\n\nQuick start\n- `blu devices` (pick target)\n- `blu --device <id> status`\n- `blu play|pause|stop`\n- `blu volume set 15`\n\nTarget selection (in priority order)\n- `--device <id|name|alias>`\n- `BLU_DEVICE` env var\n- config default (if set)\n\nCommon tasks\n- Grouping: `blu group status|add|remove`\n- TuneIn search/play: `blu tunein search "query"`, `blu tunein play "query"`\n\nNotes\n- Prefer `--json` for scripts.\n- Confirm target device before changing playback.\n'},{id:"eightctl",name:"Eight Sleep",emoji:"🎛️",description:"Control Eight Sleep pods (status, temperature, alarms, schedules).",tags:["eightsleep","bed","smarthome"],content:"# eightctl\n\nUse `eightctl` for Eight Sleep pod control. Requires auth.\n\nAuth\n- Config: `~/.config/eightctl/config.yaml`\n- Env: `EIGHTCTL_EMAIL`, `EIGHTCTL_PASSWORD`\n\nQuick start\n- `eightctl status`\n- `eightctl on|off`\n- `eightctl temp 20`\n\nCommon tasks\n- Alarms: `eightctl alarm list|create|dismiss`\n- Schedules: `eightctl schedule list|create|update`\n- Audio: `eightctl audio state|play|pause`\n- Base: `eightctl base info|angle`\n\nNotes\n- API is unofficial and rate-limited; avoid repeated logins.\n- Confirm before changing temperature or alarms.\n"}],Mb=[{id:"spotify-player",name:"Spotify",emoji:"🎵",description:"Terminal Spotify playback/search via spogo (preferred) or spotify_player.",tags:["spotify","music","streaming"],content:'# spogo / spotify_player\n\nUse `spogo` (preferred) for Spotify playback/search.\n\nRequirements\n- Spotify Premium account\n- Either `spogo` or `spotify_player` installed\n\nspogo setup\n- Import cookies: `spogo auth import --browser chrome`\n\nCommon CLI commands\n- Search: `spogo search track "query"`\n- Playback: `spogo play|pause|next|prev`\n- Devices: `spogo device list`, `spogo device set "<name|id>"`\n- Status: `spogo status`\n\nspotify_player commands (fallback)\n- Search: `spotify_player search "query"`\n- Playback: `spotify_player playback play|pause|next|previous`\n- Connect device: `spotify_player connect`\n- Like track: `spotify_player like`\n\nNotes\n- Config folder: `~/.config/spotify-player`\n'},{id:"gifgrep",name:"GIF Search",emoji:"🧲",description:"Search GIF providers with CLI/TUI, download results, and extract stills/sheets.",tags:["gif","images","search"],content:'# gifgrep\n\nUse `gifgrep` to search GIF providers (Tenor/Giphy), browse in TUI, download, and extract stills.\n\nQuick start\n- `gifgrep cats --max 5`\n- `gifgrep cats --format url | head -n 5`\n- `gifgrep search --json cats | jq \'.[0].url\'`\n- `gifgrep tui "office handshake"`\n- `gifgrep cats --download --max 1 --format url`\n\nTUI + previews\n- TUI: `gifgrep tui "query"`\n- CLI still previews: `--thumbs` (Kitty/Ghostty only)\n\nDownload + reveal\n- `--download` saves to ~/Downloads\n- `--reveal` shows in Finder\n\nStills + sheets\n- `gifgrep still ./clip.gif --at 1.5s -o still.png`\n- `gifgrep sheet ./clip.gif --frames 9 --cols 3 -o sheet.png`\n\nProviders\n- `--source auto|tenor|giphy`\n- `GIPHY_API_KEY` required for giphy\n'},{id:"nano-pdf",name:"PDF Editor",emoji:"📄",description:"Edit PDFs with natural-language instructions using the nano-pdf CLI.",tags:["pdf","documents","editing"],content:`# nano-pdf
1676
+ `}],Rb=[{id:"openhue",name:"Philips Hue",emoji:"💡",description:"Control Philips Hue lights/scenes via the OpenHue CLI.",tags:["hue","lights","smarthome"],content:'# OpenHue CLI\n\nUse `openhue` to control Hue lights and scenes via a Hue Bridge.\n\nSetup\n- Discover bridges: `openhue discover`\n- Guided setup: `openhue setup`\n\nRead\n- `openhue get light --json`\n- `openhue get room --json`\n- `openhue get scene --json`\n\nWrite\n- Turn on: `openhue set light <id-or-name> --on`\n- Turn off: `openhue set light <id-or-name> --off`\n- Brightness: `openhue set light <id> --on --brightness 50`\n- Color: `openhue set light <id> --on --rgb #3399FF`\n- Scene: `openhue set scene <scene-id>`\n\nNotes\n- You may need to press the Hue Bridge button during setup.\n- Use `--room "Room Name"` when light names are ambiguous.\n'},{id:"sonoscli",name:"Sonos",emoji:"🔊",description:"Control Sonos speakers (discover/status/play/volume/group).",tags:["sonos","speakers","audio"],content:'# Sonos CLI\n\nUse `sonos` to control Sonos speakers on the local network.\n\nQuick start\n- `sonos discover`\n- `sonos status --name "Kitchen"`\n- `sonos play|pause|stop --name "Kitchen"`\n- `sonos volume set 15 --name "Kitchen"`\n\nCommon tasks\n- Grouping: `sonos group status|join|unjoin|party|solo`\n- Favorites: `sonos favorites list|open`\n- Queue: `sonos queue list|play|clear`\n- Spotify search: `sonos smapi search --service "Spotify" --category tracks "query"`\n\nNotes\n- If SSDP fails, specify `--ip <speaker-ip>`.\n'},{id:"blucli",name:"BluOS",emoji:"🫐",description:"BluOS CLI (blu) for discovery, playback, grouping, and volume.",tags:["bluos","speakers","audio"],content:'# blucli (blu)\n\nUse `blu` to control Bluesound/NAD players.\n\nQuick start\n- `blu devices` (pick target)\n- `blu --device <id> status`\n- `blu play|pause|stop`\n- `blu volume set 15`\n\nTarget selection (in priority order)\n- `--device <id|name|alias>`\n- `BLU_DEVICE` env var\n- config default (if set)\n\nCommon tasks\n- Grouping: `blu group status|add|remove`\n- TuneIn search/play: `blu tunein search "query"`, `blu tunein play "query"`\n\nNotes\n- Prefer `--json` for scripts.\n- Confirm target device before changing playback.\n'},{id:"eightctl",name:"Eight Sleep",emoji:"🎛️",description:"Control Eight Sleep pods (status, temperature, alarms, schedules).",tags:["eightsleep","bed","smarthome"],content:"# eightctl\n\nUse `eightctl` for Eight Sleep pod control. Requires auth.\n\nAuth\n- Config: `~/.config/eightctl/config.yaml`\n- Env: `EIGHTCTL_EMAIL`, `EIGHTCTL_PASSWORD`\n\nQuick start\n- `eightctl status`\n- `eightctl on|off`\n- `eightctl temp 20`\n\nCommon tasks\n- Alarms: `eightctl alarm list|create|dismiss`\n- Schedules: `eightctl schedule list|create|update`\n- Audio: `eightctl audio state|play|pause`\n- Base: `eightctl base info|angle`\n\nNotes\n- API is unofficial and rate-limited; avoid repeated logins.\n- Confirm before changing temperature or alarms.\n"}],Nb=[{id:"spotify-player",name:"Spotify",emoji:"🎵",description:"Terminal Spotify playback/search via spogo (preferred) or spotify_player.",tags:["spotify","music","streaming"],content:'# spogo / spotify_player\n\nUse `spogo` (preferred) for Spotify playback/search.\n\nRequirements\n- Spotify Premium account\n- Either `spogo` or `spotify_player` installed\n\nspogo setup\n- Import cookies: `spogo auth import --browser chrome`\n\nCommon CLI commands\n- Search: `spogo search track "query"`\n- Playback: `spogo play|pause|next|prev`\n- Devices: `spogo device list`, `spogo device set "<name|id>"`\n- Status: `spogo status`\n\nspotify_player commands (fallback)\n- Search: `spotify_player search "query"`\n- Playback: `spotify_player playback play|pause|next|previous`\n- Connect device: `spotify_player connect`\n- Like track: `spotify_player like`\n\nNotes\n- Config folder: `~/.config/spotify-player`\n'},{id:"gifgrep",name:"GIF Search",emoji:"🧲",description:"Search GIF providers with CLI/TUI, download results, and extract stills/sheets.",tags:["gif","images","search"],content:'# gifgrep\n\nUse `gifgrep` to search GIF providers (Tenor/Giphy), browse in TUI, download, and extract stills.\n\nQuick start\n- `gifgrep cats --max 5`\n- `gifgrep cats --format url | head -n 5`\n- `gifgrep search --json cats | jq \'.[0].url\'`\n- `gifgrep tui "office handshake"`\n- `gifgrep cats --download --max 1 --format url`\n\nTUI + previews\n- TUI: `gifgrep tui "query"`\n- CLI still previews: `--thumbs` (Kitty/Ghostty only)\n\nDownload + reveal\n- `--download` saves to ~/Downloads\n- `--reveal` shows in Finder\n\nStills + sheets\n- `gifgrep still ./clip.gif --at 1.5s -o still.png`\n- `gifgrep sheet ./clip.gif --frames 9 --cols 3 -o sheet.png`\n\nProviders\n- `--source auto|tenor|giphy`\n- `GIPHY_API_KEY` required for giphy\n'},{id:"nano-pdf",name:"PDF Editor",emoji:"📄",description:"Edit PDFs with natural-language instructions using the nano-pdf CLI.",tags:["pdf","documents","editing"],content:`# nano-pdf
1677
1677
 
1678
1678
  Use \`nano-pdf\` to apply edits to a PDF using natural-language instructions.
1679
1679
 
@@ -1725,7 +1725,7 @@ peekaboo type "Line 1\\nLine 2" --delay 10
1725
1725
  Notes
1726
1726
  - Requires Screen Recording + Accessibility permissions.
1727
1727
  - Use \`peekaboo see --annotate\` to identify targets before clicking.
1728
- `}],Rb=[{id:"gog",name:"Google Workspace",emoji:"🎮",description:"Google Workspace CLI for Gmail, Calendar, Drive, Contacts, Sheets, and Docs.",tags:["google","gmail","calendar","drive"],content:`# gog
1728
+ `}],Ob=[{id:"gog",name:"Google Workspace",emoji:"🎮",description:"Google Workspace CLI for Gmail, Calendar, Drive, Contacts, Sheets, and Docs.",tags:["google","gmail","calendar","drive"],content:`# gog
1729
1729
 
1730
1730
  Use \`gog\` for Gmail/Calendar/Drive/Contacts/Sheets/Docs. Requires OAuth setup.
1731
1731
 
@@ -1761,8 +1761,8 @@ 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
- `}],Nb=[{id:"messaging",name:"Messaging",icon:"MessageCircle",description:"WhatsApp, iMessage, Slack, and social platforms",skills:kb},{id:"productivity",name:"Productivity",icon:"CheckSquare",description:"Notion, Trello, Things, Reminders, Obsidian",skills:Pb},{id:"development",name:"Development",icon:"Code",description:"GitHub and developer tools",skills:Ab},{id:"smart-home",name:"Smart Home",icon:"Home",description:"Philips Hue, Sonos, BluOS, Eight Sleep",skills:Db},{id:"media",name:"Media & Utilities",icon:"Music",description:"Spotify, GIFs, PDFs, audio visualization, macOS automation",skills:Mb},{id:"google",name:"Google Workspace",icon:"Mail",description:"Gmail, Calendar, Drive, Sheets, Docs",skills:Rb}],xa=()=>Nb.flatMap(i=>i.skills)});var Zu={};Ue(Zu,{skillsStore:()=>Fn});import{EventEmitter as Ob}from"events";var Qu,ka,_b,Ju,$b,Fb,Ea,Ia,Fn,Pa=L(()=>{"use strict";Vu();Xu();ze();V();Yu();Qu="orion-skills-selected",ka="orion-installed-skill-templates",_b=()=>{try{let i=fe.string(ka);if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}},Ju=i=>{fe.set(ka,JSON.stringify(i))},$b=i=>{let e="orion-skills-initialized";if(fe.string(e)&&!fe.string(ka)){let n=xa(),s=i.map(o=>o.toLowerCase()),r=n.filter(o=>s.includes(o.name.toLowerCase())||s.includes(o.id.toLowerCase())).map(o=>o.id);Ju(r),fe.remove(e),u.debug(`[Skills] Migrated to version-based system. Found ${r.length} existing template skills.`)}},Fb=async i=>{$b(i);let e=xa(),t=_b(),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{Lt.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 Ju([...t,...o]),u.info(`[Skills] Sync complete: installed ${r} new skill(s)`),r>0},Ea=(i,e)=>{if(!e||e.trim()==="")return i;let t=e.split(`
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},Ia=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=fe.string(Qu);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}saveSelectedIds(e){fe.set(Qu,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..."),Lt.ensureFolder();let e=Lt.scanFolder(),t=e.map(c=>c.name);await Fb(t)&&(e=Lt.scanFolder());let s=new Date().toISOString(),r=e.map(c=>({id:c.id,name:c.name,description:Ea(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=Lt.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()||Ea(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){Lt.deleteFile(e);let m=Lt.createFile(o,a);if(!m.success)return this.state.isUpdating=null,this.emit("change",this.state),{success:!1,error:m.error}}else{let m=Lt.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()||Ea(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=Lt.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)=>`═══════════════════════════════════════════════════════════════
1764
+ `}],_b=[{id:"messaging",name:"Messaging",icon:"MessageCircle",description:"WhatsApp, iMessage, Slack, and social platforms",skills:Ab},{id:"productivity",name:"Productivity",icon:"CheckSquare",description:"Notion, Trello, Things, Reminders, Obsidian",skills:Db},{id:"development",name:"Development",icon:"Code",description:"GitHub and developer tools",skills:Mb},{id:"smart-home",name:"Smart Home",icon:"Home",description:"Philips Hue, Sonos, BluOS, Eight Sleep",skills:Rb},{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:Ob}],xa=()=>_b.flatMap(i=>i.skills)});var ed={};Ue(ed,{skillsStore:()=>Fn});import{EventEmitter as $b}from"events";var Ju,ka,Fb,Zu,Lb,Ub,Ea,Ia,Fn,Pa=L(()=>{"use strict";Xu();Yu();ze();V();Qu();Ju="orion-skills-selected",ka="orion-installed-skill-templates",Fb=()=>{try{let i=fe.string(ka);if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}},Zu=i=>{fe.set(ka,JSON.stringify(i))},Lb=i=>{let e="orion-skills-initialized";if(fe.string(e)&&!fe.string(ka)){let n=xa(),s=i.map(o=>o.toLowerCase()),r=n.filter(o=>s.includes(o.name.toLowerCase())||s.includes(o.id.toLowerCase())).map(o=>o.id);Zu(r),fe.remove(e),u.debug(`[Skills] Migrated to version-based system. Found ${r.length} existing template skills.`)}},Ub=async i=>{Lb(i);let e=xa(),t=Fb(),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{Lt.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 Zu([...t,...o]),u.info(`[Skills] Sync complete: installed ${r} new skill(s)`),r>0},Ea=(i,e)=>{if(!e||e.trim()==="")return i;let t=e.split(`
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},Ia=class i extends $b{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=fe.string(Ju);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}saveSelectedIds(e){fe.set(Ju,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..."),Lt.ensureFolder();let e=Lt.scanFolder(),t=e.map(c=>c.name);await Ub(t)&&(e=Lt.scanFolder());let s=new Date().toISOString(),r=e.map(c=>({id:c.id,name:c.name,description:Ea(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=Lt.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()||Ea(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){Lt.deleteFile(e);let m=Lt.createFile(o,a);if(!m.success)return this.state.isUpdating=null,this.emit("change",this.state),{success:!1,error:m.error}}else{let m=Lt.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()||Ea(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=Lt.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
  ═══════════════════════════════════════════════════════════════
1768
1768
 
@@ -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)")}},Fn=Ia.getInstance()});var nd={};Ue(nd,{toolPermissionsStore:()=>td,useToolPermissionsStore:()=>Ra});import{EventEmitter as Lb}from"events";import lr from"fs";import ed from"path";import Ub from"os";function Bb(){try{if(!lr.existsSync(Lo))return null;let i=lr.readFileSync(Lo,"utf-8");return JSON.parse(i)}catch(i){return u.error(`[ToolPermissions] Failed to load permissions: ${i}`),null}}function Wb(i){try{let e=ed.dirname(Lo);lr.existsSync(e)||lr.mkdirSync(e,{recursive:!0}),lr.writeFileSync(Lo,JSON.stringify(i,null,2)),u.debug("[ToolPermissions] Saved permissions to file")}catch(e){u.error(`[ToolPermissions] Failed to save permissions: ${e}`)}}var Aa,Da,Lo,Ma,td,Ra,Na=L(()=>{"use strict";V();Aa={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},Da={ListCalls:!0,GetCallRecordings:!0,GetRecentMessages:!0,SendMessage:!0,ScheduleMessage:!0,GetContacts:!0,RunOperatorTask:!0,SearchMemory:!0,StoreMemory:!0,TelegramSend:!0,DiscordSend:!0},Lo=ed.join(Ub.homedir(),".orion","tool-permissions.json");Ma=class i extends Lb{static instance;onDeviceTools;backendTools;lastSyncedAt=null;constructor(){super();let e=Bb();e?(this.onDeviceTools={...Aa,...e.onDeviceTools},this.backendTools={...Da,...e.backendTools},this.lastSyncedAt=e.lastModified,u.debug("[ToolPermissions] Loaded permissions from file")):(this.onDeviceTools={...Aa},this.backendTools={...Da},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={...Aa},this.backendTools={...Da},this.save(),this.emit("permissions_reset")}save(){let e={onDeviceTools:this.onDeviceTools,backendTools:this.backendTools,lastModified:new Date().toISOString()};this.lastSyncedAt=e.lastModified,Wb(e)}getState(){return this}},td=Ma.getInstance(),Ra={getState:()=>td}});var rd={};Ue(rd,{TelegramToolConnectionService:()=>Uo,telegramToolConnectionService:()=>ms});import{ref as sd,onChildAdded as Hb,onChildChanged as Gb,update as jb,off as zb}from"firebase/database";import{io as qb}from"socket.io-client";import{EventEmitter as Kb}from"events";var Uo,ms,Oa=L(()=>{"use strict";V();Ws();Ot();ke();Uo=class i extends Kb{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=Nt.getInstance(),this.setupLogoutListener(),u.debug("[TelegramToolConnection] Service initialized")}setupLogoutListener(){Z.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||Ne.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&&(zb(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=sd(this.database,n);this.listenerRef=s;let r=(c,l)=>{if(!l)return;let d={...l,sessionId:l.sessionId||c};this.handleConnectionRequest(d)},o=Hb(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=Gb(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=qb(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 Z.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((I,E)=>setTimeout(()=>E(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 v=this.formatResultAsContentBlocks(f);if(!e.connected){u.warn("[TelegramToolConnection] Socket disconnected before sending response");return}let T=JSON.stringify(v);if(T.length>1048576){u.warn(`[TelegramToolConnection] Result too large (${T.length} bytes), truncating...`);let I=v.map(E=>E.type==="text"&&E.text&&E.text.length>5e4?{...E,text:E.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)")}},Fn=Ia.getInstance()});var sd={};Ue(sd,{toolPermissionsStore:()=>nd,useToolPermissionsStore:()=>Ra});import{EventEmitter as Bb}from"events";import lr from"fs";import td from"path";import Wb from"os";function Hb(){try{if(!lr.existsSync(Lo))return null;let i=lr.readFileSync(Lo,"utf-8");return JSON.parse(i)}catch(i){return u.error(`[ToolPermissions] Failed to load permissions: ${i}`),null}}function Gb(i){try{let e=td.dirname(Lo);lr.existsSync(e)||lr.mkdirSync(e,{recursive:!0}),lr.writeFileSync(Lo,JSON.stringify(i,null,2)),u.debug("[ToolPermissions] Saved permissions to file")}catch(e){u.error(`[ToolPermissions] Failed to save permissions: ${e}`)}}var Aa,Da,Lo,Ma,nd,Ra,Na=L(()=>{"use strict";V();Aa={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},Da={ListCalls:!0,GetCallRecordings:!0,GetRecentMessages:!0,SendMessage:!0,ScheduleMessage:!0,GetContacts:!0,RunOperatorTask:!0,SearchMemory:!0,StoreMemory:!0,TelegramSend:!0,DiscordSend:!0},Lo=td.join(Wb.homedir(),".orion","tool-permissions.json");Ma=class i extends Bb{static instance;onDeviceTools;backendTools;lastSyncedAt=null;constructor(){super();let e=Hb();e?(this.onDeviceTools={...Aa,...e.onDeviceTools},this.backendTools={...Da,...e.backendTools},this.lastSyncedAt=e.lastModified,u.debug("[ToolPermissions] Loaded permissions from file")):(this.onDeviceTools={...Aa},this.backendTools={...Da},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={...Aa},this.backendTools={...Da},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}},nd=Ma.getInstance(),Ra={getState:()=>nd}});var od={};Ue(od,{TelegramToolConnectionService:()=>Uo,telegramToolConnectionService:()=>ms});import{ref as rd,onChildAdded as jb,onChildChanged as zb,update as qb,off as Kb}from"firebase/database";import{io as Vb}from"socket.io-client";import{EventEmitter as Xb}from"events";var Uo,ms,Oa=L(()=>{"use strict";V();Ws();Ot();ke();Uo=class i extends Xb{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=Nt.getInstance(),this.setupLogoutListener(),u.debug("[TelegramToolConnection] Service initialized")}setupLogoutListener(){Z.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||Ne.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&&(Kb(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=rd(this.database,n);this.listenerRef=s;let r=(c,l)=>{if(!l)return;let d={...l,sessionId:l.sessionId||c};this.handleConnectionRequest(d)},o=jb(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=zb(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=Vb(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 Z.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((I,E)=>setTimeout(()=>E(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 v=this.formatResultAsContentBlocks(f);if(!e.connected){u.warn("[TelegramToolConnection] Socket disconnected before sending response");return}let T=JSON.stringify(v);if(T.length>1048576){u.warn(`[TelegramToolConnection] Result too large (${T.length} bytes), truncating...`);let I=v.map(E=>E.type==="text"&&E.text&&E.text.length>5e4?{...E,text:E.text.slice(0,5e4)+`
1779
1779
 
1780
- ... [TRUNCATED - result too large]`}:E);e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:I,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:v,success:y,error:y?null:f?.error||"Tool execution failed"});let C=Date.now()-g;u.debug(`[TelegramToolConnection] Tool ${l.name} completed in ${C}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(()=>(Pa(),Zu)),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(()=>(oo(),zl)),o=r.shared(),a=o.readDeviceKnowledge();if(a){let c=o.getKnowledgeFilePath();s.device_knowledge_instruction=`Current device knowledge (${c}): ${a}
1780
+ ... [TRUNCATED - result too large]`}:E);e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:I,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:v,success:y,error:y?null:f?.error||"Tool execution failed"});let C=Date.now()-g;u.debug(`[TelegramToolConnection] Tool ${l.name} completed in ${C}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(()=>(Pa(),ed)),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(()=>(oo(),ql)),o=r.shared(),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(()=>(Na(),nd)),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=sd(this.database,n);await jb(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}},ms=Uo.getInstance()});var Vi={};Ue(Vi,{FrontendWebSocketService:()=>Te});import{EventEmitter as Vb}from"events";import{io as Xb}from"socket.io-client";import od from"os";import id from"path";import Ut from"fs";import Yb from"axios";var zt,Te,ls=L(()=>{"use strict";V();Ot();ke();ns();rs();Fi();bl();qu();Ku();zt=id.join(od.homedir(),".orion","pending-tool-results.json"),Te=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;isFlushingPendingResults=!1;TOOL_RESULTS_HTTP_ENDPOINT="https://snowx.ai/api-beta/api/tool-results";capturedScreenshots=[];MAX_CAPTURED_SCREENSHOTS=10;pingLatencies=[];MAX_PING_SAMPLES=10;tokenCounter=new ht;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=Ne.getInstance(),this.authService=Z.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,n),this.toolRegistry=new Fr,zu(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(()=>(Oa(),rd)).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 cr(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=Xb(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.sendReconnectStateSync()}),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("tool_execution_ack",e=>{u.debug(`[FRONTEND WS] Tool execution acknowledged: ${e.toolName||"unknown"} (${e.executionId})`),this.emit("tool_execution_ack",e)}),this.socket.on("server_health_status",e=>{u.debug(`[FRONTEND WS] Server health: ${e.activeConnections} connections, ${e.pendingExecutions} pending, load: ${e.serverLoad||"unknown"}`),this.emit("server_health_status",e)}),this.socket.on("state_sync_response",e=>{u.debug(`[FRONTEND WS] State sync response: ${e.pendingToolsOnServer} pending tools on server`),e.message&&u.debug(`[FRONTEND WS] Server sync message: ${e.message}`),this.emit("state_sync_response",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.pendingToolResults.length>0&&(u.debug(`[FRONTEND WS] Preserving ${this.pendingToolResults.length} pending tool results for reconnection retry`),this.connectionMetrics.failedMessages+=0),this.activeToolExecutions.size>0&&u.debug(`[FRONTEND WS] Warning: ${this.activeToolExecutions.size} active tool executions during disconnect`),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(()=>(Na(),sd)),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=rd(this.database,n);await qb(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}},ms=Uo.getInstance()});var Vi={};Ue(Vi,{FrontendWebSocketService:()=>Te});import{EventEmitter as Yb}from"events";import{io as Qb}from"socket.io-client";import id from"os";import ad from"path";import Ut from"fs";import Jb from"axios";var zt,Te,ls=L(()=>{"use strict";V();Ot();ke();ns();rs();Fi();yl();Ku();Vu();zt=ad.join(id.homedir(),".orion","pending-tool-results.json"),Te=class i extends Yb{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;isFlushingPendingResults=!1;TOOL_RESULTS_HTTP_ENDPOINT="https://snowx.ai/api-beta/api/tool-results";capturedScreenshots=[];MAX_CAPTURED_SCREENSHOTS=10;pingLatencies=[];MAX_PING_SAMPLES=10;tokenCounter=new ht;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=Ne.getInstance(),this.authService=Z.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,n),this.toolRegistry=new Fr,qu(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(()=>(Oa(),od)).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 cr(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=Qb(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.sendReconnectStateSync()}),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("tool_execution_ack",e=>{u.debug(`[FRONTEND WS] Tool execution acknowledged: ${e.toolName||"unknown"} (${e.executionId})`),this.emit("tool_execution_ack",e)}),this.socket.on("server_health_status",e=>{u.debug(`[FRONTEND WS] Server health: ${e.activeConnections} connections, ${e.pendingExecutions} pending, load: ${e.serverLoad||"unknown"}`),this.emit("server_health_status",e)}),this.socket.on("state_sync_response",e=>{u.debug(`[FRONTEND WS] State sync response: ${e.pendingToolsOnServer} pending tools on server`),e.message&&u.debug(`[FRONTEND WS] Server sync message: ${e.message}`),this.emit("state_sync_response",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.pendingToolResults.length>0&&(u.debug(`[FRONTEND WS] Preserving ${this.pendingToolResults.length} pending tool results for reconnection retry`),this.connectionMetrics.failedMessages+=0),this.activeToolExecutions.size>0&&u.debug(`[FRONTEND WS] Warning: ${this.activeToolExecutions.size} active tool executions during disconnect`),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=pt.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")}sendReconnectStateSync(){if(!this.socket?.connected){u.debug("[FRONTEND WS] Cannot send state sync - not connected");return}try{let e=this.activeToolExecutions?Array.from(this.activeToolExecutions.keys()):[],t=this.pendingToolResults?.length??0,n=this.toolExecutionQueue?.length??0,s={timestamp:Date.now(),sessionId:this.sessionId||"",deviceId:this.deviceId||"",activeToolExecutions:e,pendingToolResultsCount:t,toolExecutionQueueLength:n,connectionQuality:this.connectionQuality||"unknown",lastHeartbeat:this.lastHeartbeat?.getTime()||null,lastPongReceived:this.lastPongReceived?.getTime()||null,reconnectAttempts:this.reconnectAttempts??0,totalReconnections:this.connectionMetrics?.totalReconnections??0};this.socket.emit("reconnect_state_sync",s),u.debug(`[FRONTEND WS] Sent state sync after reconnection: ${s.activeToolExecutions.length} active tools, ${s.pendingToolResultsCount} pending results`),t>0&&(u.debug(`[FRONTEND WS] Scheduling flush of ${t} pending tool results after reconnection`),setTimeout(()=>{this.socket?.connected&&this.pendingToolResults?.length>0&&this.flushPendingToolResultsWithFallback()},100))}catch(e){u.error(`[FRONTEND WS] Failed to send state sync: ${e}`)}}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{fl.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 cr(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 Yb.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{Ut.existsSync(zt)&&Ut.unlinkSync(zt)}catch{}return}try{let e={sessionId:this.sessionId,deviceId:this.deviceId,results:this.pendingToolResults,timestamp:new Date().toISOString()},t=id.dirname(zt);Ut.existsSync(t)||Ut.mkdirSync(t,{recursive:!0}),Ut.writeFileSync(zt,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(!Ut.existsSync(zt))return;let e=Ut.readFileSync(zt,"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)");Ut.unlinkSync(zt)}catch(e){u.error(`[FRONTEND WS] Failed to load persisted tool results: ${e}`);try{Ut.existsSync(zt)&&Ut.unlinkSync(zt)}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.isFlushingPendingResults){u.debug("[FRONTEND WS] Flush already in progress, skipping");return}if(!(!this.pendingToolResults||this.pendingToolResults.length===0)){this.isFlushingPendingResults=!0;try{u.debug(`[FRONTEND WS] 🔄 Flushing ${this.pendingToolResults.length} pending tool results with HTTP fallback`);let e=this.pendingToolResults.splice(0,this.pendingToolResults.length);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.length<this.MAX_PENDING_RESULTS?this.pendingToolResults.push(t):u.error(`[FRONTEND WS] Dropping failed result - queue full: ${t.data?.id}`))}this.persistPendingToolResults()}finally{this.isFlushingPendingResults=!1}}}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=pt.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")}sendReconnectStateSync(){if(!this.socket?.connected){u.debug("[FRONTEND WS] Cannot send state sync - not connected");return}try{let e=this.activeToolExecutions?Array.from(this.activeToolExecutions.keys()):[],t=this.pendingToolResults?.length??0,n=this.toolExecutionQueue?.length??0,s={timestamp:Date.now(),sessionId:this.sessionId||"",deviceId:this.deviceId||"",activeToolExecutions:e,pendingToolResultsCount:t,toolExecutionQueueLength:n,connectionQuality:this.connectionQuality||"unknown",lastHeartbeat:this.lastHeartbeat?.getTime()||null,lastPongReceived:this.lastPongReceived?.getTime()||null,reconnectAttempts:this.reconnectAttempts??0,totalReconnections:this.connectionMetrics?.totalReconnections??0};this.socket.emit("reconnect_state_sync",s),u.debug(`[FRONTEND WS] Sent state sync after reconnection: ${s.activeToolExecutions.length} active tools, ${s.pendingToolResultsCount} pending results`),t>0&&(u.debug(`[FRONTEND WS] Scheduling flush of ${t} pending tool results after reconnection`),setTimeout(()=>{this.socket?.connected&&this.pendingToolResults?.length>0&&this.flushPendingToolResultsWithFallback()},100))}catch(e){u.error(`[FRONTEND WS] Failed to send state sync: ${e}`)}}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{bl.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 cr(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 Jb.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{Ut.existsSync(zt)&&Ut.unlinkSync(zt)}catch{}return}try{let e={sessionId:this.sessionId,deviceId:this.deviceId,results:this.pendingToolResults,timestamp:new Date().toISOString()},t=ad.dirname(zt);Ut.existsSync(t)||Ut.mkdirSync(t,{recursive:!0}),Ut.writeFileSync(zt,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(!Ut.existsSync(zt))return;let e=Ut.readFileSync(zt,"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)");Ut.unlinkSync(zt)}catch(e){u.error(`[FRONTEND WS] Failed to load persisted tool results: ${e}`);try{Ut.existsSync(zt)&&Ut.unlinkSync(zt)}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.isFlushingPendingResults){u.debug("[FRONTEND WS] Flush already in progress, skipping");return}if(!(!this.pendingToolResults||this.pendingToolResults.length===0)){this.isFlushingPendingResults=!0;try{u.debug(`[FRONTEND WS] 🔄 Flushing ${this.pendingToolResults.length} pending tool results with HTTP fallback`);let e=this.pendingToolResults.splice(0,this.pendingToolResults.length);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.length<this.MAX_PENDING_RESULTS?this.pendingToolResults.push(t):u.error(`[FRONTEND WS] Dropping failed result - queue full: ${t.data?.id}`))}this.persistPendingToolResults()}finally{this.isFlushingPendingResults=!1}}}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
- 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=od.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(),activeToolCount:this.activeToolExecutions.size,pendingResultsCount:this.pendingToolResults.length,connectionQuality:this.connectionQuality,sessionId:this.sessionId}),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(()=>(It(),Mn)),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 dn,ad=L(()=>{"use strict";dn=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,`
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=id.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(),activeToolCount:this.activeToolExecutions.size,pendingResultsCount:this.pendingToolResults.length,connectionQuality:this.connectionQuality,sessionId:this.sessionId}),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(()=>(It(),Mn)),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 dn,cd=L(()=>{"use strict";dn=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 Qb}from"events";import{promises as Bo}from"fs";import{join as cd}from"path";import{homedir as Jb}from"os";var _a,ur,$a=L(()=>{"use strict";_a=class i extends Qb{static instance;settings;configDir;configPath;constructor(){super(),this.configDir=cd(Jb(),".orion-cli"),this.configPath=cd(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 Bo.mkdir(this.configDir,{recursive:!0});try{let e=await Bo.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 Bo.mkdir(this.configDir,{recursive:!0}),await Bo.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 Zb}from"events";import{promises as Bo}from"fs";import{join as ld}from"path";import{homedir as ey}from"os";var _a,ur,$a=L(()=>{"use strict";_a=class i extends Zb{static instance;settings;configDir;configPath;constructor(){super(),this.configDir=ld(ey(),".orion-cli"),this.configPath=ld(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 Bo.mkdir(this.configDir,{recursive:!0});try{let e=await Bo.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 Bo.mkdir(this.configDir,{recursive:!0}),await Bo.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")}}},ur=_a});var ld=L(()=>{"use strict"});import st from"fs";import gn from"path";import Zb from"os";var ey,Fa,Bt,ud=L(()=>{"use strict";V();ey=/[/\\:*?"<>|]/g,Fa=class i{static instance;guardrailsPath;constructor(){this.guardrailsPath=gn.join(Zb.homedir(),".orion","guardrails")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.guardrailsPath}ensureFolder(){try{return st.existsSync(this.guardrailsPath)||(st.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"}:ey.test(t)?{valid:!1,error:"Guardrail name contains invalid characters"}:gn.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=st.readdirSync(this.guardrailsPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=gn.join(this.guardrailsPath,n);try{if(!st.statSync(s).isFile())continue;let o=st.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=gn.join(this.guardrailsPath,`${s}.md`);try{return this.ensureFolder(),st.existsSync(r)?{success:!1,error:"A guardrail with this name already exists"}:(st.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=gn.join(this.guardrailsPath,`${e}.md`);try{return st.existsSync(s)?(st.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=gn.join(this.guardrailsPath,`${e}.md`);try{return st.existsSync(n)?(st.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=gn.join(this.guardrailsPath,`${e}.md`);try{return st.existsSync(n)?{success:!0,content:st.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=gn.join(this.guardrailsPath,`${e}.md`);return st.existsSync(n)}},Bt=Fa.getInstance()});var ty,ny,sy,ry,oy,iy,dd,gd=L(()=>{"use strict";ty=[{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")}}},ur=_a});var ud=L(()=>{"use strict"});import st from"fs";import gn from"path";import ty from"os";var ny,Fa,Bt,dd=L(()=>{"use strict";V();ny=/[/\\:*?"<>|]/g,Fa=class i{static instance;guardrailsPath;constructor(){this.guardrailsPath=gn.join(ty.homedir(),".orion","guardrails")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.guardrailsPath}ensureFolder(){try{return st.existsSync(this.guardrailsPath)||(st.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"}:ny.test(t)?{valid:!1,error:"Guardrail name contains invalid characters"}:gn.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=st.readdirSync(this.guardrailsPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=gn.join(this.guardrailsPath,n);try{if(!st.statSync(s).isFile())continue;let o=st.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=gn.join(this.guardrailsPath,`${s}.md`);try{return this.ensureFolder(),st.existsSync(r)?{success:!1,error:"A guardrail with this name already exists"}:(st.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=gn.join(this.guardrailsPath,`${e}.md`);try{return st.existsSync(s)?(st.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=gn.join(this.guardrailsPath,`${e}.md`);try{return st.existsSync(n)?(st.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=gn.join(this.guardrailsPath,`${e}.md`);try{return st.existsSync(n)?{success:!0,content:st.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=gn.join(this.guardrailsPath,`${e}.md`);return st.existsSync(n)}},Bt=Fa.getInstance()});var sy,ry,oy,iy,ay,cy,gd,md=L(()=>{"use strict";sy=[{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
 
@@ -1990,7 +1990,7 @@ Always validate and sanitize user input before processing.
1990
1990
  - Whitelist validation (allowed values) is safer than blacklist
1991
1991
  - Validate on both client AND server side
1992
1992
  - Log validation failures for security monitoring
1993
- `}],ny=[{id:"no-console-log-sensitive",name:"No Sensitive Data in Logs",description:"Never log passwords, tokens, or other sensitive data",category:"code_quality",severity:"high",tags:["logging","security","debugging"],content:`# No Sensitive Data in Logs
1993
+ `}],ry=[{id:"no-console-log-sensitive",name:"No Sensitive Data in Logs",description:"Never log passwords, tokens, or other sensitive data",category:"code_quality",severity:"high",tags:["logging","security","debugging"],content:`# No Sensitive Data in Logs
1994
1994
 
1995
1995
  Never log passwords, tokens, or other sensitive data.
1996
1996
 
@@ -2111,7 +2111,7 @@ somePromise.then(result => doSomething(result));
2111
2111
  ## Notes
2112
2112
  - Consider using error boundaries in React
2113
2113
  - Global error handlers are a safety net, not a replacement
2114
- `}],sy=[{id:"no-commit-env-files",name:"No .env Files in Git",description:"Never commit .env files or other secret-containing files to git",category:"git",severity:"critical",tags:["git","secrets","env","gitignore"],content:`# No .env Files in Git
2114
+ `}],oy=[{id:"no-commit-env-files",name:"No .env Files in Git",description:"Never commit .env files or other secret-containing files to git",category:"git",severity:"critical",tags:["git","secrets","env","gitignore"],content:`# No .env Files in Git
2115
2115
 
2116
2116
  Never commit .env files or other secret-containing files to git.
2117
2117
 
@@ -2227,7 +2227,7 @@ git push -f origin master
2227
2227
  - Set up branch protection rules on GitHub/GitLab
2228
2228
  - Never force push to any shared/protected branch
2229
2229
  - If you need to fix main, create a new commit instead
2230
- `}],ry=[{id:"backup-before-destructive",name:"Backup Before Destructive Operations",description:"Always create backups before running destructive database or file operations",category:"data",severity:"high",tags:["data","backup","database","destructive"],content:`# Backup Before Destructive Operations
2230
+ `}],iy=[{id:"backup-before-destructive",name:"Backup Before Destructive Operations",description:"Always create backups before running destructive database or file operations",category:"data",severity:"high",tags:["data","backup","database","destructive"],content:`# Backup Before Destructive Operations
2231
2231
 
2232
2232
  Always create backups before running destructive database or file operations.
2233
2233
 
@@ -2290,7 +2290,7 @@ UPDATE orders SET status = 'cancelled'; -- All orders!
2290
2290
  - In production, require approval for destructive operations
2291
2291
  - Keep backups for at least 30 days
2292
2292
  - Test restore procedures regularly
2293
- `}],oy=[{id:"verify-command-before-run",name:"Verify Commands Before Running",description:"Always verify shell commands before execution, especially destructive ones",category:"tool_misuse",severity:"high",tags:["shell","commands","bash","destructive"],content:`# Verify Commands Before Running
2293
+ `}],ay=[{id:"verify-command-before-run",name:"Verify Commands Before Running",description:"Always verify shell commands before execution, especially destructive ones",category:"tool_misuse",severity:"high",tags:["shell","commands","bash","destructive"],content:`# Verify Commands Before Running
2294
2294
 
2295
2295
  Always verify shell commands before execution, especially destructive ones.
2296
2296
 
@@ -2349,8 +2349,8 @@ 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
- `}],iy=[{id:"security",name:"Security",description:"Prevent security vulnerabilities",guardrails:ty},{id:"code_quality",name:"Code Quality",description:"Maintain code quality standards",guardrails:ny},{id:"git",name:"Git",description:"Prevent git-related mistakes",guardrails:sy},{id:"data",name:"Data",description:"Protect data integrity",guardrails:ry},{id:"tool_misuse",name:"Tool Misuse",description:"Prevent tool misuse errors",guardrails:oy}],dd=()=>iy.flatMap(i=>i.guardrails)});import{EventEmitter as ay}from"events";var md,pd,cy,ly,Ua,Ba,Wa,uy,Ha,ps,hd=L(()=>{"use strict";ld();ud();ze();V();gd();md="orion-guardrails-selected",pd="orion-installed-guardrail-templates",cy=()=>{try{let i=fe.string(pd);if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}},ly=i=>{fe.set(pd,JSON.stringify(i))},Ua=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"},Ba=i=>{let e=i.match(/##\s*Severity\s*\n+[-*]?\s*(critical|high|medium|low)/i);return e?e[1].toLowerCase():"medium"},Wa=(i,e)=>{if(!e||e.trim()==="")return i;let t=e.split(`
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},uy=async i=>{let e=dd(),t=cy(),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{Bt.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 ly([...t,...o]),u.info(`[Guardrails] Sync complete: installed ${r} new guardrail(s)`),r>0},Ha=class i extends ay{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=fe.string(md);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}saveSelectedIds(e){fe.set(md,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..."),Bt.ensureFolder();let e=Bt.scanFolder(),t=e.map(c=>c.name);await uy(t)&&(e=Bt.scanFolder());let s=new Date().toISOString(),r=e.map(c=>({id:c.id,name:c.name,description:Wa(c.name,c.content),content:c.content,category:Ua(c.content),severity:Ba(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=Bt.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()||Wa(o,a),content:a,category:s||Ua(a),severity:r||Ba(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){Bt.deleteFile(e);let h=Bt.createFile(c,l);if(!h.success)return this.state.isUpdating=null,this.emit("change",this.state),{success:!1,error:h.error}}else{let h=Bt.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()||Wa(c,l),content:l,category:r||Ua(l),severity:o||Ba(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=Bt.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)=>`═══════════════════════════════════════════════════════════════
2352
+ `}],cy=[{id:"security",name:"Security",description:"Prevent security vulnerabilities",guardrails:sy},{id:"code_quality",name:"Code Quality",description:"Maintain code quality standards",guardrails:ry},{id:"git",name:"Git",description:"Prevent git-related mistakes",guardrails:oy},{id:"data",name:"Data",description:"Protect data integrity",guardrails:iy},{id:"tool_misuse",name:"Tool Misuse",description:"Prevent tool misuse errors",guardrails:ay}],gd=()=>cy.flatMap(i=>i.guardrails)});import{EventEmitter as ly}from"events";var pd,hd,uy,dy,Ua,Ba,Wa,gy,Ha,ps,fd=L(()=>{"use strict";ud();dd();ze();V();md();pd="orion-guardrails-selected",hd="orion-installed-guardrail-templates",uy=()=>{try{let i=fe.string(hd);if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}},dy=i=>{fe.set(hd,JSON.stringify(i))},Ua=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"},Ba=i=>{let e=i.match(/##\s*Severity\s*\n+[-*]?\s*(critical|high|medium|low)/i);return e?e[1].toLowerCase():"medium"},Wa=(i,e)=>{if(!e||e.trim()==="")return i;let t=e.split(`
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},gy=async i=>{let e=gd(),t=uy(),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{Bt.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 dy([...t,...o]),u.info(`[Guardrails] Sync complete: installed ${r} new guardrail(s)`),r>0},Ha=class i extends ly{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=fe.string(pd);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}saveSelectedIds(e){fe.set(pd,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..."),Bt.ensureFolder();let e=Bt.scanFolder(),t=e.map(c=>c.name);await gy(t)&&(e=Bt.scanFolder());let s=new Date().toISOString(),r=e.map(c=>({id:c.id,name:c.name,description:Wa(c.name,c.content),content:c.content,category:Ua(c.content),severity:Ba(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=Bt.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()||Wa(o,a),content:a,category:s||Ua(a),severity:r||Ba(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){Bt.deleteFile(e);let h=Bt.createFile(c,l);if(!h.success)return this.state.isUpdating=null,this.emit("change",this.state),{success:!1,error:h.error}}else{let h=Bt.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()||Wa(c,l),content:l,category:r||Ua(l),severity:o||Ba(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=Bt.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
  ═══════════════════════════════════════════════════════════════
2356
2356
 
@@ -2371,14 +2371,14 @@ ${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)")}},ps=Ha.getInstance()});import rt from"fs";import mn from"path";import dy from"os";var gy,Ga,pn,fd=L(()=>{"use strict";V();gy=/[/\\:*?"<>|]/g,Ga=class i{static instance;charactersPath;constructor(){this.charactersPath=mn.join(dy.homedir(),".orion","characters")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.charactersPath}ensureFolder(){try{return rt.existsSync(this.charactersPath)||(rt.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"}:gy.test(t)?{valid:!1,error:"Character name contains invalid characters"}:mn.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=rt.readdirSync(this.charactersPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=mn.join(this.charactersPath,n);try{if(!rt.statSync(s).isFile())continue;let o=rt.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=mn.join(this.charactersPath,`${s}.md`);try{return this.ensureFolder(),rt.existsSync(r)?{success:!1,error:"A character with this name already exists"}:(rt.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=mn.join(this.charactersPath,`${e}.md`);try{return rt.existsSync(s)?(rt.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=mn.join(this.charactersPath,`${e}.md`);try{return rt.existsSync(n)?(rt.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=mn.join(this.charactersPath,`${e}.md`);try{return rt.existsSync(n)?{success:!0,content:rt.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=mn.join(this.charactersPath,`${e}.md`);return rt.existsSync(n)}},pn=Ga.getInstance()});import{EventEmitter as my}from"events";var ja,za,Wo,bd=L(()=>{"use strict";fd();ze();V();ja="orion-characters-active",za=class i extends my{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 fe.string(ja)||null}saveActiveId(e){e?fe.set(ja,e):fe.remove(ja)}getState(){return{...this.state}}async loadCharacters(){this.state.isLoading=!0,this.emit("change",this.state);try{u.debug("[Characters] Loading characters from file system..."),pn.ensureFolder();let e=pn.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=pn.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){pn.deleteFile(e);let d=pn.createFile(s,r);if(!d.success)return this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:d.error}}else{let d=pn.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=pn.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)")}},ps=Ha.getInstance()});import rt from"fs";import mn from"path";import my from"os";var py,Ga,pn,bd=L(()=>{"use strict";V();py=/[/\\:*?"<>|]/g,Ga=class i{static instance;charactersPath;constructor(){this.charactersPath=mn.join(my.homedir(),".orion","characters")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.charactersPath}ensureFolder(){try{return rt.existsSync(this.charactersPath)||(rt.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"}:py.test(t)?{valid:!1,error:"Character name contains invalid characters"}:mn.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=rt.readdirSync(this.charactersPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=mn.join(this.charactersPath,n);try{if(!rt.statSync(s).isFile())continue;let o=rt.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=mn.join(this.charactersPath,`${s}.md`);try{return this.ensureFolder(),rt.existsSync(r)?{success:!1,error:"A character with this name already exists"}:(rt.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=mn.join(this.charactersPath,`${e}.md`);try{return rt.existsSync(s)?(rt.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=mn.join(this.charactersPath,`${e}.md`);try{return rt.existsSync(n)?(rt.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=mn.join(this.charactersPath,`${e}.md`);try{return rt.existsSync(n)?{success:!0,content:rt.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=mn.join(this.charactersPath,`${e}.md`);return rt.existsSync(n)}},pn=Ga.getInstance()});import{EventEmitter as hy}from"events";var ja,za,Wo,yd=L(()=>{"use strict";bd();ze();V();ja="orion-characters-active",za=class i extends hy{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 fe.string(ja)||null}saveActiveId(e){e?fe.set(ja,e):fe.remove(ja)}getState(){return{...this.state}}async loadCharacters(){this.state.isLoading=!0,this.emit("change",this.state);try{u.debug("[Characters] Loading characters from file system..."),pn.ensureFolder();let e=pn.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=pn.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){pn.deleteFile(e);let d=pn.createFile(s,r);if(!d.success)return this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:d.error}}else{let d=pn.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=pn.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)")}},Wo=za.getInstance()});var Mn={};Ue(Mn,{PersonalAgentService:()=>Ye});import{EventEmitter as py}from"events";import qa from"axios";import hy from"http";import fy from"https";import{v4 as hn}from"uuid";import fn from"fs";import dr from"path";import Ho from"os";var gr,Ye,It=L(()=>{"use strict";en();ke();ls();ns();Ot();V();ad();$a();Pa();hd();bd();Na();Fo();oo();gr=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"}},Ye=class i extends py{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=Z.getInstance(),this.httpAgent=new hy.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new fy.Agent({keepAlive:!0,timeout:36e5}),u.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout");let e=Te.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([Fn.loadSkills(),ps.loadGuardrails(),Wo.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(fn.existsSync("/etc/os-release")){let n=fn.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=Ho.homedir(),n=ur.getInstance().getWorkingDirectory()||process.cwd();return{userData:dr.join(e,".orion-cli"),downloads:n,temp:Ho.tmpdir()}}async getDeviceKnowledgeInstruction(){try{let e=Ce.getKnowledgeFilePath();this.migrateDeviceKnowledgeIfNeeded(e);let t=Ce.readDeviceKnowledge();return t||(u.debug("[DeviceKnowledge] File not found, creating initial knowledge file..."),await Ce.initializeDeviceKnowledge(),u.debug(`[DeviceKnowledge] Initial knowledge file created at: ${e}`),t=Ce.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)")}},Wo=za.getInstance()});var Mn={};Ue(Mn,{PersonalAgentService:()=>Ye});import{EventEmitter as fy}from"events";import qa from"axios";import by from"http";import yy from"https";import{v4 as hn}from"uuid";import fn from"fs";import dr from"path";import Ho from"os";var gr,Ye,It=L(()=>{"use strict";en();ke();ls();ns();Ot();V();cd();$a();Pa();fd();yd();Na();Fo();oo();gr=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"}},Ye=class i extends fy{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=Z.getInstance(),this.httpAgent=new by.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new yy.Agent({keepAlive:!0,timeout:36e5}),u.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout");let e=Te.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([Fn.loadSkills(),ps.loadGuardrails(),Wo.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(fn.existsSync("/etc/os-release")){let n=fn.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=Ho.homedir(),n=ur.getInstance().getWorkingDirectory()||process.cwd();return{userData:dr.join(e,".orion-cli"),downloads:n,temp:Ho.tmpdir()}}async getDeviceKnowledgeInstruction(){try{let e=Ce.getKnowledgeFilePath();this.migrateDeviceKnowledgeIfNeeded(e);let t=Ce.readDeviceKnowledge();return t||(u.debug("[DeviceKnowledge] File not found, creating initial knowledge file..."),await Ce.initializeDeviceKnowledge(),u.debug(`[DeviceKnowledge] Initial knowledge file created at: ${e}`),t=Ce.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 (${Ce.getKnowledgeFilePath()}): No specific device knowledge available.
2384
2384
 
@@ -2423,27 +2423,27 @@ ${t}
2423
2423
  `,this.currentOutput+=r+`
2424
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=pt.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);let n=t.map(r=>{let o=r.content||r.text||"";return u.debug("[TODO-DEBUG] Processing todo item:",{id:r.id,text:o,status:r.status}),{id:r.id||hn(),content:o,text:o,completed:r.completed||!1,priority:r.priority,status:r.status||(r.completed?"completed":"pending"),activeForm:r.activeForm||o}}),s=new Date(e.timestamp||Date.now());this.currentTodoList={items:n,updatedAt:s.getTime(),todos:n,timestamp:s},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||hn(),taskId:e.taskId||e.id||hn(),sessionId:e.sessionId||hn(),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..."),Te.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=ye.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(),Te.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 re.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 re.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=Ne.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 qa.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})`),Te.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 yd={};Ue(yd,{FirebaseNativeService:()=>mr,TaskMode:()=>Xa,TaskStatus:()=>Ya});import{getDatabase as vy,ref as Va,onChildAdded as Sy,update as wy,set as Ty,serverTimestamp as xy}from"firebase/database";import{EventEmitter as Cy}from"events";var Xa,Ya,mr,Qa=L(()=>{"use strict";V();Ws();Xa=(t=>(t.NEW="new",t.EXISTING="existing",t))(Xa||{}),Ya=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s.QUEUE_FULL="queue_full",s))(Ya||{}),mr=class i extends Cy{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=Nt.getInstance()}setFirebaseInstances(e,t){u.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=vy(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=Va(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=Sy(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(()=>(It(),Mn))).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(()=>(It(),Mn)),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(()=>(It(),Mn)),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=Va(this.database,s),c={status:t,updatedAt:xy()};n&&(c.result=n),await wy(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=Va(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 Ty(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 Ey}from"events";var hs,Ja=L(()=>{"use strict";Ot();ke();Ws();Qa();It();ns();V();hs=class i extends Ey{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=Ne.getInstance(),this.authService=Z.getInstance(),this.firebaseAPI=Nt.getInstance(),this.firebaseNative=mr.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=Ye.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(Ye.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(Ye.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let n=pt.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}`),Ye.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:nn,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 ig={};Ue(ig,{BLOCKED_TYPES:()=>sg,CONVERSION_REQUIRED_TYPES:()=>eg,IMAGE_TYPES:()=>tg,TEXT_TYPES:()=>ng,categorizeFile:()=>uc,getDocumentMimeType:()=>og,getImageMimeType:()=>rg,validateFileSize:()=>Zy});function uc(i){let e=i.split(".").pop()?.toLowerCase()||"";return sg.includes(e)?{type:"blocked",needsConversion:!1,extension:e,mimeType:"application/octet-stream"}:tg.includes(e)?{type:"image",needsConversion:!1,extension:e,mimeType:rg(e)}:eg.includes(e)?{type:"document",needsConversion:!0,extension:e,mimeType:og(e)}:ng.includes(e)?{type:"text",needsConversion:!1,extension:e,mimeType:"text/plain"}:e?{type:"document",needsConversion:!1,extension:e,mimeType:"application/octet-stream"}:{type:"blocked",needsConversion:!1,extension:"",mimeType:"application/octet-stream"}}function rg(i){switch(i){case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"gif":return"image/gif";case"webp":return"image/webp";case"bmp":return"image/bmp";case"tiff":case"tif":return"image/tiff";case"ico":return"image/x-icon";default:return"image/png"}}function og(i){switch(i){case"pdf":return"application/pdf";case"doc":case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"xls":case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"ppt":case"pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case"mp3":return"audio/mpeg";case"mp4":return"video/mp4";case"wav":return"audio/wav";case"m4a":return"audio/mp4";case"txt":case"md":return"text/plain";case"json":return"application/json";case"csv":return"text/csv";case"html":case"htm":return"text/html";default:return"application/octet-stream"}}function Zy(i,e){let n={image:5242880,document:10485760,text:2097152,blocked:0}[e.type];return i>n?{valid:!1,error:`File too large. Max ${e.type} size: ${n/1024/1024}MB`}:{valid:!0}}var eg,tg,ng,sg,dc=L(()=>{"use strict";eg=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav"],tg=["png","jpg","jpeg","gif","webp","bmp","ico","tiff","tif"],ng=["txt","md","markdown","csv","html","htm","svg","js","ts","tsx","jsx","mjs","cjs","py","pyc","pyw","java","class","jar","cpp","c","h","hpp","cc","cxx","cs","vb","rb","php","go","rs","swift","kt","scala","css","scss","sass","less","json","xml","yaml","yml","toml","env","ini","conf","config","cfg","sh","bash","zsh","fish","bat","cmd","ps1","sql","graphql","proto","log"],sg=["exe","dll","sys","drv","com","scr","msi","app","dmg","pkg","vbs","vbe","ws","wsf","wsh","pif","lnk","desktop","url","zip","rar","7z","tar","gz","bz2","xz","iso","db","sqlite","mdb","accdb"]});var Xm={};Ue(Xm,{SnowXStreamHandlerService:()=>jc});import{EventEmitter as WT}from"events";var jc,Ym=L(()=>{"use strict";jc=class extends WT{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 this.reset(),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 re.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 re.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=Ne.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 qa.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})`),Te.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 vd={};Ue(vd,{FirebaseNativeService:()=>mr,TaskMode:()=>Xa,TaskStatus:()=>Ya});import{getDatabase as wy,ref as Va,onChildAdded as Ty,update as xy,set as Cy,serverTimestamp as Ey}from"firebase/database";import{EventEmitter as Iy}from"events";var Xa,Ya,mr,Qa=L(()=>{"use strict";V();Ws();Xa=(t=>(t.NEW="new",t.EXISTING="existing",t))(Xa||{}),Ya=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s.QUEUE_FULL="queue_full",s))(Ya||{}),mr=class i extends Iy{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=Nt.getInstance()}setFirebaseInstances(e,t){u.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=wy(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=Va(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=Ty(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(()=>(It(),Mn))).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(()=>(It(),Mn)),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(()=>(It(),Mn)),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=Va(this.database,s),c={status:t,updatedAt:Ey()};n&&(c.result=n),await xy(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=Va(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 Cy(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 ky}from"events";var hs,Ja=L(()=>{"use strict";Ot();ke();Ws();Qa();It();ns();V();hs=class i extends ky{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=Ne.getInstance(),this.authService=Z.getInstance(),this.firebaseAPI=Nt.getInstance(),this.firebaseNative=mr.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=Ye.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(Ye.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(Ye.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let n=pt.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}`),Ye.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:nn,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 ag={};Ue(ag,{BLOCKED_TYPES:()=>rg,CONVERSION_REQUIRED_TYPES:()=>tg,IMAGE_TYPES:()=>ng,TEXT_TYPES:()=>sg,categorizeFile:()=>uc,getDocumentMimeType:()=>ig,getImageMimeType:()=>og,validateFileSize:()=>tv});function uc(i){let e=i.split(".").pop()?.toLowerCase()||"";return rg.includes(e)?{type:"blocked",needsConversion:!1,extension:e,mimeType:"application/octet-stream"}:ng.includes(e)?{type:"image",needsConversion:!1,extension:e,mimeType:og(e)}:tg.includes(e)?{type:"document",needsConversion:!0,extension:e,mimeType:ig(e)}:sg.includes(e)?{type:"text",needsConversion:!1,extension:e,mimeType:"text/plain"}:e?{type:"document",needsConversion:!1,extension:e,mimeType:"application/octet-stream"}:{type:"blocked",needsConversion:!1,extension:"",mimeType:"application/octet-stream"}}function og(i){switch(i){case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"gif":return"image/gif";case"webp":return"image/webp";case"bmp":return"image/bmp";case"tiff":case"tif":return"image/tiff";case"ico":return"image/x-icon";default:return"image/png"}}function ig(i){switch(i){case"pdf":return"application/pdf";case"doc":case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"xls":case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"ppt":case"pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case"mp3":return"audio/mpeg";case"mp4":return"video/mp4";case"wav":return"audio/wav";case"m4a":return"audio/mp4";case"txt":case"md":return"text/plain";case"json":return"application/json";case"csv":return"text/csv";case"html":case"htm":return"text/html";default:return"application/octet-stream"}}function tv(i,e){let n={image:5242880,document:10485760,text:2097152,blocked:0}[e.type];return i>n?{valid:!1,error:`File too large. Max ${e.type} size: ${n/1024/1024}MB`}:{valid:!0}}var tg,ng,sg,rg,dc=L(()=>{"use strict";tg=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav"],ng=["png","jpg","jpeg","gif","webp","bmp","ico","tiff","tif"],sg=["txt","md","markdown","csv","html","htm","svg","js","ts","tsx","jsx","mjs","cjs","py","pyc","pyw","java","class","jar","cpp","c","h","hpp","cc","cxx","cs","vb","rb","php","go","rs","swift","kt","scala","css","scss","sass","less","json","xml","yaml","yml","toml","env","ini","conf","config","cfg","sh","bash","zsh","fish","bat","cmd","ps1","sql","graphql","proto","log"],rg=["exe","dll","sys","drv","com","scr","msi","app","dmg","pkg","vbs","vbe","ws","wsf","wsh","pif","lnk","desktop","url","zip","rar","7z","tar","gz","bz2","xz","iso","db","sqlite","mdb","accdb"]});var Ym={};Ue(Ym,{SnowXStreamHandlerService:()=>jc});import{EventEmitter as GT}from"events";var jc,Qm=L(()=>{"use strict";jc=class extends GT{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 this.reset(),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 GT}from"events";import jT from"http";import zT from"https";var xi,Qm=L(()=>{"use strict";ke();V();xi=class extends GT{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new jT.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new zT.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=Z.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let n=0;n<t;n++)try{return await e()}catch(s){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(()=>(Ym(),Xm)),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 v=>{let T=v.data,C=v.headers["content-type"]||"",I=E=>{if(E?.index!==void 0){let w=E.index;f.has(w)||f.set(w,{});let S=f.get(w);E.id&&(S.id=E.id,S.type="function"),E.function&&(S.function||(S.function={name:"",arguments:""}),E.function.name&&(S.function.name=E.function.name),E.function.arguments&&(S.function.arguments+=E.function.arguments))}l?.(E),this.emit("tool_call_delta",E)};y.on("streamEnd",()=>{f.forEach((E,w)=>{E.id&&E.function?.name&&h.push(E)}),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(T,C,a||(()=>{}),c,I),f.forEach((E,w)=>{E.id&&E.function?.name&&h.push(E)}),this.emit("done"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})}catch(E){this.emit("error",E),p(E)}}).catch(v=>{v.code==="ERR_CANCELED"?(this.emit("canceled"),m({content:"",toolCalls:h.length>0?h:void 0})):p(v)})})}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 qT}from"socket.io-client";import{EventEmitter as KT}from"events";var Ci,Jm=L(()=>{"use strict";Ot();Ci=class i extends KT{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=Ne.getInstance()}static getInstance(){return 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=qT(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 Zm,ep=L(()=>{"use strict";Zm={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 np={};Ue(np,{ServiceManager:()=>Mr});import{EventEmitter as VT}from"events";import{initializeApp as XT,getApps as tp}from"firebase/app";import{getAuth as YT}from"firebase/auth";var Mr,zc=L(()=>{"use strict";It();Qm();ke();Ot();Jm();ls();Ja();Xr();en();V();ep();Mr=class i extends VT{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=Ye.getInstance(),this.networkClient=new xi,this.authService=Z.getInstance(),this.deviceRegistration=Ne.getInstance(),this.webSocketService=Ci.getInstance(),this.frontendWebSocketService=Te.getInstance(),this.crossDeviceService=hs.getInstance(),this.toolCalling=Vs.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||Zm;if(tp().length===0?(this.firebaseApp=XT(e),u.debug("Firebase app initialized")):(this.firebaseApp=tp()[0],u.debug("Using existing Firebase app")),this.firebaseAuth=YT(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(()=>(Qa(),yd));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=ye[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 ye.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 Xc from"@sentry/node";Xc.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as cx}from"commander";import ZT from"react";import{render as ex}from"@jrichman/ink";import q,{useCallback as UT,useEffect as zm,useMemo as qm,useRef as Gc}from"react";import{Box as Ie,Text as Jt}from"@jrichman/ink";import Km from"ink-spinner";import ki from"terminal-link";import{homedir as cp}from"os";function Yc(i){let e=i.trim();return e.startsWith("~")&&(e=e.replace("~",cp())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function lp(i){return i.startsWith("http://")||i.startsWith("https://")||i.startsWith("mailto:")}function Or(i){let e=i;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,n,s)=>{let r=s;return!lp(s)&&!s.startsWith("file://")&&(s.startsWith("/")||s.startsWith("~")||/\.[a-z]{2,4}$/i.test(s))&&(r=Yc(s)),ki(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:ki(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=Yc(t);return ki(t,r,{fallback:(o,a)=>o})}),e}function _r(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 Qc(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 Jc(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 Pi(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=Or(e),e}function Zc(i){return i.replace(/\[TOOL:[^\]]+\]/g,"").trim()}import Vn from"react";ke();import Hn,{createContext as Gn,useContext as kt,useState as tc,useCallback as nc,useRef as yn,useEffect as vn,useMemo as vs}from"react";import{useApp as Vy}from"@jrichman/ink";It();Yi();import St from"chalk";import by from"ora";var Re=class{static spinner=null;static formatUserMessage(e){return St.cyan("You: ")+e}static formatAssistantMessage(e){return St.green("Assistant: ")+e}static formatError(e){return St.red("Error: ")+e}static formatWarning(e){return St.yellow("Warning: ")+e}static formatInfo(e){return St.blue("Info: ")+e}static formatSuccess(e){return St.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=by(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(St.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(St.bold.cyan(e)),console.log(St.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return St.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return St.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(St.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};V();ns();rs();import{EventEmitter as yy}from"events";import Ka from"chalk";var Go=class extends yy{delegate=null;personalAgentService=Ye.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 jT from"axios";import{EventEmitter as zT}from"events";import qT from"http";import KT from"https";var xi,Jm=L(()=>{"use strict";ke();V();xi=class extends zT{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new qT.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new KT.Agent({keepAlive:!0,timeout:36e5}),this.client=jT.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=Z.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let n=0;n<t;n++)try{return await e()}catch(s){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(()=>(Qm(),Ym)),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 v=>{let T=v.data,C=v.headers["content-type"]||"",I=E=>{if(E?.index!==void 0){let w=E.index;f.has(w)||f.set(w,{});let S=f.get(w);E.id&&(S.id=E.id,S.type="function"),E.function&&(S.function||(S.function={name:"",arguments:""}),E.function.name&&(S.function.name=E.function.name),E.function.arguments&&(S.function.arguments+=E.function.arguments))}l?.(E),this.emit("tool_call_delta",E)};y.on("streamEnd",()=>{f.forEach((E,w)=>{E.id&&E.function?.name&&h.push(E)}),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(T,C,a||(()=>{}),c,I),f.forEach((E,w)=>{E.id&&E.function?.name&&h.push(E)}),this.emit("done"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})}catch(E){this.emit("error",E),p(E)}}).catch(v=>{v.code==="ERR_CANCELED"?(this.emit("canceled"),m({content:"",toolCalls:h.length>0?h:void 0})):p(v)})})}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 XT}from"events";var Ci,Zm=L(()=>{"use strict";Ot();Ci=class i extends XT{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=Ne.getInstance()}static getInstance(){return 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 ep,tp=L(()=>{"use strict";ep={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 sp={};Ue(sp,{ServiceManager:()=>Mr});import{EventEmitter as YT}from"events";import{initializeApp as QT,getApps as np}from"firebase/app";import{getAuth as JT}from"firebase/auth";var Mr,zc=L(()=>{"use strict";It();Jm();ke();Ot();Zm();ls();Ja();Xr();en();V();tp();Mr=class i extends YT{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=Ye.getInstance(),this.networkClient=new xi,this.authService=Z.getInstance(),this.deviceRegistration=Ne.getInstance(),this.webSocketService=Ci.getInstance(),this.frontendWebSocketService=Te.getInstance(),this.crossDeviceService=hs.getInstance(),this.toolCalling=Vs.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||ep;if(np().length===0?(this.firebaseApp=QT(e),u.debug("Firebase app initialized")):(this.firebaseApp=np()[0],u.debug("Using existing Firebase app")),this.firebaseAuth=JT(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(()=>(Qa(),vd));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=ye[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 ye.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 Yc from"@sentry/node";Yc.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as ux}from"commander";import tx from"react";import{render as nx}from"@jrichman/ink";import q,{useCallback as WT,useEffect as qm,useMemo as Km,useRef as Gc}from"react";import{Box as Ie,Text as Jt}from"@jrichman/ink";import Vm from"ink-spinner";import ki from"terminal-link";import{homedir as up}from"os";function Qc(i){let e=i.trim();return e.startsWith("~")&&(e=e.replace("~",up())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function dp(i){return i.startsWith("http://")||i.startsWith("https://")||i.startsWith("mailto:")}function Or(i){let e=i;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,n,s)=>{let r=s;return!dp(s)&&!s.startsWith("file://")&&(s.startsWith("/")||s.startsWith("~")||/\.[a-z]{2,4}$/i.test(s))&&(r=Qc(s)),ki(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:ki(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=Qc(t);return ki(t,r,{fallback:(o,a)=>o})}),e}function _r(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 Jc(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 Zc(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 Pi(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=Or(e),e}function el(i){return i.replace(/\[TOOL:[^\]]+\]/g,"").trim()}import Vn from"react";ke();import Hn,{createContext as Gn,useContext as kt,useState as tc,useCallback as nc,useRef as yn,useEffect as vn,useMemo as vs}from"react";import{useApp as Yy}from"@jrichman/ink";It();Yi();import St from"chalk";import vy from"ora";var Re=class{static spinner=null;static formatUserMessage(e){return St.cyan("You: ")+e}static formatAssistantMessage(e){return St.green("Assistant: ")+e}static formatError(e){return St.red("Error: ")+e}static formatWarning(e){return St.yellow("Warning: ")+e}static formatInfo(e){return St.blue("Info: ")+e}static formatSuccess(e){return St.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=vy(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(St.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(St.bold.cyan(e)),console.log(St.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return St.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return St.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(St.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};V();ns();rs();import{EventEmitter as Sy}from"events";import Ka from"chalk";var Go=class extends Sy{delegate=null;personalAgentService=Ye.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
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 ht,r=e.trim(),o=s.count(r);if(o>ss){console.log(Re.formatError(`Prompt too large (${o.toLocaleString()} tokens). Please reduce it to ${ss.toLocaleString()} tokens or less.`));return}if(this.delegate.isLoading){let l=pt.getInstance();l.addToQueue({content:r,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(Ka.blue(`⚡ Message queued (${l.getQueueCount()} in queue)`)),console.log(Ka.dim(" Your feedback will be sent when AI completes current task"))):console.log(Ka.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let a=null;this.delegate.isVisionEnabled&&(a=await us.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(Re.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,Ye.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||[]}};It();ns();ls();Ja();Fi();V();import{EventEmitter as Iy}from"events";import ky from"axios";import{spawn as Py,execSync as Ay}from"child_process";import vd from"chalk";import Ln from"fs";import Un from"path";import fs from"os";import{getUserAgent as Dy}from"package-manager-detector/detect";import{resolveCommand as My}from"package-manager-detector/commands";var Ry={enabled:!0,checkIntervalMs:1440*60*1e3},Sd=/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.-]+))?(?:\+([a-zA-Z0-9.-]+))?$/,Bn=class i extends Iy{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;config;cacheFilePath;updateCompleted=!1;constructor(e,t){super(),this.currentVersion=e,this.config={...Ry,...t},this.cacheFilePath=Un.join(fs.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?this.isNewerVersion(this.currentVersion,e.latestVersion)?(u.debug("Cache stale: current version newer than cached latest, re-checking"),!0):Date.now()-e.lastCheck>=this.config.checkIntervalMs:!0}loadCache(){try{if(Ln.existsSync(this.cacheFilePath)){let e=Ln.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=Un.dirname(this.cacheFilePath);Ln.existsSync(t)||Ln.mkdirSync(t,{recursive:!0}),Ln.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:Sd.test(e)}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`,n=(await ky.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(Sd);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=Dy();if(e)return u.debug(`Detected package manager from user agent: ${e}`),e;let t=process.argv[1]||"";return[process.env.PNPM_HOME,Un.join(fs.homedir(),".local","share","pnpm"),Un.join(fs.homedir(),"Library","pnpm")].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected pnpm from installation path"),"pnpm"):[Un.join(fs.homedir(),".yarn"),Un.join(fs.homedir(),".config","yarn"),process.env.YARN_GLOBAL_FOLDER].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected yarn from installation path"),"yarn"):[Un.join(fs.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 Ay(`${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=My(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=Py(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}),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 after 120s"),s())},12e4)})}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(vd.green(`
2438
- ✓ Updated to v${e.latestVersion}`)+vd.gray(` - restart CLI to use new version
2439
- `))}}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{Ln.existsSync(this.cacheFilePath)&&Ln.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 wd(){if(process.env.ORION_DEV==="true"||process.env.ORION_DEV==="1")return!0;let i=process.argv[1]||"";return!!(i.endsWith(".ts")&&!i.includes("node_modules")||i.includes("/orion-cli/")&&!i.includes("node_modules"))}import*as bs from"fs/promises";import*as pr from"path";var jo=class{selectedImages=[];selectedDocuments=[];maxImageSize=5*1024*1024;maxDocumentSize=10*1024*1024;maxAttachmentsAllowed=3;async addClipboardImage(e,t){if(this.getTotalCount()>=this.maxAttachmentsAllowed)throw new Error(`Maximum ${this.maxAttachmentsAllowed} attachments allowed`);if(t>this.maxImageSize)throw new Error(`Image too large. Max size: ${this.maxImageSize/1024/1024}MB`);let n=this.detectImageMimeTypeFromDataUrl(e),s={id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,data:e,mimeType:n,size:t,source:"clipboard"};this.selectedImages.push(s)}async addImageFromPath(e){if(this.getTotalCount()>=this.maxAttachmentsAllowed)throw new Error(`Maximum ${this.maxAttachmentsAllowed} attachments allowed`);let t=await bs.stat(e);if(t.size>this.maxImageSize)throw new Error(`Image too large. Max size: ${this.maxImageSize/1024/1024}MB`);let s=(await bs.readFile(e)).toString("base64"),r=pr.extname(e).slice(1).toLowerCase(),o=this.getImageMimeType(r),a=`data:${o};base64,${s}`,c={id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,data:a,mimeType:o,size:t.size,source:"file_path"};this.selectedImages.push(c)}async addDocumentFromPath(e){if(this.getTotalCount()>=this.maxAttachmentsAllowed)throw new Error(`Maximum ${this.maxAttachmentsAllowed} attachments allowed`);let t=await bs.stat(e);if(t.size>this.maxDocumentSize)throw new Error(`Document too large. Max size: ${this.maxDocumentSize/1024/1024}MB`);let s=(await bs.readFile(e)).toString("base64"),r=pr.extname(e).slice(1).toLowerCase(),o=this.getDocumentMimeType(r),a=`data:${o};base64,${s}`,c=pr.basename(e),l={id:`doc-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,fileName:c,filePath:e,data:a,mimeType:o,size:t.size};this.selectedDocuments.push(l)}async addDocumentFromBase64(e,t,n,s){if(this.getTotalCount()>=this.maxAttachmentsAllowed)throw new Error(`Maximum ${this.maxAttachmentsAllowed} attachments allowed`);if(s>this.maxDocumentSize)throw new Error(`Document too large. Max size: ${this.maxDocumentSize/1024/1024}MB`);let r={id:`doc-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,fileName:t,filePath:"",data:e,mimeType:n,size:s};this.selectedDocuments.push(r)}removeImage(e){this.selectedImages=this.selectedImages.filter(t=>t.id!==e)}removeDocument(e){this.selectedDocuments=this.selectedDocuments.filter(t=>t.id!==e)}clearImages(){this.selectedImages=[]}clearDocuments(){this.selectedDocuments=[]}clearAll(){this.selectedImages=[],this.selectedDocuments=[]}getImages(){return[...this.selectedImages]}getDocuments(){return[...this.selectedDocuments]}getTotalCount(){return this.selectedImages.length+this.selectedDocuments.length}hasAttachments(){return this.selectedImages.length>0||this.selectedDocuments.length>0}getRemainingSlots(){return this.maxAttachmentsAllowed-this.getTotalCount()}canAddMore(){return this.getTotalCount()<this.maxAttachmentsAllowed}getMaxAllowed(){return this.maxAttachmentsAllowed}detectImageMimeTypeFromDataUrl(e){let t=e.match(/^data:(image\/[^;]+);base64,(.+)$/);if(!t)return"image/png";let n=t[1],s=t[2];try{let r=Buffer.from(s.substring(0,24),"base64").toString("binary"),o=new Uint8Array(r.length);for(let c=0;c<r.length;c++)o[c]=r.charCodeAt(c);return this.detectImageFormatFromMagicBytes(o)||n}catch{return n}}detectImageFormatFromMagicBytes(e){return e.length<4?null:e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56?"image/gif":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e.length>=12&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e[0]===66&&e[1]===77?"image/bmp":e[0]===73&&e[1]===73&&e[2]===42&&e[3]===0||e[0]===77&&e[1]===77&&e[2]===0&&e[3]===42?"image/tiff":null}getImageMimeType(e){switch(e){case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"gif":return"image/gif";case"webp":return"image/webp";case"bmp":return"image/bmp";case"tiff":case"tif":return"image/tiff";case"ico":return"image/x-icon";default:return"image/png"}}getDocumentMimeType(e){switch(e){case"pdf":return"application/pdf";case"doc":case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"xls":case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"ppt":case"pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case"mp3":return"audio/mpeg";case"mp4":return"video/mp4";case"wav":return"audio/wav";case"m4a":return"audio/mp4";case"txt":case"md":return"text/plain";case"json":return"application/json";case"csv":return"text/csv";case"html":case"htm":return"text/html";default:return"application/octet-stream"}}getDocumentIcon(e){return e.includes("pdf")?"📄":e.includes("word")||e.includes("document")?"📝":e.includes("sheet")||e.includes("excel")?"📊":e.includes("presentation")||e.includes("powerpoint")?"📈":e.includes("audio")?"🎵":e.includes("video")?"🎥":e.includes("text")?"📄":e.includes("json")?"📋":"📎"}};en();ze();Et();V();import bn from"fs";import zo from"path";import Ny from"os";import Td from"crypto";var Za=200,Oy=100,_y=500,ys=class i{static instance;storagePath;state;saveTimeout=null;isDirty=!1;constructor(){let e=zo.join(Ny.homedir(),".orion-cli");this.storagePath=zo.join(e,"conversations.json"),this.state=this.loadState()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadState(){try{if(bn.existsSync(this.storagePath)){let e=bn.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()},_y)}flushPendingSaves(){this.isDirty&&(this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveTimeout=null),this.saveStateImmediate())}saveStateImmediate(){try{let e=zo.dirname(this.storagePath);bn.existsSync(e)||bn.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]);bn.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:Td.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>Za&&(this.state.messages[e]=n.slice(-Za),u.debug(`[STORAGE] Trimmed messages to ${Za} 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||Td.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(`
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,Ye.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||[]}};It();ns();ls();Ja();Fi();V();import{EventEmitter as Py}from"events";import Ay from"axios";import{spawn as Dy,execSync as My}from"child_process";import Sd from"chalk";import Ln from"fs";import Un from"path";import fs from"os";import{getUserAgent as Ry}from"package-manager-detector/detect";import{resolveCommand as Ny}from"package-manager-detector/commands";var Oy={enabled:!0,checkIntervalMs:1440*60*1e3},wd=/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.-]+))?(?:\+([a-zA-Z0-9.-]+))?$/,Bn=class i extends Py{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;config;cacheFilePath;updateCompleted=!1;constructor(e,t){super(),this.currentVersion=e,this.config={...Oy,...t},this.cacheFilePath=Un.join(fs.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?this.isNewerVersion(this.currentVersion,e.latestVersion)?(u.debug("Cache stale: current version newer than cached latest, re-checking"),!0):Date.now()-e.lastCheck>=this.config.checkIntervalMs:!0}loadCache(){try{if(Ln.existsSync(this.cacheFilePath)){let e=Ln.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=Un.dirname(this.cacheFilePath);Ln.existsSync(t)||Ln.mkdirSync(t,{recursive:!0}),Ln.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:wd.test(e)}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`,n=(await Ay.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(wd);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=Ry();if(e)return u.debug(`Detected package manager from user agent: ${e}`),e;let t=process.argv[1]||"";return[process.env.PNPM_HOME,Un.join(fs.homedir(),".local","share","pnpm"),Un.join(fs.homedir(),"Library","pnpm")].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected pnpm from installation path"),"pnpm"):[Un.join(fs.homedir(),".yarn"),Un.join(fs.homedir(),".config","yarn"),process.env.YARN_GLOBAL_FOLDER].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected yarn from installation path"),"yarn"):[Un.join(fs.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 My(`${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=Dy(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}),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 after 120s"),s())},12e4)})}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(Sd.green(`
2438
+ ✓ Updated to v${e.latestVersion}`)+Sd.gray(` - restart CLI to use new version
2439
+ `))}}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{Ln.existsSync(this.cacheFilePath)&&Ln.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 Td(){if(process.env.ORION_DEV==="true"||process.env.ORION_DEV==="1")return!0;let i=process.argv[1]||"";return!!(i.endsWith(".ts")&&!i.includes("node_modules")||i.includes("/orion-cli/")&&!i.includes("node_modules"))}import*as bs from"fs/promises";import*as pr from"path";var jo=class{selectedImages=[];selectedDocuments=[];maxImageSize=5*1024*1024;maxDocumentSize=10*1024*1024;maxAttachmentsAllowed=3;async addClipboardImage(e,t){if(this.getTotalCount()>=this.maxAttachmentsAllowed)throw new Error(`Maximum ${this.maxAttachmentsAllowed} attachments allowed`);if(t>this.maxImageSize)throw new Error(`Image too large. Max size: ${this.maxImageSize/1024/1024}MB`);let n=this.detectImageMimeTypeFromDataUrl(e),s={id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,data:e,mimeType:n,size:t,source:"clipboard"};this.selectedImages.push(s)}async addImageFromPath(e){if(this.getTotalCount()>=this.maxAttachmentsAllowed)throw new Error(`Maximum ${this.maxAttachmentsAllowed} attachments allowed`);let t=await bs.stat(e);if(t.size>this.maxImageSize)throw new Error(`Image too large. Max size: ${this.maxImageSize/1024/1024}MB`);let s=(await bs.readFile(e)).toString("base64"),r=pr.extname(e).slice(1).toLowerCase(),o=this.getImageMimeType(r),a=`data:${o};base64,${s}`,c={id:`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,data:a,mimeType:o,size:t.size,source:"file_path"};this.selectedImages.push(c)}async addDocumentFromPath(e){if(this.getTotalCount()>=this.maxAttachmentsAllowed)throw new Error(`Maximum ${this.maxAttachmentsAllowed} attachments allowed`);let t=await bs.stat(e);if(t.size>this.maxDocumentSize)throw new Error(`Document too large. Max size: ${this.maxDocumentSize/1024/1024}MB`);let s=(await bs.readFile(e)).toString("base64"),r=pr.extname(e).slice(1).toLowerCase(),o=this.getDocumentMimeType(r),a=`data:${o};base64,${s}`,c=pr.basename(e),l={id:`doc-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,fileName:c,filePath:e,data:a,mimeType:o,size:t.size};this.selectedDocuments.push(l)}async addDocumentFromBase64(e,t,n,s){if(this.getTotalCount()>=this.maxAttachmentsAllowed)throw new Error(`Maximum ${this.maxAttachmentsAllowed} attachments allowed`);if(s>this.maxDocumentSize)throw new Error(`Document too large. Max size: ${this.maxDocumentSize/1024/1024}MB`);let r={id:`doc-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,fileName:t,filePath:"",data:e,mimeType:n,size:s};this.selectedDocuments.push(r)}removeImage(e){this.selectedImages=this.selectedImages.filter(t=>t.id!==e)}removeDocument(e){this.selectedDocuments=this.selectedDocuments.filter(t=>t.id!==e)}clearImages(){this.selectedImages=[]}clearDocuments(){this.selectedDocuments=[]}clearAll(){this.selectedImages=[],this.selectedDocuments=[]}getImages(){return[...this.selectedImages]}getDocuments(){return[...this.selectedDocuments]}getTotalCount(){return this.selectedImages.length+this.selectedDocuments.length}hasAttachments(){return this.selectedImages.length>0||this.selectedDocuments.length>0}getRemainingSlots(){return this.maxAttachmentsAllowed-this.getTotalCount()}canAddMore(){return this.getTotalCount()<this.maxAttachmentsAllowed}getMaxAllowed(){return this.maxAttachmentsAllowed}detectImageMimeTypeFromDataUrl(e){let t=e.match(/^data:(image\/[^;]+);base64,(.+)$/);if(!t)return"image/png";let n=t[1],s=t[2];try{let r=Buffer.from(s.substring(0,24),"base64").toString("binary"),o=new Uint8Array(r.length);for(let c=0;c<r.length;c++)o[c]=r.charCodeAt(c);return this.detectImageFormatFromMagicBytes(o)||n}catch{return n}}detectImageFormatFromMagicBytes(e){return e.length<4?null:e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56?"image/gif":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e.length>=12&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e[0]===66&&e[1]===77?"image/bmp":e[0]===73&&e[1]===73&&e[2]===42&&e[3]===0||e[0]===77&&e[1]===77&&e[2]===0&&e[3]===42?"image/tiff":null}getImageMimeType(e){switch(e){case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"gif":return"image/gif";case"webp":return"image/webp";case"bmp":return"image/bmp";case"tiff":case"tif":return"image/tiff";case"ico":return"image/x-icon";default:return"image/png"}}getDocumentMimeType(e){switch(e){case"pdf":return"application/pdf";case"doc":case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"xls":case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"ppt":case"pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case"mp3":return"audio/mpeg";case"mp4":return"video/mp4";case"wav":return"audio/wav";case"m4a":return"audio/mp4";case"txt":case"md":return"text/plain";case"json":return"application/json";case"csv":return"text/csv";case"html":case"htm":return"text/html";default:return"application/octet-stream"}}getDocumentIcon(e){return e.includes("pdf")?"📄":e.includes("word")||e.includes("document")?"📝":e.includes("sheet")||e.includes("excel")?"📊":e.includes("presentation")||e.includes("powerpoint")?"📈":e.includes("audio")?"🎵":e.includes("video")?"🎥":e.includes("text")?"📄":e.includes("json")?"📋":"📎"}};en();ze();Et();V();import bn from"fs";import zo from"path";import _y from"os";import xd from"crypto";var Za=200,$y=100,Fy=500,ys=class i{static instance;storagePath;state;saveTimeout=null;isDirty=!1;constructor(){let e=zo.join(_y.homedir(),".orion-cli");this.storagePath=zo.join(e,"conversations.json"),this.state=this.loadState()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadState(){try{if(bn.existsSync(this.storagePath)){let e=bn.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()},Fy)}flushPendingSaves(){this.isDirty&&(this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveTimeout=null),this.saveStateImmediate())}saveStateImmediate(){try{let e=zo.dirname(this.storagePath);bn.existsSync(e)||bn.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]);bn.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:xd.randomUUID(),title:e,createdAt:t,updatedAt:t,messageCount:0};if(this.state.conversations.length>=$y){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>Za&&(this.state.messages[e]=n.slice(-Za),u.debug(`[STORAGE] Trimmed messages to ${Za} 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||xd.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(`
2440
2440
  `)}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(`
2441
- `)}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=zo.dirname(n);return bn.existsSync(r)||bn.mkdirSync(r,{recursive:!0}),bn.writeFileSync(n,s,"utf8"),u.debug(`[STORAGE] Exported conversation to ${n}`),{success:!0}}catch(s){return{success:!1,error:s.message}}}},ot=ys.getInstance();import $y from"crypto";function Se(){return $y.randomUUID()}function xd(i){return i.content||i.text||"Untitled task"}import{useEffect as Cd,useRef as Wn,useCallback as Ed}from"react";import{v4 as Fy}from"uuid";function Id({personalAgent:i,frontendWS:e,handlers:t}){let n=Wn(""),s=Wn(!0),r=Wn(!1),o=Wn(!1),a=Wn(null),c=100,l=Wn(new Map),d=Wn(t);Cd(()=>{d.current=t});let g=Ed(()=>{if(a.current=null,o.current=!1,!r.current||!s.current)return;r.current=!1;let p=n.current;d.current.onMessagesUpdate(h=>h.map((f,y)=>f.role==="assistant"&&!h.slice(y+1).some(T=>T.role==="assistant")?{...f,content:p}:f))},[]);return Cd(()=>{s.current=!0,n.current="";let p=x=>{d.current.onConversationIdReceived(x)},h=()=>{d.current.onLoadingMessageChange("Processing")},f=x=>{n.current+=x,r.current=!0,o.current||(o.current=!0,a.current=setTimeout(g,c))},y=new Set,v=x=>{let A=typeof x=="string"?x:x.name,O=typeof x=="string"?void 0:x.toolCallId,D=A.toLowerCase().replace(/_/g,"")==="todowrite";d.current.onActiveToolsUpdate($=>{let _=new Map($),F=O||Fy();if(y.has(F))return _;y.add(F),setTimeout(()=>y.delete(F),500);let z=typeof x=="string"?void 0:x.arguments;return _.set(F,{toolCallId:F,name:A,arguments:z,startTime:new Date,state:"running"}),_}),D||d.current.onLoadingMessageChange("Processing")},T=x=>{if(!x||!x.toolName)return;let A;if(x.toolId)A=x.toolId;else{let H=x.arguments?JSON.stringify(x.arguments).slice(0,20):"";A=`${x.toolName}-${H}-${Date.now()}`}let O=`done:${A}`;if(y.has(O))return;y.add(O),setTimeout(()=>y.delete(O),500);let U=x.success===!1||x.error,D=x.error||x.result?.error||"",$=x.arguments,_="";x.result&&(typeof x.result=="string"?_=x.result:Array.isArray(x.result)?_=x.result.map(H=>typeof H=="string"?H:H&&typeof H=="object"?H.text||H.content||JSON.stringify(H):"").join(""):x.result.output?_=typeof x.result.output=="string"?x.result.output:JSON.stringify(x.result.output,null,2):x.result.content?_=x.result.content:_=JSON.stringify(x.result,null,2));let F=_.length>500?_.substring(0,500)+`
2441
+ `)}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=zo.dirname(n);return bn.existsSync(r)||bn.mkdirSync(r,{recursive:!0}),bn.writeFileSync(n,s,"utf8"),u.debug(`[STORAGE] Exported conversation to ${n}`),{success:!0}}catch(s){return{success:!1,error:s.message}}}},ot=ys.getInstance();import Ly from"crypto";function Se(){return Ly.randomUUID()}function Cd(i){return i.content||i.text||"Untitled task"}import{useEffect as Ed,useRef as Wn,useCallback as Id}from"react";import{v4 as Uy}from"uuid";function kd({personalAgent:i,frontendWS:e,handlers:t}){let n=Wn(""),s=Wn(!0),r=Wn(!1),o=Wn(!1),a=Wn(null),c=100,l=Wn(new Map),d=Wn(t);Ed(()=>{d.current=t});let g=Id(()=>{if(a.current=null,o.current=!1,!r.current||!s.current)return;r.current=!1;let p=n.current;d.current.onMessagesUpdate(h=>h.map((f,y)=>f.role==="assistant"&&!h.slice(y+1).some(T=>T.role==="assistant")?{...f,content:p}:f))},[]);return Ed(()=>{s.current=!0,n.current="";let p=x=>{d.current.onConversationIdReceived(x)},h=()=>{d.current.onLoadingMessageChange("Processing")},f=x=>{n.current+=x,r.current=!0,o.current||(o.current=!0,a.current=setTimeout(g,c))},y=new Set,v=x=>{let A=typeof x=="string"?x:x.name,O=typeof x=="string"?void 0:x.toolCallId,D=A.toLowerCase().replace(/_/g,"")==="todowrite";d.current.onActiveToolsUpdate($=>{let _=new Map($),F=O||Uy();if(y.has(F))return _;y.add(F),setTimeout(()=>y.delete(F),500);let z=typeof x=="string"?void 0:x.arguments;return _.set(F,{toolCallId:F,name:A,arguments:z,startTime:new Date,state:"running"}),_}),D||d.current.onLoadingMessageChange("Processing")},T=x=>{if(!x||!x.toolName)return;let A;if(x.toolId)A=x.toolId;else{let H=x.arguments?JSON.stringify(x.arguments).slice(0,20):"";A=`${x.toolName}-${H}-${Date.now()}`}let O=`done:${A}`;if(y.has(O))return;y.add(O),setTimeout(()=>y.delete(O),500);let U=x.success===!1||x.error,D=x.error||x.result?.error||"",$=x.arguments,_="";x.result&&(typeof x.result=="string"?_=x.result:Array.isArray(x.result)?_=x.result.map(H=>typeof H=="string"?H:H&&typeof H=="object"?H.text||H.content||JSON.stringify(H):"").join(""):x.result.output?_=typeof x.result.output=="string"?x.result.output:JSON.stringify(x.result.output,null,2):x.result.content?_=x.result.content:_=JSON.stringify(x.result,null,2));let F=_.length>500?_.substring(0,500)+`
2442
2442
  ...(truncated)`:_,z=`<context>
2443
2443
  ${_}
2444
2444
  </context>`,G=U?"failed":"completed",M={current:A};d.current.onActiveToolsUpdate(H=>{let B=new Map(H),j=A;if(!B.has(A)){let ne=null;for(let[pe,ue]of B.entries())ue.name===x.toolName&&ue.state==="running"&&(!ne||ue.startTime>ne)&&(ne=ue.startTime,j=pe)}if(M.current=j,B.has(j)){let ne=B.get(j);B.set(j,{...ne,arguments:ne.arguments||$,state:G,output:F,error:U?D:void 0})}else B.set(j,{toolCallId:j,name:x.toolName,arguments:$,startTime:new Date,state:G,output:F,error:U?D:void 0});return B});let R=setTimeout(()=>{l.current.delete(M.current),d.current.onActiveToolsUpdate(H=>{let B=new Map(H);return B.delete(M.current),B})},1500);l.current.set(M.current,R),d.current.onMessagesUpdate(H=>H.map((B,j)=>{if(B.role==="assistant"&&!H.slice(j+1).some(pe=>pe.role==="assistant")){let pe=B.metadata?.toolResults,ue=!pe?.includes(z);return{...B,metadata:{...B.metadata,toolResults:ue?pe?pe+`
2445
- `+z:z:pe}}}return B}))},C=x=>{!x||!x.toolCallId||d.current.onActiveToolsUpdate(A=>{let O=new Map(A),U=O.get(x.toolCallId);return U&&O.set(x.toolCallId,{...U,arguments:x.arguments}),O})},I=()=>{for(let[x,A]of l.current.entries())clearTimeout(A);if(l.current.clear(),y.clear(),r.current){r.current=!1,o.current=!1;let x=n.current;d.current.onMessagesUpdate(A=>A.map((O,U)=>O.role==="assistant"&&!A.slice(U+1).some($=>$.role==="assistant")?{...O,content:x}:O))}d.current.onLoadingChange(!1),d.current.onActiveToolsUpdate(()=>new Map),n.current=""},E=x=>{d.current.onError(x.message||"Unknown error"),d.current.onLoadingChange(!1),d.current.onActiveToolsUpdate(()=>new Map),n.current=""},w=x=>{d.current.onConfirmationRequest({id:x.confirmationId,type:x.type,title:x.title,message:x.message,command:x.command,targets:x.targets,isDestructive:x.isDestructive,timeout:x.isDestructive?x.timeout||3e4:void 0})},S=x=>{if(!x||!Array.isArray(x.todos))return;let A=x.todos.filter(O=>O&&typeof O.id=="string"&&typeof O.content=="string"&&typeof O.status=="string"&&["pending","in_progress","completed"].includes(O.status));A.length===0&&x.todos.length>0||d.current.onTodoUpdate({...x,todos:A.length>0?A:x.todos})},P=x=>{d.current.onCompactionStatus({status:x.status,originalTokens:x.originalTokens,compactedTokens:x.compactedTokens,compressionRatio:x.compressionRatio,message:x.message,error:x.error,timestamp:new Date})};return i.on("conversation_id_received",p),i.on("thinking",h),i.on("data",f),i.on("toolExecuting",v),i.on("tool_completed",T),i.on("tool_args_update",C),i.on("done",I),i.on("error",E),i.on("confirmation_request",w),i.on("todo_update",S),i.on("compaction_status",P),()=>{s.current=!1,a.current&&(clearTimeout(a.current),a.current=null);for(let[x,A]of l.current.entries())clearTimeout(A);l.current.clear(),i.off("conversation_id_received",p),i.off("thinking",h),i.off("data",f),i.off("toolExecuting",v),i.off("tool_completed",T),i.off("tool_args_update",C),i.off("done",I),i.off("error",E),i.off("confirmation_request",w),i.off("todo_update",S),i.off("compaction_status",P)}},[i,e,g]),{resetContent:Ed(()=>{n.current=""},[])}}import{useState as Ly,useEffect as kd,useCallback as Pd,useMemo as Ad,useRef as ec}from"react";function Dd({queueManager:i,frontendWS:e,crossDevice:t,isLoading:n,selectedModel:s,onCrossDeviceTask:r}){let[o,a]=Ly([]),c=ec(n),l=ec(s),d=ec(r);kd(()=>{c.current=n,l.current=s,d.current=r},[n,s,r]);let g=Ad(()=>o.filter(y=>!y.isCrossDeviceTask),[o]),m=Ad(()=>o.filter(y=>y.isCrossDeviceTask),[o]),p=o.length>0,h=Pd((y,v=[])=>i.addToQueue({content:y,imageUrls:v,attachments:[],model:l.current.name}),[i]),f=Pd(()=>{if(!i.hasQueuedMessages())return null;let y=i.processNextMessage();return y&&i.startProcessing(),y},[i]);return kd(()=>{let y=C=>{a(C)},v=()=>{},T=C=>{if(c.current){i.addToQueue({content:C.prompt,imageUrls:[],attachments:[],model:l.current.name,isCrossDeviceTask:!0,crossDeviceTaskId:C.taskId})||d.current(C.taskId,"");return}d.current(C.taskId,C.prompt)};return i.on("queue:updated",y),e.on("feedback:sent",v),t.on("CrossDeviceTaskSendMessage",T),()=>{i.off("queue:updated",y),e.off("feedback:sent",v),t.off("CrossDeviceTaskSendMessage",T)}},[i,e,t]),{queuedMessages:o,regularQueuedMessages:g,crossDeviceTasks:m,addToQueue:h,processNextMessage:f,hasQueuedMessages:p}}import{useState as Uy,useEffect as By,useRef as Wy}from"react";function Md({subAgentManager:i}){let[e,t]=Uy(new Map),n=Wy(null);return By(()=>{let s=()=>{t(new Map(i.getOperations()))},r=()=>{n.current||(n.current=setTimeout(()=>{n.current=null,t(new Map(i.getOperations()))},200))};return i.on("spawn_started",s),i.on("agent_started",s),i.on("agent_completed",s),i.on("spawn_completed",s),i.on("agent_streaming",r),i.on("progress",r),()=>{n.current&&(clearTimeout(n.current),n.current=null),i.off("spawn_started",s),i.off("agent_started",s),i.off("agent_completed",s),i.off("spawn_completed",s),i.off("agent_streaming",r),i.off("progress",r)}},[i]),{subAgentOperations:e}}Oa();import{useEffect as Hy,useState as Gy,useRef as jy,useCallback as zy}from"react";function Rd({frontendWS:i}){let[e,t]=Gy(null),n=jy(null);Hy(()=>{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),ms.on("external_session_started",r),ms.on("external_session_ended",o),()=>{i.off("external_session_started",r),i.off("external_session_ended",o),ms.off("external_session_started",r),ms.off("external_session_ended",o),n.current=null}},[i]);let s=zy(()=>{n.current=null,t(null)},[]);return{externalSession:e,clearSession:s,hasActiveSession:e!==null}}import{useState as qy,useEffect as Nd,useRef as Ky}from"react";function Od(){let[i,e]=qy(null),t=Ky(null);return Nd(()=>{t.current=i},[i]),Nd(()=>{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=i,a=setTimeout(()=>{e(c=>c===o?null:c),t.current===o&&(t.current=null)},3e3);return()=>clearTimeout(a)}},[i]),{todoList:i,setTodoList:e,todoListRef:t}}var _d=Gn(null),$d=Gn(null),Fd=Gn(null),Ld=Gn(null),Ud=Gn(null),Bd=Gn(null),qt=Gn(null),Ss={main:i=>`Orion ready
2446
- 📁 ${i}`,clear:()=>"Fresh start",newConversation:()=>"New conversation",continueConversation:()=>"Welcome back",deleted:()=>"Conversation cleared"};function sc({children:i,initialProjectPath:e,version:t}){let n=e||process.cwd(),{exit:s}=Vy(),[r]=tc(()=>new jo),o=vs(()=>({authService:Z.getInstance(),personalAgent:Ye.getInstance(),queueManager:pt.getInstance(),frontendWS:Te.getInstance(),crossDevice:hs.getInstance(),subAgentManager:js.getInstance(),attachmentManager:r}),[r]);vn(()=>(ee.enableCustomUI(),()=>ee.disableCustomUI()),[]);let a=vs(()=>ye.find(M=>M.name===fe.string("selectedPersonalModel"))||ye.find(M=>M.name==="snowx-c5")||ye[0],[]),[c,l]=tc(()=>{let M=ot.getConversations(),R=ot.getCurrentConversation();return{messages:[{id:Se(),role:"system",content:Ss.main(n),timestamp:Date.now()}],conversationId:R?.id||null,conversationTitleGenerated:!1,isLoading:!1,loadingMessage:"Processing",activeTools:new Map,subAgentOperations:new Map,externalSession:null,pendingConfirmation:null,todoList:null,compactionStatus:null,conversations:M,staticRemountKey:0}}),d=yn(c.isLoading),g=yn(c.messages),m=yn(c.conversationId),p=yn(c.pendingConfirmation),h=yn(null),f=yn(a),y=yn(!1);vn(()=>{d.current=c.isLoading,g.current=c.messages,m.current=c.conversationId,p.current=c.pendingConfirmation},[c.isLoading,c.messages,c.conversationId,c.pendingConfirmation]);let{todoList:v,setTodoList:T,todoListRef:C}=Od();vn(()=>{if(process.env.MOCK_MESSAGES!=="true")return;let M=setTimeout(()=>{let H=[{id:Se(),role:"system",content:Ss.main("/mock/project"),timestamp:Date.now()},{id:Se(),role:"user",content:"Show me all UI components for testing the chatbox",timestamp:Date.now()+100},{id:Se(),role:"assistant",content:`## Heading Level 2
2445
+ `+z:z:pe}}}return B}))},C=x=>{!x||!x.toolCallId||d.current.onActiveToolsUpdate(A=>{let O=new Map(A),U=O.get(x.toolCallId);return U&&O.set(x.toolCallId,{...U,arguments:x.arguments}),O})},I=()=>{for(let[x,A]of l.current.entries())clearTimeout(A);if(l.current.clear(),y.clear(),r.current){r.current=!1,o.current=!1;let x=n.current;d.current.onMessagesUpdate(A=>A.map((O,U)=>O.role==="assistant"&&!A.slice(U+1).some($=>$.role==="assistant")?{...O,content:x}:O))}d.current.onLoadingChange(!1),d.current.onActiveToolsUpdate(()=>new Map),n.current=""},E=x=>{d.current.onError(x.message||"Unknown error"),d.current.onLoadingChange(!1),d.current.onActiveToolsUpdate(()=>new Map),n.current=""},w=x=>{d.current.onConfirmationRequest({id:x.confirmationId,type:x.type,title:x.title,message:x.message,command:x.command,targets:x.targets,isDestructive:x.isDestructive,timeout:x.isDestructive?x.timeout||3e4:void 0})},S=x=>{if(!x||!Array.isArray(x.todos))return;let A=x.todos.filter(O=>O&&typeof O.id=="string"&&typeof O.content=="string"&&typeof O.status=="string"&&["pending","in_progress","completed"].includes(O.status));A.length===0&&x.todos.length>0||d.current.onTodoUpdate({...x,todos:A.length>0?A:x.todos})},P=x=>{d.current.onCompactionStatus({status:x.status,originalTokens:x.originalTokens,compactedTokens:x.compactedTokens,compressionRatio:x.compressionRatio,message:x.message,error:x.error,timestamp:new Date})};return i.on("conversation_id_received",p),i.on("thinking",h),i.on("data",f),i.on("toolExecuting",v),i.on("tool_completed",T),i.on("tool_args_update",C),i.on("done",I),i.on("error",E),i.on("confirmation_request",w),i.on("todo_update",S),i.on("compaction_status",P),()=>{s.current=!1,a.current&&(clearTimeout(a.current),a.current=null);for(let[x,A]of l.current.entries())clearTimeout(A);l.current.clear(),i.off("conversation_id_received",p),i.off("thinking",h),i.off("data",f),i.off("toolExecuting",v),i.off("tool_completed",T),i.off("tool_args_update",C),i.off("done",I),i.off("error",E),i.off("confirmation_request",w),i.off("todo_update",S),i.off("compaction_status",P)}},[i,e,g]),{resetContent:Id(()=>{n.current=""},[])}}import{useState as By,useEffect as Pd,useCallback as Ad,useMemo as Dd,useRef as ec}from"react";function Md({queueManager:i,frontendWS:e,crossDevice:t,isLoading:n,selectedModel:s,onCrossDeviceTask:r}){let[o,a]=By([]),c=ec(n),l=ec(s),d=ec(r);Pd(()=>{c.current=n,l.current=s,d.current=r},[n,s,r]);let g=Dd(()=>o.filter(y=>!y.isCrossDeviceTask),[o]),m=Dd(()=>o.filter(y=>y.isCrossDeviceTask),[o]),p=o.length>0,h=Ad((y,v=[])=>i.addToQueue({content:y,imageUrls:v,attachments:[],model:l.current.name}),[i]),f=Ad(()=>{if(!i.hasQueuedMessages())return null;let y=i.processNextMessage();return y&&i.startProcessing(),y},[i]);return Pd(()=>{let y=C=>{a(C)},v=()=>{},T=C=>{if(c.current){i.addToQueue({content:C.prompt,imageUrls:[],attachments:[],model:l.current.name,isCrossDeviceTask:!0,crossDeviceTaskId:C.taskId})||d.current(C.taskId,"");return}d.current(C.taskId,C.prompt)};return i.on("queue:updated",y),e.on("feedback:sent",v),t.on("CrossDeviceTaskSendMessage",T),()=>{i.off("queue:updated",y),e.off("feedback:sent",v),t.off("CrossDeviceTaskSendMessage",T)}},[i,e,t]),{queuedMessages:o,regularQueuedMessages:g,crossDeviceTasks:m,addToQueue:h,processNextMessage:f,hasQueuedMessages:p}}import{useState as Wy,useEffect as Hy,useRef as Gy}from"react";function Rd({subAgentManager:i}){let[e,t]=Wy(new Map),n=Gy(null);return Hy(()=>{let s=()=>{t(new Map(i.getOperations()))},r=()=>{n.current||(n.current=setTimeout(()=>{n.current=null,t(new Map(i.getOperations()))},200))};return i.on("spawn_started",s),i.on("agent_started",s),i.on("agent_completed",s),i.on("spawn_completed",s),i.on("agent_streaming",r),i.on("progress",r),()=>{n.current&&(clearTimeout(n.current),n.current=null),i.off("spawn_started",s),i.off("agent_started",s),i.off("agent_completed",s),i.off("spawn_completed",s),i.off("agent_streaming",r),i.off("progress",r)}},[i]),{subAgentOperations:e}}Oa();import{useEffect as jy,useState as zy,useRef as qy,useCallback as Ky}from"react";function Nd({frontendWS:i}){let[e,t]=zy(null),n=qy(null);jy(()=>{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),ms.on("external_session_started",r),ms.on("external_session_ended",o),()=>{i.off("external_session_started",r),i.off("external_session_ended",o),ms.off("external_session_started",r),ms.off("external_session_ended",o),n.current=null}},[i]);let s=Ky(()=>{n.current=null,t(null)},[]);return{externalSession:e,clearSession:s,hasActiveSession:e!==null}}import{useState as Vy,useEffect as Od,useRef as Xy}from"react";function _d(){let[i,e]=Vy(null),t=Xy(null);return Od(()=>{t.current=i},[i]),Od(()=>{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=i,a=setTimeout(()=>{e(c=>c===o?null:c),t.current===o&&(t.current=null)},3e3);return()=>clearTimeout(a)}},[i]),{todoList:i,setTodoList:e,todoListRef:t}}var $d=Gn(null),Fd=Gn(null),Ld=Gn(null),Ud=Gn(null),Bd=Gn(null),Wd=Gn(null),qt=Gn(null),Ss={main:i=>`Orion ready
2446
+ 📁 ${i}`,clear:()=>"Fresh start",newConversation:()=>"New conversation",continueConversation:()=>"Welcome back",deleted:()=>"Conversation cleared"};function sc({children:i,initialProjectPath:e,version:t}){let n=e||process.cwd(),{exit:s}=Yy(),[r]=tc(()=>new jo),o=vs(()=>({authService:Z.getInstance(),personalAgent:Ye.getInstance(),queueManager:pt.getInstance(),frontendWS:Te.getInstance(),crossDevice:hs.getInstance(),subAgentManager:js.getInstance(),attachmentManager:r}),[r]);vn(()=>(ee.enableCustomUI(),()=>ee.disableCustomUI()),[]);let a=vs(()=>ye.find(M=>M.name===fe.string("selectedPersonalModel"))||ye.find(M=>M.name==="snowx-c5")||ye[0],[]),[c,l]=tc(()=>{let M=ot.getConversations(),R=ot.getCurrentConversation();return{messages:[{id:Se(),role:"system",content:Ss.main(n),timestamp:Date.now()}],conversationId:R?.id||null,conversationTitleGenerated:!1,isLoading:!1,loadingMessage:"Processing",activeTools:new Map,subAgentOperations:new Map,externalSession:null,pendingConfirmation:null,todoList:null,compactionStatus:null,conversations:M,staticRemountKey:0}}),d=yn(c.isLoading),g=yn(c.messages),m=yn(c.conversationId),p=yn(c.pendingConfirmation),h=yn(null),f=yn(a),y=yn(!1);vn(()=>{d.current=c.isLoading,g.current=c.messages,m.current=c.conversationId,p.current=c.pendingConfirmation},[c.isLoading,c.messages,c.conversationId,c.pendingConfirmation]);let{todoList:v,setTodoList:T,todoListRef:C}=_d();vn(()=>{if(process.env.MOCK_MESSAGES!=="true")return;let M=setTimeout(()=>{let H=[{id:Se(),role:"system",content:Ss.main("/mock/project"),timestamp:Date.now()},{id:Se(),role:"user",content:"Show me all UI components for testing the chatbox",timestamp:Date.now()+100},{id:Se(),role:"assistant",content:`## Heading Level 2
2447
2447
 
2448
2448
  ### Heading Level 3
2449
2449
 
@@ -2518,12 +2518,12 @@ This response has multiple paragraphs to take up more space.
2518
2518
 
2519
2519
  - Item 1
2520
2520
  - Item 2
2521
- - Item 3`,timestamp:Date.now()+600+pe*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},j=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"}]]);l(ne=>({...ne,messages:H,todoList:B,activeTools:j,isLoading:!0,loadingMessage:"Processing mock request..."}))},500);return()=>clearTimeout(M)},[]);let[I]=tc(()=>{let M={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:a,isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new Go(M)});vn(()=>{let M=g.current.map(R=>({role:R.role,content:R.content,timestamp:new Date(R.timestamp||Date.now()),...R.tool&&{tool:R.tool},...R.toolOutput&&{toolOutput:R.toolOutput}}));I.setDelegate({messages:M,fullConversationHistory:M,isLoading:c.isLoading,currentInput:"",selectedModel:f.current,isVisionEnabled:y.current,conversationId:c.conversationId,usesCustomUI:!0,updateCurrentConversation:()=>{}})},[c.isLoading,c.conversationId,I]);let E=yn(null),w=nc(async(M,R=[])=>{if(Bn.getExistingInstance()?.checkAndUpdate().catch(()=>{}),d.current){o.queueManager.addToQueue({content:M,imageUrls:R,attachments:[],model:f.current.name})||l(ct=>({...ct,messages:[...ct.messages,{id:Se(),role:"system",content:"[!] Queue is full (max 5 messages). Your input was not saved.",timestamp:Date.now()}]}));return}let H=Date.now(),B={id:Se(),role:"user",content:M,timestamp:H},j={id:Se(),role:"assistant",content:"",timestamp:H+1},ne=[...g.current,B,j];l(ue=>({...ue,messages:ne,isLoading:!0,loadingMessage:"Processing"}));let pe=ne.map(ue=>({role:ue.role,content:ue.content,timestamp:new Date(ue.timestamp||Date.now()),...ue.tool&&{tool:ue.tool},...ue.toolOutput&&{toolOutput:ue.toolOutput}}));I.setDelegate({messages:pe,fullConversationHistory:pe,isLoading:!1,currentInput:"",selectedModel:f.current,isVisionEnabled:y.current,conversationId:m.current,usesCustomUI:!0,updateCurrentConversation:()=>{}});try{await I.sendMessage(M,R.length>0?R:void 0),r.clearAll()}catch(ue){l(ct=>({...ct,messages:[...ct.messages,{id:Se(),role:"system",content:`Error: ${ue.message}`,timestamp:Date.now()}],isLoading:!1}))}},[o.queueManager,I]);E.current=w;let S=vs(()=>({onConversationIdReceived:M=>{l(R=>({...R,conversationId:M.conversationId,conversationTitleGenerated:!!M.title}))},onMessagesUpdate:M=>{l(R=>({...R,messages:M(R.messages)}))},onActiveToolsUpdate:M=>{l(R=>({...R,activeTools:M(R.activeTools)}))},onLoadingChange:M=>{if(l(R=>({...R,isLoading:M,activeTools:M?R.activeTools:new Map,subAgentOperations:M?R.subAgentOperations:new Map})),!M){let R=C.current;R&&R.todos.some(B=>B.status!=="completed")&&T(null)}},onLoadingMessageChange:M=>{l(R=>({...R,loadingMessage:M}))},onTodoUpdate:M=>{T(M)},onConfirmationRequest:M=>{l(R=>({...R,pendingConfirmation:M}))},onCompactionStatus:M=>{l(R=>({...R,compactionStatus:M})),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null,l(R=>R.compactionStatus===M?{...R,compactionStatus:null}:R)},8e3)},onError:M=>{l(R=>({...R,messages:[...R.messages,{id:Se(),role:"system",content:`Error: ${M}`,timestamp:Date.now()}],isLoading:!1,activeTools:new Map,subAgentOperations:new Map}))}}),[T]);Id({personalAgent:o.personalAgent,frontendWS:o.frontendWS,handlers:S});let{regularQueuedMessages:P,crossDeviceTasks:x,processNextMessage:A,hasQueuedMessages:O}=Dd({queueManager:o.queueManager,frontendWS:o.frontendWS,crossDevice:o.crossDevice,isLoading:c.isLoading,selectedModel:f.current,onCrossDeviceTask:(M,R)=>{R&&E.current?.(R)}}),{subAgentOperations:U}=Md({subAgentManager:o.subAgentManager});vn(()=>{let M=Bn.getExistingInstance();if(!M)return;let R=H=>{l(B=>({...B,messages:[...B.messages,{id:Se(),role:"system",content:`[UPDATE] Orion updated v${H.from} -> v${H.to}. Restart to use the new version.`,timestamp:Date.now()}]}))};return M.on("updated",R),()=>{M.off("updated",R),h.current&&clearTimeout(h.current)}},[]);let{externalSession:D}=Rd({frontendWS:o.frontendWS});vn(()=>{l(M=>({...M,subAgentOperations:U,externalSession:D,todoList:v}))},[U,D,v]),vn(()=>{if(!c.isLoading&&O){let M=A();M&&E.current?.(M.content)}},[c.isLoading,O,A]);let $=vs(()=>({addMessage:M=>{l(R=>({...R,messages:[...R.messages,M]}))},addSystemMessage:M=>{l(R=>({...R,messages:[...R.messages,{id:Se(),role:"system",content:M,timestamp:Date.now()}]}))},updateMessages:M=>{l(R=>({...R,messages:M(R.messages)}))},setLoading:(M,R)=>{l(H=>({...H,isLoading:M,loadingMessage:R||H.loadingMessage}))},setConversationId:(M,R)=>{l(H=>({...H,conversationId:M,conversationTitleGenerated:!!R}))},clearChat:()=>{l(M=>({...M,messages:[{id:Se(),role:"system",content:Ss.clear(),timestamp:Date.now()}],conversationId:null,conversationTitleGenerated:!1,staticRemountKey:M.staticRemountKey+1})),T(null),r.clearAll()},handleSubmit:w,handleConfirmationConfirm:M=>{let R=p.current?.id;R&&(l(H=>({...H,pendingConfirmation:null})),o.personalAgent.emit("confirmation_response",{confirmationId:R,response:M,confirmed:!0}))},handleConfirmationDecline:()=>{let M=p.current?.id;M&&(l(R=>({...R,pendingConfirmation:null})),o.personalAgent.emit("confirmation_response",{confirmationId:M,response:"n",confirmed:!1}),l(R=>({...R,messages:[...R.messages,{id:Se(),role:"system",content:"[!] Action declined by user",timestamp:Date.now()}]})))},handleConfirmationTimeout:()=>{let M=p.current?.id;M&&(l(R=>({...R,pendingConfirmation:null})),o.personalAgent.emit("confirmation_response",{confirmationId:M,response:"n",confirmed:!1,timedOut:!0}),l(R=>({...R,messages:[...R.messages,{id:Se(),role:"system",content:"[!] Confirmation timed out - action declined",timestamp:Date.now()}]})))},stopStreaming:async()=>{await o.personalAgent.stopStreaming(),l(M=>({...M,isLoading:!1,activeTools:new Map,subAgentOperations:new Map,pendingConfirmation:null,messages:[...M.messages,{id:Se(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))},createConversation:M=>{let R=ot.createConversation(M);return l(H=>({...H,conversations:ot.getConversations(),conversationId:R.id,conversationTitleGenerated:!1,messages:[{id:Se(),role:"system",content:Ss.newConversation(),timestamp:Date.now()}],staticRemountKey:H.staticRemountKey+1})),T(null),R},switchConversation:M=>{d.current&&(o.personalAgent.stopStreaming().catch(()=>{}),l(j=>({...j,isLoading:!1,activeTools:new Map,subAgentOperations:new Map,pendingConfirmation:null})));let R=m.current,H=g.current;if(R&&H.length>1)for(let j of H)j.role!=="system"&&ot.addMessage(R,ys.toStoredMessage(j));ot.setCurrentConversation(M);let B=ot.getMessages(M);l(j=>({...j,conversationId:M,messages:B.length>0?B.map(ne=>ys.fromStoredMessage(ne)):[{id:Se(),role:"system",content:Ss.continueConversation(),timestamp:Date.now()}],staticRemountKey:j.staticRemountKey+1}))},deleteConversation:M=>{ot.deleteConversation(M),l(R=>({...R,conversations:ot.getConversations(),...R.conversationId===M?{conversationId:null,messages:[{id:Se(),role:"system",content:Ss.deleted(),timestamp:Date.now()}],staticRemountKey:R.staticRemountKey+1}:{}}))},updateConversationTitle:(M,R)=>{ot.updateConversationTitle(M,R),l(H=>({...H,conversations:ot.getConversations(),conversationTitleGenerated:!0}))}}),[w,o.personalAgent]),_=vs(()=>({regularQueuedMessages:P,crossDeviceTasks:x,hasQueuedMessages:O}),[P,x,O]),F=nc(M=>{f.current=M},[]),z=nc(M=>{y.current=M},[]),G=vs(()=>({state:c,actions:$,services:o,queue:_,projectPath:n}),[c,$,o,_,n]);return vn(()=>{qt._updateModelRef=F,qt._updateVisionRef=z},[F,z]),Hn.createElement(qt.Provider,{value:G},Hn.createElement(_d.Provider,{value:c},Hn.createElement($d.Provider,{value:$},Hn.createElement(Fd.Provider,{value:o},Hn.createElement(Ld.Provider,{value:_},Hn.createElement(Ud.Provider,{value:n},Hn.createElement(Bd.Provider,{value:t||"1.0.0"},i)))))))}function jn(){let i=kt(_d);if(i)return i;let e=kt(qt);if(!e)throw new Error("useChatState must be used within ChatProvider");return e.state}function Pt(){let i=kt($d);if(i)return i;let e=kt(qt);if(!e)throw new Error("useChatActions must be used within ChatProvider");return e.actions}function zn(){let i=kt(Fd);if(i)return i;let e=kt(qt);if(!e)throw new Error("useChatServices must be used within ChatProvider");return e.services}function rc(){let i=kt(Ld);if(i)return i;let e=kt(qt);if(!e)throw new Error("useChatQueue must be used within ChatProvider");return e.queue}function oc(){let i=kt(Ud);if(i)return i;let e=kt(qt);if(!e)throw new Error("useProjectPath must be used within ChatProvider");return e.projectPath}function hr(){let i=kt(Bd);return i||"1.0.0"}function Wd(){return qt}en();ze();Pn();ke();import qo,{createContext as Vo,useContext as ws,useState as Xy,useMemo as Ko,useEffect as Hd,useRef as Gd}from"react";var jd=Vo(null),zd=Vo(null),qd=Vo(null),Xo=Vo(null);function ic({children:i}){let e=Ko(()=>ye.find(d=>d.name===fe.string("selectedPersonalModel"))||ye.find(d=>d.name==="snowx-c5")||ye[0],[]),t=Gd(0),[n,s]=Xy({showHelp:!1,showModelMenu:!1,showCommandMenu:!1,showConversationList:!1,selectedModel:e,isVisionEnabled:!1,showWizard:!1,wizard:{type:null,step:1,data:{}},operationalMode:"normal",toasts:[],isReverseSearchActive:!1}),r=Pt(),o=Gd(r);Hd(()=>{o.current=r}),Hd(()=>{let d=Wd();d._updateModelRef&&d._updateModelRef(n.selectedModel),d._updateVisionRef&&d._updateVisionRef(n.isVisionEnabled)},[n.selectedModel,n.isVisionEnabled]);let a=Ko(()=>({email:Z.getInstance().getUserEmail()||"User",tier:Pe.getDisplayName(Pe.getCurrentUserTier()),userTier:Pe.getCurrentUserTier()}),[]),c=Ko(()=>({toggleHelp:()=>s(d=>({...d,showHelp:!d.showHelp})),showHelp:()=>s(d=>({...d,showHelp:!0})),hideHelp:()=>s(d=>({...d,showHelp:!1})),toggleModelMenu:()=>s(d=>({...d,showModelMenu:!d.showModelMenu})),showModelMenu:()=>s(d=>({...d,showModelMenu:!0})),hideModelMenu:()=>s(d=>({...d,showModelMenu:!1})),toggleCommandMenu:()=>s(d=>({...d,showCommandMenu:!d.showCommandMenu})),showCommandMenu:()=>s(d=>({...d,showCommandMenu:!0})),hideCommandMenu:()=>s(d=>({...d,showCommandMenu:!1})),showConversationList:()=>s(d=>({...d,showConversationList:!0})),hideConversationList:()=>s(d=>({...d,showConversationList:!1})),setModel:d=>{fe.set("selectedPersonalModel",d.name),s(g=>({...g,selectedModel:d,showModelMenu:!1})),o.current.addSystemMessage(`Switched to ${d.displayName}`)},toggleVision:()=>{let d=!1;s(g=>(d=!g.isVisionEnabled,{...g,isVisionEnabled:d})),Promise.resolve().then(()=>{o.current.addSystemMessage(`Vision mode ${d?"enabled":"disabled"}`)})},closeAllModals:()=>s(d=>({...d,showHelp:!1,showModelMenu:!1,showCommandMenu:!1,showConversationList:!1,showWizard:!1})),showDiscordWizard:()=>s(d=>({...d,showWizard:!0,showCommandMenu:!1,showConversationList:!1,wizard:{type:"discord",step:1,data:{}}})),showTelegramWizard:()=>s(d=>({...d,showWizard:!0,showCommandMenu:!1,showConversationList:!1,wizard:{type:"telegram",step:1,data:{}}})),hideWizard:()=>s(d=>({...d,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setWizardStep:d=>s(g=>({...g,wizard:{...g.wizard,step:d}})),setWizardData:(d,g)=>s(m=>({...m,wizard:{...m.wizard,data:{...m.wizard.data,[d]:g}}})),resetWizard:()=>s(d=>({...d,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setMode:d=>{s(g=>({...g,operationalMode:d})),d!=="normal"&&o.current.addSystemMessage(`Switched to ${d.toUpperCase()} mode`)},toggleYoloMode:()=>{let d="normal";s(g=>(d=g.operationalMode==="yolo"?"normal":"yolo",{...g,operationalMode:d})),Promise.resolve().then(()=>{d==="yolo"?o.current.addSystemMessage("YOLO mode enabled - all actions will be auto-approved"):o.current.addSystemMessage("YOLO mode disabled")})},togglePlanMode:()=>{let d="normal";s(g=>(d=g.operationalMode==="plan"?"normal":"plan",{...g,operationalMode:d})),Promise.resolve().then(()=>{d==="plan"?o.current.addSystemMessage("PLAN mode enabled - planning only, no execution"):o.current.addSystemMessage("PLAN mode disabled")})},showToast:(d,g="info",m)=>{let p=`toast-${Date.now()}-${t.current++}`;s(h=>({...h,toasts:[...h.toasts,{id:p,message:d,type:g,duration:m}]}))},removeToast:d=>{s(g=>({...g,toasts:g.toasts.filter(m=>m.id!==d)}))},clearToasts:()=>{s(d=>({...d,toasts:[]}))},startReverseSearch:()=>{s(d=>({...d,isReverseSearchActive:!0,showHelp:!1,showModelMenu:!1,showCommandMenu:!1,showConversationList:!1}))},stopReverseSearch:()=>{s(d=>({...d,isReverseSearchActive:!1}))}}),[]),l=Ko(()=>({state:n,actions:c,info:a}),[n,c,a]);return qo.createElement(zd.Provider,{value:c},qo.createElement(jd.Provider,{value:n},qo.createElement(qd.Provider,{value:a},qo.createElement(Xo.Provider,{value:l},i))))}function Ts(){let i=ws(jd);if(i)return i;let e=ws(Xo);if(!e)throw new Error("useUIState must be used within UIProvider");return e.state}function Kt(){let i=ws(zd);if(i)return i;let e=ws(Xo);if(!e)throw new Error("useUIActions must be used within UIProvider");return e.actions}function fr(){let i=ws(qd);if(i)return i;let e=ws(Xo);if(!e)throw new Error("useUIInfo must be used within UIProvider");return e.info}function ac(){let i=Ts();return{...i.wizard,isOpen:i.showWizard}}import ev,{createContext as tv,useContext as lg,useState as nv,useMemo as ag,useRef as cg}from"react";import Jo from"path";import cc from"fs";import qn from"path";import Yy from"os";var Xd={".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"},Yd=Object.keys(Xd),Qy=[...Yd,".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"],Kd=20*1024*1024,Vd=1*1024*1024;function Wt(i){return i<1024?`${i}B`:i<1024*1024?`${(i/1024).toFixed(1)}KB`:`${(i/(1024*1024)).toFixed(1)}MB`}function Yo(i,e=30){if(i.length<=e)return i;let t=qn.extname(i);return qn.basename(i,t).slice(0,e-t.length-3)+"..."+t}function Qd(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(`
2522
- `))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=qn.extname(a),l=Yd.includes(c),d=Qy.includes(c);return{isFilePath:!0,isImage:l,isBinary:d,path:e}}function Jy(i){return i.startsWith("~/")?qn.join(Yy.homedir(),i.slice(2)):i}function lc(i){let e=Jy(i);return qn.isAbsolute(e)?e:qn.resolve(process.cwd(),e)}function Qo(i){try{let e=lc(i),t=cc.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 Jd(i){try{let e=lc(i),t=Qo(i);if(!t.exists)return{data:null,error:t.error};if(t.size>Kd)return{data:null,error:`Image too large (${Wt(t.size)}, max ${Wt(Kd)})`};let n=cc.readFileSync(e),s=qn.extname(i).toLowerCase(),r=Xd[s]||"image/png",o=n.toString("base64");return{data:`data:${r};base64,${o}`}}catch(e){return{data:null,error:e.message}}}function Zd(i){try{let e=lc(i),t=Qo(i);return t.exists?t.size>Vd?{content:null,error:`File too large (${Wt(t.size)}, max ${Wt(Vd)})`}:{content:cc.readFileSync(e,"utf8")}:{content:null,error:t.error}}catch(e){return{content:null,error:e.message}}}dc();var sv=100,rv=50,gc=tv(null);function mc({children:i}){let{attachmentManager:e}=zn(),[t,n]=nv({input:"",cursorPosition:0,pastedTexts:[],isProcessingFiles:!1,suggestion:null,attachmentCount:0,history:[],historyIndex:-1,tempInput:"",undoStack:[],redoStack:[]}),s=cg(0),r=cg(null),o=ag(()=>({setInput:c=>{n(l=>({...l,input:c,cursorPosition:c.length}))},setCursor:c=>{n(l=>({...l,cursorPosition:Math.max(0,Math.min(c,l.input.length))}))},insertAtCursor:c=>{n(l=>{let d=l.input.slice(0,l.cursorPosition)+c+l.input.slice(l.cursorPosition);return{...l,input:d,cursorPosition:l.cursorPosition+c.length}})},deleteAtCursor:()=>{n(c=>{if(c.input===""&&c.pastedTexts.length>0)return{...c,pastedTexts:c.pastedTexts.slice(0,-1)};if(c.cursorPosition===0)return c;let l=c.input.slice(0,c.cursorPosition-1)+c.input.slice(c.cursorPosition);return{...c,input:l,cursorPosition:c.cursorPosition-1}})},clearInput:()=>{n(c=>({...c,input:"",cursorPosition:0,pastedTexts:[],suggestion:null}))},moveCursorLeft:()=>{n(c=>({...c,cursorPosition:Math.max(0,c.cursorPosition-1)}))},moveCursorRight:()=>{n(c=>({...c,cursorPosition:Math.min(c.input.length,c.cursorPosition+1)}))},moveCursorToStart:()=>{n(c=>({...c,cursorPosition:0}))},moveCursorToEnd:()=>{n(c=>({...c,cursorPosition:c.input.length}))},addPastedContent:c=>{let l=Qd(c),d=c.split(`
2523
- `);s.current+=1;let g="text",m,p;if(l.isFilePath){l.isImage?g="image_path":l.isBinary?(g="file_path",p="Binary file - cannot read as text"):g="file_path";let h=Qo(l.path);h.exists?m=h.size:p=h.error}n(h=>({...h,pastedTexts:[...h.pastedTexts,{id:s.current,content:c,lineCount:d.length,type:g,filePath:l.isFilePath?l.path:void 0,fileSize:m,error:p}]}))},addClipboardImage:async(c,l)=>{s.current+=1;try{await e.addClipboardImage(c,l),n(d=>({...d,attachmentCount:e.getTotalCount(),pastedTexts:[...d.pastedTexts,{id:s.current,content:"Clipboard image",lineCount:1,type:"clipboard_image",imageData:c,fileSize:l}]}))}catch(d){throw d}},addDocument:async(c,l,d,g)=>{s.current+=1;try{await e.addDocumentFromBase64(c,l,d,g),n(m=>({...m,attachmentCount:e.getTotalCount(),pastedTexts:[...m.pastedTexts,{id:s.current,content:l,lineCount:1,type:"file_path",fileSize:g}]}))}catch(m){throw m}},addFileAttachment:async c=>{let l=uc(c);if(l.type==="blocked")throw new Error(`File type not allowed: .${l.extension}`);l.type==="image"?await e.addImageFromPath(c):l.type==="document"&&await e.addDocumentFromPath(c),n(d=>({...d,attachmentCount:e.getTotalCount()}))},clearPastedTexts:()=>{n(c=>({...c,pastedTexts:[],attachmentCount:0})),e.clearAll()},removeLastPaste:()=>{n(c=>({...c,pastedTexts:c.pastedTexts.slice(0,-1)}))},processFilesForSubmit:async()=>{n(c=>({...c,isProcessingFiles:!0}));try{let c=t,l=c.pastedTexts.filter(w=>w.type==="image_path"&&w.filePath),d=c.pastedTexts.filter(w=>w.type==="clipboard_image"&&w.imageData),g=c.pastedTexts.filter(w=>w.type==="file_path"&&w.filePath),m=c.pastedTexts.filter(w=>w.type==="text"),p=[],h=[],f=[];for(let w of g)if(w.filePath&&!w.error){let S=Zd(w.filePath);if(S.content){let P=Jo.basename(w.filePath),x=Jo.extname(P).slice(1)||"text";h.push(`[File: ${P}]
2521
+ - Item 3`,timestamp:Date.now()+600+pe*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},j=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"}]]);l(ne=>({...ne,messages:H,todoList:B,activeTools:j,isLoading:!0,loadingMessage:"Processing mock request..."}))},500);return()=>clearTimeout(M)},[]);let[I]=tc(()=>{let M={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:a,isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new Go(M)});vn(()=>{let M=g.current.map(R=>({role:R.role,content:R.content,timestamp:new Date(R.timestamp||Date.now()),...R.tool&&{tool:R.tool},...R.toolOutput&&{toolOutput:R.toolOutput}}));I.setDelegate({messages:M,fullConversationHistory:M,isLoading:c.isLoading,currentInput:"",selectedModel:f.current,isVisionEnabled:y.current,conversationId:c.conversationId,usesCustomUI:!0,updateCurrentConversation:()=>{}})},[c.isLoading,c.conversationId,I]);let E=yn(null),w=nc(async(M,R=[])=>{if(Bn.getExistingInstance()?.checkAndUpdate().catch(()=>{}),d.current){o.queueManager.addToQueue({content:M,imageUrls:R,attachments:[],model:f.current.name})||l(ct=>({...ct,messages:[...ct.messages,{id:Se(),role:"system",content:"[!] Queue is full (max 5 messages). Your input was not saved.",timestamp:Date.now()}]}));return}let H=Date.now(),B={id:Se(),role:"user",content:M,timestamp:H},j={id:Se(),role:"assistant",content:"",timestamp:H+1},ne=[...g.current,B,j];l(ue=>({...ue,messages:ne,isLoading:!0,loadingMessage:"Processing"}));let pe=ne.map(ue=>({role:ue.role,content:ue.content,timestamp:new Date(ue.timestamp||Date.now()),...ue.tool&&{tool:ue.tool},...ue.toolOutput&&{toolOutput:ue.toolOutput}}));I.setDelegate({messages:pe,fullConversationHistory:pe,isLoading:!1,currentInput:"",selectedModel:f.current,isVisionEnabled:y.current,conversationId:m.current,usesCustomUI:!0,updateCurrentConversation:()=>{}});try{await I.sendMessage(M,R.length>0?R:void 0),r.clearAll()}catch(ue){l(ct=>({...ct,messages:[...ct.messages,{id:Se(),role:"system",content:`Error: ${ue.message}`,timestamp:Date.now()}],isLoading:!1}))}},[o.queueManager,I]);E.current=w;let S=vs(()=>({onConversationIdReceived:M=>{l(R=>({...R,conversationId:M.conversationId,conversationTitleGenerated:!!M.title}))},onMessagesUpdate:M=>{l(R=>({...R,messages:M(R.messages)}))},onActiveToolsUpdate:M=>{l(R=>({...R,activeTools:M(R.activeTools)}))},onLoadingChange:M=>{if(l(R=>({...R,isLoading:M,activeTools:M?R.activeTools:new Map,subAgentOperations:M?R.subAgentOperations:new Map})),!M){let R=C.current;R&&R.todos.some(B=>B.status!=="completed")&&T(null)}},onLoadingMessageChange:M=>{l(R=>({...R,loadingMessage:M}))},onTodoUpdate:M=>{T(M)},onConfirmationRequest:M=>{l(R=>({...R,pendingConfirmation:M}))},onCompactionStatus:M=>{l(R=>({...R,compactionStatus:M})),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null,l(R=>R.compactionStatus===M?{...R,compactionStatus:null}:R)},8e3)},onError:M=>{l(R=>({...R,messages:[...R.messages,{id:Se(),role:"system",content:`Error: ${M}`,timestamp:Date.now()}],isLoading:!1,activeTools:new Map,subAgentOperations:new Map}))}}),[T]);kd({personalAgent:o.personalAgent,frontendWS:o.frontendWS,handlers:S});let{regularQueuedMessages:P,crossDeviceTasks:x,processNextMessage:A,hasQueuedMessages:O}=Md({queueManager:o.queueManager,frontendWS:o.frontendWS,crossDevice:o.crossDevice,isLoading:c.isLoading,selectedModel:f.current,onCrossDeviceTask:(M,R)=>{R&&E.current?.(R)}}),{subAgentOperations:U}=Rd({subAgentManager:o.subAgentManager});vn(()=>{let M=Bn.getExistingInstance();if(!M)return;let R=H=>{l(B=>({...B,messages:[...B.messages,{id:Se(),role:"system",content:`[UPDATE] Orion updated v${H.from} -> v${H.to}. Restart to use the new version.`,timestamp:Date.now()}]}))};return M.on("updated",R),()=>{M.off("updated",R),h.current&&clearTimeout(h.current)}},[]);let{externalSession:D}=Nd({frontendWS:o.frontendWS});vn(()=>{l(M=>({...M,subAgentOperations:U,externalSession:D,todoList:v}))},[U,D,v]),vn(()=>{if(!c.isLoading&&O){let M=A();M&&E.current?.(M.content)}},[c.isLoading,O,A]);let $=vs(()=>({addMessage:M=>{l(R=>({...R,messages:[...R.messages,M]}))},addSystemMessage:M=>{l(R=>({...R,messages:[...R.messages,{id:Se(),role:"system",content:M,timestamp:Date.now()}]}))},updateMessages:M=>{l(R=>({...R,messages:M(R.messages)}))},setLoading:(M,R)=>{l(H=>({...H,isLoading:M,loadingMessage:R||H.loadingMessage}))},setConversationId:(M,R)=>{l(H=>({...H,conversationId:M,conversationTitleGenerated:!!R}))},clearChat:()=>{l(M=>({...M,messages:[{id:Se(),role:"system",content:Ss.clear(),timestamp:Date.now()}],conversationId:null,conversationTitleGenerated:!1,staticRemountKey:M.staticRemountKey+1})),T(null),r.clearAll()},handleSubmit:w,handleConfirmationConfirm:M=>{let R=p.current?.id;R&&(l(H=>({...H,pendingConfirmation:null})),o.personalAgent.emit("confirmation_response",{confirmationId:R,response:M,confirmed:!0}))},handleConfirmationDecline:()=>{let M=p.current?.id;M&&(l(R=>({...R,pendingConfirmation:null})),o.personalAgent.emit("confirmation_response",{confirmationId:M,response:"n",confirmed:!1}),l(R=>({...R,messages:[...R.messages,{id:Se(),role:"system",content:"[!] Action declined by user",timestamp:Date.now()}]})))},handleConfirmationTimeout:()=>{let M=p.current?.id;M&&(l(R=>({...R,pendingConfirmation:null})),o.personalAgent.emit("confirmation_response",{confirmationId:M,response:"n",confirmed:!1,timedOut:!0}),l(R=>({...R,messages:[...R.messages,{id:Se(),role:"system",content:"[!] Confirmation timed out - action declined",timestamp:Date.now()}]})))},stopStreaming:async()=>{await o.personalAgent.stopStreaming(),l(M=>({...M,isLoading:!1,activeTools:new Map,subAgentOperations:new Map,pendingConfirmation:null,messages:[...M.messages,{id:Se(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))},createConversation:M=>{let R=ot.createConversation(M);return l(H=>({...H,conversations:ot.getConversations(),conversationId:R.id,conversationTitleGenerated:!1,messages:[{id:Se(),role:"system",content:Ss.newConversation(),timestamp:Date.now()}],staticRemountKey:H.staticRemountKey+1})),T(null),R},switchConversation:M=>{d.current&&(o.personalAgent.stopStreaming().catch(()=>{}),l(j=>({...j,isLoading:!1,activeTools:new Map,subAgentOperations:new Map,pendingConfirmation:null})));let R=m.current,H=g.current;if(R&&H.length>1)for(let j of H)j.role!=="system"&&ot.addMessage(R,ys.toStoredMessage(j));ot.setCurrentConversation(M);let B=ot.getMessages(M);l(j=>({...j,conversationId:M,messages:B.length>0?B.map(ne=>ys.fromStoredMessage(ne)):[{id:Se(),role:"system",content:Ss.continueConversation(),timestamp:Date.now()}],staticRemountKey:j.staticRemountKey+1}))},deleteConversation:M=>{ot.deleteConversation(M),l(R=>({...R,conversations:ot.getConversations(),...R.conversationId===M?{conversationId:null,messages:[{id:Se(),role:"system",content:Ss.deleted(),timestamp:Date.now()}],staticRemountKey:R.staticRemountKey+1}:{}}))},updateConversationTitle:(M,R)=>{ot.updateConversationTitle(M,R),l(H=>({...H,conversations:ot.getConversations(),conversationTitleGenerated:!0}))}}),[w,o.personalAgent]),_=vs(()=>({regularQueuedMessages:P,crossDeviceTasks:x,hasQueuedMessages:O}),[P,x,O]),F=nc(M=>{f.current=M},[]),z=nc(M=>{y.current=M},[]),G=vs(()=>({state:c,actions:$,services:o,queue:_,projectPath:n}),[c,$,o,_,n]);return vn(()=>{qt._updateModelRef=F,qt._updateVisionRef=z},[F,z]),Hn.createElement(qt.Provider,{value:G},Hn.createElement($d.Provider,{value:c},Hn.createElement(Fd.Provider,{value:$},Hn.createElement(Ld.Provider,{value:o},Hn.createElement(Ud.Provider,{value:_},Hn.createElement(Bd.Provider,{value:n},Hn.createElement(Wd.Provider,{value:t||"1.0.0"},i)))))))}function jn(){let i=kt($d);if(i)return i;let e=kt(qt);if(!e)throw new Error("useChatState must be used within ChatProvider");return e.state}function Pt(){let i=kt(Fd);if(i)return i;let e=kt(qt);if(!e)throw new Error("useChatActions must be used within ChatProvider");return e.actions}function zn(){let i=kt(Ld);if(i)return i;let e=kt(qt);if(!e)throw new Error("useChatServices must be used within ChatProvider");return e.services}function rc(){let i=kt(Ud);if(i)return i;let e=kt(qt);if(!e)throw new Error("useChatQueue must be used within ChatProvider");return e.queue}function oc(){let i=kt(Bd);if(i)return i;let e=kt(qt);if(!e)throw new Error("useProjectPath must be used within ChatProvider");return e.projectPath}function hr(){let i=kt(Wd);if(i!==null)return i;throw new Error("useAppVersion must be used within ChatProvider")}function Hd(){return qt}en();ze();Pn();ke();import qo,{createContext as Vo,useContext as ws,useState as Qy,useMemo as Ko,useEffect as Gd,useRef as jd}from"react";var zd=Vo(null),qd=Vo(null),Kd=Vo(null),Xo=Vo(null);function ic({children:i}){let e=Ko(()=>ye.find(d=>d.name===fe.string("selectedPersonalModel"))||ye.find(d=>d.name==="snowx-c5")||ye[0],[]),t=jd(0),[n,s]=Qy({showHelp:!1,showModelMenu:!1,showCommandMenu:!1,showConversationList:!1,selectedModel:e,isVisionEnabled:!1,showWizard:!1,wizard:{type:null,step:1,data:{}},operationalMode:"normal",toasts:[],isReverseSearchActive:!1}),r=Pt(),o=jd(r);Gd(()=>{o.current=r}),Gd(()=>{let d=Hd();d._updateModelRef&&d._updateModelRef(n.selectedModel),d._updateVisionRef&&d._updateVisionRef(n.isVisionEnabled)},[n.selectedModel,n.isVisionEnabled]);let a=Ko(()=>({email:Z.getInstance().getUserEmail()||"User",tier:Pe.getDisplayName(Pe.getCurrentUserTier()),userTier:Pe.getCurrentUserTier()}),[]),c=Ko(()=>({toggleHelp:()=>s(d=>({...d,showHelp:!d.showHelp})),showHelp:()=>s(d=>({...d,showHelp:!0})),hideHelp:()=>s(d=>({...d,showHelp:!1})),toggleModelMenu:()=>s(d=>({...d,showModelMenu:!d.showModelMenu})),showModelMenu:()=>s(d=>({...d,showModelMenu:!0})),hideModelMenu:()=>s(d=>({...d,showModelMenu:!1})),toggleCommandMenu:()=>s(d=>({...d,showCommandMenu:!d.showCommandMenu})),showCommandMenu:()=>s(d=>({...d,showCommandMenu:!0})),hideCommandMenu:()=>s(d=>({...d,showCommandMenu:!1})),showConversationList:()=>s(d=>({...d,showConversationList:!0})),hideConversationList:()=>s(d=>({...d,showConversationList:!1})),setModel:d=>{fe.set("selectedPersonalModel",d.name),s(g=>({...g,selectedModel:d,showModelMenu:!1})),o.current.addSystemMessage(`Switched to ${d.displayName}`)},toggleVision:()=>{let d=!1;s(g=>(d=!g.isVisionEnabled,{...g,isVisionEnabled:d})),Promise.resolve().then(()=>{o.current.addSystemMessage(`Vision mode ${d?"enabled":"disabled"}`)})},closeAllModals:()=>s(d=>({...d,showHelp:!1,showModelMenu:!1,showCommandMenu:!1,showConversationList:!1,showWizard:!1})),showDiscordWizard:()=>s(d=>({...d,showWizard:!0,showCommandMenu:!1,showConversationList:!1,wizard:{type:"discord",step:1,data:{}}})),showTelegramWizard:()=>s(d=>({...d,showWizard:!0,showCommandMenu:!1,showConversationList:!1,wizard:{type:"telegram",step:1,data:{}}})),hideWizard:()=>s(d=>({...d,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setWizardStep:d=>s(g=>({...g,wizard:{...g.wizard,step:d}})),setWizardData:(d,g)=>s(m=>({...m,wizard:{...m.wizard,data:{...m.wizard.data,[d]:g}}})),resetWizard:()=>s(d=>({...d,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setMode:d=>{s(g=>({...g,operationalMode:d})),d!=="normal"&&o.current.addSystemMessage(`Switched to ${d.toUpperCase()} mode`)},toggleYoloMode:()=>{let d="normal";s(g=>(d=g.operationalMode==="yolo"?"normal":"yolo",{...g,operationalMode:d})),Promise.resolve().then(()=>{d==="yolo"?o.current.addSystemMessage("YOLO mode enabled - all actions will be auto-approved"):o.current.addSystemMessage("YOLO mode disabled")})},togglePlanMode:()=>{let d="normal";s(g=>(d=g.operationalMode==="plan"?"normal":"plan",{...g,operationalMode:d})),Promise.resolve().then(()=>{d==="plan"?o.current.addSystemMessage("PLAN mode enabled - planning only, no execution"):o.current.addSystemMessage("PLAN mode disabled")})},showToast:(d,g="info",m)=>{let p=`toast-${Date.now()}-${t.current++}`;s(h=>({...h,toasts:[...h.toasts,{id:p,message:d,type:g,duration:m}]}))},removeToast:d=>{s(g=>({...g,toasts:g.toasts.filter(m=>m.id!==d)}))},clearToasts:()=>{s(d=>({...d,toasts:[]}))},startReverseSearch:()=>{s(d=>({...d,isReverseSearchActive:!0,showHelp:!1,showModelMenu:!1,showCommandMenu:!1,showConversationList:!1}))},stopReverseSearch:()=>{s(d=>({...d,isReverseSearchActive:!1}))}}),[]),l=Ko(()=>({state:n,actions:c,info:a}),[n,c,a]);return qo.createElement(qd.Provider,{value:c},qo.createElement(zd.Provider,{value:n},qo.createElement(Kd.Provider,{value:a},qo.createElement(Xo.Provider,{value:l},i))))}function Ts(){let i=ws(zd);if(i)return i;let e=ws(Xo);if(!e)throw new Error("useUIState must be used within UIProvider");return e.state}function Kt(){let i=ws(qd);if(i)return i;let e=ws(Xo);if(!e)throw new Error("useUIActions must be used within UIProvider");return e.actions}function fr(){let i=ws(Kd);if(i)return i;let e=ws(Xo);if(!e)throw new Error("useUIInfo must be used within UIProvider");return e.info}function ac(){let i=Ts();return{...i.wizard,isOpen:i.showWizard}}import nv,{createContext as sv,useContext as ug,useState as rv,useMemo as cg,useRef as lg}from"react";import Jo from"path";import cc from"fs";import qn from"path";import Jy from"os";var Yd={".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"},Qd=Object.keys(Yd),Zy=[...Qd,".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"],Vd=20*1024*1024,Xd=1*1024*1024;function Wt(i){return i<1024?`${i}B`:i<1024*1024?`${(i/1024).toFixed(1)}KB`:`${(i/(1024*1024)).toFixed(1)}MB`}function Yo(i,e=30){if(i.length<=e)return i;let t=qn.extname(i);return qn.basename(i,t).slice(0,e-t.length-3)+"..."+t}function Jd(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(`
2522
+ `))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=qn.extname(a),l=Qd.includes(c),d=Zy.includes(c);return{isFilePath:!0,isImage:l,isBinary:d,path:e}}function ev(i){return i.startsWith("~/")?qn.join(Jy.homedir(),i.slice(2)):i}function lc(i){let e=ev(i);return qn.isAbsolute(e)?e:qn.resolve(process.cwd(),e)}function Qo(i){try{let e=lc(i),t=cc.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 Zd(i){try{let e=lc(i),t=Qo(i);if(!t.exists)return{data:null,error:t.error};if(t.size>Vd)return{data:null,error:`Image too large (${Wt(t.size)}, max ${Wt(Vd)})`};let n=cc.readFileSync(e),s=qn.extname(i).toLowerCase(),r=Yd[s]||"image/png",o=n.toString("base64");return{data:`data:${r};base64,${o}`}}catch(e){return{data:null,error:e.message}}}function eg(i){try{let e=lc(i),t=Qo(i);return t.exists?t.size>Xd?{content:null,error:`File too large (${Wt(t.size)}, max ${Wt(Xd)})`}:{content:cc.readFileSync(e,"utf8")}:{content:null,error:t.error}}catch(e){return{content:null,error:e.message}}}dc();var ov=100,iv=50,gc=sv(null);function mc({children:i}){let{attachmentManager:e}=zn(),[t,n]=rv({input:"",cursorPosition:0,pastedTexts:[],isProcessingFiles:!1,suggestion:null,attachmentCount:0,history:[],historyIndex:-1,tempInput:"",undoStack:[],redoStack:[]}),s=lg(0),r=lg(null),o=cg(()=>({setInput:c=>{n(l=>({...l,input:c,cursorPosition:c.length}))},setCursor:c=>{n(l=>({...l,cursorPosition:Math.max(0,Math.min(c,l.input.length))}))},insertAtCursor:c=>{n(l=>{let d=l.input.slice(0,l.cursorPosition)+c+l.input.slice(l.cursorPosition);return{...l,input:d,cursorPosition:l.cursorPosition+c.length}})},deleteAtCursor:()=>{n(c=>{if(c.input===""&&c.pastedTexts.length>0)return{...c,pastedTexts:c.pastedTexts.slice(0,-1)};if(c.cursorPosition===0)return c;let l=c.input.slice(0,c.cursorPosition-1)+c.input.slice(c.cursorPosition);return{...c,input:l,cursorPosition:c.cursorPosition-1}})},clearInput:()=>{n(c=>({...c,input:"",cursorPosition:0,pastedTexts:[],suggestion:null}))},moveCursorLeft:()=>{n(c=>({...c,cursorPosition:Math.max(0,c.cursorPosition-1)}))},moveCursorRight:()=>{n(c=>({...c,cursorPosition:Math.min(c.input.length,c.cursorPosition+1)}))},moveCursorToStart:()=>{n(c=>({...c,cursorPosition:0}))},moveCursorToEnd:()=>{n(c=>({...c,cursorPosition:c.input.length}))},addPastedContent:c=>{let l=Jd(c),d=c.split(`
2523
+ `);s.current+=1;let g="text",m,p;if(l.isFilePath){l.isImage?g="image_path":l.isBinary?(g="file_path",p="Binary file - cannot read as text"):g="file_path";let h=Qo(l.path);h.exists?m=h.size:p=h.error}n(h=>({...h,pastedTexts:[...h.pastedTexts,{id:s.current,content:c,lineCount:d.length,type:g,filePath:l.isFilePath?l.path:void 0,fileSize:m,error:p}]}))},addClipboardImage:async(c,l)=>{s.current+=1;try{await e.addClipboardImage(c,l),n(d=>({...d,attachmentCount:e.getTotalCount(),pastedTexts:[...d.pastedTexts,{id:s.current,content:"Clipboard image",lineCount:1,type:"clipboard_image",imageData:c,fileSize:l}]}))}catch(d){throw d}},addDocument:async(c,l,d,g)=>{s.current+=1;try{await e.addDocumentFromBase64(c,l,d,g),n(m=>({...m,attachmentCount:e.getTotalCount(),pastedTexts:[...m.pastedTexts,{id:s.current,content:l,lineCount:1,type:"file_path",fileSize:g}]}))}catch(m){throw m}},addFileAttachment:async c=>{let l=uc(c);if(l.type==="blocked")throw new Error(`File type not allowed: .${l.extension}`);l.type==="image"?await e.addImageFromPath(c):l.type==="document"&&await e.addDocumentFromPath(c),n(d=>({...d,attachmentCount:e.getTotalCount()}))},clearPastedTexts:()=>{n(c=>({...c,pastedTexts:[],attachmentCount:0})),e.clearAll()},removeLastPaste:()=>{n(c=>({...c,pastedTexts:c.pastedTexts.slice(0,-1)}))},processFilesForSubmit:async()=>{n(c=>({...c,isProcessingFiles:!0}));try{let c=t,l=c.pastedTexts.filter(w=>w.type==="image_path"&&w.filePath),d=c.pastedTexts.filter(w=>w.type==="clipboard_image"&&w.imageData),g=c.pastedTexts.filter(w=>w.type==="file_path"&&w.filePath),m=c.pastedTexts.filter(w=>w.type==="text"),p=[],h=[],f=[];for(let w of g)if(w.filePath&&!w.error){let S=eg(w.filePath);if(S.content){let P=Jo.basename(w.filePath),x=Jo.extname(P).slice(1)||"text";h.push(`[File: ${P}]
2524
2524
  \`\`\`${x}
2525
2525
  ${S.content}
2526
- \`\`\``)}else S.error&&f.push(`${Jo.basename(w.filePath)}: ${S.error}`)}for(let w of l)if(w.filePath&&!w.error){let S=await Jd(w.filePath);S.data?p.push(S.data):S.error&&f.push(`${Jo.basename(w.filePath)}: ${S.error}`)}for(let w of d)w.imageData&&!w.error&&p.push(w.imageData);let y=e.getImages();for(let w of y)p.push(w.data);let v=e.getDocuments();for(let w of v)h.push(`[Document: ${w.fileName}]
2526
+ \`\`\``)}else S.error&&f.push(`${Jo.basename(w.filePath)}: ${S.error}`)}for(let w of l)if(w.filePath&&!w.error){let S=await Zd(w.filePath);S.data?p.push(S.data):S.error&&f.push(`${Jo.basename(w.filePath)}: ${S.error}`)}for(let w of d)w.imageData&&!w.error&&p.push(w.imageData);let y=e.getImages();for(let w of y)p.push(w.data);let v=e.getDocuments();for(let w of v)h.push(`[Document: ${w.fileName}]
2527
2527
  Base64 data attached (${(w.size/1024).toFixed(1)}KB)`),p.push(w.data);let T=m.map(w=>w.content).join(`
2528
2528
 
2529
2529
  `),C=h.join(`
@@ -2532,7 +2532,7 @@ Base64 data attached (${(w.size/1024).toFixed(1)}KB)`),p.push(w.data);let T=m.ma
2532
2532
 
2533
2533
  `);return{fullInput:I?c.input.trim()?`${I}
2534
2534
 
2535
- ${c.input}`:I:c.input,imageUrls:p,errors:f}}finally{n(c=>({...c,isProcessingFiles:!1}))}},setSuggestion:c=>{n(l=>({...l,suggestion:c}))},acceptSuggestion:()=>{n(c=>{if(!c.suggestion)return c;let l=c.suggestion.startsWith(c.input)?c.suggestion.slice(c.input.length):c.suggestion,d=c.input+l;return{...c,input:d,cursorPosition:d.length,suggestion:null}})},addToHistory:c=>{c.trim()&&n(l=>{if(l.history.length>0&&l.history[l.history.length-1]===c)return l;let d=[...l.history,c];return d.length>sv&&d.shift(),{...l,history:d,historyIndex:-1,tempInput:""}})},navigateHistoryUp:()=>{let c=!1;return n(l=>{if(l.history.length===0)return l;if(l.historyIndex===-1){let d=l.history.length-1;return c=!0,{...l,tempInput:l.input,historyIndex:d,input:l.history[d],cursorPosition:l.history[d].length}}if(l.historyIndex>0){let d=l.historyIndex-1;return c=!0,{...l,historyIndex:d,input:l.history[d],cursorPosition:l.history[d].length}}return l}),c},navigateHistoryDown:()=>{let c=!1;return n(l=>{if(l.historyIndex===-1)return l;if(l.historyIndex>=l.history.length-1)return c=!0,{...l,historyIndex:-1,input:l.tempInput,cursorPosition:l.tempInput.length,tempInput:""};let d=l.historyIndex+1;return c=!0,{...l,historyIndex:d,input:l.history[d],cursorPosition:l.history[d].length}}),c},resetHistoryNavigation:()=>{n(c=>({...c,historyIndex:-1,tempInput:""}))},saveUndoState:()=>{n(c=>{let l={input:c.input,cursorPosition:c.cursorPosition};if(r.current&&r.current.input===l.input)return c;r.current=l;let d=[...c.undoStack,l];return d.length>rv&&d.shift(),{...c,undoStack:d,redoStack:[]}})},undo:()=>{let c=!1;return n(l=>{if(l.undoStack.length===0)return l;let d={input:l.input,cursorPosition:l.cursorPosition},g=[...l.undoStack],m=g.pop();return c=!0,{...l,input:m.input,cursorPosition:m.cursorPosition,undoStack:g,redoStack:[...l.redoStack,d]}}),c},redo:()=>{let c=!1;return n(l=>{if(l.redoStack.length===0)return l;let d={input:l.input,cursorPosition:l.cursorPosition},g=[...l.redoStack],m=g.pop();return c=!0,{...l,input:m.input,cursorPosition:m.cursorPosition,undoStack:[...l.undoStack,d],redoStack:g}}),c}}),[t]),a=ag(()=>({state:t,actions:o}),[t,o]);return ev.createElement(gc.Provider,{value:a},i)}function br(){let i=lg(gc);if(!i)throw new Error("useInputState must be used within InputProvider");return i.state}function Kn(){let i=lg(gc);if(!i)throw new Error("useInputActions must be used within InputProvider");return i.actions}import av,{createContext as cv,useContext as ZN,useCallback as ei,useRef as dg,useEffect as lv}from"react";import{EventEmitter as iv}from"events";function ug(){process.stdout.write("\x1B[?1006l\x1B[?1002l")}var Zo=new iv;Zo.setMaxListeners(50);var uv=cv(null);function pc({children:i,enableMouse:e=!0}){let t=dg(new Set),n=dg(new Set),s=ei(c=>{t.current.add(c)},[]),r=ei(c=>{t.current.delete(c)},[]),o=ei(c=>{n.current.add(c)},[]),a=ei(c=>{n.current.delete(c)},[]);return lv(()=>{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 Zo.on("mouse",c),()=>{Zo.off("mouse",c)}},[e]),av.createElement(uv.Provider,{value:{subscribe:s,unsubscribe:r,subscribeScroll:o,unsubscribeScroll:a,isMouseEnabled:e}},i)}import gg,{createContext as pg,useContext as sO,useState as dv,useCallback as ti,useMemo as mg}from"react";var gv=pg(null),mv=pg(null);function hc({children:i}){let[e,t]=dv(new Set),n=ti(l=>{t(d=>{if(d.has(l))return d;let g=new Set(d);return g.add(l),g})},[]),s=ti(l=>{t(d=>{if(!d.has(l))return d;let g=new Set(d);return g.delete(l),g})},[]),r=ti(()=>{t(new Set)},[]),o=ti(l=>e.has(l),[e]),a=mg(()=>({overflowingIds:e,hasOverflow:e.size>0}),[e]),c=mg(()=>({markOverflowing:n,clearOverflowing:s,clearAll:r,isOverflowing:o}),[n,s,r,o]);return gg.createElement(mv.Provider,{value:c},gg.createElement(gv.Provider,{value:a},i))}import hg,{createContext as bg,useContext as iO,useState as pv,useCallback as ni,useMemo as hv,useRef as fv}from"react";function bv(i,e){return i.modelName===e.modelName&&i.requestCount===e.requestCount&&i.totalTokens===e.totalTokens&&Math.abs(i.averageLatency-e.averageLatency)<.01}function yv(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 si(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||!bv(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||!yv(n,s))return!1}return!0}var vv=bg(null),Sv=bg(null);function fg(){let i=Date.now();return{promptCount:0,lastPromptTokenCount:0,totalInputTokens:0,totalOutputTokens:0,sessionStartTime:i,lastActivityTime:i,modelMetrics:new Map,toolCallStats:new Map}}function fc({children:i}){let[e,t]=pv(fg),n=fv(e),s=ni(l=>{t(d=>{let g={...d,promptCount:d.promptCount+1,lastPromptTokenCount:l,lastActivityTime:Date.now()};return si(d,g)?d:g})},[]),r=ni((l,d,g,m)=>{t(p=>{let h=new Map(p.modelMetrics),f=h.get(l);if(f){let v=f.requestCount+1,T=f.totalTokens+d+g,C=(f.averageLatency*f.requestCount+m)/v;h.set(l,{modelName:l,requestCount:v,totalTokens:T,averageLatency:C})}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 si(p,y)?p:y})},[]),o=ni((l,d,g)=>{t(m=>{let p=new Map(m.toolCallStats),h=p.get(l);if(h){let y=h.callCount+1,v=(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:v})}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 si(m,f)?m:f})},[]),a=ni(()=>{t(fg())},[]),c=hv(()=>({recordPrompt:s,recordModelUsage:r,recordToolCall:o,resetSession:a}),[s,r,o,a]);return hg.createElement(Sv.Provider,{value:c},hg.createElement(vv.Provider,{value:e},i))}import wv,{createContext as Tv,useContext as uO,useState as yg,useEffect as vg,useCallback as yr,useMemo as Sg,useRef as bc}from"react";var vr={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}},wg={fps:60,frameTime:16.67,memoryUsageMB:0,memoryPressure:"normal",totalRenders:0,avgRenderTime:0,peakRenderTime:0,isDegraded:!1,performanceLevel:"high"},xv=Tv(null);function yc({children:i,initialLevel:e,enableAdaptive:t=!0,memoryWarningMB:n=150,memoryCriticalMB:s=250}){let[r,o]=yg(wg),[a,c]=yg(vr[e||"high"]),l=bc([]),d=bc([]),g=bc(0),m=yr(C=>{let I=Date.now();l.current.push(C),l.current.length>100&&l.current.shift(),d.current.push(I);let E=I-1e3;d.current=d.current.filter(w=>w>E),o(w=>{let S=l.current,P=S.length>0?S.reduce((D,$)=>D+$,0)/S.length:0,x=Math.max(w.peakRenderTime,C),A=d.current.length,O=A>0?1e3/A:16.67,U=P>16||A<30;return Math.abs(P-w.avgRenderTime)<.5&&A===w.fps&&x===w.peakRenderTime&&U===w.isDegraded?w:{...w,totalRenders:w.totalRenders+1,avgRenderTime:P,peakRenderTime:x,fps:A,frameTime:O,isDegraded:U}})},[]);vg(()=>{let C=0,I="normal",E=()=>{if(typeof process<"u"&&process.memoryUsage){let P=process.memoryUsage().heapUsed/1024/1024,x=Math.round(P*10)/10,A="normal";if(P>=s?A="critical":P>=n&&(A="warning"),Math.abs(x-C)<1&&A===I)return;C=x,I=A,o(O=>({...O,memoryUsageMB:P,memoryPressure:A}))}};E();let w=setInterval(E,5e3);return()=>clearInterval(w)},[n,s]),vg(()=>{if(!t)return;let C=r.performanceLevel;r.memoryPressure==="critical"||r.fps<15?C="minimal":r.memoryPressure==="warning"||r.fps<30||r.avgRenderTime>32?C="low":r.fps<45||r.avgRenderTime>20?C="medium":r.fps>=55&&r.avgRenderTime<12&&r.memoryPressure==="normal"&&(C="high"),C!==r.performanceLevel&&(o(I=>({...I,performanceLevel:C})),c(vr[C]))},[t,r.fps,r.avgRenderTime,r.memoryPressure,r.performanceLevel]);let p=yr(C=>{o(I=>({...I,performanceLevel:C})),c(vr[C])},[]),h=yr(()=>{l.current=[],d.current=[],o(C=>({...wg,performanceLevel:C.performanceLevel}))},[]),f=yr((C,I)=>{c(E=>({...E,[C]:I}))},[]),y=yr(C=>{c(vr[C])},[]),v=Sg(()=>({recordRender:m,setPerformanceLevel:p,resetMetrics:h,updateSetting:f,applyPreset:y}),[m,p,h,f,y]),T=Sg(()=>({state:{metrics:r,settings:a},actions:v}),[r,a,v]);return wv.createElement(xv.Provider,{value:T},i)}function Tg({children:i,initialProjectPath:e,version:t}){return Vn.createElement(yc,{enableAdaptive:!0,memoryWarningMB:150,memoryCriticalMB:250},Vn.createElement(fc,null,Vn.createElement(pc,{enableMouse:!1},Vn.createElement(hc,null,Vn.createElement(sc,{initialProjectPath:e,version:t},Vn.createElement(ic,null,Vn.createElement(mc,null,i)))))))}import TO,{createContext as Cv,useContext as xO,useCallback as CO,useState as EO,useEffect as IO,useMemo as kO}from"react";var PO=Cv(null);import MO,{createContext as xg,useContext as RO,useCallback as NO,useState as OO,useMemo as _O,useRef as $O}from"react";var FO=xg(null),LO=xg(null);import WO,{createContext as Ev,useCallback as HO,useContext as GO,useEffect as jO,useMemo as zO,useRef as qO,useState as KO}from"react";var VO=Ev(null);import JO,{createContext as Kv,useContext as ZO,useEffect as e_,useState as t_,useMemo as n_,useCallback as s_}from"react";import*as Sc from"node:fs";var Iv="\x1B[?u",Cg="\x1B]11;?\x1B\\",kv="\x1B[>q",Pv="\x1B[c",Av="\x1B[>4;?m",Dv="\x1B[8m",Mv="\x1B[2K\r",Rv="\x1B[0m",Nv="\x1B[>u",Ov="\x1B[<u",_v="\x1B[?2004h",$v="\x1B[?2004l",Fv="\x1B[>4;2m",Lv="\x1B[>4;0m",Uv="\x1B[<u\x1B[>4;0m\x1B[?2004l",Bv=/\x1b\[\?(\d+)u/,Wv=/\x1bP>\|(.+?)(\x1b\\|\x07)/,Hv=/\x1b\[\?(\d+)(;\d+)*c/,Gv=/\x1b\]11;rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})(\x1b\\|\x07)/,jv=/\x1b\[>4;(\d+)m/;function zv(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 xs(){try{if(process.stdout?.fd!==void 0){Sc.writeSync(process.stdout.fd,Uv);return}}catch{}try{process.stdout.write(Ov),process.stdout.write(Lv),process.stdout.write($v)}catch{}}var vc=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(Cg)}async detectCapabilities(){if(!this.detectionComplete){if(!process.stdin.isTTY||!process.stdout.isTTY){this.detectionComplete=!0;return}return process.off("exit",xs),process.off("SIGTERM",xs),process.off("SIGINT",xs),process.on("exit",xs),process.on("SIGTERM",xs),process.on("SIGINT",xs),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(Gv);p&&(a=!0,this.terminalBackgroundColor=zv(p[1],p[2],p[3]))}if(!s&&Bv.test(n)&&(s=!0,this.kittySupported=!0),!c){let p=n.match(jv);if(p){c=!0;let h=parseInt(p[1],10);this.modifyOtherKeysSupported=h>=2}}if(!r){let p=n.match(Wv);p&&(r=!0,this.terminalName=p[1])}o||n.match(Hv)&&(o=!0,d())};process.stdin.on("data",g);try{Sc.writeSync(process.stdout.fd,Dv+Iv+Cg+kv+Av+Pv+Mv+Rv)}catch{d()}})}}enableSupportedModes(){try{this.kittySupported?(process.stdout.write(Nv),this.kittyEnabled=!0):this.modifyOtherKeysSupported&&process.stdout.write(Fv),process.stdout.write(_v)}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}}},qv=vc.getInstance();var o_=Kv(null);import c_,{createContext as Vv,useContext as l_,useState as u_,useCallback as d_,useMemo as g_,useRef as m_,useEffect as p_}from"react";var h_=Vv(null);import y_,{createContext as Xv,useContext as v_,useState as S_,useCallback as w_,useMemo as T_,useEffect as x_}from"react";var C_=Xv(null);import k_,{createContext as Yv,useContext as P_,useState as A_,useCallback as D_,useMemo as M_,useEffect as R_}from"react";var N_=Yv(null);import $_,{createContext as Qv,useContext as F_,useState as L_,useCallback as U_,useMemo as B_,useRef as W_,useEffect as H_}from"react";var G_=Qv(null);import{useRef as Ec,useEffect as iS,useCallback as aS}from"react";import{useInput as cS,useApp as lS}from"@jrichman/ink";import{useCallback as Ag}from"react";import{useApp as nS}from"@jrichman/ink";import{execSync as ri}from"child_process";import oi from"os";import Oe from"fs";function ii(){if(oi.platform()!=="darwin")return!1;try{let i=ri('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 ai(){if(oi.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"
2535
+ ${c.input}`:I:c.input,imageUrls:p,errors:f}}finally{n(c=>({...c,isProcessingFiles:!1}))}},setSuggestion:c=>{n(l=>({...l,suggestion:c}))},acceptSuggestion:()=>{n(c=>{if(!c.suggestion)return c;let l=c.suggestion.startsWith(c.input)?c.suggestion.slice(c.input.length):c.suggestion,d=c.input+l;return{...c,input:d,cursorPosition:d.length,suggestion:null}})},addToHistory:c=>{c.trim()&&n(l=>{if(l.history.length>0&&l.history[l.history.length-1]===c)return l;let d=[...l.history,c];return d.length>ov&&d.shift(),{...l,history:d,historyIndex:-1,tempInput:""}})},navigateHistoryUp:()=>{let c=!1;return n(l=>{if(l.history.length===0)return l;if(l.historyIndex===-1){let d=l.history.length-1;return c=!0,{...l,tempInput:l.input,historyIndex:d,input:l.history[d],cursorPosition:l.history[d].length}}if(l.historyIndex>0){let d=l.historyIndex-1;return c=!0,{...l,historyIndex:d,input:l.history[d],cursorPosition:l.history[d].length}}return l}),c},navigateHistoryDown:()=>{let c=!1;return n(l=>{if(l.historyIndex===-1)return l;if(l.historyIndex>=l.history.length-1)return c=!0,{...l,historyIndex:-1,input:l.tempInput,cursorPosition:l.tempInput.length,tempInput:""};let d=l.historyIndex+1;return c=!0,{...l,historyIndex:d,input:l.history[d],cursorPosition:l.history[d].length}}),c},resetHistoryNavigation:()=>{n(c=>({...c,historyIndex:-1,tempInput:""}))},saveUndoState:()=>{n(c=>{let l={input:c.input,cursorPosition:c.cursorPosition};if(r.current&&r.current.input===l.input)return c;r.current=l;let d=[...c.undoStack,l];return d.length>iv&&d.shift(),{...c,undoStack:d,redoStack:[]}})},undo:()=>{let c=!1;return n(l=>{if(l.undoStack.length===0)return l;let d={input:l.input,cursorPosition:l.cursorPosition},g=[...l.undoStack],m=g.pop();return c=!0,{...l,input:m.input,cursorPosition:m.cursorPosition,undoStack:g,redoStack:[...l.redoStack,d]}}),c},redo:()=>{let c=!1;return n(l=>{if(l.redoStack.length===0)return l;let d={input:l.input,cursorPosition:l.cursorPosition},g=[...l.redoStack],m=g.pop();return c=!0,{...l,input:m.input,cursorPosition:m.cursorPosition,undoStack:[...l.undoStack,d],redoStack:g}}),c}}),[t]),a=cg(()=>({state:t,actions:o}),[t,o]);return nv.createElement(gc.Provider,{value:a},i)}function br(){let i=ug(gc);if(!i)throw new Error("useInputState must be used within InputProvider");return i.state}function Kn(){let i=ug(gc);if(!i)throw new Error("useInputActions must be used within InputProvider");return i.actions}import lv,{createContext as uv,useContext as tO,useCallback as ei,useRef as gg,useEffect as dv}from"react";import{EventEmitter as cv}from"events";function dg(){process.stdout.write("\x1B[?1006l\x1B[?1002l")}var Zo=new cv;Zo.setMaxListeners(50);var gv=uv(null);function pc({children:i,enableMouse:e=!0}){let t=gg(new Set),n=gg(new Set),s=ei(c=>{t.current.add(c)},[]),r=ei(c=>{t.current.delete(c)},[]),o=ei(c=>{n.current.add(c)},[]),a=ei(c=>{n.current.delete(c)},[]);return dv(()=>{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 Zo.on("mouse",c),()=>{Zo.off("mouse",c)}},[e]),lv.createElement(gv.Provider,{value:{subscribe:s,unsubscribe:r,subscribeScroll:o,unsubscribeScroll:a,isMouseEnabled:e}},i)}import mg,{createContext as hg,useContext as oO,useState as mv,useCallback as ti,useMemo as pg}from"react";var pv=hg(null),hv=hg(null);function hc({children:i}){let[e,t]=mv(new Set),n=ti(l=>{t(d=>{if(d.has(l))return d;let g=new Set(d);return g.add(l),g})},[]),s=ti(l=>{t(d=>{if(!d.has(l))return d;let g=new Set(d);return g.delete(l),g})},[]),r=ti(()=>{t(new Set)},[]),o=ti(l=>e.has(l),[e]),a=pg(()=>({overflowingIds:e,hasOverflow:e.size>0}),[e]),c=pg(()=>({markOverflowing:n,clearOverflowing:s,clearAll:r,isOverflowing:o}),[n,s,r,o]);return mg.createElement(hv.Provider,{value:c},mg.createElement(pv.Provider,{value:a},i))}import fg,{createContext as yg,useContext as cO,useState as fv,useCallback as ni,useMemo as bv,useRef as yv}from"react";function vv(i,e){return i.modelName===e.modelName&&i.requestCount===e.requestCount&&i.totalTokens===e.totalTokens&&Math.abs(i.averageLatency-e.averageLatency)<.01}function Sv(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 si(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||!vv(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||!Sv(n,s))return!1}return!0}var wv=yg(null),Tv=yg(null);function bg(){let i=Date.now();return{promptCount:0,lastPromptTokenCount:0,totalInputTokens:0,totalOutputTokens:0,sessionStartTime:i,lastActivityTime:i,modelMetrics:new Map,toolCallStats:new Map}}function fc({children:i}){let[e,t]=fv(bg),n=yv(e),s=ni(l=>{t(d=>{let g={...d,promptCount:d.promptCount+1,lastPromptTokenCount:l,lastActivityTime:Date.now()};return si(d,g)?d:g})},[]),r=ni((l,d,g,m)=>{t(p=>{let h=new Map(p.modelMetrics),f=h.get(l);if(f){let v=f.requestCount+1,T=f.totalTokens+d+g,C=(f.averageLatency*f.requestCount+m)/v;h.set(l,{modelName:l,requestCount:v,totalTokens:T,averageLatency:C})}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 si(p,y)?p:y})},[]),o=ni((l,d,g)=>{t(m=>{let p=new Map(m.toolCallStats),h=p.get(l);if(h){let y=h.callCount+1,v=(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:v})}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 si(m,f)?m:f})},[]),a=ni(()=>{t(bg())},[]),c=bv(()=>({recordPrompt:s,recordModelUsage:r,recordToolCall:o,resetSession:a}),[s,r,o,a]);return fg.createElement(Tv.Provider,{value:c},fg.createElement(wv.Provider,{value:e},i))}import xv,{createContext as Cv,useContext as gO,useState as vg,useEffect as Sg,useCallback as yr,useMemo as wg,useRef as bc}from"react";var vr={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}},Tg={fps:60,frameTime:16.67,memoryUsageMB:0,memoryPressure:"normal",totalRenders:0,avgRenderTime:0,peakRenderTime:0,isDegraded:!1,performanceLevel:"high"},Ev=Cv(null);function yc({children:i,initialLevel:e,enableAdaptive:t=!0,memoryWarningMB:n=150,memoryCriticalMB:s=250}){let[r,o]=vg(Tg),[a,c]=vg(vr[e||"high"]),l=bc([]),d=bc([]),g=bc(0),m=yr(C=>{let I=Date.now();l.current.push(C),l.current.length>100&&l.current.shift(),d.current.push(I);let E=I-1e3;d.current=d.current.filter(w=>w>E),o(w=>{let S=l.current,P=S.length>0?S.reduce((D,$)=>D+$,0)/S.length:0,x=Math.max(w.peakRenderTime,C),A=d.current.length,O=A>0?1e3/A:16.67,U=P>16||A<30;return Math.abs(P-w.avgRenderTime)<.5&&A===w.fps&&x===w.peakRenderTime&&U===w.isDegraded?w:{...w,totalRenders:w.totalRenders+1,avgRenderTime:P,peakRenderTime:x,fps:A,frameTime:O,isDegraded:U}})},[]);Sg(()=>{let C=0,I="normal",E=()=>{if(typeof process<"u"&&process.memoryUsage){let P=process.memoryUsage().heapUsed/1024/1024,x=Math.round(P*10)/10,A="normal";if(P>=s?A="critical":P>=n&&(A="warning"),Math.abs(x-C)<1&&A===I)return;C=x,I=A,o(O=>({...O,memoryUsageMB:P,memoryPressure:A}))}};E();let w=setInterval(E,5e3);return()=>clearInterval(w)},[n,s]),Sg(()=>{if(!t)return;let C=r.performanceLevel;r.memoryPressure==="critical"||r.fps<15?C="minimal":r.memoryPressure==="warning"||r.fps<30||r.avgRenderTime>32?C="low":r.fps<45||r.avgRenderTime>20?C="medium":r.fps>=55&&r.avgRenderTime<12&&r.memoryPressure==="normal"&&(C="high"),C!==r.performanceLevel&&(o(I=>({...I,performanceLevel:C})),c(vr[C]))},[t,r.fps,r.avgRenderTime,r.memoryPressure,r.performanceLevel]);let p=yr(C=>{o(I=>({...I,performanceLevel:C})),c(vr[C])},[]),h=yr(()=>{l.current=[],d.current=[],o(C=>({...Tg,performanceLevel:C.performanceLevel}))},[]),f=yr((C,I)=>{c(E=>({...E,[C]:I}))},[]),y=yr(C=>{c(vr[C])},[]),v=wg(()=>({recordRender:m,setPerformanceLevel:p,resetMetrics:h,updateSetting:f,applyPreset:y}),[m,p,h,f,y]),T=wg(()=>({state:{metrics:r,settings:a},actions:v}),[r,a,v]);return xv.createElement(Ev.Provider,{value:T},i)}function xg({children:i,initialProjectPath:e,version:t}){return Vn.createElement(yc,{enableAdaptive:!0,memoryWarningMB:150,memoryCriticalMB:250},Vn.createElement(fc,null,Vn.createElement(pc,{enableMouse:!1},Vn.createElement(hc,null,Vn.createElement(sc,{initialProjectPath:e,version:t},Vn.createElement(ic,null,Vn.createElement(mc,null,i)))))))}import CO,{createContext as Iv,useContext as EO,useCallback as IO,useState as kO,useEffect as PO,useMemo as AO}from"react";var DO=Iv(null);import NO,{createContext as Cg,useContext as OO,useCallback as _O,useState as $O,useMemo as FO,useRef as LO}from"react";var UO=Cg(null),BO=Cg(null);import GO,{createContext as kv,useCallback as jO,useContext as zO,useEffect as qO,useMemo as KO,useRef as VO,useState as XO}from"react";var YO=kv(null);import e_,{createContext as Xv,useContext as t_,useEffect as n_,useState as s_,useMemo as r_,useCallback as o_}from"react";import*as Sc from"node:fs";var Pv="\x1B[?u",Eg="\x1B]11;?\x1B\\",Av="\x1B[>q",Dv="\x1B[c",Mv="\x1B[>4;?m",Rv="\x1B[8m",Nv="\x1B[2K\r",Ov="\x1B[0m",_v="\x1B[>u",$v="\x1B[<u",Fv="\x1B[?2004h",Lv="\x1B[?2004l",Uv="\x1B[>4;2m",Bv="\x1B[>4;0m",Wv="\x1B[<u\x1B[>4;0m\x1B[?2004l",Hv=/\x1b\[\?(\d+)u/,Gv=/\x1bP>\|(.+?)(\x1b\\|\x07)/,jv=/\x1b\[\?(\d+)(;\d+)*c/,zv=/\x1b\]11;rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})(\x1b\\|\x07)/,qv=/\x1b\[>4;(\d+)m/;function Kv(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 xs(){try{if(process.stdout?.fd!==void 0){Sc.writeSync(process.stdout.fd,Wv);return}}catch{}try{process.stdout.write($v),process.stdout.write(Bv),process.stdout.write(Lv)}catch{}}var vc=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(Eg)}async detectCapabilities(){if(!this.detectionComplete){if(!process.stdin.isTTY||!process.stdout.isTTY){this.detectionComplete=!0;return}return process.off("exit",xs),process.off("SIGTERM",xs),process.off("SIGINT",xs),process.on("exit",xs),process.on("SIGTERM",xs),process.on("SIGINT",xs),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(zv);p&&(a=!0,this.terminalBackgroundColor=Kv(p[1],p[2],p[3]))}if(!s&&Hv.test(n)&&(s=!0,this.kittySupported=!0),!c){let p=n.match(qv);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(jv)&&(o=!0,d())};process.stdin.on("data",g);try{Sc.writeSync(process.stdout.fd,Rv+Pv+Eg+Av+Mv+Dv+Nv+Ov)}catch{d()}})}}enableSupportedModes(){try{this.kittySupported?(process.stdout.write(_v),this.kittyEnabled=!0):this.modifyOtherKeysSupported&&process.stdout.write(Uv),process.stdout.write(Fv)}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}}},Vv=vc.getInstance();var a_=Xv(null);import u_,{createContext as Yv,useContext as d_,useState as g_,useCallback as m_,useMemo as p_,useRef as h_,useEffect as f_}from"react";var b_=Yv(null);import S_,{createContext as Qv,useContext as w_,useState as T_,useCallback as x_,useMemo as C_,useEffect as E_}from"react";var I_=Qv(null);import A_,{createContext as Jv,useContext as D_,useState as M_,useCallback as R_,useMemo as N_,useEffect as O_}from"react";var __=Jv(null);import L_,{createContext as Zv,useContext as U_,useState as B_,useCallback as W_,useMemo as H_,useRef as G_,useEffect as j_}from"react";var z_=Zv(null);import{useRef as Ec,useEffect as cS,useCallback as lS}from"react";import{useInput as uS,useApp as dS}from"@jrichman/ink";import{useCallback as Dg}from"react";import{useApp as rS}from"@jrichman/ink";import{execSync as ri}from"child_process";import oi from"os";import Oe from"fs";function ii(){if(oi.platform()!=="darwin")return!1;try{let i=ri('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 ai(){if(oi.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
2536
  use scripting additions
2537
2537
 
2538
2538
  set theClipboard to current application's NSPasteboard's generalPasteboard()
@@ -2545,7 +2545,7 @@ if imageData is not missing value then
2545
2545
  else
2546
2546
  return "error:No PNG image in clipboard"
2547
2547
  end if
2548
- `;Oe.writeFileSync(t,n);let s;try{s=ri(`osascript "${t}"`,{encoding:"utf8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim()}finally{try{Oe.unlinkSync(t)}catch{}}if(s.startsWith("error:"))return{data:null,size:0,error:s.replace("error:","")};if(!Oe.existsSync(e))return{data:null,size:0,error:"Failed to save clipboard image"};let r=Oe.readFileSync(e),o=r.length,c=`data:image/png;base64,${r.toString("base64")}`;try{Oe.unlinkSync(e)}catch{}return{data:c,size:o}}catch(n){try{Oe.existsSync(e)&&Oe.unlinkSync(e),Oe.existsSync(t)&&Oe.unlinkSync(t)}catch{}return{data:null,size:0,error:n.message||"Failed to read clipboard image"}}}function Eg(){if(oi.platform()!=="darwin")return!1;try{let i=ri('osascript -e "clipboard info"',{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]});return i.includes("com.adobe.pdf")||i.includes("public.rtf")||i.includes("public.html")||i.includes("public.url")}catch{return!1}}async function Ig(){if(oi.platform()!=="darwin")return{data:null,size:0,fileName:"",mimeType:"",error:"Clipboard document not supported on this platform"};let i=Date.now(),e=`/tmp/clipboard-doc-${i}.pdf`,t=`/tmp/clipboard-doc-script-${i}.scpt`;try{let n=`use framework "AppKit"
2548
+ `;Oe.writeFileSync(t,n);let s;try{s=ri(`osascript "${t}"`,{encoding:"utf8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim()}finally{try{Oe.unlinkSync(t)}catch{}}if(s.startsWith("error:"))return{data:null,size:0,error:s.replace("error:","")};if(!Oe.existsSync(e))return{data:null,size:0,error:"Failed to save clipboard image"};let r=Oe.readFileSync(e),o=r.length,c=`data:image/png;base64,${r.toString("base64")}`;try{Oe.unlinkSync(e)}catch{}return{data:c,size:o}}catch(n){try{Oe.existsSync(e)&&Oe.unlinkSync(e),Oe.existsSync(t)&&Oe.unlinkSync(t)}catch{}return{data:null,size:0,error:n.message||"Failed to read clipboard image"}}}function Ig(){if(oi.platform()!=="darwin")return!1;try{let i=ri('osascript -e "clipboard info"',{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]});return i.includes("com.adobe.pdf")||i.includes("public.rtf")||i.includes("public.html")||i.includes("public.url")}catch{return!1}}async function kg(){if(oi.platform()!=="darwin")return{data:null,size:0,fileName:"",mimeType:"",error:"Clipboard document not supported on this platform"};let i=Date.now(),e=`/tmp/clipboard-doc-${i}.pdf`,t=`/tmp/clipboard-doc-script-${i}.scpt`;try{let n=`use framework "AppKit"
2549
2549
  use scripting additions
2550
2550
 
2551
2551
  set theClipboard to current application's NSPasteboard's generalPasteboard()
@@ -2558,12 +2558,12 @@ if pdfData is not missing value then
2558
2558
  else
2559
2559
  return "error:No PDF in clipboard"
2560
2560
  end if
2561
- `;Oe.writeFileSync(t,n);let s;try{s=ri(`osascript "${t}"`,{encoding:"utf8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim()}finally{try{Oe.unlinkSync(t)}catch{}}if(s.startsWith("error:"))return{data:null,size:0,fileName:"",mimeType:"",error:s.replace("error:","")};if(!Oe.existsSync(e))return{data:null,size:0,fileName:"",mimeType:"",error:"Failed to save clipboard document"};let r=Oe.readFileSync(e),o=r.length,c=`data:application/pdf;base64,${r.toString("base64")}`,l=`clipboard-${i}.pdf`;try{Oe.unlinkSync(e)}catch{}return{data:c,size:o,fileName:l,mimeType:"application/pdf"}}catch(n){try{Oe.existsSync(e)&&Oe.unlinkSync(e),Oe.existsSync(t)&&Oe.unlinkSync(t)}catch{}return{data:null,size:0,fileName:"",mimeType:"",error:n.message||"Failed to read clipboard document"}}}ke();Ot();import Sn from"axios";var Vt=class i{static instance;authService;deviceRegistration;baseURL="https://snowx.ai/api-beta/api";constructor(){this.authService=Z.getInstance(),this.deviceRegistration=Ne.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 Sn.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 Sn.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 Sn.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 Sn.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 Sn.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 Sn.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 Sn.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 Sn.delete(`${this.baseURL}/integrations/telegram`,{headers:e,data:{device_id:t,user_id:n}}),!0}catch{return!1}}};ke();V();import{EventEmitter as Jv}from"events";import Zv from"axios";var eS="https://snowx.ai/api-beta/api/users/me/quota",kg=50,tS=300*1e3,wc=class i extends Jv{static instance;authService;cachedQuota=null;lastFetchTime=0;pollTimer=null;constructor(){super(),this.authService=Z.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 Zv.get(eS,{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>=kg?{percent:Math.round(t.percentUsed),type:"weekly",resetsAt:t.resetsAt,resetsInSeconds:t.resetsInSeconds}:n?.percentUsed>=kg?{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)},tS))}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}clearCache(){this.cachedQuota=null,this.lastFetchTime=0}},Sr=wc.getInstance();function Pg(i){return i>=95?"critical":i>=90?"high":i>=70?"warning":i>=50?"notice":"normal"}function wr(i,e){if(!i&&(!e||e<=0))return"";let t=i?new Date(i):new Date(Date.now()+e*1e3),n=Intl.DateTimeFormat().resolvedOptions().timeZone;return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short",timeZone:n}).format(t)}import Tc from"os";import Tr from"path";function ci(){let{exit:i}=nS(),e=jn(),t=Pt(),n=zn(),s=Kt(),r=Kn(),o=Ag(c=>c.startsWith("/"),[]);return{handleCommand:Ag(async c=>{if(!c.startsWith("/"))return{handled:!1};let l=c.toLowerCase().trim();if(l==="/history"||l==="/hist")return s.showConversationList(),r.clearInput(),{handled:!0,clearInput:!0};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(),s.hideConversationList(),{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==="/attachments"||l==="/att"){let{attachmentManager:d}=n,g=d.getImages(),m=d.getDocuments(),p=d.getTotalCount(),h=d.getMaxAllowed();if(p===0)return t.addSystemMessage("[i] No attachments. Use /img (clipboard), /doc (PDF), or /file <path>"),r.clearInput(),{handled:!0,clearInput:!0};let f=`Attachments (${p}/${h}):
2561
+ `;Oe.writeFileSync(t,n);let s;try{s=ri(`osascript "${t}"`,{encoding:"utf8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim()}finally{try{Oe.unlinkSync(t)}catch{}}if(s.startsWith("error:"))return{data:null,size:0,fileName:"",mimeType:"",error:s.replace("error:","")};if(!Oe.existsSync(e))return{data:null,size:0,fileName:"",mimeType:"",error:"Failed to save clipboard document"};let r=Oe.readFileSync(e),o=r.length,c=`data:application/pdf;base64,${r.toString("base64")}`,l=`clipboard-${i}.pdf`;try{Oe.unlinkSync(e)}catch{}return{data:c,size:o,fileName:l,mimeType:"application/pdf"}}catch(n){try{Oe.existsSync(e)&&Oe.unlinkSync(e),Oe.existsSync(t)&&Oe.unlinkSync(t)}catch{}return{data:null,size:0,fileName:"",mimeType:"",error:n.message||"Failed to read clipboard document"}}}ke();Ot();import Sn from"axios";var Vt=class i{static instance;authService;deviceRegistration;baseURL="https://snowx.ai/api-beta/api";constructor(){this.authService=Z.getInstance(),this.deviceRegistration=Ne.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 Sn.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 Sn.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 Sn.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 Sn.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 Sn.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 Sn.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 Sn.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 Sn.delete(`${this.baseURL}/integrations/telegram`,{headers:e,data:{device_id:t,user_id:n}}),!0}catch{return!1}}};ke();V();import{EventEmitter as eS}from"events";import tS from"axios";var nS="https://snowx.ai/api-beta/api/users/me/quota",Pg=50,sS=300*1e3,wc=class i extends eS{static instance;authService;cachedQuota=null;lastFetchTime=0;pollTimer=null;constructor(){super(),this.authService=Z.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 tS.get(nS,{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>=Pg?{percent:Math.round(t.percentUsed),type:"weekly",resetsAt:t.resetsAt,resetsInSeconds:t.resetsInSeconds}:n?.percentUsed>=Pg?{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)},sS))}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}clearCache(){this.cachedQuota=null,this.lastFetchTime=0}},Sr=wc.getInstance();function Ag(i){return i>=95?"critical":i>=90?"high":i>=70?"warning":i>=50?"notice":"normal"}function wr(i,e){if(!i&&(!e||e<=0))return"";let t=i?new Date(i):new Date(Date.now()+e*1e3),n=Intl.DateTimeFormat().resolvedOptions().timeZone;return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short",timeZone:n}).format(t)}import Tc from"os";import Tr from"path";function ci(){let{exit:i}=rS(),e=jn(),t=Pt(),n=zn(),s=Kt(),r=Kn(),o=Dg(c=>c.startsWith("/"),[]);return{handleCommand:Dg(async c=>{if(!c.startsWith("/"))return{handled:!1};let l=c.toLowerCase().trim();if(l==="/history"||l==="/hist")return s.showConversationList(),r.clearInput(),{handled:!0,clearInput:!0};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(),s.hideConversationList(),{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==="/attachments"||l==="/att"){let{attachmentManager:d}=n,g=d.getImages(),m=d.getDocuments(),p=d.getTotalCount(),h=d.getMaxAllowed();if(p===0)return t.addSystemMessage("[i] No attachments. Use /img (clipboard), /doc (PDF), or /file <path>"),r.clearInput(),{handled:!0,clearInput:!0};let f=`Attachments (${p}/${h}):
2562
2562
  `;return g.forEach((y,v)=>{let T=(y.size/1024/1024).toFixed(2),C=y.source==="clipboard"?"clipboard image":"image";f+=` ${v+1}. [IMG] ${C} (${T}MB)
2563
2563
  `}),m.forEach((y,v)=>{let T=(y.size/1024/1024).toFixed(2),C=y.fileName.split(".").pop()?.toUpperCase()||"FILE";f+=` ${g.length+v+1}. [${C}] ${y.fileName} (${T}MB)
2564
2564
  `}),f+=`
2565
- Use /clear to remove all attachments`,t.addSystemMessage(f),r.clearInput(),{handled:!0,clearInput:!0}}if(l==="/img"||l==="/image"||l==="/paste"){if(r.clearInput(),!ii())return t.addSystemMessage("[!] No image in clipboard. Copy an image (Cmd+C on Mac), then run /img"),{handled:!0,clearInput:!0};try{let d=await ai();d.data?(await 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){d.message.includes("Maximum")?t.addSystemMessage("[!] Maximum 3 attachments allowed"):d.message.includes("too large")?t.addSystemMessage(`[!] ${d.message}`):t.addSystemMessage(`[!] Error: ${d.message}`)}return{handled:!0,clearInput:!0}}if(l==="/doc"||l==="/pdf"||l==="/document"){if(r.clearInput(),!Eg())return t.addSystemMessage("[!] No PDF in clipboard. Copy a PDF file, then run /doc"),{handled:!0,clearInput:!0};try{let d=await Ig();d.data?(await r.addDocument(d.data,d.fileName,d.mimeType,d.size),t.addSystemMessage(`[OK] Document added: ${d.fileName}`)):t.addSystemMessage(`[!] Failed to read clipboard document: ${d.error||"Unknown error"}`)}catch(d){t.addSystemMessage(`[!] Error reading clipboard: ${d.message}`)}return{handled:!0,clearInput:!0}}if(l.startsWith("/file ")){let d=c.substring(6).trim();if(r.clearInput(),!d)return t.addSystemMessage(`[!] Usage: /file <path>
2566
- Example: /file ~/Desktop/report.pdf`),{handled:!0,clearInput:!0};try{let g=d.startsWith("~")?Tr.join(Tc.homedir(),d.slice(1)):d,m=Tr.resolve(g),p=Tc.homedir(),h=process.cwd();if(!m.startsWith(p)&&!m.startsWith(h)&&!m.startsWith("/tmp"))return t.addSystemMessage("[!] Path must be in home (~), current project, or /tmp"),{handled:!0,clearInput:!0};if(!(await(await import("fs/promises")).stat(m)).isFile())return t.addSystemMessage("[!] Path is not a file"),{handled:!0,clearInput:!0};let{categorizeFile:v}=await Promise.resolve().then(()=>(dc(),ig)),T=v(m);if(T.type==="blocked")return t.addSystemMessage(`[!] File type blocked: .${T.extension}`),{handled:!0,clearInput:!0};await r.addFileAttachment(m),t.addSystemMessage(`[OK] ${T.type} added: ${Tr.basename(m)}`)}catch(g){g.code==="ENOENT"?t.addSystemMessage("[!] File not found"):g.code==="EACCES"?t.addSystemMessage("[!] Permission denied"):g.message.includes("too large")?t.addSystemMessage(`[!] ${g.message}`):g.message.includes("Maximum")?t.addSystemMessage(`[!] ${g.message}`):t.addSystemMessage(`[!] Error: ${g.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}
2565
+ Use /clear to remove all attachments`,t.addSystemMessage(f),r.clearInput(),{handled:!0,clearInput:!0}}if(l==="/img"||l==="/image"||l==="/paste"){if(r.clearInput(),!ii())return t.addSystemMessage("[!] No image in clipboard. Copy an image (Cmd+C on Mac), then run /img"),{handled:!0,clearInput:!0};try{let d=await ai();d.data?(await 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){d.message.includes("Maximum")?t.addSystemMessage("[!] Maximum 3 attachments allowed"):d.message.includes("too large")?t.addSystemMessage(`[!] ${d.message}`):t.addSystemMessage(`[!] Error: ${d.message}`)}return{handled:!0,clearInput:!0}}if(l==="/doc"||l==="/pdf"||l==="/document"){if(r.clearInput(),!Ig())return t.addSystemMessage("[!] No PDF in clipboard. Copy a PDF file, then run /doc"),{handled:!0,clearInput:!0};try{let d=await kg();d.data?(await r.addDocument(d.data,d.fileName,d.mimeType,d.size),t.addSystemMessage(`[OK] Document added: ${d.fileName}`)):t.addSystemMessage(`[!] Failed to read clipboard document: ${d.error||"Unknown error"}`)}catch(d){t.addSystemMessage(`[!] Error reading clipboard: ${d.message}`)}return{handled:!0,clearInput:!0}}if(l.startsWith("/file ")){let d=c.substring(6).trim();if(r.clearInput(),!d)return t.addSystemMessage(`[!] Usage: /file <path>
2566
+ Example: /file ~/Desktop/report.pdf`),{handled:!0,clearInput:!0};try{let g=d.startsWith("~")?Tr.join(Tc.homedir(),d.slice(1)):d,m=Tr.resolve(g),p=Tc.homedir(),h=process.cwd();if(!m.startsWith(p)&&!m.startsWith(h)&&!m.startsWith("/tmp"))return t.addSystemMessage("[!] Path must be in home (~), current project, or /tmp"),{handled:!0,clearInput:!0};if(!(await(await import("fs/promises")).stat(m)).isFile())return t.addSystemMessage("[!] Path is not a file"),{handled:!0,clearInput:!0};let{categorizeFile:v}=await Promise.resolve().then(()=>(dc(),ag)),T=v(m);if(T.type==="blocked")return t.addSystemMessage(`[!] File type blocked: .${T.extension}`),{handled:!0,clearInput:!0};await r.addFileAttachment(m),t.addSystemMessage(`[OK] ${T.type} added: ${Tr.basename(m)}`)}catch(g){g.code==="ENOENT"?t.addSystemMessage("[!] File not found"):g.code==="EACCES"?t.addSystemMessage("[!] Permission denied"):g.message.includes("too large")?t.addSystemMessage(`[!] ${g.message}`):g.message.includes("Maximum")?t.addSystemMessage(`[!] ${g.message}`):t.addSystemMessage(`[!] Error: ${g.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}
2567
2567
 
2568
2568
  Usage: /export [markdown|json|text]
2569
2569
  - markdown (default): Export as .md file
@@ -2592,11 +2592,11 @@ ${"─".repeat(30)}
2592
2592
  Resets in ${wr(h.resetsAt,h.resetsInSeconds)}`),y+=`
2593
2593
  `,t.addSystemMessage(y)}catch(d){t.addSystemMessage(`[!] Error fetching usage: ${d.message}`)}return{handled:!0,clearInput:!0}}return t.addSystemMessage(`Unknown command: ${c}
2594
2594
 
2595
- Type /help to see available commands.`),r.clearInput(),{handled:!0,clearInput:!0}},[i,e,t,n.authService,s,r]),isCommand:o}}import{useRef as wn,useCallback as Xt,useEffect as sS}from"react";var xc=typeof requestAnimationFrame<"u"?requestAnimationFrame:i=>setImmediate(i),Cs=typeof cancelAnimationFrame<"u"?cancelAnimationFrame:i=>clearImmediate(i);var rS={flushInterval:16,maxBufferSize:32,detectPaste:!0,pasteThreshold:50,immediateFlushChars:[`
2596
- `,"\r"," "]};function Dg(i,e){let t={...rS,...e},n=wn(""),s=wn(0),r=wn(0),o=wn(0),a=wn(0),c=wn(null),l=wn(null),d=wn(i);d.current=i;let g=Xt(()=>{if(n.current===""&&s.current===0)return null;let E=Date.now()-r.current,w=t.detectPaste&&a.current>3&&E<t.pasteThreshold*a.current;return{chars:n.current,backspaces:s.current,isPaste:w,startTime:r.current}},[t.detectPaste,t.pasteThreshold]),m=Xt(()=>{let I=g();I&&(n.current="",s.current=0,a.current=0,r.current=0,d.current(I)),c.current!==null&&(Cs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null)},[g]),p=Xt(()=>{c.current===null&&(c.current=xc(()=>{c.current=null,l.current&&clearTimeout(l.current),l.current=setTimeout(m,t.flushInterval)}))},[m,t.flushInterval]),h=Xt(I=>{let E=Date.now();r.current===0&&(r.current=E),o.current=E,a.current++,n.current+=I,t.immediateFlushChars.includes(I)||n.current.length>=t.maxBufferSize?m():p()},[m,p,t.immediateFlushChars,t.maxBufferSize]),f=Xt(()=>{let I=Date.now();r.current===0&&(r.current=I),a.current++,n.current.length>0?n.current=n.current.slice(0,-1):s.current++,p()},[p]),y=Xt(()=>{let I=g();return I&&(n.current="",s.current=0,a.current=0,r.current=0),c.current!==null&&(Cs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),I},[g]),v=Xt(()=>g(),[g]),T=Xt(()=>{n.current="",s.current=0,a.current=0,r.current=0,c.current!==null&&(Cs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null)},[]),C=Xt(()=>n.current===""&&s.current===0,[]);return sS(()=>()=>{c.current!==null&&Cs(c.current),l.current&&clearTimeout(l.current)},[]),{pushChar:h,pushBackspace:f,flush:y,peek:v,clear:T,isEmpty:C}}import{useRef as Tn,useEffect as Cc,useCallback as Es,useState as oS,useMemo as Mg}from"react";function Rg(i){let e=Tn(0),t=Tn([]),n=Tn(0),s=Tn(0),r=Tn([]);return Cc(()=>{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)}}),Mg(()=>{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 Ng(i){let{targetFrameTime:e=16.67,warningThreshold:t=.8,criticalThreshold:n=1}=i||{},s=Tn(0),r=Tn(0),o=Es(()=>{s.current=performance.now(),r.current=0},[]),a=Es(()=>performance.now()-s.current+r.current<e*n,[e,n]),c=Es(d=>{r.current+=d;let g=e-r.current;return Math.max(0,g)},[e]),l=Es(()=>{let g=(performance.now()-s.current+r.current)/e;return g>=n?"critical":g>=t?"warning":"ok"},[e,t,n]);return Cc(()=>{o()}),{hasBudget:a,useBudget:c,resetBudget:o,getBudgetStatus:l}}function Og(i){let{warningThresholdMB:e=100,criticalThresholdMB:t=200,checkInterval:n=5e3}=i||{},[s,r]=oS(0);Cc(()=>{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=Mg(()=>s>=t?"critical":s>=e?"warning":"normal",[s,e,t]),a=Es(()=>{typeof global<"u"&&global.gc&&global.gc()},[]);return{heapUsedMB:s,pressure:o,requestGC:a}}function _g(i){let e=Tn(i);return e.current=i,Es(((...t)=>e.current(...t)),[])}function $g({onSubmit:i,enableProfiling:e=!1,bufferFlushInterval:t=16}){let{exit:n}=lS(),s=jn(),r=Pt(),o=Ts(),a=Kt(),c=br(),l=Kn(),{handleCommand:d,isCommand:g}=ci(),m=Ng({targetFrameTime:16.67}),{pressure:p}=Og({warningThresholdMB:150,criticalThresholdMB:250}),h=e?Rg("OptimizedKeyboardInput"):void 0,f=Ec(!1),y=Ec(0),v=Ec(0),T=500,C=_g(i),I=aS(w=>{if(w.isPaste)l.addPastedContent(w.chars);else{for(let S=0;S<w.backspaces;S++)l.deleteAtCursor();w.chars&&(l.insertAtCursor(w.chars),c.input.slice(0,c.cursorPosition)+w.chars+c.input.slice(c.cursorPosition)==="/"&&!o.showCommandMenu&&a.showCommandMenu())}},[l,c.input,c.cursorPosition,o.showCommandMenu,a]),E=Dg(I,{flushInterval:t,maxBufferSize:64,detectPaste:!0,pasteThreshold:50});return cS((w,S)=>{let P=Date.now(),x=P-y.current;if(y.current=P,!(w.startsWith("[<")||w.startsWith("[M")||/^\[<?\d+;\d+;\d+[mM]?/.test(w)||/^\d+[mM]/.test(w)||/^;\d+;\d+[mM]/.test(w)||/^\d+;\d+[mM]/.test(w))){if(S.escape){E.flush();let A=Date.now(),O=A-v.current;if(v.current=A,O<T){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||o.showConversationList){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.showConversationList&&!o.showWizard&&!(o.showCommandMenu&&(S.upArrow||S.downArrow||S.return))){if(S.ctrl&&w==="l"){E.flush(),process.stdout.write("\x1B[2J\x1B[H");return}if(S.ctrl&&w==="c"){E.flush(),s.isLoading?r.stopStreaming():n();return}if(S.ctrl&&w==="r"){E.flush(),o.isReverseSearchActive||a.startReverseSearch();return}if(S.ctrl&&w==="z"){E.flush(),l.undo();return}if(S.ctrl&&(w==="y"||w==="Z")){E.flush(),l.redo();return}if(w===""||S.ctrl&&w==="v"){if(f.current)return;if(ii()){f.current=!0,ai().then(A=>{f.current=!1,A.data&&(E.flush(),l.addClipboardImage(A.data,A.size))}).catch(()=>{f.current=!1});return}return}if(S.tab){E.flush(),c.suggestion&&l.acceptSuggestion();return}if(w==="?"&&c.input===""&&!o.showCommandMenu){E.flush(),a.toggleHelp();return}if(S.return&&!o.isReverseSearchActive){E.flush();let A=c.pastedTexts.filter(U=>!U.error||U.type==="text");(c.input.trim()||A.length>0)&&C();return}if(S.upArrow&&!o.showCommandMenu&&!o.isReverseSearchActive){E.flush(),l.navigateHistoryUp();return}if(S.downArrow&&!o.showCommandMenu&&!o.isReverseSearchActive){E.flush(),l.navigateHistoryDown();return}if(S.leftArrow){E.flush(),l.moveCursorLeft();return}if(S.rightArrow){E.flush(),l.moveCursorRight();return}if(S.ctrl&&w==="a"){E.flush(),l.moveCursorToStart();return}if(S.ctrl&&w==="e"){E.flush(),l.moveCursorToEnd();return}if(S.delete||S.backspace){E.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&&w){let A=w.includes(`
2597
- `),O=w.length>50;if(A||O){E.flush(),l.addPastedContent(w);return}E.pushChar(w)}}}}),iS(()=>()=>{E.clear()},[E]),{handleCommand:d,isCommand:g,renderProfile:h,memoryPressure:p,frameBudgetStatus:m.getBudgetStatus()}}import{useState as xr,useCallback as At,useMemo as hS,useRef as Lg,useEffect as Ug}from"react";import{useEffect as uS,useRef as Ic}from"react";import{useInput as RL}from"@jrichman/ink";var dS=0,li=[];function gS(){return`keypress-${++dS}`}function mS(i,e,t){let n=gS();return li.push({id:n,handler:i,priority:e,isActive:t}),li.sort((s,r)=>r.priority-s.priority),n}function pS(i){let e=li.findIndex(t=>t.id===i);e!==-1&&li.splice(e,1)}function Fg(i,e={}){let{priority:t=0,isActive:n=!0}=e,s=Ic(i),r=Ic(n),o=Ic(null);s.current=i,r.current=n,uS(()=>(o.current=mS((a,c)=>s.current(a,c),t,()=>r.current),()=>{o.current&&(pS(o.current),o.current=null)}),[t])}function Bg(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]=xr(o),[p,h]=xr(!1),[f,y]=xr(0),[v,T]=xr([]),[C,I]=xr(-1),E=Lg(a),w=Lg(c);E.current=a,w.current=c;let S=hS(()=>{if(!g)return[];let B=[],j;try{if(r)j=new RegExp(g,s?"g":"gi");else{let ne=g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");j=new RegExp(ne,s?"g":"gi")}}catch{return[]}return e.forEach((ne,pe)=>{let ue=t(ne),ct=j.exec(ue);ct&&B.push({item:ne,index:pe,matchStart:ct.index,matchEnd:ct.index+ct[0].length}),j.lastIndex=0}),n==="backward"&&B.reverse(),B},[e,g,t,n,s,r]),P=S.length>0&&S[f]||null,x=S.length,A=x>0,O=At(B=>{m(B),y(0),I(-1)},[]);Ug(()=>{E.current?.(g,S)},[g,S]),Ug(()=>{P&&w.current?.(P)},[P]);let U=At(()=>{x!==0&&y(B=>(B+1)%x)},[x]),D=At(()=>{x!==0&&y(B=>(B-1+x)%x)},[x]),$=At(B=>{B>=0&&B<x&&y(B)},[x]),_=At(()=>{g&&T(B=>{let j=B.filter(ne=>ne!==g);return[g,...j].slice(0,d)}),m(""),y(0),I(-1)},[g,d]),F=At(()=>{h(!0),O("")},[O]),z=At(()=>{_(),h(!1)},[_]),G=At(()=>{v.length!==0&&I(B=>{let j=Math.min(B+1,v.length-1);return m(v[j]||""),j})},[v]),M=At(()=>{C<0||I(B=>{let j=B-1;return j<0?m(""):m(v[j]||""),j})},[v,C]),R=At(B=>{m(j=>j+B),y(0),I(-1)},[]),H=At(()=>{m(B=>B.slice(0,-1)),y(0),I(-1)},[]);return Fg((B,j)=>{if(p){if(j.downArrow||j.ctrl&&B==="n")return U(),!0;if(j.upArrow||j.ctrl&&B==="p")return D(),!0;if(j.ctrl&&j.upArrow)return G(),!0;if(j.ctrl&&j.downArrow)return M(),!0;if(j.escape)return z(),!0;if(j.return)return _(),h(!1),!0;if(j.backspace||j.delete)return H(),!0;if(B&&B.length===1&&!j.ctrl&&!j.meta)return R(B),!0}},{isActive:l&&p,priority:100}),{query:g,setQuery:O,matches:S,currentMatchIndex:f,currentMatch:P,nextMatch:U,prevMatch:D,goToMatch:$,clear:_,isSearching:p,startSearch:F,stopSearch:z,history:v,historyUp:G,historyDown:M,append:R,backspace:H,matchCount:x,hasMatches:A}}function Wg(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 J,{memo as Pc,useMemo as yS}from"react";import{Box as Ht,Text as we}from"@jrichman/ink";import Hg 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"},fS={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}},kc={name:"Default Dark",type:"dark",colors:Qe,semantic:fS};var bS=kc;function Is(){return bS}var k={get text(){return Is().semantic.text},get background(){return Is().semantic.background},get border(){return Is().semantic.border},get ui(){return Is().semantic.ui},get status(){return Is().semantic.status},get colors(){return Is().colors}};function vS(i,e){let t=i.toLowerCase().replace(/_/g,"");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==="readspecialfile")return{displayName:"ReadFile",mainArg:e?.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==="runcommand"){let r=e?.command;return{displayName:"Bash",mainArg:r?r.length>50?r.substring(0,47)+"...":r:void 0}}if(t==="webfetch"||t==="readurl")return{displayName:"Fetch",mainArg:e?.url};if(t==="websearch"||t==="searchtool")return{displayName:"Search",mainArg:e?.query};if(t==="browserautomation")return{displayName:"Browser",mainArg:e?.task?e.task.substring(0,40):void 0};if(t==="mapurl")return{displayName:"MapURL",mainArg:e?.url};if(t==="task"||t==="spawnagents")return{displayName:"Task",mainArg:e?.subagent_type||e?.description};if(t==="spawnagentstool")return{displayName:"Agents",mainArg:void 0};if(t==="uploadfile")return{displayName:"Upload",mainArg:e?.file_path};if(t==="deployziphtml"||t==="deployziphtmltool")return{displayName:"Deploy",mainArg:e?.zip_file_path};if(t==="generateimage")return{displayName:"Image",mainArg:e?.prompt?.substring(0,40)};if(t==="generatevideofromtext"||t==="generatevideofromimage")return{displayName:"Video",mainArg:void 0};if(t==="generatemusic")return{displayName:"Music",mainArg:void 0};if(t==="sendemailtouser")return{displayName:"Email",mainArg:e?.subject};if(t==="orionphonecall")return{displayName:"Call",mainArg:e?.phone_number};if(t==="httprequest")return{displayName:"HTTP",mainArg:e?.url?e.url.replace(/^https?:\/\//,"").substring(0,40):void 0};if(t==="addmemory"||t==="quorymemory")return{displayName:"Memory",mainArg:void 0};if(t==="searchconversationhistory"||t==="searchpastcommands"||t==="searchpastcode")return{displayName:"History",mainArg:e?.query};if(t==="todowrite")return{displayName:"",mainArg:void 0};let n=i.replace(/_/g," ").replace(/\b\w/g,r=>r.toUpperCase()).substring(0,20),s=e?.description||e?.query||e?.path||e?.url;return{displayName:n,mainArg:s}}function SS(i){if(!i)return"";let e=i.split("/");return e.length<=2?i:".../"+e.slice(-2).join("/")}function wS(i){if(!i)return"";let e=i.split(`
2598
- `).filter(t=>t.trim());return e.length>5?`${e[0].substring(0,80).trim()} (+${e.length-1} lines)`:e.length>1?`${e.length} lines`:i.length>120?i.substring(0,117)+"...":i.trim()}var TS=Pc(function({totalRunning:e,totalCompleted:t,totalTools:n}){let s=e===0;return J.createElement(Ht,{marginBottom:0},s?J.createElement(we,{color:k.status.success},"✓ "):J.createElement(we,{color:k.status.warning},J.createElement(Hg,{type:"dots"})," "),J.createElement(we,{color:k.text.secondary,bold:!0},s?`${t} tools completed`:`Running ${e} tool${e>1?"s":""} in parallel`),!s&&t>0&&J.createElement(we,{color:k.ui.muted}," (",t,"/",n," done)"))}),ks=Pc(function({tool:e,indent:t=!1,onConfirm:n,onDecline:s}){let{displayName:r,mainArg:o}=vS(e.name,e.arguments);if(!r)return null;let a=e.state==="running",c=e.state==="completed",l=e.state==="failed",d=e.state==="pending_confirmation",g=o?SS(o):void 0;return J.createElement(Ht,{flexDirection:"column",paddingLeft:t?2:0},J.createElement(Ht,null,a&&J.createElement(we,{color:k.status.warning},J.createElement(Hg,{type:"dots"})),c&&J.createElement(we,{color:k.status.success},"✓"),l&&J.createElement(we,{color:k.status.error},"✗"),d&&J.createElement(we,{color:"#f59e0b"},"⚠"),J.createElement(we,null," "),J.createElement(we,{color:k.text.primary,bold:!0},r),g&&J.createElement(J.Fragment,null,J.createElement(we,{color:k.ui.muted},"("),J.createElement(we,{color:k.text.secondary},g),J.createElement(we,{color:k.ui.muted},")"))),c&&e.output&&J.createElement(Ht,{paddingLeft:2},J.createElement(we,{color:k.ui.muted},"└ "),J.createElement(we,{color:k.ui.muted},wS(e.output))),l&&e.error&&J.createElement(Ht,{paddingLeft:2},J.createElement(we,{color:k.ui.muted},"└ "),J.createElement(we,{color:k.status.error},e.error.substring(0,80))),d&&J.createElement(Ht,{flexDirection:"column",paddingLeft:2,marginTop:0},e.confirmationCommand&&J.createElement(Ht,null,J.createElement(we,{color:k.ui.muted},"└ "),J.createElement(we,{color:k.text.secondary},e.confirmationCommand.substring(0,80))),J.createElement(Ht,{marginTop:0},J.createElement(we,{color:k.ui.muted}," "),J.createElement(we,{color:"#f59e0b"},"Allow? "),J.createElement(we,{color:k.status.success},"[y] Yes "),J.createElement(we,{color:k.status.error},"[n] No"))))});function xS({activeTools:i,onConfirmationConfirm:e,onConfirmationDecline:t}){let{running:n,completed:s,failed:r,pending:o,hasParallel:a}=yS(()=>{if(i.size===0)return{running:[],completed:[],failed:[],pending:[],hasParallel:!1};let c=Array.from(i.values()).filter(f=>f.name.toLowerCase().replace(/_/g,"")!=="todowrite"),l=c.filter(f=>f.state==="running"),d=c.filter(f=>f.state==="completed"),g=c.filter(f=>f.state==="failed"),m=c.filter(f=>f.state==="pending_confirmation"),p=l.length+d.length>1&&m.length===0,h=p?d:d.sort((f,y)=>y.startTime.getTime()-f.startTime.getTime()).slice(0,1);return{running:l,completed:h,failed:g,pending:m,hasParallel:p}},[i]);if(n.length===0&&s.length===0&&r.length===0&&o.length===0)return null;if(a){let c=[...n,...s];return J.createElement(Ht,{flexDirection:"column",paddingX:1,marginY:1},J.createElement(TS,{totalRunning:n.length,totalCompleted:s.length,totalTools:c.length}),c.map(l=>J.createElement(ks,{key:l.toolCallId,tool:l,indent:!0,onConfirm:e,onDecline:t})),r.map(l=>J.createElement(ks,{key:l.toolCallId,tool:l,indent:!0})))}return J.createElement(Ht,{flexDirection:"column",paddingX:1,marginY:1},o.map(c=>J.createElement(ks,{key:c.toolCallId,tool:c,onConfirm:e,onDecline:t})),n.map(c=>J.createElement(ks,{key:c.toolCallId,tool:c})),s.map(c=>J.createElement(ks,{key:c.toolCallId,tool:c})),r.map(c=>J.createElement(ks,{key:c.toolCallId,tool:c})))}var Gg=Pc(xS);import ce,{memo as Ac,useMemo as jg,useState as CS,useEffect as ES}from"react";import{Box as Gt,Text as _e}from"@jrichman/ink";import zg from"ink-spinner";function IS(i,e=60){return i?i.length<=e?i:i.substring(0,e-3)+"...":"Processing..."}var kS=Ac(function({agent:e}){let t=IS(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"?ce.createElement(_e,{color:"cyan"},ce.createElement(zg,{type:"dots"})):e.status==="completed"?ce.createElement(_e,{color:"#5AD8A6"},"✓"):e.status==="failed"?ce.createElement(_e,{color:"#F5716C"},"✗"):e.status==="timeout"?ce.createElement(_e,{color:"#FBBF24"},"⏱"):ce.createElement(_e,{color:"#6B7280"},"○"),r=n(e.status);return ce.createElement(Gt,{flexDirection:"column",marginLeft:2},ce.createElement(Gt,null,s(),ce.createElement(_e,{color:r,bold:!0}," Agent #",e.agentNumber)),ce.createElement(Gt,{marginLeft:2},ce.createElement(_e,{color:"#9CA3AF"},t)),e.endTime&&e.startTime&&ce.createElement(Gt,{marginLeft:2},ce.createElement(_e,{color:"#6B7280"},((e.endTime.getTime()-e.startTime.getTime())/1e3).toFixed(1),"s")),e.error&&ce.createElement(Gt,{marginLeft:2},ce.createElement(_e,{color:"#F5716C"},"Error: ",e.error.substring(0,60),e.error.length>60?"...":"")),e.streamingContent&&e.status==="running"&&ce.createElement(Gt,{marginLeft:2},ce.createElement(_e,{color:"#6B7280"},e.streamingContent.split(`
2599
- `)[0]?.substring(0,50),"...")))}),PS=Ac(function({operation:e}){let{agents:t,completed:n,failed:s,running:r,total:o}=jg(()=>{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"?ce.createElement(_e,{color:"cyan"},ce.createElement(zg,{type:"dots"})):e.status==="completed"?ce.createElement(_e,{color:"#5AD8A6"},"✓"):ce.createElement(_e,{color:"#F5716C"},"✗"),l=e.status==="completed"?"#5AD8A6":e.status==="failed"?"#F5716C":"cyan";return ce.createElement(Gt,{flexDirection:"column"},ce.createElement(Gt,null,c(),ce.createElement(_e,{color:l,bold:!0}," ",a()),ce.createElement(_e,{color:"#6B7280"}," "),ce.createElement(_e,{backgroundColor:"#3F3F46",color:"whiteBright"}," ",n,"/",o," "),r>0&&ce.createElement(_e,{color:"cyan"}," (",r," running)"),s>0&&ce.createElement(_e,{color:"#F5716C"}," [",s," failed]")),ce.createElement(Gt,{flexDirection:"column",marginTop:1},t.map(d=>ce.createElement(kS,{key:d.agentNumber,agent:d}))))});function AS({operations:i}){let[e,t]=CS(0);ES(()=>{let s=setInterval(()=>{Array.from(i.values()).some(o=>o.status==="completed"||o.status==="failed")&&t(o=>o+1)},500);return()=>clearInterval(s)},[]);let n=jg(()=>i.size===0?[]:Array.from(i.entries()).filter(([s,r])=>r.status==="running"||r.status==="starting"?!0:r.endTime?Date.now()-r.endTime.getTime()<3e3:!1),[i,e]);return n.length===0?null:ce.createElement(Gt,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},n.map(([s,r])=>ce.createElement(PS,{key:s,operation:r})))}var qg=Ac(AS);import Xn,{memo as DS}from"react";import{Box as MS,Text as Cr}from"@jrichman/ink";import RS from"ink-spinner";function NS(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 OS(i,e=60){return i?i.length<=e?i:i.substring(0,e-3)+"...":"Processing request..."}function _S({session:i}){if(!i)return null;let e=NS(i.source),t=OS(i.message);return Xn.createElement(MS,{flexDirection:"row",paddingX:1,marginY:1,borderStyle:"round",borderColor:k.border.default},Xn.createElement(Cr,{color:k.status.warning},Xn.createElement(RS,{type:"dots"})),Xn.createElement(Cr,null," "),Xn.createElement(Cr,{color:k.text.primary,bold:!0},e),Xn.createElement(Cr,{color:k.ui.muted},": "),Xn.createElement(Cr,{color:k.text.secondary},t))}var Kg=DS(_S);import Dt,{useState as $S,useEffect as FS,useRef as Vg,memo as LS,useMemo as US,useCallback as BS}from"react";import{Box as Er,Text as Ir}from"@jrichman/ink";import WS from"ink-select-input";var HS=[{label:"Yes, proceed",value:"confirm"},{label:"No, cancel",value:"decline"}];function GS({request:i,onConfirm:e,onDecline:t,onTimeout:n}){let[s,r]=$S(i.timeout?Math.ceil(i.timeout/1e3):null),o=Vg(null),a=Vg(0);FS(()=>{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=BS(g=>{o.current&&(clearInterval(o.current),o.current=null),g.value==="confirm"?e("y"):t()},[e,t]),{actualTargets:l,displayCommand:d}=US(()=>{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 Dt.createElement(Er,{flexDirection:"column",borderStyle:"round",borderColor:"#525252",paddingX:2,paddingY:1},Dt.createElement(Ir,{color:"white",bold:!0},i.title),d&&Dt.createElement(Er,{marginTop:1},Dt.createElement(Ir,{color:"gray"},"$ "),Dt.createElement(Ir,{color:"white"},d)),l.length>0&&Dt.createElement(Er,{marginTop:1,flexDirection:"column"},l.map((g,m)=>Dt.createElement(Ir,{key:m,color:"gray"}," ",g))),s!==null&&Dt.createElement(Er,{marginTop:1},Dt.createElement(Ir,{color:"yellow"},"Auto-cancel in ",s,"s")),Dt.createElement(Er,{marginTop:1},Dt.createElement(WS,{items:HS,onSelect:c})))}var Xg=LS(GS,(i,e)=>i.request.id===e.request.id&&i.request.timeout===e.request.timeout);import Je,{memo as jS,useMemo as zS}from"react";import{Box as kr,Text as Yt}from"@jrichman/ink";import qS from"ink-spinner";var Yg=8;function KS({todoList:i}){let{incompleteTodos:e,completedTodos:t,allComplete:n,visibleTodos:s,hiddenCount:r}=zS(()=>{if(!i||i.todos.length===0)return{incompleteTodos:[],completedTodos:[],allComplete:!1,visibleTodos:[],hiddenCount:0};let o=i.todos.filter(y=>y.status!=="completed"),a=i.todos.filter(y=>y.status==="completed"),c=o.length===0&&a.length>0,l=o,d=a.slice(-2),m=[...l,...d].slice(0,Yg),p=Math.max(0,l.length-Yg),h=a.length-d.length,f=p+h;return{incompleteTodos:o,completedTodos:a,allComplete:c,visibleTodos:m,hiddenCount:f}},[i]);return!i||i.todos.length===0?null:Je.createElement(kr,{paddingX:2,marginBottom:1,flexShrink:0},Je.createElement(kr,{borderStyle:"round",borderColor:n?k.status.success:k.border.default,paddingX:2,paddingY:1,flexDirection:"column"},Je.createElement(kr,{marginBottom:1},Je.createElement(Yt,{color:k.text.primary,bold:!0},"Tasks "),Je.createElement(Yt,{color:n?k.status.success:k.text.secondary},t.length,"/",i.todos.length),n&&Je.createElement(Yt,{color:k.status.success}," ✓")),s.map((o,a)=>{let c=o.status==="completed",l=o.status==="in_progress",d=l&&o.activeForm?o.activeForm:xd(o);return Je.createElement(kr,{key:o.id||`todo-${a}`},c&&Je.createElement(Yt,{color:k.status.success},"✓"),l&&Je.createElement(Yt,{color:k.text.accent},Je.createElement(qS,{type:"dots"})),!c&&!l&&Je.createElement(Yt,{color:k.ui.muted},"○"),Je.createElement(Yt,null," "),Je.createElement(Yt,{color:c?k.ui.muted:l?k.text.primary:k.text.secondary},d))}),r>0&&Je.createElement(kr,{marginTop:0},Je.createElement(Yt,{color:k.ui.muted}," +",r," more"))))}var Qg=jS(KS);import We,{memo as VS}from"react";import{Box as Dc,Text as it}from"@jrichman/ink";function XS(){return We.createElement(Dc,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},We.createElement(it,{bold:!0,color:"whiteBright"},"Keyboard Shortcuts"),We.createElement(Dc,{marginTop:1,flexDirection:"column"},We.createElement(it,{color:"#9CA3AF"},"• ",We.createElement(it,{color:"whiteBright",bold:!0},"Enter")," ",We.createElement(it,{color:"#9CA3AF"},"Submit message")),We.createElement(it,{color:"#9CA3AF"},"• ",We.createElement(it,{color:"whiteBright",bold:!0},"?")," ",We.createElement(it,{color:"#9CA3AF"},"Toggle this help")),We.createElement(it,{color:"#9CA3AF"},"• ",We.createElement(it,{color:"whiteBright",bold:!0},"Esc")," ",We.createElement(it,{color:"#9CA3AF"},"Stop generation / Close menus")),We.createElement(it,{color:"#9CA3AF"},"• ",We.createElement(it,{color:"whiteBright",bold:!0},"Ctrl+C")," ",We.createElement(it,{color:"#9CA3AF"},"Stop generation / Exit"))),We.createElement(Dc,{marginTop:1},We.createElement(it,{color:"#6B7280"},"Press Esc to close")))}var Jg=VS(XS);import $e,{memo as tw,useMemo as nw,useCallback as sw}from"react";import{Box as di,Text as lt}from"@jrichman/ink";import Ps,{useState as YS,useEffect as QS,memo as Zg}from"react";import{Box as Mc,Text as em,useInput as JS}from"@jrichman/ink";var ZS=Zg(function({item:e,isSelected:t,highlightColor:n}){return Ps.createElement(em,{color:t?"#000":"#fff",backgroundColor:t?n:void 0},e.label)});function ew({items:i,onSelect:e,onHighlight:t,isFocused:n=!0,highlightColor:s="#D97706",itemComponent:r=ZS}){let[o,a]=YS(0);return QS(()=>{a(0)},[i.length]),JS((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?Ps.createElement(Mc,null,Ps.createElement(em,{color:"#6B7280"},"No items")):Ps.createElement(Mc,{flexDirection:"column"},i.map((c,l)=>{let d=l===o;return Ps.createElement(Mc,{key:c.value||l},Ps.createElement(r,{item:c,isSelected:d,highlightColor:s}))}))}var ui=Zg(ew);en();Pn();function rw({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}=nw(()=>{let a=ye.filter(p=>p.name.startsWith("snowx-o4")||p.name.startsWith("snowx-c")||p.name.startsWith("snowx-h")),c=ye.filter(p=>p.name.startsWith("snowx-5")||p.name.startsWith("snowx-o3")||p.name.startsWith("snowx-4")),l=ye.filter(p=>p.name.startsWith("snowx-g")),d=p=>p.map(h=>{let f=Pe.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=sw(a=>{if(a.value.startsWith("_"))return;if(!s.find(d=>d.value===a.value)?.isAccessible){t(a.value);return}let l=ye.find(d=>d.name===a.value);l&&e(l)},[s,t,e]);return $e.createElement(di,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},$e.createElement(lt,{bold:!0,color:"whiteBright"},"Select Model"),$e.createElement(di,null,$e.createElement(lt,{color:"#6B7280"},"Tier: ",Pe.getDisplayName(i)," - "),$e.createElement(lt,{color:"#5AD8A6"},"[0.5x]"),$e.createElement(lt,{color:"#6B7280"}," "),$e.createElement(lt,{color:"#9CA3AF"},"[1x]"),$e.createElement(lt,{color:"#6B7280"}," "),$e.createElement(lt,{color:"#60A5FA"},"[1.5x]"),$e.createElement(lt,{color:"#6B7280"}," "),$e.createElement(lt,{color:"#FBBF24"},"[2x]"),$e.createElement(lt,{color:"#6B7280"}," "),$e.createElement(lt,{color:"#F472B6"},"[2.5x]"),$e.createElement(lt,{color:"#6B7280"}," credits")),$e.createElement(di,{marginTop:1},$e.createElement(ui,{items:r.map(a=>({label:a.label,value:a.value})),onSelect:o,isFocused:!0,highlightColor:"#D97706"})),$e.createElement(di,{marginTop:1},$e.createElement(lt,{color:"#6B7280"},"Esc to cancel")))}var tm=tw(rw);import As,{memo as rm,useMemo as ow,useCallback as iw}from"react";import{Box as Rc,Text as nm}from"@jrichman/ink";var sm=[{command:"/model",description:"change AI model",value:"model"},{command:"/history",description:"browse & switch conversations",value:"history"},{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 (or drag image file)",value:"img"},{command:"/doc",description:"paste PDF from clipboard",value:"doc"},{command:"/file",description:"attach file by path OR drag into terminal",value:"file"},{command:"/attachments",description:"list current attachments (max 3)",value:"attachments"},{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"}],aw=rm(function({item:e,isSelected:t,highlightColor:n}){let[s,r]=e.label.split(" ");return As.createElement(Rc,{width:50,backgroundColor:t?n:void 0},As.createElement(Rc,{width:14},As.createElement(nm,{color:t?"#1a1a1a":"whiteBright",bold:!0},s)),As.createElement(nm,{color:t?"#1a1a1a":"#6B7280"},r))});function cw({filterText:i,onSelect:e}){let t=ow(()=>(i?sm.filter(r=>r.value.toLowerCase().includes(i)):sm).map(r=>({label:`${r.command} ${r.description}`,value:r.value})),[i]),n=iw(s=>{s.value&&e(s.value)},[e]);return As.createElement(Rc,{flexDirection:"column",paddingX:1,paddingY:1,width:"100%",borderStyle:"single",borderColor:"#3F3F46",backgroundColor:"#18181B"},As.createElement(ui,{items:t.length>0?t:[{label:"No matching commands",value:""}],onSelect:n,itemComponent:aw,isFocused:!0,highlightColor:"#D97706"}))}var om=rm(cw);import ie,{useState as gi,useEffect as lw,useCallback as mi,memo as uw}from"react";import{Box as Ze,Text as He,useInput as dw}from"@jrichman/ink";import gw from"ink-spinner";import{exec as mw}from"child_process";var me={brand:"#A78BFA",text:"#F8FAFC",muted:"#94A3B8",dim:"#64748B",border:"#334155",error:"#EF4444",success:"#22C55E"},pw=[{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"}],hw=[{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 fw({type:i}){let e=Kt(),t=Pt(),n=ac(),[s,r]=gi(""),[o,a]=gi(null),[c,l]=gi(!1),[d,g]=gi(0),m=Vt.getInstance(),p=i==="discord"?pw:hw,h=p.find(S=>S.id===n.step),f=p.length-1,y=mi(S=>{let P=process.platform,x;P==="darwin"?x=`open "${S}"`:P==="win32"?x=`start "" "${S}"`:x=`xdg-open "${S}"`,mw(x,()=>{})},[]);dw((S,P)=>{if(n.isOpen){if(P.escape){e.hideWizard();return}if(h?.type==="input"){if(P.return){v();return}if(P.backspace||P.delete){r(x=>x.slice(0,-1)),a(null);return}S&&!P.ctrl&&!P.meta&&!P.leftArrow&&!P.rightArrow&&!P.upArrow&&!P.downArrow&&!P.tab&&(r(x=>x+S),a(null))}else if(h?.type==="confirm"){if(P.leftArrow||P.rightArrow||S==="y"||S==="n"){g(S==="y"?1:S==="n"?0:x=>x===0?1:0);return}if(P.return){T();return}}}},{isActive:n.isOpen});let v=mi(()=>{let S=n.step,P=s.trim();if(i==="discord"){if(S===1){if(!P){a("Bot token is required");return}if(!m.validateDiscordToken(P)){a("Invalid token format. Should be like: MTIz...xxx.Yyy...zzz");return}e.setWizardData("botToken",P)}else if(S===2){if(!P){a("At least one owner ID is required");return}if(P.split(",").map(A=>A.trim()).some(A=>!/^\d{17,19}$/.test(A))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("ownerIds",P)}else if(S===3){if(P&&P.split(",").map(A=>A.trim()).filter(Boolean).some(A=>!/^\d{17,19}$/.test(A))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("guestIds",P)}}else if(S===1){if(!P){a("Bot token is required");return}if(!m.validateTelegramToken(P)){a("Invalid token format. Should be like: 123456789:ABCdef...");return}e.setWizardData("botToken",P)}else if(S===2){if(!P){a("At least one owner username is required");return}e.setWizardData("ownerUsernames",P)}else S===3&&e.setWizardData("guestUsernames",P);r(""),a(null),e.setWizardStep(S+1)},[n.step,i,s,m,e]),T=mi(()=>{let S=n.step,P=d===1;i==="discord"?S===4&&(e.setWizardData("allowGuildChat",P),e.setWizardStep(5)):S===4?(e.setWizardData("allowGroupChat",P),P?e.setWizardStep(5):(e.setWizardData("routeToDM",!1),e.setWizardStep(6))):S===5&&(e.setWizardData("routeToDM",P),e.setWizardStep(6)),g(0)},[n.step,i,d,e]),C=mi(async S=>{try{if(i==="discord"){let P=await m.connectDiscord({botToken:S.botToken,ownerUserIds:S.ownerIds.split(",").map(x=>x.trim()).filter(Boolean),guestUserIds:S.guestIds?S.guestIds.split(",").map(x=>x.trim()).filter(Boolean):[],allowGuildChat:S.allowGuildChat||!1});if(P.success){let x=P.botId?m.generateDiscordInviteUrl(P.botId):"";t.addSystemMessage(`✓ Discord connected!
2595
+ Type /help to see available commands.`),r.clearInput(),{handled:!0,clearInput:!0}},[i,e,t,n.authService,s,r]),isCommand:o}}import{useRef as wn,useCallback as Xt,useEffect as oS}from"react";var xc=typeof requestAnimationFrame<"u"?requestAnimationFrame:i=>setImmediate(i),Cs=typeof cancelAnimationFrame<"u"?cancelAnimationFrame:i=>clearImmediate(i);var iS={flushInterval:16,maxBufferSize:32,detectPaste:!0,pasteThreshold:50,immediateFlushChars:[`
2596
+ `,"\r"," "]};function Mg(i,e){let t={...iS,...e},n=wn(""),s=wn(0),r=wn(0),o=wn(0),a=wn(0),c=wn(null),l=wn(null),d=wn(i);d.current=i;let g=Xt(()=>{if(n.current===""&&s.current===0)return null;let E=Date.now()-r.current,w=t.detectPaste&&a.current>3&&E<t.pasteThreshold*a.current;return{chars:n.current,backspaces:s.current,isPaste:w,startTime:r.current}},[t.detectPaste,t.pasteThreshold]),m=Xt(()=>{let I=g();I&&(n.current="",s.current=0,a.current=0,r.current=0,d.current(I)),c.current!==null&&(Cs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null)},[g]),p=Xt(()=>{c.current===null&&(c.current=xc(()=>{c.current=null,l.current&&clearTimeout(l.current),l.current=setTimeout(m,t.flushInterval)}))},[m,t.flushInterval]),h=Xt(I=>{let E=Date.now();r.current===0&&(r.current=E),o.current=E,a.current++,n.current+=I,t.immediateFlushChars.includes(I)||n.current.length>=t.maxBufferSize?m():p()},[m,p,t.immediateFlushChars,t.maxBufferSize]),f=Xt(()=>{let I=Date.now();r.current===0&&(r.current=I),a.current++,n.current.length>0?n.current=n.current.slice(0,-1):s.current++,p()},[p]),y=Xt(()=>{let I=g();return I&&(n.current="",s.current=0,a.current=0,r.current=0),c.current!==null&&(Cs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),I},[g]),v=Xt(()=>g(),[g]),T=Xt(()=>{n.current="",s.current=0,a.current=0,r.current=0,c.current!==null&&(Cs(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null)},[]),C=Xt(()=>n.current===""&&s.current===0,[]);return oS(()=>()=>{c.current!==null&&Cs(c.current),l.current&&clearTimeout(l.current)},[]),{pushChar:h,pushBackspace:f,flush:y,peek:v,clear:T,isEmpty:C}}import{useRef as Tn,useEffect as Cc,useCallback as Es,useState as aS,useMemo as Rg}from"react";function Ng(i){let e=Tn(0),t=Tn([]),n=Tn(0),s=Tn(0),r=Tn([]);return Cc(()=>{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 Og(i){let{targetFrameTime:e=16.67,warningThreshold:t=.8,criticalThreshold:n=1}=i||{},s=Tn(0),r=Tn(0),o=Es(()=>{s.current=performance.now(),r.current=0},[]),a=Es(()=>performance.now()-s.current+r.current<e*n,[e,n]),c=Es(d=>{r.current+=d;let g=e-r.current;return Math.max(0,g)},[e]),l=Es(()=>{let g=(performance.now()-s.current+r.current)/e;return g>=n?"critical":g>=t?"warning":"ok"},[e,t,n]);return Cc(()=>{o()}),{hasBudget:a,useBudget:c,resetBudget:o,getBudgetStatus:l}}function _g(i){let{warningThresholdMB:e=100,criticalThresholdMB:t=200,checkInterval:n=5e3}=i||{},[s,r]=aS(0);Cc(()=>{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=Es(()=>{typeof global<"u"&&global.gc&&global.gc()},[]);return{heapUsedMB:s,pressure:o,requestGC:a}}function $g(i){let e=Tn(i);return e.current=i,Es(((...t)=>e.current(...t)),[])}function Fg({onSubmit:i,enableProfiling:e=!1,bufferFlushInterval:t=16}){let{exit:n}=dS(),s=jn(),r=Pt(),o=Ts(),a=Kt(),c=br(),l=Kn(),{handleCommand:d,isCommand:g}=ci(),m=Og({targetFrameTime:16.67}),{pressure:p}=_g({warningThresholdMB:150,criticalThresholdMB:250}),h=e?Ng("OptimizedKeyboardInput"):void 0,f=Ec(!1),y=Ec(0),v=Ec(0),T=500,C=$g(i),I=lS(w=>{if(w.isPaste)l.addPastedContent(w.chars);else{for(let S=0;S<w.backspaces;S++)l.deleteAtCursor();w.chars&&(l.insertAtCursor(w.chars),c.input.slice(0,c.cursorPosition)+w.chars+c.input.slice(c.cursorPosition)==="/"&&!o.showCommandMenu&&a.showCommandMenu())}},[l,c.input,c.cursorPosition,o.showCommandMenu,a]),E=Mg(I,{flushInterval:t,maxBufferSize:64,detectPaste:!0,pasteThreshold:50});return uS((w,S)=>{let P=Date.now(),x=P-y.current;if(y.current=P,!(w.startsWith("[<")||w.startsWith("[M")||/^\[<?\d+;\d+;\d+[mM]?/.test(w)||/^\d+[mM]/.test(w)||/^;\d+;\d+[mM]/.test(w)||/^\d+;\d+[mM]/.test(w))){if(S.escape){E.flush();let A=Date.now(),O=A-v.current;if(v.current=A,O<T){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||o.showConversationList){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.showConversationList&&!o.showWizard&&!(o.showCommandMenu&&(S.upArrow||S.downArrow||S.return))){if(S.ctrl&&w==="l"){E.flush(),process.stdout.write("\x1B[2J\x1B[H");return}if(S.ctrl&&w==="c"){E.flush(),s.isLoading?r.stopStreaming():n();return}if(S.ctrl&&w==="r"){E.flush(),o.isReverseSearchActive||a.startReverseSearch();return}if(S.ctrl&&w==="z"){E.flush(),l.undo();return}if(S.ctrl&&(w==="y"||w==="Z")){E.flush(),l.redo();return}if(w===""||S.ctrl&&w==="v"){if(f.current)return;if(ii()){f.current=!0,ai().then(A=>{f.current=!1,A.data&&(E.flush(),l.addClipboardImage(A.data,A.size))}).catch(()=>{f.current=!1});return}return}if(S.tab){E.flush(),c.suggestion&&l.acceptSuggestion();return}if(w==="?"&&c.input===""&&!o.showCommandMenu){E.flush(),a.toggleHelp();return}if(S.return&&!o.isReverseSearchActive){E.flush();let A=c.pastedTexts.filter(U=>!U.error||U.type==="text");(c.input.trim()||A.length>0)&&C();return}if(S.upArrow&&!o.showCommandMenu&&!o.isReverseSearchActive){E.flush(),l.navigateHistoryUp();return}if(S.downArrow&&!o.showCommandMenu&&!o.isReverseSearchActive){E.flush(),l.navigateHistoryDown();return}if(S.leftArrow){E.flush(),l.moveCursorLeft();return}if(S.rightArrow){E.flush(),l.moveCursorRight();return}if(S.ctrl&&w==="a"){E.flush(),l.moveCursorToStart();return}if(S.ctrl&&w==="e"){E.flush(),l.moveCursorToEnd();return}if(S.delete||S.backspace){E.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&&w){let A=w.includes(`
2597
+ `),O=w.length>50;if(A||O){E.flush(),l.addPastedContent(w);return}E.pushChar(w)}}}}),cS(()=>()=>{E.clear()},[E]),{handleCommand:d,isCommand:g,renderProfile:h,memoryPressure:p,frameBudgetStatus:m.getBudgetStatus()}}import{useState as xr,useCallback as At,useMemo as bS,useRef as Ug,useEffect as Bg}from"react";import{useEffect as gS,useRef as Ic}from"react";import{useInput as OL}from"@jrichman/ink";var mS=0,li=[];function pS(){return`keypress-${++mS}`}function hS(i,e,t){let n=pS();return li.push({id:n,handler:i,priority:e,isActive:t}),li.sort((s,r)=>r.priority-s.priority),n}function fS(i){let e=li.findIndex(t=>t.id===i);e!==-1&&li.splice(e,1)}function Lg(i,e={}){let{priority:t=0,isActive:n=!0}=e,s=Ic(i),r=Ic(n),o=Ic(null);s.current=i,r.current=n,gS(()=>(o.current=hS((a,c)=>s.current(a,c),t,()=>r.current),()=>{o.current&&(fS(o.current),o.current=null)}),[t])}function Wg(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]=xr(o),[p,h]=xr(!1),[f,y]=xr(0),[v,T]=xr([]),[C,I]=xr(-1),E=Ug(a),w=Ug(c);E.current=a,w.current=c;let S=bS(()=>{if(!g)return[];let B=[],j;try{if(r)j=new RegExp(g,s?"g":"gi");else{let ne=g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");j=new RegExp(ne,s?"g":"gi")}}catch{return[]}return e.forEach((ne,pe)=>{let ue=t(ne),ct=j.exec(ue);ct&&B.push({item:ne,index:pe,matchStart:ct.index,matchEnd:ct.index+ct[0].length}),j.lastIndex=0}),n==="backward"&&B.reverse(),B},[e,g,t,n,s,r]),P=S.length>0&&S[f]||null,x=S.length,A=x>0,O=At(B=>{m(B),y(0),I(-1)},[]);Bg(()=>{E.current?.(g,S)},[g,S]),Bg(()=>{P&&w.current?.(P)},[P]);let U=At(()=>{x!==0&&y(B=>(B+1)%x)},[x]),D=At(()=>{x!==0&&y(B=>(B-1+x)%x)},[x]),$=At(B=>{B>=0&&B<x&&y(B)},[x]),_=At(()=>{g&&T(B=>{let j=B.filter(ne=>ne!==g);return[g,...j].slice(0,d)}),m(""),y(0),I(-1)},[g,d]),F=At(()=>{h(!0),O("")},[O]),z=At(()=>{_(),h(!1)},[_]),G=At(()=>{v.length!==0&&I(B=>{let j=Math.min(B+1,v.length-1);return m(v[j]||""),j})},[v]),M=At(()=>{C<0||I(B=>{let j=B-1;return j<0?m(""):m(v[j]||""),j})},[v,C]),R=At(B=>{m(j=>j+B),y(0),I(-1)},[]),H=At(()=>{m(B=>B.slice(0,-1)),y(0),I(-1)},[]);return Lg((B,j)=>{if(p){if(j.downArrow||j.ctrl&&B==="n")return U(),!0;if(j.upArrow||j.ctrl&&B==="p")return D(),!0;if(j.ctrl&&j.upArrow)return G(),!0;if(j.ctrl&&j.downArrow)return M(),!0;if(j.escape)return z(),!0;if(j.return)return _(),h(!1),!0;if(j.backspace||j.delete)return H(),!0;if(B&&B.length===1&&!j.ctrl&&!j.meta)return R(B),!0}},{isActive:l&&p,priority:100}),{query:g,setQuery:O,matches:S,currentMatchIndex:f,currentMatch:P,nextMatch:U,prevMatch:D,goToMatch:$,clear:_,isSearching:p,startSearch:F,stopSearch:z,history:v,historyUp:G,historyDown:M,append:R,backspace:H,matchCount:x,hasMatches:A}}function Hg(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 J,{memo as Pc,useMemo as SS}from"react";import{Box as Ht,Text as we}from"@jrichman/ink";import Gg 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"},yS={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}},kc={name:"Default Dark",type:"dark",colors:Qe,semantic:yS};var vS=kc;function Is(){return vS}var k={get text(){return Is().semantic.text},get background(){return Is().semantic.background},get border(){return Is().semantic.border},get ui(){return Is().semantic.ui},get status(){return Is().semantic.status},get colors(){return Is().colors}};function wS(i,e){let t=i.toLowerCase().replace(/_/g,"");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==="readspecialfile")return{displayName:"ReadFile",mainArg:e?.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==="runcommand"){let r=e?.command;return{displayName:"Bash",mainArg:r?r.length>50?r.substring(0,47)+"...":r:void 0}}if(t==="webfetch"||t==="readurl")return{displayName:"Fetch",mainArg:e?.url};if(t==="websearch"||t==="searchtool")return{displayName:"Search",mainArg:e?.query};if(t==="browserautomation")return{displayName:"Browser",mainArg:e?.task?e.task.substring(0,40):void 0};if(t==="mapurl")return{displayName:"MapURL",mainArg:e?.url};if(t==="task"||t==="spawnagents")return{displayName:"Task",mainArg:e?.subagent_type||e?.description};if(t==="spawnagentstool")return{displayName:"Agents",mainArg:void 0};if(t==="uploadfile")return{displayName:"Upload",mainArg:e?.file_path};if(t==="deployziphtml"||t==="deployziphtmltool")return{displayName:"Deploy",mainArg:e?.zip_file_path};if(t==="generateimage")return{displayName:"Image",mainArg:e?.prompt?.substring(0,40)};if(t==="generatevideofromtext"||t==="generatevideofromimage")return{displayName:"Video",mainArg:void 0};if(t==="generatemusic")return{displayName:"Music",mainArg:void 0};if(t==="sendemailtouser")return{displayName:"Email",mainArg:e?.subject};if(t==="orionphonecall")return{displayName:"Call",mainArg:e?.phone_number};if(t==="httprequest")return{displayName:"HTTP",mainArg:e?.url?e.url.replace(/^https?:\/\//,"").substring(0,40):void 0};if(t==="addmemory"||t==="quorymemory")return{displayName:"Memory",mainArg:void 0};if(t==="searchconversationhistory"||t==="searchpastcommands"||t==="searchpastcode")return{displayName:"History",mainArg:e?.query};if(t==="todowrite")return{displayName:"",mainArg:void 0};let n=i.replace(/_/g," ").replace(/\b\w/g,r=>r.toUpperCase()).substring(0,20),s=e?.description||e?.query||e?.path||e?.url;return{displayName:n,mainArg:s}}function TS(i){if(!i)return"";let e=i.split("/");return e.length<=2?i:".../"+e.slice(-2).join("/")}function xS(i){if(!i)return"";let e=i.split(`
2598
+ `).filter(t=>t.trim());return e.length>5?`${e[0].substring(0,80).trim()} (+${e.length-1} lines)`:e.length>1?`${e.length} lines`:i.length>120?i.substring(0,117)+"...":i.trim()}var CS=Pc(function({totalRunning:e,totalCompleted:t,totalTools:n}){let s=e===0;return J.createElement(Ht,{marginBottom:0},s?J.createElement(we,{color:k.status.success},"✓ "):J.createElement(we,{color:k.status.warning},J.createElement(Gg,{type:"dots"})," "),J.createElement(we,{color:k.text.secondary,bold:!0},s?`${t} tools completed`:`Running ${e} tool${e>1?"s":""} in parallel`),!s&&t>0&&J.createElement(we,{color:k.ui.muted}," (",t,"/",n," done)"))}),ks=Pc(function({tool:e,indent:t=!1,onConfirm:n,onDecline:s}){let{displayName:r,mainArg:o}=wS(e.name,e.arguments);if(!r)return null;let a=e.state==="running",c=e.state==="completed",l=e.state==="failed",d=e.state==="pending_confirmation",g=o?TS(o):void 0;return J.createElement(Ht,{flexDirection:"column",paddingLeft:t?2:0},J.createElement(Ht,null,a&&J.createElement(we,{color:k.status.warning},J.createElement(Gg,{type:"dots"})),c&&J.createElement(we,{color:k.status.success},"✓"),l&&J.createElement(we,{color:k.status.error},"✗"),d&&J.createElement(we,{color:"#f59e0b"},"⚠"),J.createElement(we,null," "),J.createElement(we,{color:k.text.primary,bold:!0},r),g&&J.createElement(J.Fragment,null,J.createElement(we,{color:k.ui.muted},"("),J.createElement(we,{color:k.text.secondary},g),J.createElement(we,{color:k.ui.muted},")"))),c&&e.output&&J.createElement(Ht,{paddingLeft:2},J.createElement(we,{color:k.ui.muted},"└ "),J.createElement(we,{color:k.ui.muted},xS(e.output))),l&&e.error&&J.createElement(Ht,{paddingLeft:2},J.createElement(we,{color:k.ui.muted},"└ "),J.createElement(we,{color:k.status.error},e.error.substring(0,80))),d&&J.createElement(Ht,{flexDirection:"column",paddingLeft:2,marginTop:0},e.confirmationCommand&&J.createElement(Ht,null,J.createElement(we,{color:k.ui.muted},"└ "),J.createElement(we,{color:k.text.secondary},e.confirmationCommand.substring(0,80))),J.createElement(Ht,{marginTop:0},J.createElement(we,{color:k.ui.muted}," "),J.createElement(we,{color:"#f59e0b"},"Allow? "),J.createElement(we,{color:k.status.success},"[y] Yes "),J.createElement(we,{color:k.status.error},"[n] No"))))});function ES({activeTools:i,onConfirmationConfirm:e,onConfirmationDecline:t}){let{running:n,completed:s,failed:r,pending:o,hasParallel:a}=SS(()=>{if(i.size===0)return{running:[],completed:[],failed:[],pending:[],hasParallel:!1};let c=Array.from(i.values()).filter(f=>f.name.toLowerCase().replace(/_/g,"")!=="todowrite"),l=c.filter(f=>f.state==="running"),d=c.filter(f=>f.state==="completed"),g=c.filter(f=>f.state==="failed"),m=c.filter(f=>f.state==="pending_confirmation"),p=l.length+d.length>1&&m.length===0,h=p?d:d.sort((f,y)=>y.startTime.getTime()-f.startTime.getTime()).slice(0,1);return{running:l,completed:h,failed:g,pending:m,hasParallel:p}},[i]);if(n.length===0&&s.length===0&&r.length===0&&o.length===0)return null;if(a){let c=[...n,...s];return J.createElement(Ht,{flexDirection:"column",paddingX:1,marginY:1},J.createElement(CS,{totalRunning:n.length,totalCompleted:s.length,totalTools:c.length}),c.map(l=>J.createElement(ks,{key:l.toolCallId,tool:l,indent:!0,onConfirm:e,onDecline:t})),r.map(l=>J.createElement(ks,{key:l.toolCallId,tool:l,indent:!0})))}return J.createElement(Ht,{flexDirection:"column",paddingX:1,marginY:1},o.map(c=>J.createElement(ks,{key:c.toolCallId,tool:c,onConfirm:e,onDecline:t})),n.map(c=>J.createElement(ks,{key:c.toolCallId,tool:c})),s.map(c=>J.createElement(ks,{key:c.toolCallId,tool:c})),r.map(c=>J.createElement(ks,{key:c.toolCallId,tool:c})))}var jg=Pc(ES);import ce,{memo as Ac,useMemo as zg,useState as IS,useEffect as kS}from"react";import{Box as Gt,Text as _e}from"@jrichman/ink";import qg from"ink-spinner";function PS(i,e=60){return i?i.length<=e?i:i.substring(0,e-3)+"...":"Processing..."}var AS=Ac(function({agent:e}){let t=PS(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"?ce.createElement(_e,{color:"cyan"},ce.createElement(qg,{type:"dots"})):e.status==="completed"?ce.createElement(_e,{color:"#5AD8A6"},"✓"):e.status==="failed"?ce.createElement(_e,{color:"#F5716C"},"✗"):e.status==="timeout"?ce.createElement(_e,{color:"#FBBF24"},"⏱"):ce.createElement(_e,{color:"#6B7280"},"○"),r=n(e.status);return ce.createElement(Gt,{flexDirection:"column",marginLeft:2},ce.createElement(Gt,null,s(),ce.createElement(_e,{color:r,bold:!0}," Agent #",e.agentNumber)),ce.createElement(Gt,{marginLeft:2},ce.createElement(_e,{color:"#9CA3AF"},t)),e.endTime&&e.startTime&&ce.createElement(Gt,{marginLeft:2},ce.createElement(_e,{color:"#6B7280"},((e.endTime.getTime()-e.startTime.getTime())/1e3).toFixed(1),"s")),e.error&&ce.createElement(Gt,{marginLeft:2},ce.createElement(_e,{color:"#F5716C"},"Error: ",e.error.substring(0,60),e.error.length>60?"...":"")),e.streamingContent&&e.status==="running"&&ce.createElement(Gt,{marginLeft:2},ce.createElement(_e,{color:"#6B7280"},e.streamingContent.split(`
2599
+ `)[0]?.substring(0,50),"...")))}),DS=Ac(function({operation:e}){let{agents:t,completed:n,failed:s,running:r,total:o}=zg(()=>{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"?ce.createElement(_e,{color:"cyan"},ce.createElement(qg,{type:"dots"})):e.status==="completed"?ce.createElement(_e,{color:"#5AD8A6"},"✓"):ce.createElement(_e,{color:"#F5716C"},"✗"),l=e.status==="completed"?"#5AD8A6":e.status==="failed"?"#F5716C":"cyan";return ce.createElement(Gt,{flexDirection:"column"},ce.createElement(Gt,null,c(),ce.createElement(_e,{color:l,bold:!0}," ",a()),ce.createElement(_e,{color:"#6B7280"}," "),ce.createElement(_e,{backgroundColor:"#3F3F46",color:"whiteBright"}," ",n,"/",o," "),r>0&&ce.createElement(_e,{color:"cyan"}," (",r," running)"),s>0&&ce.createElement(_e,{color:"#F5716C"}," [",s," failed]")),ce.createElement(Gt,{flexDirection:"column",marginTop:1},t.map(d=>ce.createElement(AS,{key:d.agentNumber,agent:d}))))});function MS({operations:i}){let[e,t]=IS(0);kS(()=>{let s=setInterval(()=>{Array.from(i.values()).some(o=>o.status==="completed"||o.status==="failed")&&t(o=>o+1)},500);return()=>clearInterval(s)},[]);let n=zg(()=>i.size===0?[]:Array.from(i.entries()).filter(([s,r])=>r.status==="running"||r.status==="starting"?!0:r.endTime?Date.now()-r.endTime.getTime()<3e3:!1),[i,e]);return n.length===0?null:ce.createElement(Gt,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},n.map(([s,r])=>ce.createElement(DS,{key:s,operation:r})))}var Kg=Ac(MS);import Xn,{memo as RS}from"react";import{Box as NS,Text as Cr}from"@jrichman/ink";import OS from"ink-spinner";function _S(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 $S(i,e=60){return i?i.length<=e?i:i.substring(0,e-3)+"...":"Processing request..."}function FS({session:i}){if(!i)return null;let e=_S(i.source),t=$S(i.message);return Xn.createElement(NS,{flexDirection:"row",paddingX:1,marginY:1,borderStyle:"round",borderColor:k.border.default},Xn.createElement(Cr,{color:k.status.warning},Xn.createElement(OS,{type:"dots"})),Xn.createElement(Cr,null," "),Xn.createElement(Cr,{color:k.text.primary,bold:!0},e),Xn.createElement(Cr,{color:k.ui.muted},": "),Xn.createElement(Cr,{color:k.text.secondary},t))}var Vg=RS(FS);import Dt,{useState as LS,useEffect as US,useRef as Xg,memo as BS,useMemo as WS,useCallback as HS}from"react";import{Box as Er,Text as Ir}from"@jrichman/ink";import GS from"ink-select-input";var jS=[{label:"Yes, proceed",value:"confirm"},{label:"No, cancel",value:"decline"}];function zS({request:i,onConfirm:e,onDecline:t,onTimeout:n}){let[s,r]=LS(i.timeout?Math.ceil(i.timeout/1e3):null),o=Xg(null),a=Xg(0);US(()=>{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=HS(g=>{o.current&&(clearInterval(o.current),o.current=null),g.value==="confirm"?e("y"):t()},[e,t]),{actualTargets:l,displayCommand:d}=WS(()=>{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 Dt.createElement(Er,{flexDirection:"column",borderStyle:"round",borderColor:"#525252",paddingX:2,paddingY:1},Dt.createElement(Ir,{color:"white",bold:!0},i.title),d&&Dt.createElement(Er,{marginTop:1},Dt.createElement(Ir,{color:"gray"},"$ "),Dt.createElement(Ir,{color:"white"},d)),l.length>0&&Dt.createElement(Er,{marginTop:1,flexDirection:"column"},l.map((g,m)=>Dt.createElement(Ir,{key:m,color:"gray"}," ",g))),s!==null&&Dt.createElement(Er,{marginTop:1},Dt.createElement(Ir,{color:"yellow"},"Auto-cancel in ",s,"s")),Dt.createElement(Er,{marginTop:1},Dt.createElement(GS,{items:jS,onSelect:c})))}var Yg=BS(zS,(i,e)=>i.request.id===e.request.id&&i.request.timeout===e.request.timeout);import Je,{memo as qS,useMemo as KS}from"react";import{Box as kr,Text as Yt}from"@jrichman/ink";import VS from"ink-spinner";var Qg=8;function XS({todoList:i}){let{incompleteTodos:e,completedTodos:t,allComplete:n,visibleTodos:s,hiddenCount:r}=KS(()=>{if(!i||i.todos.length===0)return{incompleteTodos:[],completedTodos:[],allComplete:!1,visibleTodos:[],hiddenCount:0};let o=i.todos.filter(y=>y.status!=="completed"),a=i.todos.filter(y=>y.status==="completed"),c=o.length===0&&a.length>0,l=o,d=a.slice(-2),m=[...l,...d].slice(0,Qg),p=Math.max(0,l.length-Qg),h=a.length-d.length,f=p+h;return{incompleteTodos:o,completedTodos:a,allComplete:c,visibleTodos:m,hiddenCount:f}},[i]);return!i||i.todos.length===0?null:Je.createElement(kr,{paddingX:2,marginBottom:1,flexShrink:0},Je.createElement(kr,{borderStyle:"round",borderColor:n?k.status.success:k.border.default,paddingX:2,paddingY:1,flexDirection:"column"},Je.createElement(kr,{marginBottom:1},Je.createElement(Yt,{color:k.text.primary,bold:!0},"Tasks "),Je.createElement(Yt,{color:n?k.status.success:k.text.secondary},t.length,"/",i.todos.length),n&&Je.createElement(Yt,{color:k.status.success}," ✓")),s.map((o,a)=>{let c=o.status==="completed",l=o.status==="in_progress",d=l&&o.activeForm?o.activeForm:Cd(o);return Je.createElement(kr,{key:o.id||`todo-${a}`},c&&Je.createElement(Yt,{color:k.status.success},"✓"),l&&Je.createElement(Yt,{color:k.text.accent},Je.createElement(VS,{type:"dots"})),!c&&!l&&Je.createElement(Yt,{color:k.ui.muted},"○"),Je.createElement(Yt,null," "),Je.createElement(Yt,{color:c?k.ui.muted:l?k.text.primary:k.text.secondary},d))}),r>0&&Je.createElement(kr,{marginTop:0},Je.createElement(Yt,{color:k.ui.muted}," +",r," more"))))}var Jg=qS(XS);import We,{memo as YS}from"react";import{Box as Dc,Text as it}from"@jrichman/ink";function QS(){return We.createElement(Dc,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},We.createElement(it,{bold:!0,color:"whiteBright"},"Keyboard Shortcuts"),We.createElement(Dc,{marginTop:1,flexDirection:"column"},We.createElement(it,{color:"#9CA3AF"},"• ",We.createElement(it,{color:"whiteBright",bold:!0},"Enter")," ",We.createElement(it,{color:"#9CA3AF"},"Submit message")),We.createElement(it,{color:"#9CA3AF"},"• ",We.createElement(it,{color:"whiteBright",bold:!0},"?")," ",We.createElement(it,{color:"#9CA3AF"},"Toggle this help")),We.createElement(it,{color:"#9CA3AF"},"• ",We.createElement(it,{color:"whiteBright",bold:!0},"Esc")," ",We.createElement(it,{color:"#9CA3AF"},"Stop generation / Close menus")),We.createElement(it,{color:"#9CA3AF"},"• ",We.createElement(it,{color:"whiteBright",bold:!0},"Ctrl+C")," ",We.createElement(it,{color:"#9CA3AF"},"Stop generation / Exit"))),We.createElement(Dc,{marginTop:1},We.createElement(it,{color:"#6B7280"},"Press Esc to close")))}var Zg=YS(QS);import $e,{memo as sw,useMemo as rw,useCallback as ow}from"react";import{Box as di,Text as lt}from"@jrichman/ink";import Ps,{useState as JS,useEffect as ZS,memo as em}from"react";import{Box as Mc,Text as tm,useInput as ew}from"@jrichman/ink";var tw=em(function({item:e,isSelected:t,highlightColor:n}){return Ps.createElement(tm,{color:t?"#000":"#fff",backgroundColor:t?n:void 0},e.label)});function nw({items:i,onSelect:e,onHighlight:t,isFocused:n=!0,highlightColor:s="#D97706",itemComponent:r=tw}){let[o,a]=JS(0);return ZS(()=>{a(0)},[i.length]),ew((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?Ps.createElement(Mc,null,Ps.createElement(tm,{color:"#6B7280"},"No items")):Ps.createElement(Mc,{flexDirection:"column"},i.map((c,l)=>{let d=l===o;return Ps.createElement(Mc,{key:c.value||l},Ps.createElement(r,{item:c,isSelected:d,highlightColor:s}))}))}var ui=em(nw);en();Pn();function iw({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}=rw(()=>{let a=ye.filter(p=>p.name.startsWith("snowx-o4")||p.name.startsWith("snowx-c")||p.name.startsWith("snowx-h")),c=ye.filter(p=>p.name.startsWith("snowx-5")||p.name.startsWith("snowx-o3")||p.name.startsWith("snowx-4")),l=ye.filter(p=>p.name.startsWith("snowx-g")),d=p=>p.map(h=>{let f=Pe.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=ow(a=>{if(a.value.startsWith("_"))return;if(!s.find(d=>d.value===a.value)?.isAccessible){t(a.value);return}let l=ye.find(d=>d.name===a.value);l&&e(l)},[s,t,e]);return $e.createElement(di,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},$e.createElement(lt,{bold:!0,color:"whiteBright"},"Select Model"),$e.createElement(di,null,$e.createElement(lt,{color:"#6B7280"},"Tier: ",Pe.getDisplayName(i)," - "),$e.createElement(lt,{color:"#5AD8A6"},"[0.5x]"),$e.createElement(lt,{color:"#6B7280"}," "),$e.createElement(lt,{color:"#9CA3AF"},"[1x]"),$e.createElement(lt,{color:"#6B7280"}," "),$e.createElement(lt,{color:"#60A5FA"},"[1.5x]"),$e.createElement(lt,{color:"#6B7280"}," "),$e.createElement(lt,{color:"#FBBF24"},"[2x]"),$e.createElement(lt,{color:"#6B7280"}," "),$e.createElement(lt,{color:"#F472B6"},"[2.5x]"),$e.createElement(lt,{color:"#6B7280"}," credits")),$e.createElement(di,{marginTop:1},$e.createElement(ui,{items:r.map(a=>({label:a.label,value:a.value})),onSelect:o,isFocused:!0,highlightColor:"#D97706"})),$e.createElement(di,{marginTop:1},$e.createElement(lt,{color:"#6B7280"},"Esc to cancel")))}var nm=sw(iw);import As,{memo as om,useMemo as aw,useCallback as cw}from"react";import{Box as Rc,Text as sm}from"@jrichman/ink";var rm=[{command:"/model",description:"change AI model",value:"model"},{command:"/history",description:"browse & switch conversations",value:"history"},{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 (or drag image file)",value:"img"},{command:"/doc",description:"paste PDF from clipboard",value:"doc"},{command:"/file",description:"attach file by path OR drag into terminal",value:"file"},{command:"/attachments",description:"list current attachments (max 3)",value:"attachments"},{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"}],lw=om(function({item:e,isSelected:t,highlightColor:n}){let[s,r]=e.label.split(" ");return As.createElement(Rc,{width:50,backgroundColor:t?n:void 0},As.createElement(Rc,{width:14},As.createElement(sm,{color:t?"#1a1a1a":"whiteBright",bold:!0},s)),As.createElement(sm,{color:t?"#1a1a1a":"#6B7280"},r))});function uw({filterText:i,onSelect:e}){let t=aw(()=>(i?rm.filter(r=>r.value.toLowerCase().includes(i)):rm).map(r=>({label:`${r.command} ${r.description}`,value:r.value})),[i]),n=cw(s=>{s.value&&e(s.value)},[e]);return As.createElement(Rc,{flexDirection:"column",paddingX:1,paddingY:1,width:"100%",borderStyle:"single",borderColor:"#3F3F46",backgroundColor:"#18181B"},As.createElement(ui,{items:t.length>0?t:[{label:"No matching commands",value:""}],onSelect:n,itemComponent:lw,isFocused:!0,highlightColor:"#D97706"}))}var im=om(uw);import ie,{useState as gi,useEffect as dw,useCallback as mi,memo as gw}from"react";import{Box as Ze,Text as He,useInput as mw}from"@jrichman/ink";import pw from"ink-spinner";import{exec as hw}from"child_process";var me={brand:"#A78BFA",text:"#F8FAFC",muted:"#94A3B8",dim:"#64748B",border:"#334155",error:"#EF4444",success:"#22C55E"},fw=[{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"}],bw=[{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 yw({type:i}){let e=Kt(),t=Pt(),n=ac(),[s,r]=gi(""),[o,a]=gi(null),[c,l]=gi(!1),[d,g]=gi(0),m=Vt.getInstance(),p=i==="discord"?fw:bw,h=p.find(S=>S.id===n.step),f=p.length-1,y=mi(S=>{let P=process.platform,x;P==="darwin"?x=`open "${S}"`:P==="win32"?x=`start "" "${S}"`:x=`xdg-open "${S}"`,hw(x,()=>{})},[]);mw((S,P)=>{if(n.isOpen){if(P.escape){e.hideWizard();return}if(h?.type==="input"){if(P.return){v();return}if(P.backspace||P.delete){r(x=>x.slice(0,-1)),a(null);return}S&&!P.ctrl&&!P.meta&&!P.leftArrow&&!P.rightArrow&&!P.upArrow&&!P.downArrow&&!P.tab&&(r(x=>x+S),a(null))}else if(h?.type==="confirm"){if(P.leftArrow||P.rightArrow||S==="y"||S==="n"){g(S==="y"?1:S==="n"?0:x=>x===0?1:0);return}if(P.return){T();return}}}},{isActive:n.isOpen});let v=mi(()=>{let S=n.step,P=s.trim();if(i==="discord"){if(S===1){if(!P){a("Bot token is required");return}if(!m.validateDiscordToken(P)){a("Invalid token format. Should be like: MTIz...xxx.Yyy...zzz");return}e.setWizardData("botToken",P)}else if(S===2){if(!P){a("At least one owner ID is required");return}if(P.split(",").map(A=>A.trim()).some(A=>!/^\d{17,19}$/.test(A))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("ownerIds",P)}else if(S===3){if(P&&P.split(",").map(A=>A.trim()).filter(Boolean).some(A=>!/^\d{17,19}$/.test(A))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("guestIds",P)}}else if(S===1){if(!P){a("Bot token is required");return}if(!m.validateTelegramToken(P)){a("Invalid token format. Should be like: 123456789:ABCdef...");return}e.setWizardData("botToken",P)}else if(S===2){if(!P){a("At least one owner username is required");return}e.setWizardData("ownerUsernames",P)}else S===3&&e.setWizardData("guestUsernames",P);r(""),a(null),e.setWizardStep(S+1)},[n.step,i,s,m,e]),T=mi(()=>{let S=n.step,P=d===1;i==="discord"?S===4&&(e.setWizardData("allowGuildChat",P),e.setWizardStep(5)):S===4?(e.setWizardData("allowGroupChat",P),P?e.setWizardStep(5):(e.setWizardData("routeToDM",!1),e.setWizardStep(6))):S===5&&(e.setWizardData("routeToDM",P),e.setWizardStep(6)),g(0)},[n.step,i,d,e]),C=mi(async S=>{try{if(i==="discord"){let P=await m.connectDiscord({botToken:S.botToken,ownerUserIds:S.ownerIds.split(",").map(x=>x.trim()).filter(Boolean),guestUserIds:S.guestIds?S.guestIds.split(",").map(x=>x.trim()).filter(Boolean):[],allowGuildChat:S.allowGuildChat||!1});if(P.success){let x=P.botId?m.generateDiscordInviteUrl(P.botId):"";t.addSystemMessage(`✓ Discord connected!
2600
2600
 
2601
2601
  Bot: ${P.botUsername}
2602
2602
  `+(x?`Invite URL: ${x}
@@ -2606,20 +2606,20 @@ Commands: /ask, /new, /clear`),x&&y(x)}else t.addSystemMessage(`✗ Discord setu
2606
2606
  Bot: @${P.botUsername}
2607
2607
  Chat: ${x}
2608
2608
 
2609
- Send /new to start`),y(x)}else t.addSystemMessage(`✗ Telegram setup failed: ${P.error}`)}}catch(P){t.addSystemMessage(`✗ Connection error: ${P.message}`)}e.resetWizard()},[i,m,t,y,e]);lw(()=>{(i==="discord"&&n.step===5||i==="telegram"&&n.step===6)&&!c&&(l(!0),C(n.data))},[n.step,n.data,i,c,C]);let I=()=>{let S=Math.min(n.step,f),P="━".repeat(S),x="─".repeat(f-S);return ie.createElement(Ze,null,ie.createElement(He,{color:me.brand},P),ie.createElement(He,{color:me.dim},x),ie.createElement(He,{color:me.muted}," ",S,"/",f))},E=()=>h?h.type==="loading"?ie.createElement(Ze,{flexDirection:"column",paddingY:1},ie.createElement(Ze,null,ie.createElement(He,{color:me.brand},ie.createElement(gw,{type:"dots"})),ie.createElement(He,{color:me.muted}," Connecting to ",i==="discord"?"Discord":"Telegram","..."))):h.type==="input"?ie.createElement(Ze,{flexDirection:"column"},ie.createElement(He,{color:me.text},h.help),ie.createElement(He,{color:me.dim},h.hint),ie.createElement(Ze,{marginTop:1,flexDirection:"column"},ie.createElement(Ze,{paddingX:1,borderStyle:"round",borderColor:o?me.error:me.brand},ie.createElement(He,{color:s?me.text:me.dim},s||h.placeholder||"Type here..."),ie.createElement(He,{color:me.brand},"▎")),o&&ie.createElement(Ze,{marginTop:1},ie.createElement(He,{color:me.error},"✗ ",o)))):h.type==="confirm"?ie.createElement(Ze,{flexDirection:"column"},ie.createElement(He,{color:me.text},h.help),ie.createElement(He,{color:me.dim},h.hint),ie.createElement(Ze,{marginTop:1,gap:2},ie.createElement(Ze,{paddingX:2,borderStyle:"round",borderColor:d===0?me.brand:me.border},ie.createElement(He,{color:d===0?me.brand:me.muted},"No")),ie.createElement(Ze,{paddingX:2,borderStyle:"round",borderColor:d===1?me.brand:me.border},ie.createElement(He,{color:d===1?me.brand:me.muted},"Yes")))):null:null,w=i==="discord"?"Discord Setup":"Telegram Setup";return ie.createElement(Ze,{flexDirection:"column",borderStyle:"round",borderColor:me.border,paddingX:2,paddingY:1,width:60},ie.createElement(Ze,{marginBottom:1,justifyContent:"space-between"},ie.createElement(He,{bold:!0,color:me.brand},w),I()),ie.createElement(Ze,{marginBottom:1},ie.createElement(He,{bold:!0,color:me.text},h?.title)),E(),ie.createElement(Ze,{marginTop:1,borderStyle:"single",borderTop:!0,borderColor:me.border,paddingTop:1},ie.createElement(He,{color:me.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 im=uw(fw);import Fe,{memo as bw,useMemo as pi}from"react";import{Box as xn,Text as Cn}from"@jrichman/ink";var am=(i,e=60)=>i.length>e?i.substring(0,e)+"...":i;function yw({regularQueuedMessages:i,crossDeviceTasks:e}){let t=pi(()=>i.length===0?null:i.map((o,a)=>Fe.createElement(xn,{key:o.id,borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,marginBottom:1},Fe.createElement(xn,null,Fe.createElement(Cn,{color:"whiteBright",bold:!0},a+1),Fe.createElement(Cn,{color:"#6B7280"}," • "),Fe.createElement(Cn,{color:"#9CA3AF"},am(o.content))))),[i]),n=pi(()=>e.length===0?null:e.map((o,a)=>Fe.createElement(xn,{key:`cross-${o.id}`,borderStyle:"round",borderColor:"#0E7490",paddingX:2,paddingY:0,marginBottom:1},Fe.createElement(xn,null,Fe.createElement(Cn,{color:"#22D3EE",bold:!0},"[M] ",a+1),Fe.createElement(Cn,{color:"#6B7280"}," - "),Fe.createElement(Cn,{color:"#9CA3AF"},am(o.content))))),[e]),s=pi(()=>{let o=i.length;return`${o} message${o>1?"s":""} queued`},[i.length]),r=pi(()=>{let o=e.length;return`${o} cross-device task${o>1?"s":""} waiting`},[e.length]);return Fe.createElement(Fe.Fragment,null,t&&Fe.createElement(xn,{flexDirection:"column",paddingX:2,marginBottom:1},t,Fe.createElement(xn,null,Fe.createElement(Cn,{color:"#9CA3AF"},s))),n&&Fe.createElement(xn,{flexDirection:"column",paddingX:2,marginBottom:1},n,Fe.createElement(xn,null,Fe.createElement(Cn,{color:"#22D3EE"},r))))}var cm=bw(yw,(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 Mt,{memo as vw,useState as Sw}from"react";import{Box as hi,Text as Yn,useInput as ww}from"@jrichman/ink";function Tw(i){let e=Date.now()-new Date(i).getTime(),t=Math.floor(e/6e4),n=Math.floor(e/36e5),s=Math.floor(e/864e5);return s>0?`${s}d ago`:n>0?`${n}h ago`:t>0?`${t}m ago`:"just now"}function xw({conversations:i,currentConversationId:e,onSelect:t,onClose:n}){let s=[...i].sort((a,c)=>new Date(c.updatedAt).getTime()-new Date(a.updatedAt).getTime()).slice(0,20),[r,o]=Sw(()=>{let a=s.findIndex(c=>c.id===e);return a>=0?a:0});return ww((a,c)=>{if(c.upArrow){o(l=>Math.max(0,l-1));return}if(c.downArrow){o(l=>Math.min(s.length-1,l+1));return}if(c.return&&s[r]){t(s[r].id),n();return}if(c.escape||a==="q"){n();return}}),s.length===0?Mt.createElement(hi,{borderStyle:"round",borderColor:k.border.default,paddingX:2,paddingY:1},Mt.createElement(Yn,{color:k.ui.muted},"No past conversations")):Mt.createElement(hi,{flexDirection:"column",borderStyle:"round",borderColor:k.border.focused,paddingX:1,paddingY:0},Mt.createElement(hi,{marginBottom:1,paddingX:1},Mt.createElement(Yn,{color:k.text.primary,bold:!0},"Conversations "),Mt.createElement(Yn,{color:k.ui.muted},"↑↓ navigate Enter switch Esc close")),s.map((a,c)=>{let l=c===r,d=a.id===e,g=a.title||"Untitled",m=g.length>50?g.substring(0,47)+"...":g;return Mt.createElement(hi,{key:a.id,paddingX:1},Mt.createElement(Yn,{color:l?k.text.accent:k.ui.muted},l?"▶ ":" "),Mt.createElement(Yn,{color:l?k.text.primary:k.text.secondary,bold:d},m),d&&Mt.createElement(Yn,{color:k.status.success}," ●"),Mt.createElement(Yn,{color:k.ui.muted}," ",Tw(a.updatedAt)))}))}var lm=vw(xw);import K,{memo as Cw,useMemo as Nc}from"react";import{Box as Ge,Text as ae}from"@jrichman/ink";import dm from"path";import at,{memo as fi}from"react";import{Box as Pr,Text as Qt}from"@jrichman/ink";var bi={normal:{symbol:"",label:"",color:k.text.primary,description:"Normal mode"},yolo:{symbol:"*",label:"YOLO",color:k.status.error,description:"Auto-approve all actions"},plan:{symbol:">",label:"PLAN",color:k.status.success,description:"Planning mode - no execution"},shell:{symbol:"!",label:"SHELL",color:k.status.warning,description:"Shell command mode"},auto:{symbol:">",label:"AUTO",color:k.status.warning,description:"Auto-accept suggestions"}},tB=fi(function({mode:e,showLabel:t=!1,size:n="normal"}){if(e==="normal")return null;let s=bi[e];return n==="compact"?at.createElement(Qt,{color:s.color,bold:!0},s.symbol):at.createElement(Pr,{flexDirection:"row",alignItems:"center"},at.createElement(Qt,{color:s.color,bold:!0},s.symbol),t&&at.createElement(Pr,{marginLeft:1},at.createElement(Qt,{color:s.color,bold:!0},s.label)))}),nB=fi(function({mode:e,isActive:t=!0}){if(e==="normal")return null;let n=bi[e],s=t?n.color:k.ui.muted;return at.createElement(Qt,{color:s,bold:t},"[",n.label,"]")}),sB=fi(function({selectedMode:e,availableModes:t=["normal","yolo","plan","auto"],isFocused:n=!1}){return at.createElement(Pr,{flexDirection:"row",alignItems:"center"},at.createElement(Qt,{color:k.text.secondary},"Mode: "),t.map((s,r)=>{let o=bi[s],a=s===e,c=s==="normal"?"NORMAL":o.label;return at.createElement(Pr,{key:s,flexDirection:"row"},r>0&&at.createElement(Qt,{color:k.ui.muted}," | "),at.createElement(Qt,{color:a?o.color:k.ui.muted,bold:a,inverse:a&&n},c))}))}),um=fi(function({mode:e,promptSymbol:t="❯",isFocused:n=!0}){let s=bi[e],r=e!=="normal",o=r?s.color:n?k.text.accent:k.ui.muted;return at.createElement(Pr,{flexDirection:"row",alignItems:"center"},r&&at.createElement(Qt,{color:s.color,bold:!0},s.symbol),at.createElement(Qt,{color:o},t))});var Ew=" Type your message or @path/to/file";function Iw({input:i,isLoading:e,pastedTexts:t,cursorPosition:n,suggestion:s,mode:r="normal",attachmentCount:o}){let{attachmentManager:a}=zn(),{hasContent:c,ghostText:l}=Nc(()=>{let m=i.length>0||t.length>0||a.hasAttachments(),p=s&&s.toLowerCase().startsWith(i.toLowerCase())&&i.length>0?s.slice(i.length):null;return{hasContent:m,ghostText:p}},[i,t.length,s,o]),d=Nc(()=>{let m=a.getImages(),p=a.getDocuments();if(m.length===0&&p.length===0)return null;let h=[];for(let v of m){let T=v.source==="clipboard"?"CLIPBOARD":"IMG",C=` ${Wt(v.size)}`;h.push(K.createElement(Ge,{key:v.id},K.createElement(ae,{color:k.status.info}," ","[",T,"] "),K.createElement(ae,{color:k.text.secondary},"Image"),K.createElement(ae,{color:k.ui.muted},C)))}for(let v of p){let T=v.fileName.split(".").pop()?.toUpperCase()||"FILE",C=` ${Wt(v.size)}`;h.push(K.createElement(Ge,{key:v.id},K.createElement(ae,{color:k.status.info}," ","[",T,"] "),K.createElement(ae,{color:k.text.secondary},Yo(v.fileName)),K.createElement(ae,{color:k.ui.muted},C)))}let f=m.length+p.length,y=a.getMaxAllowed();return h.push(K.createElement(Ge,{key:"summary"},K.createElement(ae,{color:k.ui.muted}," Attachments: ",f,"/",y))),h},[o]),g=Nc(()=>t.length===0?null:t.map((m,p)=>{if(m.type==="clipboard_image"){let y=m.fileSize?` ${Wt(m.fileSize)}`:"",v=!!m.error;return K.createElement(Ge,{key:`pasted-${m.id}`,flexDirection:"column"},K.createElement(Ge,null,K.createElement(ae,{color:v?k.status.error:k.status.info}," ","[CLIPBOARD] "),K.createElement(ae,{color:v?k.status.error:k.text.secondary},"Image"),y&&K.createElement(ae,{color:k.ui.muted},y)),v&&K.createElement(Ge,{marginLeft:4},K.createElement(ae,{color:k.status.error,dimColor:!0},"[!] ",m.error)))}if(m.type==="image_path"&&m.filePath){let y=Yo(dm.basename(m.filePath)),v=m.fileSize?` ${Wt(m.fileSize)}`:"",T=!!m.error;return K.createElement(Ge,{key:`pasted-${m.id}`,flexDirection:"column"},K.createElement(Ge,null,K.createElement(ae,{color:T?k.status.error:k.status.info}," ","[IMG] "),K.createElement(ae,{color:T?k.status.error:k.text.secondary},y),v&&K.createElement(ae,{color:k.ui.muted},v)),T&&K.createElement(Ge,{marginLeft:4},K.createElement(ae,{color:k.status.error,dimColor:!0},"[!] ",m.error)))}if(m.type==="file_path"&&m.filePath){let y=Yo(dm.basename(m.filePath)),v=m.fileSize?` ${Wt(m.fileSize)}`:"",T=!!m.error;return K.createElement(Ge,{key:`pasted-${m.id}`,flexDirection:"column"},K.createElement(Ge,null,K.createElement(ae,{color:T?k.status.error:k.status.info}," ","[FILE] "),K.createElement(ae,{color:T?k.status.error:k.text.secondary},y),v&&K.createElement(ae,{color:k.ui.muted},v)),T&&K.createElement(Ge,{marginLeft:4},K.createElement(ae,{color:k.status.error,dimColor:!0},"[!] ",m.error)))}let h=m.lineCount-1,f=h>0?`+${h} lines`:"1 line";return K.createElement(Ge,{key:`pasted-${m.id}`},K.createElement(ae,{color:k.ui.muted}," ","[TEXT] "),K.createElement(ae,{color:k.text.secondary},"Pasted text #",p+1),K.createElement(ae,{color:k.ui.muted}," (",f,")"))}),[t]);return K.createElement(Ge,{borderStyle:"round",borderColor:c?k.border.focused:k.border.default,paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},d&&K.createElement(Ge,{flexDirection:"column",marginBottom:0},d),g&&K.createElement(Ge,{flexDirection:"column",marginBottom:0},g),K.createElement(Ge,null,K.createElement(um,{mode:r,isFocused:!e}),K.createElement(ae,null," "),i.length===0&&!e?s?K.createElement(ae,null,K.createElement(ae,{inverse:!0}," "),K.createElement(ae,{color:k.ui.muted},s),K.createElement(ae,{color:k.ui.muted,dimColor:!0}," (Tab to accept)")):K.createElement(ae,{color:k.ui.muted},Ew):K.createElement(ae,null,K.createElement(ae,{color:k.text.primary},i.slice(0,n)),!e&&K.createElement(ae,{inverse:!0}," "),K.createElement(ae,{color:k.text.primary},i.slice(n)),l&&K.createElement(ae,{color:k.ui.muted},l))))}var gm=Cw(Iw,(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 Ar,{useState as kw,useEffect as Pw,useRef as Aw,memo as Dw}from"react";import{Box as Mw,Text as Oc}from"@jrichman/ink";import Rw from"ink-spinner";function Nw(i){if(i<60)return`${i}s`;let e=Math.floor(i/60),t=i%60;return`${e}m ${t}s`}function Ow({isLoading:i,phrase:e="Processing",startTime:t}){let[n,s]=kw(0),r=Aw(null);return Pw(()=>{if(r.current&&(clearInterval(r.current),r.current=null),!i){s(0);return}let o=t||Date.now();return s(Math.floor((Date.now()-o)/1e3)),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?Ar.createElement(Mw,{flexDirection:"row",alignItems:"center",paddingX:2,marginBottom:1,flexShrink:0},Ar.createElement(Oc,{color:k.text.accent},Ar.createElement(Rw,{type:"dots"})),Ar.createElement(Oc,{color:k.text.primary}," ",e,"... "),Ar.createElement(Oc,{color:k.text.secondary},"(esc to cancel",n>0?`, ${Nw(n)}`:"",")")):null}var mm=Dw(Ow);import Ee,{memo as Hw,useMemo as wm}from"react";import{Box as Rs,Text as ut}from"@jrichman/ink";import{useState as pm,useEffect as hm,useCallback as _w,useRef as fm}from"react";import{useStdout as $w}from"@jrichman/ink";var Ds=80,Ms=24,Fw=100;function yi(i){let{debounceMs:e=Fw}=i||{},{stdout:t}=$w(),[n,s]=pm({width:t?.columns||Ds,height:t?.rows||Ms,rows:t?.rows||Ms,columns:t?.columns||Ds}),[r,o]=pm(!1),a=fm(null),c=fm(null);hm(()=>{function d(){o(!0),a.current&&clearTimeout(a.current),c.current&&clearTimeout(c.current),a.current=setTimeout(()=>{let g=process.stdout.columns||Ds,m=process.stdout.rows||Ms;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]),hm(()=>{if(t){let d=t.columns||Ds,g=t.rows||Ms;(d!==n.width||g!==n.height)&&s({width:d,height:g,rows:g,columns:d})}},[t?.columns,t?.rows]);let l=_w(()=>{s({width:process.stdout.columns||Ds,height:process.stdout.rows||Ms,rows:process.stdout.rows||Ms,columns:process.stdout.columns||Ds})},[]);return{...n,isResizing:r,refresh:l}}Fo();import{useState as En,useEffect as bm,useRef as Lw,useCallback as Uw}from"react";function ym(i=1e4){let[e,t]=En("not-ready"),[n,s]=En(!1),[r,o]=En(!1),[a,c]=En(0),[l,d]=En(5),[g,m]=En(0),[p,h]=En(!1),[f,y]=En(!1),v=Lw(!1),T=Uw(C=>{C.isInitializing||C.initState==="initializing"?t("initializing"):C.isRunning&&C.isInitialized?t("ready"):t("not-ready"),s(C.hasBrowser??!1),o(C.multiAgentMode??!1),c(C.runningAgentCount??0),d(C.maxConcurrentAgents??5),m(C.tabCount??0),h(C.isExecuting??!1),y(C.hasActiveSession??!1)},[]);return bm(()=>{let C=re.onStatusChange(I=>{T(I)});return()=>C()},[T]),bm(()=>{let C=()=>{let E=re.getStatus();E.initState==="idle"&&!v.current&&(v.current=!0,re.initialize().catch(w=>{console.debug("[useBrowserStatus] Auto-init failed:",w.message)}),E=re.getStatus()),T(E)};C();let I=setInterval(C,i);return()=>clearInterval(I)},[i,T]),{status:e,hasBrowser:n,multiAgentMode:r,runningAgentCount:a,maxConcurrentAgents:l,tabCount:g,isExecuting:p,hasActiveSession:f}}import{useState as vi,useEffect as Bw,useCallback as vm}from"react";var Ww=300*1e3;function Sm(){let[i,e]=vi(null),[t,n]=vi(null),[s,r]=vi(!1),[o,a]=vi(null),c=vm(async(m=!1)=>{r(!0),a(null);try{let p=await Sr.fetchQuotaStatus(m);e(p);let h=await Sr.getUsageDisplayData();n(h)}catch(p){a(p instanceof Error?p.message:"Failed to fetch quota")}finally{r(!1)}},[]),l=vm(async()=>{await c(!0)},[c]);Bw(()=>{c();let m=setInterval(()=>{c(!0)},Ww);return()=>clearInterval(m)},[c]);let d=t?Pg(t.percent):"normal",g=t?wr(t.resetsAt,t.resetsInSeconds):"";return{quota:i,usageDisplay:t,severity:d,resetTimeDisplay:g,isLoading:s,error:o,refresh:l}}Pn();var Gw={3:"#FFD700",2:"#A78BFA",1:"#60A5FA",0:k.ui.muted},jw={ready:"#10B981",initializing:"#F59E0B","not-ready":"#F97316"},zw={normal:k.ui.muted,notice:"#60A5FA",warning:"#FBBF24",high:"#F97316",critical:"#EF4444"};function qw(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function Kw(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 Vw({cwd:i,selectedModel:e,showScrollHint:t=!1,tier:n=0}){let{width:s}=yi(),{status:r}=ym(),{usageDisplay:o,severity:a,resetTimeDisplay:c}=Sm(),l=hr(),d=Pe.getDisplayName(n),g=Gw[n]||k.ui.muted,{displayPath:m,shortcuts:p}=wm(()=>{let f=`${e.displayName} /model`,y=" ● browser",v=t?"? help · Shift+↑↓ scroll":"? help",C=f.length+y.length+v.length+" ".length*2+4,I=Math.max(15,Math.floor((s-C)*.4));return{displayPath:Kw(qw(i),I),shortcuts:v}},[i,e.displayName,t,s]),h=wm(()=>{if(!o)return null;let{percent:f,type:y}=o,v=y==="weekly"?"weekly":"5-hour";return f>=100?`You've hit your ${v} limit`:f>=90?`${f}% of ${v} limit used`:`${f}% ${v} usage`},[o]);return Ee.createElement(Rs,{flexDirection:"column",width:"100%"},o&&Ee.createElement(Rs,{paddingX:2,justifyContent:"center"},Ee.createElement(ut,{color:zw[a]},h),c&&Ee.createElement(Ee.Fragment,null,Ee.createElement(ut,{color:k.ui.muted}," · "),Ee.createElement(ut,{color:k.ui.muted},"resets ",c))),Ee.createElement(Rs,{paddingX:2,paddingY:0,width:"100%",justifyContent:"space-between",flexDirection:"row"},Ee.createElement(Rs,null,Ee.createElement(ut,{color:k.text.link},m),Ee.createElement(ut,{color:k.ui.muted}," v",l),Ee.createElement(ut,{color:k.ui.muted}," · "),Ee.createElement(ut,{color:g,bold:!0},d)),Ee.createElement(Rs,null,Ee.createElement(ut,{color:k.text.accent},e.displayName),Ee.createElement(ut,{color:k.text.secondary}," /model"),Ee.createElement(ut,{color:k.text.secondary}," "),Ee.createElement(ut,{color:jw[r]},"●"),Ee.createElement(ut,{color:k.text.secondary}," browser")),Ee.createElement(Rs,null,Ee.createElement(ut,{color:k.text.secondary},p))))}var Tm=Hw(Vw);import Bc,{memo as Wc}from"react";import{Box as xT}from"@jrichman/ink";import de,{memo as bT,useMemo as Rm}from"react";import{Box as mt,Text as wt}from"@jrichman/ink";import Ns,{memo as Xw,useState as Yw}from"react";import{Box as _c,Text as $c,useInput as Qw}from"@jrichman/ink";function Jw({suggestions:i,onSelect:e,isActive:t=!1}){let n=i.flatMap(o=>o.options),[s,r]=Yw(0);return Qw((o,a)=>{if(!t||!e||n.length===0)return;if(o===" "||a.rightArrow||a.downArrow){r(l=>(l+1)%n.length);return}if(a.leftArrow||a.upArrow){r(l=>(l-1+n.length)%n.length);return}if(a.return){e(n[s]??"");return}let c=parseInt(o,10);!isNaN(c)&&c>=1&&c<=n.length&&e(n[c-1]??"")},{isActive:t&&!!e}),n.length===0?null:Ns.createElement(_c,{flexDirection:"column",marginTop:1},Ns.createElement(_c,{flexDirection:"row",flexWrap:"wrap",gap:1},n.map((o,a)=>{let c=a===s,l=a<9?`${a+1}`:null;return Ns.createElement(_c,{key:`sug-${a}`,borderStyle:"round",borderColor:c?k.text.accent:k.border.default,paddingX:1,paddingY:0},l&&Ns.createElement($c,{color:c?k.text.accent:k.ui.muted},l,". "),Ns.createElement($c,{color:c?k.text.accent:k.text.secondary},o))})),e&&Ns.createElement($c,{color:k.ui.muted},n.length===1?"Enter to use Tab to dismiss":`Tab/↑↓ to navigate Enter or 1-${Math.min(n.length,9)} to select`))}var xm=Xw(Jw,(i,e)=>i.suggestions===e.suggestions&&i.isActive===e.isActive?!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 Qn,{memo as Zw}from"react";import{Box as Si,Text as Fc}from"@jrichman/ink";function eT({workingFiles:i}){return i.length===0?null:Qn.createElement(Si,{flexDirection:"column",marginTop:1,width:"100%"},Qn.createElement(Si,{marginBottom:0,width:"100%"},Qn.createElement(Fc,{color:"#9CA3AF",bold:!0},"Working Files"),Qn.createElement(Fc,{color:"#6B7280"}," (",i.length,")")),Qn.createElement(Si,{flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},i.map(e=>Qn.createElement(Si,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},Qn.createElement(Fc,{color:"white"},e.name)))))}var Cm=Zw(eT,(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 dt,{memo as tT,useMemo as nT,useState as sT}from"react";import{Box as Dr,Text as In}from"@jrichman/ink";var Lc=5;function rT({conversationHistory:i,onSelect:e}){let[t,n]=sT(!1),{displayedItems:s,hiddenCount:r}=nT(()=>i.length<=Lc||t?{displayedItems:i,hiddenCount:0}:{displayedItems:i.slice(0,Lc),hiddenCount:i.length-Lc},[i,t]);return i.length===0?null:dt.createElement(Dr,{flexDirection:"column",marginTop:1},dt.createElement(Dr,{marginBottom:0},dt.createElement(In,{color:k.text.secondary},"💬 "),dt.createElement(In,{color:k.text.secondary,bold:!0},i.length," conversation",i.length!==1?"s":""," found")),dt.createElement(Dr,{flexDirection:"column",paddingLeft:2},s.map((o,a)=>dt.createElement(Dr,{key:`conv-${o.id}-${a}`},dt.createElement(In,{color:k.ui.muted},"• "),dt.createElement(In,{color:k.text.primary},o.title),dt.createElement(In,{color:k.ui.muted}," ("),dt.createElement(In,{color:k.text.link},oT(o.id)),dt.createElement(In,{color:k.ui.muted},")"))),r>0&&dt.createElement(Dr,{marginTop:0},dt.createElement(In,{color:k.text.accent},"+",r," more conversation",r!==1?"s":""))))}function oT(i,e=20){return i.length<=e?i:i.slice(0,e-3)+"..."}var Em=tT(rT);import Q,{memo as iT,useMemo as aT}from"react";import{Box as gt,Text as le}from"@jrichman/ink";Pn();function cT(i){switch(i){case 3:return"#FFD700";case 2:return"#A78BFA";case 1:return"#60A5FA";default:return k.ui.muted}}function lT(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function uT(){let i="#E8B4B8",e="#B8E4E8",t="#4A4A4A";return Q.createElement(gt,{flexDirection:"column"},Q.createElement(gt,null,Q.createElement(le,{color:i},"██"),Q.createElement(le,null," "),Q.createElement(le,{color:i},"██"),Q.createElement(le,null," "),Q.createElement(le,{color:i},"██")),Q.createElement(gt,null,Q.createElement(le,{color:i},"██████████")),Q.createElement(gt,null,Q.createElement(le,{color:i},"██"),Q.createElement(le,{color:e},"██████"),Q.createElement(le,{color:i},"██")),Q.createElement(gt,null,Q.createElement(le,{color:i},"██"),Q.createElement(le,{color:t},"██"),Q.createElement(le,{color:e},"██"),Q.createElement(le,{color:t},"██"),Q.createElement(le,{color:i},"██")),Q.createElement(gt,null,Q.createElement(le,{color:i},"██"),Q.createElement(le,{color:e},"██████"),Q.createElement(le,{color:i},"██")),Q.createElement(gt,null,Q.createElement(le,{color:i},"████"),Q.createElement(le,{color:t},"██"),Q.createElement(le,{color:i},"████")),Q.createElement(gt,null,Q.createElement(le,{color:i}," ██████ ")))}function dT({projectPath:i,variant:e="main",tier:t=0}){let n=hr(),s=aT(()=>i?lT(i):null,[i]),r=Pe.getDisplayName(t),o=cT(t);return e==="main"?Q.createElement(gt,{flexDirection:"row",paddingX:1,marginY:1,gap:2},Q.createElement(uT,null),Q.createElement(gt,{flexDirection:"column",justifyContent:"center"},Q.createElement(gt,null,Q.createElement(le,{color:k.colors.AccentPurple,bold:!0},"Orion"),Q.createElement(le,{color:k.ui.muted}," v",n),Q.createElement(le,{color:k.ui.muted}," · "),Q.createElement(le,{color:o,bold:!0},"Orion ",r)),Q.createElement(le,{color:k.text.secondary},"Your partner in getting things done."),Q.createElement(le,{color:k.text.secondary,dimColor:!0},"More done, more sleep."),s&&Q.createElement(gt,{marginTop:1},Q.createElement(le,{color:k.ui.muted},s)))):Q.createElement(gt,{paddingX:1,marginY:1},Q.createElement(le,{color:k.colors.AccentPurple},"● "),e==="fresh"&&Q.createElement(le,{color:k.text.secondary},"Ready when you are."),e==="continue"&&Q.createElement(le,{color:k.text.secondary},"Picking up where we left off."),e==="new"&&Q.createElement(le,{color:k.text.secondary},"New conversation started."))}var Im=iT(dT);function km(i){return i.includes("Orion ready")||i.includes("Fresh start")||i.includes("Welcome back")||i.includes("New conversation")||i.includes("Conversation cleared")}function Pm(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 et,{memo as wi,useMemo as gT}from"react";import{Box as Os,Text as Jn}from"@jrichman/ink";var ve={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:"*/"}};ve.ts=ve.typescript;ve.js=ve.javascript;ve.jsx=ve.javascript;ve.tsx=ve.typescript;ve.py=ve.python;ve.sh=ve.bash;ve.shell=ve.bash;ve.zsh=ve.bash;ve.rs=ve.rust;ve.golang=ve.go;ve.yml=ve.yaml;function mT(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 pT={keyword:k.status.warning,string:k.status.success,comment:k.ui.comment,number:k.text.link,function:k.text.link,operator:k.text.primary,punctuation:k.ui.muted,type:k.status.info,plain:k.text.primary},hT=wi(function({line:e,language:t}){if(!t)return et.createElement(Jn,{color:k.text.primary},e);let n=mT(e,t);return et.createElement(Jn,null,n.map((s,r)=>et.createElement(Jn,{key:r,color:pT[s.type]},s.value)))}),fT=wi(function({code:e,language:t,showLineNumbers:n=!1,startLineNumber:s=1,maxLines:r}){let{lines:o,langDef:a,truncated:c}=gT(()=>{let d=e.split(`
2610
- `),g=t?ve[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 et.createElement(Os,{flexDirection:"column"},o.map((d,g)=>et.createElement(Os,{key:g,flexDirection:"row"},n&&et.createElement(Os,{width:l+2,flexShrink:0},et.createElement(Jn,{color:k.ui.muted},String(s+g).padStart(l," ")," │")),et.createElement(Os,{flexGrow:1},et.createElement(hT,{line:d,language:a})))),c>0&&et.createElement(Jn,{color:k.ui.muted}," ... ",c," more lines"))}),Am=wi(function({code:e,language:t,showLanguageLabel:n=!0,showLineNumbers:s=!1,maxLines:r,showBorder:o=!0}){let a=t?.toLowerCase(),c=a&&ve[a]?a:void 0;return et.createElement(Os,{flexDirection:"column",borderStyle:o?"round":void 0,borderColor:o?k.border.default:void 0,paddingX:o?1:0},n&&c&&et.createElement(Os,{marginBottom:0},et.createElement(Jn,{color:k.ui.muted,dimColor:!0},c)),et.createElement(fT,{code:e,language:c,showLineNumbers:s,maxLines:r}))}),c1=wi(function({children:e}){return et.createElement(Jn,{color:k.status.warning,bold:!1},"`",e,"`")});function Dm(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 Mm(i){return/```[\s\S]*?```/.test(i)}var yT=500;function Nm(i,e){return i.length<=e?{lines:i,truncated:!1}:{lines:i.slice(0,e),truncated:!0}}function vT({message:i,onSuggestionClick:e,maxLines:t=yT,isSuggestionsActive:n=!1}){let{role:s,content:r}=i,{userTier:o}=fr(),a=Rm(()=>{if(s!=="assistant")return null;let{suggestions:l,cleanedContent:d}=_r(r),{workingFiles:g,cleanedContent:m}=Qc(d),{conversationHistory:p,cleanedContent:h}=Jc(m),y=Zc(h).split(`
2611
- `),{lines:v,truncated:T}=Nm(y,t);return{suggestions:l,workingFiles:g,conversationHistory:p,lines:v,truncated:T,totalLines:y.length}},[r,s,t]),c=Rm(()=>{if(s==="assistant")return null;let l=r.split(`
2612
- `);return Nm(l,t)},[r,s,t]);if(s==="system"&&c){if(km(r)){let{variant:m,projectPath:p}=Pm(r);return de.createElement(Im,{variant:m,projectPath:p,tier:o})}let{lines:l,truncated:d}=c,g=r.split(`
2609
+ Send /new to start`),y(x)}else t.addSystemMessage(`✗ Telegram setup failed: ${P.error}`)}}catch(P){t.addSystemMessage(`✗ Connection error: ${P.message}`)}e.resetWizard()},[i,m,t,y,e]);dw(()=>{(i==="discord"&&n.step===5||i==="telegram"&&n.step===6)&&!c&&(l(!0),C(n.data))},[n.step,n.data,i,c,C]);let I=()=>{let S=Math.min(n.step,f),P="━".repeat(S),x="─".repeat(f-S);return ie.createElement(Ze,null,ie.createElement(He,{color:me.brand},P),ie.createElement(He,{color:me.dim},x),ie.createElement(He,{color:me.muted}," ",S,"/",f))},E=()=>h?h.type==="loading"?ie.createElement(Ze,{flexDirection:"column",paddingY:1},ie.createElement(Ze,null,ie.createElement(He,{color:me.brand},ie.createElement(pw,{type:"dots"})),ie.createElement(He,{color:me.muted}," Connecting to ",i==="discord"?"Discord":"Telegram","..."))):h.type==="input"?ie.createElement(Ze,{flexDirection:"column"},ie.createElement(He,{color:me.text},h.help),ie.createElement(He,{color:me.dim},h.hint),ie.createElement(Ze,{marginTop:1,flexDirection:"column"},ie.createElement(Ze,{paddingX:1,borderStyle:"round",borderColor:o?me.error:me.brand},ie.createElement(He,{color:s?me.text:me.dim},s||h.placeholder||"Type here..."),ie.createElement(He,{color:me.brand},"▎")),o&&ie.createElement(Ze,{marginTop:1},ie.createElement(He,{color:me.error},"✗ ",o)))):h.type==="confirm"?ie.createElement(Ze,{flexDirection:"column"},ie.createElement(He,{color:me.text},h.help),ie.createElement(He,{color:me.dim},h.hint),ie.createElement(Ze,{marginTop:1,gap:2},ie.createElement(Ze,{paddingX:2,borderStyle:"round",borderColor:d===0?me.brand:me.border},ie.createElement(He,{color:d===0?me.brand:me.muted},"No")),ie.createElement(Ze,{paddingX:2,borderStyle:"round",borderColor:d===1?me.brand:me.border},ie.createElement(He,{color:d===1?me.brand:me.muted},"Yes")))):null:null,w=i==="discord"?"Discord Setup":"Telegram Setup";return ie.createElement(Ze,{flexDirection:"column",borderStyle:"round",borderColor:me.border,paddingX:2,paddingY:1,width:60},ie.createElement(Ze,{marginBottom:1,justifyContent:"space-between"},ie.createElement(He,{bold:!0,color:me.brand},w),I()),ie.createElement(Ze,{marginBottom:1},ie.createElement(He,{bold:!0,color:me.text},h?.title)),E(),ie.createElement(Ze,{marginTop:1,borderStyle:"single",borderTop:!0,borderColor:me.border,paddingTop:1},ie.createElement(He,{color:me.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 am=gw(yw);import Fe,{memo as vw,useMemo as pi}from"react";import{Box as xn,Text as Cn}from"@jrichman/ink";var cm=(i,e=60)=>i.length>e?i.substring(0,e)+"...":i;function Sw({regularQueuedMessages:i,crossDeviceTasks:e}){let t=pi(()=>i.length===0?null:i.map((o,a)=>Fe.createElement(xn,{key:o.id,borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,marginBottom:1},Fe.createElement(xn,null,Fe.createElement(Cn,{color:"whiteBright",bold:!0},a+1),Fe.createElement(Cn,{color:"#6B7280"}," • "),Fe.createElement(Cn,{color:"#9CA3AF"},cm(o.content))))),[i]),n=pi(()=>e.length===0?null:e.map((o,a)=>Fe.createElement(xn,{key:`cross-${o.id}`,borderStyle:"round",borderColor:"#0E7490",paddingX:2,paddingY:0,marginBottom:1},Fe.createElement(xn,null,Fe.createElement(Cn,{color:"#22D3EE",bold:!0},"[M] ",a+1),Fe.createElement(Cn,{color:"#6B7280"}," - "),Fe.createElement(Cn,{color:"#9CA3AF"},cm(o.content))))),[e]),s=pi(()=>{let o=i.length;return`${o} message${o>1?"s":""} queued`},[i.length]),r=pi(()=>{let o=e.length;return`${o} cross-device task${o>1?"s":""} waiting`},[e.length]);return Fe.createElement(Fe.Fragment,null,t&&Fe.createElement(xn,{flexDirection:"column",paddingX:2,marginBottom:1},t,Fe.createElement(xn,null,Fe.createElement(Cn,{color:"#9CA3AF"},s))),n&&Fe.createElement(xn,{flexDirection:"column",paddingX:2,marginBottom:1},n,Fe.createElement(xn,null,Fe.createElement(Cn,{color:"#22D3EE"},r))))}var lm=vw(Sw,(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 Mt,{memo as ww,useState as Tw}from"react";import{Box as hi,Text as Yn,useInput as xw}from"@jrichman/ink";function Cw(i){let e=Date.now()-new Date(i).getTime(),t=Math.floor(e/6e4),n=Math.floor(e/36e5),s=Math.floor(e/864e5);return s>0?`${s}d ago`:n>0?`${n}h ago`:t>0?`${t}m ago`:"just now"}function Ew({conversations:i,currentConversationId:e,onSelect:t,onClose:n}){let s=[...i].sort((a,c)=>new Date(c.updatedAt).getTime()-new Date(a.updatedAt).getTime()).slice(0,20),[r,o]=Tw(()=>{let a=s.findIndex(c=>c.id===e);return a>=0?a:0});return xw((a,c)=>{if(c.upArrow){o(l=>Math.max(0,l-1));return}if(c.downArrow){o(l=>Math.min(s.length-1,l+1));return}if(c.return&&s[r]){t(s[r].id),n();return}if(c.escape||a==="q"){n();return}}),s.length===0?Mt.createElement(hi,{borderStyle:"round",borderColor:k.border.default,paddingX:2,paddingY:1},Mt.createElement(Yn,{color:k.ui.muted},"No past conversations")):Mt.createElement(hi,{flexDirection:"column",borderStyle:"round",borderColor:k.border.focused,paddingX:1,paddingY:0},Mt.createElement(hi,{marginBottom:1,paddingX:1},Mt.createElement(Yn,{color:k.text.primary,bold:!0},"Conversations "),Mt.createElement(Yn,{color:k.ui.muted},"↑↓ navigate Enter switch Esc close")),s.map((a,c)=>{let l=c===r,d=a.id===e,g=a.title||"Untitled",m=g.length>50?g.substring(0,47)+"...":g;return Mt.createElement(hi,{key:a.id,paddingX:1},Mt.createElement(Yn,{color:l?k.text.accent:k.ui.muted},l?"▶ ":" "),Mt.createElement(Yn,{color:l?k.text.primary:k.text.secondary,bold:d},m),d&&Mt.createElement(Yn,{color:k.status.success}," ●"),Mt.createElement(Yn,{color:k.ui.muted}," ",Cw(a.updatedAt)))}))}var um=ww(Ew);import K,{memo as Iw,useMemo as Nc}from"react";import{Box as Ge,Text as ae}from"@jrichman/ink";import gm from"path";import at,{memo as fi}from"react";import{Box as Pr,Text as Qt}from"@jrichman/ink";var bi={normal:{symbol:"",label:"",color:k.text.primary,description:"Normal mode"},yolo:{symbol:"*",label:"YOLO",color:k.status.error,description:"Auto-approve all actions"},plan:{symbol:">",label:"PLAN",color:k.status.success,description:"Planning mode - no execution"},shell:{symbol:"!",label:"SHELL",color:k.status.warning,description:"Shell command mode"},auto:{symbol:">",label:"AUTO",color:k.status.warning,description:"Auto-accept suggestions"}},sB=fi(function({mode:e,showLabel:t=!1,size:n="normal"}){if(e==="normal")return null;let s=bi[e];return n==="compact"?at.createElement(Qt,{color:s.color,bold:!0},s.symbol):at.createElement(Pr,{flexDirection:"row",alignItems:"center"},at.createElement(Qt,{color:s.color,bold:!0},s.symbol),t&&at.createElement(Pr,{marginLeft:1},at.createElement(Qt,{color:s.color,bold:!0},s.label)))}),rB=fi(function({mode:e,isActive:t=!0}){if(e==="normal")return null;let n=bi[e],s=t?n.color:k.ui.muted;return at.createElement(Qt,{color:s,bold:t},"[",n.label,"]")}),oB=fi(function({selectedMode:e,availableModes:t=["normal","yolo","plan","auto"],isFocused:n=!1}){return at.createElement(Pr,{flexDirection:"row",alignItems:"center"},at.createElement(Qt,{color:k.text.secondary},"Mode: "),t.map((s,r)=>{let o=bi[s],a=s===e,c=s==="normal"?"NORMAL":o.label;return at.createElement(Pr,{key:s,flexDirection:"row"},r>0&&at.createElement(Qt,{color:k.ui.muted}," | "),at.createElement(Qt,{color:a?o.color:k.ui.muted,bold:a,inverse:a&&n},c))}))}),dm=fi(function({mode:e,promptSymbol:t="❯",isFocused:n=!0}){let s=bi[e],r=e!=="normal",o=r?s.color:n?k.text.accent:k.ui.muted;return at.createElement(Pr,{flexDirection:"row",alignItems:"center"},r&&at.createElement(Qt,{color:s.color,bold:!0},s.symbol),at.createElement(Qt,{color:o},t))});var kw=" Type your message or @path/to/file";function Pw({input:i,isLoading:e,pastedTexts:t,cursorPosition:n,suggestion:s,mode:r="normal",attachmentCount:o}){let{attachmentManager:a}=zn(),{hasContent:c,ghostText:l}=Nc(()=>{let m=i.length>0||t.length>0||a.hasAttachments(),p=s&&s.toLowerCase().startsWith(i.toLowerCase())&&i.length>0?s.slice(i.length):null;return{hasContent:m,ghostText:p}},[i,t.length,s,o]),d=Nc(()=>{let m=a.getImages(),p=a.getDocuments();if(m.length===0&&p.length===0)return null;let h=[];for(let v of m){let T=v.source==="clipboard"?"CLIPBOARD":"IMG",C=` ${Wt(v.size)}`;h.push(K.createElement(Ge,{key:v.id},K.createElement(ae,{color:k.status.info}," ","[",T,"] "),K.createElement(ae,{color:k.text.secondary},"Image"),K.createElement(ae,{color:k.ui.muted},C)))}for(let v of p){let T=v.fileName.split(".").pop()?.toUpperCase()||"FILE",C=` ${Wt(v.size)}`;h.push(K.createElement(Ge,{key:v.id},K.createElement(ae,{color:k.status.info}," ","[",T,"] "),K.createElement(ae,{color:k.text.secondary},Yo(v.fileName)),K.createElement(ae,{color:k.ui.muted},C)))}let f=m.length+p.length,y=a.getMaxAllowed();return h.push(K.createElement(Ge,{key:"summary"},K.createElement(ae,{color:k.ui.muted}," Attachments: ",f,"/",y))),h},[o]),g=Nc(()=>t.length===0?null:t.map((m,p)=>{if(m.type==="clipboard_image"){let y=m.fileSize?` ${Wt(m.fileSize)}`:"",v=!!m.error;return K.createElement(Ge,{key:`pasted-${m.id}`,flexDirection:"column"},K.createElement(Ge,null,K.createElement(ae,{color:v?k.status.error:k.status.info}," ","[CLIPBOARD] "),K.createElement(ae,{color:v?k.status.error:k.text.secondary},"Image"),y&&K.createElement(ae,{color:k.ui.muted},y)),v&&K.createElement(Ge,{marginLeft:4},K.createElement(ae,{color:k.status.error,dimColor:!0},"[!] ",m.error)))}if(m.type==="image_path"&&m.filePath){let y=Yo(gm.basename(m.filePath)),v=m.fileSize?` ${Wt(m.fileSize)}`:"",T=!!m.error;return K.createElement(Ge,{key:`pasted-${m.id}`,flexDirection:"column"},K.createElement(Ge,null,K.createElement(ae,{color:T?k.status.error:k.status.info}," ","[IMG] "),K.createElement(ae,{color:T?k.status.error:k.text.secondary},y),v&&K.createElement(ae,{color:k.ui.muted},v)),T&&K.createElement(Ge,{marginLeft:4},K.createElement(ae,{color:k.status.error,dimColor:!0},"[!] ",m.error)))}if(m.type==="file_path"&&m.filePath){let y=Yo(gm.basename(m.filePath)),v=m.fileSize?` ${Wt(m.fileSize)}`:"",T=!!m.error;return K.createElement(Ge,{key:`pasted-${m.id}`,flexDirection:"column"},K.createElement(Ge,null,K.createElement(ae,{color:T?k.status.error:k.status.info}," ","[FILE] "),K.createElement(ae,{color:T?k.status.error:k.text.secondary},y),v&&K.createElement(ae,{color:k.ui.muted},v)),T&&K.createElement(Ge,{marginLeft:4},K.createElement(ae,{color:k.status.error,dimColor:!0},"[!] ",m.error)))}let h=m.lineCount-1,f=h>0?`+${h} lines`:"1 line";return K.createElement(Ge,{key:`pasted-${m.id}`},K.createElement(ae,{color:k.ui.muted}," ","[TEXT] "),K.createElement(ae,{color:k.text.secondary},"Pasted text #",p+1),K.createElement(ae,{color:k.ui.muted}," (",f,")"))}),[t]);return K.createElement(Ge,{borderStyle:"round",borderColor:c?k.border.focused:k.border.default,paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},d&&K.createElement(Ge,{flexDirection:"column",marginBottom:0},d),g&&K.createElement(Ge,{flexDirection:"column",marginBottom:0},g),K.createElement(Ge,null,K.createElement(dm,{mode:r,isFocused:!e}),K.createElement(ae,null," "),i.length===0&&!e?s?K.createElement(ae,null,K.createElement(ae,{inverse:!0}," "),K.createElement(ae,{color:k.ui.muted},s),K.createElement(ae,{color:k.ui.muted,dimColor:!0}," (Tab to accept)")):K.createElement(ae,{color:k.ui.muted},kw):K.createElement(ae,null,K.createElement(ae,{color:k.text.primary},i.slice(0,n)),!e&&K.createElement(ae,{inverse:!0}," "),K.createElement(ae,{color:k.text.primary},i.slice(n)),l&&K.createElement(ae,{color:k.ui.muted},l))))}var mm=Iw(Pw,(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 Ar,{useState as Aw,useEffect as Dw,useRef as Mw,memo as Rw}from"react";import{Box as Nw,Text as Oc}from"@jrichman/ink";import Ow from"ink-spinner";function _w(i){if(i<60)return`${i}s`;let e=Math.floor(i/60),t=i%60;return`${e}m ${t}s`}function $w({isLoading:i,phrase:e="Processing",startTime:t}){let[n,s]=Aw(0),r=Mw(null);return Dw(()=>{if(r.current&&(clearInterval(r.current),r.current=null),!i){s(0);return}let o=t||Date.now();return s(Math.floor((Date.now()-o)/1e3)),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?Ar.createElement(Nw,{flexDirection:"row",alignItems:"center",paddingX:2,marginBottom:1,flexShrink:0},Ar.createElement(Oc,{color:k.text.accent},Ar.createElement(Ow,{type:"dots"})),Ar.createElement(Oc,{color:k.text.primary}," ",e,"... "),Ar.createElement(Oc,{color:k.text.secondary},"(esc to cancel",n>0?`, ${_w(n)}`:"",")")):null}var pm=Rw($w);import Ee,{memo as jw,useMemo as Tm}from"react";import{Box as Rs,Text as ut}from"@jrichman/ink";import{useState as hm,useEffect as fm,useCallback as Fw,useRef as bm}from"react";import{useStdout as Lw}from"@jrichman/ink";var Ds=80,Ms=24,Uw=100;function yi(i){let{debounceMs:e=Uw}=i||{},{stdout:t}=Lw(),[n,s]=hm({width:t?.columns||Ds,height:t?.rows||Ms,rows:t?.rows||Ms,columns:t?.columns||Ds}),[r,o]=hm(!1),a=bm(null),c=bm(null);fm(()=>{function d(){o(!0),a.current&&clearTimeout(a.current),c.current&&clearTimeout(c.current),a.current=setTimeout(()=>{let g=process.stdout.columns||Ds,m=process.stdout.rows||Ms;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]),fm(()=>{if(t){let d=t.columns||Ds,g=t.rows||Ms;(d!==n.width||g!==n.height)&&s({width:d,height:g,rows:g,columns:d})}},[t?.columns,t?.rows]);let l=Fw(()=>{s({width:process.stdout.columns||Ds,height:process.stdout.rows||Ms,rows:process.stdout.rows||Ms,columns:process.stdout.columns||Ds})},[]);return{...n,isResizing:r,refresh:l}}Fo();import{useState as En,useEffect as ym,useRef as Bw,useCallback as Ww}from"react";function vm(i=1e4){let[e,t]=En("not-ready"),[n,s]=En(!1),[r,o]=En(!1),[a,c]=En(0),[l,d]=En(5),[g,m]=En(0),[p,h]=En(!1),[f,y]=En(!1),v=Bw(!1),T=Ww(C=>{C.isInitializing||C.initState==="initializing"?t("initializing"):C.isRunning&&C.isInitialized?t("ready"):t("not-ready"),s(C.hasBrowser??!1),o(C.multiAgentMode??!1),c(C.runningAgentCount??0),d(C.maxConcurrentAgents??5),m(C.tabCount??0),h(C.isExecuting??!1),y(C.hasActiveSession??!1)},[]);return ym(()=>{let C=re.onStatusChange(I=>{T(I)});return()=>C()},[T]),ym(()=>{let C=()=>{let E=re.getStatus();E.initState==="idle"&&!v.current&&(v.current=!0,re.initialize().catch(w=>{console.debug("[useBrowserStatus] Auto-init failed:",w.message)}),E=re.getStatus()),T(E)};C();let I=setInterval(C,i);return()=>clearInterval(I)},[i,T]),{status:e,hasBrowser:n,multiAgentMode:r,runningAgentCount:a,maxConcurrentAgents:l,tabCount:g,isExecuting:p,hasActiveSession:f}}import{useState as vi,useEffect as Hw,useCallback as Sm}from"react";var Gw=300*1e3;function wm(){let[i,e]=vi(null),[t,n]=vi(null),[s,r]=vi(!1),[o,a]=vi(null),c=Sm(async(m=!1)=>{r(!0),a(null);try{let p=await Sr.fetchQuotaStatus(m);e(p);let h=await Sr.getUsageDisplayData();n(h)}catch(p){a(p instanceof Error?p.message:"Failed to fetch quota")}finally{r(!1)}},[]),l=Sm(async()=>{await c(!0)},[c]);Hw(()=>{c();let m=setInterval(()=>{c(!0)},Gw);return()=>clearInterval(m)},[c]);let d=t?Ag(t.percent):"normal",g=t?wr(t.resetsAt,t.resetsInSeconds):"";return{quota:i,usageDisplay:t,severity:d,resetTimeDisplay:g,isLoading:s,error:o,refresh:l}}Pn();var zw={3:"#FFD700",2:"#A78BFA",1:"#60A5FA",0:k.ui.muted},qw={ready:"#10B981",initializing:"#F59E0B","not-ready":"#F97316"},Kw={normal:k.ui.muted,notice:"#60A5FA",warning:"#FBBF24",high:"#F97316",critical:"#EF4444"};function Vw(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function Xw(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 Yw({cwd:i,selectedModel:e,showScrollHint:t=!1,tier:n=0}){let{width:s}=yi(),{status:r}=vm(),{usageDisplay:o,severity:a,resetTimeDisplay:c}=wm(),l=hr(),d=Pe.getDisplayName(n),g=zw[n]||k.ui.muted,{displayPath:m,shortcuts:p}=Tm(()=>{let f=`${e.displayName} /model`,y=" ● browser",v=t?"? help · Shift+↑↓ scroll":"? help",C=f.length+y.length+v.length+" ".length*2+4,I=Math.max(15,Math.floor((s-C)*.4));return{displayPath:Xw(Vw(i),I),shortcuts:v}},[i,e.displayName,t,s]),h=Tm(()=>{if(!o)return null;let{percent:f,type:y}=o,v=y==="weekly"?"weekly":"5-hour";return f>=100?`You've hit your ${v} limit`:f>=90?`${f}% of ${v} limit used`:`${f}% ${v} usage`},[o]);return Ee.createElement(Rs,{flexDirection:"column",width:"100%"},o&&Ee.createElement(Rs,{paddingX:2,justifyContent:"center"},Ee.createElement(ut,{color:Kw[a]},h),c&&Ee.createElement(Ee.Fragment,null,Ee.createElement(ut,{color:k.ui.muted}," · "),Ee.createElement(ut,{color:k.ui.muted},"resets ",c))),Ee.createElement(Rs,{paddingX:2,paddingY:0,width:"100%",justifyContent:"space-between",flexDirection:"row"},Ee.createElement(Rs,null,Ee.createElement(ut,{color:k.text.link},m),Ee.createElement(ut,{color:k.ui.muted}," v",l),Ee.createElement(ut,{color:k.ui.muted}," · "),Ee.createElement(ut,{color:g,bold:!0},d)),Ee.createElement(Rs,null,Ee.createElement(ut,{color:k.text.accent},e.displayName),Ee.createElement(ut,{color:k.text.secondary}," /model"),Ee.createElement(ut,{color:k.text.secondary}," "),Ee.createElement(ut,{color:qw[r]},"●"),Ee.createElement(ut,{color:k.text.secondary}," browser")),Ee.createElement(Rs,null,Ee.createElement(ut,{color:k.text.secondary},p))))}var xm=jw(Yw);import Bc,{memo as Wc}from"react";import{Box as ET}from"@jrichman/ink";import de,{memo as vT,useMemo as Nm}from"react";import{Box as mt,Text as wt}from"@jrichman/ink";import Ns,{memo as Qw,useState as Jw}from"react";import{Box as _c,Text as $c,useInput as Zw}from"@jrichman/ink";function eT({suggestions:i,onSelect:e,isActive:t=!1}){let n=i.flatMap(o=>o.options),[s,r]=Jw(0);return Zw((o,a)=>{if(!t||!e||n.length===0)return;if(o===" "||a.rightArrow||a.downArrow){r(l=>(l+1)%n.length);return}if(a.leftArrow||a.upArrow){r(l=>(l-1+n.length)%n.length);return}if(a.return){e(n[s]??"");return}let c=parseInt(o,10);!isNaN(c)&&c>=1&&c<=n.length&&e(n[c-1]??"")},{isActive:t&&!!e}),n.length===0?null:Ns.createElement(_c,{flexDirection:"column",marginTop:1},Ns.createElement(_c,{flexDirection:"row",flexWrap:"wrap",gap:1},n.map((o,a)=>{let c=a===s,l=a<9?`${a+1}`:null;return Ns.createElement(_c,{key:`sug-${a}`,borderStyle:"round",borderColor:c?k.text.accent:k.border.default,paddingX:1,paddingY:0},l&&Ns.createElement($c,{color:c?k.text.accent:k.ui.muted},l,". "),Ns.createElement($c,{color:c?k.text.accent:k.text.secondary},o))})),e&&Ns.createElement($c,{color:k.ui.muted},n.length===1?"Enter to use Tab to dismiss":`Tab/↑↓ to navigate Enter or 1-${Math.min(n.length,9)} to select`))}var Cm=Qw(eT,(i,e)=>i.suggestions===e.suggestions&&i.isActive===e.isActive?!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 Qn,{memo as tT}from"react";import{Box as Si,Text as Fc}from"@jrichman/ink";function nT({workingFiles:i}){return i.length===0?null:Qn.createElement(Si,{flexDirection:"column",marginTop:1,width:"100%"},Qn.createElement(Si,{marginBottom:0,width:"100%"},Qn.createElement(Fc,{color:"#9CA3AF",bold:!0},"Working Files"),Qn.createElement(Fc,{color:"#6B7280"}," (",i.length,")")),Qn.createElement(Si,{flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},i.map(e=>Qn.createElement(Si,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},Qn.createElement(Fc,{color:"white"},e.name)))))}var Em=tT(nT,(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 dt,{memo as sT,useMemo as rT,useState as oT}from"react";import{Box as Dr,Text as In}from"@jrichman/ink";var Lc=5;function iT({conversationHistory:i,onSelect:e}){let[t,n]=oT(!1),{displayedItems:s,hiddenCount:r}=rT(()=>i.length<=Lc||t?{displayedItems:i,hiddenCount:0}:{displayedItems:i.slice(0,Lc),hiddenCount:i.length-Lc},[i,t]);return i.length===0?null:dt.createElement(Dr,{flexDirection:"column",marginTop:1},dt.createElement(Dr,{marginBottom:0},dt.createElement(In,{color:k.text.secondary},"💬 "),dt.createElement(In,{color:k.text.secondary,bold:!0},i.length," conversation",i.length!==1?"s":""," found")),dt.createElement(Dr,{flexDirection:"column",paddingLeft:2},s.map((o,a)=>dt.createElement(Dr,{key:`conv-${o.id}-${a}`},dt.createElement(In,{color:k.ui.muted},"• "),dt.createElement(In,{color:k.text.primary},o.title),dt.createElement(In,{color:k.ui.muted}," ("),dt.createElement(In,{color:k.text.link},aT(o.id)),dt.createElement(In,{color:k.ui.muted},")"))),r>0&&dt.createElement(Dr,{marginTop:0},dt.createElement(In,{color:k.text.accent},"+",r," more conversation",r!==1?"s":""))))}function aT(i,e=20){return i.length<=e?i:i.slice(0,e-3)+"..."}var Im=sT(iT);import Q,{memo as cT,useMemo as lT}from"react";import{Box as gt,Text as le}from"@jrichman/ink";Pn();function uT(i){switch(i){case 3:return"#FFD700";case 2:return"#A78BFA";case 1:return"#60A5FA";default:return k.ui.muted}}function dT(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function gT(){let i="#E8B4B8",e="#B8E4E8",t="#4A4A4A";return Q.createElement(gt,{flexDirection:"column"},Q.createElement(gt,null,Q.createElement(le,{color:i},"██"),Q.createElement(le,null," "),Q.createElement(le,{color:i},"██"),Q.createElement(le,null," "),Q.createElement(le,{color:i},"██")),Q.createElement(gt,null,Q.createElement(le,{color:i},"██████████")),Q.createElement(gt,null,Q.createElement(le,{color:i},"██"),Q.createElement(le,{color:e},"██████"),Q.createElement(le,{color:i},"██")),Q.createElement(gt,null,Q.createElement(le,{color:i},"██"),Q.createElement(le,{color:t},"██"),Q.createElement(le,{color:e},"██"),Q.createElement(le,{color:t},"██"),Q.createElement(le,{color:i},"██")),Q.createElement(gt,null,Q.createElement(le,{color:i},"██"),Q.createElement(le,{color:e},"██████"),Q.createElement(le,{color:i},"██")),Q.createElement(gt,null,Q.createElement(le,{color:i},"████"),Q.createElement(le,{color:t},"██"),Q.createElement(le,{color:i},"████")),Q.createElement(gt,null,Q.createElement(le,{color:i}," ██████ ")))}function mT({projectPath:i,variant:e="main",tier:t=0}){let n=hr(),s=lT(()=>i?dT(i):null,[i]),r=Pe.getDisplayName(t),o=uT(t);return e==="main"?Q.createElement(gt,{flexDirection:"row",paddingX:1,marginY:1,gap:2},Q.createElement(gT,null),Q.createElement(gt,{flexDirection:"column",justifyContent:"center"},Q.createElement(gt,null,Q.createElement(le,{color:k.colors.AccentPurple,bold:!0},"Orion"),Q.createElement(le,{color:k.ui.muted}," v",n),Q.createElement(le,{color:k.ui.muted}," · "),Q.createElement(le,{color:o,bold:!0},"Orion ",r)),Q.createElement(le,{color:k.text.secondary},"Your partner in getting things done."),Q.createElement(le,{color:k.text.secondary,dimColor:!0},"More done, more sleep."),s&&Q.createElement(gt,{marginTop:1},Q.createElement(le,{color:k.ui.muted},s)))):Q.createElement(gt,{paddingX:1,marginY:1},Q.createElement(le,{color:k.colors.AccentPurple},"● "),e==="fresh"&&Q.createElement(le,{color:k.text.secondary},"Ready when you are."),e==="continue"&&Q.createElement(le,{color:k.text.secondary},"Picking up where we left off."),e==="new"&&Q.createElement(le,{color:k.text.secondary},"New conversation started."))}var km=cT(mT);function Pm(i){return i.includes("Orion ready")||i.includes("Fresh start")||i.includes("Welcome back")||i.includes("New conversation")||i.includes("Conversation cleared")}function Am(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 et,{memo as wi,useMemo as pT}from"react";import{Box as Os,Text as Jn}from"@jrichman/ink";var ve={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:"*/"}};ve.ts=ve.typescript;ve.js=ve.javascript;ve.jsx=ve.javascript;ve.tsx=ve.typescript;ve.py=ve.python;ve.sh=ve.bash;ve.shell=ve.bash;ve.zsh=ve.bash;ve.rs=ve.rust;ve.golang=ve.go;ve.yml=ve.yaml;function hT(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 fT={keyword:k.status.warning,string:k.status.success,comment:k.ui.comment,number:k.text.link,function:k.text.link,operator:k.text.primary,punctuation:k.ui.muted,type:k.status.info,plain:k.text.primary},bT=wi(function({line:e,language:t}){if(!t)return et.createElement(Jn,{color:k.text.primary},e);let n=hT(e,t);return et.createElement(Jn,null,n.map((s,r)=>et.createElement(Jn,{key:r,color:fT[s.type]},s.value)))}),yT=wi(function({code:e,language:t,showLineNumbers:n=!1,startLineNumber:s=1,maxLines:r}){let{lines:o,langDef:a,truncated:c}=pT(()=>{let d=e.split(`
2610
+ `),g=t?ve[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 et.createElement(Os,{flexDirection:"column"},o.map((d,g)=>et.createElement(Os,{key:g,flexDirection:"row"},n&&et.createElement(Os,{width:l+2,flexShrink:0},et.createElement(Jn,{color:k.ui.muted},String(s+g).padStart(l," ")," │")),et.createElement(Os,{flexGrow:1},et.createElement(bT,{line:d,language:a})))),c>0&&et.createElement(Jn,{color:k.ui.muted}," ... ",c," more lines"))}),Dm=wi(function({code:e,language:t,showLanguageLabel:n=!0,showLineNumbers:s=!1,maxLines:r,showBorder:o=!0}){let a=t?.toLowerCase(),c=a&&ve[a]?a:void 0;return et.createElement(Os,{flexDirection:"column",borderStyle:o?"round":void 0,borderColor:o?k.border.default:void 0,paddingX:o?1:0},n&&c&&et.createElement(Os,{marginBottom:0},et.createElement(Jn,{color:k.ui.muted,dimColor:!0},c)),et.createElement(yT,{code:e,language:c,showLineNumbers:s,maxLines:r}))}),u1=wi(function({children:e}){return et.createElement(Jn,{color:k.status.warning,bold:!1},"`",e,"`")});function Mm(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 ST=500;function Om(i,e){return i.length<=e?{lines:i,truncated:!1}:{lines:i.slice(0,e),truncated:!0}}function wT({message:i,onSuggestionClick:e,maxLines:t=ST,isSuggestionsActive:n=!1}){let{role:s,content:r}=i,{userTier:o}=fr(),a=Nm(()=>{if(s!=="assistant")return null;let{suggestions:l,cleanedContent:d}=_r(r),{workingFiles:g,cleanedContent:m}=Jc(d),{conversationHistory:p,cleanedContent:h}=Zc(m),y=el(h).split(`
2611
+ `),{lines:v,truncated:T}=Om(y,t);return{suggestions:l,workingFiles:g,conversationHistory:p,lines:v,truncated:T,totalLines:y.length}},[r,s,t]),c=Nm(()=>{if(s==="assistant")return null;let l=r.split(`
2612
+ `);return Om(l,t)},[r,s,t]);if(s==="system"&&c){if(Pm(r)){let{variant:m,projectPath:p}=Am(r);return de.createElement(km,{variant:m,projectPath:p,tier:o})}let{lines:l,truncated:d}=c,g=r.split(`
2613
2613
  `);return de.createElement(mt,{marginY:0,flexDirection:"column",paddingX:1},de.createElement(mt,{flexDirection:"row"},de.createElement(wt,{color:k.ui.muted},"● "),de.createElement(mt,{flexDirection:"column",flexGrow:1},l.map((m,p)=>de.createElement(wt,{key:`sys-${p}`,color:k.ui.muted},m)),d&&de.createElement(wt,{color:k.ui.muted}," ... (",g.length-t," more)"))))}if(s==="user"&&c){let{lines:l,truncated:d}=c,g=r.split(`
2614
2614
  `);return de.createElement(mt,{marginY:1,flexDirection:"column",paddingX:1},de.createElement(mt,{flexDirection:"row"},de.createElement(wt,{color:k.text.primary},"❯ "),de.createElement(mt,{flexDirection:"column",flexGrow:1},l.map((m,p)=>de.createElement(wt,{key:`user-${p}`,color:k.text.primary},m)),d&&de.createElement(wt,{color:k.ui.muted}," ... (",g.length-t," more)"))))}if(s==="assistant"&&a){let{suggestions:l,workingFiles:d,conversationHistory:g,lines:m,truncated:p,totalLines:h}=a,f=m.join(`
2615
- `),y=Mm(f);return de.createElement(mt,{marginY:1,flexDirection:"column",paddingX:1},de.createElement(mt,{flexDirection:"row"},de.createElement(wt,{color:k.text.primary},"● "),de.createElement(mt,{flexDirection:"column",flexGrow:1},y?Dm(f).map((v,T)=>v.type==="code"?de.createElement(mt,{key:`code-${T}`,marginY:1},de.createElement(Am,{code:v.content,language:v.language,showBorder:!0,maxLines:50})):v.content.split(`
2616
- `).map((C,I)=>C.trim()===""?de.createElement(wt,{key:`text-${T}-${I}`}," "):de.createElement(wt,{key:`text-${T}-${I}`,color:k.text.primary},Pi(C)))):m.map((v,T)=>v.trim()===""?de.createElement(wt,{key:`asst-${T}`}," "):de.createElement(wt,{key:`asst-${T}`,color:k.text.primary},Pi(v))),p&&de.createElement(wt,{color:k.ui.muted}," ... (",h-t," more)"))),g.length>0&&de.createElement(mt,{paddingLeft:2},de.createElement(Em,{conversationHistory:g})),d.length>0&&de.createElement(mt,{paddingLeft:2},de.createElement(Cm,{workingFiles:d})),l.length>0&&de.createElement(mt,{paddingLeft:2},de.createElement(xm,{suggestions:l,onSelect:e,isActive:n})))}return null}var Om=bT(vT,(i,e)=>i.message.id===e.message.id&&i.message.content===e.message.content&&i.maxLines===e.maxLines&&i.isSuggestionsActive===e.isSuggestionsActive);import Uc,{memo as ST}from"react";import{Box as wT,Text as _m}from"@jrichman/ink";function TT({version:i,showDetails:e=!0}){return e?Uc.createElement(wT,{marginBottom:1,paddingX:1},Uc.createElement(_m,{color:k.text.primary,bold:!0},"Orion"),i&&Uc.createElement(_m,{color:k.ui.muted,dimColor:!0}," v",i)):null}var $m=ST(TT);var CT=Wc(Om),ET=Wc($m),IT=500;function kT({messages:i,version:e,showHeader:t=!1,hasFocus:n=!0,onSuggestionClick:s,staticRemountKey:r=0}){return Bc.createElement(xT,{flexDirection:"column",key:r},t&&Bc.createElement(ET,{version:e,showDetails:!0}),i.map((o,a)=>Bc.createElement(CT,{key:o.id,message:o,maxLines:IT,onSuggestionClick:s,isSuggestionsActive:n&&a===i.length-1})))}var Fm=Wc(kT);import Lm,{memo as PT}from"react";import{Box as AT,Text as DT}from"@jrichman/ink";function MT({width:i,color:e=k.border.default,char:t="─"}){let{width:n}=yi(),s=typeof i=="number"?i:typeof i=="string"&&i.endsWith("%")?Math.floor(parseInt(i)/100*n):n-4,r=t.repeat(s);return Lm.createElement(AT,null,Lm.createElement(DT,{color:e},r))}var Um=PT(MT);import Zn,{memo as Wm,useState as $1,useEffect as RT,useRef as NT,useCallback as F1}from"react";import{Box as Ti,Text as Bm}from"@jrichman/ink";var OT={success:{icon:"✓",color:k.status.success,borderColor:k.status.success},error:{icon:"✕",color:k.status.error,borderColor:k.status.error},warning:{icon:"⚠",color:k.status.warning,borderColor:k.status.warning},info:{icon:"ℹ",color:k.status.info,borderColor:k.border.default}},_T=Wm(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=NT(null);return RT(()=>{if(n>0&&s)return l.current=setTimeout(s,n),()=>{l.current&&clearTimeout(l.current)}},[n,s]),Zn.createElement(Ti,{borderStyle:o?"round":void 0,borderColor:o?a.borderColor:void 0,paddingX:o?1:0,paddingY:0,flexDirection:"row",alignItems:"center"},Zn.createElement(Bm,{color:a.color},c),Zn.createElement(Ti,{marginLeft:1},Zn.createElement(Bm,{color:k.text.primary},e)))}),Hm=Wm(function({toasts:e,onRemove:t,maxToasts:n=3,position:s="bottom"}){let r=e.slice(-n);return r.length===0?null:Zn.createElement(Ti,{flexDirection:"column",marginTop:s==="bottom"?1:0,marginBottom:s==="top"?1:0},r.map(o=>Zn.createElement(Ti,{key:o.id,marginBottom:1},Zn.createElement(_T,{message:o.message,type:o.type,duration:o.duration??3e3,onDismiss:()=>t(o.id)}))))});import Le,{memo as Gm,useMemo as $T}from"react";import{Box as Hc,Text as Tt}from"@jrichman/ink";var FT=Gm(function({text:e,query:t}){let n=$T(()=>Wg(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 Le.createElement(Le.Fragment,null,o.map((c,l)=>Le.createElement(Tt,{key:l,color:c.isMatch?k.status.warning:k.text.primary,bold:c.isMatch,inverse:c.isMatch},c.text)),a&&Le.createElement(Tt,{color:k.ui.muted},"..."))});function LT({query:i,history:e,currentMatchIndex:t,matchCount:n,matchedEntry:s,isActive:r}){return r?Le.createElement(Hc,{flexDirection:"column",paddingX:1,borderStyle:"single",borderColor:k.border.default},Le.createElement(Hc,{flexDirection:"row"},Le.createElement(Tt,{color:k.text.accent},"(reverse-i-search)"),Le.createElement(Tt,{color:k.text.primary},"`"),Le.createElement(Tt,{color:k.status.warning},i),Le.createElement(Tt,{color:k.text.primary},"'"),Le.createElement(Tt,{color:k.ui.muted},": "),s?Le.createElement(FT,{text:s,query:i}):i?Le.createElement(Tt,{color:k.ui.muted,italic:!0},"no match"):Le.createElement(Tt,{color:k.ui.muted,italic:!0},"type to search history")),i&&Le.createElement(Hc,{flexDirection:"row",marginTop:0},Le.createElement(Tt,{color:k.ui.muted},n>0?`[${t+1}/${n}]`:"[0/0]"),Le.createElement(Tt,{color:k.ui.muted}," "),Le.createElement(Tt,{color:k.ui.muted,italic:!0},n>0?"Up/Down to navigate, Enter to select, Esc to cancel":"No matches found"))):null}var jm=Gm(LT);Pn();function BT(){let i=jn(),e=Pt(),{regularQueuedMessages:t,crossDeviceTasks:n}=rc(),s=Ts(),r=Kt(),{userTier:o}=fr(),a=br(),c=Kn(),{handleCommand:l}=ci(),d=oc(),g=Gc();i.isLoading&&g.current===void 0?g.current=Date.now():i.isLoading||(g.current=void 0);let m=g.current,p=qm(()=>{let E=null;for(let S=i.messages.length-1;S>=0;S--){let P=i.messages[S];if(P.role==="assistant"&&P.content){E=P;break}}if(!E)return null;let{suggestions:w}=_r(E.content);return w.length>0&&w[0].options.length>0?w[0].options[0]:null},[i.messages]),h=Gc(null);zm(()=>{let E=null;i.isLoading?E=null:a.input===""||p&&p.toLowerCase().startsWith(a.input.toLowerCase())?E=p:E=null,h.current!==E&&(h.current=E,c.setSuggestion(E))},[p,i.isLoading,a.input]);let f=UT(async()=>{let E=a.pastedTexts.filter(w=>!w.error||w.type==="text");if(a.input.startsWith("/")){await l(a.input);return}if(c.clearPastedTexts(),E.length>0){let{fullInput:w,imageUrls:S,errors:P}=await c.processFilesForSubmit();if(P.length>0&&!w.trim()&&S.length===0){e.addSystemMessage(`Failed to read files:
2615
+ `),y=Rm(f);return de.createElement(mt,{marginY:1,flexDirection:"column",paddingX:1},de.createElement(mt,{flexDirection:"row"},de.createElement(wt,{color:k.text.primary},"● "),de.createElement(mt,{flexDirection:"column",flexGrow:1},y?Mm(f).map((v,T)=>v.type==="code"?de.createElement(mt,{key:`code-${T}`,marginY:1},de.createElement(Dm,{code:v.content,language:v.language,showBorder:!0,maxLines:50})):v.content.split(`
2616
+ `).map((C,I)=>C.trim()===""?de.createElement(wt,{key:`text-${T}-${I}`}," "):de.createElement(wt,{key:`text-${T}-${I}`,color:k.text.primary},Pi(C)))):m.map((v,T)=>v.trim()===""?de.createElement(wt,{key:`asst-${T}`}," "):de.createElement(wt,{key:`asst-${T}`,color:k.text.primary},Pi(v))),p&&de.createElement(wt,{color:k.ui.muted}," ... (",h-t," more)"))),g.length>0&&de.createElement(mt,{paddingLeft:2},de.createElement(Im,{conversationHistory:g})),d.length>0&&de.createElement(mt,{paddingLeft:2},de.createElement(Em,{workingFiles:d})),l.length>0&&de.createElement(mt,{paddingLeft:2},de.createElement(Cm,{suggestions:l,onSelect:e,isActive:n})))}return null}var _m=vT(wT,(i,e)=>i.message.id===e.message.id&&i.message.content===e.message.content&&i.maxLines===e.maxLines&&i.isSuggestionsActive===e.isSuggestionsActive);import Uc,{memo as TT}from"react";import{Box as xT,Text as $m}from"@jrichman/ink";function CT({version:i,showDetails:e=!0}){return e?Uc.createElement(xT,{marginBottom:1,paddingX:1},Uc.createElement($m,{color:k.text.primary,bold:!0},"Orion"),i&&Uc.createElement($m,{color:k.ui.muted,dimColor:!0}," v",i)):null}var Fm=TT(CT);var IT=Wc(_m),kT=Wc(Fm),PT=500;function AT({messages:i,version:e,showHeader:t=!1,hasFocus:n=!0,onSuggestionClick:s,staticRemountKey:r=0}){return Bc.createElement(ET,{flexDirection:"column",key:r},t&&Bc.createElement(kT,{version:e,showDetails:!0}),i.map((o,a)=>Bc.createElement(IT,{key:o.id,message:o,maxLines:PT,onSuggestionClick:s,isSuggestionsActive:n&&a===i.length-1})))}var Lm=Wc(AT);import Um,{memo as DT}from"react";import{Box as MT,Text as RT}from"@jrichman/ink";function NT({width:i,color:e=k.border.default,char:t="─"}){let{width:n}=yi(),s=typeof i=="number"?i:typeof i=="string"&&i.endsWith("%")?Math.floor(parseInt(i)/100*n):n-4,r=t.repeat(s);return Um.createElement(MT,null,Um.createElement(RT,{color:e},r))}var Bm=DT(NT);import Zn,{memo as Hm,useState as L1,useEffect as OT,useRef as _T,useCallback as U1}from"react";import{Box as Ti,Text as Wm}from"@jrichman/ink";var $T={success:{icon:"✓",color:k.status.success,borderColor:k.status.success},error:{icon:"✕",color:k.status.error,borderColor:k.status.error},warning:{icon:"⚠",color:k.status.warning,borderColor:k.status.warning},info:{icon:"ℹ",color:k.status.info,borderColor:k.border.default}},FT=Hm(function({message:e,type:t="info",duration:n=3e3,onDismiss:s,icon:r,showBorder:o=!0}){let a=$T[t],c=r??a.icon,l=_T(null);return OT(()=>{if(n>0&&s)return l.current=setTimeout(s,n),()=>{l.current&&clearTimeout(l.current)}},[n,s]),Zn.createElement(Ti,{borderStyle:o?"round":void 0,borderColor:o?a.borderColor:void 0,paddingX:o?1:0,paddingY:0,flexDirection:"row",alignItems:"center"},Zn.createElement(Wm,{color:a.color},c),Zn.createElement(Ti,{marginLeft:1},Zn.createElement(Wm,{color:k.text.primary},e)))}),Gm=Hm(function({toasts:e,onRemove:t,maxToasts:n=3,position:s="bottom"}){let r=e.slice(-n);return r.length===0?null:Zn.createElement(Ti,{flexDirection:"column",marginTop:s==="bottom"?1:0,marginBottom:s==="top"?1:0},r.map(o=>Zn.createElement(Ti,{key:o.id,marginBottom:1},Zn.createElement(FT,{message:o.message,type:o.type,duration:o.duration??3e3,onDismiss:()=>t(o.id)}))))});import Le,{memo as jm,useMemo as LT}from"react";import{Box as Hc,Text as Tt}from"@jrichman/ink";var UT=jm(function({text:e,query:t}){let n=LT(()=>Hg(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 Le.createElement(Le.Fragment,null,o.map((c,l)=>Le.createElement(Tt,{key:l,color:c.isMatch?k.status.warning:k.text.primary,bold:c.isMatch,inverse:c.isMatch},c.text)),a&&Le.createElement(Tt,{color:k.ui.muted},"..."))});function BT({query:i,history:e,currentMatchIndex:t,matchCount:n,matchedEntry:s,isActive:r}){return r?Le.createElement(Hc,{flexDirection:"column",paddingX:1,borderStyle:"single",borderColor:k.border.default},Le.createElement(Hc,{flexDirection:"row"},Le.createElement(Tt,{color:k.text.accent},"(reverse-i-search)"),Le.createElement(Tt,{color:k.text.primary},"`"),Le.createElement(Tt,{color:k.status.warning},i),Le.createElement(Tt,{color:k.text.primary},"'"),Le.createElement(Tt,{color:k.ui.muted},": "),s?Le.createElement(UT,{text:s,query:i}):i?Le.createElement(Tt,{color:k.ui.muted,italic:!0},"no match"):Le.createElement(Tt,{color:k.ui.muted,italic:!0},"type to search history")),i&&Le.createElement(Hc,{flexDirection:"row",marginTop:0},Le.createElement(Tt,{color:k.ui.muted},n>0?`[${t+1}/${n}]`:"[0/0]"),Le.createElement(Tt,{color:k.ui.muted}," "),Le.createElement(Tt,{color:k.ui.muted,italic:!0},n>0?"Up/Down to navigate, Enter to select, Esc to cancel":"No matches found"))):null}var zm=jm(BT);Pn();function HT(){let i=jn(),e=Pt(),{regularQueuedMessages:t,crossDeviceTasks:n}=rc(),s=Ts(),r=Kt(),{userTier:o}=fr(),a=br(),c=Kn(),{handleCommand:l}=ci(),d=oc(),g=Gc();i.isLoading&&g.current===void 0?g.current=Date.now():i.isLoading||(g.current=void 0);let m=g.current,p=Km(()=>{let E=null;for(let S=i.messages.length-1;S>=0;S--){let P=i.messages[S];if(P.role==="assistant"&&P.content){E=P;break}}if(!E)return null;let{suggestions:w}=_r(E.content);return w.length>0&&w[0].options.length>0?w[0].options[0]:null},[i.messages]),h=Gc(null);qm(()=>{let E=null;i.isLoading?E=null:a.input===""||p&&p.toLowerCase().startsWith(a.input.toLowerCase())?E=p:E=null,h.current!==E&&(h.current=E,c.setSuggestion(E))},[p,i.isLoading,a.input]);let f=WT(async()=>{let E=a.pastedTexts.filter(w=>!w.error||w.type==="text");if(a.input.startsWith("/")){await l(a.input);return}if(c.clearPastedTexts(),E.length>0){let{fullInput:w,imageUrls:S,errors:P}=await c.processFilesForSubmit();if(P.length>0&&!w.trim()&&S.length===0){e.addSystemMessage(`Failed to read files:
2617
2617
  ${P.map(x=>` - ${x}`).join(`
2618
- `)}`);return}a.input.trim()&&c.addToHistory(a.input.trim()),e.handleSubmit(w.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:v}=$g({onSubmit:f,enableProfiling:process.env.DEBUG_PERF==="true",bufferFlushInterval:16}),T=Bg({items:a.history,getSearchText:E=>E,direction:"backward",isActive:s.isReverseSearchActive,onMatchSelect:E=>{c.setInput(E.item)}}),C=Gc(!1);zm(()=>{s.isReverseSearchActive&&!T.isSearching?T.startSearch():!s.isReverseSearchActive&&T.isSearching&&T.stopSearch(),C.current&&!T.isSearching&&s.isReverseSearchActive&&(T.currentMatch&&c.setInput(T.currentMatch.item),r.stopReverseSearch()),C.current=T.isSearching},[s.isReverseSearchActive,T.isSearching,T.startSearch,T.stopSearch,T.currentMatch,c,r]);let I=qm(()=>s.showHelp||s.showModelMenu||s.showCommandMenu||s.showWizard||s.isReverseSearchActive||s.showConversationList,[s.showHelp,s.showModelMenu,s.showCommandMenu,s.showWizard,s.isReverseSearchActive,s.showConversationList]);return q.createElement(Ie,{flexDirection:"column",width:"100%"},q.createElement(Fm,{messages:i.messages,showHeader:!1,hasFocus:!I,onSuggestionClick:E=>c.setInput(E),staticRemountKey:i.staticRemountKey}),q.createElement(Ie,{paddingX:2,flexShrink:0},q.createElement(Um,null)),i.compactionStatus&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},i.compactionStatus.status==="starting"&&q.createElement(Ie,null,q.createElement(Jt,{color:k.status.warning},q.createElement(Km,{type:"dots"})),q.createElement(Jt,{color:k.text.secondary}," Compacting context...")),i.compactionStatus.status==="complete"&&q.createElement(Ie,null,q.createElement(Jt,{color:k.status.success},"↓ "),q.createElement(Jt,{color:k.text.secondary},"Context compacted"),i.compactionStatus.originalTokens&&i.compactionStatus.compactedTokens&&q.createElement(Jt,{color:k.ui.muted}," ","(",Math.round(i.compactionStatus.originalTokens/1e3),"k → ",Math.round(i.compactionStatus.compactedTokens/1e3),"k tokens",i.compactionStatus.compressionRatio?`, saved ${Math.round((1-i.compactionStatus.compressionRatio)*100)}%`:"",")")),i.compactionStatus.status==="failed"&&q.createElement(Ie,null,q.createElement(Jt,{color:k.status.error},"✗ Compaction failed"),i.compactionStatus.error&&q.createElement(Jt,{color:k.ui.muted}," - ",i.compactionStatus.error.substring(0,60)))),i.todoList&&i.todoList.todos.length>0&&q.createElement(Ie,{flexShrink:0},q.createElement(Qg,{todoList:i.todoList})),i.externalSession&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(Kg,{session:i.externalSession})),i.activeTools.size>0&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(Gg,{activeTools:i.activeTools,onConfirmationConfirm:E=>e.handleConfirmationConfirm("y"),onConfirmationDecline:E=>e.handleConfirmationDecline()})),i.subAgentOperations.size>0&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(qg,{operations:i.subAgentOperations})),i.pendingConfirmation&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(Xg,{request:i.pendingConfirmation,onConfirm:e.handleConfirmationConfirm,onDecline:e.handleConfirmationDecline,onTimeout:e.handleConfirmationTimeout})),a.isProcessingFiles&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(Jt,{color:k.text.accent},q.createElement(Km,{type:"dots"})),q.createElement(Jt,{color:k.text.primary}," Reading files...")),!a.isProcessingFiles&&q.createElement(mm,{isLoading:i.isLoading,phrase:i.loadingMessage||"Processing",startTime:m}),(t.length>0||n.length>0)&&q.createElement(Ie,{flexShrink:0},q.createElement(cm,{regularQueuedMessages:t,crossDeviceTasks:n})),s.showWizard&&s.wizard.type&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(im,{type:s.wizard.type})),s.showConversationList&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(lm,{conversations:i.conversations,currentConversationId:i.conversationId,onSelect:E=>{e.switchConversation(E)},onClose:()=>r.hideConversationList()})),s.showCommandMenu&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:0},q.createElement(om,{filterText:a.input.startsWith("/")?a.input.substring(1).toLowerCase():"",onSelect:E=>{r.hideCommandMenu(),l(`/${E}`)}})),s.showModelMenu&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(tm,{userTier:o,onSelect:E=>{r.setModel(E),r.hideModelMenu()},onAccessDenied:E=>{e.addSystemMessage(Pe.getAccessDeniedMessage(E)),r.hideModelMenu()}})),s.showHelp&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(Jg,null)),s.isReverseSearchActive&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(jm,{query:T.query,history:a.history,currentMatchIndex:T.currentMatchIndex,matchCount:T.matchCount,matchedEntry:T.currentMatch?.item||null,isActive:s.isReverseSearchActive})),!s.showWizard&&q.createElement(Ie,{flexShrink:0,paddingX:2},q.createElement(gm,{input:a.input,isLoading:i.isLoading,pastedTexts:a.pastedTexts,cursorPosition:a.cursorPosition,suggestion:a.suggestion,mode:s.operationalMode,attachmentCount:a.attachmentCount})),s.toasts.length>0&&q.createElement(Ie,{flexShrink:0,paddingX:2},q.createElement(Hm,{toasts:s.toasts,onRemove:r.removeToast,maxToasts:3})),q.createElement(Tm,{cwd:d,selectedModel:s.selectedModel,showScrollHint:!1,tier:o}))}function Vm({initialProjectPath:i,version:e}={}){return q.createElement(Tg,{initialProjectPath:i,version:e},q.createElement(BT,null))}zc();ke();ke();import oe from"chalk";import QT from"inquirer";import{exec as JT}from"child_process";var kn=class{authService;constructor(){this.authService=Z.getInstance()}openBrowser(e){return new Promise(t=>{let n=process.platform,s;n==="darwin"?s=`open "${e}"`:n==="win32"?s=`start "" "${e}"`:s=`xdg-open "${e}"`,JT(s,r=>{r&&console.log(oe.yellow("⚠️ Could not auto-open browser. Please open the URL manually.")),t()})})}async login(){console.log(oe.blue(`
2618
+ `)}`);return}a.input.trim()&&c.addToHistory(a.input.trim()),e.handleSubmit(w.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:v}=Fg({onSubmit:f,enableProfiling:process.env.DEBUG_PERF==="true",bufferFlushInterval:16}),T=Wg({items:a.history,getSearchText:E=>E,direction:"backward",isActive:s.isReverseSearchActive,onMatchSelect:E=>{c.setInput(E.item)}}),C=Gc(!1);qm(()=>{s.isReverseSearchActive&&!T.isSearching?T.startSearch():!s.isReverseSearchActive&&T.isSearching&&T.stopSearch(),C.current&&!T.isSearching&&s.isReverseSearchActive&&(T.currentMatch&&c.setInput(T.currentMatch.item),r.stopReverseSearch()),C.current=T.isSearching},[s.isReverseSearchActive,T.isSearching,T.startSearch,T.stopSearch,T.currentMatch,c,r]);let I=Km(()=>s.showHelp||s.showModelMenu||s.showCommandMenu||s.showWizard||s.isReverseSearchActive||s.showConversationList,[s.showHelp,s.showModelMenu,s.showCommandMenu,s.showWizard,s.isReverseSearchActive,s.showConversationList]);return q.createElement(Ie,{flexDirection:"column",width:"100%"},q.createElement(Lm,{messages:i.messages,showHeader:!1,hasFocus:!I,onSuggestionClick:E=>c.setInput(E),staticRemountKey:i.staticRemountKey}),q.createElement(Ie,{paddingX:2,flexShrink:0},q.createElement(Bm,null)),i.compactionStatus&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},i.compactionStatus.status==="starting"&&q.createElement(Ie,null,q.createElement(Jt,{color:k.status.warning},q.createElement(Vm,{type:"dots"})),q.createElement(Jt,{color:k.text.secondary}," Compacting context...")),i.compactionStatus.status==="complete"&&q.createElement(Ie,null,q.createElement(Jt,{color:k.status.success},"↓ "),q.createElement(Jt,{color:k.text.secondary},"Context compacted"),i.compactionStatus.originalTokens&&i.compactionStatus.compactedTokens&&q.createElement(Jt,{color:k.ui.muted}," ","(",Math.round(i.compactionStatus.originalTokens/1e3),"k → ",Math.round(i.compactionStatus.compactedTokens/1e3),"k tokens",i.compactionStatus.compressionRatio?`, saved ${Math.round((1-i.compactionStatus.compressionRatio)*100)}%`:"",")")),i.compactionStatus.status==="failed"&&q.createElement(Ie,null,q.createElement(Jt,{color:k.status.error},"✗ Compaction failed"),i.compactionStatus.error&&q.createElement(Jt,{color:k.ui.muted}," - ",i.compactionStatus.error.substring(0,60)))),i.todoList&&i.todoList.todos.length>0&&q.createElement(Ie,{flexShrink:0},q.createElement(Jg,{todoList:i.todoList})),i.externalSession&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(Vg,{session:i.externalSession})),i.activeTools.size>0&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(jg,{activeTools:i.activeTools,onConfirmationConfirm:E=>e.handleConfirmationConfirm("y"),onConfirmationDecline:E=>e.handleConfirmationDecline()})),i.subAgentOperations.size>0&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(Kg,{operations:i.subAgentOperations})),i.pendingConfirmation&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(Yg,{request:i.pendingConfirmation,onConfirm:e.handleConfirmationConfirm,onDecline:e.handleConfirmationDecline,onTimeout:e.handleConfirmationTimeout})),a.isProcessingFiles&&q.createElement(Ie,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(Jt,{color:k.text.accent},q.createElement(Vm,{type:"dots"})),q.createElement(Jt,{color:k.text.primary}," Reading files...")),!a.isProcessingFiles&&q.createElement(pm,{isLoading:i.isLoading,phrase:i.loadingMessage||"Processing",startTime:m}),(t.length>0||n.length>0)&&q.createElement(Ie,{flexShrink:0},q.createElement(lm,{regularQueuedMessages:t,crossDeviceTasks:n})),s.showWizard&&s.wizard.type&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(am,{type:s.wizard.type})),s.showConversationList&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(um,{conversations:i.conversations,currentConversationId:i.conversationId,onSelect:E=>{e.switchConversation(E)},onClose:()=>r.hideConversationList()})),s.showCommandMenu&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:0},q.createElement(im,{filterText:a.input.startsWith("/")?a.input.substring(1).toLowerCase():"",onSelect:E=>{r.hideCommandMenu(),l(`/${E}`)}})),s.showModelMenu&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(nm,{userTier:o,onSelect:E=>{r.setModel(E),r.hideModelMenu()},onAccessDenied:E=>{e.addSystemMessage(Pe.getAccessDeniedMessage(E)),r.hideModelMenu()}})),s.showHelp&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(Zg,null)),s.isReverseSearchActive&&q.createElement(Ie,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(zm,{query:T.query,history:a.history,currentMatchIndex:T.currentMatchIndex,matchCount:T.matchCount,matchedEntry:T.currentMatch?.item||null,isActive:s.isReverseSearchActive})),!s.showWizard&&q.createElement(Ie,{flexShrink:0,paddingX:2},q.createElement(mm,{input:a.input,isLoading:i.isLoading,pastedTexts:a.pastedTexts,cursorPosition:a.cursorPosition,suggestion:a.suggestion,mode:s.operationalMode,attachmentCount:a.attachmentCount})),s.toasts.length>0&&q.createElement(Ie,{flexShrink:0,paddingX:2},q.createElement(Gm,{toasts:s.toasts,onRemove:r.removeToast,maxToasts:3})),q.createElement(xm,{cwd:d,selectedModel:s.selectedModel,showScrollHint:!1,tier:o}))}function Xm({initialProjectPath:i,version:e}={}){return q.createElement(xg,{initialProjectPath:i,version:e},q.createElement(HT,null))}zc();ke();ke();import oe from"chalk";import ZT from"inquirer";import{exec as ex}from"child_process";var kn=class{authService;constructor(){this.authService=Z.getInstance()}openBrowser(e){return new Promise(t=>{let n=process.platform,s;n==="darwin"?s=`open "${e}"`:n==="win32"?s=`start "" "${e}"`:s=`xdg-open "${e}"`,ex(s,r=>{r&&console.log(oe.yellow("⚠️ Could not auto-open browser. Please open the URL manually.")),t()})})}async login(){console.log(oe.blue(`
2619
2619
  🔐 Orion Authentication`)),console.log(oe.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(oe.yellow(`
2620
2620
  📋 Opening browser for authentication...`)),console.log(oe.cyan.underline(` ${e}`)),await this.openBrowser(e),console.log(oe.white(`
2621
2621
  1. Log in with your Orion account in the browser`)),console.log(oe.white("2. Copy the access token shown after login")),console.log(oe.white("3. Paste the token below")),console.log(oe.yellow(`
2622
- Paste your access token here:`));let{accessToken:t}=await QT.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:n=>!n||n.trim().length===0?"Access token is required":!0}]);console.log(oe.gray(`
2622
+ Paste your access token here:`));let{accessToken:t}=await ZT.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:n=>!n||n.trim().length===0?"Access token is required":!0}]);console.log(oe.gray(`
2623
2623
  Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){console.log(oe.green(`
2624
2624
  ✅ Authentication successful!`));try{let s=await this.authService.getUserInfo();s?(console.log(oe.gray(`Logged in as: ${s.email||s.username||"User"}`)),console.log(oe.gray(`Subscription: ${this.getSubscriptionDisplay(s.subscription?.tier)}`))):console.log(oe.gray("Profile loading... (may take a moment for new accounts)"))}catch{}}else console.log(oe.red(`
2625
2625
  ❌ Authentication failed. Please try again.`))}catch(n){console.log(oe.red(`
@@ -2629,7 +2629,7 @@ Verifying access token...`));try{if(await this.authService.authenticateWithAcces
2629
2629
  ❌ Logout failed`)),console.log(oe.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(oe.green(`
2630
2630
  ✅ Authenticated`)),t){console.log(oe.gray("─".repeat(50))),console.log(oe.white("User:",t.name||t.username||"N/A")),console.log(oe.white("Email:",t.email||"N/A"));let n=this.getSubscriptionDisplay(t.subscription?.tier);console.log(oe.white("Subscription:",n)),t.usage&&(console.log(oe.gray(`
2631
2631
  Usage:`)),console.log(oe.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(oe.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(oe.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(oe.yellow(`
2632
- ⚠️ Not authenticated`)),console.log(oe.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"}}};Et();$a();import{fileURLToPath as tx}from"url";import{dirname as nx,join as sx}from"path";import{readFileSync as rx}from"fs";var ox=tx(import.meta.url),ix=nx(ox),rp="1.0.0";try{rp=JSON.parse(rx(sx(ix,"../../package.json"),"utf8")).version}catch{}var sp=!1;async function qc(){let i=process.cwd();if(sp){console.log("Already running...");return}sp=!0,ee.enableCustomUI();let e=Mr.getInstance(),t=Z.getInstance();if(!e.isInitialized()){console.log("🔧 Initializing Orion services...");try{await e.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(o){console.error(`
2632
+ ⚠️ Not authenticated`)),console.log(oe.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"}}};Et();$a();import{fileURLToPath as sx}from"url";import{dirname as rx,join as qc}from"path";import{readFileSync as ox,existsSync as ix}from"fs";var ax=sx(import.meta.url),rp=rx(ax),ip="1.0.0",cx=[qc(rp,"../../package.json"),qc(rp,"../package.json"),qc(process.cwd(),"package.json")];for(let i of cx)try{if(ix(i)){let e=JSON.parse(ox(i,"utf8"));if(e.version){ip=e.version;break}}}catch{}var op=!1;async function Kc(){let i=process.cwd();if(op){console.log("Already running...");return}op=!0,ee.enableCustomUI();let e=Mr.getInstance(),t=Z.getInstance();if(!e.isInitialized()){console.log("🔧 Initializing Orion services...");try{await e.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(o){console.error(`
2633
2633
  ❌ Failed to initialize services:`,o.message),console.error(`
2634
2634
  💡 Tip: Check your internet connection and Firebase configuration.
2635
2635
  `),process.exit(1)}}(!await t.autoAuthenticate()||!t.isAuthenticated())&&(console.log(`🔐 Authentication required to use Orion CLI
@@ -2639,7 +2639,7 @@ Usage:`)),console.log(oe.white(` Standard prompts: ${t.usage.prompt||0}`)),cons
2639
2639
  `)),t.isFirebaseAuthenticated()||(console.error(`
2640
2640
  ❌ 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(`
2641
2641
  Please check your connection and try again.
2642
- `),process.exit(1)),console.log("✅ Authentication verified"),ur.getInstance().setWorkingDirectory(i),process.stdout.write("\x1B[2J\x1B[H");let{waitUntilExit:r}=ex(ZT.createElement(Vm,{initialProjectPath:i,version:rp}),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:!1});await r(),ug()}import N from"chalk";import ge from"inquirer";import tt from"ora";import{exec as ax}from"child_process";ke();var es=class{integrationsService;authService;constructor(){this.integrationsService=Vt.getInstance(),this.authService=Z.getInstance()}async ensureAuthenticated(){let e=tt("Checking authentication...").start();return await this.authService.autoAuthenticate(),this.authService.isAuthenticated()?(e.stop(),!0):(e.fail("Not authenticated"),console.log(N.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}"`,ax(n,()=>{})}async discord(){if(!await this.ensureAuthenticated())return;console.log(N.blue(`
2642
+ `),process.exit(1)),console.log("✅ Authentication verified"),ur.getInstance().setWorkingDirectory(i),process.stdout.write("\x1B[2J\x1B[H");let{waitUntilExit:r}=nx(tx.createElement(Xm,{initialProjectPath:i,version:ip}),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:!1});await r(),dg()}import N from"chalk";import ge from"inquirer";import tt from"ora";import{exec as lx}from"child_process";ke();var es=class{integrationsService;authService;constructor(){this.integrationsService=Vt.getInstance(),this.authService=Z.getInstance()}async ensureAuthenticated(){let e=tt("Checking authentication...").start();return await this.authService.autoAuthenticate(),this.authService.isAuthenticated()?(e.stop(),!0):(e.fail("Not authenticated"),console.log(N.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}"`,lx(n,()=>{})}async discord(){if(!await this.ensureAuthenticated())return;console.log(N.blue(`
2643
2643
  🎮 Discord Integration`)),console.log(N.gray("─".repeat(50)));let e=tt("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(N.green(`
2644
2644
  ✓ Connected`)),console.log(N.white(" Bot:"),N.cyan(e.botUsername||"Unknown")),console.log(N.gray(`
2645
2645
  ─ Setup Info ─`)),e.webhookUrl&&(console.log(N.white(" Webhook URL:"),N.cyan(e.webhookUrl)),console.log(N.gray(" (Add this to Discord Developer Portal → Interactions Endpoint URL)"))),e.botId){let n=this.integrationsService.generateDiscordInviteUrl(e.botId);console.log(N.white(" Invite URL:"),N.cyan(n))}console.log(N.gray(" Commands: /ask, /new, /clear")),console.log(N.gray(`
@@ -2680,4 +2680,4 @@ Current owners:`),e.ownerUsernames?.map(o=>`@${o}`).join(", ")||"None"),console.
2680
2680
  🔌 Integration Status`)),console.log(N.gray("─".repeat(50)));let e=tt("Checking...").start(),[t,n]=await Promise.all([this.integrationsService.getDiscordStatus(),this.integrationsService.getTelegramStatus()]);e.stop(),console.log(N.white(`
2681
2681
  Discord`)),t.connected?(console.log(N.green(" ✓ Connected")),console.log(N.gray(` Bot: ${t.botUsername}`)),console.log(N.gray(` Owners: ${t.ownerUserIds?.join(", ")||"None"}`)),console.log(N.gray(` Guests: ${t.guestUserIds?.length?t.guestUserIds.join(", "):"None"}`)),console.log(N.gray(` Server chat: ${t.allowGuildChat?"Enabled":"Disabled"}`))):(console.log(N.gray(" Not connected")),console.log(N.gray(" Run: orion integrations discord"))),console.log(N.white(`
2682
2682
  Telegram`)),n.connected?(console.log(N.green(" ✓ Connected")),console.log(N.gray(` Bot: @${n.botUsername}`)),console.log(N.gray(` Owners: ${n.ownerUsernames?.map(s=>`@${s}`).join(", ")||"None"}`)),console.log(N.gray(` Guests: ${n.guestUsernames?.length?n.guestUsernames.map(s=>`@${s}`).join(", "):"None"}`)),console.log(N.gray(` Group chat: ${n.allowGroupChat?"Enabled":"Disabled"}`)),n.allowGroupChat&&console.log(N.gray(` Route to DM: ${n.routeToDM?"Enabled":"Disabled"}`))):(console.log(N.gray(" Not connected")),console.log(N.gray(" Run: orion integrations telegram")))}async disconnect(){if(!await this.ensureAuthenticated())return;let e=tt("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(N.yellow(`
2683
- ⚠️ No integrations connected.`));return}s.push(new ge.Separator,{name:"Cancel",value:"cancel"});let{platform:r}=await ge.prompt([{type:"list",name:"platform",message:"Which integration to disconnect?",choices:s}]);if(r==="cancel")return;let{confirm:o}=await ge.prompt([{type:"confirm",name:"confirm",message:N.red(`Disconnect ${r}? This cannot be undone.`),default:!1}]);if(!o){console.log(N.gray("Cancelled."));return}let a=tt("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.")}};en();import lx from"dotenv";import{fileURLToPath as ux}from"url";import{dirname as dx,join as gx}from"path";import{readFileSync as mx}from"fs";lx.config();var px=ux(import.meta.url),hx=dx(px),op=JSON.parse(mx(gx(hx,"..","package.json"),"utf8")),fx=process.argv.includes("--no-update")||process.env.ORION_NO_UPDATE==="true";!wd()&&!fx&&Bn.getInstance(op.version).checkAndUpdate().catch(()=>{});var ts=new cx;ts.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(op.version).option("--no-update","Disable automatic update check");ts.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await qc()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});ts.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(()=>(zc(),np)),n=t.getInstance();console.log("🔧 Initializing Orion services..."),await n.initialize(),await n.waitForDeviceRegistration();let s=ye.find(o=>o.name===e.model)||ye[0];console.log("💭 Sending message...");let r=await n.sendMessage(i,s,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(Or(r))}catch(t){Re.stopSpinner(!1),console.error(Re.formatError(t.message)),process.exit(1)}});var Kc=ts.command("auth").description("Authentication commands");Kc.command("login").description("Login to Orion").action(async()=>{try{await new kn().login()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});Kc.command("logout").description("Logout from Orion").action(async()=>{try{await new kn().logout()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});Kc.command("status").description("Check authentication status").action(async()=>{try{await new kn().status()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});var Ei=ts.command("integrations").description("Manage Discord and Telegram integrations");Ei.command("discord").description("Setup Discord bot integration").action(async()=>{try{await new es().discord()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});Ei.command("telegram").description("Setup Telegram bot integration").action(async()=>{try{await new es().telegram()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});Ei.command("status").description("Show integration status").action(async()=>{try{await new es().status()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});Ei.command("disconnect").description("Disconnect an integration").action(async()=>{try{await new es().disconnect()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});ts.command("models").description("List available AI models").action(()=>{Re.printHeader("Available Models");for(let i of ye)console.log(`${Re.formatModelName(i.name)} - ${i.displayName}`)});process.argv.length===2?qc().catch(i=>{console.error(Re.formatError(i.message)),process.exit(1)}):ts.parse(process.argv);
2683
+ ⚠️ No integrations connected.`));return}s.push(new ge.Separator,{name:"Cancel",value:"cancel"});let{platform:r}=await ge.prompt([{type:"list",name:"platform",message:"Which integration to disconnect?",choices:s}]);if(r==="cancel")return;let{confirm:o}=await ge.prompt([{type:"confirm",name:"confirm",message:N.red(`Disconnect ${r}? This cannot be undone.`),default:!1}]);if(!o){console.log(N.gray("Cancelled."));return}let a=tt("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.")}};en();import dx from"dotenv";import{fileURLToPath as gx}from"url";import{dirname as mx,join as px}from"path";import{readFileSync as hx}from"fs";dx.config();var fx=gx(import.meta.url),bx=mx(fx),ap=JSON.parse(hx(px(bx,"..","package.json"),"utf8")),yx=process.argv.includes("--no-update")||process.env.ORION_NO_UPDATE==="true";!Td()&&!yx&&Bn.getInstance(ap.version).checkAndUpdate().catch(()=>{});var ts=new ux;ts.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(ap.version).option("--no-update","Disable automatic update check");ts.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await Kc()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});ts.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(()=>(zc(),sp)),n=t.getInstance();console.log("🔧 Initializing Orion services..."),await n.initialize(),await n.waitForDeviceRegistration();let s=ye.find(o=>o.name===e.model)||ye[0];console.log("💭 Sending message...");let r=await n.sendMessage(i,s,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(Or(r))}catch(t){Re.stopSpinner(!1),console.error(Re.formatError(t.message)),process.exit(1)}});var Vc=ts.command("auth").description("Authentication commands");Vc.command("login").description("Login to Orion").action(async()=>{try{await new kn().login()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});Vc.command("logout").description("Logout from Orion").action(async()=>{try{await new kn().logout()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});Vc.command("status").description("Check authentication status").action(async()=>{try{await new kn().status()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});var Ei=ts.command("integrations").description("Manage Discord and Telegram integrations");Ei.command("discord").description("Setup Discord bot integration").action(async()=>{try{await new es().discord()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});Ei.command("telegram").description("Setup Telegram bot integration").action(async()=>{try{await new es().telegram()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});Ei.command("status").description("Show integration status").action(async()=>{try{await new es().status()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});Ei.command("disconnect").description("Disconnect an integration").action(async()=>{try{await new es().disconnect()}catch(i){console.error(Re.formatError(i.message)),process.exit(1)}});ts.command("models").description("List available AI models").action(()=>{Re.printHeader("Available Models");for(let i of ye)console.log(`${Re.formatModelName(i.name)} - ${i.displayName}`)});process.argv.length===2?Kc().catch(i=>{console.error(Re.formatError(i.message)),process.exit(1)}):ts.parse(process.argv);