Token导航 LogoToken导航

Agent Skill · 运维和基础设施

token-optimizer(令牌优化器)

token-optimizer 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

token-optimizer 是运维和基础设施类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为执行命令;许可证信息还不明确,第三方扫描已通过,按安装量在运维和基础设施类的 2,449 个 Skill 里排第 379。

总安装 5,727周安装 246GitHub Stars 4下载 2,007核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:token-optimizer(令牌优化器)
来源仓库:https://github.com/asif2bd/openclaw-token-optimizer
仓库路径:skills/token-optimizer
安装命令:
npx skills add https://github.com/asif2bd/openclaw-token-optimizer --skill token-optimizer
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/asif2bd/openclaw-token-optimizer --skill token-optimizer

这个 Skill 是做什么的

运维和基础设施类 Skill 处理部署、监控、日志和云资源,多数需要较高的执行权限。

token-optimizer 用于降低 OpenClaw 部署中的令牌消耗与 API 成本,优化上下文使用效率。提供模型路由、心跳间隔调整与 AGENTS.md 生成等策略,显著减少冗余 token 开销。通过 npx skills add 命令安装,内置脚本可直接生成优化后的配置文件供审阅替换。

建议优先运行 context optimizer 分析实际所需文件数,避免全量上下文加载浪费资源。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

来源仓库内路径:skills/token-optimizer

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/asif2bd/openclaw-token-optimizer --skill token…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要执行命令,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

token-optimizer 怎么安装?

在终端执行 npx skills add https://github.com/asif2bd/openclaw-token-optimizer --skill token-optimizer。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

token-optimizer 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

token-optimizer 需要什么权限?

权限级别是执行命令。安装流程涉及命令执行,可能通过 npx skills add https://github.com/asif2bd/openclaw-token-optimizer --skill token-optimizer 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

token-optimizer 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

token-optimizer 用的人多吗?

公开数据是累计安装 5,727 次,近一周安装 246 次,下载 2,007 次,GitHub 4 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

token-optimizer 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要执行命令,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理运维和基础设施类任务、又不想每次都手写提示词的人。

不太适合

  • 不能接受 Skill 在你机器上执行命令的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

运维和基础设施类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
brainstorming

头脑风暴 · Codex、Claude

3,148,776173,131操作浏览器MIT通过
copywriting

文案写作 · Codex、Claude

1,996,72425,583需要联网MIT通过
openclaw-secure-linux-cloud

OpenClaw secure linux cloud 命令行 · Codex、Claude

1,853,08840接触敏感数据未明确未通过
xget

xget 命令行 · Codex、Claude

1,799,28040执行命令未明确未通过
requesting-code-review

代码审查请求 · Codex、Claude

1,590,144173,103权限未标注MIT通过
token-optimizer

令牌优化器 · 本页

5,7274执行命令未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Token Optimizer

Comprehensive toolkit for reducing token usage and API costs in OpenClaw deployments. Combines smart model routing, optimized heartbeat intervals, usage tracking, and multi-provider strategies.

Quick Start

Immediate actions (no config changes needed):

  1. Generate optimized AGENTS.md (BIGGEST WIN!): python3 scripts/context_optimizer.py generate-agents # Creates AGENTS.md.optimized — review and replace your current AGENTS.md
  2. Check what context you ACTUALLY need: python3 scripts/context_optimizer.py recommend "hi, how are you?" # Shows: Only 2 files needed (not 50+!)
  3. Install optimized heartbeat: cp assets/HEARTBEAT.template.md ~/.openclaw/workspace/HEARTBEAT.md
  4. Enforce cheaper models for casual chat: python3 scripts/model_router.py "thanks!" # Single-provider Anthropic setup: Use Sonnet, not Opus # Multi-provider setup (OpenRouter/Together): Use Haiku for max savings
  5. Check current token budget: python3 scripts/token_tracker.py check

Expected savings: 50-80% reduction in token costs for typical workloads (context optimization is the biggest factor!).

Core Capabilities

1. Context Optimization (NEW!)

Biggest token saver — Only load files you actually need, not everything upfront.

Problem: Default OpenClaw loads ALL context files every session:

  • SOUL.md, AGENTS.md, USER.md, TOOLS.md, MEMORY.md
  • docs/**/*.md (hundreds of files)
  • memory/2026-*.md (daily logs)
  • Total: Often 50K+ tokens before user even speaks!

Solution: Lazy loading based on prompt complexity.

Usage:

python3 scripts/context_optimizer.py recommend "<user prompt>"

Examples:

# Simple greeting → minimal context (2 files only!)
context_optimizer.py recommend "hi"
→ Load: SOUL.md, IDENTITY.md
→ Skip: Everything else
→ Savings: ~80% of context

# Standard work → selective loading
context_optimizer.py recommend "write a function"
→ Load: SOUL.md, IDENTITY.md, memory/TODAY.md
→ Skip: docs, old memory, knowledge base
→ Savings: ~50% of context

# Complex task → full context
context_optimizer.py recommend "analyze our entire architecture"
→ Load: SOUL.md, IDENTITY.md, MEMORY.md, memory/TODAY+YESTERDAY.md
→ Conditionally load: Relevant docs only
→ Savings: ~30% of context

Output format:

{
  "complexity": "simple",
  "context_level": "minimal",
  "recommended_files": ["SOUL.md", "IDENTITY.md"],
  "file_count": 2,
  "savings_percent": 80,
  "skip_patterns": ["docs/**/*.md", "memory/20*.md"]
}

Integration pattern: Before loading context for a new session:

from context_optimizer import recommend_context_bundle

user_prompt = "thanks for your help"
recommendation = recommend_context_bundle(user_prompt)

if recommendation["context_level"] == "minimal":
    # Load only SOUL.md + IDENTITY.md
    # Skip everything else
    # Save ~80% tokens!

Generate optimized AGENTS.md:

context_optimizer.py generate-agents
# Creates AGENTS.md.optimized with lazy loading instructions
# Review and replace your current AGENTS.md

Expected savings: 50-80% reduction in context tokens.

2. Smart Model Routing (ENHANCED!)

Automatically classify tasks and route to appropriate model tiers.

NEW: Communication pattern enforcement — Never waste Opus tokens on "hi" or "thanks"!

Usage:

python3 scripts/model_router.py "<user prompt>" [current_model] [force_tier]

Examples:

# Communication (NEW!) → ALWAYS Haiku
python3 scripts/model_router.py "thanks!"
python3 scripts/model_router.py "hi"
python3 scripts/model_router.py "ok got it"
→ Enforced: Haiku (NEVER Sonnet/Opus for casual chat)

# Simple task → suggests Haiku
python3 scripts/model_router.py "read the log file"

# Medium task → suggests Sonnet
python3 scripts/model_router.py "write a function to parse JSON"

# Complex task → suggests Opus
python3 scripts/model_router.py "design a microservices architecture"

Patterns enforced to Haiku (NEVER Sonnet/Opus):

*Communication:*

  • Greetings: hi, hey, hello, yo
  • Thanks: thanks, thank you, thx
  • Acknowledgments: ok, sure, got it, understood
  • Short responses: yes, no, yep, nope
  • Single words or very short phrases

*Background tasks:*

  • Heartbeat checks: "check email", "monitor servers"
  • Cronjobs: "scheduled task", "periodic check", "reminder"
  • Document parsing: "parse CSV", "extract data from log", "read JSON"
  • Log scanning: "scan error logs", "process logs"

Integration pattern:

from model_router import route_task

user_prompt = "show me the config"
routing = route_task(user_prompt)

if routing["should_switch"]:
    # Use routing["recommended_model"]
    # Save routing["cost_savings_percent"]

Customization: Edit ROUTING_RULES or COMMUNICATION_PATTERNS in scripts/model_router.py to adjust patterns and keywords.

3. Heartbeat Optimization

Reduce API calls from heartbeat polling with smart interval tracking:

Setup:

# Copy template to workspace
cp assets/HEARTBEAT.template.md ~/.openclaw/workspace/HEARTBEAT.md

# Plan which checks should run
python3 scripts/heartbeat_optimizer.py plan

Commands:

# Check if specific type should run now
heartbeat_optimizer.py check email
heartbeat_optimizer.py check calendar

# Record that a check was performed
heartbeat_optimizer.py record email

# Update check interval (seconds)
heartbeat_optimizer.py interval email 7200  # 2 hours

# Reset state
heartbeat_optimizer.py reset

How it works:

  • Tracks last check time for each type (email, calendar, weather, etc.)
  • Enforces minimum intervals before re-checking
  • Respects quiet hours (23:00-08:00) — skips all checks
  • Returns HEARTBEAT_OK when nothing needs attention (saves tokens)

Default intervals:

  • Email: 60 minutes
  • Calendar: 2 hours
  • Weather: 4 hours
  • Social: 2 hours
  • Monitoring: 30 minutes

Integration in HEARTBEAT.md:

## Email Check
Run only if: `heartbeat_optimizer.py check email` → `should_check: true`
After checking: `heartbeat_optimizer.py record email`

Expected savings: 50% reduction in heartbeat API calls.

Model enforcement: Heartbeat should ALWAYS use Haiku — see updated HEARTBEAT.template.md for model override instructions.

4. Cronjob Optimization (NEW!)

Problem: Cronjobs often default to expensive models (Sonnet/Opus) even for routine tasks.

Solution: Always specify Haiku for 90% of scheduled tasks.

See: assets/cronjob-model-guide.md for comprehensive guide with examples.

Quick reference:

Task TypeModelExample
Monitoring/alertsHaikuCheck server health, disk space
Data parsingHaikuExtract CSV/JSON/logs
RemindersHaikuDaily standup, backup reminders
Simple reportsHaikuStatus summaries
Content generationSonnetBlog summaries (quality matters)
Deep analysisSonnetWeekly insights
Complex reasoningNever use Opus for cronjobs

Example (good):

# Parse daily logs with Haiku
cron add --schedule "0 2 * * *" \
  --payload '{
    "kind":"agentTurn",
    "message":"Parse yesterday error logs and summarize",
    "model":"anthropic/claude-haiku-4"
  }' \
  --sessionTarget isolated

Example (bad):

# ❌ Using Opus for simple check (60x more expensive!)
cron add --schedule "*/15 * * * *" \
  --payload '{
    "kind":"agentTurn",
    "message":"Check email",
    "model":"anthropic/claude-opus-4"
  }' \
  --sessionTarget isolated

Savings: Using Haiku instead of Opus for 10 daily cronjobs = $17.70/month saved per agent.

Integration with model_router:

# Test if your cronjob should use Haiku
model_router.py "parse daily error logs"
# → Output: Haiku (background task pattern detected)

5. Token Budget Tracking

Monitor usage and alert when approaching limits:

Setup:

# Check current daily usage
python3 scripts/token_tracker.py check

# Get model suggestions
python3 scripts/token_tracker.py suggest general

# Reset daily tracking
python3 scripts/token_tracker.py reset

Output format:

{
  "date": "2026-02-06",
  "cost": 2.50,
  "tokens": 50000,
  "limit": 5.00,
  "percent_used": 50,
  "status": "ok",
  "alert": null
}

Status levels:

  • ok: Below 80% of daily limit
  • warning: 80-99% of daily limit
  • exceeded: Over daily limit

Integration pattern: Before starting expensive operations, check budget:

import json
import subprocess

result = subprocess.run(
    ["python3", "scripts/token_tracker.py", "check"],
    capture_output=True, text=True
)
budget = json.loads(result.stdout)

if budget["status"] == "exceeded":
    # Switch to cheaper model or defer non-urgent work
    use_model = "anthropic/claude-haiku-4"
elif budget["status"] == "warning":
    # Use balanced model
    use_model = "anthropic/claude-sonnet-4-5"

Customization: Edit daily_limit_usd and warn_threshold parameters in function calls.

6. Multi-Provider Strategy

See references/PROVIDERS.md for comprehensive guide on:

  • Alternative providers (OpenRouter, Together.ai, Google AI Studio)
  • Cost comparison tables
  • Routing strategies by task complexity
  • Fallback chains for rate-limited scenarios
  • API key management

Quick reference:

ProviderModelCost/MTokUse Case
AnthropicHaiku 4$0.25Simple tasks
AnthropicSonnet 4.5$3.00Balanced default
AnthropicOpus 4$15.00Complex reasoning
OpenRouterGemini 2.5 Flash$0.075Bulk operations
Google AIGemini 2.0 Flash ExpFREEDev/testing
TogetherLlama 3.3 70B$0.18Open alternative

Configuration Patches

See assets/config-patches.json for advanced optimizations:

Implemented by this skill:

  • ✅ Heartbeat optimization (fully functional)
  • ✅ Token budget tracking (fully functional)
  • ✅ Model routing logic (fully functional)

Native OpenClaw 2026.2.15 — apply directly:

  • ✅ Session pruning (contextPruning: cache-ttl) — auto-trims old tool results after Anthropic cache TTL expires
  • ✅ Bootstrap size limits (bootstrapMaxChars / bootstrapTotalMaxChars) — caps workspace file injection size
  • ✅ Cache retention long (cacheRetention: "long" for Opus) — amortizes cache write costs

Requires OpenClaw core support:

  • ⏳ Prompt caching (Anthropic API feature — verify current status)
  • ⏳ Lazy context loading (use context_optimizer.py script today)
  • ⏳ Multi-provider fallback (partially supported)

Apply config patches:

# Example: Enable multi-provider fallback
gateway config.patch --patch '{"providers": [...]}'

Native OpenClaw Diagnostics (2026.2.15+)

OpenClaw 2026.2.15 added built-in commands that complement this skill's Python scripts. Use these first for quick diagnostics before reaching for the scripts.

Context breakdown

/context list    → token count per injected file (shows exactly what's eating your prompt)
/context detail  → full breakdown including tools, skills, and system prompt sections

Use before applying bootstrap_size_limits — see which files are oversized, then set bootstrapMaxChars accordingly.

Per-response usage tracking

/usage tokens    → append token count to every reply
/usage full      → append tokens + cost estimate to every reply
/usage cost      → show cumulative cost summary from session logs
/usage off       → disable usage footer

Combine with token_tracker.py — /usage cost gives session totals; token_tracker.py tracks daily budget.

Session status

/status          → model, context %, last response tokens, estimated cost

Cache TTL Heartbeat Alignment (NEW in v1.4.0)

The problem: Anthropic charges ~3.75x more for cache *writes* than cache *reads*. If your agent goes idle and the 1h cache TTL expires, the next request re-writes the entire prompt cache — expensive.

The fix: Set heartbeat interval to 55min (just under the 1h TTL). The heartbeat keeps the cache warm, so every subsequent request pays cache-read rates instead.

# Get optimal interval for your cache TTL
python3 scripts/heartbeat_optimizer.py cache-ttl
# → recommended_interval: 55min (3300s)
# → explanation: keeps 1h Anthropic cache warm

# Custom TTL (e.g., if you've configured 2h cache)
python3 scripts/heartbeat_optimizer.py cache-ttl 7200
# → recommended_interval: 115min

Apply to your OpenClaw config:

{
  "agents": {
    "defaults": {
      "heartbeat": {
        "every": "55m"
      }
    }
  }
}

Who benefits: Anthropic API key users only. OAuth profiles already default to 1h heartbeat (OpenClaw smart default). API key profiles default to 30min — bumping to 55min is both cheaper (fewer calls) and cache-warm.


Deployment Patterns

For Personal Use

  1. Install optimized HEARTBEAT.md
  2. Run budget checks before expensive operations
  3. Manually route complex tasks to Opus only when needed

Expected savings: 20-30%

For Managed Hosting (xCloud, etc.)

  1. Default all agents to Haiku
  2. Route user interactions to Sonnet
  3. Reserve Opus for explicitly complex requests
  4. Use Gemini Flash for background operations
  5. Implement daily budget caps per customer

Expected savings: 40-60%

For High-Volume Deployments

  1. Use multi-provider fallback (OpenRouter + Together.ai)
  2. Implement aggressive routing (80% Gemini, 15% Haiku, 5% Sonnet)
  3. Deploy local Ollama for offline/cheap operations
  4. Batch heartbeat checks (every 2-4 hours, not 30 min)

Expected savings: 70-90%

Integration Examples

Workflow: Smart Task Handling

# 1. User sends message
user_msg="debug this error in the logs"

# 2. Route to appropriate model
routing=$(python3 scripts/model_router.py "$user_msg")
model=$(echo $routing | jq -r .recommended_model)

# 3. Check budget before proceeding
budget=$(python3 scripts/token_tracker.py check)
status=$(echo $budget | jq -r .status)

if [ "$status" = "exceeded" ]; then
    # Use cheapest model regardless of routing
    model="anthropic/claude-haiku-4"
fi

# 4. Process with selected model
# (OpenClaw handles this via config or override)

Workflow: Optimized Heartbeat

## HEARTBEAT.md

# Plan what to check
result=$(python3 scripts/heartbeat_optimizer.py plan)
should_run=$(echo $result | jq -r .should_run)

if [ "$should_run" = "false" ]; then
    echo "HEARTBEAT_OK"
    exit 0
fi

# Run only planned checks
planned=$(echo $result | jq -r '.planned[].type')

for check in $planned; do
    case $check in
        email) check_email ;;
        calendar) check_calendar ;;
    esac
    python3 scripts/heartbeat_optimizer.py record $check
done

Troubleshooting

Issue: Scripts fail with "module not found"

  • Fix: Ensure Python 3.7+ is installed. Scripts use only stdlib.

Issue: State files not persisting

  • Fix: Check that ~/.openclaw/workspace/memory/ directory exists and is writable.

Issue: Budget tracking shows $0.00

  • Fix: token_tracker.py needs integration with OpenClaw's session_status tool. Currently tracks manually recorded usage.

Issue: Routing suggests wrong model tier

  • Fix: Customize ROUTING_RULES in model_router.py for your specific patterns.

Maintenance

Daily:

  • Check budget status: token_tracker.py check

Weekly:

  • Review routing accuracy (are suggestions correct?)
  • Adjust heartbeat intervals based on activity

Monthly:

  • Compare costs before/after optimization
  • Review and update PROVIDERS.md with new options

Cost Estimation

Example: 100K tokens/day workload

Without skill:

  • 50K context tokens + 50K conversation tokens = 100K total
  • All Sonnet: 100K × $3/MTok = $0.30/day = $9/month
StrategyContextModelDaily CostMonthlySavings
Baseline (no optimization)50KSonnet$0.30$9.000%
Context opt only10K (-80%)Sonnet$0.18$5.4040%
Model routing only50KMixed$0.18$5.4040%
Both (this skill)10KMixed$0.09$2.7070%
Aggressive + Gemini10KGemini$0.03$0.9090%

Key insight: Context optimization (50K → 10K tokens) saves MORE than model routing!

xCloud hosting scenario (100 customers, 50K tokens/customer/day):

  • Baseline (all Sonnet, full context): $450/month
  • With token-optimizer: $135/month
  • Savings: $315/month per 100 customers (70%)

Resources

Scripts (4 total)

  • context_optimizer.py — Context loading optimization and lazy loading (NEW!)
  • model_router.py — Task classification, model suggestions, and communication enforcement (ENHANCED!)
  • heartbeat_optimizer.py — Interval management and check scheduling
  • token_tracker.py — Budget monitoring and alerts

References

  • PROVIDERS.md — Alternative AI providers, pricing, and routing strategies

Assets (3 total)

  • HEARTBEAT.template.md — Drop-in optimized heartbeat template with Haiku enforcement (ENHANCED!)
  • cronjob-model-guide.md — Complete guide for choosing models in cronjobs (NEW!)
  • config-patches.json — Advanced configuration examples

Future Enhancements

Ideas for extending this skill:

  1. Auto-routing integration — Hook into OpenClaw message pipeline
  2. Real-time usage tracking — Parse session_status automatically
  3. Cost forecasting — Predict monthly spend based on recent usage
  4. Provider health monitoring — Track API latency and failures
  5. A/B testing — Compare quality across different routing strategies

适合场景

01

调用多模型

02

代码和文本生成

03

Agent 推理流程

04

OpenRouter 模型接入

能力概览

能力 1

统一调用多种 LLM

能力 2

支持 Claude、Gemini、Kimi 等模型

能力 3

适合聊天、代码和推理任务

能力 4

可作为 Agent 模型调用入口

平台分布

Codex

39.1%
按下载量换算785

Claude

31.42%
按下载量换算631

Cursor

17.59%
按下载量换算353

Gemini CLI

9.4%
按下载量换算189

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/asif2bd/openclaw-token-optimizer --skill token-optimizer 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills