skill-executor.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. // 支持三种占位语法:${var}、{{var}}、{var}
  61. const dollarResolved = template.replace(/\$\{(\w+)\}/g, (_, key) => vars[key] ?? '');
  62. const doubleBraceResolved = dollarResolved.replace(/\{\{(\w+)\}\}/g, (_, key) => vars[key] ?? '');
  63. return doubleBraceResolved.replace(/\{(\w+)\}/g, (_, key) => vars[key] ?? '');
  64. }
  65. // 深拷贝并对所有字符串字段做模板替换
  66. function resolveTemplateDeep(obj, vars = {}) {
  67. if (obj === null || obj === undefined) return obj;
  68. if (typeof obj === 'string') return resolveTemplate(obj, vars);
  69. if (Array.isArray(obj)) return obj.map(v => resolveTemplateDeep(v, vars));
  70. if (typeof obj === 'object') {
  71. const out = {};
  72. for (const [k, v] of Object.entries(obj)) out[k] = resolveTemplateDeep(v, vars);
  73. return out;
  74. }
  75. return obj;
  76. }
  77. function expandHome(filePath) {
  78. if (!filePath || typeof filePath !== 'string') return filePath;
  79. if (filePath === '~') return os.homedir();
  80. if (filePath.startsWith('~/') || filePath.startsWith('~\\')) {
  81. return path.join(os.homedir(), filePath.slice(2));
  82. }
  83. return filePath;
  84. }
  85. function resolveTokenFromConfig(tokenConfig) {
  86. if (!tokenConfig) return '';
  87. const resolutionOrder = Array.isArray(tokenConfig.resolutionOrder)
  88. ? tokenConfig.resolutionOrder
  89. : ['configFile', 'currentToken'];
  90. for (const source of resolutionOrder) {
  91. if (source === 'configFile' && tokenConfig.configFile && tokenConfig.tokenField) {
  92. try {
  93. const configPath = expandHome(tokenConfig.configFile);
  94. if (!fs.existsSync(configPath)) continue;
  95. const configData = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
  96. const resolved = configData[tokenConfig.tokenField];
  97. if (resolved) return String(resolved).trim();
  98. } catch (e) {
  99. console.warn('[执行器] 读取 token 配置失败:', e.message);
  100. }
  101. }
  102. if (source === 'currentToken' && tokenConfig.currentToken) {
  103. return String(tokenConfig.currentToken).trim();
  104. }
  105. }
  106. return '';
  107. }
  108. function buildTokenSetupMetadata(tokenConfig) {
  109. const onMissing = tokenConfig?.onMissing || {};
  110. return {
  111. tokenConfigFile: tokenConfig?.configFile || '~/.openclaw/voc-credentials.json',
  112. tokenField: tokenConfig?.tokenField || 'vocToken',
  113. tokenSetupCommandTemplate: onMissing.tokenSetupCommandTemplate || 'node ~/.openclaw/tools/set-voc-token.js {sessionToken}',
  114. tokenSetupInstructions: onMissing.tokenSetupInstructions || '当用户完成登录和充值后,如果用户把 session token 发给你,请直接运行 node ~/.openclaw/tools/set-voc-token.js <session-token> 写入 ~/.openclaw/voc-credentials.json,然后重试当前 Skill。'
  115. };
  116. }
  117. async function resolvePaymentUrlFromTokenConfig(tokenConfig, userVars) {
  118. const paymentConfig = tokenConfig?.paymentUrlResolution;
  119. if (!paymentConfig) return '';
  120. const sessionToken = resolveTokenFromConfig(tokenConfig);
  121. if (!sessionToken) return '';
  122. const resolveVars = { ...userVars, vocToken: sessionToken, token: sessionToken };
  123. const headers = {};
  124. for (const [key, value] of Object.entries(paymentConfig.userResolveHeaders || {})) {
  125. headers[key] = resolveTemplate(value, resolveVars);
  126. }
  127. const resp = await fetch(paymentConfig.userResolveEndpoint, { headers });
  128. const data = await resp.json();
  129. if (!resp.ok || !data.objectId) {
  130. throw new Error(data.error || data.message || '无法解析当前用户');
  131. }
  132. const finalVars = { ...resolveVars, resolvedUserId: data.objectId };
  133. const url = new URL(paymentConfig.paymentBaseUrl);
  134. for (const [key, value] of Object.entries(paymentConfig.paymentParams || {})) {
  135. url.searchParams.set(key, resolveTemplate(String(value), finalVars));
  136. }
  137. return url.toString();
  138. }
  139. // ─── 4. 打开充值网址 ───
  140. function openPaymentUrl(qrCodeUrl, vars) {
  141. const url = resolveTemplate(qrCodeUrl, vars);
  142. console.log('\n╔══════════════════════════════════════════════════════╗');
  143. console.log('║ 💰 余额不足,请扫码充值 ║');
  144. console.log('╚══════════════════════════════════════════════════════╝');
  145. console.log(`\n充值网址: ${url}\n`);
  146. // 在系统浏览器中打开
  147. const platform = process.platform;
  148. const cmd = platform === 'win32' ? `start "" "${url}"`
  149. : platform === 'darwin' ? `open "${url}"`
  150. : `xdg-open "${url}"`;
  151. exec(cmd, (err) => {
  152. if (err) console.warn('自动打开浏览器失败,请手动复制上方网址');
  153. });
  154. return url;
  155. }
  156. // ─── 5. 轮询余额 ───
  157. async function pollBalance(authId, oldCount, config, sessionToken) {
  158. const checkEndpoint = config.paymentCheckEndpoint || `${API_BASE}/api/apig/getApig`;
  159. const interval = config.pollingIntervalMs || 3000;
  160. const timeout = config.pollingTimeoutMs || 300000;
  161. const maxAttempts = Math.ceil(timeout / interval);
  162. console.log(`[轮询] 等待充值完成... (每${interval / 1000}秒检查, 最多${maxAttempts}次)`);
  163. const headers = { 'Content-Type': 'application/json' };
  164. if (sessionToken) headers['X-Parse-Session-Token'] = sessionToken;
  165. for (let i = 1; i <= maxAttempts; i++) {
  166. await new Promise(r => setTimeout(r, interval));
  167. try {
  168. const resp = await fetch(checkEndpoint, {
  169. method: 'POST',
  170. headers,
  171. body: JSON.stringify({ authid: authId })
  172. });
  173. const data = await resp.json();
  174. if (data.code === 200 && data.data && data.data.count > oldCount) {
  175. console.log(`[轮询] ✅ 充值成功! 余额: ${oldCount} → ${data.data.count}`);
  176. return data.data;
  177. }
  178. console.log(`[轮询] #${i} 余额未变 (${data.data?.count ?? '?'})`);
  179. } catch (e) {
  180. console.warn(`[轮询] #${i} 请求失败:`, e.message);
  181. }
  182. }
  183. console.log('[轮询] ⚠️ 超时,余额未变化');
  184. return null;
  185. }
  186. // ─── 6. 查询 APIGAuth ───
  187. // 按 user 指针查(后端扣费只认 user + api,不要求 Company)
  188. async function getApigAuth(userId, apigId, sessionToken) {
  189. const url = `${API_BASE}/parse/classes/APIGAuth?` + new URLSearchParams({
  190. where: JSON.stringify({
  191. api: { __type: 'Pointer', className: 'APIG', objectId: apigId },
  192. user: { __type: 'Pointer', className: '_User', objectId: userId }
  193. }),
  194. limit: '1'
  195. });
  196. const headers = { 'X-Parse-Application-Id': APP_ID };
  197. if (sessionToken) headers['X-Parse-Session-Token'] = sessionToken;
  198. const resp = await fetch(url, { headers });
  199. const data = await resp.json();
  200. if (data.results && data.results.length > 0) {
  201. return data.results[0];
  202. }
  203. return null;
  204. }
  205. // ─── 7. 核心执行器 ───
  206. async function executeSkillWithBilling(skillDir, inputParams, userVars) {
  207. const config = loadSkillConfig(skillDir);
  208. console.log(`\n[执行器] Skill: ${config.displayName} (${config.name})`);
  209. console.log(`[执行器] 端点: ${config.endpoint.method} ${config.endpoint.url}`);
  210. if (!userVars.apigid && config.tokenConfig?.apigId) {
  211. userVars.apigid = config.tokenConfig.apigId;
  212. }
  213. // Step A: 先查余额(如有 user + apigid,带上 session token 以通过 ACL)
  214. let authRecord = null;
  215. const sessionToken = resolveTokenFromConfig(config.tokenConfig);
  216. if (userVars.user && userVars.apigid) {
  217. console.log(`[执行器] 查询用户余额... user=${userVars.user}, apigid=${userVars.apigid}`);
  218. authRecord = await getApigAuth(userVars.user, userVars.apigid, sessionToken);
  219. if (authRecord) {
  220. console.log(`[执行器] APIGAuth: ${authRecord.objectId}, 余额: ${authRecord.count || 0}`);
  221. // 余额为0直接触发充值,不必等API报错
  222. if ((authRecord.count || 0) <= 0) {
  223. console.log('[执行器] 余额为0,直接触发充值流程');
  224. return await handleInsufficientBalance(config, authRecord, userVars);
  225. }
  226. } else {
  227. console.log('[执行器] 未找到 APIGAuth 记录,将在调用后根据响应判断');
  228. }
  229. }
  230. // Step B: 调用 Skill API(注入 vocToken 并做模板替换)
  231. console.log(`[执行器] 调用 Skill API...`);
  232. // 模板变量池:vocToken 是权威名;TIKHUB_TOKEN/token/sessionToken 作别名兼容存量配置
  233. const templateVars = {
  234. ...userVars,
  235. ...inputParams,
  236. vocToken: sessionToken,
  237. TIKHUB_TOKEN: sessionToken,
  238. token: sessionToken,
  239. sessionToken: sessionToken
  240. };
  241. const resolvedUrl = resolveTemplate(config.endpoint.url, templateVars);
  242. const resolvedHeaders = resolveTemplateDeep(config.endpoint.headers || {}, templateVars);
  243. const resolvedQuery = resolveTemplateDeep(config.endpoint.queryParams || {}, templateVars);
  244. const resolvedBody = resolveTemplateDeep(config.endpoint.body || inputParams || {}, templateVars);
  245. // 兜底:如果配置里完全没指定鉴权头,但已有 token,自动加上 Authorization: Bearer
  246. if (sessionToken && !resolvedHeaders.Authorization && !resolvedHeaders.authorization) {
  247. resolvedHeaders.Authorization = `Bearer ${sessionToken}`;
  248. }
  249. // 拼接 queryString
  250. let finalUrl = resolvedUrl;
  251. const qsEntries = Object.entries(resolvedQuery).filter(([, v]) => v !== undefined && v !== '');
  252. if (qsEntries.length > 0) {
  253. const qs = new URLSearchParams();
  254. qsEntries.forEach(([k, v]) => qs.append(k, String(v)));
  255. finalUrl += (finalUrl.includes('?') ? '&' : '?') + qs.toString();
  256. }
  257. const method = (config.endpoint.method || 'GET').toUpperCase();
  258. console.log(`[执行器] → ${method} ${finalUrl}`);
  259. console.log(`[执行器] Authorization: ${resolvedHeaders.Authorization ? 'Bearer ' + sessionToken.slice(0, 6) + '...' + sessionToken.slice(-4) : '(无)'}`);
  260. const resp = await fetch(finalUrl, {
  261. method,
  262. headers: resolvedHeaders,
  263. body: method === 'GET' || method === 'HEAD' ? undefined : JSON.stringify(resolvedBody)
  264. });
  265. const result = await resp.json();
  266. console.log(`[执行器] 响应 HTTP ${resp.status}, code: ${result.code}, msg: ${result.msg || result.message || ''}`);
  267. // Step C: 检查是否匹配 errorHandling 条件
  268. if (config.errorHandling) {
  269. // 检查: 余额不足
  270. if (config.errorHandling.balanceInsufficient) {
  271. if (matchesErrorConditions(result, config.errorHandling.balanceInsufficient)) {
  272. console.log('[执行器] ⚡ 检测到余额不足!');
  273. return await handleInsufficientBalance(config, authRecord, userVars);
  274. }
  275. }
  276. // 检查: 未授权
  277. if (config.errorHandling.unauthorized) {
  278. if (matchesErrorConditions(result, config.errorHandling.unauthorized)) {
  279. console.log('[执行器] ⚡ 检测到未授权!');
  280. return await handleUnauthorized(config, userVars);
  281. }
  282. }
  283. }
  284. // Step D: 正常返回
  285. console.log('[执行器] ✅ Skill 调用成功');
  286. return { success: true, data: result };
  287. }
  288. // ─── 8. 处理余额不足 ───
  289. async function handleInsufficientBalance(config, authRecord, userVars) {
  290. const tc = config.tokenConfig;
  291. if (!tc || !tc.onBalanceInsufficient) {
  292. console.error('[执行器] ❌ 无 onBalanceInsufficient 配置,无法处理');
  293. return { success: false, error: 'balance_insufficient_no_handler' };
  294. }
  295. const handler = tc.onBalanceInsufficient;
  296. const oldCount = authRecord ? (authRecord.count || 0) : 0;
  297. const authId = authRecord ? authRecord.objectId : null;
  298. if (handler.action === 'showPaymentQR' || handler.action === 'resolveUserThenShowPayment') {
  299. let paymentUrl = '';
  300. if (handler.action === 'resolveUserThenShowPayment') {
  301. try {
  302. paymentUrl = await resolvePaymentUrlFromTokenConfig(tc, { ...userVars, apigid: userVars.apigid || tc.apigId });
  303. } catch (e) {
  304. console.warn('[执行器] 解析专属充值链接失败:', e.message);
  305. }
  306. }
  307. if (!paymentUrl && handler.qrCodeUrl) {
  308. paymentUrl = resolveTemplate(handler.qrCodeUrl, { ...userVars, apigid: userVars.apigid || tc.apigId });
  309. }
  310. if (!paymentUrl && tc.onMissing?.qrCodeUrl) {
  311. paymentUrl = resolveTemplate(tc.onMissing.qrCodeUrl, { ...userVars, apigid: userVars.apigid || tc.apigId });
  312. }
  313. if (!paymentUrl) {
  314. return { success: false, error: 'payment_url_unavailable' };
  315. }
  316. openPaymentUrl(paymentUrl, {});
  317. console.log(`[执行器] title: ${handler.title}`);
  318. console.log(`[执行器] message: ${handler.message}`);
  319. if (!authId) {
  320. console.log('[执行器] 无 authId,无法轮询余额。请手动充值后重试。');
  321. return { success: false, error: 'no_auth_record', paymentUrl };
  322. }
  323. const updated = await pollBalance(authId, oldCount, handler, resolveTokenFromConfig(tc));
  324. if (updated) {
  325. if (handler.onPaymentSuccess === 'retrySkillWithNewToken') {
  326. console.log('[执行器] 🔄 充值成功,准备重试 Skill...');
  327. return { success: true, recharged: true, newBalance: updated.count, action: 'retrySkill' };
  328. }
  329. return { success: true, recharged: true, newBalance: updated.count };
  330. }
  331. return { success: false, error: 'payment_timeout' };
  332. }
  333. return { success: false, error: 'unknown_action', action: handler.action };
  334. }
  335. // ─── 9. 处理未授权 ───
  336. async function handleUnauthorized(config, userVars) {
  337. const tc = config.tokenConfig;
  338. if (!tc || !tc.onMissing) {
  339. console.error('[执行器] ❌ 无 onMissing 配置');
  340. return { success: false, error: 'unauthorized_no_handler' };
  341. }
  342. const handler = tc.onMissing;
  343. let paymentUrl = '';
  344. if (handler.action === 'resolveUserThenShowPayment') {
  345. try {
  346. paymentUrl = await resolvePaymentUrlFromTokenConfig(tc, { ...userVars, apigid: userVars.apigid || tc.apigId });
  347. } catch (e) {
  348. console.warn('[执行器] 解析专属充值链接失败:', e.message);
  349. }
  350. }
  351. if (!paymentUrl && handler.qrCodeUrl) {
  352. paymentUrl = resolveTemplate(handler.qrCodeUrl, { ...userVars, apigid: userVars.apigid || tc.apigId });
  353. }
  354. if (paymentUrl) {
  355. openPaymentUrl(paymentUrl, {});
  356. console.log(`[执行器] title: ${handler.title}`);
  357. console.log(`[执行器] message: ${handler.message}`);
  358. }
  359. return {
  360. success: false,
  361. error: 'unauthorized',
  362. paymentUrl,
  363. ...buildTokenSetupMetadata(tc)
  364. };
  365. }
  366. // ─── CLI 入口 ───
  367. async function main() {
  368. const args = process.argv.slice(2);
  369. const skillDir = args.find(a => !a.startsWith('--'));
  370. if (!skillDir) {
  371. console.log('用法: node scripts/skill-executor.js <skill-dir> [--user=xxx] [--apigid=yyy]');
  372. console.log('例: node scripts/skill-executor.js jimeng/jimeng-img-v4 --user=nd7NOCmFiE --apigid=Vo3ROWEvDy');
  373. process.exit(1);
  374. }
  375. // 解析 --key=value 参数
  376. const userVars = {};
  377. args.filter(a => a.startsWith('--')).forEach(a => {
  378. const [key, val] = a.slice(2).split('=');
  379. if (key && val) userVars[key] = val;
  380. });
  381. console.log('╔══════════════════════════════════════════════════════╗');
  382. console.log('║ OpenClaw Skill 执行器 (含计费闭环) ║');
  383. console.log('╚══════════════════════════════════════════════════════╝');
  384. const result = await executeSkillWithBilling(skillDir, {
  385. prompt: '测试'
  386. }, userVars);
  387. console.log('\n[结果]', JSON.stringify(result, null, 2));
  388. }
  389. main().catch(e => {
  390. console.error('执行出错:', e.message);
  391. process.exit(1);
  392. });