@midscene/playground 1.9.8 → 1.10.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 (33) hide show
  1. package/dist/es/index.mjs +3 -2
  2. package/dist/es/launcher.mjs +4 -3
  3. package/dist/es/launcher.mjs.map +1 -1
  4. package/dist/es/recorder-ai-service.mjs +2 -0
  5. package/dist/es/recorder-ui-describer-prompt.mjs +56 -0
  6. package/dist/es/recorder-ui-describer-prompt.mjs.map +1 -0
  7. package/dist/es/recorder-ui-describer.mjs +392 -0
  8. package/dist/es/recorder-ui-describer.mjs.map +1 -0
  9. package/dist/es/server.mjs +32 -8
  10. package/dist/es/server.mjs.map +1 -1
  11. package/dist/lib/index.js +19 -6
  12. package/dist/lib/launcher.js +3 -2
  13. package/dist/lib/launcher.js.map +1 -1
  14. package/dist/lib/recorder-ai-service.js +38 -0
  15. package/dist/lib/recorder-ai-service.js.map +1 -0
  16. package/dist/lib/recorder-ui-describer-prompt.js +90 -0
  17. package/dist/lib/recorder-ui-describer-prompt.js.map +1 -0
  18. package/dist/lib/recorder-ui-describer.js +432 -0
  19. package/dist/lib/recorder-ui-describer.js.map +1 -0
  20. package/dist/lib/server.js +40 -7
  21. package/dist/lib/server.js.map +1 -1
  22. package/dist/types/index.d.ts +2 -1
  23. package/dist/types/recorder-ai-service.d.ts +1 -0
  24. package/dist/types/recorder-ui-describer-prompt.d.ts +1 -0
  25. package/dist/types/recorder-ui-describer.d.ts +20 -0
  26. package/dist/types/server.d.ts +4 -0
  27. package/package.json +9 -3
  28. package/static/index.html +1 -1
  29. package/static/static/js/index.9c67d55f.js +951 -0
  30. package/static/static/js/index.9c67d55f.js.map +1 -0
  31. package/static/static/js/index.44b83907.js +0 -948
  32. package/static/static/js/index.44b83907.js.map +0 -1
  33. /package/static/static/js/{index.44b83907.js.LICENSE.txt → index.9c67d55f.js.LICENSE.txt} +0 -0
package/dist/es/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { dataExtractionAPIs, executeAction, formatErrorMessage, noReplayAPIs, validateStructuredParams, validationAPIs } from "./common.mjs";
2
- import { PlaygroundServer } from "./server.mjs";
2
+ import { PlaygroundServer, buildPlaygroundBrowserUrl } from "./server.mjs";
3
+ import { describeRecorderUIEvent, describeRecorderUIEvents, getRecorderUIEventTargetRect } from "./recorder-ui-describer.mjs";
3
4
  import { playgroundForAgent, playgroundForAgentFactory, playgroundForSessionManager } from "./launcher.mjs";
4
5
  import { createMjpegPreviewDescriptor, createScrcpyPreviewDescriptor, createScreenshotPreviewDescriptor, definePlaygroundPlatform, resolvePreparedLaunchOptions } from "./platform.mjs";
5
6
  import { launchPreparedPlaygroundPlatform } from "./platform-launcher.mjs";
@@ -8,4 +9,4 @@ import { PlaygroundSDK } from "./sdk/index.mjs";
8
9
  import { BasePlaygroundAdapter } from "./adapters/base.mjs";
9
10
  import { LocalExecutionAdapter } from "./adapters/local-execution.mjs";
10
11
  import { RemoteExecutionAdapter } from "./adapters/remote-execution.mjs";
11
- export { BasePlaygroundAdapter, LocalExecutionAdapter, PlaygroundSDK, PlaygroundServer, RemoteExecutionAdapter, createMjpegPreviewDescriptor, createScrcpyPreviewDescriptor, createScreenshotPreviewDescriptor, dataExtractionAPIs, definePlaygroundPlatform, executeAction, formatErrorMessage, launchPreparedPlaygroundPlatform, noReplayAPIs, playgroundForAgent, playgroundForAgentFactory, playgroundForPlatforms, playgroundForSessionManager, prepareMultiPlatformPlayground, resolvePreparedLaunchOptions, validateStructuredParams, validationAPIs };
12
+ export { BasePlaygroundAdapter, LocalExecutionAdapter, PlaygroundSDK, PlaygroundServer, RemoteExecutionAdapter, buildPlaygroundBrowserUrl, createMjpegPreviewDescriptor, createScrcpyPreviewDescriptor, createScreenshotPreviewDescriptor, dataExtractionAPIs, definePlaygroundPlatform, describeRecorderUIEvent, describeRecorderUIEvents, executeAction, formatErrorMessage, getRecorderUIEventTargetRect, launchPreparedPlaygroundPlatform, noReplayAPIs, playgroundForAgent, playgroundForAgentFactory, playgroundForPlatforms, playgroundForSessionManager, prepareMultiPlatformPlayground, resolvePreparedLaunchOptions, validateStructuredParams, validationAPIs };
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { PLAYGROUND_SERVER_PORT } from "@midscene/shared/constants";
3
3
  import cors from "cors";
4
- import server_0 from "./server.mjs";
4
+ import server_0, { buildPlaygroundBrowserUrl, resolvePlaygroundBrowserHost } from "./server.mjs";
5
5
  const LOOPBACK_HOSTS = new Set([
6
6
  'localhost',
7
7
  '127.0.0.1',
@@ -47,12 +47,13 @@ function createPlaygroundLauncher(agentOrFactory) {
47
47
  if (configureServer) await configureServer(server);
48
48
  const launchedServer = await server.launch(port);
49
49
  if (verbose) console.log(`✅ Playground server started on port ${port}`);
50
- const url = `http://127.0.0.1:${port}`;
50
+ const host = resolvePlaygroundBrowserHost();
51
+ const url = buildPlaygroundBrowserUrl(host, port);
51
52
  if (openBrowser) await openInBrowser(url, browserCommand, verbose);
52
53
  return {
53
54
  server: launchedServer,
54
55
  port,
55
- host: '127.0.0.1',
56
+ host,
56
57
  close: async ()=>{
57
58
  if (verbose) console.log('🛑 Shutting down Midscene Playground...');
58
59
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"launcher.mjs","sources":["../../src/launcher.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport type { Agent } from '@midscene/core/agent';\nimport { PLAYGROUND_SERVER_PORT } from '@midscene/shared/constants';\nimport cors, { type CorsOptions } from 'cors';\nimport PlaygroundServer from './server';\nimport type { AgentFactory } from './types';\n\nexport interface LaunchPlaygroundOptions {\n /**\n * Port to start the playground server on\n * @default 5800\n */\n port?: number;\n\n /**\n * Whether to automatically open the playground in browser\n * @default true\n */\n openBrowser?: boolean;\n\n /**\n * Custom browser command to open playground\n * @default 'open' on macOS, 'start' on Windows, 'xdg-open' on Linux\n */\n browserCommand?: string;\n\n /**\n * Whether to show server logs\n * @default true\n */\n verbose?: boolean;\n\n /**\n * Fixed ID for the playground server instance\n * If provided, the same ID will be used across restarts,\n * allowing chat history to persist\n * @default undefined (generates random UUID)\n */\n id?: string;\n\n /**\n * Whether to enable CORS (Cross-Origin Resource Sharing)\n * @default false\n */\n enableCors?: boolean;\n\n /**\n * Custom static assets directory for the playground frontend\n * @default bundled static assets from @midscene/playground\n */\n staticPath?: string;\n\n /**\n * Hook for configuring the PlaygroundServer before launch\n * Useful for adding custom middleware beyond the built-in CORS option\n */\n configureServer?: (server: PlaygroundServer) => void | Promise<void>;\n\n /**\n * CORS configuration options\n * @default only allows loopback browser origins when enableCors is true\n */\n corsOptions?: CorsOptions;\n}\n\nexport interface LaunchPlaygroundResult {\n /**\n * The playground server instance\n */\n server: PlaygroundServer;\n\n /**\n * The server port\n */\n port: number;\n\n /**\n * The server host\n */\n host: string;\n\n /**\n * Function to gracefully shutdown the playground\n */\n close: () => Promise<void>;\n}\n\ntype LaunchableAgentSource = Agent | AgentFactory | undefined;\n\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);\n\nfunction isLoopbackOrigin(origin?: string) {\n if (!origin) {\n return true;\n }\n\n try {\n const url = new URL(origin);\n return LOOPBACK_HOSTS.has(url.hostname);\n } catch {\n return false;\n }\n}\n\nfunction createDefaultCorsOptions(): CorsOptions {\n return {\n origin(origin, callback) {\n callback(null, isLoopbackOrigin(origin));\n },\n credentials: true,\n };\n}\n\n/**\n * Create a playground launcher for a specific agent\n *\n * @example\n * ```typescript\n * import { playgroundForAgent } from '@midscene/playground';\n * import { SampleDevice, Agent } from '@midscene/core';\n *\n * const device = new SampleDevice();\n * const agent = new Agent(device);\n *\n * // Launch playground for the agent\n * const server = await playgroundForAgent(agent).launch();\n *\n * // Launch with CORS enabled\n * const serverWithCors = await playgroundForAgent(agent).launch({\n * enableCors: true,\n * corsOptions: {\n * origin: ['http://localhost:3000', 'http://localhost:8080'],\n * credentials: true\n * }\n * });\n *\n * // Later, when you want to shutdown:\n * server.close();\n * ```\n */\nfunction createPlaygroundLauncher(agentOrFactory: LaunchableAgentSource) {\n return {\n /**\n * Launch the playground server with optional configuration\n */\n async launch(\n options: LaunchPlaygroundOptions = {},\n ): Promise<LaunchPlaygroundResult> {\n const {\n port = PLAYGROUND_SERVER_PORT,\n openBrowser = true,\n browserCommand,\n verbose = true,\n id,\n enableCors = false,\n staticPath,\n configureServer,\n corsOptions = createDefaultCorsOptions(),\n } = options;\n\n if (\n agentOrFactory &&\n typeof agentOrFactory !== 'function' &&\n !agentOrFactory.interface\n ) {\n throw new Error('Agent must have an interface property');\n }\n\n if (verbose) {\n console.log('🚀 Starting Midscene Playground...');\n if (!agentOrFactory) {\n console.log('📱 Agent: session-managed');\n } else if (typeof agentOrFactory === 'function') {\n console.log('📱 Agent: factory');\n } else {\n console.log(`📱 Agent: ${agentOrFactory.constructor.name}`);\n console.log(`🖥️ Page: ${agentOrFactory.interface.constructor.name}`);\n }\n console.log(`🌐 Port: ${port}`);\n if (staticPath) {\n console.log(`📁 Static path: ${staticPath}`);\n }\n if (enableCors) {\n console.log('🔓 CORS enabled');\n }\n }\n\n const server = new PlaygroundServer(agentOrFactory, staticPath, id);\n\n if (enableCors) {\n server.app.use(cors(corsOptions));\n }\n\n if (configureServer) {\n await configureServer(server);\n }\n\n const launchedServer = await server.launch(port);\n\n if (verbose) {\n console.log(`✅ Playground server started on port ${port}`);\n }\n\n const url = `http://127.0.0.1:${port}`;\n\n // Open browser if requested\n if (openBrowser) {\n await openInBrowser(url, browserCommand, verbose);\n }\n\n return {\n server: launchedServer,\n port,\n host: '127.0.0.1',\n close: async () => {\n if (verbose) {\n console.log('🛑 Shutting down Midscene Playground...');\n }\n\n try {\n await launchedServer.close();\n if (verbose) {\n console.log('✅ Playground shutdown complete');\n }\n } catch (error) {\n if (verbose) {\n console.error('❌ Error during playground shutdown:', error);\n }\n throw error;\n }\n },\n };\n },\n };\n}\n\n/**\n * Create a playground launcher from an already initialized agent instance\n */\nexport function playgroundForAgent(agent: Agent) {\n return createPlaygroundLauncher(agent);\n}\n\n/**\n * Create a playground launcher from an agent factory\n * Useful for device-backed agents that need to be recreated after cancellation\n */\nexport function playgroundForAgentFactory(agentFactory: AgentFactory) {\n return createPlaygroundLauncher(agentFactory);\n}\n\nexport function playgroundForSessionManager() {\n return createPlaygroundLauncher(undefined);\n}\n\n/**\n * Open URL in browser using platform-appropriate command\n */\nasync function openInBrowser(\n url: string,\n customCommand?: string,\n verbose = true,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let command: string;\n let args: string[];\n\n if (customCommand) {\n command = customCommand;\n args = [url];\n } else {\n // Detect platform and use appropriate command\n switch (process.platform) {\n case 'darwin':\n command = 'open';\n args = [url];\n break;\n case 'win32':\n command = 'start';\n args = ['', url]; // Empty string for title\n break;\n default:\n command = 'xdg-open';\n args = [url];\n break;\n }\n }\n\n if (verbose) {\n console.log(`🌐 Opening browser: ${command} ${args.join(' ')}`);\n }\n\n const child = spawn(command, args, {\n detached: true,\n stdio: 'ignore',\n });\n\n child.on('error', (error) => {\n if (verbose) {\n console.warn('⚠️ Failed to open browser automatically:', error.message);\n console.log(`🌐 Please open manually: ${url}`);\n }\n // Don't reject, just continue - browser opening is optional\n resolve();\n });\n\n child.on('close', () => {\n resolve();\n });\n\n // Don't wait for the browser process\n child.unref();\n });\n}\n"],"names":["LOOPBACK_HOSTS","Set","isLoopbackOrigin","origin","url","URL","createDefaultCorsOptions","callback","createPlaygroundLauncher","agentOrFactory","options","port","PLAYGROUND_SERVER_PORT","openBrowser","browserCommand","verbose","id","enableCors","staticPath","configureServer","corsOptions","Error","console","server","PlaygroundServer","cors","launchedServer","openInBrowser","error","playgroundForAgent","agent","playgroundForAgentFactory","agentFactory","playgroundForSessionManager","undefined","customCommand","Promise","resolve","reject","command","args","process","child","spawn"],"mappings":";;;;AAyFA,MAAMA,iBAAiB,IAAIC,IAAI;IAAC;IAAa;IAAa;IAAO;CAAQ;AAEzE,SAASC,iBAAiBC,MAAe;IACvC,IAAI,CAAC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MJ,SAASC,MAAM;YACjC,UAAU;YACV,OAAO;QACT;QAEAE,MAAM,EAAE,CAAC,SAAS,CAACd;YACjB,IAAIb,SAAS;gBACXO,QAAQ,IAAI,CAAC,6CAA6CM,MAAM,OAAO;gBACvEN,QAAQ,GAAG,CAAC,CAAC,yBAAyB,EAAElB,KAAK;YAC/C;YAEAiC;QACF;QAEAK,MAAM,EAAE,CAAC,SAAS;YAChBL;QACF;QAGAK,MAAM,KAAK;IACb;AACF"}
1
+ {"version":3,"file":"launcher.mjs","sources":["../../src/launcher.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport type { Agent } from '@midscene/core/agent';\nimport { PLAYGROUND_SERVER_PORT } from '@midscene/shared/constants';\nimport cors, { type CorsOptions } from 'cors';\nimport PlaygroundServer, {\n buildPlaygroundBrowserUrl,\n resolvePlaygroundBrowserHost,\n} from './server';\nimport type { AgentFactory } from './types';\n\nexport interface LaunchPlaygroundOptions {\n /**\n * Port to start the playground server on\n * @default 5800\n */\n port?: number;\n\n /**\n * Whether to automatically open the playground in browser\n * @default true\n */\n openBrowser?: boolean;\n\n /**\n * Custom browser command to open playground\n * @default 'open' on macOS, 'start' on Windows, 'xdg-open' on Linux\n */\n browserCommand?: string;\n\n /**\n * Whether to show server logs\n * @default true\n */\n verbose?: boolean;\n\n /**\n * Fixed ID for the playground server instance\n * If provided, the same ID will be used across restarts,\n * allowing chat history to persist\n * @default undefined (generates random UUID)\n */\n id?: string;\n\n /**\n * Whether to enable CORS (Cross-Origin Resource Sharing)\n * @default false\n */\n enableCors?: boolean;\n\n /**\n * Custom static assets directory for the playground frontend\n * @default bundled static assets from @midscene/playground\n */\n staticPath?: string;\n\n /**\n * Hook for configuring the PlaygroundServer before launch\n * Useful for adding custom middleware beyond the built-in CORS option\n */\n configureServer?: (server: PlaygroundServer) => void | Promise<void>;\n\n /**\n * CORS configuration options\n * @default only allows loopback browser origins when enableCors is true\n */\n corsOptions?: CorsOptions;\n}\n\nexport interface LaunchPlaygroundResult {\n /**\n * The playground server instance\n */\n server: PlaygroundServer;\n\n /**\n * The server port\n */\n port: number;\n\n /**\n * The server host\n */\n host: string;\n\n /**\n * Function to gracefully shutdown the playground\n */\n close: () => Promise<void>;\n}\n\ntype LaunchableAgentSource = Agent | AgentFactory | undefined;\n\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);\n\nfunction isLoopbackOrigin(origin?: string) {\n if (!origin) {\n return true;\n }\n\n try {\n const url = new URL(origin);\n return LOOPBACK_HOSTS.has(url.hostname);\n } catch {\n return false;\n }\n}\n\nfunction createDefaultCorsOptions(): CorsOptions {\n return {\n origin(origin, callback) {\n callback(null, isLoopbackOrigin(origin));\n },\n credentials: true,\n };\n}\n\n/**\n * Create a playground launcher for a specific agent\n *\n * @example\n * ```typescript\n * import { playgroundForAgent } from '@midscene/playground';\n * import { SampleDevice, Agent } from '@midscene/core';\n *\n * const device = new SampleDevice();\n * const agent = new Agent(device);\n *\n * // Launch playground for the agent\n * const server = await playgroundForAgent(agent).launch();\n *\n * // Launch with CORS enabled\n * const serverWithCors = await playgroundForAgent(agent).launch({\n * enableCors: true,\n * corsOptions: {\n * origin: ['http://localhost:3000', 'http://localhost:8080'],\n * credentials: true\n * }\n * });\n *\n * // Later, when you want to shutdown:\n * server.close();\n * ```\n */\nfunction createPlaygroundLauncher(agentOrFactory: LaunchableAgentSource) {\n return {\n /**\n * Launch the playground server with optional configuration\n */\n async launch(\n options: LaunchPlaygroundOptions = {},\n ): Promise<LaunchPlaygroundResult> {\n const {\n port = PLAYGROUND_SERVER_PORT,\n openBrowser = true,\n browserCommand,\n verbose = true,\n id,\n enableCors = false,\n staticPath,\n configureServer,\n corsOptions = createDefaultCorsOptions(),\n } = options;\n\n if (\n agentOrFactory &&\n typeof agentOrFactory !== 'function' &&\n !agentOrFactory.interface\n ) {\n throw new Error('Agent must have an interface property');\n }\n\n if (verbose) {\n console.log('🚀 Starting Midscene Playground...');\n if (!agentOrFactory) {\n console.log('📱 Agent: session-managed');\n } else if (typeof agentOrFactory === 'function') {\n console.log('📱 Agent: factory');\n } else {\n console.log(`📱 Agent: ${agentOrFactory.constructor.name}`);\n console.log(`🖥️ Page: ${agentOrFactory.interface.constructor.name}`);\n }\n console.log(`🌐 Port: ${port}`);\n if (staticPath) {\n console.log(`📁 Static path: ${staticPath}`);\n }\n if (enableCors) {\n console.log('🔓 CORS enabled');\n }\n }\n\n const server = new PlaygroundServer(agentOrFactory, staticPath, id);\n\n if (enableCors) {\n server.app.use(cors(corsOptions));\n }\n\n if (configureServer) {\n await configureServer(server);\n }\n\n const launchedServer = await server.launch(port);\n\n if (verbose) {\n console.log(`✅ Playground server started on port ${port}`);\n }\n\n const host = resolvePlaygroundBrowserHost();\n const url = buildPlaygroundBrowserUrl(host, port);\n\n // Open browser if requested\n if (openBrowser) {\n await openInBrowser(url, browserCommand, verbose);\n }\n\n return {\n server: launchedServer,\n port,\n host,\n close: async () => {\n if (verbose) {\n console.log('🛑 Shutting down Midscene Playground...');\n }\n\n try {\n await launchedServer.close();\n if (verbose) {\n console.log('✅ Playground shutdown complete');\n }\n } catch (error) {\n if (verbose) {\n console.error('❌ Error during playground shutdown:', error);\n }\n throw error;\n }\n },\n };\n },\n };\n}\n\n/**\n * Create a playground launcher from an already initialized agent instance\n */\nexport function playgroundForAgent(agent: Agent) {\n return createPlaygroundLauncher(agent);\n}\n\n/**\n * Create a playground launcher from an agent factory\n * Useful for device-backed agents that need to be recreated after cancellation\n */\nexport function playgroundForAgentFactory(agentFactory: AgentFactory) {\n return createPlaygroundLauncher(agentFactory);\n}\n\nexport function playgroundForSessionManager() {\n return createPlaygroundLauncher(undefined);\n}\n\n/**\n * Open URL in browser using platform-appropriate command\n */\nasync function openInBrowser(\n url: string,\n customCommand?: string,\n verbose = true,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let command: string;\n let args: string[];\n\n if (customCommand) {\n command = customCommand;\n args = [url];\n } else {\n // Detect platform and use appropriate command\n switch (process.platform) {\n case 'darwin':\n command = 'open';\n args = [url];\n break;\n case 'win32':\n command = 'start';\n args = ['', url]; // Empty string for title\n break;\n default:\n command = 'xdg-open';\n args = [url];\n break;\n }\n }\n\n if (verbose) {\n console.log(`🌐 Opening browser: ${command} ${args.join(' ')}`);\n }\n\n const child = spawn(command, args, {\n detached: true,\n stdio: 'ignore',\n });\n\n child.on('error', (error) => {\n if (verbose) {\n console.warn('⚠️ Failed to open browser automatically:', error.message);\n console.log(`🌐 Please open manually: ${url}`);\n }\n // Don't reject, just continue - browser opening is optional\n resolve();\n });\n\n child.on('close', () => {\n resolve();\n });\n\n // Don't wait for the browser process\n child.unref();\n });\n}\n"],"names":["LOOPBACK_HOSTS","Set","isLoopbackOrigin","origin","url","URL","createDefaultCorsOptions","callback","createPlaygroundLauncher","agentOrFactory","options","port","PLAYGROUND_SERVER_PORT","openBrowser","browserCommand","verbose","id","enableCors","staticPath","configureServer","corsOptions","Error","console","server","PlaygroundServer","cors","launchedServer","host","resolvePlaygroundBrowserHost","buildPlaygroundBrowserUrl","openInBrowser","error","playgroundForAgent","agent","playgroundForAgentFactory","agentFactory","playgroundForSessionManager","undefined","customCommand","Promise","resolve","reject","command","args","process","child","spawn"],"mappings":";;;;AA4FA,MAAMA,iBAAiB,IAAIC,IAAI;IAAC;IAAa;IAAa;IAAO;CAAQ;AAEzE,SAASC,iBAAiBC,MAAe;IACvC,IAAI,CAACA,QACH,OAAO;IAGT,IAAI;QACF,MAAMC,MAAM,IAAIC,IAAIF;QACpB,OAAOH,eAAe,GAAG,CAACI,IAAI,QAAQ;IACxC,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA,SAASE;IACP,OAAO;QACL,QAAOH,MAAM,EAAEI,QAAQ;YACrBA,SAAS,MAAML,iBAAiBC;QAClC;QACA,aAAa;IACf;AACF;AA6BA,SAASK,yBAAyBC,cAAqC;IACrE,OAAO;QAIL,MAAM,QACJC,UAAmC,CAAC,CAAC;YAErC,MAAM,EACJC,OAAOC,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"@midscene/core/ai-model";
2
+ export { callAIWithObjectResponse };
@@ -0,0 +1,56 @@
1
+ const RECORDER_UI_DESCRIBER_SYSTEM_PROMPT = `You convert Studio preview recorder UI events into semantic replay instructions.
2
+
3
+ The recorder works from screenshots and mapped real-device coordinates only. Infer stable UI intent from the highlighted BEFORE screenshot. The AFTER screenshot is contextual evidence for state changes and scroll destinations.
4
+
5
+ Output JSON only:
6
+ {
7
+ "elementDescription": "short stable target/region description",
8
+ "replayInstruction": "one executable natural-language replay step",
9
+ "actionSummary": "short timeline summary",
10
+ "scrollDestinationDescription": "for scroll only: concrete newly visible destination content or goal",
11
+ "confidence": "high" | "medium" | "low",
12
+ "error"?: "only if no useful visual description can be inferred"
13
+ }
14
+
15
+ Rules:
16
+ - Do NOT output coordinates as the main description.
17
+ - Do NOT mention "near coordinates", "nearby element", "near point", "red marker", highlighted box, highlighted element, or screenshot.
18
+ - Prefer stable target descriptions in this order: exact stable control text > stable label > role + stable section/context > icon purpose > visual position.
19
+ - Treat placeholder or hint text that can change by user, time, data, or context as dynamic. Do not use dynamic hint values as the primary target description; prefer role + stable region + intent.
20
+ - For repeated collections, treat item identity text as dynamic unless the user is clearly verifying that exact item. This includes any list/grid/table/feed/menu or repeated record surface. Do not output descriptions like "<role> titled/named '<content>'"; prefer stable role + region + selection intent.
21
+ - Keep quoted UI text in the original UI language when it is a stable control label.
22
+ - Apply the platform guidance from the user event:
23
+ - Web: button, input, link, menu item, tab, dialog, aria-label, placeholder, form section.
24
+ - Mobile: tab, list item, text field, icon button, navigation bar, bottom bar, sheet, card, screen section.
25
+ - Desktop/computer: menu item, toolbar button, dialog field, sidebar item, window control, file row, application region.
26
+ - Pointer action rules:
27
+ - Preserve event.actionType semantics. Tap, DoubleClick, LongPress, and RightClick must not all become Click.
28
+ - Tap replayInstruction format: Tap on the element described as "<elementDescription>".
29
+ - DoubleClick replayInstruction format: Double click on the element described as "<elementDescription>".
30
+ - LongPress replayInstruction format: Long press the element described as "<elementDescription>".
31
+ - RightClick replayInstruction format: Right click on the element described as "<elementDescription>".
32
+ - Click replayInstruction format: Click on the element described as "<elementDescription>".
33
+ - Input-specific rules:
34
+ - The highlighted BEFORE screenshot marks the field that receives the text.
35
+ - The screenshot after the action may show the typed value; use it only to confirm the field, never as the field description.
36
+ - elementDescription must identify the field itself by stable field role, nearby label, region, section, or sequence intent.
37
+ - Never use "AI is analyzing element", the typed value, the page title alone, or a generic "input field" as elementDescription.
38
+ - For consecutive input events, distinguish fields by stable role, section, order, current focus, filled/empty state, and neighboring actions instead of reusing the same generic field description.
39
+ - Input replayInstruction format: Input "<value>" into the element described as "<elementDescription>".
40
+ - Scroll target quality bar:
41
+ - elementDescription describes the scrollable page, panel, list, table, or section at the highlighted scroll point.
42
+ - When multiple scrollable regions are visible, preserve the specific region where the scroll happened, such as left/right/top/bottom panel, navigation area, content pane, dialog body, table, list, or menu. Do not generalize a panel/list scroll into the whole page.
43
+ - scrollDestinationDescription is required and describes what the scroll is trying to reveal or reach, using newly visible headings, section titles, list items, or stable content from the AFTER screenshot.
44
+ - Prefer descriptions like "Playwright integration documentation page, scrolling toward the API reference section" or "Android API documentation page, scrolling to the installation steps section".
45
+ - Do NOT write generic phrases like "more content", "the page", "current screen", or "main scrollable area".
46
+ - Scroll replayInstruction format: Scroll the page/region with description "<elementDescription>" by value "<recorded value>" until "<scrollDestinationDescription>" is visible.
47
+ - Scroll actionSummary format: Scroll <elementDescription> toward <scrollDestinationDescription>.
48
+ - Drag/Swipe rules:
49
+ - Drag replayInstruction format: Drag through the area described as "<elementDescription>".
50
+ - Swipe replayInstruction format: Swipe through the area described as "<elementDescription>".
51
+ - Describe start/end regions or the dragged UI control; do not describe only the gesture path.
52
+ - KeyboardPress replayInstruction format: Press "<value>" on the element described as "<elementDescription>".
53
+ - If uncertain, provide the best concrete visible text/role/context description. Set confidence to "low"; do not fall back to coordinates.`;
54
+ export { RECORDER_UI_DESCRIBER_SYSTEM_PROMPT };
55
+
56
+ //# sourceMappingURL=recorder-ui-describer-prompt.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recorder-ui-describer-prompt.mjs","sources":["../../src/recorder-ui-describer-prompt.ts"],"sourcesContent":["export const RECORDER_UI_DESCRIBER_SYSTEM_PROMPT = `You convert Studio preview recorder UI events into semantic replay instructions.\n\nThe recorder works from screenshots and mapped real-device coordinates only. Infer stable UI intent from the highlighted BEFORE screenshot. The AFTER screenshot is contextual evidence for state changes and scroll destinations.\n\nOutput JSON only:\n{\n \"elementDescription\": \"short stable target/region description\",\n \"replayInstruction\": \"one executable natural-language replay step\",\n \"actionSummary\": \"short timeline summary\",\n \"scrollDestinationDescription\": \"for scroll only: concrete newly visible destination content or goal\",\n \"confidence\": \"high\" | \"medium\" | \"low\",\n \"error\"?: \"only if no useful visual description can be inferred\"\n}\n\nRules:\n- Do NOT output coordinates as the main description.\n- Do NOT mention \"near coordinates\", \"nearby element\", \"near point\", \"red marker\", highlighted box, highlighted element, or screenshot.\n- Prefer stable target descriptions in this order: exact stable control text > stable label > role + stable section/context > icon purpose > visual position.\n- Treat placeholder or hint text that can change by user, time, data, or context as dynamic. Do not use dynamic hint values as the primary target description; prefer role + stable region + intent.\n- For repeated collections, treat item identity text as dynamic unless the user is clearly verifying that exact item. This includes any list/grid/table/feed/menu or repeated record surface. Do not output descriptions like \"<role> titled/named '<content>'\"; prefer stable role + region + selection intent.\n- Keep quoted UI text in the original UI language when it is a stable control label.\n- Apply the platform guidance from the user event:\n - Web: button, input, link, menu item, tab, dialog, aria-label, placeholder, form section.\n - Mobile: tab, list item, text field, icon button, navigation bar, bottom bar, sheet, card, screen section.\n - Desktop/computer: menu item, toolbar button, dialog field, sidebar item, window control, file row, application region.\n- Pointer action rules:\n - Preserve event.actionType semantics. Tap, DoubleClick, LongPress, and RightClick must not all become Click.\n - Tap replayInstruction format: Tap on the element described as \"<elementDescription>\".\n - DoubleClick replayInstruction format: Double click on the element described as \"<elementDescription>\".\n - LongPress replayInstruction format: Long press the element described as \"<elementDescription>\".\n - RightClick replayInstruction format: Right click on the element described as \"<elementDescription>\".\n - Click replayInstruction format: Click on the element described as \"<elementDescription>\".\n- Input-specific rules:\n - The highlighted BEFORE screenshot marks the field that receives the text.\n - The screenshot after the action may show the typed value; use it only to confirm the field, never as the field description.\n - elementDescription must identify the field itself by stable field role, nearby label, region, section, or sequence intent.\n - Never use \"AI is analyzing element\", the typed value, the page title alone, or a generic \"input field\" as elementDescription.\n - For consecutive input events, distinguish fields by stable role, section, order, current focus, filled/empty state, and neighboring actions instead of reusing the same generic field description.\n - Input replayInstruction format: Input \"<value>\" into the element described as \"<elementDescription>\".\n- Scroll target quality bar:\n - elementDescription describes the scrollable page, panel, list, table, or section at the highlighted scroll point.\n - When multiple scrollable regions are visible, preserve the specific region where the scroll happened, such as left/right/top/bottom panel, navigation area, content pane, dialog body, table, list, or menu. Do not generalize a panel/list scroll into the whole page.\n - scrollDestinationDescription is required and describes what the scroll is trying to reveal or reach, using newly visible headings, section titles, list items, or stable content from the AFTER screenshot.\n - Prefer descriptions like \"Playwright integration documentation page, scrolling toward the API reference section\" or \"Android API documentation page, scrolling to the installation steps section\".\n - Do NOT write generic phrases like \"more content\", \"the page\", \"current screen\", or \"main scrollable area\".\n- Scroll replayInstruction format: Scroll the page/region with description \"<elementDescription>\" by value \"<recorded value>\" until \"<scrollDestinationDescription>\" is visible.\n- Scroll actionSummary format: Scroll <elementDescription> toward <scrollDestinationDescription>.\n- Drag/Swipe rules:\n - Drag replayInstruction format: Drag through the area described as \"<elementDescription>\".\n - Swipe replayInstruction format: Swipe through the area described as \"<elementDescription>\".\n - Describe start/end regions or the dragged UI control; do not describe only the gesture path.\n- KeyboardPress replayInstruction format: Press \"<value>\" on the element described as \"<elementDescription>\".\n- If uncertain, provide the best concrete visible text/role/context description. Set confidence to \"low\"; do not fall back to coordinates.`;\n"],"names":["RECORDER_UI_DESCRIBER_SYSTEM_PROMPT"],"mappings":"AAAO,MAAMA,sCAAsC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0IAoDsF,CAAC"}
@@ -0,0 +1,392 @@
1
+ import { ModelConfigManager } from "@midscene/shared/env";
2
+ import { buildMidsceneRecorderActionSummary, buildMidsceneRecorderReplayInstruction, getMidsceneRecorderSemantic } from "@midscene/shared/recorder";
3
+ import { callAIWithObjectResponse } from "./recorder-ai-service.mjs";
4
+ import { RECORDER_UI_DESCRIBER_SYSTEM_PROMPT } from "./recorder-ui-describer-prompt.mjs";
5
+ const RECORDER_UI_DESCRIBER_DEFAULT_RETRIES = 2;
6
+ const RECORDER_UI_DESCRIBER_DEFAULT_RETRY_DELAY_MS = 200;
7
+ const RECORDER_UI_DESCRIBER_DEFAULT_CONCURRENCY = 2;
8
+ function delay(ms) {
9
+ return new Promise((resolve)=>setTimeout(resolve, ms));
10
+ }
11
+ function isResolvedModelConfig(modelConfig) {
12
+ return 'string' == typeof modelConfig.modelName && ('string' == typeof modelConfig.modelDescription || 'string' == typeof modelConfig.intent || 'string' == typeof modelConfig.slot || 'string' == typeof modelConfig.openaiApiKey);
13
+ }
14
+ function resolveRecorderModelConfig(modelConfig) {
15
+ if (isResolvedModelConfig(modelConfig)) return modelConfig;
16
+ const rawModelConfig = Object.entries(modelConfig).reduce((result, [key, value])=>{
17
+ if ('string' == typeof value || 'number' == typeof value) result[key] = value;
18
+ return result;
19
+ }, {});
20
+ return new ModelConfigManager(rawModelConfig).getModelConfig('default');
21
+ }
22
+ function clamp(value, min, max) {
23
+ return Math.min(Math.max(value, min), max);
24
+ }
25
+ function isFiniteNumber(value) {
26
+ return 'number' == typeof value && Number.isFinite(value);
27
+ }
28
+ function isPendingDescription(value) {
29
+ return value?.trim() === 'AI is analyzing element...';
30
+ }
31
+ function getRecorderEventScreenshot(event) {
32
+ return event.screenshotWithBox || event.screenshotBefore || event.screenshotAfter;
33
+ }
34
+ function getRecorderEventAfterScreenshot(event) {
35
+ return event.screenshotAfter || event.screenshotWithBox;
36
+ }
37
+ function normalizeActionType(event) {
38
+ return event.actionType?.trim();
39
+ }
40
+ function getPlatformId(target) {
41
+ return target?.platformId?.toLowerCase();
42
+ }
43
+ function getPlatformSurface(target) {
44
+ switch(getPlatformId(target)){
45
+ case 'web':
46
+ return 'current web page';
47
+ case 'android':
48
+ case 'ios':
49
+ case 'harmony':
50
+ return 'current mobile screen';
51
+ case 'computer':
52
+ return 'current desktop screen';
53
+ default:
54
+ return 'current UI';
55
+ }
56
+ }
57
+ function getPlatformGuidance(target) {
58
+ switch(getPlatformId(target)){
59
+ case 'web':
60
+ return 'For web targets, use web UI terms such as button, input, link, menu item, tab, dialog, aria-label, placeholder, and form section when visible or inferable.';
61
+ case 'android':
62
+ case 'ios':
63
+ case 'harmony':
64
+ return 'For mobile targets, use mobile UI terms such as tab, list item, text field, icon button, navigation bar, bottom bar, sheet, card, and screen section.';
65
+ case 'computer':
66
+ return 'For desktop/computer targets, use desktop UI terms such as menu item, toolbar button, dialog field, sidebar item, window control, file row, and application region.';
67
+ default:
68
+ return 'Use platform-neutral UI terms such as control, field, item, icon button, list item, region, panel, and page section.';
69
+ }
70
+ }
71
+ function getPointerActionVerb(event) {
72
+ switch(normalizeActionType(event)){
73
+ case 'Tap':
74
+ return 'Tap';
75
+ case 'DoubleClick':
76
+ return 'Double click';
77
+ case 'LongPress':
78
+ return 'Long press';
79
+ case 'RightClick':
80
+ return 'Right click';
81
+ default:
82
+ return 'Click';
83
+ }
84
+ }
85
+ function getDragActionVerb(event) {
86
+ switch(normalizeActionType(event)){
87
+ case 'Swipe':
88
+ return 'Swipe';
89
+ case 'DragAndDrop':
90
+ return 'Drag';
91
+ default:
92
+ return 'Drag';
93
+ }
94
+ }
95
+ function pointToRect(x, y, size, pageInfo) {
96
+ const width = pageInfo.width || size;
97
+ const height = pageInfo.height || size;
98
+ const left = clamp(Math.floor(x - size / 2), 0, Math.max(width - 1, 0));
99
+ const top = clamp(Math.floor(y - size / 2), 0, Math.max(height - 1, 0));
100
+ return {
101
+ left,
102
+ top,
103
+ width: Math.min(size, Math.max(width - left, 1)),
104
+ height: Math.min(size, Math.max(height - top, 1))
105
+ };
106
+ }
107
+ function getPointRectSize(event) {
108
+ switch(event.type){
109
+ case 'scroll':
110
+ return 96;
111
+ case 'drag':
112
+ return 64;
113
+ default:
114
+ return 36;
115
+ }
116
+ }
117
+ function getRecorderUIEventTargetRect(event) {
118
+ const rect = event.elementRect;
119
+ if (!rect) return null;
120
+ if (isFiniteNumber(rect.width) && rect.width > 0 && isFiniteNumber(rect.height) && rect.height > 0 && (isFiniteNumber(rect.left) || isFiniteNumber(rect.top))) return {
121
+ left: rect.left || 0,
122
+ top: rect.top || 0,
123
+ width: rect.width,
124
+ height: rect.height
125
+ };
126
+ if (isFiniteNumber(rect.x) && isFiniteNumber(rect.y)) return pointToRect(rect.x, rect.y, getPointRectSize(event), event.pageInfo);
127
+ return null;
128
+ }
129
+ function getFallbackDescription(event, target) {
130
+ const pageContext = getPageSemanticContext(event);
131
+ const surface = getPlatformSurface(target);
132
+ switch(event.type){
133
+ case 'navigation':
134
+ return event.url || event.value || event.actionType || 'navigation';
135
+ case 'scroll':
136
+ return pageContext ? `${pageContext} scrollable content` : `scrollable content on the ${surface}`;
137
+ case 'drag':
138
+ return pageContext ? `gesture area in ${pageContext}` : `gesture area on the ${surface}`;
139
+ case 'input':
140
+ return `unresolved input field on the ${surface}`;
141
+ case 'keydown':
142
+ return pageContext ? `focused control in ${pageContext}` : `focused control on the ${surface}`;
143
+ default:
144
+ return pageContext ? `control in ${pageContext}` : `control on the ${surface}`;
145
+ }
146
+ }
147
+ function buildSemanticAction(event, scrollDestinationDescription) {
148
+ return {
149
+ type: event.type,
150
+ actionType: event.actionType,
151
+ value: event.value,
152
+ url: event.url,
153
+ scrollDestinationDescription
154
+ };
155
+ }
156
+ function getFallbackReplayInstruction(event, elementDescription) {
157
+ return buildMidsceneRecorderReplayInstruction(buildSemanticAction(event), elementDescription);
158
+ }
159
+ function getFallbackActionSummary(event, elementDescription) {
160
+ return buildMidsceneRecorderActionSummary(buildSemanticAction(event), elementDescription);
161
+ }
162
+ function getActionGuidance(event, target) {
163
+ const platformGuidance = getPlatformGuidance(target);
164
+ switch(event.type){
165
+ case 'click':
166
+ return `${platformGuidance} Identify the ${getPointerActionVerb(event).toLowerCase()} target by exact visible text first, then label/placeholder, then role plus stable surrounding context, then icon purpose, then visual position. Never describe it by coordinates, marker location, or as a nearby element.`;
167
+ case 'input':
168
+ return `${platformGuidance} Identify the exact input field at the marker before text entry. Use stable visible label, field role, field name, surrounding section, or sequence intent. Treat hint text that can change by user, time, data, or context as secondary evidence. Preserve the recorded input value only in replayInstruction; never describe the typed value or page title alone as the field.`;
169
+ case 'scroll':
170
+ return `${platformGuidance} Identify the scrollable page/region at the highlighted scroll point and concrete destination content revealed after scrolling. If multiple scrollable regions are visible, preserve the specific region where the scroll happened, such as left/right/top/bottom panel, navigation area, content pane, dialog body, table, list, or menu; do not generalize a panel/list scroll into the whole page. Use newly visible headings, section titles, list/table names, list items, or stable region labels; never say only "more content" or "current page".`;
171
+ case 'drag':
172
+ return `${platformGuidance} Identify the ${getDragActionVerb(event).toLowerCase()} start/end regions or the dragged UI control. Do not describe only the gesture path or coordinates.`;
173
+ case 'keydown':
174
+ return `${platformGuidance} Identify the focused element or keyboard target if visible, and preserve the recorded key in the replay instruction.`;
175
+ default:
176
+ return `${platformGuidance} Identify the UI target involved in this event using the most stable visible text or surrounding context.`;
177
+ }
178
+ }
179
+ function getEventRawCoordinates(event) {
180
+ const x = event.elementRect?.x;
181
+ const y = event.elementRect?.y;
182
+ if (isFiniteNumber(x) && isFiniteNumber(y)) return {
183
+ x,
184
+ y
185
+ };
186
+ }
187
+ function getPageSemanticContext(event) {
188
+ const candidates = [
189
+ event.title,
190
+ event.url
191
+ ].map((item)=>item?.trim()).filter(Boolean);
192
+ return candidates[0];
193
+ }
194
+ function isWeakDescription(value) {
195
+ if (!value) return true;
196
+ if (isPendingDescription(value)) return true;
197
+ const normalized = value.trim().toLowerCase();
198
+ const compact = normalized.replace(/\s+/g, '');
199
+ return 0 === normalized.length || /^\(?\d+(?:\.\d+)?,\s*\d+(?:\.\d+)?\)?$/.test(normalized) || 'target' === normalized || 'element' === normalized || 'target element' === normalized || 'the element' === normalized || 'page element' === normalized || 'input field' === normalized || 'text input' === normalized || 'text field' === normalized || 'search box' === normalized || 'more content' === normalized || 'the page' === normalized || 'current page' === normalized || 'current screen' === normalized || 'the screen' === normalized || 'current ui' === normalized || 'current visible ui' === normalized || 'current visible page' === normalized || 'current visible screen' === normalized || 'main area' === normalized || 'main scrollable area' === normalized || 'scrollable area' === normalized || 'highlighted element' === normalized || 'highlighted item' === normalized || 'marked element' === normalized || 'marked item' === normalized || normalized.includes('ai is analyzing element') || compact.includes('坐标') || compact.includes('附近') || compact.includes('附近的元素') || normalized.includes('coordinate') || normalized.includes('near the coordinate') || normalized.includes('near coordinates') || normalized.includes('nearby element') || normalized.includes('nearby item') || normalized.includes('near the marker') || normalized.includes('near marker') || normalized.includes('near the point') || normalized.includes('near point') || normalized.includes('at the point') || normalized.includes('button near point') || normalized.includes('shown in the screenshot') || normalized.includes('red rectangle') || normalized.includes('red marker') || normalized.includes('red box') || normalized.includes('highlighted element') || normalized.includes('highlighted item') || normalized.includes('highlighted screenshot');
200
+ }
201
+ function isWeakReplayInstruction(value) {
202
+ if (!value) return true;
203
+ if (isPendingDescription(value)) return true;
204
+ const normalized = value.trim().toLowerCase();
205
+ const compact = normalized.replace(/\s+/g, '');
206
+ return compact.includes('坐标') || compact.includes('附近') || normalized.includes('coordinate') || normalized.includes('near the coordinate') || normalized.includes('nearby element') || normalized.includes('nearby item') || normalized.includes('near the marker') || normalized.includes('near marker') || normalized.includes('near the point') || normalized.includes('near point') || normalized.includes('at the point') || normalized.includes('ai is analyzing element') || normalized.includes('more content') || normalized.includes('current page') || normalized.includes('current screen') || normalized.includes('highlighted element') || normalized.includes('highlighted item') || normalized.includes('red marker') || normalized.includes('red box') || normalized.includes('shown in the screenshot') || normalized.includes('highlighted screenshot');
207
+ }
208
+ function normalizeForComparison(value) {
209
+ return value.trim().toLowerCase().replace(/["'`]/g, '').replace(/\s+/g, ' ');
210
+ }
211
+ function isInputValueUsedAsFieldDescription(event, elementDescription) {
212
+ if ('input' !== event.type || !event.value || !elementDescription) return false;
213
+ const typedValue = normalizeForComparison(event.value);
214
+ if (!typedValue) return false;
215
+ const description = normalizeForComparison(elementDescription);
216
+ return description === typedValue || description === `${typedValue} input` || description === `${typedValue} field` || description === `${typedValue} text field` || description === `input ${typedValue}` || description === `field ${typedValue}` || description.includes(`typed value ${typedValue}`) || description.includes(`value ${typedValue}`);
217
+ }
218
+ function hasScrollDestination(replayInstruction, scrollDestinationDescription) {
219
+ if (scrollDestinationDescription && !isWeakDescription(scrollDestinationDescription)) return true;
220
+ const normalized = replayInstruction.toLowerCase();
221
+ return normalized.includes(' until ') || normalized.includes(' visible') || normalized.includes(' reveal') || normalized.includes(' to the ') || normalized.includes(' toward ');
222
+ }
223
+ async function describeWithRetry(event, target, highlightedScreenshot, modelConfig, options) {
224
+ let lastError;
225
+ for(let attempt = 1; attempt <= options.maxRetries; attempt += 1)try {
226
+ const afterScreenshot = getRecorderEventAfterScreenshot(event);
227
+ const pageContext = getPageSemanticContext(event);
228
+ const platformGuidance = getPlatformGuidance(target);
229
+ const userContent = [
230
+ {
231
+ type: 'text',
232
+ text: `Recorder event:
233
+ ${JSON.stringify({
234
+ type: event.type,
235
+ actionType: event.actionType,
236
+ value: event.value,
237
+ rawCoordinates: getEventRawCoordinates(event),
238
+ url: event.url,
239
+ title: event.title,
240
+ pageContext,
241
+ pageInfo: event.pageInfo,
242
+ target,
243
+ platformGuidance,
244
+ guidance: getActionGuidance(event, target)
245
+ }, null, 2)}
246
+
247
+ The target or region is highlighted in the screenshot below. Convert this event into semantic replay fields.`
248
+ },
249
+ {
250
+ type: 'image_url',
251
+ image_url: {
252
+ url: highlightedScreenshot,
253
+ detail: 'high'
254
+ }
255
+ }
256
+ ];
257
+ if (afterScreenshot) userContent.push({
258
+ type: 'text',
259
+ text: 'Screenshot after the recorded action, for context only:'
260
+ }, {
261
+ type: 'image_url',
262
+ image_url: {
263
+ url: afterScreenshot,
264
+ detail: 'high'
265
+ }
266
+ });
267
+ const response = await callAIWithObjectResponse([
268
+ {
269
+ role: 'system',
270
+ content: RECORDER_UI_DESCRIBER_SYSTEM_PROMPT
271
+ },
272
+ {
273
+ role: 'user',
274
+ content: userContent
275
+ }
276
+ ], modelConfig);
277
+ const content = response.content;
278
+ if (content.error) throw new Error(content.error);
279
+ if (isWeakDescription(content.elementDescription)) throw new Error("AI returned a weak recorder event description.");
280
+ if (isInputValueUsedAsFieldDescription(event, content.elementDescription)) throw new Error("AI used the recorded input value as the field description.");
281
+ const elementDescription = content.elementDescription.trim();
282
+ const scrollDestinationDescription = 'scroll' === event.type ? content.scrollDestinationDescription?.trim() : void 0;
283
+ if ('scroll' === event.type && !hasScrollDestination('', scrollDestinationDescription)) throw new Error("AI returned a scroll description without a destination.");
284
+ const aiReplayInstruction = content.replayInstruction?.trim();
285
+ if (aiReplayInstruction && isWeakReplayInstruction(aiReplayInstruction)) throw new Error('AI returned a weak recorder replay instruction.');
286
+ const semanticAction = buildSemanticAction(event, scrollDestinationDescription);
287
+ const replayInstruction = buildMidsceneRecorderReplayInstruction(semanticAction, elementDescription);
288
+ if (isWeakReplayInstruction(replayInstruction)) throw new Error('AI returned a weak recorder replay instruction.');
289
+ const actionSummary = buildMidsceneRecorderActionSummary(semanticAction, elementDescription);
290
+ return {
291
+ source: 'recorderAI',
292
+ status: 'ready',
293
+ elementDescription,
294
+ replayInstruction,
295
+ actionSummary,
296
+ confidence: content.confidence || 'medium'
297
+ };
298
+ } catch (error) {
299
+ lastError = error;
300
+ if (attempt < options.maxRetries) await delay(options.retryDelayMs);
301
+ }
302
+ throw lastError;
303
+ }
304
+ async function createScreenshotWithBox(event, rect) {
305
+ if (event.screenshotWithBox) return event.screenshotWithBox;
306
+ const screenshot = getRecorderEventScreenshot(event);
307
+ if (!screenshot) return;
308
+ const { compositeElementInfoImg } = await import(/* @vite-ignore */ "@midscene/shared/img");
309
+ return compositeElementInfoImg({
310
+ inputImgBase64: screenshot,
311
+ size: event.pageInfo,
312
+ elementsPositionInfo: [
313
+ {
314
+ rect
315
+ }
316
+ ],
317
+ borderThickness: 3,
318
+ annotationPadding: 2
319
+ });
320
+ }
321
+ function createFallbackEvent(event, error, screenshotWithBox, target) {
322
+ const semantic = getMidsceneRecorderSemantic(event);
323
+ const elementDescription = semantic?.elementDescription && !isWeakDescription(semantic.elementDescription) ? semantic.elementDescription : getFallbackDescription(event, target);
324
+ return {
325
+ ...event,
326
+ semantic: {
327
+ source: 'heuristic',
328
+ status: 'ready',
329
+ elementDescription,
330
+ replayInstruction: getFallbackReplayInstruction(event, elementDescription),
331
+ actionSummary: getFallbackActionSummary(event, elementDescription),
332
+ confidence: 'low',
333
+ error
334
+ },
335
+ screenshotWithBox: screenshotWithBox || event.screenshotWithBox
336
+ };
337
+ }
338
+ async function describeRecorderUIEvent(input, modelConfig, options = {}) {
339
+ const event = input.event;
340
+ const rect = getRecorderUIEventTargetRect(event);
341
+ const screenshot = getRecorderEventScreenshot(event);
342
+ if (!rect || !screenshot) {
343
+ const error = rect ? 'Recorder event has no screenshot.' : 'Recorder event has no target rectangle.';
344
+ return {
345
+ usedFallback: true,
346
+ event: createFallbackEvent(event, error, void 0, input.target)
347
+ };
348
+ }
349
+ let screenshotWithBox;
350
+ try {
351
+ const resolvedModelConfig = resolveRecorderModelConfig(modelConfig);
352
+ screenshotWithBox = await createScreenshotWithBox(event, rect);
353
+ const semanticFields = await describeWithRetry(event, input.target, screenshotWithBox || screenshot, resolvedModelConfig, {
354
+ maxRetries: options.maxRetries ?? RECORDER_UI_DESCRIBER_DEFAULT_RETRIES,
355
+ retryDelayMs: options.retryDelayMs ?? RECORDER_UI_DESCRIBER_DEFAULT_RETRY_DELAY_MS
356
+ });
357
+ return {
358
+ usedFallback: false,
359
+ event: {
360
+ ...event,
361
+ semantic: semanticFields,
362
+ screenshotWithBox: screenshotWithBox || event.screenshotWithBox
363
+ }
364
+ };
365
+ } catch (error) {
366
+ const message = error instanceof Error ? error.message : String(error);
367
+ return {
368
+ usedFallback: true,
369
+ error: message,
370
+ event: createFallbackEvent(event, message, screenshotWithBox, input.target)
371
+ };
372
+ }
373
+ }
374
+ async function describeRecorderUIEvents(inputs, modelConfig, options = {}) {
375
+ const concurrency = Math.max(1, options.concurrency ?? RECORDER_UI_DESCRIBER_DEFAULT_CONCURRENCY);
376
+ const results = new Array(inputs.length);
377
+ let cursor = 0;
378
+ async function worker() {
379
+ while(cursor < inputs.length){
380
+ const index = cursor;
381
+ cursor += 1;
382
+ results[index] = await describeRecorderUIEvent(inputs[index], modelConfig, options);
383
+ }
384
+ }
385
+ await Promise.all(Array.from({
386
+ length: Math.min(concurrency, inputs.length)
387
+ }, ()=>worker()));
388
+ return results;
389
+ }
390
+ export { describeRecorderUIEvent, describeRecorderUIEvents, getRecorderUIEventTargetRect };
391
+
392
+ //# sourceMappingURL=recorder-ui-describer.mjs.map