| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464 |
- /**
- * OpenClaw Skill 执行器 — 含余额不足检测 + 弹出充值网址逻辑
- *
- * 流程:
- * 1. 读取 api-config.json
- * 2. 解析 tokenConfig,获取 token
- * 3. 调用 Skill API
- * 4. 检查响应是否匹配 errorHandling 条件
- * 5. 如果余额不足 → 打开充值网址(qrCodeUrl)
- * 6. 轮询余额变化
- * 7. 充值成功后重试 Skill
- *
- * 用法:
- * node scripts/skill-executor.js <skill-dir> [--user=xxx] [--apigid=yyy]
- * 例: node scripts/skill-executor.js jimeng/jimeng-img-v4 --user=nd7NOCmFiE --apigid=Vo3ROWEvDy
- */
- const fs = require('fs');
- const os = require('os');
- 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 = {}) {
- if (typeof template !== 'string') return template;
- // 支持三种占位语法:${var}、{{var}}、{var}
- const dollarResolved = template.replace(/\$\{(\w+)\}/g, (_, key) => vars[key] ?? '');
- const doubleBraceResolved = dollarResolved.replace(/\{\{(\w+)\}\}/g, (_, key) => vars[key] ?? '');
- return doubleBraceResolved.replace(/\{(\w+)\}/g, (_, key) => vars[key] ?? '');
- }
- // 深拷贝并对所有字符串字段做模板替换
- function resolveTemplateDeep(obj, vars = {}) {
- if (obj === null || obj === undefined) return obj;
- if (typeof obj === 'string') return resolveTemplate(obj, vars);
- if (Array.isArray(obj)) return obj.map(v => resolveTemplateDeep(v, vars));
- if (typeof obj === 'object') {
- const out = {};
- for (const [k, v] of Object.entries(obj)) out[k] = resolveTemplateDeep(v, vars);
- return out;
- }
- return obj;
- }
- function expandHome(filePath) {
- if (!filePath || typeof filePath !== 'string') return filePath;
- if (filePath === '~') return os.homedir();
- if (filePath.startsWith('~/') || filePath.startsWith('~\\')) {
- return path.join(os.homedir(), filePath.slice(2));
- }
- return filePath;
- }
- function resolveTokenFromConfig(tokenConfig) {
- if (!tokenConfig) return '';
- const resolutionOrder = Array.isArray(tokenConfig.resolutionOrder)
- ? tokenConfig.resolutionOrder
- : ['configFile', 'currentToken'];
- for (const source of resolutionOrder) {
- if (source === 'configFile' && tokenConfig.configFile && tokenConfig.tokenField) {
- try {
- const configPath = expandHome(tokenConfig.configFile);
- if (!fs.existsSync(configPath)) continue;
- const configData = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
- const resolved = configData[tokenConfig.tokenField];
- if (resolved) return String(resolved).trim();
- } catch (e) {
- console.warn('[执行器] 读取 token 配置失败:', e.message);
- }
- }
- if (source === 'currentToken' && tokenConfig.currentToken) {
- return String(tokenConfig.currentToken).trim();
- }
- }
- return '';
- }
- function buildTokenSetupMetadata(tokenConfig) {
- const onMissing = tokenConfig?.onMissing || {};
- return {
- tokenConfigFile: tokenConfig?.configFile || '~/.openclaw/voc-credentials.json',
- tokenField: tokenConfig?.tokenField || 'vocToken',
- tokenSetupCommandTemplate: onMissing.tokenSetupCommandTemplate || 'node ~/.openclaw/tools/set-voc-token.js {sessionToken}',
- tokenSetupInstructions: onMissing.tokenSetupInstructions || '当用户完成登录和充值后,如果用户把 session token 发给你,请直接运行 node ~/.openclaw/tools/set-voc-token.js <session-token> 写入 ~/.openclaw/voc-credentials.json,然后重试当前 Skill。'
- };
- }
- async function resolvePaymentUrlFromTokenConfig(tokenConfig, userVars) {
- const paymentConfig = tokenConfig?.paymentUrlResolution;
- if (!paymentConfig) return '';
- const sessionToken = resolveTokenFromConfig(tokenConfig);
- if (!sessionToken) return '';
- const resolveVars = { ...userVars, vocToken: sessionToken, token: sessionToken };
- const headers = {};
- for (const [key, value] of Object.entries(paymentConfig.userResolveHeaders || {})) {
- headers[key] = resolveTemplate(value, resolveVars);
- }
- const resp = await fetch(paymentConfig.userResolveEndpoint, { headers });
- const data = await resp.json();
- if (!resp.ok || !data.objectId) {
- throw new Error(data.error || data.message || '无法解析当前用户');
- }
- const finalVars = { ...resolveVars, resolvedUserId: data.objectId };
- const url = new URL(paymentConfig.paymentBaseUrl);
- for (const [key, value] of Object.entries(paymentConfig.paymentParams || {})) {
- url.searchParams.set(key, resolveTemplate(String(value), finalVars));
- }
- return url.toString();
- }
- // ─── 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, sessionToken) {
- 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}次)`);
- const headers = { 'Content-Type': 'application/json' };
- if (sessionToken) headers['X-Parse-Session-Token'] = sessionToken;
- for (let i = 1; i <= maxAttempts; i++) {
- await new Promise(r => setTimeout(r, interval));
- try {
- const resp = await fetch(checkEndpoint, {
- method: 'POST',
- headers,
- 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 ───
- // 按 user 指针查(后端扣费只认 user + api,不要求 Company)
- async function getApigAuth(userId, apigId, sessionToken) {
- const url = `${API_BASE}/parse/classes/APIGAuth?` + new URLSearchParams({
- where: JSON.stringify({
- api: { __type: 'Pointer', className: 'APIG', objectId: apigId },
- user: { __type: 'Pointer', className: '_User', objectId: userId }
- }),
- limit: '1'
- });
- const headers = { 'X-Parse-Application-Id': APP_ID };
- if (sessionToken) headers['X-Parse-Session-Token'] = sessionToken;
- const resp = await fetch(url, { headers });
- 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}`);
- if (!userVars.apigid && config.tokenConfig?.apigId) {
- userVars.apigid = config.tokenConfig.apigId;
- }
- // Step A: 先查余额(如有 user + apigid,带上 session token 以通过 ACL)
- let authRecord = null;
- const sessionToken = resolveTokenFromConfig(config.tokenConfig);
- if (userVars.user && userVars.apigid) {
- console.log(`[执行器] 查询用户余额... user=${userVars.user}, apigid=${userVars.apigid}`);
- authRecord = await getApigAuth(userVars.user, userVars.apigid, sessionToken);
- 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(注入 vocToken 并做模板替换)
- console.log(`[执行器] 调用 Skill API...`);
- // 模板变量池:vocToken 是权威名;TIKHUB_TOKEN/token/sessionToken 作别名兼容存量配置
- const templateVars = {
- ...userVars,
- ...inputParams,
- vocToken: sessionToken,
- TIKHUB_TOKEN: sessionToken,
- token: sessionToken,
- sessionToken: sessionToken
- };
- const resolvedUrl = resolveTemplate(config.endpoint.url, templateVars);
- const resolvedHeaders = resolveTemplateDeep(config.endpoint.headers || {}, templateVars);
- const resolvedQuery = resolveTemplateDeep(config.endpoint.queryParams || {}, templateVars);
- const resolvedBody = resolveTemplateDeep(config.endpoint.body || inputParams || {}, templateVars);
- // 兜底:如果配置里完全没指定鉴权头,但已有 token,自动加上 Authorization: Bearer
- if (sessionToken && !resolvedHeaders.Authorization && !resolvedHeaders.authorization) {
- resolvedHeaders.Authorization = `Bearer ${sessionToken}`;
- }
- // 拼接 queryString
- let finalUrl = resolvedUrl;
- const qsEntries = Object.entries(resolvedQuery).filter(([, v]) => v !== undefined && v !== '');
- if (qsEntries.length > 0) {
- const qs = new URLSearchParams();
- qsEntries.forEach(([k, v]) => qs.append(k, String(v)));
- finalUrl += (finalUrl.includes('?') ? '&' : '?') + qs.toString();
- }
- const method = (config.endpoint.method || 'GET').toUpperCase();
- console.log(`[执行器] → ${method} ${finalUrl}`);
- console.log(`[执行器] Authorization: ${resolvedHeaders.Authorization ? 'Bearer ' + sessionToken.slice(0, 6) + '...' + sessionToken.slice(-4) : '(无)'}`);
- const resp = await fetch(finalUrl, {
- method,
- headers: resolvedHeaders,
- body: method === 'GET' || method === 'HEAD' ? undefined : JSON.stringify(resolvedBody)
- });
- const result = await resp.json();
- console.log(`[执行器] 响应 HTTP ${resp.status}, 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' || handler.action === 'resolveUserThenShowPayment') {
- let paymentUrl = '';
- if (handler.action === 'resolveUserThenShowPayment') {
- try {
- paymentUrl = await resolvePaymentUrlFromTokenConfig(tc, { ...userVars, apigid: userVars.apigid || tc.apigId });
- } catch (e) {
- console.warn('[执行器] 解析专属充值链接失败:', e.message);
- }
- }
- if (!paymentUrl && handler.qrCodeUrl) {
- paymentUrl = resolveTemplate(handler.qrCodeUrl, { ...userVars, apigid: userVars.apigid || tc.apigId });
- }
- if (!paymentUrl && tc.onMissing?.qrCodeUrl) {
- paymentUrl = resolveTemplate(tc.onMissing.qrCodeUrl, { ...userVars, apigid: userVars.apigid || tc.apigId });
- }
- if (!paymentUrl) {
- return { success: false, error: 'payment_url_unavailable' };
- }
- openPaymentUrl(paymentUrl, {});
- console.log(`[执行器] title: ${handler.title}`);
- console.log(`[执行器] message: ${handler.message}`);
- if (!authId) {
- console.log('[执行器] 无 authId,无法轮询余额。请手动充值后重试。');
- return { success: false, error: 'no_auth_record', paymentUrl };
- }
- const updated = await pollBalance(authId, oldCount, handler, resolveTokenFromConfig(tc));
- if (updated) {
- 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;
- let paymentUrl = '';
- if (handler.action === 'resolveUserThenShowPayment') {
- try {
- paymentUrl = await resolvePaymentUrlFromTokenConfig(tc, { ...userVars, apigid: userVars.apigid || tc.apigId });
- } catch (e) {
- console.warn('[执行器] 解析专属充值链接失败:', e.message);
- }
- }
- if (!paymentUrl && handler.qrCodeUrl) {
- paymentUrl = resolveTemplate(handler.qrCodeUrl, { ...userVars, apigid: userVars.apigid || tc.apigId });
- }
- if (paymentUrl) {
- openPaymentUrl(paymentUrl, {});
- console.log(`[执行器] title: ${handler.title}`);
- console.log(`[执行器] message: ${handler.message}`);
- }
- return {
- success: false,
- error: 'unauthorized',
- paymentUrl,
- ...buildTokenSetupMetadata(tc)
- };
- }
- // ─── 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 <skill-dir> [--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: '测试'
- }, userVars);
- console.log('\n[结果]', JSON.stringify(result, null, 2));
- }
- main().catch(e => {
- console.error('执行出错:', e.message);
- process.exit(1);
- });
|