skill-executor.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /**
  2. * OpenClaw Skill 执行器 — 含余额不足检测 + 弹出充值网址逻辑
  3. *
  4. * 流程:
  5. * 1. 读取 api-config.json
  6. * 2. 解析 tokenConfig,获取 token
  7. * 3. 调用 Skill API
  8. * 4. 检查响应是否匹配 errorHandling 条件
  9. * 5. 如果余额不足 → 打开充值网址(qrCodeUrl)
  10. * 6. 轮询余额变化
  11. * 7. 充值成功后重试 Skill
  12. *
  13. * 用法:
  14. * node scripts/skill-executor.js <skill-dir> [--user=xxx] [--apigid=yyy]
  15. * 例: node scripts/skill-executor.js jimeng/jimeng-img-v4 --user=nd7NOCmFiE --apigid=Vo3ROWEvDy
  16. */
  17. const fs = require('fs');
  18. const path = require('path');
  19. const { exec } = require('child_process');
  20. // ─── 配置 ───
  21. const API_BASE = 'https://server.fmode.cn';
  22. const APP_ID = 'ncloudmaster';
  23. // ─── 1. 加载 Skill 配置 ───
  24. function loadSkillConfig(skillDir) {
  25. const root = path.resolve(__dirname, '..');
  26. const configPath = path.join(root, skillDir, 'api-config.json');
  27. if (!fs.existsSync(configPath)) {
  28. throw new Error(`未找到配置: ${configPath}`);
  29. }
  30. return JSON.parse(fs.readFileSync(configPath, 'utf-8'));
  31. }
  32. // ─── 2. 匹配 errorHandling 条件 ───
  33. function matchesErrorConditions(responseData, errorDef) {
  34. if (!errorDef || !errorDef.conditions) return false;
  35. const results = errorDef.conditions.map(cond => {
  36. const fieldValue = responseData[cond.responseField];
  37. if (fieldValue === undefined || fieldValue === null) return false;
  38. switch (cond.operator) {
  39. case 'in':
  40. return Array.isArray(cond.value) && cond.value.includes(fieldValue);
  41. case 'contains':
  42. if (typeof fieldValue !== 'string') return false;
  43. return Array.isArray(cond.value)
  44. ? cond.value.some(v => fieldValue.toLowerCase().includes(v.toLowerCase()))
  45. : fieldValue.toLowerCase().includes(String(cond.value).toLowerCase());
  46. case 'equals':
  47. return fieldValue === cond.value;
  48. default:
  49. return false;
  50. }
  51. });
  52. // matchMode: "any" = 任一条件匹配即触发; "all" = 全部匹配
  53. const mode = errorDef.matchMode || 'any';
  54. return mode === 'all' ? results.every(Boolean) : results.some(Boolean);
  55. }
  56. // ─── 3. 解析模板变量 ───
  57. function resolveTemplate(template, vars) {
  58. return template.replace(/\{\{(\w+)\}\}/g, (_, key) => vars[key] || '');
  59. }
  60. // ─── 4. 打开充值网址 ───
  61. function openPaymentUrl(qrCodeUrl, vars) {
  62. const url = resolveTemplate(qrCodeUrl, vars);
  63. console.log('\n╔══════════════════════════════════════════════════════╗');
  64. console.log('║ 💰 余额不足,请扫码充值 ║');
  65. console.log('╚══════════════════════════════════════════════════════╝');
  66. console.log(`\n充值网址: ${url}\n`);
  67. // 在系统浏览器中打开
  68. const platform = process.platform;
  69. const cmd = platform === 'win32' ? `start "" "${url}"`
  70. : platform === 'darwin' ? `open "${url}"`
  71. : `xdg-open "${url}"`;
  72. exec(cmd, (err) => {
  73. if (err) console.warn('自动打开浏览器失败,请手动复制上方网址');
  74. });
  75. return url;
  76. }
  77. // ─── 5. 轮询余额 ───
  78. async function pollBalance(authId, oldCount, config) {
  79. const checkEndpoint = config.paymentCheckEndpoint || `${API_BASE}/api/apig/getApig`;
  80. const interval = config.pollingIntervalMs || 3000;
  81. const timeout = config.pollingTimeoutMs || 300000;
  82. const maxAttempts = Math.ceil(timeout / interval);
  83. console.log(`[轮询] 等待充值完成... (每${interval / 1000}秒检查, 最多${maxAttempts}次)`);
  84. for (let i = 1; i <= maxAttempts; i++) {
  85. await new Promise(r => setTimeout(r, interval));
  86. try {
  87. const resp = await fetch(checkEndpoint, {
  88. method: 'POST',
  89. headers: { 'Content-Type': 'application/json' },
  90. body: JSON.stringify({ authid: authId })
  91. });
  92. const data = await resp.json();
  93. if (data.code === 200 && data.data && data.data.count > oldCount) {
  94. console.log(`[轮询] ✅ 充值成功! 余额: ${oldCount} → ${data.data.count}`);
  95. return data.data;
  96. }
  97. console.log(`[轮询] #${i} 余额未变 (${data.data?.count ?? '?'})`);
  98. } catch (e) {
  99. console.warn(`[轮询] #${i} 请求失败:`, e.message);
  100. }
  101. }
  102. console.log('[轮询] ⚠️ 超时,余额未变化');
  103. return null;
  104. }
  105. // ─── 6. 查询 APIGAuth ───
  106. async function getApigAuth(userId, apigId) {
  107. const url = `${API_BASE}/parse/classes/APIGAuth?` + new URLSearchParams({
  108. where: JSON.stringify({
  109. api: { __type: 'Pointer', className: 'APIG', objectId: apigId },
  110. company: { __type: 'Pointer', className: 'Company', objectId: userId }
  111. }),
  112. limit: '1'
  113. });
  114. const resp = await fetch(url, {
  115. headers: { 'X-Parse-Application-Id': APP_ID }
  116. });
  117. const data = await resp.json();
  118. if (data.results && data.results.length > 0) {
  119. return data.results[0];
  120. }
  121. return null;
  122. }
  123. // ─── 7. 核心执行器 ───
  124. async function executeSkillWithBilling(skillDir, inputParams, userVars) {
  125. const config = loadSkillConfig(skillDir);
  126. console.log(`\n[执行器] Skill: ${config.displayName} (${config.name})`);
  127. console.log(`[执行器] 端点: ${config.endpoint.method} ${config.endpoint.url}`);
  128. // Step A: 先查余额(如有 user + apigid)
  129. let authRecord = null;
  130. if (userVars.user && userVars.apigid) {
  131. console.log(`[执行器] 查询用户余额... user=${userVars.user}, apigid=${userVars.apigid}`);
  132. authRecord = await getApigAuth(userVars.user, userVars.apigid);
  133. if (authRecord) {
  134. console.log(`[执行器] APIGAuth: ${authRecord.objectId}, 余额: ${authRecord.count || 0}`);
  135. // 余额为0直接触发充值,不必等API报错
  136. if ((authRecord.count || 0) <= 0) {
  137. console.log('[执行器] 余额为0,直接触发充值流程');
  138. return await handleInsufficientBalance(config, authRecord, userVars);
  139. }
  140. } else {
  141. console.log('[执行器] 未找到 APIGAuth 记录,将在调用后根据响应判断');
  142. }
  143. }
  144. // Step B: 调用 Skill API
  145. console.log(`[执行器] 调用 Skill API...`);
  146. const resp = await fetch(config.endpoint.url, {
  147. method: config.endpoint.method,
  148. headers: config.endpoint.headers,
  149. body: config.endpoint.method === 'GET' ? undefined : JSON.stringify(inputParams)
  150. });
  151. const result = await resp.json();
  152. console.log(`[执行器] 响应 code: ${result.code}, msg: ${result.msg || result.message || ''}`);
  153. // Step C: 检查是否匹配 errorHandling 条件
  154. if (config.errorHandling) {
  155. // 检查: 余额不足
  156. if (config.errorHandling.balanceInsufficient) {
  157. if (matchesErrorConditions(result, config.errorHandling.balanceInsufficient)) {
  158. console.log('[执行器] ⚡ 检测到余额不足!');
  159. return await handleInsufficientBalance(config, authRecord, userVars);
  160. }
  161. }
  162. // 检查: 未授权
  163. if (config.errorHandling.unauthorized) {
  164. if (matchesErrorConditions(result, config.errorHandling.unauthorized)) {
  165. console.log('[执行器] ⚡ 检测到未授权!');
  166. return await handleUnauthorized(config, userVars);
  167. }
  168. }
  169. }
  170. // Step D: 正常返回
  171. console.log('[执行器] ✅ Skill 调用成功');
  172. return { success: true, data: result };
  173. }
  174. // ─── 8. 处理余额不足 ───
  175. async function handleInsufficientBalance(config, authRecord, userVars) {
  176. const tc = config.tokenConfig;
  177. if (!tc || !tc.onBalanceInsufficient) {
  178. console.error('[执行器] ❌ 无 onBalanceInsufficient 配置,无法处理');
  179. return { success: false, error: 'balance_insufficient_no_handler' };
  180. }
  181. const handler = tc.onBalanceInsufficient;
  182. const oldCount = authRecord ? (authRecord.count || 0) : 0;
  183. const authId = authRecord ? authRecord.objectId : null;
  184. if (handler.action === 'showPaymentQR') {
  185. // 打开充值网址
  186. openPaymentUrl(handler.qrCodeUrl, userVars);
  187. console.log(`[执行器] title: ${handler.title}`);
  188. console.log(`[执行器] message: ${handler.message}`);
  189. if (!authId) {
  190. console.log('[执行器] 无 authId,无法轮询余额。请手动充值后重试。');
  191. return { success: false, error: 'no_auth_record', paymentUrl: resolveTemplate(handler.qrCodeUrl, userVars) };
  192. }
  193. // 轮询等待充值
  194. const updated = await pollBalance(authId, oldCount, handler);
  195. if (updated) {
  196. // 充值成功 → 重试 Skill
  197. if (handler.onPaymentSuccess === 'retrySkillWithNewToken') {
  198. console.log('[执行器] 🔄 充值成功,准备重试 Skill...');
  199. return { success: true, recharged: true, newBalance: updated.count, action: 'retrySkill' };
  200. }
  201. return { success: true, recharged: true, newBalance: updated.count };
  202. }
  203. return { success: false, error: 'payment_timeout' };
  204. }
  205. return { success: false, error: 'unknown_action', action: handler.action };
  206. }
  207. // ─── 9. 处理未授权 ───
  208. async function handleUnauthorized(config, userVars) {
  209. const tc = config.tokenConfig;
  210. if (!tc || !tc.onMissing) {
  211. console.error('[执行器] ❌ 无 onMissing 配置');
  212. return { success: false, error: 'unauthorized_no_handler' };
  213. }
  214. const handler = tc.onMissing;
  215. if (handler.action === 'showPaymentQR') {
  216. openPaymentUrl(handler.qrCodeUrl, userVars);
  217. console.log(`[执行器] title: ${handler.title}`);
  218. console.log(`[执行器] message: ${handler.message}`);
  219. }
  220. return { success: false, error: 'unauthorized', paymentUrl: resolveTemplate(handler.qrCodeUrl, userVars) };
  221. }
  222. // ─── CLI 入口 ───
  223. async function main() {
  224. const args = process.argv.slice(2);
  225. const skillDir = args.find(a => !a.startsWith('--'));
  226. if (!skillDir) {
  227. console.log('用法: node scripts/skill-executor.js <skill-dir> [--user=xxx] [--apigid=yyy]');
  228. console.log('例: node scripts/skill-executor.js jimeng/jimeng-img-v4 --user=nd7NOCmFiE --apigid=Vo3ROWEvDy');
  229. process.exit(1);
  230. }
  231. // 解析 --key=value 参数
  232. const userVars = {};
  233. args.filter(a => a.startsWith('--')).forEach(a => {
  234. const [key, val] = a.slice(2).split('=');
  235. if (key && val) userVars[key] = val;
  236. });
  237. console.log('╔══════════════════════════════════════════════════════╗');
  238. console.log('║ OpenClaw Skill 执行器 (含计费闭环) ║');
  239. console.log('╚══════════════════════════════════════════════════════╝');
  240. const result = await executeSkillWithBilling(skillDir, {
  241. prompt: '测试',
  242. token: 'Bearer r:f0333969e312a40e4703e8fe4ed1c600'
  243. }, userVars);
  244. console.log('\n[结果]', JSON.stringify(result, null, 2));
  245. }
  246. main().catch(e => {
  247. console.error('执行出错:', e.message);
  248. process.exit(1);
  249. });