Midscenejs_client-agent设置

0 阅读1分钟
import {
  AndroidAgent,
  AndroidDevice,
  getConnectedDevices,
} from '@midscene/android';

const sleep = (ms: number) => new Promise((r: any) => setTimeout(r, ms));

export async function getAndroidAgent() {
  const devices = await getConnectedDevices();
  if (devices.length === 0) {
    throw new Error('No connected Android devices found');
  }
  
  const device = new AndroidDevice(devices[0].udid);
  const android_agent = new AndroidAgent(device, {
    aiActionContext:
      'If any location, permission, user agreement, etc. popup, click agree. If login page pops up, close it.',
  });
  
  await device.connect();
  return android_agent;
}

import { chromium, Browser, Page } from 'playwright';
import { PlaywrightAgent } from '@midscene/web';
// 确保环境变量已加载
import 'dotenv/config';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 确保环境变量已加载
dotenv.config({ path: path.resolve(__dirname, '../../.env') });

export interface WebAgentWithBrowser {
  agent: PlaywrightAgent;
  browser: Browser;
  page: Page;
}

export async function getWebAgent(url: string): Promise<WebAgentWithBrowser> {
  const browser = await chromium.launch({
    headless: false, // 'true' means we can't see the browser window
    args: ['--no-sandbox', '--disable-setuid-sandbox'],
  });

  const page = await browser.newPage();
  await page.setViewportSize({
    width: 1280,
    height: 768,
  });

  await page.goto(url, {waitUntil: 'domcontentloaded', timeout: 60000}); // Increase timeout to 60 seconds and use correct parameter name

  await sleep(5000); // 👀 init Midscene agent
  const web_agent = new PlaywrightAgent(page);
  
  return {
    agent: web_agent,
    browser,
    page
  };
}