@zinley/orion 1.2.24 → 1.2.26
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.
- package/dist/index.js +221 -217
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Cm=Object.defineProperty;var L=(i,e)=>()=>(i&&(e=i(i=0)),e);var et=(i,e)=>{for(var t in e)Cm(i,t,{get:e[t],enumerable:!0})};var me,Kt=L(()=>{"use strict";me=[{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 vi,u,q=L(()=>{"use strict";vi=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=vi.getInstance()});var It={};et(It,{UserDefaults:()=>ye});import Es from"fs";import Si from"path";import km from"os";var wi,ye,We=L(()=>{"use strict";q();wi=class i{static instance;preferencesPath;preferences={};constructor(){let e=Si.join(km.homedir(),".orion");this.preferencesPath=Si.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadPreferences(){try{if(Es.existsSync(this.preferencesPath)){let e=Es.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=Si.dirname(this.preferencesPath);Es.existsSync(e)||Es.mkdirSync(e,{recursive:!0}),Es.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)}},ye=wi.getInstance()});var xe,Sn=L(()=>{"use strict";Kt();We();q();xe=class{static getDisplayName(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";case 3:return"Max";default:return"Free"}}static plusOnlyModels=[];static proOnlyModels=["snowx-o4.5","snowx-c6","snowx-5-pro"];static maxOnlyModels=["snowx-o4.6"];static getRequiredTier(e){return this.maxOnlyModels.includes(e)?3:this.proOnlyModels.includes(e)?2:this.plusOnlyModels.includes(e)?1:0}static getCurrentUserTier(){let e=ye.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=3?e:0}static setUserTier(e){ye.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 me.filter(t=>this.isModelAccessible(t.name,e))}static getAccessibleModelsForCurrentUser(){let e=this.getCurrentUserTier();return this.getAccessibleModels(e)}static getAccessDeniedMessage(e){switch(this.getRequiredTier(e)){case 1:return"This model requires a Plus subscription. Please upgrade to access.";case 2:return"This model requires a Pro subscription. Please upgrade to access.";case 3:return"This model requires a Max subscription. Please upgrade to access.";default:return"This model is not available with your current subscription."}}static getModelDisplayNameWithTier(e){return e.displayName}}});import*as Ce from"@sentry/node";var Ti,xi,Mc=L(()=>{"use strict";q();Ti=class i{static instance;isEnabled=!0;userId=null;userEmail=null;deviceId=null;constructor(){this.isEnabled=process.env.ORION_DISABLE_TELEMETRY!=="true"}static getInstance(){return i.instance||(i.instance=new i),i.instance}setUser(e,t,n){this.userId=e,this.userEmail=t||null,this.isEnabled&&Ce.setUser({id:e,email:t,subscription:n})}setDevice(e){this.deviceId=e,this.isEnabled&&Ce.setTag("device_id",e)}clearUser(){this.userId=null,this.userEmail=null,this.isEnabled&&Ce.setUser(null)}captureException(e,t){if(!this.isEnabled)return u.debug("[SENTRY] Telemetry disabled, skipping error capture"),null;if(e instanceof Error){let n=e.message.toLowerCase();if(n.includes("[done]")||n.includes("stream ended"))return null}return Ce.withScope(n=>{if(t?.tags)for(let[r,o]of Object.entries(t.tags))n.setTag(r,o);t?.sessionId&&n.setTag("session_id",t.sessionId),t?.conversationId&&n.setTag("conversation_id",t.conversationId),t?.toolName&&n.setTag("tool_name",t.toolName),t?.endpoint&&n.setTag("endpoint",t.endpoint),t?.extra&&n.setExtras(t.extra),t?.toolArgs&&n.setExtra("tool_args",t.toolArgs);let s=Ce.captureException(e);return u.debug(`[SENTRY] Captured exception: ${s}`),s})}captureMessage(e,t="info",n){return this.isEnabled?Ce.withScope(s=>{if(n?.tags)for(let[o,a]of Object.entries(n.tags))s.setTag(o,a);n?.extra&&s.setExtras(n.extra);let r=Ce.captureMessage(e,t);return u.debug(`[SENTRY] Captured message: ${r}`),r}):null}addBreadcrumb(e,t,n,s="info"){this.isEnabled&&Ce.addBreadcrumb({message:e,category:t,data:n,level:s,timestamp:Date.now()/1e3})}trackApiCall(e,t,n){this.addBreadcrumb(`${t} ${e}`,"api_call",{endpoint:e,method:t,statusCode:n})}trackToolExecution(e,t,n){this.addBreadcrumb(`Tool: ${e} - ${t?"success":"failed"}`,"tool_execution",{toolName:e,success:t,duration:n},t?"info":"warning")}trackUserAction(e,t){this.addBreadcrumb(e,"user_action",t)}trackNavigation(e,t){this.addBreadcrumb(`${e} -> ${t}`,"navigation",{from:e,to:t})}setTag(e,t){this.isEnabled&&Ce.setTag(e,t)}setExtra(e,t){this.isEnabled&&Ce.setExtra(e,t)}startTransaction(e,t){return this.isEnabled?Ce.startInactiveSpan({name:e,op:t}):null}},xi=Ti.getInstance()});var As={};et(As,{SecureStorageService:()=>Ir,secureStorage:()=>Om});import Is from"crypto";import Vt from"os";import wn from"fs";import Ci from"path";import{execSync as Pm}from"child_process";var Rc,ks,Oc,Am,Dm,Mm,Ps,Rm,Ir,Om,Ds=L(()=>{"use strict";q();Rc="aes-256-gcm",ks=16,Oc=16,Am=32,Dm=32,Mm=1e5,Ps="__enc__",Rm=["snowx_auth_token","snowx_access_token","snowx_user_data","snowx_device_id","orion_device_id","firebase_custom_token"],Ir=class i{static instance;storagePath;storage={};encryptionKey=null;salt=null;isProduction;constructor(){let e=Ci.join(Vt.homedir(),".orion-cli");this.storagePath=Ci.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(wn.existsSync(this.storagePath)){let e=wn.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=Ci.dirname(this.storagePath);wn.existsSync(e)||wn.mkdirSync(e,{recursive:!0});let t={data:this.storage,salt:this.salt?.toString("base64")};wn.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=Is.randomBytes(Am));let e=this.generateDeviceSeed();this.encryptionKey=Is.pbkdf2Sync(e,this.salt,Mm,Dm,"sha256"),u.debug("[SECURE] Encryption initialized")}generateDeviceSeed(){return[Vt.hostname(),Vt.platform(),Vt.arch(),Vt.cpus()[0]?.model||"unknown-cpu",Vt.userInfo().username,this.getMachineId()].join("|")}getMachineId(){try{if(process.platform==="linux"&&wn.existsSync("/etc/machine-id"))return wn.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let t=Pm("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID" = "([^"]+)"/);if(t)return t[1]}}catch{}return Vt.hostname()+Vt.userInfo().uid}shouldEncrypt(e){return!this.isProduction&&process.env.ORION_SKIP_ENCRYPTION==="true"?!1:Rm.some(t=>e.includes(t))}encrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");let t=Is.randomBytes(ks),n=Is.createCipheriv(Rc,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 Ps+o.toString("base64")}decrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");if(!e.startsWith(Ps))return e;let t=Buffer.from(e.slice(Ps.length),"base64"),n=t.subarray(0,ks),s=t.subarray(ks,ks+Oc),r=t.subarray(ks+Oc),o=Is.createDecipheriv(Rc,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(Ps)?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(Ps)&&(this.storage[t]=this.encrypt(n),e++)}e>0&&(this.saveStorage(),u.debug(`[SECURE] Migrated ${e} values to encrypted storage`))}},Om=Ir.getInstance()});import Nm from"axios";import{EventEmitter as _m}from"events";var Xt,kt,Ms=L(()=>{"use strict";Xt="firebase_timestamp",kt=class i extends _m{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=Nm.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(()=>(We(),It));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(we(),Nc));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 Ei={};et(Ei,{DeviceRegistrationService:()=>Pe});import{EventEmitter as $m}from"events";import{v4 as _c}from"uuid";import Rs from"os";import $c from"fs/promises";import Fm from"path";import{execSync as Os}from"child_process";import Lm from"crypto";var Pe,Pt=L(()=>{"use strict";Ms();we();q();Pe=class i extends $m{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=kt.getInstance(),this.authService=X.getInstance(),this.configDir=Fm.join(Rs.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=Rs.platform();if(e==="darwin")try{let s=Os("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=Os('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=Rs.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}`),Rs.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=Rs.platform();try{let t=null;switch(e){case"darwin":try{let a=Os("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=Os("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 $c.readFile("/etc/machine-id","utf-8").then(o=>o.trim()),u.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await $c.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=Os("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=Lm.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(()=>(We(),It)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${r}`):(r=_c(),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(()=>(We(),It)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${r}`):(r=_c(),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:Xt,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:Xt,lastSeenAt:Xt};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:Xt,lastSeenAt:Xt}],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 Nc={};et(Nc,{AuthService:()=>X});import{EventEmitter as Um}from"events";import{signInAnonymously as Bm,signInWithEmailAndPassword as Wm,createUserWithEmailAndPassword as Hm,signOut as Gm,onAuthStateChanged as Fc,updateProfile as jm,signInWithCustomToken as zm}from"firebase/auth";import Yt from"axios";import Ii from"fs/promises";import Lc from"path";import qm from"os";function Uc(i,e,t){return Promise.race([i,new Promise((n,s)=>setTimeout(()=>s(new Error(t)),e))])}var X,we=L(()=>{"use strict";Sn();q();Mc();X=class i extends Um{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=Lc.join(qm.homedir(),".orion-cli","auth.json")}static getInstance(){return i.instance||(i.instance=new i),i.instance}async initializeTokenFile(){try{let e=Lc.dirname(this.tokenFilePath);await Ii.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{secureStorage:e}=await Promise.resolve().then(()=>(Ds(),As)),{UserDefaults:t}=await Promise.resolve().then(()=>(We(),It)),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 Ii.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 Ii.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(()=>(Ds(),As));t.setItem("snowx_auth_token",e.userId),t.setItem("snowx_access_token",e.token);let{UserDefaults:n}=await Promise.resolve().then(()=>(We(),It));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";xi.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(()=>(Ds(),As)),{UserDefaults:t}=await Promise.resolve().then(()=>(We(),It));e.removeItem("snowx_auth_token"),e.removeItem("snowx_access_token"),t.remove("snowx_auth_token"),t.remove("snowx_access_token"),this.authToken=null,xi.clearUser()}catch(e){console.error("❌ Failed to clear auth token:",e)}}setFirebaseAuth(e){this.auth=e,Fc(e,t=>{this.currentUser=t,this.emit("auth_state_changed",t)})}getFirebaseAuth(){return this.auth}async getCustomTokenFromAPI(e){return this.getCustomTokenFromAPIInternal(e)}async signInWithCustomToken(e){if(!this.auth)throw new Error("Firebase Auth not initialized");let{signInWithCustomToken:t}=await import("firebase/auth");return t(this.auth,e)}async updateUserTierFromToken(e){let t;switch(e.tier){case 1:t=1;break;case 2:t=2;break;case 0:default:t=0;break}xe.setUserTier(t);let{UserDefaults:n}=await Promise.resolve().then(()=>(We(),It));n.set("userSubscriptionTier",e.tier||0),n.set("isTrialUser",!1),u.debug(`User tier updated: ${xe.getDisplayName(t)} (${e.tier})`),u.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let e=await Bm(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 Wm(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 Hm(this.auth,e,t);return this.currentUser=s.user,n&&await jm(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(()=>(Pt(),Ei));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Gm(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(()=>(Pt(),Ei));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(We(),It)),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 Yt.post(`${this.snowxAuthEndpoint}/login`,e):t=await Yt.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 Yt.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(()=>(Ds(),As)),t=e.getItem("snowx_access_token");if(t)return t;let{UserDefaults:n}=await Promise.resolve().then(()=>(We(),It));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=Fc(this.auth,async c=>{if(!r)if(r=!0,clearTimeout(o),a(),c)try{let l=await c.getIdToken(!0);s(l)}catch{s(null)}else s(null)});o=setTimeout(()=>{r||(r=!0,a(),s(null))},2e3)});if(n)return n}let e=await this.getAccessTokenFromStorage();return e?(u.debug("Using stored access token as fallback (Firebase SDK not signed in)"),e):null}getUserId(){return this.authToken?.userId||this.currentUser?.uid||null}getUserEmail(){return this.authToken?.email||this.currentUser?.email||null}async getUserTier(){if(this.authToken?.tier!==void 0)return this.authToken.tier;try{return(await this.getUserProfile())?.tier??0}catch{return console.warn("⚠️ Failed to fetch user tier, defaulting to Free tier"),0}}getCachedUserTier(){return this.authToken?.tier??0}isAuthenticated(){return!!this.authToken&&this.authToken.expiresAt>Date.now()}isFirebaseAuthenticated(){if(this.currentUser)return!0;if(this.authToken?.token&&this.isFirebaseIdToken(this.authToken.token)){let e=this.parseFirebaseIdToken(this.authToken.token);if(e&&Date.now()<=e.exp*1e3)return!0}return!1}async autoAuthenticate(){if(await this.initializeTokenFile(),this.isAuthenticated()){let e=this.getUserId(),t=this.authToken?.token;if(e&&t){u.debug("Using existing authentication token"),u.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e);try{if(this.isFirebaseIdToken(t)){let n=this.parseFirebaseIdToken(t);return n&&Date.now()<=n.exp*1e3?(u.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(u.error("Firebase ID Token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}return await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}catch(n){return u.error("Failed to authenticate with Firebase during auto-authenticate:",n.message),n.response?.status===401||n.response?.status===403||n.response?.status===404?(u.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):u.warn("Transient Firebase auth error - keeping stored token for retry"),!1}}}return!1}async authenticateFirebaseWithStoredToken(){if(console.log("🔥 [AUTH] Starting Firebase authentication..."),!this.auth)throw console.error("❌ [AUTH] Firebase Auth not initialized!"),u.error("Firebase Auth not initialized - cannot authenticate"),new Error("Firebase Auth not initialized. Please ensure ServiceManager is initialized first.");if(console.log("✅ [AUTH] Firebase Auth instance is available"),!this.authToken)throw console.error("❌ [AUTH] No auth token available!"),u.error("No auth token available - cannot authenticate with Firebase"),new Error("No authentication token available");if(console.log("✅ [AUTH] Auth token is available"),console.log(`📋 [AUTH] User ID: ${this.authToken.userId}`),this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log(`✅ [AUTH] Firebase already authenticated for user: ${this.authToken.userId}`),u.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),u.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await Uc(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 Uc(zm(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 Yt.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 Yt.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 Yt.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 Yt.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});return e.data?.data?(this.userProfile=e.data.data,this.userProfile):null}catch(e){throw e.response?.status===401&&(console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),n=t===1?1:t===2?2:0;return xe.isModelAccessible(e,n)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available for profile fetch"),null;try{let e=await Yt.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 Km}from"events";import Vm from"crypto";var at,jn=L(()=>{"use strict";q();at=class i extends Km{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 Vm.randomUUID()}}});import{encode as Wc,decode as Hc,isWithinTokenLimit as Gc,countTokens as Xm}from"gpt-tokenizer/encoding/cl100k_base";var zn,Ym,Qm,ct,qn=L(()=>{"use strict";zn=25e3,Ym=1400,Qm=17e3,ct=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??zn,this.previewTokens=e?.previewTokens??Ym,this.maxContentTokens=e?.maxContentTokens??Qm}count(e){return e?Xm(e):0}encode(e){return e?Wc(e):[]}decode(e){return!e||e.length===0?"":Hc(e)}isWithinLimit(e,t){return e?Gc(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=Gc(e,n);if(s!==!1)return{text:e,tokens:s,truncated:!1};let o=Wc(e).slice(0,n);return{text:Hc(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 Am=Object.defineProperty;var L=(i,e)=>()=>(i&&(e=i(i=0)),e);var Fe=(i,e)=>{for(var t in e)Am(i,t,{get:e[t],enumerable:!0})};var me,Kt=L(()=>{"use strict";me=[{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 wi,u,q=L(()=>{"use strict";wi=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=wi.getInstance()});var It={};Fe(It,{UserDefaults:()=>ye});import Es from"fs";import Ti from"path";import Rm from"os";var xi,ye,He=L(()=>{"use strict";q();xi=class i{static instance;preferencesPath;preferences={};constructor(){let e=Ti.join(Rm.homedir(),".orion");this.preferencesPath=Ti.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadPreferences(){try{if(Es.existsSync(this.preferencesPath)){let e=Es.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=Ti.dirname(this.preferencesPath);Es.existsSync(e)||Es.mkdirSync(e,{recursive:!0}),Es.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)}},ye=xi.getInstance()});var xe,Sn=L(()=>{"use strict";Kt();He();q();xe=class{static getDisplayName(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";case 3:return"Max";default:return"Free"}}static plusOnlyModels=[];static proOnlyModels=["snowx-o4.5","snowx-c6","snowx-5-pro"];static maxOnlyModels=["snowx-o4.6"];static getRequiredTier(e){return this.maxOnlyModels.includes(e)?3:this.proOnlyModels.includes(e)?2:this.plusOnlyModels.includes(e)?1:0}static getCurrentUserTier(){let e=ye.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=3?e:0}static setUserTier(e){ye.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 me.filter(t=>this.isModelAccessible(t.name,e))}static getAccessibleModelsForCurrentUser(){let e=this.getCurrentUserTier();return this.getAccessibleModels(e)}static getAccessDeniedMessage(e){switch(this.getRequiredTier(e)){case 1:return"This model requires a Plus subscription. Please upgrade to access.";case 2:return"This model requires a Pro subscription. Please upgrade to access.";case 3:return"This model requires a Max subscription. Please upgrade to access.";default:return"This model is not available with your current subscription."}}static getModelDisplayNameWithTier(e){return e.displayName}}});import*as Ce from"@sentry/node";var Ci,Ei,Nc=L(()=>{"use strict";q();Ci=class i{static instance;isEnabled=!0;userId=null;userEmail=null;deviceId=null;constructor(){this.isEnabled=process.env.ORION_DISABLE_TELEMETRY!=="true"}static getInstance(){return i.instance||(i.instance=new i),i.instance}setUser(e,t,n){this.userId=e,this.userEmail=t||null,this.isEnabled&&Ce.setUser({id:e,email:t,subscription:n})}setDevice(e){this.deviceId=e,this.isEnabled&&Ce.setTag("device_id",e)}clearUser(){this.userId=null,this.userEmail=null,this.isEnabled&&Ce.setUser(null)}captureException(e,t){if(!this.isEnabled)return u.debug("[SENTRY] Telemetry disabled, skipping error capture"),null;if(e instanceof Error){let n=e.message.toLowerCase();if(n.includes("[done]")||n.includes("stream ended"))return null}return Ce.withScope(n=>{if(t?.tags)for(let[r,o]of Object.entries(t.tags))n.setTag(r,o);t?.sessionId&&n.setTag("session_id",t.sessionId),t?.conversationId&&n.setTag("conversation_id",t.conversationId),t?.toolName&&n.setTag("tool_name",t.toolName),t?.endpoint&&n.setTag("endpoint",t.endpoint),t?.extra&&n.setExtras(t.extra),t?.toolArgs&&n.setExtra("tool_args",t.toolArgs);let s=Ce.captureException(e);return u.debug(`[SENTRY] Captured exception: ${s}`),s})}captureMessage(e,t="info",n){return this.isEnabled?Ce.withScope(s=>{if(n?.tags)for(let[o,a]of Object.entries(n.tags))s.setTag(o,a);n?.extra&&s.setExtras(n.extra);let r=Ce.captureMessage(e,t);return u.debug(`[SENTRY] Captured message: ${r}`),r}):null}addBreadcrumb(e,t,n,s="info"){this.isEnabled&&Ce.addBreadcrumb({message:e,category:t,data:n,level:s,timestamp:Date.now()/1e3})}trackApiCall(e,t,n){this.addBreadcrumb(`${t} ${e}`,"api_call",{endpoint:e,method:t,statusCode:n})}trackToolExecution(e,t,n){this.addBreadcrumb(`Tool: ${e} - ${t?"success":"failed"}`,"tool_execution",{toolName:e,success:t,duration:n},t?"info":"warning")}trackUserAction(e,t){this.addBreadcrumb(e,"user_action",t)}trackNavigation(e,t){this.addBreadcrumb(`${e} -> ${t}`,"navigation",{from:e,to:t})}setTag(e,t){this.isEnabled&&Ce.setTag(e,t)}setExtra(e,t){this.isEnabled&&Ce.setExtra(e,t)}startTransaction(e,t){return this.isEnabled?Ce.startInactiveSpan({name:e,op:t}):null}},Ei=Ci.getInstance()});var As={};Fe(As,{SecureStorageService:()=>Ir,secureStorage:()=>Lm});import Is from"crypto";import Vt from"os";import wn from"fs";import Ii from"path";import{execSync as Om}from"child_process";var _c,ks,$c,Nm,_m,$m,Ps,Fm,Ir,Lm,Ds=L(()=>{"use strict";q();_c="aes-256-gcm",ks=16,$c=16,Nm=32,_m=32,$m=1e5,Ps="__enc__",Fm=["snowx_auth_token","snowx_access_token","snowx_user_data","snowx_device_id","orion_device_id","firebase_custom_token"],Ir=class i{static instance;storagePath;storage={};encryptionKey=null;salt=null;isProduction;constructor(){let e=Ii.join(Vt.homedir(),".orion-cli");this.storagePath=Ii.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(wn.existsSync(this.storagePath)){let e=wn.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=Ii.dirname(this.storagePath);wn.existsSync(e)||wn.mkdirSync(e,{recursive:!0});let t={data:this.storage,salt:this.salt?.toString("base64")};wn.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=Is.randomBytes(Nm));let e=this.generateDeviceSeed();this.encryptionKey=Is.pbkdf2Sync(e,this.salt,$m,_m,"sha256"),u.debug("[SECURE] Encryption initialized")}generateDeviceSeed(){return[Vt.hostname(),Vt.platform(),Vt.arch(),Vt.cpus()[0]?.model||"unknown-cpu",Vt.userInfo().username,this.getMachineId()].join("|")}getMachineId(){try{if(process.platform==="linux"&&wn.existsSync("/etc/machine-id"))return wn.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let t=Om("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID" = "([^"]+)"/);if(t)return t[1]}}catch{}return Vt.hostname()+Vt.userInfo().uid}shouldEncrypt(e){return!this.isProduction&&process.env.ORION_SKIP_ENCRYPTION==="true"?!1:Fm.some(t=>e.includes(t))}encrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");let t=Is.randomBytes(ks),n=Is.createCipheriv(_c,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 Ps+o.toString("base64")}decrypt(e){if(!this.encryptionKey)throw new Error("Encryption not initialized");if(!e.startsWith(Ps))return e;let t=Buffer.from(e.slice(Ps.length),"base64"),n=t.subarray(0,ks),s=t.subarray(ks,ks+$c),r=t.subarray(ks+$c),o=Is.createDecipheriv(_c,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(Ps)?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(Ps)&&(this.storage[t]=this.encrypt(n),e++)}e>0&&(this.saveStorage(),u.debug(`[SECURE] Migrated ${e} values to encrypted storage`))}},Lm=Ir.getInstance()});import Um from"axios";import{EventEmitter as Bm}from"events";var Xt,kt,Ms=L(()=>{"use strict";Xt="firebase_timestamp",kt=class i extends Bm{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=Um.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(()=>(He(),It));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(Te(),Fc));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 ki={};Fe(ki,{DeviceRegistrationService:()=>Pe});import{EventEmitter as Wm}from"events";import{v4 as Lc}from"uuid";import Rs from"os";import Uc from"fs/promises";import Hm from"path";import{execSync as Os}from"child_process";import Gm from"crypto";var Pe,Pt=L(()=>{"use strict";Ms();Te();q();Pe=class i extends Wm{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=kt.getInstance(),this.authService=X.getInstance(),this.configDir=Hm.join(Rs.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=Rs.platform();if(e==="darwin")try{let s=Os("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=Os('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=Rs.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}`),Rs.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=Rs.platform();try{let t=null;switch(e){case"darwin":try{let a=Os("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=Os("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 Uc.readFile("/etc/machine-id","utf-8").then(o=>o.trim()),u.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await Uc.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=Os("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=Gm.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(()=>(He(),It)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${r}`):(r=Lc(),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(()=>(He(),It)),s="snowx_fallback_device_id",r=n.string(s);return r?u.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${r}`):(r=Lc(),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:Xt,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:Xt,lastSeenAt:Xt};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:Xt,lastSeenAt:Xt}],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 Fc={};Fe(Fc,{AuthService:()=>X});import{EventEmitter as jm}from"events";import{signInAnonymously as zm,signInWithEmailAndPassword as qm,createUserWithEmailAndPassword as Km,signOut as Vm,onAuthStateChanged as Bc,updateProfile as Xm,signInWithCustomToken as Ym}from"firebase/auth";import Yt from"axios";import Pi from"fs/promises";import Wc from"path";import Qm from"os";function Hc(i,e,t){return Promise.race([i,new Promise((n,s)=>setTimeout(()=>s(new Error(t)),e))])}var X,Te=L(()=>{"use strict";Sn();q();Nc();X=class i extends jm{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=Wc.join(Qm.homedir(),".orion-cli","auth.json")}static getInstance(){return i.instance||(i.instance=new i),i.instance}async initializeTokenFile(){try{let e=Wc.dirname(this.tokenFilePath);await Pi.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{secureStorage:e}=await Promise.resolve().then(()=>(Ds(),As)),{UserDefaults:t}=await Promise.resolve().then(()=>(He(),It)),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 Pi.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 Pi.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(()=>(Ds(),As));t.setItem("snowx_auth_token",e.userId),t.setItem("snowx_access_token",e.token);let{UserDefaults:n}=await Promise.resolve().then(()=>(He(),It));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";Ei.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(()=>(Ds(),As)),{UserDefaults:t}=await Promise.resolve().then(()=>(He(),It));e.removeItem("snowx_auth_token"),e.removeItem("snowx_access_token"),t.remove("snowx_auth_token"),t.remove("snowx_access_token"),this.authToken=null,Ei.clearUser()}catch(e){console.error("❌ Failed to clear auth token:",e)}}setFirebaseAuth(e){this.auth=e,Bc(e,t=>{this.currentUser=t,this.emit("auth_state_changed",t)})}getFirebaseAuth(){return this.auth}async getCustomTokenFromAPI(e){return this.getCustomTokenFromAPIInternal(e)}async signInWithCustomToken(e){if(!this.auth)throw new Error("Firebase Auth not initialized");let{signInWithCustomToken:t}=await import("firebase/auth");return t(this.auth,e)}async updateUserTierFromToken(e){let t;switch(e.tier){case 1:t=1;break;case 2:t=2;break;case 0:default:t=0;break}xe.setUserTier(t);let{UserDefaults:n}=await Promise.resolve().then(()=>(He(),It));n.set("userSubscriptionTier",e.tier||0),n.set("isTrialUser",!1),u.debug(`User tier updated: ${xe.getDisplayName(t)} (${e.tier})`),u.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let e=await zm(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 qm(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 Km(this.auth,e,t);return this.currentUser=s.user,n&&await Xm(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(()=>(Pt(),ki));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Vm(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(()=>(Pt(),ki));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(He(),It)),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 Yt.post(`${this.snowxAuthEndpoint}/login`,e):t=await Yt.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 Yt.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(()=>(Ds(),As)),t=e.getItem("snowx_access_token");if(t)return t;let{UserDefaults:n}=await Promise.resolve().then(()=>(He(),It));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=Bc(this.auth,async c=>{if(!r)if(r=!0,clearTimeout(o),a(),c)try{let l=await c.getIdToken(!0);s(l)}catch{s(null)}else s(null)});o=setTimeout(()=>{r||(r=!0,a(),s(null))},2e3)});if(n)return n}let e=await this.getAccessTokenFromStorage();return e?(u.debug("Using stored access token as fallback (Firebase SDK not signed in)"),e):null}getUserId(){return this.authToken?.userId||this.currentUser?.uid||null}getUserEmail(){return this.authToken?.email||this.currentUser?.email||null}async getUserTier(){if(this.authToken?.tier!==void 0)return this.authToken.tier;try{return(await this.getUserProfile())?.tier??0}catch{return console.warn("⚠️ Failed to fetch user tier, defaulting to Free tier"),0}}getCachedUserTier(){return this.authToken?.tier??0}isAuthenticated(){return!!this.authToken&&this.authToken.expiresAt>Date.now()}isFirebaseAuthenticated(){if(this.currentUser)return!0;if(this.authToken?.token&&this.isFirebaseIdToken(this.authToken.token)){let e=this.parseFirebaseIdToken(this.authToken.token);if(e&&Date.now()<=e.exp*1e3)return!0}return!1}async autoAuthenticate(){if(await this.initializeTokenFile(),this.isAuthenticated()){let e=this.getUserId(),t=this.authToken?.token;if(e&&t){u.debug("Using existing authentication token"),u.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e);try{if(this.isFirebaseIdToken(t)){let n=this.parseFirebaseIdToken(t);return n&&Date.now()<=n.exp*1e3?(u.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(u.error("Firebase ID Token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}return await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}catch(n){return u.error("Failed to authenticate with Firebase during auto-authenticate:",n.message),n.response?.status===401||n.response?.status===403||n.response?.status===404?(u.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):u.warn("Transient Firebase auth error - keeping stored token for retry"),!1}}}return!1}async authenticateFirebaseWithStoredToken(){if(console.log("🔥 [AUTH] Starting Firebase authentication..."),!this.auth)throw console.error("❌ [AUTH] Firebase Auth not initialized!"),u.error("Firebase Auth not initialized - cannot authenticate"),new Error("Firebase Auth not initialized. Please ensure ServiceManager is initialized first.");if(console.log("✅ [AUTH] Firebase Auth instance is available"),!this.authToken)throw console.error("❌ [AUTH] No auth token available!"),u.error("No auth token available - cannot authenticate with Firebase"),new Error("No authentication token available");if(console.log("✅ [AUTH] Auth token is available"),console.log(`📋 [AUTH] User ID: ${this.authToken.userId}`),this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log(`✅ [AUTH] Firebase already authenticated for user: ${this.authToken.userId}`),u.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),u.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await Hc(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 Hc(Ym(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 Yt.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 Yt.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 Yt.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 Yt.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});return e.data?.data?(this.userProfile=e.data.data,this.userProfile):null}catch(e){throw e.response?.status===401&&(console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),n=t===1?1:t===2?2:0;return xe.isModelAccessible(e,n)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available for profile fetch"),null;try{let e=await Yt.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 Jm}from"events";import Zm from"crypto";var at,zn=L(()=>{"use strict";q();at=class i extends Jm{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 Zm.randomUUID()}}});import{encode as jc,decode as zc,isWithinTokenLimit as qc,countTokens as ep}from"gpt-tokenizer/encoding/cl100k_base";var qn,tp,np,ct,Kn=L(()=>{"use strict";qn=25e3,tp=1400,np=17e3,ct=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??qn,this.previewTokens=e?.previewTokens??tp,this.maxContentTokens=e?.maxContentTokens??np}count(e){return e?ep(e):0}encode(e){return e?jc(e):[]}decode(e){return!e||e.length===0?"":zc(e)}isWithinLimit(e,t){return e?qc(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=qc(e,n);if(s!==!1)return{text:e,tokens:s,truncated:!1};let o=jc(e).slice(0,n);return{text:zc(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
|
|
28
|
-
`)}cleanupOldOperations(){if(this.operations.size<
|
|
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
|
|
27
|
+
... (${a.toLocaleString()} more tokens)`),c}get maxResponse(){return this.maxResponseTokens}get maxContent(){return this.maxContentTokens}get maxPreview(){return this.previewTokens}}});import{EventEmitter as sp}from"events";var Kc,Vc,rp,Xc,op,Ns,Yc,Ai=L(()=>{"use strict";q();Kc=10,Vc=2e3,rp=5e3,Xc=200,op=3e3,Ns=class i extends sp{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,Xc),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||"",Xc);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>Vc?o.streamingContent=c.slice(-Vc):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||"",rp),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<Kc)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-Kc+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}`)},op);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")}},Yc=Ns.getInstance()});var kr,Qc=L(()=>{"use strict";q();kr=class{tools=new Map;register(e){for(let t of e.toolNames)this.tools.set(t,e),u.debug(`[ToolRegistry] Registered tool: ${t}`)}getTool(e){let t=this.tools.get(e);if(t)return t;let n=e.toLowerCase();for(let[s,r]of this.tools.entries())if(s.toLowerCase()===n)return r}async executeTool(e,t,n,s){let r=this.getTool(e);if(!r)return u.error(`[ToolRegistry] Unknown tool: ${e}`),{id:t,toolName:e,success:!1,output:"",error:`Unknown tool: ${e}`};try{u.debug(`[ToolRegistry] Executing tool: ${e} (id: ${t})`);let o=Date.now(),a=await r.execute(t,e,n,s),c=Date.now()-o;u.debug(`[ToolRegistry] Tool ${e} completed in ${c}ms`);let l=a.map(d=>d.text||"").join(`
|
|
29
|
+
`);return{id:t,toolName:e,success:!0,output:l,content:a}}catch(o){return u.error(`[ToolRegistry] Tool execution error (${e}):`,o),{id:t,toolName:e,success:!1,output:"",error:o instanceof Error?o.message:String(o)}}}getAllToolNames(){return Array.from(this.tools.keys())}hasToolRegistered(e){return this.getTool(e)!==void 0}unregister(e){let t=e.toLowerCase(),n=[];for(let s of this.tools.keys())s.toLowerCase()===t&&n.push(s);for(let s of n)this.tools.delete(s);u.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),u.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var Jc={};Fe(Jc,{ToolDisplay:()=>Y});import ue from"chalk";var Y,wt=L(()=>{"use strict";Y=class i{static customUIMode=!1;static enableCustomUI(){i.customUIMode=!0}static disableCustomUI(){i.customUIMode=!1}static start(e,t,n){if(i.customUIMode)return;let s=this.getToolPrefix(e);if(console.log(ue.cyan(`
|
|
30
30
|
${s} ${ue.bold(e)}`)),t&&console.log(ue.gray(` ${t}`)),n){let r=n.length>120?n.substring(0,120)+ue.gray("..."):n;console.log(ue.white(` ${r}`))}}static getToolPrefix(e){let t=e.toLowerCase();return t.includes("bash")||t.includes("command")?"▸":t.includes("write")?"→":t.includes("edit")?"✎":t.includes("read")?"◆":t.includes("search")||t.includes("grep")?"⌕":"•"}static result(e){if(i.customUIMode)return;let{toolName:t,output:n,success:s,executionTime:r,truncateLines:o=50}=e,a=n||"";n&&(t.toLowerCase().includes("edit")?a=this.formatEditOutput(n,o):t.toLowerCase().includes("write")?a=this.formatWriteOutput(n,o):t.toLowerCase().includes("bash")||t.toLowerCase().includes("command")?a=this.formatBashOutput(n,o):a=this.formatGenericOutput(n,o)),a&&a.trim()&&console.log(a);let c=s?ue.green("✓"):ue.red("✗"),l=s?ue.green("SUCCESS"):ue.red("FAILED"),d=r?ue.gray(` (${r}ms)`):"";console.log(`${c} ${l}${d}
|
|
31
31
|
`)}static formatEditOutput(e,t){if(e.includes("- ")&&e.includes("+ ")){let a=e.split(`
|
|
32
32
|
`),l=a.slice(0,20).map(d=>ue.gray(" ")+d).join(`
|
|
@@ -40,19 +40,19 @@ ${s} ${ue.bold(e)}`)),t&&console.log(ue.gray(` ${t}`)),n){let r=n.length>120?n
|
|
|
40
40
|
`);let r=n.slice(0,t).map(o=>ue.gray(" ")+ue.dim(o)).join(`
|
|
41
41
|
`);return r+=`
|
|
42
42
|
`+ue.gray(` ... (${n.length-t} more lines)`),r}static error(e,t){i.customUIMode||(console.log(`
|
|
43
|
-
${ue.red("✗")} ${ue.red.bold(e)} ${ue.red("ERROR")}`),console.log(ue.gray(" ")+ue.white(t)),console.log(""))}}});import
|
|
43
|
+
${ue.red("✗")} ${ue.red.bold(e)} ${ue.red("ERROR")}`),console.log(ue.gray(" ")+ue.white(t)),console.log(""))}}});import Zc from"os";import Di from"path";function Pr(){return process.platform==="win32"}function Tn(i){if(!i)return i;let e=i.trim();return e.startsWith("~")&&(e=e.replace(/^~/,Zc.homedir())),Pr()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,Zc.homedir())),!Pr()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),Pr()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function Vn(i){if(!i||typeof i!="string")return{valid:!1,error:"File path is required"};let e=Tn(i);if(Pr()){let n=Di.basename(e).split(".")[0].toUpperCase();if(ip.includes(n))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${n}`}}return Di.isAbsolute(e)?Di.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
|
|
49
|
-
`),
|
|
48
|
+
Correct: /Users/username/Downloads/file.pdf`}}var ip,Ar=L(()=>{"use strict";ip=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});import el from"path";var ap,cp,Dr,tl=L(()=>{"use strict";q();wt();Ar();Kn();ap=["png","jpg","jpeg","gif","bmp","webp","ico","tiff","tif"],cp={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon",tiff:"image/tiff",tif:"image/tiff"},Dr=class{toolNames=["read","Read"];async execute(e,t,n,s){let r=n.file_path||n.path,o=n.offset,a=n.limit;if(!r)throw new Error("Missing file_path or path argument");let c=Tn(r),l=Vn(c);if(!l.valid)return[{type:"text",text:`Error: ${l.error}`}];u.debug(`[ReadFileTool] Reading file: ${c}${o!==void 0?`, offset: ${o}`:""}${a!==void 0?`, limit: ${a}`:""}`);let d=Date.now();Y.start("Read",n.description,c);try{let g=await import("fs/promises");try{await g.access(c)}catch{return[{type:"text",text:`Error: File does not exist at path: ${c}`}]}let m=await g.stat(c);if(m.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${c}`}];let p=el.extname(c).substring(1).toLowerCase();if(ap.includes(p)){u.debug(`[ReadFileTool] Image file detected: ${c}`);let $=(await g.readFile(c)).toString("base64"),R=cp[p]||"application/octet-stream",_=el.basename(c);u.debug(`[ReadFileTool] Image converted to base64: ${_} (${$.length} chars)`);let N=Date.now()-d;return Y.result({toolName:"Read",filePath:c,output:`Image loaded: ${_}`,success:!0,executionTime:N}),[{type:"image_url",image_url:{url:`data:${R};base64,${$}`}}]}let f=await g.readFile(c,"utf-8"),y=f.length,T=f.split(`
|
|
49
|
+
`),x=T.length,S=Math.max(o??0,0),C=new ct;if(o===void 0&&a===void 0&&C.exceedsResponseLimit(f)){let D=C.count(f),$=m.size/1024,R=$/1024,_=R>=1?`${R.toFixed(2)} MB`:`${$.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
|
|
50
50
|
|
|
51
51
|
File Information:
|
|
52
52
|
- Path: ${c}
|
|
53
53
|
- Size: ${_} (${D.toLocaleString()} tokens)
|
|
54
|
-
- Total Lines: ${
|
|
55
|
-
- Token Limit: ${
|
|
54
|
+
- Total Lines: ${x}
|
|
55
|
+
- Token Limit: ${qn.toLocaleString()}
|
|
56
56
|
|
|
57
57
|
Suggested Solutions:
|
|
58
58
|
1. Read specific lines using offset and limit:
|
|
@@ -66,19 +66,19 @@ Suggested Solutions:
|
|
|
66
66
|
- Lines 2000-4000: Read(path: "${c}", offset: 2000, limit: 2000)
|
|
67
67
|
- And so on...
|
|
68
68
|
|
|
69
|
-
The file has ${
|
|
70
|
-
`),E=
|
|
69
|
+
The file has ${x.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(x===0||f.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(S>=x)return[{type:"text",text:`Error: Offset ${S} is beyond file length. File has ${x} total lines. Try a smaller offset (0 to ${x-1}).`}];let v=a!==void 0?Math.min(S+a,x):x,I=T.slice(S,v),w=I.map((D,$)=>`${(S+$+1).toString().padStart(6," ")} ${D}`).join(`
|
|
70
|
+
`),E=w;if(o!==void 0||a!==void 0){let D=`
|
|
71
71
|
|
|
72
|
-
[Read ${I.length} lines (${
|
|
72
|
+
[Read ${I.length} lines (${S+1}-${v}) of ${x} total lines]`;E=w+D}let P=Date.now()-d;return Y.result({toolName:"Read",filePath:c,output:E,success:!0,executionTime:P}),[{type:"text",text:E}]}catch(g){u.debug(`[ReadFileTool] Failed to read file: ${g.message}`);let m;g.code==="ENOENT"?m=`Error: File does not exist at path: ${c}`:g.code==="EACCES"?m=`Error: Permission denied. Cannot read file: ${c}`:g.code==="EISDIR"?m=`Error: Path is a directory, not a file: ${c}`:m=`Error reading file: ${g.message}`;let p=Date.now()-d;return Y.result({toolName:"Read",filePath:c,output:m,success:!1,executionTime:p}),[{type:"text",text:m}]}}}});import Mr from"fs/promises";import lp from"form-data";import Mi from"axios";import Ri from"path";var Rr,nl=L(()=>{"use strict";q();wt();Te();Rr=class{toolNames=["read_special_file","read_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm","png","jpg","jpeg","gif","bmp","webp","ico"];imageExtensions=["png","jpg","jpeg","gif","bmp","webp","ico"];imageMimeTypes={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon"};async execute(e,t,n,s){let r=n.path;if(!r)throw new Error("Missing path argument");u.debug(`[ReadSpecialFileTool] Converting file: ${r}`);let o=Date.now();Y.start("ReadSpecialFile",n.description,r);try{try{await Mr.access(r)}catch{return[{type:"text",text:`Error: File does not exist at path: ${r}`}]}let a=Ri.extname(r).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let S=this.supportedExtensions.join(", ");return[{type:"text",text:`Error: Unsupported file type '${a}'. The read_special_file tool only supports Microsoft Office documents (docx, doc, xlsx, xls, pptx, ppt), PDF files (pdf), audio/video files (mp3, mp4, wav), web files (html, htm), and images (png, jpg, jpeg, gif, bmp, webp, ico). For plain text files, use the run_command tool with 'cat' instead.
|
|
73
73
|
|
|
74
|
-
Supported file types: ${
|
|
74
|
+
Supported file types: ${S}`}]}let c=await Mr.stat(r),l=Ri.basename(r);if(u.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${l} (${c.size} bytes)`),this.imageExtensions.includes(a)){u.debug(`[ReadSpecialFileTool] Image file detected: ${r}`);let C=(await Mr.readFile(r)).toString("base64"),v=this.imageMimeTypes[a]||"application/octet-stream";u.debug(`[ReadSpecialFileTool] Image converted to base64: ${l} (${C.length} chars)`);let I=Date.now()-o;return Y.result({toolName:"ReadSpecialFile",filePath:r,output:`Image loaded: ${l}`,success:!0,executionTime:I}),[{type:"image_url",image_url:{url:`data:${v};base64,${C}`}}]}let d=await this.uploadToBatchAPI(r,l);u.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${d}`);let g=await this.pollBatchStatus(d);u.debug("[ReadSpecialFileTool] Conversion completed");let m=g.files[0];if(!m||m.status==="failed"){let S=m?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${S}`}]}let p=await this.fetchFileContent(m.file_id);if(!p.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let h=c.size/1024,f=h/1024,y=f>=1?`${f.toFixed(2)} MB`:`${h.toFixed(2)} KB`,T=`# File: ${l}
|
|
75
75
|
**Type:** ${a.toUpperCase()}
|
|
76
76
|
**Size:** ${y}
|
|
77
77
|
**Conversion:** ✅ Successful
|
|
78
78
|
|
|
79
79
|
---
|
|
80
80
|
|
|
81
|
-
${p.markdown_content}`,
|
|
81
|
+
${p.markdown_content}`,x=Date.now()-o;return Y.result({toolName:"ReadSpecialFile",filePath:r,output:`Successfully converted ${l} (${y})`,success:!0,executionTime:x}),[{type:"text",text:T}]}catch(a){u.debug(`[ReadSpecialFileTool] Failed to convert file: ${a.message}`);let c=`Error converting file: ${a.message}
|
|
82
82
|
|
|
83
83
|
This could be due to:
|
|
84
84
|
• File corruption or invalid format
|
|
@@ -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 Y.result({toolName:"ReadSpecialFile",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}async uploadToBatchAPI(e,t){let n=await Mr.readFile(e),s=
|
|
89
|
+
For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,l=Date.now()-o;return Y.result({toolName:"ReadSpecialFile",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}async uploadToBatchAPI(e,t){let n=await Mr.readFile(e),s=Ri.extname(t).substring(1).toLowerCase(),o=await X.getInstance().getFirebaseIdToken(),a=new lp;a.append("files",n,{filename:t,contentType:this.getMimeType(s)});try{let c={...a.getHeaders()};o&&(c.Authorization=`Bearer ${o}`);let l=await Mi.post(`${this.baseEndpoint}/convert-batch`,a,{headers:c,timeout:3e4});if(l.status!==202)throw new Error(`Upload failed with HTTP ${l.status}`);return l.data.request_id}catch(c){throw c.response?new Error(`Upload failed (HTTP ${c.response.status}): ${JSON.stringify(c.response.data)}`):new Error(`Upload failed: ${c.message}`)}}async pollBatchStatus(e){let n=await X.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);for(let r=1;r<=this.maxPollAttempts;r++)try{let a=(await Mi.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4,headers:s})).data;if(u.debug(`[ReadSpecialFileTool] Poll ${r} - Status: ${a.files[0]?.status}, Progress: ${a.completed}/${a.total_files}`),a.completed+a.failed>=a.total_files)return a;await this.sleep(this.pollInterval)}catch(o){throw o.response?.status===404?new Error("Batch request not found or expired"):new Error(`Status check failed: ${o.message}`)}throw new Error(`Conversion timeout after ${this.maxPollAttempts*this.pollInterval/1e3} seconds`)}async fetchFileContent(e){let n=await X.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);try{let r=await Mi.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4,headers:s});if(r.data.status==="failed")throw new Error(r.data.error||"Unknown conversion error");return r.data}catch(r){throw r.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${r.message}`)}}getMimeType(e){switch(e.toLowerCase()){case"pdf":return"application/pdf";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"doc":return"application/msword";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"xls":return"application/vnd.ms-excel";case"pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case"ppt":return"application/vnd.ms-powerpoint";case"mp3":return"audio/mpeg";case"mp4":return"video/mp4";case"wav":return"audio/wav";case"html":case"htm":return"text/html";default:return"application/octet-stream"}}sleep(e){return new Promise(t=>setTimeout(t,e))}}});var Or,sl=L(()=>{"use strict";q();wt();Ar();Or=class{toolNames=["write","Write","write_file"];async execute(e,t,n,s){let r=n.file_path,o=n.content,a=n.edits;if(!r)throw new Error("Missing file_path argument");let c=Tn(r),l=Vn(c);if(!l.valid)return[{type:"text",text:`Error: ${l.error}`}];let d=Date.now();return Y.start("Write",n.description,c),o!=null?await this.executeSimpleWrite(c,o,d):await this.executeEditsMode(c,a,d)}async executeSimpleWrite(e,t,n){u.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let s=await import("fs/promises"),r=await import("path");try{let g=await s.stat(e);if(g.isDirectory()){let m=`Error: Cannot write to '${e}' - path is a directory, not a file.`,p=Date.now()-n;return Y.result({toolName:"Write",filePath:e,output:m,success:!1,executionTime:p}),[{type:"text",text:m}]}if(g.isFile()){let m=`Error: File already exists at '${e}'. Use the Edit tool to modify existing files, or delete the file first if you want to replace it entirely.`,p=Date.now()-n;return Y.result({toolName:"Write",filePath:e,output:m,success:!1,executionTime:p}),[{type:"text",text:m}]}}catch(g){if(g.code!=="ENOENT")throw g}let o=r.dirname(e);await s.mkdir(o,{recursive:!0}),await s.writeFile(e,t,"utf-8");let a=t.split(`
|
|
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
|
|
|
@@ -94,29 +94,29 @@ For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'ca
|
|
|
94
94
|
`),f="";for(let y=0;y<Math.min(h.length,8);y++)f+=`+ ${h[y]}
|
|
95
95
|
`;return h.length>8&&(f+=`+ ...
|
|
96
96
|
|
|
97
|
-
(${h.length-8} more lines)`),u.debug(`[WriteFileTool] Created new file with ${a.length} characters`),[{type:"text",text:f.trim()}]}else throw new Error("For new files, only one edit with empty search string is allowed");else{u.debug("[WriteFileTool] Reading existing file");try{a=await s.readFile(e,"utf-8"),u.debug(`[WriteFileTool] Read ${a.length} characters from existing file`)}catch(p){throw p.code==="ENOENT"?new Error(`File does not exist at path: ${e}. Use empty search string to create new file.`):new Error(`Failed to read existing file: ${p.message}`)}}let c=0,l=a,d=[];for(let p=0;p<t.length;p++){let h=t[p];if(u.debug(`[WriteFileTool] Applying edit ${p+1}/${t.length}`),h.search==="")if(o){d.push({index:p+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{u.debug("[WriteFileTool] Rewriting entire existing file"),l=h.replace,d.push({index:p+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),c++;continue}let f=l.indexOf(h.search);if(f!==-1)l=l.substring(0,f)+h.replace+l.substring(f+h.search.length),u.debug("[WriteFileTool] Replaced first occurrence"),d.push({index:p+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),c++;else{let y=`Search string not found: '${h.search}'`;return d.push({index:p+1,success:!1,message:y,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${p+1}: '${h.search}'\\n\\nEdit Summary:\\n- Total edits: ${d.length}\\n- Successful: ${d.filter(
|
|
97
|
+
(${h.length-8} more lines)`),u.debug(`[WriteFileTool] Created new file with ${a.length} characters`),[{type:"text",text:f.trim()}]}else throw new Error("For new files, only one edit with empty search string is allowed");else{u.debug("[WriteFileTool] Reading existing file");try{a=await s.readFile(e,"utf-8"),u.debug(`[WriteFileTool] Read ${a.length} characters from existing file`)}catch(p){throw p.code==="ENOENT"?new Error(`File does not exist at path: ${e}. Use empty search string to create new file.`):new Error(`Failed to read existing file: ${p.message}`)}}let c=0,l=a,d=[];for(let p=0;p<t.length;p++){let h=t[p];if(u.debug(`[WriteFileTool] Applying edit ${p+1}/${t.length}`),h.search==="")if(o){d.push({index:p+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{u.debug("[WriteFileTool] Rewriting entire existing file"),l=h.replace,d.push({index:p+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),c++;continue}let f=l.indexOf(h.search);if(f!==-1)l=l.substring(0,f)+h.replace+l.substring(f+h.search.length),u.debug("[WriteFileTool] Replaced first occurrence"),d.push({index:p+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),c++;else{let y=`Search string not found: '${h.search}'`;return d.push({index:p+1,success:!1,message:y,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${p+1}: '${h.search}'\\n\\nEdit Summary:\\n- Total edits: ${d.length}\\n- Successful: ${d.filter(x=>x.success).length}\\n- Failed: ${d.filter(x=>!x.success).length}\\n\\nIndividual Edit Results:\\n`+d.map(x=>`${x.success?"✅":"❌"} Edit ${x.index}: ${x.message}`).join("\\n")}]}}await s.writeFile(e,l,"utf-8"),u.debug(`[WriteFileTool] Successfully wrote ${l.length} characters to file`);let g=l.split(`
|
|
98
98
|
`),m="";for(let p=0;p<Math.min(g.length,8);p++)m+=`+ ${g[p]}
|
|
99
99
|
`;return g.length>8&&(m+=`+ ...
|
|
100
100
|
|
|
101
|
-
(${g.length-8} more lines)`),[{type:"text",text:m.trim()}]}catch(s){return u.debug(`[WriteFileTool] Failed to write file: ${s.message}`),[{type:"text",text:`Error writing file: ${s.message}`}]}}}});var Nr,
|
|
101
|
+
(${g.length-8} more lines)`),[{type:"text",text:m.trim()}]}catch(s){return u.debug(`[WriteFileTool] Failed to write file: ${s.message}`),[{type:"text",text:`Error writing file: ${s.message}`}]}}}});var Nr,rl=L(()=>{"use strict";q();wt();Ar();Nr=class{toolNames=["edit","Edit"];async execute(e,t,n,s){let r=n.file_path,o=n.old_string,a=n.new_string,c=n.replace_all===!0;if(!r)throw new Error("Missing file_path argument");if(o==null)throw new Error("Missing old_string argument");if(a==null)throw new Error("Missing new_string argument");let l=Tn(r),d=Vn(l);if(!d.valid)return[{type:"text",text:`Error: ${d.error}`}];u.debug(`[EditFileTool] Editing file: ${l}`);let g=Date.now();Y.start("Edit",n.description,l);try{let m=await import("fs/promises"),p=await m.readFile(l,"utf-8"),h,f=0;if(c)for(h=p;h.includes(o);)h=h.replace(o,a),f++;else p.includes(o)?(h=p.replace(o,a),f=1):h=p;if(f===0){let C=`No matches found for the specified old_string in file: ${l}`,v=Date.now()-g;return Y.result({toolName:"Edit",filePath:l,output:C,success:!1,executionTime:v}),[{type:"text",text:C}]}await m.writeFile(l,h,"utf-8");let y=`Successfully edited file: Replaced ${f} occurrence(s)`;u.debug(`[EditFileTool] ${y}`);let T=Date.now()-g,x=(await import("chalk")).default,S=`${x.red("- "+o.split(`
|
|
102
102
|
`).slice(0,5).join(`
|
|
103
103
|
- `))}
|
|
104
|
-
${
|
|
104
|
+
${x.green("+ "+a.split(`
|
|
105
105
|
`).slice(0,5).join(`
|
|
106
106
|
+ `))}
|
|
107
107
|
|
|
108
|
-
Replaced ${f} occurrence(s)`;return Y.result({toolName:"Edit",filePath:l,output:
|
|
108
|
+
Replaced ${f} occurrence(s)`;return Y.result({toolName:"Edit",filePath:l,output:S,success:!0,executionTime:T}),[{type:"text",text:y}]}catch(m){u.debug(`[EditFileTool] Failed to edit file: ${m.message}`);let p=`Error editing file: ${m.message}`,h=Date.now()-g;return Y.result({toolName:"Edit",filePath:l,output:p,success:!1,executionTime:h}),[{type:"text",text:p}]}}}});var _r,ol=L(()=>{"use strict";q();_r=class{toolNames=["upload_file"];async execute(e,t,n,s){let r=n.file_path;if(!r)throw new Error("Missing file_path argument");return u.debug(`[UploadFileTool] Upload file not implemented for CLI: ${r}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${r}`}]}}});import Oi from"fs/promises";import up from"path";import dp from"form-data";import gp from"axios";var $r,il=L(()=>{"use strict";q();wt();Te();$r=class{toolNames=["deploy_zip_html","DeployZipHTML"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let r=n.zip_file_path;if(!r)throw new Error("Missing zip_file_path argument");let o=Date.now();Y.start("DeployZipHTML",n.description,r);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let w=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 ${w} seconds.`)}u.debug(`[DeployZipHTML] Deploying HTML project: ${r}`);try{await Oi.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 Oi.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 Oi.readFile(r),g=up.basename(r).replace(/[\r\n\t"']/g,"_");u.debug(`[DeployZipHTML] File: ${g}, Size: ${c.size} bytes`);let p=await X.getInstance().getFirebaseIdToken();if(!p)throw new Error("User must be authenticated to deploy projects");let h=new dp;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 gp.post(f,h,{headers:{...h.getHeaders(),Authorization:`Bearer ${p}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(y.status!==200&&y.status!==201)throw new Error(`Deployment failed with status ${y.status}: ${JSON.stringify(y.data)}`);let T=y.data;u.debug("[DeployZipHTML] Deployed successfully"),u.debug(`[DeployZipHTML] Response: ${JSON.stringify(T,null,2)}`);let x=T.data?.deployUrl||T.deployUrl||T.url||T.deploymentUrl||T.site_url||T.siteUrl||T.website_url,S=T.data?.deployId||T.deployId||T.projectId||T.deploymentId,C=T.data?.siteId||T.siteId;this.deployCount++;let v=`# HTML Project Deployed Successfully!
|
|
109
109
|
|
|
110
|
-
**Deployment URL**: ${
|
|
110
|
+
**Deployment URL**: ${x}
|
|
111
111
|
|
|
112
112
|
**Project**: ${g}
|
|
113
113
|
**Type**: Static HTML
|
|
114
|
-
${
|
|
115
|
-
`:""}${
|
|
114
|
+
${S?`**Deploy ID**: ${S}
|
|
115
|
+
`:""}${C?`**Site ID**: ${C}
|
|
116
116
|
`:""}
|
|
117
117
|
Your site is now live and accessible!
|
|
118
118
|
|
|
119
|
-
${
|
|
119
|
+
${T.message||""}`,I=Date.now()-o;return Y.result({toolName:"DeployZipHTML",filePath:r,output:`Deployed to ${x}`,success:!0,executionTime:I}),[{type:"text",text:v}]}catch(a){u.error(`[DeployZipHTML] Deployment failed: ${a.message}`);let c=`HTML deployment failed
|
|
120
120
|
|
|
121
121
|
${a.message}
|
|
122
122
|
|
|
@@ -127,18 +127,18 @@ Troubleshooting:
|
|
|
127
127
|
4. Check network connectivity
|
|
128
128
|
5. Ensure ZIP file is under 100MB
|
|
129
129
|
|
|
130
|
-
If the issue persists, contact support.`,l=Date.now()-o;return Y.result({toolName:"DeployZipHTML",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});import
|
|
130
|
+
If the issue persists, contact support.`,l=Date.now()-o;return Y.result({toolName:"DeployZipHTML",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});import Ni from"fs/promises";import mp from"path";import pp from"form-data";import hp from"axios";var Fr,al=L(()=>{"use strict";q();wt();Te();Fr=class{toolNames=["deploy_zip_react","DeployZipReact"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let r=n.zip_file_path;if(!r)throw new Error("Missing zip_file_path argument");let o=Date.now();Y.start("DeployZipReact",n.description,r);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let w=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 ${w} seconds.`)}u.debug(`[DeployZipReact] Deploying React project: ${r}`);try{await Ni.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 Ni.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 Ni.readFile(r),g=mp.basename(r).replace(/[\r\n\t"']/g,"_");u.debug(`[DeployZipReact] File: ${g}, Size: ${c.size} bytes`);let p=await X.getInstance().getFirebaseIdToken();if(!p)throw new Error("User must be authenticated to deploy projects");let h=new pp;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 hp.post(f,h,{headers:{...h.getHeaders(),Authorization:`Bearer ${p}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(y.status!==200&&y.status!==201)throw new Error(`Deployment failed with status ${y.status}: ${JSON.stringify(y.data)}`);let T=y.data;u.debug("[DeployZipReact] Deployed successfully"),u.debug(`[DeployZipReact] Response: ${JSON.stringify(T,null,2)}`);let x=T.data?.deployUrl||T.deployUrl||T.url||T.deploymentUrl||T.site_url||T.siteUrl||T.website_url,S=T.data?.deployId||T.deployId||T.projectId||T.deploymentId,C=T.data?.siteId||T.siteId;this.deployCount++;let v=`# React Project Deployed Successfully!
|
|
131
131
|
|
|
132
|
-
**Deployment URL**: ${
|
|
132
|
+
**Deployment URL**: ${x}
|
|
133
133
|
|
|
134
134
|
**Project**: ${g}
|
|
135
135
|
**Type**: React / SPA
|
|
136
|
-
${
|
|
137
|
-
`:""}${
|
|
136
|
+
${S?`**Deploy ID**: ${S}
|
|
137
|
+
`:""}${C?`**Site ID**: ${C}
|
|
138
138
|
`:""}
|
|
139
139
|
Your React app is now live and accessible!
|
|
140
140
|
|
|
141
|
-
${
|
|
141
|
+
${T.message||""}`,I=Date.now()-o;return Y.result({toolName:"DeployZipReact",filePath:r,output:`Deployed to ${x}`,success:!0,executionTime:I}),[{type:"text",text:v}]}catch(a){u.error(`[DeployZipReact] Deployment failed: ${a.message}`);let c=`React deployment failed
|
|
142
142
|
|
|
143
143
|
${a.message}
|
|
144
144
|
|
|
@@ -149,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 Y.result({toolName:"DeployZipReact",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});var
|
|
153
|
-
`,"ruby","perl","php","julia","r ","rscript","scala","groovy","kotlin"];for(let l of n)if(e.includes(l))return lt.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 lt.extended;return(i.match(/\n/g)||[]).length>5?lt.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)?lt.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?lt.fast:lt.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)?lt.extended:i.includes("|")?lt.default:i.length<30?lt.fast:lt.default}var lt,
|
|
154
|
-
`)}function
|
|
152
|
+
If the issue persists, contact support.`,l=Date.now()-o;return Y.result({toolName:"DeployZipReact",filePath:r,output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});var cl=L(()=>{"use strict"});function fp(i){let e=i.toLowerCase();if(!e.includes("|"))return!1;let t=e.split("|"),s=t[t.length-1].trim().split(/\s+/)[0]||"";return new Set(["head","tail","sed","awk","cut","wc","uniq","sort","grep","fgrep","egrep","rg","ag","tee","cat","tr","fold","fmt","nl","pr"]).has(s)}function _s(i){let e=i.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(fp(i))return lt.pipedWithTerminator;if(i.includes("<<")&&(i.includes("EOF")||i.includes("'EOF'")||i.includes('"EOF"')||i.includes("END")||i.includes("SCRIPT")||i.includes("DOC")))return lt.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 lt.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 lt.extended;return(i.match(/\n/g)||[]).length>5?lt.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)?lt.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?lt.fast:lt.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)?lt.extended:i.includes("|")?lt.default:i.length<30?lt.fast:lt.default}var lt,_i=L(()=>{"use strict";cl();lt={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 bp,exec as yp,execSync as vp}from"child_process";import{promisify as Sp}from"util";function Li(){return process.platform}function _t(){return process.platform==="win32"}function xp(){return process.platform==="darwin"}function Xn(i,e="SIGTERM"){if(i)try{if(_t())try{vp(`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 Cp(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(_t()&&(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 ll(){return _t()?"PowerShell or Command Prompt":(xp(),"Terminal")}function $i(i,e,t="max",n){let s=f=>{if(f>=6e4){let T=Math.round(f/6e4);return`${T} minute${T>1?"s":""}`}let y=Math.round(f/1e3);return`${y} second${y>1?"s":""}`},r=()=>{switch(process.platform){case"darwin":return"Terminal.app (or iTerm2)";case"win32":return"PowerShell or Windows Terminal";case"linux":return"your terminal emulator (e.g., GNOME Terminal, Konsole)";default:return"your system terminal"}},o=()=>{switch(process.platform){case"darwin":return'Press Cmd+Space, type "Terminal", and press Enter';case"win32":return'Press Win+X and select "Windows Terminal" or "PowerShell"';case"linux":return"Press Ctrl+Alt+T or open your terminal from the applications menu";default:return"Open your system terminal application"}},a=()=>process.platform==="darwin"?["","🔍 Tip: You can also start the command in Terminal and ask me to monitor it."," I can track running Terminal processes and capture their output using the"," MonitorRunningCli tool - just tell me the Terminal window/tab to monitor."]:null,c=()=>{switch(t){case"max":return`The command exceeded the maximum allowed execution time of ${s(e)}.`;case"initial":return`The command produced no output within the initial ${s(e)} window.`;case"activity":return`The command stopped producing output for ${s(e)} (activity timeout).`;default:return`The command timed out after ${s(e)}.`}},l=r(),d=o(),g=c(),m=a(),p=["","❌ Command Timed Out","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","",g,""];n&&p.push(`Details: ${n}`,"");let h=i.length>100?i.substring(0,97)+"...":i;return p.push(`Command: ${h}`,""),p.push(`💡 For long-running commands, consider using ${l}:`,"",` 1. ${d}`," 2. Run your command there:",` ${h}`," 3. The command will continue running regardless of duration",""),m&&p.push(...m),p.push("","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","This is expected behavior for commands that take a long time to execute.","The Bash tool is designed for quick operations and has built-in timeouts","to prevent hanging indefinitely."),p.join(`
|
|
154
|
+
`)}function Ep(i,e){let t=ll();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
|
|
168
|
+
Alternative: Break down the task into non-privileged commands if possible.`}function Ip(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 kp(i,e){let t=ll();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
|
|
182
|
+
Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive) or environment variables for authentication.`}function Ap(i){for(let e of Pp){let t=e.pattern.exec(i);if(t)return{isCatastrophic:!0,pattern:e,matchedText:t[0]}}return{isCatastrophic:!1}}function Dp(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,17 +195,17 @@ The Bash tool will NEVER execute commands that could destroy your system.
|
|
|
195
195
|
If you believe this is a false positive, please:
|
|
196
196
|
1. Review the command carefully
|
|
197
197
|
2. Run it manually in your terminal if you're certain it's safe
|
|
198
|
-
3. Consider breaking down the operation into safer steps`}function
|
|
199
|
-
[Process terminated by signal: ${R}]`),I=setTimeout(()=>{if(h)return;
|
|
198
|
+
3. Consider breaking down the operation into safer steps`}function ul(i){let e=Ap(i);if(e.isCatastrophic)return Dp(i,e);let t=Cp(i);if(t.isPrivileged)return Ep(i,t.reason||"Privileged command detected");let n=Ip(i);return n.isInteractive?kp(i,n.reason||"Interactive command detected"):null}function dl(i){let e=i.trim();for(let t of Mp)if(t.test(e))return{isDelete:!0,paths:Rp(e),category:Op(e)};return{isDelete:!1,paths:[]}}function Rp(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 Op(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 wp,Tp,$s,Fi,Le,Fs,Pp,Mp,Yn=L(()=>{"use strict";_i();Kn();q();wp=Sp(yp),Tp=8500,$s=new ct({maxResponseTokens:Tp});Fi=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")}},Le=new Fi;Fs=class i{static instance;constructor(){}static getInstance(){return i.instance||(i.instance=new i),i.instance}async executeCommand(e,t,n,s,r="new",o){let a=o||_s(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(_t())await wp(`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=Li(),o,a;_t()?(o="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(o="/bin/bash",a=["-c",e]);let c=bp(o,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!_t()}),l="",d="",g=!1,m="",p="max",h=!1,f=!1,y=Date.now(),T=null,x=null,S=null,C=null,v=null,I=null,w=()=>{T&&(clearTimeout(T),T=null),x&&(clearTimeout(x),x=null),S&&(clearTimeout(S),S=null),C&&(clearTimeout(C),C=null),v&&(clearTimeout(v),v=null),I&&(clearTimeout(I),I=null)},E=$=>{h||(h=!0,w(),n($))},P=async($,R="max")=>{h||(g=!0,m=$,p=R,x&&(clearTimeout(x),x=null),S&&(clearTimeout(S),S=null),c.pid&&await this.killProcessTree(c.pid,"SIGTERM"),this.cleanupStreams(c),C=setTimeout(async()=>{h||(c.pid&&await this.killProcessTree(c.pid,"SIGKILL"),v=setTimeout(()=>{if(h)return;let _=Date.now()-s,N=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,k=$i(e,N,p,m);E({output:l+d+k,exitCode:-9,isSuccess:!1,duration:_,platform:r})},500))},1e3))};T=setTimeout(()=>{P(`Max timeout reached (${t.maxTimeout}ms)`,"max")},t.maxTimeout),t.initialTimeout>0&&(S=setTimeout(()=>{!f&&!h&&P(`No output received within initial timeout (${t.initialTimeout}ms)`,"initial")},t.initialTimeout));let D=()=>{y=Date.now(),t.useActivityTimeout&&(x&&clearTimeout(x),x=setTimeout(()=>{if(!h){let $=Date.now()-y;P(`No output for ${$}ms (activity timeout: ${t.activityTimeout}ms)`,"activity")}},t.activityTimeout))};t.useActivityTimeout&&D(),c.stdout?.on("data",$=>{f=!0,D(),S&&(clearTimeout(S),S=null),l+=$.toString()}),c.stderr?.on("data",$=>{f=!0,D(),S&&(clearTimeout(S),S=null),d+=$.toString()}),c.on("exit",($,R)=>{R&&!g&&(d+=`
|
|
199
|
+
[Process terminated by signal: ${R}]`),I=setTimeout(()=>{if(h)return;w(),this.cleanupStreams(c);let _=Date.now()-s,N=(l+d).trim();if($s.exceedsResponseLimit(N)){let k=$s.truncate(N),M=k.text.split(`
|
|
200
200
|
`);N=k.text+`
|
|
201
201
|
|
|
202
202
|
[Output truncated at `+k.tokens.toLocaleString()+` tokens]
|
|
203
|
-
[Showing first `+M.length+" lines of output]"}if(g){let k=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,M
|
|
203
|
+
[Showing first `+M.length+" lines of output]"}if(g){let k=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,M=$i(e,k,p,m);E({output:N+M,exitCode:-15,isSuccess:!1,duration:_,platform:r})}else E({output:N,exitCode:$||0,isSuccess:($||0)===0,duration:_,platform:r})},100)}),c.on("close",$=>{if(h)return;w();let R=Date.now()-s,_=(l+d).trim();if($s.exceedsResponseLimit(_)){let N=$s.count(_),k=$s.truncate(_),F=k.text.split(`
|
|
204
204
|
`).length;_=k.text+`
|
|
205
205
|
|
|
206
206
|
[Output truncated at `+k.tokens.toLocaleString()+` tokens]
|
|
207
207
|
[Showing first `+F+` lines of output]
|
|
208
|
-
[Total output was `+N.toLocaleString()+" tokens]"}if(g){let N=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,k=Ni(e,N,p,m);E({output:_+k,exitCode:-15,isSuccess:!1,duration:R,platform:r})}else E({output:_,exitCode:$||0,isSuccess:($||0)===0,duration:R,platform:r})}),c.on("error",$=>{if(h)return;S();let R=Date.now()-s;E({output:"Process execution failed: "+$.message,exitCode:-1,isSuccess:!1,duration:R,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`)}};xp=[{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"}];Ip=[/^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 Fi={};et(Fi,{ToolCallingService:()=>Ls});import{EventEmitter as Ap}from"events";import ll from"axios";import{exec as Dp,spawn as ul}from"child_process";import{promisify as Mp}from"util";import Le from"fs/promises";import At from"fs";import Yn from"path";import Rp from"os";var sE,Lr,dl,Op,Ls,Ur=L(()=>{"use strict";Xn();Oi();qn();sE=Mp(Dp),Lr=5,dl=20,Op=new Set(["Bash","execute_command","read_file","write_file","Edit","Grep","Glob"]),Ls=class i extends Ap{static instance;tools=new Map;executionHistory=[];tokenCounter=new ct;shellSessionManager=Fs.getInstance();currentUserId="orion-cli-user";fileStateCache=new Map;static MAX_FILE_STATE_CACHE_SIZE=100;backgroundProcesses=new Map;backgroundProcessCounter=0;static MAX_COMPLETED_PROCESSES=50;toolExecutionQueue=[];activeToolExecutions=0;activeToolIds=new Set;constructor(){super(),this.initializeDefaultTools()}generateToolExecId(){return`tool-${Date.now()}-${Math.random().toString(36).substr(2,6)}`}processToolQueue(){for(;this.activeToolExecutions<Lr&&this.toolExecutionQueue.length>0;){let e=this.toolExecutionQueue.shift();this.activeToolExecutions++,this.activeToolIds.add(e.id);let t=Date.now()-e.queuedAt;t>100&&console.log(`🔄 [ToolQueue] Dequeued ${e.toolName} (waited ${t}ms, active: ${this.activeToolExecutions}/${Lr})`),e.execute().then(n=>{e.resolve(n)}).catch(n=>{e.reject(n)}).finally(()=>{this.activeToolExecutions--,this.activeToolIds.delete(e.id),this.processToolQueue()})}}async queueToolExecution(e,t){if(!Op.has(e))return t();if(this.activeToolExecutions<Lr){let n=this.generateToolExecId();this.activeToolExecutions++,this.activeToolIds.add(n);try{return await t()}finally{this.activeToolExecutions--,this.activeToolIds.delete(n),this.processToolQueue()}}if(this.toolExecutionQueue.length>=dl)throw console.warn(`⚠️ [ToolQueue] Queue full (${dl}), rejecting ${e}`),new Error("Tool execution queue full. Please wait for current operations to complete.");return new Promise((n,s)=>{let r=this.generateToolExecId();console.log(`📥 [ToolQueue] Queueing ${e} (queue: ${this.toolExecutionQueue.length+1}, active: ${this.activeToolExecutions}/${Lr})`),this.toolExecutionQueue.push({id:r,toolName:e,execute:t,resolve:n,reject:s,queuedAt:Date.now()})})}static getInstance(){return i.instance||(i.instance=new i),i.instance}initializeDefaultTools(){this.registerTool({name:"web_search",description:"Search the web for information on a given topic",parameters:{type:"object",properties:{query:{type:"string",description:"The search query"},num_results:{type:"number",description:"Number of results to return (default: 5)",default:5}},required:["query"]},handler:this.webSearch.bind(this),category:"web",enabled:!0}),this.registerTool({name:"read_file",description:"Read the contents of a file. Supports reading specific line ranges with offset and limit.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to read"},offset:{type:"number",description:"The line number to start reading from (1-based). Only provide if the file is too large to read at once."},limit:{type:"number",description:"The number of lines to read. Only provide if the file is too large to read at once."}},required:["file_path"]},handler:this.readFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Read",description:"Read the contents of a file. Supports reading specific line ranges with offset and limit.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to read"},offset:{type:"number",description:"The line number to start reading from (1-based). Only provide if the file is too large to read at once."},limit:{type:"number",description:"The number of lines to read. Only provide if the file is too large to read at once."}},required:["file_path"]},handler:this.readFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"write_file",description:"Write content to a file. This will overwrite the existing file if there is one at the provided path.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to write (must be absolute, not relative)"},content:{type:"string",description:"The content to write to the file"},mode:{type:"string",description:"Write mode: write or append",enum:["write","append"],default:"write"}},required:["file_path","content"]},handler:this.writeFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Write",description:"Write content to a file. This will overwrite the existing file if there is one at the provided path.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to write (must be absolute, not relative)"},content:{type:"string",description:"The content to write to the file"}},required:["file_path","content"]},handler:this.writeFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"list_directory",description:"List the contents of a directory",parameters:{type:"object",properties:{directory_path:{type:"string",description:"Path to the directory to list"},include_hidden:{type:"boolean",description:"Include hidden files and directories",default:!1}},required:["directory_path"]},handler:this.listDirectory.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Bash",description:"Execute shell commands with support for background execution, timeouts, and output truncation",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},description:{type:"string",description:"Human-readable description of what the command does"},timeout:{type:"number",description:"Timeout in milliseconds (default: auto-detected based on command)"},run_in_background:{type:"boolean",description:"Run command in background and return immediately",default:!1},dangerouslyDisableSandbox:{type:"boolean",description:"Set to true to disable sandbox mode and run commands without sandboxing",default:!1},working_directory:{type:"string",description:"Working directory to execute the command in. Defaults to current working directory."}},required:["command"]},handler:this.bashCommand.bind(this),category:"system",enabled:!0}),this.registerTool({name:"execute_command",description:`Execute shell commands with persistent session support and interactive prompt handling. Supports both single-shot and persistent execution modes for multi-step workflows.
|
|
208
|
+
[Total output was `+N.toLocaleString()+" tokens]"}if(g){let N=p==="activity"?t.activityTimeout:p==="initial"?t.initialTimeout:t.maxTimeout,k=$i(e,N,p,m);E({output:_+k,exitCode:-15,isSuccess:!1,duration:R,platform:r})}else E({output:_,exitCode:$||0,isSuccess:($||0)===0,duration:R,platform:r})}),c.on("error",$=>{if(h)return;w();let R=Date.now()-s;E({output:"Process execution failed: "+$.message,exitCode:-1,isSuccess:!1,duration:R,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`)}};Pp=[{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"}];Mp=[/^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 Ui={};Fe(Ui,{ToolCallingService:()=>Ls});import{EventEmitter as Np}from"events";import gl from"axios";import{exec as _p,spawn as ml}from"child_process";import{promisify as $p}from"util";import Ue from"fs/promises";import At from"fs";import Qn from"path";import Fp from"os";var lE,Lr,pl,Lp,Ls,Ur=L(()=>{"use strict";Yn();_i();Kn();lE=$p(_p),Lr=5,pl=20,Lp=new Set(["Bash","execute_command","read_file","write_file","Edit","Grep","Glob"]),Ls=class i extends Np{static instance;tools=new Map;executionHistory=[];tokenCounter=new ct;shellSessionManager=Fs.getInstance();currentUserId="orion-cli-user";fileStateCache=new Map;static MAX_FILE_STATE_CACHE_SIZE=100;backgroundProcesses=new Map;backgroundProcessCounter=0;static MAX_COMPLETED_PROCESSES=50;toolExecutionQueue=[];activeToolExecutions=0;activeToolIds=new Set;constructor(){super(),this.initializeDefaultTools()}generateToolExecId(){return`tool-${Date.now()}-${Math.random().toString(36).substr(2,6)}`}processToolQueue(){for(;this.activeToolExecutions<Lr&&this.toolExecutionQueue.length>0;){let e=this.toolExecutionQueue.shift();this.activeToolExecutions++,this.activeToolIds.add(e.id);let t=Date.now()-e.queuedAt;t>100&&console.log(`🔄 [ToolQueue] Dequeued ${e.toolName} (waited ${t}ms, active: ${this.activeToolExecutions}/${Lr})`),e.execute().then(n=>{e.resolve(n)}).catch(n=>{e.reject(n)}).finally(()=>{this.activeToolExecutions--,this.activeToolIds.delete(e.id),this.processToolQueue()})}}async queueToolExecution(e,t){if(!Lp.has(e))return t();if(this.activeToolExecutions<Lr){let n=this.generateToolExecId();this.activeToolExecutions++,this.activeToolIds.add(n);try{return await t()}finally{this.activeToolExecutions--,this.activeToolIds.delete(n),this.processToolQueue()}}if(this.toolExecutionQueue.length>=pl)throw console.warn(`⚠️ [ToolQueue] Queue full (${pl}), rejecting ${e}`),new Error("Tool execution queue full. Please wait for current operations to complete.");return new Promise((n,s)=>{let r=this.generateToolExecId();console.log(`📥 [ToolQueue] Queueing ${e} (queue: ${this.toolExecutionQueue.length+1}, active: ${this.activeToolExecutions}/${Lr})`),this.toolExecutionQueue.push({id:r,toolName:e,execute:t,resolve:n,reject:s,queuedAt:Date.now()})})}static getInstance(){return i.instance||(i.instance=new i),i.instance}initializeDefaultTools(){this.registerTool({name:"web_search",description:"Search the web for information on a given topic",parameters:{type:"object",properties:{query:{type:"string",description:"The search query"},num_results:{type:"number",description:"Number of results to return (default: 5)",default:5}},required:["query"]},handler:this.webSearch.bind(this),category:"web",enabled:!0}),this.registerTool({name:"read_file",description:"Read the contents of a file. Supports reading specific line ranges with offset and limit.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to read"},offset:{type:"number",description:"The line number to start reading from (1-based). Only provide if the file is too large to read at once."},limit:{type:"number",description:"The number of lines to read. Only provide if the file is too large to read at once."}},required:["file_path"]},handler:this.readFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Read",description:"Read the contents of a file. Supports reading specific line ranges with offset and limit.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to read"},offset:{type:"number",description:"The line number to start reading from (1-based). Only provide if the file is too large to read at once."},limit:{type:"number",description:"The number of lines to read. Only provide if the file is too large to read at once."}},required:["file_path"]},handler:this.readFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"write_file",description:"Write content to a file. This will overwrite the existing file if there is one at the provided path.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to write (must be absolute, not relative)"},content:{type:"string",description:"The content to write to the file"},mode:{type:"string",description:"Write mode: write or append",enum:["write","append"],default:"write"}},required:["file_path","content"]},handler:this.writeFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Write",description:"Write content to a file. This will overwrite the existing file if there is one at the provided path.",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to write (must be absolute, not relative)"},content:{type:"string",description:"The content to write to the file"}},required:["file_path","content"]},handler:this.writeFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"list_directory",description:"List the contents of a directory",parameters:{type:"object",properties:{directory_path:{type:"string",description:"Path to the directory to list"},include_hidden:{type:"boolean",description:"Include hidden files and directories",default:!1}},required:["directory_path"]},handler:this.listDirectory.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Bash",description:"Execute shell commands with support for background execution, timeouts, and output truncation",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},description:{type:"string",description:"Human-readable description of what the command does"},timeout:{type:"number",description:"Timeout in milliseconds (default: auto-detected based on command)"},run_in_background:{type:"boolean",description:"Run command in background and return immediately",default:!1},dangerouslyDisableSandbox:{type:"boolean",description:"Set to true to disable sandbox mode and run commands without sandboxing",default:!1},working_directory:{type:"string",description:"Working directory to execute the command in. Defaults to current working directory."}},required:["command"]},handler:this.bashCommand.bind(this),category:"system",enabled:!0}),this.registerTool({name:"execute_command",description:`Execute shell commands with persistent session support and interactive prompt handling. Supports both single-shot and persistent execution modes for multi-step workflows.
|
|
209
209
|
|
|
210
210
|
🔧 SESSION MODE SELECTION (REQUIRED):
|
|
211
211
|
• Use session: "existing" for workflows that need persistent state:
|
|
@@ -239,23 +239,23 @@ 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(()=>(wt(),
|
|
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(()=>(wt(),Jc));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(()=>(Tt(),xn)),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 gl.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 Ue.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")&&At.existsSync(t)){let o=await
|
|
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")&&At.existsSync(t)){let o=await Ue.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 Ue.writeFile(t,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{file_path:t,bytes_written:n.length,message:"Notebook cell written successfully"}}}}At.existsSync(t)&&s!=="append"&&await this.validateFileNotModified(t);let r=Qn.dirname(t);return await Ue.mkdir(r,{recursive:!0}),s==="append"?await Ue.appendFile(t,n):await Ue.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 Ue.readdir(e.directory_path,{withFileTypes:!0}),n=[];for(let s of t){if(!e.include_hidden&&s.name.startsWith("."))continue;let r=await Ue.stat(Qn.join(e.directory_path,s.name));n.push({name:s.name,type:s.isDirectory()?"directory":"file",size:r.size,modified:r.mtime.toISOString()})}return{success:!0,result:{directory_path:e.directory_path,entries:n,total_count:n.length}}}catch(t){return{success:!1,error:`Failed to list directory: ${t.message}`}}}async executeCommandWithSession(e){try{let t=Fs.parseSessionMode(e.session),n=_s(e.command),s={activityTimeout:e.timeout||n.activityTimeout,maxTimeout:e.timeout||n.maxTimeout,initialTimeout:n.initialTimeout},r=await this.shellSessionManager.executeCommand(e.command,`tool-${Date.now()}`,this.currentUserId,e.session||"new",t,s);return{success:r.isSuccess,result:{command:e.command,stdout:r.output,stderr:"",exit_code:r.exitCode}}}catch(t){return{success:!1,error:`Command execution failed: ${t.message}`,result:{command:e.command,stdout:"",stderr:t.message||"",exit_code:-1}}}}async provideInput(e){return{success:!1,error:'Interactive input is not supported. Only "new" session mode is available, which does not support persistent interactive sessions.',result:{message:"Interactive input not supported",requested_input:e.input}}}async calculate(e){try{let t=e.expression.replace(/[^0-9+\-*/.() ]/g,"");if(t!==e.expression)throw new Error("Invalid characters in expression");let n=new Function("return "+t)();return{success:!0,result:{expression:e.expression,result:n,type:typeof n}}}catch(t){return{success:!1,error:`Calculation failed: ${t.message}`}}}async httpRequest(e){try{let t=await gl({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=ml("/bin/bash",["-c",t],{env:process.env,cwd:o,stdio:["ignore","pipe","pipe"],detached:!0}),g={process:d,command:t,startTime:new Date,stdout:"",stderr:""},m=5*1024*1024;d.stdout.on("data",h=>{let f=h.toString();if(f){let y=this.backgroundProcesses.get(l);if(y&&y.stdout.length<m){let T=m-y.stdout.length;y.stdout+=f.substring(0,T),this.backgroundProcesses.set(l,y)}}}),d.stderr.on("data",h=>{let f=h.toString();if(f){let y=this.backgroundProcesses.get(l);if(y&&y.stderr.length<m){let T=m-y.stderr.length;y.stderr+=f.substring(0,T),this.backgroundProcesses.set(l,y)}}}),d.on("close",h=>{let f=this.backgroundProcesses.get(l);f&&(f.exitCode=h||0,this.backgroundProcesses.set(l,f),this.cleanupCompletedProcesses())}),this.backgroundProcesses.set(l,g);let p=`Command started in background with ID: ${l}
|
|
246
246
|
PID: ${d.pid}
|
|
247
247
|
Command: ${t}
|
|
248
248
|
|
|
249
249
|
Note: The process will continue running in the background.
|
|
250
|
-
Output will be collected automatically.`;return{success:!0,result:{process_id:l,pid:d.pid,message:p}}}let a=n?{activityTimeout:n,maxTimeout:n,initialTimeout:n}:_s(t),c=await this.shellSessionManager.executeCommand(t,`tool-${Date.now()}`,this.currentUserId,"new","new",a);return{success:c.isSuccess,result:{command:t,stdout:c.output,stderr:"",exit_code:c.exitCode}}}catch(t){return{success:!1,error:`Bash command failed: ${t.message}`}}}async editFile(e){try{let{file_path:t,old_string:n,new_string:s,replace_all:r=!1}=e;if(n===s)throw new Error("No changes to make: old_string and new_string are identical");if(t.endsWith(".ipynb")&&At.existsSync(t)){let c=await
|
|
251
|
-
`).filter(E=>E);p>0&&(I=I.slice(p)),m>0&&(I=I.slice(0,m));let
|
|
252
|
-
`)}})}),
|
|
250
|
+
Output will be collected automatically.`;return{success:!0,result:{process_id:l,pid:d.pid,message:p}}}let a=n?{activityTimeout:n,maxTimeout:n,initialTimeout:n}:_s(t),c=await this.shellSessionManager.executeCommand(t,`tool-${Date.now()}`,this.currentUserId,"new","new",a);return{success:c.isSuccess,result:{command:t,stdout:c.output,stderr:"",exit_code:c.exitCode}}}catch(t){return{success:!1,error:`Bash command failed: ${t.message}`}}}async editFile(e){try{let{file_path:t,old_string:n,new_string:s,replace_all:r=!1}=e;if(n===s)throw new Error("No changes to make: old_string and new_string are identical");if(t.endsWith(".ipynb")&&At.existsSync(t)){let c=await Ue.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 Ue.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 Ue.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 Ue.writeFile(t,a,"utf-8"),this.cacheFileState(t,a),{success:!0,result:{file_path:t,replacements:r?o.split(n).length-1:1,message:"File edited successfully"}}}catch(t){return{success:!1,error:`Edit failed: ${t.message}`}}}async grepFiles(e){try{let{pattern:t,path:n=process.cwd(),glob:s,type:r,output_mode:o="files_with_matches","-i":a=!1,"-n":c=!0,"-A":l,"-B":d,"-C":g,head_limit:m=0,offset:p=0,multiline:h=!1,case_insensitive:f=!1}=e,y=[];return(a||f)&&y.push("-i"),o==="files_with_matches"?y.push("-l"):o==="count"?y.push("-c"):o==="content"&&c&&y.push("-n"),s&&y.push("--glob",s),r&&y.push("--type",r),o==="content"&&(g!==void 0?y.push("-C",String(g)):(l!==void 0&&y.push("-A",String(l)),d!==void 0&&y.push("-B",String(d)))),h&&y.push("-U","--multiline-dotall"),y.push(t,n),new Promise(T=>{let x=ml("rg",y,{stdio:["ignore","pipe","pipe"]}),S="",C="";x.stdout.on("data",v=>{S+=v.toString()}),x.stderr.on("data",v=>{C+=v.toString()}),x.on("close",v=>{if(v!==0&&v!==1){T({success:!1,error:`ripgrep failed: ${C||"Unknown error"}`});return}let I=S.trim().split(`
|
|
251
|
+
`).filter(E=>E);p>0&&(I=I.slice(p)),m>0&&(I=I.slice(0,m));let w=I.length;T({success:!0,result:{pattern:t,num_files:w,files:I,output:I.join(`
|
|
252
|
+
`)}})}),x.on("error",v=>{T({success:!1,error:`Failed to execute ripgrep: ${v.message}. Make sure ripgrep is installed.`})})})}catch(t){return{success:!1,error:`Grep failed: ${t.message}`}}}globRegexCache=new Map;static MAX_GLOB_CACHE_SIZE=50;getGlobRegex(e){let t=this.globRegexCache.get(e);if(t)return t;let n=e;if(n=n.replace(/[.+^${}()|[\]\\]/g,"\\$&"),n=n.replace(/\*\*/g,"<DOUBLESTAR>"),n=n.replace(/\*/g,"[^/]*"),n=n.replace(/<DOUBLESTAR>/g,".*"),n=n.replace(/\?/g,"."),t=new RegExp(`^${n}$`),this.globRegexCache.size>=i.MAX_GLOB_CACHE_SIZE){let s=this.globRegexCache.keys().next().value;s&&this.globRegexCache.delete(s)}return this.globRegexCache.set(e,t),t}async globFiles(e){try{let{pattern:t,path:n=process.cwd()}=e,s=this.getGlobRegex(t),r=[],o=async a=>{try{let c=await Ue.readdir(a,{withFileTypes:!0});for(let l of c){if(l.name.startsWith("."))continue;let d=Qn.join(a,l.name),g=Qn.relative(n,d);l.isDirectory()?await o(d):(s.test(g)||s.test(l.name))&&r.push(d)}}catch{}};return await o(n),{success:!0,result:{pattern:t,num_files:r.length,files:r}}}catch(t){return{success:!1,error:`Glob failed: ${t.message}`}}}async editNotebook(e){try{let{notebook_path:t,cell_id:n,new_source:s,cell_type:r="code",edit_mode:o="replace"}=e;if(!At.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 Ue.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 Ue.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=At.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(At.existsSync(e)){let s=await Ue.readFile(e,"utf-8");this.cacheFileState(e,s)}return}if(At.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=Fp.tmpdir(),s=Qn.join(n,"orion_tool_responses");At.existsSync(s)||At.mkdirSync(s,{recursive:!0});let r=Math.floor(Date.now()/1e3),o=Math.random().toString(36).substring(2,10),a=`${t}_${r}_${o}.txt`,c=Qn.join(s,a);return At.writeFileSync(c,e,"utf8"),c}catch{return null}}stopAllRunningTools(){}}});import{spawn as Up}from"child_process";var Br,hl=L(()=>{"use strict";q();Yn();Br=class{toolNames=["bash","Bash","run_command"];async execute(e,t,n,s){let r=n.command;if(r==null)throw new Error("Missing command argument");if(typeof r!="string")throw new Error(`Command must be a string. Received: ${typeof r}`);if(r.trim().length===0)throw new Error("Command cannot be empty");let o=n.session;if(o==null)o="new";else{if(typeof o!="string")throw new Error(`Session must be a string. Received: ${typeof o}`);o=o.toLowerCase()}if(o!=="new"&&o!=="existing")throw new Error(`Invalid session mode '${o}' - must be 'new' or 'existing'`);let a;if(n.timeout!==void 0&&n.timeout!==null){if(typeof n.timeout=="string"){let T=Number(n.timeout);if(Number.isNaN(T))throw new Error(`Timeout must be a valid number. Received string: "${n.timeout}"`);a=T}else if(typeof n.timeout=="number"){if(Number.isNaN(n.timeout))throw new Error("Timeout cannot be NaN");if(!Number.isFinite(n.timeout))throw new Error(`Timeout must be finite. Received: ${n.timeout}`);a=n.timeout}else throw new Error(`Timeout must be a number. Received: ${typeof n.timeout}`);if(a<=0)throw new Error(`Timeout must be positive. Received: ${a}ms`);if(a>6e5)throw new Error(`Timeout cannot exceed 600000ms (10 minutes). Received: ${a}ms`);a=Math.floor(a)}let c=n.description;c!=null&&typeof c!="string"&&u.debug(`[RunCommandTool] Invalid description type: ${typeof c}, ignoring`);let l=!1;if(n.run_in_background!==void 0&&n.run_in_background!==null)if(typeof n.run_in_background=="boolean")l=n.run_in_background;else if(typeof n.run_in_background=="string")l=n.run_in_background.toLowerCase()==="true";else throw new Error(`run_in_background must be a boolean. Received: ${typeof n.run_in_background}`);let d=ul(r);if(d)return u.debug("[RunCommandTool] Command blocked by security check"),[{type:"text",text:d}];let g=dl(r);if(g.isDelete){u.debug("[RunCommandTool] Delete command detected, requesting confirmation"),u.debug(`[RunCommandTool] Affected targets: ${g.paths.join(", ")}`);let{FrontendWebSocketService:T}=await Promise.resolve().then(()=>(Jn(),Bi)),x=T.getInstance(),S;if(x.hasElectronFrontend())S=await x.requestDeleteConfirmation(r,c);else{let{PersonalAgentService:C}=await Promise.resolve().then(()=>(Tt(),xn)),v=C.getInstance();S=await this.requestCliConfirmation(v,r,g.paths,c)}if(S==="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
|
|
256
256
|
• Backup first: cp -r [path] [path].backup, then ask again
|
|
257
257
|
• Skip and continue: If not critical, move on to other tasks
|
|
258
|
-
• Ask user: Briefly confirm if they want to keep or remove it`}];if(
|
|
258
|
+
• Ask user: Briefly confirm if they want to keep or remove it`}];if(S==="timeout")return u.debug("[RunCommandTool] Delete confirmation timed out"),[{type:"text",text:`No response (30s timeout). Command NOT executed: ${r}
|
|
259
259
|
|
|
260
260
|
User is likely busy or away. DON'T wait - choose an alternative:
|
|
261
261
|
|
|
@@ -268,36 +268,36 @@ IF CRITICAL (user explicitly asked to delete):
|
|
|
268
268
|
• Create backup first: cp -r [path] [path].backup
|
|
269
269
|
• Then mention you'll need confirmation to delete later
|
|
270
270
|
|
|
271
|
-
DO NOT keep retrying the same delete command.`}];if(
|
|
271
|
+
DO NOT keep retrying the same delete command.`}];if(S==="error")return u.debug("[RunCommandTool] Delete confirmation failed"),[{type:"text",text:`Failed to show delete confirmation dialog. The command was NOT executed for safety.
|
|
272
272
|
|
|
273
|
-
Please try again or ask the user to confirm the deletion manually.`}];u.debug("[RunCommandTool] User confirmed delete command, proceeding")}let m=a||12e4,p
|
|
273
|
+
Please try again or ask the user to confirm the deletion manually.`}];u.debug("[RunCommandTool] User confirmed delete command, proceeding")}let m=a||12e4,p=Li();u.debug(`[RunCommandTool] Executing command on platform: ${p}`),u.debug(`[RunCommandTool] Command: ${r.substring(0,50)}${r.length>50?"...":""}`),c&&u.debug(`[RunCommandTool] Description: ${c}`),u.debug(`[RunCommandTool] Session: ${o}, Timeout: ${m}ms, Background: ${l}`);let h=this.detectMkdirCommand(r);if(h.isMkdir&&h.path){let T=await import("fs/promises");try{if((await T.stat(h.path)).isDirectory())return[{type:"text",text:`Error: Directory already exists at '${h.path}'.
|
|
274
274
|
|
|
275
275
|
The mkdir command was not executed because the directory already exists.
|
|
276
|
-
If you need to ensure the directory exists, this is already satisfied.`}]}catch{}}let f=this.detectTouchCommand(r);if(f.isTouch&&f.path){let
|
|
276
|
+
If you need to ensure the directory exists, this is already satisfied.`}]}catch{}}let f=this.detectTouchCommand(r);if(f.isTouch&&f.path){let T=await import("fs/promises");try{let x=await T.stat(f.path);if(x.isFile())return[{type:"text",text:`Error: File already exists at '${f.path}'.
|
|
277
277
|
|
|
278
278
|
The touch command was not executed because the file already exists.
|
|
279
|
-
If you need to update the timestamp, use: touch -c "${f.path}"`}];if(
|
|
279
|
+
If you need to update the timestamp, use: touch -c "${f.path}"`}];if(x.isDirectory())return[{type:"text",text:`Error: A directory exists at '${f.path}'.
|
|
280
280
|
|
|
281
|
-
Cannot create a file where a directory already exists.`}]}catch{}}let y=this.detectFileOverwriteCommand(r);if(y.isOverwrite&&y.targetPath){let
|
|
281
|
+
Cannot create a file where a directory already exists.`}]}catch{}}let y=this.detectFileOverwriteCommand(r);if(y.isOverwrite&&y.targetPath){let T=await import("fs/promises");try{if((await T.stat(y.targetPath)).isFile())return[{type:"text",text:`Error: File already exists at '${y.targetPath}'.
|
|
282
282
|
|
|
283
283
|
The command would overwrite an existing file. For safety, this was blocked.
|
|
284
284
|
|
|
285
285
|
Options:
|
|
286
286
|
• Backup first: cp "${y.targetPath}" "${y.targetPath}.bak"
|
|
287
287
|
• Delete first: rm "${y.targetPath}" (requires confirmation)
|
|
288
|
-
• Use different name: Change the target filename`}]}catch{}}if(l)return this.executeBackground(e,r,m,s);try{let
|
|
289
|
-
`,
|
|
288
|
+
• Use different name: Change the target filename`}]}catch{}}if(l)return this.executeBackground(e,r,m,s);try{let T=(await Promise.resolve().then(()=>(Ur(),Ui))).ToolCallingService.getInstance(),x={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:r,session:o,timeout:m})}},S=await T.executeTool(x),C="";if(S.success){let v=(S.result?.stdout||"").trim(),I=S.result?.exitCode??0;if(C=`Command: ${r}
|
|
289
|
+
`,C+=`Exit Code: ${I}
|
|
290
290
|
|
|
291
|
-
`,v.length>0){let
|
|
292
|
-
`),E=
|
|
293
|
-
`),
|
|
291
|
+
`,v.length>0){let w=v.split(`
|
|
292
|
+
`),E=w.slice(0,15);C+=E.join(`
|
|
293
|
+
`),w.length>15&&(C+=`
|
|
294
294
|
|
|
295
|
-
... (showing first 15 of ${
|
|
296
|
-
`,
|
|
295
|
+
... (showing first 15 of ${w.length} lines)`)}else C+="(no output)";return[{type:"text",text:C}]}else{let v=S.error||"Unknown error",I=S.result?.exitCode??1;return C=`Command: ${r}
|
|
296
|
+
`,C+=`Exit Code: ${I}
|
|
297
297
|
|
|
298
|
-
`,
|
|
299
|
-
${v}`,[{type:"text",text:
|
|
300
|
-
Error: ${
|
|
298
|
+
`,C+=`Error:
|
|
299
|
+
${v}`,[{type:"text",text:C}]}}catch(T){return u.debug(`[RunCommandTool] Failed to execute bash command: ${T.message}`),[{type:"text",text:`Command: ${r}
|
|
300
|
+
Error: ${T.message}`}]}}async requestCliConfirmation(e,t,n,s){let r=`delete-cli-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,o=3e4;return u.debug(`[RunCommandTool] Requesting CLI confirmation: ${r}`),new Promise(a=>{let c=setTimeout(()=>{u.debug(`[RunCommandTool] CLI confirmation timed out: ${r}`),e.off("confirmation_response",l),a("timeout")},o),l=d=>{d.confirmationId===r&&(clearTimeout(c),e.off("confirmation_response",l),d.timedOut?a("timeout"):d.confirmed?a("confirmed"):a("declined"))};e.on("confirmation_response",l),e.emit("confirmation_request",{confirmationId:r,type:"confirmation",title:"Confirm Delete",message:"The AI wants to delete files. Continue?",command:t,targets:n,isDestructive:!0,timeout:o}),u.debug(`[RunCommandTool] CLI confirmation request emitted: ${r}`)})}async executeBackground(e,t,n,s){let r=`shell_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,o=s.workingDirectory||process.cwd();u.debug(`[RunCommandTool] Starting background process: ${r}`);let a,c;_t()?(a="powershell.exe",c=["-ExecutionPolicy","Bypass","-Command",t]):(a="/bin/bash",c=["-c",t]);let l=Up(a,c,{cwd:o,env:process.env,stdio:["ignore","pipe","pipe"],detached:!_t()});l.unref();let d={id:r,command:t,startTime:new Date,status:"running",output:[],error:[],pid:l.pid};Le.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}`),Le.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),Le.updateProcess(r,{endTime:new Date,status:"failed"})}),n&&setTimeout(()=>{let h=Le.getProcess(r);h&&h.status==="running"&&(u.debug(`[RunCommandTool] Background process ${r} timed out, killing...`),Xn(l.pid,"SIGTERM"),setTimeout(()=>{let f=Le.getProcess(r);f&&f.status==="running"&&Xn(l.pid,"SIGKILL")},3e3),Le.updateProcess(r,{status:"killed",endTime:new Date}),d.error.push(`Process timed out after ${n}ms`))},n),[{type:"text",text:`Background process started with ID: ${r}
|
|
301
301
|
PID: ${l.pid}
|
|
302
302
|
Use BashOutput tool to get output.`}]}ensureMeaningfulOutput(e,t,n){let s=(e||"").trim();return s.length===0?n?`✅ Command '${t}' executed successfully.
|
|
303
303
|
|
|
@@ -316,7 +316,7 @@ If you expected output, the command may need different parameters or the operati
|
|
|
316
316
|
Consider:
|
|
317
317
|
• Checking the command syntax and parameters
|
|
318
318
|
• Verifying file permissions and paths
|
|
319
|
-
• Running the command with verbose flags for more details`:s}detectMkdirCommand(e){let t=e.trim(),n=t.match(/^mkdir\s+(?:-[pvm]+\s+)*["']?([^"'\s]+)["']?/i);if(n)return{isMkdir:!0,path:n[1]};let s=t.match(/^mkdir\s+(?:--\w+\s+)*["']?([^"'\s]+)["']?/i);return s?{isMkdir:!0,path:s[1]}:{isMkdir:!1}}detectTouchCommand(e){let n=e.trim().match(/^touch\s+(?:-[acm]+\s+)*["']?([^"'\s]+)["']?/i);return n?{isTouch:!0,path:n[1]}:{isTouch:!1}}detectFileOverwriteCommand(e){let t=e.trim(),n=t.match(/>\s*["']?([^"'\s>|&]+)["']?$/);if(n&&!t.includes(">>"))return{isOverwrite:!0,targetPath:n[1]};let s=t.match(/^cp\s+(?:-[frp]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(s)return{isOverwrite:!0,targetPath:s[1]};let r=t.match(/^mv\s+(?:-[fn]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(r)return{isOverwrite:!0,targetPath:r[1]};let o=t.match(/wget\s+.*-O\s*["']?([^"'\s]+)["']?/i);if(o)return{isOverwrite:!0,targetPath:o[1]};let a=t.match(/curl\s+.*-o\s*["']?([^"'\s]+)["']?/i);if(a)return{isOverwrite:!0,targetPath:a[1]};let c=t.match(/dd\s+.*of=["']?([^"'\s]+)["']?/i);if(c)return{isOverwrite:!0,targetPath:c[1]};let l=t.match(/scp\s+[^:]+:[^"'\s]+\s+["']?([^"'\s]+)["']?$/i);if(l)return{isOverwrite:!0,targetPath:l[1]};let d=t.match(/rsync\s+.*\s+["']?([^"'\s]+)["']?$/i);if(d&&!d[1].includes(":"))return{isOverwrite:!0,targetPath:d[1]};let g=t.match(/install\s+(?:-[Dmpv]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(g)return{isOverwrite:!0,targetPath:g[1]};let m=t.match(/\|\s*tee\s+(?!-a)["']?([^"'\s]+)["']?/i);return m?{isOverwrite:!0,targetPath:m[1]}:{isOverwrite:!1}}}});var Wr,
|
|
319
|
+
• Running the command with verbose flags for more details`:s}detectMkdirCommand(e){let t=e.trim(),n=t.match(/^mkdir\s+(?:-[pvm]+\s+)*["']?([^"'\s]+)["']?/i);if(n)return{isMkdir:!0,path:n[1]};let s=t.match(/^mkdir\s+(?:--\w+\s+)*["']?([^"'\s]+)["']?/i);return s?{isMkdir:!0,path:s[1]}:{isMkdir:!1}}detectTouchCommand(e){let n=e.trim().match(/^touch\s+(?:-[acm]+\s+)*["']?([^"'\s]+)["']?/i);return n?{isTouch:!0,path:n[1]}:{isTouch:!1}}detectFileOverwriteCommand(e){let t=e.trim(),n=t.match(/>\s*["']?([^"'\s>|&]+)["']?$/);if(n&&!t.includes(">>"))return{isOverwrite:!0,targetPath:n[1]};let s=t.match(/^cp\s+(?:-[frp]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(s)return{isOverwrite:!0,targetPath:s[1]};let r=t.match(/^mv\s+(?:-[fn]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(r)return{isOverwrite:!0,targetPath:r[1]};let o=t.match(/wget\s+.*-O\s*["']?([^"'\s]+)["']?/i);if(o)return{isOverwrite:!0,targetPath:o[1]};let a=t.match(/curl\s+.*-o\s*["']?([^"'\s]+)["']?/i);if(a)return{isOverwrite:!0,targetPath:a[1]};let c=t.match(/dd\s+.*of=["']?([^"'\s]+)["']?/i);if(c)return{isOverwrite:!0,targetPath:c[1]};let l=t.match(/scp\s+[^:]+:[^"'\s]+\s+["']?([^"'\s]+)["']?$/i);if(l)return{isOverwrite:!0,targetPath:l[1]};let d=t.match(/rsync\s+.*\s+["']?([^"'\s]+)["']?$/i);if(d&&!d[1].includes(":"))return{isOverwrite:!0,targetPath:d[1]};let g=t.match(/install\s+(?:-[Dmpv]+\s+)*["']?[^"'\s]+["']?\s+["']?([^"'\s]+)["']?$/i);if(g)return{isOverwrite:!0,targetPath:g[1]};let m=t.match(/\|\s*tee\s+(?!-a)["']?([^"'\s]+)["']?/i);return m?{isOverwrite:!0,targetPath:m[1]}:{isOverwrite:!1}}}});var Wr,fl=L(()=>{"use strict";q();Yn();Wr=class{toolNames=["bash_output","BashOutput","TaskOutput"];async execute(e,t,n,s){try{let r=n.bash_id||n.shell_id||n.task_id;if(!r)throw new Error("bash_id is required");if(typeof r!="string")throw new Error(`bash_id must be a string. Received: ${typeof r}`);u.debug(`[BashOutputTool] Retrieving output for process: ${r}`);let o=Le.getProcess(r);if(!o)throw new Error(`Background process not found: ${r}`);let a=[...o.output,...o.error].join(""),c=o.status==="running",l=`Process ID: ${r}
|
|
320
320
|
`;if(l+=`Status: ${o.status}
|
|
321
321
|
`,l+=`PID: ${o.pid||"N/A"}
|
|
322
322
|
`,l+=`Command: ${o.command}
|
|
@@ -328,7 +328,7 @@ Consider:
|
|
|
328
328
|
--- Output ---
|
|
329
329
|
`,a?l+=a:c?l+="(no output yet - process still running)":o.exitCode===0?l+=`Process completed successfully with no output.
|
|
330
330
|
|
|
331
|
-
Note: Many commands run silently when successful (e.g., file operations, installations). The exit code 0 confirms success.`:l+="(no output)",[{type:"text",text:l}]}catch(r){return u.debug(`[BashOutputTool] Error: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});var Hr,
|
|
331
|
+
Note: Many commands run silently when successful (e.g., file operations, installations). The exit code 0 confirms success.`:l+="(no output)",[{type:"text",text:l}]}catch(r){return u.debug(`[BashOutputTool] Error: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});var Hr,bl=L(()=>{"use strict";q();Yn();Hr=class{toolNames=["kill_shell","KillShell"];async execute(e,t,n,s){try{let r=n.shell_id||n.bash_id||n.task_id;if(!r)throw new Error("shell_id is required");if(typeof r!="string")throw new Error(`shell_id must be a string. Received: ${typeof r}`);u.debug(`[KillShellTool] Killing process: ${r}`);let o=Le.getProcess(r);if(!o)throw new Error(`Background process not found: ${r}`);if(o.status!=="running")throw new Error(`Process is not running (status: ${o.status})`);if(o.pid){Xn(o.pid,"SIGTERM");let a=o.pid;setTimeout(()=>{let d=Le.getProcess(r);d&&d.status==="running"&&Xn(a,"SIGKILL")},3e3).unref(),Le.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 Wi,Bp,Gr,yl=L(()=>{"use strict";q();Yn();Wi=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=Le.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=Le.getProcess(e);if(!n){this.stopMonitoring(e);return}n.status!=="running"&&(u.debug(`[ProcessMonitoringService] Process ${e} completed with status: ${n.status}`),t.onComplete&&t.onComplete(n),this.stopMonitoring(e),this.emitAutoPrompt(e,n,t.reason))}async emitAutoPrompt(e,t,n){try{let{FrontendWebSocketService:s}=await Promise.resolve().then(()=>(Jn(),Bi)),r=s.getInstance();if(!r.isConnected()){u.debug("[ProcessMonitoringService] WebSocket not connected, cannot auto-prompt");return}let o,a=t.output.join(`
|
|
332
332
|
`).substring(0,1e3),c=t.error.join(`
|
|
333
333
|
`).substring(0,500);t.status==="completed"?o=`Background process completed successfully (ID: ${e}, Exit: ${t.exitCode}).
|
|
334
334
|
|
|
@@ -350,21 +350,21 @@ Reason for monitoring: ${n}
|
|
|
350
350
|
|
|
351
351
|
The process was terminated. Please check if this was intentional or if there was a timeout.`:o=`Background process ended with status: ${t.status} (ID: ${e}).
|
|
352
352
|
|
|
353
|
-
Reason for monitoring: ${n}`,r.emit("auto_prompt",{type:"process_completed",shellId:e,status:t.status,exitCode:t.exitCode,reason:n,message:o,timestamp:new Date().toISOString()}),u.debug(`[ProcessMonitoringService] Emitted auto-prompt for: ${e}`)}catch(s){u.debug(`[ProcessMonitoringService] Failed to emit auto-prompt: ${s}`)}}getMonitoredCount(){return this.monitoredProcesses.size}getMonitoredIds(){return Array.from(this.monitoredProcesses.keys())}clear(){for(let[e,t]of this.monitoredProcesses)clearInterval(t.intervalId);this.monitoredProcesses.clear(),u.debug("[ProcessMonitoringService] Cleared all monitors")}},
|
|
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")}},Bp=Wi.getInstance(),Gr=class{toolNames=["monitor_running_cli","MonitorRunningCli"];async execute(e,t,n,s){let r=n.shell_id,o=n.reason;if(!r||typeof r!="string"||r.trim().length===0)return[{type:"text",text:"Error: shell_id is required and must be a non-empty string"}];if(!o||typeof o!="string"||o.trim().length===0)return[{type:"text",text:"Error: reason is required and must be a non-empty string"}];if(o.length>500)return[{type:"text",text:`Error: reason is too long (${o.length} characters). Maximum 500 characters allowed.`}];u.debug(`[MonitorRunningCliTool] Starting monitoring for ${r}`),u.debug(`[MonitorRunningCliTool] Reason: ${o}`);let a=Bp.startMonitoring(r,o);return a.success?(u.debug("[MonitorRunningCliTool] Monitoring started successfully"),[{type:"text",text:`Started monitoring background process ${r}.
|
|
354
354
|
|
|
355
355
|
Reason: ${o}
|
|
356
356
|
|
|
357
357
|
You will be auto-prompted when the process completes. You can continue with other tasks in the meantime.
|
|
358
358
|
|
|
359
|
-
To check status manually, use BashOutput tool with shell_id: ${r}`}]):(u.debug(`[MonitorRunningCliTool] Failed to start monitoring: ${a.error}`),[{type:"text",text:`Failed to start monitoring: ${a.error}`}])}}});var jr,
|
|
359
|
+
To check status manually, use BashOutput tool with shell_id: ${r}`}]):(u.debug(`[MonitorRunningCliTool] Failed to start monitoring: ${a.error}`),[{type:"text",text:`Failed to start monitoring: ${a.error}`}])}}});var jr,vl=L(()=>{"use strict";q();jr=class{toolNames=["grep","Grep"];async execute(e,t,n,s){let r=n.pattern,o=n.output_mode||"files_with_matches",a=n.path||process.cwd(),c=n.glob,l=n.type,d=n["-i"]===!0,g=n["-n"]===!0,m=n["-A"],p=n["-B"],h=n["-C"],f=n.multiline===!0,y=n.head_limit;if(!r)throw new Error("Missing pattern argument");if(r.trim().length===0)throw new Error("Pattern cannot be empty");u.debug(`[GrepTool] Grep search: pattern="${r}", path="${a}", output_mode="${o}"`);try{let{exec:T}=await import("child_process"),{promisify:x}=await import("util"),S=x(T),C="rg",v=!0;try{await S("which rg",{timeout:5e3})}catch{u.debug("[GrepTool] ripgrep not found, falling back to grep"),C="grep -r",v=!1}if(v){switch(d&&(C+=" -i"),g&&(C+=" -n"),o){case"files_with_matches":C+=" -l";break;case"count":C+=" -c";break;case"content":default:break}h!==void 0?C+=` -C ${h}`:(m!==void 0&&(C+=` -A ${m}`),p!==void 0&&(C+=` -B ${p}`)),f&&(C+=" -U --multiline-dotall"),C+=` "${r.replace(/"/g,'\\"')}"`,c&&(C+=` --glob="${c}"`),l&&(C+=` --type=${l}`),C+=` "${a}"`}else{switch(d&&(C+=" -i"),g&&(C+=" -n"),o){case"files_with_matches":C+=" -l";break;case"count":C+=" -c";break}h!==void 0?C+=` -C ${h}`:(m!==void 0&&(C+=` -A ${m}`),p!==void 0&&(C+=` -B ${p}`)),C+=` "${r.replace(/"/g,'\\"')}"`,c&&(C+=` --include="${c}"`),C+=` "${a}"`}y!==void 0&&y>0&&(C+=` | head -n ${y}`),u.debug(`[GrepTool] Executing: ${C}`);let{stdout:I,stderr:w}=await S(C,{maxBuffer:10*1024*1024,timeout:3e4});if(!I&&!w)return[{type:"text",text:"No matches found"}];let E=I||w;if(o==="content"&&E){let D=`
|
|
360
360
|
|
|
361
361
|
[Found ${E.trim().split(`
|
|
362
|
-
`).length} matching line(s)]`;return[{type:"text",text:E+D}]}return[{type:"text",text:E}]}catch(
|
|
362
|
+
`).length} matching line(s)]`;return[{type:"text",text:E+D}]}return[{type:"text",text:E}]}catch(T){return T.code===1?[{type:"text",text:"No matches found"}]:(u.debug(`[GrepTool] Grep failed: ${T.message}`),T.message.includes("No such file or directory")?[{type:"text",text:`Error: Search path does not exist: ${a}`}]:[{type:"text",text:"Grep search completed with no results"}])}}}});var zr,Sl=L(()=>{"use strict";q();zr=class{toolNames=["glob","Glob"];async execute(e,t,n,s){let r=n.pattern,o=n.path||process.cwd();if(!r)throw new Error("Missing pattern argument");u.debug(`[GlobTool] Glob search: pattern="${r}", path="${o}"`);try{let{exec:a}=await import("child_process"),{promisify:c}=await import("util"),l=c(a),d=r.replace(/\*\*/g,"*"),g=process.platform==="win32"?`dir /s /b "${o}\\${d}"`:`find "${o}" -name "${d}" 2>/dev/null`,{stdout:m}=await l(g,{timeout:3e4,maxBuffer:10*1024*1024});if(!m||m.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let p=m.trim().split(`
|
|
363
363
|
`);return[{type:"text",text:`Found ${p.length} file(s):
|
|
364
364
|
${p.join(`
|
|
365
|
-
`)}`}]}catch(a){return u.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var qr,
|
|
365
|
+
`)}`}]}catch(a){return u.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var qr,wl=L(()=>{"use strict";q();qr=class{toolNames=["open_url"];async execute(e,t,n,s){let r=n.url;if(!r)throw new Error("Missing url argument");u.debug(`[OpenUrlTool] Opening URL: ${r}`),s.activeWebViewURLs.includes(r)||(s.activeWebViewURLs.push(r),u.debug(`[OpenUrlTool] Added to active URLs: ${r}`));try{let{exec:o}=await import("child_process"),a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return o(`${a} "${r}"`,c=>{c?u.debug(`[OpenUrlTool] Failed to open URL in browser: ${c.message}`):u.debug(`[OpenUrlTool] URL opened in default browser: ${r}`)}),[{type:"text",text:`✅ URL opened in default browser: ${r}`}]}catch(o){return u.debug(`[OpenUrlTool] Failed to open URL: ${o.message}`),[{type:"text",text:`❌ Failed to open URL: ${o.message}`}]}}}});import{exec as Wp,execSync as LE}from"child_process";import{promisify as Hp}from"util";function Kr(){return process.platform==="win32"}function Tl(){return process.platform==="darwin"}function xl(){return process.platform==="linux"}var BE,Cl=L(()=>{"use strict";BE=Hp(Wp)});var El={};Fe(El,{DeviceKnowledgeService:()=>Vr,deviceKnowledgeService:()=>Se});import*as Ge from"fs";import*as Qt from"path";import*as ve from"os";var Vr,Se,Xr=L(()=>{"use strict";Cl();Vr=class i{static instance;fileName="device-knowledge.md";constructor(){this.ensureDirectoryExists()}static shared(){return i.instance||(i.instance=new i),i.instance}get orionDirectory(){return Qt.join(ve.homedir(),".orion")}getKnowledgeFilePath(){return Qt.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!Ge.existsSync(this.orionDirectory))try{Ge.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),Kr()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{exec(`attrib +h "${this.orionDirectory}"`,e=>{e?console.warn("Failed to hide .orion directory on Windows:",e.message):console.log("Set hidden attribute on .orion directory (Windows)")})}catch(e){console.warn("Error hiding directory on Windows:",e)}}hasDeviceKnowledge(){return Ge.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return Ge.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),Ge.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let n=(this.readDeviceKnowledge()||"")+`
|
|
366
366
|
|
|
367
|
-
`+e;return this.writeDeviceKnowledge(n)}getKnowledgeFileSize(){try{return
|
|
367
|
+
`+e;return this.writeDeviceKnowledge(n)}getKnowledgeFileSize(){try{return Ge.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
|
|
368
368
|
|
|
369
369
|
`;e+=`**File Location**: \`${this.getKnowledgeFilePath()}\`
|
|
370
370
|
|
|
@@ -385,10 +385,10 @@ ${p.join(`
|
|
|
385
385
|
`,e+=`- **Desktop**: ${Qt.join(ve.homedir(),"Desktop")}
|
|
386
386
|
`,e+=`- **Documents**: ${Qt.join(ve.homedir(),"Documents")}
|
|
387
387
|
`,e+=`- **Downloads**: ${Qt.join(ve.homedir(),"Downloads")}
|
|
388
|
-
`,
|
|
388
|
+
`,Tl()?e+=`- **Applications**: /Applications
|
|
389
389
|
`:Kr()?(e+=`- **Program Files**: C:\\Program Files
|
|
390
390
|
`,e+=`- **AppData**: ${Qt.join(ve.homedir(),"AppData")}
|
|
391
|
-
`):
|
|
391
|
+
`):xl()&&(e+=`- **Config**: ${Qt.join(ve.homedir(),".config")}
|
|
392
392
|
`),e+=`
|
|
393
393
|
`,e+=`## URL Handling Rules
|
|
394
394
|
`,e+="- **staging.snowx.ai Redirect URLs**: Any URL in format `staging.snowx.ai/*` is a shortened URL that redirects to the main URL. Resolve the redirect to get the actual destination URL.\n\n",this.writeDeviceKnowledge(e)}updateKnowledgeSection(e,t){let s=(this.readDeviceKnowledge()||"").split(`
|
|
@@ -396,15 +396,15 @@ ${p.join(`
|
|
|
396
396
|
`);return this.writeDeviceKnowledge(c)}addNote(e,t,n="Notes"){let s=new Date().toLocaleString(),r=`### ${e} (${s})
|
|
397
397
|
${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
|
|
398
398
|
`),c=[],l=!1,d=!1;for(let m of a)m.startsWith(`## ${n}`)?(l=!0,c.push(m)):m.startsWith("## ")&&l&&!d?(c.push(""),c.push(r),c.push(""),c.push(m),l=!1,d=!0):c.push(m);l&&!d&&(c.push(""),c.push(r));let g=c.join(`
|
|
399
|
-
`);return this.writeDeviceKnowledge(g)}else return this.updateKnowledgeSection(n,r)}deleteDeviceKnowledge(){try{return
|
|
399
|
+
`);return this.writeDeviceKnowledge(g)}else return this.updateKnowledgeSection(n,r)}deleteDeviceKnowledge(){try{return Ge.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return Ge.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=Ge.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}},Se=Vr.shared()});var Yr,Il=L(()=>{"use strict";q();wt();Xr();Yr=class{toolNames=["manage_device_knowledge"];async execute(e,t,n,s){let r=n.action,o=Date.now();u.debug(`[ManageDeviceKnowledgeTool] Executing action: ${r}`),Y.start("ManageDeviceKnowledge",r);try{let a,c=!0;switch(r){case"read":{let d=Se.readDeviceKnowledge();d?a=d:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await Se.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${Se.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",c=!1);break}case"write":{let d=n.content;d?Se.writeDeviceKnowledge(d)?a="Device knowledge updated successfully.":(a="Failed to write device knowledge.",c=!1):(a='Error: Missing "content" argument for write action.',c=!1);break}case"append":{let d=n.content;d?Se.appendDeviceKnowledge(d)?a="Content appended to device knowledge successfully.":(a="Failed to append to device knowledge.",c=!1):(a='Error: Missing "content" argument for append action.',c=!1);break}case"update_section":{let d=n.section,g=n.content;!d||!g?(a='Error: Missing "section" or "content" argument for update_section action.',c=!1):Se.updateKnowledgeSection(d,g)?a=`Section "${d}" updated successfully.`:(a=`Failed to update section "${d}".`,c=!1);break}case"add_note":{let d=n.title,g=n.content,m=n.category||"Notes";!d||!g?(a='Error: Missing "title" or "content" argument for add_note action.',c=!1):Se.addNote(d,g,m)?a=`Note "${d}" added to ${m} successfully.`:(a=`Failed to add note "${d}".`,c=!1);break}case"delete":{Se.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",c=!1);break}case"path":{a=Se.getKnowledgeFilePath();break}case"exists":{a=Se.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${Se.getKnowledgeFileSize()} bytes`;break}case"export":{let d=n.destination;d?Se.exportDeviceKnowledge(d)?a=`Device knowledge exported to: ${d}`:(a=`Failed to export device knowledge to: ${d}`,c=!1):(a='Error: Missing "destination" argument for export action.',c=!1);break}case"import":{let d=n.source;d?Se.importDeviceKnowledge(d)?a=`Device knowledge imported from: ${d}`:(a=`Failed to import device knowledge from: ${d}`,c=!1):(a='Error: Missing "source" argument for import action.',c=!1);break}default:a=`Unknown action: ${r}. Valid actions: read, initialize, write, append, update_section, add_note, delete, path, exists, size, export, import`,c=!1}let l=Date.now()-o;return Y.result({toolName:"ManageDeviceKnowledge",output:a.substring(0,200)+(a.length>200?"...":""),success:c,executionTime:l}),[{type:"text",text:a}]}catch(a){u.debug(`[ManageDeviceKnowledgeTool] Error: ${a.message}`);let c=`Error managing device knowledge: ${a.message}`,l=Date.now()-o;return Y.result({toolName:"ManageDeviceKnowledge",output:c,success:!1,executionTime:l}),[{type:"text",text:c}]}}}});var Qr,kl=L(()=>{"use strict";q();Qr=class{toolNames=["operator_status"];async execute(e,t,n,s){let r=n.taskId,o=n.status,a=n.message;return u.debug(`[OperatorStatusTool] Operator status - Task ${r}: ${o} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var Jr,Pl=L(()=>{"use strict";q();Jr=class{toolNames=["provide_input"];async execute(e,t,n,s){let r=n.input;if(!r)throw new Error("Missing input argument");u.debug(`[ProvideInputTool] Delegating provide_input to backend: ${r.substring(0,20)}...`);try{let o=(await Promise.resolve().then(()=>(Ur(),Ui))).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 Gp}from"child_process";import{promisify as jp}from"util";import*as Zr from"fs/promises";import*as Al from"path";import*as Dl from"os";var zp,Zn,Hi=L(()=>{"use strict";q();zp=jp(Gp),Zn=class i{static instance;constructor(){}static getInstance(){return i.instance||(i.instance=new i),i.instance}async captureScreen(){try{let e=Al.join(Dl.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
|
|
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 zp(t);let n=await Zr.readFile(e),s=n.toString("base64");return await Zr.unlink(e).catch(()=>{}),u.debug(`[SCREENSHOT] Captured screenshot: ${n.length} bytes`),`data:image/jpeg;base64,${s}`}catch(e){return u.debug("[SCREENSHOT] Failed to capture screen:",e.message),process.platform==="linux"&&e.message.includes("scrot")?(console.log(`
|
|
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 Jr,kl=L(()=>{"use strict";q();Hi();Jr=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,n,s){u.debug("[TakeScreenshotTool] Capturing screenshot...");try{let o=await Jn.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 Gi,Wp,b,ut=L(()=>{"use strict";Gi=process.env.BROWSER_USE_DEBUG==="1"||"false"?.includes("browser-use"),Wp={log:Gi?console.log.bind(console):()=>{},debug:Gi?console.debug.bind(console):()=>{},info:Gi?console.info.bind(console):()=>{}},b=Wp});import{EventEmitter as Hp}from"eventemitter3";function Ee(i,e){let t=process.env[i];if(t){let n=parseFloat(t);if(!isNaN(n)&&n>=0)return n;console.warn(`Warning: ${i}=${t} is not a valid number, using default ${e}`)}return e}var Zr,ee,ji=L(()=>{"use strict";Zr=class extends Hp{pendingEvents=new Map;async dispatch(e,t,n){let s=`${e}_${Date.now()}_${Math.random()}`;return new Promise((r,o)=>{let a;n&&n>0&&(a=setTimeout(()=>{this.pendingEvents.delete(s),o(new Error(`Event ${e} timed out after ${n}s`))},n*1e3)),this.pendingEvents.set(s,{resolve:r,reject:o,timeout:a}),this.emit(e,{...t,_eventId:s})})}respondToEvent(e,t){let n=this.pendingEvents.get(e);n&&(n.timeout&&clearTimeout(n.timeout),n.resolve(t),this.pendingEvents.delete(e))}rejectEvent(e,t){let n=this.pendingEvents.get(e);n&&(n.timeout&&clearTimeout(n.timeout),n.reject(t),this.pendingEvents.delete(e))}};ee={NAVIGATE_TO_URL:Ee("TIMEOUT_NavigateToUrlEvent",15),CLICK_ELEMENT:Ee("TIMEOUT_ClickElementEvent",15),TYPE_TEXT:Ee("TIMEOUT_TypeTextEvent",60),SCROLL:Ee("TIMEOUT_ScrollEvent",8),SWITCH_TAB:Ee("TIMEOUT_SwitchTabEvent",10),CLOSE_TAB:Ee("TIMEOUT_CloseTabEvent",10),SCREENSHOT:Ee("TIMEOUT_ScreenshotEvent",15),BROWSER_STATE_REQUEST:Ee("TIMEOUT_BrowserStateRequestEvent",30),GO_BACK:Ee("TIMEOUT_GoBackEvent",15),GO_FORWARD:Ee("TIMEOUT_GoForwardEvent",15),REFRESH:Ee("TIMEOUT_RefreshEvent",15),WAIT:Ee("TIMEOUT_WaitEvent",60),SEND_KEYS:Ee("TIMEOUT_SendKeysEvent",60),UPLOAD_FILE:Ee("TIMEOUT_UploadFileEvent",30),GET_DROPDOWN_OPTIONS:Ee("TIMEOUT_GetDropdownOptionsEvent",15),SELECT_DROPDOWN_OPTION:Ee("TIMEOUT_SelectDropdownOptionEvent",8),SCROLL_TO_TEXT:Ee("TIMEOUT_ScrollToTextEvent",15),BROWSER_START:Ee("TIMEOUT_BrowserStartEvent",30),BROWSER_STOP:Ee("TIMEOUT_BrowserStopEvent",45)}});var j,zi=L(()=>{"use strict";j={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 Pl,rI,Us,Al=L(()=>{"use strict";ut();Pl=["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"],rI=["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(", "),Us=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 w=a.isClickable?.index||[];f.isClickable=w.includes(h)}let y=g.get(h);if(y!==void 0){let w=c.bounds||[];if(y<w.length){let I=w[y];I&&I.length>=4&&(f.bounds={x:I[0]/t,y:I[1]/t,width:I[2]/t,height:I[3]/t})}let C=c.styles||[];if(y<C.length){let I=C[y]||[],S={};for(let E=0;E<I.length&&E<r.length;E++){let P=I[E];P>=0&&P<s.length&&(S[r[E]]=s[P])}Object.keys(S).length>0&&(f.computedStyles=S,f.cursorStyle=S.cursor)}let T=c.paintOrders||[];y<T.length&&(f.paintOrder=T[y]);let x=c.clientRects||[];if(y<x.length){let I=x[y];I&&I.length>=4&&(f.clientRects={x:I[0],y:I[1],width:I[2],height:I[3]})}let v=c.scrollRects||[];if(y<v.length){let I=v[y];I&&I.length>=4&&(f.scrollRects={x:I[0],y:I[1],width:I[2],height:I[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(w=>y.toLowerCase().includes(w)))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,w=c.x-g.x,C=c.y-g.y;if(!(w<f&&w+c.width>0&&C<y+2e3&&C+c.height>-2e3))return!1;c.x-=g.x,c.y-=g.y}}}return!0}static rectIntersects(e,t){return!(e.x2<=t.x1||t.x2<=e.x1||e.y2<=t.y1||t.y2<=e.y1)}static rectContains(e,t){return e.x1<=t.x1&&e.y1<=t.y1&&e.x2>=t.x2&&e.y2>=t.y2}static splitDiff(e,t){let n=[];e.y1<t.y1&&n.push({x1:e.x1,y1:e.y1,x2:e.x2,y2:t.y1}),t.y2<e.y2&&n.push({x1:e.x1,y1:t.y2,x2:e.x2,y2:e.y2});let s=Math.max(e.y1,t.y1),r=Math.min(e.y2,t.y2);return e.x1<t.x1&&n.push({x1:e.x1,y1:s,x2:t.x1,y2:r}),t.x2<e.x2&&n.push({x1:t.x2,y1:s,x2:e.x2,y2:r}),n}static rectUnionContains(e,t){if(e.length===0)return!1;let n=[t];for(let s of e){let r=[];for(let o of n)i.rectContains(s,o)||(i.rectIntersects(o,s)?r.push(...i.splitDiff(o,s)):r.push(o));if(r.length===0)return!0;n=r}return!1}static rectUnionAdd(e,t){if(i.rectUnionContains(e,t))return[];let n=[t];for(let s of e){let r=[];for(let o of n)i.rectIntersects(o,s)?r.push(...i.splitDiff(o,s)):r.push(o);n=r}return n}applyPaintOrderFiltering(e){let t=[];for(let[a,c]of e.entries())c.snapshotNode?.paintOrder!==void 0&&c.snapshotNode?.paintOrder!==null&&c.snapshotNode?.bounds&&t.push({backendNodeId:a,node:c,paintOrder:c.snapshotNode.paintOrder,bounds:c.snapshotNode.bounds});if(t.length===0)return e;let n=new Map;for(let a of t)n.has(a.paintOrder)||n.set(a.paintOrder,[]),n.get(a.paintOrder).push(a);let s=new Set,r=[],o=Array.from(n.keys()).sort((a,c)=>c-a);for(let a of o){let c=n.get(a),l=[];for(let d of c){let g={x1:d.bounds.x,y1:d.bounds.y,x2:d.bounds.x+d.bounds.width,y2:d.bounds.y+d.bounds.height};i.rectUnionContains(r,g)&&s.add(d.backendNodeId);let m=d.node.snapshotNode?.computedStyles;if(m){let p=m["background-color"]||"rgba(0, 0, 0, 0)",h=parseFloat(m.opacity||"1");if(p==="rgba(0, 0, 0, 0)"||h<.8)continue}l.push(g)}for(let d of l){let g=i.rectUnionAdd(r,d);r.push(...g)}}if(s.size>0){b.debug(`🎨 [Paint Order] Filtering ${s.size} covered elements`);let a=new Map;for(let[c,l]of e.entries())s.has(c)||a.set(c,l);return a}return e}static PROPAGATING_ELEMENTS=[{tag:"a",role:null},{tag:"button",role:null},{tag:"div",role:"button"},{tag:"div",role:"combobox"},{tag:"span",role:"button"},{tag:"span",role:"combobox"},{tag:"input",role:"combobox"}];static DEFAULT_CONTAINMENT_THRESHOLD=.99;isPropagatingElement(e,t){let n=e.toLowerCase(),s=["tag","role"];for(let r of i.PROPAGATING_ELEMENTS)if(s.map(a=>a==="tag"?r.tag===null||r.tag===n:r.role===null||r.role===t).every(Boolean))return!0;return!1}isContained(e,t,n=i.DEFAULT_CONTAINMENT_THRESHOLD){let s=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y)),o=s*r,a=e.width*e.height;return a===0?!1:o/a>=n}shouldExcludeChild(e,t){let n=e.absolutePosition||e.snapshotNode?.bounds;if(!n||!this.isContained(n,t))return!1;let s=e.nodeName.toLowerCase(),r=e.attributes?.role;if(["input","select","textarea","label"].includes(s)||this.isPropagatingElement(s,r)||e.attributes?.onclick)return!1;let o=e.attributes?.["aria-label"];return!(o&&o.trim()||r&&["button","link","checkbox","radio","tab","menuitem","option"].includes(r))}applyBoundingBoxFiltering(e){let t=[];for(let[s,r]of e.entries()){let o=r.nodeName,a=r.attributes?.role,c=r.absolutePosition||r.snapshotNode?.bounds;this.isPropagatingElement(o,a)&&c&&t.push({backendNodeId:s,bounds:c})}if(t.length===0)return e;let n=new Set;for(let[s,r]of e.entries())if(!t.some(o=>o.backendNodeId===s)){for(let o of t)if(this.shouldExcludeChild(r,o.bounds)){n.add(s);break}}if(n.size>0){b.debug(`📦 [BBox Filter] Excluding ${n.size} elements contained within parent bounds`);let s=new Map;for(let[r,o]of e.entries())n.has(r)||s.set(r,o);return s}return e}detectModalOverlays(e,t){let n=[],s=t.width*t.height,r=.3;for(let[o,a]of e.entries()){let c=a.snapshotNode?.computedStyles,l=a.absolutePosition||a.snapshotNode?.bounds,d=a.nodeName.toLowerCase(),g=a.attributes||{},m=[],p=g.role?.toLowerCase()||"",h=g["aria-modal"]?.toLowerCase(),f=(g.class||"").toLowerCase(),y=(g.id||"").toLowerCase();(p==="dialog"||p==="alertdialog"||h==="true")&&m.push(`role=${p||"aria-modal"}`);let w=["modal","overlay","dialog","popup","drawer","backdrop","lightbox"];for(let C of w)if(f.includes(C)||y.includes(C)){m.push(`class/id contains "${C}"`);break}if(c&&l){let C=(c.position||"").toLowerCase(),x=l.width*l.height/s;if((C==="fixed"||C==="absolute")&&x>=r&&m.push(`${C} position, covers ${(x*100).toFixed(0)}% of viewport`),x>=.8){let v=parseFloat(c.opacity||"1");((c["background-color"]||"").includes("rgba")||v<1)&&m.push("full-screen semi-transparent overlay")}}m.length>0&&n.push({backendNodeId:o,nodeName:d,reason:m.join(", ")})}return n}async detectJsClickListeners(e){let t=new Set;try{let s=(await e.send("Runtime.evaluate",{expression:`
|
|
407
|
+
`)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}}});var eo,Ml=L(()=>{"use strict";q();Hi();eo=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,n,s){u.debug("[TakeScreenshotTool] Capturing screenshot...");try{let o=await Zn.getInstance().captureScreen();if(!o)throw new Error("Failed to capture screenshot - no image data returned");return u.debug("[TakeScreenshotTool] Screenshot captured successfully"),[{type:"image_url",image_url:{url:o}}]}catch(r){return u.error(`[TakeScreenshotTool] Failed to capture screenshot: ${r.message}`),[{type:"text",text:`Failed to capture screenshot: ${r.message}`}]}}}});var Gi,qp,b,ut=L(()=>{"use strict";Gi=process.env.BROWSER_USE_DEBUG==="1"||"false"?.includes("browser-use"),qp={log:Gi?console.log.bind(console):()=>{},debug:Gi?console.debug.bind(console):()=>{},info:Gi?console.info.bind(console):()=>{}},b=qp});import{EventEmitter as Kp}from"eventemitter3";function Ee(i,e){let t=process.env[i];if(t){let n=parseFloat(t);if(!isNaN(n)&&n>=0)return n;console.warn(`Warning: ${i}=${t} is not a valid number, using default ${e}`)}return e}var to,ee,ji=L(()=>{"use strict";to=class extends Kp{pendingEvents=new Map;async dispatch(e,t,n){let s=`${e}_${Date.now()}_${Math.random()}`;return new Promise((r,o)=>{let a;n&&n>0&&(a=setTimeout(()=>{this.pendingEvents.delete(s),o(new Error(`Event ${e} timed out after ${n}s`))},n*1e3)),this.pendingEvents.set(s,{resolve:r,reject:o,timeout:a}),this.emit(e,{...t,_eventId:s})})}respondToEvent(e,t){let n=this.pendingEvents.get(e);n&&(n.timeout&&clearTimeout(n.timeout),n.resolve(t),this.pendingEvents.delete(e))}rejectEvent(e,t){let n=this.pendingEvents.get(e);n&&(n.timeout&&clearTimeout(n.timeout),n.reject(t),this.pendingEvents.delete(e))}};ee={NAVIGATE_TO_URL:Ee("TIMEOUT_NavigateToUrlEvent",15),CLICK_ELEMENT:Ee("TIMEOUT_ClickElementEvent",15),TYPE_TEXT:Ee("TIMEOUT_TypeTextEvent",60),SCROLL:Ee("TIMEOUT_ScrollEvent",8),SWITCH_TAB:Ee("TIMEOUT_SwitchTabEvent",10),CLOSE_TAB:Ee("TIMEOUT_CloseTabEvent",10),SCREENSHOT:Ee("TIMEOUT_ScreenshotEvent",15),BROWSER_STATE_REQUEST:Ee("TIMEOUT_BrowserStateRequestEvent",30),GO_BACK:Ee("TIMEOUT_GoBackEvent",15),GO_FORWARD:Ee("TIMEOUT_GoForwardEvent",15),REFRESH:Ee("TIMEOUT_RefreshEvent",15),WAIT:Ee("TIMEOUT_WaitEvent",60),SEND_KEYS:Ee("TIMEOUT_SendKeysEvent",60),UPLOAD_FILE:Ee("TIMEOUT_UploadFileEvent",30),GET_DROPDOWN_OPTIONS:Ee("TIMEOUT_GetDropdownOptionsEvent",15),SELECT_DROPDOWN_OPTION:Ee("TIMEOUT_SelectDropdownOptionEvent",8),SCROLL_TO_TEXT:Ee("TIMEOUT_ScrollToTextEvent",15),BROWSER_START:Ee("TIMEOUT_BrowserStartEvent",30),BROWSER_STOP:Ee("TIMEOUT_BrowserStopEvent",45)}});var j,zi=L(()=>{"use strict";j={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 Rl,lI,Us,Ol=L(()=>{"use strict";ut();Rl=["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"],lI=["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(", "),Us=class i{constructor(e,t={}){this.page=e;this.crossOriginIframes=t.crossOriginIframes??!1,this.paintOrderFiltering=t.paintOrderFiltering??!0,this.maxIframes=t.maxIframes??100,this.maxIframeDepth=t.maxIframeDepth??5}cdpSession=null;previousElements=new Set;crossOriginIframes;paintOrderFiltering;maxIframes;maxIframeDepth;async getCDPSession(){if(!this.cdpSession){let e=this.page.context();this.cdpSession=await e.newCDPSession(this.page)}return this.cdpSession}async getViewportInfo(){try{let t=await(await this.getCDPSession()).send("Page.getLayoutMetrics"),n=t.visualViewport||{},s=t.cssVisualViewport||{},r=t.cssLayoutViewport||t.layoutViewport||{},o=s.clientWidth||r.clientWidth||1920,a=s.clientHeight||r.clientHeight||1080,c=n.clientWidth||o,l=s.clientWidth||o,d=l>0?c/l:1;return{width:o,height:a,scrollX:s.pageX||0,scrollY:s.pageY||0,devicePixelRatio:d}}catch{let t=this.page.viewportSize();return{width:t?.width||1920,height:t?.height||1080,scrollX:0,scrollY:0,devicePixelRatio:1}}}collectAllFrameIds(e){let t=[e.frame.id];if(e.childFrames&&e.childFrames.length>0)for(let n of e.childFrames)t.push(...this.collectAllFrameIds(n));return t}async getAccessibilityTree(){let e=new Map;try{let t=await this.getCDPSession();await t.send("Page.enable");let n=[];try{let a=(await t.send("Page.getFrameTree")).frameTree;a&&(n=this.collectAllFrameIds(a),b.debug(`Found ${n.length} frames for AX tree extraction`))}catch(o){b.debug("Failed to get frame tree, falling back to main frame only:",o)}let s=[];if(n.length>0)for(let o of n)s.push(t.send("Accessibility.getFullAXTree",{frameId:o}).catch(a=>(b.debug(`Failed to get AX tree for frame ${o}:`,a),{nodes:[]})));else s.push(t.send("Accessibility.getFullAXTree"));let r=await Promise.all(s);for(let o of r){let a=o.nodes||[];for(let c of a)c.backendDOMNodeId&&e.set(c.backendDOMNodeId,{nodeId:c.nodeId,ignored:c.ignored||!1,role:c.role?.value,name:c.name?.value,description:c.description?.value,value:c.value?.value,childIds:c.childIds,backendDOMNodeId:c.backendDOMNodeId,properties:c.properties})}}catch(t){b.debug("Failed to get accessibility tree:",t)}return e}async getDOMSnapshot(){try{return await(await this.getCDPSession()).send("DOMSnapshot.captureSnapshot",{computedStyles:["display","visibility","opacity","position","overflow","z-index","pointer-events"],includePaintOrder:this.paintOrderFiltering,includeDOMRects:!0})}catch(e){return b.debug("Failed to get DOM snapshot:",e),null}}isElementVisible(e){let t=(e.display||"").toLowerCase(),n=(e.visibility||"").toLowerCase(),s=e.opacity||"1",r=(e["pointer-events"]||"").toLowerCase();if(t==="none"||n==="hidden"||r==="none")return!1;try{if(parseFloat(s)<=0)return!1}catch{}return!0}buildSnapshotLookup(e,t){let n=new Map;if(!e?.documents||e.documents.length===0)return n;let s=e.strings||[],r=["display","visibility","opacity","overflow","overflow-x","overflow-y","cursor","pointer-events","position","background-color"];for(let o of e.documents){let a=o.nodes||{},c=o.layout||{},l=new Map,d=a.backendNodeId||[];for(let p=0;p<d.length;p++)l.set(d[p],p);let g=new Map,m=c.nodeIndex||[];for(let p=0;p<m.length;p++){let h=m[p];g.has(h)||g.set(h,p)}for(let[p,h]of l){let f={};if(a.isClickable){let T=a.isClickable?.index||[];f.isClickable=T.includes(h)}let y=g.get(h);if(y!==void 0){let T=c.bounds||[];if(y<T.length){let I=T[y];I&&I.length>=4&&(f.bounds={x:I[0]/t,y:I[1]/t,width:I[2]/t,height:I[3]/t})}let x=c.styles||[];if(y<x.length){let I=x[y]||[],w={};for(let E=0;E<I.length&&E<r.length;E++){let P=I[E];P>=0&&P<s.length&&(w[r[E]]=s[P])}Object.keys(w).length>0&&(f.computedStyles=w,f.cursorStyle=w.cursor)}let S=c.paintOrders||[];y<S.length&&(f.paintOrder=S[y]);let C=c.clientRects||[];if(y<C.length){let I=C[y];I&&I.length>=4&&(f.clientRects={x:I[0],y:I[1],width:I[2],height:I[3]})}let v=c.scrollRects||[];if(y<v.length){let I=v[y];I&&I.length>=4&&(f.scrollRects={x:I[0],y:I[1],width:I[2],height:I[3]})}}n.set(p,f)}}return n}isInteractiveNode(e,t,n,s,r,o,a){let c=e.toLowerCase();if(c==="html"||c==="body")return!1;if(a||(c==="iframe"||c==="frame")&&r&&r.width>100&&r.height>100)return!0;let l=["search","magnify","glass","lookup","find","query","search-icon","search-btn","search-button","searchbox"],d=(t.class||"").toLowerCase();if(l.some(f=>d.includes(f)))return!0;let g=(t.id||"").toLowerCase();if(l.some(f=>g.includes(f)))return!0;for(let[f,y]of Object.entries(t))if(f.startsWith("data-")&&y&&l.some(T=>y.toLowerCase().includes(T)))return!0;if(s&&s.properties)for(let f of s.properties)try{if(f.name==="disabled"&&f.value||f.name==="hidden"&&f.value)return!1;if(["focusable","editable","settable"].includes(f.name)&&f.value||["checked","expanded","pressed","selected"].includes(f.name)||["required","autocomplete"].includes(f.name)&&f.value||f.name==="keyshortcuts"&&f.value)return!0}catch{continue}if(new Set(["button","input","select","textarea","a","details","summary","option","optgroup"]).has(c))return!(c==="input"&&t.type==="hidden");if(["onclick","onmousedown","onmouseup","onkeydown","onkeyup","tabindex"].some(f=>f in t))return!0;let h=t.role?.toLowerCase();return!!(h&&new Set(["button","link","menuitem","option","radio","checkbox","tab","textbox","combobox","slider","spinbutton","search","searchbox"]).has(h)||s&&s.role&&new Set(["button","link","menuitem","option","radio","checkbox","tab","textbox","combobox","slider","spinbutton","listbox","search","searchbox"]).has(s.role)||r&&r.width>=10&&r.width<=50&&r.height>=10&&r.height<=50&&["class","role","onclick","data-action","aria-label"].some(y=>y in t)||t.contenteditable==="true"||o==="pointer")}isElementVisibleAccordingToAllParents(e,t){if(!e)return!1;let n=e.computedStyles||{},s=(n.display||"").toLowerCase(),r=(n.visibility||"").toLowerCase(),o=n.opacity||"1";if(s==="none"||r==="hidden")return!1;try{if(parseFloat(o)<=0)return!1}catch{}let a=e.bounds;if(!a)return!1;let c={...a};for(let l=t.length-1;l>=0;l--){let d=t[l];if((d.nodeName.toUpperCase()==="IFRAME"||d.nodeName.toUpperCase()==="FRAME")&&d.snapshotData?.bounds){let g=d.snapshotData.bounds;c.x+=g.x,c.y+=g.y}if(d.nodeName==="HTML"&&d.snapshotData){let g=d.snapshotData.scrollRects,m=d.snapshotData.clientRects;if(g&&m){let f=m.width,y=m.height,T=c.x-g.x,x=c.y-g.y;if(!(T<f&&T+c.width>0&&x<y+2e3&&x+c.height>-2e3))return!1;c.x-=g.x,c.y-=g.y}}}return!0}static rectIntersects(e,t){return!(e.x2<=t.x1||t.x2<=e.x1||e.y2<=t.y1||t.y2<=e.y1)}static rectContains(e,t){return e.x1<=t.x1&&e.y1<=t.y1&&e.x2>=t.x2&&e.y2>=t.y2}static splitDiff(e,t){let n=[];e.y1<t.y1&&n.push({x1:e.x1,y1:e.y1,x2:e.x2,y2:t.y1}),t.y2<e.y2&&n.push({x1:e.x1,y1:t.y2,x2:e.x2,y2:e.y2});let s=Math.max(e.y1,t.y1),r=Math.min(e.y2,t.y2);return e.x1<t.x1&&n.push({x1:e.x1,y1:s,x2:t.x1,y2:r}),t.x2<e.x2&&n.push({x1:t.x2,y1:s,x2:e.x2,y2:r}),n}static rectUnionContains(e,t){if(e.length===0)return!1;let n=[t];for(let s of e){let r=[];for(let o of n)i.rectContains(s,o)||(i.rectIntersects(o,s)?r.push(...i.splitDiff(o,s)):r.push(o));if(r.length===0)return!0;n=r}return!1}static rectUnionAdd(e,t){if(i.rectUnionContains(e,t))return[];let n=[t];for(let s of e){let r=[];for(let o of n)i.rectIntersects(o,s)?r.push(...i.splitDiff(o,s)):r.push(o);n=r}return n}applyPaintOrderFiltering(e){let t=[];for(let[a,c]of e.entries())c.snapshotNode?.paintOrder!==void 0&&c.snapshotNode?.paintOrder!==null&&c.snapshotNode?.bounds&&t.push({backendNodeId:a,node:c,paintOrder:c.snapshotNode.paintOrder,bounds:c.snapshotNode.bounds});if(t.length===0)return e;let n=new Map;for(let a of t)n.has(a.paintOrder)||n.set(a.paintOrder,[]),n.get(a.paintOrder).push(a);let s=new Set,r=[],o=Array.from(n.keys()).sort((a,c)=>c-a);for(let a of o){let c=n.get(a),l=[];for(let d of c){let g={x1:d.bounds.x,y1:d.bounds.y,x2:d.bounds.x+d.bounds.width,y2:d.bounds.y+d.bounds.height};i.rectUnionContains(r,g)&&s.add(d.backendNodeId);let m=d.node.snapshotNode?.computedStyles;if(m){let p=m["background-color"]||"rgba(0, 0, 0, 0)",h=parseFloat(m.opacity||"1");if(p==="rgba(0, 0, 0, 0)"||h<.8)continue}l.push(g)}for(let d of l){let g=i.rectUnionAdd(r,d);r.push(...g)}}if(s.size>0){b.debug(`🎨 [Paint Order] Filtering ${s.size} covered elements`);let a=new Map;for(let[c,l]of e.entries())s.has(c)||a.set(c,l);return a}return e}static PROPAGATING_ELEMENTS=[{tag:"a",role:null},{tag:"button",role:null},{tag:"div",role:"button"},{tag:"div",role:"combobox"},{tag:"span",role:"button"},{tag:"span",role:"combobox"},{tag:"input",role:"combobox"}];static DEFAULT_CONTAINMENT_THRESHOLD=.99;isPropagatingElement(e,t){let n=e.toLowerCase(),s=["tag","role"];for(let r of i.PROPAGATING_ELEMENTS)if(s.map(a=>a==="tag"?r.tag===null||r.tag===n:r.role===null||r.role===t).every(Boolean))return!0;return!1}isContained(e,t,n=i.DEFAULT_CONTAINMENT_THRESHOLD){let s=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y)),o=s*r,a=e.width*e.height;return a===0?!1:o/a>=n}shouldExcludeChild(e,t){let n=e.absolutePosition||e.snapshotNode?.bounds;if(!n||!this.isContained(n,t))return!1;let s=e.nodeName.toLowerCase(),r=e.attributes?.role;if(["input","select","textarea","label"].includes(s)||this.isPropagatingElement(s,r)||e.attributes?.onclick)return!1;let o=e.attributes?.["aria-label"];return!(o&&o.trim()||r&&["button","link","checkbox","radio","tab","menuitem","option"].includes(r))}applyBoundingBoxFiltering(e){let t=[];for(let[s,r]of e.entries()){let o=r.nodeName,a=r.attributes?.role,c=r.absolutePosition||r.snapshotNode?.bounds;this.isPropagatingElement(o,a)&&c&&t.push({backendNodeId:s,bounds:c})}if(t.length===0)return e;let n=new Set;for(let[s,r]of e.entries())if(!t.some(o=>o.backendNodeId===s)){for(let o of t)if(this.shouldExcludeChild(r,o.bounds)){n.add(s);break}}if(n.size>0){b.debug(`📦 [BBox Filter] Excluding ${n.size} elements contained within parent bounds`);let s=new Map;for(let[r,o]of e.entries())n.has(r)||s.set(r,o);return s}return e}detectModalOverlays(e,t){let n=[],s=t.width*t.height,r=.3;for(let[o,a]of e.entries()){let c=a.snapshotNode?.computedStyles,l=a.absolutePosition||a.snapshotNode?.bounds,d=a.nodeName.toLowerCase(),g=a.attributes||{},m=[],p=g.role?.toLowerCase()||"",h=g["aria-modal"]?.toLowerCase(),f=(g.class||"").toLowerCase(),y=(g.id||"").toLowerCase();(p==="dialog"||p==="alertdialog"||h==="true")&&m.push(`role=${p||"aria-modal"}`);let T=["modal","overlay","dialog","popup","drawer","backdrop","lightbox"];for(let x of T)if(f.includes(x)||y.includes(x)){m.push(`class/id contains "${x}"`);break}if(c&&l){let x=(c.position||"").toLowerCase(),C=l.width*l.height/s;if((x==="fixed"||x==="absolute")&&C>=r&&m.push(`${x} position, covers ${(C*100).toFixed(0)}% of viewport`),C>=.8){let v=parseFloat(c.opacity||"1");((c["background-color"]||"").includes("rgba")||v<1)&&m.push("full-screen semi-transparent overlay")}}m.length>0&&n.push({backendNodeId:o,nodeName:d,reason:m.join(", ")})}return n}async detectJsClickListeners(e){let t=new Set;try{let s=(await e.send("Runtime.evaluate",{expression:`
|
|
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||
|
|
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||Rl,n=await this.getCDPSession();try{let w=await n.send("Runtime.evaluate",{expression:"document.readyState"});b.debug(`📄 Document readyState: ${w.result?.value}`)}catch(w){b.debug("Failed to get document readyState:",w)}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(w){throw console.error("Failed to get DOM via CDP:",w),w}let c=new Map;try{let E=(await n.send("Runtime.evaluate",{expression:`
|
|
432
432
|
(() => {
|
|
433
433
|
const scrollData = {};
|
|
434
434
|
const iframes = document.querySelectorAll('iframe');
|
|
@@ -447,8 +447,8 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
|
|
|
447
447
|
});
|
|
448
448
|
return scrollData;
|
|
449
449
|
})()
|
|
450
|
-
`,returnByValue:!0})).result?.value;if(E)for(let[P,D]of Object.entries(E)){let $=D;c.set(parseInt(P),$),b.debug(`Iframe ${P} scroll position - scrollTop=${$.scrollTop}, scrollLeft=${$.scrollLeft}`)}}catch(
|
|
451
|
-
`).trim()}!Z&&
|
|
450
|
+
`,returnByValue:!0})).result?.value;if(E)for(let[P,D]of Object.entries(E)){let $=D;c.set(parseInt(P),$),b.debug(`Iframe ${P} scroll position - scrollTop=${$.scrollTop}, scrollLeft=${$.scrollLeft}`)}}catch(w){b.debug("Failed to get iframe scroll positions:",w)}let l=new Map;try{let w=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(w,r.devicePixelRatio)}catch(w){b.debug("Failed to get DOM snapshot:",w)}let d=new Map,g=[],m=new Set,p=[],h=(w,E,P,D=0)=>{E===null&&(E=[]),P===null?P={x:0,y:0}:P={x:P.x,y:P.y};let $=w.backendNodeId,R=w.nodeName?.toLowerCase()||"",_=w.nodeType;if(_===9||_===11){let Z=[];if(w.children)for(let $e of w.children){let vt=h($e,E,P,D);vt&&Z.push(vt)}return Z.length===1?Z[0]:Z.length>0?{index:-1,tagName:R,children:Z,isInteractive:!1,position:void 0}:null}if(_!==1)return null;let N={};if(w.attributes)for(let Z=0;Z<w.attributes.length;Z+=2){let $e=w.attributes[Z],vt=w.attributes[Z+1];$e&&(N[$e]=vt||"")}let k={};for(let Z of t)N[Z]&&(k[Z]=N[Z]);let M=l.get($),F=M?.isClickable??!1,B=M?.bounds,H=M?.cursorStyle,V=o.get($),le;B&&(le={x:B.x+P.x,y:B.y+P.y,width:B.width,height:B.height});let W=[...E];_===1&&R==="html"&&w.frameId&&(W.push({nodeName:"HTML",frameId:w.frameId,snapshotData:M}),M?.scrollRects&&(P.x-=M.scrollRects.x,P.y-=M.scrollRects.y)),(R==="iframe"||R==="frame")&&B&&(W.push({nodeName:R.toUpperCase(),frameId:w.frameId,snapshotData:M}),P.x+=B.x,P.y+=B.y);let G=this.isElementVisibleAccordingToAllParents(M,W),et=s.has($),Cs=this.isInteractiveNode(R,N,F,V,B,H,et),yt={index:Cs?$:-1,tagName:R,children:[],isInteractive:Cs,isVisible:G,position:le||B};if(Cs&&G){m.add($);let Z="",$e=k.role;if(V&&(Z=V.name||"",$e=V.role||$e),!Z&&w.children){let St=qt=>{let yi=[];if(qt.nodeType===3&&qt.nodeValue){let xr=qt.nodeValue.trim();xr.length>1&&yi.push(xr)}if(qt.children)for(let xr of qt.children)yi.push(...St(xr));return yi};Z=St(w).join(`
|
|
451
|
+
`).trim()}!Z&&w.nodeValue&&(Z=w.nodeValue.trim().substring(0,200)),yt.text=Z,yt.role=$e;let vt={...k};if(V&&V.properties)for(let St of V.properties)try{if(Rl.includes(St.name)&&St.value!==null&&St.value!==void 0){let Tr=St.value?.value!==void 0?St.value.value:St.value;if(typeof Tr=="boolean")vt[St.name]=Tr.toString().toLowerCase();else{let qt=String(Tr).trim();qt&&(vt[St.name]=qt)}}}catch{continue}V?.name&&!vt.ax_name&&(vt.ax_name=V.name),yt.attributes=vt;let Pc=!this.previousElements.has($.toString());yt.isNew=Pc;let Pm={nodeId:w.nodeId,backendNodeId:$,sessionId:"",frameId:w.frameId||"",targetId:"",nodeType:"element",nodeName:R,attributes:vt,isVisible:G,absolutePosition:le||B,text:Z,role:$e,isNew:Pc,hasJsClickListener:et,snapshotNode:M?{isClickable:M.isClickable,cursorStyle:M.cursorStyle,bounds:M.bounds,clientRects:M.clientRects,scrollRects:M.scrollRects,computedStyles:M.computedStyles,paintOrder:M.paintOrder}:null};d.set($,Pm)}let vn=new Set;if(w.shadowRoots)for(let Z of w.shadowRoots)Z.nodeId&&vn.add(Z.nodeId);if(w.children)for(let Z of w.children){if(Z.nodeId&&vn.has(Z.nodeId))continue;let $e=h(Z,W,P,D+1);$e&&yt.children.push($e)}if(w.contentDocument){let Z=h(w.contentDocument,W,P,D+1);Z&&yt.children.push(Z)}else if((R==="iframe"||R==="frame")&&this.crossOriginIframes&&D<this.maxIframeDepth&&w.frameId){let Z=B||M?.bounds;G&&Z&&Z.width>=50&&Z.height>=50&&p.push({treeNode:yt,frameId:w.frameId,htmlFrames:W,totalFrameOffset:{...P},depth:D+1})}if(w.shadowRoots)for(let Z of w.shadowRoots){let $e=h(Z,W,P,D+1);$e&&yt.children.push($e)}return yt},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 E=(await n.send("Target.getTargets")).targetInfos||[];await n.send("Page.enable");let D=(await n.send("Page.getFrameTree")).frameTree,$=new Map,R=_=>{let N=_.frame||{};if(N.id){let k=E.find(M=>M.type==="iframe"&&M.url&&N.url&&M.url===N.url);k&&$.set(N.id,k.targetId)}for(let k of _.childFrames||[])R(k)};D&&R(D);for(let _ of p){let N=$.get(_.frameId);if(!N){b.debug(`No target found for cross-origin iframe ${_.frameId}`);continue}try{b.debug(`Found cross-origin iframe target: ${N} for frame ${_.frameId}`);let M=this.page.frames().find(F=>F.url().includes(_.frameId)||F.name()===_.frameId);if(M)try{let F=await M.content();F&&b.debug(`Got content from cross-origin frame ${_.frameId} (${F.length} chars)`)}catch{}}catch(k){b.debug(`Failed to process cross-origin iframe ${_.frameId}:`,k)}}}catch(w){b.debug("Failed to process cross-origin iframes:",w)}}this.previousElements=new Set(Array.from(m).map(w=>w.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 w of y)b.debug(` - ${w.nodeName} (backendNodeId=${w.backendNodeId}): ${w.reason}`)}let T=d,x=d.size;e.paintOrderFiltering!==!1&&(T=this.applyPaintOrderFiltering(d));let S=T.size;e.bboxFiltering!==!1&&(T=this.applyBoundingBoxFiltering(T));let C={url:this.page.url(),title:await this.page.title(),domTree:g,selectorMap:T,viewportInfo:r};if(e.includeScreenshot!==!1){let w=await this.page.screenshot({type:"png"});C.screenshot=w.toString("base64")}let v=x-S,I=S-T.size;return b.log(`📋 [DOM] Extracted ${T.size} interactive elements with real backendNodeIds (${v} filtered by paint order, ${I} filtered by bbox)`),C}formatDOMForLLM(e,t=0,n=!0,s){let r="";for(let o of e){let a=!s||s.has(o.index);if(o.isInteractive&&a){let c=" ".repeat(t),d=`${n&&o.isNew?"*":""}[${o.index}]`,g=`<${o.tagName}`,m="";if(o.attributes){let p=[],h={},f=["title","type","checked","id","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","aria-valuemin","aria-valuemax","aria-valuenow","aria-placeholder","pattern","min","max","minlength","maxlength","step","pseudo","selected","expanded","pressed","disabled","invalid","valuemin","valuemax","valuenow","keyshortcuts","haspopup","multiselectable","required","valuetext","level","busy","live","ax_name"];for(let T of f)o.attributes[T]!==void 0&&o.attributes[T]!==""&&(h[T]=String(o.attributes[T]).trim());if(Object.keys(h).length>1){let T={},x=[];for(let S of f)if(h[S]){let C=h[S];C.length>5&&(T[C]?x.push(S):T[C]=S)}for(let S of x)delete h[S]}h.role&&h.role.toLowerCase()===o.tagName.toLowerCase()&&delete h.role,h.type&&h.type.toLowerCase()===o.tagName.toLowerCase()&&delete h.type,h.invalid?.toLowerCase()==="false"&&delete h.invalid,h.expanded&&h["aria-expanded"]&&delete h["aria-expanded"];let y=o.text?.trim().toLowerCase()||"";for(let T of["aria-label","placeholder","title"])h[T]?.trim().toLowerCase()===y&&delete h[T];for(let T of f)if(h[T]){let x=h[T];x.length>100&&(x=x.substring(0,100)+"..."),p.push(`${T}=${x}`)}p.length>0&&(m=" "+p.join(" "))}if(r+=`${c}${d}${g}${m} />`,o.tagName.toLowerCase()==="select"&&o.children.length>0){let p=this.extractSelectOptions(o.children);p.length>0&&(r+=` [options: ${p.join(", ")}]`)}r+=`
|
|
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,9 +457,9 @@ ${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 cI}from"patchright";import dt from"fs";import qi from"path";import Gp from"os";function Cn(){return qi.join(jp,zp)}async function Dl(i,e=Cn(),t=!0){let n=qi.dirname(e);dt.existsSync(n)||dt.mkdirSync(n,{recursive:!0});let s=i;if(t&&dt.existsSync(e))try{let o=JSON.parse(dt.readFileSync(e,"utf-8"));s=Kp(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(dt.writeFileSync(r,JSON.stringify(s,null,2)),dt.existsSync(e)){let o=e+".bak";dt.renameSync(e,o)}dt.renameSync(r,e),b.log(`[ProfileImport] Saved profile to ${e}`),b.log(`[ProfileImport] Total: ${s.cookieCount} cookies, ${s.originCount} origins`)}function Ml(i=Cn()){if(!dt.existsSync(i))return null;try{return JSON.parse(dt.readFileSync(i,"utf-8"))}catch(e){return console.error(`[ProfileImport] Failed to load profile: ${e.message}`),null}}function Zn(i=Cn()){return dt.existsSync(i)}function qp(i){return i?{cookies:i.cookies,origins:i.origins}:null}function Bs(i=Cn()){let e=Ml(i);return qp(e)}function Kp(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 eo(i=Cn()){if(!dt.existsSync(i))return{exists:!1,cookieCount:0,originCount:0,importedAt:null,path:i};try{let t=Ml(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 jp,zp,to=L(()=>{"use strict";ut();jp=qi.join(Gp.homedir(),".orion"),zp="browser-profile.json"});import Vp from"crypto";import{z as Ue}from"zod";function Ws(i){return i.nodeName.toLowerCase()}function Qp(i){let e=[],t=i;for(;t&&(t.nodeType===1||t.nodeType===11);){if(t.nodeType===11){t=t.parentNode;continue}if(t.parentNode&&Ws(t.parentNode)==="iframe")break;let n=Jp(t),s=Ws(t),r=n>0?`[${n}]`:"";e.unshift(`${s}${r}`),t=t.parentNode}return e.join("/")}function Jp(i){if(!i.parentNode||!i.parentNode.childrenNodes)return 0;let e=i.parentNode.childrenNodes.filter(n=>n.nodeType===1&&Ws(n)===Ws(i));if(e.length<=1)return 0;let t=e.indexOf(i);return t>=0?t+1:0}function Zp(i){let t=eh(i).join("/"),n=Object.entries(i.attributes).filter(([o])=>Xp.has(o)).sort().map(([o,a])=>`${o}=${a}`).join(""),s=`${t}|${n}`,r=Vp.createHash("sha256").update(s).digest("hex");return parseInt(r.substring(0,16),16)}function eh(i){let e=[],t=i;for(;t;)t.nodeType===1&&e.push(t),t=t.parentNode;return e.reverse(),e.map(n=>Ws(n))}function Ol(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:Qp(i),elementHash:Zp(i)}}var Rl,Xp,no,Yp,fI,so=L(()=>{"use strict";Rl=["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"],Xp=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"]),no=(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))(no||{}),Yp=Ue.object({x:Ue.number(),y:Ue.number(),width:Ue.number(),height:Ue.number()}),fI=Ue.object({nodeId:Ue.number(),backendNodeId:Ue.number(),frameId:Ue.string().nullable().optional(),nodeType:Ue.nativeEnum(no),nodeValue:Ue.string(),nodeName:Ue.string(),attributes:Ue.record(Ue.string()).nullable().optional(),bounds:Yp.nullable().optional(),xPath:Ue.string(),elementHash:Ue.number()})});import*as Dt from"path";import*as _l from"os";import*as gt from"fs";import{v4 as vI}from"uuid";function th(){if(En!==null)return En;try{if(gt.existsSync("/.dockerenv"))return En=!0,!0}catch{}try{if(gt.readFileSync("/proc/1/cgroup","utf-8").toLowerCase().includes("docker"))return En=!0,!0}catch{}try{let i=gt.readFileSync("/proc/1/cmdline","utf-8").replace(/\0/g," ");if(/\b(node|python|py|uv|app)\b/i.test(i))return En=!0,!0}catch{}try{if(gt.readdirSync("/proc").filter(t=>/^\d+$/.test(t)).length<10)return En=!0,!0}catch{}return En=!1,!1}function Hs(i,e){if(!i)return e;let t=i.toLowerCase().charAt(0);return t==="t"||t==="y"||t==="1"}function Ki(i){return i.startsWith("~")?Dt.join(_l.homedir(),i.slice(1)):i}function nh(i){if(!Nl)try{gt.mkdirSync(i,{recursive:!0}),gt.mkdirSync(Dt.join(i,"profiles"),{recursive:!0}),gt.mkdirSync(Dt.join(i,"extensions"),{recursive:!0}),Nl=!0}catch{}}function $l(){let i=Ki(process.env.XDG_CACHE_HOME||"~/.cache"),e=Ki(process.env.XDG_CONFIG_HOME||"~/.config"),t=Ki(process.env.BROWSER_USE_CONFIG_DIR||Dt.join(e,"browseruse"));nh(t);let n=Hs(process.env.ANONYMIZED_TELEMETRY,!0),s=process.env.IN_DOCKER,r=s!==void 0?Hs(s,!1):th();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:Hs(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:Dt.join(t,"config.json"),BROWSER_USE_CONFIG_PATH:process.env.BROWSER_USE_CONFIG_PATH||null,BROWSER_USE_PROFILES_DIR:Dt.join(t,"profiles"),BROWSER_USE_DEFAULT_USER_DATA_DIR:Dt.join(t,"profiles","default"),BROWSER_USE_EXTENSIONS_DIR:Dt.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:Hs(process.env.SKIP_LLM_API_KEY_VERIFICATION,!1),DEFAULT_LLM:process.env.DEFAULT_LLM||"",IN_DOCKER:r,IS_IN_EVALS:Hs(process.env.IS_IN_EVALS,!1),WIN_FONT_DIR:process.env.WIN_FONT_DIR||"C:\\Windows\\Fonts"}}var En,Nl,Fl=L(()=>{"use strict";En=null;Nl=!1});var Mt,Gs,ro,js=L(()=>{"use strict";Mt={"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"},Gs={"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},ro={text:40,title:56,goal:44}});function sh(i,e){return i.toLowerCase()==="input"&&e&&(e==="button"||e==="submit")?Vi.button:Vi[i.toLowerCase()]||Vi.default}function rh(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 Ll(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),w=Math.floor((h.x+(h.width||0))*t),C=Math.floor((h.y+(h.height||0))*t),T=Math.max(0,Math.min(f,a)),x=Math.max(0,Math.min(y,c)),v=Math.max(T,Math.min(w,a)),I=Math.max(x,Math.min(C,c)),S={x:T,y:x,width:v-T,height:I-x};if(S.width<2||S.height<2)continue;let E="";if(p.attributes){let D=["value","aria-label","title","placeholder","alt"];for(let $ of D)if(p.attributes[$]){E=p.attributes[$];break}}E||(E=p.text||""),E=E.trim();let P=n?E.length<3:!0;l.push({index:m,bbox:S,tagName:p.nodeName||"div",elementType:p.attributes?.type,text:P?String(m):void 0,backendNodeId:m})}if(l.length===0)return i;let d=oh(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 oh(i,e,t,n){let s=e,r=Math.max(Gs["2xs"],Math.min(Gs.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,w,C){let T="";if(m===h){let x=Math.min(p,f),v=Math.max(p,f);for(;x<v;){let I=Math.min(x+c,v);T+=`<line x1="${m}" y1="${x}" x2="${m}" y2="${I}" stroke="${y}" stroke-width="${C}"/>`,x+=c+l}}else{let x=Math.min(m,h),v=Math.max(m,h);for(;x<v;){let I=Math.min(x+c,v);T+=`<line x1="${x}" y1="${p}" x2="${I}" y2="${p}" stroke="${y}" stroke-width="${C}"/>`,x+=c+l}}return T}for(let m of i){let{bbox:p,tagName:h,elementType:f,text:y}=m,w=sh(h,f),C=Math.max(0,Math.floor(p.x)),T=Math.max(0,Math.floor(p.y)),x=Math.min(Math.floor(p.x+p.width),e),v=Math.min(Math.floor(p.y+p.height),t);if(x-C<=0||v-T<=0)continue;a+=g(C,T,x,T,w,void 0,d),a+=g(x,T,x,v,w,void 0,d),a+=g(x,v,C,v,w,void 0,d),a+=g(C,v,C,T,w,void 0,d);let I=x-C,S=v-T;if(y){let E=y.length*(r*.6),P=r,D=E+o*2,$=P+o*2,_=rh({x:C,y:T,width:I,height:S},E,P,o,e,t),N=_.x,k=_.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 mI}from"patchright";import dt from"fs";import qi from"path";import Vp from"os";function Cn(){return qi.join(Xp,Yp)}async function Nl(i,e=Cn(),t=!0){let n=qi.dirname(e);dt.existsSync(n)||dt.mkdirSync(n,{recursive:!0});let s=i;if(t&&dt.existsSync(e))try{let o=JSON.parse(dt.readFileSync(e,"utf-8"));s=Jp(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(dt.writeFileSync(r,JSON.stringify(s,null,2)),dt.existsSync(e)){let o=e+".bak";dt.renameSync(e,o)}dt.renameSync(r,e),b.log(`[ProfileImport] Saved profile to ${e}`),b.log(`[ProfileImport] Total: ${s.cookieCount} cookies, ${s.originCount} origins`)}function _l(i=Cn()){if(!dt.existsSync(i))return null;try{return JSON.parse(dt.readFileSync(i,"utf-8"))}catch(e){return console.error(`[ProfileImport] Failed to load profile: ${e.message}`),null}}function es(i=Cn()){return dt.existsSync(i)}function Qp(i){return i?{cookies:i.cookies,origins:i.origins}:null}function Bs(i=Cn()){let e=_l(i);return Qp(e)}function Jp(i,e){let t=a=>`${a.domain}:${a.name}:${a.path}`,n=new Map;for(let a of i.cookies||[])n.set(t(a),a);for(let a of e.cookies||[])n.set(t(a),a);let s=new Map;for(let a of i.origins||[])s.set(a.origin,a);for(let a of e.origins||[]){let c=s.get(a.origin);if(c){let l=new Map;for(let d of c.localStorage||[])l.set(d.name,d.value);for(let d of a.localStorage||[])l.set(d.name,d.value);a.localStorage=Array.from(l.entries()).map(([d,g])=>({name:d,value:g}))}s.set(a.origin,a)}let r=Array.from(n.values()),o=Array.from(s.values());return{cookies:r,origins:o,importedAt:e.importedAt,sourceType:e.sourceType,cookieCount:r.length,originCount:o.length}}function no(i=Cn()){if(!dt.existsSync(i))return{exists:!1,cookieCount:0,originCount:0,importedAt:null,path:i};try{let t=_l(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 Xp,Yp,so=L(()=>{"use strict";ut();Xp=qi.join(Vp.homedir(),".orion"),Yp="browser-profile.json"});import Zp from"crypto";import{z as Be}from"zod";function Ws(i){return i.nodeName.toLowerCase()}function nh(i){let e=[],t=i;for(;t&&(t.nodeType===1||t.nodeType===11);){if(t.nodeType===11){t=t.parentNode;continue}if(t.parentNode&&Ws(t.parentNode)==="iframe")break;let n=sh(t),s=Ws(t),r=n>0?`[${n}]`:"";e.unshift(`${s}${r}`),t=t.parentNode}return e.join("/")}function sh(i){if(!i.parentNode||!i.parentNode.childrenNodes)return 0;let e=i.parentNode.childrenNodes.filter(n=>n.nodeType===1&&Ws(n)===Ws(i));if(e.length<=1)return 0;let t=e.indexOf(i);return t>=0?t+1:0}function rh(i){let t=oh(i).join("/"),n=Object.entries(i.attributes).filter(([o])=>eh.has(o)).sort().map(([o,a])=>`${o}=${a}`).join(""),s=`${t}|${n}`,r=Zp.createHash("sha256").update(s).digest("hex");return parseInt(r.substring(0,16),16)}function oh(i){let e=[],t=i;for(;t;)t.nodeType===1&&e.push(t),t=t.parentNode;return e.reverse(),e.map(n=>Ws(n))}function Fl(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:nh(i),elementHash:rh(i)}}var $l,eh,ro,th,wI,oo=L(()=>{"use strict";$l=["title","type","checked","id","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","aria-valuemin","aria-valuemax","aria-valuenow","aria-placeholder","pattern","min","max","minlength","maxlength","step","pseudo","selected","expanded","pressed","disabled","invalid","valuemin","valuemax","valuenow","keyshortcuts","haspopup","multiselectable","required","valuetext","level","busy","live","ax_name"],eh=new Set(["class","id","name","type","placeholder","aria-label","title","role","data-testid","data-test","data-cy","data-selenium","for","required","disabled","readonly","checked","selected","multiple","href","target","rel","aria-describedby","aria-labelledby","aria-controls","aria-owns","aria-live","aria-atomic","aria-busy","aria-disabled","aria-hidden","aria-pressed","aria-checked","aria-selected","tabindex","alt","src","lang","itemscope","itemtype","itemprop","pseudo","aria-valuemin","aria-valuemax","aria-valuenow","aria-placeholder"]),ro=(m=>(m[m.ELEMENT_NODE=1]="ELEMENT_NODE",m[m.ATTRIBUTE_NODE=2]="ATTRIBUTE_NODE",m[m.TEXT_NODE=3]="TEXT_NODE",m[m.CDATA_SECTION_NODE=4]="CDATA_SECTION_NODE",m[m.ENTITY_REFERENCE_NODE=5]="ENTITY_REFERENCE_NODE",m[m.ENTITY_NODE=6]="ENTITY_NODE",m[m.PROCESSING_INSTRUCTION_NODE=7]="PROCESSING_INSTRUCTION_NODE",m[m.COMMENT_NODE=8]="COMMENT_NODE",m[m.DOCUMENT_NODE=9]="DOCUMENT_NODE",m[m.DOCUMENT_TYPE_NODE=10]="DOCUMENT_TYPE_NODE",m[m.DOCUMENT_FRAGMENT_NODE=11]="DOCUMENT_FRAGMENT_NODE",m[m.NOTATION_NODE=12]="NOTATION_NODE",m))(ro||{}),th=Be.object({x:Be.number(),y:Be.number(),width:Be.number(),height:Be.number()}),wI=Be.object({nodeId:Be.number(),backendNodeId:Be.number(),frameId:Be.string().nullable().optional(),nodeType:Be.nativeEnum(ro),nodeValue:Be.string(),nodeName:Be.string(),attributes:Be.record(Be.string()).nullable().optional(),bounds:th.nullable().optional(),xPath:Be.string(),elementHash:Be.number()})});import*as Dt from"path";import*as Ul from"os";import*as gt from"fs";import{v4 as CI}from"uuid";function ih(){if(En!==null)return En;try{if(gt.existsSync("/.dockerenv"))return En=!0,!0}catch{}try{if(gt.readFileSync("/proc/1/cgroup","utf-8").toLowerCase().includes("docker"))return En=!0,!0}catch{}try{let i=gt.readFileSync("/proc/1/cmdline","utf-8").replace(/\0/g," ");if(/\b(node|python|py|uv|app)\b/i.test(i))return En=!0,!0}catch{}try{if(gt.readdirSync("/proc").filter(t=>/^\d+$/.test(t)).length<10)return En=!0,!0}catch{}return En=!1,!1}function Hs(i,e){if(!i)return e;let t=i.toLowerCase().charAt(0);return t==="t"||t==="y"||t==="1"}function Ki(i){return i.startsWith("~")?Dt.join(Ul.homedir(),i.slice(1)):i}function ah(i){if(!Ll)try{gt.mkdirSync(i,{recursive:!0}),gt.mkdirSync(Dt.join(i,"profiles"),{recursive:!0}),gt.mkdirSync(Dt.join(i,"extensions"),{recursive:!0}),Ll=!0}catch{}}function Bl(){let i=Ki(process.env.XDG_CACHE_HOME||"~/.cache"),e=Ki(process.env.XDG_CONFIG_HOME||"~/.config"),t=Ki(process.env.BROWSER_USE_CONFIG_DIR||Dt.join(e,"browseruse"));ah(t);let n=Hs(process.env.ANONYMIZED_TELEMETRY,!0),s=process.env.IN_DOCKER,r=s!==void 0?Hs(s,!1):ih();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:Hs(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:Dt.join(t,"config.json"),BROWSER_USE_CONFIG_PATH:process.env.BROWSER_USE_CONFIG_PATH||null,BROWSER_USE_PROFILES_DIR:Dt.join(t,"profiles"),BROWSER_USE_DEFAULT_USER_DATA_DIR:Dt.join(t,"profiles","default"),BROWSER_USE_EXTENSIONS_DIR:Dt.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:Hs(process.env.SKIP_LLM_API_KEY_VERIFICATION,!1),DEFAULT_LLM:process.env.DEFAULT_LLM||"",IN_DOCKER:r,IS_IN_EVALS:Hs(process.env.IS_IN_EVALS,!1),WIN_FONT_DIR:process.env.WIN_FONT_DIR||"C:\\Windows\\Fonts"}}var En,Ll,Wl=L(()=>{"use strict";En=null;Ll=!1});var Mt,Gs,io,js=L(()=>{"use strict";Mt={"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"},Gs={"2xs":10,xs:11,sm:12,"base-sm":13,base:14,md:15,lg:18,xl:20,"2xl":24,"3xl":28,"4xl":32,"5xl":36,"6xl":48,"7xl":56,"8xl":64,"9xl":72},io={text:40,title:56,goal:44}});function ch(i,e){return i.toLowerCase()==="input"&&e&&(e==="button"||e==="submit")?Vi.button:Vi[i.toLowerCase()]||Vi.default}function lh(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 Hl(i,e,t=1,n=!0){try{let s=await import("sharp").catch(()=>null);if(!s)return b.debug("Sharp library not available, returning original screenshot"),i;let r=Buffer.from(i,"base64"),o=await s.default(r).metadata(),a=o.width||1280,c=o.height||720,l=[];for(let[m,p]of e.entries())if(p.absolutePosition){let h=p.absolutePosition,f=Math.floor(h.x*t),y=Math.floor(h.y*t),T=Math.floor((h.x+(h.width||0))*t),x=Math.floor((h.y+(h.height||0))*t),S=Math.max(0,Math.min(f,a)),C=Math.max(0,Math.min(y,c)),v=Math.max(S,Math.min(T,a)),I=Math.max(C,Math.min(x,c)),w={x:S,y:C,width:v-S,height:I-C};if(w.width<2||w.height<2)continue;let E="";if(p.attributes){let D=["value","aria-label","title","placeholder","alt"];for(let $ of D)if(p.attributes[$]){E=p.attributes[$];break}}E||(E=p.text||""),E=E.trim();let P=n?E.length<3:!0;l.push({index:m,bbox:w,tagName:p.nodeName||"div",elementType:p.attributes?.type,text:P?String(m):void 0,backendNodeId:m})}if(l.length===0)return i;let d=uh(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 uh(i,e,t,n){let s=e,r=Math.max(Gs["2xs"],Math.min(Gs.xl,Math.round(s*.01))),o=Math.max(4,Math.min(10,Math.round(s*.005))),a=`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}">`,c=6,l=4,d=2;function g(m,p,h,f,y,T,x){let S="";if(m===h){let C=Math.min(p,f),v=Math.max(p,f);for(;C<v;){let I=Math.min(C+c,v);S+=`<line x1="${m}" y1="${C}" x2="${m}" y2="${I}" stroke="${y}" stroke-width="${x}"/>`,C+=c+l}}else{let C=Math.min(m,h),v=Math.max(m,h);for(;C<v;){let I=Math.min(C+c,v);S+=`<line x1="${C}" y1="${p}" x2="${I}" y2="${p}" stroke="${y}" stroke-width="${x}"/>`,C+=c+l}}return S}for(let m of i){let{bbox:p,tagName:h,elementType:f,text:y}=m,T=ch(h,f),x=Math.max(0,Math.floor(p.x)),S=Math.max(0,Math.floor(p.y)),C=Math.min(Math.floor(p.x+p.width),e),v=Math.min(Math.floor(p.y+p.height),t);if(C-x<=0||v-S<=0)continue;a+=g(x,S,C,S,T,void 0,d),a+=g(C,S,C,v,T,void 0,d),a+=g(C,v,x,v,T,void 0,d),a+=g(x,v,x,S,T,void 0,d);let I=C-x,w=v-S;if(y){let E=y.length*(r*.6),P=r,D=E+o*2,$=P+o*2,_=lh({x,y:S,width:I,height:w},E,P,o,e,t),N=_.x,k=_.y;a+=`
|
|
461
461
|
<rect x="${N}" y="${k}" width="${D}" height="${$}"
|
|
462
|
-
fill="${
|
|
462
|
+
fill="${T}" rx="3"/>
|
|
463
463
|
`;let M=N+Math.floor((D-E)/2),F=k+Math.floor(($+P*.7)/2);a+=`
|
|
464
464
|
<text x="${M+1}" y="${F+1}"
|
|
465
465
|
fill="rgba(0,0,0,0.4)" font-family="Arial, sans-serif" font-size="${r}" font-weight="bold">
|
|
@@ -470,10 +470,10 @@ ${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 Vi,Ul=L(()=>{"use strict";ut();js();Vi={button:"#8FA3B8",input:"#A0B4C8",select:"#B8C5D0",a:"#7A92A8",textarea:"#C0CCD8",default:"#9CADB8"}});import{chromium as ih}from"patchright";import{v4 as ah}from"uuid";function ch(){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 In,Xi=L(()=>{"use strict";ut();ji();zi();Al();to();so();Fl();js();Ul();In=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||ah(),this.options=e,this.eventBus=new Zr,this.registerEventHandlers()}registerEventHandlers(){this.eventBus.on(j.NAVIGATE_TO_URL,async e=>{await this.handleNavigateToUrl(e)}),this.eventBus.on(j.CLICK_ELEMENT,async e=>{await this.handleClickElement(e)}),this.eventBus.on(j.TYPE_TEXT,async e=>{await this.handleTypeText(e)}),this.eventBus.on(j.SCROLL,async e=>{await this.handleScroll(e)}),this.eventBus.on(j.BROWSER_STATE_REQUEST,async e=>{await this.handleBrowserStateRequest(e)}),this.eventBus.on(j.SCREENSHOT,async e=>{await this.handleScreenshot(e)}),this.eventBus.on(j.GO_BACK,async e=>{await this.handleGoBack(e)}),this.eventBus.on(j.GO_FORWARD,async e=>{await this.handleGoForward(e)}),this.eventBus.on(j.REFRESH,async e=>{await this.handleRefresh(e)}),this.eventBus.on(j.WAIT,async e=>{await this.handleWait(e)}),this.eventBus.on(j.SEND_KEYS,async e=>{await this.handleSendKeys(e)}),this.eventBus.on(j.UPLOAD_FILE,async e=>{await this.handleUploadFile(e)}),this.eventBus.on(j.GET_DROPDOWN_OPTIONS,async e=>{await this.handleGetDropdownOptions(e)}),this.eventBus.on(j.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=$l(),r;this.options.useRealChromeProfile?(r=ch(),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 ih.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 Dl(t,Cn(),!0),b.log(`[BrowserSession] Saved ${e.cookies.length} cookies`),!0}}catch(e){b.debug("[BrowserSession] Could not save storage state:",e.message)}return!1}async stop(){this.started&&(await this.saveStorageStateIfPossible(),this.context&&await this.context.close(),this.browser&&await this.browser.close(),this.pages.clear(),this.started=!1)}async injectStealthScripts(e){try{await e.addInitScript(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}}),Object.defineProperty(navigator,"plugins",{get:()=>{let r=[{name:"Chrome PDF Plugin",filename:"internal-pdf-viewer",description:"Portable Document Format"},{name:"Chrome PDF Viewer",filename:"mhjfbmdgcfjbbpaeojofohoefgiehjai",description:""},{name:"Native Client",filename:"internal-nacl-plugin",description:""}];return r.item=o=>r[o]||null,r.namedItem=o=>r.find(a=>a.name===o)||null,r.refresh=()=>{},r}}),Object.defineProperty(navigator,"languages",{get:()=>["en-US","en"]}),Object.getOwnPropertyNames(window).filter(r=>r.startsWith("cdc_")||r.startsWith("$cdc_")).forEach(r=>{try{delete window[r]}catch{}}),window.chrome||(window.chrome={}),window.chrome.runtime||(window.chrome.runtime={connect:()=>{},sendMessage:()=>{},onMessage:{addListener:()=>{}}});let n=navigator.permissions?.query?.bind(navigator.permissions);n&&(navigator.permissions.query=r=>r.name==="notifications"?Promise.resolve({state:"denied",onchange:null}):n(r));let s=console.debug;console.debug=function(...r){if(!r.some(o=>String(o).includes("Runtime.enable")))return s.apply(console,r)}}),b.log("🛡️ [BrowserSession] Stealth scripts injected")}catch(t){console.warn(`[BrowserSession] Failed to inject stealth scripts: ${t.message}`)}}async handleCloudflareTurnstile(e,t){let n=e||this.getCurrentPage(),s=t?.timeout??1e4,r=t?.delayBeforeClick??2e3;try{b.log("🔐 [BrowserSession] Checking for Cloudflare Turnstile...");let o=['iframe[src*="challenges.cloudflare.com"]','iframe[src*="turnstile"]',".cf-turnstile iframe","[data-turnstile-callback] iframe"],a=null;for(let m of o)try{let p=await n.waitForSelector(m,{timeout:3e3});if(p){a=p;break}}catch{}if(!a)return b.log("🔐 [BrowserSession] No Turnstile detected, continuing..."),!1;b.log("🔐 [BrowserSession] Turnstile detected, waiting before click..."),await new Promise(m=>setTimeout(m,r+Math.random()*1e3));let c=await a.boundingBox();if(!c)return console.warn("🔐 [BrowserSession] Could not get Turnstile bounding box"),!1;let l=c.x+25+Math.random()*10,d=c.y+c.height/2+(Math.random()-.5)*10;await this.humanLikeMouseMove(n,l,d),await new Promise(m=>setTimeout(m,100+Math.random()*200)),await n.mouse.click(l,d),b.log("🔐 [BrowserSession] Clicked Turnstile checkbox"),await new Promise(m=>setTimeout(m,3e3));let g=await n.evaluate(()=>[document.querySelector('[data-turnstile-success="true"]'),document.querySelector(".cf-turnstile-success"),document.querySelector('input[name="cf-turnstile-response"]')].some(p=>p!==null));return g?b.log("✅ [BrowserSession] Turnstile challenge passed!"):console.warn("⚠️ [BrowserSession] Turnstile may require manual verification"),g}catch(o){return console.warn(`[BrowserSession] Turnstile handling failed: ${o.message}`),!1}}async humanLikeMouseMove(e,t,n){let s=e.viewportSize()||{width:1280,height:720},r=s.width/2,o=s.height/2,a=20+Math.floor(Math.random()*10),c=r+(t-r)*.5+(Math.random()-.5)*100,l=o+(n-o)*.5+(Math.random()-.5)*100;for(let d=0;d<=a;d++){let g=d/a,m=Math.pow(1-g,2)*r+2*(1-g)*g*c+Math.pow(g,2)*t,p=Math.pow(1-g,2)*o+2*(1-g)*g*l+Math.pow(g,2)*n;await e.mouse.move(m,p);let h=5+Math.random()*15*(1-Math.abs(g-.5)*2);await new Promise(f=>setTimeout(f,h))}}async navigateWithCloudflareBypass(e,t){let n=t||this.getCurrentPage();await n.goto(e,{waitUntil:"domcontentloaded"}),await new Promise(r=>setTimeout(r,2e3)),await n.evaluate(()=>{let r=document.title.toLowerCase(),o=document.body?.innerText?.toLowerCase()||"";return r.includes("just a moment")||r.includes("attention required")||o.includes("checking your browser")||o.includes("verify you are human")||document.querySelector('iframe[src*="challenges.cloudflare.com"]')!==null})&&(b.log("🔐 [BrowserSession] Cloudflare challenge detected, attempting bypass..."),await this.handleCloudflareTurnstile(n),await new Promise(o=>setTimeout(o,3e3)),await n.evaluate(()=>document.title.toLowerCase().includes("just a moment"))&&console.warn("⚠️ [BrowserSession] Still on Cloudflare challenge page - may need manual intervention"))}async autoHandleCloudflareIfNeeded(e){try{await e.evaluate(()=>{let n=document.title.toLowerCase(),s=document.body?.innerText?.substring(0,500).toLowerCase()||"";return n.includes("just a moment")||n.includes("attention required")||n.includes("please wait")||s.includes("checking your browser")||s.includes("verify you are human")||s.includes("enable javascript and cookies")||document.querySelector('iframe[src*="challenges.cloudflare.com"]')!==null||document.querySelector(".cf-turnstile")!==null})&&(b.log("🔐 [BrowserSession] Cloudflare challenge auto-detected"),await this.handleCloudflareTurnstile(e))}catch{}}getCurrentPage(){if(this.currentPageId&&this.pages.has(this.currentPageId))return this.pages.get(this.currentPageId);let e=Array.from(this.pages.entries());if(e.length>0){let[t,n]=e[e.length-1];return console.warn(`🔄 Current page closed, switching to fallback page ${t}`),this.currentPageId=t,n}throw new Error("No active page")}async ensurePage(){try{return this.getCurrentPage()}catch{if(this.context){console.warn("🔄 No active page, creating new one...");let e=await this.context.newPage(),t=this.generatePageId();return this.pages.set(t,e),this.currentPageId=t,await this.injectStealthScripts(e),this.setupPageListeners(e,t),e}throw new Error("No active page and no browser context available")}}getPage(e){return this.pages.get(e)}getPageOrCurrent(e){return e&&this.pages.has(e)?this.pages.get(e):this.getCurrentPage()}async createTabForAgent(e){if(!this.context)throw new Error("Browser context not available - call start() first");let t=await this.context.newPage(),n=e?`agent_${e}_${Date.now()}`:this.generatePageId();return this.pages.set(n,t),await this.injectStealthScripts(t),this.setupPageListeners(t,n),b.log(`🆕 [BrowserSession] Created new tab ${n} for agent${e?` ${e}`:""}`),b.log(`📊 [BrowserSession] Total tabs: ${this.pages.size}`),{pageId:n,page:t}}async getStateForPage(e,t={}){let n=this.pages.get(e);if(!n)throw new Error(`Page ${e} not found`);let s=await this.getStateFromPage(n,t);return s.domState?.selectorMap&&this.pageSelectorMaps.set(e,s.domState.selectorMap),s}getSelectorMapForPage(e){let t=this.pageSelectorMaps.get(e);return t||this.cachedSelectorMap}getElementByIndexForPage(e,t){let n=this.getSelectorMapForPage(e);return n.has(t)?n.get(t):null}async waitForPageReadiness(e,t={}){let n=t.timeout??5e3,s=t.minElements??10,r=t.stabilityChecks??2,o=Date.now(),a="unknown",c=0,l=0,d=0;for(;Date.now()-o<n;)try{let g=await e.evaluate(()=>{let p=document.readyState,h=performance.getEntriesByType("resource").filter(C=>C.responseEnd===0||C.transferSize===0&&C.decodedBodySize===0&&!C.name.startsWith("data:")).length,y=document.querySelectorAll('a, button, input, select, textarea, [role="button"], [onclick], [tabindex]').length,w=!!(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:w}});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 Us(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 x=(await c.send("Page.getLayoutMetrics")).layoutViewport||{};l={width:x.clientWidth||n.viewportSize()?.width||1280,height:x.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 T=null,x=[];try{let v=await c.send("DOM.getContentQuads",{backendNodeId:d});v?.quads?.length>0&&(x=v.quads,b.debug(`Got ${x.length} quads from DOM.getContentQuads`))}catch(v){b.debug("getContentQuads failed:",v.message)}if(x.length===0)try{let v=await c.send("DOM.getBoxModel",{backendNodeId:d});if(v?.model?.content){let I=v.model.content;I.length>=8&&(x=[[I[0],I[1],I[2],I[3],I[4],I[5],I[6],I[7]]],b.debug("Got quad from DOM.getBoxModel"))}}catch(v){b.debug("getBoxModel failed:",v.message)}if(x.length===0)try{let I=(await c.send("DOM.resolveNode",{backendNodeId:d}))?.object?.objectId;if(I){let E=(await c.send("Runtime.callFunctionOn",{objectId:I,functionDeclaration:`function() {
|
|
473
|
+
`}}return a+="</svg>",a}var Vi,Gl=L(()=>{"use strict";ut();js();Vi={button:"#8FA3B8",input:"#A0B4C8",select:"#B8C5D0",a:"#7A92A8",textarea:"#C0CCD8",default:"#9CADB8"}});import{chromium as dh}from"patchright";import{v4 as gh}from"uuid";function mh(){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 In,Xi=L(()=>{"use strict";ut();ji();zi();Ol();so();oo();Wl();js();Gl();In=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||gh(),this.options=e,this.eventBus=new to,this.registerEventHandlers()}registerEventHandlers(){this.eventBus.on(j.NAVIGATE_TO_URL,async e=>{await this.handleNavigateToUrl(e)}),this.eventBus.on(j.CLICK_ELEMENT,async e=>{await this.handleClickElement(e)}),this.eventBus.on(j.TYPE_TEXT,async e=>{await this.handleTypeText(e)}),this.eventBus.on(j.SCROLL,async e=>{await this.handleScroll(e)}),this.eventBus.on(j.BROWSER_STATE_REQUEST,async e=>{await this.handleBrowserStateRequest(e)}),this.eventBus.on(j.SCREENSHOT,async e=>{await this.handleScreenshot(e)}),this.eventBus.on(j.GO_BACK,async e=>{await this.handleGoBack(e)}),this.eventBus.on(j.GO_FORWARD,async e=>{await this.handleGoForward(e)}),this.eventBus.on(j.REFRESH,async e=>{await this.handleRefresh(e)}),this.eventBus.on(j.WAIT,async e=>{await this.handleWait(e)}),this.eventBus.on(j.SEND_KEYS,async e=>{await this.handleSendKeys(e)}),this.eventBus.on(j.UPLOAD_FILE,async e=>{await this.handleUploadFile(e)}),this.eventBus.on(j.GET_DROPDOWN_OPTIONS,async e=>{await this.handleGetDropdownOptions(e)}),this.eventBus.on(j.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=Bl(),r;this.options.useRealChromeProfile?(r=mh(),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 dh.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 Nl(t,Cn(),!0),b.log(`[BrowserSession] Saved ${e.cookies.length} cookies`),!0}}catch(e){b.debug("[BrowserSession] Could not save storage state:",e.message)}return!1}async stop(){this.started&&(await this.saveStorageStateIfPossible(),this.context&&await this.context.close(),this.browser&&await this.browser.close(),this.pages.clear(),this.started=!1)}async injectStealthScripts(e){try{await e.addInitScript(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}}),Object.defineProperty(navigator,"plugins",{get:()=>{let r=[{name:"Chrome PDF Plugin",filename:"internal-pdf-viewer",description:"Portable Document Format"},{name:"Chrome PDF Viewer",filename:"mhjfbmdgcfjbbpaeojofohoefgiehjai",description:""},{name:"Native Client",filename:"internal-nacl-plugin",description:""}];return r.item=o=>r[o]||null,r.namedItem=o=>r.find(a=>a.name===o)||null,r.refresh=()=>{},r}}),Object.defineProperty(navigator,"languages",{get:()=>["en-US","en"]}),Object.getOwnPropertyNames(window).filter(r=>r.startsWith("cdc_")||r.startsWith("$cdc_")).forEach(r=>{try{delete window[r]}catch{}}),window.chrome||(window.chrome={}),window.chrome.runtime||(window.chrome.runtime={connect:()=>{},sendMessage:()=>{},onMessage:{addListener:()=>{}}});let n=navigator.permissions?.query?.bind(navigator.permissions);n&&(navigator.permissions.query=r=>r.name==="notifications"?Promise.resolve({state:"denied",onchange:null}):n(r));let s=console.debug;console.debug=function(...r){if(!r.some(o=>String(o).includes("Runtime.enable")))return s.apply(console,r)}}),b.log("🛡️ [BrowserSession] Stealth scripts injected")}catch(t){console.warn(`[BrowserSession] Failed to inject stealth scripts: ${t.message}`)}}async handleCloudflareTurnstile(e,t){let n=e||this.getCurrentPage(),s=t?.timeout??1e4,r=t?.delayBeforeClick??2e3;try{b.log("🔐 [BrowserSession] Checking for Cloudflare Turnstile...");let o=['iframe[src*="challenges.cloudflare.com"]','iframe[src*="turnstile"]',".cf-turnstile iframe","[data-turnstile-callback] iframe"],a=null;for(let m of o)try{let p=await n.waitForSelector(m,{timeout:3e3});if(p){a=p;break}}catch{}if(!a)return b.log("🔐 [BrowserSession] No Turnstile detected, continuing..."),!1;b.log("🔐 [BrowserSession] Turnstile detected, waiting before click..."),await new Promise(m=>setTimeout(m,r+Math.random()*1e3));let c=await a.boundingBox();if(!c)return console.warn("🔐 [BrowserSession] Could not get Turnstile bounding box"),!1;let l=c.x+25+Math.random()*10,d=c.y+c.height/2+(Math.random()-.5)*10;await this.humanLikeMouseMove(n,l,d),await new Promise(m=>setTimeout(m,100+Math.random()*200)),await n.mouse.click(l,d),b.log("🔐 [BrowserSession] Clicked Turnstile checkbox"),await new Promise(m=>setTimeout(m,3e3));let g=await n.evaluate(()=>[document.querySelector('[data-turnstile-success="true"]'),document.querySelector(".cf-turnstile-success"),document.querySelector('input[name="cf-turnstile-response"]')].some(p=>p!==null));return g?b.log("✅ [BrowserSession] Turnstile challenge passed!"):console.warn("⚠️ [BrowserSession] Turnstile may require manual verification"),g}catch(o){return console.warn(`[BrowserSession] Turnstile handling failed: ${o.message}`),!1}}async humanLikeMouseMove(e,t,n){let s=e.viewportSize()||{width:1280,height:720},r=s.width/2,o=s.height/2,a=20+Math.floor(Math.random()*10),c=r+(t-r)*.5+(Math.random()-.5)*100,l=o+(n-o)*.5+(Math.random()-.5)*100;for(let d=0;d<=a;d++){let g=d/a,m=Math.pow(1-g,2)*r+2*(1-g)*g*c+Math.pow(g,2)*t,p=Math.pow(1-g,2)*o+2*(1-g)*g*l+Math.pow(g,2)*n;await e.mouse.move(m,p);let h=5+Math.random()*15*(1-Math.abs(g-.5)*2);await new Promise(f=>setTimeout(f,h))}}async navigateWithCloudflareBypass(e,t){let n=t||this.getCurrentPage();await n.goto(e,{waitUntil:"domcontentloaded"}),await new Promise(r=>setTimeout(r,2e3)),await n.evaluate(()=>{let r=document.title.toLowerCase(),o=document.body?.innerText?.toLowerCase()||"";return r.includes("just a moment")||r.includes("attention required")||o.includes("checking your browser")||o.includes("verify you are human")||document.querySelector('iframe[src*="challenges.cloudflare.com"]')!==null})&&(b.log("🔐 [BrowserSession] Cloudflare challenge detected, attempting bypass..."),await this.handleCloudflareTurnstile(n),await new Promise(o=>setTimeout(o,3e3)),await n.evaluate(()=>document.title.toLowerCase().includes("just a moment"))&&console.warn("⚠️ [BrowserSession] Still on Cloudflare challenge page - may need manual intervention"))}async autoHandleCloudflareIfNeeded(e){try{await e.evaluate(()=>{let n=document.title.toLowerCase(),s=document.body?.innerText?.substring(0,500).toLowerCase()||"";return n.includes("just a moment")||n.includes("attention required")||n.includes("please wait")||s.includes("checking your browser")||s.includes("verify you are human")||s.includes("enable javascript and cookies")||document.querySelector('iframe[src*="challenges.cloudflare.com"]')!==null||document.querySelector(".cf-turnstile")!==null})&&(b.log("🔐 [BrowserSession] Cloudflare challenge auto-detected"),await this.handleCloudflareTurnstile(e))}catch{}}getCurrentPage(){if(this.currentPageId&&this.pages.has(this.currentPageId))return this.pages.get(this.currentPageId);let e=Array.from(this.pages.entries());if(e.length>0){let[t,n]=e[e.length-1];return console.warn(`🔄 Current page closed, switching to fallback page ${t}`),this.currentPageId=t,n}throw new Error("No active page")}async ensurePage(){try{return this.getCurrentPage()}catch{if(this.context){console.warn("🔄 No active page, creating new one...");let e=await this.context.newPage(),t=this.generatePageId();return this.pages.set(t,e),this.currentPageId=t,await this.injectStealthScripts(e),this.setupPageListeners(e,t),e}throw new Error("No active page and no browser context available")}}getPage(e){return this.pages.get(e)}getPageOrCurrent(e){return e&&this.pages.has(e)?this.pages.get(e):this.getCurrentPage()}async createTabForAgent(e){if(!this.context)throw new Error("Browser context not available - call start() first");let t=await this.context.newPage(),n=e?`agent_${e}_${Date.now()}`:this.generatePageId();return this.pages.set(n,t),await this.injectStealthScripts(t),this.setupPageListeners(t,n),b.log(`🆕 [BrowserSession] Created new tab ${n} for agent${e?` ${e}`:""}`),b.log(`📊 [BrowserSession] Total tabs: ${this.pages.size}`),{pageId:n,page:t}}async getStateForPage(e,t={}){let n=this.pages.get(e);if(!n)throw new Error(`Page ${e} not found`);let s=await this.getStateFromPage(n,t);return s.domState?.selectorMap&&this.pageSelectorMaps.set(e,s.domState.selectorMap),s}getSelectorMapForPage(e){let t=this.pageSelectorMaps.get(e);return t||this.cachedSelectorMap}getElementByIndexForPage(e,t){let n=this.getSelectorMapForPage(e);return n.has(t)?n.get(t):null}async waitForPageReadiness(e,t={}){let n=t.timeout??5e3,s=t.minElements??10,r=t.stabilityChecks??2,o=Date.now(),a="unknown",c=0,l=0,d=0;for(;Date.now()-o<n;)try{let g=await e.evaluate(()=>{let p=document.readyState,h=performance.getEntriesByType("resource").filter(x=>x.responseEnd===0||x.transferSize===0&&x.decodedBodySize===0&&!x.name.startsWith("data:")).length,y=document.querySelectorAll('a, button, input, select, textarea, [role="button"], [onclick], [tabindex]').length,T=!!(document.querySelector('[class*="loading"]')||document.querySelector('[class*="skeleton"]')||document.querySelector('[class*="spinner"]')||document.querySelector('[class*="Spinner"]')||document.querySelector('[class*="Loading"]')||document.querySelector('[class*="Skeleton"]')||document.querySelector('[aria-busy="true"]')||document.querySelector('[data-loading="true"]')||document.querySelector(".placeholder"));return{readyState:p,pendingRequests:h,elementCount:y,hasLoadingIndicator:T}});if(g.elementCount===l&&g.elementCount>0?d++:d=0,a=g.readyState,c=g.pendingRequests,l=g.elementCount,(g.readyState==="complete"||g.readyState==="interactive"&&d>=r)&&g.pendingRequests<=2&&g.elementCount>=s&&!g.hasLoadingIndicator&&d>=r)return b.debug(`✅ Page ready: readyState=${g.readyState}, pending=${g.pendingRequests}, elements=${g.elementCount}, stable=${d}`),{ready:!0,pendingRequests:g.pendingRequests,readyState:g.readyState,elementCount:g.elementCount};await new Promise(p=>setTimeout(p,100))}catch{d=0,await new Promise(m=>setTimeout(m,100))}return b.debug(`⚠️ Page readiness timeout: readyState=${a}, pending=${c}, elements=${l}, stable=${d}`),{ready:!1,pendingRequests:c,readyState:a,elementCount:l}}async getStateFromPage(e,t={}){let n=await this.waitForPageReadiness(e,{timeout:5e3,minElements:5});n.ready||(b.debug(`⚠️ Proceeding with DOM extraction despite page not fully ready (readyState=${n.readyState})`),n.pendingRequests>0&&await new Promise(c=>setTimeout(c,300)));let s=await e.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,pageWidth:document.documentElement.scrollWidth,pageHeight:document.documentElement.scrollHeight})),r={viewportWidth:s.viewportWidth,viewportHeight:s.viewportHeight,pageWidth:s.pageWidth,pageHeight:s.pageHeight,scrollX:s.scrollX,scrollY:s.scrollY,pixelsAbove:s.scrollY,pixelsBelow:Math.max(0,s.pageHeight-s.viewportHeight-s.scrollY),pixelsLeft:s.scrollX,pixelsRight:Math.max(0,s.pageWidth-s.viewportWidth-s.scrollX)},o={root:null,selectorMap:new Map};if(t.includeDom!==!1)try{let c=new Us(e,{paintOrderFiltering:!0,crossOriginIframes:!1}),l=await c.getPageState({includeScreenshot:!1,useCDPAccessibility:!0}),d=l.domTree,g=l.selectorMap;o={root:this.createSimplifiedNode(d,g),selectorMap:g,llmRepresentation:(m=[])=>c.formatDOMForLLM(d,0,!0,g)},await c.close()}catch(c){b.debug("DOM extraction failed:",c.message)}let a={domState:o,url:e.url(),title:await e.title(),tabs:await this.getAllTabs(),pageInfo:r,pixelsAbove:r.pixelsAbove,pixelsBelow:r.pixelsBelow,browserErrors:[],isPdfViewer:e.url().endsWith(".pdf")||e.url().includes("chrome-extension://")&&e.url().includes("pdf"),pendingNetworkRequests:[],paginationButtons:[]};if(t.includeScreenshot!==!1)try{let c=await e.screenshot({type:"png"});a.screenshot=c.toString("base64")}catch(c){b.debug("Screenshot failed:",c.message)}return a}switchToPage(e){return this.pages.has(e)?(this.currentPageId=e,b.log(`🔄 [BrowserSession] Switched to tab ${e}`),!0):(console.warn(`⚠️ [BrowserSession] Cannot switch to tab ${e} - not found`),!1)}getTabCount(){return this.pages.size}getAllTabIds(){return Array.from(this.pages.keys())}getCurrentPageId(){return this.currentPageId}hasTab(e){return this.pages.has(e)}generatePageId(){return`page_${Date.now()}_${Math.random().toString(36).substring(7)}`}setupPageListeners(e,t){e.on("close",()=>{this.pages.delete(t),this.pageSelectorMaps.delete(t);let n=this.pageCdpSessions.get(t);if(n&&(n.detach().catch(()=>{}),this.pageCdpSessions.delete(t)),this.currentPageId===t){let s=Array.from(this.pages.keys());this.currentPageId=s[0],this.cdpSession=null}b.log(`🗑️ [BrowserSession] Page ${t} closed, cleaned up resources`)}),e.on("framenavigated",n=>{if(n===e.mainFrame()){if(this.cdpSession=null,this.cachedSelectorMap.clear(),t){let s=this.pageSelectorMaps.get(t);s&&s.clear()}b.debug(`🔄 [framenavigated] Cleared cached state for page ${t||"main"}`)}}),e.on("domcontentloaded",()=>{if(this.cachedSelectorMap.clear(),t){let n=this.pageSelectorMaps.get(t);n&&n.clear()}b.debug(`🔄 [domcontentloaded] Cleared cached state for page ${t||"main"}`)}),e.on("request",n=>{let s=n.url();!s.startsWith("data:")&&!s.startsWith("blob:")&&this.pendingRequests.add(s)}),e.on("requestfinished",n=>{this.pendingRequests.delete(n.url())}),e.on("requestfailed",n=>{this.pendingRequests.delete(n.url())}),e.on("download",async n=>{try{let s=n.suggestedFilename(),r=this.options.downloadsPath?`${this.options.downloadsPath}/${s}`:s;await n.saveAs(r),this._downloadedFiles.push(r),b.log(`📥 Downloaded: ${r}`)}catch(s){console.error(`Failed to save download: ${s.message}`)}})}setNetworkIdleConfig(e){this.networkIdleConfig={...this.networkIdleConfig,...e}}getPendingRequestCount(){return this.pendingRequests.size}async waitForNetworkIdle(e){let t={idleTime:e?.idleTime??this.networkIdleConfig.idleTime,maxInflight:e?.maxInflight??this.networkIdleConfig.maxInflight,timeout:e?.timeout??this.networkIdleConfig.timeout,pollInterval:e?.pollInterval??this.networkIdleConfig.pollInterval},n=Date.now(),s=null;for(;;){let r=(Date.now()-n)/1e3;if(r>=t.timeout)return b.debug(`Network idle timeout after ${r.toFixed(2)}s`),!1;let o=this.pendingRequests.size;if(o<=t.maxInflight){if(s===null&&(s=Date.now()),(Date.now()-s)/1e3>=t.idleTime)return b.debug(`Network idle achieved: ${o} requests for ${t.idleTime}s`),!0}else s=null;await new Promise(a=>setTimeout(a,t.pollInterval*1e3))}}isNetworkIdle(e){let t=e??this.networkIdleConfig.maxInflight;return this.pendingRequests.size<=t}extractDomain(e){try{return new URL(e).hostname}catch{return""}}getSmartNavigationTimeout(e,t){let n=this.extractDomain(e),s=this.extractDomain(t),r=n===s&&n!=="",o=r?8e3:15e3;return b.debug(`Smart navigation timeout: ${o}ms (${r?"same":"different"} domain)`),o}async handleNavigateToUrl(e){try{let t=e.waitUntil||"load",n=e.newTab||!1,s=e.pageId,r=s?this.getPageOrCurrent(s):await this.ensurePage();if(!s){if(n){let c=r.url();this.isNewTabPage(c)&&(b.debug(`Already on new tab page (${c}), reusing instead of creating new tab`),n=!1)}if(!n){let c=this.findTabByUrl(e.url);if(c&&c!==this.currentPageId){b.debug(`URL already open in tab ${c}, switching to it`),this.currentPageId=c,r=await this.ensurePage(),this.eventBus.respondToEvent(e._eventId,null);return}}if(n){let c=await this.findOrCreateNewTab();c&&(r=c)}}let o=r.url(),a=e.timeoutMs??this.getSmartNavigationTimeout(o,e.url);await r.goto(e.url,{waitUntil:t,timeout:a}),await this.autoHandleCloudflareIfNeeded(r),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}isNewTabPage(e){return e==="about:blank"||e==="chrome://new-tab-page/"||e==="chrome://newtab/"||e.startsWith("chrome://newtab")}findTabByUrl(e){for(let[t,n]of this.pages.entries())if(n.url()===e)return t;return null}async findOrCreateNewTab(){for(let[e,t]of this.pages.entries())if(e!==this.currentPageId&&this.isNewTabPage(t.url()))return b.debug(`Found existing about:blank tab ${e}, reusing it`),this.currentPageId=e,t;if(this.context)try{let e=await this.context.newPage(),t=this.generatePageId();return this.pages.set(t,e),this.currentPageId=t,await this.injectStealthScripts(e),this.setupPageListeners(e,t),b.debug(`Created new tab ${t}`),e}catch(e){console.error("Failed to create new tab:",e)}return null}async handleClickElement(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage(),s=e.node,r=e.button||"left",o=(s.nodeName||"").toLowerCase(),a=(s.attributes?.type||"").toLowerCase();if(o==="select")throw new Error("Cannot click on <select> elements. Use dropdown options action instead.");if(o==="input"&&a==="file")throw new Error("Cannot click on file input element. Use upload_file action instead.");let c=t?await this.getCdpSessionForPage(t):await this.getCdpSession(),l={width:1280,height:720};try{let C=(await c.send("Page.getLayoutMetrics")).layoutViewport||{};l={width:C.clientWidth||n.viewportSize()?.width||1280,height:C.clientHeight||n.viewportSize()?.height||720},b.debug(`📐 [click] Viewport from CDP: ${l.width}x${l.height}`)}catch{b.debug("Failed to get layout metrics, using page.viewportSize()"),l=n.viewportSize()||{width:1280,height:720}}let d=s.backendNodeId;if(b.log(`🔍 [click] Using backendNodeId: ${d} for element: ${o}`),d&&d>0)try{let S=null,C=[];try{let v=await c.send("DOM.getContentQuads",{backendNodeId:d});v?.quads?.length>0&&(C=v.quads,b.debug(`Got ${C.length} quads from DOM.getContentQuads`))}catch(v){b.debug("getContentQuads failed:",v.message)}if(C.length===0)try{let v=await c.send("DOM.getBoxModel",{backendNodeId:d});if(v?.model?.content){let I=v.model.content;I.length>=8&&(C=[[I[0],I[1],I[2],I[3],I[4],I[5],I[6],I[7]]],b.debug("Got quad from DOM.getBoxModel"))}}catch(v){b.debug("getBoxModel failed:",v.message)}if(C.length===0)try{let I=(await c.send("DOM.resolveNode",{backendNodeId:d}))?.object?.objectId;if(I){let E=(await c.send("Runtime.callFunctionOn",{objectId:I,functionDeclaration:`function() {
|
|
474
474
|
const rect = this.getBoundingClientRect();
|
|
475
475
|
return { x: rect.left, y: rect.top, width: rect.width, height: rect.height };
|
|
476
|
-
}`,returnByValue:!0}))?.result?.value;if(E){let P=E.x,D=E.y,$=E.width,R=E.height;
|
|
476
|
+
}`,returnByValue:!0}))?.result?.value;if(E){let P=E.x,D=E.y,$=E.width,R=E.height;C=[[P,D,P+$,D,P+$,D+R,P,D+R]],b.debug("Got quad from getBoundingClientRect")}}}catch(v){b.debug("JS getBoundingClientRect failed:",v.message)}if(C.length===0){b.debug("Could not get element geometry from any method, falling back to JavaScript click");try{await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_no_quads"});return}catch(v){b.debug("JS click for no-quads case failed:",v.message)}}if(C.length>0){let v=null,I=0;for(let P of C){if(P.length<8)continue;let D=[P[0],P[2],P[4],P[6]],$=[P[1],P[3],P[5],P[7]],R=Math.min(...D),_=Math.max(...D),N=Math.min(...$),k=Math.max(...$);if(_<0||k<0||R>l.width||N>l.height)continue;let M=Math.max(0,R),F=Math.min(l.width,_),B=Math.max(0,N),H=Math.min(l.height,k),V=F-M,le=H-B,W=V*le;W>I&&(I=W,v=P)}if(!v){b.debug("🔄 [click] No visible quad found, scrolling element into view first...");try{await c.send("DOM.scrollIntoViewIfNeeded",{backendNodeId:d}),await new Promise(P=>setTimeout(P,100))}catch{}try{let P=await c.send("DOM.getContentQuads",{backendNodeId:d});if(P?.quads?.length>0){C=P.quads;for(let D of C){if(D.length<8)continue;let $=[D[0],D[2],D[4],D[6]],R=[D[1],D[3],D[5],D[7]],_=Math.min(...$),N=Math.max(...$),k=Math.min(...R),M=Math.max(...R);if(N<0||M<0||_>l.width||k>l.height)continue;let F=Math.max(0,_),B=Math.min(l.width,N),H=Math.max(0,k),V=Math.min(l.height,M),le=(B-F)*(V-H);le>I&&(I=le,v=D)}}}catch{}if(!v){b.debug("⚠️ [click] Still no visible quad after scroll, falling back to JS click"),await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_no_visible_quad"});return}}let w=(v[0]+v[2]+v[4]+v[6])/4,E=(v[1]+v[3]+v[5]+v[7])/4;w=Math.max(0,Math.min(l.width-1,w)),E=Math.max(0,Math.min(l.height-1,E)),S={x:w,y:E},b.log(`🖱️ [click] Calculated center: (${w.toFixed(1)}, ${E.toFixed(1)})`)}if(S)try{await c.send("DOM.scrollIntoViewIfNeeded",{backendNodeId:d}),await new Promise(v=>setTimeout(v,50));try{let v=await c.send("DOM.getContentQuads",{backendNodeId:d});if(v?.quads?.length>0){let I=v.quads[0];if(I.length>=8){let w=(I[0]+I[2]+I[4]+I[6])/4,E=(I[1]+I[3]+I[5]+I[7])/4;w>=0&&w<=l.width&&E>=0&&E<=l.height?(S={x:w,y:E},b.debug(`📍 [click] Updated coordinates after scroll: (${w.toFixed(1)}, ${E.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(S){if(await this.checkElementOcclusionCDP(c,d,S.x,S.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:S.x,y:S.y}),await new Promise(w=>setTimeout(w,50));let I=!1;try{await Promise.race([c.send("Input.dispatchMouseEvent",{type:"mousePressed",x:S.x,y:S.y,button:r,clickCount:1}),new Promise((w,E)=>setTimeout(()=>E(new Error("mousePressed timeout")),3e3))]),I=!0}catch(w){b.debug("mousePressed timed out (possibly dialog):",w.message)}I&&await new Promise(w=>setTimeout(w,80));try{await Promise.race([c.send("Input.dispatchMouseEvent",{type:"mouseReleased",x:S.x,y:S.y,button:r,clickCount:1}),new Promise((w,E)=>setTimeout(()=>E(new Error("mouseReleased timeout")),5e3))])}catch(w){b.debug("mouseReleased timed out:",w.message)}this.eventBus.respondToEvent(e._eventId,{success:!0,method:"cdp_click",backendNodeId:d,coordinates:S});return}}catch(S){b.debug("CDP click failed, falling back to JavaScript click:",S.message);try{await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click_cdp_error"});return}catch(C){b.debug("JS click also failed:",C.message)}}finally{try{await(t?await this.getCdpSessionForPage(t):await this.getCdpSession()).send("Runtime.runIfWaitingForDebugger",{})}catch{}}if(!s.absolutePosition){b.debug("No coordinates available, attempting final JS click fallback"),await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click"});return}let{x:g,y:m,width:p,height:h}=s.absolutePosition,f=g+(p||0)/2,y=m+(h||0)/2;if(f<0||y<0||f>l.width||y>l.height){b.debug("Element out of viewport, scrolling into view");try{let S=Math.max(0,m-l.height/2);await n.evaluate(v=>window.scrollTo(0,v),S),await new Promise(v=>setTimeout(v,100));let C=await n.evaluate(()=>({x:window.scrollX,y:window.scrollY}));y=m-C.y+(h||0)/2,f=g-C.x+(p||0)/2}catch(S){b.debug("Failed to scroll element into view:",S)}}f=Math.max(1,Math.min(l.width-1,f)),y=Math.max(1,Math.min(l.height-1,y));let x=!1;if(d&&d>0&&(x=await this.checkElementOcclusionCDP(c,d,f,y)),x){b.debug("Element is occluded, falling back to JavaScript click"),await this.fallbackJSClick(n,s,t),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"js_click"});return}await n.mouse.move(f,y),await new Promise(S=>setTimeout(S,50)),await n.mouse.click(f,y,{button:r}),this.eventBus.respondToEvent(e._eventId,{success:!0,method:"mouse_click",coordinates:{x:f,y}})}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async checkElementOcclusion(e,t,n,s){try{return await e.evaluate(({x:o,y:a,nodeId:c,nodeName:l})=>{let d=document.elementFromPoint(o,a);if(!d)return!0;let g=l?.toUpperCase()||"";return!(d.tagName===g||d.closest(g)||d.querySelector(g))},{x:n,y:s,nodeId:t.nodeId,nodeName:t.nodeName})}catch{return!1}}async checkElementOcclusionCDP(e,t,n,s){try{let o=(await e.send("DOM.resolveNode",{backendNodeId:t}))?.object?.objectId;if(!o)return b.debug("Could not resolve target element, assuming occluded"),!0;let c=(await e.send("Runtime.callFunctionOn",{objectId:o,functionDeclaration:`
|
|
477
477
|
function(x, y) {
|
|
478
478
|
const getElementInfo = (el) => {
|
|
479
479
|
return {
|
|
@@ -564,7 +564,7 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
|
|
|
564
564
|
} catch (e) {
|
|
565
565
|
return {success: false, error: e.message};
|
|
566
566
|
}
|
|
567
|
-
}`,returnByValue:!0});if(c.result?.value?.success)return b.debug(`Scrolled ${c.result.value.element} by ${c.result.value.scrolled}px`),!0}}catch(a){b.debug("Failed to scroll element container:",a)}return!1}catch(s){return b.debug("scrollElementContainer error:",s),!1}}async handleScreenshot(e){try{let t=e.pageId,r=(await(t?this.getPageOrCurrent(t):await this.ensurePage()).screenshot({fullPage:e.fullPage,clip:e.clip,type:"png"})).toString("base64");this.eventBus.respondToEvent(e._eventId,r)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleBrowserStateRequest(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage(),s=await n.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,pageWidth:document.documentElement.scrollWidth,pageHeight:document.documentElement.scrollHeight})),r={viewportWidth:s.viewportWidth,viewportHeight:s.viewportHeight,pageWidth:s.pageWidth,pageHeight:s.pageHeight,scrollX:s.scrollX,scrollY:s.scrollY,pixelsAbove:s.scrollY,pixelsBelow:Math.max(0,s.pageHeight-s.viewportHeight-s.scrollY),pixelsLeft:s.scrollX,pixelsRight:Math.max(0,s.pageWidth-s.viewportWidth-s.scrollX)},o={root:null,selectorMap:new Map};if(e.includeDom!==!1)try{let c=new Us(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 Ll(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 w of Array.from(m)){let C=w,T=(C.innerText?.trim()||"").toLowerCase(),x=(C.getAttribute("data-value")||"").toLowerCase();if(!(!T&&!x)&&(T&&f.push(C.innerText?.trim()||""),!(C.getAttribute("aria-disabled")==="true"||C.hasAttribute("disabled")))){if(T===g||x===g){p=C;break}!h&&(T.includes(g)||x.includes(g))&&(h=C)}}let y=p||h;return y?(y.click(),y.dispatchEvent(new Event("input",{bubbles:!0})),y.dispatchEvent(new Event("change",{bubbles:!0})),{found:!0,selectedText:y.innerText?.trim()}):{found:!1,availableOptions:f.slice(0,20)}},e.text);if(!l.found){let d=l.availableOptions||[],g=d.length>0?` Available options: ${d.join(", ")}`:"";throw new Error(`Option "${e.text}" not found in dropdown.${g}`)}this.eventBus.respondToEvent(e._eventId,{success:!0,selectedText:e.text})}}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async getAllTabs(){let e=[];for(let[t,n]of this.pages.entries())e.push({targetId:t,url:n.url(),title:await n.title()});return e}async getState(e={}){return this.eventBus.dispatch(j.BROWSER_STATE_REQUEST,{includeScreenshot:e.includeScreenshot??!0,includeDom:e.includeDom??!0,includeRecentEvents:e.includeRecentEvents??!1},ee.BROWSER_STATE_REQUEST)}async navigate(e,t={}){return this.eventBus.dispatch(j.NAVIGATE_TO_URL,{url:e,...t},ee.NAVIGATE_TO_URL)}async screenshot(e={}){return this.eventBus.dispatch(j.SCREENSHOT,e,ee.SCREENSHOT)}async goBack(){return this.eventBus.dispatch(j.GO_BACK,{},ee.GO_BACK)}async goForward(){return this.eventBus.dispatch(j.GO_FORWARD,{},ee.GO_FORWARD)}async refresh(){return this.eventBus.dispatch(j.REFRESH,{},ee.REFRESH)}async getElementByIndex(e){return this.cachedSelectorMap&&this.cachedSelectorMap.has(e)?this.cachedSelectorMap.get(e):null}updateCachedSelectorMap(e){this.cachedSelectorMap=e}async getSelectorMap(){return this.cachedSelectorMap}clearCachedState(){b.debug("🔄 Clearing cached browser state (page navigation detected)"),this.cachedSelectorMap.clear(),this.cachedBrowserStateSummary=null;for(let[e,t]of this.pageSelectorMaps)t.clear();this.pendingRequests.clear()}async getIndexById(e){for(let[t,n]of this.cachedSelectorMap.entries())if(n.attributes&&n.attributes.id===e)return t;return null}async getIndexByClass(e){for(let[t,n]of this.cachedSelectorMap.entries())if(n.attributes&&(n.attributes.class||"").split(" ").includes(e))return t;return null}isFileInput(e){return e.nodeName?.toUpperCase()==="INPUT"&&e.attributes?.type?.toLowerCase()==="file"}async clickElement(e){return this.eventBus.dispatch(j.CLICK_ELEMENT,{node:e},ee.CLICK_ELEMENT)}async typeText(e,t){return this.eventBus.dispatch(j.TYPE_TEXT,{text:e,node:t},ee.TYPE_TEXT)}async scroll(e,t,n){return this.eventBus.dispatch(j.SCROLL,{direction:e,amount:t||500},ee.SCROLL)}async getTargetIdFromTabId(e){let t=await this.getAllTabs();for(let n of t)if(n.targetId.endsWith(e))return n.targetId;throw new Error(`No tab found with ID ending in: ${e}`)}async switchTab(e){let t=e.length===4?await this.getTargetIdFromTabId(e):e;this.currentPageId=t}async closeTab(e){let t=e.length===4?await this.getTargetIdFromTabId(e):e,n=this.pages.get(t);if(n)try{await n.close(),this.pages.delete(t),this.pageSelectorMaps.delete(t);let s=this.pageCdpSessions.get(t);if(s&&(s.detach().catch(()=>{}),this.pageCdpSessions.delete(t)),this.currentPageId===t){let r=Array.from(this.pages.keys());this.currentPageId=r.length>0?r[0]:void 0,b.log("🔄 [BrowserSession] Switched to another tab after closing current")}return b.log(`🗑️ [BrowserSession] Closed tab ${e}. Remaining tabs: ${this.pages.size}`),!0}catch(s){return console.error(`❌ [BrowserSession] Error closing tab ${e}: ${s.message}`),!1}return!1}async uploadFile(e,t){let n=await this.getElementByIndex(e);if(!n)throw new Error(`Element at index ${e} not found`);if(!this.isFileInput(n))throw new Error(`Element at index ${e} is not a file input`);return this.eventBus.dispatch(j.UPLOAD_FILE,{node:n,filePath:t},ee.UPLOAD_FILE||3e4)}async getDropdownOptions(e){let t=await this.getElementByIndex(e);if(!t)throw new Error(`Element at index ${e} not found`);return this.eventBus.dispatch(j.GET_DROPDOWN_OPTIONS,{node:t},ee.GET_DROPDOWN_OPTIONS||15e3)}async selectDropdownOption(e,t){let n=await this.getElementByIndex(e);if(!n)throw new Error(`Element at index ${e} not found`);return this.eventBus.dispatch(j.SELECT_DROPDOWN_OPTION,{node:n,text:t},ee.SELECT_DROPDOWN_OPTION||8e3)}async sendKeys(e){return this.eventBus.dispatch(j.SEND_KEYS,{keys:e.join("")},ee.SEND_KEYS)}async evaluate(e){return(await this.ensurePage()).evaluate(e)}get page(){return this.getCurrentPage()}get downloadedFiles(){return[...this._downloadedFiles]}async getCdpSession(){let e=await this.ensurePage();if(this.cdpSession)try{return await this.cdpSession.send("Runtime.evaluate",{expression:"1",returnByValue:!0}),this.cdpSession}catch(t){b.debug("CDP session stale, creating new one:",t.message);try{await this.cdpSession.detach()}catch{}this.cdpSession=null}return this.cdpSession=await e.context().newCDPSession(e),this.cdpSession}async getCdpSessionForPage(e){let t=this.pages.get(e);if(!t)throw new Error(`Page ${e} not found`);let n=this.pageCdpSessions.get(e);if(n)try{return await n.send("Runtime.evaluate",{expression:"1",returnByValue:!0}),n}catch(r){b.debug(`CDP session for page ${e} stale, creating new one:`,r.message);try{await n.detach()}catch{}this.pageCdpSessions.delete(e)}let s=await t.context().newCDPSession(t);return this.pageCdpSessions.set(e,s),s}async closeCdpSession(){this.cdpSession&&(await this.cdpSession.detach(),this.cdpSession=null)}async closeCdpSessionForPage(e){let t=this.pageCdpSessions.get(e);if(t){try{await t.detach()}catch{}this.pageCdpSessions.delete(e)}}async cookies(e){if(!this.context)throw new Error("Browser context not initialized");return this.context.cookies(e)}async setCookies(e){if(!this.context)throw new Error("Browser context not initialized");await this.context.addCookies(e)}async clearCookies(){if(!this.context)throw new Error("Browser context not initialized");await this.context.clearCookies()}async exportStorageState(e){if(!this.context)throw new Error("Browser context not initialized");return e?this.context.storageState({path:e}):this.context.storageState()}async importStorageState(e){console.warn("Storage state import is only supported during browser session initialization")}async getAllFrames(e=!0){let t=new Map,n=new Map;try{let s=await this.ensurePage(),r=await s.context().newCDPSession(s),c=((await r.send("Target.getTargets")).targetInfos||[]).filter(l=>!!(l.type==="page"||l.type==="iframe"&&e));for(let l of c){let d=l.targetId;try{let g;try{g=(await r.send("Target.attachToTarget",{targetId:d,flatten:!0})).sessionId}catch(m){b.debug(`Could not attach to target ${d}:`,m);continue}if(g){n.set(d,g),await r.send("Page.enable",void 0,g);let p=(await r.send("Page.getFrameTree",void 0,g)).frameTree;if(p){let h=(f,y=null)=>{let w=f.frame||{},C=w.id;if(C){let T=w.parentId||y,x={...w,frameTargetId:d,parentFrameId:T,childFrameIds:[],isCrossOrigin:l.type==="iframe"},v=w.crossOriginIsolatedContextType;v&&v!=="NotIsolated"&&(x.isCrossOrigin=!0);let I=f.childFrames||[];for(let S of I){let E=S.frame||{};E.id&&x.childFrameIds.push(E.id)}if(t.has(C)){let S=t.get(C);l.type==="iframe"&&(S.frameTargetId=d,S.isCrossOrigin=!0)}else t.set(C,x);for(let S of I)h(S,C)}};h(p)}}}catch(g){b.debug(`Failed to get frame tree for target ${d}:`,g)}}}catch(s){b.debug("Failed to get frames via CDP, falling back to Playwright:",s);let o=(await this.ensurePage()).mainFrame(),a=(c,l)=>{let d=c.name()||`frame_${t.size}`;t.set(d,{id:d,url:c.url(),name:c.name(),parentFrameId:l,isCrossOrigin:!1});for(let g of c.childFrames())a(g,d)};a(o,null)}return{frames:t,targetSessions:n}}async findFrameById(e){let{frames:t}=await this.getAllFrames();return t.get(e)||null}async getFrameByUrl(e){let n=(await this.ensurePage()).frames();for(let s of n)if(s.url()===e||s.url().includes(e))return s;return null}async removeHighlights(){if(this.highlightsAdded)try{await(await this.ensurePage()).evaluate(()=>{let t=document.getElementById("browser-use-debug-highlights");t&&t.remove();let n=document.getElementById("browser-use-highlights");n&&n.remove(),document.querySelectorAll("[data-browser-use-highlight]").forEach(o=>{o.remove()}),document.querySelectorAll("[data-browser-use-interaction-highlight]").forEach(o=>{o.remove()})}),this.highlightsAdded=!1}catch(e){b.debug(`Failed to remove highlights: ${e.message}`)}}async addHighlights(e){try{let t=await this.ensurePage();await this.removeHighlights(),await new Promise(s=>setTimeout(s,50));let n=[];for(let[s,r]of e.entries())if(r.absolutePosition){let{x:o,y:a,width:c,height:l}=r.absolutePosition;c>0&&l>0&&n.push({index:s,x:o,y:a,width:c,height:l,elementName:r.nodeName||"div",backendNodeId:r.backendNodeId||s})}if(n.length===0){b.debug("No valid elements to highlight");return}await t.evaluate(s=>{let r=document.getElementById("browser-use-debug-highlights");r&&r.remove(),document.querySelectorAll("[data-browser-use-highlight]").forEach(d=>d.remove());let a=2147483647,c=document.createElement("div");c.id="browser-use-debug-highlights",c.setAttribute("data-browser-use-highlight","container"),c.style.cssText=`
|
|
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 Us(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 Hl(l,o.selectorMap,d,!0)}catch(d){b.debug("Screenshot highlighting failed, using original:",d.message)}a.screenshot=l}this.cachedBrowserStateSummary=a,this.eventBus.respondToEvent(e._eventId,a)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}createSimplifiedNode(e,t){if(!e||e.length===0)return null;let n=r=>{if(!r)return null;let o=r.backendNodeId||0,c={isInteractive:t.has(o),isShadowHost:r.isShadowHost||!1,isNew:!1,shouldDisplay:!0,ignoredByPaintOrder:!1,excludedByParent:!1,isCompoundComponent:!1,children:[],originalNode:{nodeId:r.nodeId||0,backendNodeId:o,sessionId:r.sessionId||"",frameId:r.frameId||"",targetId:r.targetId||"",nodeType:r.nodeType||1,nodeName:r.nodeName||"",nodeValue:r.nodeValue||"",attributes:r.attributes||{}}};if(r.children&&Array.isArray(r.children))for(let l of r.children){let d=n(l);d&&c.children.push(d)}if(r.shadowRoots&&Array.isArray(r.shadowRoots))for(let l of r.shadowRoots){let d=n(l);d&&c.children.push(d)}if(r.contentDocument){let l=n(r.contentDocument);l&&c.children.push(l)}return c},s={isInteractive:!1,isShadowHost:!1,isNew:!1,shouldDisplay:!0,ignoredByPaintOrder:!1,excludedByParent:!1,isCompoundComponent:!1,children:[],originalNode:{nodeId:0,backendNodeId:0,sessionId:"",frameId:"",targetId:"",nodeType:9,nodeName:"#document",nodeValue:"",attributes:{}}};for(let r of e){let o=n(r);o&&s.children.push(o)}return s}async handleGoBack(e){try{let t=e.pageId;await(t?this.getPageOrCurrent(t):await this.ensurePage()).goBack(),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleGoForward(e){try{let t=e.pageId;await(t?this.getPageOrCurrent(t):await this.ensurePage()).goForward(),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleRefresh(e){try{let t=e.pageId;await(t?this.getPageOrCurrent(t):await this.ensurePage()).reload(),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleWait(e){try{let t=e.maxSeconds||60,n=Math.min(e.seconds,t);b.debug(`Waiting for ${n}s (requested: ${e.seconds}s, max: ${t}s)`),await new Promise(s=>setTimeout(s,n*1e3)),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}normalizeKeyName(e){let t={ctrl:"Control",control:"Control",cmd:"Meta",command:"Meta",meta:"Meta",win:"Meta",windows:"Meta",alt:"Alt",option:"Alt",shift:"Shift",enter:"Enter",return:"Enter",esc:"Escape",escape:"Escape",tab:"Tab",space:"Space",backspace:"Backspace",delete:"Delete",del:"Delete",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",arrowup:"ArrowUp",arrowdown:"ArrowDown",arrowleft:"ArrowLeft",arrowright:"ArrowRight",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown",insert:"Insert",ins:"Insert"},n=e.toLowerCase().trim();return t[n]||e}parseKeyCombination(e){if(e.includes("+")){let t=e.split("+").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)return null;let n=[],s="";for(let r=0;r<t.length;r++){let o=this.normalizeKeyName(t[r]);["Control","Alt","Shift","Meta"].includes(o)?n.push(o):s=o}if(!s&&t.length>0){s=this.normalizeKeyName(t[t.length-1]);let r=n.indexOf(s);r!==-1&&n.splice(r,1)}return{modifiers:n,key:s}}return{modifiers:[],key:this.normalizeKeyName(e)}}async handleSendKeys(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage(),s=e.keys,r=this.parseKeyCombination(s);if(!r)throw new Error(`Invalid key combination: ${s}`);let{modifiers:o,key:a}=r;if(o.length>0){for(let c of o)await n.keyboard.down(c);a&&await n.keyboard.press(a);for(let c=o.length-1;c>=0;c--)await n.keyboard.up(o[c])}else await n.keyboard.press(a);a==="Enter"&&await new Promise(c=>setTimeout(c,100)),this.eventBus.respondToEvent(e._eventId,null)}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleUploadFile(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage();if(!e.node||!e.node.absolutePosition)throw new Error("Element position not available for file upload");let{x:s,y:r}=e.node.absolutePosition;await n.mouse.click(s+5,r+5);let o=l=>l.replace(/([!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~])/g,"\\$1"),a;e.node.attributes?.id?a=`#${o(e.node.attributes.id)}`:e.node.attributes?.name?a=`input[name="${o(e.node.attributes.name)}"]`:a='input[type="file"]';let c=Array.isArray(e.filePath)?e.filePath:[e.filePath];await n.setInputFiles(a,c),this.eventBus.respondToEvent(e._eventId,{success:!0})}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleGetDropdownOptions(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage();if(!e.node||!e.node.absolutePosition)throw new Error("Element position not available");if((e.node.nodeName?.toLowerCase()||"")==="select"){let r=e.node.attributes?.id?`#${e.node.attributes.id}`:e.node.attributes?.name?`select[name="${e.node.attributes.name}"]`:"select",o=await n.evaluate(a=>{let c=document.querySelector(a);return c?Array.from(c.options).map(l=>({value:l.value,text:l.text,selected:l.selected})):[]},r);this.eventBus.respondToEvent(e._eventId,{type:"native_select",options:o})}else{let{x:r,y:o,width:a,height:c}=e.node.absolutePosition;await n.mouse.click(r+a/2,o+c/2),await n.waitForTimeout(300);let l=await n.evaluate(()=>{let d=document.querySelectorAll('[role="option"], [role="menuitem"], [role="listitem"], li[data-value], .dropdown-item, .select-option');return Array.from(d).map(g=>({text:g.innerText?.trim()||"",value:g.getAttribute("data-value")||g.innerText?.trim()||""}))});this.eventBus.respondToEvent(e._eventId,{type:"custom_dropdown",options:l})}}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async handleSelectDropdownOption(e){try{let t=e.pageId,n=t?this.getPageOrCurrent(t):await this.ensurePage();if(!e.node||!e.node.absolutePosition)throw new Error("Element position not available");if((e.node.nodeName?.toLowerCase()||"")==="select"){let r=e.node.attributes?.id?`#${e.node.attributes.id}`:e.node.attributes?.name?`select[name="${e.node.attributes.name}"]`:"select";await n.selectOption(r,{label:e.text}),this.eventBus.respondToEvent(e._eventId,{success:!0,selectedText:e.text})}else{let{x:r,y:o,width:a,height:c}=e.node.absolutePosition;await n.mouse.click(r+a/2,o+c/2),await n.waitForTimeout(300);let l=await n.evaluate(d=>{let g=d.toLowerCase().trim(),m=document.querySelectorAll('[role="option"], [role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"], [role="listitem"], li[data-value], .dropdown-item, .select-option, .item, .option, .menu-item, [data-value], li, a'),p=null,h=null,f=[];for(let T of Array.from(m)){let x=T,S=(x.innerText?.trim()||"").toLowerCase(),C=(x.getAttribute("data-value")||"").toLowerCase();if(!(!S&&!C)&&(S&&f.push(x.innerText?.trim()||""),!(x.getAttribute("aria-disabled")==="true"||x.hasAttribute("disabled")))){if(S===g||C===g){p=x;break}!h&&(S.includes(g)||C.includes(g))&&(h=x)}}let y=p||h;return y?(y.click(),y.dispatchEvent(new Event("input",{bubbles:!0})),y.dispatchEvent(new Event("change",{bubbles:!0})),{found:!0,selectedText:y.innerText?.trim()}):{found:!1,availableOptions:f.slice(0,20)}},e.text);if(!l.found){let d=l.availableOptions||[],g=d.length>0?` Available options: ${d.join(", ")}`:"";throw new Error(`Option "${e.text}" not found in dropdown.${g}`)}this.eventBus.respondToEvent(e._eventId,{success:!0,selectedText:e.text})}}catch(t){this.eventBus.rejectEvent(e._eventId,t)}}async getAllTabs(){let e=[];for(let[t,n]of this.pages.entries())e.push({targetId:t,url:n.url(),title:await n.title()});return e}async getState(e={}){return this.eventBus.dispatch(j.BROWSER_STATE_REQUEST,{includeScreenshot:e.includeScreenshot??!0,includeDom:e.includeDom??!0,includeRecentEvents:e.includeRecentEvents??!1},ee.BROWSER_STATE_REQUEST)}async navigate(e,t={}){return this.eventBus.dispatch(j.NAVIGATE_TO_URL,{url:e,...t},ee.NAVIGATE_TO_URL)}async screenshot(e={}){return this.eventBus.dispatch(j.SCREENSHOT,e,ee.SCREENSHOT)}async goBack(){return this.eventBus.dispatch(j.GO_BACK,{},ee.GO_BACK)}async goForward(){return this.eventBus.dispatch(j.GO_FORWARD,{},ee.GO_FORWARD)}async refresh(){return this.eventBus.dispatch(j.REFRESH,{},ee.REFRESH)}async getElementByIndex(e){return this.cachedSelectorMap&&this.cachedSelectorMap.has(e)?this.cachedSelectorMap.get(e):null}updateCachedSelectorMap(e){this.cachedSelectorMap=e}async getSelectorMap(){return this.cachedSelectorMap}clearCachedState(){b.debug("🔄 Clearing cached browser state (page navigation detected)"),this.cachedSelectorMap.clear(),this.cachedBrowserStateSummary=null;for(let[e,t]of this.pageSelectorMaps)t.clear();this.pendingRequests.clear()}async getIndexById(e){for(let[t,n]of this.cachedSelectorMap.entries())if(n.attributes&&n.attributes.id===e)return t;return null}async getIndexByClass(e){for(let[t,n]of this.cachedSelectorMap.entries())if(n.attributes&&(n.attributes.class||"").split(" ").includes(e))return t;return null}isFileInput(e){return e.nodeName?.toUpperCase()==="INPUT"&&e.attributes?.type?.toLowerCase()==="file"}async clickElement(e){return this.eventBus.dispatch(j.CLICK_ELEMENT,{node:e},ee.CLICK_ELEMENT)}async typeText(e,t){return this.eventBus.dispatch(j.TYPE_TEXT,{text:e,node:t},ee.TYPE_TEXT)}async scroll(e,t,n){return this.eventBus.dispatch(j.SCROLL,{direction:e,amount:t||500},ee.SCROLL)}async getTargetIdFromTabId(e){let t=await this.getAllTabs();for(let n of t)if(n.targetId.endsWith(e))return n.targetId;throw new Error(`No tab found with ID ending in: ${e}`)}async switchTab(e){let t=e.length===4?await this.getTargetIdFromTabId(e):e;this.currentPageId=t}async closeTab(e){let t=e.length===4?await this.getTargetIdFromTabId(e):e,n=this.pages.get(t);if(n)try{await n.close(),this.pages.delete(t),this.pageSelectorMaps.delete(t);let s=this.pageCdpSessions.get(t);if(s&&(s.detach().catch(()=>{}),this.pageCdpSessions.delete(t)),this.currentPageId===t){let r=Array.from(this.pages.keys());this.currentPageId=r.length>0?r[0]:void 0,b.log("🔄 [BrowserSession] Switched to another tab after closing current")}return b.log(`🗑️ [BrowserSession] Closed tab ${e}. Remaining tabs: ${this.pages.size}`),!0}catch(s){return console.error(`❌ [BrowserSession] Error closing tab ${e}: ${s.message}`),!1}return!1}async uploadFile(e,t){let n=await this.getElementByIndex(e);if(!n)throw new Error(`Element at index ${e} not found`);if(!this.isFileInput(n))throw new Error(`Element at index ${e} is not a file input`);return this.eventBus.dispatch(j.UPLOAD_FILE,{node:n,filePath:t},ee.UPLOAD_FILE||3e4)}async getDropdownOptions(e){let t=await this.getElementByIndex(e);if(!t)throw new Error(`Element at index ${e} not found`);return this.eventBus.dispatch(j.GET_DROPDOWN_OPTIONS,{node:t},ee.GET_DROPDOWN_OPTIONS||15e3)}async selectDropdownOption(e,t){let n=await this.getElementByIndex(e);if(!n)throw new Error(`Element at index ${e} not found`);return this.eventBus.dispatch(j.SELECT_DROPDOWN_OPTION,{node:n,text:t},ee.SELECT_DROPDOWN_OPTION||8e3)}async sendKeys(e){return this.eventBus.dispatch(j.SEND_KEYS,{keys:e.join("")},ee.SEND_KEYS)}async evaluate(e){return(await this.ensurePage()).evaluate(e)}get page(){return this.getCurrentPage()}get downloadedFiles(){return[...this._downloadedFiles]}async getCdpSession(){let e=await this.ensurePage();if(this.cdpSession)try{return await this.cdpSession.send("Runtime.evaluate",{expression:"1",returnByValue:!0}),this.cdpSession}catch(t){b.debug("CDP session stale, creating new one:",t.message);try{await this.cdpSession.detach()}catch{}this.cdpSession=null}return this.cdpSession=await e.context().newCDPSession(e),this.cdpSession}async getCdpSessionForPage(e){let t=this.pages.get(e);if(!t)throw new Error(`Page ${e} not found`);let n=this.pageCdpSessions.get(e);if(n)try{return await n.send("Runtime.evaluate",{expression:"1",returnByValue:!0}),n}catch(r){b.debug(`CDP session for page ${e} stale, creating new one:`,r.message);try{await n.detach()}catch{}this.pageCdpSessions.delete(e)}let s=await t.context().newCDPSession(t);return this.pageCdpSessions.set(e,s),s}async closeCdpSession(){this.cdpSession&&(await this.cdpSession.detach(),this.cdpSession=null)}async closeCdpSessionForPage(e){let t=this.pageCdpSessions.get(e);if(t){try{await t.detach()}catch{}this.pageCdpSessions.delete(e)}}async cookies(e){if(!this.context)throw new Error("Browser context not initialized");return this.context.cookies(e)}async setCookies(e){if(!this.context)throw new Error("Browser context not initialized");await this.context.addCookies(e)}async clearCookies(){if(!this.context)throw new Error("Browser context not initialized");await this.context.clearCookies()}async exportStorageState(e){if(!this.context)throw new Error("Browser context not initialized");return e?this.context.storageState({path:e}):this.context.storageState()}async importStorageState(e){console.warn("Storage state import is only supported during browser session initialization")}async getAllFrames(e=!0){let t=new Map,n=new Map;try{let s=await this.ensurePage(),r=await s.context().newCDPSession(s),c=((await r.send("Target.getTargets")).targetInfos||[]).filter(l=>!!(l.type==="page"||l.type==="iframe"&&e));for(let l of c){let d=l.targetId;try{let g;try{g=(await r.send("Target.attachToTarget",{targetId:d,flatten:!0})).sessionId}catch(m){b.debug(`Could not attach to target ${d}:`,m);continue}if(g){n.set(d,g),await r.send("Page.enable",void 0,g);let p=(await r.send("Page.getFrameTree",void 0,g)).frameTree;if(p){let h=(f,y=null)=>{let T=f.frame||{},x=T.id;if(x){let S=T.parentId||y,C={...T,frameTargetId:d,parentFrameId:S,childFrameIds:[],isCrossOrigin:l.type==="iframe"},v=T.crossOriginIsolatedContextType;v&&v!=="NotIsolated"&&(C.isCrossOrigin=!0);let I=f.childFrames||[];for(let w of I){let E=w.frame||{};E.id&&C.childFrameIds.push(E.id)}if(t.has(x)){let w=t.get(x);l.type==="iframe"&&(w.frameTargetId=d,w.isCrossOrigin=!0)}else t.set(x,C);for(let w of I)h(w,x)}};h(p)}}}catch(g){b.debug(`Failed to get frame tree for target ${d}:`,g)}}}catch(s){b.debug("Failed to get frames via CDP, falling back to Playwright:",s);let o=(await this.ensurePage()).mainFrame(),a=(c,l)=>{let d=c.name()||`frame_${t.size}`;t.set(d,{id:d,url:c.url(),name:c.name(),parentFrameId:l,isCrossOrigin:!1});for(let g of c.childFrames())a(g,d)};a(o,null)}return{frames:t,targetSessions:n}}async findFrameById(e){let{frames:t}=await this.getAllFrames();return t.get(e)||null}async getFrameByUrl(e){let n=(await this.ensurePage()).frames();for(let s of n)if(s.url()===e||s.url().includes(e))return s;return null}async removeHighlights(){if(this.highlightsAdded)try{await(await this.ensurePage()).evaluate(()=>{let t=document.getElementById("browser-use-debug-highlights");t&&t.remove();let n=document.getElementById("browser-use-highlights");n&&n.remove(),document.querySelectorAll("[data-browser-use-highlight]").forEach(o=>{o.remove()}),document.querySelectorAll("[data-browser-use-interaction-highlight]").forEach(o=>{o.remove()})}),this.highlightsAdded=!1}catch(e){b.debug(`Failed to remove highlights: ${e.message}`)}}async addHighlights(e){try{let t=await this.ensurePage();await this.removeHighlights(),await new Promise(s=>setTimeout(s,50));let n=[];for(let[s,r]of e.entries())if(r.absolutePosition){let{x:o,y:a,width:c,height:l}=r.absolutePosition;c>0&&l>0&&n.push({index:s,x:o,y:a,width:c,height:l,elementName:r.nodeName||"div",backendNodeId:r.backendNodeId||s})}if(n.length===0){b.debug("No valid elements to highlight");return}await t.evaluate(s=>{let r=document.getElementById("browser-use-debug-highlights");r&&r.remove(),document.querySelectorAll("[data-browser-use-highlight]").forEach(d=>d.remove());let a=2147483647,c=document.createElement("div");c.id="browser-use-debug-highlights",c.setAttribute("data-browser-use-highlight","container"),c.style.cssText=`
|
|
568
568
|
position: absolute;
|
|
569
569
|
top: 0;
|
|
570
570
|
left: 0;
|
|
@@ -610,10 +610,10 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
|
|
|
610
610
|
z-index: ${a+1};
|
|
611
611
|
margin: 0;
|
|
612
612
|
line-height: 1.4;
|
|
613
|
-
`,m.appendChild(p),c.appendChild(m)}document.body.appendChild(c)},n),this.highlightsAdded=!0}catch(t){b.debug(`Failed to add highlights: ${t.message}`)}}async highlightInteractionElement(e,t){try{let n=await this.getElementCoordinatesByBackendNodeId(e.backendNodeId,t);if(!n){b.debug(`No coordinates found for backend node ${e.backendNodeId}`);return}let s=t?this.getPageOrCurrent(t):await this.ensurePage(),{x:r,y:o,width:a,height:c}=n;await s.evaluate(({x:g,y:m,width:p,height:h,color:f,duration:y})=>{let
|
|
613
|
+
`,m.appendChild(p),c.appendChild(m)}document.body.appendChild(c)},n),this.highlightsAdded=!0}catch(t){b.debug(`Failed to add highlights: ${t.message}`)}}async highlightInteractionElement(e,t){try{let n=await this.getElementCoordinatesByBackendNodeId(e.backendNodeId,t);if(!n){b.debug(`No coordinates found for backend node ${e.backendNodeId}`);return}let s=t?this.getPageOrCurrent(t):await this.ensurePage(),{x:r,y:o,width:a,height:c}=n;await s.evaluate(({x:g,y:m,width:p,height:h,color:f,duration:y})=>{let x=!window.matchMedia("(prefers-reduced-motion: reduce)").matches,S=window.pageXOffset||document.documentElement.scrollLeft||0,C=window.pageYOffset||document.documentElement.scrollTop||0,v=document.querySelector("[data-browser-use-interaction-highlight]");v&&v.remove();let I=document.createElement("div");I.setAttribute("data-browser-use-interaction-highlight","true"),I.style.cssText=`
|
|
614
614
|
position: absolute;
|
|
615
|
-
left: ${g+
|
|
616
|
-
top: ${m+
|
|
615
|
+
left: ${g+S}px;
|
|
616
|
+
top: ${m+C}px;
|
|
617
617
|
width: ${p}px;
|
|
618
618
|
height: ${h}px;
|
|
619
619
|
background: transparent;
|
|
@@ -622,10 +622,10 @@ ${t}`,o=this.readDeviceKnowledge()||"";if(o.includes(`## ${n}`)){let a=o.split(`
|
|
|
622
622
|
pointer-events: none;
|
|
623
623
|
z-index: 2147483647;
|
|
624
624
|
box-sizing: border-box;
|
|
625
|
-
transform: ${
|
|
626
|
-
opacity: ${
|
|
627
|
-
transition: ${
|
|
628
|
-
`,document.body.appendChild(I),
|
|
625
|
+
transform: ${x?"scale(0.95)":"scale(1)"};
|
|
626
|
+
opacity: ${x?"0":"1"};
|
|
627
|
+
transition: ${x?"all 0.25s cubic-bezier(0.34, 1.56, 0.64, 1)":"none"};
|
|
628
|
+
`,document.body.appendChild(I),x&&requestAnimationFrame(()=>{setTimeout(()=>{I.style.transform="scale(1)",I.style.opacity="1"},10)}),setTimeout(()=>{x?(I.style.transform="scale(1.05)",I.style.opacity="0",I.style.transition="all 0.3s cubic-bezier(0.4, 0.0, 0.2, 1)",setTimeout(()=>I.remove(),300)):I.remove()},y)},{x:r,y:o,width:a||0,height:c||0,color:"rgb(156, 173, 184)",duration:2e3})}catch(n){b.debug(`Failed to highlight interaction element: ${n.message}`)}}async getElementCoordinates(e){try{let n=await(await this.ensurePage()).$(e);if(!n)return null;let s=await n.boundingBox();return s?{x:s.x,y:s.y,width:s.width,height:s.height}:null}catch(t){return b.debug(`Failed to get element coordinates: ${t.message}`),null}}async getElementCoordinatesByBackendNodeId(e,t){try{let n=t?await this.getCdpSessionForPage(t):await this.getCdpSession(),s=[];try{let r=await n.send("DOM.getContentQuads",{backendNodeId:e});r.quads&&r.quads.length>0&&(s=r.quads,b.debug(`Got ${s.length} quads from DOM.getContentQuads`))}catch(r){b.debug(`DOM.getContentQuads failed: ${r.message}`)}if(s.length===0)try{let r=await n.send("DOM.getBoxModel",{backendNodeId:e});if(r.model&&r.model.content&&r.model.content.length>=8){let o=r.model.content;s=[[o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7]]],b.debug("Got quad from DOM.getBoxModel")}}catch(r){b.debug(`DOM.getBoxModel failed: ${r.message}`)}if(s.length===0)try{let r=await n.send("DOM.resolveNode",{backendNodeId:e});if(r.object&&r.object.objectId){let o=await n.send("Runtime.callFunctionOn",{objectId:r.object.objectId,functionDeclaration:`
|
|
629
629
|
function() {
|
|
630
630
|
const rect = this.getBoundingClientRect();
|
|
631
631
|
return {
|
|
@@ -636,23 +636,23 @@ ${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 Yi}from"zod";var
|
|
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=Yi.object({[r.name]:r.paramSchema}).describe(r.description);s.push(o)}return s.length===0?Yi.object({}):s.length===1?s[0]:Yi.union(s)}}});import{z as U}from"zod";async function es(i,e){return i.pageId?i.browserSession.getElementByIndexForPage(i.pageId,e):i.browserSession.getElementByIndex(e)}async function Hl(i){return i.pageId?i.browserSession.getSelectorMapForPage(i.pageId):await i.browserSession.getSelectorMap()}function lh(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 Wl(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 Rh(i,e){try{return await e.browserSession.eventBus.dispatch(j.NAVIGATE_TO_URL,{...i,pageId:e.pageId},ee.NAVIGATE_TO_URL),{longTermMemory:i.new_tab?`Opened new tab with URL ${i.url}`:`Navigated to ${i.url}`}}catch(t){let n=t.message||String(t);return n.includes("CDP client not initialized")?{error:`Browser connection error: ${n}`}:["ERR_NAME_NOT_RESOLVED","ERR_INTERNET_DISCONNECTED","ERR_CONNECTION_REFUSED","ERR_TIMED_OUT","net::"].some(r=>n.includes(r))?{error:`Navigation failed - site unavailable: ${i.url}`}:{error:`Navigation failed: ${n}`}}}async function Oh(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 es(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 Hl(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(j.CLICK_ELEMENT,{node:t,button:i.button,pageId:e.pageId},ee.CLICK_ELEMENT),{longTermMemory:`Clicked element ${i.index}`}}catch(t){let n=t.message||String(t);if(n.includes("Cannot click on <select>")||n.includes("select element"))try{return await Gl({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 Nh(i,e){try{let t=await es(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=lh(i.text,s)),await e.browserSession.eventBus.dispatch(j.TYPE_TEXT,{node:t,text:i.text,clear:i.clear,isSensitive:n,sensitiveKeyName:r,pageId:e.pageId},ee.TYPE_TEXT);let o;return n?r?o=`Input ${r} into element ${i.index}`:o=`Input sensitive data into element ${i.index}`:o=`Input '${i.text}' into element ${i.index}`,{longTermMemory:o}}catch(t){return{error:`Failed to type text: ${t.message}`}}}async function _h(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 es(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(j.SCROLL,{direction:n,amount:m,node:s,pageId:e.pageId},ee.SCROLL),l++,await new Promise(p=>setTimeout(p,300))}catch{}if(c>0)try{let g=Math.floor(c*o);await e.browserSession.eventBus.dispatch(j.SCROLL,{direction:n,amount:g,node:s,pageId:e.pageId},ee.SCROLL),l+=c}catch{}return{longTermMemory:(t===1?`Scrolled ${n} ${r} ${o}px`:`Scrolled ${n} ${r} ${l.toFixed(1)} pages`).replace(" "," ")}}else{let a=Math.floor(t*o);return await e.browserSession.eventBus.dispatch(j.SCROLL,{direction:n,amount:a,node:s,pageId:e.pageId},ee.SCROLL),{longTermMemory:`Scrolled ${n} ${r} ${t} pages`.replace(" "," ")}}}catch(t){return{error:`Failed to scroll: ${t.message}`}}}async function $h(i,e){try{return await e.browserSession.eventBus.dispatch(j.GO_BACK,{pageId:e.pageId},ee.GO_BACK),{longTermMemory:"Navigated back"}}catch(t){return{error:`Failed to go back: ${t.message}`}}}async function Fh(i,e){try{return await e.browserSession.eventBus.dispatch(j.GO_FORWARD,{pageId:e.pageId},ee.GO_FORWARD),{longTermMemory:"Navigated forward"}}catch(t){return{error:`Failed to go forward: ${t.message}`}}}async function Lh(i,e){try{return await e.browserSession.eventBus.dispatch(j.REFRESH,{pageId:e.pageId},ee.REFRESH),{longTermMemory:"Refreshed page"}}catch(t){return{error:`Failed to refresh: ${t.message}`}}}async function Uh(i,e){try{return await e.browserSession.eventBus.dispatch(j.WAIT,{seconds:i.seconds,pageId:e.pageId},ee.WAIT),{longTermMemory:`Waited ${i.seconds} seconds`}}catch(t){return{error:`Failed to wait: ${t.message}`}}}async function Bh(i,e){try{return await e.browserSession.eventBus.dispatch(j.SEND_KEYS,{...i,pageId:e.pageId},ee.SEND_KEYS),{longTermMemory:`Sent keys: ${i.keys}`}}catch(t){return{error:`Failed to send keys: ${t.message}`}}}async function Wh(i,e){try{let t=await e.browserSession.eventBus.dispatch(j.SCREENSHOT,{...i,pageId:e.pageId},ee.SCREENSHOT);return{extractedContent:`Screenshot captured (${t.length} bytes)`,metadata:{screenshot:t}}}catch(t){return{error:`Failed to take screenshot: ${t.message}`}}}async function Hh(i,e){return{isDone:!0,success:i.success??!0,extractedContent:i.text,attachments:i.files_to_display||[]}}async function Gh(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(j.NAVIGATE_TO_URL,{url:r,newTab:!1,pageId:e.pageId},ee.NAVIGATE_TO_URL);let o=`Searched ${t} for '${i.query}'`;return{extractedContent:o,longTermMemory:o}}catch(t){return{error:`Failed to search: ${t.message}`}}}async function jh(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(j.SWITCH_TAB,{targetId:n.targetId},ee.SWITCH_TAB);let s=`Switched to tab #${i.tab_id}`;return{extractedContent:s,longTermMemory:s}}catch(t){return{error:`Failed to switch tab: ${t.message}`}}}async function zh(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(j.CLOSE_TAB,{targetId:n.targetId},ee.CLOSE_TAB);let s=`Closed tab #${i.tab_id}`;return{extractedContent:s,longTermMemory:s}}catch(t){return{error:`Failed to close tab: ${t.message}`}}}async function qh(i,e){try{await e.browserSession.eventBus.dispatch(j.SCROLL_TO_TEXT,{text:i.text,pageId:e.pageId},ee.SCROLL_TO_TEXT);let t=`Scrolled to text: ${i.text}`;return{extractedContent:t,longTermMemory:t}}catch{return{extractedContent:`Text '${i.text}' not found or not visible on page`,longTermMemory:`Tried scrolling to text '${i.text}' but it was not found`}}}async function Gl(i,e){try{let t=await es(e,i.index);if(!t)return{error:`Element with index ${i.index} not found`};let n=await e.browserSession.eventBus.dispatch(j.GET_DROPDOWN_OPTIONS,{node:t,pageId:e.pageId},ee.GET_DROPDOWN_OPTIONS);return n?{extractedContent:n.shortTermMemory||JSON.stringify(n),longTermMemory:n.longTermMemory||`Got dropdown options for element ${i.index}`,includeExtractedContentOnlyOnce:!0}:{error:"Failed to get dropdown options - no data returned"}}catch(t){return{error:`Failed to get dropdown options: ${t.message}`}}}async function Kh(i,e){try{let t=await es(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(j.SELECT_DROPDOWN_OPTION,{node:t,text:i.text,pageId:e.pageId},ee.SELECT_DROPDOWN_OPTION);return n?n.success==="true"||n.success===!0?{extractedContent:n.message||`Selected option: ${i.text}`,longTermMemory:`Selected dropdown option '${i.text}' at index ${i.index}`}:{error:n.error||`Failed to select option: ${i.text}`}:{error:"Failed to select dropdown option - no data returned"}}catch(t){return{error:`Failed to select dropdown option: ${t.message}`}}}async function Vh(i,e){try{let t=await es(e,i.index),n=await Hl(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 w=y.childrenNodes||y.children||[];for(let C of w)if(s(C))return C}m=h}return null})(t);if(!o&&n){let l=null,d=1/0,g=0;try{let m=e.browserSession.page;m&&(g=await m.evaluate(()=>window.scrollY||0))}catch{}for(let[m,p]of n.entries())if(s(p)){let h=p.absolutePosition?.y||0,f=Math.abs(h-g);f<d&&(d=f,l=p)}l&&(o=l)}let a=o||t;await e.browserSession.eventBus.dispatch(j.UPLOAD_FILE,{node:a,filePath:i.path,pageId:e.pageId},ee.UPLOAD_FILE);let c=`Uploaded file ${i.path} to element ${i.index}`;return{extractedContent:`Successfully uploaded file to index ${i.index}`,longTermMemory:c}}catch(t){return{error:`Failed to upload file: ${t.message}`}}}async function Xh(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to execute JavaScript"};let n=Wl(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 Yi}from"zod";var ao,jl=L(()=>{"use strict";ao=class{actions=new Map;register(e){this.actions.set(e.name,e)}getActions(){return this.actions}getAction(e){return this.actions.get(e)}async execute(e,t,n){let s=this.actions.get(e);if(!s)throw new Error(`Action ${e} not found`);let r=s.paramSchema.parse(t);return s.function(r,n)}getPromptDescription(e){let t=[];for(let n of this.actions.values()){if(e&&n.domains){if(!this.matchDomains(n.domains,e))continue}else{if(e&&!n.domains)continue;if(!e&&n.domains)continue}t.push(this.formatActionDescription(n))}return t.join(`
|
|
640
|
+
`)}formatActionDescription(e){let t=e.paramSchema,n=[];if(t._def&&t._def.shape){let s=t._def.shape();for(let[r,o]of Object.entries(s)){let a=o,c=r;a._def.typeName&&(c+=`=${a._def.typeName.replace("Zod","").toLowerCase()}`),a._def.description&&(c+=` (${a._def.description})`),n.push(c)}}return n.length>0?`${e.name}: ${e.description}. (${n.join(", ")})`:`${e.name}: ${e.description}`}matchDomains(e,t){if(!e||e.length===0)return!0;try{let s=new URL(t).hostname;for(let r of e)if(new RegExp("^"+r.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(s))return!0}catch{return!1}return!1}getActionsSchema(){let e={};for(let[t,n]of this.actions.entries())e[t]={description:n.description,parameters:n.paramSchema};return e}createActionModel(e,t){let n=[];for(let[r,o]of this.actions.entries())if(!(e&&!e.includes(r))){if(!t){o.domains||n.push(o);continue}(!o.domains||this.matchDomains(o.domains,t))&&n.push(o)}let s=[];for(let r of n){let o=Yi.object({[r.name]:r.paramSchema}).describe(r.description);s.push(o)}return s.length===0?Yi.object({}):s.length===1?s[0]:Yi.union(s)}}});import{z as U}from"zod";async function ts(i,e){return i.pageId?i.browserSession.getElementByIndexForPage(i.pageId,e):i.browserSession.getElementByIndex(e)}async function ql(i){return i.pageId?i.browserSession.getSelectorMapForPage(i.pageId):await i.browserSession.getSelectorMap()}function ph(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 zl(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 Fh(i,e){try{return await e.browserSession.eventBus.dispatch(j.NAVIGATE_TO_URL,{...i,pageId:e.pageId},ee.NAVIGATE_TO_URL),{longTermMemory:i.new_tab?`Opened new tab with URL ${i.url}`:`Navigated to ${i.url}`}}catch(t){let n=t.message||String(t);return n.includes("CDP client not initialized")?{error:`Browser connection error: ${n}`}:["ERR_NAME_NOT_RESOLVED","ERR_INTERNET_DISCONNECTED","ERR_CONNECTION_REFUSED","ERR_TIMED_OUT","net::"].some(r=>n.includes(r))?{error:`Navigation failed - site unavailable: ${i.url}`}:{error:`Navigation failed: ${n}`}}}async function Lh(i,e){try{if(i.index===0)return{error:"Cannot click on element with index 0. If there are no interactive elements use scroll(), wait(), refresh(), etc. to troubleshoot"};let t=await ts(e,i.index);if(b.log(`🔍 [click] Looking up element index ${i.index}${e.pageId?` (page: ${e.pageId})`:""}`),b.log(`🔍 [click] Element found: ${t?"yes":"no"}`),t&&(b.log(`🔍 [click] Element tag: ${t.nodeName}, text: ${t.text?.substring(0,50)}`),b.log(`🔍 [click] Element position: ${JSON.stringify(t.absolutePosition)}`),b.log(`🔍 [click] Element backendNodeId: ${t.backendNodeId}`)),!t){let n=await ql(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(j.CLICK_ELEMENT,{node:t,button:i.button,pageId:e.pageId},ee.CLICK_ELEMENT),{longTermMemory:`Clicked element ${i.index}`}}catch(t){let n=t.message||String(t);if(n.includes("Cannot click on <select>")||n.includes("select element"))try{return await Kl({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 Uh(i,e){try{let t=await ts(e,i.index);if(!t){let a=`Element index ${i.index} not available - page may have changed. Try refreshing browser state.`;return console.warn(`⚠️ ${a}`),{extractedContent:a}}e.browserSession.highlightInteractionElement(t,e.pageId).catch(()=>{});let n=e.hasSensitiveData||!1,s=e.sensitiveData,r=null;n&&s&&(r=ph(i.text,s)),await e.browserSession.eventBus.dispatch(j.TYPE_TEXT,{node:t,text:i.text,clear:i.clear,isSensitive:n,sensitiveKeyName:r,pageId:e.pageId},ee.TYPE_TEXT);let o;return n?r?o=`Input ${r} into element ${i.index}`:o=`Input sensitive data into element ${i.index}`:o=`Input '${i.text}' into element ${i.index}`,{longTermMemory:o}}catch(t){return{error:`Failed to type text: ${t.message}`}}}async function Bh(i,e){try{let t=i.pages??1,n=i.down?"down":"up",s=null;if(i.index!==void 0&&i.index!==0&&(s=await ts(e,i.index),!s))return{error:`Element index ${i.index} not found in browser state`};let r=i.index!==void 0&&i.index!==0?`element ${i.index}`:"page",o=1e3;try{let a=await e.browserSession.getCdpSession();if(a){let c=await a.send("Page.getLayoutMetrics"),l=c?.cssVisualViewport||c?.cssLayoutViewport;l?.clientHeight&&(o=Math.floor(l.clientHeight))}}catch{}if(t>=1){let a=Math.floor(t),c=t-a,l=0;for(let g=0;g<a;g++)try{let m=o;await e.browserSession.eventBus.dispatch(j.SCROLL,{direction:n,amount:m,node:s,pageId:e.pageId},ee.SCROLL),l++,await new Promise(p=>setTimeout(p,300))}catch{}if(c>0)try{let g=Math.floor(c*o);await e.browserSession.eventBus.dispatch(j.SCROLL,{direction:n,amount:g,node:s,pageId:e.pageId},ee.SCROLL),l+=c}catch{}return{longTermMemory:(t===1?`Scrolled ${n} ${r} ${o}px`:`Scrolled ${n} ${r} ${l.toFixed(1)} pages`).replace(" "," ")}}else{let a=Math.floor(t*o);return await e.browserSession.eventBus.dispatch(j.SCROLL,{direction:n,amount:a,node:s,pageId:e.pageId},ee.SCROLL),{longTermMemory:`Scrolled ${n} ${r} ${t} pages`.replace(" "," ")}}}catch(t){return{error:`Failed to scroll: ${t.message}`}}}async function Wh(i,e){try{return await e.browserSession.eventBus.dispatch(j.GO_BACK,{pageId:e.pageId},ee.GO_BACK),{longTermMemory:"Navigated back"}}catch(t){return{error:`Failed to go back: ${t.message}`}}}async function Hh(i,e){try{return await e.browserSession.eventBus.dispatch(j.GO_FORWARD,{pageId:e.pageId},ee.GO_FORWARD),{longTermMemory:"Navigated forward"}}catch(t){return{error:`Failed to go forward: ${t.message}`}}}async function Gh(i,e){try{return await e.browserSession.eventBus.dispatch(j.REFRESH,{pageId:e.pageId},ee.REFRESH),{longTermMemory:"Refreshed page"}}catch(t){return{error:`Failed to refresh: ${t.message}`}}}async function jh(i,e){try{return await e.browserSession.eventBus.dispatch(j.WAIT,{seconds:i.seconds,pageId:e.pageId},ee.WAIT),{longTermMemory:`Waited ${i.seconds} seconds`}}catch(t){return{error:`Failed to wait: ${t.message}`}}}async function zh(i,e){try{return await e.browserSession.eventBus.dispatch(j.SEND_KEYS,{...i,pageId:e.pageId},ee.SEND_KEYS),{longTermMemory:`Sent keys: ${i.keys}`}}catch(t){return{error:`Failed to send keys: ${t.message}`}}}async function qh(i,e){try{let t=await e.browserSession.eventBus.dispatch(j.SCREENSHOT,{...i,pageId:e.pageId},ee.SCREENSHOT);return{extractedContent:`Screenshot captured (${t.length} bytes)`,metadata:{screenshot:t}}}catch(t){return{error:`Failed to take screenshot: ${t.message}`}}}async function Kh(i,e){return{isDone:!0,success:i.success??!0,extractedContent:i.text,attachments:i.files_to_display||[]}}async function Vh(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(j.NAVIGATE_TO_URL,{url:r,newTab:!1,pageId:e.pageId},ee.NAVIGATE_TO_URL);let o=`Searched ${t} for '${i.query}'`;return{extractedContent:o,longTermMemory:o}}catch(t){return{error:`Failed to search: ${t.message}`}}}async function Xh(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(j.SWITCH_TAB,{targetId:n.targetId},ee.SWITCH_TAB);let s=`Switched to tab #${i.tab_id}`;return{extractedContent:s,longTermMemory:s}}catch(t){return{error:`Failed to switch tab: ${t.message}`}}}async function Yh(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(j.CLOSE_TAB,{targetId:n.targetId},ee.CLOSE_TAB);let s=`Closed tab #${i.tab_id}`;return{extractedContent:s,longTermMemory:s}}catch(t){return{error:`Failed to close tab: ${t.message}`}}}async function Qh(i,e){try{await e.browserSession.eventBus.dispatch(j.SCROLL_TO_TEXT,{text:i.text,pageId:e.pageId},ee.SCROLL_TO_TEXT);let t=`Scrolled to text: ${i.text}`;return{extractedContent:t,longTermMemory:t}}catch{return{extractedContent:`Text '${i.text}' not found or not visible on page`,longTermMemory:`Tried scrolling to text '${i.text}' but it was not found`}}}async function Kl(i,e){try{let t=await ts(e,i.index);if(!t)return{error:`Element with index ${i.index} not found`};let n=await e.browserSession.eventBus.dispatch(j.GET_DROPDOWN_OPTIONS,{node:t,pageId:e.pageId},ee.GET_DROPDOWN_OPTIONS);return n?{extractedContent:n.shortTermMemory||JSON.stringify(n),longTermMemory:n.longTermMemory||`Got dropdown options for element ${i.index}`,includeExtractedContentOnlyOnce:!0}:{error:"Failed to get dropdown options - no data returned"}}catch(t){return{error:`Failed to get dropdown options: ${t.message}`}}}async function Jh(i,e){try{let t=await ts(e,i.index);if(!t){let s=`Element index ${i.index} not available - page may have changed. Try refreshing browser state.`;return console.warn(`⚠️ ${s}`),{extractedContent:s}}let n=await e.browserSession.eventBus.dispatch(j.SELECT_DROPDOWN_OPTION,{node:t,text:i.text,pageId:e.pageId},ee.SELECT_DROPDOWN_OPTION);return n?n.success==="true"||n.success===!0?{extractedContent:n.message||`Selected option: ${i.text}`,longTermMemory:`Selected dropdown option '${i.text}' at index ${i.index}`}:{error:n.error||`Failed to select option: ${i.text}`}:{error:"Failed to select dropdown option - no data returned"}}catch(t){return{error:`Failed to select dropdown option: ${t.message}`}}}async function Zh(i,e){try{let t=await ts(e,i.index),n=await ql(e);if(!t)return{error:`Element with index ${i.index} not found`};if(e.availableFilePaths&&!e.availableFilePaths.includes(i.path)&&!(e.browserSession.downloadedFiles||[]).includes(i.path))if(e.fileSystem){if(!await e.fileSystem.getFile?.(i.path))return{error:`File path ${i.path} is not available. Upload files must be in available_file_paths, downloaded_files, or file_system.`}}else return{error:`File path ${i.path} is not available. Upload files must be in available_file_paths or downloaded_files.`};let s=l=>{if(!l)return!1;let d=(l.tagName||l.nodeName||"").toLowerCase(),g=(l.attributes?.type||"").toLowerCase();return d==="input"&&g==="file"},o=((l,d=3)=>{if(s(l))return l;let g=l.childrenNodes||l.children||[];for(let p of g)if(s(p))return p;let m=l;for(let p=0;p<d;p++){let h=m.parentNode||m.parent;if(!h)break;let f=h.childrenNodes||h.children||[];for(let y of f){if(y===m)continue;if(s(y))return y;let T=y.childrenNodes||y.children||[];for(let x of T)if(s(x))return x}m=h}return null})(t);if(!o&&n){let l=null,d=1/0,g=0;try{let m=e.browserSession.page;m&&(g=await m.evaluate(()=>window.scrollY||0))}catch{}for(let[m,p]of n.entries())if(s(p)){let h=p.absolutePosition?.y||0,f=Math.abs(h-g);f<d&&(d=f,l=p)}l&&(o=l)}let a=o||t;await e.browserSession.eventBus.dispatch(j.UPLOAD_FILE,{node:a,filePath:i.path,pageId:e.pageId},ee.UPLOAD_FILE);let c=`Uploaded file ${i.path} to element ${i.index}`;return{extractedContent:`Successfully uploaded file to index ${i.index}`,longTermMemory:c}}catch(t){return{error:`Failed to upload file: ${t.message}`}}}async function ef(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to execute JavaScript"};let n=zl(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
|
-
${
|
|
645
|
+
${zl(i.code).substring(0,500)}${i.code.length>500?"...":""}`}}}async function tf(i,e){try{let s=e.pageExtractionLlm||e.llm;if(b.log(`📤 [Extract] LLM available: ${!!s}, pageExtractionLlm: ${!!e.pageExtractionLlm}, mainLlm: ${!!e.llm}`),!s)return console.error("❌ [Extract] No LLM available for extraction"),{error:"No LLM available for extraction. Neither pageExtractionLlm nor main llm configured."};let r=e.browserSession.page;if(b.log(`📄 [Extract] Page available: ${!!r}`),!r)return{error:"No active page to extract content from"};let o=r.url(),a,c;try{let f=i.extract_links||!1,y=await r.evaluate(T=>{function x(I,w=0){if(w>20)return"";let E=I.tagName?.toLowerCase();if(["script","style","noscript","svg","path","iframe"].includes(E))return"";try{let D=window.getComputedStyle(I);if(D.display==="none"||D.visibility==="hidden")return""}catch{}let P="";if(["h1","h2","h3","h4","h5","h6"].includes(E)){let D=parseInt(E[1]),$="#".repeat(D)+" ";return P+=`
|
|
646
646
|
`+$+I.innerText.trim()+`
|
|
647
647
|
`,P}if(E==="p"){let D=I.innerText.trim();return D&&(P+=`
|
|
648
648
|
`+D+`
|
|
649
|
-
`),P}if(E==="a"&&
|
|
650
|
-
`,P;if(["div","span","section","article","main"].includes(E)){for(let D of Array.from(I.children))P+=
|
|
651
|
-
`)}return P}for(let D of Array.from(I.children))P+=
|
|
649
|
+
`),P}if(E==="a"&&T){let D=I.getAttribute("href"),$=I.innerText.trim();if(D&&$&&!D.startsWith("javascript:"))return`[${$}](${D})`}if(E==="li")return P+="- "+I.innerText.trim()+`
|
|
650
|
+
`,P;if(["div","span","section","article","main"].includes(E)){for(let D of Array.from(I.children))P+=x(D,w+1);if(P===""&&I.innerText){let D=I.innerText.trim();D.length>2&&(P=D+`
|
|
651
|
+
`)}return P}for(let D of Array.from(I.children))P+=x(D,w+1);return P}let S=document.documentElement.outerHTML,C=x(document.body),v=C.replace(/\n{3,}/g,`
|
|
652
652
|
|
|
653
|
-
`).replace(/[ \t]+/g," ").replace(/%[0-9A-Fa-f]{2}/g,"").trim();return{content:v,originalHtmlChars:
|
|
653
|
+
`).replace(/[ \t]+/g," ").replace(/%[0-9A-Fa-f]{2}/g,"").trim();return{content:v,originalHtmlChars:S.length,initialMarkdownChars:C.length,finalFilteredChars:v.length}},f);a=y.content,c={originalHtmlChars:y.originalHtmlChars,initialMarkdownChars:y.initialMarkdownChars,filteredCharsRemoved:y.initialMarkdownChars-y.finalFilteredChars,finalFilteredChars:y.finalFilteredChars}}catch(f){return{error:`Failed to extract page content: ${f.message}`}}let l=i.start_from_char||0;if(l>0){if(l>=a.length)return{error:`startFromChar (${l}) exceeds content length (${a.length}).`};a=a.substring(l)}let d=!1,g=0;if(a.length>3e4){let f=3e4,y=a.lastIndexOf(`
|
|
654
654
|
|
|
655
|
-
`,3e4);if(y>29500)f=y;else{let
|
|
655
|
+
`,3e4);if(y>29500)f=y;else{let T=a.lastIndexOf(".",3e4);T>29800&&(f=T+1)}a=a.substring(0,f),d=!0,g=l+f}let m=`Content: ${c.originalHtmlChars.toLocaleString()} HTML → ${c.finalFilteredChars.toLocaleString()} markdown chars`;l>0&&(m+=` (from char ${l.toLocaleString()})`),d&&(m+=` → ${a.length.toLocaleString()} chars (truncated, use startFromChar=${g} to continue)`);let p=`You are an expert at extracting data from the markdown of a webpage.
|
|
656
656
|
|
|
657
657
|
<instructions>
|
|
658
658
|
- Extract information from the webpage that is relevant to the query.
|
|
@@ -675,7 +675,7 @@ ${m}
|
|
|
675
675
|
|
|
676
676
|
<webpage_content>
|
|
677
677
|
${a}
|
|
678
|
-
</webpage_content>`;b.log(`🤖 [Extract] Calling LLM with ${a.length} chars of content...`);try{let f=await Promise.race([s.ainvoke([{role:"system",content:p},{role:"user",content:h}]),new Promise((
|
|
678
|
+
</webpage_content>`;b.log(`🤖 [Extract] Calling LLM with ${a.length} chars of content...`);try{let f=await Promise.race([s.ainvoke([{role:"system",content:p},{role:"user",content:h}]),new Promise((C,v)=>setTimeout(()=>v(new Error("LLM extraction timeout")),12e4))]);b.log("✅ [Extract] LLM response received");let y=typeof f.completion=="string"?f.completion:JSON.stringify(f.completion);b.log(`📝 [Extract] Extracted ${y.length} chars`);let T=`<url>
|
|
679
679
|
${o}
|
|
680
680
|
</url>
|
|
681
681
|
<query>
|
|
@@ -683,25 +683,25 @@ ${i.query}
|
|
|
683
683
|
</query>
|
|
684
684
|
<result>
|
|
685
685
|
${y}
|
|
686
|
-
</result>`,
|
|
687
|
-
Content saved to ${
|
|
688
|
-
Extracted ${y.length} chars (see extracted_content)`,
|
|
689
|
-
Extracted ${y.length} chars`,
|
|
686
|
+
</result>`,x,S=!1;if(T.length<1e3)x=T;else if(e.fileSystem)try{let C=await e.fileSystem.saveExtractedContent(T);x=`Query: ${i.query}
|
|
687
|
+
Content saved to ${C}`,S=!0}catch{x=`Query: ${i.query}
|
|
688
|
+
Extracted ${y.length} chars (see extracted_content)`,S=!0}else x=`Query: ${i.query}
|
|
689
|
+
Extracted ${y.length} chars`,S=!0;return{extractedContent:T,longTermMemory:x,includeExtractedContentOnlyOnce:S}}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 nf(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
|
|
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 sf(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
|
|
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 rf(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 of(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to search"};let n=i.pattern,s=i.regex??!1,r=i.case_sensitive??!1,o=i.context_chars??150,a=i.css_scope??null,c=i.max_results??25,l=await t.evaluate(({pattern:f,isRegex:y,caseSensitive:T,contextChars:x,cssScope:S,maxResults:C})=>{function v(I){let w=[],E=I;for(;E&&E!==document.body&&E!==document.documentElement;){let P=E.tagName?E.tagName.toLowerCase():"";if(!P)break;if(E.id)P+="#"+E.id;else if(E.className&&typeof E.className=="string"){let D=E.className.trim().split(/\s+/).slice(0,2).join(".");D&&(P+="."+D)}w.unshift(P),E=E.parentElement}return w.join(" > ")}try{let I=S?document.querySelector(S):document.body;if(!I)return{error:"CSS scope selector not found: "+S,matches:[],total:0};let w=document.createTreeWalker(I,NodeFilter.SHOW_TEXT),E="",P=[];for(;w.nextNode();){let N=w.currentNode,k=N.textContent;k&&k.trim()&&(P.push({offset:E.length,length:k.length,node:N}),E+=k)}let D;try{let N=T?"g":"gi";y?D=new RegExp(f,N):D=new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N)}catch(N){return{error:"Invalid regex pattern: "+N.message,matches:[],total:0}}let $=[],R,_=0;for(;(R=D.exec(E))!==null;){if(_++,$.length<C){let N=Math.max(0,R.index-x),k=Math.min(E.length,R.index+R[0].length+x),M=E.slice(N,k),F="";for(let B=0;B<P.length;B++){let H=P[B];if(H.offset<=R.index&&H.offset+H.length>R.index){F=v(H.node.parentElement);break}}$.push({match_text:R[0],context:(N>0?"...":"")+M+(k<E.length?"...":""),element_path:F,char_position:R.index})}R[0].length===0&&D.lastIndex++}return{matches:$,total:_,has_more:_>C}}catch(I){return{error:"search_page error: "+I.message,matches:[],total:0}}},{pattern:n,isRegex:s,caseSensitive:r,contextChars:o,cssScope:a,maxResults:c});if(l.error)return{error:l.error};let{matches:d,total:g,has_more:m}=l;if(g===0)return{extractedContent:`No matches found for "${n}" on page.`,longTermMemory:`Searched page for "${n}" - no matches found`};let p=[`Found ${g} match${g!==1?"es":""} for "${n}" on page:`,""];for(let f=0;f<d.length;f++){let y=d[f],T=y.element_path?` (in ${y.element_path})`:"";p.push(`[${f+1}] ${y.context}${T}`)}return m&&p.push(`
|
|
696
696
|
... showing ${d.length} of ${g} total matches. Increase max_results to see more.`),{extractedContent:p.join(`
|
|
697
|
-
`),longTermMemory:`Searched page for "${n}" - found ${g} matches`}}catch(t){return{error:`search_page failed: ${t.message}`}}}async function
|
|
697
|
+
`),longTermMemory:`Searched page for "${n}" - found ${g} matches`}}catch(t){return{error:`search_page failed: ${t.message}`}}}async function af(i,e){try{let t=e.browserSession.page;if(!t)return{error:"No active page to query"};let n=i.selector,s=i.attributes??null,r=i.max_results??50,o=i.include_text??!0,a=await t.evaluate(({selector:h,attributes:f,maxResults:y,includeText:T})=>{try{let x;try{x=document.querySelectorAll(h)}catch(I){return{error:"Invalid CSS selector: "+I.message,elements:[],total:0}}let S=x.length,C=Math.min(S,y),v=[];for(let I=0;I<C;I++){let w=x[I],E={index:I,tag:w.tagName.toLowerCase(),children_count:w.children.length};if(T){let P=(w.textContent||"").trim();E.text=P.length>300?P.slice(0,300)+"...":P}if(f&&f.length>0){E.attrs={};for(let P=0;P<f.length;P++){let D=w.getAttribute(f[P]);D!==null&&(E.attrs[f[P]]=D.length>500?D.slice(0,500)+"...":D)}}v.push(E)}return{elements:v,total:S,showing:C}}catch(x){return{error:"find_elements error: "+x.message,elements:[],total:0}}},{selector:n,attributes:s,maxResults:r,includeText:o});if(a.error)return{error:a.error};let{elements:c,total:l,showing:d}=a,g=d??c.length;if(l===0)return{extractedContent:`No elements found matching "${n}".`,longTermMemory:`Queried DOM for "${n}" - no elements found`};let m=[`Found ${l} element${l!==1?"s":""} matching "${n}":`,""];for(let h of c){let f=[`[${h.index}] <${h.tag}>`];if(h.text){let y=h.text.split(/\s+/).join(" ");y.length>120&&(y=y.slice(0,120)+"..."),f.push(`"${y}"`)}if(h.attrs&&Object.keys(h.attrs).length>0){let y=Object.entries(h.attrs).map(([T,x])=>`${T}="${x}"`);f.push("{"+y.join(", ")+"}")}f.push(`(${h.children_count} children)`),m.push(f.join(" "))}return g<l&&m.push(`
|
|
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 jl(i){i.register({name:"navigate",description:"Navigate to a URL",function:Rh,paramSchema:uh}),i.register({name:"click",description:"Click an element by index",function:Oh,paramSchema:dh}),i.register({name:"input",description:"Type text into an element",function:Nh,paramSchema:gh}),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:_h,paramSchema:mh}),i.register({name:"go_back",description:"Navigate back in browser history",function:$h,paramSchema:U.object({})}),i.register({name:"go_forward",description:"Navigate forward in browser history",function:Fh,paramSchema:U.object({})}),i.register({name:"refresh",description:"Refresh the current page",function:Lh,paramSchema:U.object({})}),i.register({name:"wait",description:"Wait for a specified number of seconds",function:Uh,paramSchema:hh}),i.register({name:"send_keys",description:"Send keyboard keys or shortcuts",function:Bh,paramSchema:fh}),i.register({name:"screenshot",description:"Take a screenshot of the current page",function:Wh,paramSchema:bh}),i.register({name:"done",description:"Mark the task as complete",function:Hh,paramSchema:ph}),i.register({name:"search",description:"Search the web using Google, Bing, or DuckDuckGo",function:Gh,paramSchema:yh}),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:jh,paramSchema:vh}),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:zh,paramSchema:Sh}),i.register({name:"find_text",description:"Find and scroll to specific text on the page",function:qh,paramSchema:wh}),i.register({name:"dropdown_options",description:"Get all options from a native dropdown or ARIA menu",function:Gl,paramSchema:Th}),i.register({name:"select_dropdown",description:"Select a dropdown option by the text of the option you want to select",function:Kh,paramSchema:xh}),i.register({name:"upload_file",description:"Upload a file to a file input element",function:Vh,paramSchema:Ch}),i.register({name:"evaluate",description:"Execute JavaScript code in the browser context. Use for hover, drag, zoom, custom selectors, or analyzing page structure.",function:Xh,paramSchema:Eh}),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:Yh,paramSchema:Ih}),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:Qh,paramSchema:kh}),i.register({name:"read_file",description:"Read content from a file in the agent's file system or from available_file_paths.",function:Jh,paramSchema:Ph}),i.register({name:"replace_file",description:"Replace all occurrences of a string in a file with another string.",function:Zh,paramSchema:Ah}),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:ef,paramSchema:Dh}),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:tf,paramSchema:Mh})}var uh,dh,gh,mh,ph,hh,fh,bh,yh,vh,Sh,wh,Th,xh,Ch,Eh,Ih,kh,Ph,Ah,Dh,Mh,zl=L(()=>{"use strict";ut();zi();ji();uh=U.object({url:U.string().describe("The URL to navigate to"),new_tab:U.boolean().optional().default(!1).describe("Open in a new tab")}),dh=U.object({index:U.number().min(1).describe("The element index to click (must be >= 1)"),button:U.enum(["left","right","middle"]).optional().describe("Mouse button to use")}),gh=U.object({index:U.number().min(0).describe("The element index to type into (>= 0)"),text:U.string().describe("The text to type"),clear:U.boolean().optional().default(!0).describe("Clear existing text first")}),mh=U.object({down:U.boolean().describe("Scroll direction: true=down, false=up"),pages:U.number().optional().default(1).describe("Pages to scroll (0.5=half, 1=full, 10=to bottom/top)"),index:U.number().optional().describe("Optional element index for scrollable container")}),ph=U.object({text:U.string().describe("Summary of what was accomplished"),success:U.boolean().optional().default(!0).describe("Whether the task was successful"),files_to_display:U.array(U.string()).optional().default([]).describe("File paths to include")}),hh=U.object({seconds:U.number().describe("Number of seconds to wait")}),fh=U.object({keys:U.string().describe('Keys to send (e.g., "Enter", "Control+A")')}),bh=U.object({full_page:U.boolean().optional().describe("Capture full page")}),yh=U.object({query:U.string().describe("The search query"),engine:U.enum(["google","bing","duckduckgo"]).optional().default("duckduckgo").describe("Search engine to use")}),vh=U.object({tab_id:U.string().length(4).describe("The tab ID to switch to (exactly 4 chars from target_id)")}),Sh=U.object({tab_id:U.string().length(4).describe("The tab ID to close (exactly 4 chars from target_id)")}),wh=U.object({text:U.string().describe("The text to find and scroll to")}),Th=U.object({index:U.number().describe("The element index of the dropdown/select")}),xh=U.object({index:U.number().describe("The element index of the dropdown/select"),text:U.string().describe("The text of the option to select")}),Ch=U.object({index:U.number().describe("The element index of the file input"),path:U.string().describe("The path of the file to upload")}),Eh=U.object({code:U.string().describe("JavaScript code to execute in the browser context")}),Ih=U.object({query:U.string().describe("What information to extract from the page"),extract_links:U.boolean().optional().default(!1).describe("Whether to include URLs in extraction"),start_from_char:U.number().optional().default(0).describe("Character offset to start from (for pagination)")}),kh=U.object({file_name:U.string().describe("The filename with extension (e.g., notes.md, data.json)"),content:U.string().describe("The content to write to the file"),append:U.boolean().optional().default(!1).describe("Append to existing file instead of overwriting"),trailing_newline:U.boolean().optional().default(!0).describe("Add trailing newline"),leading_newline:U.boolean().optional().default(!1).describe("Add leading newline")}),Ph=U.object({file_name:U.string().describe("The filename to read")}),Ah=U.object({file_name:U.string().describe("The filename to modify"),old_str:U.string().describe("The string to find and replace"),new_str:U.string().describe("The replacement string")}),Dh=U.object({pattern:U.string().describe("Text or regex pattern to search for in page content"),regex:U.boolean().optional().default(!1).describe("Treat pattern as regex (default: literal text match)"),case_sensitive:U.boolean().optional().default(!1).describe("Case-sensitive search (default: case-insensitive)"),context_chars:U.number().optional().default(150).describe("Characters of surrounding context per match"),css_scope:U.string().optional().describe('CSS selector to limit search scope (e.g. "div#main")'),max_results:U.number().optional().default(25).describe("Maximum matches to return")}),Mh=U.object({selector:U.string().describe('CSS selector to query elements (e.g. "table tr", "a.link", "div.product")'),attributes:U.array(U.string()).optional().describe('Specific attributes to extract (e.g. ["href", "src", "class"])'),max_results:U.number().optional().default(50).describe("Maximum elements to return"),include_text:U.boolean().optional().default(!0).describe("Include text content of each element")})});import{z as Ie}from"zod";import{v4 as nf}from"uuid";function Qi(i){return i.stepNumber>=i.maxSteps-1}function Kl(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(Ol(r))}else t.push(null)}return t}function Vl(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 ql,sf,Sk,wk,Tk,Ji=L(()=>{"use strict";so();ql={useVision:"auto",visionDetailLevel:"auto",saveConversationPath:null,saveConversationPathEncoding:"utf-8",maxFailures:3,generateGif:!1,overrideSystemMessage:null,extendSystemMessage:null,includeAttributes:Rl,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},sf={messages:[]},Sk={agentId:nf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1,messageManagerState:sf,fileSystemState:null};wk=Ie.object({isDone:Ie.boolean().nullable().optional(),success:Ie.boolean().nullable().optional(),error:Ie.string().nullable().optional(),attachments:Ie.array(Ie.string()).nullable().optional(),longTermMemory:Ie.string().nullable().optional(),extractedContent:Ie.string().nullable().optional(),includeExtractedContentOnlyOnce:Ie.boolean().optional(),metadata:Ie.record(Ie.any()).nullable().optional(),includeInMemory:Ie.boolean().optional()}).refine(i=>!(i.success===!0&&i.isDone!==!0),{message:"success=True can only be set when isDone=True. For regular actions that succeed, leave success as None. Use success=False only for actions that fail."}),Tk=Ie.object({thinking:Ie.string().nullable().optional(),evaluationPreviousGoal:Ie.string().nullable().optional(),memory:Ie.string().nullable().optional(),nextGoal:Ie.string().nullable().optional(),action:Ie.array(Ie.any()).min(1)})});var ta={};et(ta,{ActionResultSchema:()=>hf,AgentOutputSchema:()=>io,DEFAULT_AGENT_SETTINGS:()=>of,createAgentHistoryList:()=>ea,createAgentOutputSchema:()=>ao,createAgentState:()=>Zi,getAgentBrain:()=>uf,getDurationSeconds:()=>lf,getFinalResult:()=>gf,isLastStep:()=>af,isSuccessful:()=>df,loadHistoryFromFile:()=>pf,saveHistoryToFile:()=>mf,validateActionResult:()=>cf});import{v4 as rf}from"uuid";import{z as ge}from"zod";function Zi(){return{agentId:rf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1}}function af(i){return i.stepNumber>=i.maxSteps-1}function cf(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 lf(i){return(i.stepEndTime-i.stepStartTime)/1e3}function uf(i){return{thinking:i.thinking,evaluationPreviousGoal:i.evaluationPreviousGoal||"",memory:i.memory||"",nextGoal:i.nextGoal||""}}function ea(i,e){return{history:[],agentId:i,task:e,createdAt:Date.now(),finalResult:null}}function df(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 gf(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 mf(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 pf(i="AgentHistory.json"){let t=await(await import("fs/promises")).readFile(i,"utf-8");return JSON.parse(t)}function ao(i){return ge.object({thinking:ge.string().nullable().optional(),evaluationPreviousGoal:ge.string().nullable().optional(),memory:ge.string().nullable().optional(),nextGoal:ge.string().nullable().optional(),action:ge.array(i).min(1)})}var of,hf,io,co=L(()=>{"use strict";of={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};hf=ge.object({isDone:ge.boolean().optional(),success:ge.boolean().nullable().optional(),error:ge.string().nullable().optional(),attachments:ge.array(ge.string()).nullable().optional(),longTermMemory:ge.string().nullable().optional(),extractedContent:ge.string().nullable().optional(),includeExtractedContentOnlyOnce:ge.boolean().optional(),metadata:ge.record(ge.any()).nullable().optional(),includeInMemory:ge.boolean().optional()}).refine(i=>!(i.success===!0&&i.isDone!==!0),{message:"success=true can only be set when isDone=true"}),io=ge.object({thinking:ge.string().nullable().optional(),evaluationPreviousGoal:ge.string().nullable().optional(),memory:ge.string().nullable().optional(),nextGoal:ge.string().nullable().optional(),action:ge.array(ge.any()).min(1)})});function Xl(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 Vl(i){i.register({name:"navigate",description:"Navigate to a URL",function:Fh,paramSchema:hh}),i.register({name:"click",description:"Click an element by index",function:Lh,paramSchema:fh}),i.register({name:"input",description:"Type text into an element",function:Uh,paramSchema:bh}),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:Bh,paramSchema:yh}),i.register({name:"go_back",description:"Navigate back in browser history",function:Wh,paramSchema:U.object({})}),i.register({name:"go_forward",description:"Navigate forward in browser history",function:Hh,paramSchema:U.object({})}),i.register({name:"refresh",description:"Refresh the current page",function:Gh,paramSchema:U.object({})}),i.register({name:"wait",description:"Wait for a specified number of seconds",function:jh,paramSchema:Sh}),i.register({name:"send_keys",description:"Send keyboard keys or shortcuts",function:zh,paramSchema:wh}),i.register({name:"screenshot",description:"Take a screenshot of the current page",function:qh,paramSchema:Th}),i.register({name:"done",description:"Mark the task as complete",function:Kh,paramSchema:vh}),i.register({name:"search",description:"Search the web using Google, Bing, or DuckDuckGo",function:Vh,paramSchema:xh}),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:Xh,paramSchema:Ch}),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:Yh,paramSchema:Eh}),i.register({name:"find_text",description:"Find and scroll to specific text on the page",function:Qh,paramSchema:Ih}),i.register({name:"dropdown_options",description:"Get all options from a native dropdown or ARIA menu",function:Kl,paramSchema:kh}),i.register({name:"select_dropdown",description:"Select a dropdown option by the text of the option you want to select",function:Jh,paramSchema:Ph}),i.register({name:"upload_file",description:"Upload a file to a file input element",function:Zh,paramSchema:Ah}),i.register({name:"evaluate",description:"Execute JavaScript code in the browser context. Use for hover, drag, zoom, custom selectors, or analyzing page structure.",function:ef,paramSchema:Dh}),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:tf,paramSchema:Mh}),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:nf,paramSchema:Rh}),i.register({name:"read_file",description:"Read content from a file in the agent's file system or from available_file_paths.",function:sf,paramSchema:Oh}),i.register({name:"replace_file",description:"Replace all occurrences of a string in a file with another string.",function:rf,paramSchema:Nh}),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:of,paramSchema:_h}),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:af,paramSchema:$h})}var hh,fh,bh,yh,vh,Sh,wh,Th,xh,Ch,Eh,Ih,kh,Ph,Ah,Dh,Mh,Rh,Oh,Nh,_h,$h,Xl=L(()=>{"use strict";ut();zi();ji();hh=U.object({url:U.string().describe("The URL to navigate to"),new_tab:U.boolean().optional().default(!1).describe("Open in a new tab")}),fh=U.object({index:U.number().min(1).describe("The element index to click (must be >= 1)"),button:U.enum(["left","right","middle"]).optional().describe("Mouse button to use")}),bh=U.object({index:U.number().min(0).describe("The element index to type into (>= 0)"),text:U.string().describe("The text to type"),clear:U.boolean().optional().default(!0).describe("Clear existing text first")}),yh=U.object({down:U.boolean().describe("Scroll direction: true=down, false=up"),pages:U.number().optional().default(1).describe("Pages to scroll (0.5=half, 1=full, 10=to bottom/top)"),index:U.number().optional().describe("Optional element index for scrollable container")}),vh=U.object({text:U.string().describe("Summary of what was accomplished"),success:U.boolean().optional().default(!0).describe("Whether the task was successful"),files_to_display:U.array(U.string()).optional().default([]).describe("File paths to include")}),Sh=U.object({seconds:U.number().describe("Number of seconds to wait")}),wh=U.object({keys:U.string().describe('Keys to send (e.g., "Enter", "Control+A")')}),Th=U.object({full_page:U.boolean().optional().describe("Capture full page")}),xh=U.object({query:U.string().describe("The search query"),engine:U.enum(["google","bing","duckduckgo"]).optional().default("duckduckgo").describe("Search engine to use")}),Ch=U.object({tab_id:U.string().length(4).describe("The tab ID to switch to (exactly 4 chars from target_id)")}),Eh=U.object({tab_id:U.string().length(4).describe("The tab ID to close (exactly 4 chars from target_id)")}),Ih=U.object({text:U.string().describe("The text to find and scroll to")}),kh=U.object({index:U.number().describe("The element index of the dropdown/select")}),Ph=U.object({index:U.number().describe("The element index of the dropdown/select"),text:U.string().describe("The text of the option to select")}),Ah=U.object({index:U.number().describe("The element index of the file input"),path:U.string().describe("The path of the file to upload")}),Dh=U.object({code:U.string().describe("JavaScript code to execute in the browser context")}),Mh=U.object({query:U.string().describe("What information to extract from the page"),extract_links:U.boolean().optional().default(!1).describe("Whether to include URLs in extraction"),start_from_char:U.number().optional().default(0).describe("Character offset to start from (for pagination)")}),Rh=U.object({file_name:U.string().describe("The filename with extension (e.g., notes.md, data.json)"),content:U.string().describe("The content to write to the file"),append:U.boolean().optional().default(!1).describe("Append to existing file instead of overwriting"),trailing_newline:U.boolean().optional().default(!0).describe("Add trailing newline"),leading_newline:U.boolean().optional().default(!1).describe("Add leading newline")}),Oh=U.object({file_name:U.string().describe("The filename to read")}),Nh=U.object({file_name:U.string().describe("The filename to modify"),old_str:U.string().describe("The string to find and replace"),new_str:U.string().describe("The replacement string")}),_h=U.object({pattern:U.string().describe("Text or regex pattern to search for in page content"),regex:U.boolean().optional().default(!1).describe("Treat pattern as regex (default: literal text match)"),case_sensitive:U.boolean().optional().default(!1).describe("Case-sensitive search (default: case-insensitive)"),context_chars:U.number().optional().default(150).describe("Characters of surrounding context per match"),css_scope:U.string().optional().describe('CSS selector to limit search scope (e.g. "div#main")'),max_results:U.number().optional().default(25).describe("Maximum matches to return")}),$h=U.object({selector:U.string().describe('CSS selector to query elements (e.g. "table tr", "a.link", "div.product")'),attributes:U.array(U.string()).optional().describe('Specific attributes to extract (e.g. ["href", "src", "class"])'),max_results:U.number().optional().default(50).describe("Maximum elements to return"),include_text:U.boolean().optional().default(!0).describe("Include text content of each element")})});import{z as Ie}from"zod";import{v4 as cf}from"uuid";function Qi(i){return i.stepNumber>=i.maxSteps-1}function Ql(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(Fl(r))}else t.push(null)}return t}function Jl(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 Yl,lf,Ek,Ik,kk,Ji=L(()=>{"use strict";oo();Yl={useVision:"auto",visionDetailLevel:"auto",saveConversationPath:null,saveConversationPathEncoding:"utf-8",maxFailures:3,generateGif:!1,overrideSystemMessage:null,extendSystemMessage:null,includeAttributes:$l,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},lf={messages:[]},Ek={agentId:cf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1,messageManagerState:lf,fileSystemState:null};Ik=Ie.object({isDone:Ie.boolean().nullable().optional(),success:Ie.boolean().nullable().optional(),error:Ie.string().nullable().optional(),attachments:Ie.array(Ie.string()).nullable().optional(),longTermMemory:Ie.string().nullable().optional(),extractedContent:Ie.string().nullable().optional(),includeExtractedContentOnlyOnce:Ie.boolean().optional(),metadata:Ie.record(Ie.any()).nullable().optional(),includeInMemory:Ie.boolean().optional()}).refine(i=>!(i.success===!0&&i.isDone!==!0),{message:"success=True can only be set when isDone=True. For regular actions that succeed, leave success as None. Use success=False only for actions that fail."}),kk=Ie.object({thinking:Ie.string().nullable().optional(),evaluationPreviousGoal:Ie.string().nullable().optional(),memory:Ie.string().nullable().optional(),nextGoal:Ie.string().nullable().optional(),action:Ie.array(Ie.any()).min(1)})});var ta={};Fe(ta,{ActionResultSchema:()=>Sf,AgentOutputSchema:()=>co,DEFAULT_AGENT_SETTINGS:()=>df,createAgentHistoryList:()=>ea,createAgentOutputSchema:()=>lo,createAgentState:()=>Zi,getAgentBrain:()=>hf,getDurationSeconds:()=>pf,getFinalResult:()=>bf,isLastStep:()=>gf,isSuccessful:()=>ff,loadHistoryFromFile:()=>vf,saveHistoryToFile:()=>yf,validateActionResult:()=>mf});import{v4 as uf}from"uuid";import{z as ge}from"zod";function Zi(){return{agentId:uf(),nSteps:1,consecutiveFailures:0,lastResult:null,lastPlan:null,lastModelOutput:null,paused:!1,stopped:!1,sessionInitialized:!1,followUpTask:!1}}function gf(i){return i.stepNumber>=i.maxSteps-1}function mf(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 pf(i){return(i.stepEndTime-i.stepStartTime)/1e3}function hf(i){return{thinking:i.thinking,evaluationPreviousGoal:i.evaluationPreviousGoal||"",memory:i.memory||"",nextGoal:i.nextGoal||""}}function ea(i,e){return{history:[],agentId:i,task:e,createdAt:Date.now(),finalResult:null}}function ff(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 bf(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 yf(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 vf(i="AgentHistory.json"){let t=await(await import("fs/promises")).readFile(i,"utf-8");return JSON.parse(t)}function lo(i){return ge.object({thinking:ge.string().nullable().optional(),evaluationPreviousGoal:ge.string().nullable().optional(),memory:ge.string().nullable().optional(),nextGoal:ge.string().nullable().optional(),action:ge.array(i).min(1)})}var df,Sf,co,uo=L(()=>{"use strict";df={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};Sf=ge.object({isDone:ge.boolean().optional(),success:ge.boolean().nullable().optional(),error:ge.string().nullable().optional(),attachments:ge.array(ge.string()).nullable().optional(),longTermMemory:ge.string().nullable().optional(),extractedContent:ge.string().nullable().optional(),includeExtractedContentOnlyOnce:ge.boolean().optional(),metadata:ge.record(ge.any()).nullable().optional(),includeInMemory:ge.boolean().optional()}).refine(i=>!(i.success===!0&&i.isDone!==!0),{message:"success=true can only be set when isDone=true"}),co=ge.object({thinking:ge.string().nullable().optional(),evaluationPreviousGoal:ge.string().nullable().optional(),memory:ge.string().nullable().optional(),nextGoal:ge.string().nullable().optional(),action:ge.array(ge.any()).min(1)})});function Zl(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 kn(i,e){return{role:"user",content:i,name:e}}function na(i,e){return{role:"system",content:i,name:e}}var sa=L(()=>{"use strict"});import{z as Re}from"zod";function zs(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 ra(i){let e=[];return i.systemMessage&&e.push(i.systemMessage),i.stateMessage&&e.push(i.stateMessage),e.push(...i.contextMessages),e}function
|
|
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=
|
|
703
|
+
${n}`}}function ra(i){let e=[];return i.systemMessage&&e.push(i.systemMessage),i.stateMessage&&e.push(i.stateMessage),e.push(...i.contextMessages),e}function eu(){return{history:{systemMessage:null,stateMessage:null,contextMessages:[]},toolId:1,agentHistoryItems:[{stepNumber:0,systemMessage:"Agent initialized"}],readStateDescription:""}}var wf,Tf,Ok,tu=L(()=>{"use strict";wf=Re.object({stepNumber:Re.number().nullable().optional(),evaluationPreviousGoal:Re.string().nullable().optional(),memory:Re.string().nullable().optional(),nextGoal:Re.string().nullable().optional(),actionResults:Re.string().nullable().optional(),error:Re.string().nullable().optional(),systemMessage:Re.string().nullable().optional()}).refine(i=>!(i.error&&i.systemMessage),{message:"Cannot have both error and systemMessage at the same time"});Tf=Re.object({systemMessage:Re.any().nullable().optional(),stateMessage:Re.any().nullable().optional(),contextMessages:Re.array(Re.any()).default([])});Ok=Re.object({history:Tf,toolId:Re.number().default(1),agentHistoryItems:Re.array(wf).default([{stepNumber:0,systemMessage:"Agent initialized"}]),readStateDescription:Re.string().default("")})});import{minimatch as oa}from"minimatch";function ia(i){return["about:blank","chrome://new-tab-page/","chrome://new-tab-page","chrome://newtab/","chrome://newtab"].includes(i)}function nu(i,e,t=!1){try{if(ia(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)),!oa(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||oa(r,g))return!0}if(oa(r,a))return!0}return!1}catch(n){return console.error(`⛔️ Error matching URL ${i} with pattern ${e}: ${n?.name}: ${n?.message}`),!1}}var aa=L(()=>{"use strict";ut()});import su from"fs";import ru from"path";import{fileURLToPath as xf}from"url";var go,mo,ca=L(()=>{"use strict";oo();aa();go=class{maxActionsPerStep;useThinking;flashMode;promptTemplate="";systemMessage;constructor(e=10,t,n,s=!0,r=!1){this.maxActionsPerStep=e,this.useThinking=s,this.flashMode=r;let o="";t?o=t:(this.loadPromptTemplate(),o=this.promptTemplate.replace("{max_actions}",String(this.maxActionsPerStep))),n&&(o+=`
|
|
704
|
+
${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=xf(t),s=ru.dirname(n),r=ru.join(s,e);su.existsSync(r)?this.promptTemplate=su.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>
|
|
@@ -749,8 +749,8 @@ You must respond with a valid JSON in this format:
|
|
|
749
749
|
"next_goal": "Your immediate next goal",
|
|
750
750
|
"action": [{"action_name": {"param": "value"}}]
|
|
751
751
|
}
|
|
752
|
-
</output>`}getSystemMessage(){return this.systemMessage}},
|
|
753
|
-
`;let n=this.browserState.domState?.llmRepresentation?.(this.includeAttributes||[])||"",s="";n.length>this.maxClickableElementsLength&&(n=n.substring(0,this.maxClickableElementsLength),s=` (truncated to ${this.maxClickableElementsLength} characters)`);let r=!1,o=!1,a="";if(this.browserState.pageInfo){let f=this.browserState.pageInfo,y=f.viewportHeight>0?f.pixelsAbove/f.viewportHeight:0,
|
|
752
|
+
</output>`}getSystemMessage(){return this.systemMessage}},mo=class{browserState;fileSystem;agentHistoryDescription;readStateDescription;task;includeAttributes;stepInfo;pageFilteredActions;maxClickableElementsLength;sensitiveData;availableFilePaths;screenshots;visionDetailLevel;includeRecentEvents;sampleImages;constructor(e){this.browserState=e.browserStateSummary,this.fileSystem=e.fileSystem,this.agentHistoryDescription=e.agentHistoryDescription||null,this.readStateDescription=e.readStateDescription||null,this.task=e.task||null,this.includeAttributes=e.includeAttributes||null,this.stepInfo=e.stepInfo||null,this.pageFilteredActions=e.pageFilteredActions||null,this.maxClickableElementsLength=e.maxClickableElementsLength||4e4,this.sensitiveData=e.sensitiveData||null,this.availableFilePaths=e.availableFilePaths||null,this.screenshots=e.screenshots||[],this.visionDetailLevel=e.visionDetailLevel||"auto",this.includeRecentEvents=e.includeRecentEvents||!1,this.sampleImages=e.sampleImages||[]}extractPageStatistics(){let e={links:0,iframes:0,shadow_open:0,shadow_closed:0,scroll_containers:0,images:0,interactive_elements:0,total_elements:0},t=this.browserState.domState?.selectorMap;if(t&&t instanceof Map){e.interactive_elements=t.size;for(let n of Array.from(t.values())){let s=(n.nodeName||"").toLowerCase();s==="a"?e.links+=1:s==="iframe"||s==="frame"?e.iframes+=1:s==="img"&&(e.images+=1),n.isScrollable&&(e.scroll_containers+=1)}}if(this.browserState.domState?.root){let n=s=>{if(!s)return 0;let r=1;if(s.children&&Array.isArray(s.children))for(let o of s.children)r+=n(o);return r};e.total_elements=n(this.browserState.domState.root)}else t&&(e.total_elements=t.size);if(this.browserState.domState?.root){let n=s=>{if(!s||!s.originalNode)return;let r=s.originalNode;s.isShadowHost&&(s.children.some(a=>a.originalNode.nodeType===11&&a.originalNode.shadowRootType&&a.originalNode.shadowRootType.toLowerCase()==="closed")?e.shadow_closed+=1:e.shadow_open+=1);for(let o of s.children)n(o)};n(this.browserState.domState.root)}return e}getBrowserStateDescription(){let e=this.extractPageStatistics(),t="<page_stats>";e.total_elements<10&&(t+="Page appears empty (SPA not loaded?) - "),t+=`${e.links} links, ${e.interactive_elements} interactive, `,t+=`${e.iframes} iframes, ${e.scroll_containers} scroll containers`,(e.shadow_open>0||e.shadow_closed>0)&&(t+=`, ${e.shadow_open} shadow(open), ${e.shadow_closed} shadow(closed)`),e.images>0&&(t+=`, ${e.images} images`),t+=`, ${e.total_elements} total elements`,t+=`</page_stats>
|
|
753
|
+
`;let n=this.browserState.domState?.llmRepresentation?.(this.includeAttributes||[])||"",s="";n.length>this.maxClickableElementsLength&&(n=n.substring(0,this.maxClickableElementsLength),s=` (truncated to ${this.maxClickableElementsLength} characters)`);let r=!1,o=!1,a="";if(this.browserState.pageInfo){let f=this.browserState.pageInfo,y=f.viewportHeight>0?f.pixelsAbove/f.viewportHeight:0,T=f.viewportHeight>0?f.pixelsBelow/f.viewportHeight:0;r=y>0,o=T>0;let x=f.viewportHeight>0?f.pageHeight/f.viewportHeight:0;a="<page_info>",a+=`${y.toFixed(1)} pages above, `,a+=`${T.toFixed(1)} pages below, `,a+=`${x.toFixed(1)} total pages`,a+=`</page_info>
|
|
754
754
|
`}if(n!==""){if(r&&this.browserState.pageInfo){let f=this.browserState.pageInfo;n=`... ${(f.viewportHeight>0?f.pixelsAbove/f.viewportHeight:0).toFixed(1)} pages above - scroll to see more or extract structured data if you are looking for specific information ...
|
|
755
755
|
${n}`}else n=`[Start of page]
|
|
756
756
|
${n}`;if(o&&this.browserState.pageInfo){let f=this.browserState.pageInfo,y=f.viewportHeight>0?f.pixelsBelow/f.viewportHeight:0;n=`${n}
|
|
@@ -797,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
|
|
800
|
+
`),e&&this.screenshots.length>0){let s=[{type:"text",text:t}];s.push(...this.sampleImages);for(let r=0;r<this.screenshots.length;r++){let o=this.screenshots[r],a=r===this.screenshots.length-1?"Current screenshot:":"Previous screenshot:";s.push({type:"text",text:a}),s.push({type:"image_url",imageUrl:{url:`data:image/jpeg;base64,${o}`,mediaType:"image/jpeg",detail:this.visionDetailLevel}})}return{role:"user",content:s,cache:!0}}return{role:"user",content:t,cache:!0}}}});var po,ou=L(()=>{"use strict";tu();ca();sa();aa();po=class{task;state;systemPrompt;fileSystem;sensitiveDataDescription="";useThinking;maxHistoryItems;visionDetailLevel;includeToolCallExamples;includeRecentEvents;sampleImages;includeAttributes;sensitiveData;lastInputMessages=[];lastStateMessageText;constructor(e){if(this.task=e.task,this.state=e.state||eu(),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");ra(this.state.history).length===0&&this.setMessageWithType(this.systemPrompt,"system")}get agentHistoryDescription(){if(this.maxHistoryItems===null)return this.state.agentHistoryItems.map(zs).join(`
|
|
801
801
|
`);let e=this.state.agentHistoryItems.length;if(e<=this.maxHistoryItems)return this.state.agentHistoryItems.map(zs).join(`
|
|
802
802
|
`);let t=e-this.maxHistoryItems,n=this.maxHistoryItems-1,s=[zs(this.state.agentHistoryItems[0]),`<sys>[... ${t} previous steps omitted...]</sys>`],r=this.state.agentHistoryItems.slice(-n);return s.push(...r.map(zs)),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,17 +810,17 @@ ${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&&
|
|
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&&nu(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
|
|
816
|
-
`).length}writeFileContent(e){this.updateContent(e)}appendFileContent(e){this.updateContent(this.content+e)}updateContent(e){this.content=e}async syncToDisk(e){let t=Ks.join(e,this.fullName);await
|
|
817
|
-
`);for(let l of a)l.trim()&&(s.text(l.trim(),{align:"left"}),s.moveDown(.5));s.end();let c=await o;await
|
|
815
|
+
`;return s+="To use them, write <secret>the placeholder name</secret>",s}return""}createStateMessages(e,t){this.state.history.contextMessages=[],this.updateAgentHistoryDescription(t?.modelOutput,t?.result,t?.stepInfo);let n=t?.sensitiveData??this.sensitiveData;n&&(this.sensitiveData=n,this.sensitiveDataDescription=this.getSensitiveDataDescription(e.url));let s=[],r=!1;if(t?.result){for(let d of t.result)if(d.metadata?.includeScreenshot){r=!0;break}}let o=t?.useVision??"auto",a=!1;o===!0?a=!0:o==="auto"&&(a=r),a&&e.screenshot&&s.push(e.screenshot);let c=s.length>0,l=new mo({browserStateSummary:e,fileSystem:this.fileSystem,agentHistoryDescription:this.agentHistoryDescription,readStateDescription:this.state.readStateDescription,task:this.task,includeAttributes:this.includeAttributes,stepInfo:t?.stepInfo,pageFilteredActions:t?.pageFilteredActions,sensitiveData:this.sensitiveDataDescription,availableFilePaths:t?.availableFilePaths,screenshots:s,visionDetailLevel:this.visionDetailLevel,includeRecentEvents:this.includeRecentEvents,sampleImages:this.sampleImages}).getUserMessage(c);this.lastStateMessageText=Zl(l),this.setMessageWithType(l,"state")}getMessages(){return this.lastInputMessages=ra(this.state.history),this.lastInputMessages}setMessageWithType(e,t){if(t==="system")this.state.history.systemMessage=e;else if(t==="state")this.state.history.stateMessage=e;else throw new Error(`Invalid state message type: ${t}`)}addContextMessage(e){this.state.history.contextMessages.push(e)}filterSensitiveData(e){if(!this.sensitiveData)return e;let t=s=>{if(!this.sensitiveData)return s;let r={};for(let[o,a]of Object.entries(this.sensitiveData))if(typeof a=="object"&&a!==null)for(let[c,l]of Object.entries(a))l&&(r[c]=l);else a&&(r[o]=a);for(let[o,a]of Object.entries(r)){let c=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(c,"g"),`<secret>${o}</secret>`)}return s},n={...e};return typeof n.content=="string"?n.content=t(n.content):Array.isArray(n.content)&&(n.content=n.content.map(s=>s.type==="text"&&s.text?{...s,text:t(s.text)}:s)),n}getFilteredMessages(){return this.getMessages().map(t=>this.filterSensitiveData(t))}}});import fo from"fs/promises";import Jt from"fs";import Ks from"path";var ho,Cf,Pn,Zt,qs,bo,yo,vo,So,wo,To,iu=L(()=>{"use strict";ut();js();ho="Error: Invalid filename format. Must be alphanumeric with supported extension.",Cf="browseruse_agent_data",Pn=class extends Error{constructor(e){super(e),this.name="FileSystemError"}},Zt=class{name;content;constructor(e,t=""){this.name=e,this.content=t}get fullName(){return`${this.name}.${this.extension}`}get size(){return this.content.length}get lineCount(){return this.content.split(`
|
|
816
|
+
`).length}writeFileContent(e){this.updateContent(e)}appendFileContent(e){this.updateContent(this.content+e)}updateContent(e){this.content=e}async syncToDisk(e){let t=Ks.join(e,this.fullName);await fo.writeFile(t,this.content,"utf-8")}syncToDiskSync(e){let t=Ks.join(e,this.fullName);Jt.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}},qs=class extends Zt{get extension(){return"md"}},bo=class extends Zt{get extension(){return"txt"}},yo=class extends Zt{get extension(){return"json"}},vo=class extends Zt{get extension(){return"csv"}},So=class extends Zt{get extension(){return"jsonl"}},wo=class extends Zt{get extension(){return"pdf"}async syncToDisk(e){let t=Ks.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(Gs.sm);let a=this.content.split(`
|
|
817
|
+
`);for(let l of a)l.trim()&&(s.text(l.trim(),{align:"left"}),s.moveDown(.5));s.end();let c=await o;await fo.writeFile(t,c);return}}catch(n){b.debug("PDFKit not available, writing text file with .pdf extension:",n)}await fo.writeFile(t,this.content,"utf-8")}syncToDiskSync(e){let t=Ks.join(e,this.fullName);Jt.writeFileSync(t,this.content,"utf-8")}},To=class i{baseDir;dataDir;files=new Map;extractedContentCount=0;defaultFiles=["todo.md"];fileTypes={md:qs,txt:bo,json:yo,jsonl:So,csv:vo,pdf:wo};constructor(e,t=!0){this.baseDir=e,this.dataDir=Ks.join(e,Cf);try{Jt.existsSync(this.baseDir)||Jt.mkdirSync(this.baseDir,{recursive:!0}),Jt.existsSync(this.dataDir)&&Jt.rmSync(this.dataDir,{recursive:!0,force:!0}),Jt.mkdirSync(this.dataDir,{recursive:!0})}catch(n){throw new Pn(`Failed to create file system directories: ${n.message}`)}t&&this.createDefaultFiles()}getAllowedExtensions(){return Object.keys(this.fileTypes)}getFileTypeClass(e){return this.fileTypes[e.toLowerCase()]||null}createDefaultFiles(){for(let e of this.defaultFiles){let[t,n]=this.parseFilename(e),s=this.getFileTypeClass(n);if(!s)throw new Error(`Error: Invalid file extension '${n}' for file '${e}'.`);let r=new s(t);this.files.set(e,r),r.syncToDiskSync(this.dataDir)}}isValidFilename(e){let t=Object.keys(this.fileTypes).join("|");return new RegExp(`^[a-zA-Z0-9_\\-]+\\.(${t})$`).test(e)}parseFilename(e){let t=e.lastIndexOf(".");if(t===-1)throw new Error("Invalid filename: no extension found");let n=e.substring(0,t),s=e.substring(t+1).toLowerCase();return[n,s]}getDir(){return this.dataDir}getFile(e){return this.isValidFilename(e)&&this.files.get(e)||null}async listFiles(){return Array.from(this.files.values()).map(e=>e.fullName)}displayFile(e){if(!this.isValidFilename(e))return null;let t=this.getFile(e);return t?t.read():null}async readFile(e,t=!1){if(t)try{let s;try{[,s]=this.parseFilename(e)}catch{return`Error: Invalid filename format ${e}. Must be alphanumeric with a supported extension.`}if(["md","txt","json","jsonl","csv"].includes(s)){let r=await fo.readFile(e,"utf-8");return`Read from file ${e}.
|
|
818
818
|
<content>
|
|
819
819
|
${r}
|
|
820
|
-
</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
|
|
820
|
+
</content>`}else return s==="pdf"?"Error: PDF reading not yet implemented for external files.":`Error: Cannot read file ${e} as ${s} extension is not supported.`}catch(s){return s.code==="ENOENT"?`Error: File '${e}' not found.`:s.code==="EACCES"?`Error: Permission denied to read file '${e}'.`:`Error: Could not read file '${e}'.`}if(!this.isValidFilename(e))return ho;let n=this.getFile(e);if(!n)return`File '${e}' not found.`;try{let s=n.read();return`Read from file ${e}.
|
|
821
821
|
<content>
|
|
822
822
|
${s}
|
|
823
|
-
</content>`}catch(s){return s instanceof Pn?s.message:`Error: Could not read file '${e}'.`}}async writeFile(e,t){if(!this.isValidFilename(e))return
|
|
823
|
+
</content>`}catch(s){return s instanceof Pn?s.message:`Error: Could not read file '${e}'.`}}async writeFile(e,t){if(!this.isValidFilename(e))return ho;try{let[n,s]=this.parseFilename(e),r=this.getFileTypeClass(s);if(!r)throw new Error(`Error: Invalid file extension '${s}' for file '${e}'.`);let o=this.files.get(e);if(!o){let a=new r(n);this.files.set(e,a),o=a}return await o.write(t,this.dataDir),`Data written to file ${e} successfully.`}catch(n){return n instanceof Pn?n.message:`Error: Could not write to file '${e}'. ${n.message}`}}async appendFile(e,t){if(!this.isValidFilename(e))return ho;let n=this.getFile(e);if(!n)return`File '${e}' not found.`;try{return await n.append(t,this.dataDir),`Data appended to file ${e} successfully.`}catch(s){return s instanceof Pn?s.message:`Error: Could not append to file '${e}'. ${s.message}`}}async replaceFileStr(e,t,n){if(!this.isValidFilename(e))return ho;if(!t)return"Error: Cannot replace empty string. Please provide a non-empty string to replace.";let s=this.getFile(e);if(!s)return`File '${e}' not found.`;try{let r=s.read();return r=r.replace(new RegExp(t,"g"),n),await s.write(r,this.dataDir),`Successfully replaced all occurrences of "${t}" with "${n}" in file ${e}`}catch(r){return r instanceof Pn?r.message:`Error: Could not replace string in file '${e}'. ${r.message}`}}async saveExtractedContent(e){let t=`extracted_content_${this.extractedContentCount}`,n=`${t}.md`,s=new qs(t);return await s.write(e,this.dataDir),this.files.set(n,s),this.extractedContentCount+=1,n}describe(){let t="";for(let n of this.files.values()){if(n.fullName==="todo.md")continue;let s=n.read();if(!s){t+=`<file>
|
|
824
824
|
${n.fullName} - [empty file]
|
|
825
825
|
</file>
|
|
826
826
|
`;continue}let r=s.split(`
|
|
@@ -846,7 +846,7 @@ ${l}
|
|
|
846
846
|
`,t+=`${m}
|
|
847
847
|
`,t+=`</content>
|
|
848
848
|
</file>
|
|
849
|
-
`)}return t.trim()}getTodoContents(){let e=this.getFile("todo.md");return e?e.read():""}getState(){let e={};for(let[t,n]of this.files.entries())e[t]={type:n.constructor.name,data:{name:n.name,content:n.content}};return{files:e,baseDir:this.baseDir,extractedContentCount:this.extractedContentCount}}nuke(){Jt.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 qs(o.name,o.content);break;case"TxtFile":a=new
|
|
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(){Jt.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 qs(o.name,o.content);break;case"TxtFile":a=new bo(o.name,o.content);break;case"JsonFile":a=new yo(o.name,o.content);break;case"JsonlFile":a=new So(o.name,o.content);break;case"CsvFile":a=new vo(o.name,o.content);break;case"PdfFile":a=new wo(o.name,o.content);break;default:continue}t.files.set(n,a),a.syncToDiskSync(t.dataDir)}return t}}});import*as en from"fs/promises";import*as la from"path";var xo,au=L(()=>{"use strict";xo=class{agentDirectory;screenshotsDir;constructor(e){this.agentDirectory=e,this.screenshotsDir=la.join(this.agentDirectory,"screenshots")}async initialize(){await en.mkdir(this.screenshotsDir,{recursive:!0})}async storeScreenshot(e,t){let n=`step_${t}.png`,s=la.join(this.screenshotsDir,n),r=Buffer.from(e,"base64");return await en.writeFile(s,r),s}async getScreenshot(e){if(!e)return null;try{return await en.access(e),(await en.readFile(e)).toString("base64")}catch{return null}}}});import{z}from"zod";async function lu(i){if(!i)return null;try{let e=await import("fs/promises"),t=await import("path");return await e.access(i).then(()=>!0).catch(()=>!1)?(await e.readFile(i)).toString("base64"):null}catch{return null}}var Co,cu,Ef,If,kf,dP,gP,uu=L(()=>{"use strict";Co="iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAFElEQVR4nGP8//8/AwwwMSAB3BwAlm4DBfIlvvkAAAAASUVORK5CYII=",cu=z.object({url:z.string(),title:z.string(),targetId:z.string(),parentTargetId:z.string().nullable().optional()}),Ef=z.object({viewportWidth:z.number(),viewportHeight:z.number(),pageWidth:z.number(),pageHeight:z.number(),scrollX:z.number(),scrollY:z.number(),pixelsAbove:z.number(),pixelsBelow:z.number(),pixelsLeft:z.number(),pixelsRight:z.number()}),If=z.object({url:z.string(),method:z.string().default("GET"),loadingDurationMs:z.number().default(0),resourceType:z.string().nullable().optional()}),kf=z.object({buttonType:z.string(),backendNodeId:z.number(),text:z.string(),selector:z.string(),isDisabled:z.boolean().default(!1)}),dP=z.object({domState:z.any(),url:z.string(),title:z.string(),tabs:z.array(cu),screenshot:z.string().nullable().optional(),pageInfo:Ef.nullable().optional(),pixelsAbove:z.number().default(0),pixelsBelow:z.number().default(0),browserErrors:z.array(z.string()).default([]),isPdfViewer:z.boolean().default(!1),recentEvents:z.string().nullable().optional(),pendingNetworkRequests:z.array(If).default([]),paginationButtons:z.array(kf).default([])}),gP=z.object({url:z.string(),title:z.string(),tabs:z.array(cu),interactedElement:z.array(z.any().nullable()),screenshotPath:z.string().nullable().optional()})});import*as ua from"fs";async function du(i){try{return await import(i)}catch{throw new Error(`Module '${i}' not available. Install with: npm install ${i}`)}}function gu(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 mu(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 Pf(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 lu(r);t.push(a)}else o?t.push(o):e&&t.push(null)}return t}async function pu(i){let{task:e,history:t,outputPath:n="agent_history.gif",duration:s=3e3,showGoals:r=!0,showTask:o=!0,showLogo:a=!1,fontSize:c=io.text,titleFontSize:l=io.title,goalFontSize:d=io.goal,margin:g=40,lineSpacing:m=1.5}=i;if(!t.history||t.history.length===0){console.warn("[GIF] No history to create GIF from");return}let p=await Pf(t,!0);if(!p||p.length===0){console.warn("[GIF] No screenshots found in history");return}let h=null;for(let f of p)if(f&&f!==Co){h=f;break}if(!h){console.warn("[GIF] No valid screenshots found (all are placeholders or from new tab pages)");return}try{await Af({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 Of({task:e,history:t,screenshots:p,outputPath:n.replace(".gif",".html"),duration:s,showGoals:r,showTask:o})}}async function Af(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 w=await du("sharp");p=w.default||w}catch(w){throw new Error(`sharp library not available: ${w.message}`)}let h;try{let w=await du("gif-encoder-2");h=w.default||w}catch(w){throw new Error(`gif-encoder-2 library not available: ${w.message}`)}let f=Buffer.from(s,"base64"),y=await p(f).metadata(),T=y.width||1920,x=y.height||1080,S=new h(T,x,"neuquant",!0);S.setDelay(o),S.setRepeat(0),S.setQuality(10),S.start();let C=[];if(c&&e){let w=await Df(p,e,s,T,x,l,g);C.push(w)}let v=0;for(let w=0;w<t.history.length;w++){let E=t.history[w],P=n[w];if(!P)continue;if(P===Co){b.debug(`[GIF] Skipping placeholder screenshot from about:blank page at step ${w+1}`);continue}if(gu(E.state.url)){b.debug(`[GIF] Skipping screenshot from new tab page (${E.state.url}) at step ${w+1}`);continue}v++;let D=Buffer.from(P,"base64");if(a&&E.modelOutput){let $=E.modelOutput.currentState?.nextGoal||E.modelOutput.nextGoal||"",R=await Mf(p,D,v,$,T,x,l,d,g);C.push(R)}else{let $=await p(D).resize(T,x,{fit:"fill"}).raw().toBuffer();C.push($)}}if(C.length===0){console.warn("[GIF] No valid frames to create GIF");return}for(let w of C)S.addFrame(w);S.finish();let I=S.out.getData();ua.writeFileSync(r,I)}async function Df(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 Mf(i,e,t,n,s,r,o,a,c){let l=mu(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
|
-
${Vs(
|
|
872
|
+
${Vs(Rf(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 Vs(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function
|
|
875
|
+
`;return await i(e).resize(s,r,{fit:"fill"}).composite([{input:Buffer.from(d),top:0,left:0}]).raw().toBuffer()}function Vs(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Rf(i,e){return i.length<=e?i:i.substring(0,e-3)+"..."}async function Of(i){let{task:e,history:t,screenshots:n,outputPath:s,duration:r,showGoals:o,showTask:a}=i,c=[],l=0;for(let g=0;g<t.history.length;g++){let m=t.history[g],p=n[g];if(!p||p===Co||gu(m.state.url))continue;l++;let h=o&&m.modelOutput&&(m.modelOutput.currentState?.nextGoal||m.modelOutput.nextGoal)||"";c.push({screenshot:p,stepNumber:l,goal:mu(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>`;ua.writeFileSync(s,d),console.info(`[GIF] Created HTML viewer at ${s}`)}var
|
|
1143
|
+
</html>`;ua.writeFileSync(s,d),console.info(`[GIF] Created HTML viewer at ${s}`)}var hu=L(()=>{"use strict";ut();Ji();uu();js()});import{v4 as Nf}from"uuid";import fu from"fs/promises";import Eo from"path";import _f from"os";import $f from"crypto";import{spawnSync as Ff}from"child_process";import{zodToJsonSchema as Lf}from"zod-to-json-schema";var Xs,bu=L(()=>{"use strict";ut();Xi();so();jl();Xl();Ji();uo();sa();ou();ca();iu();au();hu();Xs=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=Nf(),this.task=e.task,this.llm=e.llm,this.maxSteps=e.maxSteps||100,this.outputSchema=e.outputSchema,this.settings={...Yl,...e.settings},e.browserSession)this.browserSession=e.browserSession,this.ownsBrowserSession=!1;else{let a={headless:!1};if(es())try{let c=Bs();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 In(a),this.ownsBrowserSession=!0}this.pageId=e.pageId,this.pageId&&b.log(`🔀 [Agent] Multi-agent mode: Agent ${this.id.substring(0,8)} assigned to tab ${this.pageId}`),e.actionRegistry?this.actionRegistry=e.actionRegistry:(this.actionRegistry=new ao,Vl(this.actionRegistry));let t=this.actionRegistry.createActionModel();this.dynamicAgentOutputSchema=lo(t);let n=this.actionRegistry.createActionModel(["done"]);this.doneAgentOutputSchema=lo(n),this.state=Zi(),this.history=ea(this.id,this.task);let s=_f.tmpdir();this.agentDirectory=Eo.join(s,`browser_use_agent_${this.id}`),this.fileSystem=new To(this.agentDirectory),this.screenshotService=new xo(this.agentDirectory),this.settings.directlyOpenUrl&&(this.initialUrl=this._extractStartUrl(this.task),this.initialUrl&&(b.log(`🔗 Found URL in task: ${this.initialUrl}, adding as initial action...`),this.initialActions=[{navigate:{url:this.initialUrl,new_tab:!1}}]));let o=new go(this.settings.maxActionsPerStep,this.settings.overrideSystemMessage,this.settings.extendSystemMessage,this.settings.useThinking,this.settings.flashMode).getSystemMessage();this.messageManager=new po({task:this.task,systemMessage:o,fileSystem:this.fileSystem,useThinking:this.settings.useThinking,includeAttributes:this.settings.includeAttributes??void 0,sensitiveData:this.sensitiveData,maxHistoryItems:this.settings.maxHistoryItems??void 0,visionDetailLevel:this.settings.visionDetailLevel,includeToolCallExamples:this.settings.includeToolCallExamples,includeRecentEvents:this.settings.includeRecentEvents,sampleImages:this.settings.sampleImages??void 0}),this.registerNewStepCallback=e.registerNewStepCallback,this.registerDoneCallback=e.registerDoneCallback,this.registerShouldStopCallback=e.registerShouldStopCallback,this.registerExternalAgentStatusRaiseErrorCallback=e.registerExternalAgentStatusRaiseErrorCallback,this.sensitiveData=e.sensitiveData}async run(e=100){let t=null;try{b.log(`🤖 Starting agent ${this.id.substring(0,8)} with task: ${this.task}`),b.log(`🔧 Agent setup: Session ID ${this.id.substring(this.id.length-4)}, max_steps: ${e}`);let n=Date.now();await this.screenshotService.initialize(),await this.browserSession.start();try{await this._executeInitialActions()}catch(s){if(!(s instanceof Error&&s.message==="Interrupted"))throw s}b.log(`🔄 Starting main execution loop with max ${e} steps...`);for(let s=0;s<e;s++){if(this.state.consecutiveFailures>=this.settings.maxFailures+(this.settings.finalResponseAfterFailure?1:0)){console.error(`❌ Stopping due to ${this.settings.maxFailures} consecutive failures`),t=`Stopped due to ${this.settings.maxFailures} consecutive failures`;break}if(this.state.stopped){b.log("🛑 Agent stopped"),t="Agent stopped programmatically";break}if(this.state.paused){for(b.log("⏸️ Agent paused, waiting for resume...");this.state.paused;)this.pausePromise?await this.pausePromise:await new Promise(a=>setTimeout(a,100));b.log("▶️ Agent resumed, continuing...")}let r={stepNumber:s,maxSteps:e};if(await this._executeStep(s,e,r)){b.log("✅ Task completed successfully"),this.registerDoneCallback&&await this.registerDoneCallback(this.history);break}}return this.state.nSteps>=e&&!this.state.stopped&&(t="Failed to complete task in maximum steps",b.log(`❌ ${t}`),this.history.push({modelOutput:null,result:[{error:t,includeInMemory:!0}],state:{url:"",title:"",tabs:[],interactedElement:[],screenshot:null,downloadedFiles:[],selectorMap:{}}})),this.history}catch(n){throw console.error("Agent run failed with exception:",n),t=n instanceof Error?n.message:String(n),n}finally{if(b.log("🧹 Cleaning up agent resources..."),this.settings.generateGif)try{let n=typeof this.settings.generateGif=="string"?this.settings.generateGif:Eo.join(this.agentDirectory,"agent_history.gif");b.log("📹 Generating GIF..."),await pu({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(na(s));for(let o of this.history.history){let a=this.formatBrowserState(o.state);if(n.push(kn(a)),o.modelOutput){let c=JSON.stringify(o.modelOutput);n.push({role:"assistant",content:c})}}let r=this.formatCurrentState(e,t);return n.push(kn(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||
|
|
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
|
|
1172
|
+
What is your next action?`}async callLLM(e){if(this.outputSchema)return(await this.llm.ainvoke(e,this.outputSchema)).completion;let t=this.dynamicAgentOutputSchema||co;return(await this.llm.ainvoke(e,t)).completion}async executeActions(e){let t=[];for(let n=0;n<Math.min(e.length,this.settings.maxActionsPerStep);n++){let s=e[n],r=Object.keys(s)[0],o=s[r];b.log(` ⚡ Executing action ${n+1}/${e.length}: ${r}`);try{let a=this._createActionContext(),c=await this.actionRegistry.execute(r,o,a);if(t.push(c),c.isDone)break;if(c.error){console.error(` ❌ Error: ${c.error}`);break}}catch(a){console.error(` ❌ Failed to execute ${r}:`,a.message),t.push({error:`Failed to execute ${r}: ${a.message}`});break}}return t}logModelOutput(e){if(e.thinking&&this.settings.useThinking&&b.log(` 💡 Thinking: ${e.thinking.substring(0,100)}...`),e.evaluationPreviousGoal){let t=e.evaluationPreviousGoal;t.toLowerCase().includes("success")?b.log(` ✅ Eval: ${t}`):t.toLowerCase().includes("failure")?b.log(` ❌ Eval: ${t}`):b.log(` ❔ Eval: ${t}`)}e.memory&&b.log(` 🧠 Memory: ${e.memory}`),e.nextGoal&&b.log(` 🎯 Next goal: ${e.nextGoal}`)}browserStateToHistory(e){return{url:e.url,title:e.title,tabs:[],screenshot:e.screenshot}}async attemptFinalRecovery(){b.log("🔄 Attempting final recovery...");try{let e=[];e.push(na("You have exceeded the maximum number of failures. Provide a final summary of what was accomplished and what could not be completed."));let t=await this.llm.ainvoke(e);return{isDone:!0,success:!1,longTermMemory:typeof t.completion=="string"?t.completion:JSON.stringify(t.completion)}}catch{return{isDone:!0,success:!1,error:"Failed to generate final recovery response"}}}async saveConversationStep(e){if(!(!this.settings.saveConversationPath||!this.state.lastModelOutput))try{let t=Eo.resolve(this.settings.saveConversationPath),n=`conversation_${this.id}_${this.state.nSteps}.txt`,s=Eo.join(t,n);await 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 T=await this.browserSession.getCurrentPageUrl();if(T!==r&&T!==""&&r!==""){let x=s-o-1;b.log(`🔄 Page navigation detected: ${r} → ${T}`),b.log(`📍 Interrupting remaining ${x} actions (element indices now stale)`),this.browserSession.clearCachedState(),x>0&&t.push({extractedContent:`Page navigated to ${T}. Skipped ${x} remaining action(s) because element indices are now stale.`});break}r=T}catch{}if(t[t.length-1].isDone||t[t.length-1].error||o===s-1)break}catch(c){let l=c.message||String(c);console.error(`❌ Executing action ${o+1} failed: ${l}`),t.push({error:`Action failed: ${l}`});break}}return t}_logAction(e,t,n,s){let r="\x1B[34m",o="\x1B[35m",a="\x1B[0m",c;s>1?c=`▶️ [${n}/${s}] ${r}${t}${a}:`:c=`▶️ ${r}${t}${a}:`;let d=e[t],g=[];if(d&&typeof d=="object")for(let[m,p]of Object.entries(d)){let h=p;typeof p=="string"&&p.length>150?h=p.substring(0,150)+"...":Array.isArray(p)&&JSON.stringify(p).length>200&&(h=JSON.stringify(p).substring(0,200)+"..."),typeof h=="string"&&this.sensitiveData&&(h=Jl(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,44 +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=
|
|
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=Ql(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&&Qi(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(kn(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(kn(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&&!Qi(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(kn(o))}}async _getModelOutputWithRetry(e){let t=this.dynamicAgentOutputSchema||
|
|
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(kn(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&&!Qi(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(kn(o))}}async _getModelOutputWithRetry(e){let t=this.dynamicAgentOutputSchema||co,n=this._processMessagesAndReplaceLongUrls(e),r=(await this.llm.ainvoke(e,t)).completion;Object.keys(n).length>0&&this._restoreShortenedUrlsInAgentOutput(r,n),b.log(`✅ Step ${this.state.nSteps}: Got LLM response with ${r.action?.length??0} actions`);let o=a=>!a||!Array.isArray(a)||a.length===0?!0:a.every(c=>!c||typeof c!="object"?!0:Object.keys(c).length===0);if(o(r.action)){console.warn("Model returned empty action. Retrying...");let a=kn("You forgot to return an action. Please respond with a valid JSON action according to the expected schema with your assessment and next actions."),c=[...e,a];r=(await this.llm.ainvoke(c,t)).completion,o(r.action)&&(console.warn("Model still returned empty after retry. Inserting safe done action."),r={...r,action:[{done:{success:!1,text:"No next action returned by LLM!"}}]})}return r.action&&r.action.length>this.settings.maxActionsPerStep&&(b.log(`✂️ Limiting actions from ${r.action.length} to ${this.settings.maxActionsPerStep}`),r.action=r.action.slice(0,this.settings.maxActionsPerStep)),r}async _handlePostLLMProcessing(e,t){this.registerNewStepCallback&&this.state.lastModelOutput&&await this.registerNewStepCallback(e,this.state.lastModelOutput,this.state.nSteps),this.settings.saveConversationPath&&this.state.lastModelOutput&&await this.saveConversationStep(t)}async _checkStopOrPause(){if(this.registerShouldStopCallback&&await this.registerShouldStopCallback())throw b.log("External callback requested stop"),this.state.stopped=!0,new Error("Interrupted");if(this.registerExternalAgentStatusRaiseErrorCallback&&await this.registerExternalAgentStatusRaiseErrorCallback())throw new Error("Interrupted");if(this.state.stopped)throw new Error("Interrupted");if(this.state.paused)throw new Error("Interrupted")}async saveHistory(e="AgentHistory.json"){let{saveHistoryToFile:t}=await Promise.resolve().then(()=>(uo(),ta));await t(this.history,e,this.sensitiveData),b.log(`📝 Saved agent history to ${e}`)}async loadAndRerun(e="AgentHistory.json",t){let{loadHistoryFromFile:n}=await Promise.resolve().then(()=>(uo(),ta)),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=$f.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=Lf(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;)
|
|
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;)Ff("sleep",["0.01"]);if(o)throw o;return r}}});import{zodToJsonSchema as Uf}from"zod-to-json-schema";var Io,yu=L(()=>{"use strict";Io=class{static createOptimizedJsonSchema(e){let t=Uf(e,{$refStrategy:"none"}),n=t.$defs||{},s=(c,l,d=!1)=>{if(typeof c=="object"&&c!==null&&!Array.isArray(c)){let g={},m=null,p=["additionalProperties","$defs","$schema"];for(let[h,f]of Object.entries(c))if(!p.includes(h)&&!(h==="title"&&!d))if(h==="description")f&&(g[h]=f);else if(h==="type")g[h]=f;else if(h==="$ref"&&l){let y=f.split("/").pop();if(y&&l[y]){let T=l[y];m=s(T,l)}}else h==="anyOf"&&Array.isArray(f)?g[h]=f.map(y=>s(y,l)):h==="properties"||h==="items"?g[h]=s(f,l,h==="properties"):["type","required","minimum","maximum","minItems","maxItems","pattern","default"].includes(h)?g[h]=typeof f=="object"&&f!==null?s(f,l):f:g[h]=typeof f=="object"&&f!==null||Array.isArray(f)?s(f,l):f;if(m!==null){let h={...m};for(let[f,y]of Object.entries(g))(f==="description"&&!("description"in h)||f!=="description")&&(h[f]=y);return h}else return g.type==="object"&&(g.additionalProperties=!1),g}else if(Array.isArray(c))return c.map(g=>s(g,l,d));return c},r=s(t,n);if(typeof r!="object"||r===null)throw new Error("Optimized schema result is not a dictionary");let o=r,a=c=>{if(typeof c=="object"&&c!==null&&!Array.isArray(c)){c.type==="object"&&(c.additionalProperties=!1);for(let l of Object.values(c))typeof l=="object"&&l!==null&&a(l)}else if(Array.isArray(c))for(let l of c)typeof l=="object"&&l!==null&&a(l)};return a(o),this.ensureArraysHaveItems(o),this.makeStrictCompatible(o),o}static ensureArraysHaveItems(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){e.type==="array"&&!("items"in e)&&(e.items={});for(let t of Object.values(e))typeof t=="object"&&t!==null&&this.ensureArraysHaveItems(t)}else if(Array.isArray(e))for(let t of e)typeof t=="object"&&t!==null&&this.ensureArraysHaveItems(t)}static makeStrictCompatible(e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&t!=="required"&&this.makeStrictCompatible(n);if(e.type==="object"){"properties"in e||(e.properties={});let t=Object.keys(e.properties);e.required=t}}else if(Array.isArray(e))for(let t of e)this.makeStrictCompatible(t)}static createGeminiOptimizedSchema(e){let t=this.createOptimizedJsonSchema(e),n=s=>{if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let r={};for(let[o,a]of Object.entries(s))o!=="required"&&(r[o]=n(a));return r}else if(Array.isArray(s))return s.map(n);return s};return n(t)}}});import Bf from"openai";var Wf,da,Ys,vu=L(()=>{"use strict";yu();Wf=["o4-mini","o3","o3-mini","o1","o1-pro","gpt-5","gpt-5-mini","gpt-5-nano"],da=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}`)})}},Ys=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
|
|
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}`)})}},Ys=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=Wf.some(n=>t.includes(n.toLowerCase())),this.client=new Bf({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=da.serializeMessages(e),s={model:this.model,messages:n};this.isReasoningModel?s.reasoning_effort=this.reasoningEffort:(s.temperature=this.temperature,s.frequency_penalty=this.frequencyPenalty),this.topP!==void 0&&(s.top_p=this.topP),this.seed!==void 0&&(s.seed=this.seed);try{if(t){let r=Io.createOptimizedJsonSchema(t),o=await this.client.chat.completions.create({...s,response_format:{type:"json_schema",json_schema:{name:"response",strict:!0,schema:r}}}),a=this.getUsage(o),c=o.choices[0]?.message?.content||"{}",l=JSON.parse(c);return{completion:t.parse(l),usage:a,stopReason:o.choices[0]?.finish_reason??null}}else{let r=await this.client.chat.completions.create(s),o=this.getUsage(r);return{completion:r.choices[0]?.message?.content||"",usage:o,stopReason:r.choices[0]?.finish_reason??null}}}catch(r){throw r.status===429?new Error(`Rate limit exceeded for model ${this.model}. Error: ${r.message}`):r.status?new Error(`OpenAI API error (${r.status}): ${r.message}`):new Error(`OpenAI invocation failed: ${r.message}`)}}}});import Hf from"@anthropic-ai/sdk";import{zodToJsonSchema as Gf}from"zod-to-json-schema";var ga,ko,Su=L(()=>{"use strict";ga=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}}},Eo=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 Ff({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}=ga.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={...Lf(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 Uf}from"child_process";import{existsSync as bu}from"fs";import{homedir as yu}from"os";import{join as vu}from"path";var ma,te,Io=L(()=>{"use strict";ut();mu();Xi();hu();fu();to();ma=class i{static instance=null;browserSession=null;currentAgent=null;initState="idle";initPromise=null;initError=null;browsersInstalled=!1;systemChromePath=null;isExecuting=!1;stopRequested=!1;sessionLastActivity=0;sessionHeadlessMode=!1;executionLock=null;progressCallback=null;currentStep=0;currentMaxSteps=0;currentAction="";executionStartTime=0;agentTabs=new Map;runningAgents=new Map;static MAX_CONCURRENT_AGENTS=5;multiAgentMode=!1;browserSessionInitLock=null;static PLAYWRIGHT_INSTALL_TIMEOUT=300*1e3;tools=[{name:"browser_use_agent",description:"Execute a browser automation task using AI agent. The agent can navigate websites, fill forms, click buttons, extract data, and perform complex multi-step tasks.",inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to perform in the browser (e.g., "Go to google.com and search for AI news")'},model:{type:"string",description:'LLM model to use (e.g., "gpt-4o", "claude-sonnet-4-20250514", "o3")',default:"gpt-4o"},use_vision:{type:"boolean",description:"Whether to use vision/screenshots for the agent",default:!0},max_steps:{type:"number",description:"Maximum number of steps the agent can take",default:100},headless:{type:"boolean",description:"Run browser in headless mode",default:!1},keep_alive:{type:"boolean",description:"Keep browser open after task completion",default:!1}},required:["task"]}},{name:"retry_with_browser_use_agent",description:"Retry/execute a browser automation task (alias for browser_use_agent with additional parameters)",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task to perform in the browser"},firebase_token:{type:"string",description:"Firebase authentication token for API access"},model:{type:"string",description:"LLM model to use",default:"o3"},use_vision:{type:"boolean",description:"Whether to use vision/screenshots",default:!0},max_steps:{type:"number",description:"Maximum steps",default:100},keep_alive:{type:"boolean",description:"Keep browser open after completion",default:!0}},required:["task"]}}];constructor(){}findSystemChrome(){let e=process.platform,t=[];e==="darwin"?t.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium",vu(yu(),"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",vu(yu(),"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(bu(n))return n;return null}async checkPatchrightBrowsers(){try{let{chromium:e}=await import("patchright"),t=e.executablePath();if(bu(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=Uf(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";break;case"ready":return;case"error":this.initError=null;break;case"idle":break}this.initState="initializing",this.initPromise=this._doInitialize();try{await this.initPromise}finally{this.initPromise=null}}async _doInitialize(){try{await this.ensureBrowsersAvailable(),this.initState="ready",this.initError=null}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,e}}getStatus(){let e=this.initState==="ready"&&this.browsersInstalled,t=Zn()?eo():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),Zn()){let s=eo();b.log(`🍪 [BrowserUse] Found imported profile: ${s.cookieCount} cookies, ${s.originCount} origins`);try{let r=Bs();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 In(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 Xs({task:n,llm:g,browserSession:this.browserSession,pageId:d,settings:{useVision:r??!0},maxSteps:o,registerShouldStopCallback:()=>this.stopRequested,registerNewStepCallback:async(f,y,w)=>{b.log(`📊 [BrowserUse] Sub-agent ${e} step ${w}/${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),Zn()){let p=eo();b.log(`🍪 [BrowserUse] Found imported profile: ${p.cookieCount} cookies, ${p.originCount} origins`);try{let h=Bs();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 In(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 Xs({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 Eo({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 Ys({model:e,apiKey:t,baseURL:o,temperature:.7})}return b.log("🧠 [BrowserUse] Using OpenAI provider (requires OPENAI_API_KEY)"),new Ys({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,b.log("💀 [BrowserUse] Force kill completed - must call initialize() again")}async restart(){b.log("🔄 [BrowserUse] Restarting..."),await this.forceKill(),await this.initialize(),b.log("✅ [BrowserUse] Restarted")}isRunning(){return this.isExecuting}getExecutionStatus(){return{isExecuting:this.isExecuting,currentStep:this.currentStep,maxSteps:this.currentMaxSteps,currentAction:this.currentAction,startTime:this.executionStartTime,lastActivityTime:this.sessionLastActivity,hasActiveSession:this.browserSession!==null,sessionIdleSeconds:this.getSessionIdleSeconds()}}async cleanup(){if(b.log("🧹 [BrowserUse] Cleaning up internal state (browser stays open)..."),this.stopRequested=!0,this.currentAgent){try{this.currentAgent.stop()}catch{}this.currentAgent=null}this.browserSession&&b.log("🌐 [BrowserUse] Browser session left open for user"),this.browserSession=null,this.isExecuting=!1,this.stopRequested=!1,this.sessionLastActivity=0,this.sessionHeadlessMode=!1,this.executionLock=null,b.log("✅ [BrowserUse] Cleanup completed (browser still running)")}},te=ma.shared()});var Qs,vA,Su=L(()=>{"use strict";ut();Io();we();Qs=class{toolNames=["browser_automation","BrowserAutomation","browser_use_agent","BrowserUseAgent","browser_use","BrowserUse","retry_with_browser_use_agent"];initialized=!1;lastProgressTime=0;progressHistory=[];MAX_PROGRESS_HISTORY=200;async ensureInitialized(){if(!this.initialized)try{await te.initialize(),this.initialized=!0}catch(e){throw console.error("❌ [BrowserAutomation] Failed to initialize browser-use manager:",e),e}}async initialize(){try{return await this.ensureInitialized(),{success:!0}}catch(e){return console.error("❌ [BrowserAutomation] Initialization failed:",e),{success:!1}}}async listTools(){return te.listTools()}async executeTool(e,t){return await this.ensureInitialized(),te.executeTool(e,t)}async executeToolStream(e,t,n){await this.ensureInitialized(),te.setProgressCallback(n);try{return await te.executeTool(e,t)}finally{te.setProgressCallback(null)}}async execute(e,t,n,s){let r=n.task;if(!r)return[{type:"text",text:"Missing task argument"}];b.log("🌐 [BrowserAutomation] ==================== BROWSER AUTOMATION STARTED ===================="),b.log("📋 [BrowserAutomation] Task:",r),this.lastProgressTime=Date.now(),this.progressHistory=[];try{await this.ensureInitialized(),b.log("🔐 [BrowserAutomation] Getting Firebase authentication token...");let o=null;try{o=await X.getInstance().getFirebaseIdToken(),o&&b.log("✅ [BrowserAutomation] Got Firebase ID token")}catch{console.warn("⚠️ [BrowserAutomation] Could not get Firebase token, continuing without auth")}let a={task:r,firebase_token:o,model:n.model||"o3",use_vision:n.use_vision!==!1,max_steps:n.max_steps||100,keep_alive:n.keep_alive!==!1,headless:n.headless||!1};b.log("🔧 [BrowserAutomation] Executing with streaming progress..."),te.onProgress(d=>{this.handleProgress(d)});let c=await te.executeTool("browser_use_agent",a),l=[];if(c.content&&c.content.length>0)for(let d of c.content)d.type==="text"&&l.push({type:"text",text:d.text});return c.isError?console.error("❌ [BrowserAutomation] Execution failed"):b.log("✅ [BrowserAutomation] Execution completed successfully"),l.length===0&&l.push({type:"text",text:c.isError?"Browser automation task failed":"Browser automation task completed"}),b.log("✅ [BrowserAutomation] Task completed successfully"),b.log(`📊 [BrowserAutomation] Output length: ${l.reduce((d,g)=>d+(g.text?.length||0),0)} characters`),b.log(`📊 [BrowserAutomation] Steps executed: ${this.progressHistory.length}`),l}catch(o){return console.error("❌ [BrowserAutomation] Error:",o),[{type:"text",text:`Browser automation error: ${o.message}`}]}}handleProgress(e){this.lastProgressTime=Date.now(),this.progressHistory.length>=this.MAX_PROGRESS_HISTORY&&this.progressHistory.shift(),this.progressHistory.push(e);let t=`Step ${e.step}/${e.maxSteps}`;switch(e.type){case"step_start":b.log(`🚀 [BrowserAutomation] ${t} - Starting...`);break;case"step_complete":b.log(`✅ [BrowserAutomation] ${t} - ${e.action||"Complete"}`),e.message&&b.log(` 📝 ${e.message}`),e.url&&b.log(` 🌐 URL: ${e.url}`);break;case"action_executing":b.log(`⚡ [BrowserAutomation] ${t} - Executing: ${e.action}`);break;case"error":console.error(`❌ [BrowserAutomation] ${t} - Error: ${e.message}`);break;case"done":b.log(`🎉 [BrowserAutomation] Task completed at step ${e.step}`);break}}getStatus(){return te.getStatus()}async closeBrowser(){await te.closeBrowser()}requestStop(){te.requestStop()}async executeToolForSubAgent(e,t,n){let s=null;try{s=await X.getInstance().getFirebaseIdToken()}catch{console.warn("⚠️ [BrowserAutomation] Could not get Firebase token for sub-agent")}let r={...n,firebase_token:s||n.firebase_token};return te.executeToolForSubAgent(e,t,r)}getSubAgentStatus(){return te.getSubAgentStatus()}async stopSubAgent(e){return te.stopSubAgent(e)}async stopAllSubAgents(){return te.stopAllSubAgents()}async cleanupAllSubAgents(){return te.cleanupAllSubAgents()}async stop(){return te.stop()}async forceKill(){return te.forceKill()}async restart(){return te.restart()}isRunning(){return te.isRunning()}getExecutionStatus(){return te.getExecutionStatus()}isBrowserSessionAlive(){return te.isBrowserSessionAlive()}getSessionIdleSeconds(){return te.getSessionIdleSeconds()}setProgressCallback(e){te.setProgressCallback(e)}async cleanup(){return te.cleanup()}},vA=new Qs});function wu(i){i.register(new Dr),i.register(new Rr),i.register(new Or),i.register(new Nr),i.register(new _r),i.register(new $r),i.register(new Fr),i.register(new Br),i.register(new Wr),i.register(new Hr),i.register(new Gr),i.register(new jr),i.register(new zr),i.register(new qr),i.register(new Vr),i.register(new Xr),i.register(new Yr),i.register(new Jr),i.register(new Qs)}var Tu=L(()=>{"use strict";Jc();Zc();el();tl();nl();sl();rl();gl();ml();pl();hl();fl();bl();yl();Tl();xl();Cl();kl();Su()});var Js,xu=L(()=>{"use strict";Js=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 Eu={};et(Eu,{TelegramToolConnectionService:()=>ko,telegramToolConnectionService:()=>ts});import{ref as Cu,onChildAdded as Bf,onChildChanged as Wf,update as Hf}from"firebase/database";import{io as Gf}from"socket.io-client";import{EventEmitter as jf}from"events";var ko,ts,pa=L(()=>{"use strict";q();Ms();Pt();we();ko=class i extends jf{static instance;database=null;unsubscribe=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=kt.getInstance(),this.setupLogoutListener(),u.debug("[TelegramToolConnection] Service initialized")}setupLogoutListener(){X.getInstance().on("SnowXSignOut",()=>{u.debug("[TelegramToolConnection] Sign out detected, stopping listeners"),this.stopListening(),this.disconnectAllSessions(),this.currentUserId=null,this.currentDeviceId=null,this.processedRequestIds.clear(),this.sessionCleanupInterval&&(clearInterval(this.sessionCleanupInterval),this.sessionCleanupInterval=null)})}static getInstance(){return i.instance||(i.instance=new i),i.instance}setFirebaseDatabase(e){this.database=e,u.debug("[TelegramToolConnection] Firebase database set")}setToolExecutionCallback(e){this.onToolExecutionCallback=e,u.debug("[TelegramToolConnection] Tool execution callback registered")}isCallbackRegistered(){return this.onToolExecutionCallback!==null}async startListening(e,t){let n=t||Pe.getInstance().getCurrentDeviceId();if(!n){u.error("[TelegramToolConnection] No device ID available - cannot start listening");return}if(!this.database){u.error("[TelegramToolConnection] Firebase database not set - cannot start listening");return}this.onToolExecutionCallback||(u.warn("[TelegramToolConnection] Callback not yet registered, waiting..."),await this.waitForCallbackRegistration(5e3,50)||u.error("[TelegramToolConnection] Cannot start listener - callback not registered after 5s")),this.currentUserId=e,this.currentDeviceId=n,u.info("[TelegramToolConnection] Starting listener"),u.debug(` User: ${e}`),u.debug(` Device: ${n}`),u.debug(` Callback registered: ${this.onToolExecutionCallback!==null}`),this.stopListening(),this.setupFirebaseListener(e,n)}async waitForCallbackRegistration(e=5e3,t=50){if(this.onToolExecutionCallback)return!0;let n=Date.now();for(;Date.now()-n<e;)if(await new Promise(s=>setTimeout(s,t)),this.onToolExecutionCallback)return u.debug(`[TelegramToolConnection] Callback registered after ${Date.now()-n}ms`),!0;return!1}stopListening(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),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=Cu(this.database,n),r=(c,l)=>{if(!l)return;let d={...l,sessionId:l.sessionId||c};this.handleConnectionRequest(d)},o=Bf(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=Wf(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();for(let[t,n]of this.processedRequestIds)e-n>this.PROCESSED_ID_TTL_MS&&this.processedRequestIds.delete(t);if(this.processedRequestIds.size>this.MAX_PROCESSED_IDS){let t=Array.from(this.processedRequestIds.entries()).sort((n,s)=>s[1]-n[1]).slice(0,25);this.processedRequestIds=new Map(t)}}async handleWakeUp(e){let{sessionId:t,conversationId:n,source:s="telegram"}=e;if(this.activeSessions.has(t)){if(this.activeSessions.get(t).socket.connected){await this.updateStatus("connected",t);return}this.activeSessions.delete(t)}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=Gf(o,{path:"/frontend-tools",query:{deviceId:this.currentDeviceId||"",sessionId:t,token:a},transports:["websocket","polling"],reconnection:!1,timeout:3e4,forceNew:!0}),this.setupSocketEventHandlers(r,t),this.activeSessions.set(t,{sessionId:t,socket:r,conversationId:n,source:s,createdAt:Date.now()}),this.ensureSessionCleanupRunning(),await this.waitForSocketConnection(r,3e4))await this.registerDevice(r),await this.updateStatus("connected",t),u.info(`[TelegramToolConnection] WebSocket connected for session: ${t}`);else throw new Error("WebSocket connection timeout")}catch(o){if(u.error(`[TelegramToolConnection] Failed to connect: ${o.message}`),r)try{r.removeAllListeners(),r.disconnect()}catch{}await this.updateStatus("error",t),this.activeSessions.delete(t)}}async handleCompleted(e){u.debug(`[TelegramToolConnection] Completion received, disconnecting session: ${e}`),this.disconnectSession(e)}disconnectSession(e){let t=this.activeSessions.get(e);if(t){try{t.socket.removeAllListeners(),t.socket.disconnect()}catch{}this.activeSessions.delete(e),u.debug(`[TelegramToolConnection] Session ${e} disconnected`),this.stopSessionCleanupIfEmpty()}}disconnectAllSessions(){for(let[e,t]of this.activeSessions)try{t.socket.removeAllListeners(),t.socket.disconnect()}catch{}this.activeSessions.clear(),this.stopSessionCleanupIfEmpty()}ensureSessionCleanupRunning(){this.sessionCleanupInterval||(this.sessionCleanupInterval=setInterval(()=>{this.cleanupExpiredSessions()},this.SESSION_CLEANUP_INTERVAL_MS))}stopSessionCleanupIfEmpty(){this.activeSessions.size===0&&this.sessionCleanupInterval&&(clearInterval(this.sessionCleanupInterval),this.sessionCleanupInterval=null)}cleanupExpiredSessions(){let e=Date.now();for(let[t,n]of this.activeSessions)e-n.createdAt>this.SESSION_MAX_AGE_MS&&(u.debug(`[TelegramToolConnection] Expiring stale session ${t}`),this.disconnectSession(t))}async buildSocketIOURL(){let e="ws.snowx.ai",t="";try{t=await X.getInstance().getFirebaseIdToken()||""}catch{u.warn("[TelegramToolConnection] Failed to get Firebase token")}return{url:`wss://${e}`,token:t}}setupSocketEventHandlers(e,t){e.on("connect",()=>{u.debug(`[TelegramToolConnection] Socket connected for session: ${t}`)}),e.on("disconnect",n=>{u.debug(`[TelegramToolConnection] Socket disconnected for session: ${t}, reason: ${n}`);let s=this.activeSessions.get(t),r=s?.conversationId,o=s?.source||"telegram";this.activeSessions.delete(t),r&&this.emit("external_session_ended",{source:o,conversationId:r,error:!0,timestamp:Date.now()})}),e.on("connect_error",n=>{u.error(`[TelegramToolConnection] Connection error for session: ${t}: ${n.message}`)}),e.on("connection_established",n=>{u.debug(`[TelegramToolConnection] Connection established for session: ${t}`)}),e.on("tool_execution_request",async n=>{let s=n?.data?.tool_name||"tool",o=this.activeSessions.get(t)?.source||"telegram";u.debug(`[TelegramToolConnection] Tool execution request: ${s} (session: ${t}, source: ${o})`),this.emit("remote_task_status",{status:"start",toolName:s,source:o,timestamp:Date.now()});try{await this.handleToolExecutionRequest(e,n,t)}finally{this.emit("remote_task_status",{status:"end",toolName:s,source:o,timestamp:Date.now()})}}),e.on("external_session_started",n=>{u.info(`[TelegramToolConnection] External session started - source: ${n.source}, session: ${t}`),this.emit("external_session_started",n)}),e.on("external_session_ended",n=>{u.info(`[TelegramToolConnection] External session ended - source: ${n.source}, session: ${t}`),this.emit("external_session_ended",n)})}waitForSocketConnection(e,t){return new Promise(n=>{let s=!1,r=()=>{s||(s=!0,e.off("connection_established",o),e.off("connect_error",a))},o=()=>{clearTimeout(c),r(),n(!0)},a=()=>{clearTimeout(c),r(),n(!1)},c=setTimeout(()=>{r(),n(!1)},t);e.once("connection_established",o),e.once("connect_error",a)})}async registerDevice(e){e.emit("device_registration",{deviceId:this.currentDeviceId,userId:this.currentUserId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url","browser_navigate","browser_click","browser_type"]}),u.debug("[TelegramToolConnection] Device registered")}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"macOS"}async handleToolExecutionRequest(e,t,n,s=0){let l={id:t.data?.id||"",name:t.data?.tool_name||"",arguments:t.data?.arguments||{},timestamp:t.metadata?.timestamp||new Date().toISOString()},d=t.metadata?.tool_call_id||l.id,g=Date.now(),p=this.activeSessions.get(n)?.source||"telegram";if(u.debug(`[TelegramToolConnection] Executing tool: ${l.name} (session: ${n}, source: ${p})`),!this.onToolExecutionCallback&&s<3)return u.warn(`[TelegramToolConnection] Callback not ready, retry ${s+1}/3`),await new Promise(f=>setTimeout(f,200)),this.handleToolExecutionRequest(e,t,n,s+1);let h=f=>{e.connected&&e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:[{type:"text",text:`Error: ${f}`}],success:!1,error:f})};try{let f,y=!0;this.onToolExecutionCallback?(f=await Promise.race([this.onToolExecutionCallback(l),new Promise((T,x)=>setTimeout(()=>x(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 w=this.formatResultAsContentBlocks(f);if(!e.connected){u.warn("[TelegramToolConnection] Socket disconnected before sending response");return}e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:w,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()};e==="connected"&&(s.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone);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=Cu(this.database,n);await Hf(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}},ts=ko.getInstance()});var Li={};et(Li,{FrontendWebSocketService:()=>fe});import{EventEmitter as zf}from"events";import{io as qf}from"socket.io-client";import Iu from"os";import ku from"path";import Rt from"fs";import Kf from"axios";var $t,fe,Qn=L(()=>{"use strict";q();Pt();we();jn();qn();ki();Vc();Tu();xu();$t=ku.join(Iu.homedir(),".orion","pending-tool-results.json"),fe=class i extends zf{static instance;socket=null;_connectionState="disconnected";connectionError=null;isConversationActive=!1;serverHost;deviceId=null;userId=null;sessionId=null;deviceRegistrationService;authService;toolRegistry;runningProcesses=new Map;activeWebViewURLs=[];reconnectAttempts=0;heartbeatTimer=null;baseHeartbeatInterval=2e4;lastHeartbeat=null;lastPongReceived=new Date;connectionQuality="excellent";connectionMetrics={totalConnections:0,totalDisconnections:0,disconnectionReasons:{},qualityDegradations:0,proactiveRecoveries:0,successfulRecoveries:0,failedRecoveries:0,pingResponseTimes:[],lastMetricsReset:new Date};tokenRefreshTimer=null;TOKEN_REFRESH_INTERVAL=2700*1e3;consecutivePoorQualityChecks=0;keepaliveWatchdog=null;lastKeepaliveTime=null;baseKeepaliveTimeout=12e4;extendedKeepaliveTimeout=6e5;aggressiveHeartbeatTimer=null;baseAggressiveHeartbeatInterval=5e3;toolProgressTimer=null;baseToolProgressInterval=15e3;activeToolExecutions=new Set;lastHeartbeatSent=null;superAggressiveMode=!1;connectionHealthCheckTimer=null;POOR_QUALITY_THRESHOLD=2;CONNECTION_HEALTH_CHECK_INTERVAL=1e4;toolExecutionQueue=[];activeToolCount=0;MAX_CONCURRENT_TOOLS=5;MAX_QUEUED_TOOLS=50;pendingToolResults=[];MAX_PENDING_RESULTS=100;TOOL_RESULTS_HTTP_ENDPOINT="https://snowx.ai/api-beta/api/tool-results";capturedScreenshots=[];MAX_CAPTURED_SCREENSHOTS=10;pingLatencies=[];MAX_PING_SAMPLES=10;tokenCounter=new ct;wsConnectionStartTime=null;pendingDeleteConfirmations=new Map;DELETE_CONFIRMATION_TIMEOUT=5e4;_hasElectronFrontend=!1;onConnectionStateChangeCallbacks=new Set;connectionPromise=null;constructor(e="ws.snowx.ai",t,n="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=Pe.getInstance(),this.authService=X.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,n),this.toolRegistry=new kr,wu(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(()=>(pa(),Eu)).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 Js(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=qf(t,{path:"/frontend-tools",query:{deviceId:this.deviceId||"",sessionId:this.sessionId||"",token:e},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.1,timeout:45e3,autoConnect:!0,forceNew:!0}),this.setupSocketEventHandlers()}catch(e){u.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){u.debug(`[FRONTEND WS] DISCONNECT - Reason: ${e}, Permanent: ${t}`),this.connectionMetrics.totalDisconnections++,this.connectionMetrics.disconnectionReasons[e]=(this.connectionMetrics.disconnectionReasons[e]||0)+1,this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.stopTokenRefreshTimer(),this.stopConnectionHealthCheck(),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,u.debug("[FRONTEND WS] Socket.IO disconnected")),this.connectionError=null,this._connectionState="disconnected",this.notifyConnectionStateChange(),t&&(this.isConversationActive=!1,this.reconnectAttempts=0,this.pendingToolResults.length>0&&(u.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),u.debug("[FRONTEND WS] Connection state FULLY reset (permanent disconnect)")),this.emit("disconnected")}async waitForConnection(e){return this.isConnected()?!0:new Promise((t,n)=>{let s=setTimeout(()=>{this.connectionPromise=null,n(new Error("WebSocket connection timeout"))},e);this.connectionPromise={resolve:r=>{clearTimeout(s),this.connectionPromise=null,t(r)},reject:r=>{clearTimeout(s),this.connectionPromise=null,n(r)},timeoutId:s}})}resolveConnectionPromise(e){this.connectionPromise&&this.connectionPromise.resolve(e)}rejectConnectionPromise(e){this.connectionPromise&&this.connectionPromise.reject(e)}setupSocketEventHandlers(){this.socket&&(this.socket.on("connect",()=>{u.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{u.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{u.error(`[FRONTEND WS] Socket.IO connect_error: ${e.message}`),this.connectionError=e.message,this.rejectConnectionPromise(e)}),this.socket.io.on("reconnect_attempt",e=>{this.reconnectAttempts=e,u.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{u.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{u.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{u.error("[FRONTEND WS] All reconnection attempts failed"),this.connectionError="Connection failed after multiple attempts.",this._connectionState="disconnected",this.notifyConnectionStateChange()}),this.socket.on("connection_established",e=>{this.handleConnectionEstablished(e)}),this.socket.on("tool_execution_request",e=>{u.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{u.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{u.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{u.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("ping_request",e=>{u.debug(`[FRONTEND WS] Server ping_request received: ${e.reason||"heartbeat"}`),this.socket?.connected&&this.socket.emit("ping_response",{timestamp:Date.now(),originalTimestamp:e.timestamp,hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size,isWindowVisible:!0}),this.lastPongReceived=new Date,this.consecutivePoorQualityChecks=0,this.updateConnectionQuality()}),this.socket.on("connection_quality_warning",e=>{u.debug(`[FRONTEND WS] Connection quality warning: ${e.quality} - ${e.reason}`),this.connectionMetrics.qualityDegradations++,this.socket?.connected&&this.socket.emit("ping",{timestamp:new Date().toISOString(),reason:"quality_warning_response"}),e.quality==="critical"&&this.handleConnectionQualityDegradation()}),this.socket.on("ping_ack",e=>{u.debug(`[FRONTEND WS] Ping acknowledged: health=${e.connectionHealth}, latency=${e.latency}ms`),this.lastPongReceived=new Date,e.latency!==void 0&&(this.connectionMetrics.pingResponseTimes.length>=this.MAX_PING_SAMPLES&&this.connectionMetrics.pingResponseTimes.shift(),this.connectionMetrics.pingResponseTimes.push(e.latency)),this.updateConnectionQuality()}),this.socket.on("tool_execution_dropped",e=>{let t=e.executionId||e.toolId,n=e.toolName||"unknown",s=e.message||e.reason;u.debug(`[FRONTEND WS] Tool execution dropped: ${n} (${t}) - ${s}`),t&&this.activeToolExecutions.has(t)&&(this.activeToolExecutions.delete(t),this.activeToolCount=Math.max(0,this.activeToolCount-1),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat()),this.emit("tool_dropped",{executionId:t,toolId:t,toolName:n,reason:e.reason,message:s})}),this.socket.on("long_operation_start",e=>{u.debug("[FRONTEND WS] Backend requested long operation mode"),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat()}),this.socket.on("stop_signal",e=>{this.handleStopSignal(e)}),this.socket.on("stop_all_tools",e=>{u.debug("[FRONTEND WS] Stop all tools request received"),this.handleStopAllTools(e)}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{u.debug("[FRONTEND WS] Shell cleanup request received"),this.handleShellCleanup(e)}),this.socket.on("checkpoint_request",e=>{this.handleCheckpointRequest(e)}),this.socket.on("messages_saved",e=>{this.handleMessagesSaved(e)}),this.socket.on("auto_prompt",e=>{this.handleAutoPrompt(e)}),this.socket.on("reconnection_requested",e=>{u.debug(`[FRONTEND WS] Reconnection requested by server: ${e.reason||"unknown"}`),this.handleReconnectionRequest(e)}),this.socket.on("sub_agent_event",e=>{u.debug(`[FRONTEND WS] Sub-agent event received: ${e.type}`),this.handleSubAgentEvent(e)}),this.socket.on("external_session_started",e=>{u.debug(`[FRONTEND WS] External session started: ${e.source} - ${e.message}`),this.emit("external_session_started",e)}),this.socket.on("external_session_ended",e=>{u.debug(`[FRONTEND WS] External session ended: ${e.source}${e.error?" (with error)":""}`),this.emit("external_session_ended",e)}),this.socket.on("get_image_for_annotation",e=>{u.debug(`[FRONTEND WS] Image for annotation request received - ID: ${e.id}, Path: ${e.image_path}`),this.handleImageForAnnotationRequest(e)}),this.socket.on("delete_confirmation_response",e=>{this.handleDeleteConfirmationResponse(e)}),this.socket.on("error",e=>{console.error("[FRONTEND WS] Socket.IO error:",e)}))}handleConnect(){u.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.connectionMetrics.totalConnections++,this.startHeartbeat(),this.startKeepaliveWatchdog(),this.startConnectionHealthCheck(),this.startTokenRefreshTimer(),this.activeToolExecutions.size>0&&(u.debug(`[FRONTEND WS] Restarting aggressive heartbeat - ${this.activeToolExecutions.size} tools still active`),this.startAggressiveHeartbeat())}handleConnectionEstablished(e){if(this.wsConnectionStartTime){let t=Date.now()-this.wsConnectionStartTime.getTime();u.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else u.debug("[FRONTEND WS] Connection established!");this.registerDevice(),this._connectionState="connected",this.notifyConnectionStateChange(),this.isConversationActive=!0,this.loadPersistedToolResults(),this.flushPendingToolResultsWithFallback(),this.resolveConnectionPromise(!0),this.emit("connected")}handleDisconnect(e){u.debug(`[FRONTEND WS] Handling disconnect: ${e}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.rejectConnectionPromise(new Error(`WebSocket disconnected: ${e}`)),this.isConversationActive||u.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){u.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,n=t?.type||t?.stop_type||"all";switch(u.debug(`[FRONTEND WS] Stop type: ${n}`),n){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:u.debug(`[FRONTEND WS] Unknown stop type: ${n}`)}}handleStopAllTools(e){let t=e.session_id,n=e.reason||"backend_stop";if(u.debug(`[FRONTEND WS] Stopping all tools - Session: ${t}, Reason: ${n}`),t&&this.sessionId&&t!==this.sessionId){u.debug(`[FRONTEND WS] Ignoring stop_all_tools for different session (theirs: ${t}, ours: ${this.sessionId})`);return}this.stopAllActiveTools(n)}stopAllActiveTools(e){u.debug(`[FRONTEND WS] Stopping all active tools - Reason: ${e}`),u.debug(`[FRONTEND WS] - Active tools: ${this.activeToolExecutions.size}`),u.debug(`[FRONTEND WS] - Queued tools: ${this.toolExecutionQueue.length}`),u.debug(`[FRONTEND WS] - Pending results: ${this.pendingToolResults.length}`),this.toolExecutionQueue.length>0&&(u.debug(`[FRONTEND WS] Clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]),this.activeToolExecutions.size>0&&(u.debug(`[FRONTEND WS] Marking ${this.activeToolExecutions.size} active tools as cancelled`),this.activeToolExecutions.clear(),this.activeToolCount=0),this.pendingToolResults.length>0&&(u.debug(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending results`),this.pendingToolResults=[]),this.stopAggressiveHeartbeat(),this.terminateAllRunningProcesses(),u.debug(`[FRONTEND WS] All tools stopped for reason: ${e}`)}frameFeedbackForLLM(e,t,n){return`<user_feedback priority="high" requires_response="true">
|
|
1206
|
-
${n>1?`[Mid-Task User Feedback ${t}/${n}]`:"[Mid-Task User Feedback]"}
|
|
1207
|
-
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.
|
|
1208
|
-
|
|
1209
|
-
<feedback_content>
|
|
1210
|
-
${e}
|
|
1211
|
-
</feedback_content>
|
|
1212
|
-
|
|
1213
|
-
<instructions>
|
|
1214
|
-
- You MUST acknowledge this feedback in your response
|
|
1215
|
-
- If this feedback changes your current approach, explain how you will adjust
|
|
1216
|
-
- If this feedback contradicts your current direction, STOP and address the user's concern first
|
|
1217
|
-
- Do NOT continue with your previous plan if it conflicts with this feedback
|
|
1218
|
-
</instructions>
|
|
1219
|
-
</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=at.getInstance(),a=o.getQueuedMessages(),c=a.map((d,g)=>({content:this.frameFeedbackForLLM(d.content,g+1,a.length),timestamp:Math.floor(d.timestamp.getTime()),imageUrls:d.imageUrls||[],is_mid_task_feedback:!0,requires_acknowledgment:!0})),l=c.length>0;u.debug(`[FRONTEND WS] Sending checkpoint response with ${c.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:n,session_id:s,has_feedback:l,feedback:c}),l&&(u.info(`Sent ${c.length} feedback message(s) to AI`),this.emit("feedback:sent",a),o.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,n=e.isNew;if(!t||n===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:n})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){u.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){u.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}u.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),u.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}async handleReconnectionRequest(e){let t=e.reason||"unknown",n=e.lastPingAge||0;if(u.debug(`[FRONTEND WS] Server requested reconnection - Reason: ${t}`),u.debug(`[FRONTEND WS] Connection was degraded (last ping: ${Math.round(n/1e3)}s ago)`),this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0){u.debug(`[FRONTEND WS] Deferring reconnection - ${this.activeToolExecutions.size} active, ${this.toolExecutionQueue.length} queued tools`),this.sendAggressiveHeartbeat();return}if(this.pendingToolResults.length>0){u.debug(`[FRONTEND WS] Deferring reconnection - ${this.pendingToolResults.length} pending results to send`),this.sendAggressiveHeartbeat();return}if(this.socket&&this.isConversationActive&&this.sessionId&&this.userId){u.debug("[FRONTEND WS] Initiating forced reconnection...");let s=this.sessionId,r=this.userId,o=this.deviceId;this.disconnect("reconnection_requested",!1),await new Promise(a=>setTimeout(a,500));try{await this.connectForConversation(r,s)?(u.debug("[FRONTEND WS] Reconnection successful!"),u.debug(`[FRONTEND WS] Composite key: ${o}_${s}`)):u.error("[FRONTEND WS] Reconnection failed")}catch(a){u.error(`[FRONTEND WS] Reconnection error: ${a}`)}}else u.debug("[FRONTEND WS] Cannot reconnect - missing session info or conversation not active")}handleSubAgentEvent(e){let{type:t,data:n}=e;u.debug(`[FRONTEND WS] Sub-agent event: ${t}`,n);try{Kc.handleEvent({type:t,...n}),u.debug("[FRONTEND WS] Sub-agent event forwarded to SubAgentManager")}catch(s){u.debug(`[FRONTEND WS] Failed to forward to SubAgentManager: ${s}`)}this.emit("subAgentEvent",{type:t,...n,timestamp:new Date().toISOString()})}async handleImageForAnnotationRequest(e){let{id:t,image_path:n,timeout:s=3e4}=e;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={id:e.data?.id||"",name:e.data?.tool_name||"",arguments:e.data?.arguments||{},timestamp:e.metadata?.timestamp||new Date().toISOString()},n=e.metadata?.tool_call_id||t.id;this.toolExecutionQueue.length>=this.MAX_QUEUED_TOOLS&&(u.warn("[FRONTEND WS] Tool execution queue full, dropping oldest tool"),this.toolExecutionQueue.shift()),this.toolExecutionQueue.push(async()=>{await this.executeToolWithTracking(t,n)}),this.processNextTool()}processNextTool(){if(this.activeToolCount>=this.MAX_CONCURRENT_TOOLS){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 Js(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 Kf.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{Rt.existsSync($t)&&Rt.unlinkSync($t)}catch{}return}try{let e={sessionId:this.sessionId,deviceId:this.deviceId,results:this.pendingToolResults,timestamp:new Date().toISOString()},t=ku.dirname($t);Rt.existsSync(t)||Rt.mkdirSync(t,{recursive:!0}),Rt.writeFileSync($t,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(!Rt.existsSync($t))return;let e=Rt.readFileSync($t,"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)");Rt.unlinkSync($t)}catch(e){u.error(`[FRONTEND WS] Failed to load persisted tool results: ${e}`);try{Rt.existsSync($t)&&Rt.unlinkSync($t)}catch{}}}flushPendingToolResults(){if(this.pendingToolResults.length===0)return;u.debug(`[FRONTEND WS] Flushing ${this.pendingToolResults.length} queued tool results`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e)try{this.socket?.connected?(this.socket.emit(t.type,t.data),u.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(n){u.error(`[FRONTEND WS] Failed to send queued tool result: ${n}`),this.pendingToolResults.push(t)}this.persistPendingToolResults()}async flushPendingToolResultsWithFallback(){if(this.pendingToolResults.length===0)return;u.debug(`[FRONTEND WS] 🔄 Flushing ${this.pendingToolResults.length} pending tool results with HTTP fallback`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e){let n=!1;try{this.socket?.connected&&(this.socket.emit(t.type,t.data),u.debug(`[FRONTEND WS] ✅ Sent queued tool result via WebSocket: ${t.data?.id}`),n=!0)}catch(s){u.error(`[FRONTEND WS] Failed to send via WebSocket: ${s}`)}n||await this.submitToolResultViaHttp(t.data)&&(n=!0),n||(u.warn(`[FRONTEND WS] ⚠️ Both WebSocket and HTTP failed for result: ${t.data?.id}`),this.pendingToolResults.push(t))}this.persistPendingToolResults()}registerDevice(){if(!this.userId||!this.deviceId){console.warn("[FRONTEND WS] Cannot register device - missing userId or deviceId");return}let e=["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url"];this.socket?.emit("device_registration",{deviceId:this.deviceId,userId:this.userId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:e})}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"Unknown"}captureScreenshotFromResult(e,t){try{let n=JSON.parse(t);if(Array.isArray(n))for(let s of n)s.type==="image_url"&&s.image_url?.url&&(u.debug("[FRONTEND WS] 📸 Storing screenshot for assistant message attachment"),this.capturedScreenshots.push({toolCallId:e,base64Data:s.image_url.url}),this.capturedScreenshots.length>this.MAX_CAPTURED_SCREENSHOTS&&(u.debug(`[FRONTEND WS] 🧹 Dropping oldest screenshot (limit: ${this.MAX_CAPTURED_SCREENSHOTS})`),this.capturedScreenshots.shift()))}catch(n){u.warn(`[FRONTEND WS] ⚠️ Failed to parse screenshot tool output: ${n}`)}}getCapturedScreenshots(){return[...this.capturedScreenshots]}clearCapturedScreenshots(){this.capturedScreenshots=[]}async sendToolResult(e,t,n,s,r){let o;typeof s=="string"?o=s:s&&typeof s=="object"&&"output"in s?o=s.output||s.error||"":o=JSON.stringify(s);let a=this.createContentBlocks(o,r,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:a,success:!0,error:null})}sendToolError(e,t,n,s){let r=this.createContentBlocks(s.message,!1,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:r,success:!0,error:null})}createContentBlocks(e,t,n){let s=e.trim();s.length===0&&(t?s=`Command '${n}' executed successfully.
|
|
1220
|
-
|
|
1221
|
-
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=Iu.homedir(),l=s.join(c,".orion","tool_outputs");await n.mkdir(l,{recursive:!0});let d=s.join(l,a);return await n.writeFile(d,e,"utf-8"),u.debug(`[FRONTEND WS] Created temp file: ${d}`),d}catch(n){return u.error(`[FRONTEND WS] Failed to create temp file: ${n}`),null}}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeatPing()},this.baseHeartbeatInterval),u.debug(`[FRONTEND WS] Started heartbeat (${this.baseHeartbeatInterval/1e3}s interval)`)}sendHeartbeatPing(){this.socket?.connected&&(this.socket.emit("ping",{timestamp:new Date().toISOString()}),this.lastHeartbeat=new Date)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}startAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&clearInterval(this.aggressiveHeartbeatTimer);let e=this.superAggressiveMode?2e3:this.baseAggressiveHeartbeatInterval;this.aggressiveHeartbeatTimer=setInterval(()=>{this.sendAggressiveHeartbeat()},e);let t=this.superAggressiveMode?"SUPER-AGGRESSIVE":"aggressive";u.debug(`[FRONTEND WS] Started ${t} heartbeat (${e/1e3}s interval)`),this.startToolProgressReporting()}stopAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),this.superAggressiveMode=!1,u.debug("[FRONTEND WS] Stopped aggressive heartbeat"),this.stopToolProgressReporting()}enterSuperAggressiveMode(){this.superAggressiveMode||this.activeToolExecutions.size>0&&(u.debug("[FRONTEND WS] Entering SUPER-AGGRESSIVE heartbeat mode due to connection quality degradation"),this.superAggressiveMode=!0,this.startAggressiveHeartbeat())}sendAggressiveHeartbeat(){if(this.lastHeartbeatSent=new Date,this.socket?.connected){this.socket.emit("heartbeat",{timestamp:new Date().toISOString(),hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size,superAggressive:this.superAggressiveMode});let e=this.superAggressiveMode?"SUPER-":"";u.debug(`[FRONTEND WS] Sent ${e}aggressive heartbeat (${this.activeToolExecutions.size} active tools)`)}this.updateConnectionQuality()}updateConnectionQuality(){let e=(Date.now()-this.lastPongReceived.getTime())/1e3,t=this.connectionQuality;e<10?(this.connectionQuality="excellent",this.consecutivePoorQualityChecks=0):e<30?(this.connectionQuality="good",this.consecutivePoorQualityChecks=0):e<60?(this.connectionQuality="fair",this.consecutivePoorQualityChecks=0):e<90?(this.connectionQuality="poor",this.consecutivePoorQualityChecks++):(this.connectionQuality="critical",this.consecutivePoorQualityChecks++),t!==this.connectionQuality&&u.debug(`[FRONTEND WS] Connection quality: ${t} -> ${this.connectionQuality}`),this.consecutivePoorQualityChecks>=this.POOR_QUALITY_THRESHOLD&&(this.connectionQuality==="poor"||this.connectionQuality==="critical")&&this.handleConnectionQualityDegradation()}handleConnectionQualityDegradation(){if(u.debug(`[FRONTEND WS] Proactive recovery - quality: ${this.connectionQuality}, checks: ${this.consecutivePoorQualityChecks}`),this.connectionMetrics.proactiveRecoveries++,this.activeToolExecutions.size>0&&this.enterSuperAggressiveMode(),this.socket?.connected)for(let e=0;e<3;e++)setTimeout(()=>{this.socket?.connected&&this.socket.emit("heartbeat",{timestamp:new Date().toISOString(),hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size,reason:"quality_recovery"})},e*500);setTimeout(()=>{if(this.connectionQuality==="critical"&&this.isConversationActive){if(this.activeToolExecutions.size>0){u.debug("[FRONTEND WS] Deferring reconnect - active tools in progress"),this.connectionMetrics.failedRecoveries++;return}u.debug("[FRONTEND WS] Recovery failed - attempting soft reconnect"),this.attemptSoftReconnect()}else this.connectionMetrics.successfulRecoveries++},5e3)}async attemptSoftReconnect(){if(!this.sessionId||!this.userId){u.debug("[FRONTEND WS] Cannot soft reconnect - missing session info");return}let e=this.sessionId,t=this.userId;this.disconnect("soft_reconnect",!1),await new Promise(n=>setTimeout(n,1e3));try{await this.connectForConversation(t,e)?(u.debug("[FRONTEND WS] Soft reconnect successful"),this.connectionMetrics.successfulRecoveries++):(u.debug("[FRONTEND WS] Soft reconnect failed"),this.connectionMetrics.failedRecoveries++)}catch(n){u.error(`[FRONTEND WS] Soft reconnect error: ${n}`),this.connectionMetrics.failedRecoveries++}}startToolProgressReporting(){this.toolProgressTimer&&clearInterval(this.toolProgressTimer),this.toolProgressTimer=setInterval(()=>{this.sendToolProgress()},this.baseToolProgressInterval),u.debug(`[FRONTEND WS] Started tool progress reporting (${this.baseToolProgressInterval/1e3}s interval)`)}stopToolProgressReporting(){this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),u.debug("[FRONTEND WS] Stopped tool progress reporting")}sendToolProgress(){if(this.activeToolExecutions.size!==0&&this.socket?.connected){for(let e of this.activeToolExecutions)this.socket.emit("tool_progress",{toolId:e,status:"running",timestamp:new Date().toISOString()});u.debug(`[FRONTEND WS] Sent progress update for ${this.activeToolExecutions.size} active tools`)}}getKeepaliveTimeout(){return this.activeToolExecutions.size>0?this.extendedKeepaliveTimeout:this.baseKeepaliveTimeout}startKeepaliveWatchdog(){this.lastKeepaliveTime=new Date,this.stopKeepaliveWatchdog(),this.keepaliveWatchdog=setInterval(()=>{if(!this.lastKeepaliveTime)return;let e=this.getKeepaliveTimeout(),t=Date.now()-this.lastKeepaliveTime.getTime();u.debug(`[FRONTEND WS] Keepalive check - ${Math.round(t/1e3)}s since last, timeout: ${e/1e3}s, active tools: ${this.activeToolExecutions.size}`),t>e&&(u.error(`[FRONTEND WS] KEEPALIVE TIMEOUT - No activity for ${Math.round(t/1e3)}s`),this.handleKeepaliveTimeout())},1e4),u.debug("[FRONTEND WS] Started keepalive watchdog (check every 10s)")}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}handleKeepaliveTimeout(){u.debug("[FRONTEND WS] Handling keepalive timeout"),this.emit("keepalive_timeout",{lastKeepaliveTime:this.lastKeepaliveTime,activeTools:this.activeToolExecutions.size}),this.activeToolExecutions.size>0&&(u.debug("[FRONTEND WS] Tools still active, not disconnecting"),this.sendAggressiveHeartbeat())}updateKeepalive(){this.lastKeepaliveTime=new Date}startConnectionHealthCheck(){this.connectionHealthCheckTimer&&clearInterval(this.connectionHealthCheckTimer),this.connectionHealthCheckTimer=setInterval(()=>{this.updateConnectionQuality(),(this.connectionQuality==="fair"||this.connectionQuality==="poor")&&this.socket?.connected&&this.socket.emit("ping",{timestamp:Date.now()})},this.CONNECTION_HEALTH_CHECK_INTERVAL),u.debug(`[FRONTEND WS] Started connection health check (${this.CONNECTION_HEALTH_CHECK_INTERVAL/1e3}s interval)`)}stopConnectionHealthCheck(){this.connectionHealthCheckTimer&&(clearInterval(this.connectionHealthCheckTimer),this.connectionHealthCheckTimer=null)}startTokenRefreshTimer(){this.stopTokenRefreshTimer(),this.tokenRefreshTimer=setInterval(async()=>{await this.refreshAuthToken()},this.TOKEN_REFRESH_INTERVAL),u.debug(`[FRONTEND WS] Started token refresh timer (${this.TOKEN_REFRESH_INTERVAL/6e4} min interval)`)}stopTokenRefreshTimer(){this.tokenRefreshTimer&&(clearInterval(this.tokenRefreshTimer),this.tokenRefreshTimer=null)}async refreshAuthToken(){if(!this.isConnected()){u.debug("[FRONTEND WS] Not connected, skipping token refresh");return}try{u.debug("[FRONTEND WS] Refreshing Firebase token...");let e=await this.authService.getFirebaseIdToken();e&&this.socket?(this.socket.io.opts.query={...this.socket.io.opts.query,token:e},u.debug("[FRONTEND WS] Firebase token refreshed successfully"),this.socket?.connected&&(this.socket.emit("token_refreshed",{timestamp:Date.now()}),u.debug("[FRONTEND WS] Notified server of token refresh"))):u.warn("[FRONTEND WS] No Firebase token available for refresh")}catch(e){u.error(`[FRONTEND WS] Token refresh failed: ${e}`)}}getConnectionMetrics(){let e=this.connectionMetrics.pingResponseTimes.length>0?this.connectionMetrics.pingResponseTimes.reduce((t,n)=>t+n,0)/this.connectionMetrics.pingResponseTimes.length:0;return{...this.connectionMetrics,avgPingRTT:Math.round(e),currentQuality:this.connectionQuality}}resetConnectionMetrics(){this.connectionMetrics={totalConnections:0,totalDisconnections:0,disconnectionReasons:{},qualityDegradations:0,proactiveRecoveries:0,successfulRecoveries:0,failedRecoveries:0,pingResponseTimes:[],lastMetricsReset:new Date},u.debug("[FRONTEND WS] Connection metrics reset")}terminateAllRunningProcesses(){u.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),u.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(n){u.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${n.message}`)}this.runningProcesses.clear()}async sendStopSignal(e,t="all"){if(!this.isConnected()){u.warn("[FRONTEND WS] Not connected, cannot send stop signal");return}this.socket?.emit("stop_request",{user_id:e,stop_type:t,timestamp:new Date().toISOString()}),u.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async registerSession(e,t){if(!this.isConnected()){u.debug("[FRONTEND WS] Not connected, cannot register session");return}u.debug(`[FRONTEND WS] Registering session: ${e}`),this.socket?.emit("register",{traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()}),u.debug(`[FRONTEND WS] Session registered: ${e}`)}async sendToolRequest(e){if(!this.isConnected())throw u.debug("[FRONTEND WS] Not connected, cannot send tool request"),new Error("WebSocket not connected");let t={type:"tool_execution_request",data:{id:e.id,tool_name:e.tool_name,arguments:e.arguments,timeout:e.timeout},metadata:{tool_call_id:e.tool_call_id,timestamp:new Date().toISOString()}};u.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),this.socket?.emit("tool_execution_request",t)}async requestDeleteConfirmation(e,t){if(!this.isConnected())return u.debug("[FRONTEND WS] Not connected, cannot request delete confirmation"),"error";let n=`delete-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return u.debug(`[FRONTEND WS] Requesting delete confirmation: ${n}`),u.debug(`[FRONTEND WS] Command: ${e.substring(0,100)}${e.length>100?"...":""}`),new Promise(s=>{let r=setTimeout(()=>{this.pendingDeleteConfirmations.get(n)&&(u.debug(`[FRONTEND WS] Delete confirmation timed out: ${n}`),this.pendingDeleteConfirmations.delete(n),s("timeout"))},this.DELETE_CONFIRMATION_TIMEOUT);this.pendingDeleteConfirmations.set(n,{resolve:s,timeoutId:r}),this.socket?.emit("delete_confirmation_request",{confirmationId:n,command:e,description:t,timeout:this.DELETE_CONFIRMATION_TIMEOUT,timestamp:new Date().toISOString()}),u.debug(`[FRONTEND WS] Delete confirmation request sent: ${n}`)})}handleDeleteConfirmationResponse(e){let{confirmationId:t,response:n}=e;u.debug(`[FRONTEND WS] Delete confirmation response received: ${t} = ${n}`);let s=this.pendingDeleteConfirmations.get(t);if(!s){u.debug(`[FRONTEND WS] No pending confirmation for: ${t}`);return}clearTimeout(s.timeoutId),this.pendingDeleteConfirmations.delete(t);let r=n;s.resolve(["confirmed","declined","timeout","error"].includes(n)?r:"error")}async captureFrontendToolResultForHistory(e,t,n,s){let r=t.map(o=>o.text||"").join(`
|
|
1222
|
-
`);try{let{PersonalAgentService:o}=await Promise.resolve().then(()=>(Tt(),xn)),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 tn,Pu=L(()=>{"use strict";tn=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,`
|
|
1223
|
-
|
|
1224
|
-
`),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 Vf}from"events";import{promises as Po}from"fs";import{join as Au}from"path";import{homedir as Xf}from"os";var ha,Zs,fa=L(()=>{"use strict";ha=class i extends Vf{static instance;settings;configDir;configPath;constructor(){super(),this.configDir=Au(Xf(),".orion-cli"),this.configPath=Au(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 Po.mkdir(this.configDir,{recursive:!0});try{let e=await Po.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 Po.mkdir(this.configDir,{recursive:!0}),await Po.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()?"":`
|
|
1225
|
-
--- User Instructions ---
|
|
1226
|
-
${e.instructions}
|
|
1227
|
-
--- End Instructions ---
|
|
1228
|
-
`}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")}}},Zs=ha});var Du=L(()=>{"use strict"});import Ve from"fs";import nn from"path";import Yf from"os";var Qf,ba,Ot,Mu=L(()=>{"use strict";q();Qf=/[/\\:*?"<>|]/g,ba=class i{static instance;skillsPath;constructor(){this.skillsPath=nn.join(Yf.homedir(),".orion","skills")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.skillsPath}ensureFolder(){try{return Ve.existsSync(this.skillsPath)||(Ve.mkdirSync(this.skillsPath,{recursive:!0}),u.debug(`[Skills] Created skills folder: ${this.skillsPath}`)),!0}catch(e){return u.error(`[Skills] Failed to create skills folder: ${e.message}`),!1}}validateFilename(e){if(!e||typeof e!="string")return{valid:!1,error:"Skill name is required"};let t=e.trim();return t===""?{valid:!1,error:"Skill name cannot be empty"}:Qf.test(t)?{valid:!1,error:"Skill name contains invalid characters"}:nn.join(this.skillsPath,`${t}.md`).startsWith(this.skillsPath)?{valid:!0}:{valid:!1,error:"Invalid skill name (path traversal detected)"}}scanFolder(){try{this.ensureFolder();let e=Ve.readdirSync(this.skillsPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=nn.join(this.skillsPath,n);try{if(!Ve.statSync(s).isFile())continue;let o=Ve.readFileSync(s,"utf-8"),a=n.replace(/\.md$/,"");t.push({id:a,name:a,content:o})}catch(r){u.warn(`[Skills] Failed to read skill file ${n}: ${r.message}`)}}return u.debug(`[Skills] Scanned folder, found ${t.length} skills`),t}catch(e){return u.error(`[Skills] Failed to scan skills folder: ${e.message}`),[]}}createFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=e.trim(),r=nn.join(this.skillsPath,`${s}.md`);try{return this.ensureFolder(),Ve.existsSync(r)?{success:!1,error:"A skill with this name already exists"}:(Ve.writeFileSync(r,t,"utf-8"),u.debug(`[Skills] Created skill file: ${s}`),{success:!0,id:s})}catch(o){return u.error(`[Skills] Failed to create skill file: ${o.message}`),{success:!1,error:o.message}}}updateFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=nn.join(this.skillsPath,`${e}.md`);try{return Ve.existsSync(s)?(Ve.writeFileSync(s,t,"utf-8"),u.debug(`[Skills] Updated skill file: ${e}`),{success:!0}):{success:!1,error:"Skill not found"}}catch(r){return u.error(`[Skills] Failed to update skill file: ${r.message}`),{success:!1,error:r.message}}}deleteFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=nn.join(this.skillsPath,`${e}.md`);try{return Ve.existsSync(n)?(Ve.unlinkSync(n),u.debug(`[Skills] Deleted skill file: ${e}`),{success:!0}):{success:!1,error:"Skill not found"}}catch(s){return u.error(`[Skills] Failed to delete skill file: ${s.message}`),{success:!1,error:s.message}}}readFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=nn.join(this.skillsPath,`${e}.md`);try{return Ve.existsSync(n)?{success:!0,content:Ve.readFileSync(n,"utf-8")}:{success:!1,error:"Skill not found"}}catch(s){return u.error(`[Skills] Failed to read skill file: ${s.message}`),{success:!1,error:s.message}}}exists(e){if(!this.validateFilename(e).valid)return!1;let n=nn.join(this.skillsPath,`${e}.md`);return Ve.existsSync(n)}},Ot=ba.getInstance()});var Jf,Zf,eb,tb,nb,sb,rb,ya,Ru=L(()=>{"use strict";Jf=[{id:"wacli",name:"WhatsApp",emoji:"📱",description:"Send WhatsApp messages to other people or search/sync WhatsApp history via the wacli CLI.",tags:["whatsapp","messaging","wacli"],content:`# wacli
|
|
1204
|
+
`):void 0}}},ko=class{model;client;maxTokens;temperature;topP;seed;constructor(e){this.model=e.model,this.maxTokens=e.maxTokens??8192,this.temperature=e.temperature,this.topP=e.topP,this.seed=e.seed,this.client=new Hf({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}=ga.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={...Gf(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 jf}from"child_process";import{existsSync as wu}from"fs";import{homedir as Tu}from"os";import{join as xu}from"path";import{EventEmitter as zf}from"events";var ma,te,Po=L(()=>{"use strict";ut();bu();Xi();vu();Su();so();ma=class i{static instance=null;browserSession=null;currentAgent=null;initState="idle";initPromise=null;initError=null;browsersInstalled=!1;systemChromePath=null;isExecuting=!1;stopRequested=!1;sessionLastActivity=0;sessionHeadlessMode=!1;executionLock=null;progressCallback=null;currentStep=0;currentMaxSteps=0;currentAction="";executionStartTime=0;agentTabs=new Map;runningAgents=new Map;static MAX_CONCURRENT_AGENTS=5;multiAgentMode=!1;browserSessionInitLock=null;static PLAYWRIGHT_INSTALL_TIMEOUT=300*1e3;tools=[{name:"browser_use_agent",description:"Execute a browser automation task using AI agent. The agent can navigate websites, fill forms, click buttons, extract data, and perform complex multi-step tasks.",inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to perform in the browser (e.g., "Go to google.com and search for AI news")'},model:{type:"string",description:'LLM model to use (e.g., "gpt-4o", "claude-sonnet-4-20250514", "o3")',default:"gpt-4o"},use_vision:{type:"boolean",description:"Whether to use vision/screenshots for the agent",default:!0},max_steps:{type:"number",description:"Maximum number of steps the agent can take",default:100},headless:{type:"boolean",description:"Run browser in headless mode",default:!1},keep_alive:{type:"boolean",description:"Keep browser open after task completion",default:!1}},required:["task"]}},{name:"retry_with_browser_use_agent",description:"Retry/execute a browser automation task (alias for browser_use_agent with additional parameters)",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task to perform in the browser"},firebase_token:{type:"string",description:"Firebase authentication token for API access"},model:{type:"string",description:"LLM model to use",default:"o3"},use_vision:{type:"boolean",description:"Whether to use vision/screenshots",default:!0},max_steps:{type:"number",description:"Maximum steps",default:100},keep_alive:{type:"boolean",description:"Keep browser open after completion",default:!0}},required:["task"]}}];statusEmitter=new zf;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",xu(Tu(),"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",xu(Tu(),"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=jf(r,["patchright","install","chromium"],{stdio:"pipe",shell:!0});let o="";n.stdout?.on("data",a=>{o+=a.toString(),b.log(`[Patchright] ${a.toString().trim()}`)}),n.stderr?.on("data",a=>{o+=a.toString(),b.log(`[Patchright] ${a.toString().trim()}`)}),n.on("close",a=>{t||(t=!0,clearTimeout(s),a===0?(b.log("✅ [BrowserUse] Patchright browsers installed successfully!"),e(!0)):(console.error(`❌ [BrowserUse] Patchright install failed with code ${a}`),e(!1)))}),n.on("error",a=>{t||(t=!0,clearTimeout(s),console.error("❌ [BrowserUse] Failed to run patchright install:",a),e(!1))})}catch(r){t||(t=!0,clearTimeout(s),console.error("❌ [BrowserUse] Error installing Patchright browsers:",r),e(!1))}})}async ensureBrowsersAvailable(){if(this.systemChromePath=this.findSystemChrome(),this.systemChromePath){this.browsersInstalled=!0;return}if(await this.checkPatchrightBrowsers()){this.browsersInstalled=!0;return}if(await this.installPlaywrightBrowsers()){this.browsersInstalled=!0;return}throw this.browsersInstalled=!1,console.error("❌ [BrowserUse] No browsers available. Browser automation will not work."),console.error("❌ [BrowserUse] Please install Google Chrome or run: npx patchright install chromium"),new Error("No browser available. Please install Google Chrome.")}static shared(){return i.instance||(i.instance=new i),i.instance}async initialize(){switch(this.initState){case"initializing":if(this.initPromise)return this.initPromise;this.initState="idle",this.emitStatusChange();break;case"ready":return;case"error":this.initError=null;break;case"idle":break}this.initState="initializing",this.emitStatusChange(),this.initPromise=this._doInitialize();try{await this.initPromise}finally{this.initPromise=null}}async _doInitialize(){try{await this.ensureBrowsersAvailable(),this.initState="ready",this.initError=null,this.emitStatusChange()}catch(e){throw console.error("❌ [BrowserUse] Initialization failed:",e),this.initState="error",this.initError=e instanceof Error?e:new Error(String(e)),this.browsersInstalled=!1,this.emitStatusChange(),e}}getStatus(){let e=this.initState==="ready"&&this.browsersInstalled,t=es()?no():null,n=this.browserSession&&this.sessionLastActivity>0?Math.round((Date.now()-this.sessionLastActivity)/1e3):void 0;return{isRunning:e,isInitialized:e,isInitializing:this.initState==="initializing",initState:this.initState,toolCount:this.tools.length,hasBrowser:this.browsersInstalled,browserPath:this.systemChromePath||"patchright",error:this.initError?.message,hasProfile:t?.exists??!1,profileCookies:t?.cookieCount??0,hasActiveSession:this.browserSession!==null,sessionIdleSeconds:n,isExecuting:this.isExecuting||this.runningAgents.size>0,multiAgentMode:this.multiAgentMode,runningAgentCount:this.runningAgents.size,maxConcurrentAgents:i.MAX_CONCURRENT_AGENTS,tabCount:this.browserSession?.getTabCount?.()??0}}async listTools(){if(this.initState!=="ready")throw new Error("BrowserUseManager not initialized");return this.tools}async executeTool(e,t){switch(b.log(`🔧 [BrowserUse] Executing tool '${e}'...`),b.log("🔧 [BrowserUse] Arguments:",JSON.stringify(t,null,2)),this.initState){case"initializing":if(b.log("⏳ [BrowserUse] Waiting for initialization to complete..."),this.initPromise)try{await this.initPromise}catch{return{content:[{type:"text",text:"Browser automation initialization failed. Please try again."}],isError:!0}}break;case"error":return{content:[{type:"text",text:`Browser automation failed to initialize: ${this.initError?.message||"Unknown error"}`}],isError:!0};case"idle":return{content:[{type:"text",text:"Browser automation not initialized. Please wait for initialization to complete."}],isError:!0};case"ready":break}if(this.initState!=="ready")return{content:[{type:"text",text:"Browser automation not ready"}],isError:!0};if(this.stopRequested)return b.log("🛑 [BrowserUse] Stop was requested, not starting execution"),this.stopRequested=!1,{content:[{type:"text",text:"Execution cancelled by user"}],isError:!0};if(e!=="browser_use_agent"&&e!=="retry_with_browser_use_agent")return{content:[{type:"text",text:`Unknown tool: ${e}`}],isError:!0};if(this.isExecuting&&(b.log("⚠️ [BrowserUse] Another task is already executing, waiting for it to finish..."),this.executionLock))try{await Promise.race([this.executionLock,new Promise((s,r)=>setTimeout(()=>r(new Error("Timeout waiting for previous task")),5e3))])}catch{if(this.isExecuting)return console.warn("⚠️ [BrowserUse] Previous task still running, cannot start new task"),{content:[{type:"text",text:"Another task is currently running. Please stop it first or wait for it to complete."}],isError:!0}}let n=null;this.executionLock=new Promise(s=>{n=s}),this.isExecuting=!0;try{return{content:[{type:"text",text:await this.runBrowserAgent(t)}]}}catch(s){return this.stopRequested||s.message==="Interrupted"||s.message==="Agent stopped by user"?(b.log("🛑 [BrowserUse] Execution stopped by user"),{content:[{type:"text",text:"Task stopped by user"}],isError:!1}):(console.error("❌ [BrowserUse] Tool execution failed:",s),{content:[{type:"text",text:`Error: ${s.message}`}],isError:!0})}finally{n&&n(),this.executionLock=null,this.isExecuting=!1,this.stopRequested=!1,this.currentAgent=null}}async executeToolForSubAgent(e,t,n){if(b.log(`🔀 [BrowserUse] Multi-agent execution for sub-agent ${e}`),b.log(`🔧 [BrowserUse] Tool: ${t}`),this.initState==="initializing"&&this.initPromise){b.log("⏳ [BrowserUse] Waiting for initialization...");try{await this.initPromise}catch{return{content:[{type:"text",text:"Browser automation initialization failed"}],isError:!0}}}if(this.initState!=="ready")return{content:[{type:"text",text:`Browser automation not ready (state: ${this.initState})`}],isError:!0};if(this.runningAgents.size>=i.MAX_CONCURRENT_AGENTS)return console.warn(`⚠️ [BrowserUse] Max concurrent agents (${i.MAX_CONCURRENT_AGENTS}) reached`),{content:[{type:"text",text:`Maximum concurrent browser agents (${i.MAX_CONCURRENT_AGENTS}) reached. Please wait for other agents to complete.`}],isError:!0};this.multiAgentMode=!0;try{return{content:[{type:"text",text:await this.runBrowserAgentForSubAgent(e,n)}]}}catch(s){return console.error(`❌ [BrowserUse] Sub-agent ${e} execution failed:`,s),{content:[{type:"text",text:`Error: ${s.message}`}],isError:!0}}finally{this.runningAgents.delete(e),this.runningAgents.size===0&&(this.multiAgentMode=!1,b.log("🔀 [BrowserUse] All sub-agents completed, exiting multi-agent mode"))}}async ensureBrowserSessionForMultiAgent(e){if(this.browserSession){this.sessionHeadlessMode!==e&&(b.log(`⚠️ [BrowserUse] Headless mode mismatch (current: ${this.sessionHeadlessMode}, requested: ${e})`),b.log(`⚠️ [BrowserUse] Continuing with existing session (headless: ${this.sessionHeadlessMode})`));return}if(this.browserSessionInitLock){if(b.log("⏳ [BrowserUse] Waiting for browser session init (another sub-agent is creating)..."),await this.browserSessionInitLock,this.browserSession)return;console.warn("⚠️ [BrowserUse] Browser session still null after waiting, creating now...")}let t=null;this.browserSessionInitLock=new Promise(n=>{t=n});try{b.log("🌐 [BrowserUse] Creating browser session for multi-agent mode...");let n={headless:e};if(this.systemChromePath&&(b.log(`🌐 [BrowserUse] Using system Chrome: ${this.systemChromePath}`),n.executablePath=this.systemChromePath,n.channel=void 0),es()){let s=no();b.log(`🍪 [BrowserUse] Found imported profile: ${s.cookieCount} cookies, ${s.originCount} origins`);try{let r=Bs();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 In(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 Xs({task:n,llm:g,browserSession:this.browserSession,pageId:d,settings:{useVision:r??!0},maxSteps:o,registerShouldStopCallback:()=>this.stopRequested,registerNewStepCallback:async(f,y,T)=>{b.log(`📊 [BrowserUse] Sub-agent ${e} step ${T}/${o}`)}});this.runningAgents.set(e,m),b.log(`📊 [BrowserUse] Running agents: ${this.runningAgents.size}/${i.MAX_CONCURRENT_AGENTS}`);let p=await m.run();this.sessionLastActivity=Date.now();let h=this.extractResult(p);return c||await this.cleanupSubAgent(e),h}async cleanupSubAgent(e){let t=this.agentTabs.get(e);t&&this.browserSession&&(await this.browserSession.closeTab(t),this.agentTabs.delete(e),b.log(`🗑️ [BrowserUse] Cleaned up tab for sub-agent ${e}`)),this.runningAgents.delete(e)}async cleanupAllSubAgents(){b.log(`🗑️ [BrowserUse] Cleaning up all ${this.agentTabs.size} sub-agent tabs...`);for(let[e,t]of this.agentTabs.entries())this.browserSession&&await this.browserSession.closeTab(t),this.runningAgents.delete(e);this.agentTabs.clear(),this.multiAgentMode=!1,b.log("✅ [BrowserUse] All sub-agent tabs cleaned up")}getSubAgentStatus(){return{count:this.runningAgents.size,maxAllowed:i.MAX_CONCURRENT_AGENTS,agents:Array.from(this.agentTabs.entries()).map(([e,t])=>({subAgentId:e,pageId:t}))}}async stopSubAgent(e){let t=this.runningAgents.get(e);return t?(t.stop(),await this.cleanupSubAgent(e),b.log(`🛑 [BrowserUse] Stopped sub-agent ${e}`),!0):!1}async stopAllSubAgents(){b.log(`🛑 [BrowserUse] Stopping all ${this.runningAgents.size} sub-agents...`);for(let[e,t]of this.runningAgents.entries())t.stop();await this.cleanupAllSubAgents(),b.log("✅ [BrowserUse] All sub-agents stopped")}async runBrowserAgent(e){let{task:t,model:n="gpt-4o",use_vision:s=!0,max_steps:r=100,headless:o=!1,keep_alive:a=!1,firebase_token:c}=e;b.log("🤖 [BrowserUse] Starting browser agent..."),b.log(`📝 [BrowserUse] Task: ${t}`),b.log(`🧠 [BrowserUse] Model: ${n}`),b.log(`👁️ [BrowserUse] Vision: ${s}`),b.log(`🔢 [BrowserUse] Max steps: ${r}`),b.log(`🖥️ [BrowserUse] Headless: ${o}`);try{if(this.browserSession&&this.sessionHeadlessMode!==o&&(b.log(`⚠️ [BrowserUse] Headless mode mismatch (current: ${this.sessionHeadlessMode}, requested: ${o}), closing existing session`),await this.closeBrowserSession()),this.browserSession&&(await this.validateBrowserSession()||(b.log("⚠️ [BrowserUse] Existing browser session is no longer valid, creating new one"),await this.closeBrowserSession())),this.browserSession)b.log("🔄 [BrowserUse] Reusing existing browser session");else{b.log("🌐 [BrowserUse] Creating new browser session...");let m={headless:o};if(this.systemChromePath&&(b.log(`🌐 [BrowserUse] Using system Chrome: ${this.systemChromePath}`),m.executablePath=this.systemChromePath,m.channel=void 0),es()){let p=no();b.log(`🍪 [BrowserUse] Found imported profile: ${p.cookieCount} cookies, ${p.originCount} origins`);try{let h=Bs();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 In(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 Xs({task:t,llm:l,browserSession:this.browserSession,settings:{useVision:s??!0},maxSteps:r,registerShouldStopCallback:()=>this.stopRequested?(b.log("🛑 [BrowserUse] Stop requested via callback"),!0):!1,registerNewStepCallback:async(m,p,h)=>{let f=p.action?.[0]?Object.keys(p.action[0])[0]:void 0,y=m?.url||void 0;this.emitProgress({type:"step_complete",step:h,maxSteps:r,action:f,message:p.currentState?.summary||p.nextGoal,url:y}),f&&h<r-1&&this.emitProgress({type:"action_executing",step:h+1,maxSteps:r,action:f,message:`Executing: ${f}`,url:y})},registerDoneCallback:async m=>{let p=m.history?.length||r;this.emitProgress({type:"done",step:p,maxSteps:r,message:"Task completed"})}}),this.stopRequested)throw new Error("Agent stopped by user");b.log("▶️ [BrowserUse] Running agent...");let d=await this.currentAgent.run();b.log("✅ [BrowserUse] Agent completed"),this.sessionLastActivity=Date.now();let g=this.extractResult(d);return a?b.log("🌐 [BrowserUse] Browser session kept alive (keep_alive=true)"):(b.log("🧹 [BrowserUse] Cleaning up browser session (keep_alive=false)..."),await this.closeBrowserSession()),g}catch(l){throw console.error("❌ [BrowserUse] Agent execution failed:",l),this.sessionLastActivity=Date.now(),a?b.log("🌐 [BrowserUse] Browser session kept alive after error for reuse"):(b.log("🧹 [BrowserUse] Cleaning up browser session after error (keep_alive=false)..."),await this.closeBrowserSession()),l}}createLLM(e,t){let n=e.toLowerCase();if(n.includes("claude")||n.includes("anthropic"))return b.log("🧠 [BrowserUse] Using Anthropic provider"),new ko({model:e,apiKey:process.env.ANTHROPIC_API_KEY});if(t){let s=n.includes("o3")?"o3":"gpt-4o",o=`${process.env.SNOWX_API_URL||"https://snowx.ai/api-beta/api"}/browser-use/${s}/v1`;return b.log(`🧠 [BrowserUse] Using SnowX API (ChatOpenAI) with model: ${e}`),b.log(`🔒 [BrowserUse] Using SnowX API proxy at ${o}/chat/completions`),b.log(`🔐 [BrowserUse] Firebase token preview: ${t.substring(0,50)}...`),b.log(`🔐 [BrowserUse] Firebase token length: ${t.length}`),new Ys({model:e,apiKey:t,baseURL:o,temperature:.7})}return b.log("🧠 [BrowserUse] Using OpenAI provider (requires OPENAI_API_KEY)"),new Ys({model:e,apiKey:process.env.OPENAI_API_KEY})}extractResult(e){try{if(e.finalResult){let n=e.finalResult;if(n.extractedContent)return n.extractedContent;if(n.success!==void 0)return n.success?"Task completed successfully":"Task completed with errors"}if(e.history&&e.history.length>0){let n=e.history[e.history.length-1];if(n.result&&n.result.length>0){let s=n.result[n.result.length-1];if(s.extractedContent)return s.extractedContent;if(s.isDone)return s.success?"Task completed successfully":"Task completed with errors"}}let t=[];if(e.history){for(let n of e.history)if(n.result)for(let s of n.result)s.extractedContent&&t.push(s.extractedContent)}return t.length>0?t.join(`
|
|
1205
|
+
`):"Task execution finished (no specific result)"}catch(t){return console.error("❌ [BrowserUse] Error extracting result:",t),"Task completed (result extraction failed)"}}emitProgress(e){let t={...e,timestamp:Date.now()};if(this.currentStep=e.step,this.currentMaxSteps=e.maxSteps,e.action&&(this.currentAction=e.action),this.sessionLastActivity=Date.now(),b.log(`📊 [BrowserUse] Progress: Step ${e.step}/${e.maxSteps} - ${e.type}${e.action?`: ${e.action}`:""}`),this.progressCallback)try{this.progressCallback(t)}catch(n){console.warn("⚠️ [BrowserUse] Progress callback error:",n)}}onProgress(e){this.progressCallback=e}setProgressCallback(e){this.progressCallback=e}async closeBrowserSession(){if(this.browserSession){try{await this.browserSession.stop(),b.log("✅ [BrowserUse] Browser session closed")}catch(e){console.warn("⚠️ [BrowserUse] Error closing browser session:",e)}this.browserSession=null,this.sessionLastActivity=0,this.sessionHeadlessMode=!1}this.currentAgent=null}async closeBrowser(){b.log("🔒 [BrowserUse] Explicitly closing browser session..."),await this.closeBrowserSession(),b.log("✅ [BrowserUse] Browser closed by user request")}isBrowserSessionAlive(){return this.browserSession!==null}getSessionIdleSeconds(){if(this.browserSession&&this.sessionLastActivity>0)return Math.round((Date.now()-this.sessionLastActivity)/1e3)}async validateBrowserSession(){if(!this.browserSession)return!1;try{let e=this.browserSession.getState(),t=new Promise((n,s)=>setTimeout(()=>s(new Error("Browser validation timeout (3s)")),3e3));return await Promise.race([e,t]),b.log("✅ [BrowserUse] Browser session validated - still responsive"),!0}catch(e){return console.warn(`⚠️ [BrowserUse] Browser session validation failed: ${e.message}`),console.warn("⚠️ [BrowserUse] Browser may have been closed externally or crashed"),!1}}requestStop(){b.log("🛑 [BrowserUse] Stop requested"),this.stopRequested=!0}async stop(){if(!this.isExecuting&&!this.currentAgent&&!this.stopRequested){b.log("🛑 [BrowserUse] Stop called but nothing to stop (already stopped or not running)"),this.browserSession&&(this.sessionLastActivity=Date.now());return}if(b.log("🛑 [BrowserUse] Stopping current execution (keeping browser session alive)..."),this.stopRequested=!0,b.log("🛑 [BrowserUse] Stop flag set, agent will stop at next checkpoint"),this.currentAgent)try{this.currentAgent.stop(),b.log("🛑 [BrowserUse] Agent stop() called")}catch(e){console.warn("⚠️ [BrowserUse] Error stopping agent:",e)}if(this.browserSession){try{await this.browserSession.saveStorageState(),b.log("💾 [BrowserUse] Browser state saved")}catch(e){console.warn("⚠️ [BrowserUse] Could not save browser state:",e)}b.log("🌐 [BrowserUse] Browser session kept alive for reuse"),this.sessionLastActivity=Date.now()}b.log("✅ [BrowserUse] Stop signal sent, waiting for execution to finish...")}async forceKill(){if(b.log("💀 [BrowserUse] Force killing and resetting all state..."),this.stopRequested=!0,this.isExecuting=!1,this.currentAgent){try{this.currentAgent.stop()}catch{}this.currentAgent=null}for(let[e,t]of this.runningAgents.entries())try{t.stop(),b.log(`💀 [BrowserUse] Force stopped sub-agent ${e}`)}catch{}if(this.runningAgents.clear(),this.agentTabs.clear(),this.multiAgentMode=!1,this.browserSession){try{await this.browserSession.stop()}catch{}this.browserSession=null}this.initState="idle",this.initPromise=null,this.initError=null,this.browsersInstalled=!1,this.systemChromePath=null,this.stopRequested=!1,this.sessionLastActivity=0,this.sessionHeadlessMode=!1,this.executionLock=null,this.emitStatusChange(),b.log("💀 [BrowserUse] Force kill completed - must call initialize() again")}async restart(){b.log("🔄 [BrowserUse] Restarting..."),await this.forceKill(),await this.initialize(),b.log("✅ [BrowserUse] Restarted")}isRunning(){return this.isExecuting}getExecutionStatus(){return{isExecuting:this.isExecuting,currentStep:this.currentStep,maxSteps:this.currentMaxSteps,currentAction:this.currentAction,startTime:this.executionStartTime,lastActivityTime:this.sessionLastActivity,hasActiveSession:this.browserSession!==null,sessionIdleSeconds:this.getSessionIdleSeconds()}}async cleanup(){if(b.log("🧹 [BrowserUse] Cleaning up internal state (browser stays open)..."),this.stopRequested=!0,this.currentAgent){try{this.currentAgent.stop()}catch{}this.currentAgent=null}this.browserSession&&b.log("🌐 [BrowserUse] Browser session left open for user"),this.browserSession=null,this.isExecuting=!1,this.stopRequested=!1,this.sessionLastActivity=0,this.sessionHeadlessMode=!1,this.executionLock=null,b.log("✅ [BrowserUse] Cleanup completed (browser still running)")}},te=ma.shared()});var Qs,EA,Cu=L(()=>{"use strict";ut();Po();Te();Qs=class{toolNames=["browser_automation","BrowserAutomation","browser_use_agent","BrowserUseAgent","browser_use","BrowserUse","retry_with_browser_use_agent"];initialized=!1;lastProgressTime=0;progressHistory=[];MAX_PROGRESS_HISTORY=200;async ensureInitialized(){if(!this.initialized)try{await te.initialize(),this.initialized=!0}catch(e){throw console.error("❌ [BrowserAutomation] Failed to initialize browser-use manager:",e),e}}async initialize(){try{return await this.ensureInitialized(),{success:!0}}catch(e){return console.error("❌ [BrowserAutomation] Initialization failed:",e),{success:!1}}}async listTools(){return te.listTools()}async executeTool(e,t){return await this.ensureInitialized(),te.executeTool(e,t)}async executeToolStream(e,t,n){await this.ensureInitialized(),te.setProgressCallback(n);try{return await te.executeTool(e,t)}finally{te.setProgressCallback(null)}}async execute(e,t,n,s){let r=n.task;if(!r)return[{type:"text",text:"Missing task argument"}];b.log("🌐 [BrowserAutomation] ==================== BROWSER AUTOMATION STARTED ===================="),b.log("📋 [BrowserAutomation] Task:",r),this.lastProgressTime=Date.now(),this.progressHistory=[];try{await this.ensureInitialized(),b.log("🔐 [BrowserAutomation] Getting Firebase authentication token...");let o=null;try{o=await X.getInstance().getFirebaseIdToken(),o&&b.log("✅ [BrowserAutomation] Got Firebase ID token")}catch{console.warn("⚠️ [BrowserAutomation] Could not get Firebase token, continuing without auth")}let a={task:r,firebase_token:o,model:n.model||"o3",use_vision:n.use_vision!==!1,max_steps:n.max_steps||100,keep_alive:n.keep_alive!==!1,headless:n.headless||!1};b.log("🔧 [BrowserAutomation] Executing with streaming progress..."),te.onProgress(d=>{this.handleProgress(d)});let c=await te.executeTool("browser_use_agent",a),l=[];if(c.content&&c.content.length>0)for(let d of c.content)d.type==="text"&&l.push({type:"text",text:d.text});return c.isError?console.error("❌ [BrowserAutomation] Execution failed"):b.log("✅ [BrowserAutomation] Execution completed successfully"),l.length===0&&l.push({type:"text",text:c.isError?"Browser automation task failed":"Browser automation task completed"}),b.log("✅ [BrowserAutomation] Task completed successfully"),b.log(`📊 [BrowserAutomation] Output length: ${l.reduce((d,g)=>d+(g.text?.length||0),0)} characters`),b.log(`📊 [BrowserAutomation] Steps executed: ${this.progressHistory.length}`),l}catch(o){return console.error("❌ [BrowserAutomation] Error:",o),[{type:"text",text:`Browser automation error: ${o.message}`}]}}handleProgress(e){this.lastProgressTime=Date.now(),this.progressHistory.length>=this.MAX_PROGRESS_HISTORY&&this.progressHistory.shift(),this.progressHistory.push(e);let t=`Step ${e.step}/${e.maxSteps}`;switch(e.type){case"step_start":b.log(`🚀 [BrowserAutomation] ${t} - Starting...`);break;case"step_complete":b.log(`✅ [BrowserAutomation] ${t} - ${e.action||"Complete"}`),e.message&&b.log(` 📝 ${e.message}`),e.url&&b.log(` 🌐 URL: ${e.url}`);break;case"action_executing":b.log(`⚡ [BrowserAutomation] ${t} - Executing: ${e.action}`);break;case"error":console.error(`❌ [BrowserAutomation] ${t} - Error: ${e.message}`);break;case"done":b.log(`🎉 [BrowserAutomation] Task completed at step ${e.step}`);break}}getStatus(){return te.getStatus()}async closeBrowser(){await te.closeBrowser()}requestStop(){te.requestStop()}async executeToolForSubAgent(e,t,n){let s=null;try{s=await X.getInstance().getFirebaseIdToken()}catch{console.warn("⚠️ [BrowserAutomation] Could not get Firebase token for sub-agent")}let r={...n,firebase_token:s||n.firebase_token};return te.executeToolForSubAgent(e,t,r)}getSubAgentStatus(){return te.getSubAgentStatus()}async stopSubAgent(e){return te.stopSubAgent(e)}async stopAllSubAgents(){return te.stopAllSubAgents()}async cleanupAllSubAgents(){return te.cleanupAllSubAgents()}async stop(){return te.stop()}async forceKill(){return te.forceKill()}async restart(){return te.restart()}isRunning(){return te.isRunning()}getExecutionStatus(){return te.getExecutionStatus()}isBrowserSessionAlive(){return te.isBrowserSessionAlive()}getSessionIdleSeconds(){return te.getSessionIdleSeconds()}setProgressCallback(e){te.setProgressCallback(e)}async cleanup(){return te.cleanup()}},EA=new Qs});function Eu(i){i.register(new Dr),i.register(new Rr),i.register(new Or),i.register(new Nr),i.register(new _r),i.register(new $r),i.register(new Fr),i.register(new Br),i.register(new Wr),i.register(new Hr),i.register(new Gr),i.register(new jr),i.register(new zr),i.register(new qr),i.register(new Yr),i.register(new Qr),i.register(new Jr),i.register(new eo),i.register(new Qs)}var Iu=L(()=>{"use strict";tl();nl();sl();rl();ol();il();al();hl();fl();bl();yl();vl();Sl();wl();Il();kl();Pl();Ml();Cu()});var Js,ku=L(()=>{"use strict";Js=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 Pu=L(()=>{"use strict"});import Xe from"fs";import tn from"path";import qf from"os";var Kf,pa,Rt,Au=L(()=>{"use strict";q();Kf=/[/\\:*?"<>|]/g,pa=class i{static instance;skillsPath;constructor(){this.skillsPath=tn.join(qf.homedir(),".orion","skills")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.skillsPath}ensureFolder(){try{return Xe.existsSync(this.skillsPath)||(Xe.mkdirSync(this.skillsPath,{recursive:!0}),u.debug(`[Skills] Created skills folder: ${this.skillsPath}`)),!0}catch(e){return u.error(`[Skills] Failed to create skills folder: ${e.message}`),!1}}validateFilename(e){if(!e||typeof e!="string")return{valid:!1,error:"Skill name is required"};let t=e.trim();return t===""?{valid:!1,error:"Skill name cannot be empty"}:Kf.test(t)?{valid:!1,error:"Skill name contains invalid characters"}:tn.join(this.skillsPath,`${t}.md`).startsWith(this.skillsPath)?{valid:!0}:{valid:!1,error:"Invalid skill name (path traversal detected)"}}scanFolder(){try{this.ensureFolder();let e=Xe.readdirSync(this.skillsPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=tn.join(this.skillsPath,n);try{if(!Xe.statSync(s).isFile())continue;let o=Xe.readFileSync(s,"utf-8"),a=n.replace(/\.md$/,"");t.push({id:a,name:a,content:o})}catch(r){u.warn(`[Skills] Failed to read skill file ${n}: ${r.message}`)}}return u.debug(`[Skills] Scanned folder, found ${t.length} skills`),t}catch(e){return u.error(`[Skills] Failed to scan skills folder: ${e.message}`),[]}}createFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=e.trim(),r=tn.join(this.skillsPath,`${s}.md`);try{return this.ensureFolder(),Xe.existsSync(r)?{success:!1,error:"A skill with this name already exists"}:(Xe.writeFileSync(r,t,"utf-8"),u.debug(`[Skills] Created skill file: ${s}`),{success:!0,id:s})}catch(o){return u.error(`[Skills] Failed to create skill file: ${o.message}`),{success:!1,error:o.message}}}updateFile(e,t){let n=this.validateFilename(e);if(!n.valid)return{success:!1,error:n.error};let s=tn.join(this.skillsPath,`${e}.md`);try{return Xe.existsSync(s)?(Xe.writeFileSync(s,t,"utf-8"),u.debug(`[Skills] Updated skill file: ${e}`),{success:!0}):{success:!1,error:"Skill not found"}}catch(r){return u.error(`[Skills] Failed to update skill file: ${r.message}`),{success:!1,error:r.message}}}deleteFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=tn.join(this.skillsPath,`${e}.md`);try{return Xe.existsSync(n)?(Xe.unlinkSync(n),u.debug(`[Skills] Deleted skill file: ${e}`),{success:!0}):{success:!1,error:"Skill not found"}}catch(s){return u.error(`[Skills] Failed to delete skill file: ${s.message}`),{success:!1,error:s.message}}}readFile(e){let t=this.validateFilename(e);if(!t.valid)return{success:!1,error:t.error};let n=tn.join(this.skillsPath,`${e}.md`);try{return Xe.existsSync(n)?{success:!0,content:Xe.readFileSync(n,"utf-8")}:{success:!1,error:"Skill not found"}}catch(s){return u.error(`[Skills] Failed to read skill file: ${s.message}`),{success:!1,error:s.message}}}exists(e){if(!this.validateFilename(e).valid)return!1;let n=tn.join(this.skillsPath,`${e}.md`);return Xe.existsSync(n)}},Rt=pa.getInstance()});var Vf,Xf,Yf,Qf,Jf,Zf,eb,ha,Du=L(()=>{"use strict";Vf=[{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
|
|
1229
1206
|
|
|
1230
1207
|
Use \`wacli\` to message someone on WhatsApp or sync/search WhatsApp history.
|
|
1231
1208
|
|
|
@@ -1306,7 +1283,7 @@ bird tweet "check this out" --media image.png --alt "description"
|
|
|
1306
1283
|
\`\`\`
|
|
1307
1284
|
|
|
1308
1285
|
⚠️ Posting is more likely to be rate limited.
|
|
1309
|
-
`}],
|
|
1286
|
+
`}],Xf=[{id:"notion",name:"Notion",emoji:"📝",description:"Notion API for creating and managing pages, databases, and blocks.",tags:["notion","productivity","notes"],content:`# Notion API
|
|
1310
1287
|
|
|
1311
1288
|
Create/read/update pages, databases, and blocks via Notion API.
|
|
1312
1289
|
|
|
@@ -1412,7 +1389,7 @@ obsidian-cli delete "path/note"
|
|
|
1412
1389
|
|
|
1413
1390
|
Notes
|
|
1414
1391
|
- Prefer direct edits: open the .md file and Obsidian will pick it up.
|
|
1415
|
-
`}],
|
|
1392
|
+
`}],Yf=[{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
|
|
1416
1393
|
|
|
1417
1394
|
Universal rules for writing code in any language.
|
|
1418
1395
|
|
|
@@ -1696,7 +1673,7 @@ Tell user: "Installed '<name>' skill - [what it does]"
|
|
|
1696
1673
|
1. Do NOT install
|
|
1697
1674
|
2. Try next skill from search results
|
|
1698
1675
|
3. If all fail, tell user what's missing
|
|
1699
|
-
`}],
|
|
1676
|
+
`}],Qf=[{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"}],Jf=[{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
|
|
1700
1677
|
|
|
1701
1678
|
Use \`nano-pdf\` to apply edits to a PDF using natural-language instructions.
|
|
1702
1679
|
|
|
@@ -1748,7 +1725,7 @@ peekaboo type "Line 1\\nLine 2" --delay 10
|
|
|
1748
1725
|
Notes
|
|
1749
1726
|
- Requires Screen Recording + Accessibility permissions.
|
|
1750
1727
|
- Use \`peekaboo see --annotate\` to identify targets before clicking.
|
|
1751
|
-
`}],
|
|
1728
|
+
`}],Zf=[{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
|
|
1752
1729
|
|
|
1753
1730
|
Use \`gog\` for Gmail/Calendar/Drive/Contacts/Sheets/Docs. Requires OAuth setup.
|
|
1754
1731
|
|
|
@@ -1784,8 +1761,8 @@ Docs
|
|
|
1784
1761
|
Notes
|
|
1785
1762
|
- Set \`GOG_ACCOUNT=you@gmail.com\` to avoid repeating \`--account\`.
|
|
1786
1763
|
- Confirm before sending mail or creating events.
|
|
1787
|
-
`}],
|
|
1788
|
-
`);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},
|
|
1764
|
+
`}],eb=[{id:"messaging",name:"Messaging",icon:"MessageCircle",description:"WhatsApp, iMessage, Slack, and social platforms",skills:Vf},{id:"productivity",name:"Productivity",icon:"CheckSquare",description:"Notion, Trello, Things, Reminders, Obsidian",skills:Xf},{id:"development",name:"Development",icon:"Code",description:"GitHub and developer tools",skills:Yf},{id:"smart-home",name:"Smart Home",icon:"Home",description:"Philips Hue, Sonos, BluOS, Eight Sleep",skills:Qf},{id:"media",name:"Media & Utilities",icon:"Music",description:"Spotify, GIFs, PDFs, audio visualization, macOS automation",skills:Jf},{id:"google",name:"Google Workspace",icon:"Mail",description:"Gmail, Calendar, Drive, Sheets, Docs",skills:Zf}],ha=()=>eb.flatMap(i=>i.skills)});var Ou={};Fe(Ou,{skillsStore:()=>An});import{EventEmitter as tb}from"events";var Mu,va,nb,Ru,sb,rb,ba,ya,An,Sa=L(()=>{"use strict";Pu();Au();He();q();Du();Mu="orion-skills-selected",va="orion-installed-skill-templates",nb=()=>{try{let i=ye.string(va);if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}},Ru=i=>{ye.set(va,JSON.stringify(i))},sb=i=>{let e="orion-skills-initialized";if(ye.string(e)&&!ye.string(va)){let n=ha(),s=i.map(o=>o.toLowerCase()),r=n.filter(o=>s.includes(o.name.toLowerCase())||s.includes(o.id.toLowerCase())).map(o=>o.id);Ru(r),ye.remove(e),u.debug(`[Skills] Migrated to version-based system. Found ${r.length} existing template skills.`)}},rb=async i=>{sb(i);let e=ha(),t=nb(),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{Rt.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 Ru([...t,...o]),u.info(`[Skills] Sync complete: installed ${r} new skill(s)`),r>0},ba=(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},ya=class i extends tb{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=ye.string(Mu);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}saveSelectedIds(e){ye.set(Mu,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..."),Rt.ensureFolder();let e=Rt.scanFolder(),t=e.map(c=>c.name);await rb(t)&&(e=Rt.scanFolder());let s=new Date().toISOString(),r=e.map(c=>({id:c.id,name:c.name,description:ba(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=Rt.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()||ba(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){Rt.deleteFile(e);let m=Rt.createFile(o,a);if(!m.success)return this.state.isUpdating=null,this.emit("change",this.state),{success:!1,error:m.error}}else{let m=Rt.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()||ba(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=Rt.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)=>`═══════════════════════════════════════════════════════════════
|
|
1789
1766
|
SKILL ${n+1}: ${t.name.toUpperCase()}
|
|
1790
1767
|
═══════════════════════════════════════════════════════════════
|
|
1791
1768
|
|
|
@@ -1798,22 +1775,49 @@ ${e.map(n=>` <skill>
|
|
|
1798
1775
|
<description>${n.description}</description>
|
|
1799
1776
|
</skill>`).join(`
|
|
1800
1777
|
`)}
|
|
1801
|
-
</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)")}},ns=wa.getInstance()});import Xe from"fs";import sn from"path";import lb from"os";var ub,xa,rn,$u=L(()=>{"use strict";q();ub=/[/\\:*?"<>|]/g,xa=class i{static instance;charactersPath;constructor(){this.charactersPath=sn.join(lb.homedir(),".orion","characters")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.charactersPath}ensureFolder(){try{return Xe.existsSync(this.charactersPath)||(Xe.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"}:ub.test(t)?{valid:!1,error:"Character name contains invalid characters"}:sn.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=Xe.readdirSync(this.charactersPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=sn.join(this.charactersPath,n);try{if(!Xe.statSync(s).isFile())continue;let o=Xe.readFileSync(s,"utf-8"),a=n.replace(/\.md$/,"");t.push({id:a,name:a,content:o})}catch(r){u.warn(`[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=sn.join(this.charactersPath,`${s}.md`);try{return this.ensureFolder(),Xe.existsSync(r)?{success:!1,error:"A character with this name already exists"}:(Xe.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=sn.join(this.charactersPath,`${e}.md`);try{return Xe.existsSync(s)?(Xe.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=sn.join(this.charactersPath,`${e}.md`);try{return Xe.existsSync(n)?(Xe.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=sn.join(this.charactersPath,`${e}.md`);try{return Xe.existsSync(n)?{success:!0,content:Xe.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=sn.join(this.charactersPath,`${e}.md`);return Xe.existsSync(n)}},rn=xa.getInstance()});import{EventEmitter as db}from"events";var Ca,Ea,Ao,Fu=L(()=>{"use strict";$u();We();q();Ca="orion-characters-active",Ea=class i extends db{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 ye.string(Ca)||null}saveActiveId(e){e?ye.set(Ca,e):ye.remove(Ca)}getState(){return{...this.state}}async loadCharacters(){this.state.isLoading=!0,this.emit("change",this.state);try{u.debug("[Characters] Loading characters from file system..."),rn.ensureFolder();let e=rn.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=rn.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){rn.deleteFile(e);let d=rn.createFile(s,r);if(!d.success)return this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:d.error}}else{let d=rn.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=rn.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>
|
|
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)")}},An=ya.getInstance()});var $u={};Fe($u,{toolPermissionsStore:()=>_u,useToolPermissionsStore:()=>Ca});import{EventEmitter as ob}from"events";import Zs from"fs";import Nu from"path";import ib from"os";function ab(){try{if(!Zs.existsSync(Ao))return null;let i=Zs.readFileSync(Ao,"utf-8");return JSON.parse(i)}catch(i){return u.error(`[ToolPermissions] Failed to load permissions: ${i}`),null}}function cb(i){try{let e=Nu.dirname(Ao);Zs.existsSync(e)||Zs.mkdirSync(e,{recursive:!0}),Zs.writeFileSync(Ao,JSON.stringify(i,null,2)),u.debug("[ToolPermissions] Saved permissions to file")}catch(e){u.error(`[ToolPermissions] Failed to save permissions: ${e}`)}}var wa,Ta,Ao,xa,_u,Ca,Ea=L(()=>{"use strict";q();wa={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},Ta={ListCalls:!0,GetCallRecordings:!0,GetRecentMessages:!0,SendMessage:!0,ScheduleMessage:!0,GetContacts:!0,RunOperatorTask:!0,SearchMemory:!0,StoreMemory:!0,TelegramSend:!0,DiscordSend:!0},Ao=Nu.join(ib.homedir(),".orion","tool-permissions.json");xa=class i extends ob{static instance;onDeviceTools;backendTools;lastSyncedAt=null;constructor(){super();let e=ab();e?(this.onDeviceTools={...wa,...e.onDeviceTools},this.backendTools={...Ta,...e.backendTools},this.lastSyncedAt=e.lastModified,u.debug("[ToolPermissions] Loaded permissions from file")):(this.onDeviceTools={...wa},this.backendTools={...Ta},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={...wa},this.backendTools={...Ta},this.save(),this.emit("permissions_reset")}save(){let e={onDeviceTools:this.onDeviceTools,backendTools:this.backendTools,lastModified:new Date().toISOString()};this.lastSyncedAt=e.lastModified,cb(e)}getState(){return this}},_u=xa.getInstance(),Ca={getState:()=>_u}});var Lu={};Fe(Lu,{TelegramToolConnectionService:()=>Do,telegramToolConnectionService:()=>ns});import{ref as Fu,onChildAdded as lb,onChildChanged as ub,update as db,off as gb}from"firebase/database";import{io as mb}from"socket.io-client";import{EventEmitter as pb}from"events";var Do,ns,Ia=L(()=>{"use strict";q();Ms();Pt();Te();Do=class i extends pb{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=kt.getInstance(),this.setupLogoutListener(),u.debug("[TelegramToolConnection] Service initialized")}setupLogoutListener(){X.getInstance().on("SnowXSignOut",()=>{u.debug("[TelegramToolConnection] Sign out detected, stopping listeners"),this.stopListening(),this.disconnectAllSessions(),this.currentUserId=null,this.currentDeviceId=null,this.processedRequestIds.clear(),this.sessionCleanupInterval&&(clearInterval(this.sessionCleanupInterval),this.sessionCleanupInterval=null)})}static getInstance(){return i.instance||(i.instance=new i),i.instance}setFirebaseDatabase(e){this.database=e,u.debug("[TelegramToolConnection] Firebase database set")}setToolExecutionCallback(e){this.onToolExecutionCallback=e,u.debug("[TelegramToolConnection] Tool execution callback registered")}isCallbackRegistered(){return this.onToolExecutionCallback!==null}async startListening(e,t){let n=t||Pe.getInstance().getCurrentDeviceId();if(!n){u.error("[TelegramToolConnection] No device ID available - cannot start listening");return}if(!this.database){u.error("[TelegramToolConnection] Firebase database not set - cannot start listening");return}this.onToolExecutionCallback||(u.warn("[TelegramToolConnection] Callback not yet registered, waiting..."),await this.waitForCallbackRegistration(5e3,50)||u.error("[TelegramToolConnection] Cannot start listener - callback not registered after 5s")),this.currentUserId=e,this.currentDeviceId=n,u.info("[TelegramToolConnection] Starting listener"),u.debug(` User: ${e}`),u.debug(` Device: ${n}`),u.debug(` Callback registered: ${this.onToolExecutionCallback!==null}`),this.stopListening(),this.setupFirebaseListener(e,n)}async waitForCallbackRegistration(e=5e3,t=50){if(this.onToolExecutionCallback)return!0;let n=Date.now();for(;Date.now()-n<e;)if(await new Promise(s=>setTimeout(s,t)),this.onToolExecutionCallback)return u.debug(`[TelegramToolConnection] Callback registered after ${Date.now()-n}ms`),!0;return!1}stopListening(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.listenerRef&&(gb(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=Fu(this.database,n);this.listenerRef=s;let r=(c,l)=>{if(!l)return;let d={...l,sessionId:l.sessionId||c};this.handleConnectionRequest(d)},o=lb(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=ub(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=mb(o,{path:"/frontend-tools",query:{deviceId:this.currentDeviceId||"",sessionId:t,token:a},transports:["websocket","polling"],reconnection:!1,timeout:3e4,forceNew:!0}),this.setupSocketEventHandlers(r,t),this.activeSessions.set(t,{sessionId:t,socket:r,conversationId:n,source:s,createdAt:Date.now()}),this.ensureSessionCleanupRunning(),await this.waitForSocketConnection(r,3e4))await this.registerDevice(r),await this.updateStatus("connected",t),u.info(`[TelegramToolConnection] WebSocket connected for session: ${t}`);else throw new Error("WebSocket connection timeout")}catch(o){if(u.error(`[TelegramToolConnection] Failed to connect: ${o.message}`),r)try{r.removeAllListeners(),r.disconnect()}catch{}await this.updateStatus("error",t),this.activeSessions.delete(t)}}async handleCompleted(e){u.debug(`[TelegramToolConnection] Completion received, disconnecting session: ${e}`),this.disconnectSession(e)}disconnectSession(e){let t=this.activeSessions.get(e);if(t){try{t.socket.removeAllListeners(),t.socket.disconnect()}catch{}this.activeSessions.delete(e),u.debug(`[TelegramToolConnection] Session ${e} disconnected`),this.stopSessionCleanupIfEmpty()}}disconnectAllSessions(){for(let[e,t]of this.activeSessions)try{t.socket.removeAllListeners(),t.socket.disconnect()}catch{}this.activeSessions.clear(),this.stopSessionCleanupIfEmpty()}ensureSessionCleanupRunning(){this.sessionCleanupInterval||(this.sessionCleanupInterval=setInterval(()=>{this.cleanupExpiredSessions()},this.SESSION_CLEANUP_INTERVAL_MS))}stopSessionCleanupIfEmpty(){this.activeSessions.size===0&&this.sessionCleanupInterval&&(clearInterval(this.sessionCleanupInterval),this.sessionCleanupInterval=null)}cleanupExpiredSessions(){let e=Date.now();for(let[t,n]of this.activeSessions)e-n.createdAt>this.SESSION_MAX_AGE_MS&&(u.debug(`[TelegramToolConnection] Expiring stale session ${t}`),this.disconnectSession(t))}async buildSocketIOURL(){let e="ws.snowx.ai",t="";try{t=await X.getInstance().getFirebaseIdToken()||""}catch{u.warn("[TelegramToolConnection] Failed to get Firebase token")}return{url:`wss://${e}`,token:t}}setupSocketEventHandlers(e,t){e.on("connect",()=>{u.debug(`[TelegramToolConnection] Socket connected for session: ${t}`)}),e.on("disconnect",n=>{u.debug(`[TelegramToolConnection] Socket disconnected for session: ${t}, reason: ${n}`);let s=this.activeSessions.get(t),r=s?.conversationId,o=s?.source||"telegram";this.activeSessions.delete(t),r&&this.emit("external_session_ended",{source:o,conversationId:r,error:!0,timestamp:Date.now()})}),e.on("connect_error",n=>{u.error(`[TelegramToolConnection] Connection error for session: ${t}: ${n.message}`)}),e.on("connection_established",n=>{u.debug(`[TelegramToolConnection] Connection established for session: ${t}`)}),e.on("tool_execution_request",async n=>{let s=n?.data?.tool_name||"tool",o=this.activeSessions.get(t)?.source||"telegram";u.debug(`[TelegramToolConnection] Tool execution request: ${s} (session: ${t}, source: ${o})`),this.emit("remote_task_status",{status:"start",toolName:s,source:o,timestamp:Date.now()});try{await this.handleToolExecutionRequest(e,n,t)}finally{this.emit("remote_task_status",{status:"end",toolName:s,source:o,timestamp:Date.now()})}}),e.on("external_session_started",n=>{u.info(`[TelegramToolConnection] External session started - source: ${n.source}, session: ${t}`),this.emit("external_session_started",n)}),e.on("external_session_ended",n=>{u.info(`[TelegramToolConnection] External session ended - source: ${n.source}, session: ${t}`),this.emit("external_session_ended",n)})}waitForSocketConnection(e,t){return new Promise(n=>{let s=!1,r=()=>{s||(s=!0,e.off("connection_established",o),e.off("connect_error",a))},o=()=>{clearTimeout(c),r(),n(!0)},a=()=>{clearTimeout(c),r(),n(!1)},c=setTimeout(()=>{r(),n(!1)},t);e.once("connection_established",o),e.once("connect_error",a)})}async registerDevice(e){e.emit("device_registration",{deviceId:this.currentDeviceId,userId:this.currentUserId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url","browser_navigate","browser_click","browser_type"]}),u.debug("[TelegramToolConnection] Device registered")}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"macOS"}async handleToolExecutionRequest(e,t,n,s=0){let l={id:t.data?.id||"",name:t.data?.tool_name||"",arguments:t.data?.arguments||{},timestamp:t.metadata?.timestamp||new Date().toISOString()},d=t.metadata?.tool_call_id||l.id,g=Date.now(),p=this.activeSessions.get(n)?.source||"telegram";if(u.debug(`[TelegramToolConnection] Executing tool: ${l.name} (session: ${n}, source: ${p})`),!this.onToolExecutionCallback&&s<3)return u.warn(`[TelegramToolConnection] Callback not ready, retry ${s+1}/3`),await new Promise(f=>setTimeout(f,200)),this.handleToolExecutionRequest(e,t,n,s+1);let h=f=>{e.connected&&e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:[{type:"text",text:`Error: ${f}`}],success:!1,error:f})};try{let f,y=!0;this.onToolExecutionCallback?(f=await Promise.race([this.onToolExecutionCallback(l),new Promise((C,v)=>setTimeout(()=>v(new Error(`Tool execution timed out after ${3e5/1e3}s`)),3e5))]),!f||typeof f!="object"?(y=!1,f={error:"Invalid tool result"}):(f.success===!1||f.error)&&(y=!1)):(u.error("[TelegramToolConnection] No tool execution callback registered!"),f={error:"Tool execution not available"},y=!1);let T=this.formatResultAsContentBlocks(f);if(!e.connected){u.warn("[TelegramToolConnection] Socket disconnected before sending response");return}let x=JSON.stringify(T);if(x.length>1048576){u.warn(`[TelegramToolConnection] Result too large (${x.length} bytes), truncating...`);let C=T.map(v=>v.type==="text"&&v.text&&v.text.length>5e4?{...v,text:v.text.slice(0,5e4)+`
|
|
1779
|
+
|
|
1780
|
+
... [TRUNCATED - result too large]`}:v);e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:C,success:y,error:y?null:f?.error||"Tool execution failed"})}else e.emit("tool_execution_response",{id:l.id,tool_call_id:d,tool_name:l.name,content:T,success:y,error:y?null:f?.error||"Tool execution failed"});let S=Date.now()-g;u.debug(`[TelegramToolConnection] Tool ${l.name} completed in ${S}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(()=>(Sa(),Ou)),o=r.getSelectedSkillsContent();o&&(s.skills_instruction=o,u.debug(`[TelegramToolConnection] Including skills in Firebase, length: ${o.length}`))}catch(r){u.warn(`[TelegramToolConnection] Failed to load skills: ${r.message}`)}try{let{DeviceKnowledgeService:r}=await Promise.resolve().then(()=>(Xr(),El)),o=r.getInstance(),a=o.readDeviceKnowledge();if(a){let c=o.getKnowledgeFilePath();s.device_knowledge_instruction=`Current device knowledge (${c}): ${a}
|
|
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(()=>(Ea(),$u)),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=Fu(this.database,n);await db(o,s),u.debug(`[TelegramToolConnection] Status updated to '${e}' via SDK`)}catch(o){u.error(`[TelegramToolConnection] Failed to update status: ${o.message}`)}}}getActiveSessionCount(){return this.activeSessions.size}isSessionActive(e){return this.activeSessions.has(e)}destroy(){u.debug("[TelegramToolConnection] Destroying service"),this.sessionCleanupInterval&&(clearInterval(this.sessionCleanupInterval),this.sessionCleanupInterval=null),this.stopListening(),this.disconnectAllSessions(),this.currentUserId=null,this.currentDeviceId=null,this.processedRequestIds.clear(),this.onToolExecutionCallback=null}},ns=Do.getInstance()});var Bi={};Fe(Bi,{FrontendWebSocketService:()=>fe});import{EventEmitter as hb}from"events";import{io as fb}from"socket.io-client";import Uu from"os";import Bu from"path";import Ot from"fs";import bb from"axios";var $t,fe,Jn=L(()=>{"use strict";q();Pt();Te();zn();Kn();Ai();Qc();Iu();ku();$t=Bu.join(Uu.homedir(),".orion","pending-tool-results.json"),fe=class i extends hb{static instance;socket=null;_connectionState="disconnected";connectionError=null;isConversationActive=!1;serverHost;deviceId=null;userId=null;sessionId=null;deviceRegistrationService;authService;toolRegistry;runningProcesses=new Map;activeWebViewURLs=[];reconnectAttempts=0;heartbeatTimer=null;baseHeartbeatInterval=2e4;lastHeartbeat=null;lastPongReceived=new Date;connectionQuality="excellent";connectionMetrics={totalConnections:0,totalDisconnections:0,disconnectionReasons:{},qualityDegradations:0,proactiveRecoveries:0,successfulRecoveries:0,failedRecoveries:0,pingResponseTimes:[],lastMetricsReset:new Date};tokenRefreshTimer=null;TOKEN_REFRESH_INTERVAL=2700*1e3;consecutivePoorQualityChecks=0;keepaliveWatchdog=null;lastKeepaliveTime=null;baseKeepaliveTimeout=12e4;extendedKeepaliveTimeout=6e5;aggressiveHeartbeatTimer=null;baseAggressiveHeartbeatInterval=5e3;toolProgressTimer=null;baseToolProgressInterval=15e3;activeToolExecutions=new Set;lastHeartbeatSent=null;superAggressiveMode=!1;connectionHealthCheckTimer=null;POOR_QUALITY_THRESHOLD=2;CONNECTION_HEALTH_CHECK_INTERVAL=1e4;toolExecutionQueue=[];activeToolCount=0;MAX_CONCURRENT_TOOLS=5;MAX_QUEUED_TOOLS=50;pendingToolResults=[];MAX_PENDING_RESULTS=100;TOOL_RESULTS_HTTP_ENDPOINT="https://snowx.ai/api-beta/api/tool-results";capturedScreenshots=[];MAX_CAPTURED_SCREENSHOTS=10;pingLatencies=[];MAX_PING_SAMPLES=10;tokenCounter=new ct;wsConnectionStartTime=null;pendingDeleteConfirmations=new Map;DELETE_CONFIRMATION_TIMEOUT=5e4;_hasElectronFrontend=!1;onConnectionStateChangeCallbacks=new Set;connectionPromise=null;constructor(e="ws.snowx.ai",t,n="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=Pe.getInstance(),this.authService=X.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,n),this.toolRegistry=new kr,Eu(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(()=>(Ia(),Lu)).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 Js(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=fb(t,{path:"/frontend-tools",query:{deviceId:this.deviceId||"",sessionId:this.sessionId||"",token:e},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.1,timeout:45e3,autoConnect:!0,forceNew:!0}),this.setupSocketEventHandlers()}catch(e){u.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){u.debug(`[FRONTEND WS] DISCONNECT - Reason: ${e}, Permanent: ${t}`),this.connectionMetrics.totalDisconnections++,this.connectionMetrics.disconnectionReasons[e]=(this.connectionMetrics.disconnectionReasons[e]||0)+1,this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.stopTokenRefreshTimer(),this.stopConnectionHealthCheck(),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,u.debug("[FRONTEND WS] Socket.IO disconnected")),this.connectionError=null,this._connectionState="disconnected",this.notifyConnectionStateChange(),t&&(this.isConversationActive=!1,this.reconnectAttempts=0,this.pendingToolResults.length>0&&(u.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),u.debug("[FRONTEND WS] Connection state FULLY reset (permanent disconnect)")),this.emit("disconnected")}async waitForConnection(e){return this.isConnected()?!0:new Promise((t,n)=>{let s=setTimeout(()=>{this.connectionPromise=null,n(new Error("WebSocket connection timeout"))},e);this.connectionPromise={resolve:r=>{clearTimeout(s),this.connectionPromise=null,t(r)},reject:r=>{clearTimeout(s),this.connectionPromise=null,n(r)},timeoutId:s}})}resolveConnectionPromise(e){this.connectionPromise&&this.connectionPromise.resolve(e)}rejectConnectionPromise(e){this.connectionPromise&&this.connectionPromise.reject(e)}setupSocketEventHandlers(){this.socket&&(this.socket.on("connect",()=>{u.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{u.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{u.error(`[FRONTEND WS] Socket.IO connect_error: ${e.message}`),this.connectionError=e.message,this.rejectConnectionPromise(e)}),this.socket.io.on("reconnect_attempt",e=>{this.reconnectAttempts=e,u.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{u.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{u.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{u.error("[FRONTEND WS] All reconnection attempts failed"),this.connectionError="Connection failed after multiple attempts.",this._connectionState="disconnected",this.notifyConnectionStateChange()}),this.socket.on("connection_established",e=>{this.handleConnectionEstablished(e)}),this.socket.on("tool_execution_request",e=>{u.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{u.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{u.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{u.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("ping_request",e=>{u.debug(`[FRONTEND WS] Server ping_request received: ${e.reason||"heartbeat"}`),this.socket?.connected&&this.socket.emit("ping_response",{timestamp:Date.now(),originalTimestamp:e.timestamp,hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size,isWindowVisible:!0}),this.lastPongReceived=new Date,this.consecutivePoorQualityChecks=0,this.updateConnectionQuality()}),this.socket.on("connection_quality_warning",e=>{u.debug(`[FRONTEND WS] Connection quality warning: ${e.quality} - ${e.reason}`),this.connectionMetrics.qualityDegradations++,this.socket?.connected&&this.socket.emit("ping",{timestamp:new Date().toISOString(),reason:"quality_warning_response"}),e.quality==="critical"&&this.handleConnectionQualityDegradation()}),this.socket.on("ping_ack",e=>{u.debug(`[FRONTEND WS] Ping acknowledged: health=${e.connectionHealth}, latency=${e.latency}ms`),this.lastPongReceived=new Date,e.latency!==void 0&&(this.connectionMetrics.pingResponseTimes.length>=this.MAX_PING_SAMPLES&&this.connectionMetrics.pingResponseTimes.shift(),this.connectionMetrics.pingResponseTimes.push(e.latency)),this.updateConnectionQuality()}),this.socket.on("tool_execution_dropped",e=>{let t=e.executionId||e.toolId,n=e.toolName||"unknown",s=e.message||e.reason;u.debug(`[FRONTEND WS] Tool execution dropped: ${n} (${t}) - ${s}`),t&&this.activeToolExecutions.has(t)&&(this.activeToolExecutions.delete(t),this.activeToolCount=Math.max(0,this.activeToolCount-1),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat()),this.emit("tool_dropped",{executionId:t,toolId:t,toolName:n,reason:e.reason,message:s})}),this.socket.on("long_operation_start",e=>{u.debug("[FRONTEND WS] Backend requested long operation mode"),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat()}),this.socket.on("stop_signal",e=>{this.handleStopSignal(e)}),this.socket.on("stop_all_tools",e=>{u.debug("[FRONTEND WS] Stop all tools request received"),this.handleStopAllTools(e)}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{u.debug("[FRONTEND WS] Shell cleanup request received"),this.handleShellCleanup(e)}),this.socket.on("checkpoint_request",e=>{this.handleCheckpointRequest(e)}),this.socket.on("messages_saved",e=>{this.handleMessagesSaved(e)}),this.socket.on("auto_prompt",e=>{this.handleAutoPrompt(e)}),this.socket.on("reconnection_requested",e=>{u.debug(`[FRONTEND WS] Reconnection requested by server: ${e.reason||"unknown"}`),this.handleReconnectionRequest(e)}),this.socket.on("sub_agent_event",e=>{u.debug(`[FRONTEND WS] Sub-agent event received: ${e.type}`),this.handleSubAgentEvent(e)}),this.socket.on("external_session_started",e=>{u.debug(`[FRONTEND WS] External session started: ${e.source} - ${e.message}`),this.emit("external_session_started",e)}),this.socket.on("external_session_ended",e=>{u.debug(`[FRONTEND WS] External session ended: ${e.source}${e.error?" (with error)":""}`),this.emit("external_session_ended",e)}),this.socket.on("get_image_for_annotation",e=>{u.debug(`[FRONTEND WS] Image for annotation request received - ID: ${e.id}, Path: ${e.image_path}`),this.handleImageForAnnotationRequest(e)}),this.socket.on("delete_confirmation_response",e=>{this.handleDeleteConfirmationResponse(e)}),this.socket.on("error",e=>{console.error("[FRONTEND WS] Socket.IO error:",e)}))}handleConnect(){u.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.connectionMetrics.totalConnections++,this.startHeartbeat(),this.startKeepaliveWatchdog(),this.startConnectionHealthCheck(),this.startTokenRefreshTimer(),this.activeToolExecutions.size>0&&(u.debug(`[FRONTEND WS] Restarting aggressive heartbeat - ${this.activeToolExecutions.size} tools still active`),this.startAggressiveHeartbeat())}handleConnectionEstablished(e){if(this.wsConnectionStartTime){let t=Date.now()-this.wsConnectionStartTime.getTime();u.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else u.debug("[FRONTEND WS] Connection established!");this.registerDevice(),this._connectionState="connected",this.notifyConnectionStateChange(),this.isConversationActive=!0,this.loadPersistedToolResults(),this.flushPendingToolResultsWithFallback(),this.resolveConnectionPromise(!0),this.emit("connected")}handleDisconnect(e){u.debug(`[FRONTEND WS] Handling disconnect: ${e}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.rejectConnectionPromise(new Error(`WebSocket disconnected: ${e}`)),this.isConversationActive||u.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){u.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,n=t?.type||t?.stop_type||"all";switch(u.debug(`[FRONTEND WS] Stop type: ${n}`),n){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:u.debug(`[FRONTEND WS] Unknown stop type: ${n}`)}}handleStopAllTools(e){let t=e.session_id,n=e.reason||"backend_stop";if(u.debug(`[FRONTEND WS] Stopping all tools - Session: ${t}, Reason: ${n}`),t&&this.sessionId&&t!==this.sessionId){u.debug(`[FRONTEND WS] Ignoring stop_all_tools for different session (theirs: ${t}, ours: ${this.sessionId})`);return}this.stopAllActiveTools(n)}stopAllActiveTools(e){u.debug(`[FRONTEND WS] Stopping all active tools - Reason: ${e}`),u.debug(`[FRONTEND WS] - Active tools: ${this.activeToolExecutions.size}`),u.debug(`[FRONTEND WS] - Queued tools: ${this.toolExecutionQueue.length}`),u.debug(`[FRONTEND WS] - Pending results: ${this.pendingToolResults.length}`),this.toolExecutionQueue.length>0&&(u.debug(`[FRONTEND WS] Clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]),this.activeToolExecutions.size>0&&(u.debug(`[FRONTEND WS] Marking ${this.activeToolExecutions.size} active tools as cancelled`),this.activeToolExecutions.clear(),this.activeToolCount=0),this.pendingToolResults.length>0&&(u.debug(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending results`),this.pendingToolResults=[]),this.stopAggressiveHeartbeat(),this.terminateAllRunningProcesses(),u.debug(`[FRONTEND WS] All tools stopped for reason: ${e}`)}frameFeedbackForLLM(e,t,n){return`<user_feedback priority="high" requires_response="true">
|
|
1783
|
+
${n>1?`[Mid-Task User Feedback ${t}/${n}]`:"[Mid-Task User Feedback]"}
|
|
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
|
+
|
|
1786
|
+
<feedback_content>
|
|
1787
|
+
${e}
|
|
1788
|
+
</feedback_content>
|
|
1789
|
+
|
|
1790
|
+
<instructions>
|
|
1791
|
+
- You MUST acknowledge this feedback in your response
|
|
1792
|
+
- If this feedback changes your current approach, explain how you will adjust
|
|
1793
|
+
- If this feedback contradicts your current direction, STOP and address the user's concern first
|
|
1794
|
+
- Do NOT continue with your previous plan if it conflicts with this feedback
|
|
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=at.getInstance(),a=o.getQueuedMessages(),c=a.map((d,g)=>({content:this.frameFeedbackForLLM(d.content,g+1,a.length),timestamp:Math.floor(d.timestamp.getTime()),imageUrls:d.imageUrls||[],is_mid_task_feedback:!0,requires_acknowledgment:!0})),l=c.length>0;u.debug(`[FRONTEND WS] Sending checkpoint response with ${c.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:n,session_id:s,has_feedback:l,feedback:c}),l&&(u.info(`Sent ${c.length} feedback message(s) to AI`),this.emit("feedback:sent",a),o.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,n=e.isNew;if(!t||n===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:n})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){u.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){u.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}u.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),u.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}async handleReconnectionRequest(e){let t=e.reason||"unknown",n=e.lastPingAge||0;if(u.debug(`[FRONTEND WS] Server requested reconnection - Reason: ${t}`),u.debug(`[FRONTEND WS] Connection was degraded (last ping: ${Math.round(n/1e3)}s ago)`),this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0){u.debug(`[FRONTEND WS] Deferring reconnection - ${this.activeToolExecutions.size} active, ${this.toolExecutionQueue.length} queued tools`),this.sendAggressiveHeartbeat();return}if(this.pendingToolResults.length>0){u.debug(`[FRONTEND WS] Deferring reconnection - ${this.pendingToolResults.length} pending results to send`),this.sendAggressiveHeartbeat();return}if(this.socket&&this.isConversationActive&&this.sessionId&&this.userId){u.debug("[FRONTEND WS] Initiating forced reconnection...");let s=this.sessionId,r=this.userId,o=this.deviceId;this.disconnect("reconnection_requested",!1),await new Promise(a=>setTimeout(a,500));try{await this.connectForConversation(r,s)?(u.debug("[FRONTEND WS] Reconnection successful!"),u.debug(`[FRONTEND WS] Composite key: ${o}_${s}`)):u.error("[FRONTEND WS] Reconnection failed")}catch(a){u.error(`[FRONTEND WS] Reconnection error: ${a}`)}}else u.debug("[FRONTEND WS] Cannot reconnect - missing session info or conversation not active")}handleSubAgentEvent(e){let{type:t,data:n}=e;u.debug(`[FRONTEND WS] Sub-agent event: ${t}`,n);try{Yc.handleEvent({type:t,...n}),u.debug("[FRONTEND WS] Sub-agent event forwarded to SubAgentManager")}catch(s){u.debug(`[FRONTEND WS] Failed to forward to SubAgentManager: ${s}`)}this.emit("subAgentEvent",{type:t,...n,timestamp:new Date().toISOString()})}async handleImageForAnnotationRequest(e){let{id:t,image_path:n,timeout:s=3e4}=e;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={id:e.data?.id||"",name:e.data?.tool_name||"",arguments:e.data?.arguments||{},timestamp:e.metadata?.timestamp||new Date().toISOString()},n=e.metadata?.tool_call_id||t.id;this.toolExecutionQueue.length>=this.MAX_QUEUED_TOOLS&&(u.warn("[FRONTEND WS] Tool execution queue full, dropping oldest tool"),this.toolExecutionQueue.shift()),this.toolExecutionQueue.push(async()=>{await this.executeToolWithTracking(t,n)}),this.processNextTool()}processNextTool(){if(this.activeToolCount>=this.MAX_CONCURRENT_TOOLS){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 Js(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 bb.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{Ot.existsSync($t)&&Ot.unlinkSync($t)}catch{}return}try{let e={sessionId:this.sessionId,deviceId:this.deviceId,results:this.pendingToolResults,timestamp:new Date().toISOString()},t=Bu.dirname($t);Ot.existsSync(t)||Ot.mkdirSync(t,{recursive:!0}),Ot.writeFileSync($t,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(!Ot.existsSync($t))return;let e=Ot.readFileSync($t,"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)");Ot.unlinkSync($t)}catch(e){u.error(`[FRONTEND WS] Failed to load persisted tool results: ${e}`);try{Ot.existsSync($t)&&Ot.unlinkSync($t)}catch{}}}flushPendingToolResults(){if(this.pendingToolResults.length===0)return;u.debug(`[FRONTEND WS] Flushing ${this.pendingToolResults.length} queued tool results`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e)try{this.socket?.connected?(this.socket.emit(t.type,t.data),u.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(n){u.error(`[FRONTEND WS] Failed to send queued tool result: ${n}`),this.pendingToolResults.push(t)}this.persistPendingToolResults()}async flushPendingToolResultsWithFallback(){if(this.pendingToolResults.length===0)return;u.debug(`[FRONTEND WS] 🔄 Flushing ${this.pendingToolResults.length} pending tool results with HTTP fallback`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e){let n=!1;try{this.socket?.connected&&(this.socket.emit(t.type,t.data),u.debug(`[FRONTEND WS] ✅ Sent queued tool result via WebSocket: ${t.data?.id}`),n=!0)}catch(s){u.error(`[FRONTEND WS] Failed to send via WebSocket: ${s}`)}n||await this.submitToolResultViaHttp(t.data)&&(n=!0),n||(u.warn(`[FRONTEND WS] ⚠️ Both WebSocket and HTTP failed for result: ${t.data?.id}`),this.pendingToolResults.push(t))}this.persistPendingToolResults()}registerDevice(){if(!this.userId||!this.deviceId){console.warn("[FRONTEND WS] Cannot register device - missing userId or deviceId");return}let e=["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url"];this.socket?.emit("device_registration",{deviceId:this.deviceId,userId:this.userId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:e})}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"Unknown"}captureScreenshotFromResult(e,t){try{let n=JSON.parse(t);if(Array.isArray(n))for(let s of n)s.type==="image_url"&&s.image_url?.url&&(u.debug("[FRONTEND WS] 📸 Storing screenshot for assistant message attachment"),this.capturedScreenshots.push({toolCallId:e,base64Data:s.image_url.url}),this.capturedScreenshots.length>this.MAX_CAPTURED_SCREENSHOTS&&(u.debug(`[FRONTEND WS] 🧹 Dropping oldest screenshot (limit: ${this.MAX_CAPTURED_SCREENSHOTS})`),this.capturedScreenshots.shift()))}catch(n){u.warn(`[FRONTEND WS] ⚠️ Failed to parse screenshot tool output: ${n}`)}}getCapturedScreenshots(){return[...this.capturedScreenshots]}clearCapturedScreenshots(){this.capturedScreenshots=[]}async sendToolResult(e,t,n,s,r){let o;typeof s=="string"?o=s:s&&typeof s=="object"&&"output"in s?o=s.output||s.error||"":o=JSON.stringify(s);let a=this.createContentBlocks(o,r,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:a,success:!0,error:null})}sendToolError(e,t,n,s){let r=this.createContentBlocks(s.message,!1,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:r,success:!0,error:null})}createContentBlocks(e,t,n){let s=e.trim();s.length===0&&(t?s=`Command '${n}' executed successfully.
|
|
1797
|
+
|
|
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=Uu.homedir(),l=s.join(c,".orion","tool_outputs");await n.mkdir(l,{recursive:!0});let d=s.join(l,a);return await n.writeFile(d,e,"utf-8"),u.debug(`[FRONTEND WS] Created temp file: ${d}`),d}catch(n){return u.error(`[FRONTEND WS] Failed to create temp file: ${n}`),null}}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeatPing()},this.baseHeartbeatInterval),u.debug(`[FRONTEND WS] Started heartbeat (${this.baseHeartbeatInterval/1e3}s interval)`)}sendHeartbeatPing(){this.socket?.connected&&(this.socket.emit("ping",{timestamp:new Date().toISOString()}),this.lastHeartbeat=new Date)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}startAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&clearInterval(this.aggressiveHeartbeatTimer);let e=this.superAggressiveMode?2e3:this.baseAggressiveHeartbeatInterval;this.aggressiveHeartbeatTimer=setInterval(()=>{this.sendAggressiveHeartbeat()},e);let t=this.superAggressiveMode?"SUPER-AGGRESSIVE":"aggressive";u.debug(`[FRONTEND WS] Started ${t} heartbeat (${e/1e3}s interval)`),this.startToolProgressReporting()}stopAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),this.superAggressiveMode=!1,u.debug("[FRONTEND WS] Stopped aggressive heartbeat"),this.stopToolProgressReporting()}enterSuperAggressiveMode(){this.superAggressiveMode||this.activeToolExecutions.size>0&&(u.debug("[FRONTEND WS] Entering SUPER-AGGRESSIVE heartbeat mode due to connection quality degradation"),this.superAggressiveMode=!0,this.startAggressiveHeartbeat())}sendAggressiveHeartbeat(){if(this.lastHeartbeatSent=new Date,this.socket?.connected){this.socket.emit("heartbeat",{timestamp:new Date().toISOString(),hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size,superAggressive:this.superAggressiveMode});let e=this.superAggressiveMode?"SUPER-":"";u.debug(`[FRONTEND WS] Sent ${e}aggressive heartbeat (${this.activeToolExecutions.size} active tools)`)}this.updateConnectionQuality()}updateConnectionQuality(){let e=(Date.now()-this.lastPongReceived.getTime())/1e3,t=this.connectionQuality;e<10?(this.connectionQuality="excellent",this.consecutivePoorQualityChecks=0):e<30?(this.connectionQuality="good",this.consecutivePoorQualityChecks=0):e<60?(this.connectionQuality="fair",this.consecutivePoorQualityChecks=0):e<90?(this.connectionQuality="poor",this.consecutivePoorQualityChecks++):(this.connectionQuality="critical",this.consecutivePoorQualityChecks++),t!==this.connectionQuality&&u.debug(`[FRONTEND WS] Connection quality: ${t} -> ${this.connectionQuality}`),this.consecutivePoorQualityChecks>=this.POOR_QUALITY_THRESHOLD&&(this.connectionQuality==="poor"||this.connectionQuality==="critical")&&this.handleConnectionQualityDegradation()}handleConnectionQualityDegradation(){if(u.debug(`[FRONTEND WS] Proactive recovery - quality: ${this.connectionQuality}, checks: ${this.consecutivePoorQualityChecks}`),this.connectionMetrics.proactiveRecoveries++,this.activeToolExecutions.size>0&&this.enterSuperAggressiveMode(),this.socket?.connected)for(let e=0;e<3;e++)setTimeout(()=>{this.socket?.connected&&this.socket.emit("heartbeat",{timestamp:new Date().toISOString(),hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size,reason:"quality_recovery"})},e*500);setTimeout(()=>{if(this.connectionQuality==="critical"&&this.isConversationActive){if(this.activeToolExecutions.size>0){u.debug("[FRONTEND WS] Deferring reconnect - active tools in progress"),this.connectionMetrics.failedRecoveries++;return}u.debug("[FRONTEND WS] Recovery failed - attempting soft reconnect"),this.attemptSoftReconnect()}else this.connectionMetrics.successfulRecoveries++},5e3)}async attemptSoftReconnect(){if(!this.sessionId||!this.userId){u.debug("[FRONTEND WS] Cannot soft reconnect - missing session info");return}let e=this.sessionId,t=this.userId;this.disconnect("soft_reconnect",!1),await new Promise(n=>setTimeout(n,1e3));try{await this.connectForConversation(t,e)?(u.debug("[FRONTEND WS] Soft reconnect successful"),this.connectionMetrics.successfulRecoveries++):(u.debug("[FRONTEND WS] Soft reconnect failed"),this.connectionMetrics.failedRecoveries++)}catch(n){u.error(`[FRONTEND WS] Soft reconnect error: ${n}`),this.connectionMetrics.failedRecoveries++}}startToolProgressReporting(){this.toolProgressTimer&&clearInterval(this.toolProgressTimer),this.toolProgressTimer=setInterval(()=>{this.sendToolProgress()},this.baseToolProgressInterval),u.debug(`[FRONTEND WS] Started tool progress reporting (${this.baseToolProgressInterval/1e3}s interval)`)}stopToolProgressReporting(){this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),u.debug("[FRONTEND WS] Stopped tool progress reporting")}sendToolProgress(){if(this.activeToolExecutions.size!==0&&this.socket?.connected){for(let e of this.activeToolExecutions)this.socket.emit("tool_progress",{toolId:e,status:"running",timestamp:new Date().toISOString()});u.debug(`[FRONTEND WS] Sent progress update for ${this.activeToolExecutions.size} active tools`)}}getKeepaliveTimeout(){return this.activeToolExecutions.size>0?this.extendedKeepaliveTimeout:this.baseKeepaliveTimeout}startKeepaliveWatchdog(){this.lastKeepaliveTime=new Date,this.stopKeepaliveWatchdog(),this.keepaliveWatchdog=setInterval(()=>{if(!this.lastKeepaliveTime)return;let e=this.getKeepaliveTimeout(),t=Date.now()-this.lastKeepaliveTime.getTime();u.debug(`[FRONTEND WS] Keepalive check - ${Math.round(t/1e3)}s since last, timeout: ${e/1e3}s, active tools: ${this.activeToolExecutions.size}`),t>e&&(u.error(`[FRONTEND WS] KEEPALIVE TIMEOUT - No activity for ${Math.round(t/1e3)}s`),this.handleKeepaliveTimeout())},1e4),u.debug("[FRONTEND WS] Started keepalive watchdog (check every 10s)")}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}handleKeepaliveTimeout(){u.debug("[FRONTEND WS] Handling keepalive timeout"),this.emit("keepalive_timeout",{lastKeepaliveTime:this.lastKeepaliveTime,activeTools:this.activeToolExecutions.size}),this.activeToolExecutions.size>0&&(u.debug("[FRONTEND WS] Tools still active, not disconnecting"),this.sendAggressiveHeartbeat())}updateKeepalive(){this.lastKeepaliveTime=new Date}startConnectionHealthCheck(){this.connectionHealthCheckTimer&&clearInterval(this.connectionHealthCheckTimer),this.connectionHealthCheckTimer=setInterval(()=>{this.updateConnectionQuality(),(this.connectionQuality==="fair"||this.connectionQuality==="poor")&&this.socket?.connected&&this.socket.emit("ping",{timestamp:Date.now()})},this.CONNECTION_HEALTH_CHECK_INTERVAL),u.debug(`[FRONTEND WS] Started connection health check (${this.CONNECTION_HEALTH_CHECK_INTERVAL/1e3}s interval)`)}stopConnectionHealthCheck(){this.connectionHealthCheckTimer&&(clearInterval(this.connectionHealthCheckTimer),this.connectionHealthCheckTimer=null)}startTokenRefreshTimer(){this.stopTokenRefreshTimer(),this.tokenRefreshTimer=setInterval(async()=>{await this.refreshAuthToken()},this.TOKEN_REFRESH_INTERVAL),u.debug(`[FRONTEND WS] Started token refresh timer (${this.TOKEN_REFRESH_INTERVAL/6e4} min interval)`)}stopTokenRefreshTimer(){this.tokenRefreshTimer&&(clearInterval(this.tokenRefreshTimer),this.tokenRefreshTimer=null)}async refreshAuthToken(){if(!this.isConnected()){u.debug("[FRONTEND WS] Not connected, skipping token refresh");return}try{u.debug("[FRONTEND WS] Refreshing Firebase token...");let e=await this.authService.getFirebaseIdToken();e&&this.socket?(this.socket.io.opts.query={...this.socket.io.opts.query,token:e},u.debug("[FRONTEND WS] Firebase token refreshed successfully"),this.socket?.connected&&(this.socket.emit("token_refreshed",{timestamp:Date.now()}),u.debug("[FRONTEND WS] Notified server of token refresh"))):u.warn("[FRONTEND WS] No Firebase token available for refresh")}catch(e){u.error(`[FRONTEND WS] Token refresh failed: ${e}`)}}getConnectionMetrics(){let e=this.connectionMetrics.pingResponseTimes.length>0?this.connectionMetrics.pingResponseTimes.reduce((t,n)=>t+n,0)/this.connectionMetrics.pingResponseTimes.length:0;return{...this.connectionMetrics,avgPingRTT:Math.round(e),currentQuality:this.connectionQuality}}resetConnectionMetrics(){this.connectionMetrics={totalConnections:0,totalDisconnections:0,disconnectionReasons:{},qualityDegradations:0,proactiveRecoveries:0,successfulRecoveries:0,failedRecoveries:0,pingResponseTimes:[],lastMetricsReset:new Date},u.debug("[FRONTEND WS] Connection metrics reset")}terminateAllRunningProcesses(){u.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),u.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(n){u.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${n.message}`)}this.runningProcesses.clear()}async sendStopSignal(e,t="all"){if(!this.isConnected()){u.warn("[FRONTEND WS] Not connected, cannot send stop signal");return}this.socket?.emit("stop_request",{user_id:e,stop_type:t,timestamp:new Date().toISOString()}),u.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async registerSession(e,t){if(!this.isConnected()){u.debug("[FRONTEND WS] Not connected, cannot register session");return}u.debug(`[FRONTEND WS] Registering session: ${e}`),this.socket?.emit("register",{traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()}),u.debug(`[FRONTEND WS] Session registered: ${e}`)}async sendToolRequest(e){if(!this.isConnected())throw u.debug("[FRONTEND WS] Not connected, cannot send tool request"),new Error("WebSocket not connected");let t={type:"tool_execution_request",data:{id:e.id,tool_name:e.tool_name,arguments:e.arguments,timeout:e.timeout},metadata:{tool_call_id:e.tool_call_id,timestamp:new Date().toISOString()}};u.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),this.socket?.emit("tool_execution_request",t)}async requestDeleteConfirmation(e,t){if(!this.isConnected())return u.debug("[FRONTEND WS] Not connected, cannot request delete confirmation"),"error";let n=`delete-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return u.debug(`[FRONTEND WS] Requesting delete confirmation: ${n}`),u.debug(`[FRONTEND WS] Command: ${e.substring(0,100)}${e.length>100?"...":""}`),new Promise(s=>{let r=setTimeout(()=>{this.pendingDeleteConfirmations.get(n)&&(u.debug(`[FRONTEND WS] Delete confirmation timed out: ${n}`),this.pendingDeleteConfirmations.delete(n),s("timeout"))},this.DELETE_CONFIRMATION_TIMEOUT);this.pendingDeleteConfirmations.set(n,{resolve:s,timeoutId:r}),this.socket?.emit("delete_confirmation_request",{confirmationId:n,command:e,description:t,timeout:this.DELETE_CONFIRMATION_TIMEOUT,timestamp:new Date().toISOString()}),u.debug(`[FRONTEND WS] Delete confirmation request sent: ${n}`)})}handleDeleteConfirmationResponse(e){let{confirmationId:t,response:n}=e;u.debug(`[FRONTEND WS] Delete confirmation response received: ${t} = ${n}`);let s=this.pendingDeleteConfirmations.get(t);if(!s){u.debug(`[FRONTEND WS] No pending confirmation for: ${t}`);return}clearTimeout(s.timeoutId),this.pendingDeleteConfirmations.delete(t);let r=n;s.resolve(["confirmed","declined","timeout","error"].includes(n)?r:"error")}async captureFrontendToolResultForHistory(e,t,n,s){let r=t.map(o=>o.text||"").join(`
|
|
1799
|
+
`);try{let{PersonalAgentService:o}=await Promise.resolve().then(()=>(Tt(),xn)),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 nn,Wu=L(()=>{"use strict";nn=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
|
+
|
|
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 yb}from"events";import{promises as Mo}from"fs";import{join as Hu}from"path";import{homedir as vb}from"os";var ka,er,Pa=L(()=>{"use strict";ka=class i extends yb{static instance;settings;configDir;configPath;constructor(){super(),this.configDir=Hu(vb(),".orion-cli"),this.configPath=Hu(this.configDir,"settings.json"),this.settings={isPrivacyModeEnabled:!0,defaultModel:"snowx-c5",temperature:.7,maxTokens:4096,enableMarkdownFormatting:!0,showThinkingBlocks:!0,compactMode:!1,enableColors:!0,enableToolCalling:!0,enableCrossDevice:!0,enableWebSocket:!0,enableFirebase:!0,customUserPreferences:{instructions:"",lastModified:new Date,isEnabled:!0},logLevel:"info",autoSaveHistory:!0,maxHistoryEntries:1e3},this.loadSettings()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async loadSettings(){try{await Mo.mkdir(this.configDir,{recursive:!0});try{let e=await Mo.readFile(this.configPath,"utf-8"),t=JSON.parse(e);this.settings={...this.settings,...t},this.settings.customUserPreferences.lastModified&&(this.settings.customUserPreferences.lastModified=new Date(this.settings.customUserPreferences.lastModified))}catch{await this.saveSettings()}}catch(e){console.warn("⚠️ Failed to load settings:",e)}this.emit("settingsLoaded",this.settings)}async saveSettings(){try{await Mo.mkdir(this.configDir,{recursive:!0}),await Mo.writeFile(this.configPath,JSON.stringify(this.settings,null,2)),this.emit("settingsSaved",this.settings)}catch(e){throw console.error("❌ Failed to save settings:",e),e}}async setWorkingDirectory(e){this.settings.currentWorkingDirectory=e,await this.saveSettings(),this.emit("workingDirectoryChanged",e)}getWorkingDirectory(){return this.settings.currentWorkingDirectory}async setPrivacyMode(e){this.settings.isPrivacyModeEnabled=e,await this.saveSettings(),this.emit("privacyModeChanged",e)}isPrivacyModeEnabled(){return this.settings.isPrivacyModeEnabled}async setDefaultModel(e){this.settings.defaultModel=e,await this.saveSettings(),this.emit("defaultModelChanged",e)}getDefaultModel(){return this.settings.defaultModel}async setTemperature(e){this.settings.temperature=Math.max(0,Math.min(2,e)),await this.saveSettings(),this.emit("temperatureChanged",this.settings.temperature)}getTemperature(){return this.settings.temperature}async setMarkdownFormatting(e){this.settings.enableMarkdownFormatting=e,await this.saveSettings(),this.emit("markdownFormattingChanged",e)}async setShowThinkingBlocks(e){this.settings.showThinkingBlocks=e,await this.saveSettings(),this.emit("thinkingBlocksChanged",e)}async setCompactMode(e){this.settings.compactMode=e,await this.saveSettings(),this.emit("compactModeChanged",e)}async setEnableColors(e){this.settings.enableColors=e,await this.saveSettings(),this.emit("colorsChanged",e)}async setEnableToolCalling(e){this.settings.enableToolCalling=e,await this.saveSettings(),this.emit("toolCallingChanged",e)}async setEnableCrossDevice(e){this.settings.enableCrossDevice=e,await this.saveSettings(),this.emit("crossDeviceChanged",e)}async setEnableWebSocket(e){this.settings.enableWebSocket=e,await this.saveSettings(),this.emit("webSocketChanged",e)}async setEnableFirebase(e){this.settings.enableFirebase=e,await this.saveSettings(),this.emit("firebaseChanged",e)}async updateCustomUserPreferences(e){this.settings.customUserPreferences={...this.settings.customUserPreferences,...e,lastModified:new Date},await this.saveSettings(),this.emit("customPreferencesChanged",this.settings.customUserPreferences)}getFormattedCustomPreferences(){let e=this.settings.customUserPreferences;return!e.isEnabled||!e.instructions.trim()?"":`
|
|
1802
|
+
--- User Instructions ---
|
|
1803
|
+
${e.instructions}
|
|
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")}}},er=ka});import Ye from"fs";import sn from"path";import Sb from"os";var wb,Aa,rn,Gu=L(()=>{"use strict";q();wb=/[/\\:*?"<>|]/g,Aa=class i{static instance;charactersPath;constructor(){this.charactersPath=sn.join(Sb.homedir(),".orion","characters")}static getInstance(){return i.instance||(i.instance=new i),i.instance}getPath(){return this.charactersPath}ensureFolder(){try{return Ye.existsSync(this.charactersPath)||(Ye.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"}:wb.test(t)?{valid:!1,error:"Character name contains invalid characters"}:sn.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=Ye.readdirSync(this.charactersPath),t=[];for(let n of e){if(!n.endsWith(".md"))continue;let s=sn.join(this.charactersPath,n);try{if(!Ye.statSync(s).isFile())continue;let o=Ye.readFileSync(s,"utf-8"),a=n.replace(/\.md$/,"");t.push({id:a,name:a,content:o})}catch(r){u.warn(`[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=sn.join(this.charactersPath,`${s}.md`);try{return this.ensureFolder(),Ye.existsSync(r)?{success:!1,error:"A character with this name already exists"}:(Ye.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=sn.join(this.charactersPath,`${e}.md`);try{return Ye.existsSync(s)?(Ye.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=sn.join(this.charactersPath,`${e}.md`);try{return Ye.existsSync(n)?(Ye.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=sn.join(this.charactersPath,`${e}.md`);try{return Ye.existsSync(n)?{success:!0,content:Ye.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=sn.join(this.charactersPath,`${e}.md`);return Ye.existsSync(n)}},rn=Aa.getInstance()});import{EventEmitter as Tb}from"events";var Da,Ma,Ro,ju=L(()=>{"use strict";Gu();He();q();Da="orion-characters-active",Ma=class i extends Tb{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 ye.string(Da)||null}saveActiveId(e){e?ye.set(Da,e):ye.remove(Da)}getState(){return{...this.state}}async loadCharacters(){this.state.isLoading=!0,this.emit("change",this.state);try{u.debug("[Characters] Loading characters from file system..."),rn.ensureFolder();let e=rn.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=rn.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){rn.deleteFile(e);let d=rn.createFile(s,r);if(!d.success)return this.state.isSaving=!1,this.emit("change",this.state),{success:!1,error:d.error}}else{let d=rn.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=rn.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>
|
|
1802
1806
|
${e.map(n=>` <character>
|
|
1803
1807
|
<id>${n.id}</id>
|
|
1804
1808
|
<name>${n.name}</name>
|
|
1805
1809
|
<personality>${n.content}</personality>
|
|
1806
1810
|
</character>`).join(`
|
|
1807
1811
|
`)}
|
|
1808
|
-
</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)")}},
|
|
1812
|
+
</available_characters>`}getCharacterById(e){return this.state.characters.find(t=>t.id===e)||null}reset(){this.state={characters:[],activeCharacterId:null,isLoading:!1,isSaving:!1,isDeleting:null,lastSynced:null},this.saveActiveId(null),this.emit("change",this.state),u.debug("[Characters] Reset store state (files preserved)")}},Ro=Ma.getInstance()});var xn={};Fe(xn,{PersonalAgentService:()=>je});import{EventEmitter as xb}from"events";import Ra from"axios";import Cb from"http";import Eb from"https";import{v4 as on}from"uuid";import an from"fs";import tr from"path";import Oo from"os";var nr,je,Tt=L(()=>{"use strict";Kt();Te();Jn();zn();Pt();q();Wu();Pa();Sa();ju();Ea();Po();Xr();nr=class{static PARSING_ERROR_REGEX=/json|parsing|decode|format|invalid response|malformed|serialization|unexpected token/i;static NETWORK_ERROR_REGEX=/network|connection|timeout/i;static AUTH_ERROR_REGEX=/unauthorized|authentication|forbidden/i;static NETWORK_ERROR_CODES=new Set(["ECONNREFUSED","ENOTFOUND","ETIMEDOUT","ECONNRESET","ERR_NETWORK","EPIPE","EHOSTUNREACH"]);static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",n=e?.code,s=e?.status||e?.statusCode||e?.response?.status,r=String(n||""),o=Number(s);return this.PARSING_ERROR_REGEX.test(t)?"parsing":this.NETWORK_ERROR_CODES.has(r)||this.NETWORK_ERROR_REGEX.test(t)||this.AUTH_ERROR_REGEX.test(t)||o===401||o===403||r==="401"||r==="403"?"critical":"parsing"}},je=class i extends xb{static instance;authService;apiEndpoint="https://snowx.ai/api-beta/api/chat/tool-calling";httpAgent;httpsAgent;currentTodoList=null;activeWebViewURLs=[];operatorTaskState=null;currentOutput="";completeOutputWithToolResults="";currentPromptId=null;currentAbortController=null;currentModel=null;currentSessionId=null;isStreamingActive=!1;static MAX_TOOL_CACHE_SIZE=100;static MAX_PROCESSED_IDS_SIZE=500;accumulatedToolCalls=new Map;processedToolCallIds=new Set;activeToolNames=new Set;toolArgumentsCache=new Map;baseKeepaliveTimeout=12e4;extendedKeepaliveTimeout=6e5;lastKeepaliveTime=null;keepaliveWatchdog=null;lastRequestHash=null;lastRequestTime=0;inflightRequests=new Set;storesInitialized=!1;constructor(){super(),this.authService=X.getInstance(),this.httpAgent=new Cb.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Eb.Agent({keepAlive:!0,timeout:36e5}),u.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout");let e=fe.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 and characters stores..."),await Promise.all([An.loadSkills(),Ro.loadCharacters()]),this.storesInitialized=!0,u.debug("[PERSONAL AGENT] Skills 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(an.existsSync("/etc/os-release")){let n=an.readFileSync("/etc/os-release","utf8").match(/^ID=["']?([^"'\n]+)["']?/m);if(n)return n[1].toLowerCase()}}catch{}return"linux"}return(e||"unknown").toLowerCase()}getAppStorageInfo(){let e=Oo.homedir(),n=er.getInstance().getWorkingDirectory()||process.cwd();return{userData:tr.join(e,".orion-cli"),downloads:n,temp:Oo.tmpdir()}}async getDeviceKnowledgeInstruction(){try{let e=Se.getKnowledgeFilePath();this.migrateDeviceKnowledgeIfNeeded(e);let t=Se.readDeviceKnowledge();return t||(u.debug("[DeviceKnowledge] File not found, creating initial knowledge file..."),await Se.initializeDeviceKnowledge(),u.debug(`[DeviceKnowledge] Initial knowledge file created at: ${e}`),t=Se.readDeviceKnowledge()||""),u.debug(`[DeviceKnowledge] Loaded device knowledge, length: ${t.length} characters`),`Current device knowledge (${e}): ${t}
|
|
1809
1813
|
|
|
1810
|
-
Remember to update memory about device if any new information is learned during conversation.`}catch{return`Current device knowledge (${
|
|
1814
|
+
Remember to update memory about device if any new information is learned during conversation.`}catch{return`Current device knowledge (${Se.getKnowledgeFilePath()}): No specific device knowledge available.
|
|
1811
1815
|
|
|
1812
1816
|
Remember to update memory about device if any new information is learned during conversation.`}}getProjectPathContext(){return`<context>
|
|
1813
|
-
Current project path in this session: ${
|
|
1814
|
-
</context>`}getDeviceKnowledgePath(){let e=tr.join(
|
|
1817
|
+
Current project path in this session: ${er.getInstance().getWorkingDirectory()||process.cwd()}
|
|
1818
|
+
</context>`}getDeviceKnowledgePath(){let e=tr.join(Oo.homedir(),".orion");return tr.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(an.existsSync(e))return;let t=tr.join(Oo.homedir(),"Documents","orion","orion-device-knowledge.md");if(an.existsSync(t)){u.info("📦 Migrating device knowledge to cross-platform location...");let n=tr.dirname(e);an.existsSync(n)||an.mkdirSync(n,{recursive:!0});let s=an.readFileSync(t,"utf8");an.writeFileSync(e,s,"utf8"),u.info(`✅ Device knowledge migrated to: ${e}`),u.info(` Old location: ${t} (can be safely deleted)`)}}catch(t){u.debug(`Migration skipped: ${t.message}`)}}static getInstance(){return i.instance||(i.instance=new i),i.instance}setToolArgsCache(e,t){let n=this.currentSessionId?`${this.currentSessionId}:${e}`:e;if(this.toolArgumentsCache.size>=i.MAX_TOOL_CACHE_SIZE){let s=this.toolArgumentsCache.keys().next().value;s&&this.toolArgumentsCache.delete(s)}this.toolArgumentsCache.set(n,t)}getToolArgsCache(e){let t=this.currentSessionId?`${this.currentSessionId}:${e}`:e;return this.toolArgumentsCache.get(t)}generateRequestHash(e,t){let n=`${e}:${t}:${Date.now()}`,s=0;for(let r=0;r<n.length;r++){let o=n.charCodeAt(r);s=(s<<5)-s+o,s=s&s}return s.toString(16)}isDuplicateRequest(e){let t=Date.now();return!!(this.lastRequestHash===e&&t-this.lastRequestTime<2e3||this.inflightRequests.has(e))}async sendMessageWithToolCalling(e,t,n,s=.7,r=!0,o,a,c){await this.ensureStoresLoaded();let l=this.generateRequestHash(e,t.length);if(this.isDuplicateRequest(l))return u.debug("[PERSONAL AGENT] Duplicate request detected, ignoring"),"";this.inflightRequests.add(l),this.lastRequestHash=l,this.lastRequestTime=Date.now(),this.currentPromptId=on(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=n;let d=c?.crossDeviceTaskId;d&&u.debug(`[PERSONAL AGENT] Executing cross-device task: ${d}`),c?.mode==="new"&&(t=[],u.debug("[PERSONAL AGENT] Starting new conversation (cross-device mode: new)")),this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear();let g=o||this.authService.getUserId(),m=Pe.getInstance().getCurrentDeviceId();if(!m)throw u.error("No device ID available - device registration may have failed"),new Error("Device not registered - cannot submit prompt");try{if(g){let v=`tc-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;this.currentSessionId=v,u.debug("🔌 [PRE-CONNECT] ==================== WEBSOCKET PRE-CONNECT ===================="),u.debug("🔌 [PRE-CONNECT] Connecting WebSocket BEFORE HTTP request"),u.debug(`🔌 [PRE-CONNECT] - User ID: ${g}`),u.debug(`🔌 [PRE-CONNECT] - Device ID: ${m}`),u.debug(`🔌 [PRE-CONNECT] - Session ID: ${v}`),u.debug(`🔌 [PRE-CONNECT] - Composite Key: ${m}_${v}`),await fe.getInstance().connectForConversation(g,v)?u.debug("✅ [PRE-CONNECT] WebSocket pre-connected successfully!"):u.warn("⚠️ [PRE-CONNECT] WebSocket pre-connect failed, will retry after HTTP response"),u.debug("🔌 [PRE-CONNECT] ==================== END PRE-CONNECT ====================")}else u.warn("⚠️ [PRE-CONNECT] No userId found, skipping WebSocket pre-connect")}catch(v){u.error(`❌ [PRE-CONNECT] WebSocket pre-connect error: ${v}`)}let h=`${this.getProjectPathContext()}
|
|
1815
1819
|
|
|
1816
|
-
My main prompt: ${e}`,f={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:h},...a.map(v=>({type:"image_url",image_url:{url:v}}))]:[{type:"text",text:h}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:m,model:n.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:await this.getDeviceKnowledgeInstruction(),shell_timeout_config:{activity_timeout:300,max_timeout:18e3,initial_timeout:60},timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,app_storage_info:this.getAppStorageInfo(),disabled_tools:
|
|
1820
|
+
My main prompt: ${e}`,f={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:h},...a.map(v=>({type:"image_url",image_url:{url:v}}))]:[{type:"text",text:h}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:m,model:n.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:await this.getDeviceKnowledgeInstruction(),shell_timeout_config:{activity_timeout:300,max_timeout:18e3,initial_timeout:60},timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,app_storage_info:this.getAppStorageInfo(),disabled_tools:Ca.getState().getDisabledTools(),isFocusedMode:!1,browseruse:!0,dictation:!1},y=An.getState(),T=An.formatSkillsIndexForPrompt(),x=An.getSkillsContentMap();if(T){f.skills_index=T,f.skills_content=x;let v=An.getSelectedSkillsContent();v&&(f.skills_instruction=v),u.debug(`[PERSONAL AGENT] 📚 Including ${y.skills.length} skills in request`)}let S=Ro.getActiveCharacter(),C=Ro.getActiveCharacterContent();if(S&&C&&(f.character_instruction=C,f.custom_instructions=C,u.debug(`[PERSONAL AGENT] 🎭 Including active character "${S.name}" in request`)),this.currentSessionId?(f.session_id=this.currentSessionId,u.debug(`[PERSONAL AGENT] 🔗 Including existing session_id in request: ${this.currentSessionId}`)):u.debug("[PERSONAL AGENT] 🆕 No existing session_id - backend will generate new one"),c?.conversationId)f.conversationId=c.conversationId,u.debug(`[PERSONAL AGENT] Sending request with conversationId: ${c.conversationId}`),u.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let v=t.map(I=>{let w,E=I;E.metadata?.toolResults?w=E.metadata.toolResults:E.originalContent?w=E.originalContent:w=typeof I.content=="string"?I.content:JSON.stringify(I.content);let P=[{type:"text",text:w}];return E.imageUrls&&E.imageUrls.length>0&&P.push(...E.imageUrls.map(D=>({type:"image_url",image_url:{url:D}}))),{role:I.role,content:P}});for(let I=0;I<v.length;I++)v[I].role;f.messages=v,u.debug(`[PERSONAL AGENT] Sending request with ${v.length} messages (new conversation)`)}else u.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return r?this.performStreamingToolCall(f,l):this.performNonStreamingToolCall(f,l)}async performStreamingToolCall(e,t){let n=await this.getFirebaseIdToken();return n||u.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401"),new Promise((s,r)=>{this.currentAbortController=new AbortController,this.isStreamingActive=!0;let o=[],a=Buffer.alloc(0),c="",l="",d=[],g=null,m=!1,p="";this.currentOutput="",this.completeOutputWithToolResults="";let h=new Map,f=new Set,y=new Map,T=this.authService.getUserId();Ra.post(this.apiEndpoint,e,{responseType:"stream",signal:this.currentAbortController.signal,timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n||this.getAuthToken()}`}}).then(async x=>{let S=x.data;this.startKeepaliveWatchdog();let C=x.headers["x-session-id"]||x.headers["session-id"]||x.headers["X-Session-Id"];u.debug("🔍 [SESSION-ID] ==================== SESSION ID VERIFICATION ===================="),u.debug(`🔍 [SESSION-ID] Pre-connected sessionId: ${this.currentSessionId}`),u.debug(`🔍 [SESSION-ID] Backend X-Session-Id header: ${C}`),C?(g=C,this.currentSessionId&&C!==this.currentSessionId?(u.warn("⚠️ [SESSION-ID] Backend returned different sessionId!"),u.warn(`⚠️ [SESSION-ID] - We sent: ${this.currentSessionId}`),u.warn(`⚠️ [SESSION-ID] - Backend returned: ${C}`),u.warn("⚠️ [SESSION-ID] Using backend sessionId and reconnecting WebSocket..."),this.currentSessionId=C,await fe.getInstance().connectForConversation(T||"",C)?u.debug("✅ [WEBSOCKET] Reconnected with backend sessionId"):u.error("❌ [WEBSOCKET] Failed to reconnect with backend sessionId")):this.currentSessionId?u.debug("✅ [SESSION-ID] Backend confirmed our sessionId - WebSocket already connected!"):(u.debug("🔌 [WEBSOCKET] No pre-connect, connecting now with backend sessionId"),this.currentSessionId=C,await fe.getInstance().connectForConversation(T||"",C)?u.debug("✅ [WEBSOCKET] Connected with backend sessionId"):u.error("❌ [WEBSOCKET] Failed to connect with backend sessionId"))):(u.error("❌ [SESSION-ID] ==================== ERROR ===================="),u.error("❌ [SESSION-ID] ✗ No X-Session-Id header found in response!"),this.currentSessionId?u.debug(`ℹ️ [SESSION-ID] Using pre-connected sessionId: ${this.currentSessionId}`):u.error("❌ [SESSION-ID] No sessionId available - tools may fail!")),u.debug("🔍 [SESSION-ID] ==================== END SESSION ID CHECK ===================="),S.on("data",v=>{this.updateKeepaliveTimer("stream chunk");try{a=Buffer.concat([a,v]);let P=a.length,D=Math.max(0,a.length-3);for(let $=a.length-1;$>=D;$--){let R=a[$];if((R&192)===128)continue;let _=R,N=1;(_&128)===0?N=1:(_&224)===192?N=2:(_&240)===224?N=3:(_&248)===240&&(N=4),a.length-$<N&&(P=$);break}if(P>0){let $=a.slice(0,P);a=a.slice(P),o.push($.toString("utf8"))}}catch{o.push(v.toString())}let I=o.join("");o.length=0;let w=I.split(/\r?\n/),E=w.pop()||"";E&&o.push(E);for(let P of w){let D=P.trim();if(D){if(D.startsWith(":")){D.includes("keepalive")&&this.updateKeepaliveTimer("SSE comment keepalive");continue}if(D.startsWith("event: keepalive")){this.updateKeepaliveTimer("explicit keepalive event"),this.emit("keepalive");continue}if(D.startsWith("data: ")){let $=D.slice(6).trim();if($==="[DONE]"){this.stopKeepaliveWatchdog(),this.handleConversationComplete(),this.emit("BotResponseCompleted",c),s(c);return}try{let R=JSON.parse($);if(R.type==="session_start"&&R.conversationId){let _=R.conversationId,N=R.isNewConversation||!1,k=R.title;u.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),u.debug(`[PERSONAL AGENT] conversationId: ${_}`),u.debug(`[PERSONAL AGENT] isNewConversation: ${N}`),k&&u.debug(`[PERSONAL AGENT] title: "${k}"`),R.sessionId&&!this.currentSessionId&&this.isStreamingActive&&(u.debug("🔍 [SESSION-ID] ==================== SESSION ID FROM SSE ===================="),u.debug(`🔍 [SESSION-ID] Found sessionId in session_start event: ${R.sessionId}`),u.debug("🔍 [SESSION-ID] This is a fallback for clients when header is not accessible"),this.currentSessionId=R.sessionId,fe.getInstance().connectForConversation(T||"",R.sessionId).then(F=>{F?u.debug("✅ [WEBSOCKET] Connected via SSE fallback sessionId"):u.error("❌ [WEBSOCKET] Failed to connect via SSE fallback sessionId")}).catch(F=>{u.error(`❌ [WEBSOCKET] Connection error via SSE fallback: ${F}`)}),u.debug("🔍 [SESSION-ID] ==================== END SSE FALLBACK ====================")),this.emit("conversation_id_received",{conversationId:_,isNew:N,title:k||void 0});continue}if(R.type==="title_generated"&&R.title&&R.conversationId){let _=R.title,N=R.conversationId;u.debug("[PERSONAL AGENT] Received title_generated event!"),u.debug(`[PERSONAL AGENT] conversationId: ${N}`),u.debug(`[PERSONAL AGENT] title: "${_}"`),this.emit("conversation_title_updated",{conversationId:N,title:_});continue}if(R.type==="error"||R.error){let _=R.error||R,N=_.message||"Unknown error occurred",k=_.status||500,M=_.provider||"unknown";u.debug(`[PERSONAL AGENT] API Error - Status: ${k}, Provider: ${M}`),u.debug(`[PERSONAL AGENT] Error Message: ${N}`);let F=N;try{let H=JSON.parse(N);H.error?.message&&(F=H.error.message)}catch{}let B;k===503?B=`Service Temporarily Unavailable: The AI model is currently experiencing high demand. Please try again in a few moments.
|
|
1817
1821
|
|
|
1818
1822
|
Details: ${F}`:k>=500?B=`Server Error (${k}): The AI service encountered an internal error. Please try again.
|
|
1819
1823
|
|
|
@@ -1824,7 +1828,7 @@ ${F}
|
|
|
1824
1828
|
</context>`;d.push(B),c+=B+`
|
|
1825
1829
|
`,this.completeOutputWithToolResults+=B+`
|
|
1826
1830
|
`,this.currentOutput+=B+`
|
|
1827
|
-
`;continue}if(R.tool_calls){this.updateKeepaliveTimer("tool_calls event"),u.debug("Processing tool calls:",R.tool_calls.length,"items");for(let[_,N]of R.tool_calls.entries()){u.debug("Tool call ["+_+"]:");let k=N.id,M=N.index??_;if(k&&M!==void 0?(y.set(M,k),u.debug(`Mapped index ${M} -> id ${k}`)):!k&&M!==void 0&&(k=y.get(M),k&&u.debug(`Resolved index ${M} -> id ${k}`)),k){u.debug("Processing tool call ID:",k);let F=h.get(k)||{};for(let[B,H]of Object.entries(N))if(B==="function"&&typeof H=="object"&&H!==null){let V=F.function||{},le=H;for(let[W,G]of Object.entries(le))if(W==="arguments"&&typeof G=="string"){let
|
|
1831
|
+
`;continue}if(R.tool_calls){this.updateKeepaliveTimer("tool_calls event"),u.debug("Processing tool calls:",R.tool_calls.length,"items");for(let[_,N]of R.tool_calls.entries()){u.debug("Tool call ["+_+"]:");let k=N.id,M=N.index??_;if(k&&M!==void 0?(y.set(M,k),u.debug(`Mapped index ${M} -> id ${k}`)):!k&&M!==void 0&&(k=y.get(M),k&&u.debug(`Resolved index ${M} -> id ${k}`)),k){u.debug("Processing tool call ID:",k);let F=h.get(k)||{};for(let[B,H]of Object.entries(N))if(B==="function"&&typeof H=="object"&&H!==null){let V=F.function||{},le=H;for(let[W,G]of Object.entries(le))if(W==="arguments"&&typeof G=="string"){let et=V.arguments||"";V.arguments=et+G}else V[W]=G;F.function=V}else F[B]=H;if(h.set(k,F),F.function?.name&&!f.has(k)){let B=F.function.name;f.add(k),this.activeToolNames.add(B),u.debug("[TOOL-DISPLAY] Tool started:",B,"ID:",k);let H;if(F.function?.arguments)try{H=JSON.parse(F.function.arguments),this.setToolArgsCache(k,H)}catch{}this.emit("toolExecuting",{toolCallId:k,name:B,arguments:H,startTime:new Date})}if(F.function?.name&&F.function?.arguments){let B=F.function.arguments,H=`args-${k}`;if((B.endsWith("}")||B.endsWith('"}'))&&!f.has(H))try{let V=JSON.parse(B);f.add(H),this.setToolArgsCache(k,V),u.debug("[TOOL-DISPLAY] Args complete for:",F.function.name,"ID:",k),this.emit("tool_args_update",{toolCallId:k,arguments:V})}catch{}}if(F.function?.arguments&&F.function?.name){let B=F.function.arguments;B.endsWith("}")||B.endsWith('"}')?(u.debug("Complete tool call accumulated:",k,"-",F.function.name),u.debug("Arguments:",B.substring(0,100)+(B.length>100?"...":"")),f.has(k)||(f.add(k),this.handleCompleteToolCall(F))):u.debug("Partial tool call:",k,"-",F.function.name)}}}}else if(R.tool_response&&R.tool_response.content){this.updateKeepaliveTimer("tool_response event");let _=R.tool_response.content,N=R.tool_response.id||"unknown",k=R.tool_response.name||"unknown",M=R.tool_response.role||"unknown";u.debug("[PERSONAL AGENT] TOOL RESPONSE RECEIVED:"),u.debug(" Tool ID:",N),u.debug(" Tool Name:",k),u.debug(" Tool Role:",M),u.debug(" Content Length:",_.length),u.debug(" Content Preview:",_.substring(0,200)+"..."),this.activeToolNames.delete(k);let F=this.getToolArgsCache(N);this.emit("tool_completed",{toolName:k,toolId:N,result:_,todos:R.tool_response.todos||null,arguments:F}),this.emit("toolComplete",k),R.tool_response.todos&&Array.isArray(R.tool_response.todos)&&(u.debug("[PERSONAL AGENT] Tool response contains",R.tool_response.todos.length,"todo items"),this.handleTodoUpdate({items:R.tool_response.todos}));let B=`<context>
|
|
1828
1832
|
${_}
|
|
1829
1833
|
</context>`;d.push(B),c+=B+`
|
|
1830
1834
|
`,this.completeOutputWithToolResults+=B+`
|
|
@@ -1834,7 +1838,7 @@ ${V}
|
|
|
1834
1838
|
</context>`;if(d.push(le),c+=le+`
|
|
1835
1839
|
`,this.completeOutputWithToolResults+=le+`
|
|
1836
1840
|
`,this.currentOutput+=le+`
|
|
1837
|
-
`,!k){let W=_.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(W){let G=_.replace(W[0],"").trim();if(G.length>0){c+=G,l+=G,this.currentOutput+=G,this.completeOutputWithToolResults+=G;let
|
|
1841
|
+
`,!k){let W=_.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(W){let G=_.replace(W[0],"").trim();if(G.length>0){c+=G,l+=G,this.currentOutput+=G,this.completeOutputWithToolResults+=G;let et=nn.remove(G);this.emit("data",et)}}}continue}}catch{}if(_.includes("<think>")){m=!0;let N=_.split("<think>")[0];if(N){c+=N,l+=N,this.currentOutput+=N,this.completeOutputWithToolResults+=N;let k=nn.remove(N);this.emit("data",k)}}else if(_.includes("</think>")){m=!1,p+=_.split("</think>")[0],this.emit("thinking",p),p="";let N=_.split("</think>")[1]||"";if(N){c+=N,l+=N,this.currentOutput+=N,this.completeOutputWithToolResults+=N;let k=nn.remove(N);this.emit("data",k)}}else if(m)p+=_,this.emit("thinking",p);else{c+=_,l+=_,this.currentOutput+=_,this.completeOutputWithToolResults+=_;let N=nn.remove(_);this.emit("data",N)}}else if(R.type==="checkpoint_reached"||R.event==="checkpoint_reached")u.debug("[CHECKPOINT] Backend reached checkpoint, processing queued messages as feedback"),this.handleCheckpointReached();else if(R.type==="todo_update")this.handleTodoUpdate(R.data);else if(R.type==="todo_list")this.handleTodoUpdate({items:R.todos});else if(R.type==="webview_update")this.handleWebViewUpdate(R.data);else if(R.type==="operator_progress")this.handleOperatorProgress(R.data);else if(R.type==="context_compaction_starting"||R.type==="manual_compaction_starting")u.debug("[COMPACTION] Starting:",R.message),this.emit("compaction_status",{status:"starting",conversationPercentage:R.conversationPercentage||R.percentage,message:R.message});else if(R.type==="context_compaction_complete"||R.type==="manual_compaction_complete")u.debug("[COMPACTION] Complete:",R.message),this.emit("compaction_status",{status:"complete",originalTokens:R.originalTokens,compactedTokens:R.compactedTokens,compressionRatio:R.compressionRatio,message:R.message});else if(R.type==="compaction_failed")u.debug("[COMPACTION] Failed:",R.message),this.emit("compaction_status",{status:"failed",error:R.error,message:R.message});else if(R.type==="stop"){this.handleStop(R.data),s(c);return}}catch{u.debug("Treating as plain text"),c+=$,l+=$,this.currentOutput+=$,this.completeOutputWithToolResults+=$;let _=nn.remove($);this.emit("data",_)}}}}}),S.on("end",()=>{this.stopKeepaliveWatchdog(),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),this.emit("done"),s(c)}),S.on("error",v=>{switch(this.stopKeepaliveWatchdog(),u.debug("Streaming error, disconnecting WebSocket and cleaning up"),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),nr.classify(v)){case"parsing":let w={type:"tool_result",tool_call_id:`error_${on()}`,error:!0,content:`Streaming parsing error occurred: ${v.message}. Please check response format and retry.`};u.debug("🔄 [PERSONAL AGENT] Parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(w)),fe.getInstance().handleConversationComplete(),s(c);return;case"critical":fe.getInstance().handleConversationComplete(),this.emit("error",v),r(v);break}})}).catch(x=>{if(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),x.code==="ERR_CANCELED")u.debug("Task was cancelled, disconnecting WebSocket"),fe.getInstance().handleConversationComplete(),this.emit("canceled"),s(c);else switch(nr.classify(x)){case"parsing":let C={type:"tool_result",tool_call_id:`error_${on()}`,error:!0,content:`Request parsing error: ${x.message}. Please check request format and retry.`};u.debug("🔄 [PERSONAL AGENT] Request parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(C)),fe.getInstance().handleConversationComplete(),s(c);break;case"critical":u.debug("Request failed, disconnecting WebSocket"),fe.getInstance().handleConversationComplete(),r(x);break}})})}async performNonStreamingToolCall(e,t){try{let n=await this.getFirebaseIdToken();n||u.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401");let s=await Ra.post(this.apiEndpoint,e,{timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n||this.getAuthToken()}`}});if(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),s.data?.content){if(this.currentOutput=s.data.content,this.completeOutputWithToolResults=s.data.completeOutput||s.data.content,s.data.toolResults)for(let r of s.data.toolResults)this.handleToolResult(r.tool,r.result);return s.data.content}throw new Error("No response content received")}catch(n){switch(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),nr.classify(n)){case"parsing":let r={type:"tool_result",tool_call_id:`error_${on()}`,error:!0,content:`Non-streaming API parsing error: ${n.message}. Please check request format and retry.`};return u.debug("🔄 [PERSONAL AGENT] Non-streaming API parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(r)),"";case"critical":throw this.emit("error",n),new Error(`Tool calling API Error: ${n.message}`)}}}handleCompleteToolCall(e){this.emit("tool_use",e);let t=e.function?.name||"unknown",n=null;if(e.function?.arguments)try{n=JSON.parse(e.function.arguments)}catch{u.debug("[PERSONAL AGENT] Failed to parse tool arguments:",e.function.arguments);return}n&&this.setToolArgsCache(e.id,n),this.emit("toolExecuting",{toolCallId:e.id,name:t,arguments:n,startTime:new Date}),this.executeToolViaWebSocket(e.id,t,n)}async executeToolViaWebSocket(e,t,n){try{let s=fe.getInstance(),r={id:e,tool_name:t,arguments:n||{},tool_call_id:e};await s.sendToolRequest(r)}catch(s){u.debug(`Failed to execute tool via WebSocket: ${s.message}`)}}handleToolResult(e,t){this.emit("tool_result",{tool:e,result:t}),u.debug(`Tool Result: ${e.name}`),t&&u.debug(` Result: ${JSON.stringify(t,null,2)}`)}handleWebSocketToolResponse(e){let{tool_name:t,content:n,success:s,error:r}=e;if(u.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",s),s&&n){let a=`<context>
|
|
1838
1842
|
${n.map(c=>c.text||"").join("")}
|
|
1839
1843
|
</context>`;this.completeOutputWithToolResults+=a+`
|
|
1840
1844
|
`,this.currentOutput+=a+`
|
|
@@ -1850,29 +1854,29 @@ ${t}
|
|
|
1850
1854
|
`,this.currentOutput+=r+`
|
|
1851
1855
|
`,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=at.getInstance(),t=e.getQueuedMessages();if(t.length===0){u.debug("[CHECKPOINT] No queued messages to convert");return}let n=[],s=[];for(let r of t)(r.isCrossDeviceTask?s:n).push(r);if(u.debug(`[CHECKPOINT] Found ${t.length} queued messages:`),u.debug(` - ${n.length} user messages -> convert to feedback`),u.debug(` - ${s.length} cross-device tasks -> keep in queue`),n.length>0){let r=n.map(o=>({id:o.id,content:o.content,timestamp:o.timestamp,isFeedbackMessage:!0}));this.emit("feedback:messages",r),u.info(`[CHECKPOINT] Converted ${n.length} user messages to feedback`),n.forEach(o=>{e.removeFromQueueById(o.id)})}s.length>0&&u.debug(`[CHECKPOINT] Kept ${s.length} cross-device tasks in queue for execution`)}handleTodoUpdate(e){u.debug("[TODO-DEBUG] handleTodoUpdate called with:",JSON.stringify(e).substring(0,500));let t=e.items||e.todos||[];u.debug("[TODO-DEBUG] Extracted items count:",t.length),this.currentTodoList={todos:t.map(n=>{let s=n.content||n.text||"";return u.debug("[TODO-DEBUG] Processing todo item:",{id:n.id,text:s,status:n.status}),{id:n.id||on(),content:s,text:s,completed:n.completed||!1,priority:n.priority,status:n.status||(n.completed?"completed":"pending"),activeForm:n.activeForm||s}}),timestamp:new Date(e.timestamp||Date.now())},u.debug("[TODO-DEBUG] Emitting todo_update with",this.currentTodoList.todos.length,"todos"),this.emit("todo_update",this.currentTodoList)}handleWebViewUpdate(e){Array.isArray(e)?this.activeWebViewURLs=e:e.urls?this.activeWebViewURLs=e.urls:e.url&&(this.activeWebViewURLs=[e.url]),this.emit("webview_update",this.activeWebViewURLs)}handleOperatorProgress(e){this.operatorTaskState={id:e.id||on(),taskId:e.taskId||e.id||on(),sessionId:e.sessionId||on(),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..."),fe.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=me.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(),fe.getInstance().stopAllActiveTools("user_manual_stop"),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,n;if(t&&t.trim().length>0?n=t+`
|
|
1852
1856
|
|
|
1853
|
-
[STOPPED] - Task was stopped by user`:n="Task was stopped by user before any response was generated.",this.currentPromptId)try{u.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(s){u.debug("[PERSONAL AGENT] Firebase update failed for STOP:",s)}await this.completeConversation(n,"STOP"),u.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),u.debug("[PERSONAL AGENT] Local operations stopped (sessionId preserved for backend stop)")}async stopAllRunningTools(){try{u.debug("[PERSONAL AGENT] 🛑 Stopping browser-use agent..."),await te.stop(),u.debug("[PERSONAL AGENT] ✅ Browser-use agent stopped successfully")}catch(e){u.error("[PERSONAL AGENT] ❌ Failed to stop browser-use agent:",e)}try{await te.stopAllSubAgents(),u.debug("[PERSONAL AGENT] ✅ All browser sub-agents stopped")}catch(e){u.error("[PERSONAL AGENT] ❌ Failed to stop browser sub-agents:",e)}}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",n={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(n.session_id=this.currentSessionId,u.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):u.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let s=Pe.getInstance().getCurrentDeviceId();s?(n.device_id=s,u.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${s}`)):u.debug("[PERSONAL AGENT] No device_id available for stop request"),u.debug("[PERSONAL AGENT] Sending backend stop request");let r=await this.getFirebaseIdToken();r||u.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let o=await Aa.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})`),fe.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 Wu={};et(Wu,{FirebaseNativeService:()=>sr,TaskMode:()=>Ra,TaskStatus:()=>Oa});import{getDatabase as Tb,ref as Ma,onChildAdded as xb,update as Cb,set as Eb,serverTimestamp as Ib}from"firebase/database";import{EventEmitter as kb}from"events";var Ra,Oa,sr,Na=L(()=>{"use strict";q();Ms();Ra=(t=>(t.NEW="new",t.EXISTING="existing",t))(Ra||{}),Oa=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s.QUEUE_FULL="queue_full",s))(Oa||{}),sr=class i extends kb{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=kt.getInstance()}setFirebaseInstances(e,t){u.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=Tb(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=Ma(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=xb(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(()=>(Tt(),xn))).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(()=>(Tt(),xn)),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(()=>(Tt(),xn)),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=Ma(this.database,s),c={status:t,updatedAt:Ib()};n&&(c.result=n),await Cb(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=Ma(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 Eb(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 Pb}from"events";var ss,_a=L(()=>{"use strict";Pt();we();Ms();Na();Tt();jn();q();ss=class i extends Pb{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];incomingTaskQueue=[];isProcessingIncoming=!1;currentlyExecutingTaskId=null;overlayManager=null;constructor(){super(),this.deviceRegistrationService=Pe.getInstance(),this.authService=X.getInstance(),this.firebaseAPI=kt.getInstance(),this.firebaseNative=sr.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=Ge.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(Ge.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(Ge.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let n=at.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}`),Ge.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:Xt,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 mm={};et(mm,{SnowXStreamHandlerService:()=>wc});import{EventEmitter as aT}from"events";var wc,pm=L(()=>{"use strict";wc=class extends aT{buffer="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteChunks=[];byteChunksLength=0;thinkingContentParts=[];regularContentParts=[];isInThinkingBlock=!1;thinkingBuffer="";accumulatedToolCalls=new Map;toolCallIndexToId=new Map;processedToolCallIds=new Set;isCancelled=!1;lastActivityTime=new Date;keepaliveWatchdog=null;KEEPALIVE_TIMEOUT=3e4;constructor(){super()}updateActivityTime(){this.lastActivityTime=new Date}startKeepaliveWatchdog(){this.stopKeepaliveWatchdog(),this.updateActivityTime(),this.keepaliveWatchdog=setInterval(()=>{let e=Date.now()-this.lastActivityTime.getTime();e>this.KEEPALIVE_TIMEOUT&&this.emit("keepalive_timeout",{lastActivityTime:this.lastActivityTime,timeSinceLastActivity:e})},5e3)}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}async processStreamingResponse(e,t,n,s,r){let o=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,c)=>{this.startKeepaliveWatchdog(),e.on("data",l=>{if(this.isCancelled){this.stopKeepaliveWatchdog(),a();return}this.updateActivityTime(),this.totalBytesReceived+=l.length,this.byteChunks.push(l),this.byteChunksLength+=l.length;let d=this.byteChunksLength>0?Buffer.concat(this.byteChunks):Buffer.alloc(0);this.byteChunks=[],this.byteChunksLength=0;let g=d.length,m=Math.max(0,d.length-3);for(let p=d.length-1;p>=m;p--){let h=d[p];if((h&192)===128)continue;let f=1;(h&128)===0?f=1:(h&224)===192?f=2:(h&240)===224?f=3:(h&248)===240&&(f=4),d.length-p<f&&(g=p);break}if(g>0){let p=d.slice(0,g);g<d.length&&(this.byteChunks.push(d.slice(g)),this.byteChunksLength=d.length-g);let h=p.toString("utf8");this.buffer+=h,this.rawDataReceived+=h,this.processBufferedLines(n,s,r)}}),e.on("end",()=>{if(this.stopKeepaliveWatchdog(),this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(n,s,r),this.printFinalStatistics(),this.regularContentParts.length===0&&!r){c(new Error("No response received"));return}a()}),e.on("error",l=>{this.stopKeepaliveWatchdog(),c(l)})})}processBufferedLines(e,t,n){if(this.isCancelled)return;let s,r=this.buffer.indexOf(`\r
|
|
1857
|
+
[STOPPED] - Task was stopped by user`:n="Task was stopped by user before any response was generated.",this.currentPromptId)try{u.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(s){u.debug("[PERSONAL AGENT] Firebase update failed for STOP:",s)}await this.completeConversation(n,"STOP"),u.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),u.debug("[PERSONAL AGENT] Local operations stopped (sessionId preserved for backend stop)")}async stopAllRunningTools(){try{u.debug("[PERSONAL AGENT] 🛑 Stopping browser-use agent..."),await te.stop(),u.debug("[PERSONAL AGENT] ✅ Browser-use agent stopped successfully")}catch(e){u.error("[PERSONAL AGENT] ❌ Failed to stop browser-use agent:",e)}try{await te.stopAllSubAgents(),u.debug("[PERSONAL AGENT] ✅ All browser sub-agents stopped")}catch(e){u.error("[PERSONAL AGENT] ❌ Failed to stop browser sub-agents:",e)}}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",n={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(n.session_id=this.currentSessionId,u.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):u.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let s=Pe.getInstance().getCurrentDeviceId();s?(n.device_id=s,u.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${s}`)):u.debug("[PERSONAL AGENT] No device_id available for stop request"),u.debug("[PERSONAL AGENT] Sending backend stop request");let r=await this.getFirebaseIdToken();r||u.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let o=await Ra.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})`),fe.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 zu={};Fe(zu,{FirebaseNativeService:()=>sr,TaskMode:()=>_a,TaskStatus:()=>$a});import{getDatabase as Pb,ref as Na,onChildAdded as Ab,update as Db,set as Mb,serverTimestamp as Rb}from"firebase/database";import{EventEmitter as Ob}from"events";var _a,$a,sr,Fa=L(()=>{"use strict";q();Ms();_a=(t=>(t.NEW="new",t.EXISTING="existing",t))(_a||{}),$a=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s.QUEUE_FULL="queue_full",s))($a||{}),sr=class i extends Ob{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=kt.getInstance()}setFirebaseInstances(e,t){u.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=Pb(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=Na(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=Ab(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(()=>(Tt(),xn))).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(()=>(Tt(),xn)),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(()=>(Tt(),xn)),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=Na(this.database,s),c={status:t,updatedAt:Rb()};n&&(c.result=n),await Db(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=Na(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 Mb(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 Nb}from"events";var ss,La=L(()=>{"use strict";Pt();Te();Ms();Fa();Tt();zn();q();ss=class i extends Nb{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];incomingTaskQueue=[];isProcessingIncoming=!1;currentlyExecutingTaskId=null;overlayManager=null;constructor(){super(),this.deviceRegistrationService=Pe.getInstance(),this.authService=X.getInstance(),this.firebaseAPI=kt.getInstance(),this.firebaseNative=sr.getInstance(),this.firebaseNative.on("taskReceived",e=>{this.handleNativeTaskReceived(e)}),this.authService.on("SnowXSignOut",()=>{this.stopListening()}),this.setupTaskCompletionListener()}static getInstance(){return i.instance||(i.instance=new i),i.instance}setupTaskCompletionListener(){let e=je.getInstance();e.on("BotResponseCompleted",()=>{this.handleTaskCompletion()}),e.on("BotResponseStopped",()=>{this.handleTaskCompletion()}),e.on("BotResponseError",()=>{this.handleTaskCompletion()})}async handleTaskCompletion(){u.debug("✅ [CrossDevice] Task completion event received"),this.currentlyExecutingTaskId&&(u.debug("✅ [CrossDevice] Marking task completed:",this.currentlyExecutingTaskId),await this.markTaskCompletedById(this.currentlyExecutingTaskId),this.currentlyExecutingTaskId=null),this.incomingTaskQueue.length>0&&!this.isProcessingIncoming?(u.debug(`🔵 [CrossDevice] Task completed, processing next from incoming queue (${this.incomingTaskQueue.length} waiting)`),this.processIncomingTaskQueue()):this.processNextQueuedTask()}async markTaskCompletedById(e){u.debug("🔵 [CrossDevice] Marking task complete:",e),await this.updateTaskStatus(e,"completed")}processNextQueuedTask(){if(je.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){u.debug("⏸️ [CrossDevice] System still busy, waiting for completion");return}if(this.pendingTasksQueue.length===0){u.debug("✅ [CrossDevice] No pending tasks in queue");return}let n=this.pendingTasksQueue.shift();u.debug(`📤 [CrossDevice] Processing next task from queue: ${n.taskId}`),this.executeTaskImmediately(n.taskId,n.prompt,n.mode)}async startListening(e,t){let n=t||this.deviceRegistrationService.getCurrentDeviceId();if(!n){u.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=n,u.debug(`Starting listener - User: ${e}, Device: ${n}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let s=this.authService.getFirebaseAuth();if(!s?.currentUser){u.error("No authenticated Firebase user - cannot start listeners");return}if(s.currentUser.uid!==e){u.error("SECURITY: User ID mismatch! Firebase UID:",s.currentUser.uid,"Requested:",e),u.error("Refusing to start listener for different user");return}u.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,n)}catch(s){throw u.error("Failed to start listener:",s.message),s}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),u.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){u.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){u.error("No stored user ID found - cannot authenticate Firebase for listeners");return}u.debug("Found stored user ID, getting custom token from API...");try{let n=await this.authService.getCustomTokenFromAPI(e);if(t){let s=await this.authService.signInWithCustomToken(n);u.debug("Firebase authenticated successfully - UID:",s.user.uid)}}catch(n){u.warn("Firebase authentication failed:",n.message),u.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){u.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){u.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),u.warn("🚨 [SECURITY] Task ID:",e.taskId),u.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),u.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}u.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,u.debug("Triggering UI flow for cross-device task:",e.taskId),this.overlayManager&&(this.overlayManager.currentInput=e.prompt),this.emit("CrossDeviceTaskSendMessage",{taskId:e.taskId,prompt:e.prompt,mode:e.mode}),u.debug("Cross-device task UI flow triggered successfully")}catch(t){u.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){u.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(n){u.error("Failed to process task:",n.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),u.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let n=e.split("_");if(n.length!==3||n[0]!=="task")return!1;let s=n[1],r=n[2];return s.length!==13||!Number.isInteger(Number(s))||r.length!==9?!1:/^[a-z0-9]+$/.test(r)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let n=t.id,s=t.prompt,r=t.status;if(!n||!s){u.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(r!=="pending"){u.debug("⏭️ [CrossDevice] Skipping non-pending task:",n,"Status:",r);return}this.incomingTaskQueue.push({taskId:n,prompt:s,snapshot:e}),u.debug(`📨 [CrossDevice] Task queued for processing: ${n}`),u.debug(` Incoming queue size: ${this.incomingTaskQueue.length}`),this.isProcessingIncoming||this.processIncomingTaskQueue()}catch(t){u.error("❌ [CrossDevice] Error in handleIncomingTask:",t.message)}}async processIncomingTaskQueue(){if(this.incomingTaskQueue.length===0){this.isProcessingIncoming=!1,u.debug("✅ [CrossDevice] Incoming queue empty, processing complete");return}this.isProcessingIncoming=!0;let{taskId:e,prompt:t,snapshot:n}=this.incomingTaskQueue.shift();u.debug(`🔵 [CrossDevice] Processing task: ${e}`),u.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let s=n.val();if(u.debug("🔵 [CrossDevice] Task received, updating status to processing immediately"),await this.updateTaskStatus(e,"processing"),!this.validateTaskId(e)){u.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),u.warn("🚨 [SECURITY] Task ID:",e),u.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),u.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access"),await this.updateTaskStatus(e,"completed"),this.processIncomingTaskQueue();return}if(u.debug("✅ [SECURITY] Task ID validation passed:",e),!this.canAcceptTask()){u.warn("⚠️ [CrossDevice] Cannot accept task - execution queue is full"),await this.updateTaskStatus(e,"queue_full"),this.processIncomingTaskQueue();return}u.debug("✅ [CrossDevice] Task accepted:",e),u.debug(" Prompt:",t),this.currentlyExecutingTaskId=e,this.currentTaskId=e;let o="existing";await this.executeTask(e,t,o),this.isProcessingIncoming=!1,u.debug("✅ [CrossDevice] Task dispatched for execution, waiting for completion")}canAcceptTask(){if(je.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let n=at.getInstance(),s=n.getQueueCount(),r=n.canAddToQueue();if(u.debug(`🔍 [CrossDevice] Queue capacity check: ${s}/5 used, hasSpace: ${r}`),!r)return!1}return!0}async executeTask(e,t,n){if(u.debug(`Executing task: ${e} with mode: ${n}`),u.debug(`Prompt to execute: ${t}`),je.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){u.debug(`System is busy - queueing cross-device task: ${e}`);let o={taskId:e,prompt:t,mode:n};this.pendingTasksQueue.push(o),u.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}u.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,n)}async executeTaskImmediately(e,t,n){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{u.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",n),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:n})})}catch(s){u.error("Task execution failed:",s.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,s={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(n,s)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){this.cleanupObservers();let t=()=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)},n=r=>{this.currentTaskId===e&&this.cleanupObservers()},s=r=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)};this.once("BotResponseCompleted",t),this.once("BotResponseError",n),this.once("BotResponseStopped",s)}cleanupObservers(){this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),this.currentTaskId=null}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,n="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let s=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,r={taskId:s,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:n,timestamp:Xt,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 ym={};Fe(ym,{SnowXStreamHandlerService:()=>Cc});import{EventEmitter as mT}from"events";var Cc,vm=L(()=>{"use strict";Cc=class extends mT{buffer="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteChunks=[];byteChunksLength=0;thinkingContentParts=[];regularContentParts=[];isInThinkingBlock=!1;thinkingBuffer="";accumulatedToolCalls=new Map;toolCallIndexToId=new Map;processedToolCallIds=new Set;isCancelled=!1;lastActivityTime=new Date;keepaliveWatchdog=null;KEEPALIVE_TIMEOUT=3e4;constructor(){super()}updateActivityTime(){this.lastActivityTime=new Date}startKeepaliveWatchdog(){this.stopKeepaliveWatchdog(),this.updateActivityTime(),this.keepaliveWatchdog=setInterval(()=>{let e=Date.now()-this.lastActivityTime.getTime();e>this.KEEPALIVE_TIMEOUT&&this.emit("keepalive_timeout",{lastActivityTime:this.lastActivityTime,timeSinceLastActivity:e})},5e3)}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}async processStreamingResponse(e,t,n,s,r){let o=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,c)=>{this.startKeepaliveWatchdog(),e.on("data",l=>{if(this.isCancelled){this.stopKeepaliveWatchdog(),a();return}this.updateActivityTime(),this.totalBytesReceived+=l.length,this.byteChunks.push(l),this.byteChunksLength+=l.length;let d=this.byteChunksLength>0?Buffer.concat(this.byteChunks):Buffer.alloc(0);this.byteChunks=[],this.byteChunksLength=0;let g=d.length,m=Math.max(0,d.length-3);for(let p=d.length-1;p>=m;p--){let h=d[p];if((h&192)===128)continue;let f=1;(h&128)===0?f=1:(h&224)===192?f=2:(h&240)===224?f=3:(h&248)===240&&(f=4),d.length-p<f&&(g=p);break}if(g>0){let p=d.slice(0,g);g<d.length&&(this.byteChunks.push(d.slice(g)),this.byteChunksLength=d.length-g);let h=p.toString("utf8");this.buffer+=h,this.rawDataReceived+=h,this.processBufferedLines(n,s,r)}}),e.on("end",()=>{if(this.stopKeepaliveWatchdog(),this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(n,s,r),this.printFinalStatistics(),this.regularContentParts.length===0&&!r){c(new Error("No response received"));return}a()}),e.on("error",l=>{this.stopKeepaliveWatchdog(),c(l)})})}processBufferedLines(e,t,n){if(this.isCancelled)return;let s,r=this.buffer.indexOf(`\r
|
|
1854
1858
|
`);if(r!==-1)s=r;else{let o=this.buffer.indexOf(`
|
|
1855
1859
|
`);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
|
|
1856
1860
|
`?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(`
|
|
1857
1861
|
`)),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
|
|
1858
1862
|
`);if(e!==-1)return e;let t=this.buffer.indexOf(`
|
|
1859
|
-
`);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 cT from"axios";import{EventEmitter as lT}from"events";import uT from"http";import dT from"https";var mi,hm=L(()=>{"use strict";we();q();mi=class extends lT{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new uT.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new dT.Agent({keepAlive:!0,timeout:36e5}),this.client=cT.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=X.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let n=0;n<t;n++)try{return await e()}catch(s){let r=s.response?.status,o=s.code,a=r===429||r>=500&&r<600||o==="ECONNABORTED"||o==="ETIMEDOUT"||o==="ECONNREFUSED"||o==="ENOTFOUND"||o==="ERR_NETWORK";if(r===401||r===403||r===404)throw s;if(a&&n<t-1){let l=Math.pow(2,n+1)*1e3;u.debug(`[NETWORK] Retryable error (${o||r}), attempt ${n+1}/${t}, waiting ${l/1e3}s`),await new Promise(d=>setTimeout(d,l));continue}throw r===429?new Error("Rate limit exceeded. Please try again later."):s}throw new Error("Max retries exceeded")}buildRequest(e,t,n,s=.7,r=.9,o,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:n,temperature:t.name.includes("o4-mini")?void 0:s,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:r,reasoning_effort:t.reasoningEffort,tools:o,tool_choice:a}}async performNonStreamingRequest(e,t,n=.7,s=.9,r,o){let a=this.buildRequest(e,t,!1,n,s,r,o);try{let l=(await this.executeWithRetry(async()=>{let{data:d}=await this.client.post("/chat/completions",a,{headers:this.getAuthHeaders()});return d})).choices[0];return{content:l.message.content||"",toolCalls:l.message.tool_calls}}catch(c){throw this.emit("error",c),new Error(`API Error: ${c.message}`)}}async performStreamingRequest(e,t,n=.7,s=.9,r,o,a,c,l){let{SnowXStreamHandlerService:d}=await Promise.resolve().then(()=>(pm(),mm)),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 w=>{let C=w.data,T=w.headers["content-type"]||"",x=v=>{if(v?.index!==void 0){let I=v.index;f.has(I)||f.set(I,{});let S=f.get(I);v.id&&(S.id=v.id,S.type="function"),v.function&&(S.function||(S.function={name:"",arguments:""}),v.function.name&&(S.function.name=v.function.name),v.function.arguments&&(S.function.arguments+=v.function.arguments))}l?.(v),this.emit("tool_call_delta",v)};y.on("streamEnd",()=>{f.forEach((v,I)=>{v.id&&v.function?.name&&h.push(v)}),this.emit("done"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})}),y.on("cancelled",()=>{this.emit("canceled"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})});try{await y.processStreamingResponse(C,T,a||(()=>{}),c,x),f.forEach((v,I)=>{v.id&&v.function?.name&&h.push(v)}),this.emit("done"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})}catch(v){this.emit("error",v),p(v)}}).catch(w=>{w.code==="ERR_CANCELED"?(this.emit("canceled"),m({content:"",toolCalls:h.length>0?h:void 0})):p(w)})})}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 gT}from"socket.io-client";import{EventEmitter as mT}from"events";var pi,fm=L(()=>{"use strict";Pt();pi=class i extends mT{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=Pe.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let n={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=gT(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 bm,ym=L(()=>{"use strict";bm={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 Sm={};et(Sm,{ServiceManager:()=>wr});import{EventEmitter as pT}from"events";import{initializeApp as hT,getApps as vm}from"firebase/app";import{getAuth as fT}from"firebase/auth";var wr,Tc=L(()=>{"use strict";Tt();hm();we();Pt();fm();Qn();_a();Ur();Kt();q();ym();wr=class i extends pT{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=Ge.getInstance(),this.networkClient=new mi,this.authService=X.getInstance(),this.deviceRegistration=Pe.getInstance(),this.webSocketService=pi.getInstance(),this.frontendWebSocketService=fe.getInstance(),this.crossDeviceService=ss.getInstance(),this.toolCalling=Ls.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||bm;if(vm().length===0?(this.firebaseApp=hT(e),u.debug("Firebase app initialized")):(this.firebaseApp=vm()[0],u.debug("Using existing Firebase app")),this.firebaseAuth=fT(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(()=>(Na(),Wu));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=me[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 me.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 Ic from"@sentry/node";Ic.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as TT}from"commander";import vT from"react";import{render as ST}from"@jrichman/ink";import J,{useCallback as sT,useState as rT,useEffect as Sc,useMemo as lm,useRef as um}from"react";import{Box as Be,Text as dm}from"@jrichman/ink";import oT from"ink-spinner";import bi from"terminal-link";import{homedir as Em}from"os";function kc(i){let e=i.trim();return e.startsWith("~")&&(e=e.replace("~",Em())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function Im(i){return i.startsWith("http://")||i.startsWith("https://")||i.startsWith("mailto:")}function Cr(i){let e=i;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,n,s)=>{let r=s;return!Im(s)&&!s.startsWith("file://")&&(s.startsWith("/")||s.startsWith("~")||/\.[a-z]{2,4}$/i.test(s))&&(r=kc(s)),bi(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:bi(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=kc(t);return bi(t,r,{fallback:(o,a)=>o})}),e}function Er(i){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],n;for(;(n=e.exec(i))!==null;){let o=n[1].split(`
|
|
1860
|
-
`).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
|
|
1863
|
+
`);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 pT from"axios";import{EventEmitter as hT}from"events";import fT from"http";import bT from"https";var hi,Sm=L(()=>{"use strict";Te();q();hi=class extends hT{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new fT.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new bT.Agent({keepAlive:!0,timeout:36e5}),this.client=pT.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=X.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let n=0;n<t;n++)try{return await e()}catch(s){let r=s.response?.status,o=s.code,a=r===429||r>=500&&r<600||o==="ECONNABORTED"||o==="ETIMEDOUT"||o==="ECONNREFUSED"||o==="ENOTFOUND"||o==="ERR_NETWORK";if(r===401||r===403||r===404)throw s;if(a&&n<t-1){let l=Math.pow(2,n+1)*1e3;u.debug(`[NETWORK] Retryable error (${o||r}), attempt ${n+1}/${t}, waiting ${l/1e3}s`),await new Promise(d=>setTimeout(d,l));continue}throw r===429?new Error("Rate limit exceeded. Please try again later."):s}throw new Error("Max retries exceeded")}buildRequest(e,t,n,s=.7,r=.9,o,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:n,temperature:t.name.includes("o4-mini")?void 0:s,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:r,reasoning_effort:t.reasoningEffort,tools:o,tool_choice:a}}async performNonStreamingRequest(e,t,n=.7,s=.9,r,o){let a=this.buildRequest(e,t,!1,n,s,r,o);try{let l=(await this.executeWithRetry(async()=>{let{data:d}=await this.client.post("/chat/completions",a,{headers:this.getAuthHeaders()});return d})).choices[0];return{content:l.message.content||"",toolCalls:l.message.tool_calls}}catch(c){throw this.emit("error",c),new Error(`API Error: ${c.message}`)}}async performStreamingRequest(e,t,n=.7,s=.9,r,o,a,c,l){let{SnowXStreamHandlerService:d}=await Promise.resolve().then(()=>(vm(),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 T=>{let x=T.data,S=T.headers["content-type"]||"",C=v=>{if(v?.index!==void 0){let I=v.index;f.has(I)||f.set(I,{});let w=f.get(I);v.id&&(w.id=v.id,w.type="function"),v.function&&(w.function||(w.function={name:"",arguments:""}),v.function.name&&(w.function.name=v.function.name),v.function.arguments&&(w.function.arguments+=v.function.arguments))}l?.(v),this.emit("tool_call_delta",v)};y.on("streamEnd",()=>{f.forEach((v,I)=>{v.id&&v.function?.name&&h.push(v)}),this.emit("done"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})}),y.on("cancelled",()=>{this.emit("canceled"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})});try{await y.processStreamingResponse(x,S,a||(()=>{}),c,C),f.forEach((v,I)=>{v.id&&v.function?.name&&h.push(v)}),this.emit("done"),m({content:y.getFinalResponse(),toolCalls:h.length>0?h:void 0})}catch(v){this.emit("error",v),p(v)}}).catch(T=>{T.code==="ERR_CANCELED"?(this.emit("canceled"),m({content:"",toolCalls:h.length>0?h:void 0})):p(T)})})}stopStreaming(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=void 0)}async testConnection(e){try{let t={role:"user",content:"Hello"};return!!(await this.performNonStreamingRequest([t],e,.7,.9)).content}catch{return!1}}}});import{io as yT}from"socket.io-client";import{EventEmitter as vT}from"events";var fi,wm=L(()=>{"use strict";Pt();fi=class i extends vT{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=Pe.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let n={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=yT(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 Tm,xm=L(()=>{"use strict";Tm={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 Em={};Fe(Em,{ServiceManager:()=>wr});import{EventEmitter as ST}from"events";import{initializeApp as wT,getApps as Cm}from"firebase/app";import{getAuth as TT}from"firebase/auth";var wr,Ec=L(()=>{"use strict";Tt();Sm();Te();Pt();wm();Jn();La();Ur();Kt();q();xm();wr=class i extends ST{static instance;initialized=!1;personalAgent;networkClient;authService;deviceRegistration;webSocketService;frontendWebSocketService;crossDeviceService;toolCalling;firebaseApp=null;firebaseAuth=null;options={enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0};constructor(){super(),this.personalAgent=je.getInstance(),this.networkClient=new hi,this.authService=X.getInstance(),this.deviceRegistration=Pe.getInstance(),this.webSocketService=fi.getInstance(),this.frontendWebSocketService=fe.getInstance(),this.crossDeviceService=ss.getInstance(),this.toolCalling=Ls.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||Tm;if(Cm().length===0?(this.firebaseApp=wT(e),u.debug("Firebase app initialized")):(this.firebaseApp=Cm()[0],u.debug("Using existing Firebase app")),this.firebaseAuth=TT(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(()=>(Fa(),zu));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=me[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 me.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 Ac from"@sentry/node";Ac.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as PT}from"commander";import ET from"react";import{render as IT}from"@jrichman/ink";import J,{useCallback as lT,useState as uT,useEffect as xc,useMemo as pm,useRef as hm}from"react";import{Box as We,Text as fm}from"@jrichman/ink";import dT from"ink-spinner";import vi from"terminal-link";import{homedir as Dm}from"os";function Dc(i){let e=i.trim();return e.startsWith("~")&&(e=e.replace("~",Dm())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function Mm(i){return i.startsWith("http://")||i.startsWith("https://")||i.startsWith("mailto:")}function Cr(i){let e=i;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,n,s)=>{let r=s;return!Mm(s)&&!s.startsWith("file://")&&(s.startsWith("/")||s.startsWith("~")||/\.[a-z]{2,4}$/i.test(s))&&(r=Dc(s)),vi(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:vi(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=Dc(t);return vi(t,r,{fallback:(o,a)=>o})}),e}function Er(i){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],n;for(;(n=e.exec(i))!==null;){let o=n[1].split(`
|
|
1864
|
+
`).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 Mc(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 Rc(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 Si(i){let e=i;return e=e.replace(/\*\*(.+?)\*\*/g,"$1"),e=e.replace(/__(.+?)__/g,"$1"),e=e.replace(/\*(.+?)\*/g,"$1"),e=e.replace(/_(.+?)_/g,"$1"),e=e.replace(/`(.+?)`/g,"$1"),e=Cr(e),e}function Oc(i){return i.replace(/\[TOOL:[^\]]+\]/g,"").trim()}import $n from"react";Te();import as,{createContext as us,useContext as Nt,useState as id,useCallback as Wa,useRef as Rn,useEffect as Ft,useMemo as cs}from"react";import{useApp as ny}from"@jrichman/ink";Tt();Hi();import mt from"chalk";import Ib from"ora";var ke=class{static spinner=null;static formatUserMessage(e){return mt.cyan("You: ")+e}static formatAssistantMessage(e){return mt.green("Assistant: ")+e}static formatError(e){return mt.red("Error: ")+e}static formatWarning(e){return mt.yellow("Warning: ")+e}static formatInfo(e){return mt.blue("Info: ")+e}static formatSuccess(e){return mt.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=Ib(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(mt.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(mt.bold.cyan(e)),console.log(mt.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return mt.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return mt.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(mt.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};q();zn();Kn();import{EventEmitter as kb}from"events";import Oa from"chalk";var No=class extends kb{delegate=null;personalAgentService=je.getInstance();currentStreamingTask=null;constructor(e){super(),this.delegate=e||null,this.setupPersonalAgentService()}setupPersonalAgentService(){let e=!0,t="",n=console.log;this.delegate?.usesCustomUI||(console.log=(...s)=>{let r=String(s[0]||"");(r.includes("▸")||r.includes("→")||r.includes("✎"))&&t&&(e&&(e=!1),t=""),n.apply(console,s)}),this.personalAgentService.on("data",s=>{if(t+=s,this.delegate){let r=this.delegate.messages[this.delegate.messages.length-1],o=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];r&&r.isStreaming&&(!r.content||r.content===""?r.content=s:r.content+=s),o&&o.isStreaming&&(!o.content||o.content===""?o.content=s:o.content+=s)}}),this.personalAgentService.on("thinking",s=>{}),this.personalAgentService.on("toolExecuting",s=>{this.delegate?.usesCustomUI||console.log(`
|
|
1861
1865
|
▸ ${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(`
|
|
1862
|
-
❌ 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 ct,r=e.trim(),o=s.count(r);if(o>
|
|
1866
|
+
❌ 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 ct,r=e.trim(),o=s.count(r);if(o>qn){console.log(ke.formatError(`Prompt too large (${o.toLocaleString()} tokens). Please reduce it to ${qn.toLocaleString()} tokens or less.`));return}if(this.delegate.isLoading){let l=at.getInstance();l.addToQueue({content:r,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(Oa.blue(`⚡ Message queued (${l.getQueueCount()} in queue)`)),console.log(Oa.dim(" Your feedback will be sent when AI completes current task"))):console.log(Oa.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let a=null;this.delegate.isVisionEnabled&&(a=await Zn.getInstance().captureScreen(),a?u.debug(`[MESSAGE HANDLER] Captured screenshot for vision mode: ${a.length} chars`):u.debug("[MESSAGE HANDLER] Failed to capture screenshot, sending message without vision"));let c=[];t&&t.length>0&&(c.push(...t),u.debug(`[MESSAGE HANDLER] Received ${t.length} image attachments`)),a&&c.push(a),this.delegate.currentInput="";try{n?await this.processStreamingMessage(c.length>0?c:void 0):await this.processNonStreamingMessage(c.length>0?c:void 0)}catch(l){console.error(ke.formatError(`Message failed: ${l.message}`)),this.delegate.isLoading=!1,this.emit("BotResponseError",l.message)}}async processStreamingMessage(e){if(this.delegate)try{u.debug("[MESSAGE HANDLER] Using PersonalAgentService (matches SnowX exactly)"),await this.processWithPersonalAgentService(e)}catch(t){throw t}}shouldUsePersonalAgentService(){return!0}async processWithPersonalAgentService(e){if(!this.delegate)return;let t=this.delegate.fullConversationHistory.slice(0,-2).filter(r=>!(r.isStreaming||r.role==="system"||!r.content||typeof r.content=="string"&&r.content.trim().length===0)).map(r=>({role:r.role,content:r.content})),n=this.delegate.fullConversationHistory.filter(r=>r.role==="user"),s=n[n.length-1];if(s)try{let r={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(s.content,t,this.delegate.selectedModel,.7,!0,void 0,e,r),u.debug("[MESSAGE HANDLER] PersonalAgentService processing complete")}catch(r){throw u.debug(`[MESSAGE HANDLER] PersonalAgentService error: ${r.message}`),r}}async processNonStreamingMessage(e){throw new Error("processNonStreamingMessage is deprecated - PersonalAgentService handles all conversations")}stopStreaming(){if(this.currentStreamingTask&&(this.currentStreamingTask.abort(),this.currentStreamingTask=null),this.delegate){let e="",t=this.delegate.messages.find(s=>s.isStreaming);if(t){if(e=t.content,!t.content.includes("[STOPPED]")&&!t.content.includes("[DONE]")){let r=t.content;r.trim().length>0&&(r+=`
|
|
1863
1867
|
|
|
1864
|
-
`),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,
|
|
1865
|
-
✓ Updated to v${e}`)+
|
|
1866
|
-
`))}),u.debug(`Successfully updated to ${e}`)):u.debug(`Update failed with code ${a}: ${o}`),s()}),r.on("error",a=>{u.debug("Auto-update spawn error:",a),s()}),setTimeout(()=>{this.updateCompleted||(r.kill(),u.debug("Update timed out"),s())},6e4)})}catch(t){u.debug("Auto-update failed:",t)}}isUserInteracting(){return process.stdin.isRaw?!0:process.stdin.listenerCount("keypress")>0}showPendingNotification(){if(this.updateCompleted){let e=this.loadCache();e?.latestVersion&&console.log(
|
|
1867
|
-
✓ Updated to v${e.latestVersion}`)+
|
|
1868
|
-
`))}}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{
|
|
1868
|
+
`),r+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=r}t.isStreaming=!1;let s=this.delegate.fullConversationHistory.find(r=>r.isStreaming);s&&(s.content=t.content,s.isStreaming=!1)}this.delegate.isLoading=!1,je.getInstance().stopStreaming().catch(s=>{u.error("[MESSAGE HANDLER] Error in comprehensive stop:",s)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};Tt();zn();Jn();La();Ai();q();import{EventEmitter as _b}from"events";import $b from"axios";import{spawn as Fb,execSync as Lb}from"child_process";import _o from"chalk";import Dn from"fs";import Mn from"path";import rs from"os";import{getUserAgent as Ub}from"package-manager-detector/detect";import{resolveCommand as Bb}from"package-manager-detector/commands";var Wb={enabled:!0,checkIntervalMs:1440*60*1e3},qu=/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.-]+))?(?:\+([a-zA-Z0-9.-]+))?$/,os=class i extends _b{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;config;cacheFilePath;updateCompleted=!1;constructor(e,t){super(),this.currentVersion=e,this.config={...Wb,...t},this.cacheFilePath=Mn.join(rs.homedir(),".orion","update-cache.json")}static getInstance(e,t){return i.instance||(i.instance=new i(e,t)),i.instance}static getExistingInstance(){return i.instance||null}static resetInstance(){i.instance=void 0}isEnabled(){return this.config.enabled}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}async checkAndUpdate(){if(!this.config.enabled){u.debug("Auto-update is disabled");return}if(!this.isChecking){if(!this.shouldCheckForUpdates()){u.debug("Skipping update check - within cooldown period");return}this.isChecking=!0;try{let e=await this.fetchLatestVersion();if(!this.isValidVersion(e)){u.debug(`Invalid version format from registry: ${e}`);return}this.saveCache({lastCheck:Date.now(),latestVersion:e}),this.isNewerVersion(e,this.currentVersion)?await this.performUpdate(e):u.debug(`Already on latest version: ${this.currentVersion}`)}catch(e){u.debug("Update check failed:",e)}finally{this.isChecking=!1}}}shouldCheckForUpdates(){let e=this.loadCache();return e?Date.now()-e.lastCheck>=this.config.checkIntervalMs:!0}loadCache(){try{if(Dn.existsSync(this.cacheFilePath)){let e=Dn.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=Mn.dirname(this.cacheFilePath);Dn.existsSync(t)||Dn.mkdirSync(t,{recursive:!0}),Dn.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:qu.test(e)}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`,n=(await $b.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(qu);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=Ub();if(e)return u.debug(`Detected package manager from user agent: ${e}`),e;let t=process.argv[1]||"";return[process.env.PNPM_HOME,Mn.join(rs.homedir(),".local","share","pnpm"),Mn.join(rs.homedir(),"Library","pnpm")].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected pnpm from installation path"),"pnpm"):[Mn.join(rs.homedir(),".yarn"),Mn.join(rs.homedir(),".config","yarn"),process.env.YARN_GLOBAL_FOLDER].filter(Boolean).some(o=>o&&t.includes(o))?(u.debug("Detected yarn from installation path"),"yarn"):[Mn.join(rs.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 Lb(`${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=Bb(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=Fb(t,n,{stdio:"pipe",shell:process.platform==="win32",detached:!1}),o="";r.stderr?.on("data",a=>{o+=a.toString()}),r.on("close",a=>{a===0?(this.updateCompleted=!0,this.emit("updated",{from:this.currentVersion,to:e}),setImmediate(()=>{this.isUserInteracting()?this.emit("update_notification_pending",{from:this.currentVersion,to:e}):console.log(_o.green(`
|
|
1869
|
+
✓ Updated to v${e}`)+_o.gray(` - restart CLI to use new version
|
|
1870
|
+
`))}),u.debug(`Successfully updated to ${e}`)):u.debug(`Update failed with code ${a}: ${o}`),s()}),r.on("error",a=>{u.debug("Auto-update spawn error:",a),s()}),setTimeout(()=>{this.updateCompleted||(r.kill(),u.debug("Update timed out"),s())},6e4)})}catch(t){u.debug("Auto-update failed:",t)}}isUserInteracting(){return process.stdin.isRaw?!0:process.stdin.listenerCount("keypress")>0}showPendingNotification(){if(this.updateCompleted){let e=this.loadCache();e?.latestVersion&&console.log(_o.green(`
|
|
1871
|
+
✓ Updated to v${e.latestVersion}`)+_o.gray(` - restart CLI to use new version
|
|
1872
|
+
`))}}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{Dn.existsSync(this.cacheFilePath)&&Dn.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 Ku(){if(process.env.ORION_DEV==="true"||process.env.ORION_DEV==="1"||process.argv[1]?.includes("tsx")||process.argv[1]?.endsWith(".ts"))return!0;let i=process.argv[1]||"";if(i.includes("/src/")&&!i.includes("node_modules"))return!0;let e=["/orion-cli/dist/","/orion-cli/src/"];for(let n of e)if(i.includes(n)&&!i.includes("node_modules"))return!0;return!1}Kt();He();wt();q();import cn from"fs";import $o from"path";import Hb from"os";import Vu from"crypto";var Ua=200,Gb=100,jb=500,is=class i{static instance;storagePath;state;saveTimeout=null;isDirty=!1;constructor(){let e=$o.join(Hb.homedir(),".orion-cli");this.storagePath=$o.join(e,"conversations.json"),this.state=this.loadState()}static getInstance(){return i.instance||(i.instance=new i),i.instance}loadState(){try{if(cn.existsSync(this.storagePath)){let e=cn.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()},jb)}flushPendingSaves(){this.isDirty&&(this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveTimeout=null),this.saveStateImmediate())}saveStateImmediate(){try{let e=$o.dirname(this.storagePath);cn.existsSync(e)||cn.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]);cn.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:Vu.randomUUID(),title:e,createdAt:t,updatedAt:t,messageCount:0};if(this.state.conversations.length>=Gb){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>Ua&&(this.state.messages[e]=n.slice(-Ua),u.debug(`[STORAGE] Trimmed messages to ${Ua} 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||Vu.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(`
|
|
1869
1873
|
`)}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(`
|
|
1870
|
-
`)}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
|
|
1874
|
+
`)}saveExportToFile(e,t,n){try{let s=null;switch(t){case"markdown":s=this.exportAsMarkdown(e);break;case"json":s=this.exportAsJSON(e);break;case"text":s=this.exportAsText(e);break}if(!s)return{success:!1,error:"Conversation not found or empty"};let r=$o.dirname(n);return cn.existsSync(r)||cn.mkdirSync(r,{recursive:!0}),cn.writeFileSync(n,s,"utf8"),u.debug(`[STORAGE] Exported conversation to ${n}`),{success:!0}}catch(s){return{success:!1,error:s.message}}}},Qe=is.getInstance();import zb from"crypto";function be(){return zb.randomUUID()}function Xu(i){return i.content||i.text||"Untitled task"}import{useEffect as qb,useRef as rr,useCallback as Yu}from"react";function Qu({personalAgent:i,frontendWS:e,handlers:t}){let n=rr(""),s=rr(!0),r=rr(!1),o=rr(!1),a=rr(null),c=100,l=Yu(()=>{if(a.current=null,o.current=!1,!r.current||!s.current)return;r.current=!1;let g=n.current;t.onMessagesUpdate(m=>m.map((p,h)=>p.role==="assistant"&&!m.slice(h+1).some(y=>y.role==="assistant")?{...p,content:g}:p))},[t]);return qb(()=>{s.current=!0,n.current="";let g=v=>{t.onConversationIdReceived(v)},m=()=>{t.onLoadingMessageChange("Processing")},p=v=>{n.current+=v,r.current=!0,o.current||(o.current=!0,a.current=setTimeout(l,c))},h=v=>{let I=typeof v=="string"?v:v.name,w=typeof v=="string"?`tool-${Date.now()}`:v.toolCallId,E=typeof v=="string"?void 0:v.arguments,D=I.toLowerCase().replace(/_/g,"")==="todowrite";t.onActiveToolsUpdate($=>{let R=new Map($);return R.set(w,{toolCallId:w,name:I,arguments:E,startTime:new Date,state:"running"}),R}),D||t.onLoadingMessageChange("Processing")},f=v=>{if(!v||!v.toolName)return;let I=v.toolId||`tool-${v.toolName}-${Date.now()}`,w=v.success===!1||v.error,E=v.error||v.result?.error||"",P=v.arguments,D="";v.result&&(typeof v.result=="string"?D=v.result:Array.isArray(v.result)?D=v.result.map(N=>typeof N=="string"?N:N&&typeof N=="object"?N.text||N.content||JSON.stringify(N):"").join(""):v.result.output?D=typeof v.result.output=="string"?v.result.output:JSON.stringify(v.result.output,null,2):v.result.content?D=v.result.content:D=JSON.stringify(v.result,null,2));let $=D.length>500?D.substring(0,500)+`
|
|
1871
1875
|
...(truncated)`:D,R=`<context>
|
|
1872
1876
|
${D}
|
|
1873
|
-
</context>`,_=
|
|
1874
|
-
`+R:R}}}return k}))},y=v=>{!v||!v.toolCallId||t.onActiveToolsUpdate(I=>{let
|
|
1875
|
-
📁 ${i}`,clear:()=>"Fresh start",newConversation:()=>"New conversation",continueConversation:()=>"Welcome back",deleted:()=>"Conversation cleared"};function
|
|
1877
|
+
</context>`,_=w?"failed":"completed";t.onActiveToolsUpdate(N=>{let k=new Map(N),M=I;if(!k.has(I)){for(let[F,B]of k.entries())if(B.name===v.toolName&&B.state==="running"){M=F;break}}if(k.has(M)){let F=k.get(M);k.set(M,{...F,arguments:F.arguments||P,state:_,output:$,error:w?E:void 0})}else k.set(M,{toolCallId:M,name:v.toolName,arguments:P,startTime:new Date,state:_,output:$,error:w?E:void 0});return k}),t.onMessagesUpdate(N=>N.map((k,M)=>{if(k.role==="assistant"&&!N.slice(M+1).some(B=>B.role==="assistant")){let B=k.metadata?.toolResults;return{...k,metadata:{...k.metadata,toolResults:B?B+`
|
|
1878
|
+
`+R:R}}}return k}))},y=v=>{!v||!v.toolCallId||t.onActiveToolsUpdate(I=>{let w=new Map(I),E=w.get(v.toolCallId);return E&&w.set(v.toolCallId,{...E,arguments:v.arguments}),w})},T=()=>{if(r.current){r.current=!1,o.current=!1;let v=n.current;t.onMessagesUpdate(I=>I.map((w,E)=>w.role==="assistant"&&!I.slice(E+1).some(D=>D.role==="assistant")?{...w,content:v}:w))}t.onLoadingChange(!1),t.onActiveToolsUpdate(()=>new Map),n.current=""},x=v=>{t.onError(v.message||"Unknown error"),t.onLoadingChange(!1),t.onActiveToolsUpdate(()=>new Map),n.current=""},S=v=>{t.onConfirmationRequest({id:v.confirmationId,type:v.type,title:v.title,message:v.message,command:v.command,targets:v.targets,isDestructive:v.isDestructive,timeout:v.isDestructive?v.timeout||3e4:void 0})},C=v=>{t.onTodoUpdate(v)};return i.on("conversation_id_received",g),i.on("thinking",m),i.on("data",p),i.on("toolExecuting",h),i.on("tool_completed",f),i.on("tool_args_update",y),i.on("done",T),i.on("error",x),i.on("confirmation_request",S),i.on("todo_update",C),e&&(e.on("toolExecuting",h),e.on("tool_completed",f)),()=>{s.current=!1,a.current&&(clearTimeout(a.current),a.current=null),i.off("conversation_id_received",g),i.off("thinking",m),i.off("data",p),i.off("toolExecuting",h),i.off("tool_completed",f),i.off("tool_args_update",y),i.off("done",T),i.off("error",x),i.off("confirmation_request",S),i.off("todo_update",C),e&&(e.off("toolExecuting",h),e.off("tool_completed",f))}},[i,e,t,l]),{resetContent:Yu(()=>{n.current=""},[])}}import{useState as Kb,useEffect as Ju,useCallback as Zu,useMemo as ed,useRef as Ba}from"react";function td({queueManager:i,frontendWS:e,crossDevice:t,isLoading:n,selectedModel:s,onCrossDeviceTask:r}){let[o,a]=Kb([]),c=Ba(n),l=Ba(s),d=Ba(r);Ju(()=>{c.current=n,l.current=s,d.current=r},[n,s,r]);let g=ed(()=>o.filter(y=>!y.isCrossDeviceTask),[o]),m=ed(()=>o.filter(y=>y.isCrossDeviceTask),[o]),p=o.length>0,h=Zu((y,T=[])=>i.addToQueue({content:y,imageUrls:T,attachments:[],model:l.current.name}),[i]),f=Zu(()=>{if(!i.hasQueuedMessages())return null;let y=i.processNextMessage();return y&&i.startProcessing(),y},[i]);return Ju(()=>{let y=S=>{a(S)},T=()=>{},x=S=>{if(c.current){i.addToQueue({content:S.prompt,imageUrls:[],attachments:[],model:l.current.name,isCrossDeviceTask:!0,crossDeviceTaskId:S.taskId})||d.current(S.taskId,"");return}d.current(S.taskId,S.prompt)};return i.on("queue:updated",y),e.on("feedback:sent",T),t.on("CrossDeviceTaskSendMessage",x),()=>{i.off("queue:updated",y),e.off("feedback:sent",T),t.off("CrossDeviceTaskSendMessage",x)}},[i,e,t]),{queuedMessages:o,regularQueuedMessages:g,crossDeviceTasks:m,addToQueue:h,processNextMessage:f,hasQueuedMessages:p}}import{useState as Vb,useEffect as Xb}from"react";function nd({subAgentManager:i}){let[e,t]=Vb(new Map);return Xb(()=>{let n=()=>{let s=i.getOperations();t(new Map(s))};return i.on("spawn_started",n),i.on("agent_started",n),i.on("agent_streaming",n),i.on("agent_completed",n),i.on("spawn_completed",n),i.on("progress",n),()=>{i.off("spawn_started",n),i.off("agent_started",n),i.off("agent_streaming",n),i.off("agent_completed",n),i.off("spawn_completed",n),i.off("progress",n)}},[i]),{subAgentOperations:e}}Ia();import{useEffect as Yb,useState as Qb,useRef as Jb,useCallback as Zb}from"react";function sd({frontendWS:i}){let[e,t]=Qb(null),n=Jb(null);Yb(()=>{let r=a=>{n.current={conversationId:a.conversationId,source:a.source};let c=a.message?a.message.length>80?a.message.substring(0,80)+"...":a.message:"Processing request";t({source:a.source,message:c,conversationId:a.conversationId,timestamp:a.timestamp})},o=a=>{n.current?.conversationId===a.conversationId&&(n.current=null,t(null))};return i.on("external_session_started",r),i.on("external_session_ended",o),ns.on("external_session_started",r),ns.on("external_session_ended",o),()=>{i.off("external_session_started",r),i.off("external_session_ended",o),ns.off("external_session_started",r),ns.off("external_session_ended",o),n.current=null}},[i]);let s=Zb(()=>{n.current=null,t(null)},[]);return{externalSession:e,clearSession:s,hasActiveSession:e!==null}}import{useState as ey,useEffect as rd,useRef as ty}from"react";function od(){let[i,e]=ey(null),t=ty(null);return rd(()=>{t.current=i},[i]),rd(()=>{if(!i||i.todos.length===0)return;let n=i.todos.filter(o=>o.status==="completed").length,s=i.todos.length;if(n===s&&s>0){let o=setTimeout(()=>{e(null),t.current=null},3e3);return()=>clearTimeout(o)}},[i]),{todoList:i,setTodoList:e,todoListRef:t}}var ad=us(null),cd=us(null),ld=us(null),ud=us(null),dd=us(null),Lt=us(null),ls={main:i=>`Orion ready
|
|
1879
|
+
📁 ${i}`,clear:()=>"Fresh start",newConversation:()=>"New conversation",continueConversation:()=>"Welcome back",deleted:()=>"Conversation cleared"};function Ha({children:i,initialProjectPath:e}){let t=e||process.cwd(),{exit:n}=ny(),s=cs(()=>({authService:X.getInstance(),personalAgent:je.getInstance(),queueManager:at.getInstance(),frontendWS:fe.getInstance(),crossDevice:ss.getInstance(),subAgentManager:Ns.getInstance()}),[]);Ft(()=>(Y.enableCustomUI(),()=>Y.disableCustomUI()),[]);let r=cs(()=>me.find(k=>k.name===ye.string("selectedPersonalModel"))||me.find(k=>k.name==="snowx-c5")||me[0],[]),[o,a]=id(()=>{let k=Qe.getConversations(),M=Qe.getCurrentConversation();return{messages:[{id:be(),role:"system",content:ls.main(t),timestamp:Date.now()}],conversationId:M?.id||null,conversationTitleGenerated:!1,isLoading:!1,loadingMessage:"Processing",activeTools:new Map,subAgentOperations:new Map,externalSession:null,pendingConfirmation:null,todoList:null,conversations:k,staticRemountKey:0}}),c=Rn(o.isLoading),l=Rn(o.messages),d=Rn(o.conversationId),g=Rn(o.pendingConfirmation),m=Rn(r),p=Rn(!1);Ft(()=>{c.current=o.isLoading,l.current=o.messages,d.current=o.conversationId,g.current=o.pendingConfirmation},[o.isLoading,o.messages,o.conversationId,o.pendingConfirmation]);let{todoList:h,setTodoList:f}=od();Ft(()=>{a(k=>({...k,todoList:h}))},[h]),Ft(()=>{if(process.env.MOCK_MESSAGES!=="true")return;let k=setTimeout(()=>{let F=[{id:be(),role:"system",content:ls.main("/mock/project"),timestamp:Date.now()},{id:be(),role:"user",content:"Show me all UI components for testing the chatbox",timestamp:Date.now()+100},{id:be(),role:"assistant",content:`## Heading Level 2
|
|
1876
1880
|
|
|
1877
1881
|
### Heading Level 3
|
|
1878
1882
|
|
|
@@ -1947,20 +1951,20 @@ This response has multiple paragraphs to take up more space.
|
|
|
1947
1951
|
|
|
1948
1952
|
- Item 1
|
|
1949
1953
|
- Item 2
|
|
1950
|
-
- Item 3`,timestamp:Date.now()+600+le*100}))],B={todos:[{id:"todo-1",content:"Setup project structure",status:"completed",activeForm:"Setting up project structure"},{id:"todo-2",content:"Implement core features",status:"completed",activeForm:"Implementing core features"},{id:"todo-3",content:"Add authentication",status:"in_progress",activeForm:"Adding authentication"},{id:"todo-4",content:"Write unit tests",status:"pending",activeForm:"Writing unit tests"},{id:"todo-5",content:"Setup CI/CD pipeline",status:"pending",activeForm:"Setting up CI/CD"},{id:"todo-6",content:"Deploy to production",status:"pending",activeForm:"Deploying to production"}],timestamp:new Date},H=new Map([["tool-1",{toolCallId:"tool-1",name:"Bash",arguments:{command:"npm install",description:"Install dependencies"},startTime:new Date,state:"running"}],["tool-2",{toolCallId:"tool-2",name:"Read",arguments:{file_path:"/src/index.ts"},startTime:new Date(Date.now()-5e3),state:"completed",output:"File content..."}],["tool-3",{toolCallId:"tool-3",name:"Grep",arguments:{pattern:"TODO",path:"src/"},startTime:new Date(Date.now()-3e3),state:"completed"}],["tool-4",{toolCallId:"tool-4",name:"Write",arguments:{file_path:"/src/new-file.ts"},startTime:new Date(Date.now()-1e3),state:"failed",error:"Permission denied"}],["tool-5",{toolCallId:"tool-5",name:"WebFetch",arguments:{url:"https://api.example.com/data"},startTime:new Date,state:"running"}]]);a(V=>({...V,messages:F,todoList:B,activeTools:H,isLoading:!0,loadingMessage:"Processing mock request..."}))},500);return()=>clearTimeout(k)},[]);let[y]=nd(()=>{let k={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:r,isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new Ro(k)});Ft(()=>{let k=o.messages.map(M=>({role:M.role,content:M.content,timestamp:new Date(M.timestamp||Date.now()),...M.tool&&{tool:M.tool},...M.toolOutput&&{toolOutput:M.toolOutput}}));y.setDelegate({messages:k,fullConversationHistory:k,isLoading:o.isLoading,currentInput:"",selectedModel:m.current,isVisionEnabled:p.current,conversationId:o.conversationId,usesCustomUI:!0,updateCurrentConversation:()=>{}})},[o.messages,o.isLoading,o.conversationId,y]);let w=Mn(null),C=La(async(k,M=[])=>{if(os.getExistingInstance()?.checkAndUpdate().catch(()=>{}),c.current){s.queueManager.addToQueue({content:k,imageUrls:M,attachments:[],model:m.current.name})||a(G=>({...G,messages:[...G.messages,{id:be(),role:"system",content:"[!] Queue is full (max 5 messages). Your input was not saved.",timestamp:Date.now()}]}));return}let F=Date.now(),B={id:be(),role:"user",content:k,timestamp:F},H={id:be(),role:"assistant",content:"",timestamp:F+1},V=[...l.current,B,H];a(W=>({...W,messages:V,isLoading:!0,loadingMessage:"Processing"}));let le=V.map(W=>({role:W.role,content:W.content,timestamp:new Date(W.timestamp||Date.now()),...W.tool&&{tool:W.tool},...W.toolOutput&&{toolOutput:W.toolOutput}}));y.setDelegate({messages:le,fullConversationHistory:le,isLoading:!1,currentInput:"",selectedModel:m.current,isVisionEnabled:p.current,conversationId:d.current,usesCustomUI:!0,updateCurrentConversation:()=>{}});try{await y.sendMessage(k,M.length>0?M:void 0)}catch(W){a(G=>({...G,messages:[...G.messages,{id:be(),role:"system",content:`Error: ${W.message}`,timestamp:Date.now()}],isLoading:!1}))}},[s.queueManager,y]);w.current=C;let T=cs(()=>({onConversationIdReceived:k=>{a(M=>({...M,conversationId:k.conversationId,conversationTitleGenerated:!!k.title}))},onMessagesUpdate:k=>{a(M=>({...M,messages:k(M.messages)}))},onActiveToolsUpdate:k=>{a(M=>({...M,activeTools:k(M.activeTools)}))},onLoadingChange:k=>{a(M=>({...M,isLoading:k,activeTools:k?M.activeTools:new Map,subAgentOperations:k?M.subAgentOperations:new Map}))},onLoadingMessageChange:k=>{a(M=>({...M,loadingMessage:k}))},onTodoUpdate:k=>{f(k)},onConfirmationRequest:k=>{a(M=>({...M,pendingConfirmation:k}))},onError:k=>{a(M=>({...M,messages:[...M.messages,{id:be(),role:"system",content:`Error: ${k}`,timestamp:Date.now()}],isLoading:!1,activeTools:new Map,subAgentOperations:new Map}))}}),[f]);Ku({personalAgent:s.personalAgent,frontendWS:s.frontendWS,handlers:T});let{regularQueuedMessages:x,crossDeviceTasks:v,processNextMessage:I,hasQueuedMessages:S}=Qu({queueManager:s.queueManager,frontendWS:s.frontendWS,crossDevice:s.crossDevice,isLoading:o.isLoading,selectedModel:m.current,onCrossDeviceTask:(k,M)=>{M&&w.current?.(M)}}),{subAgentOperations:E}=Ju({subAgentManager:s.subAgentManager});Ft(()=>{a(k=>({...k,subAgentOperations:E}))},[E]);let{externalSession:P}=Zu({frontendWS:s.frontendWS});Ft(()=>{a(k=>({...k,externalSession:P}))},[P]),Ft(()=>{if(!o.isLoading&&S){let k=I();k&&w.current?.(k.content)}},[o.isLoading,S,I]);let D=cs(()=>({addMessage:k=>{a(M=>({...M,messages:[...M.messages,k]}))},addSystemMessage:k=>{a(M=>({...M,messages:[...M.messages,{id:be(),role:"system",content:k,timestamp:Date.now()}]}))},updateMessages:k=>{a(M=>({...M,messages:k(M.messages)}))},setLoading:(k,M)=>{a(F=>({...F,isLoading:k,loadingMessage:M||F.loadingMessage}))},setConversationId:(k,M)=>{a(F=>({...F,conversationId:k,conversationTitleGenerated:!!M}))},clearChat:()=>{a(k=>({...k,messages:[{id:be(),role:"system",content:ls.clear(),timestamp:Date.now()}],todoList:null,conversationId:null,conversationTitleGenerated:!1,staticRemountKey:k.staticRemountKey+1}))},handleSubmit:C,handleConfirmationConfirm:k=>{let M=g.current?.id;M&&(a(F=>({...F,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:M,response:k,confirmed:!0}))},handleConfirmationDecline:()=>{let k=g.current?.id;k&&(a(M=>({...M,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:k,response:"n",confirmed:!1}),a(M=>({...M,messages:[...M.messages,{id:be(),role:"system",content:"[!] Action declined by user",timestamp:Date.now()}]})))},handleConfirmationTimeout:()=>{let k=g.current?.id;k&&(a(M=>({...M,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:k,response:"n",confirmed:!1,timedOut:!0}),a(M=>({...M,messages:[...M.messages,{id:be(),role:"system",content:"[!] Confirmation timed out - action declined",timestamp:Date.now()}]})))},stopStreaming:async()=>{await s.personalAgent.stopStreaming(),a(k=>({...k,isLoading:!1,activeTools:new Map,subAgentOperations:new Map,pendingConfirmation:null,messages:[...k.messages,{id:be(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))},createConversation:k=>{let M=Ye.createConversation(k);return a(F=>({...F,conversations:Ye.getConversations(),conversationId:M.id,conversationTitleGenerated:!1,messages:[{id:be(),role:"system",content:ls.newConversation(),timestamp:Date.now()}],todoList:null,staticRemountKey:F.staticRemountKey+1})),M},switchConversation:k=>{let M=d.current,F=l.current;if(M&&F.length>1)for(let H of F)H.role!=="system"&&Ye.addMessage(M,is.toStoredMessage(H));Ye.setCurrentConversation(k);let B=Ye.getMessages(k);a(H=>({...H,conversationId:k,messages:B.length>0?B.map(V=>is.fromStoredMessage(V)):[{id:be(),role:"system",content:ls.continueConversation(),timestamp:Date.now()}],staticRemountKey:H.staticRemountKey+1}))},deleteConversation:k=>{Ye.deleteConversation(k),a(M=>({...M,conversations:Ye.getConversations(),...M.conversationId===k?{conversationId:null,messages:[{id:be(),role:"system",content:ls.deleted(),timestamp:Date.now()}],staticRemountKey:M.staticRemountKey+1}:{}}))},updateConversationTitle:(k,M)=>{Ye.updateConversationTitle(k,M),a(F=>({...F,conversations:Ye.getConversations(),conversationTitleGenerated:!0}))}}),[C,s.personalAgent]),$=cs(()=>({regularQueuedMessages:x,crossDeviceTasks:v,hasQueuedMessages:S}),[x,v,S]),R=La(k=>{m.current=k},[]),_=La(k=>{p.current=k},[]),N=cs(()=>({state:o,actions:D,services:s,queue:$,projectPath:t}),[o,D,s,$,t]);return Ft(()=>{Lt._updateModelRef=R,Lt._updateVisionRef=_},[R,_]),as.createElement(Lt.Provider,{value:N},as.createElement(sd.Provider,{value:o},as.createElement(rd.Provider,{value:D},as.createElement(od.Provider,{value:s},as.createElement(id.Provider,{value:$},as.createElement(ad.Provider,{value:t},i))))))}function Rn(){let i=Nt(sd);if(i)return i;let e=Nt(Lt);if(!e)throw new Error("useChatState must be used within ChatProvider");return e.state}function xt(){let i=Nt(rd);if(i)return i;let e=Nt(Lt);if(!e)throw new Error("useChatActions must be used within ChatProvider");return e.actions}function Ba(){let i=Nt(od);if(i)return i;let e=Nt(Lt);if(!e)throw new Error("useChatServices must be used within ChatProvider");return e.services}function Wa(){let i=Nt(id);if(i)return i;let e=Nt(Lt);if(!e)throw new Error("useChatQueue must be used within ChatProvider");return e.queue}function Ha(){let i=Nt(ad);if(i)return i;let e=Nt(Lt);if(!e)throw new Error("useProjectPath must be used within ChatProvider");return e.projectPath}function cd(){return Lt}Kt();We();Sn();we();import _o,{createContext as Fo,useContext as ds,useState as Qb,useMemo as $o,useEffect as Jb,useRef as Zb}from"react";var ld=Fo(null),ud=Fo(null),dd=Fo(null),Lo=Fo(null);function Ga({children:i}){let e=$o(()=>me.find(l=>l.name===ye.string("selectedPersonalModel"))||me.find(l=>l.name==="snowx-c5")||me[0],[]),t=Zb(0),[n,s]=Qb({showHelp:!1,showModelMenu:!1,showCommandMenu:!1,selectedModel:e,isVisionEnabled:!1,showWizard:!1,wizard:{type:null,step:1,data:{}},operationalMode:"normal",toasts:[],isReverseSearchActive:!1}),r=xt();Jb(()=>{let l=cd();l._updateModelRef&&l._updateModelRef(n.selectedModel),l._updateVisionRef&&l._updateVisionRef(n.isVisionEnabled)},[n.selectedModel,n.isVisionEnabled]);let o=$o(()=>({email:X.getInstance().getUserEmail()||"User",tier:xe.getDisplayName(xe.getCurrentUserTier()),userTier:xe.getCurrentUserTier()}),[]),a=$o(()=>({toggleHelp:()=>s(l=>({...l,showHelp:!l.showHelp})),showHelp:()=>s(l=>({...l,showHelp:!0})),hideHelp:()=>s(l=>({...l,showHelp:!1})),toggleModelMenu:()=>s(l=>({...l,showModelMenu:!l.showModelMenu})),showModelMenu:()=>s(l=>({...l,showModelMenu:!0})),hideModelMenu:()=>s(l=>({...l,showModelMenu:!1})),toggleCommandMenu:()=>s(l=>({...l,showCommandMenu:!l.showCommandMenu})),showCommandMenu:()=>s(l=>({...l,showCommandMenu:!0})),hideCommandMenu:()=>s(l=>({...l,showCommandMenu:!1})),setModel:l=>{ye.set("selectedPersonalModel",l.name),s(d=>({...d,selectedModel:l,showModelMenu:!1})),r.addSystemMessage(`Switched to ${l.displayName}`)},toggleVision:()=>{s(l=>{let d=!l.isVisionEnabled;return r.addSystemMessage(`Vision mode ${d?"enabled":"disabled"}`),{...l,isVisionEnabled:d}})},closeAllModals:()=>s(l=>({...l,showHelp:!1,showModelMenu:!1,showCommandMenu:!1,showWizard:!1})),showDiscordWizard:()=>s(l=>({...l,showWizard:!0,showCommandMenu:!1,wizard:{type:"discord",step:1,data:{}}})),showTelegramWizard:()=>s(l=>({...l,showWizard:!0,showCommandMenu:!1,wizard:{type:"telegram",step:1,data:{}}})),hideWizard:()=>s(l=>({...l,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setWizardStep:l=>s(d=>({...d,wizard:{...d.wizard,step:l}})),setWizardData:(l,d)=>s(g=>({...g,wizard:{...g.wizard,data:{...g.wizard.data,[l]:d}}})),resetWizard:()=>s(l=>({...l,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setMode:l=>{s(d=>({...d,operationalMode:l})),l!=="normal"&&r.addSystemMessage(`Switched to ${l.toUpperCase()} mode`)},toggleYoloMode:()=>{s(l=>{let d=l.operationalMode==="yolo"?"normal":"yolo";return d==="yolo"?r.addSystemMessage("YOLO mode enabled - all actions will be auto-approved"):r.addSystemMessage("YOLO mode disabled"),{...l,operationalMode:d}})},togglePlanMode:()=>{s(l=>{let d=l.operationalMode==="plan"?"normal":"plan";return d==="plan"?r.addSystemMessage("PLAN mode enabled - planning only, no execution"):r.addSystemMessage("PLAN mode disabled"),{...l,operationalMode:d}})},showToast:(l,d="info",g)=>{let m=`toast-${Date.now()}-${t.current++}`;s(p=>({...p,toasts:[...p.toasts,{id:m,message:l,type:d,duration:g}]}))},removeToast:l=>{s(d=>({...d,toasts:d.toasts.filter(g=>g.id!==l)}))},clearToasts:()=>{s(l=>({...l,toasts:[]}))},startReverseSearch:()=>{s(l=>({...l,isReverseSearchActive:!0,showHelp:!1,showModelMenu:!1,showCommandMenu:!1}))},stopReverseSearch:()=>{s(l=>({...l,isReverseSearchActive:!1}))}}),[r]),c=$o(()=>({state:n,actions:a,info:o}),[n,a,o]);return _o.createElement(ud.Provider,{value:a},_o.createElement(ld.Provider,{value:n},_o.createElement(dd.Provider,{value:o},_o.createElement(Lo.Provider,{value:c},i))))}function gs(){let i=ds(ld);if(i)return i;let e=ds(Lo);if(!e)throw new Error("useUIState must be used within UIProvider");return e.state}function Ut(){let i=ds(ud);if(i)return i;let e=ds(Lo);if(!e)throw new Error("useUIActions must be used within UIProvider");return e.actions}function or(){let i=ds(dd);if(i)return i;let e=ds(Lo);if(!e)throw new Error("useUIInfo must be used within UIProvider");return e.info}function ja(){let i=gs();return{...i.wizard,isOpen:i.showWizard}}import sy,{createContext as ry,useContext as wd,useState as oy,useMemo as vd,useRef as Sd}from"react";import Bo from"path";import za from"fs";import On from"path";import ey from"os";var pd={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".ico":"image/x-icon",".tiff":"image/tiff",".tif":"image/tiff",".avif":"image/avif",".heic":"image/heic",".heif":"image/heif"},hd=Object.keys(pd),ty=[...hd,".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"],gd=20*1024*1024,md=1*1024*1024;function ln(i){return i<1024?`${i}B`:i<1024*1024?`${(i/1024).toFixed(1)}KB`:`${(i/(1024*1024)).toFixed(1)}MB`}function qa(i,e=30){if(i.length<=e)return i;let t=On.extname(i);return On.basename(i,t).slice(0,e-t.length-3)+"..."+t}function fd(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(`
|
|
1951
|
-
`))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=
|
|
1952
|
-
`);n.current+=1;let d="text",g,m;if(c.isFilePath){c.isImage?d="image_path":c.isBinary?(d="file_path",m="Binary file - cannot read as text"):d="file_path";let p=
|
|
1954
|
+
- Item 3`,timestamp:Date.now()+600+le*100}))],B={todos:[{id:"todo-1",content:"Setup project structure",status:"completed",activeForm:"Setting up project structure"},{id:"todo-2",content:"Implement core features",status:"completed",activeForm:"Implementing core features"},{id:"todo-3",content:"Add authentication",status:"in_progress",activeForm:"Adding authentication"},{id:"todo-4",content:"Write unit tests",status:"pending",activeForm:"Writing unit tests"},{id:"todo-5",content:"Setup CI/CD pipeline",status:"pending",activeForm:"Setting up CI/CD"},{id:"todo-6",content:"Deploy to production",status:"pending",activeForm:"Deploying to production"}],timestamp:new Date},H=new Map([["tool-1",{toolCallId:"tool-1",name:"Bash",arguments:{command:"npm install",description:"Install dependencies"},startTime:new Date,state:"running"}],["tool-2",{toolCallId:"tool-2",name:"Read",arguments:{file_path:"/src/index.ts"},startTime:new Date(Date.now()-5e3),state:"completed",output:"File content..."}],["tool-3",{toolCallId:"tool-3",name:"Grep",arguments:{pattern:"TODO",path:"src/"},startTime:new Date(Date.now()-3e3),state:"completed"}],["tool-4",{toolCallId:"tool-4",name:"Write",arguments:{file_path:"/src/new-file.ts"},startTime:new Date(Date.now()-1e3),state:"failed",error:"Permission denied"}],["tool-5",{toolCallId:"tool-5",name:"WebFetch",arguments:{url:"https://api.example.com/data"},startTime:new Date,state:"running"}]]);a(V=>({...V,messages:F,todoList:B,activeTools:H,isLoading:!0,loadingMessage:"Processing mock request..."}))},500);return()=>clearTimeout(k)},[]);let[y]=id(()=>{let k={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:r,isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new No(k)});Ft(()=>{let k=o.messages.map(M=>({role:M.role,content:M.content,timestamp:new Date(M.timestamp||Date.now()),...M.tool&&{tool:M.tool},...M.toolOutput&&{toolOutput:M.toolOutput}}));y.setDelegate({messages:k,fullConversationHistory:k,isLoading:o.isLoading,currentInput:"",selectedModel:m.current,isVisionEnabled:p.current,conversationId:o.conversationId,usesCustomUI:!0,updateCurrentConversation:()=>{}})},[o.messages,o.isLoading,o.conversationId,y]);let T=Rn(null),x=Wa(async(k,M=[])=>{if(os.getExistingInstance()?.checkAndUpdate().catch(()=>{}),c.current){s.queueManager.addToQueue({content:k,imageUrls:M,attachments:[],model:m.current.name})||a(G=>({...G,messages:[...G.messages,{id:be(),role:"system",content:"[!] Queue is full (max 5 messages). Your input was not saved.",timestamp:Date.now()}]}));return}let F=Date.now(),B={id:be(),role:"user",content:k,timestamp:F},H={id:be(),role:"assistant",content:"",timestamp:F+1},V=[...l.current,B,H];a(W=>({...W,messages:V,isLoading:!0,loadingMessage:"Processing"}));let le=V.map(W=>({role:W.role,content:W.content,timestamp:new Date(W.timestamp||Date.now()),...W.tool&&{tool:W.tool},...W.toolOutput&&{toolOutput:W.toolOutput}}));y.setDelegate({messages:le,fullConversationHistory:le,isLoading:!1,currentInput:"",selectedModel:m.current,isVisionEnabled:p.current,conversationId:d.current,usesCustomUI:!0,updateCurrentConversation:()=>{}});try{await y.sendMessage(k,M.length>0?M:void 0)}catch(W){a(G=>({...G,messages:[...G.messages,{id:be(),role:"system",content:`Error: ${W.message}`,timestamp:Date.now()}],isLoading:!1}))}},[s.queueManager,y]);T.current=x;let S=cs(()=>({onConversationIdReceived:k=>{a(M=>({...M,conversationId:k.conversationId,conversationTitleGenerated:!!k.title}))},onMessagesUpdate:k=>{a(M=>({...M,messages:k(M.messages)}))},onActiveToolsUpdate:k=>{a(M=>({...M,activeTools:k(M.activeTools)}))},onLoadingChange:k=>{a(M=>({...M,isLoading:k,activeTools:k?M.activeTools:new Map,subAgentOperations:k?M.subAgentOperations:new Map}))},onLoadingMessageChange:k=>{a(M=>({...M,loadingMessage:k}))},onTodoUpdate:k=>{f(k)},onConfirmationRequest:k=>{a(M=>({...M,pendingConfirmation:k}))},onError:k=>{a(M=>({...M,messages:[...M.messages,{id:be(),role:"system",content:`Error: ${k}`,timestamp:Date.now()}],isLoading:!1,activeTools:new Map,subAgentOperations:new Map}))}}),[f]);Qu({personalAgent:s.personalAgent,frontendWS:s.frontendWS,handlers:S});let{regularQueuedMessages:C,crossDeviceTasks:v,processNextMessage:I,hasQueuedMessages:w}=td({queueManager:s.queueManager,frontendWS:s.frontendWS,crossDevice:s.crossDevice,isLoading:o.isLoading,selectedModel:m.current,onCrossDeviceTask:(k,M)=>{M&&T.current?.(M)}}),{subAgentOperations:E}=nd({subAgentManager:s.subAgentManager});Ft(()=>{a(k=>({...k,subAgentOperations:E}))},[E]);let{externalSession:P}=sd({frontendWS:s.frontendWS});Ft(()=>{a(k=>({...k,externalSession:P}))},[P]),Ft(()=>{if(!o.isLoading&&w){let k=I();k&&T.current?.(k.content)}},[o.isLoading,w,I]);let D=cs(()=>({addMessage:k=>{a(M=>({...M,messages:[...M.messages,k]}))},addSystemMessage:k=>{a(M=>({...M,messages:[...M.messages,{id:be(),role:"system",content:k,timestamp:Date.now()}]}))},updateMessages:k=>{a(M=>({...M,messages:k(M.messages)}))},setLoading:(k,M)=>{a(F=>({...F,isLoading:k,loadingMessage:M||F.loadingMessage}))},setConversationId:(k,M)=>{a(F=>({...F,conversationId:k,conversationTitleGenerated:!!M}))},clearChat:()=>{a(k=>({...k,messages:[{id:be(),role:"system",content:ls.clear(),timestamp:Date.now()}],todoList:null,conversationId:null,conversationTitleGenerated:!1,staticRemountKey:k.staticRemountKey+1}))},handleSubmit:x,handleConfirmationConfirm:k=>{let M=g.current?.id;M&&(a(F=>({...F,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:M,response:k,confirmed:!0}))},handleConfirmationDecline:()=>{let k=g.current?.id;k&&(a(M=>({...M,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:k,response:"n",confirmed:!1}),a(M=>({...M,messages:[...M.messages,{id:be(),role:"system",content:"[!] Action declined by user",timestamp:Date.now()}]})))},handleConfirmationTimeout:()=>{let k=g.current?.id;k&&(a(M=>({...M,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:k,response:"n",confirmed:!1,timedOut:!0}),a(M=>({...M,messages:[...M.messages,{id:be(),role:"system",content:"[!] Confirmation timed out - action declined",timestamp:Date.now()}]})))},stopStreaming:async()=>{await s.personalAgent.stopStreaming(),a(k=>({...k,isLoading:!1,activeTools:new Map,subAgentOperations:new Map,pendingConfirmation:null,messages:[...k.messages,{id:be(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))},createConversation:k=>{let M=Qe.createConversation(k);return a(F=>({...F,conversations:Qe.getConversations(),conversationId:M.id,conversationTitleGenerated:!1,messages:[{id:be(),role:"system",content:ls.newConversation(),timestamp:Date.now()}],todoList:null,staticRemountKey:F.staticRemountKey+1})),M},switchConversation:k=>{let M=d.current,F=l.current;if(M&&F.length>1)for(let H of F)H.role!=="system"&&Qe.addMessage(M,is.toStoredMessage(H));Qe.setCurrentConversation(k);let B=Qe.getMessages(k);a(H=>({...H,conversationId:k,messages:B.length>0?B.map(V=>is.fromStoredMessage(V)):[{id:be(),role:"system",content:ls.continueConversation(),timestamp:Date.now()}],staticRemountKey:H.staticRemountKey+1}))},deleteConversation:k=>{Qe.deleteConversation(k),a(M=>({...M,conversations:Qe.getConversations(),...M.conversationId===k?{conversationId:null,messages:[{id:be(),role:"system",content:ls.deleted(),timestamp:Date.now()}],staticRemountKey:M.staticRemountKey+1}:{}}))},updateConversationTitle:(k,M)=>{Qe.updateConversationTitle(k,M),a(F=>({...F,conversations:Qe.getConversations(),conversationTitleGenerated:!0}))}}),[x,s.personalAgent]),$=cs(()=>({regularQueuedMessages:C,crossDeviceTasks:v,hasQueuedMessages:w}),[C,v,w]),R=Wa(k=>{m.current=k},[]),_=Wa(k=>{p.current=k},[]),N=cs(()=>({state:o,actions:D,services:s,queue:$,projectPath:t}),[o,D,s,$,t]);return Ft(()=>{Lt._updateModelRef=R,Lt._updateVisionRef=_},[R,_]),as.createElement(Lt.Provider,{value:N},as.createElement(ad.Provider,{value:o},as.createElement(cd.Provider,{value:D},as.createElement(ld.Provider,{value:s},as.createElement(ud.Provider,{value:$},as.createElement(dd.Provider,{value:t},i))))))}function On(){let i=Nt(ad);if(i)return i;let e=Nt(Lt);if(!e)throw new Error("useChatState must be used within ChatProvider");return e.state}function xt(){let i=Nt(cd);if(i)return i;let e=Nt(Lt);if(!e)throw new Error("useChatActions must be used within ChatProvider");return e.actions}function Ga(){let i=Nt(ld);if(i)return i;let e=Nt(Lt);if(!e)throw new Error("useChatServices must be used within ChatProvider");return e.services}function ja(){let i=Nt(ud);if(i)return i;let e=Nt(Lt);if(!e)throw new Error("useChatQueue must be used within ChatProvider");return e.queue}function za(){let i=Nt(dd);if(i)return i;let e=Nt(Lt);if(!e)throw new Error("useProjectPath must be used within ChatProvider");return e.projectPath}function gd(){return Lt}Kt();He();Sn();Te();import Fo,{createContext as Uo,useContext as ds,useState as sy,useMemo as Lo,useEffect as ry,useRef as oy}from"react";var md=Uo(null),pd=Uo(null),hd=Uo(null),Bo=Uo(null);function qa({children:i}){let e=Lo(()=>me.find(l=>l.name===ye.string("selectedPersonalModel"))||me.find(l=>l.name==="snowx-c5")||me[0],[]),t=oy(0),[n,s]=sy({showHelp:!1,showModelMenu:!1,showCommandMenu:!1,selectedModel:e,isVisionEnabled:!1,showWizard:!1,wizard:{type:null,step:1,data:{}},operationalMode:"normal",toasts:[],isReverseSearchActive:!1}),r=xt();ry(()=>{let l=gd();l._updateModelRef&&l._updateModelRef(n.selectedModel),l._updateVisionRef&&l._updateVisionRef(n.isVisionEnabled)},[n.selectedModel,n.isVisionEnabled]);let o=Lo(()=>({email:X.getInstance().getUserEmail()||"User",tier:xe.getDisplayName(xe.getCurrentUserTier()),userTier:xe.getCurrentUserTier()}),[]),a=Lo(()=>({toggleHelp:()=>s(l=>({...l,showHelp:!l.showHelp})),showHelp:()=>s(l=>({...l,showHelp:!0})),hideHelp:()=>s(l=>({...l,showHelp:!1})),toggleModelMenu:()=>s(l=>({...l,showModelMenu:!l.showModelMenu})),showModelMenu:()=>s(l=>({...l,showModelMenu:!0})),hideModelMenu:()=>s(l=>({...l,showModelMenu:!1})),toggleCommandMenu:()=>s(l=>({...l,showCommandMenu:!l.showCommandMenu})),showCommandMenu:()=>s(l=>({...l,showCommandMenu:!0})),hideCommandMenu:()=>s(l=>({...l,showCommandMenu:!1})),setModel:l=>{ye.set("selectedPersonalModel",l.name),s(d=>({...d,selectedModel:l,showModelMenu:!1})),r.addSystemMessage(`Switched to ${l.displayName}`)},toggleVision:()=>{s(l=>{let d=!l.isVisionEnabled;return r.addSystemMessage(`Vision mode ${d?"enabled":"disabled"}`),{...l,isVisionEnabled:d}})},closeAllModals:()=>s(l=>({...l,showHelp:!1,showModelMenu:!1,showCommandMenu:!1,showWizard:!1})),showDiscordWizard:()=>s(l=>({...l,showWizard:!0,showCommandMenu:!1,wizard:{type:"discord",step:1,data:{}}})),showTelegramWizard:()=>s(l=>({...l,showWizard:!0,showCommandMenu:!1,wizard:{type:"telegram",step:1,data:{}}})),hideWizard:()=>s(l=>({...l,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setWizardStep:l=>s(d=>({...d,wizard:{...d.wizard,step:l}})),setWizardData:(l,d)=>s(g=>({...g,wizard:{...g.wizard,data:{...g.wizard.data,[l]:d}}})),resetWizard:()=>s(l=>({...l,showWizard:!1,wizard:{type:null,step:1,data:{}}})),setMode:l=>{s(d=>({...d,operationalMode:l})),l!=="normal"&&r.addSystemMessage(`Switched to ${l.toUpperCase()} mode`)},toggleYoloMode:()=>{s(l=>{let d=l.operationalMode==="yolo"?"normal":"yolo";return d==="yolo"?r.addSystemMessage("YOLO mode enabled - all actions will be auto-approved"):r.addSystemMessage("YOLO mode disabled"),{...l,operationalMode:d}})},togglePlanMode:()=>{s(l=>{let d=l.operationalMode==="plan"?"normal":"plan";return d==="plan"?r.addSystemMessage("PLAN mode enabled - planning only, no execution"):r.addSystemMessage("PLAN mode disabled"),{...l,operationalMode:d}})},showToast:(l,d="info",g)=>{let m=`toast-${Date.now()}-${t.current++}`;s(p=>({...p,toasts:[...p.toasts,{id:m,message:l,type:d,duration:g}]}))},removeToast:l=>{s(d=>({...d,toasts:d.toasts.filter(g=>g.id!==l)}))},clearToasts:()=>{s(l=>({...l,toasts:[]}))},startReverseSearch:()=>{s(l=>({...l,isReverseSearchActive:!0,showHelp:!1,showModelMenu:!1,showCommandMenu:!1}))},stopReverseSearch:()=>{s(l=>({...l,isReverseSearchActive:!1}))}}),[r]),c=Lo(()=>({state:n,actions:a,info:o}),[n,a,o]);return Fo.createElement(pd.Provider,{value:a},Fo.createElement(md.Provider,{value:n},Fo.createElement(hd.Provider,{value:o},Fo.createElement(Bo.Provider,{value:c},i))))}function gs(){let i=ds(md);if(i)return i;let e=ds(Bo);if(!e)throw new Error("useUIState must be used within UIProvider");return e.state}function Ut(){let i=ds(pd);if(i)return i;let e=ds(Bo);if(!e)throw new Error("useUIActions must be used within UIProvider");return e.actions}function or(){let i=ds(hd);if(i)return i;let e=ds(Bo);if(!e)throw new Error("useUIInfo must be used within UIProvider");return e.info}function Ka(){let i=gs();return{...i.wizard,isOpen:i.showWizard}}import ly,{createContext as uy,useContext as Ed,useState as dy,useMemo as xd,useRef as Cd}from"react";import Ho from"path";import Va from"fs";import Nn from"path";import iy 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"},vd=Object.keys(yd),ay=[...vd,".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"],fd=20*1024*1024,bd=1*1024*1024;function ln(i){return i<1024?`${i}B`:i<1024*1024?`${(i/1024).toFixed(1)}KB`:`${(i/(1024*1024)).toFixed(1)}MB`}function Xa(i,e=30){if(i.length<=e)return i;let t=Nn.extname(i);return Nn.basename(i,t).slice(0,e-t.length-3)+"..."+t}function Sd(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(`
|
|
1955
|
+
`))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=Nn.extname(a),l=vd.includes(c),d=ay.includes(c);return{isFilePath:!0,isImage:l,isBinary:d,path:e}}function cy(i){return i.startsWith("~/")?Nn.join(iy.homedir(),i.slice(2)):i}function Ya(i){let e=cy(i);return Nn.isAbsolute(e)?e:Nn.resolve(process.cwd(),e)}function Wo(i){try{let e=Ya(i),t=Va.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 wd(i){try{let e=Ya(i),t=Wo(i);if(!t.exists)return{data:null,error:t.error};if(t.size>fd)return{data:null,error:`Image too large (${ln(t.size)}, max ${ln(fd)})`};let n=Va.readFileSync(e),s=Nn.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 Td(i){try{let e=Ya(i),t=Wo(i);return t.exists?t.size>bd?{content:null,error:`File too large (${ln(t.size)}, max ${ln(bd)})`}:{content:Va.readFileSync(e,"utf8")}:{content:null,error:t.error}}catch(e){return{content:null,error:e.message}}}var gy=100,my=50,Qa=uy(null);function Ja({children:i}){let[e,t]=dy({input:"",cursorPosition:0,pastedTexts:[],isProcessingFiles:!1,suggestion:null,history:[],historyIndex:-1,tempInput:"",undoStack:[],redoStack:[]}),n=Cd(0),s=Cd(null),r=xd(()=>({setInput:a=>{t(c=>({...c,input:a,cursorPosition:a.length}))},setCursor:a=>{t(c=>({...c,cursorPosition:Math.max(0,Math.min(a,c.input.length))}))},insertAtCursor:a=>{t(c=>{let l=c.input.slice(0,c.cursorPosition)+a+c.input.slice(c.cursorPosition);return{...c,input:l,cursorPosition:c.cursorPosition+a.length}})},deleteAtCursor:()=>{t(a=>{if(a.input===""&&a.pastedTexts.length>0)return{...a,pastedTexts:a.pastedTexts.slice(0,-1)};if(a.cursorPosition===0)return a;let c=a.input.slice(0,a.cursorPosition-1)+a.input.slice(a.cursorPosition);return{...a,input:c,cursorPosition:a.cursorPosition-1}})},clearInput:()=>{t(a=>({...a,input:"",cursorPosition:0,pastedTexts:[],suggestion:null}))},moveCursorLeft:()=>{t(a=>({...a,cursorPosition:Math.max(0,a.cursorPosition-1)}))},moveCursorRight:()=>{t(a=>({...a,cursorPosition:Math.min(a.input.length,a.cursorPosition+1)}))},moveCursorToStart:()=>{t(a=>({...a,cursorPosition:0}))},moveCursorToEnd:()=>{t(a=>({...a,cursorPosition:a.input.length}))},addPastedContent:a=>{let c=Sd(a),l=a.split(`
|
|
1956
|
+
`);n.current+=1;let d="text",g,m;if(c.isFilePath){c.isImage?d="image_path":c.isBinary?(d="file_path",m="Binary file - cannot read as text"):d="file_path";let p=Wo(c.path);p.exists?g=p.size:m=p.error}t(p=>({...p,pastedTexts:[...p.pastedTexts,{id:n.current,content:a,lineCount:l.length,type:d,filePath:c.isFilePath?c.path:void 0,fileSize:g,error:m}]}))},addClipboardImage:(a,c)=>{n.current+=1,t(l=>({...l,pastedTexts:[...l.pastedTexts,{id:n.current,content:"Clipboard image",lineCount:1,type:"clipboard_image",imageData:a,fileSize:c}]}))},clearPastedTexts:()=>{t(a=>({...a,pastedTexts:[]}))},removeLastPaste:()=>{t(a=>({...a,pastedTexts:a.pastedTexts.slice(0,-1)}))},processFilesForSubmit:async()=>{t(a=>({...a,isProcessingFiles:!0}));try{let a=e,c=a.pastedTexts.filter(S=>S.type==="image_path"&&S.filePath),l=a.pastedTexts.filter(S=>S.type==="clipboard_image"&&S.imageData),d=a.pastedTexts.filter(S=>S.type==="file_path"&&S.filePath),g=a.pastedTexts.filter(S=>S.type==="text"),m=[],p=[],h=[];for(let S of d)if(S.filePath&&!S.error){let C=Td(S.filePath);if(C.content){let v=Ho.basename(S.filePath),I=Ho.extname(v).slice(1)||"text";p.push(`[File: ${v}]
|
|
1953
1957
|
\`\`\`${I}
|
|
1954
|
-
${
|
|
1955
|
-
\`\`\``)}else
|
|
1958
|
+
${C.content}
|
|
1959
|
+
\`\`\``)}else C.error&&h.push(`${Ho.basename(S.filePath)}: ${C.error}`)}for(let S of c)if(S.filePath&&!S.error){let C=await wd(S.filePath);C.data?m.push(C.data):C.error&&h.push(`${Ho.basename(S.filePath)}: ${C.error}`)}for(let S of l)S.imageData&&!S.error&&m.push(S.imageData);let f=g.map(S=>S.content).join(`
|
|
1956
1960
|
|
|
1957
1961
|
`),y=p.join(`
|
|
1958
1962
|
|
|
1959
|
-
`),
|
|
1963
|
+
`),T=[f,y].filter(Boolean).join(`
|
|
1960
1964
|
|
|
1961
|
-
`);return{fullInput:
|
|
1965
|
+
`);return{fullInput:T?a.input.trim()?`${T}
|
|
1962
1966
|
|
|
1963
|
-
${a.input}`:w:a.input,imageUrls:m,errors:h}}finally{t(a=>({...a,isProcessingFiles:!1}))}},setSuggestion:a=>{t(c=>({...c,suggestion:a}))},acceptSuggestion:()=>{t(a=>{if(!a.suggestion)return a;let c=a.suggestion.startsWith(a.input)?a.suggestion.slice(a.input.length):a.suggestion,l=a.input+c;return{...a,input:l,cursorPosition:l.length,suggestion:null}})},addToHistory:a=>{a.trim()&&t(c=>{if(c.history.length>0&&c.history[c.history.length-1]===a)return c;let l=[...c.history,a];return l.length>iy&&l.shift(),{...c,history:l,historyIndex:-1,tempInput:""}})},navigateHistoryUp:()=>{let a=!1;return t(c=>{if(c.history.length===0)return c;if(c.historyIndex===-1){let l=c.history.length-1;return a=!0,{...c,tempInput:c.input,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}if(c.historyIndex>0){let l=c.historyIndex-1;return a=!0,{...c,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}return c}),a},navigateHistoryDown:()=>{let a=!1;return t(c=>{if(c.historyIndex===-1)return c;if(c.historyIndex>=c.history.length-1)return a=!0,{...c,historyIndex:-1,input:c.tempInput,cursorPosition:c.tempInput.length,tempInput:""};let l=c.historyIndex+1;return a=!0,{...c,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}),a},resetHistoryNavigation:()=>{t(a=>({...a,historyIndex:-1,tempInput:""}))},saveUndoState:()=>{t(a=>{let c={input:a.input,cursorPosition:a.cursorPosition};if(s.current&&s.current.input===c.input)return a;s.current=c;let l=[...a.undoStack,c];return l.length>ay&&l.shift(),{...a,undoStack:l,redoStack:[]}})},undo:()=>{let a=!1;return t(c=>{if(c.undoStack.length===0)return c;let l={input:c.input,cursorPosition:c.cursorPosition},d=[...c.undoStack],g=d.pop();return a=!0,{...c,input:g.input,cursorPosition:g.cursorPosition,undoStack:d,redoStack:[...c.redoStack,l]}}),a},redo:()=>{let a=!1;return t(c=>{if(c.redoStack.length===0)return c;let l={input:c.input,cursorPosition:c.cursorPosition},d=[...c.redoStack],g=d.pop();return a=!0,{...c,input:g.input,cursorPosition:g.cursorPosition,undoStack:[...c.undoStack,l],redoStack:d}}),a}}),[e]),o=vd(()=>({state:e,actions:r}),[e,r]);return sy.createElement(Va.Provider,{value:o},i)}function ir(){let i=wd(Va);if(!i)throw new Error("useInputState must be used within InputProvider");return i.state}function Nn(){let i=wd(Va);if(!i)throw new Error("useInputActions must be used within InputProvider");return i.actions}import uy,{createContext as dy,useContext as HR,useCallback as Ho,useRef as xd,useEffect as gy}from"react";import{EventEmitter as ly}from"events";function Td(){process.stdout.write("\x1B[?1006l\x1B[?1002l")}var Wo=new ly;Wo.setMaxListeners(50);var my=dy(null);function Ya({children:i,enableMouse:e=!0}){let t=xd(new Set),n=xd(new Set),s=Ho(c=>{t.current.add(c)},[]),r=Ho(c=>{t.current.delete(c)},[]),o=Ho(c=>{n.current.add(c)},[]),a=Ho(c=>{n.current.delete(c)},[]);return gy(()=>{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 Wo.on("mouse",c),()=>{Wo.off("mouse",c)}},[e]),uy.createElement(my.Provider,{value:{subscribe:s,unsubscribe:r,subscribeScroll:o,unsubscribeScroll:a,isMouseEnabled:e}},i)}import Cd,{createContext as Id,useContext as qR,useState as py,useCallback as Go,useMemo as Ed}from"react";var hy=Id(null),fy=Id(null);function Qa({children:i}){let[e,t]=py(new Set),n=Go(l=>{t(d=>{if(d.has(l))return d;let g=new Set(d);return g.add(l),g})},[]),s=Go(l=>{t(d=>{if(!d.has(l))return d;let g=new Set(d);return g.delete(l),g})},[]),r=Go(()=>{t(new Set)},[]),o=Go(l=>e.has(l),[e]),a=Ed(()=>({overflowingIds:e,hasOverflow:e.size>0}),[e]),c=Ed(()=>({markOverflowing:n,clearOverflowing:s,clearAll:r,isOverflowing:o}),[n,s,r,o]);return Cd.createElement(fy.Provider,{value:c},Cd.createElement(hy.Provider,{value:a},i))}import kd,{createContext as Ad,useContext as XR,useState as by,useCallback as jo,useMemo as yy,useRef as vy}from"react";function Sy(i,e){return i.modelName===e.modelName&&i.requestCount===e.requestCount&&i.totalTokens===e.totalTokens&&Math.abs(i.averageLatency-e.averageLatency)<.01}function wy(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 zo(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||!Sy(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||!wy(n,s))return!1}return!0}var Ty=Ad(null),xy=Ad(null);function Pd(){let i=Date.now();return{promptCount:0,lastPromptTokenCount:0,totalInputTokens:0,totalOutputTokens:0,sessionStartTime:i,lastActivityTime:i,modelMetrics:new Map,toolCallStats:new Map}}function Ja({children:i}){let[e,t]=by(Pd),n=vy(e),s=jo(l=>{t(d=>{let g={...d,promptCount:d.promptCount+1,lastPromptTokenCount:l,lastActivityTime:Date.now()};return zo(d,g)?d:g})},[]),r=jo((l,d,g,m)=>{t(p=>{let h=new Map(p.modelMetrics),f=h.get(l);if(f){let w=f.requestCount+1,C=f.totalTokens+d+g,T=(f.averageLatency*f.requestCount+m)/w;h.set(l,{modelName:l,requestCount:w,totalTokens:C,averageLatency:T})}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 zo(p,y)?p:y})},[]),o=jo((l,d,g)=>{t(m=>{let p=new Map(m.toolCallStats),h=p.get(l);if(h){let y=h.callCount+1,w=(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:w})}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 zo(m,f)?m:f})},[]),a=jo(()=>{t(Pd())},[]),c=yy(()=>({recordPrompt:s,recordModelUsage:r,recordToolCall:o,resetSession:a}),[s,r,o,a]);return kd.createElement(xy.Provider,{value:c},kd.createElement(Ty.Provider,{value:e},i))}import Cy,{createContext as Ey,useContext as ZR,useState as Dd,useEffect as Md,useCallback as ar,useMemo as Rd,useRef as Za}from"react";var cr={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}},Od={fps:60,frameTime:16.67,memoryUsageMB:0,memoryPressure:"normal",totalRenders:0,avgRenderTime:0,peakRenderTime:0,isDegraded:!1,performanceLevel:"high"},Iy=Ey(null);function ec({children:i,initialLevel:e,enableAdaptive:t=!0,memoryWarningMB:n=150,memoryCriticalMB:s=250}){let[r,o]=Dd(Od),[a,c]=Dd(cr[e||"high"]),l=Za([]),d=Za([]),g=Za(0),m=ar(T=>{let x=Date.now();l.current.push(T),l.current.length>100&&l.current.shift(),d.current.push(x);let v=x-1e3;d.current=d.current.filter(I=>I>v),o(I=>{let S=l.current,E=S.length>0?S.reduce((R,_)=>R+_,0)/S.length:0,P=Math.max(I.peakRenderTime,T),D=d.current.length,$=D>0?1e3/D:16.67;return{...I,totalRenders:I.totalRenders+1,avgRenderTime:E,peakRenderTime:P,fps:D,frameTime:$,isDegraded:E>16||D<30}})},[]);Md(()=>{let T=()=>{if(typeof process<"u"&&process.memoryUsage){let I=process.memoryUsage().heapUsed/1024/1024,S="normal";I>=s?S="critical":I>=n&&(S="warning"),o(E=>({...E,memoryUsageMB:I,memoryPressure:S}))}};T();let x=setInterval(T,5e3);return()=>clearInterval(x)},[n,s]),Md(()=>{if(!t)return;let T=r.performanceLevel;r.memoryPressure==="critical"||r.fps<15?T="minimal":r.memoryPressure==="warning"||r.fps<30||r.avgRenderTime>32?T="low":r.fps<45||r.avgRenderTime>20?T="medium":r.fps>=55&&r.avgRenderTime<12&&r.memoryPressure==="normal"&&(T="high"),T!==r.performanceLevel&&(o(x=>({...x,performanceLevel:T})),c(cr[T]))},[t,r.fps,r.avgRenderTime,r.memoryPressure,r.performanceLevel]);let p=ar(T=>{o(x=>({...x,performanceLevel:T})),c(cr[T])},[]),h=ar(()=>{l.current=[],d.current=[],o(T=>({...Od,performanceLevel:T.performanceLevel}))},[]),f=ar((T,x)=>{c(v=>({...v,[T]:x}))},[]),y=ar(T=>{c(cr[T])},[]),w=Rd(()=>({recordRender:m,setPerformanceLevel:p,resetMetrics:h,updateSetting:f,applyPreset:y}),[m,p,h,f,y]),C=Rd(()=>({state:{metrics:r,settings:a},actions:w}),[r,a,w]);return Cy.createElement(Iy.Provider,{value:C},i)}function Nd({children:i,initialProjectPath:e}){return _n.createElement(ec,{enableAdaptive:!0,memoryWarningMB:150,memoryCriticalMB:250},_n.createElement(Ja,null,_n.createElement(Ya,{enableMouse:!1},_n.createElement(Qa,null,_n.createElement(Ua,{initialProjectPath:e},_n.createElement(Ga,null,_n.createElement(Xa,null,i)))))))}import dO,{createContext as ky,useContext as gO,useCallback as mO,useState as pO,useEffect as hO,useMemo as fO}from"react";var bO=ky(null);import SO,{createContext as _d,useContext as wO,useCallback as TO,useState as xO,useMemo as CO,useRef as EO}from"react";var IO=_d(null),kO=_d(null);import DO,{createContext as Py,useCallback as MO,useContext as RO,useEffect as OO,useMemo as NO,useRef as _O,useState as $O}from"react";var FO=Py(null);import WO,{createContext as Yy,useContext as HO,useEffect as GO,useState as jO,useMemo as zO,useCallback as qO}from"react";import*as nc from"node:fs";var Ay="\x1B[?u",$d="\x1B]11;?\x1B\\",Dy="\x1B[>q",My="\x1B[c",Ry="\x1B[>4;?m",Oy="\x1B[8m",Ny="\x1B[2K\r",_y="\x1B[0m",$y="\x1B[>u",Fy="\x1B[<u",Ly="\x1B[?2004h",Uy="\x1B[?2004l",By="\x1B[>4;2m",Wy="\x1B[>4;0m",Hy="\x1B[<u\x1B[>4;0m\x1B[?2004l",Gy=/\x1b\[\?(\d+)u/,jy=/\x1bP>\|(.+?)(\x1b\\|\x07)/,zy=/\x1b\[\?(\d+)(;\d+)*c/,qy=/\x1b\]11;rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})(\x1b\\|\x07)/,Ky=/\x1b\[>4;(\d+)m/;function Vy(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 ms(){try{if(process.stdout?.fd!==void 0){nc.writeSync(process.stdout.fd,Hy);return}}catch{}try{process.stdout.write(Fy),process.stdout.write(Wy),process.stdout.write(Uy)}catch{}}var tc=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($d)}async detectCapabilities(){if(!this.detectionComplete){if(!process.stdin.isTTY||!process.stdout.isTTY){this.detectionComplete=!0;return}return process.off("exit",ms),process.off("SIGTERM",ms),process.off("SIGINT",ms),process.on("exit",ms),process.on("SIGTERM",ms),process.on("SIGINT",ms),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(qy);p&&(a=!0,this.terminalBackgroundColor=Vy(p[1],p[2],p[3]))}if(!s&&Gy.test(n)&&(s=!0,this.kittySupported=!0),!c){let p=n.match(Ky);if(p){c=!0;let h=parseInt(p[1],10);this.modifyOtherKeysSupported=h>=2}}if(!r){let p=n.match(jy);p&&(r=!0,this.terminalName=p[1])}o||n.match(zy)&&(o=!0,d())};process.stdin.on("data",g);try{nc.writeSync(process.stdout.fd,Oy+Ay+$d+Dy+Ry+My+Ny+_y)}catch{d()}})}}enableSupportedModes(){try{this.kittySupported?(process.stdout.write($y),this.kittyEnabled=!0):this.modifyOtherKeysSupported&&process.stdout.write(By),process.stdout.write(Ly)}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}}},Xy=tc.getInstance();var VO=Yy(null);import QO,{createContext as Qy,useContext as JO,useState as ZO,useCallback as eN,useMemo as tN,useRef as nN,useEffect as sN}from"react";var rN=Qy(null);import aN,{createContext as Jy,useContext as cN,useState as lN,useCallback as uN,useMemo as dN,useEffect as gN}from"react";var mN=Jy(null);import fN,{createContext as Zy,useContext as bN,useState as yN,useCallback as vN,useMemo as SN,useEffect as wN}from"react";var TN=Zy(null);import EN,{createContext as ev,useContext as IN,useState as kN,useCallback as PN,useMemo as AN,useRef as DN,useEffect as MN}from"react";var RN=ev(null);import{useRef as oc,useEffect as fv,useCallback as bv}from"react";import{useInput as yv,useApp as vv}from"@jrichman/ink";import{useCallback as Wd}from"react";import{useApp as ov}from"@jrichman/ink";import{execSync as Fd}from"child_process";import Ld from"os";import Bt from"fs";function qo(){if(Ld.platform()!=="darwin")return!1;try{let i=Fd('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 Ko(){if(Ld.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"
|
|
1967
|
+
${a.input}`:T:a.input,imageUrls:m,errors:h}}finally{t(a=>({...a,isProcessingFiles:!1}))}},setSuggestion:a=>{t(c=>({...c,suggestion:a}))},acceptSuggestion:()=>{t(a=>{if(!a.suggestion)return a;let c=a.suggestion.startsWith(a.input)?a.suggestion.slice(a.input.length):a.suggestion,l=a.input+c;return{...a,input:l,cursorPosition:l.length,suggestion:null}})},addToHistory:a=>{a.trim()&&t(c=>{if(c.history.length>0&&c.history[c.history.length-1]===a)return c;let l=[...c.history,a];return l.length>gy&&l.shift(),{...c,history:l,historyIndex:-1,tempInput:""}})},navigateHistoryUp:()=>{let a=!1;return t(c=>{if(c.history.length===0)return c;if(c.historyIndex===-1){let l=c.history.length-1;return a=!0,{...c,tempInput:c.input,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}if(c.historyIndex>0){let l=c.historyIndex-1;return a=!0,{...c,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}return c}),a},navigateHistoryDown:()=>{let a=!1;return t(c=>{if(c.historyIndex===-1)return c;if(c.historyIndex>=c.history.length-1)return a=!0,{...c,historyIndex:-1,input:c.tempInput,cursorPosition:c.tempInput.length,tempInput:""};let l=c.historyIndex+1;return a=!0,{...c,historyIndex:l,input:c.history[l],cursorPosition:c.history[l].length}}),a},resetHistoryNavigation:()=>{t(a=>({...a,historyIndex:-1,tempInput:""}))},saveUndoState:()=>{t(a=>{let c={input:a.input,cursorPosition:a.cursorPosition};if(s.current&&s.current.input===c.input)return a;s.current=c;let l=[...a.undoStack,c];return l.length>my&&l.shift(),{...a,undoStack:l,redoStack:[]}})},undo:()=>{let a=!1;return t(c=>{if(c.undoStack.length===0)return c;let l={input:c.input,cursorPosition:c.cursorPosition},d=[...c.undoStack],g=d.pop();return a=!0,{...c,input:g.input,cursorPosition:g.cursorPosition,undoStack:d,redoStack:[...c.redoStack,l]}}),a},redo:()=>{let a=!1;return t(c=>{if(c.redoStack.length===0)return c;let l={input:c.input,cursorPosition:c.cursorPosition},d=[...c.redoStack],g=d.pop();return a=!0,{...c,input:g.input,cursorPosition:g.cursorPosition,undoStack:[...c.undoStack,l],redoStack:d}}),a}}),[e]),o=xd(()=>({state:e,actions:r}),[e,r]);return ly.createElement(Qa.Provider,{value:o},i)}function ir(){let i=Ed(Qa);if(!i)throw new Error("useInputState must be used within InputProvider");return i.state}function _n(){let i=Ed(Qa);if(!i)throw new Error("useInputActions must be used within InputProvider");return i.actions}import fy,{createContext as by,useContext as zR,useCallback as jo,useRef as kd,useEffect as yy}from"react";import{EventEmitter as hy}from"events";function Id(){process.stdout.write("\x1B[?1006l\x1B[?1002l")}var Go=new hy;Go.setMaxListeners(50);var vy=by(null);function Za({children:i,enableMouse:e=!0}){let t=kd(new Set),n=kd(new Set),s=jo(c=>{t.current.add(c)},[]),r=jo(c=>{t.current.delete(c)},[]),o=jo(c=>{n.current.add(c)},[]),a=jo(c=>{n.current.delete(c)},[]);return yy(()=>{if(!e)return;let c=l=>{for(let d of t.current)d(l);if(l.name==="scroll-up")for(let d of n.current)d("up");else if(l.name==="scroll-down")for(let d of n.current)d("down")};return Go.on("mouse",c),()=>{Go.off("mouse",c)}},[e]),fy.createElement(vy.Provider,{value:{subscribe:s,unsubscribe:r,subscribeScroll:o,unsubscribeScroll:a,isMouseEnabled:e}},i)}import Pd,{createContext as Dd,useContext as XR,useState as Sy,useCallback as zo,useMemo as Ad}from"react";var wy=Dd(null),Ty=Dd(null);function ec({children:i}){let[e,t]=Sy(new Set),n=zo(l=>{t(d=>{if(d.has(l))return d;let g=new Set(d);return g.add(l),g})},[]),s=zo(l=>{t(d=>{if(!d.has(l))return d;let g=new Set(d);return g.delete(l),g})},[]),r=zo(()=>{t(new Set)},[]),o=zo(l=>e.has(l),[e]),a=Ad(()=>({overflowingIds:e,hasOverflow:e.size>0}),[e]),c=Ad(()=>({markOverflowing:n,clearOverflowing:s,clearAll:r,isOverflowing:o}),[n,s,r,o]);return Pd.createElement(Ty.Provider,{value:c},Pd.createElement(wy.Provider,{value:a},i))}import Md,{createContext as Od,useContext as JR,useState as xy,useCallback as qo,useMemo as Cy,useRef as Ey}from"react";function Iy(i,e){return i.modelName===e.modelName&&i.requestCount===e.requestCount&&i.totalTokens===e.totalTokens&&Math.abs(i.averageLatency-e.averageLatency)<.01}function ky(i,e){return i.toolName===e.toolName&&i.callCount===e.callCount&&i.successCount===e.successCount&&i.failureCount===e.failureCount&&Math.abs(i.averageDuration-e.averageDuration)<.01}function Ko(i,e){if(i.promptCount!==e.promptCount||i.lastPromptTokenCount!==e.lastPromptTokenCount||i.totalInputTokens!==e.totalInputTokens||i.totalOutputTokens!==e.totalOutputTokens||i.modelMetrics.size!==e.modelMetrics.size)return!1;for(let[t,n]of i.modelMetrics){let s=e.modelMetrics.get(t);if(!s||!Iy(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||!ky(n,s))return!1}return!0}var Py=Od(null),Ay=Od(null);function Rd(){let i=Date.now();return{promptCount:0,lastPromptTokenCount:0,totalInputTokens:0,totalOutputTokens:0,sessionStartTime:i,lastActivityTime:i,modelMetrics:new Map,toolCallStats:new Map}}function tc({children:i}){let[e,t]=xy(Rd),n=Ey(e),s=qo(l=>{t(d=>{let g={...d,promptCount:d.promptCount+1,lastPromptTokenCount:l,lastActivityTime:Date.now()};return Ko(d,g)?d:g})},[]),r=qo((l,d,g,m)=>{t(p=>{let h=new Map(p.modelMetrics),f=h.get(l);if(f){let T=f.requestCount+1,x=f.totalTokens+d+g,S=(f.averageLatency*f.requestCount+m)/T;h.set(l,{modelName:l,requestCount:T,totalTokens:x,averageLatency:S})}else h.set(l,{modelName:l,requestCount:1,totalTokens:d+g,averageLatency:m});let y={...p,totalInputTokens:p.totalInputTokens+d,totalOutputTokens:p.totalOutputTokens+g,lastActivityTime:Date.now(),modelMetrics:h};return Ko(p,y)?p:y})},[]),o=qo((l,d,g)=>{t(m=>{let p=new Map(m.toolCallStats),h=p.get(l);if(h){let y=h.callCount+1,T=(h.averageDuration*h.callCount+g)/y;p.set(l,{toolName:l,callCount:y,successCount:h.successCount+(d?1:0),failureCount:h.failureCount+(d?0:1),averageDuration:T})}else p.set(l,{toolName:l,callCount:1,successCount:d?1:0,failureCount:d?0:1,averageDuration:g});let f={...m,lastActivityTime:Date.now(),toolCallStats:p};return Ko(m,f)?m:f})},[]),a=qo(()=>{t(Rd())},[]),c=Cy(()=>({recordPrompt:s,recordModelUsage:r,recordToolCall:o,resetSession:a}),[s,r,o,a]);return Md.createElement(Ay.Provider,{value:c},Md.createElement(Py.Provider,{value:e},i))}import Dy,{createContext as My,useContext as nO,useState as Nd,useEffect as _d,useCallback as ar,useMemo as $d,useRef as nc}from"react";var cr={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}},Fd={fps:60,frameTime:16.67,memoryUsageMB:0,memoryPressure:"normal",totalRenders:0,avgRenderTime:0,peakRenderTime:0,isDegraded:!1,performanceLevel:"high"},Ry=My(null);function sc({children:i,initialLevel:e,enableAdaptive:t=!0,memoryWarningMB:n=150,memoryCriticalMB:s=250}){let[r,o]=Nd(Fd),[a,c]=Nd(cr[e||"high"]),l=nc([]),d=nc([]),g=nc(0),m=ar(S=>{let C=Date.now();l.current.push(S),l.current.length>100&&l.current.shift(),d.current.push(C);let v=C-1e3;d.current=d.current.filter(I=>I>v),o(I=>{let w=l.current,E=w.length>0?w.reduce((R,_)=>R+_,0)/w.length:0,P=Math.max(I.peakRenderTime,S),D=d.current.length,$=D>0?1e3/D:16.67;return{...I,totalRenders:I.totalRenders+1,avgRenderTime:E,peakRenderTime:P,fps:D,frameTime:$,isDegraded:E>16||D<30}})},[]);_d(()=>{let S=()=>{if(typeof process<"u"&&process.memoryUsage){let I=process.memoryUsage().heapUsed/1024/1024,w="normal";I>=s?w="critical":I>=n&&(w="warning"),o(E=>({...E,memoryUsageMB:I,memoryPressure:w}))}};S();let C=setInterval(S,5e3);return()=>clearInterval(C)},[n,s]),_d(()=>{if(!t)return;let S=r.performanceLevel;r.memoryPressure==="critical"||r.fps<15?S="minimal":r.memoryPressure==="warning"||r.fps<30||r.avgRenderTime>32?S="low":r.fps<45||r.avgRenderTime>20?S="medium":r.fps>=55&&r.avgRenderTime<12&&r.memoryPressure==="normal"&&(S="high"),S!==r.performanceLevel&&(o(C=>({...C,performanceLevel:S})),c(cr[S]))},[t,r.fps,r.avgRenderTime,r.memoryPressure,r.performanceLevel]);let p=ar(S=>{o(C=>({...C,performanceLevel:S})),c(cr[S])},[]),h=ar(()=>{l.current=[],d.current=[],o(S=>({...Fd,performanceLevel:S.performanceLevel}))},[]),f=ar((S,C)=>{c(v=>({...v,[S]:C}))},[]),y=ar(S=>{c(cr[S])},[]),T=$d(()=>({recordRender:m,setPerformanceLevel:p,resetMetrics:h,updateSetting:f,applyPreset:y}),[m,p,h,f,y]),x=$d(()=>({state:{metrics:r,settings:a},actions:T}),[r,a,T]);return Dy.createElement(Ry.Provider,{value:x},i)}function Ld({children:i,initialProjectPath:e}){return $n.createElement(sc,{enableAdaptive:!0,memoryWarningMB:150,memoryCriticalMB:250},$n.createElement(tc,null,$n.createElement(Za,{enableMouse:!1},$n.createElement(ec,null,$n.createElement(Ha,{initialProjectPath:e},$n.createElement(qa,null,$n.createElement(Ja,null,i)))))))}import pO,{createContext as Oy,useContext as hO,useCallback as fO,useState as bO,useEffect as yO,useMemo as vO}from"react";var SO=Oy(null);import xO,{createContext as Ud,useContext as CO,useCallback as EO,useState as IO,useMemo as kO,useRef as PO}from"react";var AO=Ud(null),DO=Ud(null);import OO,{createContext as Ny,useCallback as NO,useContext as _O,useEffect as $O,useMemo as FO,useRef as LO,useState as UO}from"react";var BO=Ny(null);import jO,{createContext as nv,useContext as zO,useEffect as qO,useState as KO,useMemo as VO,useCallback as XO}from"react";import*as oc from"node:fs";var _y="\x1B[?u",Bd="\x1B]11;?\x1B\\",$y="\x1B[>q",Fy="\x1B[c",Ly="\x1B[>4;?m",Uy="\x1B[8m",By="\x1B[2K\r",Wy="\x1B[0m",Hy="\x1B[>u",Gy="\x1B[<u",jy="\x1B[?2004h",zy="\x1B[?2004l",qy="\x1B[>4;2m",Ky="\x1B[>4;0m",Vy="\x1B[<u\x1B[>4;0m\x1B[?2004l",Xy=/\x1b\[\?(\d+)u/,Yy=/\x1bP>\|(.+?)(\x1b\\|\x07)/,Qy=/\x1b\[\?(\d+)(;\d+)*c/,Jy=/\x1b\]11;rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})(\x1b\\|\x07)/,Zy=/\x1b\[>4;(\d+)m/;function ev(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 ms(){try{if(process.stdout?.fd!==void 0){oc.writeSync(process.stdout.fd,Vy);return}}catch{}try{process.stdout.write(Gy),process.stdout.write(Ky),process.stdout.write(zy)}catch{}}var rc=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(Bd)}async detectCapabilities(){if(!this.detectionComplete){if(!process.stdin.isTTY||!process.stdout.isTTY){this.detectionComplete=!0;return}return process.off("exit",ms),process.off("SIGTERM",ms),process.off("SIGINT",ms),process.on("exit",ms),process.on("SIGTERM",ms),process.on("SIGINT",ms),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(Jy);p&&(a=!0,this.terminalBackgroundColor=ev(p[1],p[2],p[3]))}if(!s&&Xy.test(n)&&(s=!0,this.kittySupported=!0),!c){let p=n.match(Zy);if(p){c=!0;let h=parseInt(p[1],10);this.modifyOtherKeysSupported=h>=2}}if(!r){let p=n.match(Yy);p&&(r=!0,this.terminalName=p[1])}o||n.match(Qy)&&(o=!0,d())};process.stdin.on("data",g);try{oc.writeSync(process.stdout.fd,Uy+_y+Bd+$y+Ly+Fy+By+Wy)}catch{d()}})}}enableSupportedModes(){try{this.kittySupported?(process.stdout.write(Hy),this.kittyEnabled=!0):this.modifyOtherKeysSupported&&process.stdout.write(qy),process.stdout.write(jy)}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}}},tv=rc.getInstance();var QO=nv(null);import eN,{createContext as sv,useContext as tN,useState as nN,useCallback as sN,useMemo as rN,useRef as oN,useEffect as iN}from"react";var aN=sv(null);import uN,{createContext as rv,useContext as dN,useState as gN,useCallback as mN,useMemo as pN,useEffect as hN}from"react";var fN=rv(null);import vN,{createContext as ov,useContext as SN,useState as wN,useCallback as TN,useMemo as xN,useEffect as CN}from"react";var EN=ov(null);import PN,{createContext as iv,useContext as AN,useState as DN,useCallback as MN,useMemo as RN,useRef as ON,useEffect as NN}from"react";var _N=iv(null);import{useRef as cc,useEffect as Tv,useCallback as xv}from"react";import{useInput as Cv,useApp as Ev}from"@jrichman/ink";import{useCallback as zd}from"react";import{useApp as dv}from"@jrichman/ink";import{execSync as Wd}from"child_process";import Hd from"os";import Bt from"fs";function Vo(){if(Hd.platform()!=="darwin")return!1;try{let i=Wd('osascript -e "clipboard info"',{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]});return i.includes("PNGf")||i.includes("TIFF")||i.includes("JPEG")||i.includes("jp2")||i.includes("GIF")||i.includes("BMP")}catch{return!1}}async function Xo(){if(Hd.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"
|
|
1964
1968
|
use scripting additions
|
|
1965
1969
|
|
|
1966
1970
|
set theClipboard to current application's NSPasteboard's generalPasteboard()
|
|
@@ -1973,13 +1977,13 @@ if imageData is not missing value then
|
|
|
1973
1977
|
else
|
|
1974
1978
|
return "error:No PNG image in clipboard"
|
|
1975
1979
|
end if
|
|
1976
|
-
`;Bt.writeFileSync(t,n);let s;try{s=
|
|
1980
|
+
`;Bt.writeFileSync(t,n);let s;try{s=Wd(`osascript "${t}"`,{encoding:"utf8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim()}finally{try{Bt.unlinkSync(t)}catch{}}if(s.startsWith("error:"))return{data:null,size:0,error:s.replace("error:","")};if(!Bt.existsSync(e))return{data:null,size:0,error:"Failed to save clipboard image"};let r=Bt.readFileSync(e),o=r.length,c=`data:image/png;base64,${r.toString("base64")}`;try{Bt.unlinkSync(e)}catch{}return{data:c,size:o}}catch(n){try{Bt.existsSync(e)&&Bt.unlinkSync(e),Bt.existsSync(t)&&Bt.unlinkSync(t)}catch{}return{data:null,size:0,error:n.message||"Failed to read clipboard image"}}}Te();Pt();import un from"axios";var Wt=class i{static instance;authService;deviceRegistration;baseURL="https://snowx.ai/api-beta/api";constructor(){this.authService=X.getInstance(),this.deviceRegistration=Pe.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async getAuthHeaders(){let e=await this.authService.getAccessToken();if(!e)throw new Error('Not authenticated. Run "orion auth login" first.');return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}async getDeviceId(){if(!this.authService.getUserId())throw new Error('Not authenticated. Run "orion auth login" first.');let t=this.deviceRegistration.getCurrentDeviceId();if(!t)throw new Error("Device not registered. Please wait a moment and try again.");return t}generateDiscordInviteUrl(e){return`https://discord.com/api/oauth2/authorize?client_id=${e}&permissions=274877975552&scope=bot%20applications.commands`}validateDiscordToken(e){return/^[A-Za-z0-9_-]{24,}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27,}$/.test(e.trim())}async connectDiscord(e){try{let t=await this.getAuthHeaders(),n=await this.getDeviceId(),s=await un.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 un.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 un.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 un.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 un.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 un.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 un.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 un.delete(`${this.baseURL}/integrations/telegram`,{headers:e,data:{device_id:t,user_id:n}}),!0}catch{return!1}}};Te();q();import{EventEmitter as av}from"events";import cv from"axios";var lv="https://snowx.ai/api-beta/api/users/me/quota",Gd=50,uv=300*1e3,ic=class i extends av{static instance;authService;cachedQuota=null;lastFetchTime=0;pollTimer=null;constructor(){super(),this.authService=X.getInstance()}static getInstance(){return i.instance||(i.instance=new i),i.instance}async fetchQuotaStatus(e=!1){let t=Date.now();if(!e&&this.cachedQuota&&t-this.lastFetchTime<6e4)return this.cachedQuota;try{let n=this.authService.getAccessToken();if(n||(n=await this.authService.getAccessTokenFromStorage()),!n)return u.debug("[QuotaService] No auth token available"),null;let s=await cv.get(lv,{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>=Gd?{percent:Math.round(t.percentUsed),type:"weekly",resetsAt:t.resetsAt,resetsInSeconds:t.resetsInSeconds}:n?.percentUsed>=Gd?{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)},uv))}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}clearCache(){this.cachedQuota=null,this.lastFetchTime=0}},lr=ic.getInstance();function jd(i){return i>=95?"critical":i>=90?"high":i>=70?"warning":i>=50?"notice":"normal"}function ur(i,e){if(!i&&(!e||e<=0))return"";let t=i?new Date(i):new Date(Date.now()+e*1e3),n=Date.now(),s=t.getTime()-n,r=Math.floor(s/(1e3*60*60)),o=Math.floor(s%(1e3*60*60)/(1e3*60));return s<0?"now":r<24?r>0?`${r}h ${o}m`:`${o}m`:t.toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}import gv from"os";import qd from"path";function Yo(){let{exit:i}=dv(),e=On(),t=xt(),n=Ga(),s=Ut(),r=_n(),o=zd(c=>c.startsWith("/"),[]);return{handleCommand:zd(async c=>{if(!c.startsWith("/"))return{handled:!1};let l=c.toLowerCase().trim();if(l==="/help"||l==="/?")return s.showCommandMenu(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/model")return s.showModelMenu(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/clear"||l==="/new")return t.clearChat(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/vision")return s.toggleVision(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/exit"||l==="/quit")return i(),{handled:!0};if(l==="/stop")return t.stopStreaming(),r.clearInput(),{handled:!0,clearInput:!0};if(l==="/img"||l==="/image"||l==="/paste"){if(r.clearInput(),!Vo())return t.addSystemMessage("[!] No image found in clipboard"),{handled:!0,clearInput:!0};try{let d=await Xo();d.data?(r.addClipboardImage(d.data,d.size),t.addSystemMessage("[OK] Image added from clipboard")):t.addSystemMessage(`[!] Failed to read clipboard image: ${d.error||"Unknown error"}`)}catch(d){t.addSystemMessage(`[!] Error reading clipboard: ${d.message}`)}return{handled:!0,clearInput:!0}}if(l==="/signout"){t.addSystemMessage("[...] Signing out..."),r.clearInput();try{await n.authService.signOut()&&(t.addSystemMessage("[OK] Successfully signed out. Goodbye!"),setTimeout(()=>i(),1e3))}catch(d){t.addSystemMessage(`[ERROR] ${d.message}`)}return{handled:!0,clearInput:!0}}if(l.startsWith("/export")){r.clearInput();let g=l.split(/\s+/)[1]?.toLowerCase()||"markdown";if(!["markdown","md","json","text","txt"].includes(g))return t.addSystemMessage(`[!] Invalid format: ${g}
|
|
1977
1981
|
|
|
1978
1982
|
Usage: /export [markdown|json|text]
|
|
1979
1983
|
- markdown (default): Export as .md file
|
|
1980
1984
|
- json: Export as .json file
|
|
1981
|
-
- text: Export as .txt file`),{handled:!0,clearInput:!0};let p=g==="md"?"markdown":g==="txt"?"text":g,h=p==="markdown"?"md":p==="json"?"json":"txt",f=e.conversationId;if(!f)return t.addSystemMessage("[!] No active conversation to export"),{handled:!0,clearInput:!0};let
|
|
1982
|
-
${
|
|
1985
|
+
- text: Export as .txt file`),{handled:!0,clearInput:!0};let p=g==="md"?"markdown":g==="txt"?"text":g,h=p==="markdown"?"md":p==="json"?"json":"txt",f=e.conversationId;if(!f)return t.addSystemMessage("[!] No active conversation to export"),{handled:!0,clearInput:!0};let T=`orion-chat-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}.${h}`,x=qd.join(gv.homedir(),"Downloads"),S=qd.join(x,T),C=Qe.saveExportToFile(f,p,S);return C.success?t.addSystemMessage(`[OK] Conversation exported to:
|
|
1986
|
+
${S}`):t.addSystemMessage(`[!] Export failed: ${C.error}`),{handled:!0,clearInput:!0}}if(l==="/discord"||l==="/discord reconnect"||l==="/discord setup"){r.clearInput();let d=l.includes("reconnect")||l.includes("setup");try{let g=Wt.getInstance(),m=await g.getDiscordStatus();if(m.connected&&!d){let p=m.botId?g.generateDiscordInviteUrl(m.botId):"";t.addSystemMessage(`Discord: Connected
|
|
1983
1987
|
Bot: ${m.botUsername}
|
|
1984
1988
|
Owners: ${m.ownerUserIds?.join(", ")||"None"}
|
|
1985
1989
|
Server chat: ${m.allowGuildChat?"Enabled":"Disabled"}
|
|
@@ -1991,45 +1995,45 @@ Chat: ${p}
|
|
|
1991
1995
|
Owners: ${m.ownerUsernames?.map(h=>`@${h}`).join(", ")||"None"}
|
|
1992
1996
|
Group chat: ${m.allowGroupChat?"Enabled":"Disabled"}
|
|
1993
1997
|
|
|
1994
|
-
Reconfigure: /telegram reconnect`)}else s.showTelegramWizard()}catch{s.showTelegramWizard()}return{handled:!0,clearInput:!0}}if(l==="/usage"||l==="/quota"){r.clearInput(),t.addSystemMessage("[...] Fetching usage data...");try{let d=await lr.fetchQuotaStatus(!0);if(!d)return t.addSystemMessage("[!] Unable to fetch usage data. Please try again."),{handled:!0,clearInput:!0};let{token:g,tierName:m}=d,{hourly:p,weekly:h}=g,f=
|
|
1998
|
+
Reconfigure: /telegram reconnect`)}else s.showTelegramWizard()}catch{s.showTelegramWizard()}return{handled:!0,clearInput:!0}}if(l==="/usage"||l==="/quota"){r.clearInput(),t.addSystemMessage("[...] Fetching usage data...");try{let d=await lr.fetchQuotaStatus(!0);if(!d)return t.addSystemMessage("[!] Unable to fetch usage data. Please try again."),{handled:!0,clearInput:!0};let{token:g,tierName:m}=d,{hourly:p,weekly:h}=g,f=S=>{let C=Math.round(S/5),v=20-C;return`${S>=90?"🔴":S>=70?"🟡":"🟢"} [${"█".repeat(C)}${"░".repeat(v)}]`},y=`
|
|
1995
1999
|
📊 Usage Status (${m})
|
|
1996
2000
|
${"─".repeat(30)}
|
|
1997
2001
|
|
|
1998
|
-
`,
|
|
2002
|
+
`,T=Math.round(p.percentUsed);y+=`5-Hour: ${f(T)} ${T}%`,T>=50&&p.resetsInSeconds&&(y+=`
|
|
1999
2003
|
Resets in ${ur(p.resetsAt,p.resetsInSeconds)}`),y+=`
|
|
2000
2004
|
|
|
2001
|
-
`;let
|
|
2005
|
+
`;let x=Math.round(h.percentUsed);y+=`Weekly: ${f(x)} ${x}%`,x>=50&&h.resetsInSeconds&&(y+=`
|
|
2002
2006
|
Resets in ${ur(h.resetsAt,h.resetsInSeconds)}`),y+=`
|
|
2003
2007
|
`,t.addSystemMessage(y)}catch(d){t.addSystemMessage(`[!] Error fetching usage: ${d.message}`)}return{handled:!0,clearInput:!0}}return t.addSystemMessage(`Unknown command: ${c}
|
|
2004
2008
|
|
|
2005
|
-
Type /help to see available commands.`),r.clearInput(),{handled:!0,clearInput:!0}},[i,e,t,n.authService,s,r]),isCommand:o}}import{useRef as dn,useCallback as Gt,useEffect as
|
|
2006
|
-
`,"\r"," "]};function
|
|
2007
|
-
`),N=P.length>50;if(_||N){E.flush(),d.addPastedContent(P);return}E.pushChar(P)}}}}),
|
|
2008
|
-
`).length;return e>1?`${e} lines`:i.length>50?i.substring(0,47)+"...":i}function
|
|
2009
|
-
`)[0]?.substring(0,50),"...")))}),$v=lc(function({operation:e}){let{agents:t,completed:n,failed:s,running:r,total:o}=sg(()=>{let d=Array.from(e.agents.values()).sort((g,m)=>g.agentNumber-m.agentNumber);return{agents:d,completed:d.filter(g=>g.status==="completed").length,failed:d.filter(g=>g.status==="failed").length,running:d.filter(g=>g.status==="running").length,total:e.totalAgents}},[e.agents,e.totalAgents]),a=()=>e.status==="starting"||e.status==="running"?`Spawning ${o} agents`:e.status==="completed"?`${o} agents completed`:"Operation failed",c=()=>e.status==="running"||e.status==="starting"?oe.createElement(Oe,{color:"cyan"},oe.createElement(rg,{type:"dots"})):e.status==="completed"?oe.createElement(Oe,{color:"#5AD8A6"},"[done]"):oe.createElement(Oe,{color:"#F5716C"},"[fail]"),l=e.status==="completed"?"#5AD8A6":e.status==="failed"?"#F5716C":"cyan";return oe.createElement(jt,{flexDirection:"column"},oe.createElement(jt,null,c(),oe.createElement(Oe,{color:l,bold:!0}," ",a()),oe.createElement(Oe,{color:"#6B7280"}," "),oe.createElement(Oe,{backgroundColor:"#3F3F46",color:"whiteBright"}," ",n,"/",o," "),r>0&&oe.createElement(Oe,{color:"cyan"}," (",r," running)"),s>0&&oe.createElement(Oe,{color:"#F5716C"}," [",s," failed]")),oe.createElement(jt,{flexDirection:"column",marginTop:1},t.map(d=>oe.createElement(_v,{key:d.agentNumber,agent:d}))))});function Fv({operations:i}){let e=sg(()=>i.size===0?[]:Array.from(i.entries()).filter(([t,n])=>n.status==="running"||n.status==="starting"?!0:n.endTime?Date.now()-n.endTime.getTime()<1e4:!0),[i]);return e.length===0?null:oe.createElement(jt,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},e.map(([t,n])=>oe.createElement($v,{key:t,operation:n})))}var og=lc(Fv);import Fn,{memo as Lv}from"react";import{Box as Uv,Text as mr}from"@jrichman/ink";import Bv from"ink-spinner";function Wv(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 Hv(i,e=60){return i?i.length<=e?i:i.substring(0,e-3)+"...":"Processing request..."}function Gv({session:i}){if(!i)return null;let e=Wv(i.source),t=Hv(i.message);return Fn.createElement(Uv,{flexDirection:"row",paddingX:1,marginY:1,borderStyle:"round",borderColor:A.ui.border},Fn.createElement(mr,{color:A.status.warning},Fn.createElement(Bv,{type:"dots"})),Fn.createElement(mr,null," "),Fn.createElement(mr,{color:A.text.primary,bold:!0},e),Fn.createElement(mr,{color:A.ui.muted},": "),Fn.createElement(mr,{color:A.text.secondary},t))}var ig=Lv(Gv);import Et,{useState as jv,useEffect as zv,useRef as ag,memo as qv,useMemo as Kv,useCallback as Vv}from"react";import{Box as pr,Text as hr}from"@jrichman/ink";import Xv from"ink-select-input";var Yv=[{label:"Yes, proceed",value:"confirm"},{label:"No, cancel",value:"decline"}];function Qv({request:i,onConfirm:e,onDecline:t,onTimeout:n}){let[s,r]=jv(i.timeout?Math.ceil(i.timeout/1e3):null),o=ag(null),a=ag(0);zv(()=>{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=Vv(g=>{o.current&&(clearInterval(o.current),o.current=null),g.value==="confirm"?e("y"):t()},[e,t]),{actualTargets:l,displayCommand:d}=Kv(()=>{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 Et.createElement(pr,{flexDirection:"column",borderStyle:"round",borderColor:"#525252",paddingX:2,paddingY:1},Et.createElement(hr,{color:"white",bold:!0},i.title),d&&Et.createElement(pr,{marginTop:1},Et.createElement(hr,{color:"gray"},"$ "),Et.createElement(hr,{color:"white"},d)),l.length>0&&Et.createElement(pr,{marginTop:1,flexDirection:"column"},l.map((g,m)=>Et.createElement(hr,{key:m,color:"gray"}," ",g))),s!==null&&Et.createElement(pr,{marginTop:1},Et.createElement(hr,{color:"yellow"},"Auto-cancel in ",s,"s")),Et.createElement(pr,{marginTop:1},Et.createElement(Xv,{items:Yv,onSelect:c})))}var cg=qv(Qv,(i,e)=>i.request.id===e.request.id&&i.request.timeout===e.request.timeout);import ht,{memo as Jv,useMemo as Zv}from"react";import{Box as fr,Text as Ln}from"@jrichman/ink";var eS=8;function tS({todoList:i}){let{incompleteTodos:e,completedTodos:t,allComplete:n,visibleTodos:s,hiddenCount:r}=Zv(()=>{if(!i||i.todos.length===0)return{incompleteTodos:[],completedTodos:[],allComplete:!1,visibleTodos:[],hiddenCount:0};let o=i.todos.filter(g=>g.status!=="completed"),a=i.todos.filter(g=>g.status==="completed"),c=o.length===0&&a.length>0,l=[...o,...a.slice(-2)].slice(0,eS),d=i.todos.length-l.length;return{incompleteTodos:o,completedTodos:a,allComplete:c,visibleTodos:l,hiddenCount:d}},[i]);return!i||i.todos.length===0?null:ht.createElement(fr,{paddingX:2,marginBottom:1,flexShrink:0},ht.createElement(fr,{borderStyle:"round",borderColor:n?A.status.success:A.border.default,paddingX:2,paddingY:1,flexDirection:"column"},ht.createElement(fr,{marginBottom:1},ht.createElement(Ln,{color:A.text.primary,bold:!0},"Tasks"),ht.createElement(Ln,{color:A.ui.muted}," - "),ht.createElement(Ln,{color:n?A.status.success:A.text.secondary},t.length,"/",i.todos.length,n&&" ✓")),s.map((o,a)=>{let c=o.status==="completed"?"[done]":o.status==="in_progress"?"[..]":"[ ]",l=o.status==="completed"?A.status.success:o.status==="in_progress"?A.text.accent:A.ui.muted,d=o.status==="in_progress"&&o.activeForm?o.activeForm:zu(o);return ht.createElement(fr,{key:o.id||`todo-${a}`},ht.createElement(Ln,{color:l},c),ht.createElement(Ln,{color:A.ui.muted}," "),ht.createElement(Ln,{color:o.status==="completed"?A.ui.muted:A.text.primary},d))}),r>0&&ht.createElement(fr,{marginTop:0},ht.createElement(Ln,{color:A.ui.muted}," +",r," more tasks"))))}var lg=Jv(tS);import Ne,{memo as nS}from"react";import{Box as uc,Text as Qe}from"@jrichman/ink";function sS(){return Ne.createElement(uc,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},Ne.createElement(Qe,{bold:!0,color:"whiteBright"},"Keyboard Shortcuts"),Ne.createElement(uc,{marginTop:1,flexDirection:"column"},Ne.createElement(Qe,{color:"#9CA3AF"},"• ",Ne.createElement(Qe,{color:"whiteBright",bold:!0},"Enter")," ",Ne.createElement(Qe,{color:"#9CA3AF"},"Submit message")),Ne.createElement(Qe,{color:"#9CA3AF"},"• ",Ne.createElement(Qe,{color:"whiteBright",bold:!0},"?")," ",Ne.createElement(Qe,{color:"#9CA3AF"},"Toggle this help")),Ne.createElement(Qe,{color:"#9CA3AF"},"• ",Ne.createElement(Qe,{color:"whiteBright",bold:!0},"Esc")," ",Ne.createElement(Qe,{color:"#9CA3AF"},"Stop generation / Close menus")),Ne.createElement(Qe,{color:"#9CA3AF"},"• ",Ne.createElement(Qe,{color:"whiteBright",bold:!0},"Ctrl+C")," ",Ne.createElement(Qe,{color:"#9CA3AF"},"Stop generation / Exit"))),Ne.createElement(uc,{marginTop:1},Ne.createElement(Qe,{color:"#6B7280"},"Press Esc to close")))}var ug=nS(sS);import Ae,{memo as lS,useMemo as uS,useCallback as dS}from"react";import{Box as ei,Text as tt}from"@jrichman/ink";import fs,{useState as rS,useEffect as oS,memo as dg}from"react";import{Box as dc,Text as gg,useInput as iS}from"@jrichman/ink";var aS=dg(function({item:e,isSelected:t,highlightColor:n}){return fs.createElement(gg,{color:t?"#000":"#fff",backgroundColor:t?n:void 0},e.label)});function cS({items:i,onSelect:e,onHighlight:t,isFocused:n=!0,highlightColor:s="#D97706",itemComponent:r=aS}){let[o,a]=rS(0);return oS(()=>{a(0)},[i.length]),iS((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?fs.createElement(dc,null,fs.createElement(gg,{color:"#6B7280"},"No items")):fs.createElement(dc,{flexDirection:"column"},i.map((c,l)=>{let d=l===o;return fs.createElement(dc,{key:c.value||l},fs.createElement(r,{item:c,isSelected:d,highlightColor:s}))}))}var Zo=dg(cS);Kt();Sn();function gS({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}=uS(()=>{let a=me.filter(p=>p.name.startsWith("snowx-o4")||p.name.startsWith("snowx-c")||p.name.startsWith("snowx-h")),c=me.filter(p=>p.name.startsWith("snowx-5")||p.name.startsWith("snowx-o3")||p.name.startsWith("snowx-4")),l=me.filter(p=>p.name.startsWith("snowx-g")),d=p=>p.map(h=>{let f=xe.isModelAccessible(h.name,i),y=n(h.creditMultiplier);return{label:`${f?"":"[LOCKED] "}${h.displayName} ${y}`,value:h.name,isAccessible:f,creditMultiplier:h.creditMultiplier,isHeader:!1}}),g=[{label:"-- Claude --",value:"_claude_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(a),{label:"-- GPT --",value:"_gpt_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(c),{label:"-- Gemini --",value:"_gemini_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(l)],m=g.filter(p=>!p.isHeader);return{allItems:g,selectableItems:m}},[i]),o=dS(a=>{if(a.value.startsWith("_"))return;if(!s.find(d=>d.value===a.value)?.isAccessible){t(a.value);return}let l=me.find(d=>d.name===a.value);l&&e(l)},[s,t,e]);return Ae.createElement(ei,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},Ae.createElement(tt,{bold:!0,color:"whiteBright"},"Select Model"),Ae.createElement(ei,null,Ae.createElement(tt,{color:"#6B7280"},"Tier: ",xe.getDisplayName(i)," - "),Ae.createElement(tt,{color:"#5AD8A6"},"[0.5x]"),Ae.createElement(tt,{color:"#6B7280"}," "),Ae.createElement(tt,{color:"#9CA3AF"},"[1x]"),Ae.createElement(tt,{color:"#6B7280"}," "),Ae.createElement(tt,{color:"#60A5FA"},"[1.5x]"),Ae.createElement(tt,{color:"#6B7280"}," "),Ae.createElement(tt,{color:"#FBBF24"},"[2x]"),Ae.createElement(tt,{color:"#6B7280"}," "),Ae.createElement(tt,{color:"#F472B6"},"[2.5x]"),Ae.createElement(tt,{color:"#6B7280"}," credits")),Ae.createElement(ei,{marginTop:1},Ae.createElement(Zo,{items:r.map(a=>({label:a.label,value:a.value})),onSelect:o,isFocused:!0,highlightColor:"#D97706"})),Ae.createElement(ei,{marginTop:1},Ae.createElement(tt,{color:"#6B7280"},"Esc to cancel")))}var mg=lS(gS);import bs,{memo as fg,useMemo as mS,useCallback as pS}from"react";import{Box as gc,Text as pg}from"@jrichman/ink";var hg=[{command:"/model",description:"change AI model",value:"model"},{command:"/usage",description:"view usage & limits",value:"usage"},{command:"/new",description:"start new conversation",value:"new"},{command:"/clear",description:"clear conversation",value:"clear"},{command:"/stop",description:"stop current generation",value:"stop"},{command:"/vision",description:"toggle vision mode",value:"vision"},{command:"/img",description:"paste image from clipboard",value:"img"},{command:"/export",description:"export conversation (md/json/txt)",value:"export"},{command:"/discord",description:"discord integration",value:"discord"},{command:"/telegram",description:"telegram integration",value:"telegram"},{command:"/signout",description:"sign out and exit",value:"signout"},{command:"/help",description:"show help",value:"help"},{command:"/exit",description:"exit the app",value:"exit"}],hS=fg(function({item:e,isSelected:t,highlightColor:n}){let[s,r]=e.label.split(" ");return bs.createElement(gc,{width:50,backgroundColor:t?n:void 0},bs.createElement(gc,{width:14},bs.createElement(pg,{color:t?"#1a1a1a":"whiteBright",bold:!0},s)),bs.createElement(pg,{color:t?"#1a1a1a":"#6B7280"},r))});function fS({filterText:i,onSelect:e}){let t=mS(()=>(i?hg.filter(r=>r.value.toLowerCase().includes(i)):hg).map(r=>({label:`${r.command} ${r.description}`,value:r.value})),[i]),n=pS(s=>{s.value&&e(s.value)},[e]);return bs.createElement(gc,{flexDirection:"column",paddingX:1,paddingY:1,width:"100%",borderStyle:"single",borderColor:"#3F3F46",backgroundColor:"#18181B"},bs.createElement(Zo,{items:t.length>0?t:[{label:"No matching commands",value:""}],onSelect:n,itemComponent:hS,isFocused:!0,highlightColor:"#D97706"}))}var bg=fg(fS);import ne,{useState as ti,useEffect as bS,useCallback as ni,memo as yS}from"react";import{Box as ze,Text as _e,useInput as vS}from"@jrichman/ink";import SS from"ink-spinner";import{exec as wS}from"child_process";var ce={brand:"#A78BFA",text:"#F8FAFC",muted:"#94A3B8",dim:"#64748B",border:"#334155",error:"#EF4444",success:"#22C55E"},TS=[{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"}],xS=[{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 CS({type:i}){let e=Ut(),t=xt(),n=ja(),[s,r]=ti(""),[o,a]=ti(null),[c,l]=ti(!1),[d,g]=ti(0),m=Wt.getInstance(),p=i==="discord"?TS:xS,h=p.find(S=>S.id===n.step),f=p.length-1,y=ni(S=>{let E=process.platform,P;E==="darwin"?P=`open "${S}"`:E==="win32"?P=`start "" "${S}"`:P=`xdg-open "${S}"`,wS(P,()=>{})},[]);vS((S,E)=>{if(n.isOpen){if(E.escape){e.hideWizard();return}if(h?.type==="input"){if(E.return){w();return}if(E.backspace||E.delete){r(P=>P.slice(0,-1)),a(null);return}S&&!E.ctrl&&!E.meta&&!E.leftArrow&&!E.rightArrow&&!E.upArrow&&!E.downArrow&&!E.tab&&(r(P=>P+S),a(null))}else if(h?.type==="confirm"){if(E.leftArrow||E.rightArrow||S==="y"||S==="n"){g(S==="y"?1:S==="n"?0:P=>P===0?1:0);return}if(E.return){C();return}}}},{isActive:n.isOpen});let w=ni(()=>{let S=n.step,E=s.trim();if(i==="discord"){if(S===1){if(!E){a("Bot token is required");return}if(!m.validateDiscordToken(E)){a("Invalid token format. Should be like: MTIz...xxx.Yyy...zzz");return}e.setWizardData("botToken",E)}else if(S===2){if(!E){a("At least one owner ID is required");return}if(E.split(",").map(D=>D.trim()).some(D=>!/^\d{17,19}$/.test(D))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("ownerIds",E)}else if(S===3){if(E&&E.split(",").map(D=>D.trim()).filter(Boolean).some(D=>!/^\d{17,19}$/.test(D))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("guestIds",E)}}else if(S===1){if(!E){a("Bot token is required");return}if(!m.validateTelegramToken(E)){a("Invalid token format. Should be like: 123456789:ABCdef...");return}e.setWizardData("botToken",E)}else if(S===2){if(!E){a("At least one owner username is required");return}e.setWizardData("ownerUsernames",E)}else S===3&&e.setWizardData("guestUsernames",E);r(""),a(null),e.setWizardStep(S+1)},[n.step,i,s,m,e]),C=ni(()=>{let S=n.step,E=d===1;i==="discord"?S===4&&(e.setWizardData("allowGuildChat",E),e.setWizardStep(5)):S===4?(e.setWizardData("allowGroupChat",E),E?e.setWizardStep(5):(e.setWizardData("routeToDM",!1),e.setWizardStep(6))):S===5&&(e.setWizardData("routeToDM",E),e.setWizardStep(6)),g(0)},[n.step,i,d,e]),T=ni(async S=>{try{if(i==="discord"){let E=await m.connectDiscord({botToken:S.botToken,ownerUserIds:S.ownerIds.split(",").map(P=>P.trim()).filter(Boolean),guestUserIds:S.guestIds?S.guestIds.split(",").map(P=>P.trim()).filter(Boolean):[],allowGuildChat:S.allowGuildChat||!1});if(E.success){let P=E.botId?m.generateDiscordInviteUrl(E.botId):"";t.addSystemMessage(`✓ Discord connected!
|
|
2009
|
+
Type /help to see available commands.`),r.clearInput(),{handled:!0,clearInput:!0}},[i,e,t,n.authService,s,r]),isCommand:o}}import{useRef as dn,useCallback as Gt,useEffect as mv}from"react";var Fn=typeof requestAnimationFrame<"u"?requestAnimationFrame:i=>setImmediate(i),Ht=typeof cancelAnimationFrame<"u"?cancelAnimationFrame:i=>clearImmediate(i);var pv={flushInterval:16,maxBufferSize:32,detectPaste:!0,pasteThreshold:50,immediateFlushChars:[`
|
|
2010
|
+
`,"\r"," "]};function Kd(i,e){let t={...pv,...e},n=dn(""),s=dn(0),r=dn(0),o=dn(0),a=dn(0),c=dn(null),l=dn(null),d=dn(i);d.current=i;let g=Gt(()=>{if(n.current===""&&s.current===0)return null;let v=Date.now()-r.current,I=t.detectPaste&&a.current>3&&v<t.pasteThreshold*a.current;return{chars:n.current,backspaces:s.current,isPaste:I,startTime:r.current}},[t.detectPaste,t.pasteThreshold]),m=Gt(()=>{let C=g();C&&(n.current="",s.current=0,a.current=0,r.current=0,d.current(C)),c.current!==null&&(Ht(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null)},[g]),p=Gt(()=>{c.current===null&&(c.current=Fn(()=>{c.current=null,l.current&&clearTimeout(l.current),l.current=setTimeout(m,t.flushInterval)}))},[m,t.flushInterval]),h=Gt(C=>{let v=Date.now();r.current===0&&(r.current=v),o.current=v,a.current++,n.current+=C,t.immediateFlushChars.includes(C)||n.current.length>=t.maxBufferSize?m():p()},[m,p,t.immediateFlushChars,t.maxBufferSize]),f=Gt(()=>{let C=Date.now();r.current===0&&(r.current=C),a.current++,n.current.length>0?n.current=n.current.slice(0,-1):s.current++,p()},[p]),y=Gt(()=>{let C=g();return C&&(n.current="",s.current=0,a.current=0,r.current=0),c.current!==null&&(Ht(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),C},[g]),T=Gt(()=>g(),[g]),x=Gt(()=>{n.current="",s.current=0,a.current=0,r.current=0,c.current!==null&&(Ht(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null)},[]),S=Gt(()=>n.current===""&&s.current===0,[]);return mv(()=>()=>{c.current!==null&&Ht(c.current),l.current&&clearTimeout(l.current)},[]),{pushChar:h,pushBackspace:f,flush:y,peek:T,clear:x,isEmpty:S}}import{useState as hv,useEffect as fv,useRef as Qo,useCallback as bv,useMemo as yv}from"react";var Vd={high:50,normal:100,low:200},vv={minDelay:100,maxDelay:500,useRAF:!0,priority:"normal"};function Sv(i,e){let t={...vv,...e},[n,s]=hv(i),r=Qo(i),o=Qo(null),a=Qo(null),c=Qo(Date.now());r.current=i;let l=yv(()=>{let m=Vd[t.priority]||Vd.normal;return Math.max(t.minDelay,m)},[t.minDelay,t.priority]),d=bv(()=>{o.current&&(clearTimeout(o.current),o.current=null),a.current!==null&&(Ht(a.current),a.current=null),s(r.current),c.current=Date.now()},[]);return fv(()=>{if(o.current&&(clearTimeout(o.current),o.current=null),Date.now()-c.current>=t.maxDelay){d();return}let p=()=>{t.useRAF?a.current=Fn(()=>{a.current=null,s(i),c.current=Date.now()}):(s(i),c.current=Date.now())};return o.current=setTimeout(p,l),()=>{o.current&&clearTimeout(o.current),a.current!==null&&Ht(a.current)}},[i,l,t.maxDelay,t.useRAF,d]),{immediate:i,deferred:n,isPending:i!==n,sync:d}}function Xd(i,e){let t=Sv(i,e);return{...t,deferredLength:t.deferred.length,immediateLength:t.immediate.length,isTyping:t.isPending&&t.immediate.length>t.deferred.length}}import{useRef as gn,useEffect as ac,useCallback as ps,useState as wv,useMemo as Yd}from"react";function Jo(i){let e=gn(0),t=gn([]),n=gn(0),s=gn(0),r=gn([]);return ac(()=>{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)}}),Yd(()=>{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 Zo(i){let{targetFrameTime:e=16.67,warningThreshold:t=.8,criticalThreshold:n=1}=i||{},s=gn(0),r=gn(0),o=ps(()=>{s.current=performance.now(),r.current=0},[]),a=ps(()=>performance.now()-s.current+r.current<e*n,[e,n]),c=ps(d=>{r.current+=d;let g=e-r.current;return Math.max(0,g)},[e]),l=ps(()=>{let g=(performance.now()-s.current+r.current)/e;return g>=n?"critical":g>=t?"warning":"ok"},[e,t,n]);return ac(()=>{o()}),{hasBudget:a,useBudget:c,resetBudget:o,getBudgetStatus:l}}function Qd(i){let{warningThresholdMB:e=100,criticalThresholdMB:t=200,checkInterval:n=5e3}=i||{},[s,r]=wv(0);ac(()=>{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=Yd(()=>s>=t?"critical":s>=e?"warning":"normal",[s,e,t]),a=ps(()=>{typeof global<"u"&&global.gc&&global.gc()},[]);return{heapUsedMB:s,pressure:o,requestGC:a}}function Jd(i){let e=gn(i);return e.current=i,ps(((...t)=>e.current(...t)),[])}function Zd({onSubmit:i,enableProfiling:e=!1,bufferFlushInterval:t=16,deferredDelay:n=100}){let{exit:s}=Ev(),r=On(),o=xt(),a=gs(),c=Ut(),l=ir(),d=_n(),{handleCommand:g,isCommand:m}=Yo(),p=Zo({targetFrameTime:16.67}),{pressure:h}=Qd({warningThresholdMB:150,criticalThresholdMB:250}),f=e?Jo("OptimizedKeyboardInput"):void 0,{deferred:y,isPending:T}=Xd(l.input,{minDelay:n,priority:"low"}),x=cc(!1),S=cc(0),C=cc(0),v=500,I=Jd(i),w=xv(P=>{if(P.isPaste)d.addPastedContent(P.chars);else{for(let D=0;D<P.backspaces;D++)d.deleteAtCursor();P.chars&&(d.insertAtCursor(P.chars),l.input.slice(0,l.cursorPosition)+P.chars+l.input.slice(l.cursorPosition)==="/"&&!a.showCommandMenu&&c.showCommandMenu())}},[d,l.input,l.cursorPosition,a.showCommandMenu,c]),E=Kd(w,{flushInterval:t,maxBufferSize:64,detectPaste:!0,pasteThreshold:50});return Cv((P,D)=>{let $=Date.now(),R=$-S.current;if(S.current=$,!(P.startsWith("[<")||P.startsWith("[M")||/^\[<?\d+;\d+;\d+[mM]?/.test(P)||/^\d+[mM]/.test(P)||/^;\d+;\d+[mM]/.test(P)||/^\d+;\d+[mM]/.test(P))){if(p.getBudgetStatus()==="critical"&&!D.ctrl&&!D.meta&&!D.escape&&!D.return&&!D.backspace&&!D.delete){E.pushChar(P);return}if(D.escape){E.flush();let _=Date.now(),N=_-C.current;if(C.current=_,N<v){r.isLoading&&o.stopStreaming(),c.closeAllModals(),c.stopReverseSearch(),d.clearInput(),d.clearPastedTexts();return}if(r.isLoading){o.stopStreaming();return}if(a.isReverseSearchActive){c.stopReverseSearch();return}if(a.showWizard)return;if(a.showModelMenu||a.showCommandMenu){c.closeAllModals(),a.showCommandMenu&&l.input==="/"&&d.clearInput();return}if(a.showHelp){c.hideHelp();return}if(l.pastedTexts.length>0){d.clearPastedTexts();return}return}if(!a.showModelMenu&&!a.showWizard&&!(a.showCommandMenu&&(D.upArrow||D.downArrow||D.return))){if(D.ctrl&&P==="l"){E.flush(),process.stdout.write("\x1B[2J\x1B[H");return}if(D.ctrl&&P==="c"){E.flush(),r.isLoading?o.stopStreaming():s();return}if(D.ctrl&&P==="r"){E.flush(),a.isReverseSearchActive||c.startReverseSearch();return}if(D.ctrl&&P==="z"){E.flush(),d.undo();return}if(D.ctrl&&(P==="y"||P==="Z")){E.flush(),d.redo();return}if(P===""||D.ctrl&&P==="v"){if(x.current)return;if(Vo()){x.current=!0,Xo().then(_=>{x.current=!1,_.data&&(E.flush(),d.addClipboardImage(_.data,_.size))}).catch(()=>{x.current=!1});return}return}if(D.tab){E.flush(),l.suggestion&&d.acceptSuggestion();return}if(P==="?"&&l.input===""&&!a.showCommandMenu){E.flush(),c.toggleHelp();return}if(D.return&&!a.isReverseSearchActive){E.flush();let _=l.pastedTexts.filter(k=>!k.error||k.type==="text");(l.input.trim()||_.length>0)&&I();return}if(D.upArrow&&!a.showCommandMenu&&!a.isReverseSearchActive){E.flush(),d.navigateHistoryUp();return}if(D.downArrow&&!a.showCommandMenu&&!a.isReverseSearchActive){E.flush(),d.navigateHistoryDown();return}if(D.leftArrow){E.flush(),d.moveCursorLeft();return}if(D.rightArrow){E.flush(),d.moveCursorRight();return}if(D.ctrl&&P==="a"){E.flush(),d.moveCursorToStart();return}if(D.ctrl&&P==="e"){E.flush(),d.moveCursorToEnd();return}if(D.delete||D.backspace){E.flush(),d.deleteAtCursor(),a.showCommandMenu&&((l.input.slice(0,l.cursorPosition-1)+l.input.slice(l.cursorPosition)).startsWith("/")||c.hideCommandMenu());return}if(!D.ctrl&&!D.meta&&P){let _=P.includes(`
|
|
2011
|
+
`),N=P.length>50;if(_||N){E.flush(),d.addPastedContent(P);return}E.pushChar(P)}}}}),Tv(()=>()=>{E.clear()},[E]),{handleCommand:g,isCommand:m,renderProfile:f,memoryPressure:h,frameBudgetStatus:p.getBudgetStatus()}}import{useState as dr,useCallback as Ct,useMemo as Mv,useRef as tg,useEffect as ng}from"react";import{useEffect as Iv,useRef as lc}from"react";import{useInput as PF}from"@jrichman/ink";var kv=0,ei=[];function Pv(){return`keypress-${++kv}`}function Av(i,e,t){let n=Pv();return ei.push({id:n,handler:i,priority:e,isActive:t}),ei.sort((s,r)=>r.priority-s.priority),n}function Dv(i){let e=ei.findIndex(t=>t.id===i);e!==-1&&ei.splice(e,1)}function eg(i,e={}){let{priority:t=0,isActive:n=!0}=e,s=lc(i),r=lc(n),o=lc(null);s.current=i,r.current=n,Iv(()=>(o.current=Av((a,c)=>s.current(a,c),t,()=>r.current),()=>{o.current&&(Dv(o.current),o.current=null)}),[t])}function sg(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]=dr(o),[p,h]=dr(!1),[f,y]=dr(0),[T,x]=dr([]),[S,C]=dr(-1),v=tg(a),I=tg(c);v.current=a,I.current=c;let w=Mv(()=>{if(!g)return[];let W=[],G;try{if(r)G=new RegExp(g,s?"g":"gi");else{let et=g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");G=new RegExp(et,s?"g":"gi")}}catch{return[]}return e.forEach((et,Cs)=>{let yt=t(et),vn=G.exec(yt);vn&&W.push({item:et,index:Cs,matchStart:vn.index,matchEnd:vn.index+vn[0].length}),G.lastIndex=0}),n==="backward"&&W.reverse(),W},[e,g,t,n,s,r]),E=w.length>0&&w[f]||null,P=w.length,D=P>0,$=Ct(W=>{m(W),y(0),C(-1)},[]);ng(()=>{v.current?.(g,w)},[g,w]),ng(()=>{E&&I.current?.(E)},[E]);let R=Ct(()=>{P!==0&&y(W=>(W+1)%P)},[P]),_=Ct(()=>{P!==0&&y(W=>(W-1+P)%P)},[P]),N=Ct(W=>{W>=0&&W<P&&y(W)},[P]),k=Ct(()=>{g&&x(W=>{let G=W.filter(et=>et!==g);return[g,...G].slice(0,d)}),m(""),y(0),C(-1)},[g,d]),M=Ct(()=>{h(!0),$("")},[$]),F=Ct(()=>{k(),h(!1)},[k]),B=Ct(()=>{T.length!==0&&C(W=>{let G=Math.min(W+1,T.length-1);return m(T[G]||""),G})},[T]),H=Ct(()=>{S<0||C(W=>{let G=W-1;return G<0?m(""):m(T[G]||""),G})},[T,S]),V=Ct(W=>{m(G=>G+W),y(0),C(-1)},[]),le=Ct(()=>{m(W=>W.slice(0,-1)),y(0),C(-1)},[]);return eg((W,G)=>{if(p){if(G.downArrow||G.ctrl&&W==="n")return R(),!0;if(G.upArrow||G.ctrl&&W==="p")return _(),!0;if(G.ctrl&&G.upArrow)return B(),!0;if(G.ctrl&&G.downArrow)return H(),!0;if(G.escape)return F(),!0;if(G.return)return k(),h(!1),!0;if(G.backspace||G.delete)return le(),!0;if(W&&W.length===1&&!G.ctrl&&!G.meta)return V(W),!0}},{isActive:l&&p,priority:100}),{query:g,setQuery:$,matches:w,currentMatchIndex:f,currentMatch:E,nextMatch:R,prevMatch:_,goToMatch:N,clear:k,isSearching:p,startSearch:M,stopSearch:F,history:T,historyUp:B,historyDown:H,append:V,backspace:le,matchCount:P,hasMatches:D}}function rg(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 he,{memo as og,useMemo as Nv}from"react";import{Box as gr,Text as pt}from"@jrichman/ink";import _v from"ink-spinner";var ze={Foreground:"#D4D4D4",Background:"#1E1E1E",AccentBlue:"#6B9FD4",AccentPurple:"#B48EAD",AccentCyan:"#88C0D0",AccentGreen:"#A3BE8C",AccentYellow:"#EBCB8B",AccentRed:"#BF616A",Gray:"#808080",DarkGray:"#5C5C5C",LightGray:"#A0A0A0",Comment:"#6A737D"},Rv={text:{primary:ze.Foreground,secondary:ze.LightGray,accent:ze.Foreground,link:ze.AccentBlue,response:ze.Foreground},background:{primary:ze.Background,secondary:"#252526"},border:{default:"#3C3C3C",focused:ze.AccentBlue},ui:{comment:ze.Comment,symbol:ze.Gray,muted:ze.DarkGray},status:{success:ze.AccentGreen,warning:ze.AccentYellow,error:ze.AccentRed,info:ze.Gray}},uc={name:"Default Dark",type:"dark",colors:ze,semantic:Rv};var Ov=uc;function hs(){return Ov}var A={get text(){return hs().semantic.text},get background(){return hs().semantic.background},get border(){return hs().semantic.border},get ui(){return hs().semantic.ui},get status(){return hs().semantic.status},get colors(){return hs().colors}};function $v(i,e){let t=i.toLowerCase();if(t==="read"||t==="readfile")return{displayName:"Read",mainArg:e?.file_path};if(t==="write"||t==="writefile")return{displayName:"Write",mainArg:e?.file_path};if(t==="edit"||t==="editfile")return{displayName:"Edit",mainArg:e?.file_path};if(t==="grep")return{displayName:"Grep",mainArg:e?.pattern};if(t==="glob")return{displayName:"Glob",mainArg:e?.pattern};if(t==="bash"||t==="command"||t==="run_command"){let r=e?.command;return{displayName:"Bash",mainArg:r?r.length>40?r.substring(0,37)+"...":r:void 0}}if(t==="webfetch"||t==="web_fetch")return{displayName:"WebFetch",mainArg:e?.url};if(t==="websearch"||t==="web_search")return{displayName:"WebSearch",mainArg:e?.query};if(t==="task")return{displayName:"Task",mainArg:e?.subagent_type||e?.description};if(t==="todowrite"||t==="todo_write")return{displayName:"",mainArg:void 0};let n=i.charAt(0).toUpperCase()+i.slice(1).replace(/_/g,""),s=e?.description||e?.query||e?.path||e?.url;return{displayName:n,mainArg:s}}function Fv(i){if(!i)return"";let e=i.split("/");return e.length<=2?i:e.slice(-2).join("/")}var dc=og(function({tool:e}){let{displayName:t,mainArg:n}=$v(e.name,e.arguments);if(!t)return null;let s=e.state==="running",r=e.state==="completed",o=e.state==="failed",a=n?Fv(n):void 0;return he.createElement(gr,{flexDirection:"column"},he.createElement(gr,null,s&&he.createElement(pt,{color:A.status.warning},he.createElement(_v,{type:"dots"})),r&&he.createElement(pt,{color:A.status.success},"●"),o&&he.createElement(pt,{color:A.status.error},"●"),he.createElement(pt,null," "),he.createElement(pt,{color:A.text.primary,bold:!0},t),a&&he.createElement(he.Fragment,null,he.createElement(pt,{color:A.ui.muted},"("),he.createElement(pt,{color:A.text.secondary},a),he.createElement(pt,{color:A.ui.muted},")"))),r&&e.output&&he.createElement(gr,{paddingLeft:2},he.createElement(pt,{color:A.ui.muted},"└ "),he.createElement(pt,{color:A.ui.muted},Lv(e.output))),o&&e.error&&he.createElement(gr,{paddingLeft:2},he.createElement(pt,{color:A.ui.muted},"└ "),he.createElement(pt,{color:A.status.error},e.error.substring(0,60))))});function Lv(i){if(!i)return"";let e=i.split(`
|
|
2012
|
+
`).length;return e>1?`${e} lines`:i.length>50?i.substring(0,47)+"...":i}function Uv({activeTools:i}){let{running:e,completed:t,failed:n}=Nv(()=>{if(i.size===0)return{running:[],completed:[],failed:[]};let s=Array.from(i.values()).filter(r=>r.name.toLowerCase().replace(/_/g,"")!=="todowrite");return{running:s.filter(r=>r.state==="running"),completed:s.filter(r=>r.state==="completed").slice(-3),failed:s.filter(r=>r.state==="failed")}},[i]);return e.length===0&&t.length===0&&n.length===0?null:he.createElement(gr,{flexDirection:"column",paddingX:1,marginY:1},e.map(s=>he.createElement(dc,{key:s.toolCallId,tool:s})),t.map(s=>he.createElement(dc,{key:s.toolCallId,tool:s})),n.map(s=>he.createElement(dc,{key:s.toolCallId,tool:s})))}var ig=og(Uv);import oe,{memo as gc,useMemo as ag}from"react";import{Box as jt,Text as Oe}from"@jrichman/ink";import cg from"ink-spinner";function Bv(i,e=60){return i?i.length<=e?i:i.substring(0,e-3)+"...":"Processing..."}var Wv=gc(function({agent:e}){let t=Bv(e.task||"Working..."),n=o=>{switch(o){case"running":return"cyan";case"completed":return"#5AD8A6";case"failed":return"#F5716C";case"timeout":return"#FBBF24";default:return"#6B7280"}},s=()=>e.status==="running"?oe.createElement(Oe,{color:"cyan"},oe.createElement(cg,{type:"dots"})):e.status==="completed"?oe.createElement(Oe,{color:"#5AD8A6"},"[done]"):e.status==="failed"?oe.createElement(Oe,{color:"#F5716C"},"[fail]"):e.status==="timeout"?oe.createElement(Oe,{color:"#FBBF24"},"[time]"):oe.createElement(Oe,{color:"#6B7280"},"[ ]"),r=n(e.status);return oe.createElement(jt,{flexDirection:"column",marginLeft:2},oe.createElement(jt,null,s(),oe.createElement(Oe,{color:r,bold:!0}," Agent #",e.agentNumber)),oe.createElement(jt,{marginLeft:2},oe.createElement(Oe,{color:"#9CA3AF"},t)),e.error&&oe.createElement(jt,{marginLeft:2},oe.createElement(Oe,{color:"#F5716C"},"Error: ",e.error.substring(0,60),e.error.length>60?"...":"")),e.streamingContent&&e.status==="running"&&oe.createElement(jt,{marginLeft:2},oe.createElement(Oe,{color:"#6B7280"},e.streamingContent.split(`
|
|
2013
|
+
`)[0]?.substring(0,50),"...")))}),Hv=gc(function({operation:e}){let{agents:t,completed:n,failed:s,running:r,total:o}=ag(()=>{let d=Array.from(e.agents.values()).sort((g,m)=>g.agentNumber-m.agentNumber);return{agents:d,completed:d.filter(g=>g.status==="completed").length,failed:d.filter(g=>g.status==="failed").length,running:d.filter(g=>g.status==="running").length,total:e.totalAgents}},[e.agents,e.totalAgents]),a=()=>e.status==="starting"||e.status==="running"?`Spawning ${o} agents`:e.status==="completed"?`${o} agents completed`:"Operation failed",c=()=>e.status==="running"||e.status==="starting"?oe.createElement(Oe,{color:"cyan"},oe.createElement(cg,{type:"dots"})):e.status==="completed"?oe.createElement(Oe,{color:"#5AD8A6"},"[done]"):oe.createElement(Oe,{color:"#F5716C"},"[fail]"),l=e.status==="completed"?"#5AD8A6":e.status==="failed"?"#F5716C":"cyan";return oe.createElement(jt,{flexDirection:"column"},oe.createElement(jt,null,c(),oe.createElement(Oe,{color:l,bold:!0}," ",a()),oe.createElement(Oe,{color:"#6B7280"}," "),oe.createElement(Oe,{backgroundColor:"#3F3F46",color:"whiteBright"}," ",n,"/",o," "),r>0&&oe.createElement(Oe,{color:"cyan"}," (",r," running)"),s>0&&oe.createElement(Oe,{color:"#F5716C"}," [",s," failed]")),oe.createElement(jt,{flexDirection:"column",marginTop:1},t.map(d=>oe.createElement(Wv,{key:d.agentNumber,agent:d}))))});function Gv({operations:i}){let e=ag(()=>i.size===0?[]:Array.from(i.entries()).filter(([t,n])=>n.status==="running"||n.status==="starting"?!0:n.endTime?Date.now()-n.endTime.getTime()<1e4:!0),[i]);return e.length===0?null:oe.createElement(jt,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},e.map(([t,n])=>oe.createElement(Hv,{key:t,operation:n})))}var lg=gc(Gv);import Ln,{memo as jv}from"react";import{Box as zv,Text as mr}from"@jrichman/ink";import qv from"ink-spinner";function Kv(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 Vv(i,e=60){return i?i.length<=e?i:i.substring(0,e-3)+"...":"Processing request..."}function Xv({session:i}){if(!i)return null;let e=Kv(i.source),t=Vv(i.message);return Ln.createElement(zv,{flexDirection:"row",paddingX:1,marginY:1,borderStyle:"round",borderColor:A.ui.border},Ln.createElement(mr,{color:A.status.warning},Ln.createElement(qv,{type:"dots"})),Ln.createElement(mr,null," "),Ln.createElement(mr,{color:A.text.primary,bold:!0},e),Ln.createElement(mr,{color:A.ui.muted},": "),Ln.createElement(mr,{color:A.text.secondary},t))}var ug=jv(Xv);import Et,{useState as Yv,useEffect as Qv,useRef as dg,memo as Jv,useMemo as Zv,useCallback as eS}from"react";import{Box as pr,Text as hr}from"@jrichman/ink";import tS from"ink-select-input";var nS=[{label:"Yes, proceed",value:"confirm"},{label:"No, cancel",value:"decline"}];function sS({request:i,onConfirm:e,onDecline:t,onTimeout:n}){let[s,r]=Yv(i.timeout?Math.ceil(i.timeout/1e3):null),o=dg(null),a=dg(0);Qv(()=>{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=eS(g=>{o.current&&(clearInterval(o.current),o.current=null),g.value==="confirm"?e("y"):t()},[e,t]),{actualTargets:l,displayCommand:d}=Zv(()=>{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 Et.createElement(pr,{flexDirection:"column",borderStyle:"round",borderColor:"#525252",paddingX:2,paddingY:1},Et.createElement(hr,{color:"white",bold:!0},i.title),d&&Et.createElement(pr,{marginTop:1},Et.createElement(hr,{color:"gray"},"$ "),Et.createElement(hr,{color:"white"},d)),l.length>0&&Et.createElement(pr,{marginTop:1,flexDirection:"column"},l.map((g,m)=>Et.createElement(hr,{key:m,color:"gray"}," ",g))),s!==null&&Et.createElement(pr,{marginTop:1},Et.createElement(hr,{color:"yellow"},"Auto-cancel in ",s,"s")),Et.createElement(pr,{marginTop:1},Et.createElement(tS,{items:nS,onSelect:c})))}var gg=Jv(sS,(i,e)=>i.request.id===e.request.id&&i.request.timeout===e.request.timeout);import ht,{memo as rS,useMemo as oS}from"react";import{Box as fr,Text as Un}from"@jrichman/ink";var iS=8;function aS({todoList:i}){let{incompleteTodos:e,completedTodos:t,allComplete:n,visibleTodos:s,hiddenCount:r}=oS(()=>{if(!i||i.todos.length===0)return{incompleteTodos:[],completedTodos:[],allComplete:!1,visibleTodos:[],hiddenCount:0};let o=i.todos.filter(g=>g.status!=="completed"),a=i.todos.filter(g=>g.status==="completed"),c=o.length===0&&a.length>0,l=[...o,...a.slice(-2)].slice(0,iS),d=i.todos.length-l.length;return{incompleteTodos:o,completedTodos:a,allComplete:c,visibleTodos:l,hiddenCount:d}},[i]);return!i||i.todos.length===0?null:ht.createElement(fr,{paddingX:2,marginBottom:1,flexShrink:0},ht.createElement(fr,{borderStyle:"round",borderColor:n?A.status.success:A.border.default,paddingX:2,paddingY:1,flexDirection:"column"},ht.createElement(fr,{marginBottom:1},ht.createElement(Un,{color:A.text.primary,bold:!0},"Tasks"),ht.createElement(Un,{color:A.ui.muted}," - "),ht.createElement(Un,{color:n?A.status.success:A.text.secondary},t.length,"/",i.todos.length,n&&" ✓")),s.map((o,a)=>{let c=o.status==="completed"?"[done]":o.status==="in_progress"?"[..]":"[ ]",l=o.status==="completed"?A.status.success:o.status==="in_progress"?A.text.accent:A.ui.muted,d=o.status==="in_progress"&&o.activeForm?o.activeForm:Xu(o);return ht.createElement(fr,{key:o.id||`todo-${a}`},ht.createElement(Un,{color:l},c),ht.createElement(Un,{color:A.ui.muted}," "),ht.createElement(Un,{color:o.status==="completed"?A.ui.muted:A.text.primary},d))}),r>0&&ht.createElement(fr,{marginTop:0},ht.createElement(Un,{color:A.ui.muted}," +",r," more tasks"))))}var mg=rS(aS);import Ne,{memo as cS}from"react";import{Box as mc,Text as Je}from"@jrichman/ink";function lS(){return Ne.createElement(mc,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},Ne.createElement(Je,{bold:!0,color:"whiteBright"},"Keyboard Shortcuts"),Ne.createElement(mc,{marginTop:1,flexDirection:"column"},Ne.createElement(Je,{color:"#9CA3AF"},"• ",Ne.createElement(Je,{color:"whiteBright",bold:!0},"Enter")," ",Ne.createElement(Je,{color:"#9CA3AF"},"Submit message")),Ne.createElement(Je,{color:"#9CA3AF"},"• ",Ne.createElement(Je,{color:"whiteBright",bold:!0},"?")," ",Ne.createElement(Je,{color:"#9CA3AF"},"Toggle this help")),Ne.createElement(Je,{color:"#9CA3AF"},"• ",Ne.createElement(Je,{color:"whiteBright",bold:!0},"Esc")," ",Ne.createElement(Je,{color:"#9CA3AF"},"Stop generation / Close menus")),Ne.createElement(Je,{color:"#9CA3AF"},"• ",Ne.createElement(Je,{color:"whiteBright",bold:!0},"Ctrl+C")," ",Ne.createElement(Je,{color:"#9CA3AF"},"Stop generation / Exit"))),Ne.createElement(mc,{marginTop:1},Ne.createElement(Je,{color:"#6B7280"},"Press Esc to close")))}var pg=cS(lS);import Ae,{memo as hS,useMemo as fS,useCallback as bS}from"react";import{Box as ni,Text as tt}from"@jrichman/ink";import fs,{useState as uS,useEffect as dS,memo as hg}from"react";import{Box as pc,Text as fg,useInput as gS}from"@jrichman/ink";var mS=hg(function({item:e,isSelected:t,highlightColor:n}){return fs.createElement(fg,{color:t?"#000":"#fff",backgroundColor:t?n:void 0},e.label)});function pS({items:i,onSelect:e,onHighlight:t,isFocused:n=!0,highlightColor:s="#D97706",itemComponent:r=mS}){let[o,a]=uS(0);return dS(()=>{a(0)},[i.length]),gS((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?fs.createElement(pc,null,fs.createElement(fg,{color:"#6B7280"},"No items")):fs.createElement(pc,{flexDirection:"column"},i.map((c,l)=>{let d=l===o;return fs.createElement(pc,{key:c.value||l},fs.createElement(r,{item:c,isSelected:d,highlightColor:s}))}))}var ti=hg(pS);Kt();Sn();function yS({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}=fS(()=>{let a=me.filter(p=>p.name.startsWith("snowx-o4")||p.name.startsWith("snowx-c")||p.name.startsWith("snowx-h")),c=me.filter(p=>p.name.startsWith("snowx-5")||p.name.startsWith("snowx-o3")||p.name.startsWith("snowx-4")),l=me.filter(p=>p.name.startsWith("snowx-g")),d=p=>p.map(h=>{let f=xe.isModelAccessible(h.name,i),y=n(h.creditMultiplier);return{label:`${f?"":"[LOCKED] "}${h.displayName} ${y}`,value:h.name,isAccessible:f,creditMultiplier:h.creditMultiplier,isHeader:!1}}),g=[{label:"-- Claude --",value:"_claude_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(a),{label:"-- GPT --",value:"_gpt_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(c),{label:"-- Gemini --",value:"_gemini_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...d(l)],m=g.filter(p=>!p.isHeader);return{allItems:g,selectableItems:m}},[i]),o=bS(a=>{if(a.value.startsWith("_"))return;if(!s.find(d=>d.value===a.value)?.isAccessible){t(a.value);return}let l=me.find(d=>d.name===a.value);l&&e(l)},[s,t,e]);return Ae.createElement(ni,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},Ae.createElement(tt,{bold:!0,color:"whiteBright"},"Select Model"),Ae.createElement(ni,null,Ae.createElement(tt,{color:"#6B7280"},"Tier: ",xe.getDisplayName(i)," - "),Ae.createElement(tt,{color:"#5AD8A6"},"[0.5x]"),Ae.createElement(tt,{color:"#6B7280"}," "),Ae.createElement(tt,{color:"#9CA3AF"},"[1x]"),Ae.createElement(tt,{color:"#6B7280"}," "),Ae.createElement(tt,{color:"#60A5FA"},"[1.5x]"),Ae.createElement(tt,{color:"#6B7280"}," "),Ae.createElement(tt,{color:"#FBBF24"},"[2x]"),Ae.createElement(tt,{color:"#6B7280"}," "),Ae.createElement(tt,{color:"#F472B6"},"[2.5x]"),Ae.createElement(tt,{color:"#6B7280"}," credits")),Ae.createElement(ni,{marginTop:1},Ae.createElement(ti,{items:r.map(a=>({label:a.label,value:a.value})),onSelect:o,isFocused:!0,highlightColor:"#D97706"})),Ae.createElement(ni,{marginTop:1},Ae.createElement(tt,{color:"#6B7280"},"Esc to cancel")))}var bg=hS(yS);import bs,{memo as Sg,useMemo as vS,useCallback as SS}from"react";import{Box as hc,Text as yg}from"@jrichman/ink";var vg=[{command:"/model",description:"change AI model",value:"model"},{command:"/usage",description:"view usage & limits",value:"usage"},{command:"/new",description:"start new conversation",value:"new"},{command:"/clear",description:"clear conversation",value:"clear"},{command:"/stop",description:"stop current generation",value:"stop"},{command:"/vision",description:"toggle vision mode",value:"vision"},{command:"/img",description:"paste image from clipboard",value:"img"},{command:"/export",description:"export conversation (md/json/txt)",value:"export"},{command:"/discord",description:"discord integration",value:"discord"},{command:"/telegram",description:"telegram integration",value:"telegram"},{command:"/signout",description:"sign out and exit",value:"signout"},{command:"/help",description:"show help",value:"help"},{command:"/exit",description:"exit the app",value:"exit"}],wS=Sg(function({item:e,isSelected:t,highlightColor:n}){let[s,r]=e.label.split(" ");return bs.createElement(hc,{width:50,backgroundColor:t?n:void 0},bs.createElement(hc,{width:14},bs.createElement(yg,{color:t?"#1a1a1a":"whiteBright",bold:!0},s)),bs.createElement(yg,{color:t?"#1a1a1a":"#6B7280"},r))});function TS({filterText:i,onSelect:e}){let t=vS(()=>(i?vg.filter(r=>r.value.toLowerCase().includes(i)):vg).map(r=>({label:`${r.command} ${r.description}`,value:r.value})),[i]),n=SS(s=>{s.value&&e(s.value)},[e]);return bs.createElement(hc,{flexDirection:"column",paddingX:1,paddingY:1,width:"100%",borderStyle:"single",borderColor:"#3F3F46",backgroundColor:"#18181B"},bs.createElement(ti,{items:t.length>0?t:[{label:"No matching commands",value:""}],onSelect:n,itemComponent:wS,isFocused:!0,highlightColor:"#D97706"}))}var wg=Sg(TS);import ne,{useState as si,useEffect as xS,useCallback as ri,memo as CS}from"react";import{Box as qe,Text as _e,useInput as ES}from"@jrichman/ink";import IS from"ink-spinner";import{exec as kS}from"child_process";var ce={brand:"#A78BFA",text:"#F8FAFC",muted:"#94A3B8",dim:"#64748B",border:"#334155",error:"#EF4444",success:"#22C55E"},PS=[{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"}],AS=[{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 DS({type:i}){let e=Ut(),t=xt(),n=Ka(),[s,r]=si(""),[o,a]=si(null),[c,l]=si(!1),[d,g]=si(0),m=Wt.getInstance(),p=i==="discord"?PS:AS,h=p.find(w=>w.id===n.step),f=p.length-1,y=ri(w=>{let E=process.platform,P;E==="darwin"?P=`open "${w}"`:E==="win32"?P=`start "" "${w}"`:P=`xdg-open "${w}"`,kS(P,()=>{})},[]);ES((w,E)=>{if(n.isOpen){if(E.escape){e.hideWizard();return}if(h?.type==="input"){if(E.return){T();return}if(E.backspace||E.delete){r(P=>P.slice(0,-1)),a(null);return}w&&!E.ctrl&&!E.meta&&!E.leftArrow&&!E.rightArrow&&!E.upArrow&&!E.downArrow&&!E.tab&&(r(P=>P+w),a(null))}else if(h?.type==="confirm"){if(E.leftArrow||E.rightArrow||w==="y"||w==="n"){g(w==="y"?1:w==="n"?0:P=>P===0?1:0);return}if(E.return){x();return}}}},{isActive:n.isOpen});let T=ri(()=>{let w=n.step,E=s.trim();if(i==="discord"){if(w===1){if(!E){a("Bot token is required");return}if(!m.validateDiscordToken(E)){a("Invalid token format. Should be like: MTIz...xxx.Yyy...zzz");return}e.setWizardData("botToken",E)}else if(w===2){if(!E){a("At least one owner ID is required");return}if(E.split(",").map(D=>D.trim()).some(D=>!/^\d{17,19}$/.test(D))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("ownerIds",E)}else if(w===3){if(E&&E.split(",").map(D=>D.trim()).filter(Boolean).some(D=>!/^\d{17,19}$/.test(D))){a("User IDs should be 17-19 digit numbers");return}e.setWizardData("guestIds",E)}}else if(w===1){if(!E){a("Bot token is required");return}if(!m.validateTelegramToken(E)){a("Invalid token format. Should be like: 123456789:ABCdef...");return}e.setWizardData("botToken",E)}else if(w===2){if(!E){a("At least one owner username is required");return}e.setWizardData("ownerUsernames",E)}else w===3&&e.setWizardData("guestUsernames",E);r(""),a(null),e.setWizardStep(w+1)},[n.step,i,s,m,e]),x=ri(()=>{let w=n.step,E=d===1;i==="discord"?w===4&&(e.setWizardData("allowGuildChat",E),e.setWizardStep(5)):w===4?(e.setWizardData("allowGroupChat",E),E?e.setWizardStep(5):(e.setWizardData("routeToDM",!1),e.setWizardStep(6))):w===5&&(e.setWizardData("routeToDM",E),e.setWizardStep(6)),g(0)},[n.step,i,d,e]),S=ri(async w=>{try{if(i==="discord"){let E=await m.connectDiscord({botToken:w.botToken,ownerUserIds:w.ownerIds.split(",").map(P=>P.trim()).filter(Boolean),guestUserIds:w.guestIds?w.guestIds.split(",").map(P=>P.trim()).filter(Boolean):[],allowGuildChat:w.allowGuildChat||!1});if(E.success){let P=E.botId?m.generateDiscordInviteUrl(E.botId):"";t.addSystemMessage(`✓ Discord connected!
|
|
2010
2014
|
|
|
2011
2015
|
Bot: ${E.botUsername}
|
|
2012
2016
|
`+(P?`Invite URL: ${P}
|
|
2013
2017
|
`:"")+`
|
|
2014
|
-
Commands: /ask, /new, /clear`),P&&y(P)}else t.addSystemMessage(`✗ Discord setup failed: ${E.error}`)}else{let E=await m.connectTelegram({botToken:
|
|
2018
|
+
Commands: /ask, /new, /clear`),P&&y(P)}else t.addSystemMessage(`✗ Discord setup failed: ${E.error}`)}else{let E=await m.connectTelegram({botToken:w.botToken,ownerUsernames:w.ownerUsernames.split(",").map(P=>P.trim().replace(/^@/,"")).filter(Boolean),guestUsernames:w.guestUsernames?w.guestUsernames.split(",").map(P=>P.trim().replace(/^@/,"")).filter(Boolean):[],allowGroupChat:w.allowGroupChat||!1,routeToDM:w.routeToDM||!1});if(E.success){let P=m.getTelegramChatUrl(E.botUsername||"");t.addSystemMessage(`✓ Telegram connected!
|
|
2015
2019
|
|
|
2016
2020
|
Bot: @${E.botUsername}
|
|
2017
2021
|
Chat: ${P}
|
|
2018
2022
|
|
|
2019
|
-
Send /new to start`),y(P)}else t.addSystemMessage(`✗ Telegram setup failed: ${E.error}`)}}catch(E){t.addSystemMessage(`✗ Connection error: ${E.message}`)}e.resetWizard()},[i,m,t,y,e]);bS(()=>{(i==="discord"&&n.step===5||i==="telegram"&&n.step===6)&&!c&&(l(!0),T(n.data))},[n.step,n.data,i,c,T]);let x=()=>{let S=Math.min(n.step,f),E="━".repeat(S),P="─".repeat(f-S);return ne.createElement(ze,null,ne.createElement(_e,{color:ce.brand},E),ne.createElement(_e,{color:ce.dim},P),ne.createElement(_e,{color:ce.muted}," ",S,"/",f))},v=()=>h?h.type==="loading"?ne.createElement(ze,{flexDirection:"column",paddingY:1},ne.createElement(ze,null,ne.createElement(_e,{color:ce.brand},ne.createElement(SS,{type:"dots"})),ne.createElement(_e,{color:ce.muted}," Connecting to ",i==="discord"?"Discord":"Telegram","..."))):h.type==="input"?ne.createElement(ze,{flexDirection:"column"},ne.createElement(_e,{color:ce.text},h.help),ne.createElement(_e,{color:ce.dim},h.hint),ne.createElement(ze,{marginTop:1,flexDirection:"column"},ne.createElement(ze,{paddingX:1,borderStyle:"round",borderColor:o?ce.error:ce.brand},ne.createElement(_e,{color:s?ce.text:ce.dim},s||h.placeholder||"Type here..."),ne.createElement(_e,{color:ce.brand},"▎")),o&&ne.createElement(ze,{marginTop:1},ne.createElement(_e,{color:ce.error},"✗ ",o)))):h.type==="confirm"?ne.createElement(ze,{flexDirection:"column"},ne.createElement(_e,{color:ce.text},h.help),ne.createElement(_e,{color:ce.dim},h.hint),ne.createElement(ze,{marginTop:1,gap:2},ne.createElement(ze,{paddingX:2,borderStyle:"round",borderColor:d===0?ce.brand:ce.border},ne.createElement(_e,{color:d===0?ce.brand:ce.muted},"No")),ne.createElement(ze,{paddingX:2,borderStyle:"round",borderColor:d===1?ce.brand:ce.border},ne.createElement(_e,{color:d===1?ce.brand:ce.muted},"Yes")))):null:null,I=i==="discord"?"Discord Setup":"Telegram Setup";return ne.createElement(ze,{flexDirection:"column",borderStyle:"round",borderColor:ce.border,paddingX:2,paddingY:1,width:60},ne.createElement(ze,{marginBottom:1,justifyContent:"space-between"},ne.createElement(_e,{bold:!0,color:ce.brand},I),x()),ne.createElement(ze,{marginBottom:1},ne.createElement(_e,{bold:!0,color:ce.text},h?.title)),v(),ne.createElement(ze,{marginTop:1,borderStyle:"single",borderTop:!0,borderColor:ce.border,paddingTop:1},ne.createElement(_e,{color:ce.dim},h?.type==="confirm"?"← → or y/n to select • enter to confirm • esc to cancel":h?.type==="loading"?"Please wait...":"enter to continue • esc to cancel")))}var yg=yS(CS);import De,{memo as ES,useMemo as si}from"react";import{Box as mn,Text as pn}from"@jrichman/ink";var vg=(i,e=60)=>i.length>e?i.substring(0,e)+"...":i;function IS({regularQueuedMessages:i,crossDeviceTasks:e}){let t=si(()=>i.length===0?null:i.map((o,a)=>De.createElement(mn,{key:o.id,borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,marginBottom:1},De.createElement(mn,null,De.createElement(pn,{color:"whiteBright",bold:!0},a+1),De.createElement(pn,{color:"#6B7280"}," • "),De.createElement(pn,{color:"#9CA3AF"},vg(o.content))))),[i]),n=si(()=>e.length===0?null:e.map((o,a)=>De.createElement(mn,{key:`cross-${o.id}`,borderStyle:"round",borderColor:"#0E7490",paddingX:2,paddingY:0,marginBottom:1},De.createElement(mn,null,De.createElement(pn,{color:"#22D3EE",bold:!0},"[M] ",a+1),De.createElement(pn,{color:"#6B7280"}," - "),De.createElement(pn,{color:"#9CA3AF"},vg(o.content))))),[e]),s=si(()=>{let o=i.length;return`${o} message${o>1?"s":""} queued`},[i.length]),r=si(()=>{let o=e.length;return`${o} cross-device task${o>1?"s":""} waiting`},[e.length]);return De.createElement(De.Fragment,null,t&&De.createElement(mn,{flexDirection:"column",paddingX:2,marginBottom:1},t,De.createElement(mn,null,De.createElement(pn,{color:"#9CA3AF"},s))),n&&De.createElement(mn,{flexDirection:"column",paddingX:2,marginBottom:1},n,De.createElement(mn,null,De.createElement(pn,{color:"#22D3EE"},r))))}var Sg=ES(IS,(i,e)=>i.regularQueuedMessages.length===e.regularQueuedMessages.length&&i.crossDeviceTasks.length===e.crossDeviceTasks.length&&i.regularQueuedMessages.every((t,n)=>t.id===e.regularQueuedMessages[n]?.id)&&i.crossDeviceTasks.every((t,n)=>t.id===e.crossDeviceTasks[n]?.id));import Q,{memo as kS,useMemo as Tg}from"react";import{Box as nt,Text as de}from"@jrichman/ink";import xg from"path";import Je,{memo as ri}from"react";import{Box as br,Text as zt}from"@jrichman/ink";var oi={normal:{symbol:"",label:"",color:A.text.primary,description:"Normal mode"},yolo:{symbol:"*",label:"YOLO",color:A.status.error,description:"Auto-approve all actions"},plan:{symbol:">",label:"PLAN",color:A.status.success,description:"Planning mode - no execution"},shell:{symbol:"!",label:"SHELL",color:A.status.warning,description:"Shell command mode"},auto:{symbol:">",label:"AUTO",color:A.status.warning,description:"Auto-accept suggestions"}},HL=ri(function({mode:e,showLabel:t=!1,size:n="normal"}){if(e==="normal")return null;let s=oi[e];return n==="compact"?Je.createElement(zt,{color:s.color,bold:!0},s.symbol):Je.createElement(br,{flexDirection:"row",alignItems:"center"},Je.createElement(zt,{color:s.color,bold:!0},s.symbol),t&&Je.createElement(br,{marginLeft:1},Je.createElement(zt,{color:s.color,bold:!0},s.label)))}),GL=ri(function({mode:e,isActive:t=!0}){if(e==="normal")return null;let n=oi[e],s=t?n.color:A.ui.muted;return Je.createElement(zt,{color:s,bold:t},"[",n.label,"]")}),jL=ri(function({selectedMode:e,availableModes:t=["normal","yolo","plan","auto"],isFocused:n=!1}){return Je.createElement(br,{flexDirection:"row",alignItems:"center"},Je.createElement(zt,{color:A.text.secondary},"Mode: "),t.map((s,r)=>{let o=oi[s],a=s===e,c=s==="normal"?"NORMAL":o.label;return Je.createElement(br,{key:s,flexDirection:"row"},r>0&&Je.createElement(zt,{color:A.ui.muted}," | "),Je.createElement(zt,{color:a?o.color:A.ui.muted,bold:a,inverse:a&&n},c))}))}),wg=ri(function({mode:e,promptSymbol:t="❯",isFocused:n=!0}){let s=oi[e],r=e!=="normal",o=r?s.color:n?A.text.accent:A.ui.muted;return Je.createElement(br,{flexDirection:"row",alignItems:"center"},r&&Je.createElement(zt,{color:s.color,bold:!0},s.symbol),Je.createElement(zt,{color:o},t))});var PS=" Type your message or @path/to/file";function AS({input:i,isLoading:e,pastedTexts:t,cursorPosition:n,suggestion:s,mode:r="normal"}){let{hasContent:o,ghostText:a}=Tg(()=>{let l=i.length>0||t.length>0,d=s&&s.toLowerCase().startsWith(i.toLowerCase())&&i.length>0?s.slice(i.length):null;return{hasContent:l,ghostText:d}},[i,t.length,s]),c=Tg(()=>t.length===0?null:t.map((l,d)=>{if(l.type==="clipboard_image"){let p=l.fileSize?` ${ln(l.fileSize)}`:"",h=!!l.error;return Q.createElement(nt,{key:`pasted-${l.id}`,flexDirection:"column"},Q.createElement(nt,null,Q.createElement(de,{color:h?A.status.error:A.status.info}," ","[CLIPBOARD] "),Q.createElement(de,{color:h?A.status.error:A.text.secondary},"Image"),p&&Q.createElement(de,{color:A.ui.muted},p)),h&&Q.createElement(nt,{marginLeft:4},Q.createElement(de,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}if(l.type==="image_path"&&l.filePath){let p=qa(xg.basename(l.filePath)),h=l.fileSize?` ${ln(l.fileSize)}`:"",f=!!l.error;return Q.createElement(nt,{key:`pasted-${l.id}`,flexDirection:"column"},Q.createElement(nt,null,Q.createElement(de,{color:f?A.status.error:A.status.info}," ","[IMG] "),Q.createElement(de,{color:f?A.status.error:A.text.secondary},p),h&&Q.createElement(de,{color:A.ui.muted},h)),f&&Q.createElement(nt,{marginLeft:4},Q.createElement(de,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}if(l.type==="file_path"&&l.filePath){let p=qa(xg.basename(l.filePath)),h=l.fileSize?` ${ln(l.fileSize)}`:"",f=!!l.error;return Q.createElement(nt,{key:`pasted-${l.id}`,flexDirection:"column"},Q.createElement(nt,null,Q.createElement(de,{color:f?A.status.error:A.status.info}," ","[FILE] "),Q.createElement(de,{color:f?A.status.error:A.text.secondary},p),h&&Q.createElement(de,{color:A.ui.muted},h)),f&&Q.createElement(nt,{marginLeft:4},Q.createElement(de,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}let g=l.lineCount-1,m=g>0?`+${g} lines`:"1 line";return Q.createElement(nt,{key:`pasted-${l.id}`},Q.createElement(de,{color:A.ui.muted}," ","[TEXT] "),Q.createElement(de,{color:A.text.secondary},"Pasted text #",d+1),Q.createElement(de,{color:A.ui.muted}," (",m,")"))}),[t]);return Q.createElement(nt,{borderStyle:"round",borderColor:o?A.border.focused:A.border.default,paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},c&&Q.createElement(nt,{flexDirection:"column",marginBottom:0},c),Q.createElement(nt,null,Q.createElement(wg,{mode:r,isFocused:!e}),Q.createElement(de,null," "),i.length===0&&!e?s?Q.createElement(de,null,Q.createElement(de,{inverse:!0}," "),Q.createElement(de,{color:A.ui.muted},s),Q.createElement(de,{color:A.ui.muted,dimColor:!0}," (Tab to accept)")):Q.createElement(de,{color:A.ui.muted},PS):Q.createElement(de,null,Q.createElement(de,{color:A.text.primary},i.slice(0,n)),!e&&Q.createElement(de,{inverse:!0}," "),Q.createElement(de,{color:A.text.primary},i.slice(n)),a&&Q.createElement(de,{color:A.ui.muted},a))))}var Cg=kS(AS,(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 yr,{useState as DS,useEffect as MS,useRef as RS,memo as OS}from"react";import{Box as NS,Text as mc}from"@jrichman/ink";import _S from"ink-spinner";function $S(i){if(i<60)return`${i}s`;let e=Math.floor(i/60),t=i%60;return`${e}m ${t}s`}function FS({isLoading:i,phrase:e="Processing",startTime:t}){let[n,s]=DS(0),r=RS(null);return MS(()=>{if(r.current&&(clearInterval(r.current),r.current=null),!i){s(0);return}let o=t||Date.now();return r.current=setInterval(()=>{let a=Date.now(),c=Math.floor((a-o)/1e3);s(c)},1e3),()=>{r.current&&(clearInterval(r.current),r.current=null)}},[i,t]),i?yr.createElement(NS,{flexDirection:"row",alignItems:"center",paddingX:2,marginBottom:1,flexShrink:0},yr.createElement(mc,{color:A.text.accent},yr.createElement(_S,{type:"dots"})),yr.createElement(mc,{color:A.text.primary}," ",e,"... "),yr.createElement(mc,{color:A.text.secondary},"(esc to cancel",n>0?`, ${$S(n)}`:"",")")):null}var Eg=OS(FS);import Se,{memo as zS,useMemo as Rg}from"react";import{Box as ws,Text as st}from"@jrichman/ink";import{useState as Ig,useEffect as kg,useCallback as LS,useRef as Pg}from"react";import{useStdout as US}from"@jrichman/ink";var ys=80,vs=24,BS=100;function Ss(i){let{debounceMs:e=BS}=i||{},{stdout:t}=US(),[n,s]=Ig({width:t?.columns||ys,height:t?.rows||vs,rows:t?.rows||vs,columns:t?.columns||ys}),[r,o]=Ig(!1),a=Pg(null),c=Pg(null);kg(()=>{function d(){o(!0),a.current&&clearTimeout(a.current),c.current&&clearTimeout(c.current),a.current=setTimeout(()=>{let g=process.stdout.columns||ys,m=process.stdout.rows||vs;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]),kg(()=>{if(t){let d=t.columns||ys,g=t.rows||vs;(d!==n.width||g!==n.height)&&s({width:d,height:g,rows:g,columns:d})}},[t?.columns,t?.rows]);let l=LS(()=>{s({width:process.stdout.columns||ys,height:process.stdout.rows||vs,rows:process.stdout.rows||vs,columns:process.stdout.columns||ys})},[]);return{...n,isResizing:r,refresh:l}}Io();import{useState as hn,useEffect as WS,useRef as HS}from"react";function Ag(i=1e4){let[e,t]=hn("not-ready"),[n,s]=hn(!1),[r,o]=hn(!1),[a,c]=hn(0),[l,d]=hn(5),[g,m]=hn(0),[p,h]=hn(!1),[f,y]=hn(!1),w=HS(!1);return WS(()=>{let C=()=>{let x=te.getStatus();x.initState==="idle"&&!w.current&&(w.current=!0,te.initialize().catch(v=>{console.debug("[useBrowserStatus] Auto-init failed:",v.message)}),x=te.getStatus()),x.isInitializing||x.initState==="initializing"?t("initializing"):x.isRunning&&x.isInitialized?t("ready"):t("not-ready"),s(x.hasBrowser??!1),o(x.multiAgentMode??!1),c(x.runningAgentCount??0),d(x.maxConcurrentAgents??5),m(x.tabCount??0),h(x.isExecuting??!1),y(x.hasActiveSession??!1)};C();let T=setInterval(C,i);return()=>clearInterval(T)},[i]),{status:e,hasBrowser:n,multiAgentMode:r,runningAgentCount:a,maxConcurrentAgents:l,tabCount:g,isExecuting:p,hasActiveSession:f}}import{useState as ii,useEffect as GS,useCallback as Dg}from"react";var jS=300*1e3;function Mg(){let[i,e]=ii(null),[t,n]=ii(null),[s,r]=ii(!1),[o,a]=ii(null),c=Dg(async(m=!1)=>{r(!0),a(null);try{let p=await lr.fetchQuotaStatus(m);e(p);let h=await lr.getUsageDisplayData();n(h)}catch(p){a(p instanceof Error?p.message:"Failed to fetch quota")}finally{r(!1)}},[]),l=Dg(async()=>{await c(!0)},[c]);GS(()=>{c();let m=setInterval(()=>{c(!0)},jS);return()=>clearInterval(m)},[c]);let d=t?Bd(t.percent):"normal",g=t?ur(t.resetsAt,t.resetsInSeconds):"";return{quota:i,usageDisplay:t,severity:d,resetTimeDisplay:g,isLoading:s,error:o,refresh:l}}Sn();import{createRequire as qS}from"module";var KS=qS(import.meta.url),VS=KS("../../../package.json"),XS=VS.version,YS={3:"#FFD700",2:"#A78BFA",1:"#60A5FA",0:A.ui.muted},QS={ready:"#10B981",initializing:"#F59E0B","not-ready":"#F97316"},JS={normal:A.ui.muted,notice:"#60A5FA",warning:"#FBBF24",high:"#F97316",critical:"#EF4444"};function ZS(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function ew(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 tw({cwd:i,selectedModel:e,showScrollHint:t=!1,tier:n=0}){let{width:s}=Ss(),{status:r}=Ag(),{usageDisplay:o,severity:a,resetTimeDisplay:c}=Mg(),l=xe.getDisplayName(n),d=YS[n]||A.ui.muted,{displayPath:g,shortcuts:m}=Rg(()=>{let h=`${e.displayName} /model`,f=" ● browser",y=t?"? help · Shift+↑↓ scroll":"? help",C=h.length+f.length+y.length+" ".length*2+4,T=Math.max(15,Math.floor((s-C)*.4));return{displayPath:ew(ZS(i),T),shortcuts:y}},[i,e.displayName,t,s]),p=Rg(()=>{if(!o)return null;let{percent:h,type:f}=o,y=f==="weekly"?"weekly":"5-hour";return h>=100?`You've hit your ${y} limit`:h>=90?`${h}% of ${y} limit used`:`${h}% ${y} usage`},[o]);return Se.createElement(ws,{flexDirection:"column",width:"100%"},o&&Se.createElement(ws,{paddingX:2,justifyContent:"center"},Se.createElement(st,{color:JS[a]},p),c&&Se.createElement(Se.Fragment,null,Se.createElement(st,{color:A.ui.muted}," · "),Se.createElement(st,{color:A.ui.muted},"Resets in ",c))),Se.createElement(ws,{paddingX:2,paddingY:0,width:"100%",justifyContent:"space-between",flexDirection:"row"},Se.createElement(ws,null,Se.createElement(st,{color:A.text.link},g),Se.createElement(st,{color:A.ui.muted}," v",XS),Se.createElement(st,{color:A.ui.muted}," · "),Se.createElement(st,{color:d,bold:!0},l)),Se.createElement(ws,null,Se.createElement(st,{color:A.text.accent},e.displayName),Se.createElement(st,{color:A.text.secondary}," /model"),Se.createElement(st,{color:A.text.secondary}," "),Se.createElement(st,{color:QS[r]},"●"),Se.createElement(st,{color:A.text.secondary}," browser")),Se.createElement(ws,null,Se.createElement(st,{color:A.text.secondary},m))))}var Og=zS(tw);import fn,{useState as ai,useEffect as sw,useRef as ci,useCallback as rw,useLayoutEffect as ow,memo as iw}from"react";import{Box as vr,Text as Fg,getScrollHeight as aw,getInnerHeight as cw,useInput as lw}from"@jrichman/ink";import{useRef as Ng,useEffect as nw,useCallback as _g}from"react";function $g(i){let e=Ng(null),t=Ng(i);nw(()=>{t.current=i,e.current=null});let n=_g(()=>e.current??t.current,[]),s=_g(r=>{e.current=r},[]);return{getScrollTop:n,setPendingScrollTop:s}}var Lg=3;function uw({children:i,reservedLines:e=8,autoScrollToBottom:t=!0,hasFocus:n=!0}){let{height:s}=Ss(),r=Math.max(5,s-e),[o,a]=ai(0),[c,l]=ai({innerHeight:0,scrollHeight:0}),[d,g]=ai(!1),[m,p]=ai(!0),h=ci(null),f=ci(c),y=ci(0),w=ci(o),{getScrollTop:C,setPendingScrollTop:T}=$g(o),x=Qo({targetFrameTime:16.67}),v=Yo("ScrollableContainer");sw(()=>{f.current=c},[c]),ow(()=>{if(!h.current)return;let D=Math.round(cw(h.current)),$=Math.round(aw(h.current)),R=Math.max(0,$-D);w.current>=f.current.scrollHeight-f.current.innerHeight-1&&o>=w.current&&p(!0),(c.innerHeight!==D||c.scrollHeight!==$)&&(l({innerHeight:D,scrollHeight:$}),m&&t&&a(R));let N=$>r;N!==d&&g(N);let k=fn.Children.count(i);t&&y.current!==k&&m&&a(R),y.current=k,w.current=o});let I=rw(D=>{if(!x.hasBudget()){$n(()=>I(D));return}let{scrollHeight:$,innerHeight:R}=f.current,_=Math.max(0,$-R);D<0&&p(!1);let N=C(),k=Math.min(Math.max(0,N+D),_);k>=_-1&&p(!0),T(k),a(k),x.useBudget(2)},[C,T,x]);lw((D,$)=>{if(n){if($.pageUp){I(-r+2);return}if($.pageDown){I(r-2);return}if($.shift&&$.upArrow){I(-Lg);return}if($.shift&&$.downArrow){I(Lg);return}}},{isActive:n});let S=Math.max(0,c.scrollHeight-c.innerHeight),E=o>0,P=o<S;return fn.createElement(vr,{flexDirection:"column",flexGrow:1},E&&fn.createElement(vr,{paddingX:2},fn.createElement(Fg,{color:A.text.secondary},"↑ Page Up / Shift+↑ to scroll up")),fn.createElement(vr,{ref:h,height:d?r:void 0,flexDirection:"column",overflowY:d?"scroll":"hidden",overflowX:"hidden",scrollTop:o,flexGrow:1},fn.createElement(vr,{flexDirection:"column",flexShrink:0,paddingRight:1},i)),P&&fn.createElement(vr,{paddingX:2},fn.createElement(Fg,{color:A.text.secondary},"↓ Page Down / Shift+↓ to scroll down")))}var Ug=iw(uw);import bc,{memo as yc}from"react";import{Box as Ww}from"@jrichman/ink";import ie,{memo as _w,useMemo as Yg}from"react";import{Box as it,Text as ft}from"@jrichman/ink";import Ts,{memo as dw}from"react";import{Box as li,Text as Bg}from"@jrichman/ink";function gw({suggestions:i,onSelect:e}){return i.length===0?null:Ts.createElement(li,{flexDirection:"column",marginTop:1,width:"100%"},i.map((t,n)=>Ts.createElement(li,{key:`sug-block-${n}`,flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},t.options.map((s,r)=>Ts.createElement(li,{key:`sug-opt-${n}-${r}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},Ts.createElement(Bg,{color:"#22D3EE"},s))))),e&&Ts.createElement(li,{marginTop:0,width:"100%"},Ts.createElement(Bg,{color:"#6B7280"},"Type a suggestion to use it")))}var Wg=dw(gw,(i,e)=>i.suggestions===e.suggestions?!0:i.suggestions.length!==e.suggestions.length?!1:i.suggestions.every((t,n)=>{let s=e.suggestions[n];return t.options.length===s.options.length&&t.options.every((r,o)=>r===s.options[o])}));import Un,{memo as mw}from"react";import{Box as ui,Text as pc}from"@jrichman/ink";function pw({workingFiles:i}){return i.length===0?null:Un.createElement(ui,{flexDirection:"column",marginTop:1,width:"100%"},Un.createElement(ui,{marginBottom:0,width:"100%"},Un.createElement(pc,{color:"#9CA3AF",bold:!0},"Working Files"),Un.createElement(pc,{color:"#6B7280"}," (",i.length,")")),Un.createElement(ui,{flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},i.map(e=>Un.createElement(ui,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},Un.createElement(pc,{color:"white"},e.name)))))}var Hg=mw(pw,(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 rt,{memo as hw,useMemo as fw,useState as bw}from"react";import{Box as Sr,Text as bn}from"@jrichman/ink";var hc=5;function yw({conversationHistory:i,onSelect:e}){let[t,n]=bw(!1),{displayedItems:s,hiddenCount:r}=fw(()=>i.length<=hc||t?{displayedItems:i,hiddenCount:0}:{displayedItems:i.slice(0,hc),hiddenCount:i.length-hc},[i,t]);return i.length===0?null:rt.createElement(Sr,{flexDirection:"column",marginTop:1},rt.createElement(Sr,{marginBottom:0},rt.createElement(bn,{color:A.text.secondary},"💬 "),rt.createElement(bn,{color:A.text.secondary,bold:!0},i.length," conversation",i.length!==1?"s":""," found")),rt.createElement(Sr,{flexDirection:"column",paddingLeft:2},s.map((o,a)=>rt.createElement(Sr,{key:`conv-${o.id}-${a}`},rt.createElement(bn,{color:A.ui.muted},"• "),rt.createElement(bn,{color:A.text.primary},o.title),rt.createElement(bn,{color:A.ui.muted}," ("),rt.createElement(bn,{color:A.text.link},vw(o.id)),rt.createElement(bn,{color:A.ui.muted},")"))),r>0&&rt.createElement(Sr,{marginTop:0},rt.createElement(bn,{color:A.text.accent},"+",r," more conversation",r!==1?"s":""))))}function vw(i,e=20){return i.length<=e?i:i.slice(0,e-3)+"..."}var Gg=hw(yw);import K,{memo as Sw,useMemo as ww}from"react";import{Box as ot,Text as re}from"@jrichman/ink";Sn();import{createRequire as Tw}from"module";var xw=Tw(import.meta.url),Cw=xw("../../../package.json"),Ew=Cw.version;function Iw(i){switch(i){case 3:return"#FFD700";case 2:return"#A78BFA";case 1:return"#60A5FA";default:return A.ui.muted}}function kw(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function Pw(){let i="#E8B4B8",e="#B8E4E8",t="#4A4A4A";return K.createElement(ot,{flexDirection:"column"},K.createElement(ot,null,K.createElement(re,{color:i},"██"),K.createElement(re,null," "),K.createElement(re,{color:i},"██"),K.createElement(re,null," "),K.createElement(re,{color:i},"██")),K.createElement(ot,null,K.createElement(re,{color:i},"██████████")),K.createElement(ot,null,K.createElement(re,{color:i},"██"),K.createElement(re,{color:e},"██████"),K.createElement(re,{color:i},"██")),K.createElement(ot,null,K.createElement(re,{color:i},"██"),K.createElement(re,{color:t},"██"),K.createElement(re,{color:e},"██"),K.createElement(re,{color:t},"██"),K.createElement(re,{color:i},"██")),K.createElement(ot,null,K.createElement(re,{color:i},"██"),K.createElement(re,{color:e},"██████"),K.createElement(re,{color:i},"██")),K.createElement(ot,null,K.createElement(re,{color:i},"████"),K.createElement(re,{color:t},"██"),K.createElement(re,{color:i},"████")),K.createElement(ot,null,K.createElement(re,{color:i}," ██████ ")))}function Aw({projectPath:i,variant:e="main",tier:t=0}){let n=ww(()=>i?kw(i):null,[i]),s=xe.getDisplayName(t),r=Iw(t);return e==="main"?K.createElement(ot,{flexDirection:"row",paddingX:1,marginY:1,gap:2},K.createElement(Pw,null),K.createElement(ot,{flexDirection:"column",justifyContent:"center"},K.createElement(ot,null,K.createElement(re,{color:A.colors.AccentPurple,bold:!0},"Orion"),K.createElement(re,{color:A.ui.muted}," v",Ew),K.createElement(re,{color:A.ui.muted}," · "),K.createElement(re,{color:r,bold:!0},"Orion ",s)),K.createElement(re,{color:A.text.secondary},"Your partner in getting things done."),K.createElement(re,{color:A.text.secondary,dimColor:!0},"More done, more sleep."),n&&K.createElement(ot,{marginTop:1},K.createElement(re,{color:A.ui.muted},n)))):K.createElement(ot,{paddingX:1,marginY:1},K.createElement(re,{color:A.colors.AccentPurple},"● "),e==="fresh"&&K.createElement(re,{color:A.text.secondary},"Ready when you are."),e==="continue"&&K.createElement(re,{color:A.text.secondary},"Picking up where we left off."),e==="new"&&K.createElement(re,{color:A.text.secondary},"New conversation started."))}var jg=Sw(Aw);function zg(i){return i.includes("Orion ready")||i.includes("Fresh start")||i.includes("Welcome back")||i.includes("New conversation")||i.includes("Conversation cleared")}function qg(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 qe,{memo as di,useMemo as Dw}from"react";import{Box as xs,Text as Bn}from"@jrichman/ink";var pe={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:"*/"}};pe.ts=pe.typescript;pe.js=pe.javascript;pe.jsx=pe.javascript;pe.tsx=pe.typescript;pe.py=pe.python;pe.sh=pe.bash;pe.shell=pe.bash;pe.zsh=pe.bash;pe.rs=pe.rust;pe.golang=pe.go;pe.yml=pe.yaml;function Mw(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 Rw={keyword:A.status.warning,string:A.status.success,comment:A.ui.comment,number:A.text.link,function:A.text.link,operator:A.text.primary,punctuation:A.ui.muted,type:A.status.info,plain:A.text.primary},Ow=di(function({line:e,language:t}){if(!t)return qe.createElement(Bn,{color:A.text.primary},e);let n=Mw(e,t);return qe.createElement(Bn,null,n.map((s,r)=>qe.createElement(Bn,{key:r,color:Rw[s.type]},s.value)))}),Nw=di(function({code:e,language:t,showLineNumbers:n=!1,startLineNumber:s=1,maxLines:r}){let{lines:o,langDef:a,truncated:c}=Dw(()=>{let d=e.split(`
|
|
2020
|
-
`),g=t?pe[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
|
|
2021
|
-
`),{lines:y,truncated:
|
|
2022
|
-
`);return
|
|
2023
|
+
Send /new to start`),y(P)}else t.addSystemMessage(`✗ Telegram setup failed: ${E.error}`)}}catch(E){t.addSystemMessage(`✗ Connection error: ${E.message}`)}e.resetWizard()},[i,m,t,y,e]);xS(()=>{(i==="discord"&&n.step===5||i==="telegram"&&n.step===6)&&!c&&(l(!0),S(n.data))},[n.step,n.data,i,c,S]);let C=()=>{let w=Math.min(n.step,f),E="━".repeat(w),P="─".repeat(f-w);return ne.createElement(qe,null,ne.createElement(_e,{color:ce.brand},E),ne.createElement(_e,{color:ce.dim},P),ne.createElement(_e,{color:ce.muted}," ",w,"/",f))},v=()=>h?h.type==="loading"?ne.createElement(qe,{flexDirection:"column",paddingY:1},ne.createElement(qe,null,ne.createElement(_e,{color:ce.brand},ne.createElement(IS,{type:"dots"})),ne.createElement(_e,{color:ce.muted}," Connecting to ",i==="discord"?"Discord":"Telegram","..."))):h.type==="input"?ne.createElement(qe,{flexDirection:"column"},ne.createElement(_e,{color:ce.text},h.help),ne.createElement(_e,{color:ce.dim},h.hint),ne.createElement(qe,{marginTop:1,flexDirection:"column"},ne.createElement(qe,{paddingX:1,borderStyle:"round",borderColor:o?ce.error:ce.brand},ne.createElement(_e,{color:s?ce.text:ce.dim},s||h.placeholder||"Type here..."),ne.createElement(_e,{color:ce.brand},"▎")),o&&ne.createElement(qe,{marginTop:1},ne.createElement(_e,{color:ce.error},"✗ ",o)))):h.type==="confirm"?ne.createElement(qe,{flexDirection:"column"},ne.createElement(_e,{color:ce.text},h.help),ne.createElement(_e,{color:ce.dim},h.hint),ne.createElement(qe,{marginTop:1,gap:2},ne.createElement(qe,{paddingX:2,borderStyle:"round",borderColor:d===0?ce.brand:ce.border},ne.createElement(_e,{color:d===0?ce.brand:ce.muted},"No")),ne.createElement(qe,{paddingX:2,borderStyle:"round",borderColor:d===1?ce.brand:ce.border},ne.createElement(_e,{color:d===1?ce.brand:ce.muted},"Yes")))):null:null,I=i==="discord"?"Discord Setup":"Telegram Setup";return ne.createElement(qe,{flexDirection:"column",borderStyle:"round",borderColor:ce.border,paddingX:2,paddingY:1,width:60},ne.createElement(qe,{marginBottom:1,justifyContent:"space-between"},ne.createElement(_e,{bold:!0,color:ce.brand},I),C()),ne.createElement(qe,{marginBottom:1},ne.createElement(_e,{bold:!0,color:ce.text},h?.title)),v(),ne.createElement(qe,{marginTop:1,borderStyle:"single",borderTop:!0,borderColor:ce.border,paddingTop:1},ne.createElement(_e,{color:ce.dim},h?.type==="confirm"?"← → or y/n to select • enter to confirm • esc to cancel":h?.type==="loading"?"Please wait...":"enter to continue • esc to cancel")))}var Tg=CS(DS);import De,{memo as MS,useMemo as oi}from"react";import{Box as mn,Text as pn}from"@jrichman/ink";var xg=(i,e=60)=>i.length>e?i.substring(0,e)+"...":i;function RS({regularQueuedMessages:i,crossDeviceTasks:e}){let t=oi(()=>i.length===0?null:i.map((o,a)=>De.createElement(mn,{key:o.id,borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,marginBottom:1},De.createElement(mn,null,De.createElement(pn,{color:"whiteBright",bold:!0},a+1),De.createElement(pn,{color:"#6B7280"}," • "),De.createElement(pn,{color:"#9CA3AF"},xg(o.content))))),[i]),n=oi(()=>e.length===0?null:e.map((o,a)=>De.createElement(mn,{key:`cross-${o.id}`,borderStyle:"round",borderColor:"#0E7490",paddingX:2,paddingY:0,marginBottom:1},De.createElement(mn,null,De.createElement(pn,{color:"#22D3EE",bold:!0},"[M] ",a+1),De.createElement(pn,{color:"#6B7280"}," - "),De.createElement(pn,{color:"#9CA3AF"},xg(o.content))))),[e]),s=oi(()=>{let o=i.length;return`${o} message${o>1?"s":""} queued`},[i.length]),r=oi(()=>{let o=e.length;return`${o} cross-device task${o>1?"s":""} waiting`},[e.length]);return De.createElement(De.Fragment,null,t&&De.createElement(mn,{flexDirection:"column",paddingX:2,marginBottom:1},t,De.createElement(mn,null,De.createElement(pn,{color:"#9CA3AF"},s))),n&&De.createElement(mn,{flexDirection:"column",paddingX:2,marginBottom:1},n,De.createElement(mn,null,De.createElement(pn,{color:"#22D3EE"},r))))}var Cg=MS(RS,(i,e)=>i.regularQueuedMessages.length===e.regularQueuedMessages.length&&i.crossDeviceTasks.length===e.crossDeviceTasks.length&&i.regularQueuedMessages.every((t,n)=>t.id===e.regularQueuedMessages[n]?.id)&&i.crossDeviceTasks.every((t,n)=>t.id===e.crossDeviceTasks[n]?.id));import Q,{memo as OS,useMemo as Ig}from"react";import{Box as nt,Text as de}from"@jrichman/ink";import kg from"path";import Ze,{memo as ii}from"react";import{Box as br,Text as zt}from"@jrichman/ink";var ai={normal:{symbol:"",label:"",color:A.text.primary,description:"Normal mode"},yolo:{symbol:"*",label:"YOLO",color:A.status.error,description:"Auto-approve all actions"},plan:{symbol:">",label:"PLAN",color:A.status.success,description:"Planning mode - no execution"},shell:{symbol:"!",label:"SHELL",color:A.status.warning,description:"Shell command mode"},auto:{symbol:">",label:"AUTO",color:A.status.warning,description:"Auto-accept suggestions"}},zL=ii(function({mode:e,showLabel:t=!1,size:n="normal"}){if(e==="normal")return null;let s=ai[e];return n==="compact"?Ze.createElement(zt,{color:s.color,bold:!0},s.symbol):Ze.createElement(br,{flexDirection:"row",alignItems:"center"},Ze.createElement(zt,{color:s.color,bold:!0},s.symbol),t&&Ze.createElement(br,{marginLeft:1},Ze.createElement(zt,{color:s.color,bold:!0},s.label)))}),qL=ii(function({mode:e,isActive:t=!0}){if(e==="normal")return null;let n=ai[e],s=t?n.color:A.ui.muted;return Ze.createElement(zt,{color:s,bold:t},"[",n.label,"]")}),KL=ii(function({selectedMode:e,availableModes:t=["normal","yolo","plan","auto"],isFocused:n=!1}){return Ze.createElement(br,{flexDirection:"row",alignItems:"center"},Ze.createElement(zt,{color:A.text.secondary},"Mode: "),t.map((s,r)=>{let o=ai[s],a=s===e,c=s==="normal"?"NORMAL":o.label;return Ze.createElement(br,{key:s,flexDirection:"row"},r>0&&Ze.createElement(zt,{color:A.ui.muted}," | "),Ze.createElement(zt,{color:a?o.color:A.ui.muted,bold:a,inverse:a&&n},c))}))}),Eg=ii(function({mode:e,promptSymbol:t="❯",isFocused:n=!0}){let s=ai[e],r=e!=="normal",o=r?s.color:n?A.text.accent:A.ui.muted;return Ze.createElement(br,{flexDirection:"row",alignItems:"center"},r&&Ze.createElement(zt,{color:s.color,bold:!0},s.symbol),Ze.createElement(zt,{color:o},t))});var NS=" Type your message or @path/to/file";function _S({input:i,isLoading:e,pastedTexts:t,cursorPosition:n,suggestion:s,mode:r="normal"}){let{hasContent:o,ghostText:a}=Ig(()=>{let l=i.length>0||t.length>0,d=s&&s.toLowerCase().startsWith(i.toLowerCase())&&i.length>0?s.slice(i.length):null;return{hasContent:l,ghostText:d}},[i,t.length,s]),c=Ig(()=>t.length===0?null:t.map((l,d)=>{if(l.type==="clipboard_image"){let p=l.fileSize?` ${ln(l.fileSize)}`:"",h=!!l.error;return Q.createElement(nt,{key:`pasted-${l.id}`,flexDirection:"column"},Q.createElement(nt,null,Q.createElement(de,{color:h?A.status.error:A.status.info}," ","[CLIPBOARD] "),Q.createElement(de,{color:h?A.status.error:A.text.secondary},"Image"),p&&Q.createElement(de,{color:A.ui.muted},p)),h&&Q.createElement(nt,{marginLeft:4},Q.createElement(de,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}if(l.type==="image_path"&&l.filePath){let p=Xa(kg.basename(l.filePath)),h=l.fileSize?` ${ln(l.fileSize)}`:"",f=!!l.error;return Q.createElement(nt,{key:`pasted-${l.id}`,flexDirection:"column"},Q.createElement(nt,null,Q.createElement(de,{color:f?A.status.error:A.status.info}," ","[IMG] "),Q.createElement(de,{color:f?A.status.error:A.text.secondary},p),h&&Q.createElement(de,{color:A.ui.muted},h)),f&&Q.createElement(nt,{marginLeft:4},Q.createElement(de,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}if(l.type==="file_path"&&l.filePath){let p=Xa(kg.basename(l.filePath)),h=l.fileSize?` ${ln(l.fileSize)}`:"",f=!!l.error;return Q.createElement(nt,{key:`pasted-${l.id}`,flexDirection:"column"},Q.createElement(nt,null,Q.createElement(de,{color:f?A.status.error:A.status.info}," ","[FILE] "),Q.createElement(de,{color:f?A.status.error:A.text.secondary},p),h&&Q.createElement(de,{color:A.ui.muted},h)),f&&Q.createElement(nt,{marginLeft:4},Q.createElement(de,{color:A.status.error,dimColor:!0},"[!] ",l.error)))}let g=l.lineCount-1,m=g>0?`+${g} lines`:"1 line";return Q.createElement(nt,{key:`pasted-${l.id}`},Q.createElement(de,{color:A.ui.muted}," ","[TEXT] "),Q.createElement(de,{color:A.text.secondary},"Pasted text #",d+1),Q.createElement(de,{color:A.ui.muted}," (",m,")"))}),[t]);return Q.createElement(nt,{borderStyle:"round",borderColor:o?A.border.focused:A.border.default,paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},c&&Q.createElement(nt,{flexDirection:"column",marginBottom:0},c),Q.createElement(nt,null,Q.createElement(Eg,{mode:r,isFocused:!e}),Q.createElement(de,null," "),i.length===0&&!e?s?Q.createElement(de,null,Q.createElement(de,{inverse:!0}," "),Q.createElement(de,{color:A.ui.muted},s),Q.createElement(de,{color:A.ui.muted,dimColor:!0}," (Tab to accept)")):Q.createElement(de,{color:A.ui.muted},NS):Q.createElement(de,null,Q.createElement(de,{color:A.text.primary},i.slice(0,n)),!e&&Q.createElement(de,{inverse:!0}," "),Q.createElement(de,{color:A.text.primary},i.slice(n)),a&&Q.createElement(de,{color:A.ui.muted},a))))}var Pg=OS(_S,(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 yr,{useState as $S,useEffect as FS,useRef as LS,memo as US}from"react";import{Box as BS,Text as fc}from"@jrichman/ink";import WS from"ink-spinner";function HS(i){if(i<60)return`${i}s`;let e=Math.floor(i/60),t=i%60;return`${e}m ${t}s`}function GS({isLoading:i,phrase:e="Processing",startTime:t}){let[n,s]=$S(0),r=LS(null);return FS(()=>{if(r.current&&(clearInterval(r.current),r.current=null),!i){s(0);return}let o=t||Date.now();return r.current=setInterval(()=>{let a=Date.now(),c=Math.floor((a-o)/1e3);s(c)},1e3),()=>{r.current&&(clearInterval(r.current),r.current=null)}},[i,t]),i?yr.createElement(BS,{flexDirection:"row",alignItems:"center",paddingX:2,marginBottom:1,flexShrink:0},yr.createElement(fc,{color:A.text.accent},yr.createElement(WS,{type:"dots"})),yr.createElement(fc,{color:A.text.primary}," ",e,"... "),yr.createElement(fc,{color:A.text.secondary},"(esc to cancel",n>0?`, ${HS(n)}`:"",")")):null}var Ag=US(GS);import we,{memo as QS,useMemo as Fg}from"react";import{Box as ws,Text as st}from"@jrichman/ink";import{useState as Dg,useEffect as Mg,useCallback as jS,useRef as Rg}from"react";import{useStdout as zS}from"@jrichman/ink";var ys=80,vs=24,qS=100;function Ss(i){let{debounceMs:e=qS}=i||{},{stdout:t}=zS(),[n,s]=Dg({width:t?.columns||ys,height:t?.rows||vs,rows:t?.rows||vs,columns:t?.columns||ys}),[r,o]=Dg(!1),a=Rg(null),c=Rg(null);Mg(()=>{function d(){o(!0),a.current&&clearTimeout(a.current),c.current&&clearTimeout(c.current),a.current=setTimeout(()=>{let g=process.stdout.columns||ys,m=process.stdout.rows||vs;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]),Mg(()=>{if(t){let d=t.columns||ys,g=t.rows||vs;(d!==n.width||g!==n.height)&&s({width:d,height:g,rows:g,columns:d})}},[t?.columns,t?.rows]);let l=jS(()=>{s({width:process.stdout.columns||ys,height:process.stdout.rows||vs,rows:process.stdout.rows||vs,columns:process.stdout.columns||ys})},[]);return{...n,isResizing:r,refresh:l}}Po();import{useState as hn,useEffect as Og,useRef as KS,useCallback as VS}from"react";function Ng(i=1e4){let[e,t]=hn("not-ready"),[n,s]=hn(!1),[r,o]=hn(!1),[a,c]=hn(0),[l,d]=hn(5),[g,m]=hn(0),[p,h]=hn(!1),[f,y]=hn(!1),T=KS(!1),x=VS(S=>{S.isInitializing||S.initState==="initializing"?t("initializing"):S.isRunning&&S.isInitialized?t("ready"):t("not-ready"),s(S.hasBrowser??!1),o(S.multiAgentMode??!1),c(S.runningAgentCount??0),d(S.maxConcurrentAgents??5),m(S.tabCount??0),h(S.isExecuting??!1),y(S.hasActiveSession??!1)},[]);return Og(()=>{let S=te.onStatusChange(C=>{x(C)});return()=>S()},[x]),Og(()=>{let S=()=>{let v=te.getStatus();v.initState==="idle"&&!T.current&&(T.current=!0,te.initialize().catch(I=>{console.debug("[useBrowserStatus] Auto-init failed:",I.message)}),v=te.getStatus()),x(v)};S();let C=setInterval(S,i);return()=>clearInterval(C)},[i,x]),{status:e,hasBrowser:n,multiAgentMode:r,runningAgentCount:a,maxConcurrentAgents:l,tabCount:g,isExecuting:p,hasActiveSession:f}}import{useState as ci,useEffect as XS,useCallback as _g}from"react";var YS=300*1e3;function $g(){let[i,e]=ci(null),[t,n]=ci(null),[s,r]=ci(!1),[o,a]=ci(null),c=_g(async(m=!1)=>{r(!0),a(null);try{let p=await lr.fetchQuotaStatus(m);e(p);let h=await lr.getUsageDisplayData();n(h)}catch(p){a(p instanceof Error?p.message:"Failed to fetch quota")}finally{r(!1)}},[]),l=_g(async()=>{await c(!0)},[c]);XS(()=>{c();let m=setInterval(()=>{c(!0)},YS);return()=>clearInterval(m)},[c]);let d=t?jd(t.percent):"normal",g=t?ur(t.resetsAt,t.resetsInSeconds):"";return{quota:i,usageDisplay:t,severity:d,resetTimeDisplay:g,isLoading:s,error:o,refresh:l}}Sn();import{createRequire as JS}from"module";var ZS=JS(import.meta.url),ew=ZS("../../../package.json"),tw=ew.version,nw={3:"#FFD700",2:"#A78BFA",1:"#60A5FA",0:A.ui.muted},sw={ready:"#10B981",initializing:"#F59E0B","not-ready":"#F97316"},rw={normal:A.ui.muted,notice:"#60A5FA",warning:"#FBBF24",high:"#F97316",critical:"#EF4444"};function ow(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function iw(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 aw({cwd:i,selectedModel:e,showScrollHint:t=!1,tier:n=0}){let{width:s}=Ss(),{status:r}=Ng(),{usageDisplay:o,severity:a,resetTimeDisplay:c}=$g(),l=xe.getDisplayName(n),d=nw[n]||A.ui.muted,{displayPath:g,shortcuts:m}=Fg(()=>{let h=`${e.displayName} /model`,f=" ● browser",y=t?"? help · Shift+↑↓ scroll":"? help",x=h.length+f.length+y.length+" ".length*2+4,S=Math.max(15,Math.floor((s-x)*.4));return{displayPath:iw(ow(i),S),shortcuts:y}},[i,e.displayName,t,s]),p=Fg(()=>{if(!o)return null;let{percent:h,type:f}=o,y=f==="weekly"?"weekly":"5-hour";return h>=100?`You've hit your ${y} limit`:h>=90?`${h}% of ${y} limit used`:`${h}% ${y} usage`},[o]);return we.createElement(ws,{flexDirection:"column",width:"100%"},o&&we.createElement(ws,{paddingX:2,justifyContent:"center"},we.createElement(st,{color:rw[a]},p),c&&we.createElement(we.Fragment,null,we.createElement(st,{color:A.ui.muted}," · "),we.createElement(st,{color:A.ui.muted},"Resets in ",c))),we.createElement(ws,{paddingX:2,paddingY:0,width:"100%",justifyContent:"space-between",flexDirection:"row"},we.createElement(ws,null,we.createElement(st,{color:A.text.link},g),we.createElement(st,{color:A.ui.muted}," v",tw),we.createElement(st,{color:A.ui.muted}," · "),we.createElement(st,{color:d,bold:!0},l)),we.createElement(ws,null,we.createElement(st,{color:A.text.accent},e.displayName),we.createElement(st,{color:A.text.secondary}," /model"),we.createElement(st,{color:A.text.secondary}," "),we.createElement(st,{color:sw[r]},"●"),we.createElement(st,{color:A.text.secondary}," browser")),we.createElement(ws,null,we.createElement(st,{color:A.text.secondary},m))))}var Lg=QS(aw);import fn,{useState as li,useEffect as lw,useRef as ui,useCallback as uw,useLayoutEffect as dw,memo as gw}from"react";import{Box as vr,Text as Hg,getScrollHeight as mw,getInnerHeight as pw,useInput as hw}from"@jrichman/ink";import{useRef as Ug,useEffect as cw,useCallback as Bg}from"react";function Wg(i){let e=Ug(null),t=Ug(i);cw(()=>{t.current=i,e.current=null});let n=Bg(()=>e.current??t.current,[]),s=Bg(r=>{e.current=r},[]);return{getScrollTop:n,setPendingScrollTop:s}}var Gg=3;function fw({children:i,reservedLines:e=8,autoScrollToBottom:t=!0,hasFocus:n=!0}){let{height:s}=Ss(),r=Math.max(5,s-e),[o,a]=li(0),[c,l]=li({innerHeight:0,scrollHeight:0}),[d,g]=li(!1),[m,p]=li(!0),h=ui(null),f=ui(c),y=ui(0),T=ui(o),{getScrollTop:x,setPendingScrollTop:S}=Wg(o),C=Zo({targetFrameTime:16.67}),v=Jo("ScrollableContainer");lw(()=>{f.current=c},[c]),dw(()=>{if(!h.current)return;let D=Math.round(pw(h.current)),$=Math.round(mw(h.current)),R=Math.max(0,$-D);T.current>=f.current.scrollHeight-f.current.innerHeight-1&&o>=T.current&&p(!0),(c.innerHeight!==D||c.scrollHeight!==$)&&(l({innerHeight:D,scrollHeight:$}),m&&t&&a(R));let N=$>r;N!==d&&g(N);let k=fn.Children.count(i);t&&y.current!==k&&m&&a(R),y.current=k,T.current=o});let I=uw(D=>{if(!C.hasBudget()){Fn(()=>I(D));return}let{scrollHeight:$,innerHeight:R}=f.current,_=Math.max(0,$-R);D<0&&p(!1);let N=x(),k=Math.min(Math.max(0,N+D),_);k>=_-1&&p(!0),S(k),a(k),C.useBudget(2)},[x,S,C]);hw((D,$)=>{if(n){if($.pageUp){I(-r+2);return}if($.pageDown){I(r-2);return}if($.shift&&$.upArrow){I(-Gg);return}if($.shift&&$.downArrow){I(Gg);return}}},{isActive:n});let w=Math.max(0,c.scrollHeight-c.innerHeight),E=o>0,P=o<w;return fn.createElement(vr,{flexDirection:"column",flexGrow:1},E&&fn.createElement(vr,{paddingX:2},fn.createElement(Hg,{color:A.text.secondary},"↑ Page Up / Shift+↑ to scroll up")),fn.createElement(vr,{ref:h,height:d?r:void 0,flexDirection:"column",overflowY:d?"scroll":"hidden",overflowX:"hidden",scrollTop:o,flexGrow:1},fn.createElement(vr,{flexDirection:"column",flexShrink:0,paddingRight:1},i)),P&&fn.createElement(vr,{paddingX:2},fn.createElement(Hg,{color:A.text.secondary},"↓ Page Down / Shift+↓ to scroll down")))}var jg=gw(fw);import Sc,{memo as wc}from"react";import{Box as Kw}from"@jrichman/ink";import ie,{memo as Ww,useMemo as tm}from"react";import{Box as it,Text as ft}from"@jrichman/ink";import Ts,{memo as bw}from"react";import{Box as di,Text as zg}from"@jrichman/ink";function yw({suggestions:i,onSelect:e}){return i.length===0?null:Ts.createElement(di,{flexDirection:"column",marginTop:1,width:"100%"},i.map((t,n)=>Ts.createElement(di,{key:`sug-block-${n}`,flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},t.options.map((s,r)=>Ts.createElement(di,{key:`sug-opt-${n}-${r}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},Ts.createElement(zg,{color:"#22D3EE"},s))))),e&&Ts.createElement(di,{marginTop:0,width:"100%"},Ts.createElement(zg,{color:"#6B7280"},"Type a suggestion to use it")))}var qg=bw(yw,(i,e)=>i.suggestions===e.suggestions?!0:i.suggestions.length!==e.suggestions.length?!1:i.suggestions.every((t,n)=>{let s=e.suggestions[n];return t.options.length===s.options.length&&t.options.every((r,o)=>r===s.options[o])}));import Bn,{memo as vw}from"react";import{Box as gi,Text as bc}from"@jrichman/ink";function Sw({workingFiles:i}){return i.length===0?null:Bn.createElement(gi,{flexDirection:"column",marginTop:1,width:"100%"},Bn.createElement(gi,{marginBottom:0,width:"100%"},Bn.createElement(bc,{color:"#9CA3AF",bold:!0},"Working Files"),Bn.createElement(bc,{color:"#6B7280"}," (",i.length,")")),Bn.createElement(gi,{flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},i.map(e=>Bn.createElement(gi,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},Bn.createElement(bc,{color:"white"},e.name)))))}var Kg=vw(Sw,(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 rt,{memo as ww,useMemo as Tw,useState as xw}from"react";import{Box as Sr,Text as bn}from"@jrichman/ink";var yc=5;function Cw({conversationHistory:i,onSelect:e}){let[t,n]=xw(!1),{displayedItems:s,hiddenCount:r}=Tw(()=>i.length<=yc||t?{displayedItems:i,hiddenCount:0}:{displayedItems:i.slice(0,yc),hiddenCount:i.length-yc},[i,t]);return i.length===0?null:rt.createElement(Sr,{flexDirection:"column",marginTop:1},rt.createElement(Sr,{marginBottom:0},rt.createElement(bn,{color:A.text.secondary},"💬 "),rt.createElement(bn,{color:A.text.secondary,bold:!0},i.length," conversation",i.length!==1?"s":""," found")),rt.createElement(Sr,{flexDirection:"column",paddingLeft:2},s.map((o,a)=>rt.createElement(Sr,{key:`conv-${o.id}-${a}`},rt.createElement(bn,{color:A.ui.muted},"• "),rt.createElement(bn,{color:A.text.primary},o.title),rt.createElement(bn,{color:A.ui.muted}," ("),rt.createElement(bn,{color:A.text.link},Ew(o.id)),rt.createElement(bn,{color:A.ui.muted},")"))),r>0&&rt.createElement(Sr,{marginTop:0},rt.createElement(bn,{color:A.text.accent},"+",r," more conversation",r!==1?"s":""))))}function Ew(i,e=20){return i.length<=e?i:i.slice(0,e-3)+"..."}var Vg=ww(Cw);import K,{memo as Iw,useMemo as kw}from"react";import{Box as ot,Text as re}from"@jrichman/ink";Sn();import{createRequire as Pw}from"module";var Aw=Pw(import.meta.url),Dw=Aw("../../../package.json"),Mw=Dw.version;function Rw(i){switch(i){case 3:return"#FFD700";case 2:return"#A78BFA";case 1:return"#60A5FA";default:return A.ui.muted}}function Ow(i){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&i.startsWith(e)?"~"+i.slice(e.length):i}function Nw(){let i="#E8B4B8",e="#B8E4E8",t="#4A4A4A";return K.createElement(ot,{flexDirection:"column"},K.createElement(ot,null,K.createElement(re,{color:i},"██"),K.createElement(re,null," "),K.createElement(re,{color:i},"██"),K.createElement(re,null," "),K.createElement(re,{color:i},"██")),K.createElement(ot,null,K.createElement(re,{color:i},"██████████")),K.createElement(ot,null,K.createElement(re,{color:i},"██"),K.createElement(re,{color:e},"██████"),K.createElement(re,{color:i},"██")),K.createElement(ot,null,K.createElement(re,{color:i},"██"),K.createElement(re,{color:t},"██"),K.createElement(re,{color:e},"██"),K.createElement(re,{color:t},"██"),K.createElement(re,{color:i},"██")),K.createElement(ot,null,K.createElement(re,{color:i},"██"),K.createElement(re,{color:e},"██████"),K.createElement(re,{color:i},"██")),K.createElement(ot,null,K.createElement(re,{color:i},"████"),K.createElement(re,{color:t},"██"),K.createElement(re,{color:i},"████")),K.createElement(ot,null,K.createElement(re,{color:i}," ██████ ")))}function _w({projectPath:i,variant:e="main",tier:t=0}){let n=kw(()=>i?Ow(i):null,[i]),s=xe.getDisplayName(t),r=Rw(t);return e==="main"?K.createElement(ot,{flexDirection:"row",paddingX:1,marginY:1,gap:2},K.createElement(Nw,null),K.createElement(ot,{flexDirection:"column",justifyContent:"center"},K.createElement(ot,null,K.createElement(re,{color:A.colors.AccentPurple,bold:!0},"Orion"),K.createElement(re,{color:A.ui.muted}," v",Mw),K.createElement(re,{color:A.ui.muted}," · "),K.createElement(re,{color:r,bold:!0},"Orion ",s)),K.createElement(re,{color:A.text.secondary},"Your partner in getting things done."),K.createElement(re,{color:A.text.secondary,dimColor:!0},"More done, more sleep."),n&&K.createElement(ot,{marginTop:1},K.createElement(re,{color:A.ui.muted},n)))):K.createElement(ot,{paddingX:1,marginY:1},K.createElement(re,{color:A.colors.AccentPurple},"● "),e==="fresh"&&K.createElement(re,{color:A.text.secondary},"Ready when you are."),e==="continue"&&K.createElement(re,{color:A.text.secondary},"Picking up where we left off."),e==="new"&&K.createElement(re,{color:A.text.secondary},"New conversation started."))}var Xg=Iw(_w);function Yg(i){return i.includes("Orion ready")||i.includes("Fresh start")||i.includes("Welcome back")||i.includes("New conversation")||i.includes("Conversation cleared")}function Qg(i){let e=i.match(/📁\s*(.+)/),t=e?e[1].trim():void 0;return i.includes("Fresh start")||i.includes("Conversation cleared")?{variant:"fresh",projectPath:t}:i.includes("Welcome back")?{variant:"continue",projectPath:t}:i.includes("New conversation")?{variant:"new",projectPath:t}:{variant:"main",projectPath:t}}import Ke,{memo as mi,useMemo as $w}from"react";import{Box as xs,Text as Wn}from"@jrichman/ink";var pe={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:"*/"}};pe.ts=pe.typescript;pe.js=pe.javascript;pe.jsx=pe.javascript;pe.tsx=pe.typescript;pe.py=pe.python;pe.sh=pe.bash;pe.shell=pe.bash;pe.zsh=pe.bash;pe.rs=pe.rust;pe.golang=pe.go;pe.yml=pe.yaml;function Fw(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 Lw={keyword:A.status.warning,string:A.status.success,comment:A.ui.comment,number:A.text.link,function:A.text.link,operator:A.text.primary,punctuation:A.ui.muted,type:A.status.info,plain:A.text.primary},Uw=mi(function({line:e,language:t}){if(!t)return Ke.createElement(Wn,{color:A.text.primary},e);let n=Fw(e,t);return Ke.createElement(Wn,null,n.map((s,r)=>Ke.createElement(Wn,{key:r,color:Lw[s.type]},s.value)))}),Bw=mi(function({code:e,language:t,showLineNumbers:n=!1,startLineNumber:s=1,maxLines:r}){let{lines:o,langDef:a,truncated:c}=$w(()=>{let d=e.split(`
|
|
2024
|
+
`),g=t?pe[t.toLowerCase()]:void 0;return r&&d.length>r?{lines:d.slice(0,r),langDef:g,truncated:d.length-r}:{lines:d,langDef:g,truncated:0}},[e,t,r]),l=n?String(s+o.length-1).length:0;return Ke.createElement(xs,{flexDirection:"column"},o.map((d,g)=>Ke.createElement(xs,{key:g,flexDirection:"row"},n&&Ke.createElement(xs,{width:l+2,flexShrink:0},Ke.createElement(Wn,{color:A.ui.muted},String(s+g).padStart(l," ")," │")),Ke.createElement(xs,{flexGrow:1},Ke.createElement(Uw,{line:d,language:a})))),c>0&&Ke.createElement(Wn,{color:A.ui.muted}," ... ",c," more lines"))}),Jg=mi(function({code:e,language:t,showLanguageLabel:n=!0,showLineNumbers:s=!1,maxLines:r,showBorder:o=!0}){let a=t?.toLowerCase(),c=a&&pe[a]?a:void 0;return Ke.createElement(xs,{flexDirection:"column",borderStyle:o?"round":void 0,borderColor:o?A.border.default:void 0,paddingX:o?1:0},n&&c&&Ke.createElement(xs,{marginBottom:0},Ke.createElement(Wn,{color:A.ui.muted,dimColor:!0},c)),Ke.createElement(Bw,{code:e,language:c,showLineNumbers:s,maxLines:r}))}),iB=mi(function({children:e}){return Ke.createElement(Wn,{color:A.status.warning,bold:!1},"`",e,"`")});function Zg(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 em(i){return/```[\s\S]*?```/.test(i)}var Hw=150;function nm(i,e){return i.length<=e?{lines:i,truncated:!1}:{lines:i.slice(0,e),truncated:!0}}function Gw({message:i,onSuggestionClick:e,maxLines:t=Hw}){let{role:n,content:s}=i,{userTier:r}=or(),o=tm(()=>{if(n!=="assistant")return null;let{suggestions:c,cleanedContent:l}=Er(s),{workingFiles:d,cleanedContent:g}=Mc(l),{conversationHistory:m,cleanedContent:p}=Rc(g),f=Oc(p).split(`
|
|
2025
|
+
`),{lines:y,truncated:T}=nm(f,t);return{suggestions:c,workingFiles:d,conversationHistory:m,lines:y,truncated:T,totalLines:f.length}},[s,n,t]),a=tm(()=>{if(n==="assistant")return null;let c=s.split(`
|
|
2026
|
+
`);return nm(c,t)},[s,n,t]);if(n==="system"&&a){if(Yg(s)){let{variant:g,projectPath:m}=Qg(s);return ie.createElement(Xg,{variant:g,projectPath:m,tier:r})}let{lines:c,truncated:l}=a,d=s.split(`
|
|
2023
2027
|
`);return ie.createElement(it,{marginY:0,flexDirection:"column",paddingX:1},ie.createElement(it,{flexDirection:"row"},ie.createElement(ft,{color:A.ui.muted},"● "),ie.createElement(it,{flexDirection:"column",flexGrow:1},c.map((g,m)=>ie.createElement(ft,{key:`sys-${m}`,color:A.ui.muted},g)),l&&ie.createElement(ft,{color:A.ui.muted}," ... (",d.length-t," more)"))))}if(n==="user"&&a){let{lines:c,truncated:l}=a,d=s.split(`
|
|
2024
2028
|
`);return ie.createElement(it,{marginY:1,flexDirection:"column",paddingX:1},ie.createElement(it,{flexDirection:"row"},ie.createElement(ft,{color:A.text.primary},"❯ "),ie.createElement(it,{flexDirection:"column",flexGrow:1},c.map((g,m)=>ie.createElement(ft,{key:`user-${m}`,color:A.text.primary},g)),l&&ie.createElement(ft,{color:A.ui.muted}," ... (",d.length-t," more)"))))}if(n==="assistant"&&o){let{suggestions:c,workingFiles:l,conversationHistory:d,lines:g,truncated:m,totalLines:p}=o,h=g.join(`
|
|
2025
|
-
`),f=
|
|
2026
|
-
`).map((
|
|
2029
|
+
`),f=em(h);return ie.createElement(it,{marginY:1,flexDirection:"column",paddingX:1},ie.createElement(it,{flexDirection:"row"},ie.createElement(ft,{color:A.text.primary},"● "),ie.createElement(it,{flexDirection:"column",flexGrow:1},f?Zg(h).map((y,T)=>y.type==="code"?ie.createElement(it,{key:`code-${T}`,marginY:1},ie.createElement(Jg,{code:y.content,language:y.language,showBorder:!0,maxLines:50})):y.content.split(`
|
|
2030
|
+
`).map((x,S)=>x.trim()===""?ie.createElement(ft,{key:`text-${T}-${S}`}," "):ie.createElement(ft,{key:`text-${T}-${S}`,color:A.text.primary},Si(x)))):g.map((y,T)=>y.trim()===""?ie.createElement(ft,{key:`asst-${T}`}," "):ie.createElement(ft,{key:`asst-${T}`,color:A.text.primary},Si(y))),m&&ie.createElement(ft,{color:A.ui.muted}," ... (",p-t," more)"))),d.length>0&&ie.createElement(it,{paddingLeft:2},ie.createElement(Vg,{conversationHistory:d})),l.length>0&&ie.createElement(it,{paddingLeft:2},ie.createElement(Kg,{workingFiles:l})),c.length>0&&ie.createElement(it,{paddingLeft:2},ie.createElement(qg,{suggestions:c,onSelect:e})))}return null}var sm=Ww(Gw,(i,e)=>i.message.id===e.message.id&&i.message.content===e.message.content&&i.maxLines===e.maxLines);import vc,{memo as jw}from"react";import{Box as zw,Text as rm}from"@jrichman/ink";function qw({version:i,showDetails:e=!0}){return e?vc.createElement(zw,{marginBottom:1,paddingX:1},vc.createElement(rm,{color:A.text.primary,bold:!0},"Orion"),i&&vc.createElement(rm,{color:A.ui.muted,dimColor:!0}," v",i)):null}var om=jw(qw);var Vw=wc(sm),Xw=wc(om),Yw=150;function Qw({messages:i,version:e,showHeader:t=!1,hasFocus:n=!0,onSuggestionClick:s,staticRemountKey:r=0}){return Sc.createElement(Kw,{flexDirection:"column",key:r},t&&Sc.createElement(Xw,{version:e,showDetails:!0}),i.map(o=>Sc.createElement(Vw,{key:o.id,message:o,maxLines:Yw,onSuggestionClick:s})))}var im=wc(Qw);import am,{memo as Jw}from"react";import{Box as Zw,Text as eT}from"@jrichman/ink";function tT({width:i,color:e=A.border.default,char:t="─"}){let{width:n}=Ss(),s=typeof i=="number"?i:typeof i=="string"&&i.endsWith("%")?Math.floor(parseInt(i)/100*n):n-4,r=t.repeat(s);return am.createElement(Zw,null,am.createElement(eT,{color:e},r))}var cm=Jw(tT);import Hn,{memo as um,useState as NB,useEffect as nT,useRef as sT,useCallback as _B}from"react";import{Box as pi,Text as lm}from"@jrichman/ink";var rT={success:{icon:"✓",color:A.status.success,borderColor:A.status.success},error:{icon:"✕",color:A.status.error,borderColor:A.status.error},warning:{icon:"⚠",color:A.status.warning,borderColor:A.status.warning},info:{icon:"ℹ",color:A.status.info,borderColor:A.border.default}},oT=um(function({message:e,type:t="info",duration:n=3e3,onDismiss:s,icon:r,showBorder:o=!0}){let a=rT[t],c=r??a.icon,l=sT(null);return nT(()=>{if(n>0&&s)return l.current=setTimeout(s,n),()=>{l.current&&clearTimeout(l.current)}},[n,s]),Hn.createElement(pi,{borderStyle:o?"round":void 0,borderColor:o?a.borderColor:void 0,paddingX:o?1:0,paddingY:0,flexDirection:"row",alignItems:"center"},Hn.createElement(lm,{color:a.color},c),Hn.createElement(pi,{marginLeft:1},Hn.createElement(lm,{color:A.text.primary},e)))}),dm=um(function({toasts:e,onRemove:t,maxToasts:n=3,position:s="bottom"}){let r=e.slice(-n);return r.length===0?null:Hn.createElement(pi,{flexDirection:"column",marginTop:s==="bottom"?1:0,marginBottom:s==="top"?1:0},r.map(o=>Hn.createElement(pi,{key:o.id,marginBottom:1},Hn.createElement(oT,{message:o.message,type:o.type,duration:o.duration??3e3,onDismiss:()=>t(o.id)}))))});import Me,{memo as gm,useMemo as iT}from"react";import{Box as Tc,Text as bt}from"@jrichman/ink";var aT=gm(function({text:e,query:t}){let n=iT(()=>rg(e,t,!1),[e,t]),s=70,r=0,o=[],a=!1;for(let c of n){if(r>=s){a=!0;break}let l=s-r;if(c.text.length>l){o.push({text:c.text.slice(0,l),isMatch:c.isMatch}),a=!0;break}o.push(c),r+=c.text.length}return Me.createElement(Me.Fragment,null,o.map((c,l)=>Me.createElement(bt,{key:l,color:c.isMatch?A.status.warning:A.text.primary,bold:c.isMatch,inverse:c.isMatch},c.text)),a&&Me.createElement(bt,{color:A.ui.muted},"..."))});function cT({query:i,history:e,currentMatchIndex:t,matchCount:n,matchedEntry:s,isActive:r}){return r?Me.createElement(Tc,{flexDirection:"column",paddingX:1,borderStyle:"single",borderColor:A.border.default},Me.createElement(Tc,{flexDirection:"row"},Me.createElement(bt,{color:A.text.accent},"(reverse-i-search)"),Me.createElement(bt,{color:A.text.primary},"`"),Me.createElement(bt,{color:A.status.warning},i),Me.createElement(bt,{color:A.text.primary},"'"),Me.createElement(bt,{color:A.ui.muted},": "),s?Me.createElement(aT,{text:s,query:i}):i?Me.createElement(bt,{color:A.ui.muted,italic:!0},"no match"):Me.createElement(bt,{color:A.ui.muted,italic:!0},"type to search history")),i&&Me.createElement(Tc,{flexDirection:"row",marginTop:0},Me.createElement(bt,{color:A.ui.muted},n>0?`[${t+1}/${n}]`:"[0/0]"),Me.createElement(bt,{color:A.ui.muted}," "),Me.createElement(bt,{color:A.ui.muted,italic:!0},n>0?"Up/Down to navigate, Enter to select, Esc to cancel":"No matches found"))):null}var mm=gm(cT);Sn();function gT(){let i=On(),e=xt(),{regularQueuedMessages:t,crossDeviceTasks:n}=ja(),s=gs(),r=Ut(),{userTier:o}=or(),a=ir(),c=_n(),{handleCommand:l}=Yo(),d=za(),[g,m]=uT();xc(()=>{i.isLoading&&!g?m(Date.now()):i.isLoading||m(void 0)},[i.isLoading,g]);let p=pm(()=>{let v=null;for(let w=i.messages.length-1;w>=0;w--){let E=i.messages[w];if(E.role==="assistant"&&E.content){v=E;break}}if(!v)return null;let{suggestions:I}=Er(v.content);return I.length>0&&I[0].options.length>0?I[0].options[0]:null},[i.messages]),h=hm(null);xc(()=>{let v=null;i.isLoading?v=null:a.input===""||p&&p.toLowerCase().startsWith(a.input.toLowerCase())?v=p:v=null,h.current!==v&&(h.current=v,c.setSuggestion(v))},[p,i.isLoading,a.input]);let f=lT(async()=>{let v=a.pastedTexts.filter(I=>!I.error||I.type==="text");if(a.input.startsWith("/")){await l(a.input);return}if(c.clearPastedTexts(),v.length>0){let{fullInput:I,imageUrls:w,errors:E}=await c.processFilesForSubmit();if(E.length>0&&!I.trim()&&w.length===0){e.addSystemMessage(`Failed to read files:
|
|
2027
2031
|
${E.map(P=>` - ${P}`).join(`
|
|
2028
|
-
`)}`);return}a.input.trim()&&c.addToHistory(a.input.trim()),e.handleSubmit(I.trim()||"Please analyze this image.",
|
|
2032
|
+
`)}`);return}a.input.trim()&&c.addToHistory(a.input.trim()),e.handleSubmit(I.trim()||"Please analyze this image.",w)}else a.input.trim()&&c.addToHistory(a.input.trim()),e.handleSubmit(a.input.trim());c.clearInput()},[a.input,a.pastedTexts,c,e,l]),{memoryPressure:y,frameBudgetStatus:T}=Zd({onSubmit:f,enableProfiling:process.env.DEBUG_PERF==="true",bufferFlushInterval:16,deferredDelay:100}),x=sg({items:a.history,getSearchText:v=>v,direction:"backward",isActive:s.isReverseSearchActive,onMatchSelect:v=>{c.setInput(v.item)}}),S=hm(!1);xc(()=>{s.isReverseSearchActive&&!x.isSearching?x.startSearch():!s.isReverseSearchActive&&x.isSearching&&x.stopSearch(),S.current&&!x.isSearching&&s.isReverseSearchActive&&(x.currentMatch&&c.setInput(x.currentMatch.item),r.stopReverseSearch()),S.current=x.isSearching},[s.isReverseSearchActive,x.isSearching,x.startSearch,x.stopSearch,x.currentMatch,c,r]);let C=pm(()=>s.showHelp||s.showModelMenu||s.showCommandMenu||s.showWizard||s.isReverseSearchActive,[s.showHelp,s.showModelMenu,s.showCommandMenu,s.showWizard,s.isReverseSearchActive]);return J.createElement(We,{flexDirection:"column",width:"100%",height:"100%"},J.createElement(jg,{reservedLines:12,autoScrollToBottom:!0,hasFocus:!C},J.createElement(im,{messages:i.messages,showHeader:!1,hasFocus:!C,onSuggestionClick:v=>c.setInput(v),staticRemountKey:i.staticRemountKey})),J.createElement(We,{paddingX:2,flexShrink:0},J.createElement(cm,null)),i.todoList&&i.todoList.todos.length>0&&J.createElement(We,{flexShrink:0},J.createElement(mg,{todoList:i.todoList})),i.externalSession&&J.createElement(We,{paddingX:2,marginBottom:1,flexShrink:0},J.createElement(ug,{session:i.externalSession})),i.activeTools.size>0&&J.createElement(We,{paddingX:2,marginBottom:1,flexShrink:0},J.createElement(ig,{activeTools:i.activeTools})),i.subAgentOperations.size>0&&J.createElement(We,{paddingX:2,marginBottom:1,flexShrink:0},J.createElement(lg,{operations:i.subAgentOperations})),i.pendingConfirmation&&J.createElement(We,{paddingX:2,marginBottom:1,flexShrink:0},J.createElement(gg,{request:i.pendingConfirmation,onConfirm:e.handleConfirmationConfirm,onDecline:e.handleConfirmationDecline,onTimeout:e.handleConfirmationTimeout})),a.isProcessingFiles&&J.createElement(We,{paddingX:2,marginBottom:1,flexShrink:0},J.createElement(fm,{color:A.text.accent},J.createElement(dT,{type:"dots"})),J.createElement(fm,{color:A.text.primary}," Reading files...")),!a.isProcessingFiles&&J.createElement(Ag,{isLoading:i.isLoading,phrase:i.loadingMessage||"Processing",startTime:g}),(t.length>0||n.length>0)&&J.createElement(We,{flexShrink:0},J.createElement(Cg,{regularQueuedMessages:t,crossDeviceTasks:n})),s.showWizard&&s.wizard.type&&J.createElement(We,{flexShrink:0,paddingX:2,marginBottom:1},J.createElement(Tg,{type:s.wizard.type})),s.showCommandMenu&&J.createElement(We,{flexShrink:0,paddingX:2,marginBottom:0},J.createElement(wg,{filterText:a.input.startsWith("/")?a.input.substring(1).toLowerCase():"",onSelect:v=>{r.hideCommandMenu(),l(`/${v}`)}})),s.showModelMenu&&J.createElement(We,{flexShrink:0,paddingX:2,marginBottom:1},J.createElement(bg,{userTier:o,onSelect:v=>{r.setModel(v),r.hideModelMenu()},onAccessDenied:v=>{e.addSystemMessage(xe.getAccessDeniedMessage(v)),r.hideModelMenu()}})),s.showHelp&&J.createElement(We,{flexShrink:0,paddingX:2,marginBottom:1},J.createElement(pg,null)),s.isReverseSearchActive&&J.createElement(We,{flexShrink:0,paddingX:2,marginBottom:1},J.createElement(mm,{query:x.query,history:a.history,currentMatchIndex:x.currentMatchIndex,matchCount:x.matchCount,matchedEntry:x.currentMatch?.item||null,isActive:s.isReverseSearchActive})),!s.showWizard&&J.createElement(We,{flexShrink:0,paddingX:2},J.createElement(Pg,{input:a.input,isLoading:i.isLoading,pastedTexts:a.pastedTexts,cursorPosition:a.cursorPosition,suggestion:a.suggestion,mode:s.operationalMode})),s.toasts.length>0&&J.createElement(We,{flexShrink:0,paddingX:2},J.createElement(dm,{toasts:s.toasts,onRemove:r.removeToast,maxToasts:3})),J.createElement(Lg,{cwd:d,selectedModel:s.selectedModel,showScrollHint:!1,tier:o}))}function bm({initialProjectPath:i}={}){return J.createElement(Ld,{initialProjectPath:i},J.createElement(gT,null))}Ec();Te();Te();import se from"chalk";import xT from"inquirer";import{exec as CT}from"child_process";var yn=class{authService;constructor(){this.authService=X.getInstance()}openBrowser(e){return new Promise(t=>{let n=process.platform,s;n==="darwin"?s=`open "${e}"`:n==="win32"?s=`start "" "${e}"`:s=`xdg-open "${e}"`,CT(s,r=>{r&&console.log(se.yellow("⚠️ Could not auto-open browser. Please open the URL manually.")),t()})})}async login(){console.log(se.blue(`
|
|
2029
2033
|
🔐 Orion Authentication`)),console.log(se.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(se.yellow(`
|
|
2030
2034
|
📋 Opening browser for authentication...`)),console.log(se.cyan.underline(` ${e}`)),await this.openBrowser(e),console.log(se.white(`
|
|
2031
2035
|
1. Log in with your Orion account in the browser`)),console.log(se.white("2. Copy the access token shown after login")),console.log(se.white("3. Paste the token below")),console.log(se.yellow(`
|
|
2032
|
-
Paste your access token here:`));let{accessToken:t}=await
|
|
2036
|
+
Paste your access token here:`));let{accessToken:t}=await xT.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:n=>!n||n.trim().length===0?"Access token is required":!0}]);console.log(se.gray(`
|
|
2033
2037
|
Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let s=await this.authService.getUserInfo();console.log(se.green(`
|
|
2034
2038
|
✅ Authentication successful!`)),s&&(console.log(se.gray(`Logged in as: ${s.email||s.username||"User"}`)),console.log(se.gray(`Subscription: ${this.getSubscriptionDisplay(s.subscription?.tier)}`)))}else console.log(se.red(`
|
|
2035
2039
|
❌ Authentication failed. Please try again.`))}catch(n){console.log(se.red(`
|
|
@@ -2039,7 +2043,7 @@ Verifying access token...`));try{if(await this.authService.authenticateWithAcces
|
|
|
2039
2043
|
❌ Logout failed`)),console.log(se.gray("Some cleanup operations may have failed, but local data has been cleared.")))}async status(){if(await this.authService.autoAuthenticate(),this.authService.isAuthenticated()){let t=await this.authService.getUserInfo();if(console.log(se.green(`
|
|
2040
2044
|
✅ Authenticated`)),t){console.log(se.gray("─".repeat(50))),console.log(se.white("User:",t.name||t.username||"N/A")),console.log(se.white("Email:",t.email||"N/A"));let n=this.getSubscriptionDisplay(t.subscription?.tier);console.log(se.white("Subscription:",n)),t.usage&&(console.log(se.gray(`
|
|
2041
2045
|
Usage:`)),console.log(se.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(se.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(se.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(se.yellow(`
|
|
2042
|
-
⚠️ Not authenticated`)),console.log(se.gray('Run "orion auth login" to authenticate'))}getSubscriptionDisplay(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}};wt();
|
|
2046
|
+
⚠️ Not authenticated`)),console.log(se.gray('Run "orion auth login" to authenticate'))}getSubscriptionDisplay(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}};wt();Pa();var Im=!1;async function Ic(){let i=process.cwd();if(Im){console.log("Already running...");return}Im=!0,Y.enableCustomUI();let e=wr.getInstance(),t=X.getInstance();if(!e.isInitialized()){console.log("🔧 Initializing Orion services...");try{await e.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(o){console.error(`
|
|
2043
2047
|
❌ Failed to initialize services:`,o.message),console.error(`
|
|
2044
2048
|
💡 Tip: Check your internet connection and Firebase configuration.
|
|
2045
2049
|
`),process.exit(1)}}(!await t.autoAuthenticate()||!t.isAuthenticated())&&(console.log(`🔐 Authentication required to use Orion CLI
|
|
@@ -2049,8 +2053,8 @@ Usage:`)),console.log(se.white(` Standard prompts: ${t.usage.prompt||0}`)),cons
|
|
|
2049
2053
|
`)),t.isFirebaseAuthenticated()||(console.error(`
|
|
2050
2054
|
❌ 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(`
|
|
2051
2055
|
Please check your connection and try again.
|
|
2052
|
-
`),process.exit(1)),console.log("✅ Authentication verified"),
|
|
2053
|
-
🎮 Discord Integration`)),console.log(O.gray("─".repeat(50)));let e=
|
|
2056
|
+
`),process.exit(1)),console.log("✅ Authentication verified"),er.getInstance().setWorkingDirectory(i),process.stdout.write("\x1B[2J\x1B[H");let{waitUntilExit:r}=IT(ET.createElement(bm,{initialProjectPath:i}),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:!1,alternateBuffer:!0});await r(),Id()}import O from"chalk";import ae from"inquirer";import Ve from"ora";import{exec as kT}from"child_process";Te();var Gn=class{integrationsService;authService;constructor(){this.integrationsService=Wt.getInstance(),this.authService=X.getInstance()}async ensureAuthenticated(){let e=Ve("Checking authentication...").start();return await this.authService.autoAuthenticate(),this.authService.isAuthenticated()?(e.stop(),!0):(e.fail("Not authenticated"),console.log(O.gray('Run "orion auth login" first.')),!1)}openBrowser(e){let t=process.platform,n;t==="darwin"?n=`open "${e}"`:t==="win32"?n=`start "" "${e}"`:n=`xdg-open "${e}"`,kT(n,()=>{})}async discord(){if(!await this.ensureAuthenticated())return;console.log(O.blue(`
|
|
2057
|
+
🎮 Discord Integration`)),console.log(O.gray("─".repeat(50)));let e=Ve("Checking connection status...").start(),t=await this.integrationsService.getDiscordStatus();e.stop(),t.connected?await this.manageDiscord(t):await this.setupDiscord()}async manageDiscord(e){if(console.log(O.green(`
|
|
2054
2058
|
✓ Connected`)),console.log(O.white(" Bot:"),O.cyan(e.botUsername||"Unknown")),console.log(O.gray(`
|
|
2055
2059
|
─ Setup Info ─`)),e.webhookUrl&&(console.log(O.white(" Webhook URL:"),O.cyan(e.webhookUrl)),console.log(O.gray(" (Add this to Discord Developer Portal → Interactions Endpoint URL)"))),e.botId){let n=this.integrationsService.generateDiscordInviteUrl(e.botId);console.log(O.white(" Invite URL:"),O.cyan(n))}console.log(O.gray(" Commands: /ask, /new, /clear")),console.log(O.gray(`
|
|
2056
2060
|
─ Access Control ─`)),console.log(O.white(" Owners:"),e.ownerUserIds?.length?e.ownerUserIds.join(", "):O.gray("None")),console.log(O.white(" Guests:"),e.guestUserIds?.length?e.guestUserIds.join(", "):O.gray("None")),console.log(O.gray(`
|
|
@@ -2062,14 +2066,14 @@ Opening invite link...`)),this.openBrowser(n),console.log(O.cyan(n))}break;case"
|
|
|
2062
2066
|
─ Step 2: Enter Bot Token ─`));let{botToken:t}=await ae.prompt([{type:"password",name:"botToken",message:"Bot Token:",mask:"*",validate:l=>l?.trim()?this.integrationsService.validateDiscordToken(l)?!0:"Invalid token format. Discord tokens look like: NzE2MjE0....":"Bot token is required"}]);console.log(O.white(`
|
|
2063
2067
|
─ Step 3: Access Control ─`)),console.log(O.gray(" Owners: Full access including device tools (files, browser, apps)")),console.log(O.gray(" Guests: Cloud-only tools, sandboxed conversations")),console.log(O.yellow(` ⚠️ Only add people you fully trust as owners.
|
|
2064
2068
|
`));let{ownerIds:n}=await ae.prompt([{type:"input",name:"ownerIds",message:"Owner Discord User IDs (comma-separated):",validate:l=>l?.trim()?!0:"At least one owner is required"}]),{guestIds:s}=await ae.prompt([{type:"input",name:"guestIds",message:"Guest Discord User IDs (optional, press Enter to skip):"}]),r=!1,{allowGuild:o}=await ae.prompt([{type:"confirm",name:"allowGuild",message:"Allow server/guild chat? (or DM only)",default:!1}]);if(o){console.log(O.yellow(`
|
|
2065
|
-
⚠️ Warning: Server chat means others in the server can see bot responses.`));let{confirmGuild:l}=await ae.prompt([{type:"confirm",name:"confirmGuild",message:"Are you sure you want to enable server chat?",default:!1}]);l?r=!0:console.log(O.gray("Server chat will be disabled."))}let a=
|
|
2069
|
+
⚠️ Warning: Server chat means others in the server can see bot responses.`));let{confirmGuild:l}=await ae.prompt([{type:"confirm",name:"confirmGuild",message:"Are you sure you want to enable server chat?",default:!1}]);l?r=!0:console.log(O.gray("Server chat will be disabled."))}let a=Ve("Connecting to Discord...").start(),c=await this.integrationsService.connectDiscord({botToken:t.trim(),ownerUserIds:n.split(",").map(l=>l.trim()).filter(Boolean),guestUserIds:s?s.split(",").map(l=>l.trim()).filter(Boolean):[],allowGuildChat:r});if(c.success){if(a.succeed("Discord bot connected!"),console.log(O.white(`
|
|
2066
2070
|
─ Finish Setup ─`)),console.log(O.white(" Bot:"),O.cyan(c.botUsername)),c.webhookUrl&&(console.log(O.white(`
|
|
2067
2071
|
1. Set Interactions Endpoint URL:`)),console.log(O.cyan(` ${c.webhookUrl}`)),console.log(O.gray(" (Copy this to Discord Developer Portal → Your App → General Information)"))),c.botId){let l=this.integrationsService.generateDiscordInviteUrl(c.botId);console.log(O.white(`
|
|
2068
2072
|
2. Invite bot to your server:`)),console.log(O.cyan(` ${l}`));let{openInvite:d}=await ae.prompt([{type:"confirm",name:"openInvite",message:"Open invite link now?",default:!0}]);d&&this.openBrowser(l)}console.log(O.white(`
|
|
2069
2073
|
3. Start chatting!`)),console.log(O.gray(" Use /ask, /new, or /clear commands in Discord"))}else a.fail(`Connection failed: ${c.error}`)}async updateDiscordUsers(e){console.log(O.gray(`
|
|
2070
|
-
Current owners:`),e.ownerUserIds?.join(", ")||"None"),console.log(O.gray("Current guests:"),e.guestUserIds?.join(", ")||"None");let{ownerIds:t}=await ae.prompt([{type:"input",name:"ownerIds",message:"Owner User IDs (comma-separated):",default:e.ownerUserIds?.join(", ")||"",validate:o=>o?.trim()?!0:"At least one owner required"}]),{guestIds:n}=await ae.prompt([{type:"input",name:"guestIds",message:"Guest User IDs (optional):",default:e.guestUserIds?.join(", ")||""}]),s=
|
|
2071
|
-
⚠️ Warning: Enabling server chat means:`)),console.log(O.gray(" - Bot will respond in server channels (not just DMs)")),console.log(O.gray(" - Others in the server can see bot responses"));let{confirm:r}=await ae.prompt([{type:"confirm",name:"confirm",message:"Enable server chat?",default:!1}]);if(!r){console.log(O.gray("Cancelled."));return}}let n=
|
|
2072
|
-
📱 Telegram Integration`)),console.log(O.gray("─".repeat(50)));let e=
|
|
2074
|
+
Current owners:`),e.ownerUserIds?.join(", ")||"None"),console.log(O.gray("Current guests:"),e.guestUserIds?.join(", ")||"None");let{ownerIds:t}=await ae.prompt([{type:"input",name:"ownerIds",message:"Owner User IDs (comma-separated):",default:e.ownerUserIds?.join(", ")||"",validate:o=>o?.trim()?!0:"At least one owner required"}]),{guestIds:n}=await ae.prompt([{type:"input",name:"guestIds",message:"Guest User IDs (optional):",default:e.guestUserIds?.join(", ")||""}]),s=Ve("Updating...").start(),r=await this.integrationsService.updateDiscord({ownerUserIds:t.split(",").map(o=>o.trim()).filter(Boolean),guestUserIds:n?n.split(",").map(o=>o.trim()).filter(Boolean):[]});r.success?s.succeed("Updated successfully."):s.fail(`Update failed: ${r.error}`)}async toggleDiscordGuild(e,t){if(t){console.log(O.yellow(`
|
|
2075
|
+
⚠️ Warning: Enabling server chat means:`)),console.log(O.gray(" - Bot will respond in server channels (not just DMs)")),console.log(O.gray(" - Others in the server can see bot responses"));let{confirm:r}=await ae.prompt([{type:"confirm",name:"confirm",message:"Enable server chat?",default:!1}]);if(!r){console.log(O.gray("Cancelled."));return}}let n=Ve(`${t?"Enabling":"Disabling"} server chat...`).start(),s=await this.integrationsService.updateDiscord({allowGuildChat:t});s.success?n.succeed(`Server chat ${t?"enabled":"disabled"}.`):n.fail(`Failed: ${s.error}`)}async disconnectDiscordConfirm(){let{confirm:e}=await ae.prompt([{type:"confirm",name:"confirm",message:O.red("Disconnect Discord bot? This cannot be undone."),default:!1}]);if(!e){console.log(O.gray("Cancelled."));return}let t=Ve("Disconnecting...").start();await this.integrationsService.disconnectDiscord()?t.succeed("Discord disconnected."):t.fail("Failed to disconnect.")}async disconnectDiscordQuiet(){await this.integrationsService.disconnectDiscord()}async telegram(){if(!await this.ensureAuthenticated())return;console.log(O.blue(`
|
|
2076
|
+
📱 Telegram Integration`)),console.log(O.gray("─".repeat(50)));let e=Ve("Checking connection status...").start(),t=await this.integrationsService.getTelegramStatus();e.stop(),t.connected?await this.manageTelegram(t):await this.setupTelegram()}async manageTelegram(e){console.log(O.green(`
|
|
2073
2077
|
✓ Connected`)),console.log(O.white(" Bot:"),O.cyan(`@${e.botUsername}`));let t=this.integrationsService.getTelegramChatUrl(e.botUsername||"");console.log(O.white(" Chat:"),O.cyan(t)),console.log(O.gray(" 💡 Send /new to start a fresh conversation. Memory persists.")),console.log(O.gray(`
|
|
2074
2078
|
─ Access Control ─`)),console.log(O.white(" Owners:"),e.ownerUsernames?.length?e.ownerUsernames.map(r=>`@${r}`).join(", "):O.gray("None")),console.log(O.white(" Guests:"),e.guestUsernames?.length?e.guestUsernames.map(r=>`@${r}`).join(", "):O.gray("None")),console.log(O.gray(`
|
|
2075
2079
|
─ Chat Mode ─`)),console.log(O.white(" Group chat:"),e.allowGroupChat?O.green("Enabled"):O.gray("Disabled (DM only)")),e.allowGroupChat&&console.log(O.white(" Route to DM:"),e.routeToDM?O.green("Enabled"):O.gray("Disabled"));let n=[{name:"💬 Open chat in Telegram",value:"open_chat"},{name:"👥 Update owners/guests",value:"update_users"},{name:e.allowGroupChat?"🔒 Disable group chat":"🌐 Enable group chat",value:"toggle_group"}];e.allowGroupChat&&n.push({name:e.routeToDM?"📥 Disable route to DM":"📤 Enable route to DM",value:"toggle_route_dm"}),n.push({name:"🔄 Reconnect with new token",value:"reconnect"},new ae.Separator,{name:O.red("🗑️ Disconnect"),value:"disconnect"},{name:"Cancel",value:"cancel"});let{action:s}=await ae.prompt([{type:"list",name:"action",message:`
|
|
@@ -2081,13 +2085,13 @@ Opening Telegram...`)),this.openBrowser(t);break;case"update_users":await this.u
|
|
|
2081
2085
|
`));let{ownerUsernames:n}=await ae.prompt([{type:"input",name:"ownerUsernames",message:"Owner Telegram usernames (with @, comma-separated):",validate:d=>d?.trim()?!0:"At least one owner is required"}]),{guestUsernames:s}=await ae.prompt([{type:"input",name:"guestUsernames",message:"Guest usernames (optional, press Enter to skip):"}]);console.log(O.white(`
|
|
2082
2086
|
─ Step 4: Chat Settings ─`));let r=!1,o=!1,{allowGroup:a}=await ae.prompt([{type:"confirm",name:"allowGroup",message:"Allow group chat? (or DM only)",default:!1}]);if(a){console.log(O.yellow(`
|
|
2083
2087
|
⚠️ For group chat, you need to disable Privacy Mode:`)),console.log(O.gray(" 1. Open @BotFather")),console.log(O.gray(" 2. Send /setprivacy")),console.log(O.gray(" 3. Select your bot")),console.log(O.gray(' 4. Choose "Disable"')),console.log(O.gray(` Without this, the bot only responds to /commands in groups.
|
|
2084
|
-
`));let{confirmGroup:d}=await ae.prompt([{type:"confirm",name:"confirmGroup",message:"I understand. Enable group chat?",default:!0}]);if(d){r=!0;let{enableRouteDM:g}=await ae.prompt([{type:"confirm",name:"enableRouteDM",message:"Route group responses to DM? (keeps group chat clean)",default:!1}]);o=g}else console.log(O.gray("Group chat will be disabled."))}let c=
|
|
2088
|
+
`));let{confirmGroup:d}=await ae.prompt([{type:"confirm",name:"confirmGroup",message:"I understand. Enable group chat?",default:!0}]);if(d){r=!0;let{enableRouteDM:g}=await ae.prompt([{type:"confirm",name:"enableRouteDM",message:"Route group responses to DM? (keeps group chat clean)",default:!1}]);o=g}else console.log(O.gray("Group chat will be disabled."))}let c=Ve("Connecting to Telegram...").start(),l=await this.integrationsService.connectTelegram({botToken:t.trim(),ownerUsernames:n.split(",").map(d=>d.trim().replace(/^@/,"")).filter(Boolean),guestUsernames:s?s.split(",").map(d=>d.trim().replace(/^@/,"")).filter(Boolean):[],allowGroupChat:r,routeToDM:o});if(l.success){c.succeed("Telegram bot connected!");let d=this.integrationsService.getTelegramChatUrl(l.botUsername||"");console.log(O.white(`
|
|
2085
2089
|
Bot:`),O.cyan(`@${l.botUsername}`)),console.log(O.white(" Chat:"),O.cyan(d)),console.log(O.gray(`
|
|
2086
2090
|
💡 Send /new to start a fresh conversation.`));let{openChat:g}=await ae.prompt([{type:"confirm",name:"openChat",message:"Open chat in Telegram?",default:!0}]);g&&this.openBrowser(d)}else c.fail(`Connection failed: ${l.error}`)}async updateTelegramUsers(e){console.log(O.gray(`
|
|
2087
|
-
Current owners:`),e.ownerUsernames?.map(o=>`@${o}`).join(", ")||"None"),console.log(O.gray("Current guests:"),e.guestUsernames?.map(o=>`@${o}`).join(", ")||"None");let{ownerUsernames:t}=await ae.prompt([{type:"input",name:"ownerUsernames",message:"Owner usernames (with @, comma-separated):",default:e.ownerUsernames?.map(o=>`@${o}`).join(", ")||"",validate:o=>o?.trim()?!0:"At least one owner required"}]),{guestUsernames:n}=await ae.prompt([{type:"input",name:"guestUsernames",message:"Guest usernames (optional):",default:e.guestUsernames?.map(o=>`@${o}`).join(", ")||""}]),s=
|
|
2091
|
+
Current owners:`),e.ownerUsernames?.map(o=>`@${o}`).join(", ")||"None"),console.log(O.gray("Current guests:"),e.guestUsernames?.map(o=>`@${o}`).join(", ")||"None");let{ownerUsernames:t}=await ae.prompt([{type:"input",name:"ownerUsernames",message:"Owner usernames (with @, comma-separated):",default:e.ownerUsernames?.map(o=>`@${o}`).join(", ")||"",validate:o=>o?.trim()?!0:"At least one owner required"}]),{guestUsernames:n}=await ae.prompt([{type:"input",name:"guestUsernames",message:"Guest usernames (optional):",default:e.guestUsernames?.map(o=>`@${o}`).join(", ")||""}]),s=Ve("Updating...").start(),r=await this.integrationsService.updateTelegram({ownerUsernames:t.split(",").map(o=>o.trim().replace(/^@/,"")).filter(Boolean),guestUsernames:n?n.split(",").map(o=>o.trim().replace(/^@/,"")).filter(Boolean):[]});r.success?s.succeed("Updated successfully."):s.fail(`Update failed: ${r.error}`)}async toggleTelegramGroup(e,t){if(t){console.log(O.yellow(`
|
|
2088
2092
|
⚠️ To use group chat, disable Privacy Mode in @BotFather:`)),console.log(O.gray(" /setprivacy → Select your bot → Disable")),console.log(O.gray(` Without this, the bot only responds to /commands in groups.
|
|
2089
|
-
`));let{confirm:r}=await ae.prompt([{type:"confirm",name:"confirm",message:"Enable group chat?",default:!1}]);if(!r){console.log(O.gray("Cancelled."));return}}let n=
|
|
2090
|
-
🔌 Integration Status`)),console.log(O.gray("─".repeat(50)));let e=
|
|
2093
|
+
`));let{confirm:r}=await ae.prompt([{type:"confirm",name:"confirm",message:"Enable group chat?",default:!1}]);if(!r){console.log(O.gray("Cancelled."));return}}let n=Ve(`${t?"Enabling":"Disabling"} group chat...`).start(),s=await this.integrationsService.updateTelegram({allowGroupChat:t,routeToDM:t?e.routeToDM:!1});s.success?n.succeed(`Group chat ${t?"enabled":"disabled"}.`):n.fail(`Failed: ${s.error}`)}async toggleTelegramRouteDM(e,t){let n=Ve(`${t?"Enabling":"Disabling"} route to DM...`).start(),s=await this.integrationsService.updateTelegram({routeToDM:t});s.success?(n.succeed(`Route to DM ${t?"enabled":"disabled"}.`),t&&console.log(O.gray(" Group responses will be sent via private DM."))):n.fail(`Failed: ${s.error}`)}async disconnectTelegramConfirm(){let{confirm:e}=await ae.prompt([{type:"confirm",name:"confirm",message:O.red("Disconnect Telegram bot? This cannot be undone."),default:!1}]);if(!e){console.log(O.gray("Cancelled."));return}let t=Ve("Disconnecting...").start();await this.integrationsService.disconnectTelegram()?t.succeed("Telegram disconnected."):t.fail("Failed to disconnect.")}async disconnectTelegramQuiet(){await this.integrationsService.disconnectTelegram()}async status(){if(!await this.ensureAuthenticated())return;console.log(O.blue(`
|
|
2094
|
+
🔌 Integration Status`)),console.log(O.gray("─".repeat(50)));let e=Ve("Checking...").start(),[t,n]=await Promise.all([this.integrationsService.getDiscordStatus(),this.integrationsService.getTelegramStatus()]);e.stop(),console.log(O.white(`
|
|
2091
2095
|
Discord`)),t.connected?(console.log(O.green(" ✓ Connected")),console.log(O.gray(` Bot: ${t.botUsername}`)),console.log(O.gray(` Owners: ${t.ownerUserIds?.join(", ")||"None"}`)),console.log(O.gray(` Guests: ${t.guestUserIds?.length?t.guestUserIds.join(", "):"None"}`)),console.log(O.gray(` Server chat: ${t.allowGuildChat?"Enabled":"Disabled"}`))):(console.log(O.gray(" Not connected")),console.log(O.gray(" Run: orion integrations discord"))),console.log(O.white(`
|
|
2092
|
-
Telegram`)),n.connected?(console.log(O.green(" ✓ Connected")),console.log(O.gray(` Bot: @${n.botUsername}`)),console.log(O.gray(` Owners: ${n.ownerUsernames?.map(s=>`@${s}`).join(", ")||"None"}`)),console.log(O.gray(` Guests: ${n.guestUsernames?.length?n.guestUsernames.map(s=>`@${s}`).join(", "):"None"}`)),console.log(O.gray(` Group chat: ${n.allowGroupChat?"Enabled":"Disabled"}`)),n.allowGroupChat&&console.log(O.gray(` Route to DM: ${n.routeToDM?"Enabled":"Disabled"}`))):(console.log(O.gray(" Not connected")),console.log(O.gray(" Run: orion integrations telegram")))}async disconnect(){if(!await this.ensureAuthenticated())return;let e=
|
|
2093
|
-
⚠️ No integrations connected.`));return}s.push(new ae.Separator,{name:"Cancel",value:"cancel"});let{platform:r}=await ae.prompt([{type:"list",name:"platform",message:"Which integration to disconnect?",choices:s}]);if(r==="cancel")return;let{confirm:o}=await ae.prompt([{type:"confirm",name:"confirm",message:O.red(`Disconnect ${r}? This cannot be undone.`),default:!1}]);if(!o){console.log(O.gray("Cancelled."));return}let a=
|
|
2096
|
+
Telegram`)),n.connected?(console.log(O.green(" ✓ Connected")),console.log(O.gray(` Bot: @${n.botUsername}`)),console.log(O.gray(` Owners: ${n.ownerUsernames?.map(s=>`@${s}`).join(", ")||"None"}`)),console.log(O.gray(` Guests: ${n.guestUsernames?.length?n.guestUsernames.map(s=>`@${s}`).join(", "):"None"}`)),console.log(O.gray(` Group chat: ${n.allowGroupChat?"Enabled":"Disabled"}`)),n.allowGroupChat&&console.log(O.gray(` Route to DM: ${n.routeToDM?"Enabled":"Disabled"}`))):(console.log(O.gray(" Not connected")),console.log(O.gray(" Run: orion integrations telegram")))}async disconnect(){if(!await this.ensureAuthenticated())return;let e=Ve("Checking connections...").start(),[t,n]=await Promise.all([this.integrationsService.getDiscordStatus(),this.integrationsService.getTelegramStatus()]);e.stop();let s=[];if(t.connected&&s.push({name:`🎮 Discord (${t.botUsername})`,value:"discord"}),n.connected&&s.push({name:`📱 Telegram (@${n.botUsername})`,value:"telegram"}),s.length===0){console.log(O.yellow(`
|
|
2097
|
+
⚠️ No integrations connected.`));return}s.push(new ae.Separator,{name:"Cancel",value:"cancel"});let{platform:r}=await ae.prompt([{type:"list",name:"platform",message:"Which integration to disconnect?",choices:s}]);if(r==="cancel")return;let{confirm:o}=await ae.prompt([{type:"confirm",name:"confirm",message:O.red(`Disconnect ${r}? This cannot be undone.`),default:!1}]);if(!o){console.log(O.gray("Cancelled."));return}let a=Ve("Disconnecting...").start();(r==="discord"?await this.integrationsService.disconnectDiscord():await this.integrationsService.disconnectTelegram())?a.succeed(`${r.charAt(0).toUpperCase()+r.slice(1)} disconnected.`):a.fail("Failed to disconnect.")}};Kt();import AT from"dotenv";import{fileURLToPath as DT}from"url";import{dirname as MT,join as RT}from"path";import{readFileSync as OT}from"fs";AT.config();var NT=DT(import.meta.url),_T=MT(NT),km=JSON.parse(OT(RT(_T,"..","package.json"),"utf8")),$T=process.argv.includes("--no-update")||process.env.ORION_NO_UPDATE==="true";!Ku()&&!$T&&os.getInstance(km.version).checkAndUpdate().catch(()=>{});var jn=new PT;jn.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(km.version).option("--no-update","Disable automatic update check");jn.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await Ic()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});jn.command("ask <question>").description("Ask a single question (Advanced Mode with Orion features)").option("-m, --model <model>","Select AI model","snowx-5c").option("-s, --stream","Enable streaming response",!0).action(async(i,e)=>{try{let{ServiceManager:t}=await Promise.resolve().then(()=>(Ec(),Em)),n=t.getInstance();console.log("🔧 Initializing Orion services..."),await n.initialize(),await n.waitForDeviceRegistration();let s=me.find(o=>o.name===e.model)||me[0];console.log("💭 Sending message...");let r=await n.sendMessage(i,s,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(Cr(r))}catch(t){ke.stopSpinner(!1),console.error(ke.formatError(t.message)),process.exit(1)}});var kc=jn.command("auth").description("Authentication commands");kc.command("login").description("Login to Orion").action(async()=>{try{await new yn().login()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});kc.command("logout").description("Logout from Orion").action(async()=>{try{await new yn().logout()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});kc.command("status").description("Check authentication status").action(async()=>{try{await new yn().status()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});var bi=jn.command("integrations").description("Manage Discord and Telegram integrations");bi.command("discord").description("Setup Discord bot integration").action(async()=>{try{await new Gn().discord()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});bi.command("telegram").description("Setup Telegram bot integration").action(async()=>{try{await new Gn().telegram()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});bi.command("status").description("Show integration status").action(async()=>{try{await new Gn().status()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});bi.command("disconnect").description("Disconnect an integration").action(async()=>{try{await new Gn().disconnect()}catch(i){console.error(ke.formatError(i.message)),process.exit(1)}});jn.command("models").description("List available AI models").action(()=>{ke.printHeader("Available Models");for(let i of me)console.log(`${ke.formatModelName(i.name)} - ${i.displayName}`)});process.argv.length===2?Ic().catch(i=>{console.error(ke.formatError(i.message)),process.exit(1)}):jn.parse(process.argv);
|