ef-compiler.js 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518
  1. // EasyFlow 编译器 - 工作流任务解析和执行器
  2. // 配置参数
  3. const DEFAULT_STEP_INTERVAL = 1000; // 默认步骤间隔1秒
  4. const DEFAULT_SCROLL_DISTANCE = 100; // 默认每次滚动距离(像素)
  5. // 变量上下文(用于存储变量值)
  6. let variableContext = {};
  7. // 变量上下文是否已初始化(防止循环中重置变量)
  8. let variableContextInitialized = false;
  9. // 全局步骤计数器(用于连续的步骤编号)
  10. let globalStepCounter = 0;
  11. // 当前工作流文件夹路径(用于日志记录)
  12. let currentWorkflowFolderPath = null;
  13. /**
  14. * 记录日志(同时输出到 console 和文件)
  15. * @param {string} message - 日志消息
  16. * @param {string} folderPath - 工作流文件夹路径(可选,如果不提供则使用 currentWorkflowFolderPath)
  17. */
  18. async function logMessage(message, folderPath = null) {
  19. // 尝试写入日志文件(异步,不阻塞主流程)
  20. // 注意:不输出到 console,只写入日志文件
  21. try {
  22. const targetFolderPath = folderPath || currentWorkflowFolderPath;
  23. if (targetFolderPath && electronAPI.appendLog) {
  24. electronAPI.appendLog(targetFolderPath, message).catch(err => {
  25. // 静默失败,不影响主流程
  26. });
  27. }
  28. } catch (error) {
  29. // 静默失败,不影响主流程
  30. }
  31. }
  32. // 打印所有 outVars 的值
  33. async function logOutVars(action, variableContext, folderPath = null) {
  34. if (!action.outVars || !Array.isArray(action.outVars) || action.outVars.length === 0) {
  35. return;
  36. }
  37. const outVarsInfo = action.outVars.map((varName, index) => {
  38. const varNameClean = extractVarName(varName);
  39. const value = variableContext[varNameClean];
  40. // 如果值太长,截断显示(超过100字符)
  41. let displayValue = value;
  42. if (typeof value === 'string' && value.length > 100) {
  43. displayValue = value.substring(0, 100) + '...';
  44. }
  45. return `${varNameClean}: ${JSON.stringify(displayValue)}`;
  46. });
  47. // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
  48. // const logMsg = `输出变量: ${outVarsInfo.join(', ')}`;
  49. // await logMessage(logMsg, folderPath);
  50. }
  51. const path = require('path')
  52. const fs = require('fs')
  53. const { spawnSync } = require('child_process')
  54. const funcDir = path.join(__dirname, 'Func')
  55. const projectRoot = path.resolve(__dirname, '..', '..')
  56. const adbInteractPath = path.join(projectRoot, 'nodejs', 'adb', 'adb-interact.js')
  57. const { generateHistorySummary, getHistorySummary } = require(path.join(funcDir, 'chat', 'chat-history.js'))
  58. const { executeOcrChat } = require(path.join(funcDir, 'chat', 'ocr-chat.js'))
  59. const { executeImgBoundingBoxLocation } = require(path.join(funcDir, 'img-bounding-box-location.js'))
  60. const { executeImgCenterPointLocation, matchImageAndGetCoordinate } = require(path.join(funcDir, 'img-center-point-location.js'))
  61. const { executeImgCropping } = require(path.join(funcDir, 'img-cropping.js'))
  62. const { executeReadLastMessage } = require(path.join(funcDir, 'chat', 'read-last-message.js'))
  63. const { executeReadTxt, readTextFile } = require(path.join(funcDir, 'read-txt.js'))
  64. const { executeSaveTxt, writeTextFile } = require(path.join(funcDir, 'save-txt.js'))
  65. const { executeSmartChatAppend } = require(path.join(funcDir, 'chat', 'smart-chat-append.js'))
  66. function runAdb(action, args = [], deviceId = '') {
  67. const r = spawnSync('node', [adbInteractPath, action, ...args, deviceId], { encoding: 'utf-8', timeout: 10000 })
  68. return { success: r.status === 0, error: r.stderr }
  69. }
  70. const sendTap = (device, x, y) => runAdb('tap', [String(x), String(y)], device)
  71. const sendSwipe = (device, x1, y1, x2, y2, duration) => runAdb('swipe-coords', [String(x1), String(y1), String(x2), String(y2), String(duration || 300)], device)
  72. const sendKeyEvent = (device, keyCode) => runAdb('keyevent', [String(keyCode)], device)
  73. const sendText = (device, text) => runAdb('text', [String(text)], device)
  74. function appendLog(folderPath, message) {
  75. fs.appendFileSync(path.join(folderPath, 'log.txt'), message + '\n')
  76. return Promise.resolve()
  77. }
  78. const _stub = (name) => ({ success: false, error: `${name} 需在主进程实现` })
  79. const electronAPI = {
  80. sendTap, sendSwipe, sendKeyEvent, sendText,
  81. matchImageAndGetCoordinate,
  82. findTextAndGetCoordinate: () => _stub('findTextAndGetCoordinate'),
  83. appendLog, readTextFile, writeTextFile,
  84. saveChatHistory: () => _stub('saveChatHistory'),
  85. readChatHistory: () => _stub('readChatHistory'),
  86. readAllChatHistory: () => _stub('readAllChatHistory'),
  87. saveChatHistorySummary: () => _stub('saveChatHistorySummary'),
  88. getChatHistorySummary: () => _stub('getChatHistorySummary'),
  89. saveChatHistoryTxt: () => _stub('saveChatHistoryTxt'),
  90. extractChatHistory: () => _stub('extractChatHistory'),
  91. readLastMessage: () => _stub('readLastMessage'),
  92. ocrLastMessage: () => _stub('ocrLastMessage'),
  93. getCachedScreenshot: () => _stub('getCachedScreenshot'),
  94. captureScreenshot: () => _stub('captureScreenshot'),
  95. sendScroll: () => _stub('sendScroll'),
  96. sendSystemKey: () => _stub('sendSystemKey'),
  97. matchImageRegionLocation: () => _stub('matchImageRegionLocation'),
  98. }
  99. /**
  100. * 解析时间字符串(格式:2026/1/13 02:09)
  101. * @param {string} timeStr - 时间字符串
  102. * @returns {Date|null} 解析后的日期对象,失败返回null
  103. */
  104. function parseTimeString(timeStr) {
  105. if (!timeStr || timeStr.trim() === '') {
  106. return null;
  107. }
  108. try {
  109. // 支持格式:2026/1/13 02:09 或 2026/01/13 02:09
  110. const parts = timeStr.trim().split(' ');
  111. if (parts.length !== 2) {
  112. return null;
  113. }
  114. const datePart = parts[0].split('/');
  115. const timePart = parts[1].split(':');
  116. if (datePart.length !== 3 || timePart.length !== 2) {
  117. return null;
  118. }
  119. const year = parseInt(datePart[0], 10);
  120. const month = parseInt(datePart[1], 10) - 1; // 月份从0开始
  121. const day = parseInt(datePart[2], 10);
  122. const hour = parseInt(timePart[0], 10);
  123. const minute = parseInt(timePart[1], 10);
  124. const date = new Date(year, month, day, hour, minute, 0, 0);
  125. // 验证日期是否有效
  126. if (isNaN(date.getTime())) {
  127. return null;
  128. }
  129. return date;
  130. } catch (error) {
  131. return null;
  132. }
  133. }
  134. /**
  135. * 解析延迟字符串(格式:10s, 5m, 2h)
  136. * @param {string} delayStr - 延迟字符串
  137. * @returns {number|null} 延迟的毫秒数,失败返回null
  138. */
  139. function parseDelayString(delayStr) {
  140. if (!delayStr || delayStr.trim() === '') {
  141. return 0; // 空字符串表示不延迟
  142. }
  143. try {
  144. const trimmed = delayStr.trim();
  145. const unit = trimmed.slice(-1).toLowerCase();
  146. const value = parseInt(trimmed.slice(0, -1), 10);
  147. if (isNaN(value) || value < 0) {
  148. return null;
  149. }
  150. switch (unit) {
  151. case 's':
  152. return value * 1000; // 秒转毫秒
  153. case 'm':
  154. return value * 60 * 1000; // 分钟转毫秒
  155. case 'h':
  156. return value * 60 * 60 * 1000; // 小时转毫秒
  157. default:
  158. return null;
  159. }
  160. } catch (error) {
  161. return null;
  162. }
  163. }
  164. /**
  165. * 计算需要等待的时间(毫秒)
  166. * @param {string} data - 执行时间字符串(格式:2026/1/13 02:09)
  167. * @param {string} delay - 延迟字符串(格式:10s, 5m, 2h)
  168. * @returns {number} 需要等待的毫秒数
  169. */
  170. function calculateWaitTime(data, delay) {
  171. // 始终返回 0,不等待,立即执行
  172. return 0;
  173. }
  174. /**
  175. * 从变量名中提取变量名(去除 {variable} 格式的包裹)
  176. * @param {string} varName - 变量名(可能包含 {})
  177. * @returns {string} 提取后的变量名
  178. */
  179. function extractVarName(varName) {
  180. if (typeof varName === 'string' && varName.startsWith('{') && varName.endsWith('}')) {
  181. return varName.slice(1, -1);
  182. }
  183. return varName;
  184. }
  185. /**
  186. * 替换字符串中的变量(只支持 {{variable}} 格式,用于字符串拼接)
  187. * @param {string} str - 原始字符串
  188. * @param {Object} context - 变量上下文
  189. * @returns {string} 替换后的字符串
  190. */
  191. function replaceVariablesInString(str, context = variableContext) {
  192. if (typeof str !== 'string') {
  193. return str;
  194. }
  195. let result = str;
  196. // 只替换 {{variable}} 格式的变量(双花括号,用于字符串拼接)
  197. // 支持变量名中包含连字符,如 {{chat-history}}
  198. const doubleBracePattern = /\{\{([\w-]+)\}\}/g;
  199. result = result.replace(doubleBracePattern, (match, varName) => {
  200. const varValue = context[varName];
  201. if (varValue === undefined || varValue === null) {
  202. return '';
  203. }
  204. // 如果值是空字符串,返回空字符串
  205. if (varValue === '') {
  206. return '';
  207. }
  208. // 如果值是字符串 "undefined" 或 "null",视为空
  209. if (varValue === 'undefined' || varValue === 'null') {
  210. return '';
  211. }
  212. // 如果是字符串,尝试判断是否是 JSON 数组字符串
  213. if (typeof varValue === 'string') {
  214. try {
  215. const parsed = JSON.parse(varValue);
  216. if (Array.isArray(parsed)) {
  217. // 如果是空数组,返回空字符串
  218. if (parsed.length === 0) {
  219. return '';
  220. }
  221. // 如果不是空数组,返回原始 JSON 字符串
  222. return varValue;
  223. }
  224. } catch (e) {
  225. // 不是 JSON,按普通字符串处理
  226. }
  227. }
  228. // 如果是数组或对象,转换为 JSON 字符串
  229. if (Array.isArray(varValue) || typeof varValue === 'object') {
  230. try {
  231. return JSON.stringify(varValue);
  232. } catch (e) {
  233. return String(varValue);
  234. }
  235. }
  236. return String(varValue);
  237. });
  238. return result;
  239. }
  240. /**
  241. * 解析变量值(支持 {variable} 格式)
  242. * @param {any} value - 原始值
  243. * @param {Object} context - 变量上下文
  244. * @returns {any} 解析后的值
  245. */
  246. function resolveValue(value, context = variableContext) {
  247. if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) {
  248. const varName = value.slice(1, -1);
  249. return context[varName] !== undefined ? context[varName] : value;
  250. }
  251. if (Array.isArray(value)) {
  252. return value.map(item => resolveValue(item, context));
  253. }
  254. if (typeof value === 'object' && value !== null) {
  255. const resolved = {};
  256. for (const key in value) {
  257. resolved[key] = resolveValue(value[key], context);
  258. }
  259. return resolved;
  260. }
  261. return value;
  262. }
  263. /**
  264. * 手动解析并计算算术表达式(不使用 eval 或 Function)
  265. * 支持 +, -, *, / 和括号
  266. * @param {string} expr - 表达式字符串,如 "1+2*3"
  267. * @returns {number} 计算结果
  268. */
  269. function parseArithmeticExpression(expr) {
  270. let index = 0;
  271. // 跳过空格
  272. const skipWhitespace = () => {
  273. while (index < expr.length && /\s/.test(expr[index])) {
  274. index++;
  275. }
  276. };
  277. // 解析数字
  278. const parseNumber = () => {
  279. skipWhitespace();
  280. let numStr = '';
  281. let hasDot = false;
  282. while (index < expr.length) {
  283. const char = expr[index];
  284. if (char >= '0' && char <= '9') {
  285. numStr += char;
  286. index++;
  287. } else if (char === '.' && !hasDot) {
  288. numStr += '.';
  289. hasDot = true;
  290. index++;
  291. } else {
  292. break;
  293. }
  294. }
  295. if (numStr === '') {
  296. throw new Error('期望数字');
  297. }
  298. const num = parseFloat(numStr);
  299. if (isNaN(num)) {
  300. throw new Error(`无效的数字: ${numStr}`);
  301. }
  302. return num;
  303. };
  304. // 解析因子(数字或括号表达式)
  305. const parseFactor = () => {
  306. skipWhitespace();
  307. if (index >= expr.length) {
  308. throw new Error('表达式不完整');
  309. }
  310. // 处理负号(一元运算符)
  311. let isNegative = false;
  312. if (expr[index] === '-') {
  313. isNegative = true;
  314. index++;
  315. skipWhitespace();
  316. } else if (expr[index] === '+') {
  317. // 正号可以忽略
  318. index++;
  319. skipWhitespace();
  320. }
  321. let result;
  322. if (expr[index] === '(') {
  323. index++; // 跳过 '('
  324. result = parseExpression();
  325. skipWhitespace();
  326. if (index >= expr.length || expr[index] !== ')') {
  327. throw new Error('缺少右括号');
  328. }
  329. index++; // 跳过 ')'
  330. } else {
  331. result = parseNumber();
  332. }
  333. return isNegative ? -result : result;
  334. };
  335. // 解析项(处理 * 和 /)
  336. const parseTerm = () => {
  337. let result = parseFactor();
  338. skipWhitespace();
  339. while (index < expr.length) {
  340. const op = expr[index];
  341. if (op === '*') {
  342. index++;
  343. result *= parseFactor();
  344. } else if (op === '/') {
  345. index++;
  346. const divisor = parseFactor();
  347. if (divisor === 0) {
  348. throw new Error('除以零');
  349. }
  350. result /= divisor;
  351. } else {
  352. break;
  353. }
  354. skipWhitespace();
  355. }
  356. return result;
  357. };
  358. // 解析表达式(处理 + 和 -)
  359. const parseExpression = () => {
  360. let result = parseTerm();
  361. skipWhitespace();
  362. while (index < expr.length) {
  363. const op = expr[index];
  364. if (op === '+') {
  365. index++;
  366. result += parseTerm();
  367. } else if (op === '-') {
  368. index++;
  369. result -= parseTerm();
  370. } else {
  371. break;
  372. }
  373. skipWhitespace();
  374. }
  375. return result;
  376. };
  377. try {
  378. const result = parseExpression();
  379. skipWhitespace();
  380. if (index < expr.length) {
  381. throw new Error(`表达式解析不完整,剩余: ${expr.substring(index)}`);
  382. }
  383. return result;
  384. } catch (error) {
  385. throw new Error(`表达式解析失败: ${error.message}`);
  386. }
  387. }
  388. /**
  389. * 评估算术表达式(支持 +, -, *, / 运算)
  390. * 只处理 {variable} 格式(单花括号),用于数字运算
  391. * @param {string} expression - 表达式字符串,如 "{turn} + 1"
  392. * @param {Object} context - 变量上下文
  393. * @returns {any} 计算结果
  394. */
  395. function evaluateExpression(expression, context = variableContext) {
  396. if (typeof expression !== 'string') {
  397. return expression;
  398. }
  399. try {
  400. // 替换变量(只处理 {variable} 格式,单花括号用于数字运算)
  401. let expr = expression.trim();
  402. // 只匹配 {variable} 格式,不匹配 {{variable}} 格式
  403. // 使用负向前瞻确保不会匹配双花括号的开始部分
  404. const varPattern = /\{(\w+)\}(?!\})/g;
  405. const originalExpr = expr;
  406. let hasVariables = false;
  407. expr = expr.replace(varPattern, (match, varName) => {
  408. hasVariables = true;
  409. const value = context[varName];
  410. if (value === undefined || value === null) {
  411. return '0';
  412. }
  413. // 数字类型直接转换
  414. if (typeof value === 'number') {
  415. return String(value);
  416. }
  417. // 布尔类型转换
  418. if (typeof value === 'boolean') {
  419. return value ? '1' : '0';
  420. }
  421. // 尝试将字符串转换为数字
  422. if (typeof value === 'string') {
  423. const numValue = Number(value);
  424. // 如果字符串可以转换为数字,且不是空字符串,使用数字
  425. if (!isNaN(numValue) && value.trim() !== '') {
  426. return String(numValue);
  427. }
  428. // 如果无法转换为数字,返回 0 避免错误
  429. return '0';
  430. }
  431. // 其他类型尝试转换为数字
  432. const numValue = Number(value);
  433. if (!isNaN(numValue)) {
  434. return String(numValue);
  435. }
  436. return '0';
  437. });
  438. // 如果没有变量且没有运算符,直接返回原值
  439. if (!hasVariables && !/[+\-*/]/.test(expr)) {
  440. const numValue = Number(expr);
  441. if (!isNaN(numValue) && expr.trim() !== '') {
  442. return numValue;
  443. }
  444. return expr;
  445. }
  446. // 检查是否包含算术运算符
  447. if (!/[+\-*/]/.test(expr)) {
  448. // 没有运算符,直接返回解析后的值
  449. const numValue = Number(expr);
  450. if (!isNaN(numValue) && expr.trim() !== '') {
  451. return numValue;
  452. }
  453. return expr;
  454. }
  455. // 手动解析简单的算术表达式(只支持 +, -, *, /)
  456. // 移除所有空格
  457. expr = expr.replace(/\s+/g, '');
  458. // 检查是否只包含数字、运算符、小数点和括号
  459. if (!/^[0-9+\-*/().]+$/.test(expr)) {
  460. // 包含不允许的字符,返回原值
  461. return resolveValue(originalExpr, context);
  462. }
  463. // 验证表达式格式(防止注入)
  464. // 确保表达式以数字或括号开头,以数字或括号结尾
  465. if (!/^[0-9(]/.test(expr) || !/[0-9)]$/.test(expr)) {
  466. return resolveValue(originalExpr, context);
  467. }
  468. // 手动解析并计算表达式(不使用 eval 或 Function)
  469. const result = parseArithmeticExpression(expr);
  470. // 如果结果是数字,返回数字类型
  471. if (typeof result === 'number' && !isNaN(result) && isFinite(result)) {
  472. return result;
  473. }
  474. // 如果结果不是有效数字,返回原值
  475. return resolveValue(originalExpr, context);
  476. } catch (error) {
  477. // 如果计算失败,尝试直接解析变量
  478. return resolveValue(expression, context);
  479. }
  480. }
  481. /**
  482. * 评估条件表达式(不使用eval,手动解析)
  483. * @param {string} condition - 条件表达式
  484. * @param {Object} context - 变量上下文
  485. * @returns {boolean} 条件结果
  486. */
  487. function evaluateCondition(condition, context = variableContext) {
  488. if (!condition) return true;
  489. try {
  490. // 替换变量
  491. // 支持变量名中包含连字符,如 {chat-history}
  492. // 使用 [\w-]+ 来匹配字母、数字、下划线和连字符
  493. let expr = condition;
  494. const varPattern = /\{([\w-]+)\}/g;
  495. expr = expr.replace(varPattern, (match, varName) => {
  496. const value = context[varName];
  497. // 如果变量不存在,视为空字符串(所有变量都是 string 或 int 类型)
  498. if (value === undefined || value === null) {
  499. return '""';
  500. }
  501. // 如果值是空字符串,也返回 '""'
  502. if (value === '') {
  503. return '""';
  504. }
  505. // 如果值是字符串 "undefined" 或 "null",也视为空字符串
  506. if (value === 'undefined' || value === 'null') {
  507. return '""';
  508. }
  509. // 确保字符串类型
  510. if (typeof value === 'string') {
  511. // 尝试判断是否是 JSON 字符串
  512. try {
  513. const parsed = JSON.parse(value);
  514. if (Array.isArray(parsed)) {
  515. // 如果是 JSON 数组字符串,转换为 JSON 字符串用于比较(保持原格式)
  516. const escaped = value.replace(/"/g, '\\"');
  517. return `"${escaped}"`;
  518. }
  519. } catch (e) {
  520. // 不是 JSON,按普通字符串处理
  521. }
  522. // 转义字符串中的引号
  523. const escaped = value.replace(/"/g, '\\"');
  524. return `"${escaped}"`;
  525. }
  526. if (Array.isArray(value)) {
  527. // 数组转换为 JSON 字符串(与 chat-history 和 currentMessage 格式一致)
  528. try {
  529. const jsonStr = JSON.stringify(value);
  530. const escaped = jsonStr.replace(/"/g, '\\"');
  531. return `"${escaped}"`;
  532. } catch (e) {
  533. return `"[]"`;
  534. }
  535. }
  536. if (typeof value === 'number') return value;
  537. if (typeof value === 'boolean') return value;
  538. // 其他类型转为字符串
  539. return `"${String(value)}"`;
  540. });
  541. // 手动解析简单的条件表达式(不使用eval)
  542. // 支持: ==, !=, >, <, >=, <=, &&, ||
  543. const result = parseConditionExpression(expr);
  544. return result;
  545. } catch (error) {
  546. return false;
  547. }
  548. }
  549. /**
  550. * 手动解析条件表达式(避免使用eval)
  551. * @param {string} expr - 表达式字符串
  552. * @returns {boolean} 结果
  553. */
  554. function parseConditionExpression(expr) {
  555. // 去除空格
  556. expr = expr.trim();
  557. // 处理逻辑运算符(从低优先级到高优先级)
  558. // 先处理 ||
  559. if (expr.includes('||')) {
  560. const parts = expr.split('||').map(p => p.trim());
  561. return parts.some(part => parseConditionExpression(part));
  562. }
  563. // 处理 &&
  564. if (expr.includes('&&')) {
  565. const parts = expr.split('&&').map(p => p.trim());
  566. return parts.every(part => parseConditionExpression(part));
  567. }
  568. // 处理比较运算符
  569. const operators = [
  570. { op: '!=', fn: (a, b) => a != b },
  571. { op: '==', fn: (a, b) => {
  572. // 确保类型一致:如果一边是字符串,另一边也转为字符串
  573. if (typeof a === 'string' && typeof b !== 'string') {
  574. b = String(b);
  575. } else if (typeof b === 'string' && typeof a !== 'string') {
  576. a = String(a);
  577. }
  578. // 特殊处理:空字符串比较
  579. // 如果两边都是空字符串,直接返回 true
  580. if (a === '' && b === '') {
  581. return true;
  582. }
  583. // 特殊处理:如果一边是空字符串,另一边是 JSON 数组字符串,判断数组是否为空
  584. if ((a === '' && typeof b === 'string') || (b === '' && typeof a === 'string')) {
  585. const jsonStr = a === '' ? b : a;
  586. try {
  587. const parsed = JSON.parse(jsonStr);
  588. if (Array.isArray(parsed)) {
  589. return parsed.length === 0; // 空数组 == 空字符串
  590. }
  591. } catch (e) {
  592. // 不是 JSON,按普通比较
  593. }
  594. }
  595. return a == b;
  596. }},
  597. { op: '>=', fn: (a, b) => Number(a) >= Number(b) },
  598. { op: '<=', fn: (a, b) => Number(a) <= Number(b) },
  599. { op: '>', fn: (a, b) => Number(a) > Number(b) },
  600. { op: '<', fn: (a, b) => Number(a) < Number(b) }
  601. ];
  602. for (const { op, fn } of operators) {
  603. if (expr.includes(op)) {
  604. const parts = expr.split(op).map(p => p.trim());
  605. if (parts.length === 2) {
  606. const left = parseValue(parts[0]);
  607. const right = parseValue(parts[1]);
  608. // 调试:如果是 relationBg 相关的条件,输出调试信息
  609. if (expr.includes('relationBg')) {
  610. // 只在开发时输出,不影响生产
  611. }
  612. return fn(left, right);
  613. }
  614. }
  615. }
  616. // 如果没有运算符,尝试解析为布尔值
  617. const value = parseValue(expr);
  618. if (typeof value === 'boolean') return value;
  619. if (typeof value === 'string') {
  620. // 空字符串为false
  621. if (value === '' || value === 'undefined') return false;
  622. // 尝试解析 JSON 字符串,如果是空数组 "[]",返回 false
  623. try {
  624. const parsed = JSON.parse(value);
  625. if (Array.isArray(parsed)) {
  626. return parsed.length > 0;
  627. }
  628. // 如果是空对象 "{}",返回 false
  629. if (typeof parsed === 'object' && Object.keys(parsed).length === 0) {
  630. return false;
  631. }
  632. } catch (e) {
  633. // 不是 JSON,按普通字符串处理
  634. }
  635. // 非空字符串为true
  636. return true;
  637. }
  638. // 数字:0为false,非0为true
  639. if (typeof value === 'number') return value !== 0;
  640. return Boolean(value);
  641. }
  642. /**
  643. * 解析值(字符串、数字、布尔值)
  644. * @param {string} str - 字符串
  645. * @returns {any} 解析后的值
  646. */
  647. function parseValue(str) {
  648. str = str.trim();
  649. // 布尔值
  650. if (str === 'true') return true;
  651. if (str === 'false') return false;
  652. // 字符串(带引号)
  653. if ((str.startsWith('"') && str.endsWith('"')) ||
  654. (str.startsWith("'") && str.endsWith("'"))) {
  655. return str.slice(1, -1).replace(/\\"/g, '"').replace(/\\'/g, "'");
  656. }
  657. // 数字
  658. if (/^-?\d+(\.\d+)?$/.test(str)) {
  659. return parseFloat(str);
  660. }
  661. // undefined
  662. if (str === 'undefined') return undefined;
  663. // 默认返回字符串
  664. return str;
  665. }
  666. /**
  667. * 解析工作流格式(支持 variables, execute)
  668. * @param {Object} workflow - 工作流配置对象
  669. * @returns {Object} 解析后的工作流
  670. */
  671. function parseWorkflow(workflow) {
  672. if (!workflow || typeof workflow !== 'object') {
  673. return null;
  674. }
  675. // 初始化变量上下文(仅在未初始化时初始化,避免循环中重置)
  676. if (!variableContextInitialized) {
  677. variableContext = workflow.variables ? {} : {};
  678. if (workflow.variables) {
  679. // 转换变量类型:只允许 number 或 string
  680. for (const key in workflow.variables) {
  681. const value = workflow.variables[key];
  682. if (value === null || value === undefined) {
  683. variableContext[key] = ''; // null/undefined 转换为空字符串
  684. } else if (typeof value === 'boolean') {
  685. variableContext[key] = value ? '1' : '0'; // boolean 转换为字符串 '1' 或 '0'
  686. } else if (typeof value === 'number') {
  687. variableContext[key] = value; // number 保持不变
  688. } else if (typeof value === 'string') {
  689. variableContext[key] = value; // string 保持不变
  690. } else {
  691. variableContext[key] = String(value); // 其他类型转换为字符串
  692. }
  693. }
  694. }
  695. variableContextInitialized = true;
  696. } else {
  697. // 如果已初始化,只更新新增的变量(保留已有变量值)
  698. if (workflow.variables) {
  699. for (const key in workflow.variables) {
  700. // 如果变量已存在且不为空,则保留原值;否则使用新值
  701. if (variableContext[key] === undefined || variableContext[key] === null || variableContext[key] === '') {
  702. const value = workflow.variables[key];
  703. // 转换变量类型:只允许 number 或 string
  704. if (value === null || value === undefined) {
  705. variableContext[key] = ''; // null/undefined 转换为空字符串
  706. } else if (typeof value === 'boolean') {
  707. variableContext[key] = value ? '1' : '0'; // boolean 转换为字符串 '1' 或 '0'
  708. } else if (typeof value === 'number') {
  709. variableContext[key] = value; // number 保持不变
  710. } else if (typeof value === 'string') {
  711. variableContext[key] = value; // string 保持不变
  712. } else {
  713. variableContext[key] = String(value); // 其他类型转换为字符串
  714. }
  715. }
  716. }
  717. }
  718. }
  719. // 解析 execute 字段
  720. let actions = [];
  721. if (workflow.execute && Array.isArray(workflow.execute)) {
  722. actions = parseActions(workflow.execute);
  723. } else {
  724. // 如果没有 execute 字段,返回空数组
  725. actions = [];
  726. }
  727. // 处理 schedule 字段
  728. let schedule = workflow.schedule || {};
  729. // 如果 schedule 是数组,转换为对象格式(取第一个元素)
  730. if (Array.isArray(schedule)) {
  731. schedule = schedule.length > 0 ? schedule[0] : {};
  732. }
  733. // 如果 schedule 是对象但包含嵌套的 schedule 字段,提取内部对象
  734. if (schedule && typeof schedule === 'object' && schedule.schedule) {
  735. schedule = schedule.schedule;
  736. }
  737. // 处理 repeat 字段:将 "forever" 转换为 -1
  738. if (schedule && typeof schedule === 'object') {
  739. if (schedule.repeat === 'forever' || schedule.repeat === 'Forever') {
  740. schedule.repeat = -1;
  741. }
  742. }
  743. return {
  744. schedule: schedule,
  745. variables: variableContext,
  746. actions: actions
  747. };
  748. }
  749. /**
  750. * 解析操作数组(支持新旧格式)
  751. * @param {Array} actions - 操作数组
  752. * @returns {Array} 解析后的操作列表
  753. */
  754. function parseActions(actions) {
  755. if (!Array.isArray(actions)) {
  756. return [];
  757. }
  758. const parsedActions = [];
  759. for (const action of actions) {
  760. if (typeof action !== 'object' || action === null) {
  761. continue;
  762. }
  763. // 新格式:使用 type 字段
  764. if (action.type) {
  765. parsedActions.push(parseNewFormatAction(action));
  766. }
  767. // 旧格式:向后兼容
  768. else {
  769. parsedActions.push(parseOldFormatAction(action));
  770. }
  771. }
  772. return parsedActions;
  773. }
  774. /**
  775. * 解析新格式操作
  776. * @param {Object} action - 操作对象
  777. * @returns {Object} 解析后的操作
  778. */
  779. function parseNewFormatAction(action) {
  780. const parsed = {
  781. type: action.type,
  782. method: action.method,
  783. // target和value保留原始值,在执行时再解析(因为变量可能在执行时才被赋值)
  784. target: action.target,
  785. value: action.value,
  786. variable: action.variable,
  787. condition: action.condition,
  788. delay: action.delay || '',
  789. timeout: action.timeout,
  790. retry: action.retry
  791. };
  792. // 根据类型添加特定字段
  793. switch (action.type) {
  794. case 'adb':
  795. // 统一 ADB 操作,通过 method 区分
  796. parsed.method = action.method;
  797. // 支持新的 inVars/outVars 格式(都可以为空)
  798. if (action.inVars && Array.isArray(action.inVars)) {
  799. parsed.inVars = action.inVars.map(v => extractVarName(v));
  800. } else {
  801. parsed.inVars = [];
  802. }
  803. if (action.outVars && Array.isArray(action.outVars)) {
  804. parsed.outVars = action.outVars.map(v => extractVarName(v));
  805. } else {
  806. parsed.outVars = [];
  807. }
  808. // 向后兼容:保留旧字段
  809. parsed.target = action.target;
  810. parsed.value = action.value;
  811. parsed.variable = action.variable;
  812. parsed.clear = action.clear || false;
  813. break;
  814. case 'locate':
  815. // locate 操作(向后兼容)
  816. break;
  817. case 'click':
  818. // click 操作(向后兼容)
  819. break;
  820. case 'input':
  821. parsed.clear = action.clear || false;
  822. break;
  823. case 'ocr':
  824. parsed.area = action.area;
  825. parsed.avatar = resolveValue(action.avatar);
  826. break;
  827. case 'extract-messages':
  828. case 'ocr-chat':
  829. case 'ocr-chat-history': // 向后兼容
  830. case 'extract-chat-history': // 向后兼容
  831. // 支持新的 inVars/outVars 格式(都可以为空)
  832. if (action.inVars && Array.isArray(action.inVars)) {
  833. parsed.inVars = action.inVars.map(v => extractVarName(v));
  834. if (action.inVars.length >= 2) {
  835. parsed.avatar1 = action.inVars[0];
  836. parsed.avatar2 = action.inVars[1];
  837. } else if (action.inVars.length === 1) {
  838. parsed.avatar1 = action.inVars[0];
  839. parsed.avatar2 = action.avatar2;
  840. }
  841. } else {
  842. parsed.inVars = [];
  843. parsed.avatar1 = action.avatar1;
  844. parsed.avatar2 = action.avatar2;
  845. }
  846. if (action.outVars && Array.isArray(action.outVars)) {
  847. parsed.outVars = action.outVars.map(v => extractVarName(v));
  848. if (action.outVars.length > 0) {
  849. parsed.variable = extractVarName(action.outVars[0]);
  850. }
  851. } else {
  852. parsed.outVars = [];
  853. if (action.variable) {
  854. parsed.variable = extractVarName(action.variable);
  855. }
  856. }
  857. // 向后兼容:支持旧的 friendAvatar 和 myAvatar
  858. if (action.friendAvatar && !parsed.avatar1) parsed.avatar1 = action.friendAvatar;
  859. if (action.myAvatar && !parsed.avatar2) parsed.avatar2 = action.myAvatar;
  860. break;
  861. case 'save-messages':
  862. // 保存消息记录到文件
  863. break;
  864. case 'generate-summary':
  865. parsed.summaryVariable = action.summaryVariable;
  866. break;
  867. case 'ai-generate':
  868. parsed.prompt = resolveValue(action.prompt);
  869. parsed.model = action.model;
  870. // 支持新的 inVars/outVars 格式(都可以为空)
  871. if (action.inVars && Array.isArray(action.inVars)) {
  872. parsed.inVars = action.inVars.map(v => extractVarName(v));
  873. } else {
  874. parsed.inVars = [];
  875. }
  876. if (action.outVars && Array.isArray(action.outVars)) {
  877. parsed.outVars = action.outVars.map(v => extractVarName(v));
  878. if (action.outVars.length > 0) {
  879. parsed.variable = extractVarName(action.outVars[0]);
  880. }
  881. } else {
  882. parsed.outVars = [];
  883. if (action.variable) {
  884. parsed.variable = extractVarName(action.variable);
  885. }
  886. }
  887. break;
  888. case 'schedule':
  889. // schedule 操作:condition 定义调度条件,interval 定义要执行的动作
  890. parsed.condition = action.condition || {};
  891. // 处理 repeat 字段:将 "forever" 转换为 -1
  892. if (parsed.condition && typeof parsed.condition === 'object') {
  893. if (parsed.condition.repeat === 'forever' || parsed.condition.repeat === 'Forever') {
  894. parsed.condition.repeat = -1;
  895. }
  896. }
  897. // interval 字段包含要执行的动作数组
  898. if (action.interval && Array.isArray(action.interval)) {
  899. parsed.interval = parseActions(action.interval);
  900. } else {
  901. parsed.interval = [];
  902. }
  903. break;
  904. case 'if':
  905. // 支持 ture 作为 then 的别名(可能是拼写错误,但为了兼容性支持)
  906. parsed.then = action.then || action.ture ? parseActions(action.then || action.ture) : [];
  907. parsed.else = action.else ? parseActions(action.else) : [];
  908. break;
  909. case 'for':
  910. parsed.variable = action.variable;
  911. parsed.items = resolveValue(action.items);
  912. parsed.body = action.body ? parseActions(action.body) : [];
  913. break;
  914. case 'while':
  915. // 支持 ture 作为 body 的别名(可能是拼写错误,但为了兼容性支持)
  916. parsed.body = action.body || action.ture ? parseActions(action.body || action.ture) : [];
  917. break;
  918. case 'delay':
  919. parsed.value = action.value || action.delay || '0s';
  920. break;
  921. case 'set':
  922. parsed.variable = action.variable;
  923. parsed.value = resolveValue(action.value);
  924. break;
  925. case 'random':
  926. // 支持新格式:inVars[min, max] 和 outVars[{variable}]
  927. if (action.inVars && Array.isArray(action.inVars) && action.inVars.length >= 2) {
  928. parsed.min = action.inVars[0];
  929. parsed.max = action.inVars[1];
  930. } else {
  931. // 向后兼容旧格式
  932. parsed.min = action.min;
  933. parsed.max = action.max;
  934. }
  935. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  936. parsed.variable = action.outVars[0];
  937. } else {
  938. // 向后兼容旧格式
  939. parsed.variable = action.variable;
  940. }
  941. // integer 默认为 true(随机数总是整数)
  942. parsed.integer = action.integer !== undefined ? action.integer : true;
  943. break;
  944. case 'log':
  945. // log 操作:支持 inVars 或 value 字段
  946. if (action.inVars && Array.isArray(action.inVars)) {
  947. parsed.inVars = action.inVars.map(v => extractVarName(v));
  948. } else {
  949. parsed.inVars = [];
  950. }
  951. // 支持 value 字段作为直接输出内容
  952. if (action.value) {
  953. parsed.value = action.value;
  954. }
  955. break;
  956. case 'read-last-message':
  957. // 支持新的 inVars/outVars 格式,也支持 inputVars/outputVars(大小写不同,都可以为空)
  958. const inputVars = action.inVars || action.inputVars || [];
  959. const outputVars = action.outVars || action.outputVars || [];
  960. parsed.inVars = inputVars.map(v => extractVarName(v));
  961. parsed.outVars = outputVars.map(v => extractVarName(v));
  962. if (inputVars.length > 0) {
  963. parsed.inputVar = extractVarName(inputVars[0]);
  964. }
  965. if (outputVars.length > 0) {
  966. parsed.textVariable = extractVarName(outputVars[0]);
  967. }
  968. if (outputVars.length > 1) {
  969. parsed.senderVariable = extractVarName(outputVars[1]);
  970. }
  971. // 向后兼容:支持旧的 textVariable 和 senderVariable
  972. if (!parsed.textVariable) parsed.textVariable = action.textVariable;
  973. if (!parsed.senderVariable) parsed.senderVariable = action.senderVariable;
  974. break;
  975. case 'read-txt':
  976. case 'read-text': // 向后兼容别名
  977. // 支持新的 inVars/outVars 格式
  978. if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 0) {
  979. parsed.inVars = action.inVars.map(v => extractVarName(v));
  980. parsed.filePath = action.inVars[0];
  981. } else {
  982. parsed.inVars = [];
  983. parsed.filePath = action.filePath;
  984. }
  985. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  986. parsed.variable = extractVarName(action.outVars[0]);
  987. } else if (action.variable) {
  988. parsed.variable = extractVarName(action.variable);
  989. }
  990. break;
  991. case 'save-txt':
  992. case 'save-text': // 向后兼容别名
  993. // 支持新的 inVars/outVars 格式
  994. // 入参顺序:第一个参数是内容,第二个参数是文件路径
  995. if (action.inVars && Array.isArray(action.inVars)) {
  996. parsed.inVars = action.inVars.map(v => extractVarName(v));
  997. if (action.inVars.length > 0) {
  998. parsed.content = action.inVars[0]; // 第一个参数是内容
  999. }
  1000. if (action.inVars.length > 1) {
  1001. parsed.filePath = action.inVars[1]; // 第二个参数是文件路径
  1002. }
  1003. } else {
  1004. parsed.inVars = [];
  1005. parsed.filePath = action.filePath;
  1006. parsed.content = action.content;
  1007. }
  1008. // save-txt 通常不需要 outVars,但为了兼容性支持
  1009. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  1010. parsed.variable = extractVarName(action.outVars[0]);
  1011. }
  1012. break;
  1013. case 'img-bounding-box-location':
  1014. // 支持新的 inVars/outVars 格式(都可以为空)
  1015. if (action.inVars && Array.isArray(action.inVars)) {
  1016. parsed.inVars = action.inVars.map(v => extractVarName(v));
  1017. // 如果 inVars 有值,从变量中读取 screenshot 和 region
  1018. if (action.inVars.length > 0) parsed.screenshot = action.inVars[0];
  1019. if (action.inVars.length > 1) parsed.region = action.inVars[1];
  1020. } else {
  1021. parsed.inVars = [];
  1022. parsed.screenshot = action.screenshot;
  1023. parsed.region = action.region;
  1024. }
  1025. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  1026. parsed.variable = extractVarName(action.outVars[0]);
  1027. } else if (action.variable) {
  1028. parsed.variable = extractVarName(action.variable);
  1029. }
  1030. break;
  1031. case 'img-center-point-location':
  1032. // 支持新的 inVars/outVars 格式(都可以为空)
  1033. if (action.inVars && Array.isArray(action.inVars)) {
  1034. parsed.inVars = action.inVars.map(v => extractVarName(v));
  1035. // 如果 inVars 有值,从变量中读取 template
  1036. if (action.inVars.length > 0) parsed.template = action.inVars[0];
  1037. } else {
  1038. parsed.inVars = [];
  1039. parsed.template = action.template;
  1040. }
  1041. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  1042. parsed.variable = extractVarName(action.outVars[0]);
  1043. } else if (action.variable) {
  1044. parsed.variable = extractVarName(action.variable);
  1045. }
  1046. break;
  1047. case 'img-cropping':
  1048. // 支持新的 inVars/outVars 格式
  1049. if (action.inVars && Array.isArray(action.inVars)) {
  1050. parsed.inVars = action.inVars.map(v => extractVarName(v));
  1051. // 如果 inVars 有值,从变量中读取 area 和 savePath
  1052. if (action.inVars.length > 0) parsed.area = action.inVars[0];
  1053. if (action.inVars.length > 1) parsed.savePath = action.inVars[1];
  1054. } else {
  1055. parsed.inVars = [];
  1056. parsed.area = action.area;
  1057. parsed.savePath = action.savePath;
  1058. }
  1059. // img-cropping 通常不需要 outVars,但为了兼容性支持
  1060. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  1061. parsed.variable = extractVarName(action.outVars[0]);
  1062. }
  1063. break;
  1064. case 'scroll':
  1065. case 'swipe':
  1066. case 'press':
  1067. case 'string-press':
  1068. case 'keyevent':
  1069. // 保持原有逻辑(向后兼容)
  1070. break;
  1071. }
  1072. return parsed;
  1073. }
  1074. /**
  1075. * 解析旧格式操作(向后兼容)
  1076. * @param {Object} action - 操作对象
  1077. * @returns {Object} 解析后的操作
  1078. */
  1079. function parseOldFormatAction(action) {
  1080. const times = action.times && action.times > 0 ? parseInt(action.times, 10) : 1;
  1081. const data = action.data || '';
  1082. const delay = action.delay || '';
  1083. // 检查 press 操作
  1084. if (action.press) {
  1085. return {
  1086. type: 'press',
  1087. value: action.press,
  1088. times: times,
  1089. data: data,
  1090. delay: delay,
  1091. };
  1092. }
  1093. // 检查 input 操作
  1094. else if (action.input !== undefined) {
  1095. return {
  1096. type: 'input',
  1097. value: action.input,
  1098. times: times,
  1099. data: data,
  1100. delay: delay,
  1101. };
  1102. }
  1103. // 检查 swipe 操作
  1104. else if (action.swipe) {
  1105. const swipeValue = action.swipe;
  1106. const validSwipeDirections = ['up-down', 'down-up', 'left-right', 'right-left'];
  1107. if (!validSwipeDirections.includes(swipeValue)) {
  1108. return null;
  1109. }
  1110. return {
  1111. type: 'swipe',
  1112. value: swipeValue,
  1113. times: times,
  1114. data: data,
  1115. delay: delay,
  1116. };
  1117. }
  1118. // 检查 string-press 操作
  1119. else if (action['string-press']) {
  1120. return {
  1121. type: 'string-press',
  1122. value: action['string-press'],
  1123. times: times,
  1124. data: data,
  1125. delay: delay,
  1126. };
  1127. }
  1128. // 检查 scroll 操作
  1129. else if (action.scroll) {
  1130. const scrollValue = action.scroll;
  1131. const validScrollDirections = ['up-down', 'down-up', 'left-right', 'right-left'];
  1132. if (!validScrollDirections.includes(scrollValue)) {
  1133. return null;
  1134. }
  1135. return {
  1136. type: 'scroll',
  1137. value: scrollValue,
  1138. times: times,
  1139. data: data,
  1140. delay: delay,
  1141. };
  1142. }
  1143. else {
  1144. return null;
  1145. }
  1146. }
  1147. /**
  1148. * 获取操作名称(用于显示)
  1149. * @param {Object} action - 操作对象
  1150. * @returns {string} 操作名称
  1151. */
  1152. function getActionName(action) {
  1153. const typeNames = {
  1154. 'schedule': '定时执行',
  1155. 'adb': 'ADB操作',
  1156. 'press': '点击图片',
  1157. 'input': '输入文本',
  1158. 'swipe': '滑动',
  1159. 'string-press': '点击文字',
  1160. 'scroll': '滚动',
  1161. 'locate': '定位',
  1162. 'click': '点击',
  1163. 'ocr': '文字识别',
  1164. 'extract-messages': '提取消息记录',
  1165. 'save-messages': '保存消息记录',
  1166. 'generate-summary': '生成总结',
  1167. 'ocr-chat': 'OCR识别对话',
  1168. // 向后兼容
  1169. 'ocr-chat-history': 'OCR提取消息记录',
  1170. 'extract-chat-history': '提取消息记录', // 向后兼容
  1171. 'generate-history-summary': '生成总结',
  1172. 'img-bounding-box-location': '图像区域定位',
  1173. 'img-center-point-location': '图像中心点定位',
  1174. 'img-cropping': '裁剪图片区域',
  1175. 'read-last-message': '读取最后一条消息',
  1176. 'read-txt': '读取文本文件',
  1177. 'read-text': '读取文本文件', // 向后兼容别名
  1178. 'save-txt': '保存文本文件',
  1179. 'save-text': '保存文本文件', // 向后兼容别名
  1180. 'smart-chat-append': '智能合并聊天记录',
  1181. 'ai-generate': 'AI生成',
  1182. 'if': '条件判断',
  1183. 'for': '循环',
  1184. 'while': '循环',
  1185. 'delay': '延迟',
  1186. 'set': '设置变量',
  1187. 'random': '生成随机数',
  1188. 'echo': '打印信息',
  1189. 'log': '打印信息' // 向后兼容
  1190. };
  1191. const typeName = typeNames[action.type] || action.type;
  1192. const value = action.value || action.target || '';
  1193. const displayValue = typeof value === 'string' ? value : JSON.stringify(value);
  1194. if (action.type === 'schedule') {
  1195. const condition = action.condition || {};
  1196. const interval = condition.interval || '0s';
  1197. const repeat = condition.repeat !== undefined ? condition.repeat : 1;
  1198. const repeatText = repeat === -1 ? '无限循环' : `重复${repeat}次`;
  1199. return `${typeName}: ${interval}, ${repeatText}`;
  1200. } else if (action.type === 'input') {
  1201. return `${typeName}: ${displayValue.length > 20 ? displayValue.substring(0, 20) + '...' : displayValue}`;
  1202. } else if (action.type === 'string-press' || action.type === 'click') {
  1203. return `${typeName}: ${displayValue.length > 20 ? displayValue.substring(0, 20) + '...' : displayValue}`;
  1204. } else if (action.type === 'if') {
  1205. return `${typeName}: ${action.condition || ''}`;
  1206. } else if (action.type === 'for') {
  1207. return `${typeName}: ${action.variable || ''}`;
  1208. } else if (action.type === 'set') {
  1209. return `${typeName}: ${action.variable || ''}`;
  1210. } else {
  1211. return `${typeName}: ${displayValue}`;
  1212. }
  1213. }
  1214. /**
  1215. * 计算滑动操作的坐标
  1216. * @param {string} direction - 滑动方向: up-down, down-up, left-right, right-left
  1217. * @param {number} width - 设备宽度
  1218. * @param {number} height - 设备高度
  1219. * @returns {Object} 包含起始和结束坐标的对象 {x1, y1, x2, y2}
  1220. */
  1221. function calculateSwipeCoordinates(direction, width, height) {
  1222. // 滑动距离为屏幕的 70%,起始和结束位置各留 15% 的边距
  1223. const margin = 0.15;
  1224. const swipeDistance = 0.7;
  1225. let x1, y1, x2, y2;
  1226. switch (direction) {
  1227. case 'up-down':
  1228. // 从上往下滑动
  1229. x1 = x2 = Math.round(width / 2);
  1230. y1 = Math.round(height * margin);
  1231. y2 = Math.round(height * (margin + swipeDistance));
  1232. break;
  1233. case 'down-up':
  1234. // 从下往上滑动
  1235. x1 = x2 = Math.round(width / 2);
  1236. y1 = Math.round(height * (margin + swipeDistance));
  1237. y2 = Math.round(height * margin);
  1238. break;
  1239. case 'left-right':
  1240. // 从左往右滑动
  1241. y1 = y2 = Math.round(height / 2);
  1242. x1 = Math.round(width * margin);
  1243. x2 = Math.round(width * (margin + swipeDistance));
  1244. break;
  1245. case 'right-left':
  1246. // 从右往左滑动
  1247. y1 = y2 = Math.round(height / 2);
  1248. x1 = Math.round(width * (margin + swipeDistance));
  1249. x2 = Math.round(width * margin);
  1250. break;
  1251. default:
  1252. throw new Error(`未知的滑动方向: ${direction}`);
  1253. }
  1254. return { x1, y1, x2, y2 };
  1255. }
  1256. /**
  1257. * 执行单个操作
  1258. * @param {Object} action - 操作对象
  1259. * @param {string} device - 设备 ID
  1260. * @param {string} folderPath - 文件夹路径(用于 press 操作查找图片)
  1261. * @param {Object} resolution - 设备分辨率 {width, height}
  1262. * @returns {Promise<Object>} 执行结果 {success, error?, result?}
  1263. */
  1264. async function executeAction(action, device, folderPath, resolution) {
  1265. try {
  1266. // 检查条件
  1267. if (action.condition && !evaluateCondition(action.condition)) {
  1268. return { success: true, skipped: true };
  1269. }
  1270. switch (action.type) {
  1271. case 'adb': {
  1272. // 统一 ADB 操作
  1273. const method = action.method;
  1274. if (!method) {
  1275. return { success: false, error: 'adb 操作缺少 method 参数' };
  1276. }
  1277. // 从 inVars 读取参数
  1278. const inVars = action.inVars || [];
  1279. const outVars = action.outVars || [];
  1280. switch (method) {
  1281. case 'input': {
  1282. // 输入文本:inVars[0] 是输入文本
  1283. let inputValue = null;
  1284. if (inVars.length > 0) {
  1285. const inputVar = extractVarName(inVars[0]);
  1286. inputValue = variableContext[inputVar];
  1287. } else if (action.value) {
  1288. inputValue = resolveValue(action.value);
  1289. }
  1290. if (!inputValue) {
  1291. return { success: false, error: 'input 操作缺少输入内容' };
  1292. }
  1293. // 如果设置了clear,先清空输入框
  1294. if (action.clear) {
  1295. for (let i = 0; i < 200; i++) {
  1296. const clearResult = await electronAPI.sendKeyEvent(device, '67');
  1297. if (!clearResult.success) break;
  1298. await new Promise(resolve => setTimeout(resolve, 10));
  1299. }
  1300. await new Promise(resolve => setTimeout(resolve, 200));
  1301. }
  1302. if (!electronAPI || !electronAPI.sendText) {
  1303. return { success: false, error: '输入 API 不可用' };
  1304. }
  1305. const textResult = await electronAPI.sendText(device, String(inputValue));
  1306. if (!textResult.success) {
  1307. return { success: false, error: `输入失败: ${textResult.error}` };
  1308. }
  1309. return { success: true };
  1310. }
  1311. case 'click': {
  1312. // 点击操作:inVars[0] 是位置(坐标对象或变量名)
  1313. let position = null;
  1314. if (inVars.length > 0) {
  1315. const posVar = extractVarName(inVars[0]);
  1316. position = variableContext[posVar];
  1317. } else if (action.target) {
  1318. position = resolveValue(action.target);
  1319. }
  1320. if (!position) {
  1321. return { success: false, error: 'click 操作缺少位置参数' };
  1322. }
  1323. // 如果 position 是字符串,尝试解析为坐标对象
  1324. if (typeof position === 'string') {
  1325. if (position === '') {
  1326. return { success: false, error: 'click 操作缺少位置参数(位置变量为空)' };
  1327. }
  1328. try {
  1329. // 尝试解析 JSON 字符串(例如:{"x":123,"y":456})
  1330. position = JSON.parse(position);
  1331. } catch (e) {
  1332. // 如果不是 JSON,可能是 "x,y" 格式,尝试解析
  1333. const parts = position.split(',');
  1334. if (parts.length === 2) {
  1335. const x = parseFloat(parts[0].trim());
  1336. const y = parseFloat(parts[1].trim());
  1337. if (!isNaN(x) && !isNaN(y)) {
  1338. position = { x: Math.round(x), y: Math.round(y) };
  1339. } else {
  1340. return { success: false, error: `click 操作的位置格式错误,无法解析字符串: ${position}` };
  1341. }
  1342. } else {
  1343. return { success: false, error: `click 操作的位置格式错误,无法解析字符串: ${position}` };
  1344. }
  1345. }
  1346. }
  1347. // 如果 position 是数组 [x, y],转换为对象
  1348. if (Array.isArray(position) && position.length >= 2) {
  1349. position = { x: position[0], y: position[1] };
  1350. }
  1351. // 如果 position 是 corners 对象(四个顶点),计算中心点
  1352. if (position && typeof position === 'object' && position.topLeft && position.bottomRight) {
  1353. const centerX = Math.round((position.topLeft.x + position.bottomRight.x) / 2);
  1354. const centerY = Math.round((position.topLeft.y + position.bottomRight.y) / 2);
  1355. position = { x: centerX, y: centerY };
  1356. }
  1357. if (!position || typeof position !== 'object' || position.x === undefined || position.y === undefined) {
  1358. return { success: false, error: 'click 操作的位置格式错误,需要 {x, y} 对象' };
  1359. }
  1360. if (!electronAPI || !electronAPI.sendTap) {
  1361. return { success: false, error: '点击 API 不可用' };
  1362. }
  1363. const tapResult = await electronAPI.sendTap(device, position.x, position.y);
  1364. if (!tapResult.success) {
  1365. return { success: false, error: `点击失败: ${tapResult.error}` };
  1366. }
  1367. return { success: true };
  1368. }
  1369. case 'locate': {
  1370. // 定位操作:inVars[0] 是目标(图片路径或文字),outVars[0] 保存位置
  1371. // 支持通过 action.method 或 action.targetMethod 指定定位方法
  1372. const locateMethod = action.method || action.targetMethod || 'image'; // image, text, coordinate
  1373. let position = null;
  1374. if (locateMethod === 'image') {
  1375. let imagePath = null;
  1376. if (inVars.length > 0) {
  1377. const imageVar = extractVarName(inVars[0]);
  1378. imagePath = variableContext[imageVar] || imageVar;
  1379. } else if (action.target) {
  1380. imagePath = action.target;
  1381. }
  1382. if (!imagePath) {
  1383. return { success: false, error: 'locate 操作(image)缺少图片路径' };
  1384. }
  1385. // resources 作为根目录
  1386. const fullPath = imagePath.startsWith('/') || imagePath.includes(':')
  1387. ? imagePath
  1388. : `${folderPath}/resources/${imagePath}`;
  1389. if (!electronAPI || !electronAPI.matchImageAndGetCoordinate) {
  1390. return { success: false, error: '图像匹配 API 不可用' };
  1391. }
  1392. const matchResult = await electronAPI.matchImageAndGetCoordinate(device, fullPath);
  1393. if (!matchResult.success) {
  1394. return { success: false, error: `图像匹配失败: ${matchResult.error}` };
  1395. }
  1396. position = matchResult.clickPosition;
  1397. } else if (locateMethod === 'text') {
  1398. let targetText = null;
  1399. if (inVars.length > 0) {
  1400. const textVar = extractVarName(inVars[0]);
  1401. targetText = variableContext[textVar] || textVar;
  1402. } else if (action.target) {
  1403. targetText = action.target;
  1404. }
  1405. if (!targetText) {
  1406. return { success: false, error: 'locate 操作(text)缺少文字内容' };
  1407. }
  1408. if (!electronAPI || !electronAPI.findTextAndGetCoordinate) {
  1409. return { success: false, error: '文字识别 API 不可用' };
  1410. }
  1411. const matchResult = await electronAPI.findTextAndGetCoordinate(device, targetText);
  1412. if (!matchResult.success) {
  1413. return { success: false, error: `文字识别失败: ${matchResult.error}` };
  1414. }
  1415. position = matchResult.clickPosition;
  1416. } else if (locateMethod === 'coordinate') {
  1417. let coord = null;
  1418. if (inVars.length > 0) {
  1419. const coordVar = extractVarName(inVars[0]);
  1420. coord = variableContext[coordVar];
  1421. } else if (action.target) {
  1422. coord = resolveValue(action.target);
  1423. }
  1424. if (!coord) {
  1425. return { success: false, error: 'locate 操作(coordinate)缺少坐标' };
  1426. }
  1427. position = Array.isArray(coord) ? { x: coord[0], y: coord[1] } : coord;
  1428. }
  1429. // 保存到变量
  1430. if (outVars.length > 0) {
  1431. const outputVar = extractVarName(outVars[0]);
  1432. variableContext[outputVar] = position;
  1433. await logOutVars(action, variableContext, folderPath);
  1434. } else if (action.variable) {
  1435. variableContext[action.variable] = position;
  1436. }
  1437. return { success: true, result: position };
  1438. }
  1439. case 'swipe': {
  1440. // 滑动操作:inVars[0] 是方向,inVars[1] 和 inVars[2] 可选(起始和结束位置)
  1441. let direction = null;
  1442. if (inVars.length > 0) {
  1443. const dirVar = extractVarName(inVars[0]);
  1444. direction = variableContext[dirVar] || dirVar;
  1445. } else if (action.value) {
  1446. direction = resolveValue(action.value);
  1447. }
  1448. if (!direction) {
  1449. return { success: false, error: 'swipe 操作缺少方向参数' };
  1450. }
  1451. let x1, y1, x2, y2;
  1452. if (inVars.length >= 3) {
  1453. // 从 inVars 读取起始和结束位置
  1454. const startVar = extractVarName(inVars[1]);
  1455. const endVar = extractVarName(inVars[2]);
  1456. const start = variableContext[startVar];
  1457. const end = variableContext[endVar];
  1458. if (start && end) {
  1459. x1 = start.x || start[0];
  1460. y1 = start.y || start[1];
  1461. x2 = end.x || end[0];
  1462. y2 = end.y || end[1];
  1463. }
  1464. }
  1465. // 如果没有提供具体坐标,使用方向计算坐标
  1466. if (x1 === undefined || y1 === undefined || x2 === undefined || y2 === undefined) {
  1467. const coords = calculateSwipeCoordinates(direction, resolution.width, resolution.height);
  1468. x1 = coords.x1;
  1469. y1 = coords.y1;
  1470. x2 = coords.x2;
  1471. y2 = coords.y2;
  1472. }
  1473. if (!electronAPI || !electronAPI.sendSwipe) {
  1474. return { success: false, error: '滑动 API 不可用' };
  1475. }
  1476. const swipeResult = await electronAPI.sendSwipe(device, x1, y1, x2, y2, 300);
  1477. if (!swipeResult.success) {
  1478. return { success: false, error: `滑动失败: ${swipeResult.error}` };
  1479. }
  1480. return { success: true };
  1481. }
  1482. case 'scroll': {
  1483. // 滚动操作:inVars[0] 是方向
  1484. let direction = null;
  1485. if (inVars.length > 0) {
  1486. const dirVar = extractVarName(inVars[0]);
  1487. direction = variableContext[dirVar] || dirVar;
  1488. } else if (action.value) {
  1489. direction = resolveValue(action.value);
  1490. }
  1491. if (!direction) {
  1492. return { success: false, error: 'scroll 操作缺少方向参数' };
  1493. }
  1494. if (!electronAPI || !electronAPI.sendScroll) {
  1495. return { success: false, error: '滚动 API 不可用' };
  1496. }
  1497. const scrollResult = await electronAPI.sendScroll(
  1498. device,
  1499. direction,
  1500. resolution.width,
  1501. resolution.height,
  1502. DEFAULT_SCROLL_DISTANCE,
  1503. 500
  1504. );
  1505. if (!scrollResult.success) {
  1506. return { success: false, error: `滚动失败: ${scrollResult.error}` };
  1507. }
  1508. return { success: true };
  1509. }
  1510. case 'keyevent': {
  1511. // 按键操作:inVars[0] 是按键代码(如 "4" 表示返回键,"KEYCODE_BACK" 也可以)
  1512. let keyCode = null;
  1513. if (inVars.length > 0) {
  1514. const keyVar = extractVarName(inVars[0]);
  1515. keyCode = variableContext[keyVar] || keyVar;
  1516. } else if (action.value) {
  1517. keyCode = resolveValue(action.value);
  1518. }
  1519. if (!keyCode) {
  1520. return { success: false, error: 'keyevent 操作缺少按键代码参数' };
  1521. }
  1522. // 如果是字符串 "KEYCODE_BACK",转换为 "4"
  1523. if (keyCode === 'KEYCODE_BACK') {
  1524. keyCode = '4';
  1525. }
  1526. if (!electronAPI || !electronAPI.sendSystemKey) {
  1527. return { success: false, error: '系统按键 API 不可用' };
  1528. }
  1529. const keyResult = await electronAPI.sendSystemKey(device, String(keyCode));
  1530. if (!keyResult.success) {
  1531. return { success: false, error: `按键失败: ${keyResult.error}` };
  1532. }
  1533. return { success: true };
  1534. }
  1535. case 'press': {
  1536. // 图像匹配并点击:inVars[0] 是图片路径
  1537. let imagePath = null;
  1538. if (inVars.length > 0) {
  1539. const imageVar = extractVarName(inVars[0]);
  1540. imagePath = variableContext[imageVar] || imageVar;
  1541. } else if (action.value) {
  1542. imagePath = action.value;
  1543. }
  1544. if (!imagePath) {
  1545. return { success: false, error: 'press 操作缺少图片路径' };
  1546. }
  1547. const fullPath = imagePath.startsWith('/') || imagePath.includes(':')
  1548. ? imagePath
  1549. : `${folderPath}/${imagePath}`;
  1550. if (!electronAPI || !electronAPI.matchImageAndGetCoordinate) {
  1551. return { success: false, error: '图像匹配 API 不可用' };
  1552. }
  1553. const matchResult = await electronAPI.matchImageAndGetCoordinate(device, fullPath);
  1554. if (!matchResult.success) {
  1555. return { success: false, error: `图像匹配失败: ${matchResult.error}` };
  1556. }
  1557. const { clickPosition } = matchResult;
  1558. const { x, y } = clickPosition;
  1559. if (!electronAPI || !electronAPI.sendTap) {
  1560. return { success: false, error: '点击 API 不可用' };
  1561. }
  1562. const tapResult = await electronAPI.sendTap(device, x, y);
  1563. if (!tapResult.success) {
  1564. return { success: false, error: `点击失败: ${tapResult.error}` };
  1565. }
  1566. return { success: true };
  1567. }
  1568. case 'string-press': {
  1569. // 文字识别并点击:inVars[0] 是文字
  1570. let targetText = null;
  1571. if (inVars.length > 0) {
  1572. const textVar = extractVarName(inVars[0]);
  1573. targetText = variableContext[textVar] || textVar;
  1574. } else if (action.value) {
  1575. targetText = action.value;
  1576. }
  1577. if (!targetText) {
  1578. return { success: false, error: 'string-press 操作缺少文字内容' };
  1579. }
  1580. if (!electronAPI || !electronAPI.findTextAndGetCoordinate) {
  1581. return { success: false, error: '文字识别 API 不可用' };
  1582. }
  1583. const matchResult = await electronAPI.findTextAndGetCoordinate(device, targetText);
  1584. if (!matchResult.success) {
  1585. return { success: false, error: `文字识别失败: ${matchResult.error}` };
  1586. }
  1587. const { clickPosition } = matchResult;
  1588. const { x, y } = clickPosition;
  1589. if (!electronAPI || !electronAPI.sendTap) {
  1590. return { success: false, error: '点击 API 不可用' };
  1591. }
  1592. const tapResult = await electronAPI.sendTap(device, x, y);
  1593. if (!tapResult.success) {
  1594. return { success: false, error: `点击失败: ${tapResult.error}` };
  1595. }
  1596. return { success: true };
  1597. }
  1598. default:
  1599. return { success: false, error: `未知的 adb method: ${method}` };
  1600. }
  1601. }
  1602. case 'locate': {
  1603. // 定位操作
  1604. const method = action.method || 'image';
  1605. let position = null;
  1606. if (method === 'image') {
  1607. const imagePath = action.target.startsWith('/') || action.target.includes(':')
  1608. ? action.target
  1609. : `${folderPath}/${action.target}`;
  1610. if (!electronAPI || !electronAPI.matchImageAndGetCoordinate) {
  1611. return { success: false, error: '图像匹配 API 不可用' };
  1612. }
  1613. const matchResult = await electronAPI.matchImageAndGetCoordinate(device, imagePath);
  1614. if (!matchResult.success) {
  1615. return { success: false, error: `图像匹配失败: ${matchResult.error}` };
  1616. }
  1617. position = matchResult.clickPosition;
  1618. } else if (method === 'text') {
  1619. if (!electronAPI || !electronAPI.findTextAndGetCoordinate) {
  1620. return { success: false, error: '文字识别 API 不可用' };
  1621. }
  1622. const matchResult = await electronAPI.findTextAndGetCoordinate(device, action.target);
  1623. if (!matchResult.success) {
  1624. return { success: false, error: `文字识别失败: ${matchResult.error}` };
  1625. }
  1626. position = matchResult.clickPosition;
  1627. } else if (method === 'coordinate') {
  1628. position = Array.isArray(action.target)
  1629. ? { x: action.target[0], y: action.target[1] }
  1630. : action.target;
  1631. }
  1632. // 保存到变量
  1633. if (action.variable && position) {
  1634. variableContext[action.variable] = position;
  1635. }
  1636. return { success: true, result: position };
  1637. }
  1638. case 'click': {
  1639. // 点击操作
  1640. const method = action.method || 'position';
  1641. let position = null;
  1642. if (method === 'position') {
  1643. position = resolveValue(action.target);
  1644. } else if (method === 'image') {
  1645. const imagePath = action.target.startsWith('/') || action.target.includes(':')
  1646. ? action.target
  1647. : `${folderPath}/${action.target}`;
  1648. if (!electronAPI || !electronAPI.matchImageAndGetCoordinate) {
  1649. return { success: false, error: '图像匹配 API 不可用' };
  1650. }
  1651. const matchResult = await electronAPI.matchImageAndGetCoordinate(device, imagePath);
  1652. if (!matchResult.success) {
  1653. return { success: false, error: `图像匹配失败: ${matchResult.error}` };
  1654. }
  1655. position = matchResult.clickPosition;
  1656. } else if (method === 'text') {
  1657. if (!electronAPI || !electronAPI.findTextAndGetCoordinate) {
  1658. return { success: false, error: '文字识别 API 不可用' };
  1659. }
  1660. const matchResult = await electronAPI.findTextAndGetCoordinate(device, action.target);
  1661. if (!matchResult.success) {
  1662. return { success: false, error: `文字识别失败: ${matchResult.error}` };
  1663. }
  1664. position = matchResult.clickPosition;
  1665. }
  1666. if (!position || !position.x || !position.y) {
  1667. return { success: false, error: '无法获取点击位置' };
  1668. }
  1669. if (!electronAPI || !electronAPI.sendTap) {
  1670. return { success: false, error: '点击 API 不可用' };
  1671. }
  1672. const tapResult = await electronAPI.sendTap(device, position.x, position.y);
  1673. if (!tapResult.success) {
  1674. return { success: false, error: `点击失败: ${tapResult.error}` };
  1675. }
  1676. return { success: true };
  1677. }
  1678. case 'press': {
  1679. // 向后兼容:图像匹配并点击
  1680. // resources 作为根目录
  1681. const imagePath = `${folderPath}/resources/${action.value}`;
  1682. if (!electronAPI || !electronAPI.matchImageAndGetCoordinate) {
  1683. return { success: false, error: '图像匹配 API 不可用' };
  1684. }
  1685. const matchResult = await electronAPI.matchImageAndGetCoordinate(device, imagePath);
  1686. if (!matchResult.success) {
  1687. return { success: false, error: `图像匹配失败: ${matchResult.error}` };
  1688. }
  1689. const { clickPosition } = matchResult;
  1690. const { x, y } = clickPosition;
  1691. if (!electronAPI || !electronAPI.sendTap) {
  1692. return { success: false, error: '点击 API 不可用' };
  1693. }
  1694. const tapResult = await electronAPI.sendTap(device, x, y);
  1695. if (!tapResult.success) {
  1696. return { success: false, error: `点击失败: ${tapResult.error}` };
  1697. }
  1698. return { success: true };
  1699. }
  1700. case 'input': {
  1701. // 输入文本
  1702. const inputStartTime = Date.now();
  1703. // 先解析value(可能在运行时变量才被赋值,需要重新解析)
  1704. let inputValue = resolveValue(action.value);
  1705. // 如果value为空或undefined,且target存在,使用target(用于向后兼容,target可能也是定位文字)
  1706. if (!inputValue && action.target) {
  1707. // 如果target看起来像定位文字(不是变量引用),就不使用它
  1708. const resolvedTarget = resolveValue(action.target);
  1709. // 只有当target是变量引用时才使用它作为输入值
  1710. if (resolvedTarget !== action.target || !action.target.includes(' ')) {
  1711. inputValue = resolvedTarget;
  1712. }
  1713. }
  1714. // 如果还是没有值,报错
  1715. if (!inputValue) {
  1716. return { success: false, error: '输入内容为空' };
  1717. }
  1718. // 如果target是定位方式,先定位输入框(暂未实现,直接输入文本)
  1719. if (action.method === 'locate' && action.target) {
  1720. // 这里可以添加定位输入框的逻辑
  1721. // 暂时直接使用 sendText
  1722. }
  1723. if (!electronAPI || !electronAPI.sendText) {
  1724. return { success: false, error: '输入 API 不可用' };
  1725. }
  1726. // 如果设置了clear,先清空输入框(通过发送退格键)
  1727. if (action.clear) {
  1728. // 发送退格键清空输入框(假设最多200个字符)
  1729. // 使用Android的KEYCODE_DEL,值为67
  1730. for (let i = 0; i < 200; i++) {
  1731. const clearResult = await electronAPI.sendKeyEvent(device, '67');
  1732. if (!clearResult.success) {
  1733. break;
  1734. }
  1735. await new Promise(resolve => setTimeout(resolve, 10));
  1736. }
  1737. // 等待清空完成
  1738. await new Promise(resolve => setTimeout(resolve, 200));
  1739. }
  1740. const textResult = await electronAPI.sendText(device, inputValue);
  1741. if (!textResult.success) {
  1742. return { success: false, error: `输入失败: ${textResult.error}` };
  1743. }
  1744. // 确保正确显示UTF-8编码的中文
  1745. try {
  1746. const displayValue = Buffer.isBuffer(inputValue)
  1747. ? inputValue.toString('utf8')
  1748. : String(inputValue);
  1749. // 输入成功,不打印日志
  1750. } catch (e) {
  1751. // 输入成功,不打印日志
  1752. }
  1753. return { success: true };
  1754. }
  1755. case 'ocr': {
  1756. // OCR识别
  1757. if (!electronAPI || !electronAPI.ocrLastMessage) {
  1758. return { success: false, error: 'OCR API 不可用' };
  1759. }
  1760. const method = action.method || 'full-screen';
  1761. let avatarPath = null;
  1762. const area = action.area;
  1763. // 如果是by-avatar方法,需要获取头像路径
  1764. if (method === 'by-avatar' && action.avatar) {
  1765. const avatarName = resolveValue(action.avatar);
  1766. if (avatarName) {
  1767. // 头像路径:从工作流文件夹路径中提取文件夹名,然后拼接头像文件名
  1768. // folderPath格式可能是:C:\...\static\processing\工作流名称
  1769. // 我们需要传递:工作流名称/头像文件名
  1770. const folderName = folderPath.split(/[/\\]/).pop();
  1771. avatarPath = `${folderName}/${avatarName}`;
  1772. }
  1773. }
  1774. // 调用OCR API,传递工作流文件夹路径
  1775. const ocrResult = await electronAPI.ocrLastMessage(device, method, avatarPath, area, folderPath);
  1776. if (!ocrResult.success) {
  1777. return { success: false, error: `OCR识别失败: ${ocrResult.error}` };
  1778. }
  1779. // 保存识别结果到变量
  1780. if (action.variable) {
  1781. variableContext[action.variable] = ocrResult.text || '';
  1782. // 确保正确显示UTF-8编码的中文
  1783. const displayText = ocrResult.text || '';
  1784. try {
  1785. // 如果text是Buffer,转换为字符串
  1786. const textStr = Buffer.isBuffer(displayText)
  1787. ? displayText.toString('utf8')
  1788. : String(displayText);
  1789. // OCR识别结果已保存到变量
  1790. } catch (e) {
  1791. // 如果转换失败,直接输出
  1792. // OCR识别结果已保存到变量
  1793. }
  1794. }
  1795. return {
  1796. success: true,
  1797. text: ocrResult.text,
  1798. position: ocrResult.position
  1799. };
  1800. }
  1801. case 'extract-messages':
  1802. case 'ocr-chat':
  1803. case 'ocr-chat-history': // 向后兼容
  1804. case 'extract-chat-history': { // 向后兼容
  1805. // 提取消息记录
  1806. // 获取头像路径(支持新的 inVars 格式,也支持旧参数 avatar1/avatar2 和 friendAvatar/myAvatar)
  1807. const folderName = folderPath.split(/[/\\]/).pop();
  1808. let avatar1Path = null;
  1809. let avatar2Path = null;
  1810. // 优先使用新的 inVars 格式
  1811. let avatar1Name, avatar2Name, regionArea = null;
  1812. let friendRgb = null, myRgb = null;
  1813. if (action.inVars && Array.isArray(action.inVars)) {
  1814. if (action.inVars.length >= 3) {
  1815. // 三个参数:可能是 RGB格式 或 头像+区域格式
  1816. const param1 = resolveValue(action.inVars[0]);
  1817. const param2 = resolveValue(action.inVars[1]);
  1818. // 检查是否是RGB格式(格式:"(r,g,b)")
  1819. const rgbPattern = /^\((\d+),(\d+),(\d+)\)$/;
  1820. if (typeof param1 === 'string' && rgbPattern.test(param1.trim()) &&
  1821. typeof param2 === 'string' && rgbPattern.test(param2.trim())) {
  1822. // RGB格式:第一个是好友RGB,第二个是我的RGB,第三个是区域
  1823. friendRgb = param1.trim();
  1824. myRgb = param2.trim();
  1825. // 第三个参数是区域
  1826. const regionVar = extractVarName(action.inVars[2]);
  1827. regionArea = variableContext[regionVar];
  1828. if (regionArea === undefined) {
  1829. const regionResolved = resolveValue(action.inVars[2]);
  1830. if (regionResolved && typeof regionResolved === 'object') {
  1831. regionArea = regionResolved;
  1832. }
  1833. }
  1834. } else {
  1835. // 头像格式:头像1、头像2、区域
  1836. avatar1Name = action.inVars[0];
  1837. avatar2Name = action.inVars[1];
  1838. const regionVar = extractVarName(action.inVars[2]);
  1839. regionArea = variableContext[regionVar];
  1840. if (regionArea === undefined) {
  1841. const regionResolved = resolveValue(action.inVars[2]);
  1842. if (regionResolved && typeof regionResolved === 'object') {
  1843. regionArea = regionResolved;
  1844. }
  1845. }
  1846. }
  1847. // 验证区域格式
  1848. if (regionArea) {
  1849. if (typeof regionArea === 'string') {
  1850. try {
  1851. regionArea = JSON.parse(regionArea);
  1852. } catch (e) {
  1853. regionArea = null;
  1854. }
  1855. }
  1856. if (regionArea && typeof regionArea === 'object') {
  1857. if (!regionArea.topLeft || !regionArea.bottomRight) {
  1858. regionArea = null;
  1859. }
  1860. }
  1861. }
  1862. } else if (action.inVars.length >= 2) {
  1863. // 两个参数:可能是 RGB格式 或 头像格式
  1864. const param1 = resolveValue(action.inVars[0]);
  1865. const param2 = resolveValue(action.inVars[1]);
  1866. // 检查是否是RGB格式
  1867. const rgbPattern = /^\((\d+),(\d+),(\d+)\)$/;
  1868. if (typeof param1 === 'string' && rgbPattern.test(param1.trim()) &&
  1869. typeof param2 === 'string' && rgbPattern.test(param2.trim())) {
  1870. // RGB格式:第一个是好友RGB,第二个是我的RGB
  1871. friendRgb = param1.trim();
  1872. myRgb = param2.trim();
  1873. } else {
  1874. // 头像格式:头像1、头像2(无区域,使用全屏)
  1875. avatar1Name = action.inVars[0];
  1876. avatar2Name = action.inVars[1];
  1877. }
  1878. } else if (action.inVars.length === 1) {
  1879. // 一个参数:头像1(向后兼容)
  1880. avatar1Name = action.inVars[0];
  1881. avatar2Name = action.avatar2 || action.myAvatar;
  1882. }
  1883. } else {
  1884. // 使用旧参数
  1885. avatar1Name = action.avatar1 || action.friendAvatar;
  1886. avatar2Name = action.avatar2 || action.myAvatar;
  1887. }
  1888. if (avatar1Name) {
  1889. const avatar1Resolved = resolveValue(avatar1Name);
  1890. if (avatar1Resolved) {
  1891. // resources 作为根目录
  1892. avatar1Path = `${folderName}/resources/${avatar1Resolved}`;
  1893. }
  1894. }
  1895. if (avatar2Name) {
  1896. const avatar2Resolved = resolveValue(avatar2Name);
  1897. if (avatar2Resolved) {
  1898. // resources 作为根目录
  1899. avatar2Path = `${folderName}/resources/${avatar2Resolved}`;
  1900. }
  1901. }
  1902. // 调用 Func 目录下的执行函数
  1903. // 确保 regionArea 是对象格式(如果是字符串,尝试解析为 JSON)
  1904. let regionParam = regionArea;
  1905. if (regionArea && typeof regionArea === 'string') {
  1906. try {
  1907. regionParam = JSON.parse(regionArea);
  1908. } catch (e) {
  1909. // 解析失败,使用 null(函数内部会处理)
  1910. regionParam = null;
  1911. }
  1912. }
  1913. const chatResult = await executeOcrChat({
  1914. device,
  1915. avatar1: avatar1Path,
  1916. avatar2: avatar2Path,
  1917. folderPath,
  1918. region: regionParam, // 传递区域参数(对象格式,如果提供)
  1919. friendRgb: friendRgb, // 传递好友RGB(如果提供)
  1920. myRgb: myRgb // 传递我的RGB(如果提供)
  1921. });
  1922. if (!chatResult.success) {
  1923. return { success: false, error: `提取消息记录失败: ${chatResult.error}` };
  1924. }
  1925. // 保存消息记录到变量(支持新的 outVars 格式)
  1926. let outputVarName = null;
  1927. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  1928. outputVarName = extractVarName(action.outVars[0]);
  1929. } else if (action.variable) {
  1930. outputVarName = extractVarName(action.variable);
  1931. }
  1932. if (outputVarName) {
  1933. // 使用JSON字符串格式的消息记录
  1934. const messagesJson = chatResult.messagesJson || JSON.stringify(chatResult.messages || []);
  1935. variableContext[outputVarName] = messagesJson;
  1936. await logOutVars(action, variableContext, folderPath);
  1937. }
  1938. return {
  1939. success: true,
  1940. messages: chatResult.messages || [],
  1941. messagesJson: chatResult.messagesJson || JSON.stringify(chatResult.messages || []),
  1942. lastMessage: chatResult.messages && chatResult.messages.length > 0 ? chatResult.messages[chatResult.messages.length - 1] : null
  1943. };
  1944. }
  1945. case 'ai-generate': {
  1946. // AI生成
  1947. let prompt = resolveValue(action.prompt);
  1948. // 如果提供了 inVars,替换 prompt 中的变量
  1949. if (action.inVars && Array.isArray(action.inVars)) {
  1950. for (let i = 0; i < action.inVars.length; i++) {
  1951. const varName = extractVarName(action.inVars[i]);
  1952. const varValue = variableContext[varName];
  1953. // 替换 prompt 中的变量占位符(例如 {currentMessage})
  1954. if (varValue !== undefined && varValue !== null) {
  1955. const placeholder = `{${varName}}`;
  1956. // 检查是否是空数组 JSON 字符串
  1957. let replaceValue = String(varValue);
  1958. if (typeof varValue === 'string' && varValue.trim() === '[]') {
  1959. try {
  1960. const parsed = JSON.parse(varValue);
  1961. if (Array.isArray(parsed) && parsed.length === 0) {
  1962. replaceValue = '';
  1963. }
  1964. } catch (e) {
  1965. // 不是 JSON,继续使用原值
  1966. }
  1967. }
  1968. prompt = prompt.replace(new RegExp(placeholder.replace(/[{}]/g, '\\$&'), 'g'), replaceValue);
  1969. }
  1970. }
  1971. }
  1972. // 替换 prompt 中的变量(包括 historySummary 和其他变量)
  1973. // 注意:这里需要先替换 historySummary,因为它可能包含在 prompt 模板中
  1974. if (prompt.includes('{historySummary}')) {
  1975. let historySummary = variableContext['historySummary'] || '';
  1976. // 如果变量中没有历史总结,尝试从文件中读取
  1977. if (!historySummary) {
  1978. historySummary = await getHistorySummary(folderPath);
  1979. // 如果从文件读取成功,也更新变量上下文
  1980. if (historySummary) {
  1981. variableContext['historySummary'] = historySummary;
  1982. }
  1983. }
  1984. prompt = prompt.replace(/{historySummary}/g, historySummary);
  1985. }
  1986. // 替换 prompt 中所有剩余的变量占位符(支持 {{variable}} 和 {variable} 格式)
  1987. prompt = replaceVariablesInString(prompt, variableContext);
  1988. try {
  1989. // 调用AI API(使用现有的GPT API)
  1990. const requestBody = {
  1991. prompt: prompt,
  1992. modelName: action.model || 'gpt-5-nano-ca'
  1993. };
  1994. const response = await fetch('https://ai-anim.com/api/text2textByModel', {
  1995. method: 'POST',
  1996. headers: { 'Content-Type': 'application/json' },
  1997. body: JSON.stringify(requestBody)
  1998. });
  1999. if (!response.ok) {
  2000. const errorText = await response.text();
  2001. return { success: false, error: `AI请求失败: ${response.statusText}` };
  2002. }
  2003. const data = await response.json();
  2004. // API 返回格式:{ success: true, data: { output_text: "..." } }
  2005. // 或者:{ data: { output_text: "..." } }
  2006. // 优先从 data.data.output_text 提取,然后是 data.output_text,最后是其他字段
  2007. let rawResult = '';
  2008. if (data.data && typeof data.data === 'object' && data.data.output_text) {
  2009. rawResult = data.data.output_text;
  2010. } else if (data.output_text) {
  2011. rawResult = data.output_text;
  2012. } else if (data.text) {
  2013. rawResult = data.text;
  2014. } else if (data.content) {
  2015. rawResult = data.content;
  2016. } else if (data.data && typeof data.data === 'string') {
  2017. rawResult = data.data;
  2018. } else {
  2019. // 如果都没有,尝试从整个响应中提取
  2020. rawResult = JSON.stringify(data);
  2021. }
  2022. // 确保 rawResult 是字符串
  2023. rawResult = rawResult ? String(rawResult) : '';
  2024. // 解析AI返回的JSON格式回复
  2025. let result = rawResult;
  2026. try {
  2027. // 尝试从返回文本中提取JSON
  2028. // 方法1: 尝试直接解析整个文本
  2029. try {
  2030. const jsonResult = JSON.parse(rawResult.trim());
  2031. if (jsonResult.reply) {
  2032. result = jsonResult.reply;
  2033. }
  2034. } catch (e) {
  2035. // 方法2: 尝试从代码块中提取JSON
  2036. const codeBlockMatch = rawResult.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
  2037. if (codeBlockMatch) {
  2038. try {
  2039. const jsonResult = JSON.parse(codeBlockMatch[1]);
  2040. if (jsonResult.reply) {
  2041. result = jsonResult.reply;
  2042. }
  2043. } catch (e2) {
  2044. // JSON解析失败,继续使用原始文本
  2045. }
  2046. } else {
  2047. // 方法3: 尝试从文本中查找JSON对象
  2048. const jsonMatch = rawResult.match(/\{\s*"reply"\s*:\s*"([^"]+)"\s*\}/);
  2049. if (jsonMatch) {
  2050. result = jsonMatch[1];
  2051. } else {
  2052. // 方法4: 尝试查找单行的JSON格式
  2053. const lines = rawResult.split('\n').map(line => line.trim()).filter(line => line);
  2054. for (const line of lines) {
  2055. if (line.startsWith('{') && line.includes('"reply"')) {
  2056. try {
  2057. const jsonResult = JSON.parse(line);
  2058. if (jsonResult.reply) {
  2059. result = jsonResult.reply;
  2060. break;
  2061. }
  2062. } catch (e3) {
  2063. // 继续尝试下一行
  2064. }
  2065. }
  2066. }
  2067. }
  2068. }
  2069. }
  2070. } catch (parseError) {
  2071. // 如果解析失败,使用原始文本
  2072. }
  2073. // 保存到变量(支持 outVars 格式)
  2074. // outVars[0] 是 AI 生成的结果,outVars[1](如果有)是 aiCallBack 变量
  2075. if (action.outVars && Array.isArray(action.outVars)) {
  2076. // 第一个输出变量保存 AI 生成结果
  2077. if (action.outVars.length > 0) {
  2078. const outputVarName = extractVarName(action.outVars[0]);
  2079. if (outputVarName) {
  2080. variableContext[outputVarName] = result;
  2081. }
  2082. }
  2083. // 第二个输出变量(如果有)设置为 1 表示 AI 生成完成(aiCallBack)
  2084. if (action.outVars.length > 1) {
  2085. const callbackVarName = extractVarName(action.outVars[1]);
  2086. if (callbackVarName) {
  2087. variableContext[callbackVarName] = 1;
  2088. }
  2089. }
  2090. await logOutVars(action, variableContext, folderPath);
  2091. } else if (action.variable) {
  2092. // 向后兼容:使用旧的 variable 字段
  2093. const outputVarName = extractVarName(action.variable);
  2094. if (outputVarName) {
  2095. variableContext[outputVarName] = result;
  2096. }
  2097. }
  2098. // 向后兼容:如果 aiCallBack 在 inVars 中提供,也设置它(但优先使用 outVars)
  2099. if (!action.outVars || !Array.isArray(action.outVars) || action.outVars.length <= 1) {
  2100. if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 1) {
  2101. const callbackVarName = extractVarName(action.inVars[1]);
  2102. if (callbackVarName) {
  2103. variableContext[callbackVarName] = 1;
  2104. }
  2105. }
  2106. }
  2107. return { success: true, result };
  2108. } catch (error) {
  2109. return { success: false, error: `AI生成失败: ${error.message}` };
  2110. }
  2111. }
  2112. case 'save-messages':
  2113. case 'generate-summary':
  2114. case 'generate-history-summary': { // 向后兼容
  2115. // 生成消息记录的AI总结
  2116. if (!action.variable) {
  2117. return { success: false, error: '缺少变量名' };
  2118. }
  2119. const messages = variableContext[action.variable];
  2120. if (!messages) {
  2121. return { success: false, error: `变量 ${action.variable} 不存在或为空` };
  2122. }
  2123. const modelName = action.model || 'gpt-5-nano-ca';
  2124. const result = await generateHistorySummary(messages, folderPath, modelName);
  2125. if (!result.success) {
  2126. return { success: false, error: `生成消息记录总结失败: ${result.error}` };
  2127. }
  2128. // 保存总结到变量
  2129. if (action.summaryVariable) {
  2130. variableContext[action.summaryVariable] = result.summary;
  2131. // 消息记录总结已保存到变量
  2132. }
  2133. return { success: true, summary: result.summary };
  2134. }
  2135. case 'set': {
  2136. // 设置变量
  2137. if (action.variable) {
  2138. const varName = extractVarName(action.variable);
  2139. // 如果 value 是字符串且包含算术运算符,尝试计算表达式
  2140. let finalValue = action.value;
  2141. if (typeof action.value === 'string' && /[+\-*/]/.test(action.value)) {
  2142. finalValue = evaluateExpression(action.value, variableContext);
  2143. } else if (typeof action.value === 'string') {
  2144. // 如果 value 是字符串,检查是否包含变量引用({variable} 格式)
  2145. // 替换字符串中的所有变量引用
  2146. const varPattern = /\{([\w-]+)\}/g;
  2147. let hasVariables = false;
  2148. finalValue = action.value.replace(varPattern, (match, varName) => {
  2149. hasVariables = true;
  2150. const value = variableContext[varName];
  2151. if (value === undefined || value === null) {
  2152. return match; // 如果变量不存在,保留原样
  2153. }
  2154. return String(value);
  2155. });
  2156. // 如果没有找到变量引用,使用 resolveValue 解析(处理单个变量引用的情况)
  2157. if (!hasVariables) {
  2158. finalValue = resolveValue(action.value, variableContext);
  2159. }
  2160. } else {
  2161. // 否则使用 resolveValue 解析变量引用
  2162. finalValue = resolveValue(action.value, variableContext);
  2163. }
  2164. variableContext[varName] = finalValue;
  2165. }
  2166. return { success: true };
  2167. }
  2168. case 'random': {
  2169. // 生成随机数
  2170. // 支持新格式:inVars[min, max] 和 outVars[{variable}]
  2171. let varName, min, max;
  2172. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  2173. varName = extractVarName(action.outVars[0]);
  2174. } else if (action.variable) {
  2175. // 向后兼容旧格式
  2176. varName = extractVarName(action.variable);
  2177. } else {
  2178. return { success: false, error: 'random 操作缺少 variable 或 outVars 参数' };
  2179. }
  2180. if (action.inVars && Array.isArray(action.inVars) && action.inVars.length >= 2) {
  2181. // 新格式:从 inVars 读取 min 和 max
  2182. min = Number(action.inVars[0]);
  2183. max = Number(action.inVars[1]);
  2184. } else {
  2185. // 向后兼容旧格式
  2186. min = action.min !== undefined ? Number(action.min) : 0;
  2187. max = action.max !== undefined ? Number(action.max) : 100;
  2188. }
  2189. const integer = action.integer !== undefined ? action.integer : true;
  2190. if (isNaN(min) || isNaN(max)) {
  2191. return { success: false, error: 'random 操作的 min 和 max 必须是数字' };
  2192. }
  2193. if (min > max) {
  2194. return { success: false, error: 'random 操作的 min 不能大于 max' };
  2195. }
  2196. let randomValue;
  2197. if (integer) {
  2198. randomValue = Math.floor(Math.random() * (max - min + 1)) + min;
  2199. } else {
  2200. randomValue = Math.random() * (max - min) + min;
  2201. }
  2202. variableContext[varName] = randomValue;
  2203. return { success: true };
  2204. }
  2205. case 'echo': {
  2206. try {
  2207. // 打印信息到 console.log、UI 和 log.txt 文件
  2208. // 支持 inVars 或 value 字段
  2209. let message = '';
  2210. if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 0) {
  2211. // 从 inVars 中读取变量值
  2212. const messages = action.inVars.map(varWithBraces => {
  2213. const varName = extractVarName(varWithBraces);
  2214. const varValue = variableContext[varName];
  2215. // 如果变量包含 {variable} 或 {{variable}} 格式,尝试解析为变量名
  2216. if (varWithBraces.startsWith('{') && varWithBraces.endsWith('}')) {
  2217. return varValue !== undefined ? String(varValue) : varWithBraces;
  2218. }
  2219. // 如果不是变量格式,直接使用原值
  2220. return varWithBraces;
  2221. });
  2222. message = messages.join(' ');
  2223. } else if (action.value) {
  2224. // 使用 value 字段,支持变量替换(只支持 {{variable}} 格式,用于字符串拼接)
  2225. // 先提取所有变量名,用于调试
  2226. const doubleBracePattern = /\{\{([\w-]+)\}\}/g;
  2227. const variablesInValue = [];
  2228. let match;
  2229. while ((match = doubleBracePattern.exec(action.value)) !== null) {
  2230. variablesInValue.push(match[1]);
  2231. }
  2232. message = replaceVariablesInString(action.value, variableContext);
  2233. // 如果消息为空或只包含原始变量格式,添加调试信息
  2234. if (!message || message === action.value) {
  2235. const missingVars = variablesInValue.filter(varName => {
  2236. const varValue = variableContext[varName];
  2237. return varValue === undefined || varValue === null || varValue === '';
  2238. });
  2239. if (missingVars.length > 0) {
  2240. message = `${action.value} [变量未定义或为空: ${missingVars.join(', ')}]`;
  2241. }
  2242. }
  2243. } else {
  2244. // 如果没有提供任何内容,输出空字符串
  2245. message = '';
  2246. }
  2247. // 输出到 console.log(仅限小红书随机浏览工作流)
  2248. if (folderPath && folderPath.includes('小红书随机浏览工作流')) {
  2249. console.log(message);
  2250. }
  2251. // 写入 log.txt 文件(只有 echo 类型写入文件)
  2252. // 添加系统时间到消息中
  2253. // 即使 message 为空也记录,以便调试
  2254. const now = new Date();
  2255. const year = now.getFullYear();
  2256. const month = String(now.getMonth() + 1).padStart(2, '0');
  2257. const day = String(now.getDate()).padStart(2, '0');
  2258. const hour = String(now.getHours()).padStart(2, '0');
  2259. const minute = String(now.getMinutes()).padStart(2, '0');
  2260. const second = String(now.getSeconds()).padStart(2, '0');
  2261. const timeStr = `${year}/${month}/${day} ${hour}:${minute}:${second}`;
  2262. const messageWithTime = message ? `${message} [系统时间: ${timeStr}]` : `[空消息] [系统时间: ${timeStr}]`;
  2263. await logMessage(messageWithTime, folderPath);
  2264. // 发送 log 消息事件到 UI
  2265. const logEvent = new CustomEvent('log-message', {
  2266. detail: {
  2267. message: message
  2268. }
  2269. });
  2270. window.dispatchEvent(logEvent);
  2271. return { success: true };
  2272. } catch (error) {
  2273. // 如果 echo 执行出错,记录错误到 log.txt
  2274. const now = new Date();
  2275. const year = now.getFullYear();
  2276. const month = String(now.getMonth() + 1).padStart(2, '0');
  2277. const day = String(now.getDate()).padStart(2, '0');
  2278. const hour = String(now.getHours()).padStart(2, '0');
  2279. const minute = String(now.getMinutes()).padStart(2, '0');
  2280. const second = String(now.getSeconds()).padStart(2, '0');
  2281. const timeStr = `${year}/${month}/${day} ${hour}:${minute}:${second}`;
  2282. const errorMsg = `[错误] echo 执行失败: ${error.message} [系统时间: ${timeStr}]`;
  2283. await logMessage(errorMsg, folderPath);
  2284. return { success: false, error: `echo 执行失败: ${error.message}` };
  2285. }
  2286. }
  2287. case 'log': { // 向后兼容,但不写入 log.txt
  2288. // 打印信息到 console.log 和 UI(不写入 log.txt)
  2289. // 支持 inVars 或 value 字段
  2290. let message = '';
  2291. if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 0) {
  2292. // 从 inVars 中读取变量值
  2293. const messages = action.inVars.map(varWithBraces => {
  2294. const varName = extractVarName(varWithBraces);
  2295. const varValue = variableContext[varName];
  2296. // 如果变量包含 {variable} 或 {{variable}} 格式,尝试解析为变量名
  2297. if (varWithBraces.startsWith('{') && varWithBraces.endsWith('}')) {
  2298. return varValue !== undefined ? String(varValue) : varWithBraces;
  2299. }
  2300. // 如果不是变量格式,直接使用原值
  2301. return varWithBraces;
  2302. });
  2303. message = messages.join(' ');
  2304. } else if (action.value) {
  2305. // 使用 value 字段,支持变量替换(只支持 {{variable}} 格式,用于字符串拼接)
  2306. message = replaceVariablesInString(action.value, variableContext);
  2307. } else {
  2308. // 如果没有提供任何内容,输出空字符串
  2309. message = '';
  2310. }
  2311. // 输出到 console.log(仅限小红书随机浏览工作流)
  2312. if (folderPath && folderPath.includes('小红书随机浏览工作流')) {
  2313. console.log(message);
  2314. }
  2315. // 注意:log 类型不写入 log.txt 文件,只发送到 UI
  2316. // 发送 log 消息事件到 UI
  2317. const logEvent = new CustomEvent('log-message', {
  2318. detail: {
  2319. message: message
  2320. }
  2321. });
  2322. window.dispatchEvent(logEvent);
  2323. return { success: true };
  2324. }
  2325. case 'img-bounding-box-location': {
  2326. // 图像区域定位
  2327. // 支持新的 inVars/outVars 格式(都可以为空)
  2328. let screenshotPath = action.screenshot;
  2329. let regionPath = action.region;
  2330. // 如果提供了 inVars,从变量中读取或直接使用
  2331. if (action.inVars && Array.isArray(action.inVars)) {
  2332. if (action.inVars.length === 1) {
  2333. // 如果只有一个参数,将其作为 region(区域图片)
  2334. const firstVar = extractVarName(action.inVars[0]);
  2335. const firstValue = variableContext[firstVar];
  2336. if (firstValue && typeof firstValue === 'string' && !firstValue.includes('{')) {
  2337. regionPath = firstValue;
  2338. } else {
  2339. // 如果变量不存在,直接使用 inVars[0] 作为路径
  2340. regionPath = action.inVars[0];
  2341. }
  2342. // screenshot 需要自动从设备获取(传递 null)
  2343. screenshotPath = null;
  2344. } else if (action.inVars.length >= 2) {
  2345. // 如果有两个参数,第一个是 screenshot,第二个是 region
  2346. const screenshotVar = extractVarName(action.inVars[0]);
  2347. const screenshotValue = variableContext[screenshotVar];
  2348. if (screenshotValue && typeof screenshotValue === 'string' && !screenshotValue.includes('{')) {
  2349. screenshotPath = screenshotValue;
  2350. } else {
  2351. screenshotPath = action.inVars[0];
  2352. }
  2353. const regionVar = extractVarName(action.inVars[1]);
  2354. const regionValue = variableContext[regionVar];
  2355. if (regionValue && typeof regionValue === 'string' && !regionValue.includes('{')) {
  2356. regionPath = regionValue;
  2357. } else {
  2358. regionPath = action.inVars[1];
  2359. }
  2360. }
  2361. }
  2362. // 如果没有提供路径,使用默认值或从 action 中读取
  2363. if (screenshotPath !== null && !screenshotPath) screenshotPath = action.screenshot;
  2364. if (!regionPath) regionPath = action.region;
  2365. if (!regionPath) {
  2366. return { success: false, error: '缺少区域截图路径' };
  2367. }
  2368. // 如果 screenshotPath 为 null,需要自动从设备获取
  2369. if (screenshotPath === null && !device) {
  2370. return { success: false, error: '缺少完整截图路径,且无法自动获取设备截图(缺少设备ID)' };
  2371. }
  2372. // 调用 Func 目录下的执行函数
  2373. const result = await executeImgBoundingBoxLocation({
  2374. device,
  2375. screenshot: screenshotPath,
  2376. region: regionPath,
  2377. folderPath
  2378. });
  2379. if (!result.success) {
  2380. return { success: false, error: `图像区域定位失败: ${result.error}` };
  2381. }
  2382. // 保存结果到变量(支持 outVars 格式)
  2383. // img-bounding-box-location 返回四个顶点坐标
  2384. let outputVarName = null;
  2385. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  2386. outputVarName = extractVarName(action.outVars[0]);
  2387. } else if (action.variable) {
  2388. outputVarName = extractVarName(action.variable);
  2389. }
  2390. if (outputVarName) {
  2391. // 将对象转换为 JSON 字符串(只允许 string 或 int 类型)
  2392. if (result.corners && typeof result.corners === 'object') {
  2393. variableContext[outputVarName] = JSON.stringify(result.corners);
  2394. } else {
  2395. variableContext[outputVarName] = '';
  2396. }
  2397. // 图像区域定位结果已保存到变量
  2398. await logOutVars(action, variableContext, folderPath);
  2399. }
  2400. return { success: true, result: result.corners };
  2401. }
  2402. case 'img-center-point-location': {
  2403. // 图像中心点定位
  2404. // 支持新的 inVars/outVars 格式(都可以为空)
  2405. let templatePath = action.template;
  2406. // 如果提供了 inVars,从变量中读取或直接使用
  2407. if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 0) {
  2408. const templateVar = extractVarName(action.inVars[0]);
  2409. const templateValue = variableContext[templateVar];
  2410. if (templateValue && typeof templateValue === 'string' && !templateValue.includes('{')) {
  2411. templatePath = templateValue;
  2412. } else {
  2413. // 如果变量不存在,直接使用 inVars[0] 作为路径
  2414. templatePath = action.inVars[0];
  2415. }
  2416. }
  2417. // 如果没有提供路径,使用默认值或从 action 中读取
  2418. if (!templatePath) templatePath = action.template;
  2419. if (!templatePath) {
  2420. return { success: false, error: '缺少模板图片路径' };
  2421. }
  2422. if (!device) {
  2423. return { success: false, error: '缺少设备 ID,无法自动获取截图' };
  2424. }
  2425. // 调用 Func 目录下的执行函数
  2426. const result = await executeImgCenterPointLocation({
  2427. device,
  2428. template: templatePath,
  2429. folderPath
  2430. });
  2431. if (!result.success) {
  2432. return { success: false, error: `图像中心点定位失败: ${result.error}` };
  2433. }
  2434. // 保存结果到变量(支持 outVars 格式)
  2435. let outputVarName = null;
  2436. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  2437. outputVarName = extractVarName(action.outVars[0]);
  2438. } else if (action.variable) {
  2439. outputVarName = extractVarName(action.variable);
  2440. }
  2441. if (outputVarName) {
  2442. // 保存中心点坐标为字符串(JSON 格式):只允许 number 或 string
  2443. if (result.center && typeof result.center === 'object' && result.center.x !== undefined && result.center.y !== undefined) {
  2444. variableContext[outputVarName] = JSON.stringify({ x: result.center.x, y: result.center.y });
  2445. } else {
  2446. variableContext[outputVarName] = '';
  2447. }
  2448. // 图像中心点定位结果已保存到变量
  2449. await logOutVars(action, variableContext, folderPath);
  2450. }
  2451. return { success: true, result: result.center };
  2452. }
  2453. case 'img-cropping': {
  2454. // 裁剪图片区域
  2455. // 支持新的 inVars 格式
  2456. let area = action.area;
  2457. let savePath = action.savePath;
  2458. // 如果提供了 inVars,从变量中读取或直接使用
  2459. if (action.inVars && Array.isArray(action.inVars)) {
  2460. if (action.inVars.length > 0) {
  2461. const areaVar = extractVarName(action.inVars[0]);
  2462. const areaValue = variableContext[areaVar];
  2463. if (areaValue !== undefined) {
  2464. area = areaValue;
  2465. } else {
  2466. area = resolveValue(action.inVars[0]);
  2467. }
  2468. }
  2469. if (action.inVars.length > 1) {
  2470. const savePathVar = extractVarName(action.inVars[1]);
  2471. const savePathValue = variableContext[savePathVar];
  2472. if (savePathValue !== undefined) {
  2473. savePath = savePathValue;
  2474. } else {
  2475. savePath = resolveValue(action.inVars[1]);
  2476. }
  2477. }
  2478. }
  2479. if (!area) {
  2480. return { success: false, error: 'img-cropping 缺少 area 参数' };
  2481. }
  2482. if (!savePath) {
  2483. return { success: false, error: 'img-cropping 缺少 savePath 参数' };
  2484. }
  2485. const result = await executeImgCropping({
  2486. area,
  2487. savePath,
  2488. folderPath,
  2489. device // 传递设备ID,用于获取最新截图
  2490. });
  2491. if (!result.success) {
  2492. // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
  2493. return { success: false, error: result.error };
  2494. }
  2495. // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
  2496. // 如果提供了 outVars,可以将结果保存到变量
  2497. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  2498. const outputVarName = extractVarName(action.outVars[0]);
  2499. if (outputVarName) {
  2500. // 只允许 string 或 int 类型,保存成功标志为 "1" 或 1
  2501. variableContext[outputVarName] = result.success ? '1' : '0';
  2502. }
  2503. }
  2504. await logOutVars(action, variableContext, folderPath);
  2505. return { success: true };
  2506. }
  2507. case 'read-last-message': {
  2508. // 读取最后一条消息
  2509. // 支持新的 inVars/outVars 格式,也支持 inputVars/outputVars
  2510. const inputVars = action.inVars || action.inputVars || [];
  2511. const outputVars = action.outVars || action.outputVars || [];
  2512. let textVar = action.textVariable;
  2513. let senderVar = action.senderVariable;
  2514. let inputVar = null;
  2515. if (outputVars.length > 0) {
  2516. textVar = extractVarName(outputVars[0]);
  2517. }
  2518. if (outputVars.length > 1) {
  2519. senderVar = extractVarName(outputVars[1]);
  2520. }
  2521. if (inputVars.length > 0) {
  2522. inputVar = extractVarName(inputVars[0]);
  2523. }
  2524. if (!textVar && !senderVar) {
  2525. return { success: false, error: 'read-last-message 缺少 textVariable 或 senderVariable 参数' };
  2526. }
  2527. // 如果提供了 inputVar,从变量中读取数据
  2528. let inputData = null;
  2529. if (inputVar && variableContext[inputVar] !== undefined) {
  2530. inputData = variableContext[inputVar];
  2531. }
  2532. // 确保 inputData 是字符串类型(如果是对象或数组,转换为 JSON 字符串)
  2533. let inputDataString = inputData;
  2534. if (inputData !== null && inputData !== undefined) {
  2535. if (typeof inputData === 'string') {
  2536. inputDataString = inputData;
  2537. } else if (Array.isArray(inputData) || typeof inputData === 'object') {
  2538. inputDataString = JSON.stringify(inputData);
  2539. } else {
  2540. inputDataString = String(inputData);
  2541. }
  2542. } else {
  2543. inputDataString = null; // null 表示从文件读取
  2544. }
  2545. const result = await executeReadLastMessage({
  2546. folderPath,
  2547. inputData: inputDataString, // 确保是字符串类型,如果为 null,则从 history 文件夹读取
  2548. textVariable: textVar,
  2549. senderVariable: senderVar
  2550. });
  2551. if (!result.success) {
  2552. return { success: false, error: result.error };
  2553. }
  2554. // 保存消息文本和发送者到变量
  2555. if (textVar) {
  2556. variableContext[textVar] = result.text;
  2557. // 最后一条消息文本已保存到变量
  2558. }
  2559. if (senderVar) {
  2560. variableContext[senderVar] = result.sender;
  2561. // 最后一条消息发送者已保存到变量
  2562. }
  2563. await logOutVars(action, variableContext, folderPath);
  2564. return { success: true, text: result.text, sender: result.sender };
  2565. }
  2566. case 'read-txt':
  2567. case 'read-text': { // 向后兼容别名
  2568. // 读取根目录下的文本文件
  2569. // 支持新的 inVars/outVars 格式
  2570. let filePath = action.filePath;
  2571. let varName = action.variable;
  2572. if (action.inVars && Array.isArray(action.inVars) && action.inVars.length > 0) {
  2573. // 从 inVars 读取文件路径(可能是变量或直接路径)
  2574. const filePathVar = extractVarName(action.inVars[0]);
  2575. const filePathValue = variableContext[filePathVar];
  2576. if (filePathValue !== undefined) {
  2577. filePath = filePathValue;
  2578. } else {
  2579. filePath = resolveValue(action.inVars[0]);
  2580. }
  2581. }
  2582. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  2583. varName = extractVarName(action.outVars[0]);
  2584. } else if (action.variable) {
  2585. varName = extractVarName(action.variable);
  2586. }
  2587. if (!filePath) {
  2588. return { success: false, error: 'read-txt 缺少 filePath 参数' };
  2589. }
  2590. if (!varName) {
  2591. return { success: false, error: 'read-txt 缺少 variable 参数' };
  2592. }
  2593. const result = await executeReadTxt({
  2594. filePath,
  2595. folderPath
  2596. });
  2597. if (!result.success) {
  2598. return { success: false, error: result.error };
  2599. }
  2600. // 保存文件内容到变量(确保始终是字符串类型,即使是空字符串)
  2601. const content = result.content || '';
  2602. variableContext[varName] = typeof content === 'string' ? content : String(content);
  2603. // 确保变量始终是字符串类型(即使是空字符串)
  2604. if (variableContext[varName] === undefined || variableContext[varName] === null) {
  2605. variableContext[varName] = '';
  2606. }
  2607. await logOutVars(action, variableContext, folderPath);
  2608. return { success: true, content: result.content };
  2609. }
  2610. case 'smart-chat-append': {
  2611. // 智能合并历史聊天记录和当前聊天记录,自动检测并去除连续重合部分后返回新的聊天记录字符串
  2612. // 支持新的 inVars/outVars 格式
  2613. let history = action.history;
  2614. let current = action.current;
  2615. if (action.inVars && Array.isArray(action.inVars)) {
  2616. // 从 inVars 读取历史记录和当前记录(可能是变量或直接值)
  2617. if (action.inVars.length > 0) {
  2618. const historyVar = extractVarName(action.inVars[0]);
  2619. const historyValue = variableContext[historyVar];
  2620. if (historyValue !== undefined) {
  2621. history = historyValue;
  2622. } else {
  2623. history = resolveValue(action.inVars[0]);
  2624. }
  2625. }
  2626. if (action.inVars.length > 1) {
  2627. const currentVar = extractVarName(action.inVars[1]);
  2628. const currentValue = variableContext[currentVar];
  2629. if (currentValue !== undefined) {
  2630. current = currentValue;
  2631. } else {
  2632. current = resolveValue(action.inVars[1]);
  2633. }
  2634. }
  2635. }
  2636. if (history === undefined || history === null) {
  2637. history = '';
  2638. }
  2639. if (current === undefined || current === null) {
  2640. current = '';
  2641. }
  2642. const result = await executeSmartChatAppend({
  2643. history: typeof history === 'string' ? history : String(history),
  2644. current: typeof current === 'string' ? current : String(current)
  2645. });
  2646. if (!result.success) {
  2647. return { success: false, error: result.error };
  2648. }
  2649. // 保存结果到变量
  2650. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  2651. const outputVarName = extractVarName(action.outVars[0]);
  2652. if (outputVarName && result.result) {
  2653. variableContext[outputVarName] = result.result;
  2654. }
  2655. } else if (action.variable) {
  2656. const varName = extractVarName(action.variable);
  2657. if (varName && result.result) {
  2658. variableContext[varName] = result.result;
  2659. }
  2660. }
  2661. return { success: true, result: result.result };
  2662. }
  2663. case 'save-txt':
  2664. case 'save-text': { // 向后兼容别名
  2665. // 保存字符串为文本文件
  2666. // 支持新的 inVars/outVars 格式
  2667. let filePath = action.filePath;
  2668. let content = action.content;
  2669. if (action.inVars && Array.isArray(action.inVars)) {
  2670. // 从 inVars 读取内容和文件路径(可能是变量或直接值)
  2671. // 入参顺序:第一个参数是内容,第二个参数是文件路径
  2672. if (action.inVars.length > 0) {
  2673. // 第一个参数是内容
  2674. const contentVar = extractVarName(action.inVars[0]);
  2675. const contentValue = variableContext[contentVar];
  2676. if (contentValue !== undefined) {
  2677. content = contentValue;
  2678. } else {
  2679. content = resolveValue(action.inVars[0]);
  2680. }
  2681. }
  2682. if (action.inVars.length > 1) {
  2683. // 第二个参数是文件路径
  2684. const filePathVar = extractVarName(action.inVars[1]);
  2685. const filePathValue = variableContext[filePathVar];
  2686. if (filePathValue !== undefined) {
  2687. filePath = filePathValue;
  2688. } else {
  2689. filePath = resolveValue(action.inVars[1]);
  2690. }
  2691. }
  2692. }
  2693. if (!filePath) {
  2694. return { success: false, error: 'save-txt 缺少 filePath 参数' };
  2695. }
  2696. if (content === undefined || content === null) {
  2697. return { success: false, error: 'save-txt 缺少 content 参数' };
  2698. }
  2699. const result = await executeSaveTxt({
  2700. filePath,
  2701. content,
  2702. folderPath
  2703. });
  2704. if (!result.success) {
  2705. return { success: false, error: result.error };
  2706. }
  2707. // 如果提供了 outVars,可以将结果保存到变量(虽然通常不需要)
  2708. if (action.outVars && Array.isArray(action.outVars) && action.outVars.length > 0) {
  2709. const outputVarName = extractVarName(action.outVars[0]);
  2710. if (outputVarName) {
  2711. // 只允许 string 或 int 类型,保存成功标志为 "1" 或 1
  2712. variableContext[outputVarName] = result.success ? '1' : '0';
  2713. }
  2714. }
  2715. await logOutVars(action, variableContext, folderPath);
  2716. return { success: true };
  2717. }
  2718. case 'delay': {
  2719. // 延迟
  2720. const delayMs = parseDelayString(action.value || action.delay || '0s');
  2721. if (delayMs > 0) {
  2722. await new Promise(resolve => setTimeout(resolve, delayMs));
  2723. }
  2724. return { success: true };
  2725. }
  2726. case 'swipe': {
  2727. // 滑动操作
  2728. if (!electronAPI || !electronAPI.sendSwipe) {
  2729. return { success: false, error: '滑动 API 不可用' };
  2730. }
  2731. const { x1, y1, x2, y2 } = calculateSwipeCoordinates(
  2732. action.value,
  2733. resolution.width,
  2734. resolution.height
  2735. );
  2736. const swipeResult = await electronAPI.sendSwipe(device, x1, y1, x2, y2, 300);
  2737. if (!swipeResult.success) {
  2738. return { success: false, error: `滑动失败: ${swipeResult.error}` };
  2739. }
  2740. // 成功滑动
  2741. return { success: true };
  2742. }
  2743. case 'string-press': {
  2744. // 向后兼容:文字识别并点击
  2745. if (!electronAPI || !electronAPI.findTextAndGetCoordinate) {
  2746. return { success: false, error: '文字识别 API 不可用' };
  2747. }
  2748. const matchResult = await electronAPI.findTextAndGetCoordinate(device, action.value);
  2749. if (!matchResult.success) {
  2750. return { success: false, error: `文字识别失败: ${matchResult.error}` };
  2751. }
  2752. const { clickPosition } = matchResult;
  2753. const { x, y } = clickPosition;
  2754. if (!electronAPI || !electronAPI.sendTap) {
  2755. return { success: false, error: '点击 API 不可用' };
  2756. }
  2757. const tapResult = await electronAPI.sendTap(device, x, y);
  2758. if (!tapResult.success) {
  2759. return { success: false, error: `点击失败: ${tapResult.error}` };
  2760. }
  2761. // 成功点击文字
  2762. return { success: true };
  2763. }
  2764. case 'scroll': {
  2765. // 滚动操作(小幅度滚动)
  2766. if (!electronAPI || !electronAPI.sendScroll) {
  2767. return { success: false, error: '滚动 API 不可用' };
  2768. }
  2769. const scrollResult = await electronAPI.sendScroll(
  2770. device,
  2771. action.value,
  2772. resolution.width,
  2773. resolution.height,
  2774. DEFAULT_SCROLL_DISTANCE,
  2775. 500
  2776. );
  2777. if (!scrollResult.success) {
  2778. return { success: false, error: `滚动失败: ${scrollResult.error}` };
  2779. }
  2780. // 成功滚动
  2781. return { success: true };
  2782. }
  2783. default:
  2784. return { success: false, error: `未知的操作类型: ${action.type}` };
  2785. }
  2786. } catch (error) {
  2787. // 记录错误到 log.txt
  2788. const now = new Date();
  2789. const year = now.getFullYear();
  2790. const month = String(now.getMonth() + 1).padStart(2, '0');
  2791. const day = String(now.getDate()).padStart(2, '0');
  2792. const hour = String(now.getHours()).padStart(2, '0');
  2793. const minute = String(now.getMinutes()).padStart(2, '0');
  2794. const second = String(now.getSeconds()).padStart(2, '0');
  2795. const timeStr = `${year}/${month}/${day} ${hour}:${minute}:${second}`;
  2796. const errorMsg = `[错误] 操作执行失败: ${error.message} [系统时间: ${timeStr}]`;
  2797. await logMessage(errorMsg, folderPath).catch(() => {
  2798. // 静默失败,不影响主流程
  2799. });
  2800. return { success: false, error: error.message };
  2801. }
  2802. }
  2803. /**
  2804. * 执行操作序列(支持嵌套和条件)
  2805. * @param {Array} actions - 解析后的操作列表
  2806. * @param {string} device - 设备 ID
  2807. * @param {string} folderPath - 文件夹路径
  2808. * @param {Object} resolution - 设备分辨率
  2809. * @param {number} stepInterval - 步骤间隔时间(毫秒),默认1秒
  2810. * @param {Function} onStepComplete - 每步完成后的回调函数
  2811. * @param {Function} shouldStop - 检查是否应该停止的函数
  2812. * @param {number} depth - 嵌套深度(用于递归)
  2813. * @returns {Promise<Object>} 执行结果 {success, error?, completedSteps}
  2814. */
  2815. async function executeActionSequence(
  2816. actions,
  2817. device,
  2818. folderPath,
  2819. resolution,
  2820. stepInterval = DEFAULT_STEP_INTERVAL,
  2821. onStepComplete = null,
  2822. shouldStop = null,
  2823. depth = 0
  2824. ) {
  2825. // 如果是顶层(depth === 0),重置全局步骤计数器和变量初始化标志
  2826. if (depth === 0) {
  2827. globalStepCounter = 0;
  2828. // 重置变量初始化标志,允许在新工作流开始时重新初始化
  2829. variableContextInitialized = false;
  2830. // 保存当前工作流文件夹路径,用于日志记录
  2831. currentWorkflowFolderPath = folderPath;
  2832. // 添加分割线,分开每次执行的日志
  2833. await logMessage('========================', folderPath);
  2834. }
  2835. let completedSteps = 0;
  2836. const stepPrefix = depth > 0 ? ' '.repeat(depth) : '';
  2837. for (let i = 0; i < actions.length; i++) {
  2838. // 检查是否应该停止
  2839. if (shouldStop && shouldStop()) {
  2840. // 执行被停止
  2841. return { success: false, error: '执行被停止', completedSteps };
  2842. }
  2843. const action = actions[i];
  2844. // 处理特殊操作类型
  2845. if (action.type === 'schedule') {
  2846. // schedule 操作:根据 condition 中的 interval 和 repeat 执行动作
  2847. const condition = action.condition || {};
  2848. const intervalStr = condition.interval || '0s';
  2849. const repeat = condition.repeat !== undefined ? condition.repeat : 1;
  2850. const actionsToExecute = action.interval || [];
  2851. // 解析间隔时间
  2852. const intervalMs = parseDelayString(intervalStr) || 0;
  2853. // 确定循环次数(-1 表示无限循环)
  2854. const maxIterations = repeat === -1 ? Infinity : (typeof repeat === 'number' ? repeat : 1);
  2855. let iteration = 0;
  2856. while (iteration < maxIterations) {
  2857. if (shouldStop && shouldStop()) {
  2858. return { success: false, error: '执行被停止', completedSteps };
  2859. }
  2860. iteration++;
  2861. // 如果不是第一次迭代,等待间隔时间
  2862. if (iteration > 1 && intervalMs > 0) {
  2863. // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
  2864. let remainingTime = intervalMs;
  2865. const countdownInterval = 100;
  2866. while (remainingTime > 0) {
  2867. if (shouldStop && shouldStop()) {
  2868. return { success: false, error: '执行被停止', completedSteps };
  2869. }
  2870. const waitTime = Math.min(countdownInterval, remainingTime);
  2871. await new Promise(resolve => setTimeout(resolve, waitTime));
  2872. remainingTime -= waitTime;
  2873. }
  2874. }
  2875. // 执行动作序列
  2876. if (actionsToExecute.length > 0) {
  2877. const result = await executeActionSequence(
  2878. actionsToExecute,
  2879. device,
  2880. folderPath,
  2881. resolution,
  2882. stepInterval,
  2883. onStepComplete,
  2884. shouldStop,
  2885. depth + 1
  2886. );
  2887. if (!result.success) {
  2888. return result;
  2889. }
  2890. completedSteps += result.completedSteps || 0;
  2891. }
  2892. }
  2893. continue;
  2894. }
  2895. if (action.type === 'if') {
  2896. const conditionResult = evaluateCondition(action.condition);
  2897. // 支持 ture(拼写错误)和 false 作为 then 和 else 的别名
  2898. const actionsToExecute = conditionResult ? (action.then || action.ture || []) : (action.else || action.false || []);
  2899. if (actionsToExecute.length > 0) {
  2900. const result = await executeActionSequence(
  2901. actionsToExecute,
  2902. device,
  2903. folderPath,
  2904. resolution,
  2905. stepInterval,
  2906. onStepComplete,
  2907. shouldStop,
  2908. depth + 1
  2909. );
  2910. if (!result.success) {
  2911. return result;
  2912. }
  2913. completedSteps += result.completedSteps || 0;
  2914. }
  2915. continue;
  2916. }
  2917. if (action.type === 'for') {
  2918. const items = Array.isArray(action.items) ? action.items : [];
  2919. for (const item of items) {
  2920. if (shouldStop && shouldStop()) {
  2921. return { success: false, error: '执行被停止', completedSteps };
  2922. }
  2923. // 设置循环变量
  2924. if (action.variable) {
  2925. variableContext[action.variable] = item;
  2926. }
  2927. if (action.body && action.body.length > 0) {
  2928. const result = await executeActionSequence(
  2929. action.body,
  2930. device,
  2931. folderPath,
  2932. resolution,
  2933. stepInterval,
  2934. onStepComplete,
  2935. shouldStop,
  2936. depth + 1
  2937. );
  2938. if (!result.success) {
  2939. return result;
  2940. }
  2941. completedSteps += result.completedSteps || 0;
  2942. }
  2943. }
  2944. continue;
  2945. }
  2946. if (action.type === 'while') {
  2947. while (evaluateCondition(action.condition)) {
  2948. if (shouldStop && shouldStop()) {
  2949. return { success: false, error: '执行被停止', completedSteps };
  2950. }
  2951. if (action.body && action.body.length > 0) {
  2952. const result = await executeActionSequence(
  2953. action.body,
  2954. device,
  2955. folderPath,
  2956. resolution,
  2957. stepInterval,
  2958. onStepComplete,
  2959. shouldStop,
  2960. depth + 1
  2961. );
  2962. if (!result.success) {
  2963. return result;
  2964. }
  2965. completedSteps += result.completedSteps || 0;
  2966. }
  2967. }
  2968. continue;
  2969. }
  2970. // 普通操作
  2971. const times = action.times || 1;
  2972. // 发送步骤开始执行事件
  2973. if (onStepComplete) {
  2974. const stepName = getActionName(action);
  2975. onStepComplete(i + 1, actions.length, stepName, 0, times, 0);
  2976. }
  2977. // 计算等待时间(根据 data 和 delay)
  2978. const waitTime = calculateWaitTime(action.data, action.delay);
  2979. if (waitTime > 0) {
  2980. const waitSeconds = Math.round(waitTime / 1000);
  2981. // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
  2982. // 在等待期间也更新倒计时
  2983. let remainingTime = waitTime;
  2984. const countdownInterval = 100;
  2985. const stepName = getActionName(action);
  2986. while (remainingTime > 0) {
  2987. if (shouldStop && shouldStop()) {
  2988. return { success: false, error: '执行被停止', completedSteps };
  2989. }
  2990. if (onStepComplete) {
  2991. onStepComplete(i + 1, actions.length, stepName, remainingTime, times, 0);
  2992. }
  2993. const waitTimeChunk = Math.min(countdownInterval, remainingTime);
  2994. await new Promise(resolve => setTimeout(resolve, waitTimeChunk));
  2995. remainingTime -= waitTimeChunk;
  2996. }
  2997. }
  2998. // 根据 times 重复执行操作
  2999. for (let t = 0; t < times; t++) {
  3000. // 检查是否应该停止
  3001. if (shouldStop && shouldStop()) {
  3002. // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
  3003. return { success: false, error: '执行被停止', completedSteps };
  3004. }
  3005. // 发送步骤执行中事件(包含当前执行次数)
  3006. if (onStepComplete) {
  3007. const stepName = getActionName(action);
  3008. onStepComplete(i + 1, actions.length, stepName, 0, times, t + 1);
  3009. }
  3010. // 使用全局步骤计数器
  3011. globalStepCounter++;
  3012. const currentStepNumber = globalStepCounter;
  3013. // 记录步骤开始时间
  3014. const stepStartTime = Date.now();
  3015. const startTimeStr = new Date(stepStartTime).toLocaleString('zh-CN', {
  3016. year: 'numeric',
  3017. month: '2-digit',
  3018. day: '2-digit',
  3019. hour: '2-digit',
  3020. minute: '2-digit',
  3021. second: '2-digit',
  3022. hour12: false
  3023. });
  3024. // 获取操作类型名称
  3025. const typeName = getActionName(action);
  3026. // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
  3027. // 执行操作
  3028. const result = await executeAction(action, device, folderPath, resolution);
  3029. // 记录步骤结束时间
  3030. const stepEndTime = Date.now();
  3031. const endTimeStr = new Date(stepEndTime).toLocaleString('zh-CN', {
  3032. year: 'numeric',
  3033. month: '2-digit',
  3034. day: '2-digit',
  3035. hour: '2-digit',
  3036. minute: '2-digit',
  3037. second: '2-digit',
  3038. hour12: false
  3039. });
  3040. const stepDuration = (stepEndTime - stepStartTime) / 1000; // 转换为秒
  3041. // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
  3042. if (!result.success) {
  3043. // 记录错误到 log.txt
  3044. const now = new Date();
  3045. const year = now.getFullYear();
  3046. const month = String(now.getMonth() + 1).padStart(2, '0');
  3047. const day = String(now.getDate()).padStart(2, '0');
  3048. const hour = String(now.getHours()).padStart(2, '0');
  3049. const minute = String(now.getMinutes()).padStart(2, '0');
  3050. const second = String(now.getSeconds()).padStart(2, '0');
  3051. const timeStr = `${year}/${month}/${day} ${hour}:${minute}:${second}`;
  3052. const errorMsg = `[错误] ${getActionName(action)} 执行失败: ${result.error} [系统时间: ${timeStr}]`;
  3053. await logMessage(errorMsg, folderPath).catch(() => {
  3054. // 静默失败,不影响主流程
  3055. });
  3056. return { success: false, error: result.error, completedSteps: i };
  3057. }
  3058. // 如果不是最后一次重复,等待一小段时间
  3059. if (t < times - 1) {
  3060. await new Promise(resolve => setTimeout(resolve, 500));
  3061. }
  3062. }
  3063. completedSteps++;
  3064. // 调用完成回调
  3065. if (onStepComplete) {
  3066. const stepName = getActionName(action);
  3067. onStepComplete(i + 1, actions.length, stepName, 0, times, times);
  3068. }
  3069. // 如果不是最后一步,等待间隔时间
  3070. if (i < actions.length - 1) {
  3071. let remainingTime = stepInterval;
  3072. const countdownInterval = 100;
  3073. const nextStepName = getActionName(actions[i + 1]);
  3074. const nextTimes = actions[i + 1].times || 1;
  3075. while (remainingTime > 0) {
  3076. if (shouldStop && shouldStop()) {
  3077. return { success: false, error: '执行被停止', completedSteps };
  3078. }
  3079. if (onStepComplete) {
  3080. onStepComplete(i + 1, actions.length, nextStepName, remainingTime, nextTimes, 0);
  3081. }
  3082. const waitTime = Math.min(countdownInterval, remainingTime);
  3083. await new Promise(resolve => setTimeout(resolve, waitTime));
  3084. remainingTime -= waitTime;
  3085. }
  3086. }
  3087. }
  3088. if (depth === 0) {
  3089. // 注意:系统日志不再写入 log.txt,只保留 echo 类型的日志
  3090. }
  3091. return { success: true, completedSteps };
  3092. }
  3093. module.exports = { parseWorkflow, parseActions, calculateSwipeCoordinates, executeAction, executeActionSequence }