@ui-tars-test/cli 0.3.18 → 0.3.20
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.
- package/dist/cli/start.js +21 -2
- package/dist/cli/start.js.map +1 -1
- package/dist/cli/start.mjs +21 -2
- package/dist/cli/start.mjs.map +1 -1
- package/dist/src/cli/start.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/cli/start.js
CHANGED
|
@@ -59,6 +59,16 @@ var external_js_yaml_default = /*#__PURE__*/ __webpack_require__.n(external_js_y
|
|
|
59
59
|
const operator_nutjs_namespaceObject = require("@ui-tars-test/operator-nutjs");
|
|
60
60
|
const operator_adb_namespaceObject = require("@ui-tars-test/operator-adb");
|
|
61
61
|
const operator_browser_namespaceObject = require("@ui-tars-test/operator-browser");
|
|
62
|
+
class ExposedNutJSOperator extends operator_nutjs_namespaceObject.NutJSOperator {
|
|
63
|
+
async getScreenResolution() {
|
|
64
|
+
await this.initialize();
|
|
65
|
+
const ctx = this.screenContext();
|
|
66
|
+
return {
|
|
67
|
+
width: ctx.screenWidth,
|
|
68
|
+
height: ctx.screenHeight
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
}
|
|
62
72
|
const saveConversationLog = (events, targetOutputDir, sessionId)=>{
|
|
63
73
|
const logPath = external_node_path_default().join(targetOutputDir, `${sessionId}.md`);
|
|
64
74
|
let content = `# Conversation Log - ${sessionId}\n\n`;
|
|
@@ -298,6 +308,7 @@ const start = async (options)=>{
|
|
|
298
308
|
else console.warn('[CLI] Preflight check error:', e);
|
|
299
309
|
}
|
|
300
310
|
let targetOperator = null;
|
|
311
|
+
let screenResolutionInfo = '';
|
|
301
312
|
const targetType = options.target || await prompts_namespaceObject.select({
|
|
302
313
|
message: 'Please select your operator target:',
|
|
303
314
|
options: [
|
|
@@ -328,7 +339,15 @@ const start = async (options)=>{
|
|
|
328
339
|
break;
|
|
329
340
|
case 'computer':
|
|
330
341
|
default:
|
|
331
|
-
|
|
342
|
+
const op = new ExposedNutJSOperator();
|
|
343
|
+
try {
|
|
344
|
+
const { width, height } = await op.getScreenResolution();
|
|
345
|
+
screenResolutionInfo = `Current screen resolution: ${width}x${height}. Please output absolute coordinates based on this resolution. `;
|
|
346
|
+
console.log(`[CLI] Detected screen resolution: ${width}x${height}`);
|
|
347
|
+
} catch (e) {
|
|
348
|
+
console.warn('[CLI] Failed to get screen resolution:', e);
|
|
349
|
+
}
|
|
350
|
+
targetOperator = op;
|
|
332
351
|
break;
|
|
333
352
|
}
|
|
334
353
|
const useTasksFile = Boolean(options.tasks);
|
|
@@ -351,7 +370,7 @@ const start = async (options)=>{
|
|
|
351
370
|
abortController.abort();
|
|
352
371
|
});
|
|
353
372
|
const systemPrompts = [
|
|
354
|
-
|
|
373
|
+
`${screenResolutionInfo}You are provided with a task description, a history of previous actions, and corresponding screenshots. Your goal is to perform the next action to complete the task. Please note that if performing the same action multiple times results in a static screen with no changes, you should attempt a modified or alternative action.`,
|
|
355
374
|
'## Function Definition\n\n- You have access to the following functions:\n{"type": "function", "name": "call_user", "parameters": {"type": "object", "properties": {"content": {"type": "string", "description": "Message or information displayed to the user to request their input, feedback, or guidance."}}, "required": []}, "description": "This function is used to interact with the user by displaying a message and requesting their input, feedback, or guidance."}\n{"type": "function", "name": "click", "parameters": {"type": "object", "properties": {"point": {"type": "string", "description": "Click coordinates. The format is: <point>x y</point>"}}, "required": ["point"]}, "description": "Mouse left single click action."}\n{"type": "function", "name": "drag", "parameters": {"type": "object", "properties": {"start_point": {"type": "string", "description": "Drag start point. The format is: <point>x y</point>"}, "end_point": {"type": "string", "description": "Drag end point. The format is: <point>x y</point>"}}, "required": ["start_point", "end_point"]}, "description": "Mouse left button drag action."}\n{"type": "function", "name": "finished", "parameters": {"type": "object", "properties": {"content": {"type": "string", "description": "Provide the final answer or response to complete the task."}}, "required": []}, "description": "This function is used to indicate the completion of a task by providing the final answer or response."}\n{"type": "function", "name": "hotkey", "parameters": {"type": "object", "properties": {"key": {"type": "string", "description": "Hotkeys you want to press. Split keys with a space and use lowercase."}}, "required": ["key"]}, "description": "Press hotkey."}\n{"type": "function", "function": {"name": "infeasible", "parameters": {"type": "object", "properties": {"content": {"type": "string", "description": "Message or information displayed to the user to explain why the current task is infeasible."}}, "required": ["content"]}, "description": "This function is used to indicate that the current task is infeasible thus agent ends the task."}\n{"type": "function", "name": "left_double", "parameters": {"type": "object", "properties": {"point": {"type": "string", "description": "Click coordinates. The format is: <point>x y</point>"}}, "required": ["point"]}, "description": "Mouse left double click action."}\n{"type": "function", "name": "right_single", "parameters": {"type": "object", "properties": {"point": {"type": "string", "description": "Click coordinates. The format is: <point>x y</point>"}}, "required": ["point"]}, "description": "Mouse right single click action."}\n{"type": "function", "name": "scroll", "parameters": {"type": "object", "properties": {"point": {"type": "string", "description": "Scroll start position. If not specified, default to execute on the current mouse position. The format is: <point>x y</point>"}, "direction": {"type": "string", "description": "Scroll direction.", "enum": ["up", "down", "left", "right"]}}, "required": ["direction", "point"]}, "description": "Scroll action."}\n{"type": "function", "name": "type", "parameters": {"type": "object", "properties": {"content": {"type": "string", "description": "Type content. If you want to submit your input, use \\n at the end of content."}}, "required": ["content"]}, "description": "Type content."}\n{"type": "function", "name": "wait", "parameters": {"type": "object", "properties": {"time": {"type": "integer", "description": "Wait time in seconds."}}, "required": []}, "description": "Wait for a while."}\n\n- To call a function, use the following structure without any suffix:\n\n<think_never_used_51bce0c785ca2f68081bfa7d91973934> reasoning process </think_never_used_51bce0c785ca2f68081bfa7d91973934>\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_name><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\n\n## Important Notes\n- Function calls must begin with <function_never_used_51bce0c785ca2f68081bfa7d91973934= and end with </function_never_used_51bce0c785ca2f68081bfa7d91973934>.\n- All required parameters must be explicitly provided.\n\n## Additional Notes\n- You can execute multiple actions within a single tool call. For example:\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_1><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_2><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_3>value_4</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\n- 当你判断任务请求是无法执行的时候,你应该调用Infeasible工具结束任务并解释原因。\n 判断标准:当一个请求符合以下任何一条标准时,应被归类为“无法执行”。\n 1. 技术/物理层面的矛盾: 指令本身包含逻辑上或物理上无法实现的要求。\n 2. 工具/功能错配: 指令要求在一个软件中执行另一个软件的功能,或者执行该软件根本不具备的功能。\n 3. 超出操作边界/范围: 指令要求执行的操作超出了当前用户会话、权限或应用程序的逻辑边界,涉及未告知的隐私信息或者未授权的操作。\n 4. 依赖隐性知识或外部条件: 任务的完成依赖于Agent无法获取的外部硬件、物理环境、未声明的插件/扩展、或特定的文件/数据。\n\n 输出指令:\n 如果请求被判断为“无法执行”,你应该向用户解释为什么这个任务超出了你的能力范围(例如,指出它需要直接操作某个硬件),并尽可能提供一个指导性的替代方案,让用户可以自己完成该任务。\n 你应该非常非常谨慎地使用Infeasible工具,因为它会直接结束任务并降低用户体验。所以非必要的时候,你不应该调用Infeasible工具,尽量以finish工具结束任务并向用户提示原因就好。'
|
|
356
375
|
];
|
|
357
376
|
const guiAgent = new agent_sdk_namespaceObject.GUIAgent({
|
package/dist/cli/start.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli/start.js","sources":["webpack://@ui-tars-test/cli/webpack/runtime/compat_get_default_export","webpack://@ui-tars-test/cli/webpack/runtime/define_property_getters","webpack://@ui-tars-test/cli/webpack/runtime/has_own_property","webpack://@ui-tars-test/cli/webpack/runtime/make_namespace_object","webpack://@ui-tars-test/cli/./src/cli/start.ts"],"sourcesContent":["// getDefaultExport function for compatibility with non-ESM modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};\n","__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};","/*\n * Copyright (c) 2025 Bytedance, Inc. and its affiliates.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport os from 'node:os';\nimport ffmpeg from 'fluent-ffmpeg';\n// @ts-ignore\nimport ffmpegStatic from 'ffmpeg-static';\n\nimport fetch from 'node-fetch';\nimport { GUIAgent } from '@ui-tars-test/agent-sdk';\nimport * as p from '@clack/prompts';\nimport yaml from 'js-yaml';\n\nimport { NutJSOperator } from '@ui-tars-test/operator-nutjs';\nimport { AdbOperator } from '@ui-tars-test/operator-adb';\nimport { BrowserOperator } from '@ui-tars-test/operator-browser';\n\nexport interface CliOptions {\n presets?: string;\n target?: string;\n query?: string;\n config?: string;\n output?: string;\n tasks?: string;\n maxLoopCount?: string;\n}\n\nconst saveConversationLog = (events: any[], targetOutputDir: string, sessionId: string) => {\n const logPath = path.join(targetOutputDir, `${sessionId}.md`);\n let content = `# Conversation Log - ${sessionId}\\n\\n`;\n\n events.forEach((e) => {\n const time = new Date(e.timestamp || Date.now()).toISOString();\n content += `## [${time}] ${e.type}\\n`;\n\n // Debug raw event structure in console to identify correct fields\n // console.log(`[DEBUG] Event type: ${e.type}`, JSON.stringify(e, null, 2));\n\n if (e.content) {\n if (Array.isArray(e.content)) {\n e.content.forEach((part: any) => {\n if (part.type === 'text') content += `${part.text}\\n`;\n if (part.type === 'image_url') content += `[Image Content]\\n`;\n });\n } else if (typeof e.content === 'string') {\n content += `${e.content}\\n`;\n } else {\n content += `\\`\\`\\`json\\n${JSON.stringify(e.content, null, 2)}\\n\\`\\`\\`\\n`;\n }\n }\n\n // Check specific event types based on observation\n // It seems 'tool_call' and 'assistant_message' might store data differently than expected\n // Let's try to be more permissive in finding the content\n\n if (e.type === 'tool_call') {\n // Based on ToolCallEvent interface in agent-event-stream.ts\n // It has 'name' and 'arguments' properties directly\n if (e.name) content += `> Tool Call: ${e.name}\\n`;\n if (e.arguments) content += `> Arguments: ${JSON.stringify(e.arguments, null, 2)}\\n`;\n\n // Fallback if it's nested in toolCall property\n const toolCall = e.toolCall;\n if (toolCall) {\n if (toolCall.name) content += `> Tool Call: ${toolCall.name}\\n`;\n if (toolCall.arguments)\n content += `> Arguments: ${JSON.stringify(toolCall.arguments, null, 2)}\\n`;\n }\n } else if (e.type === 'assistant_message') {\n // Based on AssistantMessageEvent interface in agent-event-stream.ts\n // It has 'content' and 'toolCalls' properties directly\n if (e.content) content += `${e.content}\\n`;\n if (e.rawContent) content += `\\n> Raw Content (Debug): ${JSON.stringify(e.rawContent)}\\n`;\n if (e.toolCalls) content += `> Tool Calls: ${JSON.stringify(e.toolCalls, null, 2)}\\n`;\n\n // Fallback if it's nested in message property\n const message = e.message;\n if (message) {\n if (message.content) content += `${message.content}\\n`;\n if (message.rawContent)\n content += `\\n> Raw Content (Debug): ${JSON.stringify(message.rawContent)}\\n`;\n if (message.tool_calls)\n content += `> Tool Calls: ${JSON.stringify(message.tool_calls, null, 2)}\\n`;\n }\n }\n\n if (e.metadata) {\n // Avoid printing large metadata like screenshots if they are embedded there (usually they are in content or separate)\n // For screenshot events, metadata might contain type='screenshot'\n if (e.metadata.type === 'screenshot') {\n content += `> Action: Screenshot captured\\n`;\n } else {\n content += `> Metadata: ${JSON.stringify(e.metadata)}\\n`;\n }\n }\n\n if (e.input) {\n content += `> Input: ${JSON.stringify(e.input, null, 2)}\\n`;\n }\n\n if (e.output) {\n content += `> Output: ${JSON.stringify(e.output, null, 2)}\\n`;\n }\n\n content += '\\n';\n });\n\n try {\n fs.writeFileSync(logPath, content);\n console.log(`[CLI] Conversation log saved: ${logPath}`);\n return logPath;\n } catch (err) {\n console.warn(`[CLI] Failed to save conversation log: ${err}`);\n return null;\n }\n};\n\nexport const start = async (options: CliOptions) => {\n if (ffmpegStatic) {\n let finalFfmpegPath = ffmpegStatic;\n // In production build (bundled), ffmpeg-static might return a path that doesn't exist\n // because it relies on __dirname which changes after bundling.\n // However, we copy the binary to the dist folder in post-build script.\n // We should check if we are running from the bundled version.\n const bundledFfmpegPath = path.join(__dirname, 'ffmpeg');\n if (fs.existsSync(bundledFfmpegPath)) {\n finalFfmpegPath = bundledFfmpegPath;\n console.log(`[CLI] Using bundled ffmpeg: ${finalFfmpegPath}`);\n } else {\n console.log(`[CLI] Using default ffmpeg-static path: ${finalFfmpegPath}`);\n }\n\n if (os.platform() === 'darwin' && os.arch() === 'arm64') {\n console.log(`[CLI] Setting ffmpeg path: ${finalFfmpegPath}`);\n }\n ffmpeg.setFfmpegPath(finalFfmpegPath);\n } else {\n console.warn(\n '[CLI] ffmpeg-static not found. Video generation might fail if ffmpeg is not in PATH.',\n );\n }\n\n const CONFIG_PATH = options.config || path.join(os.homedir(), '.gui-agent-cli.json');\n\n // read config file\n let config = {\n baseURL: '',\n apiKey: '', // secretlint-disable-line\n model: '',\n provider: 'openai', // Default provider\n useResponsesApi: false,\n maxLoopCount: options.maxLoopCount ? Number(options.maxLoopCount) : 1000,\n };\n\n if (options.presets) {\n const response = await fetch(options.presets);\n if (!response.ok) {\n throw new Error(`Failed to fetch preset: ${response.status}`);\n }\n\n const yamlText = await response.text();\n const preset = yaml.load(yamlText) as any;\n\n config.apiKey = preset?.vlmApiKey; // secretlint-disable-line\n config.baseURL = preset?.vlmBaseUrl;\n config.model = preset?.vlmModelName;\n config.useResponsesApi = preset?.useResponsesApi ?? false;\n } else if (fs.existsSync(CONFIG_PATH)) {\n try {\n config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));\n } catch (error) {\n console.warn('read config file failed', error);\n }\n }\n\n if (!config.baseURL || !config.apiKey || !config.model) {\n const configAnswers = await p.group(\n {\n provider: () =>\n p.select({\n message: 'Select model provider:',\n options: [\n { value: 'volcengine', label: 'VolcEngine' },\n { value: 'azure-openai', label: 'Azure OpenAI' },\n { value: 'anthropic', label: 'Anthropic Claude' },\n { value: 'openai', label: 'OpenAI' },\n { value: 'lm-studio', label: 'LM Studio' },\n { value: 'deepseek', label: 'DeepSeek' },\n { value: 'ollama', label: 'Ollama' },\n ],\n }),\n baseURL: () => p.text({ message: 'please input vlm model baseURL:' }),\n apiKey: () => p.text({ message: 'please input vlm model apiKey:' }), // secretlint-disable-line\n model: () => p.text({ message: 'please input vlm model name:' }),\n },\n {\n onCancel: () => {\n p.cancel('operation cancelled');\n process.exit(0);\n },\n },\n );\n\n config = { ...config, ...configAnswers };\n\n if (config.provider === 'azure-openai') {\n // Ensure azure config object exists\n if (!(config as any).azure) {\n (config as any).azure = {};\n }\n\n // Auto-populate azure.endpoint from baseURL if not present\n // This is crucial for our custom fetch interceptor in llm-client to work\n if (!(config as any).azure.endpoint && config.baseURL) {\n (config as any).azure.endpoint = config.baseURL;\n }\n\n if (!(config as any).azure?.apiVersion) {\n const azureConfig = await p.group(\n {\n apiVersion: () =>\n p.text({\n message: 'please input azure api version (optional, default: 2024-10-01-preview):',\n }),\n // Add prompt for X-TT-LOGID which is required for some internal gateways\n logId: () =>\n p.text({\n message: 'please input X-TT-LOGID (optional, for internal gateway):',\n }),\n },\n {\n onCancel: () => {\n p.cancel('operation cancelled');\n process.exit(0);\n },\n },\n );\n\n if (azureConfig.apiVersion) {\n (config as any).azure.apiVersion = azureConfig.apiVersion;\n }\n\n if (azureConfig.logId) {\n if (!(config as any).headers) {\n (config as any).headers = {};\n }\n (config as any).headers['X-TT-LOGID'] = azureConfig.logId;\n }\n }\n }\n\n // save config to file\n try {\n fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));\n console.log('model config file saved to:', CONFIG_PATH);\n } catch (error) {\n console.error('save model config file failed', error);\n }\n }\n\n // Diagnostic: print model config loaded\n try {\n const maskedKey = config.apiKey\n ? `${config.apiKey.slice(0, 6)}...${config.apiKey.slice(-4)}`\n : '(empty)';\n console.log('[CLI] Loaded model config:');\n console.log(` provider: ${config.provider}`);\n console.log(` baseURL: ${config.baseURL}`);\n console.log(` model: ${config.model}`);\n console.log(` apiKey: ${maskedKey}`); // secretlint-disable-line\n console.log(` useResponsesApi: ${Boolean((config as any).useResponsesApi)}`);\n } catch (e) {\n console.warn('[CLI] Failed to print model config diagnostics:', e);\n }\n\n // Basic baseURL validation and hints for OpenAI-compatible servers\n try {\n if (config.baseURL) {\n let parsed: URL | null = null;\n try {\n parsed = new URL(config.baseURL);\n } catch (_) {\n console.warn('[CLI] Warning: baseURL is not a valid URL:', config.baseURL);\n }\n if (parsed) {\n const endsWithV1 = /\\/v1\\/?$/.test(parsed.pathname);\n if (!endsWithV1) {\n console.warn(\n '[CLI] Hint: OpenAI-compatible endpoints typically end with \"/v1\" (e.g. https://host/v1).',\n );\n }\n if (parsed.protocol !== 'https:') {\n console.warn('[CLI] Hint: use HTTPS for most providers. Current:', parsed.protocol);\n }\n }\n }\n } catch (e) {\n console.warn('[CLI] baseURL validation failed:', e);\n }\n\n // Preflight: check Chat Completions non-streaming response shape for OpenAI-compatible servers\n try {\n if (config.provider === 'openai' && config.baseURL && config.model) {\n const url = new URL(config.baseURL.replace(/\\/$/, ''));\n url.pathname = url.pathname.replace(/\\/$/, '') + '/chat/completions';\n console.log('[CLI] Preflight: POST', url.toString());\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 16000);\n const resp = await fetch(url.toString(), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n },\n body: JSON.stringify({\n model: config.model,\n messages: [{ role: 'user', content: 'ping' }],\n stream: false,\n }),\n signal: controller.signal,\n } as any);\n clearTimeout(timeout);\n const text = await resp.text();\n if (!resp.ok) {\n console.warn('[CLI] Preflight failed:', resp.status, resp.statusText);\n console.warn('[CLI] Preflight response body:', text.slice(0, 500));\n } else {\n try {\n const json = JSON.parse(text);\n const hasChoices = Array.isArray(json?.choices) && json.choices.length > 0;\n console.log('[CLI] Preflight ok. choices[0] exists:', hasChoices);\n if (!hasChoices) {\n console.warn(\n '[CLI] Preflight: response does not contain choices[]. Service may not implement Chat Completions.',\n );\n }\n } catch (_) {\n console.warn('[CLI] Preflight ok but response is not JSON:', text.slice(0, 200));\n }\n }\n }\n } catch (e: any) {\n if (e?.name === 'AbortError') {\n console.warn('[CLI] Preflight check timed out (16s). Proceeding without preflight.');\n } else {\n console.warn('[CLI] Preflight check error:', e);\n }\n }\n\n let targetOperator = null;\n const targetType =\n options.target ||\n ((await p.select({\n message: 'Please select your operator target:',\n options: [\n { value: 'computer', label: 'computer (Desktop automation)' },\n { value: 'android', label: 'android (Android automation)' },\n { value: 'browser', label: 'browser (Web automation)' },\n ],\n })) as string);\n\n switch (targetType) {\n case 'android':\n // Note: AdbOperator will auto-detect connected devices\n console.log('Initializing ADB operator...');\n targetOperator = new AdbOperator();\n break;\n case 'browser':\n // Use default browser options\n targetOperator = new BrowserOperator({\n browserType: 'chrome' as any,\n browser: null as any, // Will be initialized internally\n });\n break;\n case 'computer':\n default:\n targetOperator = new NutJSOperator();\n break;\n }\n\n const useTasksFile = Boolean(options.tasks);\n const answers = useTasksFile\n ? { instruction: '' }\n : options.query\n ? { instruction: options.query }\n : await p.group(\n {\n instruction: () => p.text({ message: 'Input your instruction' }),\n },\n {\n onCancel: () => {\n p.cancel('操作已取消');\n process.exit(0);\n },\n },\n );\n\n const abortController = new AbortController();\n process.on('SIGINT', () => {\n abortController.abort();\n });\n\n const systemPrompts = [\n 'You are provided with a task description, a history of previous actions, and corresponding screenshots. Your goal is to perform the next action to complete the task. Please note that if performing the same action multiple times results in a static screen with no changes, you should attempt a modified or alternative action.',\n '## Function Definition\\n\\n- You have access to the following functions:\\n{\"type\": \"function\", \"name\": \"call_user\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Message or information displayed to the user to request their input, feedback, or guidance.\"}}, \"required\": []}, \"description\": \"This function is used to interact with the user by displaying a message and requesting their input, feedback, or guidance.\"}\\n{\"type\": \"function\", \"name\": \"click\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse left single click action.\"}\\n{\"type\": \"function\", \"name\": \"drag\", \"parameters\": {\"type\": \"object\", \"properties\": {\"start_point\": {\"type\": \"string\", \"description\": \"Drag start point. The format is: <point>x y</point>\"}, \"end_point\": {\"type\": \"string\", \"description\": \"Drag end point. The format is: <point>x y</point>\"}}, \"required\": [\"start_point\", \"end_point\"]}, \"description\": \"Mouse left button drag action.\"}\\n{\"type\": \"function\", \"name\": \"finished\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Provide the final answer or response to complete the task.\"}}, \"required\": []}, \"description\": \"This function is used to indicate the completion of a task by providing the final answer or response.\"}\\n{\"type\": \"function\", \"name\": \"hotkey\", \"parameters\": {\"type\": \"object\", \"properties\": {\"key\": {\"type\": \"string\", \"description\": \"Hotkeys you want to press. Split keys with a space and use lowercase.\"}}, \"required\": [\"key\"]}, \"description\": \"Press hotkey.\"}\\n{\"type\": \"function\", \"function\": {\"name\": \"infeasible\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Message or information displayed to the user to explain why the current task is infeasible.\"}}, \"required\": [\"content\"]}, \"description\": \"This function is used to indicate that the current task is infeasible thus agent ends the task.\"}\\n{\"type\": \"function\", \"name\": \"left_double\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse left double click action.\"}\\n{\"type\": \"function\", \"name\": \"right_single\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse right single click action.\"}\\n{\"type\": \"function\", \"name\": \"scroll\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Scroll start position. If not specified, default to execute on the current mouse position. The format is: <point>x y</point>\"}, \"direction\": {\"type\": \"string\", \"description\": \"Scroll direction.\", \"enum\": [\"up\", \"down\", \"left\", \"right\"]}}, \"required\": [\"direction\", \"point\"]}, \"description\": \"Scroll action.\"}\\n{\"type\": \"function\", \"name\": \"type\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Type content. If you want to submit your input, use \\\\n at the end of content.\"}}, \"required\": [\"content\"]}, \"description\": \"Type content.\"}\\n{\"type\": \"function\", \"name\": \"wait\", \"parameters\": {\"type\": \"object\", \"properties\": {\"time\": {\"type\": \"integer\", \"description\": \"Wait time in seconds.\"}}, \"required\": []}, \"description\": \"Wait for a while.\"}\\n\\n- To call a function, use the following structure without any suffix:\\n\\n<think_never_used_51bce0c785ca2f68081bfa7d91973934> reasoning process </think_never_used_51bce0c785ca2f68081bfa7d91973934>\\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_name><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\\n\\n## Important Notes\\n- Function calls must begin with <function_never_used_51bce0c785ca2f68081bfa7d91973934= and end with </function_never_used_51bce0c785ca2f68081bfa7d91973934>.\\n- All required parameters must be explicitly provided.\\n\\n## Additional Notes\\n- You can execute multiple actions within a single tool call. For example:\\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_1><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_2><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_3>value_4</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\\n- 当你判断任务请求是无法执行的时候,你应该调用Infeasible工具结束任务并解释原因。\\n 判断标准:当一个请求符合以下任何一条标准时,应被归类为“无法执行”。\\n 1. 技术/物理层面的矛盾: 指令本身包含逻辑上或物理上无法实现的要求。\\n 2. 工具/功能错配: 指令要求在一个软件中执行另一个软件的功能,或者执行该软件根本不具备的功能。\\n 3. 超出操作边界/范围: 指令要求执行的操作超出了当前用户会话、权限或应用程序的逻辑边界,涉及未告知的隐私信息或者未授权的操作。\\n 4. 依赖隐性知识或外部条件: 任务的完成依赖于Agent无法获取的外部硬件、物理环境、未声明的插件/扩展、或特定的文件/数据。\\n\\n 输出指令:\\n 如果请求被判断为“无法执行”,你应该向用户解释为什么这个任务超出了你的能力范围(例如,指出它需要直接操作某个硬件),并尽可能提供一个指导性的替代方案,让用户可以自己完成该任务。\\n 你应该非常非常谨慎地使用Infeasible工具,因为它会直接结束任务并降低用户体验。所以非必要的时候,你不应该调用Infeasible工具,尽量以finish工具结束任务并向用户提示原因就好。',\n ];\n\n const guiAgent = new GUIAgent({\n model: {\n id: config.model,\n provider: config.provider as any, // Type assertion to avoid TypeScript error\n baseURL: config.baseURL,\n apiKey: config.apiKey, // secretlint-disable-line\n azure: (config as any).azure,\n headers: (config as any).headers || (config as any).defaultHeaders,\n } as any,\n operator: targetOperator,\n systemPrompt: systemPrompts.join('\\n\\n'),\n });\n\n if (useTasksFile) {\n const demoDir = path.resolve(path.join(__dirname, '..', '..', 'demo'));\n const tasksPath =\n options.tasks === 'demo' ? path.join(demoDir, 'tasks.json') : path.resolve(options.tasks!);\n try {\n const dirOfTasks = path.dirname(tasksPath);\n fs.mkdirSync(dirOfTasks, { recursive: true });\n if (!fs.existsSync(tasksPath)) {\n const sample = [\n { taskId: 'task-1', query: 'Open Chrome and go to github.com' },\n { taskId: 'task-2', query: \"Search for 'GUI Agent automation' on Google\" },\n ];\n fs.writeFileSync(tasksPath, JSON.stringify(sample, null, 2));\n console.log(`[CLI] Sample tasks.json created: ${tasksPath}`);\n }\n } catch (e) {\n console.warn('[CLI] Failed to prepare tasks file directory', e);\n }\n\n let tasks: Array<{ taskId: string; query: string; timeout?: number }> = [];\n try {\n const raw = fs.readFileSync(tasksPath, 'utf-8');\n const parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) tasks = parsed;\n else console.warn('[CLI] tasks file is not an array');\n } catch (e) {\n console.error('[CLI] Failed to read tasks file', e);\n process.exit(1);\n }\n\n const targetOutputDir = options.output\n ? path.resolve(options.output)\n : options.tasks === 'demo'\n ? path.join(demoDir, 'results')\n : path.join(os.homedir(), '.gui-agent-results');\n console.log(`[CLI] Output directory (resolved): ${targetOutputDir}`);\n fs.mkdirSync(targetOutputDir, { recursive: true });\n\n for (const task of tasks) {\n const taskAC = new AbortController();\n const timeoutMs = task.timeout ?? 25 * 60 * 1000;\n const timeoutId = setTimeout(() => {\n console.log(`[CLI] Task ${task.taskId} timed out after ${timeoutMs}ms`);\n taskAC.abort();\n }, timeoutMs);\n\n const onGlobalAbort = () => taskAC.abort();\n abortController.signal.addEventListener('abort', onGlobalAbort);\n\n const taskAgent = new GUIAgent({\n model: {\n id: config.model,\n provider: config.provider as any, // Type assertion to avoid TypeScript error\n baseURL: config.baseURL,\n apiKey: config.apiKey, // secretlint-disable-line\n azure: (config as any).azure,\n headers: (config as any).headers || (config as any).defaultHeaders,\n } as any,\n operator: targetOperator,\n systemPrompt: systemPrompts.join('\\n\\n'),\n // @ts-ignore\n signal: taskAC.signal,\n });\n\n let resultEvent: any;\n const startTime = Date.now();\n\n try {\n console.log(`[CLI] Starting task: ${task.taskId} at ${new Date(startTime).toISOString()}`);\n resultEvent = await taskAgent.run(task.query);\n } catch (taskErr: any) {\n if (taskAC.signal.aborted) {\n console.warn(`[CLI] Task ${task.taskId} was aborted (Timeout or SIGINT).`);\n resultEvent = { content: 'Task aborted or timed out' };\n } else {\n console.error(`[CLI] Task failed: ${task.taskId}`, taskErr);\n resultEvent = { content: `Error: ${taskErr.message}` };\n }\n } finally {\n clearTimeout(timeoutId);\n abortController.signal.removeEventListener('abort', onGlobalAbort);\n }\n\n try {\n const endTime = Date.now();\n const duration = endTime - startTime;\n\n const eventStream = taskAgent.getEventStream();\n const allEvents = eventStream.getEvents();\n const runStartEvents = allEvents.filter((e: any) => e.type === 'agent_run_start');\n const lastRunStart = runStartEvents[runStartEvents.length - 1] as any;\n const startIndex = allEvents.findIndex((e: any) => e.id === lastRunStart?.id);\n const endIndex = allEvents.findIndex(\n (e: any, idx: number) => idx > startIndex && e.type === 'agent_run_end',\n );\n const rangeEvents =\n startIndex >= 0\n ? endIndex >= 0\n ? allEvents.slice(startIndex, endIndex + 1)\n : allEvents.slice(startIndex)\n : allEvents;\n const envEvents = rangeEvents.filter((e: any) => e.type === 'environment_input');\n const screenshotEvents = envEvents.filter(\n (e: any) => e.metadata && e.metadata.type === 'screenshot',\n );\n\n // Generate video recording from screenshots\n let videoPath = '';\n if (screenshotEvents.length > 0) {\n const tempDir = path.join(os.tmpdir(), 'gui-agent-rec', task.taskId);\n try {\n fs.mkdirSync(tempDir, { recursive: true });\n\n const validFrames: { file: string; timestamp: number }[] = [];\n let frameCount = 0;\n for (const event of screenshotEvents) {\n if (Array.isArray((event as any).content)) {\n const imgPart = ((event as any).content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n if (buffer.length > 0) {\n const extension =\n buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff\n ? 'jpg'\n : 'png';\n const fileName = `${String(frameCount).padStart(4, '0')}.${extension}`;\n const framePath = path.join(tempDir, fileName);\n fs.writeFileSync(framePath, buffer);\n validFrames.push({\n file: fileName,\n timestamp: (event as any).timestamp || Date.now(),\n });\n frameCount++;\n }\n }\n }\n }\n\n if (validFrames.length > 0) {\n const concatFilePath = path.join(tempDir, 'filelist.txt');\n let fileContent = '';\n const hasTimestamps = validFrames.some(\n (f, i) => i > 0 && f.timestamp !== validFrames[0].timestamp,\n );\n\n for (let i = 0; i < validFrames.length; i++) {\n const frame = validFrames[i];\n let duration = 1.0;\n if (hasTimestamps && i < validFrames.length - 1) {\n const diff = (validFrames[i + 1].timestamp - frame.timestamp) / 1000;\n if (diff > 0.1 && diff < 60) duration = diff;\n } else if (i === validFrames.length - 1) {\n duration = 2.0;\n }\n fileContent += `file '${frame.file}'\\n`;\n fileContent += `duration ${duration.toFixed(3)}\\n`;\n }\n if (validFrames.length > 0) {\n fileContent += `file '${validFrames[validFrames.length - 1].file}'\\n`;\n }\n fs.writeFileSync(concatFilePath, fileContent);\n\n const outputVideoPath = path.join(targetOutputDir, `${task.taskId}.mp4`);\n console.log(`[CLI] Generating video recording: ${outputVideoPath}`);\n\n await new Promise<void>((resolve, reject) => {\n ffmpeg()\n .input(concatFilePath)\n .inputOptions(['-f', 'concat', '-safe', '0'])\n .output(outputVideoPath)\n .outputOptions([\n '-c:v',\n 'libx264',\n '-pix_fmt',\n 'yuv420p',\n // scale needs to be even numbers for libx264\n '-vf',\n 'scale=trunc(iw/2)*2:trunc(ih/2)*2',\n ])\n .on('start', (cmd) => console.log(`[CLI] Ffmpeg command: ${cmd}`))\n .on('stderr', (line) => console.log(`[CLI] Ffmpeg stderr: ${line}`))\n .on('end', () => resolve())\n .on('error', (err: any) => {\n console.error('[CLI] Ffmpeg error:', err);\n reject(err);\n })\n .run();\n });\n\n videoPath = outputVideoPath;\n console.log(`[CLI] Video saved: ${videoPath}`);\n }\n } catch (recErr) {\n console.warn('[CLI] Failed to generate video recording', recErr);\n } finally {\n // Cleanup temp dir\n try {\n fs.rmSync(tempDir, { recursive: true, force: true });\n } catch (_) {\n /* ignore */\n }\n }\n }\n\n const lastScreenshot =\n screenshotEvents.length > 0\n ? (screenshotEvents[screenshotEvents.length - 1] as any)\n : null;\n\n let resultPicPath = '';\n if (lastScreenshot && Array.isArray(lastScreenshot.content)) {\n const imgPart = (lastScreenshot.content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n resultPicPath = path.join(targetOutputDir, `${task.taskId}.png`);\n fs.writeFileSync(resultPicPath, buffer);\n console.log(`[CLI] Screenshot saved: ${resultPicPath}`);\n }\n }\n if (!resultPicPath) {\n console.log('[CLI] No screenshot captured; resultPic will be empty.');\n }\n\n const conversationLogPath = saveConversationLog(rangeEvents, targetOutputDir, task.taskId);\n\n const finalAnswer = (resultEvent as any)?.content ?? '';\n const report = {\n taskId: task.taskId,\n taskContent: task.query,\n startTime,\n endTime,\n duration,\n resultPic: resultPicPath,\n video: videoPath || null,\n conversationLog: conversationLogPath,\n finalAnswer,\n };\n const reportPath = path.join(targetOutputDir, `${task.taskId}.json`);\n fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));\n console.log(`Result saved: ${reportPath}`);\n console.log(`[CLI] Report JSON path: ${reportPath}`);\n } catch (reportErr) {\n console.warn(`[CLI] Failed to save report for task ${task.taskId}`, reportErr);\n }\n }\n return;\n }\n\n // Enhanced error logging around agent run\n let resultEvent: any;\n const startTime = Date.now();\n let isReportSaved = false;\n\n const saveSingleTaskReport = async (finalAnswer: string) => {\n if (isReportSaved) return;\n isReportSaved = true;\n\n const endTime = Date.now();\n const duration = endTime - startTime;\n\n try {\n const eventStream = guiAgent.getEventStream();\n const allEvents = eventStream.getEvents();\n const runStartEvents = allEvents.filter((e: any) => e.type === 'agent_run_start');\n const sessionId =\n runStartEvents.length > 0\n ? (runStartEvents[runStartEvents.length - 1] as any).sessionId\n : `${Date.now()}`;\n\n const envEvents = allEvents.filter((e: any) => e.type === 'environment_input');\n const screenshotEvents = envEvents.filter(\n (e: any) => e.metadata && e.metadata.type === 'screenshot',\n );\n const lastScreenshot =\n screenshotEvents.length > 0 ? (screenshotEvents[screenshotEvents.length - 1] as any) : null;\n\n const targetOutputDir = options.output\n ? path.resolve(options.output)\n : path.join(os.homedir(), '.gui-agent-results');\n console.log(`[CLI] Output directory (resolved): ${targetOutputDir}`);\n fs.mkdirSync(targetOutputDir, { recursive: true });\n console.log(`[CLI] TaskId/SessionId: ${sessionId}`);\n\n // Generate video recording from screenshots\n let videoPath = '';\n if (screenshotEvents.length > 0) {\n const tempDir = path.join(os.tmpdir(), 'gui-agent-rec', sessionId);\n try {\n fs.mkdirSync(tempDir, { recursive: true });\n\n const validFrames: { file: string; timestamp: number }[] = [];\n let frameCount = 0;\n for (const event of screenshotEvents) {\n if (Array.isArray((event as any).content)) {\n const imgPart = ((event as any).content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n if (buffer.length > 0) {\n const extension =\n buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff ? 'jpg' : 'png';\n const fileName = `${String(frameCount).padStart(4, '0')}.${extension}`;\n const framePath = path.join(tempDir, fileName);\n fs.writeFileSync(framePath, buffer);\n validFrames.push({\n file: fileName,\n timestamp: (event as any).timestamp || Date.now(),\n });\n frameCount++;\n }\n }\n }\n }\n\n if (validFrames.length > 0) {\n const concatFilePath = path.join(tempDir, 'filelist.txt');\n let fileContent = '';\n const hasTimestamps = validFrames.some(\n (f, i) => i > 0 && f.timestamp !== validFrames[0].timestamp,\n );\n\n for (let i = 0; i < validFrames.length; i++) {\n const frame = validFrames[i];\n let duration = 1.0;\n if (hasTimestamps && i < validFrames.length - 1) {\n const diff = (validFrames[i + 1].timestamp - frame.timestamp) / 1000;\n if (diff > 0.1 && diff < 60) duration = diff;\n } else if (i === validFrames.length - 1) {\n duration = 2.0;\n }\n fileContent += `file '${frame.file}'\\n`;\n fileContent += `duration ${duration.toFixed(3)}\\n`;\n }\n if (validFrames.length > 0) {\n fileContent += `file '${validFrames[validFrames.length - 1].file}'\\n`;\n }\n fs.writeFileSync(concatFilePath, fileContent);\n\n const outputVideoPath = path.join(targetOutputDir, `${sessionId}.mp4`);\n console.log(`[CLI] Generating video recording: ${outputVideoPath}`);\n\n await new Promise<void>((resolve, reject) => {\n ffmpeg()\n .input(concatFilePath)\n .inputOptions(['-f', 'concat', '-safe', '0'])\n .output(outputVideoPath)\n .outputOptions([\n '-c:v',\n 'libx264',\n '-pix_fmt',\n 'yuv420p',\n // scale needs to be even numbers for libx264\n '-vf',\n 'scale=trunc(iw/2)*2:trunc(ih/2)*2',\n ])\n .on('start', (cmd) => console.log(`[CLI] Ffmpeg command: ${cmd}`))\n .on('stderr', (line) => console.log(`[CLI] Ffmpeg stderr: ${line}`))\n .on('end', () => resolve())\n .on('error', (err: any) => {\n console.error('[CLI] Ffmpeg error:', err);\n reject(err);\n })\n .run();\n });\n\n videoPath = outputVideoPath;\n console.log(`[CLI] Video saved: ${videoPath}`);\n }\n } catch (recErr) {\n console.warn('[CLI] Failed to generate video recording', recErr);\n } finally {\n // Cleanup temp dir\n try {\n fs.rmSync(tempDir, { recursive: true, force: true });\n } catch (_) {\n /* ignore */\n }\n }\n }\n\n let resultPicPath = '';\n if (lastScreenshot && Array.isArray(lastScreenshot.content)) {\n const imgPart = (lastScreenshot.content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n resultPicPath = path.join(targetOutputDir, `${sessionId}.png`);\n fs.writeFileSync(resultPicPath, buffer);\n console.log(`[CLI] Screenshot saved: ${resultPicPath}`);\n }\n }\n if (!resultPicPath) {\n console.log('[CLI] No screenshot captured; resultPic will be empty.');\n }\n\n const conversationLogPath = saveConversationLog(\n // For single task run, we can just use all events as it is a fresh process/run\n allEvents,\n targetOutputDir,\n sessionId,\n );\n\n const report = {\n taskId: sessionId,\n taskContent: answers.instruction || options.query,\n startTime,\n endTime,\n duration,\n resultPic: resultPicPath,\n video: videoPath || null,\n conversationLog: conversationLogPath,\n finalAnswer,\n };\n const reportPath = path.join(targetOutputDir, `${sessionId}.json`);\n fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));\n console.log(`Result saved: ${reportPath}`);\n console.log(`[CLI] Report JSON path: ${reportPath}`);\n } catch (err) {\n console.warn('Failed to generate result report:', err);\n }\n };\n\n process.removeAllListeners('SIGINT');\n process.on('SIGINT', async () => {\n console.log('\\n[CLI] Received SIGINT. Saving report and exiting...');\n abortController.abort();\n await saveSingleTaskReport('用户已手动终止');\n process.exit(0);\n });\n\n try {\n console.log(\n '[CLI] Starting GUIAgent run with instruction:',\n answers.instruction || options.query,\n );\n resultEvent = await guiAgent.run(answers.instruction);\n console.log('[CLI] GUIAgent run completed.');\n } catch (err: any) {\n if (err.name === 'AbortError' || abortController.signal.aborted) {\n console.log('[CLI] GUIAgent run aborted.');\n } else {\n console.error('[CLI] GUIAgent run failed.');\n const errMsg = err?.message || String(err);\n console.error('[CLI] Error message:', errMsg);\n if (err?.status) console.error('[CLI] HTTP status:', err.status);\n if (err?.code) console.error('[CLI] Error code:', err.code);\n const respData = err?.response?.data || err?.response?.body || err?.data;\n if (respData) {\n try {\n const text = typeof respData === 'string' ? respData : JSON.stringify(respData);\n console.error('[CLI] Response body:', text.slice(0, 500));\n } catch (_) {\n console.error('[CLI] Response body: [unprintable]');\n }\n }\n }\n }\n\n await saveSingleTaskReport((resultEvent as any)?.content ?? '');\n};\n\nexport const resetConfig = async (configPath?: string) => {\n const CONFIG_PATH = configPath || path.join(os.homedir(), '.gui-agent-cli.json');\n\n try {\n if (fs.existsSync(CONFIG_PATH)) {\n fs.unlinkSync(CONFIG_PATH);\n console.log(`✓ Configuration file removed: ${CONFIG_PATH}`);\n } else {\n console.log(`No configuration file found at: ${CONFIG_PATH}`);\n }\n\n console.log(\n 'Configuration has been reset. The next time you run gui-agent, you will be prompted to configure your settings again.',\n );\n } catch (error) {\n console.error('Failed to reset configuration:', error);\n process.exit(1);\n }\n};\n"],"names":["__webpack_require__","module","getter","definition","key","Object","obj","prop","Symbol","saveConversationLog","events","targetOutputDir","sessionId","logPath","path","content","e","time","Date","Array","part","JSON","toolCall","message","fs","console","err","start","options","ffmpegStatic","finalFfmpegPath","bundledFfmpegPath","__dirname","os","ffmpeg","CONFIG_PATH","config","Number","response","fetch","Error","yamlText","preset","yaml","error","configAnswers","p","process","_config_azure","azureConfig","maskedKey","Boolean","parsed","URL","_","endsWithV1","url","controller","AbortController","timeout","setTimeout","resp","clearTimeout","text","json","hasChoices","targetOperator","targetType","AdbOperator","BrowserOperator","NutJSOperator","useTasksFile","answers","abortController","systemPrompts","guiAgent","GUIAgent","demoDir","tasksPath","dirOfTasks","sample","tasks","raw","task","taskAC","timeoutMs","timeoutId","onGlobalAbort","taskAgent","resultEvent","startTime","taskErr","endTime","duration","eventStream","allEvents","runStartEvents","lastRunStart","startIndex","endIndex","idx","rangeEvents","envEvents","screenshotEvents","videoPath","tempDir","validFrames","frameCount","event","_imgPart_image_url","imgPart","c","dataUri","commaIndex","base64Data","buffer","Buffer","extension","fileName","String","framePath","concatFilePath","fileContent","hasTimestamps","f","i","frame","diff","outputVideoPath","Promise","resolve","reject","cmd","line","recErr","lastScreenshot","resultPicPath","_imgPart_image_url1","conversationLogPath","finalAnswer","report","reportPath","reportErr","isReportSaved","saveSingleTaskReport","_err_response","_err_response1","errMsg","respData","resetConfig","configPath"],"mappings":";;;;;;;IACAA,oBAAoB,CAAC,GAAG,CAACC;QACxB,IAAIC,SAASD,UAAUA,OAAO,UAAU,GACvC,IAAOA,MAAM,CAAC,UAAU,GACxB,IAAOA;QACRD,oBAAoB,CAAC,CAACE,QAAQ;YAAE,GAAGA;QAAO;QAC1C,OAAOA;IACR;;;ICPAF,oBAAoB,CAAC,GAAG,CAAC,UAASG;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGH,oBAAoB,CAAC,CAACG,YAAYC,QAAQ,CAACJ,oBAAoB,CAAC,CAAC,UAASI,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAJ,oBAAoB,CAAC,GAAG,CAACM,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFP,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOQ,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;;;;;;;;;;;;;;;AC2BA,MAAMI,sBAAsB,CAACC,QAAeC,iBAAyBC;IACnE,MAAMC,UAAUC,6BAAAA,IAAS,CAACH,iBAAiB,GAAGC,UAAU,GAAG,CAAC;IAC5D,IAAIG,UAAU,CAAC,qBAAqB,EAAEH,UAAU,IAAI,CAAC;IAErDF,OAAO,OAAO,CAAC,CAACM;QACd,MAAMC,OAAO,IAAIC,KAAKF,EAAE,SAAS,IAAIE,KAAK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WH,AAAAA,CAAAA,QAAAA,MAAAA,KAAAA,IAAAA,QAAAA,CAAAA,gBAAAA,IAAK,QAAQ,AAAD,IAAZA,KAAAA,IAAAA,cAAe,IAAI,AAAD,KAAKC,CAAAA,QAAAA,MAAAA,KAAAA,IAAAA,QAAAA,CAAAA,iBAAAA,IAAK,QAAQ,AAAD,IAAZA,KAAAA,IAAAA,eAAe,IAAI,AAAD,KAAKxH,CAAAA,QAAAA,MAAAA,KAAAA,IAAAA,IAAK,IAAI,AAAD;YACvE,IAAI0H,UACF,IAAI;gBACF,MAAMrF,OAAO,AAAoB,YAApB,OAAOqF,WAAwBA,WAAW/H,KAAK,SAAS,CAAC+H;gBACtE3H,QAAQ,KAAK,CAAC,wBAAwBsC,KAAK,KAAK,CAAC,GAAG;YACtD,EAAE,OAAOT,GAAG;gBACV7B,QAAQ,KAAK,CAAC;YAChB;QAEJ;IACF;IAEA,MAAMuH,qBAAqB,AAACvD,CAAAA,QAAAA,cAAAA,KAAAA,IAAAA,YAAqB,OAAO,AAAD,KAAK;AAC9D;AAEO,MAAM4D,cAAc,OAAOC;IAChC,MAAMnH,cAAcmH,cAAcxI,6BAAAA,IAAS,CAACmB,2BAAAA,OAAU,IAAI;IAE1D,IAAI;QACF,IAAIT,2BAAAA,UAAa,CAACW,cAAc;YAC9BX,2BAAAA,UAAa,CAACW;YACdV,QAAQ,GAAG,CAAC,CAAC,qCAA8B,EAAEU,aAAa;QAC5D,OACEV,QAAQ,GAAG,CAAC,CAAC,gCAAgC,EAAEU,aAAa;QAG9DV,QAAQ,GAAG,CACT;IAEJ,EAAE,OAAOmB,OAAO;QACdnB,QAAQ,KAAK,CAAC,kCAAkCmB;QAChDG,QAAQ,IAAI,CAAC;IACf;AACF"}
|
|
1
|
+
{"version":3,"file":"cli/start.js","sources":["webpack://@ui-tars-test/cli/webpack/runtime/compat_get_default_export","webpack://@ui-tars-test/cli/webpack/runtime/define_property_getters","webpack://@ui-tars-test/cli/webpack/runtime/has_own_property","webpack://@ui-tars-test/cli/webpack/runtime/make_namespace_object","webpack://@ui-tars-test/cli/./src/cli/start.ts"],"sourcesContent":["// getDefaultExport function for compatibility with non-ESM modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};\n","__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};","/*\n * Copyright (c) 2025 Bytedance, Inc. and its affiliates.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport os from 'node:os';\nimport ffmpeg from 'fluent-ffmpeg';\n// @ts-ignore\nimport ffmpegStatic from 'ffmpeg-static';\n\nimport fetch from 'node-fetch';\nimport { GUIAgent } from '@ui-tars-test/agent-sdk';\nimport * as p from '@clack/prompts';\nimport yaml from 'js-yaml';\n\nimport { NutJSOperator } from '@ui-tars-test/operator-nutjs';\nimport { AdbOperator } from '@ui-tars-test/operator-adb';\nimport { BrowserOperator } from '@ui-tars-test/operator-browser';\n\nclass ExposedNutJSOperator extends NutJSOperator {\n public async getScreenResolution() {\n await this.initialize();\n const ctx = this.screenContext();\n return { width: ctx.screenWidth, height: ctx.screenHeight };\n }\n}\n\nexport interface CliOptions {\n presets?: string;\n target?: string;\n query?: string;\n config?: string;\n output?: string;\n tasks?: string;\n maxLoopCount?: string;\n}\n\nconst saveConversationLog = (events: any[], targetOutputDir: string, sessionId: string) => {\n const logPath = path.join(targetOutputDir, `${sessionId}.md`);\n let content = `# Conversation Log - ${sessionId}\\n\\n`;\n\n events.forEach((e) => {\n const time = new Date(e.timestamp || Date.now()).toISOString();\n content += `## [${time}] ${e.type}\\n`;\n\n // Debug raw event structure in console to identify correct fields\n // console.log(`[DEBUG] Event type: ${e.type}`, JSON.stringify(e, null, 2));\n\n if (e.content) {\n if (Array.isArray(e.content)) {\n e.content.forEach((part: any) => {\n if (part.type === 'text') content += `${part.text}\\n`;\n if (part.type === 'image_url') content += `[Image Content]\\n`;\n });\n } else if (typeof e.content === 'string') {\n content += `${e.content}\\n`;\n } else {\n content += `\\`\\`\\`json\\n${JSON.stringify(e.content, null, 2)}\\n\\`\\`\\`\\n`;\n }\n }\n\n // Check specific event types based on observation\n // It seems 'tool_call' and 'assistant_message' might store data differently than expected\n // Let's try to be more permissive in finding the content\n\n if (e.type === 'tool_call') {\n // Based on ToolCallEvent interface in agent-event-stream.ts\n // It has 'name' and 'arguments' properties directly\n if (e.name) content += `> Tool Call: ${e.name}\\n`;\n if (e.arguments) content += `> Arguments: ${JSON.stringify(e.arguments, null, 2)}\\n`;\n\n // Fallback if it's nested in toolCall property\n const toolCall = e.toolCall;\n if (toolCall) {\n if (toolCall.name) content += `> Tool Call: ${toolCall.name}\\n`;\n if (toolCall.arguments)\n content += `> Arguments: ${JSON.stringify(toolCall.arguments, null, 2)}\\n`;\n }\n } else if (e.type === 'assistant_message') {\n // Based on AssistantMessageEvent interface in agent-event-stream.ts\n // It has 'content' and 'toolCalls' properties directly\n if (e.content) content += `${e.content}\\n`;\n if (e.rawContent) content += `\\n> Raw Content (Debug): ${JSON.stringify(e.rawContent)}\\n`;\n if (e.toolCalls) content += `> Tool Calls: ${JSON.stringify(e.toolCalls, null, 2)}\\n`;\n\n // Fallback if it's nested in message property\n const message = e.message;\n if (message) {\n if (message.content) content += `${message.content}\\n`;\n if (message.rawContent)\n content += `\\n> Raw Content (Debug): ${JSON.stringify(message.rawContent)}\\n`;\n if (message.tool_calls)\n content += `> Tool Calls: ${JSON.stringify(message.tool_calls, null, 2)}\\n`;\n }\n }\n\n if (e.metadata) {\n // Avoid printing large metadata like screenshots if they are embedded there (usually they are in content or separate)\n // For screenshot events, metadata might contain type='screenshot'\n if (e.metadata.type === 'screenshot') {\n content += `> Action: Screenshot captured\\n`;\n } else {\n content += `> Metadata: ${JSON.stringify(e.metadata)}\\n`;\n }\n }\n\n if (e.input) {\n content += `> Input: ${JSON.stringify(e.input, null, 2)}\\n`;\n }\n\n if (e.output) {\n content += `> Output: ${JSON.stringify(e.output, null, 2)}\\n`;\n }\n\n content += '\\n';\n });\n\n try {\n fs.writeFileSync(logPath, content);\n console.log(`[CLI] Conversation log saved: ${logPath}`);\n return logPath;\n } catch (err) {\n console.warn(`[CLI] Failed to save conversation log: ${err}`);\n return null;\n }\n};\n\nexport const start = async (options: CliOptions) => {\n if (ffmpegStatic) {\n let finalFfmpegPath = ffmpegStatic;\n // In production build (bundled), ffmpeg-static might return a path that doesn't exist\n // because it relies on __dirname which changes after bundling.\n // However, we copy the binary to the dist folder in post-build script.\n // We should check if we are running from the bundled version.\n const bundledFfmpegPath = path.join(__dirname, 'ffmpeg');\n if (fs.existsSync(bundledFfmpegPath)) {\n finalFfmpegPath = bundledFfmpegPath;\n console.log(`[CLI] Using bundled ffmpeg: ${finalFfmpegPath}`);\n } else {\n console.log(`[CLI] Using default ffmpeg-static path: ${finalFfmpegPath}`);\n }\n\n if (os.platform() === 'darwin' && os.arch() === 'arm64') {\n console.log(`[CLI] Setting ffmpeg path: ${finalFfmpegPath}`);\n }\n ffmpeg.setFfmpegPath(finalFfmpegPath);\n } else {\n console.warn(\n '[CLI] ffmpeg-static not found. Video generation might fail if ffmpeg is not in PATH.',\n );\n }\n\n const CONFIG_PATH = options.config || path.join(os.homedir(), '.gui-agent-cli.json');\n\n // read config file\n let config = {\n baseURL: '',\n apiKey: '', // secretlint-disable-line\n model: '',\n provider: 'openai', // Default provider\n useResponsesApi: false,\n maxLoopCount: options.maxLoopCount ? Number(options.maxLoopCount) : 1000,\n };\n\n if (options.presets) {\n const response = await fetch(options.presets);\n if (!response.ok) {\n throw new Error(`Failed to fetch preset: ${response.status}`);\n }\n\n const yamlText = await response.text();\n const preset = yaml.load(yamlText) as any;\n\n config.apiKey = preset?.vlmApiKey; // secretlint-disable-line\n config.baseURL = preset?.vlmBaseUrl;\n config.model = preset?.vlmModelName;\n config.useResponsesApi = preset?.useResponsesApi ?? false;\n } else if (fs.existsSync(CONFIG_PATH)) {\n try {\n config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));\n } catch (error) {\n console.warn('read config file failed', error);\n }\n }\n\n if (!config.baseURL || !config.apiKey || !config.model) {\n const configAnswers = await p.group(\n {\n provider: () =>\n p.select({\n message: 'Select model provider:',\n options: [\n { value: 'volcengine', label: 'VolcEngine' },\n { value: 'azure-openai', label: 'Azure OpenAI' },\n { value: 'anthropic', label: 'Anthropic Claude' },\n { value: 'openai', label: 'OpenAI' },\n { value: 'lm-studio', label: 'LM Studio' },\n { value: 'deepseek', label: 'DeepSeek' },\n { value: 'ollama', label: 'Ollama' },\n ],\n }),\n baseURL: () => p.text({ message: 'please input vlm model baseURL:' }),\n apiKey: () => p.text({ message: 'please input vlm model apiKey:' }), // secretlint-disable-line\n model: () => p.text({ message: 'please input vlm model name:' }),\n },\n {\n onCancel: () => {\n p.cancel('operation cancelled');\n process.exit(0);\n },\n },\n );\n\n config = { ...config, ...configAnswers };\n\n if (config.provider === 'azure-openai') {\n // Ensure azure config object exists\n if (!(config as any).azure) {\n (config as any).azure = {};\n }\n\n // Auto-populate azure.endpoint from baseURL if not present\n // This is crucial for our custom fetch interceptor in llm-client to work\n if (!(config as any).azure.endpoint && config.baseURL) {\n (config as any).azure.endpoint = config.baseURL;\n }\n\n if (!(config as any).azure?.apiVersion) {\n const azureConfig = await p.group(\n {\n apiVersion: () =>\n p.text({\n message: 'please input azure api version (optional, default: 2024-10-01-preview):',\n }),\n // Add prompt for X-TT-LOGID which is required for some internal gateways\n logId: () =>\n p.text({\n message: 'please input X-TT-LOGID (optional, for internal gateway):',\n }),\n },\n {\n onCancel: () => {\n p.cancel('operation cancelled');\n process.exit(0);\n },\n },\n );\n\n if (azureConfig.apiVersion) {\n (config as any).azure.apiVersion = azureConfig.apiVersion;\n }\n\n if (azureConfig.logId) {\n if (!(config as any).headers) {\n (config as any).headers = {};\n }\n (config as any).headers['X-TT-LOGID'] = azureConfig.logId;\n }\n }\n }\n\n // save config to file\n try {\n fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));\n console.log('model config file saved to:', CONFIG_PATH);\n } catch (error) {\n console.error('save model config file failed', error);\n }\n }\n\n // Diagnostic: print model config loaded\n try {\n const maskedKey = config.apiKey\n ? `${config.apiKey.slice(0, 6)}...${config.apiKey.slice(-4)}`\n : '(empty)';\n console.log('[CLI] Loaded model config:');\n console.log(` provider: ${config.provider}`);\n console.log(` baseURL: ${config.baseURL}`);\n console.log(` model: ${config.model}`);\n console.log(` apiKey: ${maskedKey}`); // secretlint-disable-line\n console.log(` useResponsesApi: ${Boolean((config as any).useResponsesApi)}`);\n } catch (e) {\n console.warn('[CLI] Failed to print model config diagnostics:', e);\n }\n\n // Basic baseURL validation and hints for OpenAI-compatible servers\n try {\n if (config.baseURL) {\n let parsed: URL | null = null;\n try {\n parsed = new URL(config.baseURL);\n } catch (_) {\n console.warn('[CLI] Warning: baseURL is not a valid URL:', config.baseURL);\n }\n if (parsed) {\n const endsWithV1 = /\\/v1\\/?$/.test(parsed.pathname);\n if (!endsWithV1) {\n console.warn(\n '[CLI] Hint: OpenAI-compatible endpoints typically end with \"/v1\" (e.g. https://host/v1).',\n );\n }\n if (parsed.protocol !== 'https:') {\n console.warn('[CLI] Hint: use HTTPS for most providers. Current:', parsed.protocol);\n }\n }\n }\n } catch (e) {\n console.warn('[CLI] baseURL validation failed:', e);\n }\n\n // Preflight: check Chat Completions non-streaming response shape for OpenAI-compatible servers\n try {\n if (config.provider === 'openai' && config.baseURL && config.model) {\n const url = new URL(config.baseURL.replace(/\\/$/, ''));\n url.pathname = url.pathname.replace(/\\/$/, '') + '/chat/completions';\n console.log('[CLI] Preflight: POST', url.toString());\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 16000);\n const resp = await fetch(url.toString(), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n },\n body: JSON.stringify({\n model: config.model,\n messages: [{ role: 'user', content: 'ping' }],\n stream: false,\n }),\n signal: controller.signal,\n } as any);\n clearTimeout(timeout);\n const text = await resp.text();\n if (!resp.ok) {\n console.warn('[CLI] Preflight failed:', resp.status, resp.statusText);\n console.warn('[CLI] Preflight response body:', text.slice(0, 500));\n } else {\n try {\n const json = JSON.parse(text);\n const hasChoices = Array.isArray(json?.choices) && json.choices.length > 0;\n console.log('[CLI] Preflight ok. choices[0] exists:', hasChoices);\n if (!hasChoices) {\n console.warn(\n '[CLI] Preflight: response does not contain choices[]. Service may not implement Chat Completions.',\n );\n }\n } catch (_) {\n console.warn('[CLI] Preflight ok but response is not JSON:', text.slice(0, 200));\n }\n }\n }\n } catch (e: any) {\n if (e?.name === 'AbortError') {\n console.warn('[CLI] Preflight check timed out (16s). Proceeding without preflight.');\n } else {\n console.warn('[CLI] Preflight check error:', e);\n }\n }\n\n let targetOperator = null;\n let screenResolutionInfo = '';\n const targetType =\n options.target ||\n ((await p.select({\n message: 'Please select your operator target:',\n options: [\n { value: 'computer', label: 'computer (Desktop automation)' },\n { value: 'android', label: 'android (Android automation)' },\n { value: 'browser', label: 'browser (Web automation)' },\n ],\n })) as string);\n\n switch (targetType) {\n case 'android':\n // Note: AdbOperator will auto-detect connected devices\n console.log('Initializing ADB operator...');\n targetOperator = new AdbOperator();\n break;\n case 'browser':\n // Use default browser options\n targetOperator = new BrowserOperator({\n browserType: 'chrome' as any,\n browser: null as any, // Will be initialized internally\n });\n break;\n case 'computer':\n default:\n const op = new ExposedNutJSOperator();\n try {\n const { width, height } = await op.getScreenResolution();\n screenResolutionInfo = `Current screen resolution: ${width}x${height}. Please output absolute coordinates based on this resolution. `;\n console.log(`[CLI] Detected screen resolution: ${width}x${height}`);\n } catch (e) {\n console.warn('[CLI] Failed to get screen resolution:', e);\n }\n targetOperator = op;\n break;\n }\n\n const useTasksFile = Boolean(options.tasks);\n const answers = useTasksFile\n ? { instruction: '' }\n : options.query\n ? { instruction: options.query }\n : await p.group(\n {\n instruction: () => p.text({ message: 'Input your instruction' }),\n },\n {\n onCancel: () => {\n p.cancel('操作已取消');\n process.exit(0);\n },\n },\n );\n\n const abortController = new AbortController();\n process.on('SIGINT', () => {\n abortController.abort();\n });\n\n const systemPrompts = [\n `${screenResolutionInfo}You are provided with a task description, a history of previous actions, and corresponding screenshots. Your goal is to perform the next action to complete the task. Please note that if performing the same action multiple times results in a static screen with no changes, you should attempt a modified or alternative action.`,\n '## Function Definition\\n\\n- You have access to the following functions:\\n{\"type\": \"function\", \"name\": \"call_user\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Message or information displayed to the user to request their input, feedback, or guidance.\"}}, \"required\": []}, \"description\": \"This function is used to interact with the user by displaying a message and requesting their input, feedback, or guidance.\"}\\n{\"type\": \"function\", \"name\": \"click\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse left single click action.\"}\\n{\"type\": \"function\", \"name\": \"drag\", \"parameters\": {\"type\": \"object\", \"properties\": {\"start_point\": {\"type\": \"string\", \"description\": \"Drag start point. The format is: <point>x y</point>\"}, \"end_point\": {\"type\": \"string\", \"description\": \"Drag end point. The format is: <point>x y</point>\"}}, \"required\": [\"start_point\", \"end_point\"]}, \"description\": \"Mouse left button drag action.\"}\\n{\"type\": \"function\", \"name\": \"finished\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Provide the final answer or response to complete the task.\"}}, \"required\": []}, \"description\": \"This function is used to indicate the completion of a task by providing the final answer or response.\"}\\n{\"type\": \"function\", \"name\": \"hotkey\", \"parameters\": {\"type\": \"object\", \"properties\": {\"key\": {\"type\": \"string\", \"description\": \"Hotkeys you want to press. Split keys with a space and use lowercase.\"}}, \"required\": [\"key\"]}, \"description\": \"Press hotkey.\"}\\n{\"type\": \"function\", \"function\": {\"name\": \"infeasible\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Message or information displayed to the user to explain why the current task is infeasible.\"}}, \"required\": [\"content\"]}, \"description\": \"This function is used to indicate that the current task is infeasible thus agent ends the task.\"}\\n{\"type\": \"function\", \"name\": \"left_double\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse left double click action.\"}\\n{\"type\": \"function\", \"name\": \"right_single\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse right single click action.\"}\\n{\"type\": \"function\", \"name\": \"scroll\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Scroll start position. If not specified, default to execute on the current mouse position. The format is: <point>x y</point>\"}, \"direction\": {\"type\": \"string\", \"description\": \"Scroll direction.\", \"enum\": [\"up\", \"down\", \"left\", \"right\"]}}, \"required\": [\"direction\", \"point\"]}, \"description\": \"Scroll action.\"}\\n{\"type\": \"function\", \"name\": \"type\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Type content. If you want to submit your input, use \\\\n at the end of content.\"}}, \"required\": [\"content\"]}, \"description\": \"Type content.\"}\\n{\"type\": \"function\", \"name\": \"wait\", \"parameters\": {\"type\": \"object\", \"properties\": {\"time\": {\"type\": \"integer\", \"description\": \"Wait time in seconds.\"}}, \"required\": []}, \"description\": \"Wait for a while.\"}\\n\\n- To call a function, use the following structure without any suffix:\\n\\n<think_never_used_51bce0c785ca2f68081bfa7d91973934> reasoning process </think_never_used_51bce0c785ca2f68081bfa7d91973934>\\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_name><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\\n\\n## Important Notes\\n- Function calls must begin with <function_never_used_51bce0c785ca2f68081bfa7d91973934= and end with </function_never_used_51bce0c785ca2f68081bfa7d91973934>.\\n- All required parameters must be explicitly provided.\\n\\n## Additional Notes\\n- You can execute multiple actions within a single tool call. For example:\\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_1><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_2><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_3>value_4</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\\n- 当你判断任务请求是无法执行的时候,你应该调用Infeasible工具结束任务并解释原因。\\n 判断标准:当一个请求符合以下任何一条标准时,应被归类为“无法执行”。\\n 1. 技术/物理层面的矛盾: 指令本身包含逻辑上或物理上无法实现的要求。\\n 2. 工具/功能错配: 指令要求在一个软件中执行另一个软件的功能,或者执行该软件根本不具备的功能。\\n 3. 超出操作边界/范围: 指令要求执行的操作超出了当前用户会话、权限或应用程序的逻辑边界,涉及未告知的隐私信息或者未授权的操作。\\n 4. 依赖隐性知识或外部条件: 任务的完成依赖于Agent无法获取的外部硬件、物理环境、未声明的插件/扩展、或特定的文件/数据。\\n\\n 输出指令:\\n 如果请求被判断为“无法执行”,你应该向用户解释为什么这个任务超出了你的能力范围(例如,指出它需要直接操作某个硬件),并尽可能提供一个指导性的替代方案,让用户可以自己完成该任务。\\n 你应该非常非常谨慎地使用Infeasible工具,因为它会直接结束任务并降低用户体验。所以非必要的时候,你不应该调用Infeasible工具,尽量以finish工具结束任务并向用户提示原因就好。',\n ];\n\n const guiAgent = new GUIAgent({\n model: {\n id: config.model,\n provider: config.provider as any, // Type assertion to avoid TypeScript error\n baseURL: config.baseURL,\n apiKey: config.apiKey, // secretlint-disable-line\n azure: (config as any).azure,\n headers: (config as any).headers || (config as any).defaultHeaders,\n } as any,\n operator: targetOperator,\n systemPrompt: systemPrompts.join('\\n\\n'),\n });\n\n if (useTasksFile) {\n const demoDir = path.resolve(path.join(__dirname, '..', '..', 'demo'));\n const tasksPath =\n options.tasks === 'demo' ? path.join(demoDir, 'tasks.json') : path.resolve(options.tasks!);\n try {\n const dirOfTasks = path.dirname(tasksPath);\n fs.mkdirSync(dirOfTasks, { recursive: true });\n if (!fs.existsSync(tasksPath)) {\n const sample = [\n { taskId: 'task-1', query: 'Open Chrome and go to github.com' },\n { taskId: 'task-2', query: \"Search for 'GUI Agent automation' on Google\" },\n ];\n fs.writeFileSync(tasksPath, JSON.stringify(sample, null, 2));\n console.log(`[CLI] Sample tasks.json created: ${tasksPath}`);\n }\n } catch (e) {\n console.warn('[CLI] Failed to prepare tasks file directory', e);\n }\n\n let tasks: Array<{ taskId: string; query: string; timeout?: number }> = [];\n try {\n const raw = fs.readFileSync(tasksPath, 'utf-8');\n const parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) tasks = parsed;\n else console.warn('[CLI] tasks file is not an array');\n } catch (e) {\n console.error('[CLI] Failed to read tasks file', e);\n process.exit(1);\n }\n\n const targetOutputDir = options.output\n ? path.resolve(options.output)\n : options.tasks === 'demo'\n ? path.join(demoDir, 'results')\n : path.join(os.homedir(), '.gui-agent-results');\n console.log(`[CLI] Output directory (resolved): ${targetOutputDir}`);\n fs.mkdirSync(targetOutputDir, { recursive: true });\n\n for (const task of tasks) {\n const taskAC = new AbortController();\n const timeoutMs = task.timeout ?? 25 * 60 * 1000;\n const timeoutId = setTimeout(() => {\n console.log(`[CLI] Task ${task.taskId} timed out after ${timeoutMs}ms`);\n taskAC.abort();\n }, timeoutMs);\n\n const onGlobalAbort = () => taskAC.abort();\n abortController.signal.addEventListener('abort', onGlobalAbort);\n\n const taskAgent = new GUIAgent({\n model: {\n id: config.model,\n provider: config.provider as any, // Type assertion to avoid TypeScript error\n baseURL: config.baseURL,\n apiKey: config.apiKey, // secretlint-disable-line\n azure: (config as any).azure,\n headers: (config as any).headers || (config as any).defaultHeaders,\n } as any,\n operator: targetOperator,\n systemPrompt: systemPrompts.join('\\n\\n'),\n // @ts-ignore\n signal: taskAC.signal,\n });\n\n let resultEvent: any;\n const startTime = Date.now();\n\n try {\n console.log(`[CLI] Starting task: ${task.taskId} at ${new Date(startTime).toISOString()}`);\n resultEvent = await taskAgent.run(task.query);\n } catch (taskErr: any) {\n if (taskAC.signal.aborted) {\n console.warn(`[CLI] Task ${task.taskId} was aborted (Timeout or SIGINT).`);\n resultEvent = { content: 'Task aborted or timed out' };\n } else {\n console.error(`[CLI] Task failed: ${task.taskId}`, taskErr);\n resultEvent = { content: `Error: ${taskErr.message}` };\n }\n } finally {\n clearTimeout(timeoutId);\n abortController.signal.removeEventListener('abort', onGlobalAbort);\n }\n\n try {\n const endTime = Date.now();\n const duration = endTime - startTime;\n\n const eventStream = taskAgent.getEventStream();\n const allEvents = eventStream.getEvents();\n const runStartEvents = allEvents.filter((e: any) => e.type === 'agent_run_start');\n const lastRunStart = runStartEvents[runStartEvents.length - 1] as any;\n const startIndex = allEvents.findIndex((e: any) => e.id === lastRunStart?.id);\n const endIndex = allEvents.findIndex(\n (e: any, idx: number) => idx > startIndex && e.type === 'agent_run_end',\n );\n const rangeEvents =\n startIndex >= 0\n ? endIndex >= 0\n ? allEvents.slice(startIndex, endIndex + 1)\n : allEvents.slice(startIndex)\n : allEvents;\n const envEvents = rangeEvents.filter((e: any) => e.type === 'environment_input');\n const screenshotEvents = envEvents.filter(\n (e: any) => e.metadata && e.metadata.type === 'screenshot',\n );\n\n // Generate video recording from screenshots\n let videoPath = '';\n if (screenshotEvents.length > 0) {\n const tempDir = path.join(os.tmpdir(), 'gui-agent-rec', task.taskId);\n try {\n fs.mkdirSync(tempDir, { recursive: true });\n\n const validFrames: { file: string; timestamp: number }[] = [];\n let frameCount = 0;\n for (const event of screenshotEvents) {\n if (Array.isArray((event as any).content)) {\n const imgPart = ((event as any).content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n if (buffer.length > 0) {\n const extension =\n buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff\n ? 'jpg'\n : 'png';\n const fileName = `${String(frameCount).padStart(4, '0')}.${extension}`;\n const framePath = path.join(tempDir, fileName);\n fs.writeFileSync(framePath, buffer);\n validFrames.push({\n file: fileName,\n timestamp: (event as any).timestamp || Date.now(),\n });\n frameCount++;\n }\n }\n }\n }\n\n if (validFrames.length > 0) {\n const concatFilePath = path.join(tempDir, 'filelist.txt');\n let fileContent = '';\n const hasTimestamps = validFrames.some(\n (f, i) => i > 0 && f.timestamp !== validFrames[0].timestamp,\n );\n\n for (let i = 0; i < validFrames.length; i++) {\n const frame = validFrames[i];\n let duration = 1.0;\n if (hasTimestamps && i < validFrames.length - 1) {\n const diff = (validFrames[i + 1].timestamp - frame.timestamp) / 1000;\n if (diff > 0.1 && diff < 60) duration = diff;\n } else if (i === validFrames.length - 1) {\n duration = 2.0;\n }\n fileContent += `file '${frame.file}'\\n`;\n fileContent += `duration ${duration.toFixed(3)}\\n`;\n }\n if (validFrames.length > 0) {\n fileContent += `file '${validFrames[validFrames.length - 1].file}'\\n`;\n }\n fs.writeFileSync(concatFilePath, fileContent);\n\n const outputVideoPath = path.join(targetOutputDir, `${task.taskId}.mp4`);\n console.log(`[CLI] Generating video recording: ${outputVideoPath}`);\n\n await new Promise<void>((resolve, reject) => {\n ffmpeg()\n .input(concatFilePath)\n .inputOptions(['-f', 'concat', '-safe', '0'])\n .output(outputVideoPath)\n .outputOptions([\n '-c:v',\n 'libx264',\n '-pix_fmt',\n 'yuv420p',\n // scale needs to be even numbers for libx264\n '-vf',\n 'scale=trunc(iw/2)*2:trunc(ih/2)*2',\n ])\n .on('start', (cmd) => console.log(`[CLI] Ffmpeg command: ${cmd}`))\n .on('stderr', (line) => console.log(`[CLI] Ffmpeg stderr: ${line}`))\n .on('end', () => resolve())\n .on('error', (err: any) => {\n console.error('[CLI] Ffmpeg error:', err);\n reject(err);\n })\n .run();\n });\n\n videoPath = outputVideoPath;\n console.log(`[CLI] Video saved: ${videoPath}`);\n }\n } catch (recErr) {\n console.warn('[CLI] Failed to generate video recording', recErr);\n } finally {\n // Cleanup temp dir\n try {\n fs.rmSync(tempDir, { recursive: true, force: true });\n } catch (_) {\n /* ignore */\n }\n }\n }\n\n const lastScreenshot =\n screenshotEvents.length > 0\n ? (screenshotEvents[screenshotEvents.length - 1] as any)\n : null;\n\n let resultPicPath = '';\n if (lastScreenshot && Array.isArray(lastScreenshot.content)) {\n const imgPart = (lastScreenshot.content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n resultPicPath = path.join(targetOutputDir, `${task.taskId}.png`);\n fs.writeFileSync(resultPicPath, buffer);\n console.log(`[CLI] Screenshot saved: ${resultPicPath}`);\n }\n }\n if (!resultPicPath) {\n console.log('[CLI] No screenshot captured; resultPic will be empty.');\n }\n\n const conversationLogPath = saveConversationLog(rangeEvents, targetOutputDir, task.taskId);\n\n const finalAnswer = (resultEvent as any)?.content ?? '';\n const report = {\n taskId: task.taskId,\n taskContent: task.query,\n startTime,\n endTime,\n duration,\n resultPic: resultPicPath,\n video: videoPath || null,\n conversationLog: conversationLogPath,\n finalAnswer,\n };\n const reportPath = path.join(targetOutputDir, `${task.taskId}.json`);\n fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));\n console.log(`Result saved: ${reportPath}`);\n console.log(`[CLI] Report JSON path: ${reportPath}`);\n } catch (reportErr) {\n console.warn(`[CLI] Failed to save report for task ${task.taskId}`, reportErr);\n }\n }\n return;\n }\n\n // Enhanced error logging around agent run\n let resultEvent: any;\n const startTime = Date.now();\n let isReportSaved = false;\n\n const saveSingleTaskReport = async (finalAnswer: string) => {\n if (isReportSaved) return;\n isReportSaved = true;\n\n const endTime = Date.now();\n const duration = endTime - startTime;\n\n try {\n const eventStream = guiAgent.getEventStream();\n const allEvents = eventStream.getEvents();\n const runStartEvents = allEvents.filter((e: any) => e.type === 'agent_run_start');\n const sessionId =\n runStartEvents.length > 0\n ? (runStartEvents[runStartEvents.length - 1] as any).sessionId\n : `${Date.now()}`;\n\n const envEvents = allEvents.filter((e: any) => e.type === 'environment_input');\n const screenshotEvents = envEvents.filter(\n (e: any) => e.metadata && e.metadata.type === 'screenshot',\n );\n const lastScreenshot =\n screenshotEvents.length > 0 ? (screenshotEvents[screenshotEvents.length - 1] as any) : null;\n\n const targetOutputDir = options.output\n ? path.resolve(options.output)\n : path.join(os.homedir(), '.gui-agent-results');\n console.log(`[CLI] Output directory (resolved): ${targetOutputDir}`);\n fs.mkdirSync(targetOutputDir, { recursive: true });\n console.log(`[CLI] TaskId/SessionId: ${sessionId}`);\n\n // Generate video recording from screenshots\n let videoPath = '';\n if (screenshotEvents.length > 0) {\n const tempDir = path.join(os.tmpdir(), 'gui-agent-rec', sessionId);\n try {\n fs.mkdirSync(tempDir, { recursive: true });\n\n const validFrames: { file: string; timestamp: number }[] = [];\n let frameCount = 0;\n for (const event of screenshotEvents) {\n if (Array.isArray((event as any).content)) {\n const imgPart = ((event as any).content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n if (buffer.length > 0) {\n const extension =\n buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff ? 'jpg' : 'png';\n const fileName = `${String(frameCount).padStart(4, '0')}.${extension}`;\n const framePath = path.join(tempDir, fileName);\n fs.writeFileSync(framePath, buffer);\n validFrames.push({\n file: fileName,\n timestamp: (event as any).timestamp || Date.now(),\n });\n frameCount++;\n }\n }\n }\n }\n\n if (validFrames.length > 0) {\n const concatFilePath = path.join(tempDir, 'filelist.txt');\n let fileContent = '';\n const hasTimestamps = validFrames.some(\n (f, i) => i > 0 && f.timestamp !== validFrames[0].timestamp,\n );\n\n for (let i = 0; i < validFrames.length; i++) {\n const frame = validFrames[i];\n let duration = 1.0;\n if (hasTimestamps && i < validFrames.length - 1) {\n const diff = (validFrames[i + 1].timestamp - frame.timestamp) / 1000;\n if (diff > 0.1 && diff < 60) duration = diff;\n } else if (i === validFrames.length - 1) {\n duration = 2.0;\n }\n fileContent += `file '${frame.file}'\\n`;\n fileContent += `duration ${duration.toFixed(3)}\\n`;\n }\n if (validFrames.length > 0) {\n fileContent += `file '${validFrames[validFrames.length - 1].file}'\\n`;\n }\n fs.writeFileSync(concatFilePath, fileContent);\n\n const outputVideoPath = path.join(targetOutputDir, `${sessionId}.mp4`);\n console.log(`[CLI] Generating video recording: ${outputVideoPath}`);\n\n await new Promise<void>((resolve, reject) => {\n ffmpeg()\n .input(concatFilePath)\n .inputOptions(['-f', 'concat', '-safe', '0'])\n .output(outputVideoPath)\n .outputOptions([\n '-c:v',\n 'libx264',\n '-pix_fmt',\n 'yuv420p',\n // scale needs to be even numbers for libx264\n '-vf',\n 'scale=trunc(iw/2)*2:trunc(ih/2)*2',\n ])\n .on('start', (cmd) => console.log(`[CLI] Ffmpeg command: ${cmd}`))\n .on('stderr', (line) => console.log(`[CLI] Ffmpeg stderr: ${line}`))\n .on('end', () => resolve())\n .on('error', (err: any) => {\n console.error('[CLI] Ffmpeg error:', err);\n reject(err);\n })\n .run();\n });\n\n videoPath = outputVideoPath;\n console.log(`[CLI] Video saved: ${videoPath}`);\n }\n } catch (recErr) {\n console.warn('[CLI] Failed to generate video recording', recErr);\n } finally {\n // Cleanup temp dir\n try {\n fs.rmSync(tempDir, { recursive: true, force: true });\n } catch (_) {\n /* ignore */\n }\n }\n }\n\n let resultPicPath = '';\n if (lastScreenshot && Array.isArray(lastScreenshot.content)) {\n const imgPart = (lastScreenshot.content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n resultPicPath = path.join(targetOutputDir, `${sessionId}.png`);\n fs.writeFileSync(resultPicPath, buffer);\n console.log(`[CLI] Screenshot saved: ${resultPicPath}`);\n }\n }\n if (!resultPicPath) {\n console.log('[CLI] No screenshot captured; resultPic will be empty.');\n }\n\n const conversationLogPath = saveConversationLog(\n // For single task run, we can just use all events as it is a fresh process/run\n allEvents,\n targetOutputDir,\n sessionId,\n );\n\n const report = {\n taskId: sessionId,\n taskContent: answers.instruction || options.query,\n startTime,\n endTime,\n duration,\n resultPic: resultPicPath,\n video: videoPath || null,\n conversationLog: conversationLogPath,\n finalAnswer,\n };\n const reportPath = path.join(targetOutputDir, `${sessionId}.json`);\n fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));\n console.log(`Result saved: ${reportPath}`);\n console.log(`[CLI] Report JSON path: ${reportPath}`);\n } catch (err) {\n console.warn('Failed to generate result report:', err);\n }\n };\n\n process.removeAllListeners('SIGINT');\n process.on('SIGINT', async () => {\n console.log('\\n[CLI] Received SIGINT. Saving report and exiting...');\n abortController.abort();\n await saveSingleTaskReport('用户已手动终止');\n process.exit(0);\n });\n\n try {\n console.log(\n '[CLI] Starting GUIAgent run with instruction:',\n answers.instruction || options.query,\n );\n resultEvent = await guiAgent.run(answers.instruction);\n console.log('[CLI] GUIAgent run completed.');\n } catch (err: any) {\n if (err.name === 'AbortError' || abortController.signal.aborted) {\n console.log('[CLI] GUIAgent run aborted.');\n } else {\n console.error('[CLI] GUIAgent run failed.');\n const errMsg = err?.message || String(err);\n console.error('[CLI] Error message:', errMsg);\n if (err?.status) console.error('[CLI] HTTP status:', err.status);\n if (err?.code) console.error('[CLI] Error code:', err.code);\n const respData = err?.response?.data || err?.response?.body || err?.data;\n if (respData) {\n try {\n const text = typeof respData === 'string' ? respData : JSON.stringify(respData);\n console.error('[CLI] Response body:', text.slice(0, 500));\n } catch (_) {\n console.error('[CLI] Response body: [unprintable]');\n }\n }\n }\n }\n\n await saveSingleTaskReport((resultEvent as any)?.content ?? '');\n};\n\nexport const resetConfig = async (configPath?: string) => {\n const CONFIG_PATH = configPath || path.join(os.homedir(), '.gui-agent-cli.json');\n\n try {\n if (fs.existsSync(CONFIG_PATH)) {\n fs.unlinkSync(CONFIG_PATH);\n console.log(`✓ Configuration file removed: ${CONFIG_PATH}`);\n } else {\n console.log(`No configuration file found at: ${CONFIG_PATH}`);\n }\n\n console.log(\n 'Configuration has been reset. The next time you run gui-agent, you will be prompted to configure your settings again.',\n );\n } catch (error) {\n console.error('Failed to reset configuration:', error);\n process.exit(1);\n }\n};\n"],"names":["__webpack_require__","module","getter","definition","key","Object","obj","prop","Symbol","ExposedNutJSOperator","NutJSOperator","ctx","saveConversationLog","events","targetOutputDir","sessionId","logPath","path","content","e","time","Date","Array","part","JSON","toolCall","message","fs","console","err","start","options","ffmpegStatic","finalFfmpegPath","bundledFfmpegPath","__dirname","os","ffmpeg","CONFIG_PATH","config","Number","response","fetch","Error","yamlText","preset","yaml","error","configAnswers","p","process","_config_azure","azureConfig","maskedKey","Boolean","parsed","URL","_","endsWithV1","url","controller","AbortController","timeout","setTimeout","resp","clearTimeout","text","json","hasChoices","targetOperator","screenResolutionInfo","targetType","AdbOperator","BrowserOperator","op","width","height","useTasksFile","answers","abortController","systemPrompts","guiAgent","GUIAgent","demoDir","tasksPath","dirOfTasks","sample","tasks","raw","task","taskAC","timeoutMs","timeoutId","onGlobalAbort","taskAgent","resultEvent","startTime","taskErr","endTime","duration","eventStream","allEvents","runStartEvents","lastRunStart","startIndex","endIndex","idx","rangeEvents","envEvents","screenshotEvents","videoPath","tempDir","validFrames","frameCount","event","_imgPart_image_url","imgPart","c","dataUri","commaIndex","base64Data","buffer","Buffer","extension","fileName","String","framePath","concatFilePath","fileContent","hasTimestamps","f","i","frame","diff","outputVideoPath","Promise","resolve","reject","cmd","line","recErr","lastScreenshot","resultPicPath","_imgPart_image_url1","conversationLogPath","finalAnswer","report","reportPath","reportErr","isReportSaved","saveSingleTaskReport","_err_response","_err_response1","errMsg","respData","resetConfig","configPath"],"mappings":";;;;;;;IACAA,oBAAoB,CAAC,GAAG,CAACC;QACxB,IAAIC,SAASD,UAAUA,OAAO,UAAU,GACvC,IAAOA,MAAM,CAAC,UAAU,GACxB,IAAOA;QACRD,oBAAoB,CAAC,CAACE,QAAQ;YAAE,GAAGA;QAAO;QAC1C,OAAOA;IACR;;;ICPAF,oBAAoB,CAAC,GAAG,CAAC,UAASG;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGH,oBAAoB,CAAC,CAACG,YAAYC,QAAQ,CAACJ,oBAAoB,CAAC,CAAC,UAASI,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAJ,oBAAoB,CAAC,GAAG,CAACM,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFP,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOQ,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;;;;;;;;;;;;;;;ACiBA,MAAMI,6BAA6BC,+BAAAA,aAAaA;IAC9C,MAAa,sBAAsB;QACjC,MAAM,IAAI,CAAC,UAAU;QACrB,MAAMC,MAAM,IAAI,CAAC,aAAa;QAC9B,OAAO;YAAE,OAAOA,IAAI,WAAW;YAAE,QAAQA,IAAI,YAAY;QAAC;IAC5D;AACF;AAYA,MAAMC,sBAAsB,CAACC,QAAeC,iBAAyBC;IACnE,MAAMC,UAAU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AEO,MAAM4D,cAAc,OAAOC;IAChC,MAAMtH,cAAcsH,cAAc3I,6BAAAA,IAAS,CAACmB,2BAAAA,OAAU,IAAI;IAE1D,IAAI;QACF,IAAIT,2BAAAA,UAAa,CAACW,cAAc;YAC9BX,2BAAAA,UAAa,CAACW;YACdV,QAAQ,GAAG,CAAC,CAAC,qCAA8B,EAAEU,aAAa;QAC5D,OACEV,QAAQ,GAAG,CAAC,CAAC,gCAAgC,EAAEU,aAAa;QAG9DV,QAAQ,GAAG,CACT;IAEJ,EAAE,OAAOmB,OAAO;QACdnB,QAAQ,KAAK,CAAC,kCAAkCmB;QAChDG,QAAQ,IAAI,CAAC;IACf;AACF"}
|
package/dist/cli/start.mjs
CHANGED
|
@@ -14,6 +14,16 @@ import js_yaml from "js-yaml";
|
|
|
14
14
|
import { NutJSOperator } from "@ui-tars-test/operator-nutjs";
|
|
15
15
|
import { AdbOperator } from "@ui-tars-test/operator-adb";
|
|
16
16
|
import { BrowserOperator } from "@ui-tars-test/operator-browser";
|
|
17
|
+
class ExposedNutJSOperator extends NutJSOperator {
|
|
18
|
+
async getScreenResolution() {
|
|
19
|
+
await this.initialize();
|
|
20
|
+
const ctx = this.screenContext();
|
|
21
|
+
return {
|
|
22
|
+
width: ctx.screenWidth,
|
|
23
|
+
height: ctx.screenHeight
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
17
27
|
const saveConversationLog = (events, targetOutputDir, sessionId)=>{
|
|
18
28
|
const logPath = node_path.join(targetOutputDir, `${sessionId}.md`);
|
|
19
29
|
let content = `# Conversation Log - ${sessionId}\n\n`;
|
|
@@ -253,6 +263,7 @@ const start = async (options)=>{
|
|
|
253
263
|
else console.warn('[CLI] Preflight check error:', e);
|
|
254
264
|
}
|
|
255
265
|
let targetOperator = null;
|
|
266
|
+
let screenResolutionInfo = '';
|
|
256
267
|
const targetType = options.target || await prompts_select({
|
|
257
268
|
message: 'Please select your operator target:',
|
|
258
269
|
options: [
|
|
@@ -283,7 +294,15 @@ const start = async (options)=>{
|
|
|
283
294
|
break;
|
|
284
295
|
case 'computer':
|
|
285
296
|
default:
|
|
286
|
-
|
|
297
|
+
const op = new ExposedNutJSOperator();
|
|
298
|
+
try {
|
|
299
|
+
const { width, height } = await op.getScreenResolution();
|
|
300
|
+
screenResolutionInfo = `Current screen resolution: ${width}x${height}. Please output absolute coordinates based on this resolution. `;
|
|
301
|
+
console.log(`[CLI] Detected screen resolution: ${width}x${height}`);
|
|
302
|
+
} catch (e) {
|
|
303
|
+
console.warn('[CLI] Failed to get screen resolution:', e);
|
|
304
|
+
}
|
|
305
|
+
targetOperator = op;
|
|
287
306
|
break;
|
|
288
307
|
}
|
|
289
308
|
const useTasksFile = Boolean(options.tasks);
|
|
@@ -306,7 +325,7 @@ const start = async (options)=>{
|
|
|
306
325
|
abortController.abort();
|
|
307
326
|
});
|
|
308
327
|
const systemPrompts = [
|
|
309
|
-
|
|
328
|
+
`${screenResolutionInfo}You are provided with a task description, a history of previous actions, and corresponding screenshots. Your goal is to perform the next action to complete the task. Please note that if performing the same action multiple times results in a static screen with no changes, you should attempt a modified or alternative action.`,
|
|
310
329
|
'## Function Definition\n\n- You have access to the following functions:\n{"type": "function", "name": "call_user", "parameters": {"type": "object", "properties": {"content": {"type": "string", "description": "Message or information displayed to the user to request their input, feedback, or guidance."}}, "required": []}, "description": "This function is used to interact with the user by displaying a message and requesting their input, feedback, or guidance."}\n{"type": "function", "name": "click", "parameters": {"type": "object", "properties": {"point": {"type": "string", "description": "Click coordinates. The format is: <point>x y</point>"}}, "required": ["point"]}, "description": "Mouse left single click action."}\n{"type": "function", "name": "drag", "parameters": {"type": "object", "properties": {"start_point": {"type": "string", "description": "Drag start point. The format is: <point>x y</point>"}, "end_point": {"type": "string", "description": "Drag end point. The format is: <point>x y</point>"}}, "required": ["start_point", "end_point"]}, "description": "Mouse left button drag action."}\n{"type": "function", "name": "finished", "parameters": {"type": "object", "properties": {"content": {"type": "string", "description": "Provide the final answer or response to complete the task."}}, "required": []}, "description": "This function is used to indicate the completion of a task by providing the final answer or response."}\n{"type": "function", "name": "hotkey", "parameters": {"type": "object", "properties": {"key": {"type": "string", "description": "Hotkeys you want to press. Split keys with a space and use lowercase."}}, "required": ["key"]}, "description": "Press hotkey."}\n{"type": "function", "function": {"name": "infeasible", "parameters": {"type": "object", "properties": {"content": {"type": "string", "description": "Message or information displayed to the user to explain why the current task is infeasible."}}, "required": ["content"]}, "description": "This function is used to indicate that the current task is infeasible thus agent ends the task."}\n{"type": "function", "name": "left_double", "parameters": {"type": "object", "properties": {"point": {"type": "string", "description": "Click coordinates. The format is: <point>x y</point>"}}, "required": ["point"]}, "description": "Mouse left double click action."}\n{"type": "function", "name": "right_single", "parameters": {"type": "object", "properties": {"point": {"type": "string", "description": "Click coordinates. The format is: <point>x y</point>"}}, "required": ["point"]}, "description": "Mouse right single click action."}\n{"type": "function", "name": "scroll", "parameters": {"type": "object", "properties": {"point": {"type": "string", "description": "Scroll start position. If not specified, default to execute on the current mouse position. The format is: <point>x y</point>"}, "direction": {"type": "string", "description": "Scroll direction.", "enum": ["up", "down", "left", "right"]}}, "required": ["direction", "point"]}, "description": "Scroll action."}\n{"type": "function", "name": "type", "parameters": {"type": "object", "properties": {"content": {"type": "string", "description": "Type content. If you want to submit your input, use \\n at the end of content."}}, "required": ["content"]}, "description": "Type content."}\n{"type": "function", "name": "wait", "parameters": {"type": "object", "properties": {"time": {"type": "integer", "description": "Wait time in seconds."}}, "required": []}, "description": "Wait for a while."}\n\n- To call a function, use the following structure without any suffix:\n\n<think_never_used_51bce0c785ca2f68081bfa7d91973934> reasoning process </think_never_used_51bce0c785ca2f68081bfa7d91973934>\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_name><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\n\n## Important Notes\n- Function calls must begin with <function_never_used_51bce0c785ca2f68081bfa7d91973934= and end with </function_never_used_51bce0c785ca2f68081bfa7d91973934>.\n- All required parameters must be explicitly provided.\n\n## Additional Notes\n- You can execute multiple actions within a single tool call. For example:\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_1><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_2><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_3>value_4</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\n- 当你判断任务请求是无法执行的时候,你应该调用Infeasible工具结束任务并解释原因。\n 判断标准:当一个请求符合以下任何一条标准时,应被归类为“无法执行”。\n 1. 技术/物理层面的矛盾: 指令本身包含逻辑上或物理上无法实现的要求。\n 2. 工具/功能错配: 指令要求在一个软件中执行另一个软件的功能,或者执行该软件根本不具备的功能。\n 3. 超出操作边界/范围: 指令要求执行的操作超出了当前用户会话、权限或应用程序的逻辑边界,涉及未告知的隐私信息或者未授权的操作。\n 4. 依赖隐性知识或外部条件: 任务的完成依赖于Agent无法获取的外部硬件、物理环境、未声明的插件/扩展、或特定的文件/数据。\n\n 输出指令:\n 如果请求被判断为“无法执行”,你应该向用户解释为什么这个任务超出了你的能力范围(例如,指出它需要直接操作某个硬件),并尽可能提供一个指导性的替代方案,让用户可以自己完成该任务。\n 你应该非常非常谨慎地使用Infeasible工具,因为它会直接结束任务并降低用户体验。所以非必要的时候,你不应该调用Infeasible工具,尽量以finish工具结束任务并向用户提示原因就好。'
|
|
311
330
|
];
|
|
312
331
|
const guiAgent = new GUIAgent({
|
package/dist/cli/start.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli/start.mjs","sources":["webpack://@ui-tars-test/cli/./src/cli/start.ts"],"sourcesContent":["/*\n * Copyright (c) 2025 Bytedance, Inc. and its affiliates.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport os from 'node:os';\nimport ffmpeg from 'fluent-ffmpeg';\n// @ts-ignore\nimport ffmpegStatic from 'ffmpeg-static';\n\nimport fetch from 'node-fetch';\nimport { GUIAgent } from '@ui-tars-test/agent-sdk';\nimport * as p from '@clack/prompts';\nimport yaml from 'js-yaml';\n\nimport { NutJSOperator } from '@ui-tars-test/operator-nutjs';\nimport { AdbOperator } from '@ui-tars-test/operator-adb';\nimport { BrowserOperator } from '@ui-tars-test/operator-browser';\n\nexport interface CliOptions {\n presets?: string;\n target?: string;\n query?: string;\n config?: string;\n output?: string;\n tasks?: string;\n maxLoopCount?: string;\n}\n\nconst saveConversationLog = (events: any[], targetOutputDir: string, sessionId: string) => {\n const logPath = path.join(targetOutputDir, `${sessionId}.md`);\n let content = `# Conversation Log - ${sessionId}\\n\\n`;\n\n events.forEach((e) => {\n const time = new Date(e.timestamp || Date.now()).toISOString();\n content += `## [${time}] ${e.type}\\n`;\n\n // Debug raw event structure in console to identify correct fields\n // console.log(`[DEBUG] Event type: ${e.type}`, JSON.stringify(e, null, 2));\n\n if (e.content) {\n if (Array.isArray(e.content)) {\n e.content.forEach((part: any) => {\n if (part.type === 'text') content += `${part.text}\\n`;\n if (part.type === 'image_url') content += `[Image Content]\\n`;\n });\n } else if (typeof e.content === 'string') {\n content += `${e.content}\\n`;\n } else {\n content += `\\`\\`\\`json\\n${JSON.stringify(e.content, null, 2)}\\n\\`\\`\\`\\n`;\n }\n }\n\n // Check specific event types based on observation\n // It seems 'tool_call' and 'assistant_message' might store data differently than expected\n // Let's try to be more permissive in finding the content\n\n if (e.type === 'tool_call') {\n // Based on ToolCallEvent interface in agent-event-stream.ts\n // It has 'name' and 'arguments' properties directly\n if (e.name) content += `> Tool Call: ${e.name}\\n`;\n if (e.arguments) content += `> Arguments: ${JSON.stringify(e.arguments, null, 2)}\\n`;\n\n // Fallback if it's nested in toolCall property\n const toolCall = e.toolCall;\n if (toolCall) {\n if (toolCall.name) content += `> Tool Call: ${toolCall.name}\\n`;\n if (toolCall.arguments)\n content += `> Arguments: ${JSON.stringify(toolCall.arguments, null, 2)}\\n`;\n }\n } else if (e.type === 'assistant_message') {\n // Based on AssistantMessageEvent interface in agent-event-stream.ts\n // It has 'content' and 'toolCalls' properties directly\n if (e.content) content += `${e.content}\\n`;\n if (e.rawContent) content += `\\n> Raw Content (Debug): ${JSON.stringify(e.rawContent)}\\n`;\n if (e.toolCalls) content += `> Tool Calls: ${JSON.stringify(e.toolCalls, null, 2)}\\n`;\n\n // Fallback if it's nested in message property\n const message = e.message;\n if (message) {\n if (message.content) content += `${message.content}\\n`;\n if (message.rawContent)\n content += `\\n> Raw Content (Debug): ${JSON.stringify(message.rawContent)}\\n`;\n if (message.tool_calls)\n content += `> Tool Calls: ${JSON.stringify(message.tool_calls, null, 2)}\\n`;\n }\n }\n\n if (e.metadata) {\n // Avoid printing large metadata like screenshots if they are embedded there (usually they are in content or separate)\n // For screenshot events, metadata might contain type='screenshot'\n if (e.metadata.type === 'screenshot') {\n content += `> Action: Screenshot captured\\n`;\n } else {\n content += `> Metadata: ${JSON.stringify(e.metadata)}\\n`;\n }\n }\n\n if (e.input) {\n content += `> Input: ${JSON.stringify(e.input, null, 2)}\\n`;\n }\n\n if (e.output) {\n content += `> Output: ${JSON.stringify(e.output, null, 2)}\\n`;\n }\n\n content += '\\n';\n });\n\n try {\n fs.writeFileSync(logPath, content);\n console.log(`[CLI] Conversation log saved: ${logPath}`);\n return logPath;\n } catch (err) {\n console.warn(`[CLI] Failed to save conversation log: ${err}`);\n return null;\n }\n};\n\nexport const start = async (options: CliOptions) => {\n if (ffmpegStatic) {\n let finalFfmpegPath = ffmpegStatic;\n // In production build (bundled), ffmpeg-static might return a path that doesn't exist\n // because it relies on __dirname which changes after bundling.\n // However, we copy the binary to the dist folder in post-build script.\n // We should check if we are running from the bundled version.\n const bundledFfmpegPath = path.join(__dirname, 'ffmpeg');\n if (fs.existsSync(bundledFfmpegPath)) {\n finalFfmpegPath = bundledFfmpegPath;\n console.log(`[CLI] Using bundled ffmpeg: ${finalFfmpegPath}`);\n } else {\n console.log(`[CLI] Using default ffmpeg-static path: ${finalFfmpegPath}`);\n }\n\n if (os.platform() === 'darwin' && os.arch() === 'arm64') {\n console.log(`[CLI] Setting ffmpeg path: ${finalFfmpegPath}`);\n }\n ffmpeg.setFfmpegPath(finalFfmpegPath);\n } else {\n console.warn(\n '[CLI] ffmpeg-static not found. Video generation might fail if ffmpeg is not in PATH.',\n );\n }\n\n const CONFIG_PATH = options.config || path.join(os.homedir(), '.gui-agent-cli.json');\n\n // read config file\n let config = {\n baseURL: '',\n apiKey: '', // secretlint-disable-line\n model: '',\n provider: 'openai', // Default provider\n useResponsesApi: false,\n maxLoopCount: options.maxLoopCount ? Number(options.maxLoopCount) : 1000,\n };\n\n if (options.presets) {\n const response = await fetch(options.presets);\n if (!response.ok) {\n throw new Error(`Failed to fetch preset: ${response.status}`);\n }\n\n const yamlText = await response.text();\n const preset = yaml.load(yamlText) as any;\n\n config.apiKey = preset?.vlmApiKey; // secretlint-disable-line\n config.baseURL = preset?.vlmBaseUrl;\n config.model = preset?.vlmModelName;\n config.useResponsesApi = preset?.useResponsesApi ?? false;\n } else if (fs.existsSync(CONFIG_PATH)) {\n try {\n config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));\n } catch (error) {\n console.warn('read config file failed', error);\n }\n }\n\n if (!config.baseURL || !config.apiKey || !config.model) {\n const configAnswers = await p.group(\n {\n provider: () =>\n p.select({\n message: 'Select model provider:',\n options: [\n { value: 'volcengine', label: 'VolcEngine' },\n { value: 'azure-openai', label: 'Azure OpenAI' },\n { value: 'anthropic', label: 'Anthropic Claude' },\n { value: 'openai', label: 'OpenAI' },\n { value: 'lm-studio', label: 'LM Studio' },\n { value: 'deepseek', label: 'DeepSeek' },\n { value: 'ollama', label: 'Ollama' },\n ],\n }),\n baseURL: () => p.text({ message: 'please input vlm model baseURL:' }),\n apiKey: () => p.text({ message: 'please input vlm model apiKey:' }), // secretlint-disable-line\n model: () => p.text({ message: 'please input vlm model name:' }),\n },\n {\n onCancel: () => {\n p.cancel('operation cancelled');\n process.exit(0);\n },\n },\n );\n\n config = { ...config, ...configAnswers };\n\n if (config.provider === 'azure-openai') {\n // Ensure azure config object exists\n if (!(config as any).azure) {\n (config as any).azure = {};\n }\n\n // Auto-populate azure.endpoint from baseURL if not present\n // This is crucial for our custom fetch interceptor in llm-client to work\n if (!(config as any).azure.endpoint && config.baseURL) {\n (config as any).azure.endpoint = config.baseURL;\n }\n\n if (!(config as any).azure?.apiVersion) {\n const azureConfig = await p.group(\n {\n apiVersion: () =>\n p.text({\n message: 'please input azure api version (optional, default: 2024-10-01-preview):',\n }),\n // Add prompt for X-TT-LOGID which is required for some internal gateways\n logId: () =>\n p.text({\n message: 'please input X-TT-LOGID (optional, for internal gateway):',\n }),\n },\n {\n onCancel: () => {\n p.cancel('operation cancelled');\n process.exit(0);\n },\n },\n );\n\n if (azureConfig.apiVersion) {\n (config as any).azure.apiVersion = azureConfig.apiVersion;\n }\n\n if (azureConfig.logId) {\n if (!(config as any).headers) {\n (config as any).headers = {};\n }\n (config as any).headers['X-TT-LOGID'] = azureConfig.logId;\n }\n }\n }\n\n // save config to file\n try {\n fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));\n console.log('model config file saved to:', CONFIG_PATH);\n } catch (error) {\n console.error('save model config file failed', error);\n }\n }\n\n // Diagnostic: print model config loaded\n try {\n const maskedKey = config.apiKey\n ? `${config.apiKey.slice(0, 6)}...${config.apiKey.slice(-4)}`\n : '(empty)';\n console.log('[CLI] Loaded model config:');\n console.log(` provider: ${config.provider}`);\n console.log(` baseURL: ${config.baseURL}`);\n console.log(` model: ${config.model}`);\n console.log(` apiKey: ${maskedKey}`); // secretlint-disable-line\n console.log(` useResponsesApi: ${Boolean((config as any).useResponsesApi)}`);\n } catch (e) {\n console.warn('[CLI] Failed to print model config diagnostics:', e);\n }\n\n // Basic baseURL validation and hints for OpenAI-compatible servers\n try {\n if (config.baseURL) {\n let parsed: URL | null = null;\n try {\n parsed = new URL(config.baseURL);\n } catch (_) {\n console.warn('[CLI] Warning: baseURL is not a valid URL:', config.baseURL);\n }\n if (parsed) {\n const endsWithV1 = /\\/v1\\/?$/.test(parsed.pathname);\n if (!endsWithV1) {\n console.warn(\n '[CLI] Hint: OpenAI-compatible endpoints typically end with \"/v1\" (e.g. https://host/v1).',\n );\n }\n if (parsed.protocol !== 'https:') {\n console.warn('[CLI] Hint: use HTTPS for most providers. Current:', parsed.protocol);\n }\n }\n }\n } catch (e) {\n console.warn('[CLI] baseURL validation failed:', e);\n }\n\n // Preflight: check Chat Completions non-streaming response shape for OpenAI-compatible servers\n try {\n if (config.provider === 'openai' && config.baseURL && config.model) {\n const url = new URL(config.baseURL.replace(/\\/$/, ''));\n url.pathname = url.pathname.replace(/\\/$/, '') + '/chat/completions';\n console.log('[CLI] Preflight: POST', url.toString());\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 16000);\n const resp = await fetch(url.toString(), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n },\n body: JSON.stringify({\n model: config.model,\n messages: [{ role: 'user', content: 'ping' }],\n stream: false,\n }),\n signal: controller.signal,\n } as any);\n clearTimeout(timeout);\n const text = await resp.text();\n if (!resp.ok) {\n console.warn('[CLI] Preflight failed:', resp.status, resp.statusText);\n console.warn('[CLI] Preflight response body:', text.slice(0, 500));\n } else {\n try {\n const json = JSON.parse(text);\n const hasChoices = Array.isArray(json?.choices) && json.choices.length > 0;\n console.log('[CLI] Preflight ok. choices[0] exists:', hasChoices);\n if (!hasChoices) {\n console.warn(\n '[CLI] Preflight: response does not contain choices[]. Service may not implement Chat Completions.',\n );\n }\n } catch (_) {\n console.warn('[CLI] Preflight ok but response is not JSON:', text.slice(0, 200));\n }\n }\n }\n } catch (e: any) {\n if (e?.name === 'AbortError') {\n console.warn('[CLI] Preflight check timed out (16s). Proceeding without preflight.');\n } else {\n console.warn('[CLI] Preflight check error:', e);\n }\n }\n\n let targetOperator = null;\n const targetType =\n options.target ||\n ((await p.select({\n message: 'Please select your operator target:',\n options: [\n { value: 'computer', label: 'computer (Desktop automation)' },\n { value: 'android', label: 'android (Android automation)' },\n { value: 'browser', label: 'browser (Web automation)' },\n ],\n })) as string);\n\n switch (targetType) {\n case 'android':\n // Note: AdbOperator will auto-detect connected devices\n console.log('Initializing ADB operator...');\n targetOperator = new AdbOperator();\n break;\n case 'browser':\n // Use default browser options\n targetOperator = new BrowserOperator({\n browserType: 'chrome' as any,\n browser: null as any, // Will be initialized internally\n });\n break;\n case 'computer':\n default:\n targetOperator = new NutJSOperator();\n break;\n }\n\n const useTasksFile = Boolean(options.tasks);\n const answers = useTasksFile\n ? { instruction: '' }\n : options.query\n ? { instruction: options.query }\n : await p.group(\n {\n instruction: () => p.text({ message: 'Input your instruction' }),\n },\n {\n onCancel: () => {\n p.cancel('操作已取消');\n process.exit(0);\n },\n },\n );\n\n const abortController = new AbortController();\n process.on('SIGINT', () => {\n abortController.abort();\n });\n\n const systemPrompts = [\n 'You are provided with a task description, a history of previous actions, and corresponding screenshots. Your goal is to perform the next action to complete the task. Please note that if performing the same action multiple times results in a static screen with no changes, you should attempt a modified or alternative action.',\n '## Function Definition\\n\\n- You have access to the following functions:\\n{\"type\": \"function\", \"name\": \"call_user\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Message or information displayed to the user to request their input, feedback, or guidance.\"}}, \"required\": []}, \"description\": \"This function is used to interact with the user by displaying a message and requesting their input, feedback, or guidance.\"}\\n{\"type\": \"function\", \"name\": \"click\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse left single click action.\"}\\n{\"type\": \"function\", \"name\": \"drag\", \"parameters\": {\"type\": \"object\", \"properties\": {\"start_point\": {\"type\": \"string\", \"description\": \"Drag start point. The format is: <point>x y</point>\"}, \"end_point\": {\"type\": \"string\", \"description\": \"Drag end point. The format is: <point>x y</point>\"}}, \"required\": [\"start_point\", \"end_point\"]}, \"description\": \"Mouse left button drag action.\"}\\n{\"type\": \"function\", \"name\": \"finished\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Provide the final answer or response to complete the task.\"}}, \"required\": []}, \"description\": \"This function is used to indicate the completion of a task by providing the final answer or response.\"}\\n{\"type\": \"function\", \"name\": \"hotkey\", \"parameters\": {\"type\": \"object\", \"properties\": {\"key\": {\"type\": \"string\", \"description\": \"Hotkeys you want to press. Split keys with a space and use lowercase.\"}}, \"required\": [\"key\"]}, \"description\": \"Press hotkey.\"}\\n{\"type\": \"function\", \"function\": {\"name\": \"infeasible\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Message or information displayed to the user to explain why the current task is infeasible.\"}}, \"required\": [\"content\"]}, \"description\": \"This function is used to indicate that the current task is infeasible thus agent ends the task.\"}\\n{\"type\": \"function\", \"name\": \"left_double\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse left double click action.\"}\\n{\"type\": \"function\", \"name\": \"right_single\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse right single click action.\"}\\n{\"type\": \"function\", \"name\": \"scroll\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Scroll start position. If not specified, default to execute on the current mouse position. The format is: <point>x y</point>\"}, \"direction\": {\"type\": \"string\", \"description\": \"Scroll direction.\", \"enum\": [\"up\", \"down\", \"left\", \"right\"]}}, \"required\": [\"direction\", \"point\"]}, \"description\": \"Scroll action.\"}\\n{\"type\": \"function\", \"name\": \"type\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Type content. If you want to submit your input, use \\\\n at the end of content.\"}}, \"required\": [\"content\"]}, \"description\": \"Type content.\"}\\n{\"type\": \"function\", \"name\": \"wait\", \"parameters\": {\"type\": \"object\", \"properties\": {\"time\": {\"type\": \"integer\", \"description\": \"Wait time in seconds.\"}}, \"required\": []}, \"description\": \"Wait for a while.\"}\\n\\n- To call a function, use the following structure without any suffix:\\n\\n<think_never_used_51bce0c785ca2f68081bfa7d91973934> reasoning process </think_never_used_51bce0c785ca2f68081bfa7d91973934>\\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_name><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\\n\\n## Important Notes\\n- Function calls must begin with <function_never_used_51bce0c785ca2f68081bfa7d91973934= and end with </function_never_used_51bce0c785ca2f68081bfa7d91973934>.\\n- All required parameters must be explicitly provided.\\n\\n## Additional Notes\\n- You can execute multiple actions within a single tool call. For example:\\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_1><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_2><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_3>value_4</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\\n- 当你判断任务请求是无法执行的时候,你应该调用Infeasible工具结束任务并解释原因。\\n 判断标准:当一个请求符合以下任何一条标准时,应被归类为“无法执行”。\\n 1. 技术/物理层面的矛盾: 指令本身包含逻辑上或物理上无法实现的要求。\\n 2. 工具/功能错配: 指令要求在一个软件中执行另一个软件的功能,或者执行该软件根本不具备的功能。\\n 3. 超出操作边界/范围: 指令要求执行的操作超出了当前用户会话、权限或应用程序的逻辑边界,涉及未告知的隐私信息或者未授权的操作。\\n 4. 依赖隐性知识或外部条件: 任务的完成依赖于Agent无法获取的外部硬件、物理环境、未声明的插件/扩展、或特定的文件/数据。\\n\\n 输出指令:\\n 如果请求被判断为“无法执行”,你应该向用户解释为什么这个任务超出了你的能力范围(例如,指出它需要直接操作某个硬件),并尽可能提供一个指导性的替代方案,让用户可以自己完成该任务。\\n 你应该非常非常谨慎地使用Infeasible工具,因为它会直接结束任务并降低用户体验。所以非必要的时候,你不应该调用Infeasible工具,尽量以finish工具结束任务并向用户提示原因就好。',\n ];\n\n const guiAgent = new GUIAgent({\n model: {\n id: config.model,\n provider: config.provider as any, // Type assertion to avoid TypeScript error\n baseURL: config.baseURL,\n apiKey: config.apiKey, // secretlint-disable-line\n azure: (config as any).azure,\n headers: (config as any).headers || (config as any).defaultHeaders,\n } as any,\n operator: targetOperator,\n systemPrompt: systemPrompts.join('\\n\\n'),\n });\n\n if (useTasksFile) {\n const demoDir = path.resolve(path.join(__dirname, '..', '..', 'demo'));\n const tasksPath =\n options.tasks === 'demo' ? path.join(demoDir, 'tasks.json') : path.resolve(options.tasks!);\n try {\n const dirOfTasks = path.dirname(tasksPath);\n fs.mkdirSync(dirOfTasks, { recursive: true });\n if (!fs.existsSync(tasksPath)) {\n const sample = [\n { taskId: 'task-1', query: 'Open Chrome and go to github.com' },\n { taskId: 'task-2', query: \"Search for 'GUI Agent automation' on Google\" },\n ];\n fs.writeFileSync(tasksPath, JSON.stringify(sample, null, 2));\n console.log(`[CLI] Sample tasks.json created: ${tasksPath}`);\n }\n } catch (e) {\n console.warn('[CLI] Failed to prepare tasks file directory', e);\n }\n\n let tasks: Array<{ taskId: string; query: string; timeout?: number }> = [];\n try {\n const raw = fs.readFileSync(tasksPath, 'utf-8');\n const parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) tasks = parsed;\n else console.warn('[CLI] tasks file is not an array');\n } catch (e) {\n console.error('[CLI] Failed to read tasks file', e);\n process.exit(1);\n }\n\n const targetOutputDir = options.output\n ? path.resolve(options.output)\n : options.tasks === 'demo'\n ? path.join(demoDir, 'results')\n : path.join(os.homedir(), '.gui-agent-results');\n console.log(`[CLI] Output directory (resolved): ${targetOutputDir}`);\n fs.mkdirSync(targetOutputDir, { recursive: true });\n\n for (const task of tasks) {\n const taskAC = new AbortController();\n const timeoutMs = task.timeout ?? 25 * 60 * 1000;\n const timeoutId = setTimeout(() => {\n console.log(`[CLI] Task ${task.taskId} timed out after ${timeoutMs}ms`);\n taskAC.abort();\n }, timeoutMs);\n\n const onGlobalAbort = () => taskAC.abort();\n abortController.signal.addEventListener('abort', onGlobalAbort);\n\n const taskAgent = new GUIAgent({\n model: {\n id: config.model,\n provider: config.provider as any, // Type assertion to avoid TypeScript error\n baseURL: config.baseURL,\n apiKey: config.apiKey, // secretlint-disable-line\n azure: (config as any).azure,\n headers: (config as any).headers || (config as any).defaultHeaders,\n } as any,\n operator: targetOperator,\n systemPrompt: systemPrompts.join('\\n\\n'),\n // @ts-ignore\n signal: taskAC.signal,\n });\n\n let resultEvent: any;\n const startTime = Date.now();\n\n try {\n console.log(`[CLI] Starting task: ${task.taskId} at ${new Date(startTime).toISOString()}`);\n resultEvent = await taskAgent.run(task.query);\n } catch (taskErr: any) {\n if (taskAC.signal.aborted) {\n console.warn(`[CLI] Task ${task.taskId} was aborted (Timeout or SIGINT).`);\n resultEvent = { content: 'Task aborted or timed out' };\n } else {\n console.error(`[CLI] Task failed: ${task.taskId}`, taskErr);\n resultEvent = { content: `Error: ${taskErr.message}` };\n }\n } finally {\n clearTimeout(timeoutId);\n abortController.signal.removeEventListener('abort', onGlobalAbort);\n }\n\n try {\n const endTime = Date.now();\n const duration = endTime - startTime;\n\n const eventStream = taskAgent.getEventStream();\n const allEvents = eventStream.getEvents();\n const runStartEvents = allEvents.filter((e: any) => e.type === 'agent_run_start');\n const lastRunStart = runStartEvents[runStartEvents.length - 1] as any;\n const startIndex = allEvents.findIndex((e: any) => e.id === lastRunStart?.id);\n const endIndex = allEvents.findIndex(\n (e: any, idx: number) => idx > startIndex && e.type === 'agent_run_end',\n );\n const rangeEvents =\n startIndex >= 0\n ? endIndex >= 0\n ? allEvents.slice(startIndex, endIndex + 1)\n : allEvents.slice(startIndex)\n : allEvents;\n const envEvents = rangeEvents.filter((e: any) => e.type === 'environment_input');\n const screenshotEvents = envEvents.filter(\n (e: any) => e.metadata && e.metadata.type === 'screenshot',\n );\n\n // Generate video recording from screenshots\n let videoPath = '';\n if (screenshotEvents.length > 0) {\n const tempDir = path.join(os.tmpdir(), 'gui-agent-rec', task.taskId);\n try {\n fs.mkdirSync(tempDir, { recursive: true });\n\n const validFrames: { file: string; timestamp: number }[] = [];\n let frameCount = 0;\n for (const event of screenshotEvents) {\n if (Array.isArray((event as any).content)) {\n const imgPart = ((event as any).content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n if (buffer.length > 0) {\n const extension =\n buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff\n ? 'jpg'\n : 'png';\n const fileName = `${String(frameCount).padStart(4, '0')}.${extension}`;\n const framePath = path.join(tempDir, fileName);\n fs.writeFileSync(framePath, buffer);\n validFrames.push({\n file: fileName,\n timestamp: (event as any).timestamp || Date.now(),\n });\n frameCount++;\n }\n }\n }\n }\n\n if (validFrames.length > 0) {\n const concatFilePath = path.join(tempDir, 'filelist.txt');\n let fileContent = '';\n const hasTimestamps = validFrames.some(\n (f, i) => i > 0 && f.timestamp !== validFrames[0].timestamp,\n );\n\n for (let i = 0; i < validFrames.length; i++) {\n const frame = validFrames[i];\n let duration = 1.0;\n if (hasTimestamps && i < validFrames.length - 1) {\n const diff = (validFrames[i + 1].timestamp - frame.timestamp) / 1000;\n if (diff > 0.1 && diff < 60) duration = diff;\n } else if (i === validFrames.length - 1) {\n duration = 2.0;\n }\n fileContent += `file '${frame.file}'\\n`;\n fileContent += `duration ${duration.toFixed(3)}\\n`;\n }\n if (validFrames.length > 0) {\n fileContent += `file '${validFrames[validFrames.length - 1].file}'\\n`;\n }\n fs.writeFileSync(concatFilePath, fileContent);\n\n const outputVideoPath = path.join(targetOutputDir, `${task.taskId}.mp4`);\n console.log(`[CLI] Generating video recording: ${outputVideoPath}`);\n\n await new Promise<void>((resolve, reject) => {\n ffmpeg()\n .input(concatFilePath)\n .inputOptions(['-f', 'concat', '-safe', '0'])\n .output(outputVideoPath)\n .outputOptions([\n '-c:v',\n 'libx264',\n '-pix_fmt',\n 'yuv420p',\n // scale needs to be even numbers for libx264\n '-vf',\n 'scale=trunc(iw/2)*2:trunc(ih/2)*2',\n ])\n .on('start', (cmd) => console.log(`[CLI] Ffmpeg command: ${cmd}`))\n .on('stderr', (line) => console.log(`[CLI] Ffmpeg stderr: ${line}`))\n .on('end', () => resolve())\n .on('error', (err: any) => {\n console.error('[CLI] Ffmpeg error:', err);\n reject(err);\n })\n .run();\n });\n\n videoPath = outputVideoPath;\n console.log(`[CLI] Video saved: ${videoPath}`);\n }\n } catch (recErr) {\n console.warn('[CLI] Failed to generate video recording', recErr);\n } finally {\n // Cleanup temp dir\n try {\n fs.rmSync(tempDir, { recursive: true, force: true });\n } catch (_) {\n /* ignore */\n }\n }\n }\n\n const lastScreenshot =\n screenshotEvents.length > 0\n ? (screenshotEvents[screenshotEvents.length - 1] as any)\n : null;\n\n let resultPicPath = '';\n if (lastScreenshot && Array.isArray(lastScreenshot.content)) {\n const imgPart = (lastScreenshot.content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n resultPicPath = path.join(targetOutputDir, `${task.taskId}.png`);\n fs.writeFileSync(resultPicPath, buffer);\n console.log(`[CLI] Screenshot saved: ${resultPicPath}`);\n }\n }\n if (!resultPicPath) {\n console.log('[CLI] No screenshot captured; resultPic will be empty.');\n }\n\n const conversationLogPath = saveConversationLog(rangeEvents, targetOutputDir, task.taskId);\n\n const finalAnswer = (resultEvent as any)?.content ?? '';\n const report = {\n taskId: task.taskId,\n taskContent: task.query,\n startTime,\n endTime,\n duration,\n resultPic: resultPicPath,\n video: videoPath || null,\n conversationLog: conversationLogPath,\n finalAnswer,\n };\n const reportPath = path.join(targetOutputDir, `${task.taskId}.json`);\n fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));\n console.log(`Result saved: ${reportPath}`);\n console.log(`[CLI] Report JSON path: ${reportPath}`);\n } catch (reportErr) {\n console.warn(`[CLI] Failed to save report for task ${task.taskId}`, reportErr);\n }\n }\n return;\n }\n\n // Enhanced error logging around agent run\n let resultEvent: any;\n const startTime = Date.now();\n let isReportSaved = false;\n\n const saveSingleTaskReport = async (finalAnswer: string) => {\n if (isReportSaved) return;\n isReportSaved = true;\n\n const endTime = Date.now();\n const duration = endTime - startTime;\n\n try {\n const eventStream = guiAgent.getEventStream();\n const allEvents = eventStream.getEvents();\n const runStartEvents = allEvents.filter((e: any) => e.type === 'agent_run_start');\n const sessionId =\n runStartEvents.length > 0\n ? (runStartEvents[runStartEvents.length - 1] as any).sessionId\n : `${Date.now()}`;\n\n const envEvents = allEvents.filter((e: any) => e.type === 'environment_input');\n const screenshotEvents = envEvents.filter(\n (e: any) => e.metadata && e.metadata.type === 'screenshot',\n );\n const lastScreenshot =\n screenshotEvents.length > 0 ? (screenshotEvents[screenshotEvents.length - 1] as any) : null;\n\n const targetOutputDir = options.output\n ? path.resolve(options.output)\n : path.join(os.homedir(), '.gui-agent-results');\n console.log(`[CLI] Output directory (resolved): ${targetOutputDir}`);\n fs.mkdirSync(targetOutputDir, { recursive: true });\n console.log(`[CLI] TaskId/SessionId: ${sessionId}`);\n\n // Generate video recording from screenshots\n let videoPath = '';\n if (screenshotEvents.length > 0) {\n const tempDir = path.join(os.tmpdir(), 'gui-agent-rec', sessionId);\n try {\n fs.mkdirSync(tempDir, { recursive: true });\n\n const validFrames: { file: string; timestamp: number }[] = [];\n let frameCount = 0;\n for (const event of screenshotEvents) {\n if (Array.isArray((event as any).content)) {\n const imgPart = ((event as any).content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n if (buffer.length > 0) {\n const extension =\n buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff ? 'jpg' : 'png';\n const fileName = `${String(frameCount).padStart(4, '0')}.${extension}`;\n const framePath = path.join(tempDir, fileName);\n fs.writeFileSync(framePath, buffer);\n validFrames.push({\n file: fileName,\n timestamp: (event as any).timestamp || Date.now(),\n });\n frameCount++;\n }\n }\n }\n }\n\n if (validFrames.length > 0) {\n const concatFilePath = path.join(tempDir, 'filelist.txt');\n let fileContent = '';\n const hasTimestamps = validFrames.some(\n (f, i) => i > 0 && f.timestamp !== validFrames[0].timestamp,\n );\n\n for (let i = 0; i < validFrames.length; i++) {\n const frame = validFrames[i];\n let duration = 1.0;\n if (hasTimestamps && i < validFrames.length - 1) {\n const diff = (validFrames[i + 1].timestamp - frame.timestamp) / 1000;\n if (diff > 0.1 && diff < 60) duration = diff;\n } else if (i === validFrames.length - 1) {\n duration = 2.0;\n }\n fileContent += `file '${frame.file}'\\n`;\n fileContent += `duration ${duration.toFixed(3)}\\n`;\n }\n if (validFrames.length > 0) {\n fileContent += `file '${validFrames[validFrames.length - 1].file}'\\n`;\n }\n fs.writeFileSync(concatFilePath, fileContent);\n\n const outputVideoPath = path.join(targetOutputDir, `${sessionId}.mp4`);\n console.log(`[CLI] Generating video recording: ${outputVideoPath}`);\n\n await new Promise<void>((resolve, reject) => {\n ffmpeg()\n .input(concatFilePath)\n .inputOptions(['-f', 'concat', '-safe', '0'])\n .output(outputVideoPath)\n .outputOptions([\n '-c:v',\n 'libx264',\n '-pix_fmt',\n 'yuv420p',\n // scale needs to be even numbers for libx264\n '-vf',\n 'scale=trunc(iw/2)*2:trunc(ih/2)*2',\n ])\n .on('start', (cmd) => console.log(`[CLI] Ffmpeg command: ${cmd}`))\n .on('stderr', (line) => console.log(`[CLI] Ffmpeg stderr: ${line}`))\n .on('end', () => resolve())\n .on('error', (err: any) => {\n console.error('[CLI] Ffmpeg error:', err);\n reject(err);\n })\n .run();\n });\n\n videoPath = outputVideoPath;\n console.log(`[CLI] Video saved: ${videoPath}`);\n }\n } catch (recErr) {\n console.warn('[CLI] Failed to generate video recording', recErr);\n } finally {\n // Cleanup temp dir\n try {\n fs.rmSync(tempDir, { recursive: true, force: true });\n } catch (_) {\n /* ignore */\n }\n }\n }\n\n let resultPicPath = '';\n if (lastScreenshot && Array.isArray(lastScreenshot.content)) {\n const imgPart = (lastScreenshot.content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n resultPicPath = path.join(targetOutputDir, `${sessionId}.png`);\n fs.writeFileSync(resultPicPath, buffer);\n console.log(`[CLI] Screenshot saved: ${resultPicPath}`);\n }\n }\n if (!resultPicPath) {\n console.log('[CLI] No screenshot captured; resultPic will be empty.');\n }\n\n const conversationLogPath = saveConversationLog(\n // For single task run, we can just use all events as it is a fresh process/run\n allEvents,\n targetOutputDir,\n sessionId,\n );\n\n const report = {\n taskId: sessionId,\n taskContent: answers.instruction || options.query,\n startTime,\n endTime,\n duration,\n resultPic: resultPicPath,\n video: videoPath || null,\n conversationLog: conversationLogPath,\n finalAnswer,\n };\n const reportPath = path.join(targetOutputDir, `${sessionId}.json`);\n fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));\n console.log(`Result saved: ${reportPath}`);\n console.log(`[CLI] Report JSON path: ${reportPath}`);\n } catch (err) {\n console.warn('Failed to generate result report:', err);\n }\n };\n\n process.removeAllListeners('SIGINT');\n process.on('SIGINT', async () => {\n console.log('\\n[CLI] Received SIGINT. Saving report and exiting...');\n abortController.abort();\n await saveSingleTaskReport('用户已手动终止');\n process.exit(0);\n });\n\n try {\n console.log(\n '[CLI] Starting GUIAgent run with instruction:',\n answers.instruction || options.query,\n );\n resultEvent = await guiAgent.run(answers.instruction);\n console.log('[CLI] GUIAgent run completed.');\n } catch (err: any) {\n if (err.name === 'AbortError' || abortController.signal.aborted) {\n console.log('[CLI] GUIAgent run aborted.');\n } else {\n console.error('[CLI] GUIAgent run failed.');\n const errMsg = err?.message || String(err);\n console.error('[CLI] Error message:', errMsg);\n if (err?.status) console.error('[CLI] HTTP status:', err.status);\n if (err?.code) console.error('[CLI] Error code:', err.code);\n const respData = err?.response?.data || err?.response?.body || err?.data;\n if (respData) {\n try {\n const text = typeof respData === 'string' ? respData : JSON.stringify(respData);\n console.error('[CLI] Response body:', text.slice(0, 500));\n } catch (_) {\n console.error('[CLI] Response body: [unprintable]');\n }\n }\n }\n }\n\n await saveSingleTaskReport((resultEvent as any)?.content ?? '');\n};\n\nexport const resetConfig = async (configPath?: string) => {\n const CONFIG_PATH = configPath || path.join(os.homedir(), '.gui-agent-cli.json');\n\n try {\n if (fs.existsSync(CONFIG_PATH)) {\n fs.unlinkSync(CONFIG_PATH);\n console.log(`✓ Configuration file removed: ${CONFIG_PATH}`);\n } else {\n console.log(`No configuration file found at: ${CONFIG_PATH}`);\n }\n\n console.log(\n 'Configuration has been reset. The next time you run gui-agent, you will be prompted to configure your settings again.',\n );\n } catch (error) {\n console.error('Failed to reset configuration:', error);\n process.exit(1);\n }\n};\n"],"names":["saveConversationLog","events","targetOutputDir","sessionId","logPath","path","content","e","time","Date","Array","part","JSON","toolCall","message","fs","console","err","start","options","ffmpegStatic","finalFfmpegPath","bundledFfmpegPath","__dirname","os","ffmpeg","CONFIG_PATH","config","Number","response","fetch","Error","yamlText","preset","yaml","error","configAnswers","p","process","_config_azure","azureConfig","maskedKey","Boolean","parsed","URL","_","endsWithV1","url","controller","AbortController","timeout","setTimeout","resp","clearTimeout","text","json","hasChoices","targetOperator","targetType","AdbOperator","BrowserOperator","NutJSOperator","useTasksFile","answers","abortController","systemPrompts","guiAgent","GUIAgent","demoDir","tasksPath","dirOfTasks","sample","tasks","raw","task","taskAC","timeoutMs","timeoutId","onGlobalAbort","taskAgent","resultEvent","startTime","taskErr","endTime","duration","eventStream","allEvents","runStartEvents","lastRunStart","startIndex","endIndex","idx","rangeEvents","envEvents","screenshotEvents","videoPath","tempDir","validFrames","frameCount","event","_imgPart_image_url","imgPart","c","dataUri","commaIndex","base64Data","buffer","Buffer","extension","fileName","String","framePath","concatFilePath","fileContent","hasTimestamps","f","i","frame","diff","outputVideoPath","Promise","resolve","reject","cmd","line","recErr","lastScreenshot","resultPicPath","_imgPart_image_url1","conversationLogPath","finalAnswer","report","reportPath","reportErr","isReportSaved","saveSingleTaskReport","_err_response","_err_response1","errMsg","respData","resetConfig","configPath"],"mappings":";;;;;;;;;;;;;;;;AAiCA,MAAMA,sBAAsB,CAACC,QAAeC,iBAAyBC;IACnE,MAAMC,UAAUC,UAAAA,IAAS,CAACH,iBAAiB,GAAGC,UAAU,GAAG,CAAC;IAC5D,IAAIG,UAAU,CAAC,qBAAqB,EAAEH,UAAU,IAAI,CAAC;IAErDF,OAAO,OAAO,CAAC,CAACM;QACd,MAAMC,OAAO,IAAIC,KAAKF,EAAE,SAAS,IAAIE,KAAK,GAAG,IAAI,WAAW;QAC5DH,WAAW,CAAC,IAAI,EAAEE,KAAK,EAAE,EAAED,EAAE,IAAI,CAAC,EAAE,CAAC;QAKrC,IAAIA,EAAE,OAAO,EACX,IAAIG,MAAM,OA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T,GAAG;gBACV7B,QAAQ,KAAK,CAAC;YAChB;QAEJ;IACF;IAEA,MAAMuH,qBAAqB,AAACvD,CAAAA,QAAAA,cAAAA,KAAAA,IAAAA,YAAqB,OAAO,AAAD,KAAK;AAC9D;AAEO,MAAM4D,cAAc,OAAOC;IAChC,MAAMnH,cAAcmH,cAAcxI,UAAAA,IAAS,CAACmB,QAAAA,OAAU,IAAI;IAE1D,IAAI;QACF,IAAIT,QAAAA,UAAa,CAACW,cAAc;YAC9BX,QAAAA,UAAa,CAACW;YACdV,QAAQ,GAAG,CAAC,CAAC,qCAA8B,EAAEU,aAAa;QAC5D,OACEV,QAAQ,GAAG,CAAC,CAAC,gCAAgC,EAAEU,aAAa;QAG9DV,QAAQ,GAAG,CACT;IAEJ,EAAE,OAAOmB,OAAO;QACdnB,QAAQ,KAAK,CAAC,kCAAkCmB;QAChDG,QAAQ,IAAI,CAAC;IACf;AACF"}
|
|
1
|
+
{"version":3,"file":"cli/start.mjs","sources":["webpack://@ui-tars-test/cli/./src/cli/start.ts"],"sourcesContent":["/*\n * Copyright (c) 2025 Bytedance, Inc. and its affiliates.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport os from 'node:os';\nimport ffmpeg from 'fluent-ffmpeg';\n// @ts-ignore\nimport ffmpegStatic from 'ffmpeg-static';\n\nimport fetch from 'node-fetch';\nimport { GUIAgent } from '@ui-tars-test/agent-sdk';\nimport * as p from '@clack/prompts';\nimport yaml from 'js-yaml';\n\nimport { NutJSOperator } from '@ui-tars-test/operator-nutjs';\nimport { AdbOperator } from '@ui-tars-test/operator-adb';\nimport { BrowserOperator } from '@ui-tars-test/operator-browser';\n\nclass ExposedNutJSOperator extends NutJSOperator {\n public async getScreenResolution() {\n await this.initialize();\n const ctx = this.screenContext();\n return { width: ctx.screenWidth, height: ctx.screenHeight };\n }\n}\n\nexport interface CliOptions {\n presets?: string;\n target?: string;\n query?: string;\n config?: string;\n output?: string;\n tasks?: string;\n maxLoopCount?: string;\n}\n\nconst saveConversationLog = (events: any[], targetOutputDir: string, sessionId: string) => {\n const logPath = path.join(targetOutputDir, `${sessionId}.md`);\n let content = `# Conversation Log - ${sessionId}\\n\\n`;\n\n events.forEach((e) => {\n const time = new Date(e.timestamp || Date.now()).toISOString();\n content += `## [${time}] ${e.type}\\n`;\n\n // Debug raw event structure in console to identify correct fields\n // console.log(`[DEBUG] Event type: ${e.type}`, JSON.stringify(e, null, 2));\n\n if (e.content) {\n if (Array.isArray(e.content)) {\n e.content.forEach((part: any) => {\n if (part.type === 'text') content += `${part.text}\\n`;\n if (part.type === 'image_url') content += `[Image Content]\\n`;\n });\n } else if (typeof e.content === 'string') {\n content += `${e.content}\\n`;\n } else {\n content += `\\`\\`\\`json\\n${JSON.stringify(e.content, null, 2)}\\n\\`\\`\\`\\n`;\n }\n }\n\n // Check specific event types based on observation\n // It seems 'tool_call' and 'assistant_message' might store data differently than expected\n // Let's try to be more permissive in finding the content\n\n if (e.type === 'tool_call') {\n // Based on ToolCallEvent interface in agent-event-stream.ts\n // It has 'name' and 'arguments' properties directly\n if (e.name) content += `> Tool Call: ${e.name}\\n`;\n if (e.arguments) content += `> Arguments: ${JSON.stringify(e.arguments, null, 2)}\\n`;\n\n // Fallback if it's nested in toolCall property\n const toolCall = e.toolCall;\n if (toolCall) {\n if (toolCall.name) content += `> Tool Call: ${toolCall.name}\\n`;\n if (toolCall.arguments)\n content += `> Arguments: ${JSON.stringify(toolCall.arguments, null, 2)}\\n`;\n }\n } else if (e.type === 'assistant_message') {\n // Based on AssistantMessageEvent interface in agent-event-stream.ts\n // It has 'content' and 'toolCalls' properties directly\n if (e.content) content += `${e.content}\\n`;\n if (e.rawContent) content += `\\n> Raw Content (Debug): ${JSON.stringify(e.rawContent)}\\n`;\n if (e.toolCalls) content += `> Tool Calls: ${JSON.stringify(e.toolCalls, null, 2)}\\n`;\n\n // Fallback if it's nested in message property\n const message = e.message;\n if (message) {\n if (message.content) content += `${message.content}\\n`;\n if (message.rawContent)\n content += `\\n> Raw Content (Debug): ${JSON.stringify(message.rawContent)}\\n`;\n if (message.tool_calls)\n content += `> Tool Calls: ${JSON.stringify(message.tool_calls, null, 2)}\\n`;\n }\n }\n\n if (e.metadata) {\n // Avoid printing large metadata like screenshots if they are embedded there (usually they are in content or separate)\n // For screenshot events, metadata might contain type='screenshot'\n if (e.metadata.type === 'screenshot') {\n content += `> Action: Screenshot captured\\n`;\n } else {\n content += `> Metadata: ${JSON.stringify(e.metadata)}\\n`;\n }\n }\n\n if (e.input) {\n content += `> Input: ${JSON.stringify(e.input, null, 2)}\\n`;\n }\n\n if (e.output) {\n content += `> Output: ${JSON.stringify(e.output, null, 2)}\\n`;\n }\n\n content += '\\n';\n });\n\n try {\n fs.writeFileSync(logPath, content);\n console.log(`[CLI] Conversation log saved: ${logPath}`);\n return logPath;\n } catch (err) {\n console.warn(`[CLI] Failed to save conversation log: ${err}`);\n return null;\n }\n};\n\nexport const start = async (options: CliOptions) => {\n if (ffmpegStatic) {\n let finalFfmpegPath = ffmpegStatic;\n // In production build (bundled), ffmpeg-static might return a path that doesn't exist\n // because it relies on __dirname which changes after bundling.\n // However, we copy the binary to the dist folder in post-build script.\n // We should check if we are running from the bundled version.\n const bundledFfmpegPath = path.join(__dirname, 'ffmpeg');\n if (fs.existsSync(bundledFfmpegPath)) {\n finalFfmpegPath = bundledFfmpegPath;\n console.log(`[CLI] Using bundled ffmpeg: ${finalFfmpegPath}`);\n } else {\n console.log(`[CLI] Using default ffmpeg-static path: ${finalFfmpegPath}`);\n }\n\n if (os.platform() === 'darwin' && os.arch() === 'arm64') {\n console.log(`[CLI] Setting ffmpeg path: ${finalFfmpegPath}`);\n }\n ffmpeg.setFfmpegPath(finalFfmpegPath);\n } else {\n console.warn(\n '[CLI] ffmpeg-static not found. Video generation might fail if ffmpeg is not in PATH.',\n );\n }\n\n const CONFIG_PATH = options.config || path.join(os.homedir(), '.gui-agent-cli.json');\n\n // read config file\n let config = {\n baseURL: '',\n apiKey: '', // secretlint-disable-line\n model: '',\n provider: 'openai', // Default provider\n useResponsesApi: false,\n maxLoopCount: options.maxLoopCount ? Number(options.maxLoopCount) : 1000,\n };\n\n if (options.presets) {\n const response = await fetch(options.presets);\n if (!response.ok) {\n throw new Error(`Failed to fetch preset: ${response.status}`);\n }\n\n const yamlText = await response.text();\n const preset = yaml.load(yamlText) as any;\n\n config.apiKey = preset?.vlmApiKey; // secretlint-disable-line\n config.baseURL = preset?.vlmBaseUrl;\n config.model = preset?.vlmModelName;\n config.useResponsesApi = preset?.useResponsesApi ?? false;\n } else if (fs.existsSync(CONFIG_PATH)) {\n try {\n config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));\n } catch (error) {\n console.warn('read config file failed', error);\n }\n }\n\n if (!config.baseURL || !config.apiKey || !config.model) {\n const configAnswers = await p.group(\n {\n provider: () =>\n p.select({\n message: 'Select model provider:',\n options: [\n { value: 'volcengine', label: 'VolcEngine' },\n { value: 'azure-openai', label: 'Azure OpenAI' },\n { value: 'anthropic', label: 'Anthropic Claude' },\n { value: 'openai', label: 'OpenAI' },\n { value: 'lm-studio', label: 'LM Studio' },\n { value: 'deepseek', label: 'DeepSeek' },\n { value: 'ollama', label: 'Ollama' },\n ],\n }),\n baseURL: () => p.text({ message: 'please input vlm model baseURL:' }),\n apiKey: () => p.text({ message: 'please input vlm model apiKey:' }), // secretlint-disable-line\n model: () => p.text({ message: 'please input vlm model name:' }),\n },\n {\n onCancel: () => {\n p.cancel('operation cancelled');\n process.exit(0);\n },\n },\n );\n\n config = { ...config, ...configAnswers };\n\n if (config.provider === 'azure-openai') {\n // Ensure azure config object exists\n if (!(config as any).azure) {\n (config as any).azure = {};\n }\n\n // Auto-populate azure.endpoint from baseURL if not present\n // This is crucial for our custom fetch interceptor in llm-client to work\n if (!(config as any).azure.endpoint && config.baseURL) {\n (config as any).azure.endpoint = config.baseURL;\n }\n\n if (!(config as any).azure?.apiVersion) {\n const azureConfig = await p.group(\n {\n apiVersion: () =>\n p.text({\n message: 'please input azure api version (optional, default: 2024-10-01-preview):',\n }),\n // Add prompt for X-TT-LOGID which is required for some internal gateways\n logId: () =>\n p.text({\n message: 'please input X-TT-LOGID (optional, for internal gateway):',\n }),\n },\n {\n onCancel: () => {\n p.cancel('operation cancelled');\n process.exit(0);\n },\n },\n );\n\n if (azureConfig.apiVersion) {\n (config as any).azure.apiVersion = azureConfig.apiVersion;\n }\n\n if (azureConfig.logId) {\n if (!(config as any).headers) {\n (config as any).headers = {};\n }\n (config as any).headers['X-TT-LOGID'] = azureConfig.logId;\n }\n }\n }\n\n // save config to file\n try {\n fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));\n console.log('model config file saved to:', CONFIG_PATH);\n } catch (error) {\n console.error('save model config file failed', error);\n }\n }\n\n // Diagnostic: print model config loaded\n try {\n const maskedKey = config.apiKey\n ? `${config.apiKey.slice(0, 6)}...${config.apiKey.slice(-4)}`\n : '(empty)';\n console.log('[CLI] Loaded model config:');\n console.log(` provider: ${config.provider}`);\n console.log(` baseURL: ${config.baseURL}`);\n console.log(` model: ${config.model}`);\n console.log(` apiKey: ${maskedKey}`); // secretlint-disable-line\n console.log(` useResponsesApi: ${Boolean((config as any).useResponsesApi)}`);\n } catch (e) {\n console.warn('[CLI] Failed to print model config diagnostics:', e);\n }\n\n // Basic baseURL validation and hints for OpenAI-compatible servers\n try {\n if (config.baseURL) {\n let parsed: URL | null = null;\n try {\n parsed = new URL(config.baseURL);\n } catch (_) {\n console.warn('[CLI] Warning: baseURL is not a valid URL:', config.baseURL);\n }\n if (parsed) {\n const endsWithV1 = /\\/v1\\/?$/.test(parsed.pathname);\n if (!endsWithV1) {\n console.warn(\n '[CLI] Hint: OpenAI-compatible endpoints typically end with \"/v1\" (e.g. https://host/v1).',\n );\n }\n if (parsed.protocol !== 'https:') {\n console.warn('[CLI] Hint: use HTTPS for most providers. Current:', parsed.protocol);\n }\n }\n }\n } catch (e) {\n console.warn('[CLI] baseURL validation failed:', e);\n }\n\n // Preflight: check Chat Completions non-streaming response shape for OpenAI-compatible servers\n try {\n if (config.provider === 'openai' && config.baseURL && config.model) {\n const url = new URL(config.baseURL.replace(/\\/$/, ''));\n url.pathname = url.pathname.replace(/\\/$/, '') + '/chat/completions';\n console.log('[CLI] Preflight: POST', url.toString());\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 16000);\n const resp = await fetch(url.toString(), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n },\n body: JSON.stringify({\n model: config.model,\n messages: [{ role: 'user', content: 'ping' }],\n stream: false,\n }),\n signal: controller.signal,\n } as any);\n clearTimeout(timeout);\n const text = await resp.text();\n if (!resp.ok) {\n console.warn('[CLI] Preflight failed:', resp.status, resp.statusText);\n console.warn('[CLI] Preflight response body:', text.slice(0, 500));\n } else {\n try {\n const json = JSON.parse(text);\n const hasChoices = Array.isArray(json?.choices) && json.choices.length > 0;\n console.log('[CLI] Preflight ok. choices[0] exists:', hasChoices);\n if (!hasChoices) {\n console.warn(\n '[CLI] Preflight: response does not contain choices[]. Service may not implement Chat Completions.',\n );\n }\n } catch (_) {\n console.warn('[CLI] Preflight ok but response is not JSON:', text.slice(0, 200));\n }\n }\n }\n } catch (e: any) {\n if (e?.name === 'AbortError') {\n console.warn('[CLI] Preflight check timed out (16s). Proceeding without preflight.');\n } else {\n console.warn('[CLI] Preflight check error:', e);\n }\n }\n\n let targetOperator = null;\n let screenResolutionInfo = '';\n const targetType =\n options.target ||\n ((await p.select({\n message: 'Please select your operator target:',\n options: [\n { value: 'computer', label: 'computer (Desktop automation)' },\n { value: 'android', label: 'android (Android automation)' },\n { value: 'browser', label: 'browser (Web automation)' },\n ],\n })) as string);\n\n switch (targetType) {\n case 'android':\n // Note: AdbOperator will auto-detect connected devices\n console.log('Initializing ADB operator...');\n targetOperator = new AdbOperator();\n break;\n case 'browser':\n // Use default browser options\n targetOperator = new BrowserOperator({\n browserType: 'chrome' as any,\n browser: null as any, // Will be initialized internally\n });\n break;\n case 'computer':\n default:\n const op = new ExposedNutJSOperator();\n try {\n const { width, height } = await op.getScreenResolution();\n screenResolutionInfo = `Current screen resolution: ${width}x${height}. Please output absolute coordinates based on this resolution. `;\n console.log(`[CLI] Detected screen resolution: ${width}x${height}`);\n } catch (e) {\n console.warn('[CLI] Failed to get screen resolution:', e);\n }\n targetOperator = op;\n break;\n }\n\n const useTasksFile = Boolean(options.tasks);\n const answers = useTasksFile\n ? { instruction: '' }\n : options.query\n ? { instruction: options.query }\n : await p.group(\n {\n instruction: () => p.text({ message: 'Input your instruction' }),\n },\n {\n onCancel: () => {\n p.cancel('操作已取消');\n process.exit(0);\n },\n },\n );\n\n const abortController = new AbortController();\n process.on('SIGINT', () => {\n abortController.abort();\n });\n\n const systemPrompts = [\n `${screenResolutionInfo}You are provided with a task description, a history of previous actions, and corresponding screenshots. Your goal is to perform the next action to complete the task. Please note that if performing the same action multiple times results in a static screen with no changes, you should attempt a modified or alternative action.`,\n '## Function Definition\\n\\n- You have access to the following functions:\\n{\"type\": \"function\", \"name\": \"call_user\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Message or information displayed to the user to request their input, feedback, or guidance.\"}}, \"required\": []}, \"description\": \"This function is used to interact with the user by displaying a message and requesting their input, feedback, or guidance.\"}\\n{\"type\": \"function\", \"name\": \"click\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse left single click action.\"}\\n{\"type\": \"function\", \"name\": \"drag\", \"parameters\": {\"type\": \"object\", \"properties\": {\"start_point\": {\"type\": \"string\", \"description\": \"Drag start point. The format is: <point>x y</point>\"}, \"end_point\": {\"type\": \"string\", \"description\": \"Drag end point. The format is: <point>x y</point>\"}}, \"required\": [\"start_point\", \"end_point\"]}, \"description\": \"Mouse left button drag action.\"}\\n{\"type\": \"function\", \"name\": \"finished\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Provide the final answer or response to complete the task.\"}}, \"required\": []}, \"description\": \"This function is used to indicate the completion of a task by providing the final answer or response.\"}\\n{\"type\": \"function\", \"name\": \"hotkey\", \"parameters\": {\"type\": \"object\", \"properties\": {\"key\": {\"type\": \"string\", \"description\": \"Hotkeys you want to press. Split keys with a space and use lowercase.\"}}, \"required\": [\"key\"]}, \"description\": \"Press hotkey.\"}\\n{\"type\": \"function\", \"function\": {\"name\": \"infeasible\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Message or information displayed to the user to explain why the current task is infeasible.\"}}, \"required\": [\"content\"]}, \"description\": \"This function is used to indicate that the current task is infeasible thus agent ends the task.\"}\\n{\"type\": \"function\", \"name\": \"left_double\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse left double click action.\"}\\n{\"type\": \"function\", \"name\": \"right_single\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Click coordinates. The format is: <point>x y</point>\"}}, \"required\": [\"point\"]}, \"description\": \"Mouse right single click action.\"}\\n{\"type\": \"function\", \"name\": \"scroll\", \"parameters\": {\"type\": \"object\", \"properties\": {\"point\": {\"type\": \"string\", \"description\": \"Scroll start position. If not specified, default to execute on the current mouse position. The format is: <point>x y</point>\"}, \"direction\": {\"type\": \"string\", \"description\": \"Scroll direction.\", \"enum\": [\"up\", \"down\", \"left\", \"right\"]}}, \"required\": [\"direction\", \"point\"]}, \"description\": \"Scroll action.\"}\\n{\"type\": \"function\", \"name\": \"type\", \"parameters\": {\"type\": \"object\", \"properties\": {\"content\": {\"type\": \"string\", \"description\": \"Type content. If you want to submit your input, use \\\\n at the end of content.\"}}, \"required\": [\"content\"]}, \"description\": \"Type content.\"}\\n{\"type\": \"function\", \"name\": \"wait\", \"parameters\": {\"type\": \"object\", \"properties\": {\"time\": {\"type\": \"integer\", \"description\": \"Wait time in seconds.\"}}, \"required\": []}, \"description\": \"Wait for a while.\"}\\n\\n- To call a function, use the following structure without any suffix:\\n\\n<think_never_used_51bce0c785ca2f68081bfa7d91973934> reasoning process </think_never_used_51bce0c785ca2f68081bfa7d91973934>\\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_name><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\\n\\n## Important Notes\\n- Function calls must begin with <function_never_used_51bce0c785ca2f68081bfa7d91973934= and end with </function_never_used_51bce0c785ca2f68081bfa7d91973934>.\\n- All required parameters must be explicitly provided.\\n\\n## Additional Notes\\n- You can execute multiple actions within a single tool call. For example:\\n<seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_1><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_1>value_1</parameter_never_used_51bce0c785ca2f68081bfa7d91973934><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934><function_never_used_51bce0c785ca2f68081bfa7d91973934=example_function_2><parameter_never_used_51bce0c785ca2f68081bfa7d91973934=example_parameter_3>value_4</parameter_never_used_51bce0c785ca2f68081bfa7d91973934></function_never_used_51bce0c785ca2f68081bfa7d91973934></seed:tool_call_never_used_51bce0c785ca2f68081bfa7d91973934>\\n- 当你判断任务请求是无法执行的时候,你应该调用Infeasible工具结束任务并解释原因。\\n 判断标准:当一个请求符合以下任何一条标准时,应被归类为“无法执行”。\\n 1. 技术/物理层面的矛盾: 指令本身包含逻辑上或物理上无法实现的要求。\\n 2. 工具/功能错配: 指令要求在一个软件中执行另一个软件的功能,或者执行该软件根本不具备的功能。\\n 3. 超出操作边界/范围: 指令要求执行的操作超出了当前用户会话、权限或应用程序的逻辑边界,涉及未告知的隐私信息或者未授权的操作。\\n 4. 依赖隐性知识或外部条件: 任务的完成依赖于Agent无法获取的外部硬件、物理环境、未声明的插件/扩展、或特定的文件/数据。\\n\\n 输出指令:\\n 如果请求被判断为“无法执行”,你应该向用户解释为什么这个任务超出了你的能力范围(例如,指出它需要直接操作某个硬件),并尽可能提供一个指导性的替代方案,让用户可以自己完成该任务。\\n 你应该非常非常谨慎地使用Infeasible工具,因为它会直接结束任务并降低用户体验。所以非必要的时候,你不应该调用Infeasible工具,尽量以finish工具结束任务并向用户提示原因就好。',\n ];\n\n const guiAgent = new GUIAgent({\n model: {\n id: config.model,\n provider: config.provider as any, // Type assertion to avoid TypeScript error\n baseURL: config.baseURL,\n apiKey: config.apiKey, // secretlint-disable-line\n azure: (config as any).azure,\n headers: (config as any).headers || (config as any).defaultHeaders,\n } as any,\n operator: targetOperator,\n systemPrompt: systemPrompts.join('\\n\\n'),\n });\n\n if (useTasksFile) {\n const demoDir = path.resolve(path.join(__dirname, '..', '..', 'demo'));\n const tasksPath =\n options.tasks === 'demo' ? path.join(demoDir, 'tasks.json') : path.resolve(options.tasks!);\n try {\n const dirOfTasks = path.dirname(tasksPath);\n fs.mkdirSync(dirOfTasks, { recursive: true });\n if (!fs.existsSync(tasksPath)) {\n const sample = [\n { taskId: 'task-1', query: 'Open Chrome and go to github.com' },\n { taskId: 'task-2', query: \"Search for 'GUI Agent automation' on Google\" },\n ];\n fs.writeFileSync(tasksPath, JSON.stringify(sample, null, 2));\n console.log(`[CLI] Sample tasks.json created: ${tasksPath}`);\n }\n } catch (e) {\n console.warn('[CLI] Failed to prepare tasks file directory', e);\n }\n\n let tasks: Array<{ taskId: string; query: string; timeout?: number }> = [];\n try {\n const raw = fs.readFileSync(tasksPath, 'utf-8');\n const parsed = JSON.parse(raw);\n if (Array.isArray(parsed)) tasks = parsed;\n else console.warn('[CLI] tasks file is not an array');\n } catch (e) {\n console.error('[CLI] Failed to read tasks file', e);\n process.exit(1);\n }\n\n const targetOutputDir = options.output\n ? path.resolve(options.output)\n : options.tasks === 'demo'\n ? path.join(demoDir, 'results')\n : path.join(os.homedir(), '.gui-agent-results');\n console.log(`[CLI] Output directory (resolved): ${targetOutputDir}`);\n fs.mkdirSync(targetOutputDir, { recursive: true });\n\n for (const task of tasks) {\n const taskAC = new AbortController();\n const timeoutMs = task.timeout ?? 25 * 60 * 1000;\n const timeoutId = setTimeout(() => {\n console.log(`[CLI] Task ${task.taskId} timed out after ${timeoutMs}ms`);\n taskAC.abort();\n }, timeoutMs);\n\n const onGlobalAbort = () => taskAC.abort();\n abortController.signal.addEventListener('abort', onGlobalAbort);\n\n const taskAgent = new GUIAgent({\n model: {\n id: config.model,\n provider: config.provider as any, // Type assertion to avoid TypeScript error\n baseURL: config.baseURL,\n apiKey: config.apiKey, // secretlint-disable-line\n azure: (config as any).azure,\n headers: (config as any).headers || (config as any).defaultHeaders,\n } as any,\n operator: targetOperator,\n systemPrompt: systemPrompts.join('\\n\\n'),\n // @ts-ignore\n signal: taskAC.signal,\n });\n\n let resultEvent: any;\n const startTime = Date.now();\n\n try {\n console.log(`[CLI] Starting task: ${task.taskId} at ${new Date(startTime).toISOString()}`);\n resultEvent = await taskAgent.run(task.query);\n } catch (taskErr: any) {\n if (taskAC.signal.aborted) {\n console.warn(`[CLI] Task ${task.taskId} was aborted (Timeout or SIGINT).`);\n resultEvent = { content: 'Task aborted or timed out' };\n } else {\n console.error(`[CLI] Task failed: ${task.taskId}`, taskErr);\n resultEvent = { content: `Error: ${taskErr.message}` };\n }\n } finally {\n clearTimeout(timeoutId);\n abortController.signal.removeEventListener('abort', onGlobalAbort);\n }\n\n try {\n const endTime = Date.now();\n const duration = endTime - startTime;\n\n const eventStream = taskAgent.getEventStream();\n const allEvents = eventStream.getEvents();\n const runStartEvents = allEvents.filter((e: any) => e.type === 'agent_run_start');\n const lastRunStart = runStartEvents[runStartEvents.length - 1] as any;\n const startIndex = allEvents.findIndex((e: any) => e.id === lastRunStart?.id);\n const endIndex = allEvents.findIndex(\n (e: any, idx: number) => idx > startIndex && e.type === 'agent_run_end',\n );\n const rangeEvents =\n startIndex >= 0\n ? endIndex >= 0\n ? allEvents.slice(startIndex, endIndex + 1)\n : allEvents.slice(startIndex)\n : allEvents;\n const envEvents = rangeEvents.filter((e: any) => e.type === 'environment_input');\n const screenshotEvents = envEvents.filter(\n (e: any) => e.metadata && e.metadata.type === 'screenshot',\n );\n\n // Generate video recording from screenshots\n let videoPath = '';\n if (screenshotEvents.length > 0) {\n const tempDir = path.join(os.tmpdir(), 'gui-agent-rec', task.taskId);\n try {\n fs.mkdirSync(tempDir, { recursive: true });\n\n const validFrames: { file: string; timestamp: number }[] = [];\n let frameCount = 0;\n for (const event of screenshotEvents) {\n if (Array.isArray((event as any).content)) {\n const imgPart = ((event as any).content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n if (buffer.length > 0) {\n const extension =\n buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff\n ? 'jpg'\n : 'png';\n const fileName = `${String(frameCount).padStart(4, '0')}.${extension}`;\n const framePath = path.join(tempDir, fileName);\n fs.writeFileSync(framePath, buffer);\n validFrames.push({\n file: fileName,\n timestamp: (event as any).timestamp || Date.now(),\n });\n frameCount++;\n }\n }\n }\n }\n\n if (validFrames.length > 0) {\n const concatFilePath = path.join(tempDir, 'filelist.txt');\n let fileContent = '';\n const hasTimestamps = validFrames.some(\n (f, i) => i > 0 && f.timestamp !== validFrames[0].timestamp,\n );\n\n for (let i = 0; i < validFrames.length; i++) {\n const frame = validFrames[i];\n let duration = 1.0;\n if (hasTimestamps && i < validFrames.length - 1) {\n const diff = (validFrames[i + 1].timestamp - frame.timestamp) / 1000;\n if (diff > 0.1 && diff < 60) duration = diff;\n } else if (i === validFrames.length - 1) {\n duration = 2.0;\n }\n fileContent += `file '${frame.file}'\\n`;\n fileContent += `duration ${duration.toFixed(3)}\\n`;\n }\n if (validFrames.length > 0) {\n fileContent += `file '${validFrames[validFrames.length - 1].file}'\\n`;\n }\n fs.writeFileSync(concatFilePath, fileContent);\n\n const outputVideoPath = path.join(targetOutputDir, `${task.taskId}.mp4`);\n console.log(`[CLI] Generating video recording: ${outputVideoPath}`);\n\n await new Promise<void>((resolve, reject) => {\n ffmpeg()\n .input(concatFilePath)\n .inputOptions(['-f', 'concat', '-safe', '0'])\n .output(outputVideoPath)\n .outputOptions([\n '-c:v',\n 'libx264',\n '-pix_fmt',\n 'yuv420p',\n // scale needs to be even numbers for libx264\n '-vf',\n 'scale=trunc(iw/2)*2:trunc(ih/2)*2',\n ])\n .on('start', (cmd) => console.log(`[CLI] Ffmpeg command: ${cmd}`))\n .on('stderr', (line) => console.log(`[CLI] Ffmpeg stderr: ${line}`))\n .on('end', () => resolve())\n .on('error', (err: any) => {\n console.error('[CLI] Ffmpeg error:', err);\n reject(err);\n })\n .run();\n });\n\n videoPath = outputVideoPath;\n console.log(`[CLI] Video saved: ${videoPath}`);\n }\n } catch (recErr) {\n console.warn('[CLI] Failed to generate video recording', recErr);\n } finally {\n // Cleanup temp dir\n try {\n fs.rmSync(tempDir, { recursive: true, force: true });\n } catch (_) {\n /* ignore */\n }\n }\n }\n\n const lastScreenshot =\n screenshotEvents.length > 0\n ? (screenshotEvents[screenshotEvents.length - 1] as any)\n : null;\n\n let resultPicPath = '';\n if (lastScreenshot && Array.isArray(lastScreenshot.content)) {\n const imgPart = (lastScreenshot.content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n resultPicPath = path.join(targetOutputDir, `${task.taskId}.png`);\n fs.writeFileSync(resultPicPath, buffer);\n console.log(`[CLI] Screenshot saved: ${resultPicPath}`);\n }\n }\n if (!resultPicPath) {\n console.log('[CLI] No screenshot captured; resultPic will be empty.');\n }\n\n const conversationLogPath = saveConversationLog(rangeEvents, targetOutputDir, task.taskId);\n\n const finalAnswer = (resultEvent as any)?.content ?? '';\n const report = {\n taskId: task.taskId,\n taskContent: task.query,\n startTime,\n endTime,\n duration,\n resultPic: resultPicPath,\n video: videoPath || null,\n conversationLog: conversationLogPath,\n finalAnswer,\n };\n const reportPath = path.join(targetOutputDir, `${task.taskId}.json`);\n fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));\n console.log(`Result saved: ${reportPath}`);\n console.log(`[CLI] Report JSON path: ${reportPath}`);\n } catch (reportErr) {\n console.warn(`[CLI] Failed to save report for task ${task.taskId}`, reportErr);\n }\n }\n return;\n }\n\n // Enhanced error logging around agent run\n let resultEvent: any;\n const startTime = Date.now();\n let isReportSaved = false;\n\n const saveSingleTaskReport = async (finalAnswer: string) => {\n if (isReportSaved) return;\n isReportSaved = true;\n\n const endTime = Date.now();\n const duration = endTime - startTime;\n\n try {\n const eventStream = guiAgent.getEventStream();\n const allEvents = eventStream.getEvents();\n const runStartEvents = allEvents.filter((e: any) => e.type === 'agent_run_start');\n const sessionId =\n runStartEvents.length > 0\n ? (runStartEvents[runStartEvents.length - 1] as any).sessionId\n : `${Date.now()}`;\n\n const envEvents = allEvents.filter((e: any) => e.type === 'environment_input');\n const screenshotEvents = envEvents.filter(\n (e: any) => e.metadata && e.metadata.type === 'screenshot',\n );\n const lastScreenshot =\n screenshotEvents.length > 0 ? (screenshotEvents[screenshotEvents.length - 1] as any) : null;\n\n const targetOutputDir = options.output\n ? path.resolve(options.output)\n : path.join(os.homedir(), '.gui-agent-results');\n console.log(`[CLI] Output directory (resolved): ${targetOutputDir}`);\n fs.mkdirSync(targetOutputDir, { recursive: true });\n console.log(`[CLI] TaskId/SessionId: ${sessionId}`);\n\n // Generate video recording from screenshots\n let videoPath = '';\n if (screenshotEvents.length > 0) {\n const tempDir = path.join(os.tmpdir(), 'gui-agent-rec', sessionId);\n try {\n fs.mkdirSync(tempDir, { recursive: true });\n\n const validFrames: { file: string; timestamp: number }[] = [];\n let frameCount = 0;\n for (const event of screenshotEvents) {\n if (Array.isArray((event as any).content)) {\n const imgPart = ((event as any).content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n if (buffer.length > 0) {\n const extension =\n buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff ? 'jpg' : 'png';\n const fileName = `${String(frameCount).padStart(4, '0')}.${extension}`;\n const framePath = path.join(tempDir, fileName);\n fs.writeFileSync(framePath, buffer);\n validFrames.push({\n file: fileName,\n timestamp: (event as any).timestamp || Date.now(),\n });\n frameCount++;\n }\n }\n }\n }\n\n if (validFrames.length > 0) {\n const concatFilePath = path.join(tempDir, 'filelist.txt');\n let fileContent = '';\n const hasTimestamps = validFrames.some(\n (f, i) => i > 0 && f.timestamp !== validFrames[0].timestamp,\n );\n\n for (let i = 0; i < validFrames.length; i++) {\n const frame = validFrames[i];\n let duration = 1.0;\n if (hasTimestamps && i < validFrames.length - 1) {\n const diff = (validFrames[i + 1].timestamp - frame.timestamp) / 1000;\n if (diff > 0.1 && diff < 60) duration = diff;\n } else if (i === validFrames.length - 1) {\n duration = 2.0;\n }\n fileContent += `file '${frame.file}'\\n`;\n fileContent += `duration ${duration.toFixed(3)}\\n`;\n }\n if (validFrames.length > 0) {\n fileContent += `file '${validFrames[validFrames.length - 1].file}'\\n`;\n }\n fs.writeFileSync(concatFilePath, fileContent);\n\n const outputVideoPath = path.join(targetOutputDir, `${sessionId}.mp4`);\n console.log(`[CLI] Generating video recording: ${outputVideoPath}`);\n\n await new Promise<void>((resolve, reject) => {\n ffmpeg()\n .input(concatFilePath)\n .inputOptions(['-f', 'concat', '-safe', '0'])\n .output(outputVideoPath)\n .outputOptions([\n '-c:v',\n 'libx264',\n '-pix_fmt',\n 'yuv420p',\n // scale needs to be even numbers for libx264\n '-vf',\n 'scale=trunc(iw/2)*2:trunc(ih/2)*2',\n ])\n .on('start', (cmd) => console.log(`[CLI] Ffmpeg command: ${cmd}`))\n .on('stderr', (line) => console.log(`[CLI] Ffmpeg stderr: ${line}`))\n .on('end', () => resolve())\n .on('error', (err: any) => {\n console.error('[CLI] Ffmpeg error:', err);\n reject(err);\n })\n .run();\n });\n\n videoPath = outputVideoPath;\n console.log(`[CLI] Video saved: ${videoPath}`);\n }\n } catch (recErr) {\n console.warn('[CLI] Failed to generate video recording', recErr);\n } finally {\n // Cleanup temp dir\n try {\n fs.rmSync(tempDir, { recursive: true, force: true });\n } catch (_) {\n /* ignore */\n }\n }\n }\n\n let resultPicPath = '';\n if (lastScreenshot && Array.isArray(lastScreenshot.content)) {\n const imgPart = (lastScreenshot.content as any[]).find(\n (c: any) => c.type === 'image_url' && c.image_url && c.image_url.url,\n );\n const dataUri: string | undefined = imgPart?.image_url?.url;\n if (dataUri && typeof dataUri === 'string' && dataUri.startsWith('data:')) {\n const commaIndex = dataUri.indexOf(',');\n const base64Data = commaIndex >= 0 ? dataUri.substring(commaIndex + 1) : dataUri;\n const buffer = Buffer.from(base64Data, 'base64');\n resultPicPath = path.join(targetOutputDir, `${sessionId}.png`);\n fs.writeFileSync(resultPicPath, buffer);\n console.log(`[CLI] Screenshot saved: ${resultPicPath}`);\n }\n }\n if (!resultPicPath) {\n console.log('[CLI] No screenshot captured; resultPic will be empty.');\n }\n\n const conversationLogPath = saveConversationLog(\n // For single task run, we can just use all events as it is a fresh process/run\n allEvents,\n targetOutputDir,\n sessionId,\n );\n\n const report = {\n taskId: sessionId,\n taskContent: answers.instruction || options.query,\n startTime,\n endTime,\n duration,\n resultPic: resultPicPath,\n video: videoPath || null,\n conversationLog: conversationLogPath,\n finalAnswer,\n };\n const reportPath = path.join(targetOutputDir, `${sessionId}.json`);\n fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));\n console.log(`Result saved: ${reportPath}`);\n console.log(`[CLI] Report JSON path: ${reportPath}`);\n } catch (err) {\n console.warn('Failed to generate result report:', err);\n }\n };\n\n process.removeAllListeners('SIGINT');\n process.on('SIGINT', async () => {\n console.log('\\n[CLI] Received SIGINT. Saving report and exiting...');\n abortController.abort();\n await saveSingleTaskReport('用户已手动终止');\n process.exit(0);\n });\n\n try {\n console.log(\n '[CLI] Starting GUIAgent run with instruction:',\n answers.instruction || options.query,\n );\n resultEvent = await guiAgent.run(answers.instruction);\n console.log('[CLI] GUIAgent run completed.');\n } catch (err: any) {\n if (err.name === 'AbortError' || abortController.signal.aborted) {\n console.log('[CLI] GUIAgent run aborted.');\n } else {\n console.error('[CLI] GUIAgent run failed.');\n const errMsg = err?.message || String(err);\n console.error('[CLI] Error message:', errMsg);\n if (err?.status) console.error('[CLI] HTTP status:', err.status);\n if (err?.code) console.error('[CLI] Error code:', err.code);\n const respData = err?.response?.data || err?.response?.body || err?.data;\n if (respData) {\n try {\n const text = typeof respData === 'string' ? respData : JSON.stringify(respData);\n console.error('[CLI] Response body:', text.slice(0, 500));\n } catch (_) {\n console.error('[CLI] Response body: [unprintable]');\n }\n }\n }\n }\n\n await saveSingleTaskReport((resultEvent as any)?.content ?? '');\n};\n\nexport const resetConfig = async (configPath?: string) => {\n const CONFIG_PATH = configPath || path.join(os.homedir(), '.gui-agent-cli.json');\n\n try {\n if (fs.existsSync(CONFIG_PATH)) {\n fs.unlinkSync(CONFIG_PATH);\n console.log(`✓ Configuration file removed: ${CONFIG_PATH}`);\n } else {\n console.log(`No configuration file found at: ${CONFIG_PATH}`);\n }\n\n console.log(\n 'Configuration has been reset. The next time you run gui-agent, you will be prompted to configure your settings again.',\n );\n } catch (error) {\n console.error('Failed to reset configuration:', error);\n process.exit(1);\n }\n};\n"],"names":["ExposedNutJSOperator","NutJSOperator","ctx","saveConversationLog","events","targetOutputDir","sessionId","logPath","path","content","e","time","Date","Array","part","JSON","toolCall","message","fs","console","err","start","options","ffmpegStatic","finalFfmpegPath","bundledFfmpegPath","__dirname","os","ffmpeg","CONFIG_PATH","config","Number","response","fetch","Error","yamlText","preset","yaml","error","configAnswers","p","process","_config_azure","azureConfig","maskedKey","Boolean","parsed","URL","_","endsWithV1","url","controller","AbortController","timeout","setTimeout","resp","clearTimeout","text","json","hasChoices","targetOperator","screenResolutionInfo","targetType","AdbOperator","BrowserOperator","op","width","height","useTasksFile","answers","abortController","systemPrompts","guiAgent","GUIAgent","demoDir","tasksPath","dirOfTasks","sample","tasks","raw","task","taskAC","timeoutMs","timeoutId","onGlobalAbort","taskAgent","resultEvent","startTime","taskErr","endTime","duration","eventStream","allEvents","runStartEvents","lastRunStart","startIndex","endIndex","idx","rangeEvents","envEvents","screenshotEvents","videoPath","tempDir","validFrames","frameCount","event","_imgPart_image_url","imgPart","c","dataUri","commaIndex","base64Data","buffer","Buffer","extension","fileName","String","framePath","concatFilePath","fileContent","hasTimestamps","f","i","frame","diff","outputVideoPath","Promise","resolve","reject","cmd","line","recErr","lastScreenshot","resultPicPath","_imgPart_image_url1","conversationLogPath","finalAnswer","report","reportPath","reportErr","isReportSaved","saveSingleTaskReport","_err_response","_err_response1","errMsg","respData","resetConfig","configPath"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAMA,6BAA6BC;IACjC,MAAa,sBAAsB;QACjC,MAAM,IAAI,CAAC,UAAU;QACrB,MAAMC,MAAM,IAAI,CAAC,aAAa;QAC9B,OAAO;YAAE,OAAOA,IAAI,WAAW;YAAE,QAAQA,IAAI,YAAY;QAAC;IAC5D;AACF;AAYA,MAAMC,sBAAsB,CAACC,QAAeC,iBAAyBC;IACnE,MAAMC,UAAUC,UAAAA,IAAS,CAACH,iBAAiB,GAAGC,UAAU,GAAG,CAAC;IAC5D,IAAIG,UAAU,CAAC,qBAAqB,EAAEH,UAAU,IAAI,CAAC;IAErDF,OAAO,OAAO,CAAC,CAACM;QACd,MAAMC,OAAO,IAAIC,KAAKF,EAAE,SAAS,IAAIE,KAAK,GAAG,IAAI,WAAW;QAC5DH,WAAW,CAAC,IAAI,EAAEE,KAAK,EAAE,EAAED,EAAE,IAAI,CAAC,EAAE,CAAC;QAKrC,IAAIA,EAAE,OAAO,EACX,IAAIG,MAAM,OAAO,CAACH,EAAE,OAAO,GACzBA,EAAE,OAAO,CAAC,OAAO,CAAC,CAACI;YACjB,IAAIA,AAAc,WAAdA,KAAK,IAAI,EAAaL,WAAW,GAAGK,KAAK,IAAI,CAAC,EAAE,CAAC;YACrD,IAAIA,AAAc,gBAAdA,KAAK,IAAI,EAAkBL,WAAW,CAAC,iBAAiB,CAAC;QAC/D;aACK,IAAI,AAAqB,YAArB,OAAOC,EAAE,OAAO,EACzBD,WAAW,GAAGC,EAAE,OAAO,CAAC,EAAE,CAAC;aAE3BD,WAAW,CAAC,YAAY,EAAEM,KAAK,SAAS,CAACL,EAAE,OAAO,EAAE,M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7B,QAAQ,KAAK,CAAC;YAChB;QAEJ;IACF;IAEA,MAAM0H,qBAAqB,AAACvD,CAAAA,QAAAA,cAAAA,KAAAA,IAAAA,YAAqB,OAAO,AAAD,KAAK;AAC9D;AAEO,MAAM4D,cAAc,OAAOC;IAChC,MAAMtH,cAAcsH,cAAc3I,UAAAA,IAAS,CAACmB,QAAAA,OAAU,IAAI;IAE1D,IAAI;QACF,IAAIT,QAAAA,UAAa,CAACW,cAAc;YAC9BX,QAAAA,UAAa,CAACW;YACdV,QAAQ,GAAG,CAAC,CAAC,qCAA8B,EAAEU,aAAa;QAC5D,OACEV,QAAQ,GAAG,CAAC,CAAC,gCAAgC,EAAEU,aAAa;QAG9DV,QAAQ,GAAG,CACT;IAEJ,EAAE,OAAOmB,OAAO;QACdnB,QAAQ,KAAK,CAAC,kCAAkCmB;QAChDG,QAAQ,IAAI,CAAC;IACf;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.d.ts","sourceRoot":"","sources":["../../../src/cli/start.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"start.d.ts","sourceRoot":"","sources":["../../../src/cli/start.ts"],"names":[],"mappings":"AA+BA,MAAM,WAAW,UAAU;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AA4FD,eAAO,MAAM,KAAK,GAAU,SAAS,UAAU,kBAqxB9C,CAAC;AAEF,eAAO,MAAM,WAAW,GAAU,aAAa,MAAM,kBAkBpD,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ui-tars-test/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.20",
|
|
4
4
|
"description": "CLI for GUI Agent",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"@clack/prompts": "^0.11.0",
|
|
40
|
-
"@ui-tars-test/agent-sdk": "^0.3.
|
|
40
|
+
"@ui-tars-test/agent-sdk": "^0.3.19",
|
|
41
41
|
"@ui-tars-test/operator-adb": "^0.3.0",
|
|
42
42
|
"@ui-tars-test/operator-browser": "^0.3.0",
|
|
43
43
|
"@ui-tars-test/operator-nutjs": "^0.3.5",
|