workflow-json-parser.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. /**
  2. * 工作流 JSON 解析:只解析 type,按 type 分派给 actions 下各脚本自行解析并执行。
  3. * 依赖:actions/*(各 parser,含 set-parser 的 extractVarName/resolveValue、fun-parser 的 fun 类 type)
  4. */
  5. const setParser = require('./actions/set-parser.js')
  6. const extractVarName = setParser.extractVarName
  7. const resolveValue = setParser.resolveValue
  8. const funNodeRegistry = require('./actions/fun/fun-node-registry.js')
  9. const actionModules = [
  10. require('./actions/delay-parser.js'),
  11. setParser,
  12. require('./actions/fun/adb/adb-parser.js'),
  13. require('./actions/echo-parser.js'),
  14. require('./actions/random-parser.js'),
  15. require('./actions/schedule-parser.js'),
  16. require('./actions/if-parser.js'),
  17. require('./actions/for-parser.js'),
  18. require('./actions/while-parser.js'),
  19. require('./actions/try-parser.js'),
  20. require('./actions/fun/fun-parser.js'),
  21. ]
  22. const registry = {}
  23. actionModules.forEach(mod => {
  24. const types = mod.types ? (Array.isArray(mod.types) ? mod.types : [mod.types]) : []
  25. types.forEach(t => {
  26. registry[t] = { parse: mod.parse, execute: mod.execute }
  27. })
  28. })
  29. function parseAction(type, action, parseContext) {
  30. const entry = registry[type]
  31. if (!entry || !entry.parse) return { ...action, type }
  32. return entry.parse(action, parseContext)
  33. }
  34. async function executeAction(type, action, executeContext) {
  35. const entry = registry[type]
  36. if (!entry || !entry.execute) return { success: false, error: `Unknown action type: ${type}` }
  37. return entry.execute(action, executeContext)
  38. }
  39. /**
  40. * Get display name for action (used in UI / log; English only for log.txt)
  41. */
  42. function getActionName(action) {
  43. const typeNames = {
  44. 'schedule': 'schedule',
  45. 'adb': 'adb',
  46. 'press': 'press image',
  47. 'input': 'input text',
  48. 'swipe': 'swipe',
  49. 'string-press': 'press text',
  50. 'scroll': 'scroll',
  51. 'locate': 'locate',
  52. 'click': 'click',
  53. 'ocr': 'ocr',
  54. 'extract-messages': 'extract messages',
  55. 'save-messages': 'save messages',
  56. 'generate-summary': 'generate summary',
  57. 'ocr-chat': 'ocr chat',
  58. 'ocr-chat-history': 'ocr chat history',
  59. 'extract-chat-history': 'extract chat history',
  60. 'generate-history-summary': 'generate history summary',
  61. 'img-bounding-box-location': 'img bounding box',
  62. 'img-center-point-location': 'img center point',
  63. 'img-cropping': 'img cropping',
  64. 'img-scale': 'img scale',
  65. 'read-last-message': 'read last message',
  66. 'read-txt': 'read text file',
  67. 'read-text': 'read text file',
  68. 'save-txt': 'save text file',
  69. 'save-text': 'save text file',
  70. 'smart-chat-append': 'smart chat append',
  71. 'ai-generate': 'ai generate',
  72. 'if': 'if',
  73. 'for': 'for',
  74. 'while': 'while',
  75. 'try': 'try',
  76. 'delay': 'delay',
  77. 'set': 'set variable',
  78. 'random': 'random',
  79. 'echo': 'echo',
  80. }
  81. ;(funNodeRegistry || []).forEach((def) => { typeNames[def.type] = def.displayName || def.type })
  82. const typeName = (action.type === 'fun' || action.type === 'ai' || action.type === 'io')
  83. ? (typeNames[action.method] || action.method || action.type)
  84. : (typeNames[action.type] || action.type)
  85. const value = action.value || action.target || ''
  86. const displayValue = typeof value === 'string' ? value : JSON.stringify(value)
  87. if (action.type === 'schedule') {
  88. const condition = action.condition || {}
  89. const interval = condition.interval || '0s'
  90. const repeat = condition.repeat !== undefined ? condition.repeat : 1
  91. const repeatText = repeat === -1 ? 'infinite' : `repeat ${repeat}`
  92. return `${typeName}: ${interval}, ${repeatText}`
  93. }
  94. if (action.type === 'echo') {
  95. const parts = (action.inVars && Array.isArray(action.inVars)) ? action.inVars.map((v) => (v == null ? '' : String(v))) : []
  96. const joined = parts.join(' ').trim()
  97. const d = joined.length > 40 ? joined.substring(0, 40) + '...' : joined
  98. return `${typeName}: ${d || '(empty)'}`
  99. }
  100. if (action.type === 'input') {
  101. return `${typeName}: ${displayValue.length > 20 ? displayValue.substring(0, 20) + '...' : displayValue}`
  102. }
  103. if (action.type === 'string-press' || action.type === 'click') {
  104. return `${typeName}: ${displayValue.length > 20 ? displayValue.substring(0, 20) + '...' : displayValue}`
  105. }
  106. if (action.type === 'if') return `${typeName}: ${action.condition || ''}`
  107. if (action.type === 'for') return `${typeName}: ${action.variable || ''}`
  108. if (action.type === 'try') return typeName
  109. if (action.type === 'set') return `${typeName}: ${action.variable || ''}`
  110. if (action.type === 'fun' || action.type === 'ai' || action.type === 'io') {
  111. const m = action.method && String(action.method)
  112. if (m && m.startsWith('adb-')) return `adb ${m.slice(4)}: ${displayValue}`
  113. if (m === 'json-to-arr' || m === 'json-json-to-arr') return `json to arr: ${displayValue}`
  114. return `${typeName}: ${displayValue}`
  115. }
  116. return `${typeName}: ${displayValue}`
  117. }
  118. /**
  119. * 解析操作数组:只按 type 分派,由各 action 脚本自己解析。
  120. * 非法结点、未知 type、缺 type 均抛错并中止解析(不静默跳过、不原样透传)。
  121. */
  122. function parseActions (actions, state, pathPrefix = 'execute') {
  123. if (!Array.isArray(actions)) {
  124. throw new Error(`[${pathPrefix}] 必须为数组`)
  125. }
  126. const parsedActions = []
  127. for (let i = 0; i < actions.length; i++) {
  128. const itemPath = `${pathPrefix}[${i}]`
  129. const action = actions[i]
  130. if (action === null || typeof action !== 'object' || Array.isArray(action)) {
  131. throw new Error(`[${itemPath}] 结点必须为对象`)
  132. }
  133. if (!action.type || typeof action.type !== 'string') {
  134. throw new Error(`[${itemPath}] 缺少字符串字段 type`)
  135. }
  136. const entry = registry[action.type]
  137. if (!entry || !entry.parse) {
  138. throw new Error(`[${itemPath}] 未知的 type: "${action.type}"`)
  139. }
  140. const parseActionsChild = (childArr, segment) => {
  141. if (!Array.isArray(childArr)) {
  142. throw new Error(`[${itemPath}.${segment}] 必须为数组`)
  143. }
  144. return parseActions(childArr, state, `${itemPath}.${segment}`)
  145. }
  146. const parseContext = {
  147. extractVarName,
  148. resolveValue,
  149. variableContext: state.variableContext,
  150. state,
  151. parseActions: parseActionsChild,
  152. actionPath: itemPath,
  153. }
  154. try {
  155. parsedActions.push(entry.parse(action, parseContext))
  156. } catch (e) {
  157. const msg = e && e.message ? String(e.message) : String(e)
  158. if (msg.includes(itemPath)) throw e
  159. throw new Error(`[${itemPath}] ${msg}`)
  160. }
  161. }
  162. return parsedActions
  163. }
  164. /**
  165. * 解析工作流 JSON(支持 variables, execute)
  166. * state: { variableContext, getInitialized(), setInitialized(bool) }
  167. */
  168. function parseWorkflow(workflow, state) {
  169. if (!workflow || typeof workflow !== 'object') return null
  170. const { variableContext, getInitialized, setInitialized } = state
  171. if (!getInitialized || !getInitialized()) {
  172. for (const key in variableContext) delete variableContext[key]
  173. if (workflow.variables) {
  174. for (const key in workflow.variables) {
  175. const value = workflow.variables[key]
  176. if (value === null || value === undefined) variableContext[key] = ''
  177. else if (typeof value === 'boolean') variableContext[key] = value ? '1' : '0'
  178. else if (typeof value === 'number') variableContext[key] = value
  179. else if (typeof value === 'string') variableContext[key] = value
  180. else if (Array.isArray(value) || (typeof value === 'object' && value !== null)) variableContext[key] = value
  181. else variableContext[key] = String(value)
  182. }
  183. }
  184. if (setInitialized) setInitialized(true)
  185. } else if (workflow.variables) {
  186. for (const key in workflow.variables) {
  187. const cur = variableContext[key]
  188. if (cur === undefined || cur === null || cur === '') {
  189. const value = workflow.variables[key]
  190. if (value === null || value === undefined) variableContext[key] = ''
  191. else if (typeof value === 'boolean') variableContext[key] = value ? '1' : '0'
  192. else if (typeof value === 'number') variableContext[key] = value
  193. else if (typeof value === 'string') variableContext[key] = value
  194. else if (Array.isArray(value) || (typeof value === 'object' && value !== null)) variableContext[key] = value
  195. else variableContext[key] = String(value)
  196. }
  197. }
  198. }
  199. const actions = workflow.execute && Array.isArray(workflow.execute)
  200. ? parseActions(workflow.execute, state)
  201. : []
  202. let schedule = workflow.schedule || {}
  203. if (Array.isArray(schedule)) schedule = schedule.length > 0 ? schedule[0] : {}
  204. if (schedule && typeof schedule === 'object' && schedule.schedule) schedule = schedule.schedule
  205. if (schedule && typeof schedule === 'object' && (schedule.repeat === 'forever' || schedule.repeat === 'Forever')) schedule.repeat = -1
  206. return { schedule, variables: variableContext, actions }
  207. }
  208. module.exports = { parseWorkflow, parseActions, getActionName, registry, parseAction, executeAction }