Token Optimizer 1.0.0
✂️ TOKEN节约器 - 工作流程控制器。通过问题预检、路径验证、进度检查、错误快速定位,防止重复无效工作,节约TOKEN消耗。兼容Windows/Mac/Linux/MaxClaw/ClawHub。
安装 / 下载方式
TotalClaw CLI推荐
totalclaw install skilldb:smxtx~token-optimizer-1-0-0cURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/skilldb%3Asmxtx~token-optimizer-1-0-0/file -o token-optimizer-1-0-0.mdGit 仓库获取源码
git clone https://github.com/openclaw/skills/commit/439d483aba4566419081be1ee5f43b4a4282ec27<div align="center">
# ✂️ TOKEN节约器
**工作流程控制器 · 预检优于补救 · 验证优于猜测 · 记录优于遗忘**
[]()
[
[]()
</div>
---
## 一、核心价值
### 1.1 问题
- **重复无效工作**: 同样的错误反复出现、同样的检查重复进行
- **错误-修复循环**: 修复→测试→再修复→再测试的恶性循环
- **TOKEN浪费**: 每个错误修复消耗大量TOKEN,每个重复检查消耗更多
- **路径迷失**: 不知道当前在哪一步、不知道下一步该做什么
### 1.2 解决
```
TOKEN节约 = (预防问题 + 快速定位 + 减少循环) × 每问题节约TOKEN
```
### 1.3 效果
| 指标 | 改善前 | 改善后 | 节约率 |
|------|--------|--------|--------|
| 重复检查次数 | 5+次/问题 | 1次/问题 | 80% |
| 错误定位时间 | 45分钟 | 5分钟 | 89% |
| TOKEN消耗 | 高 | 低 | 60%+ |
---
## 二、四大控制组件
### 2.1 组件概览
```
┌─────────────────────────────────────────────────────────────────┐
│ TOKEN节约器 - 控制架构 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ 问题预检器 │ → │ 路径验证器 │ → │ 进度检查点 │ │
│ │ Pre-Check │ │ Path-Verify│ │ Checkpoint │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ ↓ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ 错误快速定位 │ ← │ 日志分析器 │ ← │ 经验记录器 │ │
│ │ Fast-Locate │ │ Log-Analyze│ │ Memory-Log │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
```
### 2.2 组件说明
| 组件 | 功能 | 适用场景 |
|------|------|----------|
| **问题预检器** | 执行前检查常见错误模式 | 任何任务开始前 |
| **路径验证器** | 确认当前路径是否正确 | 遇到错误时 |
| **进度检查点** | 记录关键里程碑 | 任务执行中 |
| **错误快速定位器** | 缩小问题范围 | 错误发生后 |
| **日志分析器** | 自动解析日志输出 | 查看日志时 |
| **经验记录器** | 保存问题-解决方案对 | 问题解决后 |
---
## 三、问题预检器 (Pre-Check)
### 3.1 检查清单
#### 代码修改类
```
☑ 1. 文件存在性检查 - 目标文件是否存在?
☑ 2. 路径正确性检查 - 路径格式是否正确?
☑ 3. 依赖可用性检查 - import的模块是否可用?
☑ 4. 语法正确性检查 - 代码语法是否正确?
☑ 5. 权限检查 - 是否有读写权限?
```
#### API调用类
```
☑ 1. 服务可用性检查 - 后端服务是否运行?
☑ 2. 端口占用检查 - 端口是否被占用?
☑ 3. 网络连通性检查 - 目标地址是否可达?
☑ 4. 认证状态检查 - Token/API Key是否有效?
☑ 5. 限流检查 - 是否触发频率限制?
```
#### 构建部署类
```
☑ 1. 构建产物检查 - dist目录是否更新?
☑ 2. 环境变量检查 - 必要变量是否设置?
☑ 3. 进程冲突检查 - 是否有残留进程?
☑ 4. 磁盘空间检查 - 空间是否充足?
☑ 5. 打包完整性检查 - asar是否最新?
```
### 3.2 预检执行流程
```
任务开始
↓
执行问题预检清单
↓
发现问题 → 修复后再继续
↓
无问题 → 继续执行
↓
记录检查通过
```
### 3.3 预检器组件代码
```javascript
/**
* TOKEN节约器 - 问题预检器 (Pre-Checker)
*
* 功能: 在执行任务前检查常见错误模式,预防问题发生
*/
const { execSync } = require('child_process');
const fs = require('fs');
class PreChecker {
constructor() {
this.results = [];
this.config = { timeout: 5000 };
}
checkFile(filePath) {
// 参数安全检查
if (!filePath || typeof filePath !== 'string') return false;
if (filePath.length > 10000) return false; // 防止DoS
const exists = fs.existsSync(filePath);
this.results.push({ type: 'file', path: filePath, exists });
return exists;
}
checkPort(port) {
try {
const isWindows = process.platform === 'win32';
const cmd = isWindows
? `netstat -ano | findstr :${port}`
: `lsof -i :${port}`;
const output = execSync(cmd, { encoding: 'utf-8', timeout: this.config.timeout });
const inUse = new RegExp(`:${port}`).test(output);
this.results.push({ type: 'port', port, inUse, available: !inUse });
return !inUse;
} catch { return true; } // 端口未被占用
}
checkProcess(processName) {
try {
const isWindows = process.platform === 'win32';
const cmd = isWindows
? `powershell -Command "Get-Process -Name '${processName}' -ErrorAction SilentlyContinue | Select-Object Id"`
: `pgrep -x "${processName}"`;
const output = execSync(cmd, { encoding: 'utf-8' });
const pids = output.trim().split('\n').filter(l => /^\d+$/.test(l.trim())).map(Number);
const result = { type: 'process', name: processName, running: pids.length > 0, count: pids.length, pids };
this.results.push(result);
return result;
} catch {
return { type: 'process', name: processName, running: false, count: 0, pids: [] };
}
}
getReport() {
return { timestamp: new Date().toISOString(), total: this.results.length, results: this.results };
}
}
module.exports = PreChecker;
```
---
## 四、路径验证器 (Path-Verify)
### 4.1 验证流程
```
遇到错误/问题
↓
确定问题类型 (前端/后端/网络/环境)
↓
按类型验证路径
↓
找到问题节点
↓
修复后继续
```
### 4.2 分层验证检查表
#### 前端问题
```
☑ 1. dist目录是否最新?
☑ 2. 浏览器是否刷新到最新?
☑ 3. API路径配置是否正确?
☑ 4. 环境变量是否正确?
☑ 5. 打包文件(asar)是否更新?
```
#### 后端问题
```
☑ 1. 服务是否启动?
☑ 2. 端口是否正确监听?
☑ 3. 路由是否正确注册?
☑ 4. 数据库连接是否正常?
☑ 5. 日志是否有错误?
```
### 4.3 快速定位决策树
```
问题: API 404
↓
curl后端API通吗?
├── 通 → 前端问题 → dist最新吗? → 是 → 完整重启
│ └── 否 → 重新构建
│
└── 不通 → 后端问题 → 端口监听正常吗?
├── 正常 → 查看后端日志
└── 不正常 → 检查进程/重启
```
---
## 五、进度检查点 (Checkpoint)
### 5.1 检查点设计
```
任务开始 → [检查点1] → 子任务1 → [检查点2] → 子任务2 → [检查点3] → ... → 完成
↓ ↓ ↓
记录状态 验证结果 保存检查点
```
### 5.2 检查点模板
```markdown
## 检查点 [#]
**时间**: YYYY-MM-DD HH:MM
**任务**: [当前任务描述]
**状态**: ⬜ 进行中 | ✅ 完成 | ❌ 失败
### 已完成
- [x] 子任务1
- [x] 子任务2
### 当前问题
> 描述遇到的问题(如有)
### 下一步
- [ ] 子任务3
- [ ] 子任务4
### TOKEN消耗
- 预估: XXX
- 实际: YYY
- 状态: ⚠️ 超预算 | ✅ 正常
```
### 5.3 检查点组件代码
```javascript
/**
* TOKEN节约器 - 进度检查点 (Checkpoint)
*/
const fs = require('fs');
class Checkpoint {
constructor(options = {}) {
this.storagePath = options.storagePath || './checkpoint-data.json';
this.autoSave = options.autoSave !== false;
this.data = { checkpoints: [], currentPhase: null, tokenBudget: options.tokenBudget || null, tokenUsed: 0 };
this.load();
}
load() {
try {
if (fs.existsSync(this.storagePath)) {
this.data = JSON.parse(fs.readFileSync(this.storagePath, 'utf-8'));
}
} catch (e) { /* 忽略 */ }
}
save() {
try {
this.data.lastUpdate = new Date().toISOString();
const dir = require('path').dirname(this.storagePath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(this.storagePath, JSON.stringify(this.data, null, 2));
return true;
} catch { return false; }
}
create(name, metadata = {}) {
const checkpoint = {
id: `cp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
name, timestamp: new Date().toISOString(), phase: this.data.currentPhase, status: metadata.status || 'in_progress', data: metadata, tokenAtPoint: this.data.tokenUsed
};
this.data.checkpoints.push(checkpoint);
if (this.autoSave) this.save();
return checkpoint;
}
setPhase(phase) {
this.data.currentPhase = phase;
this.create(`阶段切换 → ${phase}`, { type: 'phase_change'});
}
updateToken(used) {
this.data.tokenUsed += used;
this.create('TOKEN更新', { type: 'token', increment: used, total: this.data.tokenUsed });
if (this.autoSave) this.save();
const ratio = this.data.tokenUsed / this.data.tokenBudget;
if (ratio > 0.9) return 'critical';
if (ratio > 0.75) return 'warning';
return 'ok';
}
getState() {
return {
currentPhase: this.data.currentPhase,
totalCheckpoints: this.data.checkpoints.length,
latestCheckpoint: this.data.checkpoints[this.data.checkpoints.length - 1],