import { createHash } from 'node:crypto'; import { z } from '@midscene/core'; import { type AgentBehaviorInitArgs, agentBehaviorInitArgShape, getAgentInitArgsSignature, shouldRebuildAgentForInitArgs, } from '@midscene/shared/agent-tools/agent-behavior-init-args'; import { BaseMidsceneTools, type InitArgSpec, } from '@midscene/shared/agent-tools/base-tools'; import type { ToolDefinition } from '@midscene/shared/agent-tools/types'; import { getDebug } from '@midscene/shared/logger'; import { type IOSAgent, agentFromWebDriverAgent } from './agent'; import { IOSDevice, type IOSDeviceOpt } from './device'; import { assertWdaConnectionOptions } from './wda-options'; const debug = getDebug('agent-tools:ios'); const iosInitArgShape = { wdaBaseUrl: z .string() .optional() .describe( 'Full WebDriverAgent API base URL, including gateway path prefix', ), wdaHost: z .string() .optional() .describe('WebDriverAgent host, defaults to localhost'), wdaPort: z.number().optional().describe('WebDriverAgent port'), sessionId: z .string() .optional() .describe('Existing WebDriverAgent session ID to reuse'), wdaMjpegPort: z .number() .optional() .describe('WebDriverAgent MJPEG streaming port'), wdaMjpegUrl: z .string() .optional() .describe('Full HTTP(S) WebDriverAgent MJPEG stream URL'), wdaMjpegFrameSource: z .object({ enabled: z.boolean().optional() }) .optional() .describe( 'Opt-in: use the WDA MJPEG stream as a continuous frame source for UI observation (default off)', ), ...agentBehaviorInitArgShape, }; type IOSInitArgs = AgentBehaviorInitArgs & Pick< IOSDeviceOpt, | 'wdaBaseUrl' | 'wdaHost' | 'wdaPort' | 'sessionId' | 'wdaMjpegPort' | 'wdaMjpegUrl' | 'wdaMjpegFrameSource' >; function getTargetIdentity(initArgs?: IOSInitArgs): string { if (initArgs?.wdaBaseUrl || initArgs?.wdaMjpegUrl) { const fingerprint = createHash('sha256') .update( `${initArgs.wdaBaseUrl ?? ''}\0${initArgs.wdaMjpegUrl ?? ''}\0${initArgs.sessionId ?? ''}`, ) .digest('hex') .slice(0, 12); return `wda-${fingerprint}`; } if (initArgs?.wdaHost || initArgs?.wdaPort || initArgs?.sessionId) { const wdaHost = initArgs.wdaHost ?? 'localhost'; const wdaPort = initArgs.wdaPort ?? 'default'; const sessionSegment = initArgs.sessionId ? `-session-${initArgs.sessionId}` : ''; return `wda-${wdaHost}-${wdaPort}${sessionSegment}`; } return 'auto'; } /** * iOS-specific tools manager * Extends BaseMidsceneTools to provide iOS WebDriverAgent connection tools */ export class IOSMidsceneTools extends BaseMidsceneTools { protected getCliReportSessionName() { return 'midscene-ios'; } protected readonly initArgSpec: InitArgSpec = { namespace: 'ios', shape: iosInitArgShape, cli: { preferBareKeys: true, }, adapt: (extracted) => extracted as IOSInitArgs | undefined, }; private lastOptsSignature?: string; protected createTemporaryDevice() { // Create minimal temporary instance without connecting to WebDriverAgent // The constructor only initializes WDA backend, doesn't establish connection return new IOSDevice({}); } protected async ensureAgent(opts?: IOSInitArgs): Promise { assertWdaConnectionOptions(opts); const nextSignature = getAgentInitArgsSignature(opts); if ( this.agent && shouldRebuildAgentForInitArgs(this.lastOptsSignature, nextSignature) ) { try { await this.agent.destroy?.(); } catch (error) { debug('Failed to destroy agent during cleanup:', error); } this.agent = undefined; } if (this.agent) { return this.agent; } debug('Creating iOS agent with WebDriverAgent options'); const reportOptions = this.readCliReportAgentOptions(); this.agent = await agentFromWebDriverAgent({ autoDismissKeyboard: false, ...(reportOptions ?? {}), ...(opts ?? {}), }); this.lastOptsSignature = nextSignature; return this.agent; } /** * Provide iOS-specific platform tools */ protected preparePlatformTools(): ToolDefinition[] { return [ { name: 'ios_connect', description: 'Connect to iOS device or simulator via WebDriverAgent', schema: this.getAgentInitArgSchema(), cli: this.getAgentInitArgCliMetadata(), handler: async (args: Record) => { const initArgs = this.extractAgentInitParam(args); assertWdaConnectionOptions(initArgs); const identity = getTargetIdentity(initArgs); const reportSession = this.createNewCliReportSession(identity); this.commitCliReportSession(reportSession); if (this.agent) { try { await this.agent.destroy?.(); } catch (error) { debug('Failed to destroy agent during connect:', error); } this.agent = undefined; this.lastOptsSignature = undefined; } const agent = await this.ensureAgent(initArgs); const screenshot = await agent.page.screenshotBase64(); return { content: [ { type: 'text', text: 'Connected to iOS device', }, ...this.buildScreenshotContent(screenshot), ], isError: false, }; }, }, { name: 'ios_disconnect', description: 'Disconnect from current iOS device and release WebDriverAgent resources', schema: {}, handler: this.createDisconnectHandler('iOS device'), }, ]; } }