import type { TMultimodalPrompt, TUserPrompt } from '@/common'; import type { DetailedLocateParam, LocateOption, MidsceneYamlScript, MidsceneYamlScriptWebEnv, } from '@/types'; import { getDebug } from '@midscene/shared/logger'; import { assert } from '@midscene/shared/utils'; import yaml from 'js-yaml'; import { buildLocatePromptWithContext } from '../agent/prompt-context'; const debugUtils = getDebug('yaml:utils'); const topLevelTasksPattern = /^tasks\s*:/; const topLevelYamlKeyPattern = /^[^\s#][^:]*:/; export type WebTargetSource = 'page' | 'browser' | 'web' | 'target'; export type ResolvedWebTarget = { source: WebTargetSource; target: Partial & { mode: 'page' | 'browser' }; mode: 'page' | 'browser'; }; export type WebTargetConfig = Partial< Record> >; const webTargetSources: WebTargetSource[] = [ 'page', 'browser', 'web', 'target', ]; export function resolveWebTarget( config: WebTargetConfig, ): ResolvedWebTarget | undefined { const entries = webTargetSources .map((source) => [source, config[source]] as const) .filter( ( entry, ): entry is readonly [ WebTargetSource, Partial, ] => typeof entry[1] !== 'undefined', ); if (entries.length === 0) { return undefined; } if (entries.length > 1) { const specifiedTargets = entries.map(([source]) => source); throw new Error( `[midscene] Only one web target can be specified, but found multiple: ${specifiedTargets.join( ', ', )}. Please specify only one of: page, browser, web, or target.`, ); } const [source, target] = entries[0]; const explicitMode = target.mode; if ( typeof explicitMode !== 'undefined' && explicitMode !== 'page' && explicitMode !== 'browser' ) { throw new Error( `[midscene] web target mode must be either "page" or "browser", but got "${explicitMode}".`, ); } if (source === 'page' && explicitMode === 'browser') { throw new Error( '[midscene] page target cannot use mode: browser. Use browser: instead.', ); } if (source === 'browser' && explicitMode === 'page') { throw new Error( '[midscene] browser target cannot use mode: page. Use page: instead.', ); } const mode = source === 'page' ? 'page' : source === 'browser' ? 'browser' : (explicitMode ?? 'page'); if (mode === 'page' && target.autoFollowNewPage) { throw new Error( '[midscene] autoFollowNewPage requires browser mode. Use browser: or web.mode: browser.', ); } if ( mode === 'browser' && typeof target.forceSameTabNavigation !== 'undefined' ) { throw new Error( '[midscene] forceSameTabNavigation cannot be used in browser mode. Use page: or web.mode: page when same-tab navigation is required.', ); } return { source, mode, target: { ...target, mode, }, }; } /** Legacy output settings apply to every host, including native Test setup. * Target-local values keep their original priority; config supplies defaults. */ export function resolveYamlOutputConfig( script: Omit, ): { output?: string; unstableLogContent?: boolean | string; } { const target = resolveWebTarget(script)?.target ?? script.android ?? script.ios ?? script.harmony ?? script.computer; return { output: target?.output ?? script.config?.output, unstableLogContent: target?.unstableLogContent ?? script.config?.unstableLogContent, }; } function interpolateEnvVarRefs( value: string, keepUnresolvedRefs = false, ): string { let result = ''; let lastIndex = 0; let searchFrom = 0; while (searchFrom < value.length) { const start = value.indexOf('${', searchFrom); if (start === -1) { break; } const end = value.indexOf('}', start + 2); if (end === -1) { break; } const rawName = value.slice(start + 2, end); if (!rawName) { searchFrom = end + 1; continue; } result += value.slice(lastIndex, start); const envVar = rawName.trim(); const envValue = process.env[envVar]; if (envValue === undefined) { if (keepUnresolvedRefs) { result += value.slice(start, end + 1); } else { throw new Error(`Environment variable "${envVar}" is not defined`); } } else { result += envValue; } lastIndex = end + 1; searchFrom = end + 1; } return result + value.slice(lastIndex); } const multimodalLocateOptionFieldMap: Record = { images: true, convertHttpImage2Base64: true, }; const multimodalLocateOptionKeys = Object.keys( multimodalLocateOptionFieldMap, ) as Array; function extractMultimodalPrompt( opt?: LocateOption, ): Partial | undefined { if (typeof opt !== 'object' || opt === null) { return undefined; } const entries = multimodalLocateOptionKeys .map((key) => [key, opt[key]] as const) .filter(([, value]) => value !== undefined); return entries.length ? (Object.fromEntries(entries) as Partial) : undefined; } export function interpolateEnvVars(content: string): string { // Process line by line to skip commented lines const lines = content.split('\n'); const processedLines = lines.map((line) => { // Check if the line is a YAML comment (starts with # after optional whitespace) const trimmedLine = line.trimStart(); if (trimmedLine.startsWith('#')) { // Skip interpolation for comment lines return line; } // Process environment variables for non-comment lines return interpolateEnvVarRefs(line); }); return processedLines.join('\n'); } function interpolateYamlScriptEnvVars(content: string): string { let inTopLevelTasksBlock = false; return content .split('\n') .map((line) => { const trimmedLine = line.trimStart(); if (!trimmedLine || trimmedLine.startsWith('#')) { return line; } const indentSize = line.length - trimmedLine.length; if (indentSize === 0) { if (topLevelTasksPattern.test(trimmedLine)) { inTopLevelTasksBlock = true; return line; } if (topLevelYamlKeyPattern.test(trimmedLine)) { inTopLevelTasksBlock = false; } } return interpolateEnvVarRefs(line, inTopLevelTasksBlock); }) .join('\n'); } export function parseYamlScript( content: string, filePath?: string, ): MidsceneYamlScript { return parseLegacyYamlScript(content, filePath); } /** Internal collection observer; the public parser keeps its original signature. */ export function parseLegacyYamlScript( content: string, filePath?: string, onConfig?: (config: Omit) => void, ): MidsceneYamlScript { let processedContent = content; if (content.indexOf('android') !== -1 && content.match(/deviceId:\s*(\d+)/)) { let matchedDeviceId; processedContent = content.replace( /deviceId:\s*(\d+)/g, (match, deviceId) => { matchedDeviceId = deviceId; return `deviceId: '${deviceId}'`; }, ); console.warn( `please use string-style deviceId in yaml script, for example: deviceId: "${matchedDeviceId}"`, ); } const interpolatedContent = interpolateYamlScriptEnvVars(processedContent); const obj = yaml.load(interpolatedContent, { schema: yaml.JSON_SCHEMA, }) as MidsceneYamlScript; if (obj && typeof obj === 'object' && !Array.isArray(obj)) onConfig?.(obj); const pathTip = filePath ? `, failed to load ${filePath}` : ''; resolveWebTarget(obj); assert(obj.tasks, `property "tasks" is required in yaml script ${pathTip}`); assert( Array.isArray(obj.tasks), `property "tasks" must be an array in yaml script, but got ${obj.tasks}`, ); return obj; } export function buildDetailedLocateParam( locatePrompt: TUserPrompt, opt?: LocateOption, ): DetailedLocateParam | undefined { debugUtils('will call buildDetailedLocateParam', locatePrompt, opt); // Normalize object-form TUserPrompt: when the object only contains a // `prompt` string (no multimodal fields like `images`), unwrap it to // avoid double nesting like { prompt: { prompt: '...' } }. let normalizedLocatePrompt: TUserPrompt = locatePrompt; if ( typeof locatePrompt === 'object' && locatePrompt !== null && 'prompt' in locatePrompt ) { const { prompt: innerPrompt, ...rest } = locatePrompt; const hasMultimodalFields = Object.keys(rest).length > 0; normalizedLocatePrompt = hasMultimodalFields ? locatePrompt : innerPrompt; } let prompt = normalizedLocatePrompt || opt?.prompt || (opt as any)?.locate; // as a shortcut let deepLocate = false; let cacheable = true; let xpath = undefined; if (typeof opt === 'object' && opt !== null) { // Backward-compatible: accept `deepThink` as a deprecated alias for `deepLocate`. // All downstream code works on `deepLocate` only; the compatibility resolution // is intentionally kept here at the entry point so it does not bleed through // the rest of the call stack. deepLocate = opt.deepLocate ?? opt.deepThink ?? false; cacheable = opt.cacheable ?? true; xpath = opt.xpath; if (locatePrompt && opt.prompt && locatePrompt !== opt.prompt) { console.warn( 'conflict prompt for item', locatePrompt, opt, 'maybe you put the prompt in the wrong place', ); } prompt = prompt || opt.prompt; } if (!prompt) { debugUtils( 'no prompt, will return undefined in buildDetailedLocateParam', opt, ); return undefined; } const promptDisplay = typeof prompt === 'string' ? prompt : prompt.prompt; const context = opt?.context?.trim() || undefined; prompt = buildLocatePromptWithContext(prompt, opt?.context); const multimodalPrompt = extractMultimodalPrompt(opt); if (multimodalPrompt) { prompt = typeof prompt === 'string' ? { prompt, ...multimodalPrompt, } : { ...prompt, ...multimodalPrompt, }; } return { prompt, ...(context ? { promptDisplay, context } : {}), deepLocate, cacheable, xpath, }; } export function buildDetailedLocateParamAndRestParams( locatePrompt: TUserPrompt, opt: LocateOption | undefined, excludeKeys: string[] = [], ): { locateParam: DetailedLocateParam | undefined; restParams: Record; } { const multimodalPrompt = extractMultimodalPrompt(opt); const locateParam = buildDetailedLocateParam(locatePrompt, opt); // Extract all keys from opt except the ones already included in locateParam const restParams: Record = {}; if (typeof opt === 'object' && opt !== null) { // Get all keys from opt const allKeys = Object.keys(opt); // `context` has already been merged into the locate prompt. const locateParamKeys = Object.keys(locateParam || {}); const multimodalPromptKeys = typeof locateParam?.prompt === 'object' && locateParam?.prompt !== null ? Object.keys(multimodalPrompt || {}) : []; // Extract all other keys for (const key of allKeys) { if ( !locateParamKeys.includes(key) && key !== 'context' && key !== 'deepThink' && !multimodalPromptKeys.includes(key) && !excludeKeys.includes(key) && key !== 'locate' ) { restParams[key] = opt[key as keyof LocateOption]; } } } return { locateParam, restParams, }; }