Session Cost Tracking (codesession-cli)
Track agent session costs, file changes, and git commits. Enforces budget limits and provides detailed session analytics with a full web dashboard.
Latest: v2.5.1 - cs run <command> wraps everything in one step (session + proxy + run + cost summary). cs today for multi-project context. Dashboard Help tab, Codex pricing, security fixes.
📦 npm • ⭐ GitHub • 📝 Changelog
Installation
CODEBLOCK0
After installing, the cs command is available globally. The OpenClaw agent will automatically use it to track sessions.
Requirements: Node.js 18+ and C/C++ build tools (needed to compile the embedded SQLite module).
| OS | Install build tools |
|---|
| Ubuntu/Debian | INLINECODE3 |
| macOS |
xcode-select --install |
| Windows | npm install -g windows-build-tools or install Visual Studio Build Tools |
| Alpine | apk add build-base python3 |
Data is stored locally at ~/.codesession/sessions.db.
When to use
- - Always start a tracked session at the beginning of a multi-step task
- Always log AI usage after each API call you make
- Always end the session when the task is complete
- Check budget before expensive operations
- Use
cs dashboard to review session data in a browser
Commands
Start tracking
CODEBLOCK1
Agent mode vs interactive mode: With --json, the session is created in the database, JSON is printed, and the process exits immediately -- the session stays "active" and tracks git changes when you run cs end. Without --json, the process stays running with a live file watcher and git commit poller until you press Ctrl+C or run cs end in another terminal.
Log AI usage (after each API call)
# With granular tokens (cost auto-calculated from built-in pricing):
cs log-ai -p anthropic -m claude-sonnet-4 --prompt-tokens 8000 --completion-tokens 2000 --json
# With agent name tracking (NEW in v1.9.1):
cs log-ai -p anthropic -m claude-sonnet-4 --prompt-tokens 8000 --completion-tokens 2000 --agent "Code Review Bot" --json
# With manual cost:
cs log-ai -p anthropic -m claude-opus-4-6 -t 15000 -c 0.30 --json
# With all fields:
cs log-ai -p openai -m gpt-4o --prompt-tokens 5000 --completion-tokens 1500 -c 0.04 --agent "Research Agent" --json
Providers:
anthropic,
openai,
google,
mistral,
deepseek
Cost is auto-calculated from a configurable pricing table (21+ built-in models including Codex). Use
cs pricing list --json to see known models. If a model is unknown, provide
-c <cost> manually.
Agent Name (optional): Use --agent "Agent Name" to track which agent performed the work. Perfect for multi-agent systems, A/B testing, and cost attribution. Agent names appear in the dashboard and can be used to filter/analyze costs per agent.
Check current status
cs status --json
Returns JSON with current session cost, tokens, files changed, duration. All JSON responses include
schemaVersion and
codesessionVersion fields.
End session and get summary
cs end -n "completion notes" --json
When ending, codesession automatically scans git for all files changed and commits made since the session started -- even if
--json mode was used (no live watcher needed).
Web Dashboard
CODEBLOCK5
The dashboard shows:
- - Overview — KPIs, daily cost/token trends, spend projections, cost velocity
- Sessions — searchable/sortable table, per-session detail with timeline, files, commits, AI calls, notes
- Models — per-model & per-provider cost breakdown, token ratios, usage charts
- Insights — file hotspots, activity heatmap, project breakdown, pricing table
- Alerts — set daily/total/per-session cost thresholds with alarm mode (sound + browser notifications)
- Start Fresh — reset all session data from the sidebar
View session details
CODEBLOCK6
View historical stats
CODEBLOCK7
Export sessions
CODEBLOCK8
Add notes / annotations
cs note "Starting refactor phase"
cs note "Tests passing, moving to cleanup"
Timestamped annotations appear in
cs show --json under
annotations.
Recover stale sessions
cs recover --max-age 12
Auto-ends any active sessions older than 12 hours.
Agent Workflow
Agents should always use --json on every command for structured, parseable output.
- 1. At task start: INLINECODE27
- Add context notes: INLINECODE28
- After each AI call: INLINECODE29
- Check spend:
cs status --json -- read aiCost field - At task end: INLINECODE32
- Review past sessions: INLINECODE33
Tip: Use the --agent flag to identify your agent's work, especially useful in multi-agent systems where different agents handle different tasks (e.g., "Code Review Bot", "Test Writer", "Documentation Agent").
Pricing
Pricing is configurable. Run cs pricing list to see all known model prices. Override or add models:
CODEBLOCK11
If the model isn't in the pricing table, you must provide -c <cost> when logging.
Proxy mode & cs run (v2.5.0)
The fastest way to track any agent run:
CODEBLOCK12
This starts a session, launches the proxy, runs your command, then ends the session and prints a cost summary. No extra terminals, no env vars to export.
If you prefer manual control, start the proxy in one terminal and set env vars:
CODEBLOCK13
The proxy binds to 127.0.0.1 only. It never stores prompt text or API keys — only token counts are written to the session.
Budget awareness
If the user has set a budget or you detect high spending:
- - Check
cs status --json before expensive operations - Warn the user if
aiCost exceeds $5.00 in a single session - Suggest cheaper models if costs are escalating
Important
- - Use
--close-stale on cs start to avoid "session_active" errors from prior crashes - If
cs is not installed, skip session tracking — don't block the user's task - Always use
--json on every command — agents must use structured output - With
--json, cs start creates the session and exits (no long-running process needed) - Sessions are scoped by git root — running from a subdirectory still matches the repo-level session
- On errors in
--json mode, exit code is always 1 and the response has INLINECODE48 - Check
schemaVersion in JSON responses to detect breaking changes
Update check
Periodically check if the CLI is up to date (e.g. at session start or once per day):
CODEBLOCK14
If the installed version is behind, notify the user:
"codesession-cli update available: v1.9.4 -> v2.0.0. Run npm install -g codesession-cli to update."
Don't block the workflow for an update — just inform and continue.
JSON output
All commands support --json for machine-readable output. Use this when you need to parse session data programmatically.
会话成本追踪 (codesession-cli)
追踪代理会话成本、文件变更和Git提交。强制执行预算限制,并提供包含完整Web仪表盘的详细会话分析。
最新版本: v2.5.1 - cs run 将一切整合为一步操作(会话+代理+运行+成本摘要)。cs today 用于多项目上下文。仪表盘帮助选项卡、Codex定价、安全修复。
📦 npm • ⭐ GitHub • 📝 更新日志
安装
bash
1. 从npm全局安装CLI
npm install -g codesession-cli
2. 安装OpenClaw技能
clawhub install codesession
安装后,cs命令即可全局使用。OpenClaw代理将自动使用它来追踪会话。
要求: Node.js 18+ 和 C/C++ 构建工具(用于编译嵌入式SQLite模块)。
| 操作系统 | 安装构建工具 |
|---|
| Ubuntu/Debian | sudo apt-get install -y build-essential python3 |
| macOS |
xcode-select --install |
| Windows | npm install -g windows-build-tools 或安装 Visual Studio Build Tools |
| Alpine | apk add build-base python3 |
数据存储在本地 ~/.codesession/sessions.db。
何时使用
- - 始终在多步骤任务开始时启动追踪会话
- 始终在每次API调用后记录AI使用情况
- 始终在任务完成时结束会话
- 在执行昂贵操作前检查预算
- 使用 cs dashboard 在浏览器中查看会话数据
命令
开始追踪
bash
代理模式(始终使用 --json 获取结构化输出):
cs start 任务描述 --json --close-stale
如果会话未关闭则恢复(例如崩溃后):
cs start 任务描述 --json --resume
人工/交互模式(保持运行并实时监控文件):
cs start 任务描述
代理模式 vs 交互模式: 使用 --json 时,会话在数据库中创建,打印JSON,进程立即退出——会话保持活跃状态,并在运行 cs end 时追踪git变更。不使用 --json 时,进程保持运行,带有实时文件监控器和git提交轮询器,直到按Ctrl+C或在另一个终端运行 cs end。
记录AI使用情况(每次API调用后)
bash
带粒度令牌(成本从内置定价自动计算):
cs log-ai -p anthropic -m claude-sonnet-4 --prompt-tokens 8000 --completion-tokens 2000 --json
带代理名称追踪(v1.9.1新增):
cs log-ai -p anthropic -m claude-sonnet-4 --prompt-tokens 8000 --completion-tokens 2000 --agent 代码审查机器人 --json
手动指定成本:
cs log-ai -p anthropic -m claude-opus-4-6 -t 15000 -c 0.30 --json
所有字段:
cs log-ai -p openai -m gpt-4o --prompt-tokens 5000 --completion-tokens 1500 -c 0.04 --agent 研究代理 --json
提供商:anthropic、openai、google、mistral、deepseek
成本从可配置的定价表自动计算(包括Codex在内的21+内置模型)。使用 cs pricing list --json 查看已知模型。如果模型未知,请手动提供 -c 。
代理名称(可选): 使用 --agent 代理名称 追踪哪个代理执行了工作。非常适合多代理系统、A/B测试和成本归因。代理名称显示在仪表盘中,可用于按代理筛选/分析成本。
检查当前状态
bash
cs status --json
返回包含当前会话成本、令牌、文件变更、持续时间的JSON。所有JSON响应都包含 schemaVersion 和 codesessionVersion 字段。
结束会话并获取摘要
bash
cs end -n 完成备注 --json
结束时,codesession自动扫描git以查找自会话开始以来所有变更的文件和提交——即使使用了 --json 模式(无需实时监控器)。
Web仪表盘
bash
cs dashboard
打开 http://localhost:3737,包含完整分析UI
cs dashboard --port 4000 # 自定义端口
cs dashboard --no-open # 不自动打开浏览器
仪表盘显示:
- - 概览 — KPI、每日成本/令牌趋势、支出预测、成本速度
- 会话 — 可搜索/排序表格、每个会话详情(含时间线、文件、提交、AI调用、备注)
- 模型 — 按模型和按提供商的成本分解、令牌比率、使用图表
- 洞察 — 文件热点、活动热力图、项目分解、定价表
- 警报 — 设置每日/总计/每会话成本阈值,带警报模式(声音+浏览器通知)
- 重新开始 — 从侧边栏重置所有会话数据
查看会话详情
bash
cs show --json --files --commits
查看历史统计
bash
cs stats --json
导出会话
bash
cs export --format json --limit 10
cs export --format csv
添加备注/注释
bash
cs note 开始重构阶段
cs note 测试通过,进入清理阶段
带时间戳的注释出现在 cs show --json 的 annotations 下。
恢复过期会话
bash
cs recover --max-age 12
自动结束所有超过12小时的活跃会话。
代理工作流程
代理应始终在每个命令上使用 --json 以获取结构化、可解析的输出。
- 1. 任务开始时:cs start 修复认证bug --json --close-stale
- 添加上下文备注:cs note 分析认证流程 --json
- 每次AI调用后:cs log-ai -p anthropic -m claude-sonnet-4 --prompt-tokens 8000 --completion-tokens 2000 --agent Bug修复器 --json
- 检查支出:cs status --json — 读取 aiCost 字段
- 任务结束时:cs end -n 修复了认证bug,添加了测试 --json
- 查看过往会话:cs dashboard
提示: 使用 --agent 标志标识代理的工作,在多代理系统中尤其有用,不同代理处理不同任务(例如代码审查机器人、测试编写器、文档代理)。
定价
定价可配置。运行 cs pricing list 查看所有已知模型价格。覆盖或添加模型:
bash
纯模型键
cs pricing set my-model 5.00 15.00
提供商命名空间键(避免冲突)
cs pricing set gpt-4o 2.50 10.00 --provider openai
如果模型不在定价表中,记录时必须提供 -c 。
代理模式与 cs run (v2.5.0)
追踪任何代理运行的最快方式:
bash
cs run python my_agent.py
或:cs run --name 修复认证 node agent.js
这会启动会话、启动代理、运行命令,然后结束会话并打印成本摘要。无需额外终端,无需导出环境变量。
如果更喜欢手动控制,在一个终端启动代理并设置环境变量:
bash
cs proxy --session 我的任务 # 也会自动启动会话
然后在代理shell中:
export ANTHROPIC
BASEURL=http://127.0.0.1:3739
export OPENAI
BASEURL=http://127.0.0.1:3739/v1
代理仅绑定到 127.0.0.1。它从不存储提示文本或API密钥——只有令牌计数被写入会话。
预算意识
如果用户设置了预算或检测到高支出:
- - 在执行昂贵操作前检查 cs status --json
- 如果单次会话中 aiCost 超过 $5.00,警告用户
- 如果成本不断上升,建议更便宜的模型
重要事项
- - 在 cs start 上使用 --close-stale 以避免先前崩溃导致的session_active错误
- 如果未安装 cs,跳过会话追踪——不要阻塞用户的任务
-