Spaces:
Running
Running
File size: 14,527 Bytes
a9c717b 3d1ba88 a9c717b 3db3e6c a9c717b 3db3e6c a9c717b 3db3e6c a9c717b 3db3e6c a9c717b 3db3e6c a9c717b 3db3e6c a9c717b 3db3e6c a9c717b 3db3e6c a9c717b 3db3e6c a9c717b 3db3e6c a9c717b 3db3e6c a9c717b 3f6bf76 3db3e6c 3f6bf76 3db3e6c 3f6bf76 3db3e6c 3f6bf76 3db3e6c 3f6bf76 3db3e6c 3f6bf76 a9c717b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
"""
Interactive Browser Portal for Copilot
--------------------------------------
Allows admin to interact with the browser directly through /qazmlp
"""
import asyncio
import logging
from typing import Optional
from playwright.async_api import async_playwright, Page, BrowserContext
logger = logging.getLogger("kai_api.copilot_portal")
class CopilotPortal:
"""Manages an interactive browser session for Copilot."""
def __init__(self):
self.browser = None
self.context: Optional[BrowserContext] = None
self.page: Optional[Page] = None
self.playwright = None
self.is_initialized = False
self.last_screenshot = "/tmp/copilot_portal.png"
self.message_queue = []
self.last_activity = None
def is_running(self) -> bool:
"""Check if the portal is currently running."""
if not self.is_initialized:
return False
if not self.browser:
return False
try:
# Check if browser is still connected
return self.browser.is_connected()
except:
return False
async def initialize(self):
"""Initialize the browser and navigate to Copilot with enhanced stealth."""
if self.is_initialized:
return
try:
logger.info("🚀 Portal: Launching browser with stealth...")
self.playwright = await async_playwright().start()
# Enhanced browser args for stealth
self.browser = await self.playwright.chromium.launch(
headless=True,
args=[
"--disable-blink-features=AutomationControlled",
"--disable-features=IsolateOrigins,site-per-process",
"--disable-site-isolation-trials",
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-gpu",
"--disable-web-security",
"--disable-features=BlockInsecurePrivateNetworkRequests",
"--disable-features=InterestCohort",
"--window-size=1280,800",
"--start-maximized",
"--force-color-profile=srgb",
"--disable-background-timer-throttling",
"--disable-backgrounding-occluded-windows",
"--disable-renderer-backgrounding",
],
)
# More realistic browser context
self.context = await self.browser.new_context(
viewport={"width": 1280, "height": 800},
user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
locale="en-US",
timezone_id="America/New_York",
geolocation={"latitude": 40.7128, "longitude": -74.0060}, # NYC
permissions=["geolocation"],
color_scheme="light",
reduced_motion="no-preference",
)
# Enhanced stealth script
await self.context.add_init_script("""
// Override navigator properties
Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
Object.defineProperty(navigator, 'plugins', {get: () => [1, 2, 3, 4, 5]});
Object.defineProperty(navigator, 'languages', {get: () => ['en-US', 'en']});
// Override permissions
const originalQuery = window.navigator.permissions.query;
window.navigator.permissions.query = (parameters) => (
parameters.name === 'notifications' ?
Promise.resolve({ state: Notification.permission }) :
originalQuery(parameters)
);
// Add Chrome runtime
window.chrome = {
runtime: {
OnInstalledReason: {
CHROME_UPDATE: "chrome_update",
INSTALL: "install",
SHARED_MODULE_UPDATE: "shared_module_update",
UPDATE: "update"
},
OnRestartRequiredReason: {
APP_UPDATE: "app_update",
OS_UPDATE: "os_update",
PERIODIC: "periodic"
},
PlatformArch: {
ARM: "arm",
ARM64: "arm64",
MIPS: "mips",
MIPS64: "mips64",
X86_32: "x86-32",
X86_64: "x86-64"
},
PlatformNaclArch: {
ARM: "arm",
MIPS: "mips",
MIPS64: "mips64",
MIPS64_EL: "mips64el",
ARM64: "arm64",
X86_32: "x86-32",
X86_64: "x86-64"
},
PlatformOs: {
ANDROID: "android",
CROS: "cros",
LINUX: "linux",
MAC: "mac",
OPENBSD: "openbsd",
WIN: "win"
},
RequestUpdateCheckStatus: {
NO_UPDATE: "no_update",
THROTTLED: "throttled",
UPDATE_AVAILABLE: "update_available"
}
}
};
// Override WebGL
const getParameter = WebGLRenderingContext.prototype.getParameter;
WebGLRenderingContext.prototype.getParameter = function(parameter) {
if (parameter === 37445) {
return 'Intel Inc.';
}
if (parameter === 37446) {
return 'Intel Iris OpenGL Engine';
}
return getParameter(parameter);
};
""")
self.page = await self.context.new_page()
# Navigate to Copilot
logger.info("Portal: Navigating to Copilot...")
await self.page.goto("https://copilot.microsoft.com/", timeout=60000)
await asyncio.sleep(5)
self.is_initialized = True
logger.info("✅ Portal: Browser ready!")
# Take initial screenshot
await self.take_screenshot()
except Exception as e:
logger.error(f"Failed to initialize portal: {e}")
raise
async def take_screenshot(self) -> str:
"""Take a screenshot of the current page state."""
if not self.page:
return ""
try:
await self.page.screenshot(path=self.last_screenshot, full_page=False)
return self.last_screenshot
except Exception as e:
logger.error(f"Screenshot failed: {e}")
return ""
async def get_page_content(self) -> str:
"""Get current page HTML content for debugging."""
if not self.page:
return ""
try:
return await self.page.content()
except:
return ""
async def send_message(self, message: str) -> str:
"""Send a message through the portal."""
if not self.page:
return "Error: Browser not initialized"
try:
# Find input field
input_selectors = [
'textarea',
'div[contenteditable="true"]',
'[data-testid="chat-input"]',
'[role="textbox"]',
]
input_found = False
for selector in input_selectors:
try:
el = await self.page.wait_for_selector(selector, timeout=5000)
if el:
# Click and type
await el.click()
await self.page.keyboard.type(message, delay=10)
await asyncio.sleep(0.5)
await self.page.keyboard.press("Enter")
input_found = True
logger.info(f"Portal: Message sent via {selector}")
break
except:
continue
if not input_found:
return "Error: Could not find input field"
# Wait for response
await asyncio.sleep(3)
# Try to extract response
response_text = await self._extract_response()
# Take screenshot after response
await self.take_screenshot()
return response_text or "No response yet, check screenshot"
except Exception as e:
logger.error(f"Portal send error: {e}")
await self.take_screenshot()
return f"Error: {str(e)}"
async def _extract_response(self) -> str:
"""Try to extract the latest response."""
try:
return await self.page.evaluate("""
() => {
const selectors = [
'[data-message-author-role="assistant"]',
'.message-content',
'.ac-textBlock',
'[class*="response"]',
'article',
];
for (const sel of selectors) {
const els = document.querySelectorAll(sel);
if (els.length > 0) {
const last = els[els.length - 1];
const text = last.innerText || last.textContent || '';
if (text.trim().length > 10) return text.trim();
}
}
return '';
}
""")
except:
return ""
async def click_new_chat(self):
"""Click the New Chat button."""
if not self.page:
return
try:
btn = await self.page.query_selector('button:has-text("New chat")')
if btn:
await btn.click()
await asyncio.sleep(2)
await self.take_screenshot()
except Exception as e:
logger.error(f"Click new chat error: {e}")
async def refresh_page(self):
"""Refresh the page."""
if not self.page:
return
try:
await self.page.reload()
await asyncio.sleep(5)
await self.take_screenshot()
except Exception as e:
logger.error(f"Refresh error: {e}")
async def click_at_coordinates(self, x: float, y: float):
"""Click at specific coordinates on the page and immediately take screenshot."""
if not self.page:
logger.error("Portal: No page available for click")
return
try:
logger.info(f"Portal: Clicking at coordinates ({x}, {y})")
# First try clicking on main page
await self.page.mouse.click(x, y)
# Wait a short moment for the page to react
await asyncio.sleep(0.5)
# Check if there's an iframe at that location (CAPTCHA is often in iframe)
iframe_clicked = await self._try_click_iframe(x, y)
if iframe_clicked:
logger.info("Portal: Clicked inside iframe")
# Wait a bit more for any CAPTCHA processing
await asyncio.sleep(1)
# Take screenshot immediately
await self.take_screenshot()
logger.info("Portal: Click completed, screenshot taken")
except Exception as e:
logger.error(f"Portal click error: {e}")
# Still try to take screenshot on error
try:
await self.take_screenshot()
except:
pass
async def _try_click_iframe(self, x: float, y: float) -> bool:
"""Try to click inside iframes at the given coordinates."""
try:
# Get all iframes
iframes = await self.page.query_selector_all('iframe')
for iframe in iframes:
try:
# Check if iframe is visible and contains the coordinates
box = await iframe.bounding_box()
if box and box['x'] <= x <= box['x'] + box['width'] and box['y'] <= y <= box['y'] + box['height']:
# Click inside the iframe
frame = await iframe.content_frame()
if frame:
# Calculate relative coordinates
rel_x = x - box['x']
rel_y = y - box['y']
await frame.mouse.click(rel_x, rel_y)
return True
except:
continue
return False
except Exception as e:
logger.error(f"Iframe click error: {e}")
return False
async def close(self):
"""Close the browser."""
try:
if self.browser:
await self.browser.close()
if self.playwright:
await self.playwright.stop()
self.is_initialized = False
logger.info("Portal: Browser closed")
except Exception as e:
logger.error(f"Close error: {e}")
# Global portal instance
_portal: Optional[CopilotPortal] = None
def get_portal() -> CopilotPortal:
"""Get or create the global portal instance."""
global _portal
if _portal is None:
_portal = CopilotPortal()
return _portal
|