@midscene/core 1.7.4 → 1.7.5-beta-20260420031652.0

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.
Files changed (36) hide show
  1. package/dist/es/agent/ui-utils.mjs +13 -1
  2. package/dist/es/agent/ui-utils.mjs.map +1 -1
  3. package/dist/es/agent/utils.mjs +1 -1
  4. package/dist/es/ai-model/service-caller/index.mjs +94 -78
  5. package/dist/es/ai-model/service-caller/index.mjs.map +1 -1
  6. package/dist/es/ai-model/service-caller/request-timeout.mjs +49 -0
  7. package/dist/es/ai-model/service-caller/request-timeout.mjs.map +1 -0
  8. package/dist/es/common.mjs +6 -1
  9. package/dist/es/common.mjs.map +1 -1
  10. package/dist/es/dump/screenshot-store.mjs +7 -6
  11. package/dist/es/dump/screenshot-store.mjs.map +1 -1
  12. package/dist/es/report-generator.mjs +21 -20
  13. package/dist/es/report-generator.mjs.map +1 -1
  14. package/dist/es/utils.mjs +2 -2
  15. package/dist/es/yaml/player.mjs +1 -16
  16. package/dist/es/yaml/player.mjs.map +1 -1
  17. package/dist/lib/agent/ui-utils.js +13 -1
  18. package/dist/lib/agent/ui-utils.js.map +1 -1
  19. package/dist/lib/agent/utils.js +1 -1
  20. package/dist/lib/ai-model/service-caller/index.js +94 -78
  21. package/dist/lib/ai-model/service-caller/index.js.map +1 -1
  22. package/dist/lib/ai-model/service-caller/request-timeout.js +95 -0
  23. package/dist/lib/ai-model/service-caller/request-timeout.js.map +1 -0
  24. package/dist/lib/common.js +6 -1
  25. package/dist/lib/common.js.map +1 -1
  26. package/dist/lib/dump/screenshot-store.js +6 -5
  27. package/dist/lib/dump/screenshot-store.js.map +1 -1
  28. package/dist/lib/report-generator.js +19 -18
  29. package/dist/lib/report-generator.js.map +1 -1
  30. package/dist/lib/utils.js +2 -2
  31. package/dist/lib/yaml/player.js +1 -16
  32. package/dist/lib/yaml/player.js.map +1 -1
  33. package/dist/types/ai-model/service-caller/request-timeout.d.ts +32 -0
  34. package/dist/types/dump/screenshot-store.d.ts +2 -2
  35. package/dist/types/report-generator.d.ts +5 -0
  36. package/package.json +2 -2
@@ -261,22 +261,7 @@ class ScriptPlayer {
261
261
  const schemaIsStringParam = isStringParamSchema(matchedAction.paramSchema);
262
262
  let stringParamToCall;
263
263
  const specialActionParamToCall = 'string' == typeof actionParamForMatchedAction ? buildShortcutActionParam(matchedAction.name, matchedAction.interfaceAlias, actionParamForMatchedAction) : void 0;
264
- if ('string' == typeof actionParamForMatchedAction && ('Launch' === matchedAction.name || 'launch' === matchedAction.interfaceAlias) && 'function' == typeof agent.launch) {
265
- debug(`Calling agent.launch with: ${actionParamForMatchedAction}`);
266
- const result = await agent.launch(actionParamForMatchedAction);
267
- const resultName = flowItem.name;
268
- if (void 0 !== result) this.setResult(resultName, result);
269
- } else if ('string' == typeof actionParamForMatchedAction && ('Terminate' === matchedAction.name || 'terminate' === matchedAction.interfaceAlias) && 'function' == typeof agent.terminate) {
270
- debug(`Calling agent.terminate with: ${actionParamForMatchedAction}`);
271
- const result = await agent.terminate(actionParamForMatchedAction);
272
- const resultName = flowItem.name;
273
- if (void 0 !== result) this.setResult(resultName, result);
274
- } else if ('string' == typeof actionParamForMatchedAction && ('RunAdbShell' === matchedAction.name || 'runAdbShell' === matchedAction.interfaceAlias) && 'function' == typeof agent.runAdbShell) {
275
- debug(`Calling agent.runAdbShell with: ${actionParamForMatchedAction}`);
276
- const result = await agent.runAdbShell(actionParamForMatchedAction);
277
- const resultName = flowItem.name;
278
- if (void 0 !== result) this.setResult(resultName, result);
279
- } else if (specialActionParamToCall) {
264
+ if (specialActionParamToCall) {
280
265
  debug(`matchedAction: ${matchedAction.name}`, `flowParams: ${JSON.stringify(specialActionParamToCall)}`);
281
266
  const result = await agent.callActionInActionSpace(matchedAction.name, specialActionParamToCall);
282
267
  const resultName = flowItem.name;
@@ -1 +1 @@
1
- {"version":3,"file":"yaml/player.mjs","sources":["../../../src/yaml/player.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport { assert, ifInBrowser, ifInWorker } from '@midscene/shared/utils';\nimport { type ZodTypeAny, z } from 'zod';\n\n// previous defined yaml flow, as a helper\ninterface MidsceneYamlFlowItemAIInput extends LocateOption {\n // previous version\n // aiInput: string; // value to input\n // locate: TUserPrompt; // where to input\n aiInput: TUserPrompt | undefined; // where to input\n value: string | number; // value to input\n}\n\ninterface MidsceneYamlFlowItemAIKeyboardPress extends LocateOption {\n // previous version\n // aiKeyboardPress: string;\n // locate?: TUserPrompt; // where to press, optional\n aiKeyboardPress: TUserPrompt | undefined; // where to press\n keyName: string; // key to press\n}\n\ninterface MidsceneYamlFlowItemAIScroll extends LocateOption, ScrollParam {\n // previous version\n // aiScroll: null;\n // locate?: TUserPrompt; // which area to scroll, optional\n aiScroll: TUserPrompt | undefined; // which area to scroll\n}\n\nimport type { Agent } from '@/agent/agent';\nimport type { TUserPrompt } from '@/common';\nimport type {\n DeviceAction,\n FreeFn,\n LocateOption,\n MidsceneYamlFlowItemAIAction,\n MidsceneYamlFlowItemAIAssert,\n MidsceneYamlFlowItemAIWaitFor,\n MidsceneYamlFlowItemEvaluateJavaScript,\n MidsceneYamlFlowItemLogScreenshot,\n MidsceneYamlFlowItemSleep,\n MidsceneYamlScript,\n MidsceneYamlScriptEnv,\n ScriptPlayerStatusValue,\n ScriptPlayerTaskStatus,\n ScrollParam,\n} from '@/types';\nimport { getMidsceneRunSubDir } from '@midscene/shared/common';\nimport { getDebug } from '@midscene/shared/logger';\nimport {\n buildDetailedLocateParam,\n buildDetailedLocateParamAndRestParams,\n} from './utils';\n\nconst debug = getDebug('yaml-player');\nconst aiTaskHandlerMap = {\n aiQuery: 'aiQuery',\n aiNumber: 'aiNumber',\n aiString: 'aiString',\n aiBoolean: 'aiBoolean',\n aiAsk: 'aiAsk',\n aiLocate: 'aiLocate',\n} as const;\n\ntype AISimpleTaskKey = keyof typeof aiTaskHandlerMap;\n\nconst isStringParamSchema = (schema?: ZodTypeAny): boolean => {\n if (!schema) {\n return false;\n }\n\n const schemaDef = (schema as any)?._def;\n if (!schemaDef?.typeName) {\n return false;\n }\n\n switch (schemaDef.typeName) {\n case z.ZodFirstPartyTypeKind.ZodString:\n case z.ZodFirstPartyTypeKind.ZodEnum:\n case z.ZodFirstPartyTypeKind.ZodNativeEnum:\n return true;\n case z.ZodFirstPartyTypeKind.ZodLiteral:\n return typeof schemaDef.value === 'string';\n case z.ZodFirstPartyTypeKind.ZodOptional:\n case z.ZodFirstPartyTypeKind.ZodNullable:\n case z.ZodFirstPartyTypeKind.ZodDefault:\n return isStringParamSchema(schemaDef.innerType);\n case z.ZodFirstPartyTypeKind.ZodEffects:\n return isStringParamSchema(schemaDef.schema);\n case z.ZodFirstPartyTypeKind.ZodPipeline:\n return isStringParamSchema(schemaDef.out);\n case z.ZodFirstPartyTypeKind.ZodUnion: {\n const options = schemaDef.options as ZodTypeAny[] | undefined;\n return Array.isArray(options)\n ? options.every((option) => isStringParamSchema(option))\n : false;\n }\n default:\n return false;\n }\n};\n\nconst buildShortcutActionParam = (\n actionName: string,\n interfaceAlias: string | undefined,\n value: string,\n) => {\n if (actionName === 'Launch' || interfaceAlias === 'launch') {\n return { uri: value };\n }\n\n if (actionName === 'Terminate' || interfaceAlias === 'terminate') {\n return { uri: value };\n }\n\n if (actionName === 'RunAdbShell' || interfaceAlias === 'runAdbShell') {\n return { command: value };\n }\n\n return undefined;\n};\nexport class ScriptPlayer<T extends MidsceneYamlScriptEnv> {\n public currentTaskIndex?: number;\n public taskStatusList: ScriptPlayerTaskStatus[] = [];\n public status: ScriptPlayerStatusValue = 'init';\n public reportFile?: string | null;\n public result: Record<string, any>;\n private unnamedResultIndex = 0;\n public output?: string | null;\n public unstableLogContent?: string | null;\n public errorInSetup?: Error;\n private interfaceAgent: Agent | null = null;\n public agentStatusTip?: string;\n public target?: MidsceneYamlScriptEnv;\n private actionSpace: DeviceAction[] = [];\n private scriptPath?: string;\n constructor(\n private script: MidsceneYamlScript,\n private setupAgent: (platform: T) => Promise<{\n agent: Agent;\n freeFn: FreeFn[];\n }>,\n public onTaskStatusChange?: (taskStatus: ScriptPlayerTaskStatus) => void,\n scriptPath?: string,\n ) {\n this.scriptPath = scriptPath;\n this.result = {};\n const resolvedAiActContext =\n script.agent?.aiActContext ?? script.agent?.aiActionContext;\n\n if (resolvedAiActContext !== undefined && script.agent) {\n if (\n script.agent.aiActContext === undefined &&\n script.agent.aiActionContext !== undefined\n ) {\n console.warn(\n 'agent.aiActionContext is deprecated, please use agent.aiActContext instead. The legacy name is still accepted for backward compatibility.',\n );\n }\n\n script.agent.aiActContext = resolvedAiActContext;\n }\n\n this.target =\n script.target ||\n script.web ||\n script.android ||\n script.ios ||\n script.computer ||\n script.config;\n\n if (ifInBrowser || ifInWorker) {\n this.output = undefined;\n debug('output is undefined in browser or worker');\n } else if (this.target?.output) {\n this.output = resolve(process.cwd(), this.target.output);\n debug('setting output by config.output', this.output);\n } else {\n const scriptName = this.scriptPath\n ? basename(this.scriptPath, '.yaml').replace(/\\.(ya?ml)$/i, '')\n : 'script';\n this.output = join(\n getMidsceneRunSubDir('output'),\n `${scriptName}-${Date.now()}.json`,\n );\n debug('setting output by script path', this.output);\n }\n\n if (ifInBrowser || ifInWorker) {\n this.unstableLogContent = undefined;\n } else if (typeof this.target?.unstableLogContent === 'string') {\n this.unstableLogContent = resolve(\n process.cwd(),\n this.target.unstableLogContent,\n );\n } else if (this.target?.unstableLogContent === true) {\n this.unstableLogContent = join(\n getMidsceneRunSubDir('output'),\n 'unstableLogContent.json',\n );\n }\n\n this.taskStatusList = (script.tasks || []).map((task, taskIndex) => ({\n ...task,\n index: taskIndex,\n status: 'init',\n totalSteps: task.flow?.length || 0,\n }));\n }\n\n private setResult(key: string | undefined, value: any) {\n const keyToUse = key || this.unnamedResultIndex++;\n if (this.result[keyToUse]) {\n console.warn(`result key ${keyToUse} already exists, will overwrite`);\n }\n this.result[keyToUse] = value;\n\n return this.flushResult();\n }\n\n private setPlayerStatus(status: ScriptPlayerStatusValue, error?: Error) {\n this.status = status;\n this.errorInSetup = error;\n }\n\n private notifyCurrentTaskStatusChange(taskIndex?: number) {\n const taskIndexToNotify =\n typeof taskIndex === 'number' ? taskIndex : this.currentTaskIndex;\n\n if (typeof taskIndexToNotify !== 'number') {\n return;\n }\n\n const taskStatus = this.taskStatusList[taskIndexToNotify];\n if (this.onTaskStatusChange) {\n this.onTaskStatusChange(taskStatus);\n }\n }\n\n private async setTaskStatus(\n index: number,\n statusValue: ScriptPlayerStatusValue,\n error?: Error,\n ) {\n this.taskStatusList[index].status = statusValue;\n if (error) {\n this.taskStatusList[index].error = error;\n }\n\n this.notifyCurrentTaskStatusChange(index);\n }\n\n private setTaskIndex(taskIndex: number) {\n this.currentTaskIndex = taskIndex;\n }\n\n private flushResult() {\n if (this.output) {\n const output = resolve(process.cwd(), this.output);\n const outputDir = dirname(output);\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n writeFileSync(output, JSON.stringify(this.result || {}, undefined, 2));\n }\n }\n\n private flushUnstableLogContent() {\n if (this.unstableLogContent) {\n const content = this.interfaceAgent?._unstableLogContent();\n const filePath = resolve(process.cwd(), this.unstableLogContent);\n const outputDir = dirname(filePath);\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n writeFileSync(filePath, JSON.stringify(content, null, 2));\n }\n }\n\n async playTask(taskStatus: ScriptPlayerTaskStatus, agent: Agent) {\n const { flow } = taskStatus;\n assert(flow, 'missing flow in task');\n\n for (const flowItemIndex in flow) {\n const currentStep = Number.parseInt(flowItemIndex, 10);\n taskStatus.currentStep = currentStep;\n const flowItem = flow[flowItemIndex];\n\n // Skip Finalize action from cache - it's a planning-only marker\n if ('Finalize' in flowItem) {\n continue;\n }\n\n debug(\n `playing step ${flowItemIndex}, flowItem=${JSON.stringify(flowItem)}`,\n );\n const simpleAIKey = (\n Object.keys(aiTaskHandlerMap) as AISimpleTaskKey[]\n ).find((key) => Object.prototype.hasOwnProperty.call(flowItem, key));\n if (\n 'aiAct' in (flowItem as MidsceneYamlFlowItemAIAction) ||\n 'aiAction' in (flowItem as MidsceneYamlFlowItemAIAction) ||\n 'ai' in (flowItem as MidsceneYamlFlowItemAIAction)\n ) {\n const actionTask = flowItem as MidsceneYamlFlowItemAIAction;\n const { aiAct, aiAction, ai, ...actionOptions } = actionTask;\n const prompt = aiAct || aiAction || ai;\n assert(prompt, 'missing prompt for ai (aiAct)');\n await agent.aiAct(prompt, actionOptions);\n } else if ('aiAssert' in (flowItem as MidsceneYamlFlowItemAIAssert)) {\n const assertTask = flowItem as MidsceneYamlFlowItemAIAssert;\n const {\n aiAssert: prompt,\n errorMessage: msg,\n name,\n ...restOpts\n } = assertTask;\n assert(prompt, 'missing prompt for aiAssert');\n const { pass, thought, message } =\n (await agent.aiAssert(prompt, msg, {\n ...restOpts,\n keepRawResponse: true,\n })) || {};\n\n this.setResult(name, {\n pass,\n thought,\n message,\n });\n\n if (!pass) {\n throw new Error(message);\n }\n } else if (simpleAIKey) {\n const {\n [simpleAIKey]: prompt,\n name,\n ...options\n } = flowItem as Record<string, any>;\n assert(prompt, `missing prompt for ${simpleAIKey}`);\n const agentMethod = (agent as any)[aiTaskHandlerMap[simpleAIKey]];\n assert(\n typeof agentMethod === 'function',\n `missing agent method for ${simpleAIKey}`,\n );\n const aiResult = await agentMethod.call(agent, prompt, options);\n this.setResult(name, aiResult);\n } else if ('aiWaitFor' in (flowItem as MidsceneYamlFlowItemAIWaitFor)) {\n const waitForTask = flowItem as MidsceneYamlFlowItemAIWaitFor;\n const { aiWaitFor, timeout, ...restWaitForOpts } = waitForTask;\n const prompt = aiWaitFor;\n assert(prompt, 'missing prompt for aiWaitFor');\n const waitForOptions = {\n ...restWaitForOpts,\n ...(timeout !== undefined ? { timeout, timeoutMs: timeout } : {}),\n };\n await agent.aiWaitFor(prompt, waitForOptions);\n } else if ('sleep' in (flowItem as MidsceneYamlFlowItemSleep)) {\n const sleepTask = flowItem as MidsceneYamlFlowItemSleep;\n const ms = sleepTask.sleep;\n let msNumber = ms;\n if (typeof ms === 'string') {\n msNumber = Number.parseInt(ms, 10);\n }\n assert(\n msNumber && msNumber > 0,\n `ms for sleep must be greater than 0, but got ${ms}`,\n );\n await new Promise((resolve) => setTimeout(resolve, msNumber));\n } else if (\n 'javascript' in (flowItem as MidsceneYamlFlowItemEvaluateJavaScript)\n ) {\n const evaluateJavaScriptTask =\n flowItem as MidsceneYamlFlowItemEvaluateJavaScript;\n\n const result = await agent.evaluateJavaScript(\n evaluateJavaScriptTask.javascript,\n );\n this.setResult(evaluateJavaScriptTask.name, result);\n } else if (\n 'logScreenshot' in (flowItem as MidsceneYamlFlowItemLogScreenshot) ||\n 'recordToReport' in (flowItem as MidsceneYamlFlowItemLogScreenshot)\n ) {\n const recordTask = flowItem as MidsceneYamlFlowItemLogScreenshot;\n const title =\n recordTask.recordToReport ?? recordTask.logScreenshot ?? 'untitled';\n const content = recordTask.content || '';\n await agent.recordToReport(title, { content });\n } else if ('aiInput' in (flowItem as MidsceneYamlFlowItemAIInput)) {\n // may be input empty string ''\n const {\n aiInput,\n value: rawValue,\n ...inputTask\n } = flowItem as MidsceneYamlFlowItemAIInput;\n\n // Compatibility with previous version:\n // Old format: { aiInput: string (value), locate: TUserPrompt }\n // New format - 1: { aiInput: TUserPrompt, value: string | number }\n // New format - 2: { aiInput: undefined, locate: TUserPrompt, value: string | number }\n let locatePrompt: TUserPrompt | undefined;\n let value: string | number | undefined;\n if ((inputTask as any).locate) {\n // Old format - aiInput is the value, locate is the prompt\n // Keep backward compatibility: empty string is treated as no value\n value = (aiInput as string | number) || rawValue;\n locatePrompt = (inputTask as any).locate;\n } else {\n // New format - aiInput is the prompt, value is the value\n locatePrompt = aiInput || '';\n value = rawValue;\n }\n\n // Convert value to string for Input action\n await agent.callActionInActionSpace('Input', {\n ...inputTask,\n ...(value !== undefined ? { value: String(value) } : {}),\n ...(locatePrompt\n ? { locate: buildDetailedLocateParam(locatePrompt, inputTask) }\n : {}),\n });\n } else if (\n 'aiKeyboardPress' in (flowItem as MidsceneYamlFlowItemAIKeyboardPress)\n ) {\n const { aiKeyboardPress, ...keyboardPressTask } =\n flowItem as MidsceneYamlFlowItemAIKeyboardPress;\n\n // Compatibility with previous version:\n // Old format: { aiKeyboardPress: string (key), locate?: TUserPrompt }\n // New format - 1: { aiKeyboardPress: TUserPrompt, keyName: string }\n // New format - 2: { aiKeyboardPress: , locate?: TUserPrompt, keyName: string }\n let locatePrompt: TUserPrompt | undefined;\n let keyName: string | undefined;\n if ((keyboardPressTask as any).locate) {\n // Old format - aiKeyboardPress is the key, locate is the prompt\n keyName = aiKeyboardPress as string;\n locatePrompt = (keyboardPressTask as any).locate;\n } else if (keyboardPressTask.keyName) {\n // New format - aiKeyboardPress is the prompt, key is the key\n keyName = keyboardPressTask.keyName;\n locatePrompt = aiKeyboardPress;\n } else {\n keyName = aiKeyboardPress as string;\n }\n\n await agent.callActionInActionSpace('KeyboardPress', {\n ...keyboardPressTask,\n ...(keyName ? { keyName } : {}),\n ...(locatePrompt\n ? {\n locate: buildDetailedLocateParam(\n locatePrompt,\n keyboardPressTask,\n ),\n }\n : {}),\n });\n } else if ('aiScroll' in (flowItem as MidsceneYamlFlowItemAIScroll)) {\n const { aiScroll, ...scrollTask } =\n flowItem as MidsceneYamlFlowItemAIScroll;\n\n // Compatibility with previous version:\n // Old format: { aiScroll: null, locate?: TUserPrompt, direction, scrollType, distance? }\n // New format - 1: { aiScroll: TUserPrompt, direction, scrollType, distance? }\n // New format - 2: { aiScroll: undefined, locate: TUserPrompt, direction, scrollType, distance? }\n const { locate, ...scrollOptions } = scrollTask as any;\n const locatePrompt: TUserPrompt | undefined = locate ?? aiScroll;\n\n await agent.aiScroll(locatePrompt, scrollOptions);\n } else if ('aiTap' in flowItem) {\n const { aiTap, prompt, locate, ...tapOptions } = flowItem as any;\n\n let locatePrompt: TUserPrompt;\n let opts = tapOptions;\n // Support both formats:\n // 1. { aiTap: null, locate: { prompt, images, ... } } (locate as sibling key)\n // 2. { aiTap: { locate: { prompt, images, ... } } } (locate nested in aiTap)\n const locateObj =\n locate ??\n (typeof aiTap === 'object' && aiTap !== null\n ? aiTap.locate\n : undefined);\n\n if (typeof aiTap === 'string' && aiTap) {\n // User YAML: aiTap: 'search input box'\n locatePrompt = aiTap;\n } else if (typeof locateObj === 'object' && locateObj?.prompt) {\n // buildYamlFlowFromPlans: { aiTap: '', locate: { prompt, deepLocate, cacheable } }\n const { prompt: lp, ...locateOpts } = locateObj;\n locatePrompt = lp;\n opts = { ...locateOpts, ...tapOptions };\n } else {\n // User YAML: aiTap: { prompt: '...' } or aiTap: null + prompt: '...'\n locatePrompt = aiTap?.prompt || prompt || locateObj;\n }\n\n assert(locatePrompt, 'missing prompt for aiTap');\n await agent.aiTap(locatePrompt, opts);\n } else {\n // generic action, find the action in actionSpace\n\n /* for aiRightClick, the parameters are a flattened data for the 'locate', these are all valid data\n\n - aiRightClick: 'search input box'\n - aiRightClick: 'search input box'\n deepLocate: true\n cacheable: false\n - aiRightClick:\n prompt: 'search input box'\n - aiRightClick:\n prompt: 'search input box'\n deepLocate: true\n cacheable: false\n */\n\n const actionSpace = this.actionSpace;\n let locatePromptShortcut: string | undefined;\n let actionParamForMatchedAction: unknown;\n const matchedAction = actionSpace.find((action) => {\n const actionInterfaceAlias = action.interfaceAlias;\n if (\n actionInterfaceAlias &&\n Object.prototype.hasOwnProperty.call(flowItem, actionInterfaceAlias)\n ) {\n actionParamForMatchedAction =\n flowItem[actionInterfaceAlias as keyof typeof flowItem];\n if (typeof actionParamForMatchedAction === 'string') {\n locatePromptShortcut = actionParamForMatchedAction;\n }\n return true;\n }\n\n const keyOfActionInActionSpace = action.name;\n if (\n Object.prototype.hasOwnProperty.call(\n flowItem,\n keyOfActionInActionSpace,\n )\n ) {\n actionParamForMatchedAction =\n flowItem[keyOfActionInActionSpace as keyof typeof flowItem];\n if (typeof actionParamForMatchedAction === 'string') {\n locatePromptShortcut = actionParamForMatchedAction;\n }\n return true;\n }\n\n return false;\n });\n\n assert(\n matchedAction,\n `unknown flowItem in yaml: ${JSON.stringify(flowItem)}`,\n );\n\n const schemaIsStringParam = isStringParamSchema(\n matchedAction.paramSchema,\n );\n let stringParamToCall: string | undefined;\n const specialActionParamToCall =\n typeof actionParamForMatchedAction === 'string'\n ? buildShortcutActionParam(\n matchedAction.name,\n matchedAction.interfaceAlias,\n actionParamForMatchedAction,\n )\n : undefined;\n if (\n typeof actionParamForMatchedAction === 'string' &&\n (matchedAction.name === 'Launch' ||\n matchedAction.interfaceAlias === 'launch') &&\n typeof (agent as any).launch === 'function'\n ) {\n // Call agent.launch directly for Launch action with string param\n debug(`Calling agent.launch with: ${actionParamForMatchedAction}`);\n const result = await (agent as any).launch(\n actionParamForMatchedAction,\n );\n\n const resultName = (flowItem as any).name;\n if (result !== undefined) {\n this.setResult(resultName, result);\n }\n } else if (\n typeof actionParamForMatchedAction === 'string' &&\n (matchedAction.name === 'Terminate' ||\n matchedAction.interfaceAlias === 'terminate') &&\n typeof (agent as any).terminate === 'function'\n ) {\n // Call agent.terminate directly for Terminate action with string param\n debug(`Calling agent.terminate with: ${actionParamForMatchedAction}`);\n const result = await (agent as any).terminate(\n actionParamForMatchedAction,\n );\n\n const resultName = (flowItem as any).name;\n if (result !== undefined) {\n this.setResult(resultName, result);\n }\n } else if (\n typeof actionParamForMatchedAction === 'string' &&\n (matchedAction.name === 'RunAdbShell' ||\n matchedAction.interfaceAlias === 'runAdbShell') &&\n typeof (agent as any).runAdbShell === 'function'\n ) {\n // Call agent.runAdbShell directly for RunAdbShell action with string param\n debug(\n `Calling agent.runAdbShell with: ${actionParamForMatchedAction}`,\n );\n const result = await (agent as any).runAdbShell(\n actionParamForMatchedAction,\n );\n\n const resultName = (flowItem as any).name;\n if (result !== undefined) {\n this.setResult(resultName, result);\n }\n } else if (specialActionParamToCall) {\n debug(\n `matchedAction: ${matchedAction.name}`,\n `flowParams: ${JSON.stringify(specialActionParamToCall)}`,\n );\n const result = await agent.callActionInActionSpace(\n matchedAction.name,\n specialActionParamToCall,\n );\n\n const resultName = (flowItem as any).name;\n if (result !== undefined) {\n this.setResult(resultName, result);\n }\n } else if (\n typeof actionParamForMatchedAction === 'string' &&\n schemaIsStringParam\n ) {\n if (matchedAction.paramSchema) {\n const parseResult = matchedAction.paramSchema.safeParse(\n actionParamForMatchedAction,\n );\n if (parseResult.success && typeof parseResult.data === 'string') {\n stringParamToCall = parseResult.data;\n } else if (!parseResult.success) {\n debug(\n `parse failed for action ${matchedAction.name} with string param`,\n parseResult.error,\n );\n stringParamToCall = actionParamForMatchedAction;\n }\n } else {\n stringParamToCall = actionParamForMatchedAction;\n }\n\n if (stringParamToCall !== undefined) {\n debug(\n `matchedAction: ${matchedAction.name}`,\n `flowParams: ${JSON.stringify(stringParamToCall)}`,\n );\n const result = await agent.callActionInActionSpace(\n matchedAction.name,\n stringParamToCall,\n );\n\n // Store result if there's a name property in flowItem\n const resultName = (flowItem as any).name;\n if (result !== undefined) {\n this.setResult(resultName, result);\n }\n }\n } else {\n // Determine the source for parameter extraction:\n // - If we have a locatePromptShortcut, use the flowItem (for actions like aiTap with prompt)\n // - Otherwise, use actionParamForMatchedAction (for actions like runWdaRequest with structured params)\n const sourceForParams =\n locatePromptShortcut &&\n typeof actionParamForMatchedAction === 'string'\n ? { ...flowItem, prompt: locatePromptShortcut }\n : typeof actionParamForMatchedAction === 'object' &&\n actionParamForMatchedAction !== null\n ? actionParamForMatchedAction\n : flowItem;\n\n const { locateParam, restParams } =\n buildDetailedLocateParamAndRestParams(\n locatePromptShortcut || '',\n sourceForParams as LocateOption,\n [\n matchedAction.name,\n matchedAction.interfaceAlias || '_never_mind_',\n ],\n );\n\n const flowParams = {\n ...restParams,\n locate: locateParam,\n };\n\n debug(\n `matchedAction: ${matchedAction.name}`,\n `flowParams: ${JSON.stringify(flowParams, null, 2)}`,\n );\n const result = await agent.callActionInActionSpace(\n matchedAction.name,\n flowParams,\n );\n\n // Store result if there's a name property in flowItem\n const resultName = (flowItem as any).name;\n if (result !== undefined) {\n this.setResult(resultName, result);\n }\n }\n }\n }\n this.reportFile = agent.reportFile;\n await this.flushUnstableLogContent();\n }\n\n async run() {\n const { target, web, android, ios, computer, tasks } = this.script;\n const webEnv = web || target;\n const androidEnv = android;\n const iosEnv = ios;\n const computerEnv = computer;\n const platform = webEnv || androidEnv || iosEnv || computerEnv;\n\n this.setPlayerStatus('running');\n\n let agent: Agent | null = null;\n let freeFn: FreeFn[] = [];\n try {\n const { agent: newAgent, freeFn: newFreeFn } = await this.setupAgent(\n platform as T,\n );\n this.actionSpace = await newAgent.getActionSpace();\n agent = newAgent;\n const originalOnTaskStartTip = agent.onTaskStartTip;\n agent.onTaskStartTip = (tip) => {\n if (this.status === 'running') {\n this.agentStatusTip = tip;\n }\n originalOnTaskStartTip?.(tip);\n };\n freeFn = [\n ...(newFreeFn || []),\n {\n name: 'restore-agent-onTaskStartTip',\n fn: () => {\n if (agent) {\n agent.onTaskStartTip = originalOnTaskStartTip;\n }\n },\n },\n ];\n } catch (e) {\n this.setPlayerStatus('error', e as Error);\n return;\n }\n this.interfaceAgent = agent;\n\n let taskIndex = 0;\n this.setPlayerStatus('running');\n let errorFlag = false;\n while (taskIndex < tasks.length) {\n const taskStatus = this.taskStatusList[taskIndex];\n this.setTaskStatus(taskIndex, 'running' as any);\n this.setTaskIndex(taskIndex);\n\n try {\n await this.playTask(taskStatus, this.interfaceAgent);\n this.setTaskStatus(taskIndex, 'done' as any);\n } catch (e) {\n this.setTaskStatus(taskIndex, 'error' as any, e as Error);\n\n if (taskStatus.continueOnError) {\n // nothing more to do\n } else {\n this.reportFile = agent.reportFile;\n errorFlag = true;\n break;\n }\n }\n this.reportFile = agent?.reportFile;\n taskIndex++;\n }\n\n if (errorFlag) {\n this.setPlayerStatus('error');\n } else {\n this.setPlayerStatus('done');\n }\n this.agentStatusTip = '';\n\n // free the resources\n for (const fn of freeFn) {\n try {\n // console.log('freeing', fn.name);\n await fn.fn();\n // console.log('freed', fn.name);\n } catch (e) {\n // console.error('error freeing', fn.name, e);\n }\n }\n }\n}\n"],"names":["debug","getDebug","aiTaskHandlerMap","isStringParamSchema","schema","schemaDef","z","options","Array","option","buildShortcutActionParam","actionName","interfaceAlias","value","ScriptPlayer","key","keyToUse","console","status","error","taskIndex","taskIndexToNotify","taskStatus","index","statusValue","output","resolve","process","outputDir","dirname","existsSync","mkdirSync","writeFileSync","JSON","undefined","content","filePath","agent","flow","assert","flowItemIndex","currentStep","Number","flowItem","simpleAIKey","Object","actionTask","aiAct","aiAction","ai","actionOptions","prompt","assertTask","msg","name","restOpts","pass","thought","message","Error","agentMethod","aiResult","waitForTask","aiWaitFor","timeout","restWaitForOpts","waitForOptions","sleepTask","ms","msNumber","Promise","setTimeout","evaluateJavaScriptTask","result","recordTask","title","aiInput","rawValue","inputTask","locatePrompt","String","buildDetailedLocateParam","aiKeyboardPress","keyboardPressTask","keyName","aiScroll","scrollTask","locate","scrollOptions","aiTap","tapOptions","opts","locateObj","lp","locateOpts","actionSpace","locatePromptShortcut","actionParamForMatchedAction","matchedAction","action","actionInterfaceAlias","keyOfActionInActionSpace","schemaIsStringParam","stringParamToCall","specialActionParamToCall","resultName","parseResult","sourceForParams","locateParam","restParams","buildDetailedLocateParamAndRestParams","flowParams","target","web","android","ios","computer","tasks","webEnv","androidEnv","iosEnv","computerEnv","platform","freeFn","newAgent","newFreeFn","originalOnTaskStartTip","tip","e","errorFlag","fn","script","setupAgent","onTaskStatusChange","scriptPath","resolvedAiActContext","ifInBrowser","ifInWorker","scriptName","basename","join","getMidsceneRunSubDir","Date","task"],"mappings":";;;;;;;;;;;;;;;;;AAsDA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,mBAAmB;IACvB,SAAS;IACT,UAAU;IACV,UAAU;IACV,WAAW;IACX,OAAO;IACP,UAAU;AACZ;AAIA,MAAMC,sBAAsB,CAACC;IAC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H,YAAe;gBACnE,GAAG2H,IAAI;gBACP,OAAO3H;gBACP,QAAQ;gBACR,YAAY2H,KAAK,IAAI,EAAE,UAAU;YACnC;IACF;AAmlBF"}
1
+ {"version":3,"file":"yaml/player.mjs","sources":["../../../src/yaml/player.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport { assert, ifInBrowser, ifInWorker } from '@midscene/shared/utils';\nimport { type ZodTypeAny, z } from 'zod';\n\n// previous defined yaml flow, as a helper\ninterface MidsceneYamlFlowItemAIInput extends LocateOption {\n // previous version\n // aiInput: string; // value to input\n // locate: TUserPrompt; // where to input\n aiInput: TUserPrompt | undefined; // where to input\n value: string | number; // value to input\n}\n\ninterface MidsceneYamlFlowItemAIKeyboardPress extends LocateOption {\n // previous version\n // aiKeyboardPress: string;\n // locate?: TUserPrompt; // where to press, optional\n aiKeyboardPress: TUserPrompt | undefined; // where to press\n keyName: string; // key to press\n}\n\ninterface MidsceneYamlFlowItemAIScroll extends LocateOption, ScrollParam {\n // previous version\n // aiScroll: null;\n // locate?: TUserPrompt; // which area to scroll, optional\n aiScroll: TUserPrompt | undefined; // which area to scroll\n}\n\nimport type { Agent } from '@/agent/agent';\nimport type { TUserPrompt } from '@/common';\nimport type {\n DeviceAction,\n FreeFn,\n LocateOption,\n MidsceneYamlFlowItemAIAction,\n MidsceneYamlFlowItemAIAssert,\n MidsceneYamlFlowItemAIWaitFor,\n MidsceneYamlFlowItemEvaluateJavaScript,\n MidsceneYamlFlowItemLogScreenshot,\n MidsceneYamlFlowItemSleep,\n MidsceneYamlScript,\n MidsceneYamlScriptEnv,\n ScriptPlayerStatusValue,\n ScriptPlayerTaskStatus,\n ScrollParam,\n} from '@/types';\nimport { getMidsceneRunSubDir } from '@midscene/shared/common';\nimport { getDebug } from '@midscene/shared/logger';\nimport {\n buildDetailedLocateParam,\n buildDetailedLocateParamAndRestParams,\n} from './utils';\n\nconst debug = getDebug('yaml-player');\nconst aiTaskHandlerMap = {\n aiQuery: 'aiQuery',\n aiNumber: 'aiNumber',\n aiString: 'aiString',\n aiBoolean: 'aiBoolean',\n aiAsk: 'aiAsk',\n aiLocate: 'aiLocate',\n} as const;\n\ntype AISimpleTaskKey = keyof typeof aiTaskHandlerMap;\n\nconst isStringParamSchema = (schema?: ZodTypeAny): boolean => {\n if (!schema) {\n return false;\n }\n\n const schemaDef = (schema as any)?._def;\n if (!schemaDef?.typeName) {\n return false;\n }\n\n switch (schemaDef.typeName) {\n case z.ZodFirstPartyTypeKind.ZodString:\n case z.ZodFirstPartyTypeKind.ZodEnum:\n case z.ZodFirstPartyTypeKind.ZodNativeEnum:\n return true;\n case z.ZodFirstPartyTypeKind.ZodLiteral:\n return typeof schemaDef.value === 'string';\n case z.ZodFirstPartyTypeKind.ZodOptional:\n case z.ZodFirstPartyTypeKind.ZodNullable:\n case z.ZodFirstPartyTypeKind.ZodDefault:\n return isStringParamSchema(schemaDef.innerType);\n case z.ZodFirstPartyTypeKind.ZodEffects:\n return isStringParamSchema(schemaDef.schema);\n case z.ZodFirstPartyTypeKind.ZodPipeline:\n return isStringParamSchema(schemaDef.out);\n case z.ZodFirstPartyTypeKind.ZodUnion: {\n const options = schemaDef.options as ZodTypeAny[] | undefined;\n return Array.isArray(options)\n ? options.every((option) => isStringParamSchema(option))\n : false;\n }\n default:\n return false;\n }\n};\n\nconst buildShortcutActionParam = (\n actionName: string,\n interfaceAlias: string | undefined,\n value: string,\n) => {\n if (actionName === 'Launch' || interfaceAlias === 'launch') {\n return { uri: value };\n }\n\n if (actionName === 'Terminate' || interfaceAlias === 'terminate') {\n return { uri: value };\n }\n\n if (actionName === 'RunAdbShell' || interfaceAlias === 'runAdbShell') {\n return { command: value };\n }\n\n return undefined;\n};\nexport class ScriptPlayer<T extends MidsceneYamlScriptEnv> {\n public currentTaskIndex?: number;\n public taskStatusList: ScriptPlayerTaskStatus[] = [];\n public status: ScriptPlayerStatusValue = 'init';\n public reportFile?: string | null;\n public result: Record<string, any>;\n private unnamedResultIndex = 0;\n public output?: string | null;\n public unstableLogContent?: string | null;\n public errorInSetup?: Error;\n private interfaceAgent: Agent | null = null;\n public agentStatusTip?: string;\n public target?: MidsceneYamlScriptEnv;\n private actionSpace: DeviceAction[] = [];\n private scriptPath?: string;\n constructor(\n private script: MidsceneYamlScript,\n private setupAgent: (platform: T) => Promise<{\n agent: Agent;\n freeFn: FreeFn[];\n }>,\n public onTaskStatusChange?: (taskStatus: ScriptPlayerTaskStatus) => void,\n scriptPath?: string,\n ) {\n this.scriptPath = scriptPath;\n this.result = {};\n const resolvedAiActContext =\n script.agent?.aiActContext ?? script.agent?.aiActionContext;\n\n if (resolvedAiActContext !== undefined && script.agent) {\n if (\n script.agent.aiActContext === undefined &&\n script.agent.aiActionContext !== undefined\n ) {\n console.warn(\n 'agent.aiActionContext is deprecated, please use agent.aiActContext instead. The legacy name is still accepted for backward compatibility.',\n );\n }\n\n script.agent.aiActContext = resolvedAiActContext;\n }\n\n this.target =\n script.target ||\n script.web ||\n script.android ||\n script.ios ||\n script.computer ||\n script.config;\n\n if (ifInBrowser || ifInWorker) {\n this.output = undefined;\n debug('output is undefined in browser or worker');\n } else if (this.target?.output) {\n this.output = resolve(process.cwd(), this.target.output);\n debug('setting output by config.output', this.output);\n } else {\n const scriptName = this.scriptPath\n ? basename(this.scriptPath, '.yaml').replace(/\\.(ya?ml)$/i, '')\n : 'script';\n this.output = join(\n getMidsceneRunSubDir('output'),\n `${scriptName}-${Date.now()}.json`,\n );\n debug('setting output by script path', this.output);\n }\n\n if (ifInBrowser || ifInWorker) {\n this.unstableLogContent = undefined;\n } else if (typeof this.target?.unstableLogContent === 'string') {\n this.unstableLogContent = resolve(\n process.cwd(),\n this.target.unstableLogContent,\n );\n } else if (this.target?.unstableLogContent === true) {\n this.unstableLogContent = join(\n getMidsceneRunSubDir('output'),\n 'unstableLogContent.json',\n );\n }\n\n this.taskStatusList = (script.tasks || []).map((task, taskIndex) => ({\n ...task,\n index: taskIndex,\n status: 'init',\n totalSteps: task.flow?.length || 0,\n }));\n }\n\n private setResult(key: string | undefined, value: any) {\n const keyToUse = key || this.unnamedResultIndex++;\n if (this.result[keyToUse]) {\n console.warn(`result key ${keyToUse} already exists, will overwrite`);\n }\n this.result[keyToUse] = value;\n\n return this.flushResult();\n }\n\n private setPlayerStatus(status: ScriptPlayerStatusValue, error?: Error) {\n this.status = status;\n this.errorInSetup = error;\n }\n\n private notifyCurrentTaskStatusChange(taskIndex?: number) {\n const taskIndexToNotify =\n typeof taskIndex === 'number' ? taskIndex : this.currentTaskIndex;\n\n if (typeof taskIndexToNotify !== 'number') {\n return;\n }\n\n const taskStatus = this.taskStatusList[taskIndexToNotify];\n if (this.onTaskStatusChange) {\n this.onTaskStatusChange(taskStatus);\n }\n }\n\n private async setTaskStatus(\n index: number,\n statusValue: ScriptPlayerStatusValue,\n error?: Error,\n ) {\n this.taskStatusList[index].status = statusValue;\n if (error) {\n this.taskStatusList[index].error = error;\n }\n\n this.notifyCurrentTaskStatusChange(index);\n }\n\n private setTaskIndex(taskIndex: number) {\n this.currentTaskIndex = taskIndex;\n }\n\n private flushResult() {\n if (this.output) {\n const output = resolve(process.cwd(), this.output);\n const outputDir = dirname(output);\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n writeFileSync(output, JSON.stringify(this.result || {}, undefined, 2));\n }\n }\n\n private flushUnstableLogContent() {\n if (this.unstableLogContent) {\n const content = this.interfaceAgent?._unstableLogContent();\n const filePath = resolve(process.cwd(), this.unstableLogContent);\n const outputDir = dirname(filePath);\n if (!existsSync(outputDir)) {\n mkdirSync(outputDir, { recursive: true });\n }\n writeFileSync(filePath, JSON.stringify(content, null, 2));\n }\n }\n\n async playTask(taskStatus: ScriptPlayerTaskStatus, agent: Agent) {\n const { flow } = taskStatus;\n assert(flow, 'missing flow in task');\n\n for (const flowItemIndex in flow) {\n const currentStep = Number.parseInt(flowItemIndex, 10);\n taskStatus.currentStep = currentStep;\n const flowItem = flow[flowItemIndex];\n\n // Skip Finalize action from cache - it's a planning-only marker\n if ('Finalize' in flowItem) {\n continue;\n }\n\n debug(\n `playing step ${flowItemIndex}, flowItem=${JSON.stringify(flowItem)}`,\n );\n const simpleAIKey = (\n Object.keys(aiTaskHandlerMap) as AISimpleTaskKey[]\n ).find((key) => Object.prototype.hasOwnProperty.call(flowItem, key));\n if (\n 'aiAct' in (flowItem as MidsceneYamlFlowItemAIAction) ||\n 'aiAction' in (flowItem as MidsceneYamlFlowItemAIAction) ||\n 'ai' in (flowItem as MidsceneYamlFlowItemAIAction)\n ) {\n const actionTask = flowItem as MidsceneYamlFlowItemAIAction;\n const { aiAct, aiAction, ai, ...actionOptions } = actionTask;\n const prompt = aiAct || aiAction || ai;\n assert(prompt, 'missing prompt for ai (aiAct)');\n await agent.aiAct(prompt, actionOptions);\n } else if ('aiAssert' in (flowItem as MidsceneYamlFlowItemAIAssert)) {\n const assertTask = flowItem as MidsceneYamlFlowItemAIAssert;\n const {\n aiAssert: prompt,\n errorMessage: msg,\n name,\n ...restOpts\n } = assertTask;\n assert(prompt, 'missing prompt for aiAssert');\n const { pass, thought, message } =\n (await agent.aiAssert(prompt, msg, {\n ...restOpts,\n keepRawResponse: true,\n })) || {};\n\n this.setResult(name, {\n pass,\n thought,\n message,\n });\n\n if (!pass) {\n throw new Error(message);\n }\n } else if (simpleAIKey) {\n const {\n [simpleAIKey]: prompt,\n name,\n ...options\n } = flowItem as Record<string, any>;\n assert(prompt, `missing prompt for ${simpleAIKey}`);\n const agentMethod = (agent as any)[aiTaskHandlerMap[simpleAIKey]];\n assert(\n typeof agentMethod === 'function',\n `missing agent method for ${simpleAIKey}`,\n );\n const aiResult = await agentMethod.call(agent, prompt, options);\n this.setResult(name, aiResult);\n } else if ('aiWaitFor' in (flowItem as MidsceneYamlFlowItemAIWaitFor)) {\n const waitForTask = flowItem as MidsceneYamlFlowItemAIWaitFor;\n const { aiWaitFor, timeout, ...restWaitForOpts } = waitForTask;\n const prompt = aiWaitFor;\n assert(prompt, 'missing prompt for aiWaitFor');\n const waitForOptions = {\n ...restWaitForOpts,\n ...(timeout !== undefined ? { timeout, timeoutMs: timeout } : {}),\n };\n await agent.aiWaitFor(prompt, waitForOptions);\n } else if ('sleep' in (flowItem as MidsceneYamlFlowItemSleep)) {\n const sleepTask = flowItem as MidsceneYamlFlowItemSleep;\n const ms = sleepTask.sleep;\n let msNumber = ms;\n if (typeof ms === 'string') {\n msNumber = Number.parseInt(ms, 10);\n }\n assert(\n msNumber && msNumber > 0,\n `ms for sleep must be greater than 0, but got ${ms}`,\n );\n await new Promise((resolve) => setTimeout(resolve, msNumber));\n } else if (\n 'javascript' in (flowItem as MidsceneYamlFlowItemEvaluateJavaScript)\n ) {\n const evaluateJavaScriptTask =\n flowItem as MidsceneYamlFlowItemEvaluateJavaScript;\n\n const result = await agent.evaluateJavaScript(\n evaluateJavaScriptTask.javascript,\n );\n this.setResult(evaluateJavaScriptTask.name, result);\n } else if (\n 'logScreenshot' in (flowItem as MidsceneYamlFlowItemLogScreenshot) ||\n 'recordToReport' in (flowItem as MidsceneYamlFlowItemLogScreenshot)\n ) {\n const recordTask = flowItem as MidsceneYamlFlowItemLogScreenshot;\n const title =\n recordTask.recordToReport ?? recordTask.logScreenshot ?? 'untitled';\n const content = recordTask.content || '';\n await agent.recordToReport(title, { content });\n } else if ('aiInput' in (flowItem as MidsceneYamlFlowItemAIInput)) {\n // may be input empty string ''\n const {\n aiInput,\n value: rawValue,\n ...inputTask\n } = flowItem as MidsceneYamlFlowItemAIInput;\n\n // Compatibility with previous version:\n // Old format: { aiInput: string (value), locate: TUserPrompt }\n // New format - 1: { aiInput: TUserPrompt, value: string | number }\n // New format - 2: { aiInput: undefined, locate: TUserPrompt, value: string | number }\n let locatePrompt: TUserPrompt | undefined;\n let value: string | number | undefined;\n if ((inputTask as any).locate) {\n // Old format - aiInput is the value, locate is the prompt\n // Keep backward compatibility: empty string is treated as no value\n value = (aiInput as string | number) || rawValue;\n locatePrompt = (inputTask as any).locate;\n } else {\n // New format - aiInput is the prompt, value is the value\n locatePrompt = aiInput || '';\n value = rawValue;\n }\n\n // Convert value to string for Input action\n await agent.callActionInActionSpace('Input', {\n ...inputTask,\n ...(value !== undefined ? { value: String(value) } : {}),\n ...(locatePrompt\n ? { locate: buildDetailedLocateParam(locatePrompt, inputTask) }\n : {}),\n });\n } else if (\n 'aiKeyboardPress' in (flowItem as MidsceneYamlFlowItemAIKeyboardPress)\n ) {\n const { aiKeyboardPress, ...keyboardPressTask } =\n flowItem as MidsceneYamlFlowItemAIKeyboardPress;\n\n // Compatibility with previous version:\n // Old format: { aiKeyboardPress: string (key), locate?: TUserPrompt }\n // New format - 1: { aiKeyboardPress: TUserPrompt, keyName: string }\n // New format - 2: { aiKeyboardPress: , locate?: TUserPrompt, keyName: string }\n let locatePrompt: TUserPrompt | undefined;\n let keyName: string | undefined;\n if ((keyboardPressTask as any).locate) {\n // Old format - aiKeyboardPress is the key, locate is the prompt\n keyName = aiKeyboardPress as string;\n locatePrompt = (keyboardPressTask as any).locate;\n } else if (keyboardPressTask.keyName) {\n // New format - aiKeyboardPress is the prompt, key is the key\n keyName = keyboardPressTask.keyName;\n locatePrompt = aiKeyboardPress;\n } else {\n keyName = aiKeyboardPress as string;\n }\n\n await agent.callActionInActionSpace('KeyboardPress', {\n ...keyboardPressTask,\n ...(keyName ? { keyName } : {}),\n ...(locatePrompt\n ? {\n locate: buildDetailedLocateParam(\n locatePrompt,\n keyboardPressTask,\n ),\n }\n : {}),\n });\n } else if ('aiScroll' in (flowItem as MidsceneYamlFlowItemAIScroll)) {\n const { aiScroll, ...scrollTask } =\n flowItem as MidsceneYamlFlowItemAIScroll;\n\n // Compatibility with previous version:\n // Old format: { aiScroll: null, locate?: TUserPrompt, direction, scrollType, distance? }\n // New format - 1: { aiScroll: TUserPrompt, direction, scrollType, distance? }\n // New format - 2: { aiScroll: undefined, locate: TUserPrompt, direction, scrollType, distance? }\n const { locate, ...scrollOptions } = scrollTask as any;\n const locatePrompt: TUserPrompt | undefined = locate ?? aiScroll;\n\n await agent.aiScroll(locatePrompt, scrollOptions);\n } else if ('aiTap' in flowItem) {\n const { aiTap, prompt, locate, ...tapOptions } = flowItem as any;\n\n let locatePrompt: TUserPrompt;\n let opts = tapOptions;\n // Support both formats:\n // 1. { aiTap: null, locate: { prompt, images, ... } } (locate as sibling key)\n // 2. { aiTap: { locate: { prompt, images, ... } } } (locate nested in aiTap)\n const locateObj =\n locate ??\n (typeof aiTap === 'object' && aiTap !== null\n ? aiTap.locate\n : undefined);\n\n if (typeof aiTap === 'string' && aiTap) {\n // User YAML: aiTap: 'search input box'\n locatePrompt = aiTap;\n } else if (typeof locateObj === 'object' && locateObj?.prompt) {\n // buildYamlFlowFromPlans: { aiTap: '', locate: { prompt, deepLocate, cacheable } }\n const { prompt: lp, ...locateOpts } = locateObj;\n locatePrompt = lp;\n opts = { ...locateOpts, ...tapOptions };\n } else {\n // User YAML: aiTap: { prompt: '...' } or aiTap: null + prompt: '...'\n locatePrompt = aiTap?.prompt || prompt || locateObj;\n }\n\n assert(locatePrompt, 'missing prompt for aiTap');\n await agent.aiTap(locatePrompt, opts);\n } else {\n // generic action, find the action in actionSpace\n\n /* for aiRightClick, the parameters are a flattened data for the 'locate', these are all valid data\n\n - aiRightClick: 'search input box'\n - aiRightClick: 'search input box'\n deepLocate: true\n cacheable: false\n - aiRightClick:\n prompt: 'search input box'\n - aiRightClick:\n prompt: 'search input box'\n deepLocate: true\n cacheable: false\n */\n\n const actionSpace = this.actionSpace;\n let locatePromptShortcut: string | undefined;\n let actionParamForMatchedAction: unknown;\n const matchedAction = actionSpace.find((action) => {\n const actionInterfaceAlias = action.interfaceAlias;\n if (\n actionInterfaceAlias &&\n Object.prototype.hasOwnProperty.call(flowItem, actionInterfaceAlias)\n ) {\n actionParamForMatchedAction =\n flowItem[actionInterfaceAlias as keyof typeof flowItem];\n if (typeof actionParamForMatchedAction === 'string') {\n locatePromptShortcut = actionParamForMatchedAction;\n }\n return true;\n }\n\n const keyOfActionInActionSpace = action.name;\n if (\n Object.prototype.hasOwnProperty.call(\n flowItem,\n keyOfActionInActionSpace,\n )\n ) {\n actionParamForMatchedAction =\n flowItem[keyOfActionInActionSpace as keyof typeof flowItem];\n if (typeof actionParamForMatchedAction === 'string') {\n locatePromptShortcut = actionParamForMatchedAction;\n }\n return true;\n }\n\n return false;\n });\n\n assert(\n matchedAction,\n `unknown flowItem in yaml: ${JSON.stringify(flowItem)}`,\n );\n\n const schemaIsStringParam = isStringParamSchema(\n matchedAction.paramSchema,\n );\n let stringParamToCall: string | undefined;\n const specialActionParamToCall =\n typeof actionParamForMatchedAction === 'string'\n ? buildShortcutActionParam(\n matchedAction.name,\n matchedAction.interfaceAlias,\n actionParamForMatchedAction,\n )\n : undefined;\n if (specialActionParamToCall) {\n debug(\n `matchedAction: ${matchedAction.name}`,\n `flowParams: ${JSON.stringify(specialActionParamToCall)}`,\n );\n const result = await agent.callActionInActionSpace(\n matchedAction.name,\n specialActionParamToCall,\n );\n\n const resultName = (flowItem as any).name;\n if (result !== undefined) {\n this.setResult(resultName, result);\n }\n } else if (\n typeof actionParamForMatchedAction === 'string' &&\n schemaIsStringParam\n ) {\n if (matchedAction.paramSchema) {\n const parseResult = matchedAction.paramSchema.safeParse(\n actionParamForMatchedAction,\n );\n if (parseResult.success && typeof parseResult.data === 'string') {\n stringParamToCall = parseResult.data;\n } else if (!parseResult.success) {\n debug(\n `parse failed for action ${matchedAction.name} with string param`,\n parseResult.error,\n );\n stringParamToCall = actionParamForMatchedAction;\n }\n } else {\n stringParamToCall = actionParamForMatchedAction;\n }\n\n if (stringParamToCall !== undefined) {\n debug(\n `matchedAction: ${matchedAction.name}`,\n `flowParams: ${JSON.stringify(stringParamToCall)}`,\n );\n const result = await agent.callActionInActionSpace(\n matchedAction.name,\n stringParamToCall,\n );\n\n // Store result if there's a name property in flowItem\n const resultName = (flowItem as any).name;\n if (result !== undefined) {\n this.setResult(resultName, result);\n }\n }\n } else {\n // Determine the source for parameter extraction:\n // - If we have a locatePromptShortcut, use the flowItem (for actions like aiTap with prompt)\n // - Otherwise, use actionParamForMatchedAction (for actions like runWdaRequest with structured params)\n const sourceForParams =\n locatePromptShortcut &&\n typeof actionParamForMatchedAction === 'string'\n ? { ...flowItem, prompt: locatePromptShortcut }\n : typeof actionParamForMatchedAction === 'object' &&\n actionParamForMatchedAction !== null\n ? actionParamForMatchedAction\n : flowItem;\n\n const { locateParam, restParams } =\n buildDetailedLocateParamAndRestParams(\n locatePromptShortcut || '',\n sourceForParams as LocateOption,\n [\n matchedAction.name,\n matchedAction.interfaceAlias || '_never_mind_',\n ],\n );\n\n const flowParams = {\n ...restParams,\n locate: locateParam,\n };\n\n debug(\n `matchedAction: ${matchedAction.name}`,\n `flowParams: ${JSON.stringify(flowParams, null, 2)}`,\n );\n const result = await agent.callActionInActionSpace(\n matchedAction.name,\n flowParams,\n );\n\n // Store result if there's a name property in flowItem\n const resultName = (flowItem as any).name;\n if (result !== undefined) {\n this.setResult(resultName, result);\n }\n }\n }\n }\n this.reportFile = agent.reportFile;\n await this.flushUnstableLogContent();\n }\n\n async run() {\n const { target, web, android, ios, computer, tasks } = this.script;\n const webEnv = web || target;\n const androidEnv = android;\n const iosEnv = ios;\n const computerEnv = computer;\n const platform = webEnv || androidEnv || iosEnv || computerEnv;\n\n this.setPlayerStatus('running');\n\n let agent: Agent | null = null;\n let freeFn: FreeFn[] = [];\n try {\n const { agent: newAgent, freeFn: newFreeFn } = await this.setupAgent(\n platform as T,\n );\n this.actionSpace = await newAgent.getActionSpace();\n agent = newAgent;\n const originalOnTaskStartTip = agent.onTaskStartTip;\n agent.onTaskStartTip = (tip) => {\n if (this.status === 'running') {\n this.agentStatusTip = tip;\n }\n originalOnTaskStartTip?.(tip);\n };\n freeFn = [\n ...(newFreeFn || []),\n {\n name: 'restore-agent-onTaskStartTip',\n fn: () => {\n if (agent) {\n agent.onTaskStartTip = originalOnTaskStartTip;\n }\n },\n },\n ];\n } catch (e) {\n this.setPlayerStatus('error', e as Error);\n return;\n }\n this.interfaceAgent = agent;\n\n let taskIndex = 0;\n this.setPlayerStatus('running');\n let errorFlag = false;\n while (taskIndex < tasks.length) {\n const taskStatus = this.taskStatusList[taskIndex];\n this.setTaskStatus(taskIndex, 'running' as any);\n this.setTaskIndex(taskIndex);\n\n try {\n await this.playTask(taskStatus, this.interfaceAgent);\n this.setTaskStatus(taskIndex, 'done' as any);\n } catch (e) {\n this.setTaskStatus(taskIndex, 'error' as any, e as Error);\n\n if (taskStatus.continueOnError) {\n // nothing more to do\n } else {\n this.reportFile = agent.reportFile;\n errorFlag = true;\n break;\n }\n }\n this.reportFile = agent?.reportFile;\n taskIndex++;\n }\n\n if (errorFlag) {\n this.setPlayerStatus('error');\n } else {\n this.setPlayerStatus('done');\n }\n this.agentStatusTip = '';\n\n // free the resources\n for (const fn of freeFn) {\n try {\n // console.log('freeing', fn.name);\n await fn.fn();\n // console.log('freed', fn.name);\n } catch (e) {\n // console.error('error freeing', fn.name, e);\n }\n }\n }\n}\n"],"names":["debug","getDebug","aiTaskHandlerMap","isStringParamSchema","schema","schemaDef","z","options","Array","option","buildShortcutActionParam","actionName","interfaceAlias","value","ScriptPlayer","key","keyToUse","console","status","error","taskIndex","taskIndexToNotify","taskStatus","index","statusValue","output","resolve","process","outputDir","dirname","existsSync","mkdirSync","writeFileSync","JSON","undefined","content","filePath","agent","flow","assert","flowItemIndex","currentStep","Number","flowItem","simpleAIKey","Object","actionTask","aiAct","aiAction","ai","actionOptions","prompt","assertTask","msg","name","restOpts","pass","thought","message","Error","agentMethod","aiResult","waitForTask","aiWaitFor","timeout","restWaitForOpts","waitForOptions","sleepTask","ms","msNumber","Promise","setTimeout","evaluateJavaScriptTask","result","recordTask","title","aiInput","rawValue","inputTask","locatePrompt","String","buildDetailedLocateParam","aiKeyboardPress","keyboardPressTask","keyName","aiScroll","scrollTask","locate","scrollOptions","aiTap","tapOptions","opts","locateObj","lp","locateOpts","actionSpace","locatePromptShortcut","actionParamForMatchedAction","matchedAction","action","actionInterfaceAlias","keyOfActionInActionSpace","schemaIsStringParam","stringParamToCall","specialActionParamToCall","resultName","parseResult","sourceForParams","locateParam","restParams","buildDetailedLocateParamAndRestParams","flowParams","target","web","android","ios","computer","tasks","webEnv","androidEnv","iosEnv","computerEnv","platform","freeFn","newAgent","newFreeFn","originalOnTaskStartTip","tip","e","errorFlag","fn","script","setupAgent","onTaskStatusChange","scriptPath","resolvedAiActContext","ifInBrowser","ifInWorker","scriptName","basename","join","getMidsceneRunSubDir","Date","task"],"mappings":";;;;;;;;;;;;;;;;;AAsDA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,mBAAmB;IACvB,SAAS;IACT,UAAU;IACV,UAAU;IACV,WAAW;IACX,OAAO;IACP,UAAU;AACZ;AAIA,MAAMC,sBAAsB,CAACC;IAC3B,IAAI,CAACA,QACH,OAAO;IAGT,MAAMC,YAAaD,QAAgB;IACnC,IAAI,CAACC,WAAW,UACd,OAAO;IAGT,OAAQA,UAAU,QAAQ;QACxB,KAAKC,EAAE,qBAAqB,CAAC,SAAS;QACtC,KAAKA,EAAE,qBAAqB,CAAC,OAAO;QACpC,KAAKA,EAAE,qBAAqB,CAAC,aAAa;YACxC,OAAO;QACT,KAAKA,EAAE,qBAAqB,CAAC,UAAU;YACrC,OAAO,AAA2B,YAA3B,OAAOD,UAAU,KAAK;QAC/B,KAAKC,EAAE,qBAAqB,CAAC,WAAW;QACxC,KAAKA,EAAE,qBAAqB,CAAC,WAAW;QACxC,KAAKA,EAAE,qBAAqB,CAAC,UAAU;YACrC,OAAOH,oBAAoBE,UAAU,SAAS;QAChD,KAAKC,EAAE,qBAAqB,CAAC,UAAU;YACrC,OAAOH,oBAAoBE,UAAU,MAAM;QAC7C,KAAKC,EAAE,qBAAqB,CAAC,WAAW;YACtC,OAAOH,oBAAoBE,UAAU,GAAG;QAC1C,KAAKC,EAAE,qBAAqB,CAAC,QAAQ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AAU,GAC9BC,SAAS,IAAI,CAAC,UAAU,EAAE,SAAS,OAAO,CAAC,eAAe,MAC1D;YACJ,IAAI,CAAC,MAAM,GAAGC,KACZC,qBAAqB,WACrB,GAAGH,WAAW,CAAC,EAAEI,KAAK,GAAG,GAAG,KAAK,CAAC;YAEpC9I,MAAM,iCAAiC,IAAI,CAAC,MAAM;QACpD;QAEA,IAAIwI,eAAeC,YACjB,IAAI,CAAC,kBAAkB,GAAGvG;aACrB,IAAI,AAA2C,YAA3C,OAAO,IAAI,CAAC,MAAM,EAAE,oBAC7B,IAAI,CAAC,kBAAkB,GAAGR,2BACxBC,QAAQ,GAAG,IACX,IAAI,CAAC,MAAM,CAAC,kBAAkB;aAE3B,IAAI,IAAI,CAAC,MAAM,EAAE,uBAAuB,MAC7C,IAAI,CAAC,kBAAkB,GAAGiH,KACxBC,qBAAqB,WACrB;QAIJ,IAAI,CAAC,cAAc,GAAIV,AAAAA,CAAAA,OAAO,KAAK,IAAI,EAAC,EAAG,GAAG,CAAC,CAACY,MAAM3H,YAAe;gBACnE,GAAG2H,IAAI;gBACP,OAAO3H;gBACP,QAAQ;gBACR,YAAY2H,KAAK,IAAI,EAAE,UAAU;YACnC;IACF;AAiiBF"}
@@ -116,7 +116,19 @@ function paramStr(task) {
116
116
  if ('object' == typeof value) {
117
117
  const locateStr = locateParamStr(value);
118
118
  if (locateStr) return locateStr;
119
- return JSON.stringify(value, void 0, 2);
119
+ const entries = Object.entries(value);
120
+ if (0 === entries.length) return '';
121
+ const formatValue = (v)=>{
122
+ if ('string' == typeof v) return v;
123
+ if (null == v) return String(v);
124
+ if ('object' == typeof v) return JSON.stringify(v);
125
+ return String(v);
126
+ };
127
+ if (1 === entries.length) {
128
+ const [key, v] = entries[0];
129
+ return `${key}: ${formatValue(v)}`;
130
+ }
131
+ return entries.map(([key, v])=>`${key}: ${formatValue(v)}`).join(', ');
120
132
  }
121
133
  return String(value);
122
134
  }
@@ -1 +1 @@
1
- {"version":3,"file":"agent/ui-utils.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/agent/ui-utils.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type {\n DetailedLocateParam,\n ExecutionTask,\n ExecutionTaskAction,\n ExecutionTaskInsightAssertion,\n ExecutionTaskInsightQuery,\n ExecutionTaskPlanning,\n ExecutionTaskPlanningLocate,\n PullParam,\n ScrollParam,\n} from '@/types';\n\nexport function typeStr(task: ExecutionTask) {\n // // For Action tasks with subType, show \"Action Space / subType\"\n // if (task.type === 'Action' && task.subType) {\n // return `Action Space / ${task.subType}`;\n // }\n\n // // For all other cases with subType, show \"type / subType\"\n // if (task.subType) {\n // return `${task.type} / ${task.subType}`;\n // }\n\n // No subType, just show type\n return task.subType || task.type;\n}\n\nexport function locateParamStr(locate?: DetailedLocateParam | string): string {\n if (!locate) {\n return '';\n }\n\n if (typeof locate === 'string') {\n return locate;\n }\n\n if (typeof locate === 'object') {\n // Check for nested prompt.prompt (Planning Locate tasks)\n if (\n typeof locate.prompt === 'object' &&\n locate.prompt !== null &&\n locate.prompt.prompt\n ) {\n const prompt = locate.prompt.prompt;\n return prompt;\n }\n\n // Check for direct prompt string\n if (typeof locate.prompt === 'string') {\n return locate.prompt;\n }\n\n // Check for description field (Action Space tasks like Tap, Hover)\n if (typeof (locate as any).description === 'string') {\n return (locate as any).description;\n }\n }\n\n return '';\n}\n\nexport function scrollParamStr(scrollParam?: ScrollParam) {\n if (!scrollParam) {\n return '';\n }\n return `${scrollParam.direction || 'down'}, ${scrollParam.scrollType || 'singleAction'}, ${scrollParam.distance || 'distance-not-set'}`;\n}\n\nexport function pullParamStr(pullParam?: PullParam) {\n if (!pullParam) {\n return '';\n }\n const parts: string[] = [];\n parts.push(`direction: ${pullParam.direction || 'down'}`);\n if (pullParam.distance) {\n parts.push(`distance: ${pullParam.distance}`);\n }\n if (pullParam.duration) {\n parts.push(`duration: ${pullParam.duration}ms`);\n }\n return parts.join(', ');\n}\n\nexport function extractInsightParam(taskParam: any): {\n content: string;\n images?: Array<{ name: string; url: string }>;\n} {\n if (!taskParam) {\n return { content: '' };\n }\n\n // Helper to extract images from multimodalPrompt\n const extractImages = (source: any) => {\n return source?.multimodalPrompt?.images &&\n Array.isArray(source.multimodalPrompt.images)\n ? source.multimodalPrompt.images\n : undefined;\n };\n\n // Helper to stringify if needed\n const toContent = (value: any) =>\n typeof value === 'string' ? value : JSON.stringify(value);\n\n // Extract from demand\n if (taskParam.demand) {\n return {\n content: toContent(taskParam.demand),\n images: extractImages(taskParam),\n };\n }\n\n // Extract from assertion\n if (taskParam.assertion) {\n return {\n content: toContent(taskParam.assertion),\n images: extractImages(taskParam),\n };\n }\n\n // Extract from dataDemand\n if (taskParam.dataDemand) {\n const { dataDemand } = taskParam;\n\n if (typeof dataDemand === 'string') {\n return { content: dataDemand };\n }\n\n if (typeof dataDemand === 'object') {\n return {\n content: toContent(dataDemand.demand || dataDemand),\n images: extractImages(dataDemand),\n };\n }\n }\n\n return { content: '' };\n}\n\nexport function taskTitleStr(\n type:\n | 'Tap'\n | 'Hover'\n | 'Input'\n | 'RightClick'\n | 'KeyboardPress'\n | 'Scroll'\n | 'Act'\n | 'Query'\n | 'Assert'\n | 'WaitFor'\n | 'Locate'\n | 'Boolean'\n | 'Number'\n | 'String',\n prompt: string,\n) {\n if (prompt) {\n return `${type} - ${prompt}`;\n }\n return type;\n}\n\nexport function paramStr(task: ExecutionTask) {\n let value: string | undefined | object;\n if (task.type === 'Planning') {\n if (task.subType === 'Locate') {\n value = locateParamStr((task as ExecutionTaskPlanningLocate)?.param);\n } else {\n // Prefer AI-generated output.log over user input\n const planTask = task as ExecutionTaskPlanning;\n value = planTask.output?.log || planTask.param?.userInstruction;\n }\n }\n\n if (task.type === 'Insight') {\n value = extractInsightParam((task as any)?.param).content;\n }\n\n if (task.type === 'Action Space') {\n const locate = (task as ExecutionTaskAction)?.param?.locate;\n const locateStr = locate ? locateParamStr(locate) : '';\n\n value = task.thought || '';\n if (typeof (task as ExecutionTaskAction)?.param?.timeMs === 'number') {\n value = `${(task as ExecutionTaskAction)?.param?.timeMs}ms`;\n } else if (\n typeof (task as ExecutionTaskAction)?.param?.scrollType === 'string'\n ) {\n value = scrollParamStr((task as ExecutionTaskAction)?.param);\n } else if (\n typeof (task as ExecutionTaskAction)?.param?.direction === 'string' &&\n (task as ExecutionTaskAction)?.subType === 'PullGesture'\n ) {\n value = pullParamStr((task as ExecutionTaskAction)?.param);\n } else if (\n typeof (task as ExecutionTaskAction)?.param?.value !== 'undefined'\n ) {\n value = (task as ExecutionTaskAction)?.param?.value;\n } else if (\n (task as ExecutionTaskAction)?.param &&\n typeof (task as ExecutionTaskAction)?.param === 'object' &&\n Object.keys((task as ExecutionTaskAction)?.param || {}).length > 0\n ) {\n // General parameter handling for actions with custom parameters\n // (e.g., runWdaRequest, runAdbShell)\n value = (task as ExecutionTaskAction)?.param;\n }\n\n if (locateStr) {\n if (value && typeof value !== 'object') {\n value = `${locateStr} - ${value}`;\n } else {\n value = locateStr;\n }\n }\n }\n\n if (typeof value === 'undefined') return '';\n\n if (typeof value === 'string') return value;\n\n if (typeof value === 'object') {\n const locateStr = locateParamStr(value as any);\n if (locateStr) {\n return locateStr;\n }\n return JSON.stringify(value, undefined, 2);\n }\n\n return String(value);\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","typeStr","task","locateParamStr","locate","prompt","scrollParamStr","scrollParam","pullParamStr","pullParam","parts","extractInsightParam","taskParam","extractImages","source","Array","undefined","toContent","value","JSON","dataDemand","taskTitleStr","type","paramStr","planTask","locateStr","String"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;ACMO,SAASI,QAAQC,IAAmB;IAYzC,OAAOA,KAAK,OAAO,IAAIA,KAAK,IAAI;AAClC;AAEO,SAASC,eAAeC,MAAqC;IAClE,IAAI,CAACA,QACH,OAAO;IAGT,IAAI,AAAkB,YAAlB,OAAOA,QACT,OAAOA;IAGT,IAAI,AAAkB,YAAlB,OAAOA,QAAqB;QAE9B,IACE,AAAyB,YAAzB,OAAOA,OAAO,MAAM,IACpBA,AAAkB,SAAlBA,OAAO,MAAM,IACbA,OAAO,MAAM,CAAC,MAAM,EACpB;YACA,MAAMC,SAASD,OAAO,MAAM,CAAC,MAAM;YACnC,OAAOC;QACT;QAGA,IAAI,AAAyB,YAAzB,OAAOD,OAAO,MAAM,EACtB,OAAOA,OAAO,MAAM;QAItB,IAAI,AAAuC,YAAvC,OAAQA,OAAe,WAAW,EACpC,OAAQA,OAAe,WAAW;IAEtC;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QAGzC,IAAIuB,WAEAP,QADEA,SAAS,AAAiB,YAAjB,OAAOA,QACV,GAAGO,UAAU,GAAG,EAAEP,OAAO,GAEzBO;IAGd;IAEA,IAAI,AAAiB,WAAVP,OAAuB,OAAO;IAEzC,IAAI,AAAiB,YAAjB,OAAOA,OAAoB,OAAOA;IAEtC,IAAI,AAAiB,YAAjB,OAAOA,OAAoB;QAC7B,MAAMO,YAAYtB,eAAee;QACjC,IAAIO,WACF,OAAOA;QAET,OAAON,KAAK,SAAS,CAACD,OAAOF,QAAW;IAC1C;IAEA,OAAOU,OAAOR;AAChB"}
1
+ {"version":3,"file":"agent/ui-utils.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/agent/ui-utils.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type {\n DetailedLocateParam,\n ExecutionTask,\n ExecutionTaskAction,\n ExecutionTaskInsightAssertion,\n ExecutionTaskInsightQuery,\n ExecutionTaskPlanning,\n ExecutionTaskPlanningLocate,\n PullParam,\n ScrollParam,\n} from '@/types';\n\nexport function typeStr(task: ExecutionTask) {\n // // For Action tasks with subType, show \"Action Space / subType\"\n // if (task.type === 'Action' && task.subType) {\n // return `Action Space / ${task.subType}`;\n // }\n\n // // For all other cases with subType, show \"type / subType\"\n // if (task.subType) {\n // return `${task.type} / ${task.subType}`;\n // }\n\n // No subType, just show type\n return task.subType || task.type;\n}\n\nexport function locateParamStr(locate?: DetailedLocateParam | string): string {\n if (!locate) {\n return '';\n }\n\n if (typeof locate === 'string') {\n return locate;\n }\n\n if (typeof locate === 'object') {\n // Check for nested prompt.prompt (Planning Locate tasks)\n if (\n typeof locate.prompt === 'object' &&\n locate.prompt !== null &&\n locate.prompt.prompt\n ) {\n const prompt = locate.prompt.prompt;\n return prompt;\n }\n\n // Check for direct prompt string\n if (typeof locate.prompt === 'string') {\n return locate.prompt;\n }\n\n // Check for description field (Action Space tasks like Tap, Hover)\n if (typeof (locate as any).description === 'string') {\n return (locate as any).description;\n }\n }\n\n return '';\n}\n\nexport function scrollParamStr(scrollParam?: ScrollParam) {\n if (!scrollParam) {\n return '';\n }\n return `${scrollParam.direction || 'down'}, ${scrollParam.scrollType || 'singleAction'}, ${scrollParam.distance || 'distance-not-set'}`;\n}\n\nexport function pullParamStr(pullParam?: PullParam) {\n if (!pullParam) {\n return '';\n }\n const parts: string[] = [];\n parts.push(`direction: ${pullParam.direction || 'down'}`);\n if (pullParam.distance) {\n parts.push(`distance: ${pullParam.distance}`);\n }\n if (pullParam.duration) {\n parts.push(`duration: ${pullParam.duration}ms`);\n }\n return parts.join(', ');\n}\n\nexport function extractInsightParam(taskParam: any): {\n content: string;\n images?: Array<{ name: string; url: string }>;\n} {\n if (!taskParam) {\n return { content: '' };\n }\n\n // Helper to extract images from multimodalPrompt\n const extractImages = (source: any) => {\n return source?.multimodalPrompt?.images &&\n Array.isArray(source.multimodalPrompt.images)\n ? source.multimodalPrompt.images\n : undefined;\n };\n\n // Helper to stringify if needed\n const toContent = (value: any) =>\n typeof value === 'string' ? value : JSON.stringify(value);\n\n // Extract from demand\n if (taskParam.demand) {\n return {\n content: toContent(taskParam.demand),\n images: extractImages(taskParam),\n };\n }\n\n // Extract from assertion\n if (taskParam.assertion) {\n return {\n content: toContent(taskParam.assertion),\n images: extractImages(taskParam),\n };\n }\n\n // Extract from dataDemand\n if (taskParam.dataDemand) {\n const { dataDemand } = taskParam;\n\n if (typeof dataDemand === 'string') {\n return { content: dataDemand };\n }\n\n if (typeof dataDemand === 'object') {\n return {\n content: toContent(dataDemand.demand || dataDemand),\n images: extractImages(dataDemand),\n };\n }\n }\n\n return { content: '' };\n}\n\nexport function taskTitleStr(\n type:\n | 'Tap'\n | 'Hover'\n | 'Input'\n | 'RightClick'\n | 'KeyboardPress'\n | 'Scroll'\n | 'Act'\n | 'Query'\n | 'Assert'\n | 'WaitFor'\n | 'Locate'\n | 'Boolean'\n | 'Number'\n | 'String',\n prompt: string,\n) {\n if (prompt) {\n return `${type} - ${prompt}`;\n }\n return type;\n}\n\nexport function paramStr(task: ExecutionTask) {\n let value: string | undefined | object;\n if (task.type === 'Planning') {\n if (task.subType === 'Locate') {\n value = locateParamStr((task as ExecutionTaskPlanningLocate)?.param);\n } else {\n // Prefer AI-generated output.log over user input\n const planTask = task as ExecutionTaskPlanning;\n value = planTask.output?.log || planTask.param?.userInstruction;\n }\n }\n\n if (task.type === 'Insight') {\n value = extractInsightParam((task as any)?.param).content;\n }\n\n if (task.type === 'Action Space') {\n const locate = (task as ExecutionTaskAction)?.param?.locate;\n const locateStr = locate ? locateParamStr(locate) : '';\n\n value = task.thought || '';\n if (typeof (task as ExecutionTaskAction)?.param?.timeMs === 'number') {\n value = `${(task as ExecutionTaskAction)?.param?.timeMs}ms`;\n } else if (\n typeof (task as ExecutionTaskAction)?.param?.scrollType === 'string'\n ) {\n value = scrollParamStr((task as ExecutionTaskAction)?.param);\n } else if (\n typeof (task as ExecutionTaskAction)?.param?.direction === 'string' &&\n (task as ExecutionTaskAction)?.subType === 'PullGesture'\n ) {\n value = pullParamStr((task as ExecutionTaskAction)?.param);\n } else if (\n typeof (task as ExecutionTaskAction)?.param?.value !== 'undefined'\n ) {\n value = (task as ExecutionTaskAction)?.param?.value;\n } else if (\n (task as ExecutionTaskAction)?.param &&\n typeof (task as ExecutionTaskAction)?.param === 'object' &&\n Object.keys((task as ExecutionTaskAction)?.param || {}).length > 0\n ) {\n // General parameter handling for actions with custom parameters\n // (e.g., runWdaRequest, runAdbShell)\n value = (task as ExecutionTaskAction)?.param;\n }\n\n if (locateStr) {\n if (value && typeof value !== 'object') {\n value = `${locateStr} - ${value}`;\n } else {\n value = locateStr;\n }\n }\n }\n\n if (typeof value === 'undefined') return '';\n\n if (typeof value === 'string') return value;\n\n if (typeof value === 'object') {\n const locateStr = locateParamStr(value as any);\n if (locateStr) {\n return locateStr;\n }\n // Flatten `{key: \"raw value\"}` into `key: raw value` instead of emitting\n // a pretty-printed JSON string. JSON.stringify would escape every inner\n // quote as `\\\"`, and the UI renders the result as plain text — so a\n // command like `grep -E \"version\"` ends up shown with the literal\n // backslashes, which is both noisy and confusing for users.\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length === 0) {\n return '';\n }\n const formatValue = (v: unknown): string => {\n if (typeof v === 'string') return v;\n if (v === null || v === undefined) return String(v);\n if (typeof v === 'object') return JSON.stringify(v);\n return String(v);\n };\n if (entries.length === 1) {\n const [key, v] = entries[0];\n return `${key}: ${formatValue(v)}`;\n }\n return entries.map(([key, v]) => `${key}: ${formatValue(v)}`).join(', ');\n }\n\n return String(value);\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","typeStr","task","locateParamStr","locate","prompt","scrollParamStr","scrollParam","pullParamStr","pullParam","parts","extractInsightParam","taskParam","extractImages","source","Array","undefined","toContent","value","JSON","dataDemand","taskTitleStr","type","paramStr","planTask","locateStr","entries","formatValue","v","String"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,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I,AAAa,YAAb,OAAOA,GAAgB,OAAOA;YAClC,IAAIA,QAAAA,GAA+B,OAAOC,OAAOD;YACjD,IAAI,AAAa,YAAb,OAAOA,GAAgB,OAAOT,KAAK,SAAS,CAACS;YACjD,OAAOC,OAAOD;QAChB;QACA,IAAIF,AAAmB,MAAnBA,QAAQ,MAAM,EAAQ;YACxB,MAAM,CAAC9B,KAAKgC,EAAE,GAAGF,OAAO,CAAC,EAAE;YAC3B,OAAO,GAAG9B,IAAI,EAAE,EAAE+B,YAAYC,IAAI;QACpC;QACA,OAAOF,QAAQ,GAAG,CAAC,CAAC,CAAC9B,KAAKgC,EAAE,GAAK,GAAGhC,IAAI,EAAE,EAAE+B,YAAYC,IAAI,EAAE,IAAI,CAAC;IACrE;IAEA,OAAOC,OAAOX;AAChB"}
@@ -170,7 +170,7 @@ async function matchElementFromCache(context, cacheEntry, cachePrompt, cacheable
170
170
  return;
171
171
  }
172
172
  }
173
- const getMidsceneVersion = ()=>"1.7.4";
173
+ const getMidsceneVersion = ()=>"1.7.5-beta-20260420031652.0";
174
174
  const parsePrompt = (prompt)=>{
175
175
  if ('string' == typeof prompt) return {
176
176
  textPrompt: prompt,
@@ -51,6 +51,7 @@ var external_openai_default = /*#__PURE__*/ __webpack_require__.n(external_opena
51
51
  const util_js_namespaceObject = require("../auto-glm/util.js");
52
52
  const external_codex_app_server_js_namespaceObject = require("./codex-app-server.js");
53
53
  const external_image_detail_js_namespaceObject = require("./image-detail.js");
54
+ const external_request_timeout_js_namespaceObject = require("./request-timeout.js");
54
55
  function _define_property(obj, key, value) {
55
56
  if (key in obj) Object.defineProperty(obj, key, {
56
57
  value: value,
@@ -132,6 +133,9 @@ async function createChatClient({ modelConfig }) {
132
133
  throw new Error(`Invalid SOCKS proxy URL: ${socksProxy}. Expected format: socks4://host:port, socks5://host:port, or with authentication: socks5://user:pass@host:port`);
133
134
  }
134
135
  }
136
+ const effectiveTimeoutMs = (0, external_request_timeout_js_namespaceObject.resolveEffectiveTimeoutMs)({
137
+ timeout
138
+ });
135
139
  const openAIOptions = {
136
140
  baseURL: openaiBaseURL,
137
141
  apiKey: openaiApiKey,
@@ -141,8 +145,9 @@ async function createChatClient({ modelConfig }) {
141
145
  }
142
146
  } : {},
143
147
  ...openaiExtraConfig,
144
- ...'number' == typeof timeout ? {
145
- timeout
148
+ maxRetries: 0,
149
+ ...null !== effectiveTimeoutMs ? {
150
+ timeout: effectiveTimeoutMs
146
151
  } : {},
147
152
  dangerouslyAllowBrowser: true
148
153
  };
@@ -179,6 +184,7 @@ async function callAI(messages, modelConfig, options) {
179
184
  const { completion, modelName, modelDescription, uiTarsModelVersion, modelFamily } = await createChatClient({
180
185
  modelConfig
181
186
  });
187
+ const effectiveTimeoutMs = (0, external_request_timeout_js_namespaceObject.resolveEffectiveTimeoutMs)(modelConfig);
182
188
  const extraBody = modelConfig.extraBody;
183
189
  const maxTokens = env_namespaceObject.globalConfigManager.getEnvConfigValueAsNumber(env_namespaceObject.MIDSCENE_MODEL_MAX_TOKENS) ?? env_namespaceObject.globalConfigManager.getEnvConfigValueAsNumber(env_namespaceObject.OPENAI_MAX_TOKENS);
184
190
  const debugCall = (0, logger_namespaceObject.getDebug)('ai:call');
@@ -265,55 +271,58 @@ async function callAI(messages, modelConfig, options) {
265
271
  try {
266
272
  debugCall(`sending ${isStreaming ? 'streaming ' : ''}request to ${modelName}`);
267
273
  if (isStreaming) {
268
- const stream = await completion.create({
269
- model: modelName,
270
- messages: messagesWithImageDetail,
271
- ...commonConfig,
272
- ...reasoningEffortConfig,
273
- ...extraBody
274
- }, {
275
- stream: true,
276
- ...options?.abortSignal ? {
277
- signal: options.abortSignal
278
- } : {}
279
- });
280
- requestId = stream._request_id;
281
- for await (const chunk of stream){
282
- const content = chunk.choices?.[0]?.delta?.content || '';
283
- const reasoning_content = chunk.choices?.[0]?.delta?.reasoning_content || '';
284
- if (chunk.usage) usage = chunk.usage;
285
- if (content || reasoning_content) {
286
- accumulated += content;
287
- accumulatedReasoning += reasoning_content;
288
- const chunkData = {
289
- content,
290
- reasoning_content,
291
- accumulated,
292
- isComplete: false,
293
- usage: void 0
294
- };
295
- options.onChunk(chunkData);
296
- }
297
- if (chunk.choices?.[0]?.finish_reason) {
298
- timeCost = Date.now() - startTime;
299
- if (!usage) {
300
- const estimatedTokens = Math.max(1, Math.floor(accumulated.length / 4));
301
- usage = {
302
- prompt_tokens: estimatedTokens,
303
- completion_tokens: estimatedTokens,
304
- total_tokens: 2 * estimatedTokens
274
+ const { signal: streamSignal, cleanup: cleanupStreamSignal } = (0, external_request_timeout_js_namespaceObject.buildRequestAbortSignal)(effectiveTimeoutMs, options?.abortSignal);
275
+ try {
276
+ const stream = await completion.create({
277
+ model: modelName,
278
+ messages: messagesWithImageDetail,
279
+ ...commonConfig,
280
+ ...reasoningEffortConfig,
281
+ ...extraBody
282
+ }, {
283
+ stream: true,
284
+ signal: streamSignal
285
+ });
286
+ requestId = stream._request_id;
287
+ for await (const chunk of stream){
288
+ const content = chunk.choices?.[0]?.delta?.content || '';
289
+ const reasoning_content = chunk.choices?.[0]?.delta?.reasoning_content || '';
290
+ if (chunk.usage) usage = chunk.usage;
291
+ if (content || reasoning_content) {
292
+ accumulated += content;
293
+ accumulatedReasoning += reasoning_content;
294
+ const chunkData = {
295
+ content,
296
+ reasoning_content,
297
+ accumulated,
298
+ isComplete: false,
299
+ usage: void 0
305
300
  };
301
+ options.onChunk(chunkData);
302
+ }
303
+ if (chunk.choices?.[0]?.finish_reason) {
304
+ timeCost = Date.now() - startTime;
305
+ if (!usage) {
306
+ const estimatedTokens = Math.max(1, Math.floor(accumulated.length / 4));
307
+ usage = {
308
+ prompt_tokens: estimatedTokens,
309
+ completion_tokens: estimatedTokens,
310
+ total_tokens: 2 * estimatedTokens
311
+ };
312
+ }
313
+ const finalChunk = {
314
+ content: '',
315
+ accumulated,
316
+ reasoning_content: '',
317
+ isComplete: true,
318
+ usage: buildUsageInfo(usage, requestId)
319
+ };
320
+ options.onChunk(finalChunk);
321
+ break;
306
322
  }
307
- const finalChunk = {
308
- content: '',
309
- accumulated,
310
- reasoning_content: '',
311
- isComplete: true,
312
- usage: buildUsageInfo(usage, requestId)
313
- };
314
- options.onChunk(finalChunk);
315
- break;
316
323
  }
324
+ } finally{
325
+ cleanupStreamSignal();
317
326
  }
318
327
  content = accumulated;
319
328
  debugProfileStats(`streaming model, ${modelName}, mode, ${modelFamily || 'default'}, cost-ms, ${timeCost}, temperature, ${temperature ?? ''}`);
@@ -322,36 +331,43 @@ async function callAI(messages, modelConfig, options) {
322
331
  const retryInterval = modelConfig.retryInterval ?? 2000;
323
332
  const maxAttempts = retryCount + 1;
324
333
  let lastError;
325
- for(let attempt = 1; attempt <= maxAttempts; attempt++)try {
326
- const result = await completion.create({
327
- model: modelName,
328
- messages: messagesWithImageDetail,
329
- ...commonConfig,
330
- ...reasoningEffortConfig,
331
- ...extraBody
332
- }, options?.abortSignal ? {
333
- signal: options.abortSignal
334
- } : void 0);
335
- timeCost = Date.now() - startTime;
336
- debugProfileStats(`model, ${modelName}, mode, ${modelFamily || 'default'}, ui-tars-version, ${uiTarsModelVersion}, prompt-tokens, ${result.usage?.prompt_tokens || ''}, completion-tokens, ${result.usage?.completion_tokens || ''}, total-tokens, ${result.usage?.total_tokens || ''}, cost-ms, ${timeCost}, requestId, ${result._request_id || ''}, temperature, ${temperature ?? ''}`);
337
- debugProfileDetail(`model usage detail: ${JSON.stringify(result.usage)}`);
338
- if (!result.choices) throw new Error(`invalid response from LLM service: ${JSON.stringify(result)}`);
339
- content = result.choices[0].message.content;
340
- accumulatedReasoning = result.choices[0].message?.reasoning_content || '';
341
- usage = result.usage;
342
- requestId = result._request_id;
343
- if (!hasUsableText(content) && hasUsableText(accumulatedReasoning)) {
344
- warnCall('empty content from AI model, using reasoning content');
345
- content = accumulatedReasoning;
346
- }
347
- if (!hasUsableText(content)) throw new AIResponseParseError('empty content from AI model', JSON.stringify(result), buildUsageInfo(usage, requestId));
348
- break;
349
- } catch (error) {
350
- lastError = error;
351
- if (options?.abortSignal?.aborted) break;
352
- if (attempt < maxAttempts) {
353
- warnCall(`AI call failed (attempt ${attempt}/${maxAttempts}), retrying in ${retryInterval}ms... Error: ${lastError.message}`);
354
- await new Promise((resolve)=>setTimeout(resolve, retryInterval));
334
+ for(let attempt = 1; attempt <= maxAttempts; attempt++){
335
+ const { signal: attemptSignal, cleanup: cleanupAttemptSignal } = (0, external_request_timeout_js_namespaceObject.buildRequestAbortSignal)(effectiveTimeoutMs, options?.abortSignal);
336
+ try {
337
+ const result = await completion.create({
338
+ model: modelName,
339
+ messages: messagesWithImageDetail,
340
+ ...commonConfig,
341
+ ...reasoningEffortConfig,
342
+ ...extraBody
343
+ }, {
344
+ signal: attemptSignal
345
+ });
346
+ timeCost = Date.now() - startTime;
347
+ debugProfileStats(`model, ${modelName}, mode, ${modelFamily || 'default'}, ui-tars-version, ${uiTarsModelVersion}, prompt-tokens, ${result.usage?.prompt_tokens || ''}, completion-tokens, ${result.usage?.completion_tokens || ''}, total-tokens, ${result.usage?.total_tokens || ''}, cost-ms, ${timeCost}, requestId, ${result._request_id || ''}, temperature, ${temperature ?? ''}`);
348
+ debugProfileDetail(`model usage detail: ${JSON.stringify(result.usage)}`);
349
+ if (!result.choices) throw new Error(`invalid response from LLM service: ${JSON.stringify(result)}`);
350
+ content = result.choices[0].message.content;
351
+ accumulatedReasoning = result.choices[0].message?.reasoning_content || '';
352
+ usage = result.usage;
353
+ requestId = result._request_id;
354
+ if (!hasUsableText(content) && hasUsableText(accumulatedReasoning)) {
355
+ warnCall('empty content from AI model, using reasoning content');
356
+ content = accumulatedReasoning;
357
+ }
358
+ if (!hasUsableText(content)) throw new AIResponseParseError('empty content from AI model', JSON.stringify(result), buildUsageInfo(usage, requestId));
359
+ break;
360
+ } catch (error) {
361
+ lastError = error;
362
+ const wasHardTimeout = (0, external_request_timeout_js_namespaceObject.isHardTimeoutError)(lastError);
363
+ if (wasHardTimeout) warnCall(`AI call hit hard timeout (${effectiveTimeoutMs}ms, attempt ${attempt}/${maxAttempts}, model ${modelName}, intent ${modelConfig.intent})`);
364
+ if (options?.abortSignal?.aborted) break;
365
+ if (attempt < maxAttempts) {
366
+ warnCall(`AI call failed (attempt ${attempt}/${maxAttempts}), retrying in ${retryInterval}ms... Error: ${lastError.message}`);
367
+ await new Promise((resolve)=>setTimeout(resolve, retryInterval));
368
+ }
369
+ } finally{
370
+ cleanupAttemptSignal();
355
371
  }
356
372
  }
357
373
  if (!content) throw lastError;