mirror of
https://github.com/hellodigua/ChatLab.git
synced 2026-10-26 02:04:37 +08:00
docs(cli): add agent query usage guide
This commit is contained in:
1 parent
c4f5e06e5e
commit
98a92c73f1
5 files changed
+245
-6
No files matched your search
@@ -0,0 +1,60 @@
|
||||
---
|
||||
name: chatlab-cli
|
||||
description: Query local chat history (WeChat/QQ/Telegram/WhatsApp and more) through the chatlab CLI. Use when the user asks what a chat group talked about, who said something first, conversation stats, topics, or keyword evidence from imported chat records.
|
||||
---
|
||||
|
||||
# ChatLab CLI for AI Agents
|
||||
|
||||
`chatlab` queries locally imported chat history. Read-only for agents: search, list, stats, topics, SQL fallback. Run `chatlab manifest` once to get the full machine-readable command tree (commands, options, exit codes, examples).
|
||||
|
||||
## Contract
|
||||
|
||||
- Always pass `--format` explicitly: `agent` for message bodies (preprocessed, token-friendly text), `json` for structural data (`--no-content`, `--fields`, stats).
|
||||
- stdout carries exactly one JSON envelope per call; logs go to stderr.
|
||||
- Success: `{ ok: true, command, data, meta }`. Failure: `{ ok: false, command, error: { code, message, hint, candidates? } }`.
|
||||
- Exit codes: 0 ok, 2 bad argument/disabled capability, 3 not found, 4 ambiguous (retry with an id from `error.candidates`), 5 SQL error.
|
||||
- Pagination: when `meta.hasMore` is true, re-run the same query with `--cursor <meta.nextCursor>`.
|
||||
- Time: ISO dates (`2026-06-01`, `"2026-06-01 08:30"`), `today`, `yesterday`, or `--last 30d` (h/d/w). Date-only `--until` includes the whole day; resolved bounds are echoed in `meta.timeRange`.
|
||||
- Members: pass an id, exact name, or `me` (the data owner). Ambiguity returns candidates with ids.
|
||||
- Privacy preprocessing (desensitization, blacklist) is always on. Do not use `--raw`; it is disabled unless the user opts in.
|
||||
- `[#1021]` markers in agent text are message ids; `[#1021*]` marks search hits; `[#1021-1024]` is a merged block. Use these ids as evidence citations.
|
||||
|
||||
## Task recipes
|
||||
|
||||
```bash
|
||||
# Discover sessions (skip --session everywhere if there is only one)
|
||||
chatlab sessions list --format json
|
||||
|
||||
# "What did this group talk about today?"
|
||||
chatlab messages list --session <id> --since today --limit 100 --max-tokens 2000 --format agent
|
||||
|
||||
# "Main topics this month?" (AI summaries; falls back to keywords if empty)
|
||||
chatlab topics list --session <id> --since 2026-07-01 --format agent
|
||||
chatlab stats keywords --session <id> --last 30d --top 20 --format json
|
||||
|
||||
# "Who mentioned X first? Give evidence."
|
||||
chatlab messages search "服务器迁移" --session <id> --sort asc --limit 5 --context 3 --format agent
|
||||
|
||||
# Follow up an evidence id from [#1021*]
|
||||
chatlab messages context --id 1021 --session <id> --window 10 --format agent
|
||||
|
||||
# "What did I talk about with 小红 last month?"
|
||||
chatlab messages between --member me --member 小红 --session <id> --last 30d --format agent
|
||||
|
||||
# "Who is most active?"
|
||||
chatlab stats activity --session <id> --top 10 --format json
|
||||
|
||||
# Scout hit distribution before pulling bodies (json is correct here)
|
||||
chatlab messages search "旅游" "旅行" --session <id> --since 2026-01-01 --no-content --limit 100 --format json
|
||||
|
||||
# Next page of results
|
||||
chatlab messages search "报销" --session <id> --cursor <meta.nextCursor> --format agent
|
||||
|
||||
# Advanced fallback: read-only SQL (string cells are desensitized)
|
||||
chatlab schema --session <id> --format json
|
||||
chatlab sql "SELECT strftime('%Y-%m', ts, 'unixepoch') AS m, COUNT(*) AS n FROM message GROUP BY m" --session <id> --format json
|
||||
```
|
||||
|
||||
## Token budget
|
||||
|
||||
`--limit` caps primary hits, `--max-messages` caps context expansion, `--max-tokens` caps agent text (default 4000), `--max-chars` caps per-message length. Prefer narrowing time ranges and paginating over raising limits.
|
||||
@@ -12,6 +12,7 @@
|
||||
"bin/",
|
||||
"dist/",
|
||||
"dist-web/",
|
||||
"SKILL.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"engines": {
|
||||
|
||||
@@ -10,6 +10,7 @@ const enSidebar: DefaultTheme.SidebarItem[] = [
|
||||
{ text: 'Export Chat Records', link: '/usage/how-to-export' },
|
||||
{ text: 'Import Chat Records', link: '/usage/how-to-import' },
|
||||
{ text: 'Configure AI', link: '/usage/how-to-config-ai' },
|
||||
{ text: 'External Agent Calls', link: '/usage/cli-query' },
|
||||
{ text: 'Troubleshooting', link: '/usage/troubleshooting' },
|
||||
],
|
||||
},
|
||||
@@ -23,9 +24,7 @@ const enSidebar: DefaultTheme.SidebarItem[] = [
|
||||
},
|
||||
{
|
||||
text: 'Contributing',
|
||||
items: [
|
||||
{ text: 'Development Guide', link: '/contributing/development' },
|
||||
],
|
||||
items: [{ text: 'Development Guide', link: '/contributing/development' }],
|
||||
},
|
||||
{ text: 'Acknowledgments', link: '/contributing/acknowledgments' },
|
||||
]
|
||||
@@ -39,6 +38,7 @@ const cnSidebar: DefaultTheme.SidebarItem[] = [
|
||||
{ text: '导出聊天记录', link: '/cn/usage/how-to-export' },
|
||||
{ text: '导入聊天记录', link: '/cn/usage/how-to-import' },
|
||||
{ text: '配置 AI', link: '/cn/usage/how-to-config-ai' },
|
||||
{ text: '外部 Agent 调用', link: '/cn/usage/cli-query' },
|
||||
{ text: '故障排查', link: '/cn/usage/troubleshooting' },
|
||||
{ text: '常见问题', link: '/cn/usage/faq' },
|
||||
],
|
||||
@@ -55,9 +55,7 @@ const cnSidebar: DefaultTheme.SidebarItem[] = [
|
||||
},
|
||||
{
|
||||
text: '贡献',
|
||||
items: [
|
||||
{ text: '开发指南', link: '/cn/contributing/development' },
|
||||
],
|
||||
items: [{ text: '开发指南', link: '/cn/contributing/development' }],
|
||||
},
|
||||
{ text: '致谢', link: '/cn/contributing/acknowledgments' },
|
||||
]
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
---
|
||||
outline: deep
|
||||
---
|
||||
|
||||
# 外部 Agent 调用
|
||||
|
||||
ChatLab 可以作为 Codex、Claude Code、HermesAgent 等外部 Agent 的本地聊天数据工具层。外部 Agent 负责对话、规划和总结,ChatLab 负责受控地读取、搜索、统计和整理本地聊天记录。
|
||||
|
||||
这种模式不需要打开 ChatLab 网页,也不需要先启动 ChatLab 桌面界面。外部 Agent 会按需调用轻量的 `chatlab` CLI,在本地完成受控查询、搜索和统计,并拿到已经过隐私预处理的文本。
|
||||
|
||||
## 适合什么场景
|
||||
|
||||
- 你已经在使用 Codex、Claude Code、HermesAgent 等外部 Agent,并希望复用它们的订阅、token、模型能力和工作流。
|
||||
- 你希望外部 Agent 能按需分析 ChatLab 里的聊天记录,但不想把原始数据库或完整聊天导出直接交给 Agent。
|
||||
- 你希望先由 ChatLab 完成脱敏、黑名单过滤、清洗、合并和截断,再把适合分析的文本与证据 id 提供给 Agent。
|
||||
|
||||
`chatlab` CLI 提供一组面向 AI Agent 优化、同时人类可读的查询命令。所有查询命令只读,默认应用你在 ChatLab 中配置的隐私预处理(脱敏、黑名单)。
|
||||
|
||||
安装:`npm i chatlab-cli -g`(需要 Node.js ≥ 20),并先在 ChatLab 中导入聊天记录。
|
||||
|
||||
## 命令总览
|
||||
|
||||
```bash
|
||||
chatlab sessions list # 列出已导入的会话
|
||||
chatlab sessions show # 查看单个会话详情
|
||||
chatlab members list # 会话成员列表
|
||||
chatlab members history # 成员改名历史
|
||||
chatlab messages list # 按时间窗口列消息
|
||||
chatlab messages search <关键词...> # 关键词搜索(支持多词、上下文、翻页)
|
||||
chatlab messages context --id <id> # 查看某条消息前后现场
|
||||
chatlab messages between # 两个成员之间的对话
|
||||
chatlab stats overview # 会话概览统计
|
||||
chatlab stats activity # 成员活跃度排行
|
||||
chatlab stats time --by day # 时间分布(hour/weekday/day/month)
|
||||
chatlab stats keywords # 高频词(已过隐私过滤)
|
||||
chatlab stats response # 回复速度排行
|
||||
chatlab topics list # AI 分段摘要列表
|
||||
chatlab topics show --id <id> # 某个分段的原始消息
|
||||
chatlab sql "<SELECT ...>" # 只读 SQL 兜底(字符串默认脱敏)
|
||||
chatlab schema # 查看数据库表结构
|
||||
chatlab manifest # 机读命令清单(给 Agent 一次读全)
|
||||
```
|
||||
|
||||
只有一个会话时可省略 `--session`;多个会话时命令会返回候选列表提示消歧。
|
||||
|
||||
## 输出格式
|
||||
|
||||
通过 `--format` 显式指定:
|
||||
|
||||
- **`agent`**:推荐给 AI Agent 的格式。返回 JSON 信封,正文是经过完整预处理管道(清洗、黑名单、去噪、合并连续发言、脱敏、token 截断)的紧凑文本,每条消息带 `[#id]` 引用标记,搜索命中标 `[#id*]`。
|
||||
- **`json`**:程序化解析格式。返回结构化消息数组,仍应用隐私步骤(清洗、黑名单、脱敏),但不合并、不去噪。适合 `--no-content`、`--fields` 之类的结构化勘察。
|
||||
- **`text`**:人类可读输出(终端默认)。
|
||||
|
||||
agent/json 模式下 stdout 只包含一个 JSON 响应信封,日志一律走 stderr:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"command": "messages.search",
|
||||
"data": { "text": "returned: 2\n\n--- 2026/6/1 ---\n[#1*] 09:00 老王: 今年五一去旅游吧..." },
|
||||
"meta": { "totalHits": 2, "returnedHits": 2, "hasMore": false, "preprocess": { "desensitized": true }, "apiVersion": 1 }
|
||||
}
|
||||
```
|
||||
|
||||
失败时返回 `{ "ok": false, "error": { "code", "message", "hint", "candidates" } }`,并配合语义化退出码:0 成功、2 参数错误/能力未开启、3 未找到、4 歧义(附候选列表)、5 SQL 错误。
|
||||
|
||||
## 常用查询参数
|
||||
|
||||
- **时间**:`--since` / `--until` 支持 `2026-06-01`、`"2026-06-01 08:30"`、ISO 8601、`today`、`yesterday`;`--last 30d` 支持 h/d/w。日期形式的 `--until` 包含整天,解析后的绝对边界回显在 `meta.timeRange`。
|
||||
- **成员**:`--member` 接受成员 id、精确名称或 `me`(数据所有者);重名时返回候选 id。
|
||||
- **翻页**:`meta.hasMore` 为 true 时,用 `--cursor <meta.nextCursor>` 取下一页;cursor 与查询条件绑定。
|
||||
- **Token 控制**:`--limit`(主对象数)、`--max-messages`(上下文展开上限)、`--max-tokens`(agent 正文预算,默认 4000)、`--max-chars`(单条内容截断)。
|
||||
|
||||
## 隐私边界
|
||||
|
||||
- 所有查询命令默认应用你在 ChatLab 设置中的脱敏规则与黑名单,包括 `stats keywords` 的词表、`topics list` 的摘要和 `sql` 结果中的字符串字段。
|
||||
- `--raw`(绕过预处理)默认禁用,仅当你显式执行 `chatlab config set cli.allow_raw true` 或设置 `CHATLAB_CLI_ALLOW_RAW=1` 后可用。
|
||||
- 不需要 SQL 兜底能力时,可用 `chatlab config set cli.allow_sql false` 关闭 `sql` 命令。
|
||||
|
||||
## 给 Agent 的使用指南
|
||||
|
||||
npm 包内附带 `SKILL.md`(Agent 使用指南:命令速查 + 任务配方),可放入项目的 `AGENTS.md`、Claude Code skill 或 Cursor rules。也可以让 Agent 直接执行 `chatlab manifest` 获取机读命令清单。
|
||||
|
||||
典型配方——"谁最早提到某个问题?给出证据":
|
||||
|
||||
```bash
|
||||
chatlab messages search "服务器迁移" --sort asc --limit 5 --context 3 --format agent
|
||||
# 从返回文本的 [#1021*] 标记拿到消息 id,再深挖现场:
|
||||
chatlab messages context --id 1021 --window 10 --format agent
|
||||
```
|
||||
@@ -0,0 +1,90 @@
|
||||
---
|
||||
outline: deep
|
||||
---
|
||||
|
||||
# External Agent Calls
|
||||
|
||||
ChatLab can act as the local chat-data tool layer for external agents such as Codex, Claude Code, and HermesAgent. The agent handles conversation, planning, and synthesis; ChatLab handles controlled local reads, search, statistics, and organization of local chat records.
|
||||
|
||||
This mode does not require opening the ChatLab web UI, and it does not require starting the ChatLab desktop interface first. External agents call the lightweight `chatlab` CLI on demand, run controlled local queries, searches, and statistics, then receive privacy-processed text.
|
||||
|
||||
## When to use it
|
||||
|
||||
- You already use an external agent such as Codex, Claude Code, or HermesAgent, and want to reuse its subscription, tokens, model capabilities, and workflow.
|
||||
- You want the agent to analyze ChatLab records on demand, but you do not want to hand it the raw database or a full chat export.
|
||||
- You want ChatLab to handle desensitization, blacklist filtering, cleaning, merging, and truncation before sending analysis-ready text and evidence ids to the agent.
|
||||
|
||||
The `chatlab` CLI ships a set of query commands optimized for AI agents while staying human-readable. All query commands are read-only and apply your ChatLab privacy preprocessing (desensitization, blacklist) by default.
|
||||
|
||||
Install with `npm i chatlab-cli -g` (Node.js ≥ 20) and import chat records in ChatLab first.
|
||||
|
||||
## Command overview
|
||||
|
||||
```bash
|
||||
chatlab sessions list # List imported sessions
|
||||
chatlab sessions show # Session details
|
||||
chatlab members list # Session members
|
||||
chatlab members history # Member name history
|
||||
chatlab messages list # List messages in a time window
|
||||
chatlab messages search <keywords...> # Keyword search (multi-word, context, paging)
|
||||
chatlab messages context --id <id> # Messages around a specific id
|
||||
chatlab messages between # Conversation between two members
|
||||
chatlab stats overview # Session overview
|
||||
chatlab stats activity # Member activity ranking
|
||||
chatlab stats time --by day # Time distribution (hour/weekday/day/month)
|
||||
chatlab stats keywords # High-frequency words (privacy-filtered)
|
||||
chatlab stats response # Reply speed ranking
|
||||
chatlab topics list # AI segment summaries
|
||||
chatlab topics show --id <id> # Original messages of one segment
|
||||
chatlab sql "<SELECT ...>" # Read-only SQL fallback (strings desensitized)
|
||||
chatlab schema # Database schema
|
||||
chatlab manifest # Machine-readable command manifest for agents
|
||||
```
|
||||
|
||||
With a single session `--session` can be omitted; with multiple sessions, commands return candidates for disambiguation.
|
||||
|
||||
## Output formats
|
||||
|
||||
Pass `--format` explicitly:
|
||||
|
||||
- **`agent`**: recommended for AI agents. A JSON envelope whose body is compact text produced by the full preprocessing pipeline (cleaning, blacklist, denoising, merging consecutive messages, desensitization, token-aware truncation). Every message carries a `[#id]` citation marker; search hits are marked `[#id*]`.
|
||||
- **`json`**: for programmatic parsing. Structured message items with privacy steps applied (cleaning, blacklist, desensitization) but no merging or denoising. The right choice for structural scouting with `--no-content` / `--fields`.
|
||||
- **`text`**: human-readable output (TTY default).
|
||||
|
||||
In agent/json mode stdout contains exactly one JSON envelope; logs go to stderr:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"command": "messages.search",
|
||||
"data": { "text": "returned: 2\n\n--- 2026/6/1 ---\n[#1*] 09:00 Wang: how about a trip on May Day..." },
|
||||
"meta": { "totalHits": 2, "returnedHits": 2, "hasMore": false, "preprocess": { "desensitized": true }, "apiVersion": 1 }
|
||||
}
|
||||
```
|
||||
|
||||
Failures return `{ "ok": false, "error": { "code", "message", "hint", "candidates" } }` with semantic exit codes: 0 success, 2 invalid argument or disabled capability, 3 not found, 4 ambiguous (with candidates), 5 SQL error.
|
||||
|
||||
## Common query parameters
|
||||
|
||||
- **Time**: `--since` / `--until` accept `2026-06-01`, `"2026-06-01 08:30"`, ISO 8601, `today`, `yesterday`; `--last 30d` supports h/d/w. Date-only `--until` includes the whole day; resolved bounds are echoed in `meta.timeRange`.
|
||||
- **Members**: `--member` accepts a member id, exact name, or `me` (the data owner); ambiguous names return candidate ids.
|
||||
- **Paging**: when `meta.hasMore` is true, pass `--cursor <meta.nextCursor>`; cursors are bound to the exact query conditions.
|
||||
- **Token budget**: `--limit` (primary objects), `--max-messages` (context expansion cap), `--max-tokens` (agent text budget, default 4000), `--max-chars` (per-message truncation).
|
||||
|
||||
## Privacy boundaries
|
||||
|
||||
- All query commands apply your ChatLab desensitize rules and blacklist by default — including the `stats keywords` vocabulary, `topics list` summaries, and string cells in `sql` results.
|
||||
- `--raw` (bypassing preprocessing) is disabled by default; it only works after you explicitly run `chatlab config set cli.allow_raw true` or set `CHATLAB_CLI_ALLOW_RAW=1`.
|
||||
- If you don't need the SQL fallback, disable it with `chatlab config set cli.allow_sql false`.
|
||||
|
||||
## Agent usage guide
|
||||
|
||||
The npm package ships a `SKILL.md` (command quick reference + task recipes) you can drop into your project's `AGENTS.md`, a Claude Code skill, or Cursor rules. Agents can also run `chatlab manifest` to fetch the machine-readable command tree in one call.
|
||||
|
||||
A typical recipe — "who mentioned this first? give evidence":
|
||||
|
||||
```bash
|
||||
chatlab messages search "server migration" --sort asc --limit 5 --context 3 --format agent
|
||||
# Take the message id from the [#1021*] marker in the returned text, then dig in:
|
||||
chatlab messages context --id 1021 --window 10 --format agent
|
||||
```
|
||||
Reference in new issue
Block a user