android2harmony 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/agents/scripts/hmos-precheck/index.mjs +0 -8
  2. package/agents/self-tester.md +339 -0
  3. package/dist/index.js +635 -77
  4. package/dist/index.js.map +4 -4
  5. package/package.json +37 -29
  6. package/skills/hmos-incremental-ui-align/README.md +251 -0
  7. package/skills/hmos-incremental-ui-align/SKILL.md +365 -0
  8. package/skills/hmos-incremental-ui-align/diff_analysis.md +53 -0
  9. package/skills/hmos-incremental-ui-align/page_align.md +62 -0
  10. package/skills/hmos-incremental-ui-align/references/Comparison_Template.md +38 -0
  11. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@Link/350/243/205/351/245/260/345/231/250/357/274/232/347/210/266/345/255/220/345/217/214/345/220/221/345/220/214/346/255/245.md +648 -0
  12. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@Observed/350/243/205/351/245/260/345/231/250/345/222/214@ObjectLink/350/243/205/351/245/260/345/231/250/357/274/232/345/265/214/345/245/227/347/261/273/345/257/271/350/261/241/345/261/236/346/200/247/345/217/230/345/214/226.md +2089 -0
  13. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@Prop/350/243/205/351/245/260/345/231/250/357/274/232/347/210/266/345/255/220/345/215/225/345/220/221/345/220/214/346/255/245.md +1033 -0
  14. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@Provide/350/243/205/351/245/260/345/231/250/345/222/214@Consume/350/243/205/351/245/260/345/231/250/357/274/232/344/270/216/345/220/216/344/273/243/347/273/204/344/273/266/345/217/214/345/220/221/345/220/214/346/255/245.md +1183 -0
  15. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@State/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/206/205/347/212/266/346/200/201.md +576 -0
  16. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@Track/350/243/205/351/245/260/345/231/250/357/274/232class/345/257/271/350/261/241/345/261/236/346/200/247/347/272/247/346/233/264/346/226/260.md +297 -0
  17. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/@Watch/350/243/205/351/245/260/345/231/250/357/274/232/347/212/266/346/200/201/345/217/230/351/207/217/346/233/264/346/224/271/351/200/232/347/237/245.md +395 -0
  18. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/AppStorage/357/274/232/345/272/224/347/224/250/345/205/250/345/261/200/347/232/204UI/347/212/266/346/200/201/345/255/230/345/202/250.md +903 -0
  19. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/Environment/357/274/232/350/256/276/345/244/207/347/216/257/345/242/203/346/237/245/350/257/242.md +106 -0
  20. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/LocalStorage/357/274/232/351/241/265/351/235/242/347/272/247UI/347/212/266/346/200/201/345/255/230/345/202/250.md +1178 -0
  21. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/MVVM/346/250/241/345/274/217V1.md +911 -0
  22. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243/PersistentStorage/357/274/232/346/214/201/344/271/205/345/214/226/345/255/230/345/202/250UI/347/212/266/346/200/201.md +355 -0
  23. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243//347/256/241/347/220/206/345/272/224/347/224/250/346/213/245/346/234/211/347/232/204/347/212/266/346/200/201/346/246/202/350/277/260.md +11 -0
  24. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/!!/350/257/255/346/263/225/357/274/232/345/217/214/345/220/221/347/273/221/345/256/232.md +206 -0
  25. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Computed/350/243/205/351/245/260/345/231/250/357/274/232/350/256/241/347/256/227/345/261/236/346/200/247.md +373 -0
  26. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Event/350/243/205/351/245/260/345/231/250/357/274/232/350/247/204/350/214/203/347/273/204/344/273/266/350/276/223/345/207/272.md +158 -0
  27. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Local/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/206/205/351/203/250/347/212/266/346/200/201.md +750 -0
  28. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Monitor/350/243/205/351/245/260/345/231/250/357/274/232/347/212/266/346/200/201/345/217/230/351/207/217/344/277/256/346/224/271/345/274/202/346/255/245/347/233/221/345/220/254.md +1704 -0
  29. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@ObservedV2/350/243/205/351/245/260/345/231/250/345/222/214@Trace/350/243/205/351/245/260/345/231/250/357/274/232/347/261/273/345/261/236/346/200/247/345/217/230/345/214/226/350/247/202/346/265/213.md +1012 -0
  30. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Once/350/243/205/351/245/260/345/231/250/357/274/232/345/210/235/345/247/213/345/214/226/345/220/214/346/255/245/344/270/200/346/254/241.md +164 -0
  31. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Param/350/243/205/351/245/260/345/231/250/357/274/232/347/273/204/344/273/266/345/244/226/351/203/250/350/276/223/345/205/245.md +840 -0
  32. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Provider/350/243/205/351/245/260/345/231/250/345/222/214@Consumer/350/243/205/351/245/260/345/231/250/357/274/232/350/267/250/347/273/204/344/273/266/345/261/202/347/272/247/345/217/214/345/220/221/345/220/214/346/255/245.md +856 -0
  33. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/@Type/350/243/205/351/245/260/345/231/250/357/274/232/346/240/207/350/256/260/347/261/273/345/261/236/346/200/247/347/232/204/347/261/273/345/236/213.md +83 -0
  34. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/AppStorageV2/357/274/232/345/272/224/347/224/250/345/205/250/345/261/200UI/347/212/266/346/200/201/345/255/230/345/202/250.md +294 -0
  35. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/MVVM/346/250/241/345/274/217/357/274/210V2/357/274/211.md +1407 -0
  36. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/PersistenceV2/357/274/232/346/214/201/344/271/205/345/214/226/345/255/230/345/202/250UI/347/212/266/346/200/201.md +1220 -0
  37. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2/_/350/214/203/345/274/217/351/200/211/346/213/251/350/257/264/346/230/216.md +47 -0
  38. package/skills/hmos-incremental-ui-align/references/MVVM/345/274/200/345/217/221/346/226/207/346/241/243V2//347/212/266/346/200/201/347/256/241/347/220/206V1/345/220/221V2/350/277/201/347/247/273/344/270/216/346/267/267/347/224/250/346/214/207/345/257/274.md +840 -0
  39. package/skills/hmos-incremental-ui-align/references/State_Model_Template.md +74 -0
  40. package/skills/hmos-incremental-ui-align/references/UI_Analysis_Template.md +34 -0
  41. package/skills/hmos-incremental-ui-align/references/android-to-harmonyOS-ui-atomic-component-mapping-reference.md +2533 -0
  42. package/skills/hmos-incremental-ui-align/references/android-to-harmonyOS-ui-interaction-mapping-reference.md +555 -0
  43. package/skills/hmos-incremental-ui-align/references/android-to-harmonyOS-ui-layout-mapping-reference.md +117 -0
  44. package/skills/hmos-incremental-ui-align/scripts/app_feature_verify.ts +999 -0
  45. package/skills/hmos-incremental-ui-align/scripts/extract_checklist.ts +343 -0
  46. package/skills/hmos-incremental-ui-align/scripts/navigation-capure.md +76 -0
  47. package/skills/hmos-incremental-ui-align/scripts/page_capture.ts +977 -0
  48. package/skills/hmos-incremental-ui-align/scripts/page_capture_burst.ts +188 -0
  49. package/skills/hmos-spec-generate/SKILL.md +1 -1
  50. package/tools/autotest/deps/autotest-agent-0.1.1.tgz +0 -0
  51. package/tools/autotest/engine/batch-launcher.ts +326 -0
  52. package/tools/autotest/engine/report-tool.ts +773 -0
  53. package/tools/autotest/engine/self-test-runner.ts +1024 -0
  54. package/tools/autotest/engine/testcases-tool.ts +246 -0
  55. package/tools/autotest/resolve-metadata-tool.ts +143 -0
  56. package/tools/autotest/runner/logger.ts +45 -0
  57. package/tools/autotest/runner/process-utils.ts +41 -0
  58. package/tools/autotest/validate.ts +115 -0
@@ -0,0 +1,999 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 应用页面导航工具 (TypeScript 版) —— 使用视觉 LLM 按指定路径操作设备,导航到目标页面。
4
+ *
5
+ * 等价于 app_feature_verify.py(functional equivalence,非逐字节一致),去掉了对 Python /
6
+ * uv / phone-agent 的依赖。零第三方依赖,仅用 Node 内置模块 + 全局 fetch,可独立分发。
7
+ * 运行环境:Node ≥ 22.18 或 ≥ 23.6(原生剥离类型,无需编译)。
8
+ *
9
+ * 复刻自 Zhipu Open-AutoGLM (`phone-agent` 0.1.1) 的 ReAct 循环:
10
+ * 截图 + 当前app名 → 拼 messages → 请求模型 → 切出 thinking/action
11
+ * → parse_action → 换算坐标(0-1000→px) → 执行 hdc/adb 命令
12
+ * → 把 <thinking><answer> 塞回历史 → 判断 finish? → 循环到 max_steps
13
+ *
14
+ * 已内建 py 版通过 monkey-patch 修复的 3 个 phone-agent 0.1.1 bug:
15
+ * ① 鸿蒙 swipe 最后一个参数是速度(pps) 而非时长(ms)
16
+ * ② 模型输出剥离 <thinking>/<answer> 包裹
17
+ * ③ do() 畸形输出的正则兜底解析
18
+ *
19
+ * 用法:
20
+ * # 自由 prompt 导航(会自动前置 "打开{app},")
21
+ * node app_feature_verify.ts --device adb --app Gallery --package com.example.gallery --prompt "进入设置页面"
22
+ * # 按功能路径导航
23
+ * node app_feature_verify.ts --app 简单图库 --package com.simplemobiletools.gallery.pro --task "L1相册详情L2更多L3筛选媒体文件"
24
+ * # 功能清单文件(.md)
25
+ * node app_feature_verify.ts --app xxx --package yyy --feature ./features.md
26
+ */
27
+
28
+ import { randomUUID } from 'node:crypto';
29
+ import { spawnSync } from 'node:child_process';
30
+ import * as fs from 'node:fs';
31
+ import * as os from 'node:os';
32
+ import * as path from 'node:path';
33
+
34
+ type DeviceType = 'hdc' | 'adb';
35
+
36
+ // 与 phone-agent 一致的默认动作后延时(秒)。可用 HT_ACTION_DELAY 覆盖。
37
+ const ACTION_DELAY = Number(process.env.HT_ACTION_DELAY ?? '1') || 1;
38
+
39
+ const sleep = (seconds: number): Promise<void> =>
40
+ new Promise((resolve) => setTimeout(resolve, Math.max(0, seconds) * 1000));
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // System prompt —— 逐字复刻 phone_agent/config/prompts_zh.py 的 SYSTEM_PROMPT。
44
+ // 这是模型行为的"契约",必须与 py 版一致,否则同一模型会输出不兼容内容。
45
+ // ---------------------------------------------------------------------------
46
+ function buildSystemPrompt(): string {
47
+ const now = new Date();
48
+ const weekdayNames = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
49
+ const formattedDate =
50
+ `${now.getFullYear()}年${String(now.getMonth() + 1).padStart(2, '0')}月` +
51
+ `${String(now.getDate()).padStart(2, '0')}日 ${weekdayNames[now.getDay()]}`;
52
+ return (
53
+ '今天的日期是: ' +
54
+ formattedDate +
55
+ `
56
+ 你是一个智能体分析专家,可以根据操作历史和当前状态图执行一系列操作来完成任务。
57
+ 你必须严格按照要求输出以下格式:
58
+ <thinking>{think}</thinking>
59
+ <answer>{action}</answer>
60
+
61
+ 其中:
62
+ - {think} 是对你为什么选择这个操作的简短推理说明。
63
+ - {action} 是本次执行的具体操作指令,必须严格遵循下方定义的指令格式。
64
+
65
+ 操作指令及其作用如下:
66
+ - do(action="Launch", app="xxx")
67
+ Launch是启动目标app的操作,这比通过主屏幕导航更快。此操作完成后,您将自动收到结果状态的截图。
68
+ - do(action="Tap", element=[x,y])
69
+ Tap是点击操作,点击屏幕上的特定点。可用此操作点击按钮、选择项目、从主屏幕打开应用程序,或与任何可点击的用户界面元素进行交互。坐标系统从左上角 (0,0) 开始到右下角(999,999)结束。此操作完成后,您将自动收到结果状态的截图。
70
+ - do(action="Tap", element=[x,y], message="重要操作")
71
+ 基本功能同Tap,点击涉及财产、支付、隐私等敏感按钮时触发。
72
+ - do(action="Type", text="xxx")
73
+ Type是输入操作,在当前聚焦的输入框中输入文本。使用此操作前,请确保输入框已被聚焦(先点击它)。输入的文本将像使用键盘输入一样输入。重要提示:手机可能正在使用 ADB 键盘,该键盘不会像普通键盘那样占用屏幕空间。要确认键盘已激活,请查看屏幕底部是否显示 'ADB Keyboard {ON}' 类似的文本,或者检查输入框是否处于激活/高亮状态。不要仅仅依赖视觉上的键盘显示。自动清除文本:当你使用输入操作时,输入框中现有的任何文本(包括占位符文本和实际输入)都会在输入新文本前自动清除。你无需在输入前手动清除文本——直接使用输入操作输入所需文本即可。操作完成后,你将自动收到结果状态的截图。
74
+ - do(action="Type_Name", text="xxx")
75
+ Type_Name是输入人名的操作,基本功能同Type。
76
+ - do(action="Interact")
77
+ Interact是当有多个满足条件的选项时而触发的交互操作,询问用户如何选择。
78
+ - do(action="Swipe", start=[x1,y1], end=[x2,y2])
79
+ Swipe是滑动操作,通过从起始坐标拖动到结束坐标来执行滑动手势。可用于滚动内容、在屏幕之间导航、下拉通知栏以及项目栏或进行基于手势的导航。坐标系统从左上角 (0,0) 开始到右下角(999,999)结束。滑动持续时间会自动调整以实现自然的移动。此操作完成后,您将自动收到结果状态的截图。
80
+ - do(action="Note", message="True")
81
+ 记录当前页面内容以便后续总结。
82
+ - do(action="Call_API", instruction="xxx")
83
+ 总结或评论当前页面或已记录的内容。
84
+ - do(action="Long Press", element=[x,y])
85
+ Long Pres是长按操作,在屏幕上的特定点长按指定时间。可用于触发上下文菜单、选择文本或激活长按交互。坐标系统从左上角 (0,0) 开始到右下角(999,999)结束。此操作完成后,您将自动收到结果状态的屏幕截图。
86
+ - do(action="Double Tap", element=[x,y])
87
+ Double Tap在屏幕上的特定点快速连续点按两次。使用此操作可以激活双击交互,如缩放、选择文本或打开项目。坐标系统从左上角 (0,0) 开始到右下角(999,999)结束。此操作完成后,您将自动收到结果状态的截图。
88
+ - do(action="Back")
89
+ 导航返回到上一个屏幕或关闭当前对话框。相当于按下 Android 的返回按钮。使用此操作可以从更深的屏幕返回、关闭弹出窗口或退出当前上下文。此操作完成后,您将自动收到结果状态的截图。
90
+ - do(action="Home")
91
+ Home是回到系统桌面的操作,相当于按下 Android 主屏幕按钮。使用此操作可退出当前应用并返回启动器,或从已知状态启动新任务。此操作完成后,您将自动收到结果状态的截图。
92
+ - do(action="Wait", duration="x seconds")
93
+ 等待页面加载,x为需要等待多少秒。
94
+ - finish(message="xxx")
95
+ finish是结束任务的操作,表示准确完整完成任务,message是终止信息。
96
+
97
+ 必须遵循的规则:
98
+ 1. 在执行任何操作前,先检查当前app是否是目标app,如果不是,先执行 Launch。
99
+ 2. 如果进入到了无关页面,先执行 Back。如果执行Back后页面没有变化,请点击页面左上角的返回键进行返回,或者右上角的X号关闭。
100
+ 3. 如果页面未加载出内容,最多连续 Wait 三次,否则执行 Back重新进入。
101
+ 4. 如果页面显示网络问题,需要重新加载,请点击重新加载。
102
+ 5. 如果当前页面找不到目标联系人、商品、店铺等信息,可以尝试 Swipe 滑动查找。
103
+ 6. 遇到价格区间、时间区间等筛选条件,如果没有完全符合的,可以放宽要求。
104
+ 7. 在做小红书总结类任务时一定要筛选图文笔记。
105
+ 8. 购物车全选后再点击全选可以把状态设为全不选,在做购物车任务时,如果购物车里已经有商品被选中时,你需要点击全选后再点击取消全选,再去找需要购买或者删除的商品。
106
+ 9. 在做外卖任务时,如果相应店铺购物车里已经有其他商品你需要先把购物车清空再去购买用户指定的外卖。
107
+ 10. 在做点外卖任务时,如果用户需要点多个外卖,请尽量在同一店铺进行购买,如果无法找到可以下单,并说明某个商品未找到。
108
+ 11. 请严格遵循用户意图执行任务,用户的特殊要求可以执行多次搜索,滑动查找。
109
+ 12. 在选择日期时,如果原滑动方向与预期日期越来越远,请向反方向滑动查找。
110
+ 13. 执行任务过程中如果有多个可选择的项目栏,请逐个查找每个项目栏,直到完成任务,一定不要在同一项目栏多次查找,从而陷入死循环。
111
+ 14. 在执行下一步操作前请一定要检查上一步的操作是否生效,如果点击没生效,可能因为app反应较慢,请先稍微等待一下,如果还是不生效请调整一下点击位置重试,如果仍然不生效请跳过这一步继续任务,并在finish message说明点击不生效。
112
+ 15. 在执行任务中如果遇到滑动不生效的情况,请调整一下起始点位置,增大滑动距离重试,如果还是不生效,有可能是已经滑到底了,请继续向反方向滑动,直到顶部或底部,如果仍然没有符合要求的结果,请跳过这一步继续任务,并在finish message说明但没找到要求的项目。
113
+ 16. 在做游戏任务时如果在战斗页面如果有自动战斗一定要开启自动战斗,如果多轮历史状态相似要检查自动战斗是否开启。
114
+ 17. 如果没有合适的搜索结果,可能是因为搜索页面不对,请返回到搜索页面的上一级尝试重新搜索,如果尝试三次返回上一级搜索后仍然没有符合要求的结果,执行 finish(message="原因")。
115
+ 18. 在结束任务前请一定要仔细检查任务是否完整准确的完成,如果出现错选、漏选、多选的情况,请返回之前的步骤进行纠正。
116
+ `
117
+ );
118
+ }
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // 子进程封装(复用 page_capture.ts 的模式)
122
+ // ---------------------------------------------------------------------------
123
+ function runBin(
124
+ bin: string,
125
+ args: string[],
126
+ opts: { timeout?: number; binary?: boolean } = {},
127
+ ): { stdout: string; stdoutBuf: Buffer; stderr: string; code: number | null } {
128
+ const res = spawnSync(bin, args, {
129
+ timeout: (opts.timeout ?? 15) * 1000,
130
+ maxBuffer: 128 * 1024 * 1024,
131
+ windowsHide: true,
132
+ });
133
+ const outBuf = (res.stdout as Buffer) ?? Buffer.alloc(0);
134
+ const errBuf = (res.stderr as Buffer) ?? Buffer.alloc(0);
135
+ if (res.error && (res.error as NodeJS.ErrnoException).code === 'ETIMEDOUT') {
136
+ console.log(` [WARN] ${bin} timeout: ${args.join(' ')}`);
137
+ }
138
+ return {
139
+ stdout: outBuf.toString('utf-8'),
140
+ stdoutBuf: outBuf,
141
+ stderr: errBuf.toString('utf-8'),
142
+ code: res.status,
143
+ };
144
+ }
145
+
146
+ // ---------------------------------------------------------------------------
147
+ // 图片尺寸解析(无需第三方库)—— 坐标换算需要截图的像素宽高。
148
+ // PNG: IHDR 在偏移 16(宽)/20(高)。JPEG: 扫描 SOF 标记读取宽高。
149
+ // ---------------------------------------------------------------------------
150
+ function imageSize(buf: Buffer): { width: number; height: number } {
151
+ // PNG
152
+ if (buf.length >= 24 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {
153
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
154
+ }
155
+ // JPEG
156
+ if (buf.length >= 4 && buf[0] === 0xff && buf[1] === 0xd8) {
157
+ let i = 2;
158
+ while (i < buf.length - 1) {
159
+ if (buf[i] !== 0xff) {
160
+ i += 1;
161
+ continue;
162
+ }
163
+ const marker = buf[i + 1];
164
+ // SOF0..SOF15 (排除 C4=DHT, C8=JPG, CC=DAC)
165
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
166
+ const height = buf.readUInt16BE(i + 5);
167
+ const width = buf.readUInt16BE(i + 7);
168
+ return { width, height };
169
+ }
170
+ if (marker === 0xd8 || marker === 0xd9 || (marker >= 0xd0 && marker <= 0xd7)) {
171
+ i += 2;
172
+ continue;
173
+ }
174
+ const segLen = buf.readUInt16BE(i + 2);
175
+ i += 2 + segLen;
176
+ }
177
+ }
178
+ return { width: 1080, height: 2400 }; // 回落默认值
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // 设备驱动层(HDC / ADB)
183
+ // ---------------------------------------------------------------------------
184
+ interface Screenshot {
185
+ base64: string;
186
+ mime: string;
187
+ width: number;
188
+ height: number;
189
+ }
190
+
191
+ interface DeviceDriver {
192
+ getScreenshot(): Screenshot;
193
+ getCurrentApp(): string;
194
+ launchApp(appName: string): boolean;
195
+ tap(x: number, y: number): void;
196
+ doubleTap(x: number, y: number): void;
197
+ longPress(x: number, y: number): void;
198
+ swipe(x1: number, y1: number, x2: number, y2: number): void;
199
+ back(): void;
200
+ home(): void;
201
+ typeText(text: string): void;
202
+ }
203
+
204
+ // 应用注册表:app_name -> package(由 --app/--package 动态填充)
205
+ const APP_PACKAGES = new Map<string, string>();
206
+
207
+ class HdcDriver implements DeviceDriver {
208
+ private serial: string | null;
209
+ constructor(serial: string | null) {
210
+ this.serial = serial;
211
+ }
212
+ private prefix(): string[] {
213
+ return this.serial ? ['-t', this.serial] : [];
214
+ }
215
+ private shell(args: string[], timeout = 15) {
216
+ return runBin('hdc', [...this.prefix(), 'shell', ...args], { timeout });
217
+ }
218
+
219
+ getScreenshot(): Screenshot {
220
+ const remote = '/data/local/tmp/tmp_screenshot.jpeg';
221
+ let out = this.shell(['snapshot_display', '-f', remote], 10);
222
+ const combined = (out.stdout + out.stderr).toLowerCase();
223
+ if (combined.includes('fail') || combined.includes('error')) {
224
+ // 备用方法(新版 HarmonyOS)
225
+ this.shell(['screenshot', remote], 10);
226
+ }
227
+ const localPath = path.join(os.tmpdir(), `ht_shot_${process.pid}_${Date.now()}.jpeg`);
228
+ runBin('hdc', [...this.prefix(), 'file', 'recv', remote, localPath], { timeout: 10 });
229
+ try {
230
+ const buf = fs.readFileSync(localPath);
231
+ fs.unlinkSync(localPath);
232
+ const { width, height } = imageSize(buf);
233
+ return { base64: buf.toString('base64'), mime: 'image/jpeg', width, height };
234
+ } catch {
235
+ return fallbackScreenshot();
236
+ }
237
+ }
238
+
239
+ getCurrentApp(): string {
240
+ const out = this.shell(['aa', 'dump', '-l']).stdout;
241
+ if (!out) return 'System Home';
242
+ let currentBundle: string | null = null;
243
+ let foreground: string | null = null;
244
+ for (const line of out.split('\n')) {
245
+ if (line.includes('app name [')) {
246
+ const m = line.match(/\[([^\]]+)\]/);
247
+ if (m) currentBundle = m[1];
248
+ }
249
+ if (line.toLowerCase().includes('state #foreground')) {
250
+ if (currentBundle) {
251
+ foreground = currentBundle;
252
+ break;
253
+ }
254
+ }
255
+ if (line.includes('Mission ID')) currentBundle = null;
256
+ }
257
+ if (foreground) {
258
+ for (const [name, pkg] of APP_PACKAGES) if (pkg === foreground) return name;
259
+ return foreground;
260
+ }
261
+ return 'System Home';
262
+ }
263
+
264
+ launchApp(appName: string): boolean {
265
+ const bundle = APP_PACKAGES.get(appName);
266
+ if (!bundle) {
267
+ console.log(`[HDC] App '${appName}' not registered`);
268
+ return false;
269
+ }
270
+ const ability = process.env.HT_HMOS_ABILITY || 'EntryAbility';
271
+ this.shell(['aa', 'start', '-b', bundle, '-a', ability]);
272
+ return true;
273
+ }
274
+
275
+ tap(x: number, y: number): void {
276
+ this.shell(['uitest', 'uiInput', 'click', String(x), String(y)]);
277
+ }
278
+ doubleTap(x: number, y: number): void {
279
+ this.shell(['uitest', 'uiInput', 'doubleClick', String(x), String(y)]);
280
+ }
281
+ longPress(x: number, y: number): void {
282
+ this.shell(['uitest', 'uiInput', 'longClick', String(x), String(y)]);
283
+ }
284
+ swipe(x1: number, y1: number, x2: number, y2: number): void {
285
+ // Patch ①: 鸿蒙 swipe 最后一个参数是速度(pps),不是时长(ms)。
286
+ const distance = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
287
+ let durationMs = Math.trunc((distance * distance) / 1000);
288
+ durationMs = Math.max(500, Math.min(durationMs, 1000));
289
+ let velocity = Math.trunc((distance / durationMs) * 4000);
290
+ velocity = Math.max(500, Math.min(velocity, 40000));
291
+ this.shell(['uitest', 'uiInput', 'swipe', String(x1), String(y1), String(x2), String(y2), String(velocity)]);
292
+ }
293
+ back(): void {
294
+ this.shell(['uitest', 'uiInput', 'keyEvent', 'Back']);
295
+ }
296
+ home(): void {
297
+ this.shell(['uitest', 'uiInput', 'keyEvent', 'Home']);
298
+ }
299
+ typeText(text: string): void {
300
+ const escaped = text.replace(/"/g, '\\"').replace(/\$/g, '\\$');
301
+ this.shell(['uitest', 'uiInput', 'text', escaped]);
302
+ }
303
+ }
304
+
305
+ class AdbDriver implements DeviceDriver {
306
+ private serial: string | null;
307
+ constructor(serial: string | null) {
308
+ this.serial = serial;
309
+ }
310
+ private prefix(): string[] {
311
+ return this.serial ? ['-s', this.serial] : [];
312
+ }
313
+ private shell(args: string[], timeout = 15) {
314
+ return runBin('adb', [...this.prefix(), 'shell', ...args], { timeout });
315
+ }
316
+
317
+ getScreenshot(): Screenshot {
318
+ const { stdoutBuf, code } = runBin('adb', [...this.prefix(), 'exec-out', 'screencap', '-p'], {
319
+ timeout: 15,
320
+ binary: true,
321
+ });
322
+ if (code !== 0 || stdoutBuf.length === 0) return fallbackScreenshot();
323
+ const { width, height } = imageSize(stdoutBuf);
324
+ return { base64: stdoutBuf.toString('base64'), mime: 'image/png', width, height };
325
+ }
326
+
327
+ getCurrentApp(): string {
328
+ const out = this.shell(['dumpsys', 'window']).stdout;
329
+ for (const line of out.split('\n')) {
330
+ if (line.includes('mCurrentFocus') || line.includes('mFocusedApp')) {
331
+ for (const [name, pkg] of APP_PACKAGES) if (line.includes(pkg)) return name;
332
+ }
333
+ }
334
+ return 'System Home';
335
+ }
336
+
337
+ launchApp(appName: string): boolean {
338
+ const pkg = APP_PACKAGES.get(appName);
339
+ if (!pkg) {
340
+ console.log(`[ADB] App '${appName}' not registered`);
341
+ return false;
342
+ }
343
+ this.shell(['monkey', '-p', pkg, '-c', 'android.intent.category.LAUNCHER', '1']);
344
+ return true;
345
+ }
346
+
347
+ tap(x: number, y: number): void {
348
+ this.shell(['input', 'tap', String(x), String(y)]);
349
+ }
350
+ doubleTap(x: number, y: number): void {
351
+ this.shell(['input', 'tap', String(x), String(y)]);
352
+ this.shell(['input', 'tap', String(x), String(y)]);
353
+ }
354
+ longPress(x: number, y: number): void {
355
+ this.shell(['input', 'swipe', String(x), String(y), String(x), String(y), '3000']);
356
+ }
357
+ swipe(x1: number, y1: number, x2: number, y2: number): void {
358
+ const distSq = (x1 - x2) ** 2 + (y1 - y2) ** 2;
359
+ let durationMs = Math.trunc(distSq / 1000);
360
+ durationMs = Math.max(1000, Math.min(durationMs, 2000));
361
+ this.shell(['input', 'swipe', String(x1), String(y1), String(x2), String(y2), String(durationMs)]);
362
+ }
363
+ back(): void {
364
+ this.shell(['input', 'keyevent', '4']);
365
+ }
366
+ home(): void {
367
+ this.shell(['input', 'keyevent', 'KEYCODE_HOME']);
368
+ }
369
+ typeText(text: string): void {
370
+ // 需设备安装 ADB Keyboard (com.android.adbkeyboard/.AdbIME)
371
+ const encoded = Buffer.from(text, 'utf-8').toString('base64');
372
+ this.shell(['am', 'broadcast', '-a', 'ADB_INPUT_B64', '--es', 'msg', encoded]);
373
+ }
374
+ }
375
+
376
+ function fallbackScreenshot(): Screenshot {
377
+ // 1x1 黑色 PNG(截图失败时的占位,避免整个循环崩溃)
378
+ const png = Buffer.from(
379
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC',
380
+ 'base64',
381
+ );
382
+ return { base64: png.toString('base64'), mime: 'image/png', width: 1080, height: 2400 };
383
+ }
384
+
385
+ // ---------------------------------------------------------------------------
386
+ // 模型输出解析:切 thinking/action(复刻 ModelClient._parse_response 规则 1-4)
387
+ // ---------------------------------------------------------------------------
388
+ function splitThinkingAction(content: string): { thinking: string; action: string } {
389
+ // 保留 <thinking> 内容用于展示。
390
+ const thinkM = content.match(/<thinking>(.*?)<\/thinking>/s);
391
+ const think = thinkM ? thinkM[1].trim() : '';
392
+
393
+ // Patch ②: 先剥离 <thinking>/<answer> 包裹,再按标记切出干净的动作
394
+ // (避免把标签塞进 action,也避免存进历史时二次包裹)。
395
+ let cleaned = content.replace(/<thinking>.*?<\/thinking>\s*/gs, '');
396
+ const ansM = cleaned.match(/<answer>\s*(.*?)\s*<\/answer>/s);
397
+ if (ansM) cleaned = ansM[1];
398
+ cleaned = cleaned.replace(/<\/answer>/g, '').trim();
399
+
400
+ if (cleaned.includes('finish(message=')) {
401
+ const idx = cleaned.indexOf('finish(message=');
402
+ return { thinking: think || cleaned.slice(0, idx).trim(), action: cleaned.slice(idx) };
403
+ }
404
+ if (cleaned.includes('do(action=')) {
405
+ const idx = cleaned.indexOf('do(action=');
406
+ return { thinking: think || cleaned.slice(0, idx).trim(), action: cleaned.slice(idx) };
407
+ }
408
+ return { thinking: think, action: cleaned || content };
409
+ }
410
+
411
+ // ---------------------------------------------------------------------------
412
+ // 动作解析(复刻 actions/handler.parse_action + skill 的 Patch ②③)
413
+ // ---------------------------------------------------------------------------
414
+ type Action = Record<string, unknown> & { _metadata: 'do' | 'finish' };
415
+
416
+ function stripLlmTags(text: string): string {
417
+ let t = text.replace(/<thinking>.*?<\/thinking>\s*/gs, '');
418
+ const m = t.match(/<answer>\s*(.*?)\s*<\/answer>/s);
419
+ if (m) t = m[1];
420
+ return t.replace(/<\/answer>/g, '').trim();
421
+ }
422
+
423
+ // 解析形如 do(action="Tap", element=[x,y], message="...") 的键值参数。
424
+ // 用逐键正则代替 Python 的 ast —— 覆盖 phone-agent 全部动作字段。
425
+ function parseDoArgs(inner: string): Record<string, unknown> {
426
+ const args: Record<string, unknown> = {};
427
+ const strRe = /(\w+)\s*=\s*"((?:[^"\\]|\\.)*)"/g;
428
+ let m: RegExpExecArray | null;
429
+ while ((m = strRe.exec(inner)) !== null) {
430
+ args[m[1]] = m[2].replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\r/g, '\r').replace(/\\"/g, '"');
431
+ }
432
+ const arrRe = /(\w+)\s*=\s*\[\s*(-?\d+)\s*,\s*(-?\d+)\s*\]/g;
433
+ while ((m = arrRe.exec(inner)) !== null) {
434
+ args[m[1]] = [parseInt(m[2], 10), parseInt(m[3], 10)];
435
+ }
436
+ return args;
437
+ }
438
+
439
+ function parseAction(response: string): Action | null {
440
+ const cleaned = stripLlmTags(response);
441
+ for (const text of [cleaned, response.trim()]) {
442
+ const finishM = text.match(/finish\s*\(\s*message\s*=\s*"((?:[^"\\]|\\.)*)"\s*\)/s);
443
+ if (finishM) {
444
+ return { _metadata: 'finish', message: finishM[1].replace(/\\"/g, '"').replace(/\\n/g, '\n') };
445
+ }
446
+ const doM = text.match(/do\s*\((.*)\)\s*$/s) || text.match(/do\s*\((.*?)\)/s);
447
+ if (doM) {
448
+ const args = parseDoArgs(doM[1]);
449
+ if (args.action) return { _metadata: 'do', ...args } as Action;
450
+ }
451
+ }
452
+ return null;
453
+ }
454
+
455
+ // ---------------------------------------------------------------------------
456
+ // LLM 客户端(OpenAI 兼容 /chat/completions,非流式)
457
+ // ---------------------------------------------------------------------------
458
+ interface ModelConfig {
459
+ baseUrl: string;
460
+ apiKey: string;
461
+ modelName: string;
462
+ temperature: number;
463
+ }
464
+
465
+ type ChatMessage = { role: string; content: unknown };
466
+
467
+ /** /chat/completions 响应里关心的字段(其余字段忽略,避免耦合网关差异) */
468
+ interface ChatCompletionResponse {
469
+ choices?: { message?: { content?: string } }[];
470
+ }
471
+
472
+ /** 内置 DevEco MaaS 网关:baseUrl 含 devecostudio,走其专属协议(Chat-Id 头、精简 body)。 */
473
+ function isDevEcoMaaS(cfg: ModelConfig): boolean {
474
+ return cfg.baseUrl.includes('devecostudio');
475
+ }
476
+
477
+ /** /chat/completions 端点地址(baseUrl 去尾斜杠后拼路径,兼容末尾带/的配置)。 */
478
+ function chatCompletionsUrl(cfg: ModelConfig): string {
479
+ return cfg.baseUrl.replace(/\/$/, '') + '/chat/completions';
480
+ }
481
+
482
+ /** 请求头:通用 OpenAI 头 + 内置网关的 Chat-Id(32 位 hex UUID 去连字符)。 */
483
+ function buildHeaders(cfg: ModelConfig): Record<string, string> {
484
+ const headers: Record<string, string> = {
485
+ 'Content-Type': 'application/json',
486
+ Authorization: `Bearer ${cfg.apiKey}`,
487
+ };
488
+ if (isDevEcoMaaS(cfg)) {
489
+ headers['Chat-Id'] = randomUUID().replace(/-/g, '');
490
+ }
491
+ return headers;
492
+ }
493
+
494
+ /**
495
+ * 请求体:内置网关只发 OpenAI 兼容最小集 {model, messages, stream};
496
+ * 三方端点补采样参数(参考 Deveco Code ui-verification-mcp 的调用实现)。
497
+ */
498
+ function buildBody(cfg: ModelConfig, messages: ChatMessage[]): Record<string, unknown> {
499
+ const body: Record<string, unknown> = { model: cfg.modelName, messages, stream: false };
500
+ if (!isDevEcoMaaS(cfg)) {
501
+ body.max_tokens = 3000;
502
+ body.temperature = cfg.temperature;
503
+ body.top_p = 0.85;
504
+ body.frequency_penalty = 0.2;
505
+ }
506
+ return body;
507
+ }
508
+
509
+ /** 从 /chat/completions 响应里取第一选择的 content(缺失则兜底空串)。 */
510
+ function extractContent(data: ChatCompletionResponse): string {
511
+ return data.choices?.[0]?.message?.content ?? '';
512
+ }
513
+
514
+ /** 发非流式 /chat/completions 请求,返回模型输出的 content。 */
515
+ async function requestModel(cfg: ModelConfig, messages: ChatMessage[]): Promise<string> {
516
+ const resp = await fetch(chatCompletionsUrl(cfg), {
517
+ method: 'POST',
518
+ headers: buildHeaders(cfg),
519
+ body: JSON.stringify(buildBody(cfg, messages)),
520
+ });
521
+ if (!resp.ok) {
522
+ const text = await resp.text().catch(() => '');
523
+ throw new Error(`Model HTTP ${resp.status}: ${text.slice(0, 500)}`);
524
+ }
525
+ return extractContent((await resp.json()) as ChatCompletionResponse);
526
+ }
527
+
528
+ // ---------------------------------------------------------------------------
529
+ // 消息构造(复刻 MessageBuilder)
530
+ // ---------------------------------------------------------------------------
531
+ function userMessage(text: string, shot?: Screenshot): ChatMessage {
532
+ const content: unknown[] = [];
533
+ if (shot) {
534
+ content.push({ type: 'image_url', image_url: { url: `data:${shot.mime};base64,${shot.base64}` } });
535
+ }
536
+ content.push({ type: 'text', text });
537
+ return { role: 'user', content };
538
+ }
539
+
540
+ function stripImages(msg: ChatMessage): ChatMessage {
541
+ if (Array.isArray(msg.content)) {
542
+ return { ...msg, content: msg.content.filter((c) => (c as { type?: string }).type === 'text') };
543
+ }
544
+ return msg;
545
+ }
546
+
547
+ // ---------------------------------------------------------------------------
548
+ // Agent 主循环(复刻 PhoneAgent.run / _execute_step)
549
+ // ---------------------------------------------------------------------------
550
+ class PhoneAgent {
551
+ private cfg: ModelConfig;
552
+ private device: DeviceDriver;
553
+ private maxSteps: number;
554
+ private verbose: boolean;
555
+ private context: ChatMessage[] = [];
556
+
557
+ constructor(cfg: ModelConfig, device: DeviceDriver, maxSteps: number, verbose: boolean) {
558
+ this.cfg = cfg;
559
+ this.device = device;
560
+ this.maxSteps = maxSteps;
561
+ this.verbose = verbose;
562
+ }
563
+
564
+ reset(): void {
565
+ this.context = [];
566
+ }
567
+
568
+ async run(task: string): Promise<string> {
569
+ this.context = [];
570
+ let stepCount = 0;
571
+ let isFirst = true;
572
+
573
+ while (stepCount < this.maxSteps) {
574
+ stepCount += 1;
575
+
576
+ const shot = this.device.getScreenshot();
577
+ const currentApp = this.device.getCurrentApp();
578
+ const screenInfo = JSON.stringify({ current_app: currentApp });
579
+
580
+ if (isFirst) {
581
+ this.context.push({ role: 'system', content: buildSystemPrompt() });
582
+ this.context.push(userMessage(`${task}\n\n${screenInfo}`, shot));
583
+ isFirst = false;
584
+ } else {
585
+ this.context.push(userMessage(`** Screen Info **\n\n${screenInfo}`, shot));
586
+ }
587
+
588
+ let content: string;
589
+ try {
590
+ content = await requestModel(this.cfg, this.context);
591
+ } catch (e) {
592
+ return `Model error: ${(e as Error).message}`;
593
+ }
594
+
595
+ const { thinking, action: actionStr } = splitThinkingAction(content);
596
+ if (this.verbose) {
597
+ console.log(`\n${'='.repeat(50)}\n💭 思考过程:\n${'-'.repeat(50)}`);
598
+ console.log(thinking || '(无)');
599
+ console.log(`${'-'.repeat(50)}\n🎯 执行动作: ${actionStr}\n${'='.repeat(50)}`);
600
+ }
601
+
602
+ // 解析失败 → 当作 finish(原文作为 message),与 py 版一致。
603
+ const action = parseAction(actionStr) ?? { _metadata: 'finish', message: actionStr };
604
+
605
+ // 从历史里移除图片,省 token(复刻 remove_images_from_message)
606
+ this.context[this.context.length - 1] = stripImages(this.context[this.context.length - 1]);
607
+ this.context.push({
608
+ role: 'assistant',
609
+ content: `<thinking>${thinking}</thinking><answer>${actionStr}</answer>`,
610
+ });
611
+
612
+ if (action._metadata === 'finish') {
613
+ return (action.message as string) || 'Task completed';
614
+ }
615
+
616
+ await this.execute(action, shot.width, shot.height);
617
+ await sleep(ACTION_DELAY);
618
+ }
619
+ return 'Max steps reached';
620
+ }
621
+
622
+ private async execute(action: Action, width: number, height: number): Promise<void> {
623
+ const toPx = (el: unknown): [number, number] => {
624
+ const [rx, ry] = el as [number, number];
625
+ return [Math.trunc((rx / 1000) * width), Math.trunc((ry / 1000) * height)];
626
+ };
627
+ const name = action.action as string;
628
+ try {
629
+ switch (name) {
630
+ case 'Launch':
631
+ this.device.launchApp(action.app as string);
632
+ break;
633
+ case 'Tap': {
634
+ const [x, y] = toPx(action.element);
635
+ this.device.tap(x, y);
636
+ break;
637
+ }
638
+ case 'Double Tap': {
639
+ const [x, y] = toPx(action.element);
640
+ this.device.doubleTap(x, y);
641
+ break;
642
+ }
643
+ case 'Long Press': {
644
+ const [x, y] = toPx(action.element);
645
+ this.device.longPress(x, y);
646
+ break;
647
+ }
648
+ case 'Swipe': {
649
+ const [sx, sy] = toPx(action.start);
650
+ const [ex, ey] = toPx(action.end);
651
+ this.device.swipe(sx, sy, ex, ey);
652
+ break;
653
+ }
654
+ case 'Type':
655
+ case 'Type_Name':
656
+ this.device.typeText((action.text as string) ?? '');
657
+ break;
658
+ case 'Back':
659
+ this.device.back();
660
+ break;
661
+ case 'Home':
662
+ this.device.home();
663
+ break;
664
+ case 'Wait': {
665
+ const dur = parseFloat(String(action.duration ?? '1').replace('seconds', '').trim());
666
+ await sleep(Number.isFinite(dur) ? dur : 1);
667
+ break;
668
+ }
669
+ case 'Note':
670
+ case 'Call_API':
671
+ case 'Interact':
672
+ case 'Take_over':
673
+ // 占位动作(phone-agent 亦为空实现)
674
+ break;
675
+ default:
676
+ console.log(` [WARN] Unknown action: ${name}`);
677
+ }
678
+ } catch (e) {
679
+ console.log(` [WARN] Action '${name}' failed: ${(e as Error).message}`);
680
+ }
681
+ }
682
+ }
683
+
684
+ // ---------------------------------------------------------------------------
685
+ // 功能清单解析 / prompt 构建 / 到达判定(复刻 py 版逻辑)
686
+ // ---------------------------------------------------------------------------
687
+ interface FeatureItem {
688
+ [k: string]: unknown;
689
+ }
690
+
691
+ function parseFeatureMd(filePath: string): FeatureItem[] {
692
+ const text = fs.readFileSync(filePath, 'utf-8');
693
+ const results: FeatureItem[] = [];
694
+ let currentFeature = '';
695
+ let current: FeatureItem | null = null;
696
+ let collecting: string | null = null;
697
+
698
+ for (const line of text.split(/\r?\n/)) {
699
+ const stripped = line.trim();
700
+ const feat = stripped.match(/^##\s+Feature:\s*(.+)$/);
701
+ if (feat) {
702
+ if (current) results.push(current);
703
+ current = null;
704
+ currentFeature = feat[1].trim();
705
+ collecting = null;
706
+ continue;
707
+ }
708
+ const scen = stripped.match(/^###\s+Scenario:\s*(.+)$/);
709
+ if (scen) {
710
+ if (current) results.push(current);
711
+ const scenarioName = scen[1].trim();
712
+ const featureName = currentFeature.replace(/^FEA-\d+\s*/, '');
713
+ current = {
714
+ feature: currentFeature,
715
+ scenario: scenarioName,
716
+ preconditions: [] as string[],
717
+ actions: [] as string[],
718
+ expectations: [] as string[],
719
+ L1: featureName,
720
+ L2: scenarioName,
721
+ L3: '',
722
+ };
723
+ collecting = null;
724
+ continue;
725
+ }
726
+ if (!current) continue;
727
+ if (/^-\s*前置条件[::]/.test(stripped)) {
728
+ collecting = 'preconditions';
729
+ continue;
730
+ }
731
+ const act = stripped.match(/^-\s*动作[::]\s*(.+)$/);
732
+ if (act) {
733
+ collecting = null;
734
+ (current.actions as string[]).push(act[1].trim());
735
+ continue;
736
+ }
737
+ const exp = stripped.match(/^-\s*预期结果[::]\s*(.+)$/);
738
+ if (exp) {
739
+ collecting = null;
740
+ (current.expectations as string[]).push(exp[1].trim());
741
+ continue;
742
+ }
743
+ const sub = line.match(/^\s+-\s+(.+)$/);
744
+ if (sub && collecting === 'preconditions') {
745
+ (current.preconditions as string[]).push(sub[1].trim());
746
+ continue;
747
+ }
748
+ if (stripped && !stripped.startsWith('-')) collecting = null;
749
+ }
750
+ if (current) results.push(current);
751
+ return results;
752
+ }
753
+
754
+ function getFeaturePath(item: FeatureItem): { pathStr: string; leaf: string } {
755
+ let keys = ['L1', 'L2', 'L3'].filter((k) => k in item);
756
+ if (keys.length === 0) keys = ['一级', '二级', '三级'].filter((k) => k in item);
757
+ if (keys.length === 0) keys = Object.keys(item).slice(0, 3);
758
+ const parts: string[] = [];
759
+ for (const k of keys) {
760
+ const v = item[k];
761
+ if (v != null && String(v).trim()) parts.push(String(v).trim());
762
+ }
763
+ if (parts.length === 0) return { pathStr: '', leaf: '' };
764
+ return { pathStr: parts.join(' > '), leaf: parts[parts.length - 1] };
765
+ }
766
+
767
+ function buildNavigatePrompt(appName: string, pathStr: string, leaf: string, hints?: string): string {
768
+ let prompt =
769
+ `打开${appName},按照以下路径依次点击导航到目标页面:${pathStr}。` +
770
+ `最终目标是到达「${leaf}」所在的页面。` +
771
+ '注意:' +
772
+ '1. 鸿蒙手机浅色/深色模式切换路径:设置->显示与亮度' +
773
+ "2. '更多'组件可能表示为 三横 或者 三点。" +
774
+ "3. '设置'组件可能表示为 齿轮。" +
775
+ "到达目标页面后请回复'已到达',无法到达请回复'未找到'。";
776
+ if (hints) prompt += `\n补充提示: ${hints}`;
777
+ return prompt;
778
+ }
779
+
780
+ function judgeReached(msg: string): boolean {
781
+ if (!msg) return false;
782
+ const reached = ['已到达', '到达', '存在', '找到', '完成', '成功', '已确认', '已进入', '已打开'];
783
+ const failed = ['未找到', '不存在', '无法找到', '无法到达', '没有', '失败', '未到达'];
784
+ const firstLine = msg.split('\n')[0];
785
+ if (failed.some((k) => firstLine.includes(k))) return false;
786
+ if (reached.some((k) => firstLine.includes(k))) return true;
787
+ return false;
788
+ }
789
+
790
+ // ---------------------------------------------------------------------------
791
+ // 模型配置加载(复刻 _load_model_config:env > config.json > GLM 兼容)
792
+ // ---------------------------------------------------------------------------
793
+ function loadModelConfig(
794
+ cliApiKey: string,
795
+ stdinModel?: { apiKey: string; modelName: string; baseURL: string } | null,
796
+ ): ModelConfig {
797
+ // 最高优先级:plugin 工具经 stdin 注入的模型配置——key 不经 env/argv/磁盘。
798
+ if (stdinModel?.apiKey) {
799
+ return {
800
+ apiKey: stdinModel.apiKey,
801
+ baseUrl: stdinModel.baseURL || 'http://localhost:8000/v1',
802
+ modelName: stdinModel.modelName,
803
+ temperature: 0.1,
804
+ };
805
+ }
806
+ let apiKey = (cliApiKey || process.env.HOMETRANS_MODEL_API_KEY || '').trim();
807
+ let baseUrl = (process.env.HOMETRANS_MODEL_BASE_URL || '').trim();
808
+ let modelName = (process.env.HOMETRANS_MODEL_NAME || '').trim();
809
+ let temperature = 0.1;
810
+
811
+ const configPath = path.join(os.homedir(), '.hometrans', 'config.json');
812
+ if (fs.existsSync(configPath)) {
813
+ try {
814
+ const cfg = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
815
+ const um = cfg?.autotest?.unified_model ?? {};
816
+ apiKey = apiKey || String(um.api_key ?? '').trim();
817
+ baseUrl = baseUrl || String(um.base_url ?? '').trim();
818
+ modelName = modelName || String(um.name ?? '').trim();
819
+ if (um.temperature != null) temperature = Number(um.temperature);
820
+ } catch {
821
+ /* ignore */
822
+ }
823
+ }
824
+
825
+ if (apiKey) {
826
+ return { baseUrl: baseUrl || 'http://localhost:8000/v1', apiKey, modelName, temperature };
827
+ }
828
+ const glmKey = (process.env.GLM_API_KEY || '').trim();
829
+ if (glmKey) {
830
+ return {
831
+ baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
832
+ apiKey: glmKey,
833
+ modelName: 'autoglm-phone',
834
+ temperature: 0.1,
835
+ };
836
+ }
837
+ return { baseUrl: 'http://localhost:8000/v1', apiKey: 'EMPTY', modelName: '', temperature };
838
+ }
839
+
840
+ // ---------------------------------------------------------------------------
841
+ // CLI
842
+ // ---------------------------------------------------------------------------
843
+ interface Args {
844
+ device: DeviceType;
845
+ app: string;
846
+ package: string;
847
+ task: string | null;
848
+ prompt: string | null;
849
+ feature: string | null;
850
+ limit: number | null;
851
+ offset: number;
852
+ apiKey: string;
853
+ maxSteps: number;
854
+ appHints: string | null;
855
+ serial: string | null;
856
+ quiet: boolean;
857
+ modelStdin: boolean;
858
+ }
859
+
860
+ function parseArgs(argv: string[]): Args {
861
+ const a: Args = {
862
+ device: 'hdc',
863
+ app: '',
864
+ package: '',
865
+ task: null,
866
+ prompt: null,
867
+ feature: null,
868
+ limit: null,
869
+ offset: 1,
870
+ apiKey: '',
871
+ maxSteps: 30,
872
+ appHints: null,
873
+ serial: null,
874
+ quiet: false,
875
+ modelStdin: false,
876
+ };
877
+ for (let i = 0; i < argv.length; i++) {
878
+ const arg = argv[i];
879
+ const next = () => argv[++i];
880
+ switch (arg) {
881
+ case '--device': a.device = next() as DeviceType; break;
882
+ case '--app': a.app = next(); break;
883
+ case '--package': a.package = next(); break;
884
+ case '--task': a.task = next(); break;
885
+ case '--prompt': a.prompt = next(); break;
886
+ case '--feature': a.feature = next(); break;
887
+ case '--limit': a.limit = parseInt(next(), 10); break;
888
+ case '--offset': a.offset = parseInt(next(), 10); break;
889
+ case '--api-key': a.apiKey = next(); break;
890
+ case '--max-steps': a.maxSteps = parseInt(next(), 10); break;
891
+ case '--app-hints': a.appHints = next(); break;
892
+ case '--serial': a.serial = next(); break;
893
+ case '-q':
894
+ case '--quiet': a.quiet = true; break;
895
+ case '--model-stdin': a.modelStdin = true; break;
896
+ default:
897
+ console.log(`[WARN] 未知参数: ${arg}`);
898
+ }
899
+ }
900
+ return a;
901
+ }
902
+
903
+ async function main(): Promise<number> {
904
+ const args = parseArgs(process.argv.slice(2));
905
+
906
+ if (!args.app || !args.package) {
907
+ console.error('错误: 必须指定 --app 和 --package');
908
+ return 2;
909
+ }
910
+ if (!args.prompt && !args.task && !args.feature) {
911
+ console.error('错误: 必须指定 --feature、--task 或 --prompt 之一');
912
+ return 2;
913
+ }
914
+
915
+ // 注册应用(复刻 register_app)
916
+ APP_PACKAGES.set(args.app, args.package);
917
+
918
+ // plugin 工具经 stdin 注入模型配置(--model-stdin):同步读 fd 0 取 key,
919
+ // 不进 env/argv;空或坏 JSON 不崩,回落到下方常规解析链。
920
+ let stdinModel: { apiKey: string; modelName: string; baseURL: string } | null = null;
921
+ if (args.modelStdin) {
922
+ try {
923
+ stdinModel = JSON.parse(fs.readFileSync(0, 'utf-8'));
924
+ } catch {
925
+ /* 坏/空 stdin:回落 env/config.json */
926
+ }
927
+ }
928
+
929
+ const model = loadModelConfig(args.apiKey, stdinModel);
930
+ if (!model.apiKey || model.apiKey === 'EMPTY') {
931
+ if (!args.quiet) {
932
+ console.log('提示: 未找到可用的模型配置。请运行 `ht init` 配置统一模型,');
933
+ console.log('或通过 --api-key 传入 API Key。\n');
934
+ }
935
+ }
936
+
937
+ const deviceLabel = args.device === 'adb' ? 'ADB (Android)' : 'HDC (HarmonyOS)';
938
+ console.log(`设备: ${deviceLabel}, 应用: ${args.app} (${args.package})`);
939
+ console.log('-'.repeat(50));
940
+
941
+ const driver: DeviceDriver =
942
+ args.device === 'adb' ? new AdbDriver(args.serial) : new HdcDriver(args.serial);
943
+ const agent = new PhoneAgent(model, driver, args.maxSteps, !args.quiet);
944
+
945
+ // 收集任务列表 [(prompt, label), ...](复刻 navigate 的三种模式)
946
+ const tasks: { prompt: string; label: string }[] = [];
947
+ if (args.prompt) {
948
+ tasks.push({ prompt: `打开${args.app},${args.prompt}`, label: args.prompt });
949
+ } else if (args.task) {
950
+ const parts = args.task.split(/(L[123])/);
951
+ const item: FeatureItem = {};
952
+ for (let j = 1; j < parts.length - 1; j += 2) {
953
+ const val = parts[j + 1].trim();
954
+ if (val) item[parts[j]] = val;
955
+ }
956
+ const { pathStr, leaf } = getFeaturePath(item);
957
+ if (pathStr) tasks.push({ prompt: buildNavigatePrompt(args.app, pathStr, leaf, args.appHints ?? undefined), label: pathStr });
958
+ } else if (args.feature) {
959
+ if (!args.feature.toLowerCase().endsWith('.md')) {
960
+ console.error('错误: --feature 仅支持 .md 功能清单,或改用 --prompt / --task。');
961
+ return 2;
962
+ }
963
+ let features = parseFeatureMd(args.feature);
964
+ if (args.offset > 1) features = features.slice(args.offset - 1);
965
+ if (args.limit != null) features = features.slice(0, args.limit);
966
+ for (const item of features) {
967
+ const { pathStr, leaf } = getFeaturePath(item);
968
+ if (pathStr) tasks.push({ prompt: buildNavigatePrompt(args.app, pathStr, leaf, args.appHints ?? undefined), label: pathStr });
969
+ }
970
+ }
971
+
972
+ for (let i = 0; i < tasks.length; i++) {
973
+ const { prompt, label } = tasks[i];
974
+ console.log(tasks.length > 1 ? `\n[${i + 1}/${tasks.length}] 导航: ${label}` : `导航: ${label}`);
975
+
976
+ let reached = false;
977
+ try {
978
+ const resultMsg = await agent.run(prompt);
979
+ reached = judgeReached(resultMsg);
980
+ } catch {
981
+ reached = false;
982
+ }
983
+ console.log(reached ? '到达目标页面' : '未找到目标页面');
984
+
985
+ if (i < tasks.length - 1) agent.reset();
986
+ }
987
+ return 0;
988
+ }
989
+
990
+ // 用 exitCode 而非 process.exit(),让事件循环自然排空,
991
+ // 规避 Windows 上 libuv 在句柄关闭期间被 process.exit 打断的 teardown 断言。
992
+ main()
993
+ .then((code) => {
994
+ process.exitCode = code;
995
+ })
996
+ .catch((e) => {
997
+ console.error(e);
998
+ process.exitCode = 1;
999
+ });