android2harmony 0.1.4 → 0.1.5

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 (104) hide show
  1. package/README.md +1 -407
  2. package/agents/self-tester.md +376 -376
  3. package/dist/index.js +134 -116
  4. package/dist/index.js.map +3 -3
  5. package/package.json +36 -32
  6. package/skills/a2h-resource-convert/SKILL.md +902 -0
  7. package/skills/a2h-resource-convert/references/code-vector-icon-rules.md +335 -0
  8. package/skills/{hmos-resources-convert → a2h-resource-convert}/references/conversion-rules.md +15 -2
  9. package/skills/{hmos-resources-convert → a2h-resource-convert}/references/dependency-analysis-rules.md +24 -2
  10. package/skills/a2h-resource-convert/references/lottie-conversion-rules.md +219 -0
  11. package/skills/{hmos-resources-convert → a2h-resource-convert}/references/resource-mapping-rules.md +27 -2
  12. package/skills/{hmos-resources-convert → a2h-resource-convert}/references/xml-drawable-to-svg-rules.md +118 -1
  13. package/skills/a2h-resource-convert/scripts/a2h_resource_convert.js +2166 -0
  14. package/skills/a2h-resource-convert/scripts/code_vector_icons.js +607 -0
  15. package/skills/a2h-resource-convert/scripts/package.json +3 -0
  16. package/skills/a2h-resource-convert/scripts/svg_fidelity_check.js +632 -0
  17. package/skills/a2h-ui-transfer/SKILL.md +420 -0
  18. package/skills/a2h-ui-transfer/references/conversion-procedure.md +572 -0
  19. package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/_/350/214/203/345/274/217/351/200/211/346/213/251/350/257/264/346/230/216.md +1 -1
  20. package/skills/a2h-ui-transfer/references/mvvm-v2/_/350/243/205/351/245/260/345/231/250/351/200/237/346/237/245.md +133 -0
  21. package/skills/{hmos-batch-ui-align/scripts/android_parse_fast.ts → a2h-ui-transfer/scripts/android_parse_fast.js} +397 -283
  22. package/skills/a2h-ui-transfer/scripts/arkts_static_check.js +1624 -0
  23. package/skills/a2h-ui-transfer/scripts/measure_pack.js +1005 -0
  24. package/skills/a2h-ui-transfer/scripts/package.json +3 -0
  25. package/skills/hmos-incremental-ui-align/README.md +251 -251
  26. package/skills/hmos-incremental-ui-align/SKILL.md +364 -364
  27. package/skills/hmos-incremental-ui-align/references/State_Model_Template.md +2 -2
  28. package/skills/hmos-incremental-ui-align/scripts/app_feature_verify.js +790 -0
  29. package/skills/hmos-incremental-ui-align/scripts/extract_checklist.js +285 -0
  30. package/skills/hmos-incremental-ui-align/scripts/navigation-capure.md +76 -76
  31. package/skills/hmos-incremental-ui-align/scripts/page_capture.js +756 -0
  32. package/skills/hmos-incremental-ui-align/scripts/page_capture_burst.js +155 -0
  33. package/skills/hmos-batch-ui-align/SKILL.md +0 -141
  34. package/skills/hmos-batch-ui-align/references/conversion-procedure.md +0 -217
  35. package/skills/hmos-incremental-ui-align/scripts/app_feature_verify.ts +0 -999
  36. package/skills/hmos-incremental-ui-align/scripts/extract_checklist.ts +0 -343
  37. package/skills/hmos-incremental-ui-align/scripts/page_capture.ts +0 -977
  38. package/skills/hmos-incremental-ui-align/scripts/page_capture_burst.ts +0 -188
  39. package/skills/hmos-resources-convert/SKILL.md +0 -654
  40. package/skills/hmos-resources-convert/template/AppScope/app.json5 +0 -10
  41. package/skills/hmos-resources-convert/template/AppScope/resources/base/element/string.json +0 -8
  42. package/skills/hmos-resources-convert/template/AppScope/resources/base/media/background.png +0 -0
  43. package/skills/hmos-resources-convert/template/AppScope/resources/base/media/foreground.png +0 -0
  44. package/skills/hmos-resources-convert/template/AppScope/resources/base/media/layered_image.json +0 -7
  45. package/skills/hmos-resources-convert/template/build-profile.json5 +0 -42
  46. package/skills/hmos-resources-convert/template/code-linter.json5 +0 -32
  47. package/skills/hmos-resources-convert/template/entry/build-profile.json5 +0 -33
  48. package/skills/hmos-resources-convert/template/entry/hvigorfile.ts +0 -6
  49. package/skills/hmos-resources-convert/template/entry/obfuscation-rules.txt +0 -23
  50. package/skills/hmos-resources-convert/template/entry/oh-package.json5 +0 -10
  51. package/skills/hmos-resources-convert/template/entry/src/main/ets/entryability/EntryAbility.ets +0 -48
  52. package/skills/hmos-resources-convert/template/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +0 -16
  53. package/skills/hmos-resources-convert/template/entry/src/main/ets/pages/Index.ets +0 -23
  54. package/skills/hmos-resources-convert/template/entry/src/main/module.json5 +0 -55
  55. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/element/color.json +0 -8
  56. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/element/float.json +0 -8
  57. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/element/string.json +0 -16
  58. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/media/background.png +0 -0
  59. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/media/foreground.png +0 -0
  60. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/media/layered_image.json +0 -7
  61. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/media/startIcon.png +0 -0
  62. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/profile/backup_config.json +0 -3
  63. package/skills/hmos-resources-convert/template/entry/src/main/resources/base/profile/main_pages.json +0 -5
  64. package/skills/hmos-resources-convert/template/entry/src/main/resources/dark/element/color.json +0 -8
  65. package/skills/hmos-resources-convert/template/entry/src/mock/mock-config.json5 +0 -2
  66. package/skills/hmos-resources-convert/template/entry/src/ohosTest/ets/test/Ability.test.ets +0 -35
  67. package/skills/hmos-resources-convert/template/entry/src/ohosTest/ets/test/List.test.ets +0 -5
  68. package/skills/hmos-resources-convert/template/entry/src/ohosTest/module.json5 +0 -16
  69. package/skills/hmos-resources-convert/template/entry/src/test/List.test.ets +0 -5
  70. package/skills/hmos-resources-convert/template/entry/src/test/LocalUnit.test.ets +0 -33
  71. package/skills/hmos-resources-convert/template/hvigor/hvigor-config.json5 +0 -23
  72. package/skills/hmos-resources-convert/template/hvigorfile.ts +0 -6
  73. package/skills/hmos-resources-convert/template/oh-package-lock.json5 +0 -28
  74. package/skills/hmos-resources-convert/template/oh-package.json5 +0 -10
  75. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mappings/android-to-harmonyOS-ui-atomic-component-mapping-reference.md +0 -0
  76. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mappings/android-to-harmonyOS-ui-interaction-mapping-reference.md +0 -0
  77. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mappings/android-to-harmonyOS-ui-layout-mapping-reference.md +0 -0
  78. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/@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" +0 -0
  79. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/@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" +0 -0
  80. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/@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" +0 -0
  81. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/@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" +0 -0
  82. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/@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" +0 -0
  83. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/@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" +0 -0
  84. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/@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" +0 -0
  85. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/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" +0 -0
  86. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/Environment/357/274/232/350/256/276/345/244/207/347/216/257/345/242/203/346/237/245/350/257/242.md" +0 -0
  87. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/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" +0 -0
  88. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/MVVM/346/250/241/345/274/217/357/274/210V1/357/274/211.md" +0 -0
  89. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm/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" +0 -0
  90. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm//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" +0 -0
  91. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/!!/350/257/255/346/263/225/357/274/232/345/217/214/345/220/221/347/273/221/345/256/232.md" +0 -0
  92. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/@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" +0 -0
  93. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/@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" +0 -0
  94. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/@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" +0 -0
  95. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/@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" +0 -0
  96. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/@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" +0 -0
  97. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/@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" +0 -0
  98. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/@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" +0 -0
  99. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/@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" +0 -0
  100. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/@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" +0 -0
  101. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/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" +0 -0
  102. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/MVVM/346/250/241/345/274/217/357/274/210V2/357/274/211.md" +0 -0
  103. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2/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" +0 -0
  104. /package/skills/{hmos-batch-ui-align → a2h-ui-transfer}/references/mvvm-v2//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" +0 -0
@@ -0,0 +1,790 @@
1
+ #!/usr/bin/env node
2
+ import { randomUUID } from "node:crypto";
3
+ import { spawnSync } from "node:child_process";
4
+ import * as fs from "node:fs";
5
+ import * as os from "node:os";
6
+ import * as path from "node:path";
7
+ const ACTION_DELAY = Number(process.env.HT_ACTION_DELAY ?? "1") || 1;
8
+ const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, Math.max(0, seconds) * 1e3));
9
+ function buildSystemPrompt() {
10
+ const now = /* @__PURE__ */ new Date();
11
+ const weekdayNames = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
12
+ const formattedDate = `${now.getFullYear()}年${String(now.getMonth() + 1).padStart(2, "0")}月${String(now.getDate()).padStart(2, "0")}日 ${weekdayNames[now.getDay()]}`;
13
+ return "今天的日期是: " + formattedDate + `
14
+ 你是一个智能体分析专家,可以根据操作历史和当前状态图执行一系列操作来完成任务。
15
+ 你必须严格按照要求输出以下格式:
16
+ <thinking>{think}</thinking>
17
+ <answer>{action}</answer>
18
+
19
+ 其中:
20
+ - {think} 是对你为什么选择这个操作的简短推理说明。
21
+ - {action} 是本次执行的具体操作指令,必须严格遵循下方定义的指令格式。
22
+
23
+ 操作指令及其作用如下:
24
+ - do(action="Launch", app="xxx")
25
+ Launch是启动目标app的操作,这比通过主屏幕导航更快。此操作完成后,您将自动收到结果状态的截图。
26
+ - do(action="Tap", element=[x,y])
27
+ Tap是点击操作,点击屏幕上的特定点。可用此操作点击按钮、选择项目、从主屏幕打开应用程序,或与任何可点击的用户界面元素进行交互。坐标系统从左上角 (0,0) 开始到右下角(999,999)结束。此操作完成后,您将自动收到结果状态的截图。
28
+ - do(action="Tap", element=[x,y], message="重要操作")
29
+ 基本功能同Tap,点击涉及财产、支付、隐私等敏感按钮时触发。
30
+ - do(action="Type", text="xxx")
31
+ Type是输入操作,在当前聚焦的输入框中输入文本。使用此操作前,请确保输入框已被聚焦(先点击它)。输入的文本将像使用键盘输入一样输入。重要提示:手机可能正在使用 ADB 键盘,该键盘不会像普通键盘那样占用屏幕空间。要确认键盘已激活,请查看屏幕底部是否显示 'ADB Keyboard {ON}' 类似的文本,或者检查输入框是否处于激活/高亮状态。不要仅仅依赖视觉上的键盘显示。自动清除文本:当你使用输入操作时,输入框中现有的任何文本(包括占位符文本和实际输入)都会在输入新文本前自动清除。你无需在输入前手动清除文本——直接使用输入操作输入所需文本即可。操作完成后,你将自动收到结果状态的截图。
32
+ - do(action="Type_Name", text="xxx")
33
+ Type_Name是输入人名的操作,基本功能同Type。
34
+ - do(action="Interact")
35
+ Interact是当有多个满足条件的选项时而触发的交互操作,询问用户如何选择。
36
+ - do(action="Swipe", start=[x1,y1], end=[x2,y2])
37
+ Swipe是滑动操作,通过从起始坐标拖动到结束坐标来执行滑动手势。可用于滚动内容、在屏幕之间导航、下拉通知栏以及项目栏或进行基于手势的导航。坐标系统从左上角 (0,0) 开始到右下角(999,999)结束。滑动持续时间会自动调整以实现自然的移动。此操作完成后,您将自动收到结果状态的截图。
38
+ - do(action="Note", message="True")
39
+ 记录当前页面内容以便后续总结。
40
+ - do(action="Call_API", instruction="xxx")
41
+ 总结或评论当前页面或已记录的内容。
42
+ - do(action="Long Press", element=[x,y])
43
+ Long Pres是长按操作,在屏幕上的特定点长按指定时间。可用于触发上下文菜单、选择文本或激活长按交互。坐标系统从左上角 (0,0) 开始到右下角(999,999)结束。此操作完成后,您将自动收到结果状态的屏幕截图。
44
+ - do(action="Double Tap", element=[x,y])
45
+ Double Tap在屏幕上的特定点快速连续点按两次。使用此操作可以激活双击交互,如缩放、选择文本或打开项目。坐标系统从左上角 (0,0) 开始到右下角(999,999)结束。此操作完成后,您将自动收到结果状态的截图。
46
+ - do(action="Back")
47
+ 导航返回到上一个屏幕或关闭当前对话框。相当于按下 Android 的返回按钮。使用此操作可以从更深的屏幕返回、关闭弹出窗口或退出当前上下文。此操作完成后,您将自动收到结果状态的截图。
48
+ - do(action="Home")
49
+ Home是回到系统桌面的操作,相当于按下 Android 主屏幕按钮。使用此操作可退出当前应用并返回启动器,或从已知状态启动新任务。此操作完成后,您将自动收到结果状态的截图。
50
+ - do(action="Wait", duration="x seconds")
51
+ 等待页面加载,x为需要等待多少秒。
52
+ - finish(message="xxx")
53
+ finish是结束任务的操作,表示准确完整完成任务,message是终止信息。
54
+
55
+ 必须遵循的规则:
56
+ 1. 在执行任何操作前,先检查当前app是否是目标app,如果不是,先执行 Launch。
57
+ 2. 如果进入到了无关页面,先执行 Back。如果执行Back后页面没有变化,请点击页面左上角的返回键进行返回,或者右上角的X号关闭。
58
+ 3. 如果页面未加载出内容,最多连续 Wait 三次,否则执行 Back重新进入。
59
+ 4. 如果页面显示网络问题,需要重新加载,请点击重新加载。
60
+ 5. 如果当前页面找不到目标联系人、商品、店铺等信息,可以尝试 Swipe 滑动查找。
61
+ 6. 遇到价格区间、时间区间等筛选条件,如果没有完全符合的,可以放宽要求。
62
+ 7. 在做小红书总结类任务时一定要筛选图文笔记。
63
+ 8. 购物车全选后再点击全选可以把状态设为全不选,在做购物车任务时,如果购物车里已经有商品被选中时,你需要点击全选后再点击取消全选,再去找需要购买或者删除的商品。
64
+ 9. 在做外卖任务时,如果相应店铺购物车里已经有其他商品你需要先把购物车清空再去购买用户指定的外卖。
65
+ 10. 在做点外卖任务时,如果用户需要点多个外卖,请尽量在同一店铺进行购买,如果无法找到可以下单,并说明某个商品未找到。
66
+ 11. 请严格遵循用户意图执行任务,用户的特殊要求可以执行多次搜索,滑动查找。
67
+ 12. 在选择日期时,如果原滑动方向与预期日期越来越远,请向反方向滑动查找。
68
+ 13. 执行任务过程中如果有多个可选择的项目栏,请逐个查找每个项目栏,直到完成任务,一定不要在同一项目栏多次查找,从而陷入死循环。
69
+ 14. 在执行下一步操作前请一定要检查上一步的操作是否生效,如果点击没生效,可能因为app反应较慢,请先稍微等待一下,如果还是不生效请调整一下点击位置重试,如果仍然不生效请跳过这一步继续任务,并在finish message说明点击不生效。
70
+ 15. 在执行任务中如果遇到滑动不生效的情况,请调整一下起始点位置,增大滑动距离重试,如果还是不生效,有可能是已经滑到底了,请继续向反方向滑动,直到顶部或底部,如果仍然没有符合要求的结果,请跳过这一步继续任务,并在finish message说明但没找到要求的项目。
71
+ 16. 在做游戏任务时如果在战斗页面如果有自动战斗一定要开启自动战斗,如果多轮历史状态相似要检查自动战斗是否开启。
72
+ 17. 如果没有合适的搜索结果,可能是因为搜索页面不对,请返回到搜索页面的上一级尝试重新搜索,如果尝试三次返回上一级搜索后仍然没有符合要求的结果,执行 finish(message="原因")。
73
+ 18. 在结束任务前请一定要仔细检查任务是否完整准确的完成,如果出现错选、漏选、多选的情况,请返回之前的步骤进行纠正。
74
+ `;
75
+ }
76
+ function runBin(bin, args, opts = {}) {
77
+ const res = spawnSync(bin, args, {
78
+ timeout: (opts.timeout ?? 15) * 1e3,
79
+ maxBuffer: 128 * 1024 * 1024,
80
+ windowsHide: true
81
+ });
82
+ const outBuf = res.stdout ?? Buffer.alloc(0);
83
+ const errBuf = res.stderr ?? Buffer.alloc(0);
84
+ if (res.error && res.error.code === "ETIMEDOUT") {
85
+ console.log(` [WARN] ${bin} timeout: ${args.join(" ")}`);
86
+ }
87
+ return {
88
+ stdout: outBuf.toString("utf-8"),
89
+ stdoutBuf: outBuf,
90
+ stderr: errBuf.toString("utf-8"),
91
+ code: res.status
92
+ };
93
+ }
94
+ function imageSize(buf) {
95
+ if (buf.length >= 24 && buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71) {
96
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
97
+ }
98
+ if (buf.length >= 4 && buf[0] === 255 && buf[1] === 216) {
99
+ let i = 2;
100
+ while (i < buf.length - 1) {
101
+ if (buf[i] !== 255) {
102
+ i += 1;
103
+ continue;
104
+ }
105
+ const marker = buf[i + 1];
106
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
107
+ const height = buf.readUInt16BE(i + 5);
108
+ const width = buf.readUInt16BE(i + 7);
109
+ return { width, height };
110
+ }
111
+ if (marker === 216 || marker === 217 || marker >= 208 && marker <= 215) {
112
+ i += 2;
113
+ continue;
114
+ }
115
+ const segLen = buf.readUInt16BE(i + 2);
116
+ i += 2 + segLen;
117
+ }
118
+ }
119
+ return { width: 1080, height: 2400 };
120
+ }
121
+ const APP_PACKAGES = /* @__PURE__ */ new Map();
122
+ class HdcDriver {
123
+ serial;
124
+ constructor(serial) {
125
+ this.serial = serial;
126
+ }
127
+ prefix() {
128
+ return this.serial ? ["-t", this.serial] : [];
129
+ }
130
+ shell(args, timeout = 15) {
131
+ return runBin("hdc", [...this.prefix(), "shell", ...args], { timeout });
132
+ }
133
+ getScreenshot() {
134
+ const remote = "/data/local/tmp/tmp_screenshot.jpeg";
135
+ let out = this.shell(["snapshot_display", "-f", remote], 10);
136
+ const combined = (out.stdout + out.stderr).toLowerCase();
137
+ if (combined.includes("fail") || combined.includes("error")) {
138
+ this.shell(["screenshot", remote], 10);
139
+ }
140
+ const localPath = path.join(os.tmpdir(), `ht_shot_${process.pid}_${Date.now()}.jpeg`);
141
+ runBin("hdc", [...this.prefix(), "file", "recv", remote, localPath], { timeout: 10 });
142
+ try {
143
+ const buf = fs.readFileSync(localPath);
144
+ fs.unlinkSync(localPath);
145
+ const { width, height } = imageSize(buf);
146
+ return { base64: buf.toString("base64"), mime: "image/jpeg", width, height };
147
+ } catch {
148
+ return fallbackScreenshot();
149
+ }
150
+ }
151
+ getCurrentApp() {
152
+ const out = this.shell(["aa", "dump", "-l"]).stdout;
153
+ if (!out) return "System Home";
154
+ let currentBundle = null;
155
+ let foreground = null;
156
+ for (const line of out.split("\n")) {
157
+ if (line.includes("app name [")) {
158
+ const m = line.match(/\[([^\]]+)\]/);
159
+ if (m) currentBundle = m[1];
160
+ }
161
+ if (line.toLowerCase().includes("state #foreground")) {
162
+ if (currentBundle) {
163
+ foreground = currentBundle;
164
+ break;
165
+ }
166
+ }
167
+ if (line.includes("Mission ID")) currentBundle = null;
168
+ }
169
+ if (foreground) {
170
+ for (const [name, pkg] of APP_PACKAGES) if (pkg === foreground) return name;
171
+ return foreground;
172
+ }
173
+ return "System Home";
174
+ }
175
+ launchApp(appName) {
176
+ const bundle = APP_PACKAGES.get(appName);
177
+ if (!bundle) {
178
+ console.log(`[HDC] App '${appName}' not registered`);
179
+ return false;
180
+ }
181
+ const ability = process.env.HT_HMOS_ABILITY || "EntryAbility";
182
+ this.shell(["aa", "start", "-b", bundle, "-a", ability]);
183
+ return true;
184
+ }
185
+ tap(x, y) {
186
+ this.shell(["uitest", "uiInput", "click", String(x), String(y)]);
187
+ }
188
+ doubleTap(x, y) {
189
+ this.shell(["uitest", "uiInput", "doubleClick", String(x), String(y)]);
190
+ }
191
+ longPress(x, y) {
192
+ this.shell(["uitest", "uiInput", "longClick", String(x), String(y)]);
193
+ }
194
+ swipe(x1, y1, x2, y2) {
195
+ const distance = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
196
+ let durationMs = Math.trunc(distance * distance / 1e3);
197
+ durationMs = Math.max(500, Math.min(durationMs, 1e3));
198
+ let velocity = Math.trunc(distance / durationMs * 4e3);
199
+ velocity = Math.max(500, Math.min(velocity, 4e4));
200
+ this.shell(["uitest", "uiInput", "swipe", String(x1), String(y1), String(x2), String(y2), String(velocity)]);
201
+ }
202
+ back() {
203
+ this.shell(["uitest", "uiInput", "keyEvent", "Back"]);
204
+ }
205
+ home() {
206
+ this.shell(["uitest", "uiInput", "keyEvent", "Home"]);
207
+ }
208
+ typeText(text) {
209
+ const escaped = text.replace(/"/g, '\\"').replace(/\$/g, "\\$");
210
+ this.shell(["uitest", "uiInput", "text", escaped]);
211
+ }
212
+ }
213
+ class AdbDriver {
214
+ serial;
215
+ constructor(serial) {
216
+ this.serial = serial;
217
+ }
218
+ prefix() {
219
+ return this.serial ? ["-s", this.serial] : [];
220
+ }
221
+ shell(args, timeout = 15) {
222
+ return runBin("adb", [...this.prefix(), "shell", ...args], { timeout });
223
+ }
224
+ getScreenshot() {
225
+ const { stdoutBuf, code } = runBin("adb", [...this.prefix(), "exec-out", "screencap", "-p"], {
226
+ timeout: 15,
227
+ binary: true
228
+ });
229
+ if (code !== 0 || stdoutBuf.length === 0) return fallbackScreenshot();
230
+ const { width, height } = imageSize(stdoutBuf);
231
+ return { base64: stdoutBuf.toString("base64"), mime: "image/png", width, height };
232
+ }
233
+ getCurrentApp() {
234
+ const out = this.shell(["dumpsys", "window"]).stdout;
235
+ for (const line of out.split("\n")) {
236
+ if (line.includes("mCurrentFocus") || line.includes("mFocusedApp")) {
237
+ for (const [name, pkg] of APP_PACKAGES) if (line.includes(pkg)) return name;
238
+ }
239
+ }
240
+ return "System Home";
241
+ }
242
+ launchApp(appName) {
243
+ const pkg = APP_PACKAGES.get(appName);
244
+ if (!pkg) {
245
+ console.log(`[ADB] App '${appName}' not registered`);
246
+ return false;
247
+ }
248
+ this.shell(["monkey", "-p", pkg, "-c", "android.intent.category.LAUNCHER", "1"]);
249
+ return true;
250
+ }
251
+ tap(x, y) {
252
+ this.shell(["input", "tap", String(x), String(y)]);
253
+ }
254
+ doubleTap(x, y) {
255
+ this.shell(["input", "tap", String(x), String(y)]);
256
+ this.shell(["input", "tap", String(x), String(y)]);
257
+ }
258
+ longPress(x, y) {
259
+ this.shell(["input", "swipe", String(x), String(y), String(x), String(y), "3000"]);
260
+ }
261
+ swipe(x1, y1, x2, y2) {
262
+ const distSq = (x1 - x2) ** 2 + (y1 - y2) ** 2;
263
+ let durationMs = Math.trunc(distSq / 1e3);
264
+ durationMs = Math.max(1e3, Math.min(durationMs, 2e3));
265
+ this.shell(["input", "swipe", String(x1), String(y1), String(x2), String(y2), String(durationMs)]);
266
+ }
267
+ back() {
268
+ this.shell(["input", "keyevent", "4"]);
269
+ }
270
+ home() {
271
+ this.shell(["input", "keyevent", "KEYCODE_HOME"]);
272
+ }
273
+ typeText(text) {
274
+ const encoded = Buffer.from(text, "utf-8").toString("base64");
275
+ this.shell(["am", "broadcast", "-a", "ADB_INPUT_B64", "--es", "msg", encoded]);
276
+ }
277
+ }
278
+ function fallbackScreenshot() {
279
+ const png = Buffer.from(
280
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC",
281
+ "base64"
282
+ );
283
+ return { base64: png.toString("base64"), mime: "image/png", width: 1080, height: 2400 };
284
+ }
285
+ function splitThinkingAction(content) {
286
+ const thinkM = content.match(/<thinking>(.*?)<\/thinking>/s);
287
+ const think = thinkM ? thinkM[1].trim() : "";
288
+ let cleaned = content.replace(/<thinking>.*?<\/thinking>\s*/gs, "");
289
+ const ansM = cleaned.match(/<answer>\s*(.*?)\s*<\/answer>/s);
290
+ if (ansM) cleaned = ansM[1];
291
+ cleaned = cleaned.replace(/<\/answer>/g, "").trim();
292
+ if (cleaned.includes("finish(message=")) {
293
+ const idx = cleaned.indexOf("finish(message=");
294
+ return { thinking: think || cleaned.slice(0, idx).trim(), action: cleaned.slice(idx) };
295
+ }
296
+ if (cleaned.includes("do(action=")) {
297
+ const idx = cleaned.indexOf("do(action=");
298
+ return { thinking: think || cleaned.slice(0, idx).trim(), action: cleaned.slice(idx) };
299
+ }
300
+ return { thinking: think, action: cleaned || content };
301
+ }
302
+ function stripLlmTags(text) {
303
+ let t = text.replace(/<thinking>.*?<\/thinking>\s*/gs, "");
304
+ const m = t.match(/<answer>\s*(.*?)\s*<\/answer>/s);
305
+ if (m) t = m[1];
306
+ return t.replace(/<\/answer>/g, "").trim();
307
+ }
308
+ function parseDoArgs(inner) {
309
+ const args = {};
310
+ const strRe = /(\w+)\s*=\s*"((?:[^"\\]|\\.)*)"/g;
311
+ let m;
312
+ while ((m = strRe.exec(inner)) !== null) {
313
+ args[m[1]] = m[2].replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\r/g, "\r").replace(/\\"/g, '"');
314
+ }
315
+ const arrRe = /(\w+)\s*=\s*\[\s*(-?\d+)\s*,\s*(-?\d+)\s*\]/g;
316
+ while ((m = arrRe.exec(inner)) !== null) {
317
+ args[m[1]] = [parseInt(m[2], 10), parseInt(m[3], 10)];
318
+ }
319
+ return args;
320
+ }
321
+ function parseAction(response) {
322
+ const cleaned = stripLlmTags(response);
323
+ for (const text of [cleaned, response.trim()]) {
324
+ const finishM = text.match(/finish\s*\(\s*message\s*=\s*"((?:[^"\\]|\\.)*)"\s*\)/s);
325
+ if (finishM) {
326
+ return { _metadata: "finish", message: finishM[1].replace(/\\"/g, '"').replace(/\\n/g, "\n") };
327
+ }
328
+ const doM = text.match(/do\s*\((.*)\)\s*$/s) || text.match(/do\s*\((.*?)\)/s);
329
+ if (doM) {
330
+ const args = parseDoArgs(doM[1]);
331
+ if (args.action) return { _metadata: "do", ...args };
332
+ }
333
+ }
334
+ return null;
335
+ }
336
+ function isDevEcoMaaS(cfg) {
337
+ return cfg.baseUrl.includes("devecostudio");
338
+ }
339
+ function chatCompletionsUrl(cfg) {
340
+ return cfg.baseUrl.replace(/\/$/, "") + "/chat/completions";
341
+ }
342
+ function buildHeaders(cfg) {
343
+ const headers = {
344
+ "Content-Type": "application/json",
345
+ Authorization: `Bearer ${cfg.apiKey}`
346
+ };
347
+ if (isDevEcoMaaS(cfg)) {
348
+ headers["Chat-Id"] = randomUUID().replace(/-/g, "");
349
+ }
350
+ return headers;
351
+ }
352
+ function buildBody(cfg, messages) {
353
+ const body = { model: cfg.modelName, messages, stream: false };
354
+ if (!isDevEcoMaaS(cfg)) {
355
+ body.max_tokens = 3e3;
356
+ body.temperature = cfg.temperature;
357
+ body.top_p = 0.85;
358
+ body.frequency_penalty = 0.2;
359
+ }
360
+ return body;
361
+ }
362
+ function extractContent(data) {
363
+ return data.choices?.[0]?.message?.content ?? "";
364
+ }
365
+ async function requestModel(cfg, messages) {
366
+ const resp = await fetch(chatCompletionsUrl(cfg), {
367
+ method: "POST",
368
+ headers: buildHeaders(cfg),
369
+ body: JSON.stringify(buildBody(cfg, messages))
370
+ });
371
+ if (!resp.ok) {
372
+ const text = await resp.text().catch(() => "");
373
+ throw new Error(`Model HTTP ${resp.status}: ${text.slice(0, 500)}`);
374
+ }
375
+ return extractContent(await resp.json());
376
+ }
377
+ function userMessage(text, shot) {
378
+ const content = [];
379
+ if (shot) {
380
+ content.push({ type: "image_url", image_url: { url: `data:${shot.mime};base64,${shot.base64}` } });
381
+ }
382
+ content.push({ type: "text", text });
383
+ return { role: "user", content };
384
+ }
385
+ function stripImages(msg) {
386
+ if (Array.isArray(msg.content)) {
387
+ return { ...msg, content: msg.content.filter((c) => c.type === "text") };
388
+ }
389
+ return msg;
390
+ }
391
+ class PhoneAgent {
392
+ cfg;
393
+ device;
394
+ maxSteps;
395
+ verbose;
396
+ context = [];
397
+ constructor(cfg, device, maxSteps, verbose) {
398
+ this.cfg = cfg;
399
+ this.device = device;
400
+ this.maxSteps = maxSteps;
401
+ this.verbose = verbose;
402
+ }
403
+ reset() {
404
+ this.context = [];
405
+ }
406
+ async run(task) {
407
+ this.context = [];
408
+ let stepCount = 0;
409
+ let isFirst = true;
410
+ while (stepCount < this.maxSteps) {
411
+ stepCount += 1;
412
+ const shot = this.device.getScreenshot();
413
+ const currentApp = this.device.getCurrentApp();
414
+ const screenInfo = JSON.stringify({ current_app: currentApp });
415
+ if (isFirst) {
416
+ this.context.push({ role: "system", content: buildSystemPrompt() });
417
+ this.context.push(userMessage(`${task}
418
+
419
+ ${screenInfo}`, shot));
420
+ isFirst = false;
421
+ } else {
422
+ this.context.push(userMessage(`** Screen Info **
423
+
424
+ ${screenInfo}`, shot));
425
+ }
426
+ let content;
427
+ try {
428
+ content = await requestModel(this.cfg, this.context);
429
+ } catch (e) {
430
+ return `Model error: ${e.message}`;
431
+ }
432
+ const { thinking, action: actionStr } = splitThinkingAction(content);
433
+ if (this.verbose) {
434
+ console.log(`
435
+ ${"=".repeat(50)}
436
+ 💭 思考过程:
437
+ ${"-".repeat(50)}`);
438
+ console.log(thinking || "(无)");
439
+ console.log(`${"-".repeat(50)}
440
+ 🎯 执行动作: ${actionStr}
441
+ ${"=".repeat(50)}`);
442
+ }
443
+ const action = parseAction(actionStr) ?? { _metadata: "finish", message: actionStr };
444
+ this.context[this.context.length - 1] = stripImages(this.context[this.context.length - 1]);
445
+ this.context.push({
446
+ role: "assistant",
447
+ content: `<thinking>${thinking}</thinking><answer>${actionStr}</answer>`
448
+ });
449
+ if (action._metadata === "finish") {
450
+ return action.message || "Task completed";
451
+ }
452
+ await this.execute(action, shot.width, shot.height);
453
+ await sleep(ACTION_DELAY);
454
+ }
455
+ return "Max steps reached";
456
+ }
457
+ async execute(action, width, height) {
458
+ const toPx = (el) => {
459
+ const [rx, ry] = el;
460
+ return [Math.trunc(rx / 1e3 * width), Math.trunc(ry / 1e3 * height)];
461
+ };
462
+ const name = action.action;
463
+ try {
464
+ switch (name) {
465
+ case "Launch":
466
+ this.device.launchApp(action.app);
467
+ break;
468
+ case "Tap": {
469
+ const [x, y] = toPx(action.element);
470
+ this.device.tap(x, y);
471
+ break;
472
+ }
473
+ case "Double Tap": {
474
+ const [x, y] = toPx(action.element);
475
+ this.device.doubleTap(x, y);
476
+ break;
477
+ }
478
+ case "Long Press": {
479
+ const [x, y] = toPx(action.element);
480
+ this.device.longPress(x, y);
481
+ break;
482
+ }
483
+ case "Swipe": {
484
+ const [sx, sy] = toPx(action.start);
485
+ const [ex, ey] = toPx(action.end);
486
+ this.device.swipe(sx, sy, ex, ey);
487
+ break;
488
+ }
489
+ case "Type":
490
+ case "Type_Name":
491
+ this.device.typeText(action.text ?? "");
492
+ break;
493
+ case "Back":
494
+ this.device.back();
495
+ break;
496
+ case "Home":
497
+ this.device.home();
498
+ break;
499
+ case "Wait": {
500
+ const dur = parseFloat(String(action.duration ?? "1").replace("seconds", "").trim());
501
+ await sleep(Number.isFinite(dur) ? dur : 1);
502
+ break;
503
+ }
504
+ case "Note":
505
+ case "Call_API":
506
+ case "Interact":
507
+ case "Take_over":
508
+ break;
509
+ default:
510
+ console.log(` [WARN] Unknown action: ${name}`);
511
+ }
512
+ } catch (e) {
513
+ console.log(` [WARN] Action '${name}' failed: ${e.message}`);
514
+ }
515
+ }
516
+ }
517
+ function parseFeatureMd(filePath) {
518
+ const text = fs.readFileSync(filePath, "utf-8");
519
+ const results = [];
520
+ let currentFeature = "";
521
+ let current = null;
522
+ let collecting = null;
523
+ for (const line of text.split(/\r?\n/)) {
524
+ const stripped = line.trim();
525
+ const feat = stripped.match(/^##\s+Feature:\s*(.+)$/);
526
+ if (feat) {
527
+ if (current) results.push(current);
528
+ current = null;
529
+ currentFeature = feat[1].trim();
530
+ collecting = null;
531
+ continue;
532
+ }
533
+ const scen = stripped.match(/^###\s+Scenario:\s*(.+)$/);
534
+ if (scen) {
535
+ if (current) results.push(current);
536
+ const scenarioName = scen[1].trim();
537
+ const featureName = currentFeature.replace(/^FEA-\d+\s*/, "");
538
+ current = {
539
+ feature: currentFeature,
540
+ scenario: scenarioName,
541
+ preconditions: [],
542
+ actions: [],
543
+ expectations: [],
544
+ L1: featureName,
545
+ L2: scenarioName,
546
+ L3: ""
547
+ };
548
+ collecting = null;
549
+ continue;
550
+ }
551
+ if (!current) continue;
552
+ if (/^-\s*前置条件[::]/.test(stripped)) {
553
+ collecting = "preconditions";
554
+ continue;
555
+ }
556
+ const act = stripped.match(/^-\s*动作[::]\s*(.+)$/);
557
+ if (act) {
558
+ collecting = null;
559
+ current.actions.push(act[1].trim());
560
+ continue;
561
+ }
562
+ const exp = stripped.match(/^-\s*预期结果[::]\s*(.+)$/);
563
+ if (exp) {
564
+ collecting = null;
565
+ current.expectations.push(exp[1].trim());
566
+ continue;
567
+ }
568
+ const sub = line.match(/^\s+-\s+(.+)$/);
569
+ if (sub && collecting === "preconditions") {
570
+ current.preconditions.push(sub[1].trim());
571
+ continue;
572
+ }
573
+ if (stripped && !stripped.startsWith("-")) collecting = null;
574
+ }
575
+ if (current) results.push(current);
576
+ return results;
577
+ }
578
+ function getFeaturePath(item) {
579
+ let keys = ["L1", "L2", "L3"].filter((k) => k in item);
580
+ if (keys.length === 0) keys = ["一级", "二级", "三级"].filter((k) => k in item);
581
+ if (keys.length === 0) keys = Object.keys(item).slice(0, 3);
582
+ const parts = [];
583
+ for (const k of keys) {
584
+ const v = item[k];
585
+ if (v != null && String(v).trim()) parts.push(String(v).trim());
586
+ }
587
+ if (parts.length === 0) return { pathStr: "", leaf: "" };
588
+ return { pathStr: parts.join(" > "), leaf: parts[parts.length - 1] };
589
+ }
590
+ function buildNavigatePrompt(appName, pathStr, leaf, hints) {
591
+ let prompt = `打开${appName},按照以下路径依次点击导航到目标页面:${pathStr}。最终目标是到达「${leaf}」所在的页面。注意:1. 鸿蒙手机浅色/深色模式切换路径:设置->显示与亮度2. '更多'组件可能表示为 三横 或者 三点。3. '设置'组件可能表示为 齿轮。到达目标页面后请回复'已到达',无法到达请回复'未找到'。`;
592
+ if (hints) prompt += `
593
+ 补充提示: ${hints}`;
594
+ return prompt;
595
+ }
596
+ function judgeReached(msg) {
597
+ if (!msg) return false;
598
+ const reached = ["已到达", "到达", "存在", "找到", "完成", "成功", "已确认", "已进入", "已打开"];
599
+ const failed = ["未找到", "不存在", "无法找到", "无法到达", "没有", "失败", "未到达"];
600
+ const firstLine = msg.split("\n")[0];
601
+ if (failed.some((k) => firstLine.includes(k))) return false;
602
+ if (reached.some((k) => firstLine.includes(k))) return true;
603
+ return false;
604
+ }
605
+ function loadModelConfig(cliApiKey, stdinModel) {
606
+ if (stdinModel?.apiKey) {
607
+ return {
608
+ apiKey: stdinModel.apiKey,
609
+ baseUrl: stdinModel.baseURL || "http://localhost:8000/v1",
610
+ modelName: stdinModel.modelName,
611
+ temperature: 0.1
612
+ };
613
+ }
614
+ let apiKey = (cliApiKey || process.env.HOMETRANS_MODEL_API_KEY || "").trim();
615
+ let baseUrl = (process.env.HOMETRANS_MODEL_BASE_URL || "").trim();
616
+ let modelName = (process.env.HOMETRANS_MODEL_NAME || "").trim();
617
+ let temperature = 0.1;
618
+ const configPath = path.join(os.homedir(), ".hometrans", "config.json");
619
+ if (fs.existsSync(configPath)) {
620
+ try {
621
+ const cfg = JSON.parse(fs.readFileSync(configPath, "utf-8"));
622
+ const um = cfg?.autotest?.unified_model ?? {};
623
+ apiKey = apiKey || String(um.api_key ?? "").trim();
624
+ baseUrl = baseUrl || String(um.base_url ?? "").trim();
625
+ modelName = modelName || String(um.name ?? "").trim();
626
+ if (um.temperature != null) temperature = Number(um.temperature);
627
+ } catch {
628
+ }
629
+ }
630
+ if (apiKey) {
631
+ return { baseUrl: baseUrl || "http://localhost:8000/v1", apiKey, modelName, temperature };
632
+ }
633
+ const glmKey = (process.env.GLM_API_KEY || "").trim();
634
+ if (glmKey) {
635
+ return {
636
+ baseUrl: "https://open.bigmodel.cn/api/paas/v4",
637
+ apiKey: glmKey,
638
+ modelName: "autoglm-phone",
639
+ temperature: 0.1
640
+ };
641
+ }
642
+ return { baseUrl: "http://localhost:8000/v1", apiKey: "EMPTY", modelName: "", temperature };
643
+ }
644
+ function parseArgs(argv) {
645
+ const a = {
646
+ device: "hdc",
647
+ app: "",
648
+ package: "",
649
+ task: null,
650
+ prompt: null,
651
+ feature: null,
652
+ limit: null,
653
+ offset: 1,
654
+ apiKey: "",
655
+ maxSteps: 30,
656
+ appHints: null,
657
+ serial: null,
658
+ quiet: false,
659
+ modelStdin: false
660
+ };
661
+ for (let i = 0; i < argv.length; i++) {
662
+ const arg = argv[i];
663
+ const next = () => argv[++i];
664
+ switch (arg) {
665
+ case "--device":
666
+ a.device = next();
667
+ break;
668
+ case "--app":
669
+ a.app = next();
670
+ break;
671
+ case "--package":
672
+ a.package = next();
673
+ break;
674
+ case "--task":
675
+ a.task = next();
676
+ break;
677
+ case "--prompt":
678
+ a.prompt = next();
679
+ break;
680
+ case "--feature":
681
+ a.feature = next();
682
+ break;
683
+ case "--limit":
684
+ a.limit = parseInt(next(), 10);
685
+ break;
686
+ case "--offset":
687
+ a.offset = parseInt(next(), 10);
688
+ break;
689
+ case "--api-key":
690
+ a.apiKey = next();
691
+ break;
692
+ case "--max-steps":
693
+ a.maxSteps = parseInt(next(), 10);
694
+ break;
695
+ case "--app-hints":
696
+ a.appHints = next();
697
+ break;
698
+ case "--serial":
699
+ a.serial = next();
700
+ break;
701
+ case "-q":
702
+ case "--quiet":
703
+ a.quiet = true;
704
+ break;
705
+ case "--model-stdin":
706
+ a.modelStdin = true;
707
+ break;
708
+ default:
709
+ console.log(`[WARN] 未知参数: ${arg}`);
710
+ }
711
+ }
712
+ return a;
713
+ }
714
+ async function main() {
715
+ const args = parseArgs(process.argv.slice(2));
716
+ if (!args.app || !args.package) {
717
+ console.error("错误: 必须指定 --app 和 --package");
718
+ return 2;
719
+ }
720
+ if (!args.prompt && !args.task && !args.feature) {
721
+ console.error("错误: 必须指定 --feature、--task 或 --prompt 之一");
722
+ return 2;
723
+ }
724
+ APP_PACKAGES.set(args.app, args.package);
725
+ let stdinModel = null;
726
+ if (args.modelStdin) {
727
+ try {
728
+ stdinModel = JSON.parse(fs.readFileSync(0, "utf-8"));
729
+ } catch {
730
+ }
731
+ }
732
+ const model = loadModelConfig(args.apiKey, stdinModel);
733
+ if (!model.apiKey || model.apiKey === "EMPTY") {
734
+ if (!args.quiet) {
735
+ console.log("提示: 未找到可用的模型配置。请运行 `ht init` 配置统一模型,");
736
+ console.log("或通过 --api-key 传入 API Key。\n");
737
+ }
738
+ }
739
+ const deviceLabel = args.device === "adb" ? "ADB (Android)" : "HDC (HarmonyOS)";
740
+ console.log(`设备: ${deviceLabel}, 应用: ${args.app} (${args.package})`);
741
+ console.log("-".repeat(50));
742
+ const driver = args.device === "adb" ? new AdbDriver(args.serial) : new HdcDriver(args.serial);
743
+ const agent = new PhoneAgent(model, driver, args.maxSteps, !args.quiet);
744
+ const tasks = [];
745
+ if (args.prompt) {
746
+ tasks.push({ prompt: `打开${args.app},${args.prompt}`, label: args.prompt });
747
+ } else if (args.task) {
748
+ const parts = args.task.split(/(L[123])/);
749
+ const item = {};
750
+ for (let j = 1; j < parts.length - 1; j += 2) {
751
+ const val = parts[j + 1].trim();
752
+ if (val) item[parts[j]] = val;
753
+ }
754
+ const { pathStr, leaf } = getFeaturePath(item);
755
+ if (pathStr) tasks.push({ prompt: buildNavigatePrompt(args.app, pathStr, leaf, args.appHints ?? void 0), label: pathStr });
756
+ } else if (args.feature) {
757
+ if (!args.feature.toLowerCase().endsWith(".md")) {
758
+ console.error("错误: --feature 仅支持 .md 功能清单,或改用 --prompt / --task。");
759
+ return 2;
760
+ }
761
+ let features = parseFeatureMd(args.feature);
762
+ if (args.offset > 1) features = features.slice(args.offset - 1);
763
+ if (args.limit != null) features = features.slice(0, args.limit);
764
+ for (const item of features) {
765
+ const { pathStr, leaf } = getFeaturePath(item);
766
+ if (pathStr) tasks.push({ prompt: buildNavigatePrompt(args.app, pathStr, leaf, args.appHints ?? void 0), label: pathStr });
767
+ }
768
+ }
769
+ for (let i = 0; i < tasks.length; i++) {
770
+ const { prompt, label } = tasks[i];
771
+ console.log(tasks.length > 1 ? `
772
+ [${i + 1}/${tasks.length}] 导航: ${label}` : `导航: ${label}`);
773
+ let reached = false;
774
+ try {
775
+ const resultMsg = await agent.run(prompt);
776
+ reached = judgeReached(resultMsg);
777
+ } catch {
778
+ reached = false;
779
+ }
780
+ console.log(reached ? "到达目标页面" : "未找到目标页面");
781
+ if (i < tasks.length - 1) agent.reset();
782
+ }
783
+ return 0;
784
+ }
785
+ main().then((code) => {
786
+ process.exitCode = code;
787
+ }).catch((e) => {
788
+ console.error(e);
789
+ process.exitCode = 1;
790
+ });