/** * OpenClaw Skill 执行器 — 含余额不足检测 + 弹出充值网址逻辑 * * 流程: * 1. 读取 api-config.json * 2. 解析 tokenConfig,获取 token * 3. 调用 Skill API * 4. 检查响应是否匹配 errorHandling 条件 * 5. 如果余额不足 → 打开充值网址(qrCodeUrl) * 6. 轮询余额变化 * 7. 充值成功后重试 Skill * * 用法: * node scripts/skill-executor.js [--user=xxx] [--apigid=yyy] * 例: node scripts/skill-executor.js jimeng/jimeng-img-v4 --user=nd7NOCmFiE --apigid=Vo3ROWEvDy */ const fs = require('fs'); const path = require('path'); const { exec } = require('child_process'); // ─── 配置 ─── const API_BASE = 'https://server.fmode.cn'; const APP_ID = 'ncloudmaster'; // ─── 1. 加载 Skill 配置 ─── function loadSkillConfig(skillDir) { const root = path.resolve(__dirname, '..'); const configPath = path.join(root, skillDir, 'api-config.json'); if (!fs.existsSync(configPath)) { throw new Error(`未找到配置: ${configPath}`); } return JSON.parse(fs.readFileSync(configPath, 'utf-8')); } // ─── 2. 匹配 errorHandling 条件 ─── function matchesErrorConditions(responseData, errorDef) { if (!errorDef || !errorDef.conditions) return false; const results = errorDef.conditions.map(cond => { const fieldValue = responseData[cond.responseField]; if (fieldValue === undefined || fieldValue === null) return false; switch (cond.operator) { case 'in': return Array.isArray(cond.value) && cond.value.includes(fieldValue); case 'contains': if (typeof fieldValue !== 'string') return false; return Array.isArray(cond.value) ? cond.value.some(v => fieldValue.toLowerCase().includes(v.toLowerCase())) : fieldValue.toLowerCase().includes(String(cond.value).toLowerCase()); case 'equals': return fieldValue === cond.value; default: return false; } }); // matchMode: "any" = 任一条件匹配即触发; "all" = 全部匹配 const mode = errorDef.matchMode || 'any'; return mode === 'all' ? results.every(Boolean) : results.some(Boolean); } // ─── 3. 解析模板变量 ─── function resolveTemplate(template, vars) { return template.replace(/\{\{(\w+)\}\}/g, (_, key) => vars[key] || ''); } // ─── 4. 打开充值网址 ─── function openPaymentUrl(qrCodeUrl, vars) { const url = resolveTemplate(qrCodeUrl, vars); console.log('\n╔══════════════════════════════════════════════════════╗'); console.log('║ 💰 余额不足,请扫码充值 ║'); console.log('╚══════════════════════════════════════════════════════╝'); console.log(`\n充值网址: ${url}\n`); // 在系统浏览器中打开 const platform = process.platform; const cmd = platform === 'win32' ? `start "" "${url}"` : platform === 'darwin' ? `open "${url}"` : `xdg-open "${url}"`; exec(cmd, (err) => { if (err) console.warn('自动打开浏览器失败,请手动复制上方网址'); }); return url; } // ─── 5. 轮询余额 ─── async function pollBalance(authId, oldCount, config) { const checkEndpoint = config.paymentCheckEndpoint || `${API_BASE}/api/apig/getApig`; const interval = config.pollingIntervalMs || 3000; const timeout = config.pollingTimeoutMs || 300000; const maxAttempts = Math.ceil(timeout / interval); console.log(`[轮询] 等待充值完成... (每${interval / 1000}秒检查, 最多${maxAttempts}次)`); for (let i = 1; i <= maxAttempts; i++) { await new Promise(r => setTimeout(r, interval)); try { const resp = await fetch(checkEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ authid: authId }) }); const data = await resp.json(); if (data.code === 200 && data.data && data.data.count > oldCount) { console.log(`[轮询] ✅ 充值成功! 余额: ${oldCount} → ${data.data.count}`); return data.data; } console.log(`[轮询] #${i} 余额未变 (${data.data?.count ?? '?'})`); } catch (e) { console.warn(`[轮询] #${i} 请求失败:`, e.message); } } console.log('[轮询] ⚠️ 超时,余额未变化'); return null; } // ─── 6. 查询 APIGAuth ─── async function getApigAuth(userId, apigId) { const url = `${API_BASE}/parse/classes/APIGAuth?` + new URLSearchParams({ where: JSON.stringify({ api: { __type: 'Pointer', className: 'APIG', objectId: apigId }, company: { __type: 'Pointer', className: 'Company', objectId: userId } }), limit: '1' }); const resp = await fetch(url, { headers: { 'X-Parse-Application-Id': APP_ID } }); const data = await resp.json(); if (data.results && data.results.length > 0) { return data.results[0]; } return null; } // ─── 7. 核心执行器 ─── async function executeSkillWithBilling(skillDir, inputParams, userVars) { const config = loadSkillConfig(skillDir); console.log(`\n[执行器] Skill: ${config.displayName} (${config.name})`); console.log(`[执行器] 端点: ${config.endpoint.method} ${config.endpoint.url}`); // Step A: 先查余额(如有 user + apigid) let authRecord = null; if (userVars.user && userVars.apigid) { console.log(`[执行器] 查询用户余额... user=${userVars.user}, apigid=${userVars.apigid}`); authRecord = await getApigAuth(userVars.user, userVars.apigid); if (authRecord) { console.log(`[执行器] APIGAuth: ${authRecord.objectId}, 余额: ${authRecord.count || 0}`); // 余额为0直接触发充值,不必等API报错 if ((authRecord.count || 0) <= 0) { console.log('[执行器] 余额为0,直接触发充值流程'); return await handleInsufficientBalance(config, authRecord, userVars); } } else { console.log('[执行器] 未找到 APIGAuth 记录,将在调用后根据响应判断'); } } // Step B: 调用 Skill API console.log(`[执行器] 调用 Skill API...`); const resp = await fetch(config.endpoint.url, { method: config.endpoint.method, headers: config.endpoint.headers, body: config.endpoint.method === 'GET' ? undefined : JSON.stringify(inputParams) }); const result = await resp.json(); console.log(`[执行器] 响应 code: ${result.code}, msg: ${result.msg || result.message || ''}`); // Step C: 检查是否匹配 errorHandling 条件 if (config.errorHandling) { // 检查: 余额不足 if (config.errorHandling.balanceInsufficient) { if (matchesErrorConditions(result, config.errorHandling.balanceInsufficient)) { console.log('[执行器] ⚡ 检测到余额不足!'); return await handleInsufficientBalance(config, authRecord, userVars); } } // 检查: 未授权 if (config.errorHandling.unauthorized) { if (matchesErrorConditions(result, config.errorHandling.unauthorized)) { console.log('[执行器] ⚡ 检测到未授权!'); return await handleUnauthorized(config, userVars); } } } // Step D: 正常返回 console.log('[执行器] ✅ Skill 调用成功'); return { success: true, data: result }; } // ─── 8. 处理余额不足 ─── async function handleInsufficientBalance(config, authRecord, userVars) { const tc = config.tokenConfig; if (!tc || !tc.onBalanceInsufficient) { console.error('[执行器] ❌ 无 onBalanceInsufficient 配置,无法处理'); return { success: false, error: 'balance_insufficient_no_handler' }; } const handler = tc.onBalanceInsufficient; const oldCount = authRecord ? (authRecord.count || 0) : 0; const authId = authRecord ? authRecord.objectId : null; if (handler.action === 'showPaymentQR') { // 打开充值网址 openPaymentUrl(handler.qrCodeUrl, userVars); console.log(`[执行器] title: ${handler.title}`); console.log(`[执行器] message: ${handler.message}`); if (!authId) { console.log('[执行器] 无 authId,无法轮询余额。请手动充值后重试。'); return { success: false, error: 'no_auth_record', paymentUrl: resolveTemplate(handler.qrCodeUrl, userVars) }; } // 轮询等待充值 const updated = await pollBalance(authId, oldCount, handler); if (updated) { // 充值成功 → 重试 Skill if (handler.onPaymentSuccess === 'retrySkillWithNewToken') { console.log('[执行器] 🔄 充值成功,准备重试 Skill...'); return { success: true, recharged: true, newBalance: updated.count, action: 'retrySkill' }; } return { success: true, recharged: true, newBalance: updated.count }; } return { success: false, error: 'payment_timeout' }; } return { success: false, error: 'unknown_action', action: handler.action }; } // ─── 9. 处理未授权 ─── async function handleUnauthorized(config, userVars) { const tc = config.tokenConfig; if (!tc || !tc.onMissing) { console.error('[执行器] ❌ 无 onMissing 配置'); return { success: false, error: 'unauthorized_no_handler' }; } const handler = tc.onMissing; if (handler.action === 'showPaymentQR') { openPaymentUrl(handler.qrCodeUrl, userVars); console.log(`[执行器] title: ${handler.title}`); console.log(`[执行器] message: ${handler.message}`); } return { success: false, error: 'unauthorized', paymentUrl: resolveTemplate(handler.qrCodeUrl, userVars) }; } // ─── CLI 入口 ─── async function main() { const args = process.argv.slice(2); const skillDir = args.find(a => !a.startsWith('--')); if (!skillDir) { console.log('用法: node scripts/skill-executor.js [--user=xxx] [--apigid=yyy]'); console.log('例: node scripts/skill-executor.js jimeng/jimeng-img-v4 --user=nd7NOCmFiE --apigid=Vo3ROWEvDy'); process.exit(1); } // 解析 --key=value 参数 const userVars = {}; args.filter(a => a.startsWith('--')).forEach(a => { const [key, val] = a.slice(2).split('='); if (key && val) userVars[key] = val; }); console.log('╔══════════════════════════════════════════════════════╗'); console.log('║ OpenClaw Skill 执行器 (含计费闭环) ║'); console.log('╚══════════════════════════════════════════════════════╝'); const result = await executeSkillWithBilling(skillDir, { prompt: '测试', token: 'Bearer r:f0333969e312a40e4703e8fe4ed1c600' }, userVars); console.log('\n[结果]', JSON.stringify(result, null, 2)); } main().catch(e => { console.error('执行出错:', e.message); process.exit(1); });