skill-executor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 os = require('os');
  19. const path = require('path');
  20. const { exec } = require('child_process');
  21. // ─── 配置 ───
  22. const API_BASE = 'https://server.fmode.cn';
  23. const APP_ID = 'ncloudmaster';
  24. // ─── 1. 加载 Skill 配置 ───
  25. function loadSkillConfig(skillDir) {
  26. const root = path.resolve(__dirname, '..');
  27. const configPath = path.join(root, skillDir, 'api-config.json');
  28. if (!fs.existsSync(configPath)) {
  29. throw new Error(`未找到配置: ${configPath}`);
  30. }
  31. return JSON.parse(fs.readFileSync(configPath, 'utf-8'));
  32. }
  33. // ─── 2. 匹配 errorHandling 条件 ───
  34. function matchesErrorConditions(responseData, errorDef) {
  35. if (!errorDef || !errorDef.conditions) return false;
  36. const results = errorDef.conditions.map(cond => {
  37. const fieldValue = responseData[cond.responseField];
  38. if (fieldValue === undefined || fieldValue === null) return false;
  39. switch (cond.operator) {
  40. case 'in':
  41. return Array.isArray(cond.value) && cond.value.includes(fieldValue);
  42. case 'contains':
  43. if (typeof fieldValue !== 'string') return false;
  44. return Array.isArray(cond.value)
  45. ? cond.value.some(v => fieldValue.toLowerCase().includes(v.toLowerCase()))
  46. : fieldValue.toLowerCase().includes(String(cond.value).toLowerCase());
  47. case 'equals':
  48. return fieldValue === cond.value;
  49. default:
  50. return false;
  51. }
  52. });
  53. // matchMode: "any" = 任一条件匹配即触发; "all" = 全部匹配
  54. const mode = errorDef.matchMode || 'any';
  55. return mode === 'all' ? results.every(Boolean) : results.some(Boolean);
  56. }
  57. // ─── 3. 解析模板变量 ───
  58. function resolveTemplate(template, vars = {}) {
  59. if (typeof template !== 'string') return template;
  60. const doubleBraceResolved = template.replace(/\{\{(\w+)\}\}/g, (_, key) => vars[key] ?? '');
  61. return doubleBraceResolved.replace(/\{(\w+)\}/g, (_, key) => vars[key] ?? '');
  62. }
  63. function expandHome(filePath) {
  64. if (!filePath || typeof filePath !== 'string') return filePath;
  65. if (filePath === '~') return os.homedir();
  66. if (filePath.startsWith('~/') || filePath.startsWith('~\\')) {
  67. return path.join(os.homedir(), filePath.slice(2));
  68. }
  69. return filePath;
  70. }
  71. function resolveTokenFromConfig(tokenConfig) {
  72. if (!tokenConfig) return '';
  73. const resolutionOrder = Array.isArray(tokenConfig.resolutionOrder)
  74. ? tokenConfig.resolutionOrder
  75. : ['configFile', 'currentToken'];
  76. for (const source of resolutionOrder) {
  77. if (source === 'configFile' && tokenConfig.configFile && tokenConfig.tokenField) {
  78. try {
  79. const configPath = expandHome(tokenConfig.configFile);
  80. if (!fs.existsSync(configPath)) continue;
  81. const configData = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
  82. const resolved = configData[tokenConfig.tokenField];
  83. if (resolved) return String(resolved).trim();
  84. } catch (e) {
  85. console.warn('[执行器] 读取 token 配置失败:', e.message);
  86. }
  87. }
  88. if (source === 'currentToken' && tokenConfig.currentToken) {
  89. return String(tokenConfig.currentToken).trim();
  90. }
  91. }
  92. return '';
  93. }
  94. function buildTokenSetupMetadata(tokenConfig) {
  95. const onMissing = tokenConfig?.onMissing || {};
  96. return {
  97. tokenConfigFile: tokenConfig?.configFile || '~/.openclaw/voc-credentials.json',
  98. tokenField: tokenConfig?.tokenField || 'vocToken',
  99. tokenSetupCommandTemplate: onMissing.tokenSetupCommandTemplate || 'node scripts/tools/set-voc-token.js {sessionToken}',
  100. tokenSetupInstructions: onMissing.tokenSetupInstructions || '当用户完成登录和充值后,如果用户把 session token 发给你,请直接运行 node scripts/tools/set-voc-token.js <session-token> 写入 ~/.openclaw/voc-credentials.json,然后重试当前 Skill。'
  101. };
  102. }
  103. async function resolvePaymentUrlFromTokenConfig(tokenConfig, userVars) {
  104. const paymentConfig = tokenConfig?.paymentUrlResolution;
  105. if (!paymentConfig) return '';
  106. const sessionToken = resolveTokenFromConfig(tokenConfig);
  107. if (!sessionToken) return '';
  108. const resolveVars = { ...userVars, vocToken: sessionToken, token: sessionToken };
  109. const headers = {};
  110. for (const [key, value] of Object.entries(paymentConfig.userResolveHeaders || {})) {
  111. headers[key] = resolveTemplate(value, resolveVars);
  112. }
  113. const resp = await fetch(paymentConfig.userResolveEndpoint, { headers });
  114. const data = await resp.json();
  115. if (!resp.ok || !data.objectId) {
  116. throw new Error(data.error || data.message || '无法解析当前用户');
  117. }
  118. const finalVars = { ...resolveVars, resolvedUserId: data.objectId };
  119. const url = new URL(paymentConfig.paymentBaseUrl);
  120. for (const [key, value] of Object.entries(paymentConfig.paymentParams || {})) {
  121. url.searchParams.set(key, resolveTemplate(String(value), finalVars));
  122. }
  123. return url.toString();
  124. }
  125. // ─── 4. 打开充值网址 ───
  126. function openPaymentUrl(qrCodeUrl, vars) {
  127. const url = resolveTemplate(qrCodeUrl, vars);
  128. console.log('\n╔══════════════════════════════════════════════════════╗');
  129. console.log('║ 💰 余额不足,请扫码充值 ║');
  130. console.log('╚══════════════════════════════════════════════════════╝');
  131. console.log(`\n充值网址: ${url}\n`);
  132. // 在系统浏览器中打开
  133. const platform = process.platform;
  134. const cmd = platform === 'win32' ? `start "" "${url}"`
  135. : platform === 'darwin' ? `open "${url}"`
  136. : `xdg-open "${url}"`;
  137. exec(cmd, (err) => {
  138. if (err) console.warn('自动打开浏览器失败,请手动复制上方网址');
  139. });
  140. return url;
  141. }
  142. // ─── 5. 轮询余额 ───
  143. async function pollBalance(authId, oldCount, config) {
  144. const checkEndpoint = config.paymentCheckEndpoint || `${API_BASE}/api/apig/getApig`;
  145. const interval = config.pollingIntervalMs || 3000;
  146. const timeout = config.pollingTimeoutMs || 300000;
  147. const maxAttempts = Math.ceil(timeout / interval);
  148. console.log(`[轮询] 等待充值完成... (每${interval / 1000}秒检查, 最多${maxAttempts}次)`);
  149. for (let i = 1; i <= maxAttempts; i++) {
  150. await new Promise(r => setTimeout(r, interval));
  151. try {
  152. const resp = await fetch(checkEndpoint, {
  153. method: 'POST',
  154. headers: { 'Content-Type': 'application/json' },
  155. body: JSON.stringify({ authid: authId })
  156. });
  157. const data = await resp.json();
  158. if (data.code === 200 && data.data && data.data.count > oldCount) {
  159. console.log(`[轮询] ✅ 充值成功! 余额: ${oldCount} → ${data.data.count}`);
  160. return data.data;
  161. }
  162. console.log(`[轮询] #${i} 余额未变 (${data.data?.count ?? '?'})`);
  163. } catch (e) {
  164. console.warn(`[轮询] #${i} 请求失败:`, e.message);
  165. }
  166. }
  167. console.log('[轮询] ⚠️ 超时,余额未变化');
  168. return null;
  169. }
  170. // ─── 6. 查询 APIGAuth ───
  171. async function getApigAuth(userId, apigId) {
  172. const url = `${API_BASE}/parse/classes/APIGAuth?` + new URLSearchParams({
  173. where: JSON.stringify({
  174. api: { __type: 'Pointer', className: 'APIG', objectId: apigId },
  175. company: { __type: 'Pointer', className: 'Company', objectId: userId }
  176. }),
  177. limit: '1'
  178. });
  179. const resp = await fetch(url, {
  180. headers: { 'X-Parse-Application-Id': APP_ID }
  181. });
  182. const data = await resp.json();
  183. if (data.results && data.results.length > 0) {
  184. return data.results[0];
  185. }
  186. return null;
  187. }
  188. // ─── 7. 核心执行器 ───
  189. async function executeSkillWithBilling(skillDir, inputParams, userVars) {
  190. const config = loadSkillConfig(skillDir);
  191. console.log(`\n[执行器] Skill: ${config.displayName} (${config.name})`);
  192. console.log(`[执行器] 端点: ${config.endpoint.method} ${config.endpoint.url}`);
  193. if (!userVars.apigid && config.tokenConfig?.apigId) {
  194. userVars.apigid = config.tokenConfig.apigId;
  195. }
  196. // Step A: 先查余额(如有 user + apigid)
  197. let authRecord = null;
  198. if (userVars.user && userVars.apigid) {
  199. console.log(`[执行器] 查询用户余额... user=${userVars.user}, apigid=${userVars.apigid}`);
  200. authRecord = await getApigAuth(userVars.user, userVars.apigid);
  201. if (authRecord) {
  202. console.log(`[执行器] APIGAuth: ${authRecord.objectId}, 余额: ${authRecord.count || 0}`);
  203. // 余额为0直接触发充值,不必等API报错
  204. if ((authRecord.count || 0) <= 0) {
  205. console.log('[执行器] 余额为0,直接触发充值流程');
  206. return await handleInsufficientBalance(config, authRecord, userVars);
  207. }
  208. } else {
  209. console.log('[执行器] 未找到 APIGAuth 记录,将在调用后根据响应判断');
  210. }
  211. }
  212. // Step B: 调用 Skill API
  213. console.log(`[执行器] 调用 Skill API...`);
  214. const resp = await fetch(config.endpoint.url, {
  215. method: config.endpoint.method,
  216. headers: config.endpoint.headers,
  217. body: config.endpoint.method === 'GET' ? undefined : JSON.stringify(inputParams)
  218. });
  219. const result = await resp.json();
  220. console.log(`[执行器] 响应 code: ${result.code}, msg: ${result.msg || result.message || ''}`);
  221. // Step C: 检查是否匹配 errorHandling 条件
  222. if (config.errorHandling) {
  223. // 检查: 余额不足
  224. if (config.errorHandling.balanceInsufficient) {
  225. if (matchesErrorConditions(result, config.errorHandling.balanceInsufficient)) {
  226. console.log('[执行器] ⚡ 检测到余额不足!');
  227. return await handleInsufficientBalance(config, authRecord, userVars);
  228. }
  229. }
  230. // 检查: 未授权
  231. if (config.errorHandling.unauthorized) {
  232. if (matchesErrorConditions(result, config.errorHandling.unauthorized)) {
  233. console.log('[执行器] ⚡ 检测到未授权!');
  234. return await handleUnauthorized(config, userVars);
  235. }
  236. }
  237. }
  238. // Step D: 正常返回
  239. console.log('[执行器] ✅ Skill 调用成功');
  240. return { success: true, data: result };
  241. }
  242. // ─── 8. 处理余额不足 ───
  243. async function handleInsufficientBalance(config, authRecord, userVars) {
  244. const tc = config.tokenConfig;
  245. if (!tc || !tc.onBalanceInsufficient) {
  246. console.error('[执行器] ❌ 无 onBalanceInsufficient 配置,无法处理');
  247. return { success: false, error: 'balance_insufficient_no_handler' };
  248. }
  249. const handler = tc.onBalanceInsufficient;
  250. const oldCount = authRecord ? (authRecord.count || 0) : 0;
  251. const authId = authRecord ? authRecord.objectId : null;
  252. if (handler.action === 'showPaymentQR' || handler.action === 'resolveUserThenShowPayment') {
  253. let paymentUrl = '';
  254. if (handler.action === 'resolveUserThenShowPayment') {
  255. try {
  256. paymentUrl = await resolvePaymentUrlFromTokenConfig(tc, { ...userVars, apigid: userVars.apigid || tc.apigId });
  257. } catch (e) {
  258. console.warn('[执行器] 解析专属充值链接失败:', e.message);
  259. }
  260. }
  261. if (!paymentUrl && handler.qrCodeUrl) {
  262. paymentUrl = resolveTemplate(handler.qrCodeUrl, { ...userVars, apigid: userVars.apigid || tc.apigId });
  263. }
  264. if (!paymentUrl && tc.onMissing?.qrCodeUrl) {
  265. paymentUrl = resolveTemplate(tc.onMissing.qrCodeUrl, { ...userVars, apigid: userVars.apigid || tc.apigId });
  266. }
  267. if (!paymentUrl) {
  268. return { success: false, error: 'payment_url_unavailable' };
  269. }
  270. openPaymentUrl(paymentUrl, {});
  271. console.log(`[执行器] title: ${handler.title}`);
  272. console.log(`[执行器] message: ${handler.message}`);
  273. if (!authId) {
  274. console.log('[执行器] 无 authId,无法轮询余额。请手动充值后重试。');
  275. return { success: false, error: 'no_auth_record', paymentUrl };
  276. }
  277. const updated = await pollBalance(authId, oldCount, handler);
  278. if (updated) {
  279. if (handler.onPaymentSuccess === 'retrySkillWithNewToken') {
  280. console.log('[执行器] 🔄 充值成功,准备重试 Skill...');
  281. return { success: true, recharged: true, newBalance: updated.count, action: 'retrySkill' };
  282. }
  283. return { success: true, recharged: true, newBalance: updated.count };
  284. }
  285. return { success: false, error: 'payment_timeout' };
  286. }
  287. return { success: false, error: 'unknown_action', action: handler.action };
  288. }
  289. // ─── 9. 处理未授权 ───
  290. async function handleUnauthorized(config, userVars) {
  291. const tc = config.tokenConfig;
  292. if (!tc || !tc.onMissing) {
  293. console.error('[执行器] ❌ 无 onMissing 配置');
  294. return { success: false, error: 'unauthorized_no_handler' };
  295. }
  296. const handler = tc.onMissing;
  297. let paymentUrl = '';
  298. if (handler.action === 'resolveUserThenShowPayment') {
  299. try {
  300. paymentUrl = await resolvePaymentUrlFromTokenConfig(tc, { ...userVars, apigid: userVars.apigid || tc.apigId });
  301. } catch (e) {
  302. console.warn('[执行器] 解析专属充值链接失败:', e.message);
  303. }
  304. }
  305. if (!paymentUrl && handler.qrCodeUrl) {
  306. paymentUrl = resolveTemplate(handler.qrCodeUrl, { ...userVars, apigid: userVars.apigid || tc.apigId });
  307. }
  308. if (paymentUrl) {
  309. openPaymentUrl(paymentUrl, {});
  310. console.log(`[执行器] title: ${handler.title}`);
  311. console.log(`[执行器] message: ${handler.message}`);
  312. }
  313. return {
  314. success: false,
  315. error: 'unauthorized',
  316. paymentUrl,
  317. ...buildTokenSetupMetadata(tc)
  318. };
  319. }
  320. // ─── CLI 入口 ───
  321. async function main() {
  322. const args = process.argv.slice(2);
  323. const skillDir = args.find(a => !a.startsWith('--'));
  324. if (!skillDir) {
  325. console.log('用法: node scripts/skill-executor.js <skill-dir> [--user=xxx] [--apigid=yyy]');
  326. console.log('例: node scripts/skill-executor.js jimeng/jimeng-img-v4 --user=nd7NOCmFiE --apigid=Vo3ROWEvDy');
  327. process.exit(1);
  328. }
  329. // 解析 --key=value 参数
  330. const userVars = {};
  331. args.filter(a => a.startsWith('--')).forEach(a => {
  332. const [key, val] = a.slice(2).split('=');
  333. if (key && val) userVars[key] = val;
  334. });
  335. console.log('╔══════════════════════════════════════════════════════╗');
  336. console.log('║ OpenClaw Skill 执行器 (含计费闭环) ║');
  337. console.log('╚══════════════════════════════════════════════════════╝');
  338. const result = await executeSkillWithBilling(skillDir, {
  339. prompt: '测试'
  340. }, userVars);
  341. console.log('\n[结果]', JSON.stringify(result, null, 2));
  342. }
  343. main().catch(e => {
  344. console.error('执行出错:', e.message);
  345. process.exit(1);
  346. });