Compare commits

..

2 Commits

Author SHA1 Message Date
jackwener 4b16dde2e8 refactor: use CliError subclasses in chatgpt, cursor, and codex adapters
- chatgpt: ConfigError (macOS check), CommandExecutionError
- cursor: SelectorError (input element), EmptyResultError (no history)
- codex: SelectorError (composer/input element)

This enables better error handling and user-facing error messages.

10 files changed, 223 tests pass.
2026-03-24 21:09:27 +08:00
jackwener 98499792b7 refactor: use CliError subclasses in chatgpt adapters
Replace raw Error throws with appropriate CliError subclasses:
- chatgpt/status.ts: ConfigError for platform limitation
- chatgpt/ask.ts: ConfigError for platform limitation
- chatgpt/new.ts: ConfigError for platform limitation
- chatgpt/read.ts: ConfigError for platform limitation, CommandExecutionError for read failures

This enables better error handling and user-facing error messages.
2026-03-24 21:09:26 +08:00
601 changed files with 5051 additions and 51349 deletions
@@ -0,0 +1,249 @@
---
name: cross-project-adapter-migration
description: "Cross-project CLI command migration workflow for opencli. Use when importing commands from external CLI projects (python/node) like rdt-cli, twitter-cli, etc. Covers: source analysis → gap matrix → batch migration → README/SKILL.md update."
---
# Cross-Project Adapter Migration
> 从外部 CLI 项目(Python/Node/Go 等)批量迁移命令到 opencli 的标准化流程。
## When to Use
- 用户说"把 xxx-cli 的命令迁移过来"
- 用户说"看看 xxx 项目有什么可以借鉴的"
- 用户说"对齐 xxx-cli 的功能"
- 在为新平台扩展 opencli 时,发现已有第三方 CLI 工具
## Prerequisites
- 熟悉 [CLI-EXPLORER.md](file:///Users/jakevin/code/opencli/CLI-EXPLORER.md)adapter 开发决策树)
- 熟悉 [SKILL.md](file:///Users/jakevin/code/opencli/SKILL.md)(命令参考 & 模板)
---
## Phase 1: 源项目分析
### 1.1 克隆 & 理解源项目
```bash
# 克隆源项目到 /tmp 做分析
git clone <source_repo_url> /tmp/<source-cli>
```
分析重点:
- **命令列表**:找到所有可用命令(查看 CLI 入口文件、help 输出或 README
- **认证方式**CookieAPI KeyOAuth?浏览器自动化?
- **数据源**:公开 APIGraphQL?页面抓取?
- **输出字段**:每个命令返回哪些数据字段
### 1.2 生成命令清单
列出源项目所有命令,包括:
| 命令 | 类型 | API/方法 | 输出字段 |
|------|------|---------|---------|
| `xxx feed` | Read | `GET /api/feed` | title, author, time |
| `xxx post` | Write | `POST /api/tweet` | status, id |
---
## Phase 2: 功能对比矩阵
### 2.1 查看 opencli 现有命令
```bash
ls src/clis/<site>/ # 查看已有适配器
opencli list | grep <site> # 确认已注册命令
```
### 2.2 生成对比矩阵
对每个源项目命令,标注三种状态:
| 功能 | 源项目 | opencli 现有 | 行动 |
|------|--------|-------------|------|
| feed | ✅ `xxx feed` | ❌ 无 | ✅ **新增** |
| search | ✅ `xxx search` | ✅ `search.ts` | ❌ 已有,跳过 |
| hot | ✅ `xxx hot` | ⚠️ `hot.yaml`(不完整) | ✅ **增强** |
| like | ✅ `xxx like` | ✅ `like.ts` | ❌ 已有,跳过 |
### 2.3 筛选迁移目标
去掉已有的、低价值的,保留高价值缺失命令,按 Read/Write 分类:
**筛选原则**
- ✅ 高使用频率的命令优先
- ✅ 已有但不完整的命令标记为"增强"
- ❌ 源项目特有但 opencli 架构不支持的功能(如需要持久化存储的)跳过
- ❌ 与现有功能完全重复的跳过
---
## Phase 3: 批量实现
> [!IMPORTANT]
> 实现前必须查阅 [CLI-EXPLORER.md](file:///Users/jakevin/code/opencli/CLI-EXPLORER.md) 确认策略选择。
### 3.1 选择实现方式
基于决策树分类:
| 类别 | 方式 | 适用条件 |
|------|------|---------|
| **Read + 简单 API** | YAML pipeline | 纯 fetch/select/map,无复杂 JS |
| **Read + GraphQL/分页/签名** | TypeScript adapter | 需要 JS 逻辑 |
| **Write 操作** | TypeScript + `Strategy.UI` | 点击/输入等 DOM 操作 |
| **Write + API** | TypeScript + `Strategy.COOKIE/HEADER` | 直接 POST API |
### 3.2 实现顺序
**先 Read 后 Write,先 YAML 后 TS**
1. **Phase A**: YAML Read 适配器(最快,通常每个 10-20 行)
2. **Phase B**: TS Read 适配器(需要 evaluate/intercept 的)
3. **Phase C**: TS Write 适配器(需 UI 自动化或 POST API
### 3.3 实现模板
#### YAML Read 适配器模板(Cookie 策略)
```yaml
site: <site>
name: <command>
description: <描述>
domain: www.<site>.com
strategy: cookie
browser: true
args:
limit:
type: int
default: 20
pipeline:
- navigate: https://www.<site>.com
- evaluate: |
(async () => {
const res = await fetch('<api_endpoint>', { credentials: 'include' });
const d = await res.json();
return (d.data?.items || []).map(item => ({
title: item.title,
// ... map source fields
}));
})()
- map:
rank: ${{ index + 1 }}
title: ${{ item.title }}
- limit: ${{ args.limit }}
columns: [rank, title]
```
#### TS Write 适配器模板(UI 策略)
```typescript
import { cli, Strategy } from '../../registry.js';
cli({
site: '<site>',
name: '<command>',
description: '<描述>',
strategy: Strategy.UI,
args: [{ name: 'target', required: true, help: '<参数说明>' }],
columns: ['status', 'message'],
func: async (page, kwargs) => {
await page.goto(`https://www.<site>.com/${kwargs.target}`);
await page.wait({ text: '<expected_text>', timeout: 10 });
// 获取 snapshot 找到目标按钮
const snapshot = await page.accessibility.snapshot();
// 点击按钮 ...
return [{ status: 'success', message: '<action> completed' }];
},
});
```
### 3.4 公共模式复用
迁移过程中如果发现多个适配器共享逻辑,考虑提取到 `src/clis/<site>/utils.ts` 工具文件:
```typescript
// src/clis/<site>/utils.ts
export async function fetchWithAuth(page, url) { ... }
export function parseItem(raw) { ... }
```
---
## Phase 4: 验证 & 发布
### 4.1 构建验证
```bash
npx tsc --noEmit # TypeScript 编译检查
opencli list | grep <site> # 确认所有命令已注册
```
### 4.2 运行验证(关键!)
每个新命令必须实际运行:
```bash
# Read 命令
opencli <site> <command> --limit 3 -f json
opencli <site> <command> --limit 3 -v # verbose 查看 pipeline
# Write 命令(谨慎!会实际操作)
opencli <site> <command> <test_target>
```
### 4.3 更新文档
迁移完成后必须更新以下文件:
1. **README.md** — 在对应平台区域添加新命令示例
2. **SKILL.md** — 在 Commands Reference 中添加新命令
### 4.4 提交 & 推送
```bash
git add -A
git commit -m "feat(<site>): migrate <N> commands from <source-cli>
- Phase A: <N> YAML adapters (read operations)
- Phase B: <N> TS adapters (write operations)
- Source: <source_repo_url>"
git push
```
---
## Checklist
- [ ] 源项目命令清单已生成
- [ ] 对比矩阵已确认,高价值缺失命令已筛选
- [ ] 用户确认迁移范围
- [ ] Phase A: YAML Read 适配器已完成
- [ ] Phase B: TS Read 适配器已完成
- [ ] Phase C: TS Write 适配器已完成
- [ ] `npx tsc --noEmit` 编译通过
- [ ] 所有新命令已实际运行验证
- [ ] README.md 已更新
- [ ] SKILL.md 已更新
- [ ] 已 commit + push
## 实战案例参考
### rdt-cli → opencli Reddit2026-03-16
- **源项目**: `rdt-cli`25 个 Python 命令)
- **筛选结果**: 13 个高价值命令
- **实现**: 7 个 YAMLread + 6 个 TSwrite
- **产出**: +11 文件,+767 行代码,Reddit 适配器从 4 → 15+275%
### twitter-cli → opencli Twitter2026-03-16
- **源项目**: `twitter-cli`20+ Python 命令)
- **筛选结果**: 11 个待实现
- **策略**: Read 用 `Strategy.COOKIE` + GraphQL fetchWrite 用 `Strategy.UI`
@@ -0,0 +1,54 @@
---
description: Migrate commands from an external CLI project into opencli adapters
---
// turbo-all
## Steps
1. Clone the source CLI project for analysis:
```bash
git clone <source_repo_url> /tmp/<source-cli>
```
2. Analyze source project: list all commands, auth method, API endpoints, and output fields.
3. Check existing opencli adapters for the target site:
```bash
ls src/clis/<site>/
opencli list | grep <site>
```
4. Generate a comparison matrix table (source commands vs opencli existing). Mark each as: ✅ **New** / ✅ **Enhance** / ❌ **Skip**. Ask user to confirm which commands to migrate.
5. Implement YAML Read adapters first (highest ROI, 10-20 lines each). Place files in `src/clis/<site>/<name>.yaml`.
6. Implement TS Read adapters for complex cases (GraphQL, pagination, signing). Place files in `src/clis/<site>/<name>.ts`.
7. Implement TS Write adapters using `Strategy.UI` or `Strategy.COOKIE`. Place files in `src/clis/<site>/<name>.ts`.
8. Verify build:
```bash
npx tsc --noEmit
```
9. Verify all commands are registered:
```bash
opencli list | grep <site>
```
10. Run each new command to verify it works:
```bash
opencli <site> <command> --limit 3 -f json
```
11. Update README.md with new command examples in the appropriate platform section.
12. Update SKILL.md Commands Reference with new commands.
13. Commit and push:
```bash
git add -A
git commit -m "feat(<site>): migrate <N> commands from <source-cli>"
git push
```
+4 -5
View File
@@ -1,5 +1,5 @@
name: Setup Chrome
description: Install real Chrome for browser testing (with xvfb on Linux)
name: Setup Chrome + xvfb
description: Install real Chrome and xvfb virtual display for headed browser testing
outputs:
chrome-path:
@@ -19,9 +19,8 @@ runs:
shell: bash
run: |
echo "Chrome path: ${{ steps.setup-chrome.outputs.chrome-path }}"
"${{ steps.setup-chrome.outputs.chrome-path }}" --version
${{ steps.setup-chrome.outputs.chrome-path }} --version
- name: Install xvfb (Linux only)
if: runner.os == 'Linux'
- name: Install xvfb for headed mode
shell: bash
run: sudo apt-get install -y xvfb
+1 -3
View File
@@ -24,10 +24,8 @@ Related issue:
- [ ] Added doc page under `docs/adapters/` (if new adapter)
- [ ] Updated `docs/adapters/index.md` table (if new adapter)
- [ ] Updated sidebar in `docs/.vitepress/config.mts` (if new adapter)
- [ ] Updated `README.md` / `README.zh-CN.md` when command discoverability changed
- [ ] Used positional args for the command's primary subject unless a named flag is clearly better
- [ ] Normalized expected adapter failures to `CliError` subclasses instead of raw `Error`
## Screenshots / Output
<!-- If applicable, paste CLI output or screenshots here. -->
+6 -8
View File
@@ -4,14 +4,8 @@ on:
push:
branches: [ "main" ]
tags: [ "v*.*.*" ]
paths:
- 'extension/**'
- '.github/workflows/build-extension.yml'
pull_request:
branches: [ "main" ]
paths:
- 'extension/**'
- '.github/workflows/build-extension.yml'
permissions:
contents: write
@@ -39,8 +33,12 @@ jobs:
working-directory: extension
- name: Prepare extension package
run: npm run package:release -- --out ../extension-package
working-directory: extension
run: |
rm -rf extension-package
mkdir -p extension-package
cp extension/manifest.json extension-package/
cp -R extension/dist extension-package/
cp -R extension/icons extension-package/
- name: Create Extension ZIP
run: |
+6 -48
View File
@@ -16,11 +16,7 @@ concurrency:
jobs:
# ── Fast gate: typecheck + build ──
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
@@ -39,15 +35,12 @@ jobs:
run: npm run build
# ── Unit tests (vitest shard) ──
# PR: ubuntu + Node 22 only (fast feedback, 2 jobs).
# Push to main/dev: full matrix for cross-platform/cross-version coverage (12 jobs).
unit-test:
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
os: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && fromJSON('["ubuntu-latest","macos-latest","windows-latest"]') || fromJSON('["ubuntu-latest"]') }}
node-version: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && fromJSON('["20","22"]') || fromJSON('["22"]') }}
node-version: ['20', '22']
shard: [1, 2]
steps:
- uses: actions/checkout@v6
@@ -63,28 +56,6 @@ jobs:
- name: Run unit tests (Node ${{ matrix.node-version }}, shard ${{ matrix.shard }}/2)
run: npm test -- --reporter=verbose --shard=${{ matrix.shard }}/2
# ── Bun compatibility check ──
bun-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.3.5
- uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run unit tests under Bun
run: bun vitest run --project unit --reporter=verbose
# Adapter tests are pure unit tests — OS doesn't affect results.
adapter-test:
runs-on: ubuntu-latest
needs: build
@@ -106,13 +77,7 @@ jobs:
smoke-test:
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
needs: build
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
# NOTE: Windows excluded — browser-actions/setup-chrome hangs during
# Chrome MSI installation on Windows runners (known issue).
os: [ubuntu-latest, macos-latest]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
@@ -124,24 +89,17 @@ jobs:
- name: Install dependencies
run: npm ci
- name: Setup Chrome
- name: Setup Chrome + xvfb
uses: ./.github/actions/setup-chrome
id: setup-chrome
- name: Build
run: npm run build
- name: Run smoke tests (Linux, via xvfb)
if: runner.os == 'Linux'
- name: Run smoke tests
run: |
xvfb-run --auto-servernum --server-args="-screen 0 1280x720x24" \
npx vitest run tests/smoke/ --reporter=verbose
env:
OPENCLI_BROWSER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
- name: Run smoke tests (macOS / Windows)
if: runner.os != 'Linux'
run: npx vitest run tests/smoke/ --reporter=verbose
env:
OPENCLI_BROWSER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
timeout-minutes: 15
+3 -36
View File
@@ -3,28 +3,8 @@ name: E2E Headed Chrome
on:
push:
branches: [main, dev]
paths:
- 'extension/**'
- 'src/browser/**'
- 'src/daemon.ts'
- 'src/execution.ts'
- 'src/interceptor.ts'
- 'tests/e2e/**'
- 'tests/smoke/**'
- '.github/actions/setup-chrome/**'
- '.github/workflows/e2e-headed.yml'
pull_request:
branches: [main, dev]
paths:
- 'extension/**'
- 'src/browser/**'
- 'src/daemon.ts'
- 'src/execution.ts'
- 'src/interceptor.ts'
- 'tests/e2e/**'
- 'tests/smoke/**'
- '.github/actions/setup-chrome/**'
- '.github/workflows/e2e-headed.yml'
workflow_dispatch:
concurrency:
@@ -33,13 +13,7 @@ concurrency:
jobs:
e2e-headed:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
# NOTE: Windows excluded — browser-actions/setup-chrome hangs during
# Chrome MSI installation on Windows runners (known issue).
os: [ubuntu-latest, macos-latest]
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v6
@@ -52,23 +26,16 @@ jobs:
- name: Install dependencies
run: npm ci
- name: Setup Chrome
- name: Setup Chrome + xvfb
uses: ./.github/actions/setup-chrome
id: setup-chrome
- name: Build
run: npm run build
- name: Run E2E tests (Linux, via xvfb)
if: runner.os == 'Linux'
- name: Run E2E tests (headed Chrome + xvfb)
run: |
xvfb-run --auto-servernum --server-args="-screen 0 1280x720x24" \
npx vitest run tests/e2e/ --reporter=verbose
env:
OPENCLI_BROWSER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
- name: Run E2E tests (macOS / Windows)
if: runner.os != 'Linux'
run: npx vitest run tests/e2e/ --reporter=verbose
env:
OPENCLI_BROWSER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
+30
View File
@@ -0,0 +1,30 @@
name: Publish Any Commit
on:
push:
branches: [main, dev]
pull_request:
branches: [main, dev]
permissions: {}
jobs:
publish:
if: ${{ vars.PKG_PR_NEW_ENABLED == 'true' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Publish to pkg.pr.new
run: npx pkg-pr-new publish
+3
View File
@@ -31,3 +31,6 @@ jobs:
- name: npm audit (production)
run: npm audit --omit=dev --audit-level=high
- name: Check for known vulnerabilities
run: npx --yes audit-ci@^7 --high --skip-dev
-2
View File
@@ -22,5 +22,3 @@ docs/.vitepress/cache
# Database files
*.db
autoresearch/results/
extension/dist/
-162
View File
@@ -1,167 +1,5 @@
# Changelog
## [1.6.1](https://github.com/jackwener/opencli/compare/v1.6.0...v1.6.1) (2026-04-02)
### Bug Fixes
* sync package-lock.json version with package.json ([#698](https://github.com/jackwener/opencli/issues/698))
## [1.6.0](https://github.com/jackwener/opencli/compare/v1.5.9...v1.6.0) (2026-04-02)
### Features
* **opencli-operate:** add browser control commands for Claude Code skill ([#614](https://github.com/jackwener/opencli/issues/614))
* **docs:** add tab completion to getting started guides ([#658](https://github.com/jackwener/opencli/issues/658))
### Bug Fixes
* **twitter:** resolve article ID to tweet ID before GraphQL query ([#688](https://github.com/jackwener/opencli/issues/688))
* **xiaohongshu:** clarify empty note shell hint ([#686](https://github.com/jackwener/opencli/issues/686))
* **skills:** add YAML frontmatter for discovery and improve descriptions ([#694](https://github.com/jackwener/opencli/issues/694))
### Refactoring
* centralize daemon transport client ([#692](https://github.com/jackwener/opencli/issues/692))
## [1.5.9](https://github.com/jackwener/opencli/compare/v1.5.8...v1.5.9) (2026-04-02)
### Features
* **amazon:** add browser adapter — bestsellers, search, product, offer, discussion ([#659](https://github.com/jackwener/opencli/issues/659))
* **skills:** create skills/ directory structure with opencli-usage, opencli-explorer, opencli-oneshot ([#670](https://github.com/jackwener/opencli/issues/670))
* **record:** add minimal record write candidates ([#665](https://github.com/jackwener/opencli/issues/665))
### Refactoring
* src cleanup — deduplicate errors, cache VM, extract BasePage, remove Playwright MCP legacy ([#667](https://github.com/jackwener/opencli/issues/667))
* remove bind-current, restore owned-only browser automation model ([#664](https://github.com/jackwener/opencli/issues/664))
### Chores
* remove .agents directory ([#668](https://github.com/jackwener/opencli/issues/668))
## [1.5.8](https://github.com/jackwener/opencli/compare/v1.5.7...v1.5.8) (2026-04-01)
### Bug Fixes
* **extension:** avoid mutating healthy tabs before debugger attach and add regression coverage ([#662](https://github.com/jackwener/opencli/issues/662))
## [1.5.7](https://github.com/jackwener/opencli/compare/v1.5.6...v1.5.7) (2026-04-01)
### Features
* **daemon:** replace 5min idle timeout with long-lived daemon model (4h default, dual-condition exit) ([#641](https://github.com/jackwener/opencli/issues/641))
* **daemon:** add `opencli daemon status/stop/restart` CLI commands ([#641](https://github.com/jackwener/opencli/issues/641))
* **youtube:** add search filters — `--type` shorts/video/channel, `--upload`, `--sort` ([#616](https://github.com/jackwener/opencli/issues/616))
* **notebooklm:** add read commands and compatibility layer ([#622](https://github.com/jackwener/opencli/issues/622))
* **instagram:** add media download command ([#623](https://github.com/jackwener/opencli/issues/623))
* **stealth:** harden CDP debugger detection countermeasures ([#644](https://github.com/jackwener/opencli/issues/644))
* **v2ex:** add id, node, url, content, member fields to topic output ([#646](https://github.com/jackwener/opencli/issues/646), [#648](https://github.com/jackwener/opencli/issues/648))
* **electron:** auto-launcher — zero-config CDP connection ([#653](https://github.com/jackwener/opencli/issues/653))
### Bug Fixes
* **douyin:** repair creator draft flow — switch from broken API pipeline to UI-driven approach ([#640](https://github.com/jackwener/opencli/issues/640))
* **douyin:** support current creator API response shapes for activities, profile, collections, hashtag, videos ([#618](https://github.com/jackwener/opencli/issues/618))
* **bilibili:** distinguish login-gated subtitles from empty results ([#645](https://github.com/jackwener/opencli/issues/645))
* **facebook:** avoid in-page redirect in search — use navigate step instead of window.location.href ([#642](https://github.com/jackwener/opencli/issues/642))
* **substack:** update selectors for DOM redesign ([#624](https://github.com/jackwener/opencli/issues/624))
* **weread:** recover book details from cached shelf fallback ([#628](https://github.com/jackwener/opencli/issues/628))
* **docs:** use relative links in adapter index ([#629](https://github.com/jackwener/opencli/issues/629))
## [1.4.1](https://github.com/jackwener/opencli/compare/v1.4.0...v1.4.1) (2026-03-25)
### Features
* **douyin:** add Douyin creator center adapter — 14 commands, 8-phase publish pipeline ([#416](https://github.com/jackwener/opencli/issues/416))
* **weibo,youtube:** add Weibo commands and YouTube channel/comments ([#418](https://github.com/jackwener/opencli/issues/418))
* **twitter:** add filter option for search ([#410](https://github.com/jackwener/opencli/issues/410))
* **extension:** add popup UI, privacy policy, and CSP for Chrome Web Store ([#415](https://github.com/jackwener/opencli/issues/415))
* add url field to 9 search adapters (67% -> 97% coverage) ([#414](https://github.com/jackwener/opencli/issues/414))
### Bug Fixes
* **extension:** improve UX when daemon is not running — show hint in popup, reduce reconnect noise ([#424](https://github.com/jackwener/opencli/issues/424))
* remove incorrect gws and readwise external CLI entries ([#419](https://github.com/jackwener/opencli/issues/419), [#420](https://github.com/jackwener/opencli/issues/420))
### CI
* limit default e2e to bilibili/zhihu/v2ex, gate extended browser tests ([#421](https://github.com/jackwener/opencli/issues/421), [#423](https://github.com/jackwener/opencli/issues/423))
## [1.4.0](https://github.com/jackwener/opencli/compare/v1.3.3...v1.4.0) (2026-03-25)
### Features
* **pixiv:** add Pixiv adapter — ranking, search, user illusts, detail, download ([#403](https://github.com/jackwener/opencli/issues/403))
* **plugin:** add lifecycle hooks API — onStartup, onBeforeExecute, onAfterExecute ([#376](https://github.com/jackwener/opencli/issues/376))
* **plugin:** validate plugin structure on install and update ([#364](https://github.com/jackwener/opencli/issues/364))
* **xueqiu:** add Danjuan fund account commands — fund-holdings, fund-snapshot ([#391](https://github.com/jackwener/opencli/issues/391))
* **tiktok:** add video URL to search results ([#404](https://github.com/jackwener/opencli/issues/404))
* **linkedin:** add timeline feed command ([#342](https://github.com/jackwener/opencli/issues/342))
* **jd:** add JD.com product details adapter ([#344](https://github.com/jackwener/opencli/issues/344))
* **web:** add generic `web read` command for any URL → Markdown ([#343](https://github.com/jackwener/opencli/issues/343))
* **dictionary:** add dictionary search, synonyms, and examples adapters ([#241](https://github.com/jackwener/opencli/issues/241))
### Bug Fixes
* **analysis:** fix hasLimit using wrong Set (SEARCH_PARAMS → LIMIT_PARAMS) ([#412](https://github.com/jackwener/opencli/issues/412))
* **pipeline:** remove phantom scroll step — declared but never registered ([#412](https://github.com/jackwener/opencli/issues/412))
* **validate:** add missing download step to KNOWN_STEP_NAMES ([#412](https://github.com/jackwener/opencli/issues/412))
* **extension:** security hardening — tab isolation, URL validation, cookie scope ([#409](https://github.com/jackwener/opencli/issues/409))
* **sort:** use localeCompare with natural numeric sort by default ([#306](https://github.com/jackwener/opencli/issues/306))
* **pipeline:** evaluate chained || in template engine ([#305](https://github.com/jackwener/opencli/issues/305))
* **pipeline:** check HTTP status in fetch step ([#384](https://github.com/jackwener/opencli/issues/384))
* **plugin:** resolve Windows path and symlink issues ([#400](https://github.com/jackwener/opencli/issues/400))
* **download:** scope cookies to target domain ([#385](https://github.com/jackwener/opencli/issues/385))
* **extension:** fix same-url navigation timeout ([#380](https://github.com/jackwener/opencli/issues/380))
* fix ChatWise Windows connect ([#405](https://github.com/jackwener/opencli/issues/405))
* resolve 6 critical + 11 important bugs from deep code review ([#337](https://github.com/jackwener/opencli/issues/337), [#340](https://github.com/jackwener/opencli/issues/340))
* harden security-sensitive execution paths ([#335](https://github.com/jackwener/opencli/issues/335))
* **stealth:** harden anti-detection against advanced fingerprinting ([#357](https://github.com/jackwener/opencli/issues/357))
### Code Quality
* replace all `catch (err: any)` with typed `getErrorMessage()` across 13 files ([#412](https://github.com/jackwener/opencli/issues/412))
* adopt CliError subclasses in social and desktop adapters ([#367](https://github.com/jackwener/opencli/issues/367), [#372](https://github.com/jackwener/opencli/issues/372), [#375](https://github.com/jackwener/opencli/issues/375))
* simplify codebase with type dedup, shared analysis module, and consistent naming ([#373](https://github.com/jackwener/opencli/issues/373))
* **ci:** add cross-platform CI matrix (Linux/macOS/Windows) ([#402](https://github.com/jackwener/opencli/issues/402))
## [1.3.3](https://github.com/jackwener/opencli/compare/v1.3.2...v1.3.3) (2026-03-25)
### Features
* **browser:** add stealth anti-detection for CDP and daemon modes ([#319](https://github.com/jackwener/opencli/issues/319))
### Bug Fixes
* **stealth:** review fixes — guard plugins, rewrite stack trace cleanup ([#320](https://github.com/jackwener/opencli/issues/320))
## [1.3.2](https://github.com/jackwener/opencli/compare/v1.3.1...v1.3.2) (2026-03-24)
-57
View File
@@ -1,57 +0,0 @@
# Privacy Policy — OpenCLI Browser Extension
**Last updated**: 2026-03-25
## What the extension does
The OpenCLI Browser Extension is a bridge between the [OpenCLI](https://github.com/jackwener/opencli) command-line tool and your Chrome browser. It receives commands from a **locally running daemon** process via WebSocket (`localhost` only) and executes them in **isolated Chrome windows** that are separate from your normal browsing session.
## Data collection
The extension does **NOT** collect, store, transmit, or sell any personal data. Specifically:
- **No analytics or telemetry** — no data is sent to any remote server.
- **No user tracking** — no cookies, identifiers, or fingerprints are created.
- **No external network requests** — all communication is strictly `localhost` (WebSocket to `ws://localhost:19825`).
## Permissions explained
| Permission | Why it's needed |
|------------|----------------|
| `debugger` | Required to use Chrome DevTools Protocol (CDP) for browser automation — executing JavaScript, capturing page content, and taking screenshots in isolated windows. |
| `tabs` | Required to create and manage isolated automation windows and tabs, separate from the user's browsing session. |
| `cookies` | Required to read site-specific cookies (scoped by domain) so CLI commands can authenticate with websites the user is already logged into. Cookies are **never written, modified, or transmitted externally**. |
| `activeTab` | Required to identify the currently active tab for context-aware commands. |
| `alarms` | Required to maintain the WebSocket connection to the local daemon via periodic keepalive checks. |
## Data flow
```
User's terminal (opencli CLI)
↓ (spawns)
Local daemon process (localhost:19825)
↓ (WebSocket, localhost only)
Chrome Extension (this extension)
↓ (Chrome APIs)
Isolated Chrome automation window
```
All data stays on the user's machine. No data leaves `localhost`.
## Cookie access
The extension reads cookies **only** when explicitly requested by a CLI command, and **only** for the specific domain the command targets. It cannot and does not dump all cookies. Cookie data is returned to the local daemon process and is never sent to any external server.
## Third-party services
This extension does not integrate with, send data to, or receive data from any third-party service.
## Open source
This extension is fully open source. You can audit the complete source code at:
https://github.com/jackwener/opencli/tree/main/extension
## Contact
For privacy questions or concerns, please open an issue at:
https://github.com/jackwener/opencli/issues
+219 -144
View File
@@ -1,163 +1,207 @@
# OpenCLI
> **Make any website, Electron App, or Local Tool your CLI.**
> **Make any website, Electron App, or Local Tool your CLI.**
> Zero risk · Reuse Chrome login · AI-powered discovery · Universal CLI Hub
[![中文文档](https://img.shields.io/badge/docs-%E4%B8%AD%E6%96%87-0F766E?style=flat-square)](./README.zh-CN.md)
[中文文档](./README.zh-CN.md)
[![npm](https://img.shields.io/npm/v/@jackwener/opencli?style=flat-square)](https://www.npmjs.com/package/@jackwener/opencli)
[![Node.js Version](https://img.shields.io/node/v/@jackwener/opencli?style=flat-square)](https://nodejs.org)
[![License](https://img.shields.io/npm/l/@jackwener/opencli?style=flat-square)](./LICENSE)
A CLI tool that turns **any website**, **Electron app**, or **local CLI tool** into a command-line interface — Bilibili, Zhihu, 小红书, Twitter/X, Reddit, YouTube, Antigravity, `gh`, `docker`, and [many more](#built-in-commands) — powered by browser session reuse and AI-native discovery.
**Built for AI Agents** — Load the [`opencli-operate` skill](./skills/opencli-operate/SKILL.md) to give any AI agent (Claude Code, Cursor) direct browser control. Operate any website, then crystallize those interactions into reusable CLI commands. Configure `opencli list` in your `AGENT.md` or `.cursorrules` so the AI auto-discovers all available tools.
**Built for AI Agents**: Simply configure an instruction in your global `AGENT.md` or `.cursorrules` guiding the AI to execute `opencli list` via Bash to discover available tools. Register your favorite local CLIs (`opencli register mycli`), and the AI will automatically learn how to invoke all your tools perfectly!
**CLI Hub** — Register any local CLI (`opencli register mycli`) so AI agents can discover and call it alongside built-in commands. Auto-installs missing tools via your package manager (e.g. if `gh` isn't installed, `opencli gh ...` runs `brew install gh` first then re-executes seamlessly).
**CLI for Electron Apps** — Turn any Electron application into a CLI tool. Recombine, script, and extend apps like Antigravity Ultra from the terminal. AI agents can now control other AI apps natively.
**CLI All Electron Apps! The Most Powerful Update Has Arrived!**
Turn ANY Electron application into a CLI tool! Recombine, script, and extend applications like Antigravity Ultra seamlessly. Now AI can control itself natively. Unlimited possibilities await!
---
## Highlights
- **CLI All Electron** — CLI-ify apps like Antigravity Ultra! Now AI can control itself natively.
- **Browser Automation** — `operate` gives AI agents direct browser control: click, type, extract, screenshot — any interaction, fully scriptable.
- **Website → CLI** — Turn any website into a deterministic CLI: 70+ pre-built adapters, or crystallize your own with `opencli record`.
- **CLI All Electron** — CLI-ify apps like Antigravity Ultra! Now AI can control itself natively using cc/openclaw!
- **Account-safe** — Reuses Chrome's logged-in state; your credentials never leave the browser.
- **Anti-detection built-in** — Patches `navigator.webdriver`, stubs `window.chrome`, fakes plugin lists, cleans ChromeDriver/Playwright globals, and strips CDP frames from Error stack traces. Extensive anti-fingerprinting and risk-control evasion measures baked in at every layer.
- **AI Agent ready** — `explore` discovers APIs, `synthesize` generates adapters, `cascade` finds auth strategies, `operate` controls the browser directly.
- **AI Agent ready** — `explore` discovers APIs, `synthesize` generates adapters, `cascade` finds auth strategies.
- **External CLI Hub** — Discover, auto-install, and passthrough commands to any external CLI (gh, obsidian, docker, etc). Zero setup.
- **Self-healing setup** — `opencli doctor` diagnoses and auto-starts the daemon, extension, and live browser connectivity.
- **Dynamic Loader** — Simply drop `.ts` or `.yaml` adapters into the `clis/` folder for auto-registration.
- **Dual-Engine Architecture** — Supports both YAML declarative data pipelines and robust browser runtime TypeScript injections.
## Why opencli?
There are many great browser automation tools. Here's when opencli is the right choice:
| Your need | Best tool | Why |
|-----------|-----------|-----|
| Scheduled data extraction from specific sites | **opencli** | Pre-built adapters, deterministic JSON, zero LLM cost |
| AI agent needs reliable site operations | **opencli** | Hundreds of commands, structured output, fast deterministic response |
| Explore an unknown website ad-hoc | Browser-Use, Stagehand | LLM-driven general browsing for one-off tasks |
| Large-scale web crawling | Crawl4AI, Scrapy | Purpose-built for throughput and scale |
| Control desktop Electron apps from terminal | **opencli** | CDP + AppleScript — the only CLI tool that does this |
**What makes opencli different:**
- **Zero LLM cost** — No tokens consumed at runtime. Run 10,000 times and pay nothing.
- **Deterministic** — Same command, same output schema, every time. Pipeable, scriptable, CI-friendly.
- **Broad coverage** — 73+ sites across global and Chinese platforms (Bilibili, Zhihu, Xiaohongshu, Reddit, HackerNews, and more), plus desktop Electron apps via CDP.
- **Broad coverage** — 50+ sites across global and Chinese platforms (Bilibili, Zhihu, Xiaohongshu, Reddit, HackerNews, and more), plus desktop Electron apps via CDP.
---
> For a detailed comparison with Browser-Use, Crawl4AI, Firecrawl, and others, see the [Comparison Guide](./docs/comparison.md).
## Quick Start
## Prerequisites
### 1. Install Browser Bridge Extension
- **Node.js**: >= 20.0.0
- **Chrome** running **and logged into the target site** (e.g. bilibili.com, zhihu.com, xiaohongshu.com).
> OpenCLI connects to your browser through a lightweight **Browser Bridge** Chrome Extension + micro-daemon (zero config, auto-start).
> **⚠️ Important**: Browser commands reuse your Chrome login session. You must be logged into the target website in Chrome before running commands. If you get empty data or errors, check your login status first.
OpenCLI connects to your browser through a lightweight **Browser Bridge** Chrome Extension + micro-daemon (zero config, auto-start).
### Browser Bridge Extension Setup
You can install the extension via either method:
**Method 1: Download Pre-built Release (Recommended)**
1. Go to the GitHub [Releases page](https://github.com/jackwener/opencli/releases) and download the latest `opencli-extension.zip`.
2. Unzip the file and open `chrome://extensions`, enable **Developer mode** (top-right toggle).
3. Click **Load unpacked** and select the unzipped folder.
### 2. Install OpenCLI
**Method 2: Load Source (For Developers)**
1. Open `chrome://extensions` and enable **Developer mode**.
2. Click **Load unpacked** and select the `extension/` directory from this repository.
**Install via npm (recommended)**
That's it! The daemon auto-starts when you run any browser command. No tokens, no manual configuration.
> **Tip**: Use `opencli doctor` for ongoing diagnosis:
> ```bash
> opencli doctor # Check extension + daemon connectivity
> ```
## Quick Start
### Install via npm (recommended)
```bash
npm install -g @jackwener/opencli
```
### 3. Verify & Try
Then use directly:
```bash
opencli doctor # Check extension + daemon connectivity
opencli daemon status # Check daemon state (PID, uptime, memory)
opencli list # See all commands
opencli list -f yaml # List commands as YAML
opencli hackernews top --limit 5 # Public API, no browser
opencli bilibili hot --limit 5 # Browser command
opencli zhihu hot -f json # JSON output
opencli zhihu hot -f yaml # YAML output
```
**Try it out:**
### Install from source (for developers)
```bash
opencli list # See all commands
opencli hackernews top --limit 5 # Public API, no browser needed
opencli bilibili hot --limit 5 # Browser command (requires Extension)
git clone git@github.com:jackwener/opencli.git
cd opencli
npm install
npm run build
npm link # Link binary globally
opencli list # Now you can use it anywhere!
```
### 4. Browser Automation — Make Websites Accessible for AI Agents
Point your AI agent (Claude Code, Cursor) to [`skills/opencli-operate/SKILL.md`](./skills/opencli-operate/SKILL.md). It has everything needed — full command reference, examples, and workflow.
Available commands: `open`, `state`, `click`, `type`, `select`, `keys`, `wait`, `get`, `screenshot`, `scroll`, `back`, `eval`, `network`, `init`, `verify`, `close`.
### Update
```bash
npm install -g @jackwener/opencli@latest
```
### Install AI Skills
OpenCLI provides [skills](./skills/) for AI agents (Claude Code, etc.):
```bash
# Install all OpenCLI skills
npx skills add jackwener/opencli
# Or install specific skills
npx skills add jackwener/opencli --skill opencli-usage # Command reference
npx skills add jackwener/opencli --skill opencli-operate # Browser automation for AI agents
npx skills add jackwener/opencli --skill opencli-explorer # Adapter development guide
npx skills add jackwener/opencli --skill opencli-oneshot # Quick command reference
```
---
### For Developers
**Install from source**
```bash
git clone git@github.com:jackwener/opencli.git && cd opencli && npm install && npm run build && npm link
```
**Load Source Browser Bridge Extension**
1. Open `chrome://extensions` and enable **Developer mode** (top-right toggle).
2. Click **Load unpacked** and select the `extension/` directory from this repository.
---
## Prerequisites
- **Node.js**: >= 20.0.0 (or **Bun** >= 1.0)
- **Chrome** running **and logged into the target site** (e.g. bilibili.com, zhihu.com, xiaohongshu.com).
> **⚠️ Important**: Browser commands reuse your Chrome login session. You must be logged into the target website in Chrome before running commands. If you get empty data or errors, check your login status first.
## Built-in Commands
| Site | Commands |
|------|----------|
| **xiaohongshu** | `search` `note` `comments` `feed` `user` `download` `publish` `notifications` `creator-notes` `creator-notes-summary` `creator-note-detail` `creator-profile` `creator-stats` |
| **bilibili** | `hot` `search` `history` `feed` `ranking` `download` `comments` `dynamic` `favorite` `following` `me` `subtitle` `user-videos` |
| **tieba** | `hot` `posts` `search` `read` |
| **twitter** | `trending` `search` `timeline` `bookmarks` `post` `download` `profile` `article` `like` `likes` `notifications` `reply` `reply-dm` `thread` `follow` `unfollow` `followers` `following` `block` `unblock` `bookmark` `unbookmark` `delete` `hide-reply` `accept` |
| **reddit** | `hot` `frontpage` `popular` `search` `subreddit` `user` `user-posts` `user-comments` `read` `save` `saved` `subscribe` `upvote` `upvoted` `comment` |
| **amazon** | `bestsellers` `search` `product` `offer` `discussion` |
| **gemini** | `new` `ask` `image` |
| **notebooklm** | `status` `list` `open` `select` `current` `get` `metadata` `source-list` `source-get` `source-fulltext` `source-guide` `history` `note-list` `notes-list` `notes-get` `summary` |
| **spotify** | `auth` `status` `play` `pause` `next` `prev` `volume` `search` `queue` `shuffle` `repeat` |
Run `opencli list` for the live registry.
73+ adapters in total — **[→ see all supported sites & commands](./docs/adapters/index.md)**
| Site | Commands | Mode |
|------|----------|------|
| **twitter** | `trending` `bookmarks` `profile` `search` `timeline` `thread` `following` `followers` `notifications` `post` `reply` `delete` `like` `article` `follow` `unfollow` `bookmark` `unbookmark` `download` `accept` `reply-dm` `block` `unblock` `hide-reply` | Browser |
| **reddit** | `hot` `frontpage` `popular` `search` `subreddit` `read` `user` `user-posts` `user-comments` `upvote` `save` `comment` `subscribe` `saved` `upvoted` | Browser |
| **cursor** | `status` `send` `read` `new` `dump` `composer` `model` `extract-code` `ask` `screenshot` `history` `export` | Desktop |
| **bilibili** | `hot` `search` `me` `favorite` `history` `feed` `subtitle` `dynamic` `ranking` `following` `user-videos` `download` | Browser |
| **codex** | `status` `send` `read` `new` `dump` `extract-diff` `model` `ask` `screenshot` `history` `export` | Desktop |
| **chatwise** | `status` `new` `send` `read` `ask` `model` `history` `export` `screenshot` | Desktop |
| **doubao** | `status` `new` `send` `read` `ask` | Browser |
| **doubao-app** | `status` `new` `send` `read` `ask` `screenshot` `dump` | Desktop |
| **notion** | `status` `search` `read` `new` `write` `sidebar` `favorites` `export` | Desktop |
| **discord-app** | `status` `send` `read` `channels` `servers` `search` `members` | Desktop |
| **v2ex** | `hot` `latest` `topic` `node` `user` `member` `replies` `nodes` `daily` `me` `notifications` | Public / Browser |
| **xueqiu** | `feed` `hot-stock` `hot` `search` `stock` `watchlist` `earnings-date` | Browser |
| **antigravity** | `status` `send` `read` `new` `dump` `extract-code` `model` `watch` | Desktop |
| **chatgpt** | `status` `new` `send` `read` `ask` | Desktop |
| **xiaohongshu** | `search` `notifications` `feed` `user` `download` `publish` `creator-notes` `creator-note-detail` `creator-notes-summary` `creator-profile` `creator-stats` | Browser |
| **apple-podcasts** | `search` `episodes` `top` | Public |
| **xiaoyuzhou** | `podcast` `podcast-episodes` `episode` | Public |
| **zhihu** | `hot` `search` `question` `download` | Browser |
| **weixin** | `download` | Browser |
| **youtube** | `search` `video` `transcript` | Browser |
| **boss** | `search` `detail` `recommend` `joblist` `greet` `batchgreet` `send` `chatlist` `chatmsg` `invite` `mark` `exchange` `resume` `stats` | Browser |
| **coupang** | `search` `add-to-cart` | Browser |
| **bbc** | `news` | Public |
| **bloomberg** | `main` `markets` `economics` `industries` `tech` `politics` `businessweek` `opinions` `feeds` `news` | Public / Browser |
| **ctrip** | `search` | Browser |
| **devto** | `top` `tag` `user` | Public |
| **dictionary** | `search` `synonyms` `examples` | Public |
| **arxiv** | `search` `paper` | Public |
| **wikipedia** | `search` `summary` `random` `trending` | Public |
| **hackernews** | `top` `new` `best` `ask` `show` `jobs` `search` `user` | Public |
| **linkedin** | `search` | Browser |
| **reuters** | `search` | Browser |
| **smzdm** | `search` | Browser |
| **weibo** | `hot` `search` | Browser |
| **yahoo-finance** | `quote` | Browser |
| **sinafinance** | `news` | 🌐 Public |
| **barchart** | `quote` `options` `greeks` `flow` | Browser |
| **chaoxing** | `assignments` `exams` | Browser |
| **grok** | `ask` | Browser |
| **hf** | `top` | Public |
| **jike** | `feed` `search` `create` `like` `comment` `repost` `notifications` `post` `topic` `user` | Browser |
| **jimeng** | `generate` `history` | Browser |
| **yollomi** | `generate` `video` `edit` `upload` `models` `remove-bg` `upscale` `face-swap` `restore` `try-on` `background` `object-remover` | Browser |
| **linux-do** | `hot` `latest` `search` `categories` `category` `topic` | Public |
| **stackoverflow** | `hot` `search` `bounties` `unanswered` | Public |
| **steam** | `top-sellers` | Public |
| **weread** | `shelf` `search` `book` `highlights` `notes` `notebooks` `ranking` | Browser |
| **douban** | `search` `top250` `subject` `marks` `reviews` `movie-hot` `book-hot` | Browser |
| **facebook** | `feed` `profile` `search` `friends` `groups` `events` `notifications` `memories` `add-friend` `join-group` | Browser |
| **google** | `news` `search` `suggest` `trends` | Public |
| **instagram** | `explore` `profile` `search` `user` `followers` `following` `follow` `unfollow` `like` `unlike` `comment` `save` `unsave` `saved` | Browser |
| **lobsters** | `hot` `newest` `active` `tag` | Public |
| **medium** | `feed` `search` `user` | Browser |
| **sinablog** | `hot` `search` `article` `user` | Browser |
| **substack** | `feed` `search` `publication` | Browser |
| **tiktok** | `explore` `search` `profile` `user` `following` `follow` `unfollow` `like` `unlike` `comment` `save` `unsave` `live` `notifications` `friends` | Browser |
## CLI Hub
OpenCLI acts as a universal hub for your existing command-line tools — unified discovery, pure passthrough execution, and auto-install (if a tool isn't installed, OpenCLI runs `brew install <tool>` automatically before re-running the command).
### External CLI Hub
| External CLI | Description | Example |
|--------------|-------------|---------|
OpenCLI acts as a universal hub for your existing command-line tools. It provides unified discovery, automatic installation, and pure passthrough execution.
| External CLI | Description | Commands Example |
|--------------|-------------|------------------|
| **gh** | GitHub CLI | `opencli gh pr list --limit 5` |
| **obsidian** | Obsidian vault management | `opencli obsidian search query="AI"` |
| **docker** | Docker | `opencli docker ps` |
| **lark-cli** | Lark/Feishu — messages, docs, calendar, tasks, 200+ commands | `opencli lark-cli calendar +agenda` |
| **dingtalk** | DingTalk — cross-platform CLI for DingTalk's full suite, designed for humans and AI agents | `opencli dingtalk msg send --to user "hello"` |
| **wecom** | WeCom/企业微信 — CLI for WeCom open platform, for humans and AI agents | `opencli wecom msg send --to user "hello"` |
| **vercel** | Vercel — deploy projects, manage domains, env vars, logs | `opencli vercel deploy --prod` |
| **docker** | Docker command-line interface | `opencli docker ps` |
| **readwise** | Readwise & Reader CLI | `opencli readwise login` |
| **gws** | Google Workspace CLI — Docs, Sheets, Drive, Gmail, Calendar | `opencli gws docs list` |
**Register your own** — add any local CLI so AI agents can discover it via `opencli list`:
**Zero Configuration**: OpenCLI purely passes your inputs to the underlying binary via standard I/O streams. The external CLI works exactly as it naturally would, maintaining its standard output formats.
**Auto-Installation**: If you run `opencli gh ...` and `gh` is not installed on your system, OpenCLI will automatically try to install it using your system's package manager (e.g., `brew install gh`) before seamlessly re-running the command.
**Register Your Own**:
Add any local CLI to your OpenCLI registry so AI agents can automatically discover it via the `opencli list` command.
```bash
opencli register mycli
```
### Desktop App Adapters
Control Electron desktop apps directly from the terminal. Each adapter has its own detailed documentation:
Each desktop adapter has its own detailed documentation with commands reference, setup guide, and examples:
| App | Description | Doc |
|-----|-------------|-----|
@@ -170,71 +214,83 @@ Control Electron desktop apps directly from the terminal. Each adapter has its o
| **Discord** | Discord Desktop — messages, channels, servers | [Doc](./docs/adapters/desktop/discord.md) |
| **Doubao** | Control Doubao AI desktop app via CDP | [Doc](./docs/adapters/desktop/doubao-app.md) |
To add a new Electron app, start with [docs/guide/electron-app-cli.md](./docs/guide/electron-app-cli.md).
## Download Support
OpenCLI supports downloading images, videos, and articles from supported platforms.
### Supported Platforms
| Platform | Content Types | Notes |
|----------|---------------|-------|
| **xiaohongshu** | Images, Videos | Downloads all media from a note |
| **bilibili** | Videos | Requires `yt-dlp` installed |
| **twitter** | Images, Videos | From user media tab or single tweet |
| **douban** | Images | Poster / still image lists |
| **pixiv** | Images | Original-quality illustrations, multi-page |
| **zhihu** | Articles (Markdown) | Exports with optional image download |
| **weixin** | Articles (Markdown) | WeChat Official Account articles |
| **twitter** | Images, Videos | Downloads from user media tab or single tweet |
| **zhihu** | Articles (Markdown) | Exports articles with optional image download |
| **weixin** | Articles (Markdown) | Exports WeChat Official Account articles |
For video downloads, install `yt-dlp` first: `brew install yt-dlp`
### Prerequisites
For video downloads from streaming platforms, you need to install `yt-dlp`:
```bash
opencli xiaohongshu download abc123 --output ./xhs
opencli bilibili download BV1xxx --output ./bilibili
opencli twitter download elonmusk --limit 20 --output ./twitter
# Install yt-dlp
pip install yt-dlp
# or
brew install yt-dlp
```
### Usage Examples
```bash
# Download images/videos from Xiaohongshu note
opencli xiaohongshu download abc123 --output ./xhs
# Download Bilibili video (requires yt-dlp)
opencli bilibili download BV1xxx --output ./bilibili
opencli bilibili download BV1xxx --quality 1080p # Specify quality
# Download Twitter media from user
opencli twitter download elonmusk --limit 20 --output ./twitter
# Download single tweet media
opencli twitter download --tweet-url "https://x.com/user/status/123" --output ./twitter
# Export Zhihu article to Markdown
opencli zhihu download "https://zhuanlan.zhihu.com/p/xxx" --output ./zhihu
# Export with local images
opencli zhihu download "https://zhuanlan.zhihu.com/p/xxx" --download-images
# Export WeChat article to Markdown
opencli weixin download --url "https://mp.weixin.qq.com/s/xxx" --output ./weixin
```
## Output Formats
All built-in commands support `--format` / `-f` with `table` (default), `json`, `yaml`, `md`, and `csv`.
All built-in commands support `--format` / `-f` with `table`, `json`, `yaml`, `md`, and `csv`.
The `list` command supports the same format options, and keeps `--json` for backward compatibility.
```bash
opencli bilibili hot -f json # Pipe to jq or LLMs
opencli bilibili hot -f csv # Spreadsheet-friendly
opencli list -f yaml # Command registry as YAML
opencli bilibili hot -f table # Default: rich terminal table
opencli bilibili hot -f json # JSON (pipe to jq or LLMs)
opencli bilibili hot -f yaml # YAML (human-readable structured output)
opencli bilibili hot -f md # Markdown
opencli bilibili hot -f csv # CSV
opencli bilibili hot -v # Verbose: show pipeline debug steps
```
## Exit Codes
opencli follows Unix `sysexits.h` conventions so it integrates naturally with shell pipelines and CI scripts:
| Code | Meaning | When |
|------|---------|------|
| `0` | Success | Command completed normally |
| `1` | Generic error | Unexpected / unclassified failure |
| `2` | Usage error | Bad arguments or unknown command |
| `66` | Empty result | No data returned (`EX_NOINPUT`) |
| `69` | Service unavailable | Browser Bridge not connected (`EX_UNAVAILABLE`) |
| `75` | Temporary failure | Command timed out — retry (`EX_TEMPFAIL`) |
| `77` | Auth required | Not logged in to target site (`EX_NOPERM`) |
| `78` | Config error | Missing credentials or bad config (`EX_CONFIG`) |
| `130` | Interrupted | Ctrl-C / SIGINT |
```bash
opencli spotify status || echo "exit $?" # 69 if browser not running
opencli github issues 2>/dev/null
[ $? -eq 77 ] && opencli github auth # auto-auth if not logged in
```
## Plugins
Extend OpenCLI with community-contributed adapters:
Extend OpenCLI with community-contributed adapters. Plugins use the same YAML/TS format as built-in commands and are automatically discovered at startup.
```bash
opencli plugin install github:user/opencli-plugin-my-tool
opencli plugin list
opencli plugin update --all
opencli plugin uninstall my-tool
opencli plugin install github:user/opencli-plugin-my-tool # Install
opencli plugin list # List installed
opencli plugin update my-tool # Update to latest
opencli plugin uninstall my-tool # Remove
```
| Plugin | Type | Description |
@@ -242,39 +298,58 @@ opencli plugin uninstall my-tool
| [opencli-plugin-github-trending](https://github.com/ByteYue/opencli-plugin-github-trending) | YAML | GitHub Trending repositories |
| [opencli-plugin-hot-digest](https://github.com/ByteYue/opencli-plugin-hot-digest) | TS | Multi-platform trending aggregator |
| [opencli-plugin-juejin](https://github.com/Astro-Han/opencli-plugin-juejin) | YAML | 稀土掘金 (Juejin) hot articles |
| [opencli-plugin-vk](https://github.com/flobo3/opencli-plugin-vk) | TS | VK (VKontakte) wall, feed, and search |
See [Plugins Guide](./docs/guide/plugins.md) for creating your own plugin.
## For AI Agents (Developer Guide)
If you are an AI assistant tasked with creating a new command adapter for `opencli`, please follow the AI Agent workflow below:
> **Quick mode**: To generate a single command for a specific page URL, see [CLI-ONESHOT.md](./CLI-ONESHOT.md) — just a URL + one-line goal, 4 steps done.
> **Full mode**: Before writing any adapter code, read [CLI-EXPLORER.md](./CLI-EXPLORER.md). It contains the complete browser exploration workflow, the 5-tier authentication strategy decision tree, and debugging guide.
```bash
opencli explore https://example.com --site mysite # Discover APIs + capabilities
opencli synthesize mysite # Generate YAML adapters
opencli generate https://example.com --goal "hot" # One-shot: explore → synthesize → register
opencli cascade https://api.example.com/data # Auto-probe: PUBLIC → COOKIE → HEADER
# 1. Deep Explore — discover APIs, infer capabilities, detect framework
opencli explore https://example.com --site mysite
# 2. Synthesize — generate YAML adapters from explore artifacts
opencli synthesize mysite
# 3. Generate — one-shot: explore → synthesize → register
opencli generate https://example.com --goal "hot"
# 4. Strategy Cascade — auto-probe: PUBLIC → COOKIE → HEADER
opencli cascade https://api.example.com/data
```
Explore outputs to `.opencli/explore/<site>/` (manifest.json, endpoints.json, capabilities.json, auth.json).
## Testing
See **[TESTING.md](./TESTING.md)** for how to run and write tests.
## Troubleshooting
- **"Extension not connected"** — Ensure the Browser Bridge extension is installed and **enabled** in `chrome://extensions`.
- **"attach failed: Cannot access a chrome-extension:// URL"** — Another extension may be interfering. Try disabling other extensions temporarily.
- **Empty data or 'Unauthorized' error** — Your Chrome login session may have expired. Navigate to the target site and log in again.
- **Node API errors** — Ensure Node.js >= 20. Some dependencies require modern Node APIs.
- **Daemon issues** — Check status: `curl localhost:19825/status` · View logs: `curl localhost:19825/logs`
- **"Extension not connected"**
- Ensure the opencli Browser Bridge extension is installed and **enabled** in `chrome://extensions`.
- **"attach failed: Cannot access a chrome-extension:// URL"**
- Another Chrome extension (e.g. youmind, New Tab Override, or AI assistant extensions) may be interfering. Try **disabling other extensions** temporarily, then retry.
- **Empty data returns or 'Unauthorized' error**
- Your login session in Chrome might have expired. Open a normal Chrome tab, navigate to the target site, and log in or refresh the page.
- **Node API errors**
- Make sure you are using Node.js >= 20. Some dependencies require modern Node APIs.
- **Daemon issues**
- Check daemon status: `curl localhost:19825/status`
- View extension logs: `curl localhost:19825/logs`
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=jackwener/opencli&type=Date)](https://star-history.com/#jackwener/opencli&Date)
## License
[Apache-2.0](./LICENSE)
+33 -88
View File
@@ -3,14 +3,15 @@
> **把任何网站、本地工具、Electron 应用变成能够让 AI 调用的命令行!**
> 零风控 · 复用 Chrome 登录 · AI 自动发现接口 · 全能 CLI 枢纽
[![English](https://img.shields.io/badge/docs-English-1D4ED8?style=flat-square)](./README.md)
[English](./README.md)
[![npm](https://img.shields.io/npm/v/@jackwener/opencli?style=flat-square)](https://www.npmjs.com/package/@jackwener/opencli)
[![Node.js Version](https://img.shields.io/node/v/@jackwener/opencli?style=flat-square)](https://nodejs.org)
[![License](https://img.shields.io/npm/l/@jackwener/opencli?style=flat-square)](./LICENSE)
OpenCLI 将任何网站、本地 CLI 或 Electron 应用(如 Antigravity)变成命令行工具 — B站、知乎、小红书、Twitter/X、Reddit、YouTube,以及 `gh``docker` 等[多种站点与工具](#内置命令) — 复用浏览器登录态,AI 驱动探索。
**专为 AI Agent 打造**加载 [`opencli-operate` skill](./skills/opencli-operate/SKILL.md),赋予 AI AgentClaude Code、Cursor 等)直接操控浏览器的能力——操作任意网站,并将这些交互沉淀为可复用的 CLI 命令。在 `AGENT.md``.cursorrules` 中配置 `opencli list`AI 即可自动发现并调用所有可用工具
**专为 AI Agent 打造**只需在全局 `.cursorrules``AGENT.md` 中配置简单指令,引导 AI 通过 Bash 执行 `opencli list` 来检索可用的 CLI 工具及其用法。随后,将你常用的 CLI 列表整合注册进去(`opencli register mycli`AI 便能瞬间学会自动调用相应的本地工具
**opencli 支持 CLI 化所有 electron 应用!最强大更新来袭!**
CLI all electron!现在支持把所有 electron 应用 CLI 化,从而组合出各种神奇的能力。
@@ -22,15 +23,32 @@ CLI all electron!现在支持把所有 electron 应用 CLI 化,从而组合
## 亮点
- **CLI All Electron** — 支持把所有 electron 应用(如 Antigravity UltraCLI 化,让 AI 控制自己!
- **浏览器自动化** — `operate` 赋予 AI Agent 直接操控浏览器的能力:点击、输入、提取、截图,任意交互皆可脚本化
- **网页转 CLI** — 将任意网站变成确定性命令行工具:73+ 预置适配器,或用 `opencli record` 沉淀自己的操作
- **多站点覆盖** — 73+ 站点,横跨全球与中国平台(B站、知乎、小红书、Reddit、HackerNews 等),并支持通过 CDP 控制桌面 Electron 应用
- **多站点覆盖** — 覆盖 B站、知乎、小红书、Twitter、Reddit,以及多种桌面应用
- **零风控** — 复用 Chrome 登录态,无需存储任何凭证
- **外部 CLI 枢纽** — 统一发现、自动安装、透传执行 `gh``docker` 等本地 CLI
- **自修复配置** — `opencli doctor` 自动启动 daemon,诊断扩展和浏览器连接状态
- **AI 原生** — `explore` 自动发现 API`synthesize` 生成适配器,`cascade` 探测认证策略`operate` 直接控制浏览器
- **AI 原生** — `explore` 自动发现 API`synthesize` 生成适配器,`cascade` 探测认证策略
- **动态加载引擎** — 声明式的 `.yaml` 或者底层定制的 `.ts` 适配器,放入 `clis/` 文件夹即可自动注册生效
## 为什么选 opencli
浏览器自动化工具很多,opencli 适合什么场景?
| 你的需求 | 最佳工具 | 原因 |
|----------|----------|------|
| 定时从特定站点提取结构化数据 | **opencli** | 预定义适配器,确定性 JSON 输出,零 LLM 成本 |
| AI Agent 需要可靠的站点操作 | **opencli** | 数百条命令,结构化输出,快速确定性响应 |
| 临时探索未知网站 | Browser-Use、Stagehand | LLM 驱动的通用浏览,适合一次性任务 |
| 大规模网页爬取 | Crawl4AI、Scrapy | 专为吞吐量和规模设计 |
| 从终端控制桌面 Electron 应用 | **opencli** | CDP + AppleScript,目前唯一能做到这一点的 CLI 工具 |
**opencli 的核心差异:**
- **零 LLM 成本** — 运行时不消耗任何 token,跑一万次不花一分钱
- **确定性** — 同一命令永远返回同一结构,可管道化、可脚本化、CI 友好
- **覆盖广泛** — 50+ 站点,横跨全球与中国平台(B站、知乎、小红书、Reddit、HackerNews 等),并支持通过 CDP 控制桌面 Electron 应用
> 与 Browser-Use、Crawl4AI、Firecrawl 等工具的详细对比,请查看 [Comparison Guide](./docs/comparison.md)。
## 前置要求
@@ -56,11 +74,9 @@ OpenCLI 通过轻量化的 **Browser Bridge** Chrome 扩展 + 微型 daemon 与
完成!运行任何 opencli 浏览器命令时,后台微型 daemon 会自动启动与浏览器通信。无需配 API Token,零代码配置。
> **Tip**:后续诊断和 daemon 管理
> **Tip**:后续诊断用 `opencli doctor`
> ```bash
> opencli doctor # 检查扩展和 daemon 连通性
> opencli daemon status # 查看 daemon 状态
> opencli daemon stop # 停止 daemon
> ```
## 快速开始
@@ -99,27 +115,6 @@ opencli list # 可以在任何地方使用了!
npm install -g @jackwener/opencli@latest
```
### 浏览器自动化 — 让 AI Agent 直接控制浏览器
将 [`skills/opencli-operate/SKILL.md`](./skills/opencli-operate/SKILL.md) 指向你的 AI AgentClaude Code、Cursor),即可开箱即用,内含完整命令参考与使用示例。
可用命令:`open``state``click``type``select``keys``wait``get``screenshot``scroll``back``eval``network``init``verify``close`
### 安装 AI Skills
OpenCLI 提供 [skills](./skills/) 供 AI AgentClaude Code 等)使用:
```bash
# 安装所有 OpenCLI skills
npx skills add jackwener/opencli
# 或安装特定 skill
npx skills add jackwener/opencli --skill opencli-usage # 命令参考
npx skills add jackwener/opencli --skill opencli-operate # 浏览器自动化(AI Agent 专用)
npx skills add jackwener/opencli --skill opencli-explorer # 适配器开发指南
npx skills add jackwener/opencli --skill opencli-oneshot # 快速命令参考
```
## 内置命令
运行 `opencli list` 查看完整注册表。
@@ -128,19 +123,18 @@ npx skills add jackwener/opencli --skill opencli-oneshot # 快速命令参
|------|------|------|
| **twitter** | `trending` `bookmarks` `profile` `search` `timeline` `thread` `following` `followers` `notifications` `post` `reply` `delete` `like` `article` `follow` `unfollow` `bookmark` `unbookmark` `download` `accept` `reply-dm` `block` `unblock` `hide-reply` | 浏览器 |
| **reddit** | `hot` `frontpage` `popular` `search` `subreddit` `read` `user` `user-posts` `user-comments` `upvote` `save` `comment` `subscribe` `saved` `upvoted` | 浏览器 |
| **tieba** | `hot` `posts` `search` `read` | 浏览器 |
| **cursor** | `status` `send` `read` `new` `dump` `composer` `model` `extract-code` `ask` `screenshot` `history` `export` | 桌面端 |
| **bilibili** | `hot` `search` `me` `favorite` `history` `feed` `subtitle` `dynamic` `ranking` `following` `user-videos` `download` | 浏览器 |
| **codex** | `status` `send` `read` `new` `dump` `extract-diff` `model` `ask` `screenshot` `history` `export` | 桌面端 |
| **chatwise** | `status` `new` `send` `read` `ask` `model` `history` `export` `screenshot` | 桌面端 |
| **doubao** | `status` `new` `send` `read` `ask` `history` `detail` `meeting-summary` `meeting-transcript` | 浏览器 |
| **doubao** | `status` `new` `send` `read` `ask` | 浏览器 |
| **doubao-app** | `status` `new` `send` `read` `ask` `screenshot` `dump` | 桌面端 |
| **notion** | `status` `search` `read` `new` `write` `sidebar` `favorites` `export` | 桌面端 |
| **discord-app** | `status` `send` `read` `channels` `servers` `search` `members` | 桌面端 |
| **v2ex** | `hot` `latest` `topic` `node` `user` `member` `replies` `nodes` `daily` `me` `notifications` | 公开 / 浏览器 |
| **xueqiu** | `feed` `hot-stock` `hot` `search` `stock` `comments` `watchlist` `earnings-date` `fund-holdings` `fund-snapshot` | 浏览器 |
| **xueqiu** | `feed` `hot-stock` `hot` `search` `stock` `watchlist` `earnings-date` | 浏览器 |
| **antigravity** | `status` `send` `read` `new` `dump` `extract-code` `model` `watch` | 桌面端 |
| **chatgpt** | `status` `new` `send` `read` `ask` `model` | 桌面端 |
| **chatgpt** | `status` `new` `send` `read` `ask` | 桌面端 |
| **xiaohongshu** | `search` `notifications` `feed` `user` `download` `publish` `creator-notes` `creator-note-detail` `creator-notes-summary` `creator-profile` `creator-stats` | 浏览器 |
| **apple-podcasts** | `search` `episodes` `top` | 公开 |
| **xiaoyuzhou** | `podcast` `podcast-episodes` `episode` | 公开 |
@@ -155,14 +149,11 @@ npx skills add jackwener/opencli --skill opencli-oneshot # 快速命令参
| **devto** | `top` `tag` `user` | 公开 |
| **dictionary** | `search` `synonyms` `examples` | 公开 |
| **arxiv** | `search` `paper` | 公开 |
| **paperreview** | `submit` `review` `feedback` | 公开 |
| **wikipedia** | `search` `summary` `random` `trending` | 公开 |
| **hackernews** | `top` `new` `best` `ask` `show` `jobs` `search` `user` | 公共 API |
| **jd** | `item` | 浏览器 |
| **linkedin** | `search` `timeline` | 浏览器 |
| **linkedin** | `search` | 浏览器 |
| **reuters** | `search` | 浏览器 |
| **smzdm** | `search` | 浏览器 |
| **web** | `read` | 浏览器 |
| **weibo** | `hot` `search` | 浏览器 |
| **yahoo-finance** | `quote` | 浏览器 |
| **sinafinance** | `news` | 🌐 公开 |
@@ -173,31 +164,20 @@ npx skills add jackwener/opencli --skill opencli-oneshot # 快速命令参
| **jike** | `feed` `search` `create` `like` `comment` `repost` `notifications` `post` `topic` `user` | 浏览器 |
| **jimeng** | `generate` `history` | 浏览器 |
| **yollomi** | `generate` `video` `edit` `upload` `models` `remove-bg` `upscale` `face-swap` `restore` `try-on` `background` `object-remover` | 浏览器 |
| **linux-do** | `feed` `categories` `tags` `search` `topic` `user-topics` `user-posts` | 浏览器 |
| **linux-do** | `hot` `latest` `search` `categories` `category` `topic` | 公开 |
| **stackoverflow** | `hot` `search` `bounties` `unanswered` | 公开 |
| **steam** | `top-sellers` | 公开 |
| **weread** | `shelf` `search` `book` `highlights` `notes` `notebooks` `ranking` | 浏览器 |
| **douban** | `search` `top250` `subject` `photos` `download` `marks` `reviews` `movie-hot` `book-hot` | 浏览器 |
| **douban** | `search` `top250` `subject` `marks` `reviews` `movie-hot` `book-hot` | 浏览器 |
| **facebook** | `feed` `profile` `search` `friends` `groups` `events` `notifications` `memories` `add-friend` `join-group` | 浏览器 |
| **google** | `news` `search` `suggest` `trends` | 公开 |
| **amazon** | `bestsellers` `search` `product` `offer` `discussion` | 浏览器 |
| **gemini** | `new` `ask` `image` | 浏览器 |
| **spotify** | `auth` `status` `play` `pause` `next` `prev` `volume` `search` `queue` `shuffle` `repeat` | OAuth API |
| **notebooklm** | `status` `list` `open` `select` `current` `get` `metadata` `source-list` `source-get` `source-fulltext` `source-guide` `history` `note-list` `notes-list` `notes-get` `summary` | 浏览器 |
| **36kr** | `news` `hot` `search` `article` | 公开 / 浏览器 |
| **imdb** | `search` `title` `top` `trending` `person` `reviews` | 公开 |
| **producthunt** | `posts` `today` `hot` `browse` | 公开 / 浏览器 |
| **instagram** | `explore` `profile` `search` `user` `followers` `following` `follow` `unfollow` `like` `unlike` `comment` `save` `unsave` `saved` | 浏览器 |
| **lobsters** | `hot` `newest` `active` `tag` | 公开 |
| **medium** | `feed` `search` `user` | 浏览器 |
| **sinablog** | `hot` `search` `article` `user` | 浏览器 |
| **substack** | `feed` `search` `publication` | 浏览器 |
| **pixiv** | `ranking` `search` `user` `illusts` `detail` `download` | 浏览器 |
| **tiktok** | `explore` `search` `profile` `user` `following` `follow` `unfollow` `like` `unlike` `comment` `save` `unsave` `live` `notifications` `friends` | 浏览器 |
| **bluesky** | `search` `trending` `user` `profile` `thread` `feeds` `followers` `following` `starter-packs` | 公开 |
| **douyin** | `videos` `publish` `drafts` `draft` `delete` `stats` `profile` `update` `hashtag` `location` `activities` `collections` | 浏览器 |
73+ 适配器 — **[→ 查看完整命令列表](./docs/adapters/index.md)**
### 外部 CLI 枢纽
@@ -208,10 +188,8 @@ OpenCLI 也可以作为你现有命令行工具的统一入口,负责发现、
| **gh** | GitHub CLI | `opencli gh pr list --limit 5` |
| **obsidian** | Obsidian 仓库管理 | `opencli obsidian search query="AI"` |
| **docker** | Docker 命令行工具 | `opencli docker ps` |
| **lark-cli** | 飞书 CLI — 消息、文档、日历、任务,200+ 命令 | `opencli lark-cli calendar +agenda` |
| **dingtalk** | 钉钉 CLI — 钉钉全套产品能力的跨平台命令行工具,支持人类和 AI Agent 使用 | `opencli dingtalk msg send --to user "hello"` |
| **wecom** | 企业微信 CLI — 企业微信开放平台命令行工具,支持人类和 AI Agent 使用 | `opencli wecom msg send --to user "hello"` |
| **vercel** | Vercel — 部署项目、管理域名、环境变量、日志 | `opencli vercel deploy --prod` |
| **readwise** | Readwise / Reader CLI | `opencli readwise login` |
| **gws** | Google Workspace CLI — Docs, Sheets, Drive, Gmail, Calendar | `opencli gws docs list` |
**零配置透传**:OpenCLI 会把你的输入原样转发给底层二进制,保留原生 stdout / stderr 行为。
@@ -249,10 +227,8 @@ OpenCLI 支持从各平台下载图片、视频和文章。
| **小红书** | 图片、视频 | 下载笔记中的所有媒体文件 |
| **B站** | 视频 | 需要安装 `yt-dlp` |
| **Twitter/X** | 图片、视频 | 从用户媒体页或单条推文下载 |
| **Pixiv** | 图片 | 下载原始画质插画,支持多页作品 |
| **知乎** | 文章(Markdown) | 导出文章,可选下载图片到本地 |
| **微信公众号** | 文章(Markdown | 导出微信公众号文章为 Markdown |
| **豆瓣** | 图片 | 下载电影条目的海报 / 剧照图片 |
### 前置依赖
@@ -281,9 +257,6 @@ opencli twitter download elonmusk --limit 20 --output ./twitter
# 下载单条推文的媒体
opencli twitter download --tweet-url "https://x.com/user/status/123" --output ./twitter
# 下载豆瓣电影海报 / 剧照
opencli douban download 30382501 --output ./douban
# 导出知乎文章为 Markdown
opencli zhihu download "https://zhuanlan.zhihu.com/p/xxx" --output ./zhihu
@@ -311,31 +284,6 @@ opencli bilibili hot -f csv # CSV
opencli bilibili hot -v # 详细模式:展示管线执行步骤调试信息
```
## 退出码
opencli 遵循 Unix `sysexits.h` 惯例,可无缝接入 shell 管道和 CI 脚本:
| 退出码 | 含义 | 触发场景 |
|--------|------|----------|
| `0` | 成功 | 命令正常完成 |
| `1` | 通用错误 | 未分类的意外错误 |
| `2` | 用法错误 | 参数错误或未知命令 |
| `66` | 无数据 | 命令返回空结果(`EX_NOINPUT` |
| `69` | 服务不可用 | Browser Bridge 未连接(`EX_UNAVAILABLE` |
| `75` | 临时失败 | 命令超时,可重试(`EX_TEMPFAIL` |
| `77` | 需要认证 | 未登录目标网站(`EX_NOPERM` |
| `78` | 配置错误 | 凭证缺失或配置有误(`EX_CONFIG` |
| `130` | 中断 | Ctrl-C / SIGINT |
```bash
opencli bilibili hot 2>/dev/null
case $? in
0) echo "ok" ;;
69) echo "请先启动 Browser Bridge" ;;
77) echo "请先登录 bilibili.com" ;;
esac
```
## 插件
通过社区贡献的插件扩展 OpenCLI。插件使用与内置命令相同的 YAML/TS 格式,启动时自动发现。
@@ -344,12 +292,9 @@ esac
opencli plugin install github:user/opencli-plugin-my-tool # 安装
opencli plugin list # 查看已安装
opencli plugin update my-tool # 更新到最新
opencli plugin update --all # 更新全部已安装插件
opencli plugin uninstall my-tool # 卸载
```
当 plugin 的版本被记录到 `~/.opencli/plugins.lock.json` 后,`opencli plugin list` 也会显示对应的短 commit hash。
| 插件 | 类型 | 描述 |
|------|------|------|
| [opencli-plugin-github-trending](https://github.com/ByteYue/opencli-plugin-github-trending) | YAML | GitHub Trending 仓库 |
+772
View File
@@ -0,0 +1,772 @@
---
name: opencli
description: "OpenCLI — Make any website or Electron App your CLI. Zero risk, AI-powered, reuse Chrome login."
version: 1.3.1
author: jackwener
tags: [cli, browser, web, chrome-extension, cdp, bilibili, zhihu, twitter, github, v2ex, hackernews, reddit, xiaohongshu, xueqiu, youtube, boss, coupang, yollomi, AI, agent]
---
# OpenCLI
> Make any website or Electron App your CLI. Reuse Chrome login, zero risk, AI-powered discovery.
> [!CAUTION]
> **AI Agent 必读:创建或修改任何适配器之前,你必须先阅读 [CLI-EXPLORER.md](./CLI-EXPLORER.md)**
> 该文档包含完整的 API 发现工作流(必须使用浏览器探索)、5 级认证策略决策树、平台 SDK 速查表、`tap` 步骤调试流程、分页 API 模板、级联请求模式、以及常见陷阱。
> **本文件(SKILL.md)仅提供命令参考和简化模板,不足以正确开发适配器。**
## Install & Run
```bash
# npm global install (recommended)
npm install -g @jackwener/opencli
opencli <command>
# Or from source
cd ~/code/opencli && npm install
npx tsx src/main.ts <command>
# Update to latest
npm update -g @jackwener/opencli
```
## Prerequisites
Browser commands require:
1. Chrome browser running **(logged into target sites)**
2. **opencli Browser Bridge** Chrome extension installed (load `extension/` as unpacked in `chrome://extensions`)
3. No further setup needed — the daemon auto-starts on first browser command
> **Note**: You must be logged into the target website in Chrome before running commands. Tabs opened during command execution are auto-closed afterwards.
Public API commands (`hackernews`, `v2ex`) need no browser.
## Commands Reference
### Data Commands
```bash
# Bilibili (browser)
opencli bilibili hot --limit 10 # B站热门视频
opencli bilibili search "rust" # 搜索视频 (query positional)
opencli bilibili me # 我的信息
opencli bilibili favorite # 我的收藏
opencli bilibili history --limit 20 # 观看历史
opencli bilibili feed --limit 10 # 动态时间线
opencli bilibili user-videos --uid 12345 # 用户投稿
opencli bilibili subtitle --bvid BV1xxx # 获取视频字幕 (支持 --lang zh-CN)
opencli bilibili dynamic --limit 10 # 动态
opencli bilibili ranking --limit 10 # 排行榜
opencli bilibili following --limit 20 # 我的关注列表 (支持 --uid 查看他人)
# 知乎 (browser)
opencli zhihu hot --limit 10 # 知乎热榜
opencli zhihu search "AI" # 搜索 (query positional)
opencli zhihu question 34816524 # 问题详情和回答 (id positional)
# 小红书 (browser)
opencli xiaohongshu search "美食" # 搜索笔记 (query positional)
opencli xiaohongshu notifications # 通知(mentions/likes/connections
opencli xiaohongshu feed --limit 10 # 推荐 Feed
opencli xiaohongshu user xxx # 用户主页 (id positional)
opencli xiaohongshu creator-notes --limit 10 # 创作者笔记列表
opencli xiaohongshu creator-note-detail --note-id xxx # 笔记详情
opencli xiaohongshu creator-notes-summary # 笔记数据概览
opencli xiaohongshu creator-profile # 创作者资料
opencli xiaohongshu creator-stats # 创作者数据统计
# 雪球 Xueqiu (browser)
opencli xueqiu hot-stock --limit 10 # 雪球热门股票榜
opencli xueqiu stock --symbol SH600519 # 查看股票实时行情
opencli xueqiu watchlist # 获取自选股/持仓列表
opencli xueqiu feed # 我的关注 timeline
opencli xueqiu hot --limit 10 # 雪球热榜
opencli xueqiu search "特斯拉" # 搜索 (query positional)
# GitHub (via gh External CLI)
opencli gh repo list # 列出仓库 (passthrough to gh)
opencli gh pr list --limit 5 # PR 列表
opencli gh issue list # Issue 列表
# Twitter/X (browser)
opencli twitter trending --limit 10 # 热门话题
opencli twitter bookmarks --limit 20 # 获取收藏的书签推文
opencli twitter search "AI" # 搜索推文 (query positional)
opencli twitter profile elonmusk # 用户资料
opencli twitter timeline --limit 20 # 时间线
opencli twitter thread 1234567890 # 推文 thread(原文 + 回复)
opencli twitter article 1891511252174299446 # 推文长文内容
opencli twitter follow elonmusk # 关注用户
opencli twitter unfollow elonmusk # 取消关注
opencli twitter bookmark https://x.com/... # 收藏推文
opencli twitter unbookmark https://x.com/... # 取消收藏
# Reddit (browser)
opencli reddit hot --limit 10 # 热门帖子
opencli reddit hot --subreddit programming # 指定子版块
opencli reddit frontpage --limit 10 # 首页 /r/all
opencli reddit popular --limit 10 # /r/popular 热门
opencli reddit search "AI" --sort top --time week # 搜索(支持排序+时间过滤)
opencli reddit subreddit rust --sort top --time month # 子版块浏览(支持时间过滤)
opencli reddit read --post-id 1abc123 # 阅读帖子 + 评论
opencli reddit user spez # 用户资料(karma、注册时间)
opencli reddit user-posts spez # 用户发帖历史
opencli reddit user-comments spez # 用户评论历史
opencli reddit upvote --post-id xxx --direction up # 投票(up/down/none
opencli reddit save --post-id xxx # 收藏帖子
opencli reddit comment --post-id xxx "Great!" # 发表评论 (text positional)
opencli reddit subscribe --subreddit python # 订阅子版块
opencli reddit saved --limit 10 # 我的收藏
opencli reddit upvoted --limit 10 # 我的赞
# V2EX (public + browser)
opencli v2ex hot --limit 10 # 热门话题
opencli v2ex latest --limit 10 # 最新话题
opencli v2ex topic 1024 # 主题详情 (id positional)
opencli v2ex daily # 每日签到 (browser)
opencli v2ex me # 我的信息 (browser)
opencli v2ex notifications --limit 10 # 通知 (browser)
# Hacker News (public)
opencli hackernews top --limit 10 # Top stories
# BBC (public)
opencli bbc news --limit 10 # BBC News RSS headlines
# 微博 (browser)
opencli weibo hot --limit 10 # 微博热搜
# BOSS直聘 (browser)
opencli boss search "AI agent" # 搜索职位 (query positional)
opencli boss detail --security-id xxx # 职位详情
opencli boss recommend --limit 10 # 推荐职位
opencli boss joblist --limit 10 # 职位列表
opencli boss greet --security-id xxx # 打招呼
opencli boss batchgreet --job-id xxx # 批量打招呼
opencli boss send --uid xxx "消息内容" # 发消息 (text positional)
opencli boss chatlist --limit 10 # 聊天列表
opencli boss chatmsg --security-id xxx # 聊天记录
opencli boss invite --security-id xxx # 邀请沟通
opencli boss mark --security-id xxx # 标记管理
opencli boss exchange --security-id xxx # 交换联系方式
opencli boss resume # 简历管理
opencli boss stats # 数据统计
# YouTube (browser)
opencli youtube search "rust" # 搜索视频 (query positional)
opencli youtube video "https://www.youtube.com/watch?v=xxx" # 视频元数据
opencli youtube transcript "https://www.youtube.com/watch?v=xxx" # 获取视频字幕/转录
opencli youtube transcript "xxx" --lang zh-Hans --mode raw # 指定语言 + 原始时间戳模式
# Yahoo Finance (browser)
opencli yahoo-finance quote --symbol AAPL # 股票行情
# Sina Finance
opencli sinafinance news --limit 10 --type 1 # 7x24实时快讯 (0=全部 1=A股 2=宏观 3=公司 4=数据 5=市场 6=国际 7=观点 8=央行 9=其它)
# Reuters (browser)
opencli reuters search "AI" # 路透社搜索 (query positional)
# 什么值得买 (browser)
opencli smzdm search "耳机" # 搜索好价 (query positional)
# 携程 (browser)
opencli ctrip search "三亚" # 搜索目的地 (query positional)
# Antigravity (Electron/CDP)
opencli antigravity status # 检查 CDP 连接
opencli antigravity send "hello" # 发送文本到当前 agent 聊天框
opencli antigravity read # 读取整个聊天记录面板
opencli antigravity new # 清空聊天、开启新对话
opencli antigravity dump # 导出 DOM 和快照调试信息
opencli antigravity extract-code # 自动抽取 AI 回复中的代码块
opencli antigravity model claude # 切换底层模型
opencli antigravity watch # 流式监听增量消息
# Barchart (browser)
opencli barchart quote --symbol AAPL # 股票行情
opencli barchart options --symbol AAPL # 期权链
opencli barchart greeks --symbol AAPL # 期权 Greeks
opencli barchart flow --limit 20 # 异常期权活动
# Jike 即刻 (browser)
opencli jike feed --limit 10 # 动态流
opencli jike search "AI" # 搜索 (query positional)
opencli jike create "内容" # 发布动态 (text positional)
opencli jike like xxx # 点赞 (id positional)
opencli jike comment xxx "评论" # 评论 (id + text positional)
opencli jike repost xxx # 转发 (id positional)
opencli jike notifications # 通知
# Linux.do (public)
opencli linux-do hot --limit 10 # 热门话题
opencli linux-do latest --limit 10 # 最新话题
opencli linux-do search "rust" # 搜索 (query positional)
opencli linux-do topic 1024 # 主题详情 (id positional)
# StackOverflow (public)
opencli stackoverflow hot --limit 10 # 热门问题
opencli stackoverflow search "typescript" # 搜索 (query positional)
opencli stackoverflow bounties --limit 10 # 悬赏问题
# WeRead 微信读书 (browser)
opencli weread shelf --limit 10 # 书架
opencli weread search "AI" # 搜索图书 (query positional)
opencli weread book xxx # 图书详情 (book-id positional)
opencli weread highlights xxx # 划线笔记 (book-id positional)
opencli weread notes xxx # 想法笔记 (book-id positional)
opencli weread ranking --limit 10 # 排行榜
# Jimeng 即梦 AI (browser)
opencli jimeng generate --prompt "描述" # AI 生图
opencli jimeng history --limit 10 # 生成历史
# Yollomi yollomi.com (browser — 需在 Chrome 登录 yollomi.com,复用站点 session)
opencli yollomi models --type image # 列出图像模型与积分
opencli yollomi generate "提示词" --model z-image-turbo # 文生图
opencli yollomi video "提示词" --model kling-2-1 # 视频
opencli yollomi upload ./photo.jpg # 上传得 URL,供 img2img / 工具链使用
opencli yollomi remove-bg <image-url> # 去背景(免费)
opencli yollomi edit <image-url> "改成油画风格" # Qwen 图像编辑
# Grok (default + explicit web)
opencli grok ask --prompt "问题" # 提问 Grok(兼容默认路径)
opencli grok ask --prompt "问题" --web # 显式 grok.com consumer web UI 路径
# HuggingFace (public)
opencli hf top --limit 10 # 热门模型
# 超星学习通 (browser)
opencli chaoxing assignments # 作业列表
opencli chaoxing exams # 考试列表
# Douban 豆瓣 (browser)
opencli douban search "三体" # 搜索 (query positional)
opencli douban top250 # 豆瓣 Top 250
opencli douban subject 1234567 # 条目详情 (id positional)
opencli douban marks --limit 10 # 我的标记
opencli douban reviews --limit 10 # 短评
# Facebook (browser)
opencli facebook feed --limit 10 # 动态流
opencli facebook profile username # 用户资料 (id positional)
opencli facebook search "AI" # 搜索 (query positional)
opencli facebook friends # 好友列表
opencli facebook groups # 群组
opencli facebook events # 活动
opencli facebook notifications # 通知
opencli facebook memories # 回忆
opencli facebook add-friend username # 添加好友 (id positional)
opencli facebook join-group groupid # 加入群组 (id positional)
# Instagram (browser)
opencli instagram explore # 探索
opencli instagram profile username # 用户资料 (id positional)
opencli instagram search "AI" # 搜索 (query positional)
opencli instagram user username # 用户详情 (id positional)
opencli instagram followers username # 粉丝 (id positional)
opencli instagram following username # 关注 (id positional)
opencli instagram follow username # 关注用户 (id positional)
opencli instagram unfollow username # 取消关注 (id positional)
opencli instagram like postid # 点赞 (id positional)
opencli instagram unlike postid # 取消点赞 (id positional)
opencli instagram comment postid "评论" # 评论 (id + text positional)
opencli instagram save postid # 收藏 (id positional)
opencli instagram unsave postid # 取消收藏 (id positional)
opencli instagram saved # 已收藏列表
# TikTok (browser)
opencli tiktok explore # 探索
opencli tiktok search "AI" # 搜索 (query positional)
opencli tiktok profile username # 用户资料 (id positional)
opencli tiktok user username # 用户详情 (id positional)
opencli tiktok following username # 关注列表 (id positional)
opencli tiktok follow username # 关注 (id positional)
opencli tiktok unfollow username # 取消关注 (id positional)
opencli tiktok like videoid # 点赞 (id positional)
opencli tiktok unlike videoid # 取消点赞 (id positional)
opencli tiktok comment videoid "评论" # 评论 (id + text positional)
opencli tiktok save videoid # 收藏 (id positional)
opencli tiktok unsave videoid # 取消收藏 (id positional)
opencli tiktok live # 直播
opencli tiktok notifications # 通知
opencli tiktok friends # 朋友
# Medium (browser)
opencli medium feed --limit 10 # 动态流
opencli medium search "AI" # 搜索 (query positional)
opencli medium user username # 用户主页 (id positional)
# Substack (browser)
opencli substack feed --limit 10 # 订阅动态
opencli substack search "AI" # 搜索 (query positional)
opencli substack publication name # 出版物详情 (id positional)
# Sinablog 新浪博客 (browser)
opencli sinablog hot --limit 10 # 热门
opencli sinablog search "AI" # 搜索 (query positional)
opencli sinablog article url # 文章详情
opencli sinablog user username # 用户主页 (id positional)
# Lobsters (public)
opencli lobsters hot --limit 10 # 热门
opencli lobsters newest --limit 10 # 最新
opencli lobsters active --limit 10 # 活跃
opencli lobsters tag rust # 按标签筛选 (tag positional)
# Google (public)
opencli google news --limit 10 # 新闻
opencli google search "AI" # 搜索 (query positional)
opencli google suggest "AI" # 搜索建议 (query positional)
opencli google trends # 趋势
# DEV.to (public)
opencli devto top --limit 10 # 热门文章
opencli devto tag javascript --limit 10 # 按标签 (tag positional)
opencli devto user username # 用户文章 (username positional)
# Steam (public)
opencli steam top-sellers --limit 10 # 热销游戏
# Wikipedia (public)
opencli wikipedia search "AI" # 搜索 (query positional)
opencli wikipedia summary "Python" # 摘要 (title positional)
```
### Desktop Adapter Commands
```bash
# Cursor (desktop — CDP via Electron)
opencli cursor status # 检查连接
opencli cursor send "message" # 发送消息
opencli cursor read # 读取回复
opencli cursor new # 新建对话
opencli cursor dump # 导出 DOM 调试信息
opencli cursor composer # Composer 模式
opencli cursor model claude # 切换模型
opencli cursor extract-code # 提取代码块
opencli cursor ask "question" # 一键提问并等回复
opencli cursor screenshot # 截图
opencli cursor history # 对话历史
opencli cursor export # 导出对话
# Codex (desktop — headless CLI agent)
opencli codex status # 检查连接
opencli codex send "message" # 发送消息
opencli codex read # 读取回复
opencli codex new # 新建对话
opencli codex dump # 导出调试信息
opencli codex extract-diff # 提取 diff
opencli codex model gpt-4 # 切换模型
opencli codex ask "question" # 一键提问并等回复
opencli codex screenshot # 截图
opencli codex history # 对话历史
opencli codex export # 导出对话
# ChatGPT (desktop — macOS AppleScript/CDP)
opencli chatgpt status # 检查应用状态
opencli chatgpt new # 新建对话
opencli chatgpt send "message" # 发送消息
opencli chatgpt read # 读取回复
opencli chatgpt ask "question" # 一键提问并等回复
# ChatWise (desktop — multi-LLM client)
opencli chatwise status # 检查连接
opencli chatwise new # 新建对话
opencli chatwise send "message" # 发送消息
opencli chatwise read # 读取回复
opencli chatwise ask "question" # 一键提问并等回复
opencli chatwise model claude # 切换模型
opencli chatwise history # 对话历史
opencli chatwise export # 导出对话
opencli chatwise screenshot # 截图
# Notion (desktop — CDP via Electron)
opencli notion status # 检查连接
opencli notion search "keyword" # 搜索页面
opencli notion read # 读取当前页面
opencli notion new # 新建页面
opencli notion write "content" # 写入内容
opencli notion sidebar # 侧边栏导航
opencli notion favorites # 收藏列表
opencli notion export # 导出
# Discord App (desktop — CDP via Electron)
opencli discord-app status # 检查连接
opencli discord-app send "message" # 发送消息
opencli discord-app read # 读取消息
opencli discord-app channels # 频道列表
opencli discord-app servers # 服务器列表
opencli discord-app search "keyword" # 搜索
opencli discord-app members # 成员列表
# Doubao App 豆包桌面版 (desktop — CDP via Electron)
opencli doubao-app status # 检查连接
opencli doubao-app new # 新建对话
opencli doubao-app send "message" # 发送消息
opencli doubao-app read # 读取回复
opencli doubao-app ask "question" # 一键提问并等回复
opencli doubao-app screenshot # 截图
opencli doubao-app dump # 导出 DOM 调试信息
```
### Management Commands
```bash
opencli list # List all commands (including External CLIs)
opencli list --json # JSON output
opencli list -f yaml # YAML output
opencli install <name> # Auto-install an external CLI (e.g., gh, obsidian)
opencli register <name> # Register a local custom CLI for unified discovery
opencli validate # Validate all CLI definitions
opencli validate bilibili # Validate specific site
opencli doctor # Diagnose browser bridge (auto-starts daemon, includes live test)
```
### AI Agent Workflow
```bash
# Deep Explore: network intercept → response analysis → capability inference
opencli explore <url> --site <name>
# Synthesize: generate evaluate-based YAML pipelines from explore artifacts
opencli synthesize <site>
# Generate: one-shot explore → synthesize → register
opencli generate <url> --goal "hot"
# Record: YOU operate the page, opencli captures every API call → YAML candidates
# Opens the URL in automation window, injects fetch/XHR interceptor into ALL tabs,
# polls every 2s, auto-stops after 60s (or press Enter to stop early).
opencli record <url> # 录制,site name 从域名推断
opencli record <url> --site mysite # 指定 site name
opencli record <url> --timeout 120000 # 自定义超时(毫秒,默认 60000)
opencli record <url> --poll 1000 # 缩短轮询间隔(毫秒,默认 2000)
opencli record <url> --out .opencli/record/x # 自定义输出目录
# Output:
# .opencli/record/<site>/captured.json ← 原始捕获数据(带 url/method/body
# .opencli/record/<site>/candidates/*.yaml ← 高置信度候选适配器(score ≥ 8,有 array 结果)
# Strategy Cascade: auto-probe PUBLIC → COOKIE → HEADER
opencli cascade <api-url>
# Explore with interactive fuzzing (click buttons to trigger lazy APIs)
opencli explore <url> --auto --click "字幕,CC,评论"
# Validate: validate adapter definitions
opencli validate
```
## Output Formats
All built-in commands support `--format` / `-f` with `table`, `json`, `yaml`, `md`, and `csv`.
The `list` command supports the same formats and also keeps `--json` as a compatibility alias.
```bash
opencli list -f yaml # YAML command registry
opencli bilibili hot -f table # Default: rich table
opencli bilibili hot -f json # JSON (pipe to jq, feed to AI agent)
opencli bilibili hot -f yaml # YAML (readable structured output)
opencli bilibili hot -f md # Markdown
opencli bilibili hot -f csv # CSV
```
## Verbose Mode
```bash
opencli bilibili hot -v # Show each pipeline step and data flow
```
## Record Workflow
`record` 是为「无法用 `explore` 自动发现」的页面(需要登录操作、复杂交互、SPA 内路由)准备的手动录制方案。
### 工作原理
```
opencli record <url>
→ 打开 automation window 并导航到目标 URL
→ 向所有 tab 注入 fetch/XHR 拦截器(幂等,可重复注入)
→ 每 2s 轮询一次:发现新 tab 自动注入,drain 所有 tab 的捕获缓冲区
→ 超时(默认 60s)或按 Enter 停止
→ 分析捕获到的 JSON 请求:去重 → 评分 → 生成候选 YAML
```
**拦截器特性**
- 同时 patch `window.fetch``XMLHttpRequest`
- 只捕获 `Content-Type: application/json` 的响应
- 过滤纯对象少于 2 个 key 的响应(避免 tracking/ping
- 跨 tab 隔离:每个 tab 独立缓冲区,轮询时分别 drain
- 幂等注入:同一 tab 二次注入时先 restore 原始函数再重新 patch,不丢失已捕获数据
### 使用步骤
```bash
# 1. 启动录制(建议 --timeout 给足操作时间)
opencli record "https://example.com/page" --timeout 120000
# 2. 在弹出的 automation window 里正常操作页面:
# - 打开列表、搜索、点击条目、切换 Tab
# - 凡是触发网络请求的操作都会被捕获
# 3. 完成操作后按 Enter 停止(或等超时自动停止)
# 4. 查看结果
cat .opencli/record/<site>/captured.json # 原始捕获
ls .opencli/record/<site>/candidates/ # 候选 YAML
```
### 页面类型与捕获预期
| 页面类型 | 预期捕获量 | 说明 |
|---------|-----------|------|
| 列表/搜索页 | 多(5~20+) | 每次搜索/翻页都会触发新请求 |
| 详情页(只读) | 少(1~5) | 首屏数据一次性返回,后续操作走 form/redirect |
| SPA 内路由跳转 | 中等 | 路由切换会触发新接口,但首屏请求在注入前已发出 |
| 需要登录的页面 | 视操作而定 | 确保 Chrome 已登录目标网站 |
> **注意**:如果页面在导航完成前就发出了大部分请求(服务端渲染 / SSR 注水),拦截器会错过这些请求。
> 解决方案:在页面加载完成后,手动触发能产生新请求的操作(搜索、翻页、切 Tab、展开折叠项等)。
### 候选 YAML → TS CLI 转换
生成的候选 YAML 是起点,通常需要转换为 TypeScript(尤其是 tae 等内部系统):
**候选 YAML 结构**(自动生成):
```yaml
site: tae
name: getList # 从 URL path 推断的名称
strategy: cookie
browser: true
pipeline:
- navigate: https://...
- evaluate: |
(async () => {
const res = await fetch('/approval/getList.json?procInsId=...', { credentials: 'include' });
const data = await res.json();
return (data?.content?.operatorRecords || []).map(item => ({ ... }));
})()
```
**转换为 TS CLI**(参考 `src/clis/tae/add-expense.ts` 风格):
```typescript
import { cli, Strategy } from '../../registry.js';
cli({
site: 'tae',
name: 'get-approval',
description: '查看报销单审批流程和操作记录',
domain: 'tae.alibaba-inc.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'proc_ins_id', type: 'string', required: true, positional: true, help: '流程实例 IDprocInsId' },
],
columns: ['step', 'operator', 'action', 'time'],
func: async (page, kwargs) => {
await page.goto('https://tae.alibaba-inc.com/expense/pc.html?_authType=SAML');
await page.wait(2);
const result = await page.evaluate(`(async () => {
const res = await fetch('/approval/getList.json?taskId=&procInsId=${kwargs.proc_ins_id}', {
credentials: 'include'
});
const data = await res.json();
return data?.content?.operatorRecords || [];
})()`);
return (result as any[]).map((r, i) => ({
step: i + 1,
operator: r.operatorName || r.userId,
action: r.operationType,
time: r.operateTime,
}));
},
});
```
**转换要点**
1. URL 中的动态 ID`procInsId``taskId` 等)提取为 `args`
2. `captured.json` 里的真实 body 结构用于确定正确的数据路径(如 `content.operatorRecords`
3. tae 系统统一用 `{ success, content, errorCode, errorMsg }` 外层包裹,取数据要走 `content.*`
4. 认证方式:cookie`credentials: 'include'`),不需要额外 header
5. 文件放入 `src/clis/<site>/`,无需手动注册,`npm run build` 后自动发现
### 故障排查
| 现象 | 原因 | 解法 |
|------|------|------|
| 捕获 0 条请求 | 拦截器注入失败,或页面无 JSON API | 检查 daemon 是否运行:`curl localhost:19825/status` |
| 捕获量少(1~3 条) | 页面是只读详情页,首屏数据已在注入前发出 | 手动操作触发更多请求(搜索/翻页),或换用列表页 |
| 候选 YAML 为 0 | 捕获到的 JSON 都没有 array 结构 | 直接看 `captured.json` 手写 TS CLI |
| 新开的 tab 没有被拦截 | 轮询间隔内 tab 已关闭 | 缩短 `--poll 500` |
| 二次运行 record 时数据不连续 | 正常,每次 `record` 启动都是新的 automation window | 无需处理 |
## Creating Adapters
> [!TIP]
> **快速模式**:如果你只想为一个具体页面生成一个命令,直接看 [CLI-ONESHOT.md](./CLI-ONESHOT.md)。
> 只需要一个 URL + 一句话描述,4 步搞定。
> [!IMPORTANT]
> **完整模式 — 在写任何代码之前,先阅读 [CLI-EXPLORER.md](./CLI-EXPLORER.md)。**
> 它包含:① AI Agent 浏览器探索工作流 ② 认证策略决策树 ③ 平台 SDK(如 Bilibili 的 `apiGet`/`fetchJson`)④ YAML vs TS 选择指南 ⑤ `tap` 步骤调试方法 ⑥ 级联请求模板 ⑦ 常见陷阱表。
> **下方仅为简化模板参考,直接使用极易踩坑。**
### YAML Pipeline (declarative, recommended)
Create `src/clis/<site>/<name>.yaml`:
```yaml
site: mysite
name: hot
description: Hot topics
domain: www.mysite.com
strategy: cookie # public | cookie | header | intercept | ui
browser: true
args:
limit:
type: int
default: 20
description: Number of items
pipeline:
- navigate: https://www.mysite.com
- evaluate: |
(async () => {
const res = await fetch('/api/hot', { credentials: 'include' });
const d = await res.json();
return d.data.items.map(item => ({
title: item.title,
score: item.score,
}));
})()
- map:
rank: ${{ index + 1 }}
title: ${{ item.title }}
score: ${{ item.score }}
- limit: ${{ args.limit }}
columns: [rank, title, score]
```
For public APIs (no browser):
```yaml
strategy: public
browser: false
pipeline:
- fetch:
url: https://api.example.com/hot.json
- select: data.items
- map:
title: ${{ item.title }}
- limit: ${{ args.limit }}
```
### TypeScript Adapter (programmatic)
Create `src/clis/<site>/<name>.ts`. It will be automatically dynamically loaded (DO NOT manually import it in `index.ts`):
```typescript
import { cli, Strategy } from '../../registry.js';
cli({
site: 'mysite',
name: 'search',
strategy: Strategy.INTERCEPT, // Or COOKIE
args: [{ name: 'query', required: true, positional: true }],
columns: ['rank', 'title', 'url'],
func: async (page, kwargs) => {
await page.goto('https://www.mysite.com/search');
// Inject native XHR/Fetch interceptor hook
await page.installInterceptor('/api/search');
// Auto scroll down to trigger lazy loading
await page.autoScroll({ times: 3, delayMs: 2000 });
// Retrieve intercepted JSON payloads
const requests = await page.getInterceptedRequests();
let results = [];
for (const req of requests) {
results.push(...req.data.items);
}
return results.map((item, i) => ({
rank: i + 1, title: item.title, url: item.url,
}));
},
});
```
**When to use TS**: XHR interception (`page.installInterceptor`), infinite scrolling (`page.autoScroll`), cookie extraction, complex data transforms (like GraphQL unwrapping).
## Pipeline Steps
| Step | Description | Example |
|------|-------------|---------|
| `navigate` | Go to URL | `navigate: https://example.com` |
| `fetch` | HTTP request (browser cookies) | `fetch: { url: "...", params: { q: "..." } }` |
| `evaluate` | Run JavaScript in page | `evaluate: \| (async () => { ... })()` |
| `select` | Extract JSON path | `select: data.items` |
| `map` | Map fields | `map: { title: "${{ item.title }}" }` |
| `filter` | Filter items | `filter: item.score > 100` |
| `sort` | Sort items | `sort: { by: score, order: desc }` |
| `limit` | Cap result count | `limit: ${{ args.limit }}` |
| `intercept` | Declarative XHR capture | `intercept: { trigger: "navigate:...", capture: "api/hot" }` |
| `tap` | Store action + XHR capture | `tap: { store: "feed", action: "fetchFeeds", capture: "homefeed" }` |
| `snapshot` | Page accessibility tree | `snapshot: { interactive: true }` |
| `click` | Click element | `click: ${{ ref }}` |
| `type` | Type text | `type: { ref: "@1", text: "hello" }` |
| `wait` | Wait for time/text | `wait: 2` or `wait: { text: "loaded" }` |
| `press` | Press key | `press: Enter` |
## Template Syntax
```yaml
# Arguments with defaults
${{ args.query }}
${{ args.limit | default(20) }}
# Current item (in map/filter)
${{ item.title }}
${{ item.data.nested.field }}
# Index (0-based)
${{ index }}
${{ index + 1 }}
```
## 5-Tier Authentication Strategy
| Tier | Name | Method | Example |
|------|------|--------|---------|
| 1 | `public` | No auth, Node.js fetch | Hacker News, V2EX |
| 2 | `cookie` | Browser fetch with `credentials: include` | Bilibili, Zhihu |
| 3 | `header` | Custom headers (ct0, Bearer) | Twitter GraphQL |
| 4 | `intercept` | XHR interception + store mutation | 小红书 Pinia |
| 5 | `ui` | Full UI automation (click/type/scroll) | Last resort |
## Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `OPENCLI_DAEMON_PORT` | 19825 | Daemon listen port |
| `OPENCLI_BROWSER_CONNECT_TIMEOUT` | 30 | Browser connection timeout (sec) |
| `OPENCLI_BROWSER_COMMAND_TIMEOUT` | 45 | Command execution timeout (sec) |
| `OPENCLI_BROWSER_EXPLORE_TIMEOUT` | 120 | Explore timeout (sec) |
| `OPENCLI_VERBOSE` | — | Show daemon/extension logs |
## Troubleshooting
| Issue | Solution |
|-------|----------|
| `npx not found` | Install Node.js: `brew install node` |
| `Extension not connected` | 1) Chrome must be open 2) Install opencli Browser Bridge extension |
| `Target page context` error | Add `navigate:` step before `evaluate:` in YAML |
| Empty table data | Check if evaluate returns correct data path |
| Daemon issues | `curl localhost:19825/status` to check, `curl localhost:19825/logs` for extension logs |
-1
View File
@@ -68,7 +68,6 @@ src/
| `tests/e2e/browser-auth.test.ts` | `bilibili``twitter``v2ex``xueqiu``linux-do``xiaohongshu` 的需登录命令 graceful failure |
| `tests/e2e/management.test.ts` | `list``validate``verify``--version``--help`、unknown command |
| `tests/e2e/output-formats.test.ts` | `json` / `yaml` / `csv` / `md` 输出格式校验 |
| `tests/e2e/plugin-management.test.ts` | `plugin install` / `list` / `update` / `uninstall` 全生命周期 |
### 烟雾测试(1 个文件)
-1
View File
@@ -1 +0,0 @@
56/59
-1
View File
@@ -1 +0,0 @@
31/31
-688
View File
@@ -1,688 +0,0 @@
[
{
"name": "extract-title-example",
"steps": [
"opencli operate open https://example.com",
"opencli operate eval \"document.title\""
],
"judge": {
"type": "contains",
"value": "Example Domain"
}
},
{
"name": "extract-title-iana",
"steps": [
"opencli operate open https://www.iana.org",
"opencli operate eval \"document.querySelector('h1')?.textContent\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "extract-paragraph-wiki-js",
"steps": [
"opencli operate open https://en.wikipedia.org/wiki/JavaScript",
"opencli operate eval \"(() => { const ps = document.querySelectorAll('#mw-content-text .mw-parser-output > p'); for (const p of ps) { const t = p.textContent?.trim(); if (t && t.length > 50 && !t.startsWith('{')) return t.slice(0,300); } return ''; })()\""
],
"judge": {
"type": "contains",
"value": "programming language"
}
},
{
"name": "extract-paragraph-wiki-python",
"steps": [
"opencli operate open \"https://en.wikipedia.org/wiki/Python_(programming_language)\"",
"opencli operate eval \"(() => { const ps = document.querySelectorAll('#mw-content-text .mw-parser-output > p'); for (const p of ps) { const t = p.textContent?.trim(); if (t && t.length > 50 && !t.startsWith('{')) return t.slice(0,300); } return ''; })()\""
],
"judge": {
"type": "contains",
"value": "programming language"
}
},
{
"name": "extract-github-stars",
"steps": [
"opencli operate open https://github.com/browser-use/browser-use",
"opencli operate eval \"document.querySelector('#repo-stars-counter-star')?.textContent?.trim()\""
],
"judge": {
"type": "matchesPattern",
"pattern": "\\d"
}
},
{
"name": "extract-github-description",
"steps": [
"opencli operate open https://github.com/anthropics/claude-code",
"opencli operate eval \"document.querySelector('p.f4, [data-testid=about-description], .f4.my-3, .BorderGrid-cell p')?.textContent?.trim()\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "extract-github-readme-heading",
"steps": [
"opencli operate open https://github.com/vercel/next.js",
"opencli operate eval \"document.querySelector('article h1, article h2')?.textContent?.trim()\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "extract-npm-downloads",
"steps": [
"opencli operate open https://www.npmjs.com/package/zod",
"opencli operate eval \"document.querySelector('[data-nosnippet]')?.textContent?.trim() || document.querySelector('p.f2874b88')?.textContent?.trim()\""
],
"judge": {
"type": "matchesPattern",
"pattern": "\\d"
}
},
{
"name": "extract-npm-description",
"steps": [
"opencli operate open https://www.npmjs.com/package/express",
"opencli operate eval \"document.querySelector('p[class*=description], [data-testid=package-description], #readme p')?.textContent?.trim()\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "list-hn-top5",
"steps": [
"opencli operate open https://news.ycombinator.com",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('.titleline > a')].slice(0,5).map(a=>({title:a.textContent,url:a.href})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 5
}
},
{
"name": "list-hn-top10",
"steps": [
"opencli operate open https://news.ycombinator.com",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('.athing')].slice(0,10).map(tr=>{const a=tr.querySelector('.titleline>a');const s=tr.nextElementSibling?.querySelector('.score');return{title:a?.textContent,score:parseInt(s?.textContent)||0}}))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 10
}
},
{
"name": "list-books-5",
"steps": [
"opencli operate open https://books.toscrape.com",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('article.product_pod')].slice(0,5).map(el=>({title:el.querySelector('h3 a')?.getAttribute('title'),price:el.querySelector('.price_color')?.textContent})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 5
}
},
{
"name": "list-books-10",
"steps": [
"opencli operate open https://books.toscrape.com",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('article.product_pod')].slice(0,10).map(el=>({title:el.querySelector('h3 a')?.getAttribute('title'),price:el.querySelector('.price_color')?.textContent})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 10
}
},
{
"name": "list-quotes-3",
"steps": [
"opencli operate open https://quotes.toscrape.com",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('.quote')].slice(0,3).map(el=>({text:el.querySelector('.text')?.textContent,author:el.querySelector('.author')?.textContent})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 3
}
},
{
"name": "list-quotes-tags",
"steps": [
"opencli operate open https://quotes.toscrape.com",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('.quote')].slice(0,5).map(el=>({text:el.querySelector('.text')?.textContent,author:el.querySelector('.author')?.textContent,tags:[...el.querySelectorAll('.tag')].map(t=>t.textContent)})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 5
}
},
{
"name": "list-github-trending",
"steps": [
"opencli operate open https://github.com/trending",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('article.Box-row')].slice(0,3).map(el=>({name:el.querySelector('h2 a')?.textContent?.trim().replace(/\\s+/g,' '),desc:el.querySelector('p')?.textContent?.trim()})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 3
}
},
{
"name": "list-github-trending-lang",
"steps": [
"opencli operate open https://github.com/trending/python",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('article.Box-row')].slice(0,5).map(el=>({name:el.querySelector('h2 a')?.textContent?.trim().replace(/\\s+/g,' ')})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 5
}
},
{
"name": "list-jsonplaceholder-posts",
"steps": [
"opencli operate open https://jsonplaceholder.typicode.com/posts",
"opencli operate eval \"JSON.stringify(JSON.parse(document.body.innerText).slice(0,5).map(p=>({id:p.id,title:p.title})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 5
}
},
{
"name": "list-jsonplaceholder-users",
"steps": [
"opencli operate open https://jsonplaceholder.typicode.com/users",
"opencli operate eval \"JSON.stringify(JSON.parse(document.body.innerText).map(u=>({name:u.name,email:u.email})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 5
}
},
{
"name": "search-google",
"steps": [
"opencli operate open https://www.google.com",
"opencli operate eval \"document.querySelector('textarea[name=q], input[name=q]').value='opencli github';document.querySelector('form').submit();'submitted'\"",
"opencli operate wait time 3",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('h3')].slice(0,3).map(h=>h.textContent))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 3
},
"note": "index 5 may vary"
},
{
"name": "search-ddg",
"steps": [
"opencli operate open https://duckduckgo.com",
"opencli operate state",
"opencli operate type 1 \"weather beijing\"",
"opencli operate keys Enter",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('[data-testid=result-title-a]')].slice(0,3).map(a=>a.textContent))\""
],
"judge": {
"type": "nonEmpty"
},
"note": "index may vary"
},
{
"name": "search-ddg-tech",
"steps": [
"opencli operate open https://duckduckgo.com",
"opencli operate eval \"document.querySelector('input[name=q]').value='TypeScript tutorial';document.querySelector('form').submit();'submitted'\"",
"opencli operate wait time 3",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('[data-testid=result-title-a], .result__a')].slice(0,3).map(a=>({title:a.textContent,url:a.href})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 3
},
"note": "index may vary"
},
{
"name": "search-wiki",
"steps": [
"opencli operate open https://en.wikipedia.org",
"opencli operate eval \"document.querySelector('input[name=search]').value='Rust programming language';document.querySelector('form#searchform, form[role=search]').submit();'submitted'\"",
"opencli operate wait time 3",
"opencli operate eval \"(() => { const ps = document.querySelectorAll('#mw-content-text .mw-parser-output > p'); for (const p of ps) { const t = p.textContent?.trim(); if (t && t.length > 50) return t.slice(0,300); } return ''; })()\""
],
"judge": {
"type": "contains",
"value": "programming language"
},
"note": "index may vary"
},
{
"name": "search-npm",
"steps": [
"opencli operate open https://www.npmjs.com",
"opencli operate state",
"opencli operate type 1 \"react\"",
"opencli operate keys Enter",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('[data-testid=pkg-list-item] h3, section h3')].slice(0,3).map(h=>h.textContent?.trim()))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 3
},
"note": "index may vary"
},
{
"name": "search-github",
"steps": [
"opencli operate open https://github.com/search?q=browser+automation&type=repositories",
"opencli operate wait time 3",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('.search-title a, [data-testid=results-list] a.Link--primary')].slice(0,3).map(a=>a.textContent?.trim().replace(/\\\\s+/g,' ')))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 3
},
"note": "index may vary"
},
{
"name": "nav-click-link-example",
"steps": [
"opencli operate open https://example.com",
"opencli operate eval \"document.querySelector('a')?.click();'clicked'\"",
"opencli operate wait time 2",
"opencli operate eval \"document.title\""
],
"judge": {
"type": "contains",
"value": "IANA"
}
},
{
"name": "nav-click-hn-first",
"steps": [
"opencli operate open https://news.ycombinator.com",
"opencli operate eval \"document.querySelector('.titleline a')?.click();'clicked'\"",
"opencli operate wait time 2",
"opencli operate eval \"document.title\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "nav-click-hn-comments",
"steps": [
"opencli operate open https://news.ycombinator.com",
"opencli operate eval \"document.querySelector('.subtext a:last-child')?.click(); 'clicked'\"",
"opencli operate eval \"document.title\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "nav-click-wiki-link",
"steps": [
"opencli operate open https://en.wikipedia.org/wiki/JavaScript",
"opencli operate eval \"document.querySelector('#toc a, .toc a, [href=\\\"#History\\\"]')?.click(); 'clicked'\"",
"opencli operate eval \"document.querySelector('#History, #History ~ p')?.textContent?.slice(0,100)\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "nav-click-github-tab",
"steps": [
"opencli operate open https://github.com/vercel/next.js",
"opencli operate eval \"document.querySelector('[data-tab-item=i1issues-tab] a, #issues-tab')?.click(); 'clicked'\"",
"opencli operate eval \"document.title\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "nav-go-back",
"steps": [
"opencli operate open https://example.com",
"opencli operate eval \"document.querySelector('a')?.click();'clicked'\"",
"opencli operate wait time 2",
"opencli operate back",
"opencli operate wait time 2",
"opencli operate eval \"document.title\""
],
"judge": {
"type": "contains",
"value": "Example Domain"
}
},
{
"name": "nav-multi-step",
"steps": [
"opencli operate open https://quotes.toscrape.com",
"opencli operate eval \"document.querySelector('.next a')?.click(); 'clicked'\"",
"opencli operate eval \"document.querySelector('.quote .text')?.textContent\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "scroll-footer-quotes",
"steps": [
"opencli operate open https://quotes.toscrape.com",
"opencli operate scroll down",
"opencli operate scroll down",
"opencli operate eval \"document.querySelector('footer, .footer, .tags-box')?.textContent?.trim().slice(0,100)\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "scroll-footer-books",
"steps": [
"opencli operate open https://books.toscrape.com",
"opencli operate scroll down",
"opencli operate scroll down",
"opencli operate eval \"document.querySelector('.pager .current')?.textContent?.trim()\""
],
"judge": {
"type": "matchesPattern",
"pattern": "\\d"
}
},
{
"name": "scroll-long-page",
"steps": [
"opencli operate open https://jsonplaceholder.typicode.com/posts",
"opencli operate eval \"JSON.parse(document.body.innerText).length\""
],
"judge": {
"type": "matchesPattern",
"pattern": "\\d"
}
},
{
"name": "scroll-find-element",
"steps": [
"opencli operate open https://quotes.toscrape.com",
"opencli operate eval \"document.querySelector('.next a')?.href\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "scroll-lazy-load",
"steps": [
"opencli operate open https://books.toscrape.com",
"opencli operate eval \"document.querySelectorAll('article.product_pod').length\""
],
"judge": {
"type": "matchesPattern",
"pattern": "\\d"
}
},
{
"name": "form-simple-name",
"steps": [
"opencli operate open https://httpbin.org/forms/post",
"opencli operate eval \"var el=document.querySelector('[name=custname]');el.value='OpenCLI Test';el.dispatchEvent(new Event('input',{bubbles:true}));el.value\""
],
"judge": {
"type": "contains",
"value": "OpenCLI"
},
"note": "index may vary"
},
{
"name": "form-text-inputs",
"steps": [
"opencli operate open https://httpbin.org/forms/post",
"opencli operate eval \"var n=document.querySelector('[name=custname]');n.value='Alice';n.dispatchEvent(new Event('input',{bubbles:true}));var t=document.querySelector('[name=custtel]');t.value='555-1234';t.dispatchEvent(new Event('input',{bubbles:true}));n.value+'|'+t.value\""
],
"judge": {
"type": "contains",
"value": "Alice"
},
"note": "index may vary"
},
{
"name": "form-radio-select",
"steps": [
"opencli operate open https://httpbin.org/forms/post",
"opencli operate eval \"document.querySelector('[value=medium]').checked=true;document.querySelector('[value=medium]').dispatchEvent(new Event('change',{bubbles:true}));document.querySelector('[value=medium]').checked\""
],
"judge": {
"type": "contains",
"value": "true"
}
},
{
"name": "form-checkbox",
"steps": [
"opencli operate open https://httpbin.org/forms/post",
"opencli operate eval \"var cb=document.querySelector('[value=cheese]');cb.checked=true;cb.dispatchEvent(new Event('change',{bubbles:true}));cb.checked\""
],
"judge": {
"type": "contains",
"value": "true"
}
},
{
"name": "form-textarea",
"steps": [
"opencli operate open https://httpbin.org/forms/post",
"opencli operate eval \"var ta=document.querySelector('textarea[name=comments]');ta.value='AutoResearch test';ta.dispatchEvent(new Event('input',{bubbles:true}));ta.value\""
],
"judge": {
"type": "contains",
"value": "AutoResearch"
}
},
{
"name": "form-login-fake",
"steps": [
"opencli operate open https://the-internet.herokuapp.com/login",
"opencli operate eval \"var u=document.querySelector('#username');u.value='testuser';u.dispatchEvent(new Event('input',{bubbles:true}));var p=document.querySelector('#password');p.value='testpass';p.dispatchEvent(new Event('input',{bubbles:true}));u.value+'|'+p.value\""
],
"judge": {
"type": "contains",
"value": "testuser"
},
"note": "index may vary"
},
{
"name": "complex-wiki-toc",
"steps": [
"opencli operate open https://en.wikipedia.org/wiki/JavaScript",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('.toc li a, #toc li a, .vector-toc-contents a')].slice(0,8).map(a=>a.textContent?.trim()))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 5
}
},
{
"name": "complex-books-detail",
"steps": [
"opencli operate open https://books.toscrape.com",
"opencli operate eval \"document.querySelector('article.product_pod h3 a')?.click();'clicked'\"",
"opencli operate eval \"JSON.stringify({title:document.querySelector('h1')?.textContent,price:document.querySelector('.price_color')?.textContent})\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "complex-quotes-page2",
"steps": [
"opencli operate open https://quotes.toscrape.com",
"opencli operate eval \"document.querySelector('.next a')?.click();'clicked'\"",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('.quote')].slice(0,3).map(el=>({text:el.querySelector('.text')?.textContent,author:el.querySelector('.author')?.textContent})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 3
}
},
{
"name": "complex-github-repo-info",
"steps": [
"opencli operate open https://github.com/expressjs/express",
"opencli operate eval \"JSON.stringify({lang:document.querySelector('[itemprop=programmingLanguage]')?.textContent?.trim(),license:document.querySelector('[data-analytics-event*=license] span, .Layout-sidebar [href*=LICENSE]')?.textContent?.trim()})\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "complex-hn-story-comments",
"steps": [
"opencli operate open https://news.ycombinator.com",
"opencli operate eval \"document.querySelector('.subtext a:last-child')?.click();'clicked'\"",
"opencli operate eval \"document.querySelector('.fatitem .titleline a')?.textContent\""
],
"judge": {
"type": "nonEmpty"
}
},
{
"name": "complex-multi-extract",
"steps": [
"opencli operate open https://en.wikipedia.org/wiki/TypeScript",
"opencli operate eval \"JSON.stringify({title:document.title,firstParagraph:document.querySelector('#mw-content-text p')?.textContent?.slice(0,150)})\""
],
"judge": {
"type": "contains",
"value": "TypeScript"
}
},
{
"name": "bench-reddit-top5",
"steps": [
"opencli operate open https://old.reddit.com",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('#siteTable .thing .title a.title')].slice(0,5).map(a=>a.textContent))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 5
},
"set": "test"
},
{
"name": "bench-imdb-matrix",
"steps": [
"opencli operate open https://www.imdb.com/title/tt0133093/",
"opencli operate eval \"JSON.stringify({title:document.querySelector('h1 span, [data-testid=hero__pageTitle] span')?.textContent,year:document.querySelector('a[href*=releaseinfo], [data-testid=hero-title-block__metadata] a')?.textContent})\""
],
"judge": {
"type": "contains",
"value": "1999"
},
"set": "test"
},
{
"name": "bench-npm-zod",
"steps": [
"opencli operate open https://www.npmjs.com/package/zod",
"opencli operate eval \"JSON.stringify({name:document.querySelector('h1 span, #top h2')?.textContent?.trim(),description:document.querySelector('[data-testid=package-description], p.package-description-redundant')?.textContent?.trim()})\""
],
"judge": {
"type": "nonEmpty"
},
"set": "test"
},
{
"name": "bench-wiki-search",
"steps": [
"opencli operate open https://en.wikipedia.org/wiki/Machine_learning",
"opencli operate eval \"(() => { const ps = document.querySelectorAll('#mw-content-text .mw-parser-output > p'); for (const p of ps) { const t = p.textContent?.trim(); if (t && t.length > 50) return t.slice(0,300); } return ''; })()\""
],
"judge": {
"type": "contains",
"value": "learning"
},
"set": "test"
},
{
"name": "bench-github-profile",
"steps": [
"opencli operate open https://github.com/torvalds",
"opencli operate eval \"JSON.stringify({name:document.querySelector('[itemprop=name]')?.textContent?.trim(),bio:document.querySelector('[data-bio-text]')?.textContent?.trim()||document.querySelector('.p-note')?.textContent?.trim()})\""
],
"judge": {
"type": "nonEmpty"
},
"set": "test"
},
{
"name": "bench-books-category",
"steps": [
"opencli operate open https://books.toscrape.com",
"opencli operate eval \"document.querySelector('a[href*=science]')?.click();'clicked'\"",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('article.product_pod h3 a')].slice(0,3).map(a=>a.getAttribute('title')))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 3
},
"set": "test"
},
{
"name": "bench-quotes-author",
"steps": [
"opencli operate open https://quotes.toscrape.com",
"opencli operate eval \"document.querySelector('.author + a, a[href*=author]')?.click();'clicked'\"",
"opencli operate eval \"document.querySelector('.author-description, .author-details p')?.textContent?.slice(0,100)\""
],
"judge": {
"type": "nonEmpty"
},
"set": "test"
},
{
"name": "bench-ddg-images",
"steps": [
"opencli operate open https://duckduckgo.com",
"opencli operate eval \"document.querySelector('input[name=q]').value='sunset';document.querySelector('form').submit();'submitted'\"",
"opencli operate wait time 3",
"opencli operate eval \"JSON.stringify([...document.querySelectorAll('[data-testid=result-title-a], .result__a')].slice(0,3).map(a=>a.textContent))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 3
},
"set": "test",
"note": "index may vary"
},
{
"name": "bench-httpbin-headers",
"steps": [
"opencli operate open https://httpbin.org/headers",
"opencli operate eval \"JSON.parse(document.body.innerText).headers['User-Agent']\""
],
"judge": {
"type": "nonEmpty"
},
"set": "test"
},
{
"name": "bench-jsonapi-todo",
"steps": [
"opencli operate open https://jsonplaceholder.typicode.com/todos",
"opencli operate eval \"JSON.stringify(JSON.parse(document.body.innerText).slice(0,5).map(t=>({id:t.id,title:t.title,completed:t.completed})))\""
],
"judge": {
"type": "arrayMinLength",
"minLength": 5
},
"set": "test"
}
]
-163
View File
@@ -1,163 +0,0 @@
#!/usr/bin/env npx tsx
/**
* /autoresearch:debug — Hypothesis-driven debugging for specific failing tasks.
*
* Scientific method: Gather → Hypothesize → Test → Classify → Log → Repeat
*
* Usage:
* npx tsx autoresearch/commands/debug.ts --task extract-npm-description
* npx tsx autoresearch/commands/debug.ts --task bench-imdb-matrix --iterations 5
*/
import { execSync } from 'node:child_process';
import { readFileSync, appendFileSync, writeFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from '../config.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = join(__dirname, '..', '..');
const TASKS_FILE = join(__dirname, '..', 'browse-tasks.json');
const DEBUG_LOG = join(ROOT, 'debug-results.tsv');
interface BrowseTask {
name: string;
steps: string[];
judge: { type: string; value?: string; minLength?: number; pattern?: string };
}
function exec(cmd: string): string {
try {
return execSync(cmd, {
cwd: ROOT, timeout: 30_000, encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
}).trim();
} catch (err: any) {
return err.stdout?.trim() ?? err.message ?? '';
}
}
function initLog(): void {
if (!existsSync(DEBUG_LOG)) {
writeFileSync(DEBUG_LOG, '# AutoResearch Debug Log\niteration\ttask\thypothesis\tresult\tverdict\tdescription\n', 'utf-8');
}
}
function appendLog(iteration: number, task: string, hypothesis: string, result: string, verdict: string, description: string): void {
appendFileSync(DEBUG_LOG, `${iteration}\t${task}\t${hypothesis}\t${result}\t${verdict}\t${description}\n`, 'utf-8');
}
async function main() {
const args = parseArgs(process.argv.slice(2));
const taskName = args.task;
const maxIterations = args.iterations ?? 10;
if (!taskName) {
console.error('Usage: npx tsx autoresearch/commands/debug.ts --task <task-name> [--iterations N]');
console.error('\nAvailable tasks:');
const tasks: BrowseTask[] = JSON.parse(readFileSync(TASKS_FILE, 'utf-8'));
// Show only failing tasks
for (const task of tasks) {
try { exec('opencli operate close'); } catch {}
let lastOutput = '';
for (const step of task.steps) lastOutput = exec(step);
const passed = lastOutput.trim().length > 0; // simplified check
if (!passed) console.error(`${task.name}`);
}
process.exit(1);
}
const tasks: BrowseTask[] = JSON.parse(readFileSync(TASKS_FILE, 'utf-8'));
const task = tasks.find(t => t.name === taskName);
if (!task) {
console.error(`Task not found: ${taskName}`);
process.exit(1);
}
console.log(`\n🔍 AutoResearch Debug: ${taskName}`);
console.log(` Steps: ${task.steps.length}`);
console.log(` Judge: ${task.judge.type}${task.judge.value ? ` "${task.judge.value}"` : ''}`);
console.log(` Max iterations: ${maxIterations}\n`);
initLog();
// Phase 1: Gather — run the task and capture output
console.log('Phase 1: Gathering symptoms...');
try { exec('opencli operate close'); } catch {}
let lastOutput = '';
for (let i = 0; i < task.steps.length; i++) {
const step = task.steps[i];
console.log(` Step ${i + 1}: ${step.slice(0, 80)}`);
lastOutput = exec(step);
if (i < task.steps.length - 1) {
console.log(`${lastOutput.slice(0, 100)}`);
}
}
console.log(`\n Final output: ${lastOutput.slice(0, 200)}`);
console.log(` Judge expects: ${JSON.stringify(task.judge)}`);
// Phase 2: Hypothesize + investigate via Claude Code
for (let iter = 1; iter <= maxIterations; iter++) {
console.log(`\n━━━ Debug Iteration ${iter}/${maxIterations} ━━━`);
const prompt = `You are debugging a failing browser automation task.
## Task: ${taskName}
Steps:
${task.steps.map((s, i) => ` ${i + 1}. ${s}`).join('\n')}
## Judge criteria
${JSON.stringify(task.judge)}
## Last output
${lastOutput.slice(0, 500)}
## Instructions
1. Form a SPECIFIC, FALSIFIABLE hypothesis about why this task fails
2. Run the MINIMUM experiment to test your hypothesis (e.g. run one step, check output)
3. Classify: CONFIRMED (bug found), DISPROVEN (try different hypothesis), INCONCLUSIVE
4. If CONFIRMED: describe the root cause and suggest a fix
5. Output format: one line "HYPOTHESIS: ...", one line "RESULT: CONFIRMED|DISPROVEN|INCONCLUSIVE — ..."
Do NOT fix the code — just diagnose. Use opencli operate commands to investigate.`;
try {
const result = execSync(
`claude -p --dangerously-skip-permissions --allowedTools "Bash(opencli:*),Bash(npm:*),Read,Grep,Glob" --output-format text --no-session-persistence "${prompt.replace(/"/g, '\\"')}"`,
{ cwd: ROOT, timeout: 120_000, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }
).trim();
// Extract hypothesis and result
const hypMatch = result.match(/HYPOTHESIS:\s*(.+)/i);
const resMatch = result.match(/RESULT:\s*(CONFIRMED|DISPROVEN|INCONCLUSIVE)\s*[-—]\s*(.+)/i);
const hypothesis = hypMatch?.[1]?.trim() ?? 'unknown';
const verdict = resMatch?.[1]?.trim() ?? 'INCONCLUSIVE';
const description = resMatch?.[2]?.trim() ?? result.split('\n').pop()?.trim() ?? '';
console.log(` Hypothesis: ${hypothesis.slice(0, 100)}`);
console.log(` Verdict: ${verdict}${description.slice(0, 100)}`);
appendLog(iter, taskName, hypothesis, lastOutput.slice(0, 50), verdict, description);
if (verdict === 'CONFIRMED') {
console.log(`\n✅ Root cause found at iteration ${iter}!`);
console.log(` ${description}`);
break;
}
} catch (err: any) {
console.error(` Error: ${err.message?.slice(0, 100)}`);
appendLog(iter, taskName, 'error', '', 'CRASH', err.message?.slice(0, 80) ?? '');
}
// Re-run task for fresh output
try { exec('opencli operate close'); } catch {}
for (const step of task.steps) lastOutput = exec(step);
}
try { exec('opencli operate close'); } catch {}
console.log(`\nDebug log saved to: ${DEBUG_LOG}\n`);
}
main();
-145
View File
@@ -1,145 +0,0 @@
#!/usr/bin/env npx tsx
/**
* /autoresearch:fix — Iterative error elimination.
*
* Auto-detects broken state (build → test → browse tests) and iteratively
* fixes errors one at a time. Stops when error count reaches 0.
*
* Priority: build errors → test failures → browse task failures
*
* Usage:
* npx tsx autoresearch/commands/fix.ts
* npx tsx autoresearch/commands/fix.ts --iterations 10
*/
import { execSync } from 'node:child_process';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from '../config.js';
import { Engine, type ModifyContext } from '../engine.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = join(__dirname, '..', '..');
function exec(cmd: string): { ok: boolean; output: string } {
try {
const output = execSync(cmd, {
cwd: ROOT, timeout: 120_000, encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
}).trim();
return { ok: true, output };
} catch (err: any) {
return { ok: false, output: (err.stdout ?? '') + '\n' + (err.stderr ?? '') };
}
}
/** Detect current broken state and return verify command + error count */
function detectBrokenState(): { verify: string; errors: number; description: string } | null {
// 1. Build
const build = exec('npm run build 2>&1');
if (!build.ok) {
const errorCount = (build.output.match(/error TS/g) || []).length || 1;
return {
verify: 'npm run build 2>&1 | grep -c "error TS" || echo 0',
errors: errorCount,
description: `${errorCount} TypeScript build error(s)`,
};
}
// 2. Tests
const test = exec('npm test 2>&1');
if (!test.ok) {
const failMatch = test.output.match(/(\d+)\s+fail/i);
const errorCount = failMatch ? parseInt(failMatch[1], 10) : 1;
return {
verify: 'npm test 2>&1 | grep -oP "\\d+(?= fail)" || echo 0',
errors: errorCount,
description: `${errorCount} test failure(s)`,
};
}
// 3. Browse tests
const browse = exec('npx tsx autoresearch/eval-browse.ts 2>&1');
const scoreMatch = browse.output.match(/SCORE=(\d+)\/(\d+)/);
if (scoreMatch) {
const passed = parseInt(scoreMatch[1], 10);
const total = parseInt(scoreMatch[2], 10);
const failures = total - passed;
if (failures > 0) {
return {
verify: 'npx tsx autoresearch/eval-browse.ts 2>&1 | tail -1',
errors: failures,
description: `${failures} browse task failure(s) (${passed}/${total})`,
};
}
}
return null; // all clean
}
async function main() {
const args = parseArgs(process.argv.slice(2));
const maxIterations = args.iterations ?? 20;
console.log('\n🔧 AutoResearch Fix — Detecting broken state...\n');
const broken = detectBrokenState();
if (!broken) {
console.log(' ✓ All clean — nothing to fix!\n');
return;
}
console.log(` Found: ${broken.description}`);
console.log(` Verify: ${broken.verify}\n`);
const config = {
goal: `Fix all errors: ${broken.description}`,
scope: ['src/**/*.ts', 'extension/src/**/*.ts'],
metric: 'error_count',
direction: 'lower' as const,
verify: broken.verify,
guard: 'npm run build',
iterations: maxIterations,
minDelta: 1,
};
const logPath = join(ROOT, 'autoresearch-results.tsv');
const engine = new Engine(config, logPath, {
modify: async (ctx: ModifyContext) => {
const prompt = `Fix ONE error. Current error count: ${ctx.currentMetric}. Goal: 0 errors.
Read the error output, understand the root cause, and make ONE focused fix.
Do NOT fix multiple unrelated errors at once.
Do NOT modify test files.
${ctx.stuckHint ? `STUCK HINT: ${ctx.stuckHint}` : ''}`;
try {
const result = execSync(
`claude -p --dangerously-skip-permissions --allowedTools "Bash(npm:*),Bash(npx:*),Read,Edit,Write,Glob,Grep" --output-format text --no-session-persistence "${prompt.replace(/"/g, '\\"')}"`,
{ cwd: ROOT, timeout: 180_000, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }
).trim();
const lines = result.split('\n').filter(l => l.trim());
return lines[lines.length - 1]?.trim()?.slice(0, 120) || 'fix attempt';
} catch {
return null;
}
},
onStatus: (msg) => console.log(msg),
});
try {
const results = await engine.run();
const finalMetric = results[results.length - 1]?.metric ?? broken.errors;
if (finalMetric === 0) {
console.log('\n✅ All errors fixed!\n');
} else {
console.log(`\n⚠ ${finalMetric} error(s) remaining after ${maxIterations} iterations.\n`);
}
} catch (err: any) {
console.error(`\n❌ ${err.message}`);
process.exit(1);
}
}
main();
-88
View File
@@ -1,88 +0,0 @@
#!/usr/bin/env npx tsx
/**
* /autoresearch:plan — Interactive configuration wizard.
*
* Walks through goal, scope, metric, verify, guard settings
* and outputs a ready-to-paste run command.
*
* Usage:
* npx tsx autoresearch/commands/plan.ts
*/
import { execSync } from 'node:child_process';
import { createInterface } from 'node:readline';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { PRESETS } from '../presets/index.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = join(__dirname, '..', '..');
const rl = createInterface({ input: process.stdin, output: process.stdout });
const ask = (q: string): Promise<string> => new Promise(r => rl.question(q, r));
async function main() {
console.log('\n🔬 AutoResearch — Configuration Wizard\n');
// Offer presets first
const presetNames = Object.keys(PRESETS);
console.log('Available presets:');
presetNames.forEach((name, i) => {
console.log(` [${i + 1}] ${name}${PRESETS[name].goal}`);
});
console.log(` [0] Custom config\n`);
const choice = await ask('Choose preset or 0 for custom: ');
const idx = parseInt(choice, 10);
if (idx > 0 && idx <= presetNames.length) {
const name = presetNames[idx - 1];
const iterations = await ask('Iterations (empty = unbounded): ');
const iterFlag = iterations ? ` --iterations ${iterations}` : '';
console.log(`\n✅ Ready to run:\n`);
console.log(` npx tsx autoresearch/commands/run.ts --preset ${name}${iterFlag}\n`);
rl.close();
return;
}
// Custom config
const goal = await ask('Goal (what to improve): ');
const scope = await ask('Scope (file globs, comma-separated): ');
const metric = await ask('Metric name (e.g. pass_count, coverage): ');
const direction = await ask('Direction (higher/lower): ') as 'higher' | 'lower';
const verify = await ask('Verify command (must output a number): ');
// Dry-run verify
console.log('\n Dry-running verify command...');
try {
const output = execSync(verify, { cwd: ROOT, timeout: 120_000, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
const { extractMetric } = await import('../config.js');
const value = extractMetric(output);
if (value != null) {
console.log(` ✓ Verify works — current ${metric}: ${value}`);
} else {
console.log(` ⚠ Verify ran but no number extracted from output:\n ${output.slice(0, 200)}`);
}
} catch (err: any) {
console.log(` ✗ Verify failed: ${err.message?.slice(0, 100)}`);
}
const guard = await ask('Guard command (optional, press Enter to skip): ');
const iterations = await ask('Iterations (empty = unbounded): ');
const parts = ['npx tsx autoresearch/commands/run.ts'];
parts.push(`--goal "${goal}"`);
parts.push(`--scope "${scope}"`);
parts.push(`--metric "${metric}"`);
parts.push(`--direction ${direction}`);
parts.push(`--verify "${verify}"`);
if (guard) parts.push(`--guard "${guard}"`);
if (iterations) parts.push(`--iterations ${iterations}`);
console.log(`\n✅ Ready to run:\n`);
console.log(` ${parts.join(' \\\n ')}\n`);
rl.close();
}
main();
-138
View File
@@ -1,138 +0,0 @@
#!/usr/bin/env npx tsx
/**
* /autoresearch — Main autonomous iteration loop.
*
* Usage:
* npx tsx autoresearch/commands/run.ts --preset operate-reliability
* npx tsx autoresearch/commands/run.ts --preset operate-reliability --iterations 5
* npx tsx autoresearch/commands/run.ts --goal "..." --scope "src/*.ts" --verify "..." --iterations 10
*
* The modify callback spawns Claude Code to make ONE atomic change per iteration.
* Engine handles commit, verify, guard, keep/discard, and logging.
*/
import { execSync } from 'node:child_process';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs, type AutoResearchConfig } from '../config.js';
import { Engine, type ModifyContext } from '../engine.js';
import { PRESETS } from '../presets/index.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = join(__dirname, '..', '..');
function buildModifyPrompt(ctx: ModifyContext, config: AutoResearchConfig): string {
const recent = ctx.recentLog.slice(-10).map(r =>
` ${r.status.padEnd(12)} ${r.description}`
).join('\n');
return `You are an autonomous improvement agent. Make ONE atomic change to improve this metric.
## Goal
${config.goal}
## Current State
- Metric (${config.metric}): ${ctx.currentMetric} (best: ${ctx.bestMetric})
- Iteration: ${ctx.iteration}
- Consecutive discards: ${ctx.consecutiveDiscards}
${ctx.stuckHint ? `\n## STUCK — Try a Different Approach\n${ctx.stuckHint}` : ''}
## Recent History
${recent || ' (no history yet)'}
## Git Log (recent experiments)
${ctx.gitLog.split('\n').slice(0, 10).join('\n')}
## Scope (files you can modify)
${ctx.scopeFiles.join('\n')}
## Rules
1. Make ONE atomic change (one logical intent, even if multiple files)
2. Read the failing test output or code BEFORE modifying
3. DO NOT modify test files or the verify command
4. Describe what you changed in one sentence (no "and" linking unrelated actions)
5. If previous approach was discarded, try something DIFFERENT
6. Focus on the specific failures — read error messages carefully`;
}
async function modify(ctx: ModifyContext, config: AutoResearchConfig): Promise<string | null> {
const prompt = buildModifyPrompt(ctx, config);
console.log(' Claude Code making a change...');
try {
const result = execSync(
`claude -p --dangerously-skip-permissions --allowedTools "Bash(npm:*),Bash(npx:*),Bash(git:*),Read,Edit,Write,Glob,Grep" --output-format text --no-session-persistence "${prompt.replace(/"/g, '\\"')}"`,
{
cwd: ROOT,
timeout: 180_000,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
env: process.env,
}
).trim();
// Extract description from Claude's response (last non-empty line or summary)
const lines = result.split('\n').filter(l => l.trim());
const desc = lines[lines.length - 1]?.trim() || 'change made by Claude Code';
return desc.slice(0, 120);
} catch (err: any) {
console.error(' Claude Code failed:', err.message?.slice(0, 100));
return null;
}
}
async function main() {
const args = parseArgs(process.argv.slice(2));
// Resolve config from preset or CLI args
let config: AutoResearchConfig;
if (args.preset) {
config = PRESETS[args.preset];
if (!config) {
console.error(`Unknown preset: ${args.preset}`);
console.error(`Available: ${Object.keys(PRESETS).join(', ')}`);
process.exit(1);
}
// Allow CLI overrides
if (args.iterations != null) config = { ...config, iterations: args.iterations };
if (args.guard != null) config = { ...config, guard: args.guard };
} else if (args.goal && args.verify) {
config = {
goal: args.goal,
scope: args.scope ?? ['src/**/*.ts'],
metric: args.metric ?? 'score',
direction: args.direction ?? 'higher',
verify: args.verify,
guard: args.guard,
iterations: args.iterations,
minDelta: args.minDelta,
};
} else {
console.error('Usage: npx tsx autoresearch/commands/run.ts --preset <name> [--iterations N]');
console.error(' or: npx tsx autoresearch/commands/run.ts --goal "..." --verify "..." --scope "..."');
console.error(`\nAvailable presets: ${Object.keys(PRESETS).join(', ')}`);
process.exit(1);
}
console.log(`\n🔬 AutoResearch: ${config.goal}`);
console.log(` Metric: ${config.metric} (${config.direction})`);
console.log(` Verify: ${config.verify}`);
console.log(` Guard: ${config.guard ?? '(none)'}`);
console.log(` Iterations: ${config.iterations ?? '∞'}`);
console.log('');
const logPath = join(ROOT, 'autoresearch-results.tsv');
const engine = new Engine(config, logPath, {
modify: (ctx) => modify(ctx, config),
onStatus: (msg) => console.log(msg),
});
try {
await engine.run();
} catch (err: any) {
console.error(`\n❌ ${err.message}`);
process.exit(1);
}
}
main();
-82
View File
@@ -1,82 +0,0 @@
/**
* AutoResearch Configuration — type definitions and CLI parsing.
*
* Based on Karpathy's autoresearch: constraint + mechanical metric + unbounded loop.
*/
export interface AutoResearchConfig {
/** Plain-language goal, e.g. "Increase operate pass rate to 59/59" */
goal: string;
/** Glob patterns for files the agent can modify */
scope: string[];
/** What the metric measures, e.g. "pass_count" */
metric: string;
/** Whether improvement means the number goes up or down */
direction: 'higher' | 'lower';
/** Shell command that outputs a number (the metric value) */
verify: string;
/** Optional guard command — must pass for a keep decision */
guard?: string;
/** Max iterations (undefined = unbounded) */
iterations?: number;
/** Minimum delta to count as real improvement (noise filter) */
minDelta?: number;
}
export type IterationStatus =
| 'baseline'
| 'keep'
| 'keep (reworked)'
| 'discard'
| 'crash'
| 'no-op'
| 'hook-blocked';
export interface IterationResult {
iteration: number;
commit: string;
metric: number;
delta: number;
guard: 'pass' | 'fail' | '-';
status: IterationStatus;
description: string;
}
/** Parse CLI args into a partial config (missing fields filled by preset or prompts) */
export function parseArgs(argv: string[]): Partial<AutoResearchConfig> & { preset?: string; task?: string } {
const config: Partial<AutoResearchConfig> & { preset?: string; task?: string } = {};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
const next = argv[i + 1];
switch (arg) {
case '--preset': config.preset = next; i++; break;
case '--goal': config.goal = next; i++; break;
case '--scope': config.scope = next?.split(','); i++; break;
case '--metric': config.metric = next; i++; break;
case '--direction': config.direction = next as 'higher' | 'lower'; i++; break;
case '--verify': config.verify = next; i++; break;
case '--guard': config.guard = next; i++; break;
case '--iterations': config.iterations = parseInt(next, 10); i++; break;
case '--min-delta': config.minDelta = parseFloat(next); i++; break;
case '--task': config.task = next; i++; break;
}
}
return config;
}
/** Extract a number from command output using common patterns */
export function extractMetric(output: string): number | null {
// Try: last line that looks like a number
const lines = output.trim().split('\n');
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i].trim();
// Match standalone numbers: "56", "95.2", "SCORE=56/59" → 56
const scoreMatch = line.match(/SCORE[=:]\s*(\d+)/i);
if (scoreMatch) return parseFloat(scoreMatch[1]);
const numMatch = line.match(/^[\d.]+$/);
if (numMatch) return parseFloat(numMatch[0]);
}
// Fallback: first number in output
const fallback = output.match(/(\d+(?:\.\d+)?)/);
return fallback ? parseFloat(fallback[1]) : null;
}
-359
View File
@@ -1,359 +0,0 @@
/**
* AutoResearch Engine — Karpathy's 8-phase autonomous iteration loop.
*
* Phase 0: Precondition checks (git clean, no locks)
* Phase 1: Review (read scope files + log + git history)
* Phase 2: Ideate (select next change based on history)
* Phase 3: Modify (one atomic change — delegated to caller)
* Phase 4: Commit (git add + commit with experiment prefix)
* Phase 5: Verify (run verify command, extract metric)
* Phase 5.5: Guard (optional regression check)
* Phase 6: Decide (keep/discard/crash + rollback)
* Phase 7: Log (append TSV)
* Phase 8: Repeat
*/
import { execSync } from 'node:child_process';
import { readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { type AutoResearchConfig, type IterationResult, type IterationStatus, extractMetric } from './config.js';
import { Logger } from './logger.js';
export interface EngineCallbacks {
/** Called at Phase 2-3: review context, ideate, and make ONE change.
* Return a one-sentence description of what was changed, or null to skip. */
modify(context: ModifyContext): Promise<string | null>;
/** Called when engine needs to report status */
onStatus?(msg: string): void;
}
export interface ModifyContext {
iteration: number;
bestMetric: number;
currentMetric: number;
recentLog: IterationResult[];
gitLog: string;
scopeFiles: string[];
consecutiveDiscards: number;
stuckHint: string | null;
}
const ROOT = join(import.meta.dirname ?? process.cwd(), '..');
function exec(cmd: string, opts?: { timeout?: number; cwd?: string }): string {
try {
return execSync(cmd, {
cwd: opts?.cwd ?? ROOT,
timeout: opts?.timeout ?? 120_000,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
env: process.env,
}).trim();
} catch (err: any) {
return err.stdout?.trim() ?? err.message ?? '';
}
}
function execStrict(cmd: string, opts?: { timeout?: number }): string {
return execSync(cmd, {
cwd: ROOT,
timeout: opts?.timeout ?? 120_000,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
env: process.env,
}).trim();
}
export class Engine {
private config: AutoResearchConfig;
private logger: Logger;
private callbacks: EngineCallbacks;
private bestMetric: number = 0;
private currentMetric: number = 0;
private iteration: number = 0;
constructor(config: AutoResearchConfig, logPath: string, callbacks: EngineCallbacks) {
this.config = config;
this.logger = new Logger(logPath);
this.callbacks = callbacks;
}
private log(msg: string): void {
this.callbacks.onStatus?.(msg);
}
/** Phase 0: Precondition checks */
private checkPreconditions(): void {
// Git repo exists
try { execStrict('git rev-parse --git-dir'); }
catch { throw new Error('Not a git repository'); }
// Clean working tree
const status = exec('git status --porcelain');
if (status) throw new Error(`Working tree not clean:\n${status}`);
// No stale locks
if (existsSync(join(ROOT, '.git', 'index.lock'))) {
throw new Error('Stale .git/index.lock found — remove it first');
}
// Not detached HEAD
try { execStrict('git symbolic-ref HEAD'); }
catch { throw new Error('Detached HEAD — checkout a branch first'); }
}
/** Phase 5: Run verify command and extract metric */
private runVerify(): number | null {
this.log(' verify...');
const output = exec(this.config.verify, { timeout: 300_000 });
return extractMetric(output);
}
/** Phase 5.5: Run guard command */
private runGuard(): boolean {
if (!this.config.guard) return true;
this.log(' guard...');
try {
execStrict(this.config.guard, { timeout: 300_000 });
return true;
} catch {
return false;
}
}
/** Phase 4: Commit changes */
private commit(description: string): string | null {
// Stage all changes in scope (but not untracked outside scope)
exec('git add -A');
const diff = exec('git diff --cached --quiet; echo $?');
if (diff === '0') return null; // no changes
try {
execStrict(`git commit -m "experiment(operate): ${description.replace(/"/g, '\\"')}"`);
return exec('git rev-parse --short HEAD');
} catch {
// Hook failure
exec('git reset HEAD');
return 'hook-blocked';
}
}
/** Phase 6: Rollback */
private safeRevert(): void {
try {
execStrict('git revert HEAD --no-edit');
} catch {
exec('git revert --abort');
exec('git reset --hard HEAD~1');
}
}
/** Get stuck hint when >5 consecutive discards */
private getStuckHint(discards: number): string | null {
if (discards < 5) return null;
const hints = [
'Re-read ALL scope files from scratch. Try a completely different approach.',
'Review entire results log — what worked before? Try combining successful changes.',
'Try the OPPOSITE of what has been failing.',
'Try a radical architectural change instead of incremental tweaks.',
'Simplify — remove complexity rather than adding it.',
];
return hints[Math.min(discards - 5, hints.length - 1)];
}
/** Run the main loop */
async run(): Promise<IterationResult[]> {
const results: IterationResult[] = [];
// Phase 0: Preconditions
this.log('Phase 0: Precondition checks...');
this.checkPreconditions();
// Initialize logger
this.logger.init(this.config);
// Baseline measurement
this.log('Measuring baseline...');
const baseline = this.runVerify();
if (baseline == null) throw new Error('Verify command returned no metric for baseline');
this.bestMetric = baseline;
this.currentMetric = baseline;
const baselineCommit = exec('git rev-parse --short HEAD');
const baselineResult: IterationResult = {
iteration: 0,
commit: baselineCommit,
metric: baseline,
delta: 0,
guard: this.config.guard ? (this.runGuard() ? 'pass' : 'fail') : '-',
status: 'baseline',
description: `initial state — ${this.config.metric} ${baseline}`,
};
this.logger.append(baselineResult);
results.push(baselineResult);
this.log(`Baseline: ${this.config.metric} = ${baseline}`);
// Main loop
const maxIter = this.config.iterations ?? Infinity;
for (this.iteration = 1; this.iteration <= maxIter; this.iteration++) {
this.log(`\n━━━ Iteration ${this.iteration}${maxIter < Infinity ? `/${maxIter}` : ''} ━━━`);
// Phase 1: Review
const gitLog = exec('git log --oneline -20');
const recentLog = this.logger.readLast(20);
const scopeFiles = this.config.scope;
const consecutiveDiscards = this.logger.consecutiveDiscards();
// Phase 2-3: Ideate + Modify (delegated to callback)
const context: ModifyContext = {
iteration: this.iteration,
bestMetric: this.bestMetric,
currentMetric: this.currentMetric,
recentLog,
gitLog,
scopeFiles,
consecutiveDiscards,
stuckHint: this.getStuckHint(consecutiveDiscards),
};
let description: string | null;
try {
description = await this.callbacks.modify(context);
} catch (err: any) {
this.log(` modify error: ${err.message}`);
const result: IterationResult = {
iteration: this.iteration,
commit: '-',
metric: this.currentMetric,
delta: 0,
guard: '-',
status: 'crash',
description: `modify crashed: ${err.message?.slice(0, 80)}`,
};
this.logger.append(result);
results.push(result);
continue;
}
if (!description) {
const result: IterationResult = {
iteration: this.iteration,
commit: '-',
metric: this.currentMetric,
delta: 0,
guard: '-',
status: 'no-op',
description: 'no changes made',
};
this.logger.append(result);
results.push(result);
continue;
}
// Phase 4: Commit
this.log(` commit: ${description}`);
const commitHash = this.commit(description);
if (!commitHash) {
const result: IterationResult = {
iteration: this.iteration,
commit: '-',
metric: this.currentMetric,
delta: 0,
guard: '-',
status: 'no-op',
description: `no diff after: ${description}`,
};
this.logger.append(result);
results.push(result);
continue;
}
if (commitHash === 'hook-blocked') {
const result: IterationResult = {
iteration: this.iteration,
commit: '-',
metric: this.currentMetric,
delta: 0,
guard: '-',
status: 'hook-blocked',
description: `hook rejected: ${description}`,
};
this.logger.append(result);
results.push(result);
continue;
}
// Phase 5: Verify
const metric = this.runVerify();
if (metric == null) {
this.log(' verify crashed — reverting');
this.safeRevert();
const result: IterationResult = {
iteration: this.iteration,
commit: '-',
metric: this.currentMetric,
delta: 0,
guard: '-',
status: 'crash',
description: `verify crashed: ${description}`,
};
this.logger.append(result);
results.push(result);
continue;
}
const improved = this.config.direction === 'higher'
? metric > this.bestMetric
: metric < this.bestMetric;
const delta = +(metric - this.bestMetric).toFixed(4);
const absDelta = Math.abs(delta);
const minDelta = this.config.minDelta ?? 0;
// Phase 5.5: Guard
let guardResult: 'pass' | 'fail' | '-' = '-';
if (this.config.guard && improved && absDelta >= minDelta) {
guardResult = this.runGuard() ? 'pass' : 'fail';
}
// Phase 6: Decide
let status: IterationStatus;
if (improved && absDelta >= minDelta && (guardResult !== 'fail')) {
status = 'keep';
this.bestMetric = metric;
this.currentMetric = metric;
this.log(` ✓ KEEP — ${this.config.metric}: ${metric} (${delta >= 0 ? '+' : ''}${delta})`);
} else if (improved && guardResult === 'fail') {
this.log(' guard failed — reverting');
this.safeRevert();
status = 'discard';
this.log(` ✗ DISCARD (guard) — ${description}`);
} else {
this.safeRevert();
status = 'discard';
const reason = absDelta < minDelta ? 'below min delta' : 'no improvement';
this.log(` ✗ DISCARD (${reason}) — ${this.config.metric}: ${metric} (${delta >= 0 ? '+' : ''}${delta})`);
}
const result: IterationResult = {
iteration: this.iteration,
commit: status === 'keep' ? commitHash : '-',
metric,
delta,
guard: guardResult,
status,
description,
};
this.logger.append(result);
results.push(result);
}
// Summary
const keeps = results.filter(r => r.status === 'keep' || r.status === 'keep (reworked)');
const discards = results.filter(r => r.status === 'discard');
this.log(`\n${'━'.repeat(50)}`);
this.log(`Done: ${this.iteration - 1} iterations, ${keeps.length} kept, ${discards.length} discarded`);
this.log(`Final ${this.config.metric}: ${this.bestMetric} (started at ${results[0]?.metric})`);
return results;
}
}
-185
View File
@@ -1,185 +0,0 @@
#!/usr/bin/env npx tsx
/**
* Layer 1: Deterministic Browse Command Testing
*
* Runs predefined opencli operate command sequences against real websites.
* No LLM involved — tests command reliability only.
*
* Usage:
* npx tsx autoresearch/eval-browse.ts # Run all tasks
* npx tsx autoresearch/eval-browse.ts --task hn-top5 # Run single task
*/
import { execSync } from 'node:child_process';
import { readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const TASKS_FILE = join(__dirname, 'browse-tasks.json');
const RESULTS_DIR = join(__dirname, 'results');
const BASELINE_FILE = join(__dirname, 'baseline-browse.txt');
interface BrowseTask {
name: string;
steps: string[];
judge: JudgeCriteria;
set?: 'test';
note?: string;
}
type JudgeCriteria =
| { type: 'contains'; value: string }
| { type: 'arrayMinLength'; minLength: number }
| { type: 'nonEmpty' }
| { type: 'matchesPattern'; pattern: string };
interface TaskResult {
name: string;
passed: boolean;
duration: number;
error?: string;
set: 'train' | 'test';
}
function judge(criteria: JudgeCriteria, output: string): boolean {
try {
switch (criteria.type) {
case 'contains':
return output.toLowerCase().includes(criteria.value.toLowerCase());
case 'arrayMinLength': {
try {
const arr = JSON.parse(output);
if (Array.isArray(arr)) return arr.length >= criteria.minLength;
} catch { /* not JSON array */ }
return false;
}
case 'nonEmpty':
return output.trim().length > 0 && output.trim() !== 'null' && output.trim() !== 'undefined';
case 'matchesPattern':
return new RegExp(criteria.pattern).test(output);
default:
return false;
}
} catch {
return false;
}
}
function runCommand(cmd: string): string {
try {
return execSync(cmd, {
cwd: join(__dirname, '..'),
timeout: 30000,
encoding: 'utf-8',
env: process.env,
stdio: ['pipe', 'pipe', 'pipe'],
}).trim();
} catch (err: any) {
return err.stdout?.trim() ?? '';
}
}
function runTask(task: BrowseTask): TaskResult {
const start = Date.now();
let lastOutput = '';
try {
for (const step of task.steps) {
lastOutput = runCommand(step);
}
const passed = judge(task.judge, lastOutput);
return {
name: task.name,
passed,
duration: Date.now() - start,
error: passed ? undefined : `Output: ${lastOutput.slice(0, 100)}`,
set: task.set === 'test' ? 'test' : 'train',
};
} catch (err: any) {
return {
name: task.name,
passed: false,
duration: Date.now() - start,
error: err.message?.slice(0, 100),
set: task.set === 'test' ? 'test' : 'train',
};
}
}
function main() {
const args = process.argv.slice(2);
const singleTask = args.includes('--task') ? args[args.indexOf('--task') + 1] : null;
const allTasks: BrowseTask[] = JSON.parse(readFileSync(TASKS_FILE, 'utf-8'));
const tasks = singleTask ? allTasks.filter(t => t.name === singleTask) : allTasks;
if (tasks.length === 0) {
console.error(`Task "${singleTask}" not found.`);
process.exit(1);
}
console.log(`\n🔬 Layer 1: Browse Commands — ${tasks.length} tasks\n`);
const results: TaskResult[] = [];
for (let i = 0; i < tasks.length; i++) {
const task = tasks[i];
process.stdout.write(` [${i + 1}/${tasks.length}] ${task.name}...`);
const result = runTask(task);
results.push(result);
const icon = result.passed ? '✓' : '✗';
console.log(` ${icon} (${(result.duration / 1000).toFixed(1)}s)`);
// Close browser between tasks for clean state
if (i < tasks.length - 1) {
try { runCommand('opencli operate close'); } catch { /* ignore */ }
}
}
// Final close
try { runCommand('opencli operate close'); } catch { /* ignore */ }
// Summary
const trainResults = results.filter(r => r.set === 'train');
const testResults = results.filter(r => r.set === 'test');
const totalPassed = results.filter(r => r.passed).length;
const trainPassed = trainResults.filter(r => r.passed).length;
const testPassed = testResults.filter(r => r.passed).length;
const totalDuration = results.reduce((s, r) => s + r.duration, 0);
console.log(`\n${'─'.repeat(50)}`);
console.log(` Score: ${totalPassed}/${results.length} (train: ${trainPassed}/${trainResults.length}, test: ${testPassed}/${testResults.length})`);
console.log(` Time: ${Math.round(totalDuration / 60000)}min`);
const failures = results.filter(r => !r.passed);
if (failures.length > 0) {
console.log(`\n Failures:`);
for (const f of failures) {
console.log(`${f.name}: ${f.error ?? 'unknown'}`);
}
}
console.log('');
// Save result
mkdirSync(RESULTS_DIR, { recursive: true });
const existing = readdirSync(RESULTS_DIR).filter(f => f.startsWith('browse-')).length;
const roundNum = String(existing + 1).padStart(3, '0');
const resultPath = join(RESULTS_DIR, `browse-${roundNum}.json`);
writeFileSync(resultPath, JSON.stringify({
timestamp: new Date().toISOString(),
score: `${totalPassed}/${results.length}`,
trainScore: `${trainPassed}/${trainResults.length}`,
testScore: `${testPassed}/${testResults.length}`,
duration: `${Math.round(totalDuration / 60000)}min`,
tasks: results,
}, null, 2), 'utf-8');
console.log(` Results saved to: ${resultPath}`);
console.log(`\nSCORE=${totalPassed}/${results.length}`);
}
main();
-248
View File
@@ -1,248 +0,0 @@
#!/usr/bin/env npx tsx
/**
* Layer 2: Claude Code Skill E2E Testing (LLM Judge)
*
* Spawns Claude Code with the opencli-operate skill. Claude Code
* completes the task using browse commands AND judges its own result.
*
* Task format: YAML with judge_context (multi-criteria, like Browser Use)
*
* Usage:
* npx tsx autoresearch/eval-skill.ts # Run all
* npx tsx autoresearch/eval-skill.ts --task hn-top5 # Run single
*/
import { execSync } from 'node:child_process';
import { readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const TASKS_FILE = join(__dirname, 'skill-tasks.yaml');
const RESULTS_DIR = join(__dirname, 'results');
const SKILL_PATH = join(__dirname, '..', 'skills', 'opencli-operate', 'SKILL.md');
// ── Types ──────────────────────────────────────────────────────────
interface SkillTask {
name: string;
task: string;
url?: string;
judge_context: string[];
max_steps?: number;
}
interface TaskResult {
name: string;
passed: boolean;
duration: number;
cost: number;
explanation: string;
}
// ── Task Definitions (inline, to avoid YAML dependency) ────────────
const TASKS: SkillTask[] = [
// Extract
{ name: "extract-title-example", task: "Extract the main heading text from this page", url: "https://example.com", judge_context: ["Output must contain 'Example Domain'"] },
{ name: "extract-paragraph-wiki", task: "Extract the first paragraph of the JavaScript article", url: "https://en.wikipedia.org/wiki/JavaScript", judge_context: ["Output must mention 'programming language'", "Output must contain actual paragraph text, not just the title"] },
{ name: "extract-github-stars", task: "Find the number of stars on this repository", url: "https://github.com/browser-use/browser-use", judge_context: ["Output must contain a number (the star count)"] },
{ name: "extract-npm-downloads", task: "Find the weekly download count for this package", url: "https://www.npmjs.com/package/zod", judge_context: ["Output must contain a number (weekly downloads)"] },
// List extraction
{ name: "list-hn-top5", task: "Extract the top 5 stories with their titles", url: "https://news.ycombinator.com", judge_context: ["Output must contain 5 story titles", "Each title must be an actual HN story, not made up"] },
{ name: "list-books-5", task: "Extract the first 5 books with their title and price", url: "https://books.toscrape.com", judge_context: ["Output must contain 5 books", "Each book must have a title and a price"] },
{ name: "list-quotes-3", task: "Extract the first 3 quotes with their text and author", url: "https://quotes.toscrape.com", judge_context: ["Output must contain 3 quotes", "Each quote must have text and an author name"] },
{ name: "list-github-trending", task: "Extract the top 3 trending repositories with name and description", url: "https://github.com/trending", judge_context: ["Output must contain 3 repositories", "Each must have a repo name"] },
{ name: "list-jsonplaceholder", task: "Extract the first 5 posts with their title", url: "https://jsonplaceholder.typicode.com/posts", judge_context: ["Output must contain 5 posts", "Each post must have a title"] },
// Search
{ name: "search-ddg", task: "Search for 'TypeScript tutorial' and extract the first 3 result titles", url: "https://duckduckgo.com", judge_context: ["The agent must type a search query", "Output must contain at least 3 search result titles"] },
{ name: "search-npm", task: "Search for 'react' and extract the top 3 package names", url: "https://www.npmjs.com", judge_context: ["The agent must search for 'react'", "Output must contain at least 3 package names"] },
{ name: "search-wiki", task: "Search for 'Rust programming language' and extract the first sentence of the article", url: "https://en.wikipedia.org", judge_context: ["The agent must search and navigate to the article", "Output must mention 'programming language'"] },
// Navigation
{ name: "nav-click-link", task: "Click the 'More information...' link and extract the heading of the new page", url: "https://example.com", judge_context: ["The agent must click a link", "Output must contain 'IANA' or reference the new page"] },
{ name: "nav-click-hn", task: "Click on the first story link and tell me the title of the page you land on", url: "https://news.ycombinator.com", judge_context: ["The agent must click a story link", "Output must contain the title of the destination page"] },
{ name: "nav-go-back", task: "Click the 'More information...' link, then go back, and tell me the heading of the original page", url: "https://example.com", judge_context: ["The agent must click a link then go back", "Output must contain 'Example Domain'"] },
{ name: "nav-multi-step", task: "Click the Next page link at the bottom, then extract the first quote from page 2", url: "https://quotes.toscrape.com", judge_context: ["The agent must navigate to page 2", "Output must contain a quote from page 2"] },
// Scroll
{ name: "scroll-footer", task: "Scroll to the bottom and extract the footer text", url: "https://quotes.toscrape.com", judge_context: ["The agent must scroll down", "Output must contain footer or bottom-of-page content"] },
{ name: "scroll-pagination", task: "Find the pagination info at the bottom of the page", url: "https://books.toscrape.com", judge_context: ["Output must contain page number or pagination info"] },
// Form
{ name: "form-fill-basic", task: "Fill the Customer Name with 'OpenCLI' and Telephone with '555-0100'. Do not submit.", url: "https://httpbin.org/forms/post", judge_context: ["The agent must type 'OpenCLI' into a name field", "The agent must type '555-0100' into a phone field", "The form must NOT be submitted"] },
{ name: "form-radio", task: "Select the 'Medium' pizza size option. Do not submit.", url: "https://httpbin.org/forms/post", judge_context: ["The agent must select a radio button for Medium size"] },
{ name: "form-login", task: "Fill the username with 'testuser' and password with 'testpass'. Do not submit.", url: "https://the-internet.herokuapp.com/login", judge_context: ["The agent must fill the username field", "The agent must fill the password field", "The form must NOT be submitted"] },
// Complex
{ name: "complex-wiki-toc", task: "Extract the table of contents headings", url: "https://en.wikipedia.org/wiki/JavaScript", judge_context: ["Output must contain at least 5 section headings from the table of contents"] },
{ name: "complex-books-detail", task: "Click on the first book and extract its title and price from the detail page", url: "https://books.toscrape.com", judge_context: ["The agent must click on a book", "Output must contain the book title", "Output must contain a price"] },
{ name: "complex-quotes-page2", task: "Navigate to page 2 and extract the first 3 quotes with their authors", url: "https://quotes.toscrape.com", judge_context: ["The agent must navigate to page 2", "Output must contain 3 quotes with authors"] },
{ name: "complex-multi-extract", task: "Extract both the page title and the first paragraph text", url: "https://en.wikipedia.org/wiki/TypeScript", judge_context: ["Output must contain 'TypeScript'", "Output must contain actual paragraph text"] },
// Bench (harder, real-world)
{ name: "bench-reddit", task: "Extract the titles of the top 5 posts", url: "https://old.reddit.com", judge_context: ["Output must contain 5 post titles", "Titles must be actual Reddit posts"] },
{ name: "bench-imdb", task: "Find the year and rating of The Matrix", url: "https://www.imdb.com/title/tt0133093/", judge_context: ["Output must contain '1999'", "Output must contain a rating number"] },
{ name: "bench-github-profile", task: "Extract the bio and number of public repositories", url: "https://github.com/torvalds", judge_context: ["Output must contain bio text or 'Linux'", "Output must contain a number for repos"] },
{ name: "bench-httpbin", task: "Extract the User-Agent header shown on this page", url: "https://httpbin.org/headers", judge_context: ["Output must contain a User-Agent string"] },
{ name: "bench-jsonapi-todo", task: "Extract the first 5 todo items with their title and completion status", url: "https://jsonplaceholder.typicode.com/todos", judge_context: ["Output must contain 5 todo items", "Each must have a title and completed status"] },
// Codex form (the real test)
{ name: "codex-form-fill", task: "Fill the basic information using 'opencli' as the identity (first name=open, last name=cli, email=opencli@example.com, GitHub username=opencli). Do NOT submit the form.", url: "https://openai.com/form/codex-for-oss/", judge_context: ["The agent must fill the first name field", "The agent must fill the last name field", "The agent must fill the email field", "The form must NOT be submitted"], max_steps: 15 },
];
// ── Run Task ───────────────────────────────────────────────────────
function runSkillTask(task: SkillTask): TaskResult {
const start = Date.now();
const skillContent = readFileSync(SKILL_PATH, 'utf-8');
const urlPart = task.url ? ` Start URL: ${task.url}` : '';
const criteria = task.judge_context.map((c, i) => `${i + 1}. ${c}`).join('\n');
const prompt = `Complete this browser task using opencli operate commands:
TASK: ${task.task}${urlPart}
After completing the task, evaluate your own result against these criteria:
${criteria}
At the very end of your response, output a JSON verdict on its own line:
{"success": true/false, "explanation": "brief explanation"}
Always close the browser with 'opencli operate close' when done.`;
try {
const output = execSync(
`claude -p --dangerously-skip-permissions --allowedTools "Bash(opencli:*)" --system-prompt ${JSON.stringify(skillContent)} --output-format json --no-session-persistence ${JSON.stringify(prompt)}`,
{
cwd: join(__dirname, '..'),
timeout: (task.max_steps ?? 10) * 15_000,
encoding: 'utf-8',
env: process.env,
stdio: ['pipe', 'pipe', 'pipe'],
}
);
const duration = Date.now() - start;
// Parse Claude Code output
let resultText = '';
let cost = 0;
try {
const parsed = JSON.parse(output);
resultText = parsed.result ?? output;
cost = parsed.total_cost_usd ?? 0;
} catch {
resultText = output;
}
// Extract verdict JSON from the result
const verdict = extractVerdict(resultText);
return {
name: task.name,
passed: verdict.success,
duration,
cost,
explanation: verdict.explanation,
};
} catch (err: any) {
return {
name: task.name,
passed: false,
duration: Date.now() - start,
cost: 0,
explanation: (err.stdout ?? err.message ?? 'timeout or crash').slice(0, 200),
};
}
}
function extractVerdict(text: string): { success: boolean; explanation: string } {
// Try to find {"success": ...} JSON in the text
const jsonMatches = text.match(/\{"success"\s*:\s*(true|false)\s*,\s*"explanation"\s*:\s*"([^"]*)"\s*\}/g);
if (jsonMatches) {
const last = jsonMatches[jsonMatches.length - 1];
try {
return JSON.parse(last);
} catch { /* fall through */ }
}
// Fallback: check for success indicators in text
const lower = text.toLowerCase();
if (lower.includes('"success": true') || lower.includes('"success":true')) {
return { success: true, explanation: 'Parsed success from output' };
}
if (lower.includes('"success": false') || lower.includes('"success":false')) {
return { success: false, explanation: 'Parsed failure from output' };
}
// Final fallback: assume failure if we can't parse
return { success: false, explanation: 'Could not parse verdict from output' };
}
// ── Main ───────────────────────────────────────────────────────────
function main() {
const args = process.argv.slice(2);
const singleTask = args.includes('--task') ? args[args.indexOf('--task') + 1] : null;
const tasks = singleTask ? TASKS.filter(t => t.name === singleTask) : TASKS;
if (tasks.length === 0) {
console.error(`Task "${singleTask}" not found. Available: ${TASKS.map(t => t.name).join(', ')}`);
process.exit(1);
}
console.log(`\n🔬 Layer 2: Skill E2E (LLM Judge) — ${tasks.length} tasks\n`);
const results: TaskResult[] = [];
for (let i = 0; i < tasks.length; i++) {
const task = tasks[i];
process.stdout.write(` [${i + 1}/${tasks.length}] ${task.name}...`);
const result = runSkillTask(task);
results.push(result);
const icon = result.passed ? '✓' : '✗';
const costStr = result.cost > 0 ? `, $${result.cost.toFixed(2)}` : '';
console.log(` ${icon} (${Math.round(result.duration / 1000)}s${costStr})`);
}
// Summary
const totalPassed = results.filter(r => r.passed).length;
const totalCost = results.reduce((s, r) => s + r.cost, 0);
const totalDuration = results.reduce((s, r) => s + r.duration, 0);
console.log(`\n${'─'.repeat(50)}`);
console.log(` Score: ${totalPassed}/${results.length} (${Math.round(totalPassed / results.length * 100)}%)`);
console.log(` Cost: $${totalCost.toFixed(2)}`);
console.log(` Time: ${Math.round(totalDuration / 60000)}min`);
const failures = results.filter(r => !r.passed);
if (failures.length > 0) {
console.log(`\n Failures:`);
for (const f of failures) {
console.log(`${f.name}: ${f.explanation}`);
}
}
console.log('');
// Save
mkdirSync(RESULTS_DIR, { recursive: true });
const existing = readdirSync(RESULTS_DIR).filter(f => f.startsWith('skill-')).length;
const roundNum = String(existing + 1).padStart(3, '0');
const resultPath = join(RESULTS_DIR, `skill-${roundNum}.json`);
writeFileSync(resultPath, JSON.stringify({
timestamp: new Date().toISOString(),
score: `${totalPassed}/${results.length}`,
totalCost,
duration: `${Math.round(totalDuration / 60000)}min`,
tasks: results,
}, null, 2), 'utf-8');
console.log(` Results saved to: ${resultPath}`);
console.log(`\nSCORE=${totalPassed}/${results.length}`);
}
main();
-69
View File
@@ -1,69 +0,0 @@
/**
* AutoResearch TSV Logger — append-only results log with metadata header.
*/
import { writeFileSync, readFileSync, existsSync, appendFileSync } from 'node:fs';
import type { AutoResearchConfig, IterationResult } from './config.js';
const COLUMNS = ['iteration', 'commit', 'metric', 'delta', 'guard', 'status', 'description'];
export class Logger {
constructor(private path: string) {}
/** Create the TSV file with metadata header */
init(config: AutoResearchConfig): void {
const header = [
`# metric_direction: ${config.direction === 'higher' ? 'higher_is_better' : 'lower_is_better'}`,
`# goal: ${config.goal}`,
`# scope: ${config.scope.join(', ')}`,
`# verify: ${config.verify}`,
config.guard ? `# guard: ${config.guard}` : null,
COLUMNS.join('\t'),
].filter(Boolean).join('\n');
writeFileSync(this.path, header + '\n', 'utf-8');
}
/** Append one iteration result */
append(result: IterationResult): void {
const row = [
result.iteration,
result.commit,
result.metric,
result.delta >= 0 ? `+${result.delta}` : result.delta,
result.guard,
result.status,
result.description,
].join('\t');
appendFileSync(this.path, row + '\n', 'utf-8');
}
/** Read last N entries for pattern recognition */
readLast(n: number): IterationResult[] {
if (!existsSync(this.path)) return [];
const lines = readFileSync(this.path, 'utf-8').split('\n')
.filter(l => l && !l.startsWith('#') && !l.startsWith('iteration'));
return lines.slice(-n).map(line => {
const [iteration, commit, metric, delta, guard, status, ...desc] = line.split('\t');
return {
iteration: parseInt(iteration, 10),
commit,
metric: parseFloat(metric),
delta: parseFloat(delta),
guard: guard as 'pass' | 'fail' | '-',
status: status as IterationResult['status'],
description: desc.join('\t'),
};
});
}
/** Count consecutive discards from the end */
consecutiveDiscards(): number {
const entries = this.readLast(20);
let count = 0;
for (let i = entries.length - 1; i >= 0; i--) {
if (entries[i].status === 'discard') count++;
else break;
}
return count;
}
}
-11
View File
@@ -1,11 +0,0 @@
export { operateReliability } from './operate-reliability.js';
export { skillQuality } from './skill-quality.js';
import type { AutoResearchConfig } from '../config.js';
import { operateReliability } from './operate-reliability.js';
import { skillQuality } from './skill-quality.js';
export const PRESETS: Record<string, AutoResearchConfig> = {
'operate-reliability': operateReliability,
'skill-quality': skillQuality,
};
@@ -1,24 +0,0 @@
/**
* Preset: Operate Command Reliability
*
* Optimizes opencli operate commands against the Layer 1 deterministic test suite.
* Metric: number of passing browse-tasks (out of 59).
*/
import type { AutoResearchConfig } from '../config.js';
export const operateReliability: AutoResearchConfig = {
goal: 'Increase operate command pass rate to 59/59 (100%)',
scope: [
'src/browser/dom-snapshot.ts',
'src/browser/dom-helpers.ts',
'src/browser/base-page.ts',
'src/browser/page.ts',
'src/cli.ts',
],
metric: 'pass_count',
direction: 'higher',
verify: 'npx tsx autoresearch/eval-browse.ts 2>&1 | tail -1',
guard: 'npm run build',
minDelta: 1,
};
-20
View File
@@ -1,20 +0,0 @@
/**
* Preset: Skill E2E Quality
*
* Optimizes the opencli-operate SKILL.md against the Layer 2 LLM E2E test suite.
* Metric: number of passing skill-tasks (out of 35).
*/
import type { AutoResearchConfig } from '../config.js';
export const skillQuality: AutoResearchConfig = {
goal: 'Increase skill E2E pass rate to 35/35 (100%)',
scope: [
'skills/opencli-operate/SKILL.md',
],
metric: 'pass_count',
direction: 'higher',
verify: 'npx tsx autoresearch/eval-skill.ts 2>&1 | tail -1',
guard: 'npm run build',
iterations: 20,
};
-9
View File
@@ -1,9 +0,0 @@
#!/bin/bash
# Layer 1: Deterministic browse command testing
set -e
cd "$(dirname "$0")/.."
echo "Building OpenCLI..."
npm run build > /dev/null 2>&1
echo "Build OK"
echo ""
npx tsx autoresearch/eval-browse.ts "$@"
-9
View File
@@ -1,9 +0,0 @@
#!/bin/bash
# Layer 2: Claude Code skill E2E testing
set -e
cd "$(dirname "$0")/.."
echo "Building OpenCLI..."
npm run build > /dev/null 2>&1
echo "Build OK"
echo ""
npx tsx autoresearch/eval-skill.ts "$@"
-24
View File
@@ -32,7 +32,6 @@ export default defineConfig({
{ text: 'Comparison', link: '/comparison' },
{ text: 'Browser Bridge', link: '/guide/browser-bridge' },
{ text: 'Troubleshooting', link: '/guide/troubleshooting' },
{ text: 'Add an Electron App CLI', link: '/guide/electron-app-cli' },
{ text: 'Plugins', link: '/guide/plugins' },
],
},
@@ -50,7 +49,6 @@ export default defineConfig({
items: [
{ text: 'Twitter / X', link: '/adapters/browser/twitter' },
{ text: 'Reddit', link: '/adapters/browser/reddit' },
{ text: 'Tieba', link: '/adapters/browser/tieba' },
{ text: 'Bilibili', link: '/adapters/browser/bilibili' },
{ text: 'Zhihu', link: '/adapters/browser/zhihu' },
{ text: 'Xiaohongshu', link: '/adapters/browser/xiaohongshu' },
@@ -69,28 +67,12 @@ export default defineConfig({
{ text: 'Jimeng', link: '/adapters/browser/jimeng' },
{ text: 'Yollomi', link: '/adapters/browser/yollomi' },
{ text: 'LINUX DO', link: '/adapters/browser/linux-do' },
{ text: 'Band', link: '/adapters/browser/band' },
{ text: 'Chaoxing', link: '/adapters/browser/chaoxing' },
{ text: 'Grok', link: '/adapters/browser/grok' },
{ text: 'Amazon', link: '/adapters/browser/amazon' },
{ text: 'Gemini', link: '/adapters/browser/gemini' },
{ text: 'NotebookLM', link: '/adapters/browser/notebooklm' },
{ text: 'WeRead', link: '/adapters/browser/weread' },
{ text: 'Douban', link: '/adapters/browser/douban' },
{ text: 'Sina Blog', link: '/adapters/browser/sinablog' },
{ text: 'Substack', link: '/adapters/browser/substack' },
{ text: 'Pixiv', link: '/adapters/browser/pixiv' },
{ text: 'Douban', link: '/adapters/browser/douban' },
{ text: 'Doubao', link: '/adapters/browser/doubao' },
{ text: 'Facebook', link: '/adapters/browser/facebook' },
{ text: 'Google', link: '/adapters/browser/google' },
{ text: 'IMDb', link: '/adapters/browser/imdb' },
{ text: 'Instagram', link: '/adapters/browser/instagram' },
{ text: 'JD.com', link: '/adapters/browser/jd' },
{ text: 'Medium', link: '/adapters/browser/medium' },
{ text: 'TikTok', link: '/adapters/browser/tiktok' },
{ text: 'Web (Generic)', link: '/adapters/browser/web' },
{ text: 'Weixin', link: '/adapters/browser/weixin' },
],
},
{
@@ -105,15 +87,11 @@ export default defineConfig({
{ text: 'Xiaoyuzhou', link: '/adapters/browser/xiaoyuzhou' },
{ text: 'Yahoo Finance', link: '/adapters/browser/yahoo-finance' },
{ text: 'arXiv', link: '/adapters/browser/arxiv' },
{ text: 'paperreview.ai', link: '/adapters/browser/paperreview' },
{ text: 'Barchart', link: '/adapters/browser/barchart' },
{ text: 'Hugging Face', link: '/adapters/browser/hf' },
{ text: 'Sina Finance', link: '/adapters/browser/sinafinance' },
{ text: 'Spotify', link: '/adapters/browser/spotify' },
{ text: 'Stack Overflow', link: '/adapters/browser/stackoverflow' },
{ text: 'Wikipedia', link: '/adapters/browser/wikipedia' },
{ text: 'Lobsters', link: '/adapters/browser/lobsters' },
{ text: 'Steam', link: '/adapters/browser/steam' },
],
},
{
@@ -127,7 +105,6 @@ export default defineConfig({
{ text: 'ChatWise', link: '/adapters/desktop/chatwise' },
{ text: 'Notion', link: '/adapters/desktop/notion' },
{ text: 'Discord', link: '/adapters/desktop/discord' },
{ text: 'Doubao App', link: '/adapters/desktop/doubao-app' },
],
},
],
@@ -177,7 +154,6 @@ export default defineConfig({
{ text: '快速开始', link: '/zh/guide/getting-started' },
{ text: '安装', link: '/zh/guide/installation' },
{ text: 'Browser Bridge', link: '/zh/guide/browser-bridge' },
{ text: '给新 Electron 应用生成 CLI', link: '/zh/guide/electron-app-cli' },
{ text: '插件', link: '/zh/guide/plugins' },
],
},
-32
View File
@@ -1,32 +0,0 @@
# ONES 项目管理平台(OpenCLI
基于官方 [ONES Project API](https://developer.ones.cn/zh-CN/docs/api/readme/),经 **Chrome + Browser Bridge** 在页面里 `fetch``credentials: 'include'`)。
## 环境变量
| 变量 | 必填 | 说明 |
|------|------|------|
| `ONES_BASE_URL` | 是 | 与 Chrome 中访问的 ONES 根 URL 一致 |
| `ONES_USER_ID` / `ONES_AUTH_TOKEN` | 视部署 | 若接口强制要文档中的 Header,再设置(可先只依赖浏览器登录) |
| `ONES_EMAIL` / `ONES_PHONE` / `ONES_PASSWORD` | 否 | 供 `ones login` 脚本化 |
## 命令
```bash
export ONES_BASE_URL=https://your-host
# 安装扩展,Chrome 已登录 ONES
opencli ones me
opencli ones token-info # teams column includes name(uuid), useful for tasks
opencli ones tasks <teamUUID> --limit 20 --project <optional>
opencli ones my-tasks <teamUUID> --limit 100 # default assignee=self
opencli ones my-tasks <teamUUID> --mode field004 # deployments using field004 as assignee
opencli ones my-tasks <teamUUID> --mode both # assignee OR creator
opencli ones task <taskUUID> --team <teamUUID> # single task (URL .../task/<uuid>)
opencli ones worklog <taskUUID> 2 --team <teamUUID> # log hours for today
opencli ones worklog <taskUUID> 1 --team <teamUUID> --date 2026-03-01 # backfill
opencli ones login --email you@corp.com --password '***' # optional; stderr prints header export hints
opencli ones logout
```
更完整的说明见 [docs/adapters/browser/ones.md](../adapters/browser/ones.md)。
-48
View File
@@ -1,48 +0,0 @@
# 36kr (36氪)
**Mode**: 🌐 Public / 🔐 Browser · **Domain**: `36kr.com`
## Commands
| Command | Description |
|---------|-------------|
| `opencli 36kr hot` | 36氪热榜 — trending articles |
| `opencli 36kr news` | Latest tech/startup news from 36kr |
| `opencli 36kr search <query>` | Search 36kr articles |
| `opencli 36kr article <id-or-url>` | Read full article content |
## Usage Examples
```bash
# Trending articles
opencli 36kr hot --limit 10
# Hot by type
opencli 36kr hot --type renqi --limit 10
opencli 36kr hot --type zonghe --limit 10
# Latest news
opencli 36kr news --limit 20
# Search articles
opencli 36kr search "AI" --limit 10
opencli 36kr search "OpenAI" --limit 5
# Read full article (by ID or URL)
opencli 36kr article 3000000123456
opencli 36kr article https://36kr.com/p/3000000123456
# JSON output
opencli 36kr hot -f json
```
## Notes
- `news` uses the public RSS feed and works without Browser Bridge.
- `hot`, `search`, and `article` use Browser Bridge and are best run with Chrome open.
- `hot --type` accepts `catalog`, `renqi`, `zonghe`, and `shoucang`.
## Prerequisites
- `news`: No browser required — uses public RSS feed
- `hot`, `search`, `article`: Chrome running with [Browser Bridge extension](/guide/browser-bridge) installed
-53
View File
@@ -1,53 +0,0 @@
# Amazon
**Mode**: 🔐 Browser · **Domain**: `amazon.com`
## Commands
| Command | Description |
|---------|-------------|
| `opencli amazon bestsellers [<best-sellers-url>]` | Read Amazon Best Sellers pages for ranked candidate discovery |
| `opencli amazon search "<query>"` | Read Amazon search results for coarse filtering |
| `opencli amazon product <asin-or-url>` | Read a product page with title, price, rating, breadcrumbs, and bullets |
| `opencli amazon offer <asin-or-url>` | Read seller / fulfillment / buy-box facts from the product page |
| `opencli amazon discussion <asin-or-url>` | Read review summary and sample customer reviews |
## Usage Examples
```bash
# Root Best Sellers page
opencli amazon bestsellers https://www.amazon.com/Best-Sellers/zgbs --limit 10 -f json
# Category-specific Best Sellers page
opencli amazon bestsellers "<category-best-sellers-url>" --limit 50 -f json
# Search products
opencli amazon search "desk shelf organizer" --limit 20 -f json
# Validate one product
opencli amazon product B0FJS72893 -f json
# Validate seller / offer facts
opencli amazon offer B0FJS72893 -f json
# Read review summary + samples
opencli amazon discussion B0FJS72893 --limit 5 -f json
```
## Prerequisites
- Chrome running with an active `amazon.com` session in the shared profile
- [Browser Bridge extension](/guide/browser-bridge) installed
## Notes
- This adapter only returns fields visible on public Amazon pages.
- `bestsellers` and `search` are for candidate discovery; `product`, `offer`, and `discussion` are the validation surfaces.
- `offer` is the right surface for `sold_by`, `ships_from`, and Amazon-retail exclusion.
- `discussion` may return review data even when Q&A is absent. Missing Q&A is a normal outcome, not an error.
## Troubleshooting
- If Amazon shows a robot-check page, clear it in Chrome and retry.
- If CDP is attached to the wrong tab, retry with `OPENCLI_CDP_TARGET=amazon.com`.
- Avoid running multiple Amazon browser commands in parallel against the same shared Chrome target.
-63
View File
@@ -1,63 +0,0 @@
# Band
**Mode**: 🔐 Browser · **Domain**: `www.band.us`
Read posts, comments, and notifications from [Band](https://www.band.us), a private community platform. Authentication uses your logged-in Chrome session (cookie-based).
## Commands
| Command | Description |
|---------|-------------|
| `opencli band bands` | List all Bands you belong to |
| `opencli band posts <band_no>` | List posts from a Band |
| `opencli band post <band_no> <post_no>` | Export full post content including nested comments |
| `opencli band mentions` | Show notifications where you were @mentioned |
## Usage Examples
```bash
# List all your bands (get band_no from here)
opencli band bands
# List recent posts in a band
opencli band posts 12345678 --limit 10
# Export a post with comments
opencli band post 12345678 987654321
# Export post body only (skip comments)
opencli band post 12345678 987654321 --comments false
# Export post and download attached photos
opencli band post 12345678 987654321 --output ./band-photos
# Show recent @mention notifications
opencli band mentions --limit 20
# Show only unread mentions
opencli band mentions --unread true
# Show all notification types
opencli band mentions --filter all
```
### `band mentions` filter options
| Filter | Description |
|--------|-------------|
| `mentioned` | Only notifications where you were @mentioned (default) |
| `all` | All notifications |
| `post` | Post-related notifications |
| `comment` | Comment-related notifications |
## Prerequisites
- Chrome running and **logged into** [band.us](https://www.band.us)
- [Browser Bridge extension](/guide/browser-bridge) installed
## Notes
- `band_no` is the numeric ID in the Band URL: `band.us/band/{band_no}/post`
- `band bands` lists all your bands with their `band_no` values
- `band post` output rows: `type=post` (the post itself), `type=comment` (top-level comment), `type=reply` (nested reply)
- Photo downloads use the full-resolution URL (thumbnail query params are stripped automatically)
-53
View File
@@ -1,53 +0,0 @@
# Bluesky
**Mode**: 🌐 Public · **Domain**: `bsky.app`
## Commands
| Command | Description |
|---------|-------------|
| `opencli bluesky profile` | User profile info |
| `opencli bluesky user` | Recent posts from a user |
| `opencli bluesky trending` | Trending topics |
| `opencli bluesky search` | Search users |
| `opencli bluesky feeds` | Popular feed generators |
| `opencli bluesky followers` | User's followers |
| `opencli bluesky following` | Accounts a user follows |
| `opencli bluesky thread` | Post thread with replies |
| `opencli bluesky starter-packs` | User's starter packs |
## Usage Examples
```bash
# User profile
opencli bluesky profile --handle bsky.app
# Recent posts
opencli bluesky user --handle bsky.app --limit 10
# Trending topics
opencli bluesky trending --limit 10
# Search users
opencli bluesky search --query "AI" --limit 10
# Popular feeds
opencli bluesky feeds --limit 10
# Followers / following
opencli bluesky followers --handle bsky.app --limit 10
opencli bluesky following --handle bsky.app
# Post thread with replies
opencli bluesky thread --uri "at://did:.../app.bsky.feed.post/..."
# Starter packs
opencli bluesky starter-packs --handle bsky.app
# JSON output
opencli bluesky profile --handle bsky.app -f json
```
## Prerequisites
None — all commands use the public Bluesky AT Protocol API, no browser or login required.
-14
View File
@@ -9,8 +9,6 @@
| `opencli douban search` | 搜索豆瓣电影、图书或音乐 |
| `opencli douban top250` | 豆瓣电影 Top 250 |
| `opencli douban subject` | 条目详情 |
| `opencli douban photos` | 获取电影海报/剧照图片列表 |
| `opencli douban download` | 下载电影海报/剧照图片 |
| `opencli douban marks` | 我的标记 |
| `opencli douban reviews` | 我的短评 |
| `opencli douban movie-hot` | 豆瓣电影热门榜单 |
@@ -34,18 +32,6 @@ opencli douban top250 --limit 10
# 条目详情
opencli douban subject 1292052
# 获取海报直链(默认 type=Rb)
opencli douban photos 30382501 --limit 20
# 下载海报到本地目录
opencli douban download 30382501 --output ./douban
# 只下载指定 photo_id 的一张图
opencli douban download 30382501 --photo-id 2913621075 --output ./douban
# 返回 JSON,便于上层界面直接渲染图片并右键取图
opencli douban photos 30382501 -f json
# 电影热门
opencli douban movie-hot --limit 10
+1 -5
View File
@@ -11,16 +11,12 @@ Browser adapter for [Doubao Chat](https://www.doubao.com/chat).
| `opencli doubao send "..."` | Send a message to the current Doubao chat |
| `opencli doubao read` | Read the visible Doubao conversation |
| `opencli doubao ask "..."` | Send a prompt and wait for a reply |
| `opencli doubao detail <id>` | 对话详情 |
| `opencli doubao history` | 历史对话列表 |
| `opencli doubao meeting-summary <id>` | 会议总结 |
| `opencli doubao meeting-transcript <id>` | 会议记录 |
## Prerequisites
- Chrome is running
- You are already logged into [doubao.com](https://www.doubao.com/)
- Browser Bridge extension is installed and enabled for OpenCLI
- Playwright MCP Bridge / browser bridge is configured for OpenCLI
## Examples
-75
View File
@@ -1,75 +0,0 @@
# Douyin (抖音创作者中心)
**Mode**: 🔐 Browser · **Domain**: `creator.douyin.com`
## Commands
| Command | Description |
|---------|-------------|
| `opencli douyin profile` | 获取账号信息 |
| `opencli douyin videos` | 获取作品列表 |
| `opencli douyin drafts` | 获取草稿列表 |
| `opencli douyin draft` | 上传视频并保存为草稿 |
| `opencli douyin publish` | 定时发布视频到抖音 |
| `opencli douyin update` | 更新视频信息 |
| `opencli douyin delete` | 删除作品 |
| `opencli douyin stats` | 查询作品数据分析 |
| `opencli douyin collections` | 获取合集列表 |
| `opencli douyin activities` | 获取官方活动列表 |
| `opencli douyin location` | 搜索发布可用的地理位置 |
| `opencli douyin hashtag search` | 按关键词搜索话题 |
| `opencli douyin hashtag suggest` | 基于封面 URI 推荐话题 |
| `opencli douyin hashtag hot` | 获取热点词 |
## Usage Examples
```bash
# 账号与作品
opencli douyin profile
opencli douyin videos --limit 10
opencli douyin videos --status scheduled
opencli douyin drafts
# 发布前辅助信息
opencli douyin collections
opencli douyin activities
opencli douyin location "东京塔"
opencli douyin hashtag search "春游"
opencli douyin hashtag hot --limit 10
# 保存草稿
opencli douyin draft ./video.mp4 \
--title "春游 vlog" \
--caption "#春游 先存草稿"
# 定时发布
opencli douyin publish ./video.mp4 \
--title "春游 vlog" \
--caption "#春游 今天去看樱花" \
--schedule "2026-04-08T12:00:00+09:00"
# 也支持 Unix 秒字符串
opencli douyin publish ./video.mp4 \
--title "春游 vlog" \
--schedule 1775617200
# 更新与删除
opencli douyin update 1234567890 --caption "更新后的文案"
opencli douyin update 1234567890 --reschedule "2026-04-09T20:00:00+09:00"
opencli douyin delete 1234567890
# JSON 输出
opencli douyin profile -f json
```
## Prerequisites
- Chrome running and **logged into** `creator.douyin.com`
- The logged-in account must have access to Douyin Creator Center publishing features
- [Browser Bridge extension](/guide/browser-bridge) installed
## Notes
- `publish` requires `--schedule` to be at least 2 hours later and no more than 14 days later
- `draft` and `publish` upload the video through Douyin/ByteDance browser-authenticated APIs, so cookies in the active browser session must be valid
- `hashtag suggest` expects a valid `cover`/`cover_uri` value produced during the publish pipeline; for normal manual use, `hashtag search` and `hashtag hot` are usually more convenient
-72
View File
@@ -1,72 +0,0 @@
# Gemini
**Mode**: 🔐 Browser · **Domain**: `gemini.google.com`
## Commands
| Command | Description |
|---------|-------------|
| `opencli gemini new` | Start a new Gemini web chat |
| `opencli gemini ask <prompt>` | Send a prompt and return only the assistant reply |
| `opencli gemini image <prompt>` | Generate images in Gemini and optionally save them locally |
## Usage Examples
```bash
# Start a fresh chat
opencli gemini new
# Ask Gemini and return minimal plain-text output
opencli gemini ask "Reply with exactly: HELLO"
# Ask in a new chat and wait longer
opencli gemini ask "Summarize this design in 3 bullets" --new true --timeout 90
# Generate an icon image with short flags
opencli gemini image "Generate a tiny cyan moon icon" --rt 1:1 --st icon
# Only generate in Gemini and print the page link without downloading files
opencli gemini image "A watercolor sunset over a lake" --sd true
# Save generated images to a custom directory
opencli gemini image "A flat illustration of a robot" --op ~/tmp/gemini-images
```
## Options
### `ask`
| Option | Description |
|--------|-------------|
| `prompt` | Prompt to send (required positional argument) |
| `--timeout` | Max seconds to wait for a reply (default: `60`) |
| `--new` | Start a new chat before sending (default: `false`) |
### `image`
| Option | Description |
|--------|-------------|
| `prompt` | Image prompt to send (required positional argument) |
| `--rt` | Aspect ratio shorthand: `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3` |
| `--st` | Optional style shorthand, e.g. `icon`, `anime`, `watercolor` |
| `--op` | Output directory for downloaded images (default: `~/tmp/gemini-images`) |
| `--sd` | Skip download and only print the Gemini page link |
## Behavior
- `ask` uses plain minimal output and returns only the assistant response text prefixed with `💬`.
- `image` also uses plain output and prints `status / file / link` instead of a table.
- `image` always starts from a fresh Gemini chat before sending the prompt.
- When `--sd` is enabled, `image` keeps the generation in Gemini and only prints the conversation link.
## Prerequisites
- Chrome is running
- You are already logged into `gemini.google.com`
- [Browser Bridge extension](/guide/browser-bridge) is installed
## Caveats
- This adapter drives the Gemini consumer web UI, not a public API.
- It depends on the current browser session and may fail if Gemini shows login, consent, challenge, quota, or other gating UI.
- DOM or product changes on Gemini can break composer detection, new-chat handling, or image export behavior.
-47
View File
@@ -1,47 +0,0 @@
# IMDb
**Mode**: 🌐 Public (Browser) · **Domain**: `www.imdb.com`
## Commands
| Command | Description |
|---------|-------------|
| `opencli imdb search` | Search movies, TV shows, and people |
| `opencli imdb title` | Get movie or TV show details |
| `opencli imdb top` | IMDb Top 250 Movies |
| `opencli imdb trending` | IMDb Most Popular Movies |
| `opencli imdb person` | Get actor or director info |
| `opencli imdb reviews` | Get user reviews for a title |
## Usage Examples
```bash
# Search for a movie
opencli imdb search "inception" --limit 10
# Get movie details
opencli imdb title tt1375666
# Get TV series details (also accepts full URL)
opencli imdb title "https://www.imdb.com/title/tt0903747/"
# Top 250 movies
opencli imdb top --limit 20
# Currently trending movies
opencli imdb trending --limit 10
# Actor/director info with filmography
opencli imdb person nm0634240 --limit 5
# User reviews
opencli imdb reviews tt1375666 --limit 5
# JSON output
opencli imdb top --limit 5 -f json
```
## Prerequisites
- Chrome with Browser Bridge extension installed
- No login required (all data is public)
+2 -2
View File
@@ -6,7 +6,7 @@
| Command | Description |
|---------|-------------|
| `opencli jd item <sku>` | Fetch product details (price, shop, specs, AVIF images) |
| `opencli jd item <sku>` | Fetch product details (price, images, specs) |
## Usage Examples
@@ -14,7 +14,7 @@
# Get product details by SKU
opencli jd item 100291143898
# Limit returned AVIF images
# Limit detail images
opencli jd item 100291143898 --images 5
# JSON output
+21 -182
View File
@@ -6,198 +6,37 @@
| Command | Description |
|---------|-------------|
| `opencli linux-do feed` | Browse topics (site-wide, by tag, or by category) |
| `opencli linux-do categories` | List all categories |
| `opencli linux-do tags` | List popular tags |
| `opencli linux-do search <query>` | Search topics |
| `opencli linux-do topic <id>` | View topic posts |
| `opencli linux-do user-topics <username>` | Topics created by a user |
| `opencli linux-do user-posts <username>` | Replies posted by a user |
| `opencli linux-do hot` | 热门话题 |
| `opencli linux-do latest` | 最新话题 |
| `opencli linux-do categories` | 板块列表 |
| `opencli linux-do category` | 板块话题 |
| `opencli linux-do search` | 搜索话题 |
| `opencli linux-do topic` | 话题详情 |
## feed
Browse topic listings. Defaults to latest topics when called with no arguments.
- Supports filtering by `--tag`, `--category`, or both
- `--tag` accepts tag name, slug, or ID
- `--category` accepts category name, slug, ID, or `Parent / Child` path for sub-categories
- Use `--view` to switch between latest / hot / top
### Basic
## Usage Examples
```bash
# Latest topics (default)
opencli linux-do feed
# Hot topics this week
opencli linux-do hot --limit 20
# Hot topics
opencli linux-do feed --view hot
# Hot topics by period
opencli linux-do hot --period daily
opencli linux-do hot --period monthly
# Top topics — default period is weekly
opencli linux-do feed --view top
opencli linux-do feed --view top --period daily
opencli linux-do feed --view top --period monthly
# Latest topics
opencli linux-do latest --limit 10
# Sort by views descending
opencli linux-do feed --order views
# List all categories
opencli linux-do categories
# Sort by created time ascending
opencli linux-do feed --order created --ascending
# Search topics
opencli linux-do search "NixOS"
# Limit results
opencli linux-do feed --limit 10
# View topic details
opencli linux-do topic 12345
# JSON output
opencli linux-do feed -f json
```
### Filter by tag
```bash
# By tag name, slug, or ID — all equivalent
opencli linux-do feed --tag "ChatGPT"
opencli linux-do feed --tag chatgpt
opencli linux-do feed --tag 3
# Tag + hot view
opencli linux-do feed --tag "ChatGPT" --view hot
# Tag + top view with period
opencli linux-do feed --tag "OpenAI" --view top --period monthly
```
### Filter by category
Supports both top-level and sub-categories. Sub-categories auto-resolve their parent path.
```bash
# Top-level category — name, slug, or ID
opencli linux-do feed --category "开发调优"
opencli linux-do feed --category develop
opencli linux-do feed --category 4
# Sub-category
opencli linux-do feed --category "开发调优 / Lv1"
opencli linux-do feed --category "网盘资源"
# Category + hot / top view
opencli linux-do feed --category "开发调优" --view hot
opencli linux-do feed --category "开发调优" --view top --period weekly
```
### Category + tag
Combine `--category` and `--tag` to narrow results within a category.
```bash
opencli linux-do feed --category "开发调优" --tag "ChatGPT"
opencli linux-do feed --category "网盘资源" --tag "OpenAI"
opencli linux-do feed --category 94 --tag 4 --view top --period monthly
```
### Parameters
| Parameter | Description | Default |
|-----------|-------------|---------|
| `--view V` | `latest`, `hot`, `top` | `latest` |
| `--tag VALUE` | Tag name, slug, or ID | — |
| `--category VALUE` | Category name, slug, or ID | — |
| `--limit N` | Number of results | `20` |
| `--order O` | `default`, `created`, `activity`, `views`, `posts`, `category`, `likes`, `op_likes`, `posters` | `default` |
| `--ascending` | Sort ascending instead of descending | off |
| `--period P` | `all`, `daily`, `weekly`, `monthly`, `quarterly`, `yearly` (only with `--view top`) | `weekly` |
Output columns: `title`, `replies`, `created`, `likes`, `views`, `url`
## categories
List forum categories with optional sub-category expansion.
```bash
opencli linux-do categories
opencli linux-do categories --subcategories
opencli linux-do categories --limit 50
```
When `--subcategories` is enabled, sub-categories are rendered as `Parent / Child` so the `name` value can be copied directly into `opencli linux-do feed --category ...`.
Output columns: `name`, `slug`, `id`, `topics`, `description`
## tags
List tags sorted by usage count.
```bash
opencli linux-do tags
opencli linux-do tags --limit 50
```
Output columns: `rank`, `name`, `count`, `url`
## search
Search topics by keyword.
```bash
opencli linux-do search "NixOS"
opencli linux-do search "Docker" --limit 10
opencli linux-do search "Claude" -f json
```
Output columns: `rank`, `title`, `views`, `likes`, `replies`, `url`
## topic
View posts within a topic (first page).
```bash
opencli linux-do topic 1234
opencli linux-do topic 1234 --limit 50
opencli linux-do topic 1234 --main_only -f json | jq -r '.[0].content'
```
Notes:
- `--main_only` returns only the main post row and keeps the body untruncated
Output columns: `author`, `content`, `likes`, `created_at`
## user-topics
List topics created by a user.
```bash
opencli linux-do user-topics neo
opencli linux-do user-topics neo --limit 10
```
Output columns: `rank`, `title`, `replies`, `created_at`, `likes`, `views`, `url`
## user-posts
List replies posted by a user.
```bash
opencli linux-do user-posts neo
opencli linux-do user-posts neo --limit 10
```
Output columns: `index`, `topic_user`, `topic`, `reply`, `time`, `url`
## Compatibility
The legacy commands below are still available as compatibility wrappers while `feed` becomes the canonical entrypoint:
```bash
opencli linux-do latest
opencli linux-do hot --period weekly
opencli linux-do category develop 4
```
Preferred modern forms:
```bash
opencli linux-do feed --view latest
opencli linux-do feed --view top --period weekly
opencli linux-do feed --category 4
opencli linux-do hot -f json
```
## Prerequisites
-69
View File
@@ -1,69 +0,0 @@
# NotebookLM
**Mode**: 🔐 Browser Bridge · **Domain**: `notebooklm.google.com`
## Commands
| Command | Description |
|---------|-------------|
| `opencli notebooklm status` | Check whether NotebookLM is reachable in the current Chrome session |
| `opencli notebooklm list` | List notebooks visible from the NotebookLM home page |
| `opencli notebooklm open <notebook>` | Open one notebook in the NotebookLM automation workspace by id or URL |
| `opencli notebooklm current` | Show metadata for the currently opened notebook in the automation workspace |
| `opencli notebooklm get` | Get richer metadata for the current notebook |
| `opencli notebooklm source-list` | List sources in the current notebook |
| `opencli notebooklm source-get <source>` | Resolve one source in the current notebook by id or title |
| `opencli notebooklm source-fulltext <source>` | Fetch extracted source fulltext through NotebookLM RPC |
| `opencli notebooklm source-guide <source>` | Fetch guide summary and keywords for one source |
| `opencli notebooklm history` | List conversation history threads for the current notebook |
| `opencli notebooklm note-list` | List Studio notes visible in the current notebook |
| `opencli notebooklm notes-get <note>` | Read the currently visible Studio note by title |
| `opencli notebooklm summary` | Read the current notebook summary |
## Compatibility Aliases
| Alias | Canonical command |
|-------|-------------------|
| `opencli notebooklm select <notebook>` | `opencli notebooklm open <notebook>` |
| `opencli notebooklm metadata` | `opencli notebooklm get` |
| `opencli notebooklm notes-list` | `opencli notebooklm note-list` |
## Positioning
This adapter reuses the existing OpenCLI Browser Bridge runtime:
- no custom NotebookLM extension
- no exported cookie replay
- requests and page state stay in the real Chrome session
The current milestone focuses on a stable NotebookLM read surface in desktop Chrome with an already logged-in Google account.
## Usage Examples
```bash
opencli notebooklm status
opencli notebooklm list -f json
opencli notebooklm open nb-demo -f json
opencli notebooklm current -f json
opencli notebooklm metadata -f json
opencli notebooklm source-list -f json
opencli notebooklm source-get "Quarterly report" -f json
opencli notebooklm source-guide "Quarterly report" -f json
opencli notebooklm source-fulltext "Quarterly report" -f json
opencli notebooklm history -f json
opencli notebooklm notes-list -f json
opencli notebooklm notes-get "Draft note" -f json
opencli notebooklm summary -f json
```
## Prerequisites
- Chrome running and logged into Google / NotebookLM
- [Browser Bridge extension](/guide/browser-bridge) installed
- NotebookLM accessible in the current browser session
## Notes
- Notebook-oriented commands run in OpenCLI's owned NotebookLM automation workspace/window. Use `opencli notebooklm open <notebook>` first to choose the current notebook for follow-up commands.
- `list`, `get`, `source-list`, `history`, `source-fulltext`, and `source-guide` prefer NotebookLM RPC paths and fall back only when the richer path is unavailable.
- `notes-get` currently reads note content only from the visible Studio note editor; if the note is listed but not open, open it in NotebookLM first and then retry.
-59
View File
@@ -1,59 +0,0 @@
# ONES
**Mode**: 🔐 Browser Bridge · **Domain**: `ones.cn` (self-hosted via `ONES_BASE_URL`)
## Commands
| Command | Description |
|---------|-------------|
| `opencli ones login` | Login via Project API (`auth/login`) |
| `opencli ones me` | Current user profile (`users/me`) |
| `opencli ones token-info` | Token/user/team summary (`auth/token_info`) |
| `opencli ones tasks` | Team task list with status/project labels and hours |
| `opencli ones my-tasks` | My tasks (`assign`/`field004`/`owner`/`both`) |
| `opencli ones task` | Task detail by UUID (`team/:team/task/:id/info`) |
| `opencli ones worklog` | Log/backfill hours (GraphQL `addManhour` first, then REST fallbacks) |
| `opencli ones logout` | Logout (`auth/logout`) |
## Usage Examples
```bash
# Required: your ONES base URL
export ONES_BASE_URL=https://your-instance.example.com
# Optional if your deployment requires auth headers
# export ONES_USER_ID=...
# export ONES_AUTH_TOKEN=...
# Login/profile
opencli ones login --email you@company.com --password 'your-password'
opencli ones me
opencli ones token-info
# Task lists
opencli ones tasks <teamUUID> --limit 20
opencli ones tasks <teamUUID> --project <projectUUID> --assign <userUUID>
opencli ones my-tasks <teamUUID> --limit 100
opencli ones my-tasks <teamUUID> --mode both
# Task detail
opencli ones task <taskUUID> --team <teamUUID>
# Worklog: today / backfill
opencli ones worklog <taskUUID> 2 --team <teamUUID>
opencli ones worklog <taskUUID> 1.5 --team <teamUUID> --date 2026-03-23 --note "integration"
opencli ones logout
```
## Prerequisites
- Chrome running and logged into your ONES instance
- [Browser Bridge extension](/guide/browser-bridge) installed
- `ONES_BASE_URL` set to the same origin opened in Chrome
## Notes
- This adapter targets legacy ONES Project API deployments.
- `ONES_TEAM_UUID` can be set to omit `--team` in `tasks` / `my-tasks` / `task`.
- Hours display and input use `ONES_MANHOUR_SCALE` (default `100000`).
-43
View File
@@ -1,43 +0,0 @@
# paperreview.ai
**Mode**: 🌐 Public · **Domain**: `paperreview.ai`
## Commands
| Command | Description |
|---------|-------------|
| `opencli paperreview submit` | Submit a PDF to paperreview.ai for review |
| `opencli paperreview review` | Fetch a review by token |
| `opencli paperreview feedback` | Send feedback on a completed review |
## Usage Examples
```bash
# Validate a local PDF without uploading it
opencli paperreview submit ./paper.pdf --email you@example.com --venue RAL --dry-run true
# Request an upload slot but stop before the actual upload
opencli paperreview submit ./paper.pdf --email you@example.com --venue RAL --prepare-only true
# Submit a paper for review
opencli paperreview submit ./paper.pdf --email you@example.com --venue RAL -f json
# Check the review status or fetch the final review
opencli paperreview review tok_123 -f json
# Submit feedback on the review quality
opencli paperreview feedback tok_123 --helpfulness 4 --critical-error no --actionable-suggestions yes
```
## Prerequisites
- No browser required — uses public paperreview.ai endpoints
- The input file must be a local `.pdf`
- paperreview.ai currently rejects files larger than `10MB`
- `submit` requires `--email`; `--venue` is optional
## Notes
- `submit` returns both the review token and the review URL when submission succeeds
- `review` returns `processing` until the paperreview.ai result is ready
- `feedback` expects `yes` / `no` values for `--critical-error` and `--actionable-suggestions`
-92
View File
@@ -1,92 +0,0 @@
# Pixiv
**Mode**: 🔐 Browser · **Domain**: `www.pixiv.net`
## Commands
| Command | Description |
|---------|-------------|
| `opencli pixiv ranking` | Daily/weekly/monthly illustration rankings |
| `opencli pixiv search <query>` | Search illustrations by keyword or tag |
| `opencli pixiv user <uid>` | View artist profile info |
| `opencli pixiv illusts <user-id>` | List illustrations by artist |
| `opencli pixiv detail <id>` | View illustration details |
| `opencli pixiv download <illust-id>` | Download original-quality images |
## Usage Examples
### Ranking
```bash
# Daily rankings (default)
opencli pixiv ranking --limit 10
# Weekly / monthly rankings
opencli pixiv ranking --mode weekly
opencli pixiv ranking --mode monthly
# R18 rankings
opencli pixiv ranking --mode daily_r18
opencli pixiv ranking --mode weekly_r18
# Other modes: rookie, original, male, female
opencli pixiv ranking --mode rookie
```
### Search
```bash
# Search by keyword or tag
opencli pixiv search "初音ミク" --limit 20
# Filter by content rating
opencli pixiv search "風景" --mode safe # Safe-for-work only
opencli pixiv search "風景" --mode r18 # R18 only
opencli pixiv search "風景" --mode all # All (default)
# Sort by popularity
opencli pixiv search "VOCALOID" --order popular_d
# All sort options: date_d (newest), date (oldest), popular_d, popular_male_d, popular_female_d
# Pagination
opencli pixiv search "オリジナル" --page 2 --limit 30
```
### User & Illustrations
```bash
# View artist profile
opencli pixiv user 11
# List artist's illustrations (newest first)
opencli pixiv illusts 11 --limit 10
# View illustration details (tags, stats, type)
opencli pixiv detail 12345678
```
### Download
```bash
# Download all images from an illustration
opencli pixiv download 12345678
# Download to a custom directory
opencli pixiv download 12345678 --output ./my-images
```
### Output Formats
```bash
# JSON output
opencli pixiv ranking -f json
# Verbose mode
opencli pixiv search "test" -v
```
## Prerequisites
- Chrome running and **logged into** pixiv.net
- [Browser Bridge extension](/guide/browser-bridge) installed
-49
View File
@@ -1,49 +0,0 @@
# Product Hunt
**Mode**: 🌐 Public / 🔐 Browser · **Domain**: `www.producthunt.com`
## Commands
| Command | Description |
|---------|-------------|
| `opencli producthunt posts` | Latest Product Hunt launches (optional category filter) |
| `opencli producthunt today` | Today's Product Hunt launches (most recent day in feed) |
| `opencli producthunt hot` | Today's top Product Hunt launches with vote counts |
| `opencli producthunt browse <category>` | Best products in a Product Hunt category |
## Usage Examples
```bash
# Today's top launches with vote counts
opencli producthunt hot --limit 10
# Latest posts (RSS feed)
opencli producthunt posts --limit 20
# Filter by category
opencli producthunt posts --category developer-tools --limit 10
# Today's launches only
opencli producthunt today --limit 10
# Browse best products in a category
opencli producthunt browse vibe-coding --limit 10
opencli producthunt browse ai-agents --limit 10
opencli producthunt browse developer-tools --limit 10
# JSON output
opencli producthunt hot -f json
```
## Category Slugs
Common categories for `browse` and `posts --category`:
`ai-agents`, `ai-coding-agents`, `ai-code-editors`, `ai-chatbots`, `ai-workflow-automation`,
`vibe-coding`, `developer-tools`, `productivity`, `design-creative`, `marketing-sales`,
`no-code-platforms`, `llms`, `finance`, `social-community`, `engineering-development`
## Prerequisites
- `posts` and `today` — no browser required (public RSS feed)
- `hot` and `browse` — Chrome running with [Browser Bridge extension](/guide/browser-bridge) installed
+6 -56
View File
@@ -1,19 +1,15 @@
# 新浪财经 (Sina Finance)
**Mode**: 🌐 Public / 🔐 Browser · **Domain**: `finance.sina.com.cn`
**Mode**: 🌐 Public · **Domain**: `finance.sina.com.cn`
## Commands
| Command | Description | Mode |
|---------|-------------|------|
| `opencli sinafinance news` | 新浪财经 7×24 小时实时快讯 | 🌐 Public |
| `opencli sinafinance rolling-news` | 新浪财经滚动新闻 | 🔐 Browser |
| `opencli sinafinance stock` | 新浪财经行情(A股/港股/美股) | 🌐 Public |
| Command | Description |
|---------|-------------|
| `opencli sinafinance news` | 新浪财经 7×24 小时实时快讯 |
## Usage Examples
### news - 7×24 实时快讯
```bash
# Latest financial news
opencli sinafinance news --limit 20
@@ -27,59 +23,13 @@ opencli sinafinance news --type 6 # 国际
opencli sinafinance news -f json
```
### rolling-news - 滚动新闻
```bash
# Rolling news feed
opencli sinafinance rolling-news
# JSON output
opencli sinafinance rolling-news -f json
```
### stock - 股票行情
```bash
# Search and view A-share stock
opencli sinafinance stock 贵州茅台 --market cn
# Search and view HK stock
opencli sinafinance stock 腾讯控股 --market hk
# Search and view US stock
opencli sinafinance stock aapl --market us
# Auto-detect market (searches cn, hk, us in order)
opencli sinafinance stock 招商证券
# JSON output
opencli sinafinance stock 贵州茅台 -f json
```
## Options
### news
### Options
| Option | Description |
|--------|-------------|
| `--limit` | Max results, up to 50 (default: 20) |
| `--type` | News type: `0`=全部, `1`=A股, `2`=宏观, `3`=公司, `4`=数据, `5`=市场, `6`=国际, `7`=观点, `8`=央行, `9`=其它 |
### stock
| Option | Description |
|--------|-------------|
| `--market` | Market: `cn`, `hk`, `us`, `auto` (default: auto). When `auto`, searches in cn, hk, us order |
## Prerequisites
- `news` & `stock`: No browser required — uses public API
- `rolling-news`: Chrome running and **logged into** `finance.sina.com.cn`
- For `rolling-news`: [Browser Bridge extension](/guide/browser-bridge) installed
## Notes
- `news` and `stock` use public APIs — no browser or login needed
- `stock` supports Chinese names, Chinese codes, and ticker symbols; auto-detects market
- Market priority for auto-detection: cn (A股) → hk (港股) → us (美股)
- US stock `High`/`Low` columns show 52-week range; A股/港股 show today's range
- No browser required — uses public API
-62
View File
@@ -1,62 +0,0 @@
# Spotify
**Mode**: 🔑 OAuth API · **Domains**: `accounts.spotify.com`, `api.spotify.com`
## Commands
| Command | Description |
|---------|-------------|
| `opencli spotify auth` | Authenticate with Spotify and store tokens locally |
| `opencli spotify status` | Show current playback status |
| `opencli spotify play [query]` | Resume playback or search-and-play a track |
| `opencli spotify pause` | Pause playback |
| `opencli spotify next` | Skip to the next track |
| `opencli spotify prev` | Skip to the previous track |
| `opencli spotify volume <0-100>` | Set playback volume |
| `opencli spotify search <query>` | Search Spotify tracks |
| `opencli spotify queue <query>` | Add a track to the playback queue |
| `opencli spotify shuffle <on|off>` | Toggle shuffle |
| `opencli spotify repeat <off|track|context>` | Set repeat mode |
## Usage Examples
```bash
# First-time setup
opencli spotify auth
# What is playing right now?
opencli spotify status
# Resume playback
opencli spotify play
# Search and immediately play a track
opencli spotify play "Numb Linkin Park"
# Search without playing
opencli spotify search "Daft Punk" --limit 5 -f json
# Queue a track
opencli spotify queue "Get Lucky"
# Playback controls
opencli spotify pause
opencli spotify next
opencli spotify prev
opencli spotify volume 35
opencli spotify shuffle on
opencli spotify repeat track
```
## Setup
1. Create a Spotify app at <https://developer.spotify.com/dashboard>
2. Add `http://127.0.0.1:8888/callback` to the app's Redirect URIs
3. Fill in `SPOTIFY_CLIENT_ID` and `SPOTIFY_CLIENT_SECRET` in `~/.opencli/spotify.env`
4. Run `opencli spotify auth`
## Notes
- Browser Bridge is not required.
- Tokens are stored locally at `~/.opencli/spotify-tokens.json`.
- Playback commands work best when you already have an active Spotify device/session.
-45
View File
@@ -1,45 +0,0 @@
# Tieba
**Mode**: 🔐 Browser · **Domain**: `tieba.baidu.com`
## Commands
| Command | Description |
|---------|-------------|
| `opencli tieba hot` | Read Tieba trending topics |
| `opencli tieba posts <forum>` | List threads in one forum |
| `opencli tieba search <keyword>` | Search threads across Tieba |
| `opencli tieba read <thread-id>` | Read one thread page |
## Usage Examples
```bash
# Trending topics
opencli tieba hot --limit 5
# List forum threads
opencli tieba posts 李毅 --limit 10
# Search Tieba
opencli tieba search 编程 --limit 10
# Read one thread
opencli tieba read 10163164720 --limit 10
# Read page 2 of a thread
opencli tieba read 10163164720 --page 2 --limit 10
# JSON output
opencli tieba hot -f json
```
## Notes
- `tieba search` currently supports only `--page 1`
- `tieba read --limit` counts reply rows; page 1 may also include the main post
## Prerequisites
- Chrome running and able to open `tieba.baidu.com`
- [Browser Bridge extension](/guide/browser-bridge) installed
- For `posts`, `search`, and `read`, a valid Tieba login session in Chrome is recommended
-6
View File
@@ -37,12 +37,6 @@
# Quick start
opencli twitter trending --limit 5
# Search top tweets (default)
opencli twitter search "react 19"
# Search latest/live tweets
opencli twitter search "react 19" --filter live
# JSON output
opencli twitter trending -f json
+1 -6
View File
@@ -6,13 +6,8 @@
| Command | Description |
|---------|-------------|
| `opencli weibo hot` | 微博热搜 |
| `opencli weibo hot` | |
| `opencli weibo search` | Search Weibo posts by keyword |
| `opencli weibo feed` | 首页时间线 |
| `opencli weibo user` | 用户信息 |
| `opencli weibo me` | 我的信息 |
| `opencli weibo post` | 发微博 |
| `opencli weibo comments` | 微博评论 |
## Usage Examples
-2
View File
@@ -8,8 +8,6 @@
|---------|-------------|
| `opencli wikipedia search` | Search Wikipedia articles |
| `opencli wikipedia summary` | Get Wikipedia article summary |
| `opencli wikipedia random` | Random Wikipedia article |
| `opencli wikipedia trending` | Trending Wikipedia articles |
## Usage Examples
+10 -19
View File
@@ -7,18 +7,15 @@
| Command | Description |
|---------|-------------|
| `opencli xiaohongshu search` | Search notes by keyword (returns title, author, likes, URL) |
| `opencli xiaohongshu note` | Read full note content (title, author, description, likes, collects, comments, tags) |
| `opencli xiaohongshu comments` | Read comments from a note (`--with-replies` for nested 楼中楼 replies) |
| `opencli xiaohongshu feed` | Home feed recommendations (via Pinia store interception) |
| `opencli xiaohongshu notifications` | User notifications (mentions, likes, connections) |
| `opencli xiaohongshu user` | Get public notes from a user profile |
| `opencli xiaohongshu download` | Download images and videos from a note |
| `opencli xiaohongshu publish` | Publish image-text notes (creator center UI automation) |
| `opencli xiaohongshu creator-notes` | Creator's note list with per-note metrics |
| `opencli xiaohongshu creator-note-detail` | Detailed analytics for a single creator note |
| `opencli xiaohongshu creator-notes-summary` | Combined note list + detail analytics summary |
| `opencli xiaohongshu creator-profile` | Creator account info (followers, growth level) |
| `opencli xiaohongshu creator-stats` | Creator data overview (views, likes, collects, trends) |
| `opencli xiaohongshu notifications` | |
| `opencli xiaohongshu feed` | |
| `opencli xiaohongshu user` | |
| `opencli xiaohongshu download` | |
| `opencli xiaohongshu creator-notes` | |
| `opencli xiaohongshu creator-note-detail` | |
| `opencli xiaohongshu creator-notes-summary` | |
| `opencli xiaohongshu creator-profile` | |
| `opencli xiaohongshu creator-stats` | |
## Usage Examples
@@ -26,19 +23,13 @@
# Search for notes
opencli xiaohongshu search 美食 --limit 10
# Read a note's full content (pass URL from search results to preserve xsec_token)
opencli xiaohongshu note "https://www.xiaohongshu.com/search_result/<id>?xsec_token=..."
# Read comments with nested replies (楼中楼)
opencli xiaohongshu comments "https://www.xiaohongshu.com/search_result/<id>?xsec_token=..." --with-replies --limit 20
# JSON output
opencli xiaohongshu search 旅行 -f json
# Other commands
opencli xiaohongshu feed
opencli xiaohongshu notifications
opencli xiaohongshu download <note-id or url>
opencli xiaohongshu download <url>
```
## Prerequisites
+9 -32
View File
@@ -1,21 +1,18 @@
# Xueqiu (雪球)
**Mode**: 🔐 Browser · **Domain**: `xueqiu.com` / `danjuanfunds.com`
**Mode**: 🔐 Browser · **Domain**: `xueqiu.com`
## Commands
| Command | Description |
|---------|-------------|
| `opencli xueqiu feed` | 获取雪球首页时间线 |
| `opencli xueqiu earnings-date` | 获取股票预计财报发布日期 |
| `opencli xueqiu hot-stock` | 获取雪球热门股票榜 |
| `opencli xueqiu hot` | 获取雪球热门动态 |
| `opencli xueqiu search` | 搜索雪球股票(代码或名称) |
| `opencli xueqiu stock` | 获取雪球股票实时行情 |
| `opencli xueqiu comments` | 获取单只股票的讨论动态(按时间排序) |
| `opencli xueqiu watchlist` | 获取雪球自选股列表 |
| `opencli xueqiu fund-holdings` | 获取蛋卷基金持仓明细(可用 `--account` 按子账户过滤) |
| `opencli xueqiu fund-snapshot` | 获取蛋卷基金快照(总资产、子账户、持仓,推荐 `-f json` |
| `opencli xueqiu feed` | |
| `opencli xueqiu earnings-date` | |
| `opencli xueqiu hot-stock` | |
| `opencli xueqiu hot` | |
| `opencli xueqiu search` | |
| `opencli xueqiu stock` | |
| `opencli xueqiu watchlist` | |
## Usage Examples
@@ -29,21 +26,9 @@ opencli xueqiu search 茅台
# View one stock
opencli xueqiu stock SH600519
# View recent discussions for one stock
opencli xueqiu comments SH600519 --limit 5
# Upcoming earnings dates
opencli xueqiu earnings-date SH600519 --next
# Danjuan all holdings
opencli xueqiu fund-holdings
# Filter one Danjuan sub-account
opencli xueqiu fund-holdings --account 默认账户
# Full Danjuan snapshot as JSON
opencli xueqiu fund-snapshot -f json
# JSON output
opencli xueqiu feed -f json
@@ -53,13 +38,5 @@ opencli xueqiu feed -v
## Prerequisites
- Chrome running and **logged into** `xueqiu.com`
- For fund commands, Chrome must also be logged into `danjuanfunds.com` and able to open `https://danjuanfunds.com/my-money`
- Chrome running and **logged into** xueqiu.com
- [Browser Bridge extension](/guide/browser-bridge) installed
## Notes
- `fund-holdings` exposes both market value and share fields (`volume`, `usableRemainShare`)
- `fund-snapshot -f json` is the easiest way to persist a full account snapshot for later analysis or diffing
- `comments` returns stock-scoped discussion posts from the symbol page, not reply threads under one parent post
- If the commands return empty data, first confirm the logged-in browser can directly see the Danjuan asset page
-49
View File
@@ -1,49 +0,0 @@
# 知识星球 (ZSXQ)
**Mode**: 🔐 Browser · **Domain**: `wx.zsxq.com`
Read groups, topics, search results, dynamics, and single-topic details from [知识星球](https://wx.zsxq.com) using your logged-in Chrome session.
## Commands
| Command | Description |
|---------|-------------|
| `opencli zsxq groups` | List the groups your account has joined |
| `opencli zsxq topics` | List topics in the active group |
| `opencli zsxq topic <id>` | Fetch a single topic with comments |
| `opencli zsxq search <keyword>` | Search topics inside a group |
| `opencli zsxq dynamics` | List recent dynamics across groups |
## Usage Examples
```bash
# List your groups
opencli zsxq groups
# List topics from the active group in Chrome
opencli zsxq topics --limit 20
# Search inside the active group
opencli zsxq search "opencli"
# Search inside a specific group explicitly
opencli zsxq search "opencli" --group_id 123456789
# Export a single topic with comments
opencli zsxq topic 987654321 --comment_limit 20
# Read recent dynamics across all joined groups
opencli zsxq dynamics --limit 20
```
## Prerequisites
- Chrome running and **logged into** [wx.zsxq.com](https://wx.zsxq.com)
- [Browser Bridge extension](/guide/browser-bridge) installed
## Notes
- `zsxq topics` and `zsxq search` use the current active group context from Chrome by default
- If there is no active group context, pass `--group_id <id>` or open the target group in Chrome first
- `zsxq groups` returns `group_id`, which you can reuse with `--group_id`
- `zsxq topic` surfaces a missing topic as `NOT_FOUND` instead of a generic fetch error
-5
View File
@@ -14,13 +14,8 @@ The current built-in commands use native AppleScript automation — no extra lau
- `opencli chatgpt status`: Check if the ChatGPT app is currently running.
- `opencli chatgpt new`: Activate ChatGPT and press `Cmd+N` to start a new conversation.
- `opencli chatgpt send "message"`: Copy your message to clipboard, activate ChatGPT, paste, and submit.
- `opencli chatgpt send "message" --model thinking`: Switch model/mode first, then send the message.
- `opencli chatgpt read`: Read the last visible message from the focused ChatGPT window via the Accessibility tree.
- `opencli chatgpt ask "message"`: Send a prompt and wait for the visible reply in one shot.
- `opencli chatgpt ask "message" --model instant`: Run a one-shot prompt using a specific model/mode.
- `opencli chatgpt model thinking`: Switch the active ChatGPT model/mode without sending a message.
Supported model choices: `auto`, `instant`, `thinking`, `5.2-instant`, `5.2-thinking`.
## Approach 2: CDP (Advanced, Electron Debug Mode)
+53 -73
View File
@@ -6,86 +6,66 @@ Run `opencli list` for the live registry.
| Site | Commands | Mode |
|------|----------|------|
| **[twitter](./browser/twitter)** | `trending` `bookmarks` `profile` `search` `timeline` `thread` `following` `followers` `notifications` `post` `reply` `delete` `like` `likes` `article` `follow` `unfollow` `bookmark` `unbookmark` `download` `accept` `reply-dm` `block` `unblock` `hide-reply` | 🔐 Browser |
| **[reddit](./browser/reddit)** | `hot` `frontpage` `popular` `search` `subreddit` `read` `user` `user-posts` `user-comments` `upvote` `save` `comment` `subscribe` `saved` `upvoted` | 🔐 Browser |
| **[tieba](./browser/tieba)** | `hot` `posts` `search` `read` | 🔐 Browser |
| **[bilibili](./browser/bilibili)** | `hot` `search` `me` `favorite` `history` `feed` `subtitle` `dynamic` `ranking` `following` `user-videos` `download` | 🔐 Browser |
| **[zhihu](./browser/zhihu)** | `hot` `search` `question` `download` | 🔐 Browser |
| **[xiaohongshu](./browser/xiaohongshu)** | `search` `notifications` `feed` `user` `note` `comments` `download` `publish` `creator-notes` `creator-note-detail` `creator-notes-summary` `creator-profile` `creator-stats` | 🔐 Browser |
| **[xueqiu](./browser/xueqiu)** | `feed` `hot-stock` `hot` `search` `stock` `comments` `watchlist` `earnings-date` `fund-holdings` `fund-snapshot` | 🔐 Browser |
| **[youtube](./browser/youtube)** | `search` `video` `transcript` | 🔐 Browser |
| **[v2ex](./browser/v2ex)** | `hot` `latest` `topic` `node` `user` `member` `replies` `nodes` `daily` `me` `notifications` | 🌐 / 🔐 |
| **[bloomberg](./browser/bloomberg)** | `main` `markets` `economics` `industries` `tech` `politics` `businessweek` `opinions` `feeds` `news` | 🌐 / 🔐 |
| **[weibo](./browser/weibo)** | `hot` `search` `feed` `user` `me` `post` `comments` | 🔐 Browser |
| **[linkedin](./browser/linkedin)** | `search` `timeline` | 🔐 Browser |
| **[coupang](./browser/coupang)** | `search` `add-to-cart` | 🔐 Browser |
| **[boss](./browser/boss)** | `search` `detail` `recommend` `joblist` `greet` `batchgreet` `send` `chatlist` `chatmsg` `invite` `mark` `exchange` `resume` `stats` | 🔐 Browser |
| **[ctrip](./browser/ctrip)** | `search` | 🔐 Browser |
| **[reuters](./browser/reuters)** | `search` | 🔐 Browser |
| **[smzdm](./browser/smzdm)** | `search` | 🔐 Browser |
| **[jike](./browser/jike)** | `feed` `search` `post` `topic` `user` `create` `comment` `like` `repost` `notifications` | 🔐 Browser |
| **[jimeng](./browser/jimeng)** | `generate` `history` | 🔐 Browser |
| **[yollomi](./browser/yollomi)** | `generate` `video` `edit` `upload` `models` `remove-bg` `upscale` `face-swap` `restore` `try-on` `background` `object-remover` | 🔐 Browser |
| **[linux-do](./browser/linux-do)** | `hot` `latest` `feed` `search` `categories` `category` `tags` `topic` `user-posts` `user-topics` | 🔐 Browser |
| **[chaoxing](./browser/chaoxing)** | `assignments` `exams` | 🔐 Browser |
| **[grok](./browser/grok)** | `ask` | 🔐 Browser |
| **[gemini](./browser/gemini)** | `new` `ask` `image` | 🔐 Browser |
| **[notebooklm](./browser/notebooklm)** | `status` `list` `open` `select` `current` `get` `metadata` `source-list` `source-get` `source-fulltext` `source-guide` `history` `note-list` `notes-list` `notes-get` `summary` | 🔐 Browser |
| **[doubao](./browser/doubao)** | `status` `new` `send` `read` `ask` `history` `detail` `meeting-summary` `meeting-transcript` | 🔐 Browser |
| **[weread](./browser/weread)** | `shelf` `search` `book` `ranking` `notebooks` `highlights` `notes` | 🔐 Browser |
| **[douban](./browser/douban)** | `search` `top250` `subject` `photos` `download` `marks` `reviews` `movie-hot` `book-hot` | 🔐 Browser |
| **[facebook](./browser/facebook)** | `feed` `profile` `search` `friends` `groups` `events` `notifications` `memories` `add-friend` `join-group` | 🔐 Browser |
| **[imdb](./browser/imdb)** | `search` `title` `top` `trending` `person` `reviews` | 🌐 / 🔐 |
| **[instagram](./browser/instagram)** | `explore` `profile` `search` `user` `followers` `following` `follow` `unfollow` `like` `unlike` `comment` `save` `unsave` `saved` | 🔐 Browser |
| **[medium](./browser/medium)** | `feed` `search` `user` | 🔐 Browser |
| **[sinablog](./browser/sinablog)** | `hot` `search` `article` `user` | 🔐 Browser |
| **[substack](./browser/substack)** | `feed` `search` `publication` | 🔐 Browser |
| **[pixiv](./browser/pixiv)** | `ranking` `search` `user` `illusts` `detail` `download` | 🔐 Browser |
| **[tiktok](./browser/tiktok)** | `explore` `search` `profile` `user` `following` `follow` `unfollow` `like` `unlike` `comment` `save` `unsave` `live` `notifications` `friends` | 🔐 Browser |
| **[google](./browser/google)** | `news` `search` `suggest` `trends` | 🌐 / 🔐 |
| **[jd](./browser/jd)** | `item` | 🔐 Browser |
| **[amazon](./browser/amazon)** | `bestsellers` `search` `product` `offer` `discussion` | 🔐 Browser |
| **[web](./browser/web)** | `read` | 🔐 Browser |
| **[weixin](./browser/weixin)** | `download` | 🔐 Browser |
| **[36kr](./browser/36kr)** | `news` `hot` `search` `article` | 🌐 / 🔐 |
| **[producthunt](./browser/producthunt)** | `posts` `today` `hot` `browse` | 🌐 / 🔐 |
| **[ones](./browser/ones)** | `login` `me` `token-info` `tasks` `my-tasks` `task` `worklog` `logout` | 🔐 Browser Bridge + `ONES_BASE_URL` |
| **[band](./browser/band)** | `bands` `posts` `post` `mentions` | 🔐 Browser |
| **[zsxq](./browser/zsxq)** | `groups` `dynamics` `topics` `topic` `search` | 🔐 Browser |
| **[bluesky](./browser/bluesky)** | `search` `profile` `user` `feeds` `followers` `following` `thread` `trending` `starter-packs` | 🌐 Public |
| **[douyin](./browser/douyin)** | `profile` `videos` `user-videos` `activities` `collections` `hashtag` `location` `stats` `publish` `draft` `drafts` `delete` `update` | 🔐 Browser |
| **[twitter](/adapters/browser/twitter)** | `trending` `bookmarks` `profile` `search` `timeline` `thread` `following` `followers` `notifications` `post` `reply` `delete` `like` `article` `follow` `unfollow` `bookmark` `unbookmark` `download` `accept` `reply-dm` `block` `unblock` `hide-reply` | 🔐 Browser |
| **[reddit](/adapters/browser/reddit)** | `hot` `frontpage` `popular` `search` `subreddit` `read` `user` `user-posts` `user-comments` `upvote` `save` `comment` `subscribe` `saved` `upvoted` | 🔐 Browser |
| **[bilibili](/adapters/browser/bilibili)** | `hot` `search` `me` `favorite` `history` `feed` `subtitle` `dynamic` `ranking` `following` `user-videos` `download` | 🔐 Browser |
| **[zhihu](/adapters/browser/zhihu)** | `hot` `search` `question` `download` | 🔐 Browser |
| **[xiaohongshu](/adapters/browser/xiaohongshu)** | `search` `notifications` `feed` `user` `download` `publish` `creator-notes` `creator-note-detail` `creator-notes-summary` `creator-profile` `creator-stats` | 🔐 Browser |
| **[xueqiu](/adapters/browser/xueqiu)** | `feed` `hot-stock` `hot` `search` `stock` `watchlist` `earnings-date` | 🔐 Browser |
| **[youtube](/adapters/browser/youtube)** | `search` `video` `transcript` | 🔐 Browser |
| **[v2ex](/adapters/browser/v2ex)** | `hot` `latest` `topic` `node` `user` `member` `replies` `nodes` `daily` `me` `notifications` | 🌐 / 🔐 |
| **[bloomberg](/adapters/browser/bloomberg)** | `main` `markets` `economics` `industries` `tech` `politics` `businessweek` `opinions` `feeds` `news` | 🌐 / 🔐 |
| **[weibo](/adapters/browser/weibo)** | `hot` `search` | 🔐 Browser |
| **[linkedin](/adapters/browser/linkedin)** | `search` `timeline` | 🔐 Browser |
| **[coupang](/adapters/browser/coupang)** | `search` `add-to-cart` | 🔐 Browser |
| **[boss](/adapters/browser/boss)** | `search` `detail` `recommend` `joblist` `greet` `batchgreet` `send` `chatlist` `chatmsg` `invite` `mark` `exchange` `resume` `stats` | 🔐 Browser |
| **[ctrip](/adapters/browser/ctrip)** | `search` | 🔐 Browser |
| **[reuters](/adapters/browser/reuters)** | `search` | 🔐 Browser |
| **[smzdm](/adapters/browser/smzdm)** | `search` | 🔐 Browser |
| **[jike](/adapters/browser/jike)** | `feed` `search` `post` `topic` `user` `create` `comment` `like` `repost` `notifications` | 🔐 Browser |
| **[jimeng](/adapters/browser/jimeng)** | `generate` `history` | 🔐 Browser |
| **[yollomi](/adapters/browser/yollomi)** | `generate` `video` `edit` `upload` `models` `remove-bg` `upscale` `face-swap` `restore` `try-on` `background` `object-remover` | 🔐 Browser |
| **[linux-do](/adapters/browser/linux-do)** | `hot` `latest` `categories` `category` `search` `topic` | 🔐 Browser |
| **[chaoxing](/adapters/browser/chaoxing)** | `assignments` `exams` | 🔐 Browser |
| **[grok](/adapters/browser/grok)** | `ask` | 🔐 Browser |
| **[doubao](/adapters/browser/doubao)** | `status` `new` `send` `read` `ask` | 🔐 Browser |
| **[weread](/adapters/browser/weread)** | `shelf` `search` `book` `ranking` `notebooks` `highlights` `notes` | 🔐 Browser |
| **[douban](/adapters/browser/douban)** | `search` `top250` `subject` `marks` `reviews` `movie-hot` `book-hot` | 🔐 Browser |
| **[facebook](/adapters/browser/facebook)** | `feed` `profile` `search` `friends` `groups` `events` `notifications` `memories` `add-friend` `join-group` | 🔐 Browser |
| **[instagram](/adapters/browser/instagram)** | `explore` `profile` `search` `user` `followers` `following` `follow` `unfollow` `like` `unlike` `comment` `save` `unsave` `saved` | 🔐 Browser |
| **[medium](/adapters/browser/medium)** | `feed` `search` `user` | 🔐 Browser |
| **[sinablog](/adapters/browser/sinablog)** | `hot` `search` `article` `user` | 🔐 Browser |
| **[substack](/adapters/browser/substack)** | `feed` `search` `publication` | 🔐 Browser |
| **[tiktok](/adapters/browser/tiktok)** | `explore` `search` `profile` `user` `following` `follow` `unfollow` `like` `unlike` `comment` `save` `unsave` `live` `notifications` `friends` | 🔐 Browser |
## Public API Adapters
| Site | Commands | Mode |
|------|----------|------|
| **[hackernews](./browser/hackernews)** | `top` `new` `best` `ask` `show` `jobs` `search` `user` | 🌐 Public |
| **[bbc](./browser/bbc)** | `news` | 🌐 Public |
| **[devto](./browser/devto)** | `top` `tag` `user` | 🌐 Public |
| **[dictionary](./browser/dictionary)** | `search` `synonyms` `examples` | 🌐 Public |
| **[apple-podcasts](./browser/apple-podcasts)** | `search` `episodes` `top` | 🌐 Public |
| **[xiaoyuzhou](./browser/xiaoyuzhou)** | `podcast` `podcast-episodes` `episode` | 🌐 Public |
| **[yahoo-finance](./browser/yahoo-finance)** | `quote` | 🌐 Public |
| **[arxiv](./browser/arxiv)** | `search` `paper` | 🌐 Public |
| **[paperreview](./browser/paperreview)** | `submit` `review` `feedback` | 🌐 Public |
| **[barchart](./browser/barchart)** | `quote` `options` `greeks` `flow` | 🌐 Public |
| **[hf](./browser/hf)** | `top` | 🌐 Public |
| **[sinafinance](./browser/sinafinance)** | `news` | 🌐 Public |
| **[spotify](./browser/spotify)** | `auth` `status` `play` `pause` `next` `prev` `volume` `search` `queue` `shuffle` `repeat` | 🔑 OAuth API |
| **[stackoverflow](./browser/stackoverflow)** | `hot` `search` `bounties` `unanswered` | 🌐 Public |
| **[wikipedia](./browser/wikipedia)** | `search` `summary` `random` `trending` | 🌐 Public |
| **[lobsters](./browser/lobsters)** | `hot` `newest` `active` `tag` | 🌐 Public |
| **[steam](./browser/steam)** | `top-sellers` | 🌐 Public |
| **[hackernews](/adapters/browser/hackernews)** | `top` `new` `best` `ask` `show` `jobs` `search` `user` | 🌐 Public |
| **[bbc](/adapters/browser/bbc)** | `news` | 🌐 Public |
| **[devto](/adapters/browser/devto)** | `top` `tag` `user` | 🌐 Public |
| **[dictionary](/adapters/browser/dictionary)** | `search` `synonyms` `examples` | 🌐 Public |
| **[apple-podcasts](/adapters/browser/apple-podcasts)** | `search` `episodes` `top` | 🌐 Public |
| **[xiaoyuzhou](/adapters/browser/xiaoyuzhou)** | `podcast` `podcast-episodes` `episode` | 🌐 Public |
| **[yahoo-finance](/adapters/browser/yahoo-finance)** | `quote` | 🌐 Public |
| **[arxiv](/adapters/browser/arxiv)** | `search` `paper` | 🌐 Public |
| **[barchart](/adapters/browser/barchart)** | `quote` `options` `greeks` `flow` | 🌐 Public |
| **[hf](/adapters/browser/hf)** | `top` | 🌐 Public |
| **[sinafinance](/adapters/browser/sinafinance)** | `news` | 🌐 Public |
| **[stackoverflow](/adapters/browser/stackoverflow)** | `hot` `search` `bounties` `unanswered` | 🌐 Public |
| **[wikipedia](/adapters/browser/wikipedia)** | `search` `summary` `random` `trending` | 🌐 Public |
| **[lobsters](/adapters/browser/lobsters)** | `hot` `newest` `active` `tag` | 🌐 Public |
## Desktop Adapters
| App | Description | Commands |
|-----|-------------|----------|
| **[Cursor](./desktop/cursor)** | Control Cursor IDE | `status` `send` `read` `new` `dump` `composer` `model` `extract-code` `ask` `screenshot` `history` `export` |
| **[Codex](./desktop/codex)** | Drive OpenAI Codex CLI agent | `status` `send` `read` `new` `extract-diff` `model` `ask` `screenshot` `history` `export` |
| **[Antigravity](./desktop/antigravity)** | Control Antigravity Ultra | `status` `send` `read` `new` `dump` `extract-code` `model` `watch` |
| **[ChatGPT](./desktop/chatgpt)** | Automate ChatGPT macOS app | `status` `new` `send` `read` `ask` `model` |
| **[ChatWise](./desktop/chatwise)** | Multi-LLM client | `status` `new` `send` `read` `ask` `model` `history` `export` `screenshot` |
| **[Notion](./desktop/notion)** | Search, read, write pages | `status` `search` `read` `new` `write` `sidebar` `favorites` `export` |
| **[Discord](./desktop/discord)** | Desktop messages & channels | `status` `send` `read` `channels` `servers` `search` `members` |
| **[Doubao App](./desktop/doubao-app)** | Doubao AI desktop app via CDP | `status` `new` `send` `read` `ask` `screenshot` `dump` |
| **[Cursor](/adapters/desktop/cursor)** | Control Cursor IDE | `status` `send` `read` `new` `dump` `composer` `model` `extract-code` `ask` `screenshot` `history` `export` |
| **[Codex](/adapters/desktop/codex)** | Drive OpenAI Codex CLI agent | `status` `send` `read` `new` `extract-diff` `model` `ask` `screenshot` `history` `export` |
| **[Antigravity](/adapters/desktop/antigravity)** | Control Antigravity Ultra | `status` `send` `read` `new` `dump` `extract-code` `model` `watch` |
| **[ChatGPT](/adapters/desktop/chatgpt)** | Automate ChatGPT macOS app | `status` `new` `send` `read` `ask` |
| **[ChatWise](/adapters/desktop/chatwise)** | Multi-LLM client | `status` `new` `send` `read` `ask` `model` `history` `export` `screenshot` |
| **[Notion](/adapters/desktop/notion)** | Search, read, write pages | `status` `search` `read` `new` `write` `sidebar` `favorites` `export` |
| **[Discord](/adapters/desktop/discord)** | Desktop messages & channels | `status` `send` `read` `channels` `servers` `search` `members` |
| **[Doubao App](/adapters/desktop/doubao-app)** | Doubao AI desktop app via CDP | `status` `new` `send` `read` `ask` `screenshot` `dump` |
-4
View File
@@ -9,7 +9,6 @@ OpenCLI supports downloading images, videos, and articles from supported platfor
| **xiaohongshu** | Images, Videos | Downloads all media from a note |
| **bilibili** | Videos | Requires `yt-dlp` installed |
| **twitter** | Images, Videos | Downloads from user media tab or single tweet |
| **douban** | Images | Downloads poster / still image lists from movie subjects |
| **zhihu** | Articles (Markdown) | Exports articles with optional image download |
| **weixin** | Articles (Markdown) | Exports WeChat Official Account articles |
@@ -40,9 +39,6 @@ opencli twitter download elonmusk --limit 20 --output ./twitter
# Download single tweet media
opencli twitter download --tweet-url "https://x.com/user/status/123" --output ./twitter
# Download Douban posters / stills
opencli douban download 30382501 --output ./douban
# Export Zhihu article to Markdown
opencli zhihu download "https://zhuanlan.zhihu.com/p/xxx" --output ./zhihu
-99
View File
@@ -1,99 +0,0 @@
# Rate Limiter Plugin
An optional plugin that adds a random sleep between browser-based commands to reduce the risk of platform rate-limiting or bot detection.
## Install
```bash
opencli plugin install github:jackwener/opencli-plugin-rate-limiter
```
Or copy the example below into `~/.opencli/plugins/rate-limiter/` to use it locally without installing from GitHub.
## What it does
After every command targeting a browser platform (xiaohongshu, weibo, bilibili, douyin, tiktok, …), the plugin sleeps for a random duration — 530 seconds by default — before returning control to the caller.
## Configuration
| Variable | Default | Description |
|---|---|---|
| `OPENCLI_RATE_MIN` | `5` | Minimum sleep in seconds |
| `OPENCLI_RATE_MAX` | `30` | Maximum sleep in seconds |
| `OPENCLI_NO_RATE` | — | Set to `1` to disable entirely (local dev) |
```bash
# Shorter delays for light scraping
OPENCLI_RATE_MIN=3 OPENCLI_RATE_MAX=10 opencli xiaohongshu search "AI眼镜"
# Skip delays when iterating locally
OPENCLI_NO_RATE=1 opencli bilibili comments BV1WtAGzYEBm
```
## Local installation (without GitHub)
1. Create the plugin directory:
```bash
mkdir -p ~/.opencli/plugins/rate-limiter
```
2. Create `~/.opencli/plugins/rate-limiter/package.json`:
```json
{ "type": "module" }
```
3. Create `~/.opencli/plugins/rate-limiter/index.js`:
```js
import { onAfterExecute } from '@jackwener/opencli/hooks'
const BROWSER_DOMAINS = [
'xiaohongshu', 'weibo', 'bilibili', 'douyin', 'tiktok',
'instagram', 'twitter', 'youtube', 'zhihu', 'douban',
'jike', 'weixin', 'xiaoyuzhou',
]
onAfterExecute(async (ctx) => {
if (process.env.OPENCLI_NO_RATE === '1') return
const site = ctx.command?.split('/')?.[0] ?? ''
if (!BROWSER_DOMAINS.includes(site)) return
const min = Number(process.env.OPENCLI_RATE_MIN ?? 5)
const max = Number(process.env.OPENCLI_RATE_MAX ?? 30)
const ms = Math.floor(Math.random() * (max - min + 1) + min) * 1000
process.stderr.write(`[rate-limiter] ${site}: sleeping ${(ms / 1000).toFixed(0)}s\n`)
await new Promise(r => setTimeout(r, ms))
})
```
4. Verify it loaded:
```bash
OPENCLI_NO_RATE=1 opencli xiaohongshu search "test" 2>&1 | grep rate-limiter
# → (no output — plugin loaded but rate limit skipped)
opencli xiaohongshu search "test" 2>&1 | grep rate-limiter
# → [rate-limiter] xiaohongshu: sleeping 12s
```
## Writing your own plugin
Plugins are plain JS/TS files in `~/.opencli/plugins/<name>/`. A plugin file must export a hook registration call that matches the pattern `onStartup(`, `onBeforeExecute(`, or `onAfterExecute(` — opencli's discovery engine uses this pattern to identify hook files vs. command files.
```js
// ~/.opencli/plugins/my-plugin/index.js
import { onAfterExecute } from '@jackwener/opencli/hooks'
onAfterExecute(async (ctx) => {
// ctx.command — e.g. "bilibili/comments"
// ctx.args — coerced command arguments
// ctx.error — set if the command threw
console.error(`[my-plugin] finished: ${ctx.command}`)
})
```
See [hooks.ts](../../src/hooks.ts) for the full `HookContext` type.
+1 -1
View File
@@ -87,7 +87,7 @@ OpenCLI occupies a specific niche in the browser automation ecosystem. This guid
- **Zero LLM cost** — No tokens consumed at runtime. Run 10,000 times for free.
- **Deterministic output** — Same command always returns the same schema. Pipeable, scriptable, CI-friendly.
- **Speed** — Adapter commands return in seconds, not minutes.
- **Broad platform coverage** — 73+ sites spanning global platforms (Reddit, HackerNews, Twitter, YouTube) and Chinese platforms (Bilibili, Zhihu, Xiaohongshu, Douban, Weibo) with adapters that understand local anti-bot patterns.
- **Broad platform coverage** — 50+ sites spanning global platforms (Reddit, HackerNews, Twitter, YouTube) and Chinese platforms (Bilibili, Zhihu, Xiaohongshu, Douban, Weibo) with adapters that understand local anti-bot patterns.
- **Desktop app control** — CDP adapters for Cursor, Codex, Notion, ChatGPT, Discord, and more.
- **Easy to extend** — Drop a `.yaml` or `.ts` adapter into the `clis/` folder for auto-registration. Contributing a new site adapter is straightforward.
+1 -18
View File
@@ -28,12 +28,6 @@ npm link
This is the most common type of contribution. Start with YAML when possible, and use TypeScript only when you need browser-side logic or multi-step flows.
Before you start:
- Prefer positional args for the command's primary subject (`search <query>`, `topic <id>`, `download <url>`). Reserve named flags for optional modifiers such as `--limit`, `--sort`, `--lang`, and `--output`.
- Normalize expected adapter failures to `CliError` subclasses instead of raw `Error` whenever possible. Prefer `AuthRequiredError`, `EmptyResultError`, `CommandExecutionError`, `TimeoutError`, and `ArgumentError` so the top-level CLI can render better messages and hints.
- If you add a new adapter or make a command newly discoverable, update the matching doc page and the user-facing indexes that expose it.
### YAML Adapter (Recommended for data-fetching commands)
Create a file like `src/clis/<site>/<command>.yaml`:
@@ -77,7 +71,6 @@ Create a file like `src/clis/<site>/<command>.ts`:
```typescript
import { cli, Strategy } from '../../registry.js';
import { CommandExecutionError, EmptyResultError } from '../../errors.js';
cli({
site: 'mysite',
@@ -86,7 +79,7 @@ cli({
domain: 'www.mysite.com',
strategy: Strategy.COOKIE,
args: [
{ name: 'query', positional: true, required: true, help: 'Search query' },
{ name: 'query', required: true, help: 'Search query' },
{ name: 'limit', type: 'int', default: 10, help: 'Max results' },
],
columns: ['title', 'url', 'date'],
@@ -94,8 +87,6 @@ cli({
func: async (page, kwargs) => {
const { query, limit = 10 } = kwargs;
// ... browser automation logic
if (!Array.isArray(data)) throw new CommandExecutionError('MySite returned an unexpected response');
if (!data.length) throw new EmptyResultError('mysite search', 'Try a different keyword');
return data.slice(0, Number(limit)).map((item: any) => ({
title: item.title,
url: item.url,
@@ -119,7 +110,6 @@ opencli <site> <command> -v # Verbose mode for debugging
- **ES Modules** — use `.js` extensions in imports (TypeScript output).
- **Naming**: `kebab-case` for files, `camelCase` for variables/functions, `PascalCase` for types/classes.
- **No default exports** — use named exports.
- **Errors** — throw `CliError` subclasses for expected adapter failures; avoid raw `Error` for normal adapter control flow.
## Commit Convention
@@ -146,10 +136,3 @@ chore: bump vitest to v4
```
4. Commit using conventional commit format
5. Push and open a PR
If your PR adds a new adapter or changes user-facing commands, also verify:
- Adapter docs exist under `docs/adapters/`
- `docs/adapters/index.md` is updated for new adapters
- VitePress sidebar includes the new doc page
- `README.md` / `README.zh-CN.md` stay aligned when command discoverability changes
-18
View File
@@ -6,7 +6,6 @@ Use TypeScript adapters when you need browser-side logic, multi-step flows, DOM
```typescript
import { cli, Strategy } from '../../registry.js';
import { CommandExecutionError, EmptyResultError } from '../../errors.js';
cli({
site: 'mysite',
@@ -35,9 +34,6 @@ cli({
})()
`);
if (!Array.isArray(data)) throw new CommandExecutionError('MySite returned an unexpected response');
if (!data.length) throw new EmptyResultError('mysite search', 'Try a different keyword');
return data.slice(0, Number(limit)).map((item: any) => ({
title: item.title,
url: item.url,
@@ -73,20 +69,6 @@ Contains parsed CLI arguments as key-value pairs. Always destructure with defaul
const { query, limit = 10, format = 'json' } = kwargs;
```
For most search/read/detail commands, the main subject should be positional (`opencli mysite search "rust"`, `opencli mysite article 123`) instead of a named flag such as `--query` or `--id`. Keep named flags for optional modifiers.
## Error Handling
Prefer throwing `CliError` subclasses from `src/errors.ts` for expected adapter failures:
- `AuthRequiredError` for missing login / cookies
- `EmptyResultError` for empty but valid responses
- `CommandExecutionError` for unexpected API or browser failures
- `TimeoutError` for site timeouts
- `ArgumentError` for invalid user input
Avoid raw `Error` for normal adapter control flow. This keeps top-level CLI output consistent and preserves hints for users.
## AI-Assisted Development
Use the AI workflow tools to accelerate adapter creation:
-16
View File
@@ -2,8 +2,6 @@
YAML adapters are the recommended way to add new commands when the site offers a straightforward API. They use a declarative pipeline approach — no TypeScript required.
Use YAML only when the command stays mostly declarative. If you find yourself embedding long JavaScript expressions, many fallbacks, or multi-step browser logic, move the command to a TypeScript adapter instead of growing an opaque template blob.
## Basic Structure
::: v-pre
@@ -35,14 +33,6 @@ columns: [rank, title, score, url]
```
:::
For most commands, keep the primary subject positional. Good examples:
- `opencli mysite search "rust"`
- `opencli mysite topic 123`
- `opencli mysite download "https://example.com/post/1"`
Prefer named flags only for optional modifiers such as `--limit`, `--sort`, `--lang`, or `--output`.
## Pipeline Steps
### `fetch`
@@ -116,9 +106,3 @@ Use `${{ ... }}` for dynamic values:
## Real Example
See [`src/clis/hackernews/top.yaml`](https://github.com/jackwener/opencli/blob/main/src/clis/hackernews/top.yaml).
## Guardrails
- Add fallbacks for optional fields in `map` expressions when upstream payloads may be sparse.
- Keep template expressions short and readable. If the expression starts looking like a mini program, switch to TypeScript.
- If you add a new adapter, also add the matching doc page plus index/sidebar entries so `doc-coverage` stays green.
-12
View File
@@ -35,15 +35,3 @@ opencli doctor # Check extension + daemon connectivity
```
The daemon manages the WebSocket connection between your CLI commands and the Chrome extension. The extension executes JavaScript in the context of web pages, with access to the logged-in session.
## Daemon Lifecycle
The daemon auto-starts on first browser command and stays alive for **4 hours** by default. It exits only when both conditions are met: no CLI requests for the timeout period AND no Chrome extension connected.
```bash
opencli daemon status # Check daemon state (PID, uptime, extension, memory)
opencli daemon stop # Graceful shutdown
opencli daemon restart # Stop + restart
```
Override the timeout via the `OPENCLI_DAEMON_TIMEOUT` environment variable (milliseconds). Set to `0` to keep the daemon alive indefinitely.
-200
View File
@@ -1,200 +0,0 @@
---
description: How to turn a new Electron desktop app into an OpenCLI adapter
---
# Add a New Electron App CLI
This guide is the **fast entry point** for turning a new Electron desktop application into an OpenCLI adapter.
If you want the full background and deeper SOP, read:
- [CLI-ifying Electron Applications](/advanced/electron)
- [Chrome DevTools Protocol](/advanced/cdp)
- [TypeScript Adapter Guide](/developer/ts-adapter)
## When to use this guide
Use this workflow when the target app:
- is built with **Electron**, or at least exposes a working **Chrome DevTools Protocol (CDP)** endpoint
- can be launched with `--remote-debugging-port=<port>`
- should be automated through its real UI instead of a public HTTP API
If the app is **not** Electron and does **not** expose CDP, use the native desktop automation pattern instead. See [CLI-ifying Electron Applications](/advanced/electron#non-electron-pattern-applescript).
## The shortest path
### 1. Confirm the app is Electron
Typical macOS check:
```bash
ls /Applications/AppName.app/Contents/Frameworks/Electron\ Framework.framework
```
If Electron is present, the next step is usually to launch the app with a debugging port.
### 2. Launch it with CDP enabled
```bash
/Applications/AppName.app/Contents/MacOS/AppName --remote-debugging-port=9222
```
Then point OpenCLI at that CDP endpoint:
```bash
export OPENCLI_CDP_ENDPOINT="http://127.0.0.1:9222"
```
### 3. Start with the 5-command pattern
For a new Electron adapter, implement these commands first in `src/clis/<app>/`:
- `status.ts` — verify the app is reachable through CDP
- `dump.ts` — inspect DOM and snapshot structure before guessing selectors
- `read.ts` — extract the visible context you actually need
- `send.ts` — inject text and submit through the real editor
- `new.ts` — create a new session, tab, thread, or document
This is the standard baseline because it gives you:
- a connection check
- a reverse-engineering tool
- one read path
- one write path
- one session reset path
The full rationale and examples are in [CLI-ifying Electron Applications](/advanced/electron).
## Recommended implementation workflow
### Step 1: Build `status`
Goal: prove CDP connectivity before touching app-specific logic.
Typical checks:
- current URL
- document title
- app shell presence
If `status` is unstable, stop there and fix connectivity first.
### Step 2: Build `dump`
Do **not** guess selectors from the rendered UI.
Dump:
- `document.body.innerHTML`
- accessibility snapshot
- any stable attributes such as `data-testid`, `role`, `aria-*`, framework-specific markers
Use the dump to identify real containers, buttons, composers, and conversation regions.
### Step 3: Build `read`
Target only the app region that matters.
Good targets:
- message list
- editor history
- visible thread content
- selected document panel
Avoid dumping the entire page text into the final command output.
### Step 4: Build `send`
Most Electron apps use React-style controlled editors, so direct `.value = ...` assignments are often ignored.
Prefer editor-aware input patterns such as:
- focus the editable region
- use `document.execCommand('insertText', false, text)` when applicable
- use real key presses like `Enter`, `Meta+Enter`, or app-specific shortcuts
### Step 5: Build `new`
Many desktop apps rely on keyboard shortcuts for “new chat”, “new tab”, or “new note”.
Typical pattern:
```ts
const isMac = process.platform === 'darwin';
await page.pressKey(isMac ? 'Meta+N' : 'Control+N');
await page.wait(1);
```
## Where to put files
For a TypeScript desktop adapter, the usual layout is:
```text
src/clis/<app>/status.ts
src/clis/<app>/dump.ts
src/clis/<app>/read.ts
src/clis/<app>/send.ts
src/clis/<app>/new.ts
src/clis/<app>/utils.ts
```
If the app grows beyond the baseline, add higher-level commands such as:
- `ask`
- `history`
- `model`
- `screenshot`
- `export`
## What to document when you add a new app
When the adapter is ready, also add:
- an adapter doc under `docs/adapters/desktop/`
- command list and examples
- launch instructions with `--remote-debugging-port`
- any required environment variables
- platform-specific caveats
Examples to study:
- `docs/adapters/desktop/codex.md`
- `docs/adapters/desktop/chatwise.md`
- `docs/adapters/desktop/notion.md`
- `docs/adapters/desktop/discord.md`
## Common failure modes
### CDP endpoint exists, but commands are flaky
Usually one of these:
- the wrong window/tab is selected
- the app has not finished rendering
- selectors were guessed instead of discovered from `dump`
- the editor is controlled and ignores direct value assignment
### The app is Chromium-based but not truly controllable
Some desktop apps embed Chromium but do not expose a usable CDP surface.
In that case, switch to the non-Electron desktop automation approach instead of forcing the Electron pattern.
### You already have a browser workflow and wonder whether to reuse it
If the app exposes a normal web URL and the browser flow is enough, a browser adapter is usually simpler.
Use an Electron adapter only when the desktop app is the real integration surface.
## Recommended reading order
If you are starting from zero:
1. This page
2. [CLI-ifying Electron Applications](/advanced/electron)
3. [Chrome DevTools Protocol](/advanced/cdp)
4. [TypeScript Adapter Guide](/developer/ts-adapter)
5. One concrete desktop adapter doc under `docs/adapters/desktop/`
## Practical rule
Do not start with a large feature surface.
Start with:
- `status`
- `dump`
- `read`
- `send`
- `new`
Once those are stable, extend outward.
-22
View File
@@ -48,27 +48,6 @@ opencli bilibili hot -f csv # CSV
opencli bilibili hot -v # Verbose: show pipeline debug
```
### Tab Completion
OpenCLI supports intelligent tab completion to speed up command input:
```bash
# Add shell completion to your startup config
echo 'eval "$(opencli completion zsh)"' >> ~/.zshrc # Zsh
echo 'eval "$(opencli completion bash)"' >> ~/.bashrc # Bash
echo 'opencli completion fish | source' >> ~/.config/fish/config.fish # Fish
# Restart your shell, then press Tab to complete:
opencli [Tab] # Complete site names (bilibili, zhihu, twitter...)
opencli bilibili [Tab] # Complete commands (hot, search, me, download...)
```
The completion includes:
- All available sites and adapters
- Built-in commands (list, explore, validate...)
- Command aliases
- Real-time updates as you add new adapters
## Next Steps
- [Installation details](/guide/installation)
@@ -76,4 +55,3 @@ The completion includes:
- [Plugins — extend with community adapters](/guide/plugins)
- [All available adapters](/adapters/)
- [For developers / AI agents](/developer/contributing)
- [Add a new Electron app CLI](/guide/electron-app-cli)
-107
View File
@@ -11,12 +11,6 @@ opencli plugin install github:ByteYue/opencli-plugin-github-trending
# List installed plugins
opencli plugin list
# Update one plugin
opencli plugin update github-trending
# Update all installed plugins
opencli plugin update --all
# Use the plugin (it's just a regular command)
opencli github-trending repos --limit 10
@@ -31,113 +25,12 @@ Plugins live in `~/.opencli/plugins/<name>/`. Each subdirectory is scanned at st
### Supported Source Formats
```bash
# GitHub shorthand
opencli plugin install github:user/repo
opencli plugin install github:user/repo/subplugin # install specific sub-plugin from monorepo
opencli plugin install https://github.com/user/repo
# Any git-cloneable URL
opencli plugin install https://gitlab.example.com/team/repo.git
opencli plugin install ssh://git@gitlab.example.com/team/repo.git
opencli plugin install git@gitlab.example.com:team/repo.git
# Local plugin (for development)
opencli plugin install file:///path/to/plugin
opencli plugin install /path/to/plugin
```
The repo name prefix `opencli-plugin-` is automatically stripped for the local directory name. For example, `opencli-plugin-hot-digest` becomes `hot-digest`.
## Plugin Manifest (`opencli-plugin.json`)
Plugins can include an `opencli-plugin.json` manifest file at the repo root to declare metadata:
```json
{
"name": "my-plugin",
"version": "1.0.0",
"opencli": ">=1.0.0",
"description": "My awesome plugin"
}
```
| Field | Description |
|-------|-------------|
| `name` | Plugin name (overrides repo-derived name) |
| `version` | Semantic version |
| `opencli` | Required opencli version range (e.g. `>=1.0.0`, `^1.2.0`) |
| `description` | Human-readable description |
| `plugins` | Monorepo sub-plugin declarations (see below) |
The manifest is optional — plugins without one continue to work exactly as before.
## Monorepo Plugins
A single repository can contain multiple plugins by declaring a `plugins` field in `opencli-plugin.json`:
```json
{
"version": "1.0.0",
"opencli": ">=1.0.0",
"description": "My plugin collection",
"plugins": {
"polymarket": {
"path": "packages/polymarket",
"description": "Prediction market analysis",
"version": "1.2.0"
},
"defi": {
"path": "packages/defi",
"description": "DeFi protocol data",
"version": "0.8.0",
"opencli": ">=1.2.0"
},
"experimental": {
"path": "packages/experimental",
"disabled": true
}
}
}
```
### Installing
```bash
# Install ALL enabled sub-plugins from a monorepo
opencli plugin install github:user/opencli-plugins
# Install a SPECIFIC sub-plugin
opencli plugin install github:user/opencli-plugins/polymarket
```
### How It Works
- The monorepo is cloned once to `~/.opencli/monorepos/<repo>/`
- Each sub-plugin gets a symlink in `~/.opencli/plugins/<name>/` pointing to its subdirectory
- Command discovery works transparently — symlinks are scanned just like regular directories
- Disabled sub-plugins (with `"disabled": true`) are skipped during install
- Sub-plugins can specify their own `opencli` compatibility range
### Updating
Updating any sub-plugin from a monorepo pulls the entire repo and refreshes all sub-plugins:
```bash
opencli plugin update polymarket # updates the monorepo, refreshes all
```
### Uninstalling
```bash
opencli plugin uninstall polymarket # removes just this sub-plugin's symlink
```
When the last sub-plugin from a monorepo is uninstalled, the monorepo clone is automatically cleaned up.
## Version Tracking
OpenCLI records installed plugin versions in `~/.opencli/plugins.lock.json`. Each entry stores the plugin source, current git commit hash, install time, and last update time. `opencli plugin list` shows the short commit hash when version metadata is available.
## Creating a Plugin
### Option 1: YAML Plugin (Simplest)
+4 -9
View File
@@ -20,22 +20,17 @@
### Daemon issues
```bash
# Check daemon status (PID, uptime, extension connection, memory)
opencli daemon status
# Check daemon status
curl localhost:19825/status
# View extension logs
curl localhost:19825/logs
# Stop or restart the daemon
opencli daemon stop
opencli daemon restart
# Full diagnostics
# Kill and restart daemon
pkill -f opencli-daemon
opencli doctor
```
> The daemon auto-exits after 4 hours of inactivity (no CLI requests and no extension connection). Override with `OPENCLI_DAEMON_TIMEOUT` (milliseconds, `0` = never timeout).
### Desktop adapter connection issues
For Electron/CDP-based adapters (Cursor, Codex, etc.):
File diff suppressed because it is too large Load Diff
@@ -1,857 +0,0 @@
# Daemon Lifecycle Redesign Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Replace the daemon's aggressive 5-minute idle timeout with a long-lived model (4h default) that requires both CLI inactivity AND Extension disconnection before exiting, plus add `daemon status/stop/restart` CLI commands.
**Architecture:** The daemon keeps its existing HTTP + WebSocket bridge architecture. We change the idle timeout logic to track two independent activity signals (CLI requests and Extension connection), add `/status` and `/shutdown` HTTP endpoints, reduce the Extension reconnect backoff cap, and register new CLI commands via Commander.js.
**Tech Stack:** Node.js, TypeScript, Commander.js, ws, Vitest
---
## File Structure
| File | Action | Responsibility |
|------|--------|----------------|
| `src/constants.ts` | Modify | Add `DEFAULT_DAEMON_IDLE_TIMEOUT` constant |
| `src/daemon.ts` | Modify | Dual-condition idle timer, `/status` endpoint, `/shutdown` endpoint |
| `src/daemon.test.ts` | Create | Unit tests for idle timer logic, `/status`, `/shutdown` |
| `extension/src/protocol.ts` | Modify | Change `WS_RECONNECT_MAX_DELAY` from 60000 to 5000 |
| `src/cli.ts` | Modify | Register `daemon` subcommand group |
| `src/commands/daemon.ts` | Create | `status`, `stop`, `restart` subcommand implementations |
| `src/commands/daemon.test.ts` | Create | Unit tests for daemon commands |
| `src/browser/mcp.ts` | Modify | Better connection-waiting UX messages, 200ms poll interval |
---
### Task 1: Add `DEFAULT_DAEMON_IDLE_TIMEOUT` constant
**Files:**
- Modify: `src/constants.ts`
- [ ] **Step 1: Add the constant**
In `src/constants.ts`, add after the `DEFAULT_DAEMON_PORT` line:
```typescript
/** Default idle timeout before daemon auto-exits (ms). Override via OPENCLI_DAEMON_TIMEOUT env var. */
export const DEFAULT_DAEMON_IDLE_TIMEOUT = 4 * 60 * 60 * 1000; // 4 hours
```
- [ ] **Step 2: Commit**
```bash
git add src/constants.ts
git commit -m "feat(daemon): add DEFAULT_DAEMON_IDLE_TIMEOUT constant (4 hours)"
```
---
### Task 2: Implement dual-condition idle timer in daemon
**Files:**
- Modify: `src/daemon.ts:27,29-57,116-123,196-198,245-262,265-269`
- Test: `src/daemon.test.ts` (create)
- [ ] **Step 1: Write failing tests for the new idle timer logic**
Create `src/daemon.test.ts`:
```typescript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// We test the idle timer logic by extracting it into testable functions.
// The daemon module has side effects (starts server), so we test the logic unit directly.
describe('IdleManager', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('does not start timer when extension is connected', async () => {
const { IdleManager } = await import('./daemon.js');
const exit = vi.fn();
const mgr = new IdleManager(300_000, exit); // 5 min for fast test
mgr.setExtensionConnected(true);
mgr.onCliRequest();
vi.advanceTimersByTime(300_000 + 1000);
expect(exit).not.toHaveBeenCalled();
});
it('starts timer when extension disconnects and CLI is idle', async () => {
const { IdleManager } = await import('./daemon.js');
const exit = vi.fn();
const mgr = new IdleManager(300_000, exit);
mgr.onCliRequest(); // CLI was active
mgr.setExtensionConnected(true);
mgr.setExtensionConnected(false); // Extension disconnects
// Should not exit immediately — CLI was just active
expect(exit).not.toHaveBeenCalled();
// Advance past timeout
vi.advanceTimersByTime(300_000 + 1000);
expect(exit).toHaveBeenCalledTimes(1);
});
it('exits immediately on extension disconnect if CLI has been idle past timeout', async () => {
const { IdleManager } = await import('./daemon.js');
const exit = vi.fn();
const mgr = new IdleManager(300_000, exit);
mgr.onCliRequest(); // Last CLI activity
vi.advanceTimersByTime(400_000); // 400s elapsed — past 300s timeout
mgr.setExtensionConnected(true);
mgr.setExtensionConnected(false);
expect(exit).toHaveBeenCalledTimes(1);
});
it('resets timer on new CLI request', async () => {
const { IdleManager } = await import('./daemon.js');
const exit = vi.fn();
const mgr = new IdleManager(300_000, exit);
mgr.onCliRequest();
vi.advanceTimersByTime(200_000); // 200s elapsed
mgr.onCliRequest(); // Reset
vi.advanceTimersByTime(200_000); // 200s more — only 200s since last request
expect(exit).not.toHaveBeenCalled();
vi.advanceTimersByTime(100_001); // Now 300s+ since last request
expect(exit).toHaveBeenCalledTimes(1);
});
it('does not exit when timeout is 0 (disabled)', async () => {
const { IdleManager } = await import('./daemon.js');
const exit = vi.fn();
const mgr = new IdleManager(0, exit);
mgr.onCliRequest();
vi.advanceTimersByTime(24 * 60 * 60 * 1000); // 24 hours
expect(exit).not.toHaveBeenCalled();
});
it('clears timer when extension connects', async () => {
const { IdleManager } = await import('./daemon.js');
const exit = vi.fn();
const mgr = new IdleManager(300_000, exit);
mgr.onCliRequest();
vi.advanceTimersByTime(200_000); // Timer running
mgr.setExtensionConnected(true); // Should clear timer
vi.advanceTimersByTime(200_000); // Would have fired
expect(exit).not.toHaveBeenCalled();
});
});
```
- [ ] **Step 2: Run tests to verify they fail**
```bash
npx vitest run src/daemon.test.ts
```
Expected: FAIL — `IdleManager` is not exported from `./daemon.js`
- [ ] **Step 3: Extract IdleManager class and refactor daemon.ts**
In `src/daemon.ts`, replace the idle timeout section (lines 27, 29-57) with:
Replace the `IDLE_TIMEOUT` constant (line 27):
```typescript
import { DEFAULT_DAEMON_PORT, DEFAULT_DAEMON_IDLE_TIMEOUT } from './constants.js';
const PORT = parseInt(process.env.OPENCLI_DAEMON_PORT ?? String(DEFAULT_DAEMON_PORT), 10);
const IDLE_TIMEOUT = Number(process.env.OPENCLI_DAEMON_TIMEOUT ?? DEFAULT_DAEMON_IDLE_TIMEOUT);
```
Replace the idle timer state and `resetIdleTimer` function (lines 37, 49-57) with the `IdleManager` class:
```typescript
/**
* Manages daemon idle timeout with dual-condition logic:
* exits only when BOTH CLI is idle AND Extension is disconnected.
*/
export class IdleManager {
private _timer: ReturnType<typeof setTimeout> | null = null;
private _lastCliRequestTime = Date.now();
private _extensionConnected = false;
private _timeoutMs: number;
private _onExit: () => void;
constructor(timeoutMs: number, onExit: () => void) {
this._timeoutMs = timeoutMs;
this._onExit = onExit;
}
/** Call when an HTTP request arrives from CLI */
onCliRequest(): void {
this._lastCliRequestTime = Date.now();
this._resetTimer();
}
/** Call when Extension WebSocket connects or disconnects */
setExtensionConnected(connected: boolean): void {
this._extensionConnected = connected;
if (connected) {
// Extension is alive — clear any pending exit timer
this._clearTimer();
} else {
// Extension gone — check if CLI has also been idle long enough
this._resetTimer();
}
}
private _clearTimer(): void {
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
}
private _resetTimer(): void {
this._clearTimer();
// Timeout disabled
if (this._timeoutMs <= 0) return;
// Extension connected — don't start timer
if (this._extensionConnected) return;
const elapsed = Date.now() - this._lastCliRequestTime;
if (elapsed >= this._timeoutMs) {
// CLI has been idle past the timeout already
this._onExit();
return;
}
// Start timer for remaining duration
this._timer = setTimeout(() => {
this._onExit();
}, this._timeoutMs - elapsed);
}
}
```
Then create the global `idleManager` instance after the class definition:
```typescript
const idleManager = new IdleManager(IDLE_TIMEOUT, () => {
console.error('[daemon] Idle timeout (no CLI requests + no Extension), shutting down');
process.exit(0);
});
```
- [ ] **Step 4: Wire IdleManager into existing daemon code**
In the `handleRequest` function, replace `resetIdleTimer()` (line 142) with:
```typescript
idleManager.onCliRequest();
```
In the `wss.on('connection')` handler (around line 196-198), add after `extensionWs = ws;`:
```typescript
idleManager.setExtensionConnected(true);
```
In the `ws.on('close')` handler (around line 245-249), add after `extensionWs = null;`:
```typescript
idleManager.setExtensionConnected(false);
```
In the `ws.on('error')` handler (around line 259-261), add after `extensionWs = null;`:
```typescript
idleManager.setExtensionConnected(false);
```
In the `httpServer.listen` callback (line 268-269), replace `resetIdleTimer()` with:
```typescript
idleManager.onCliRequest(); // Start initial idle countdown
```
Remove the old `resetIdleTimer` function and `idleTimer` variable entirely.
- [ ] **Step 5: Run tests to verify they pass**
```bash
npx vitest run src/daemon.test.ts
```
Expected: All 6 tests PASS
- [ ] **Step 6: Commit**
```bash
git add src/daemon.ts src/daemon.test.ts
git commit -m "feat(daemon): replace fixed 5min timeout with dual-condition idle manager (4h default)"
```
---
### Task 3: Add `/status` and `/shutdown` endpoints to daemon
**Files:**
- Modify: `src/daemon.ts:116-123`
- [ ] **Step 1: Add tests for /status and /shutdown endpoints**
Append to `src/daemon.test.ts`:
```typescript
describe('/status endpoint', () => {
it('returns daemon status with correct fields', async () => {
// This is an integration test — tested via the daemon command tests.
// Here we just verify the shape of the status response type.
expect(true).toBe(true); // Placeholder — real coverage in Task 6
});
});
```
Note: The `/status` and `/shutdown` endpoints run inside the daemon process, which makes them hard to unit test in isolation. They are integration-tested via the `opencli daemon status/stop` commands in Task 6.
- [ ] **Step 2: Enhance the existing `/status` endpoint**
In `src/daemon.ts`, replace the existing `/status` handler (lines 116-123) with:
```typescript
if (req.method === 'GET' && pathname === '/status') {
const uptime = process.uptime();
const mem = process.memoryUsage();
jsonResponse(res, 200, {
ok: true,
pid: process.pid,
uptime,
extensionConnected: extensionWs?.readyState === WebSocket.OPEN,
pending: pending.size,
lastCliRequestTime: idleManager.lastCliRequestTime,
memoryMB: Math.round(mem.rss / 1024 / 1024 * 10) / 10,
port: PORT,
});
return;
}
```
Also add a public getter to `IdleManager`:
```typescript
get lastCliRequestTime(): number {
return this._lastCliRequestTime;
}
```
- [ ] **Step 3: Add the `/shutdown` endpoint**
In `src/daemon.ts`, add before the `POST /command` handler:
```typescript
if (req.method === 'POST' && pathname === '/shutdown') {
jsonResponse(res, 200, { ok: true, message: 'Shutting down' });
// Graceful shutdown after response is sent
setTimeout(() => shutdown(), 100);
return;
}
```
- [ ] **Step 4: Run all tests**
```bash
npx vitest run src/daemon.test.ts
```
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add src/daemon.ts src/daemon.test.ts
git commit -m "feat(daemon): enhance /status endpoint, add /shutdown endpoint"
```
---
### Task 4: Reduce Extension WebSocket reconnect backoff cap
**Files:**
- Modify: `extension/src/protocol.ts:57`
- [ ] **Step 1: Change the constant**
In `extension/src/protocol.ts`, change line 57:
```typescript
/** Max reconnect delay (ms) — kept short since daemon is long-lived */
export const WS_RECONNECT_MAX_DELAY = 5000;
```
- [ ] **Step 2: Commit**
```bash
git add extension/src/protocol.ts
git commit -m "feat(extension): reduce WS reconnect backoff cap from 60s to 5s"
```
---
### Task 5: Implement `daemon status/stop/restart` CLI commands
**Files:**
- Create: `src/commands/daemon.ts`
- Modify: `src/cli.ts`
- [ ] **Step 1: Create daemon command module**
Create `src/commands/daemon.ts`:
```typescript
/**
* CLI commands for daemon lifecycle management:
* opencli daemon status — show daemon state
* opencli daemon stop — graceful shutdown
* opencli daemon restart — stop + respawn
*/
import chalk from 'chalk';
import { DEFAULT_DAEMON_PORT } from '../constants.js';
const DAEMON_PORT = parseInt(process.env.OPENCLI_DAEMON_PORT ?? String(DEFAULT_DAEMON_PORT), 10);
const DAEMON_URL = `http://127.0.0.1:${DAEMON_PORT}`;
interface DaemonStatus {
ok: boolean;
pid: number;
uptime: number;
extensionConnected: boolean;
pending: number;
lastCliRequestTime: number;
memoryMB: number;
port: number;
}
async function fetchStatus(): Promise<DaemonStatus | null> {
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 2000);
const res = await fetch(`${DAEMON_URL}/status`, {
headers: { 'X-OpenCLI': '1' },
signal: controller.signal,
});
clearTimeout(timer);
if (!res.ok) return null;
return await res.json() as DaemonStatus;
} catch {
return null;
}
}
async function requestShutdown(): Promise<boolean> {
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);
const res = await fetch(`${DAEMON_URL}/shutdown`, {
method: 'POST',
headers: { 'X-OpenCLI': '1' },
signal: controller.signal,
});
clearTimeout(timer);
return res.ok;
} catch {
return false;
}
}
function formatUptime(seconds: number): string {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h > 0) return `${h}h ${m}m`;
if (m > 0) return `${m}m`;
return `${Math.floor(seconds)}s`;
}
function formatTimeSince(timestampMs: number): string {
const seconds = (Date.now() - timestampMs) / 1000;
if (seconds < 60) return `${Math.floor(seconds)}s ago`;
const m = Math.floor(seconds / 60);
if (m < 60) return `${m} min ago`;
const h = Math.floor(m / 60);
return `${h}h ${m % 60}m ago`;
}
export async function daemonStatus(): Promise<void> {
const status = await fetchStatus();
if (!status) {
console.log(`Daemon: ${chalk.dim('not running')}`);
return;
}
console.log(`Daemon: ${chalk.green('running')} (PID ${status.pid})`);
console.log(`Uptime: ${formatUptime(status.uptime)}`);
console.log(`Extension: ${status.extensionConnected ? chalk.green('connected') : chalk.yellow('disconnected')}`);
console.log(`Last CLI request: ${formatTimeSince(status.lastCliRequestTime)}`);
console.log(`Memory: ${status.memoryMB} MB`);
console.log(`Port: ${status.port}`);
}
export async function daemonStop(): Promise<void> {
const status = await fetchStatus();
if (!status) {
console.log(chalk.dim('Daemon is not running.'));
return;
}
const ok = await requestShutdown();
if (ok) {
console.log(chalk.green('Daemon stopped.'));
} else {
console.error(chalk.red('Failed to stop daemon.'));
process.exitCode = 1;
}
}
export async function daemonRestart(): Promise<void> {
const status = await fetchStatus();
if (status) {
const ok = await requestShutdown();
if (!ok) {
console.error(chalk.red('Failed to stop daemon.'));
process.exitCode = 1;
return;
}
// Wait for daemon to exit
await new Promise(r => setTimeout(r, 500));
}
// Import BrowserBridge to spawn a new daemon
const { BrowserBridge } = await import('../browser/mcp.js');
const bridge = new BrowserBridge();
try {
console.log('Starting daemon...');
await bridge.connect({ timeout: 10 });
console.log(chalk.green('Daemon restarted.'));
} catch (err) {
console.error(chalk.red(`Failed to restart daemon: ${err instanceof Error ? err.message : err}`));
process.exitCode = 1;
}
}
```
- [ ] **Step 2: Register daemon commands in cli.ts**
In `src/cli.ts`, add the import at the top:
```typescript
import { daemonStatus, daemonStop, daemonRestart } from './commands/daemon.js';
```
Add the daemon subcommand group before the `// ── External CLIs` section (around line 380):
```typescript
// ── Built-in: daemon ──────────────────────────────────────────────────────
const daemonCmd = program.command('daemon').description('Manage the opencli daemon');
daemonCmd
.command('status')
.description('Show daemon status')
.action(async () => { await daemonStatus(); });
daemonCmd
.command('stop')
.description('Stop the daemon')
.action(async () => { await daemonStop(); });
daemonCmd
.command('restart')
.description('Restart the daemon')
.action(async () => { await daemonRestart(); });
```
- [ ] **Step 3: Run linter/type check**
```bash
npx tsc --noEmit
```
Expected: No errors
- [ ] **Step 4: Commit**
```bash
git add src/commands/daemon.ts src/cli.ts
git commit -m "feat(daemon): add opencli daemon status/stop/restart commands"
```
---
### Task 6: Write tests for daemon commands
**Files:**
- Create: `src/commands/daemon.test.ts`
- [ ] **Step 1: Write tests**
Create `src/commands/daemon.test.ts`:
```typescript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Mock fetch globally for all tests
const mockFetch = vi.fn();
vi.stubGlobal('fetch', mockFetch);
// Mock chalk to avoid ANSI in assertions
vi.mock('chalk', () => ({
default: {
green: (s: string) => s,
yellow: (s: string) => s,
red: (s: string) => s,
dim: (s: string) => s,
},
}));
describe('daemonStatus', () => {
let consoleSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
});
afterEach(() => {
consoleSpy.mockRestore();
mockFetch.mockReset();
});
it('shows "not running" when daemon is unreachable', async () => {
mockFetch.mockRejectedValue(new TypeError('fetch failed'));
const { daemonStatus } = await import('./daemon.js');
await daemonStatus();
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('not running'));
});
it('shows daemon info when running', async () => {
mockFetch.mockResolvedValue({
ok: true,
json: async () => ({
ok: true,
pid: 12345,
uptime: 7200,
extensionConnected: true,
pending: 0,
lastCliRequestTime: Date.now() - 60_000,
memoryMB: 12.3,
port: 19825,
}),
});
const { daemonStatus } = await import('./daemon.js');
await daemonStatus();
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('running'));
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('12345'));
});
});
describe('daemonStop', () => {
let consoleSpy: ReturnType<typeof vi.spyOn>;
let consoleErrSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
consoleErrSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
consoleSpy.mockRestore();
consoleErrSpy.mockRestore();
mockFetch.mockReset();
});
it('reports when daemon is not running', async () => {
mockFetch.mockRejectedValue(new TypeError('fetch failed'));
const { daemonStop } = await import('./daemon.js');
await daemonStop();
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('not running'));
});
it('sends shutdown and reports success', async () => {
// First call: fetchStatus
// Second call: requestShutdown
mockFetch
.mockResolvedValueOnce({
ok: true,
json: async () => ({ ok: true, pid: 123, uptime: 100, extensionConnected: false, pending: 0, lastCliRequestTime: Date.now(), memoryMB: 10, port: 19825 }),
})
.mockResolvedValueOnce({ ok: true });
const { daemonStop } = await import('./daemon.js');
await daemonStop();
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('stopped'));
});
});
```
- [ ] **Step 2: Run tests**
```bash
npx vitest run src/commands/daemon.test.ts
```
Expected: PASS
- [ ] **Step 3: Commit**
```bash
git add src/commands/daemon.test.ts
git commit -m "test(daemon): add tests for daemon status/stop commands"
```
---
### Task 7: Improve CLI connection-waiting UX
**Files:**
- Modify: `src/browser/mcp.ts:58-118`
- [ ] **Step 1: Improve error messages and poll interval**
In `src/browser/mcp.ts`, replace the `_ensureDaemon` method (lines 58-118) with:
```typescript
private async _ensureDaemon(timeoutSeconds?: number): Promise<void> {
const effectiveSeconds = (timeoutSeconds && timeoutSeconds > 0) ? timeoutSeconds : Math.ceil(DAEMON_SPAWN_TIMEOUT / 1000);
const timeoutMs = effectiveSeconds * 1000;
// Fast path: extension already connected
if (await isExtensionConnected()) return;
// Daemon running but no extension — wait for extension with progress
if (await isDaemonRunning()) {
if (process.env.OPENCLI_VERBOSE || process.stderr.isTTY) {
process.stderr.write('⏳ Waiting for Chrome extension to connect...\n');
process.stderr.write(' Make sure Chrome is open and the OpenCLI extension is enabled.\n');
}
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 200));
if (await isExtensionConnected()) return;
}
throw new Error(
'Daemon is running but the Browser Extension is not connected.\n' +
'Please install and enable the opencli Browser Bridge extension in Chrome.',
);
}
// No daemon — spawn one
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const parentDir = path.resolve(__dirname, '..');
const daemonTs = path.join(parentDir, 'daemon.ts');
const daemonJs = path.join(parentDir, 'daemon.js');
const isTs = fs.existsSync(daemonTs);
const daemonPath = isTs ? daemonTs : daemonJs;
if (process.env.OPENCLI_VERBOSE || process.stderr.isTTY) {
process.stderr.write('⏳ Starting daemon...\n');
}
const spawnArgs = isTs
? [process.execPath, '--import', 'tsx/esm', daemonPath]
: [process.execPath, daemonPath];
this._daemonProc = spawn(spawnArgs[0], spawnArgs.slice(1), {
detached: true,
stdio: 'ignore',
env: { ...process.env },
});
this._daemonProc.unref();
// Wait for daemon + extension with faster polling
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 200));
if (await isExtensionConnected()) return;
}
if (await isDaemonRunning()) {
throw new Error(
'Daemon is running but the Browser Extension is not connected.\n' +
'Please install and enable the opencli Browser Bridge extension in Chrome.',
);
}
throw new Error(
'Failed to start opencli daemon. Try running manually:\n' +
` node ${daemonPath}\n` +
`Make sure port ${DEFAULT_DAEMON_PORT} is available.`,
);
}
```
- [ ] **Step 2: Run existing browser tests to check for regressions**
```bash
npx vitest run src/browser.test.ts
```
Expected: PASS
- [ ] **Step 3: Commit**
```bash
git add src/browser/mcp.ts
git commit -m "feat(daemon): improve CLI connection-waiting UX with progress messages and 200ms polling"
```
---
### Task 8: Run full test suite and verify
- [ ] **Step 1: Run type check**
```bash
npx tsc --noEmit
```
Expected: No errors
- [ ] **Step 2: Run all tests**
```bash
npx vitest run
```
Expected: All tests pass, no regressions
- [ ] **Step 3: Manual smoke test**
```bash
# Check daemon status (should be "not running" if daemon isn't started)
npx tsx src/main.ts daemon status
# Start daemon by running any browser command, then check status
npx tsx src/main.ts daemon status
# Stop daemon
npx tsx src/main.ts daemon stop
# Verify stopped
npx tsx src/main.ts daemon status
```
- [ ] **Step 4: Final commit if any fixes needed**
```bash
git add -A
git commit -m "fix: address issues found during smoke testing"
```
@@ -1,170 +0,0 @@
# Performance: Smart Wait & INTERCEPT Fix
**Date**: 2026-03-28
**Status**: Approved
## Problem
Three distinct performance/correctness issues:
1. **INTERCEPT strategy semantic bug**: After `installInterceptor()` + `goto()`, adapters call `wait(N)` — which now uses `waitForDomStableJs` and returns early when the DOM settles. But DOM-settle != network capture. The API response may arrive *after* DOM is stable, causing `getInterceptedRequests()` to return an empty array.
2. **Blind `wait(N)` in adapters**: ~30 high-traffic adapters (Twitter family, Medium, Substack, etc.) call `wait(5)` waiting for React/Vue to hydrate. These should wait for a specific DOM element to appear, not a fixed cap.
3. **Daemon cold-start polling**: Fixed 300ms poll loop means ~600ms before first successful `isExtensionConnected()` check, even though the daemon is typically ready in 500800ms.
## Design
### Layer 1 — `waitForCapture()` (correctness fix + perf)
Add `waitForCapture(timeout?: number): Promise<void>` to `IPage`.
Polls `window.__opencli_xhr.length > 0` every 100ms inside the browser tab. Resolves as soon as ≥1 capture arrives; rejects after `timeout` seconds.
```typescript
// dom-helpers.ts
export function waitForCaptureJs(maxMs: number): string {
return `
new Promise((resolve, reject) => {
const deadline = Date.now() + ${maxMs};
const check = () => {
if ((window.__opencli_xhr || []).length > 0) return resolve('captured');
if (Date.now() > deadline) return reject(new Error('No capture within ${maxMs / 1000}s'));
setTimeout(check, 100);
};
check();
})
`;
}
```
`page.ts` and `cdp.ts` implement `waitForCapture()` by calling `waitForCaptureJs`.
**All INTERCEPT adapters** replace `wait(N)``waitForCapture(N+2)` (slightly longer timeout as safety margin).
`stepIntercept` in `pipeline/steps/intercept.ts` replaces its internal `wait(timeout)` with `waitForCapture(timeout)`.
**Expected gain**: 36kr hot/search: 6s → ~12s. Twitter search/followers: 58s → ~13s.
### Layer 2 — `wait({ selector })` (semantic precision)
Extend `WaitOptions` with `selector?: string`.
Add `waitForSelectorJs(selector, timeoutMs)` to `dom-helpers.ts` — polls `document.querySelector(selector)` every 100ms, resolves on first match, rejects on timeout.
```typescript
// types.ts
export interface WaitOptions {
text?: string;
selector?: string; // NEW
time?: number;
timeout?: number;
}
```
```typescript
// dom-helpers.ts
export function waitForSelectorJs(selector: string, timeoutMs: number): string {
return `
new Promise((resolve, reject) => {
const deadline = Date.now() + ${timeoutMs};
const check = () => {
if (document.querySelector(${JSON.stringify(selector)})) return resolve('found');
if (Date.now() > deadline) return reject(new Error('Selector not found: ' + ${JSON.stringify(selector)}));
setTimeout(check, 100);
};
check();
})
`;
}
```
`page.ts` and `cdp.ts` handle `selector` branch in `wait()`.
**High-impact adapter changes**:
| Adapter | Old | New |
|---------|-----|-----|
| `twitter/*` (15 adapters) | `wait(5)` | `wait({ selector: '[data-testid="primaryColumn"]', timeout: 6 })` |
| `twitter/reply.ts` | `wait(5)` | `wait({ selector: '[data-testid="tweetTextarea_0"]', timeout: 8 })` |
| `medium/utils.ts` | `wait(5)` + inline 3s setTimeout | `wait({ selector: 'article', timeout: 8 })` + remove inline sleep |
| `substack/utils.ts` | `wait(5)` × 2 | `wait({ selector: 'article', timeout: 8 })` |
| `bloomberg/news.ts` | `wait(5)` | `wait({ selector: 'article', timeout: 6 })` |
| `sinablog/utils.ts` | `wait(5)` | `wait({ selector: 'article, .article', timeout: 6 })` |
| `producthunt` (already covered by layer 1) | — | — |
**Expected gain**: Twitter commands: 5s → ~0.52s. Medium: 8s → ~13s.
### Layer 3 — Daemon exponential backoff (cold-start)
Replace fixed 300ms poll in `_ensureDaemon()` (`browser/mcp.ts`) with exponential backoff:
```typescript
// before
while (Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 300));
if (await isExtensionConnected()) return;
}
// after
const backoffs = [50, 100, 200, 400, 800, 1500, 3000];
let i = 0;
while (Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, backoffs[Math.min(i++, backoffs.length - 1)]));
if (await isExtensionConnected()) return;
}
```
**Expected gain**: First cold-start check succeeds at ~150ms instead of ~600ms.
## Files Changed
### New / Modified (framework)
- `src/types.ts``WaitOptions.selector`, `IPage.waitForCapture()`
- `src/browser/dom-helpers.ts``waitForCaptureJs()`, `waitForSelectorJs()`
- `src/browser/page.ts``waitForCapture()`, `wait()` selector branch
- `src/browser/cdp.ts``waitForCapture()`, `wait()` selector branch
- `src/browser/mcp.ts` — exponential backoff in `_ensureDaemon()`
- `src/pipeline/steps/intercept.ts` — use `waitForCapture()`
### Modified (adapters — Layer 1, INTERCEPT)
- `src/clis/36kr/hot.ts`
- `src/clis/36kr/search.ts`
- `src/clis/twitter/search.ts`
- `src/clis/twitter/followers.ts`
- `src/clis/twitter/following.ts`
- `src/clis/producthunt/hot.ts`
- `src/clis/producthunt/browse.ts`
### Modified (adapters — Layer 2, selector)
- `src/clis/twitter/reply.ts`
- `src/clis/twitter/follow.ts`
- `src/clis/twitter/unfollow.ts`
- `src/clis/twitter/like.ts`
- `src/clis/twitter/bookmark.ts`
- `src/clis/twitter/unbookmark.ts`
- `src/clis/twitter/block.ts`
- `src/clis/twitter/unblock.ts`
- `src/clis/twitter/hide-reply.ts`
- `src/clis/twitter/notifications.ts`
- `src/clis/twitter/profile.ts`
- `src/clis/twitter/thread.ts`
- `src/clis/twitter/timeline.ts`
- `src/clis/twitter/delete.ts`
- `src/clis/twitter/reply-dm.ts`
- `src/clis/medium/utils.ts`
- `src/clis/substack/utils.ts`
- `src/clis/bloomberg/news.ts`
- `src/clis/sinablog/utils.ts`
## Delivery Order
1. Layer 1 (`waitForCapture`) — correctness fix, highest ROI
2. Layer 3 (backoff) — 3-line change, zero risk
3. Layer 2 (`wait({ selector })`) — largest adapter surface, can be done per-site
## Testing
- Unit tests: `waitForCaptureJs`, `waitForSelectorJs` exported and tested in `dom-helpers.test.ts` (if exists) or new test file
- Adapter tests: existing tests must continue to pass (mock `page.wait` / `page.waitForCapture`)
- Run: `npx vitest run --project unit --project adapter`
@@ -1,208 +0,0 @@
# Daemon Lifecycle Redesign
## Problem
OpenCLI's daemon auto-exits after 5 minutes of idle time. During typical development
cycles (write code → test → modify → test again), coding intervals frequently exceed
5 minutes. Each restart incurs 2-4 seconds of overhead (process spawn + Extension
WebSocket reconnection), creating a noticeable and frustrating delay.
The current design treats the daemon as a disposable process, but the actual cost
profile doesn't justify this:
| Cost of staying alive | Cost of restarting |
|-----------------------|--------------------|
| ~12 MB memory, 0% CPU | 2-4 seconds delay per restart |
The restart cost far outweighs the idle cost.
## Solution
Replace the aggressive 5-minute fixed timeout with a long-lived daemon model. The
daemon stays running for hours, exits only when truly abandoned, and reconnects to
the Chrome Extension faster when needed.
Four changes:
1. Extend idle timeout from 5 minutes to 4 hours (configurable)
2. Require dual idle condition: both no CLI requests AND no Extension connection
3. Reduce Extension WebSocket reconnect backoff cap from 60s to 5s
4. Add `opencli daemon status/stop/restart` commands
## Design
### Timeout Strategy
**Current behavior:** A single idle timer resets on each HTTP request. After 5
minutes without a request, the daemon calls `process.exit(0)`.
**New behavior:** The daemon tracks two activity signals independently:
- **CLI activity:** timestamp of the last HTTP request from any CLI invocation
- **Extension activity:** whether a WebSocket connection from the Chrome Extension
is currently open
The exit countdown starts only when BOTH conditions are met simultaneously:
- No CLI request for `IDLE_TIMEOUT` duration
- No Extension WebSocket connection
If either signal is active, the daemon stays alive. This means:
- A connected Extension keeps the daemon alive indefinitely (user has Chrome open,
likely still working)
- Recent CLI activity keeps the daemon alive even if Extension temporarily
disconnects (Chrome restarting, Extension updating)
**Timeout value:** 4 hours by default, configurable via `OPENCLI_DAEMON_TIMEOUT`
environment variable. Value in milliseconds. Set to `0` to disable timeout entirely.
```typescript
const DEFAULT_IDLE_TIMEOUT = 4 * 60 * 60 * 1000; // 4 hours
const IDLE_TIMEOUT = Number(process.env.OPENCLI_DAEMON_TIMEOUT ?? DEFAULT_IDLE_TIMEOUT);
```
**Timer implementation:**
```
resetIdleTimer():
clear existing timer
if Extension is connected:
do not start timer (Extension connection keeps daemon alive)
return
start timer with IDLE_TIMEOUT duration
on timeout: process.exit(0)
On CLI HTTP request:
update lastRequestTime
resetIdleTimer()
On Extension WebSocket connect:
clear timer (Extension keeps daemon alive)
On Extension WebSocket disconnect:
elapsed = now - lastRequestTime
if elapsed >= IDLE_TIMEOUT:
process.exit(0) // CLI has been idle long enough already
else:
start timer with (IDLE_TIMEOUT - elapsed) // count remaining time
```
### Extension Fast Reconnect
**Current behavior:** When the Extension loses its WebSocket connection to the
daemon, it reconnects with exponential backoff: 2s → 4s → 8s → 16s → 32s → 60s
(capped). In the worst case, the Extension waits up to 60 seconds before attempting
reconnection.
**New behavior:** Cap the backoff at 5 seconds instead of 60 seconds.
```typescript
// extension/src/background.ts
const WS_RECONNECT_MAX_DELAY = 5000; // was 60000
```
Rationale: with a 4-hour daemon timeout, the daemon is almost always running. Long
backoff intervals are unnecessary and only increase reconnection latency. A 5-second
cap means the Extension reconnects within 5 seconds of the daemon becoming available.
### Daemon Management Commands
Add three new CLI commands for daemon lifecycle management:
**`opencli daemon status`**
Queries the daemon's `/status` endpoint (new) and displays:
```
Daemon: running (PID 12345)
Uptime: 2h 15m
Extension: connected
Last CLI request: 8 min ago
Memory: 12.3 MB
Port: 19825
```
If daemon is not running:
```
Daemon: not running
```
**`opencli daemon stop`**
Sends a `POST /shutdown` request to the daemon, which triggers a graceful shutdown:
reject pending requests with a shutdown message, close WebSocket connections, close
HTTP server, then exit.
**`opencli daemon restart`**
Equivalent to `stop` followed by spawning a new daemon. Useful when the daemon gets
into a bad state.
**Daemon-side endpoints:**
- `GET /status` — returns JSON with PID, uptime, extension connection state, last
request time, memory usage
- `POST /shutdown` — initiates graceful shutdown
Both endpoints require the same `X-OpenCLI` header as existing endpoints for CSRF
protection.
### CLI Connection Experience
**Current behavior:** When daemon is running but Extension is not connected, the CLI
silently polls every 300ms and eventually times out with a generic error.
**New behavior:** Show a progress indicator and actionable message:
```
⏳ Waiting for Chrome extension to connect...
Make sure Chrome is open and the OpenCLI extension is enabled.
```
Poll interval reduced from 300ms to 200ms for slightly faster detection.
If the daemon is not running at all (connection refused), the CLI spawns it as before
and shows:
```
⏳ Starting daemon...
```
## Files Changed
| File | Change | Estimated LOC |
|------|--------|---------------|
| `src/daemon.ts` | Dual-condition idle timeout, `/status` endpoint, `/shutdown` endpoint | ~40 |
| `extension/src/background.ts` | `WS_RECONNECT_MAX_DELAY` 60000 → 5000 | 1 |
| `src/browser/daemon-client.ts` | Better connection-waiting UX, 200ms poll interval | ~20 |
| `src/commands/daemon.ts` (new) | `status`, `stop`, `restart` subcommands | ~80 |
| `src/constants.ts` | `DEFAULT_IDLE_TIMEOUT` constant | 2 |
**Total: ~143 lines of new/changed code.**
## Backward Compatibility
- No breaking changes to CLI commands or Extension protocol
- Existing `OPENCLI_DAEMON_PORT` environment variable continues to work
- The only observable behavior change: daemon stays alive longer
- New `daemon` subcommands are additive
## Testing
- Unit test: idle timer starts only when both CLI and Extension are idle
- Unit test: idle timer is cleared when Extension connects
- Unit test: `/status` returns correct state
- Unit test: `/shutdown` triggers graceful exit
- Integration test: daemon survives 10+ minutes without CLI requests while Extension
is connected
- Integration test: daemon exits after configured timeout when fully idle
- Integration test: `opencli daemon status/stop/restart` work correctly
## Out of Scope
- OS-level daemon management (launchd/systemd) — can be added later if needed
- Daemon auto-update mechanism
- Multi-daemon coordination
- Persistent daemon state across restarts
@@ -1,144 +0,0 @@
# Browse Skill Testing Design
Two-layer testing framework for `opencli browse` commands and the
Claude Code skill integration.
## Goal
Verify that `opencli browse` works reliably on real websites and that
Claude Code can use the skill to complete browser tasks end-to-end.
## Architecture
```
autoresearch/
├── browse-tasks.json ← 59 task definitions with browse command sequences
├── eval-browse.ts ← Layer 1: deterministic browse command testing
├── eval-skill.ts ← Layer 2: Claude Code skill E2E testing
├── run-browse.sh ← Launch Layer 1
├── run-skill.sh ← Launch Layer 2
├── baseline-browse.txt ← Layer 1 best score
├── baseline-skill.txt ← Layer 2 best score
└── results/ ← Per-run results (gitignored)
```
## Layer 1: Deterministic Browse Command Testing
Tests `opencli browse` commands directly on real websites. No LLM
involved — pure command reliability testing.
### How It Works
Each task defines a sequence of browse commands and a judge for the
last command's output:
```json
{
"name": "hn-top-stories",
"steps": [
"opencli browse open https://news.ycombinator.com",
"opencli browse eval \"JSON.stringify([...document.querySelectorAll('.titleline a')].slice(0,5).map(a=>({title:a.textContent,url:a.href})))\""
],
"judge": { "type": "arrayMinLength", "minLength": 5 }
}
```
### Execution
```bash
./autoresearch/run-browse.sh
```
- Runs all 59 tasks serially
- Each task: execute steps → judge last step output → pass/fail
- `opencli browse close` between tasks for clean state
- Expected: ~2 minutes, $0 cost
### Task Categories
| Category | Count | Example |
|----------|-------|---------|
| extract | 9 | Open page, eval JS to extract data |
| list | 10 | Open page, eval JS to extract array |
| search | 6 | Open, type query, keys Enter, eval results |
| nav | 7 | Open, click link, eval new page title |
| scroll | 5 | Open, scroll, eval footer/hidden content |
| form | 6 | Open, type into fields, eval field values |
| complex | 6 | Multi-step: open → click → navigate → extract |
| bench | 10 | Test set (various) |
## Layer 2: Claude Code Skill E2E Testing
Spawns Claude Code with the opencli-operate skill to complete tasks
autonomously using browse commands.
### How It Works
```bash
claude -p \
--system-prompt "$(cat skills/opencli-operate/SKILL.md)" \
--dangerously-skip-permissions \
--allowedTools "Bash(opencli:*)" \
--output-format json \
"用 opencli browse 完成任务:Extract the top 5 stories from Hacker News with title and score. Start URL: https://news.ycombinator.com"
```
### Execution
```bash
./autoresearch/run-skill.sh
```
- Runs all 59 tasks serially
- Each task: spawn Claude Code → it uses browse commands autonomously → judge output
- Expected: ~20 minutes, ~$5-10
### Judge
Both layers use the same judge types:
| Type | Description |
|------|-------------|
| `contains` | Output contains a substring |
| `arrayMinLength` | Output is an array with ≥ N items |
| `arrayFieldsPresent` | Array items have required fields |
| `nonEmpty` | Output is non-empty |
| `matchesPattern` | Output matches a regex |
## Output Format
```
🔬 Layer 1: Browse Commands — 59 tasks
[1/59] extract-title-example... ✓ (0.5s)
[2/59] hn-top-stories... ✓ (1.2s)
...
Score: 55/59 (93%)
Time: 2min
Cost: $0
🔬 Layer 2: Skill E2E — 59 tasks
[1/59] extract-title-example... ✓ (8s, $0.01)
[2/59] hn-top-stories... ✓ (15s, $0.08)
...
Score: 52/59 (88%)
Time: 20min
Cost: $6.50
```
## Constraints
- All 59 tasks run on real websites (no mocks)
- Layer 1: zero LLM cost, ~2 min
- Layer 2: ~$5-10 LLM cost, ~20 min
- Results saved to `autoresearch/results/` (gitignored)
- Baselines tracked in `baseline-browse.txt` and `baseline-skill.txt`
## Success Criteria
- Layer 1 ≥ 90% (browse commands work on real sites)
- Layer 2 ≥ 85% (Claude Code can use skill effectively)
- Both layers cover all 8 task categories
-12
View File
@@ -22,15 +22,3 @@ OpenCLI 通过轻量级 **Browser Bridge** Chrome 扩展 + 微守护进程连接
```bash
opencli doctor # 检查扩展 + 守护进程连接
```
## Daemon 生命周期
Daemon 在首次运行浏览器命令时自动启动,默认保持 **4 小时**。仅当 CLI 空闲超时**且** Chrome 扩展未连接时才会退出。
```bash
opencli daemon status # 查看 daemon 状态(PID、运行时长、扩展连接、内存)
opencli daemon stop # 优雅关停
opencli daemon restart # 重启
```
通过 `OPENCLI_DAEMON_TIMEOUT` 环境变量覆盖超时时间(毫秒)。设为 `0` 则永不超时。
-188
View File
@@ -1,188 +0,0 @@
# 给新 Electron 应用生成 CLI
这篇文档是把一个新的 Electron 桌面应用接入 OpenCLI 的**中文入口指南**。
如果你需要更完整的背景和标准流程,继续看:
- [Chrome DevTools Protocol(中文)](/zh/advanced/cdp)
- [CLI-ifying Electron Applications(英文深度版)](/advanced/electron)
- [TypeScript 适配器开发指南(英文)](/developer/ts-adapter)
## 这篇文档适合什么场景
当目标应用满足下面条件时,用这套流程:
- 应用是 **Electron**,或者至少能暴露可用的 **CDPChrome DevTools Protocol** 端口
- 可以通过 `--remote-debugging-port=<port>` 启动
- 你希望控制的是桌面应用本身,而不是它背后的公开 HTTP API
如果应用**不是** Electron,或者不暴露 CDP,就不要硬套这套方案。那种情况应改用原生桌面自动化方案。可参考 [英文版说明](/advanced/electron#non-electron-pattern-applescript)。
## 最短落地路径
### 1. 先确认它是不是 Electron
macOS 下常见检查方式:
```bash
ls /Applications/AppName.app/Contents/Frameworks/Electron\ Framework.framework
```
如果存在,通常就可以继续尝试 CDP。
### 2. 带 CDP 端口启动应用
```bash
/Applications/AppName.app/Contents/MacOS/AppName --remote-debugging-port=9222
```
然后把 OpenCLI 指到这个端口:
```bash
export OPENCLI_CDP_ENDPOINT="http://127.0.0.1:9222"
```
### 3. 先做 5 个基础命令
建议一个新 Electron 适配器先实现这 5 个命令:
- `status.ts` —— 确认 CDP 连通
- `dump.ts` —— 导出 DOM / snapshot,先做逆向再写逻辑
- `read.ts` —— 读取当前上下文
- `send.ts` —— 往真实编辑器里输入并发送
- `new.ts` —— 新建会话 / 标签页 / 文档
这是最稳妥的基线,因为它先把“能连上、能看见、能读、能写、能重置状态”这 5 件核心事情打通了。
## 推荐开发顺序
### 第一步:先做 `status`
目标不是功能,而是先证明:
- CDP 真的连上了
- 你连到的是对的窗口/标签页
- 应用当前页面确实可读
如果 `status` 都不稳定,先不要继续往下做。
### 第二步:做 `dump`
**不要猜 selector。**
先把这些导出来:
- `document.body.innerHTML`
- accessibility snapshot
- 稳定属性:`data-testid``role``aria-*`
然后再决定:
- 消息列表在哪
- 输入框在哪
- 按钮在哪
- 当前会话容器在哪
### 第三步:做 `read`
只读真正需要的区域,不要把整个页面文本都塞出来。
常见目标:
- 对话消息区
- 当前线程内容
- 当前编辑器历史
- 当前文档主区域
### 第四步:做 `send`
很多 Electron 应用的输入框是 React 控制组件,直接改 `.value` 往往没用。
更稳妥的方式通常是:
- 先 focus 到可编辑区域
- 能用时优先 `document.execCommand('insertText', false, text)`
- 最后用真实按键提交,比如 `Enter``Meta+Enter`
### 第五步:做 `new`
很多桌面应用的新建动作其实更适合走快捷键,而不是点按钮。
典型模式:
```ts
const isMac = process.platform === 'darwin';
await page.pressKey(isMac ? 'Meta+N' : 'Control+N');
await page.wait(1);
```
## 文件一般怎么放
一个 TypeScript 桌面适配器,通常结构是:
```text
src/clis/<app>/status.ts
src/clis/<app>/dump.ts
src/clis/<app>/read.ts
src/clis/<app>/send.ts
src/clis/<app>/new.ts
src/clis/<app>/utils.ts
```
当基础能力稳定后,再继续加:
- `ask`
- `history`
- `model`
- `screenshot`
- `export`
## 加完适配器后,还应该补什么文档
至少补这几项:
- `docs/adapters/desktop/` 下的适配器说明页
- 命令列表和示例
- 如何带 `--remote-debugging-port` 启动
- 需要哪些环境变量
- 平台限制和注意事项
可以参考这些现成文档:
- `docs/adapters/desktop/codex.md`
- `docs/adapters/desktop/chatwise.md`
- `docs/adapters/desktop/notion.md`
- `docs/adapters/desktop/discord.md`
## 常见问题
### CDP 能连,但命令不稳定
常见原因:
- 连错窗口或标签页
- 页面还没渲染完
- selector 是猜的,不是从 `dump` 里找出来的
- 输入框是受控组件,直接赋值不生效
### 应用看起来像 Chromium,但就是不好控
有些桌面应用虽然嵌了 Chromium,但并不真正暴露可用的 CDP 接口。
这种情况不要强行走 Electron 方案,应该换到非 Electron 的桌面自动化方案。
### 这个应用其实也有网页版本,还要不要做 Electron 适配器
如果网页版本已经足够稳定,浏览器适配器通常更简单。
只有当**桌面应用才是真正的集成面**时,再优先做 Electron 适配器。
## 推荐阅读顺序
如果你从零开始:
1. 先看这篇
2. 再看 [CLI-ifying Electron Applications(英文深度版)](/advanced/electron)
3. 再看 [Chrome DevTools Protocol(中文)](/zh/advanced/cdp)
4. 再看 [TypeScript Adapter Guide(英文)](/developer/ts-adapter)
5. 最后找一个现成桌面适配器文档照着做
## 最后一个实践建议
不要一上来就做很大的命令面。
先把下面 5 个做稳:
- `status`
- `dump`
- `read`
- `send`
- `new`
这 5 个稳定了,再往外扩,成本最低,返工也最少。
-22
View File
@@ -32,31 +32,9 @@ opencli bilibili hot -f md # Markdown
opencli bilibili hot -f csv # CSV
```
## 终端自动补全
OpenCLI 支持智能的 Tab 自动补全,加快命令输入:
```bash
# 把自动补全加入 shell 启动配置
echo 'eval "$(opencli completion zsh)"' >> ~/.zshrc # Zsh
echo 'eval "$(opencli completion bash)"' >> ~/.bashrc # Bash
echo 'opencli completion fish | source' >> ~/.config/fish/config.fish # Fish
# 重启 shell 后,按 Tab 键补全:
opencli [Tab] # 补全站点名称(bilibili、zhihu、twitter...
opencli bilibili [Tab] # 补全命令(hot、search、me、download...
```
补全功能包含:
- 所有可用的站点和适配器
- 内置命令(list、explore、validate...
- 命令别名
- 新增适配器时的实时更新
## 下一步
- [安装详情](/zh/guide/installation)
- [Browser Bridge 设置](/zh/guide/browser-bridge)
- [所有适配器](/zh/adapters/)
- [开发者指南](/zh/developer/contributing)
- [给新 Electron 应用生成 CLI](/zh/guide/electron-app-cli)
-75
View File
@@ -11,12 +11,6 @@ opencli plugin install github:ByteYue/opencli-plugin-github-trending
# 列出已安装插件
opencli plugin list
# 更新单个插件
opencli plugin update github-trending
# 更新全部已安装插件
opencli plugin update --all
# 使用插件(本质上就是普通 command)
opencli github-trending today
@@ -32,80 +26,11 @@ Plugins 存放在 `~/.opencli/plugins/<name>/`。每个子目录都会在启动
```bash
opencli plugin install github:user/repo
opencli plugin install github:user/repo/subplugin # 安装 monorepo 中的指定子插件
opencli plugin install https://github.com/user/repo
```
如果仓库名带 `opencli-plugin-` 前缀,本地目录会自动去掉这个前缀。例如 `opencli-plugin-hot-digest` 会变成 `hot-digest`
## 插件清单 (`opencli-plugin.json`)
插件可以在仓库根目录放置 `opencli-plugin.json` 来声明元数据:
```json
{
"name": "my-plugin",
"version": "1.0.0",
"opencli": ">=1.0.0",
"description": "我的插件"
}
```
| 字段 | 说明 |
|------|------|
| `name` | 插件名称(覆盖从仓库名推导的名称) |
| `version` | 语义化版本 |
| `opencli` | 所需的 opencli 版本范围(如 `>=1.0.0``^1.2.0` |
| `description` | 描述 |
| `plugins` | Monorepo 子插件声明(见下文) |
清单文件是可选的——没有它的插件依然可以正常工作。
## Monorepo 插件
一个仓库可以通过在 `opencli-plugin.json` 中声明 `plugins` 字段来包含多个插件:
```json
{
"version": "1.0.0",
"opencli": ">=1.0.0",
"description": "我的插件合集",
"plugins": {
"polymarket": {
"path": "packages/polymarket",
"description": "预测市场分析",
"version": "1.2.0"
},
"defi": {
"path": "packages/defi",
"description": "DeFi 协议数据",
"version": "0.8.0"
},
"experimental": {
"path": "packages/experimental",
"disabled": true
}
}
}
```
```bash
# 安装 monorepo 中的全部子插件
opencli plugin install github:user/opencli-plugins
# 安装指定子插件
opencli plugin install github:user/opencli-plugins/polymarket
```
- Monorepo 只 clone 一次到 `~/.opencli/monorepos/<repo>/`
- 每个子插件通过 symlink 出现在 `~/.opencli/plugins/<name>/`
- 更新任何子插件会拉取整个 monorepo 并刷新所有子插件
- 卸载最后一个子插件时,monorepo 目录会被自动清理
## 版本追踪
OpenCLI 会把已安装 plugin 的版本记录到 `~/.opencli/plugins.lock.json`。每条记录会保存 plugin source、当前 git commit hash、安装时间,以及最近一次更新时间。只要有这份元数据,`opencli plugin list` 就会显示对应的短 commit hash。
## YAML plugin 示例
```text
+582
View File
@@ -0,0 +1,582 @@
//#region src/protocol.ts
/** Default daemon port */
var DAEMON_PORT = 19825;
var DAEMON_HOST = "localhost";
var DAEMON_WS_URL = `ws://${DAEMON_HOST}:${DAEMON_PORT}/ext`;
`${DAEMON_HOST}${DAEMON_PORT}`;
/** Base reconnect delay for extension WebSocket (ms) */
var WS_RECONNECT_BASE_DELAY = 2e3;
/** Max reconnect delay (ms) */
var WS_RECONNECT_MAX_DELAY = 6e4;
//#endregion
//#region src/cdp.ts
/**
* CDP execution via chrome.debugger API.
*
* chrome.debugger only needs the "debugger" permission — no host_permissions.
* It can attach to any http/https tab. Avoid chrome:// and chrome-extension://
* tabs (resolveTabId in background.ts filters them).
*/
var attached = /* @__PURE__ */ new Set();
/** Check if a URL can be attached via CDP */
function isDebuggableUrl$1(url) {
if (!url) return true;
return !url.startsWith("chrome://") && !url.startsWith("chrome-extension://");
}
async function ensureAttached(tabId) {
try {
const tab = await chrome.tabs.get(tabId);
if (!isDebuggableUrl$1(tab.url)) {
attached.delete(tabId);
throw new Error(`Cannot debug tab ${tabId}: URL is ${tab.url ?? "unknown"}`);
}
} catch (e) {
if (e instanceof Error && e.message.startsWith("Cannot debug tab")) throw e;
attached.delete(tabId);
throw new Error(`Tab ${tabId} no longer exists`);
}
if (attached.has(tabId)) try {
await chrome.debugger.sendCommand({ tabId }, "Runtime.evaluate", {
expression: "1",
returnByValue: true
});
return;
} catch {
attached.delete(tabId);
}
try {
await chrome.debugger.attach({ tabId }, "1.3");
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
const hint = msg.includes("chrome-extension://") ? ". Tip: another Chrome extension may be interfering — try disabling other extensions" : "";
if (msg.includes("Another debugger is already attached")) {
try {
await chrome.debugger.detach({ tabId });
} catch {}
try {
await chrome.debugger.attach({ tabId }, "1.3");
} catch {
throw new Error(`attach failed: ${msg}${hint}`);
}
} else throw new Error(`attach failed: ${msg}${hint}`);
}
attached.add(tabId);
try {
await chrome.debugger.sendCommand({ tabId }, "Runtime.enable");
} catch {}
}
async function evaluate(tabId, expression) {
await ensureAttached(tabId);
const result = await chrome.debugger.sendCommand({ tabId }, "Runtime.evaluate", {
expression,
returnByValue: true,
awaitPromise: true
});
if (result.exceptionDetails) {
const errMsg = result.exceptionDetails.exception?.description || result.exceptionDetails.text || "Eval error";
throw new Error(errMsg);
}
return result.result?.value;
}
var evaluateAsync = evaluate;
/**
* Capture a screenshot via CDP Page.captureScreenshot.
* Returns base64-encoded image data.
*/
async function screenshot(tabId, options = {}) {
await ensureAttached(tabId);
const format = options.format ?? "png";
if (options.fullPage) {
const metrics = await chrome.debugger.sendCommand({ tabId }, "Page.getLayoutMetrics");
const size = metrics.cssContentSize || metrics.contentSize;
if (size) await chrome.debugger.sendCommand({ tabId }, "Emulation.setDeviceMetricsOverride", {
mobile: false,
width: Math.ceil(size.width),
height: Math.ceil(size.height),
deviceScaleFactor: 1
});
}
try {
const params = { format };
if (format === "jpeg" && options.quality !== void 0) params.quality = Math.max(0, Math.min(100, options.quality));
return (await chrome.debugger.sendCommand({ tabId }, "Page.captureScreenshot", params)).data;
} finally {
if (options.fullPage) await chrome.debugger.sendCommand({ tabId }, "Emulation.clearDeviceMetricsOverride").catch(() => {});
}
}
async function detach(tabId) {
if (!attached.has(tabId)) return;
attached.delete(tabId);
try {
await chrome.debugger.detach({ tabId });
} catch {}
}
function registerListeners() {
chrome.tabs.onRemoved.addListener((tabId) => {
attached.delete(tabId);
});
chrome.debugger.onDetach.addListener((source) => {
if (source.tabId) attached.delete(source.tabId);
});
chrome.tabs.onUpdated.addListener(async (tabId, info) => {
if (info.url && !isDebuggableUrl$1(info.url)) await detach(tabId);
});
}
//#endregion
//#region src/background.ts
var ws = null;
var reconnectTimer = null;
var reconnectAttempts = 0;
var _origLog = console.log.bind(console);
var _origWarn = console.warn.bind(console);
var _origError = console.error.bind(console);
function forwardLog(level, args) {
if (!ws || ws.readyState !== WebSocket.OPEN) return;
try {
const msg = args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ");
ws.send(JSON.stringify({
type: "log",
level,
msg,
ts: Date.now()
}));
} catch {}
}
console.log = (...args) => {
_origLog(...args);
forwardLog("info", args);
};
console.warn = (...args) => {
_origWarn(...args);
forwardLog("warn", args);
};
console.error = (...args) => {
_origError(...args);
forwardLog("error", args);
};
function connect() {
if (ws?.readyState === WebSocket.OPEN || ws?.readyState === WebSocket.CONNECTING) return;
try {
ws = new WebSocket(DAEMON_WS_URL);
} catch {
scheduleReconnect();
return;
}
ws.onopen = () => {
console.log("[opencli] Connected to daemon");
reconnectAttempts = 0;
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
};
ws.onmessage = async (event) => {
try {
const result = await handleCommand(JSON.parse(event.data));
ws?.send(JSON.stringify(result));
} catch (err) {
console.error("[opencli] Message handling error:", err);
}
};
ws.onclose = () => {
console.log("[opencli] Disconnected from daemon");
ws = null;
scheduleReconnect();
};
ws.onerror = () => {
ws?.close();
};
}
function scheduleReconnect() {
if (reconnectTimer) return;
reconnectAttempts++;
const delay = Math.min(WS_RECONNECT_BASE_DELAY * Math.pow(2, reconnectAttempts - 1), WS_RECONNECT_MAX_DELAY);
reconnectTimer = setTimeout(() => {
reconnectTimer = null;
connect();
}, delay);
}
var automationSessions = /* @__PURE__ */ new Map();
var WINDOW_IDLE_TIMEOUT = 12e4;
function getWorkspaceKey(workspace) {
return workspace?.trim() || "default";
}
function resetWindowIdleTimer(workspace) {
const session = automationSessions.get(workspace);
if (!session) return;
if (session.idleTimer) clearTimeout(session.idleTimer);
session.idleDeadlineAt = Date.now() + WINDOW_IDLE_TIMEOUT;
session.idleTimer = setTimeout(async () => {
const current = automationSessions.get(workspace);
if (!current) return;
try {
await chrome.windows.remove(current.windowId);
console.log(`[opencli] Automation window ${current.windowId} (${workspace}) closed (idle timeout)`);
} catch {}
automationSessions.delete(workspace);
}, WINDOW_IDLE_TIMEOUT);
}
/** Get or create the dedicated automation window. */
async function getAutomationWindow(workspace) {
const existing = automationSessions.get(workspace);
if (existing) try {
await chrome.windows.get(existing.windowId);
return existing.windowId;
} catch {
automationSessions.delete(workspace);
}
const session = {
windowId: (await chrome.windows.create({
url: "data:text/html,<html></html>",
focused: false,
width: 1280,
height: 900,
type: "normal"
})).id,
idleTimer: null,
idleDeadlineAt: Date.now() + WINDOW_IDLE_TIMEOUT
};
automationSessions.set(workspace, session);
console.log(`[opencli] Created automation window ${session.windowId} (${workspace})`);
resetWindowIdleTimer(workspace);
await new Promise((resolve) => setTimeout(resolve, 200));
return session.windowId;
}
chrome.windows.onRemoved.addListener((windowId) => {
for (const [workspace, session] of automationSessions.entries()) if (session.windowId === windowId) {
console.log(`[opencli] Automation window closed (${workspace})`);
if (session.idleTimer) clearTimeout(session.idleTimer);
automationSessions.delete(workspace);
}
});
var initialized = false;
function initialize() {
if (initialized) return;
initialized = true;
chrome.alarms.create("keepalive", { periodInMinutes: .4 });
registerListeners();
connect();
console.log("[opencli] OpenCLI extension initialized");
}
chrome.runtime.onInstalled.addListener(() => {
initialize();
});
chrome.runtime.onStartup.addListener(() => {
initialize();
});
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === "keepalive") connect();
});
async function handleCommand(cmd) {
const workspace = getWorkspaceKey(cmd.workspace);
resetWindowIdleTimer(workspace);
try {
switch (cmd.action) {
case "exec": return await handleExec(cmd, workspace);
case "navigate": return await handleNavigate(cmd, workspace);
case "tabs": return await handleTabs(cmd, workspace);
case "cookies": return await handleCookies(cmd);
case "screenshot": return await handleScreenshot(cmd, workspace);
case "close-window": return await handleCloseWindow(cmd, workspace);
case "sessions": return await handleSessions(cmd);
default: return {
id: cmd.id,
ok: false,
error: `Unknown action: ${cmd.action}`
};
}
} catch (err) {
return {
id: cmd.id,
ok: false,
error: err instanceof Error ? err.message : String(err)
};
}
}
/** Check if a URL can be attached via CDP (not chrome:// or chrome-extension://) */
function isDebuggableUrl(url) {
if (!url) return true;
return !url.startsWith("chrome://") && !url.startsWith("chrome-extension://");
}
/**
* Resolve target tab in the automation window.
* If explicit tabId is given, use that directly.
* Otherwise, find or create a tab in the dedicated automation window.
*/
async function resolveTabId(tabId, workspace) {
if (tabId !== void 0) try {
const tab = await chrome.tabs.get(tabId);
if (isDebuggableUrl(tab.url)) return tabId;
console.warn(`[opencli] Tab ${tabId} URL is not debuggable (${tab.url}), re-resolving`);
} catch {
console.warn(`[opencli] Tab ${tabId} no longer exists, re-resolving`);
}
const windowId = await getAutomationWindow(workspace);
const tabs = await chrome.tabs.query({ windowId });
const debuggableTab = tabs.find((t) => t.id && isDebuggableUrl(t.url));
if (debuggableTab?.id) return debuggableTab.id;
const reuseTab = tabs.find((t) => t.id);
if (reuseTab?.id) {
await chrome.tabs.update(reuseTab.id, { url: "data:text/html,<html></html>" });
await new Promise((resolve) => setTimeout(resolve, 300));
try {
const updated = await chrome.tabs.get(reuseTab.id);
if (isDebuggableUrl(updated.url)) return reuseTab.id;
console.warn(`[opencli] data: URI was intercepted (${updated.url}), creating fresh tab`);
} catch {}
}
const newTab = await chrome.tabs.create({
windowId,
url: "data:text/html,<html></html>",
active: true
});
if (!newTab.id) throw new Error("Failed to create tab in automation window");
return newTab.id;
}
async function listAutomationTabs(workspace) {
const session = automationSessions.get(workspace);
if (!session) return [];
try {
return await chrome.tabs.query({ windowId: session.windowId });
} catch {
automationSessions.delete(workspace);
return [];
}
}
async function listAutomationWebTabs(workspace) {
return (await listAutomationTabs(workspace)).filter((tab) => isDebuggableUrl(tab.url));
}
async function handleExec(cmd, workspace) {
if (!cmd.code) return {
id: cmd.id,
ok: false,
error: "Missing code"
};
const tabId = await resolveTabId(cmd.tabId, workspace);
try {
const data = await evaluateAsync(tabId, cmd.code);
return {
id: cmd.id,
ok: true,
data
};
} catch (err) {
return {
id: cmd.id,
ok: false,
error: err instanceof Error ? err.message : String(err)
};
}
}
async function handleNavigate(cmd, workspace) {
if (!cmd.url) return {
id: cmd.id,
ok: false,
error: "Missing url"
};
const tabId = await resolveTabId(cmd.tabId, workspace);
const beforeUrl = (await chrome.tabs.get(tabId)).url ?? "";
const targetUrl = cmd.url;
await detach(tabId);
await chrome.tabs.update(tabId, { url: targetUrl });
let timedOut = false;
await new Promise((resolve) => {
let urlChanged = false;
const listener = (id, info, tab) => {
if (id !== tabId) return;
if (info.url && info.url !== beforeUrl) urlChanged = true;
if (urlChanged && info.status === "complete") {
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
};
chrome.tabs.onUpdated.addListener(listener);
setTimeout(async () => {
try {
const currentTab = await chrome.tabs.get(tabId);
if (currentTab.url !== beforeUrl && currentTab.status === "complete") {
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
} catch {}
}, 100);
setTimeout(() => {
chrome.tabs.onUpdated.removeListener(listener);
timedOut = true;
console.warn(`[opencli] Navigate to ${targetUrl} timed out after 15s`);
resolve();
}, 15e3);
});
const tab = await chrome.tabs.get(tabId);
return {
id: cmd.id,
ok: true,
data: {
title: tab.title,
url: tab.url,
tabId,
timedOut
}
};
}
async function handleTabs(cmd, workspace) {
switch (cmd.op) {
case "list": {
const data = (await listAutomationWebTabs(workspace)).map((t, i) => ({
index: i,
tabId: t.id,
url: t.url,
title: t.title,
active: t.active
}));
return {
id: cmd.id,
ok: true,
data
};
}
case "new": {
const windowId = await getAutomationWindow(workspace);
const tab = await chrome.tabs.create({
windowId,
url: cmd.url ?? "data:text/html,<html></html>",
active: true
});
return {
id: cmd.id,
ok: true,
data: {
tabId: tab.id,
url: tab.url
}
};
}
case "close": {
if (cmd.index !== void 0) {
const target = (await listAutomationWebTabs(workspace))[cmd.index];
if (!target?.id) return {
id: cmd.id,
ok: false,
error: `Tab index ${cmd.index} not found`
};
await chrome.tabs.remove(target.id);
await detach(target.id);
return {
id: cmd.id,
ok: true,
data: { closed: target.id }
};
}
const tabId = await resolveTabId(cmd.tabId, workspace);
await chrome.tabs.remove(tabId);
await detach(tabId);
return {
id: cmd.id,
ok: true,
data: { closed: tabId }
};
}
case "select": {
if (cmd.index === void 0 && cmd.tabId === void 0) return {
id: cmd.id,
ok: false,
error: "Missing index or tabId"
};
if (cmd.tabId !== void 0) {
await chrome.tabs.update(cmd.tabId, { active: true });
return {
id: cmd.id,
ok: true,
data: { selected: cmd.tabId }
};
}
const target = (await listAutomationWebTabs(workspace))[cmd.index];
if (!target?.id) return {
id: cmd.id,
ok: false,
error: `Tab index ${cmd.index} not found`
};
await chrome.tabs.update(target.id, { active: true });
return {
id: cmd.id,
ok: true,
data: { selected: target.id }
};
}
default: return {
id: cmd.id,
ok: false,
error: `Unknown tabs op: ${cmd.op}`
};
}
}
async function handleCookies(cmd) {
const details = {};
if (cmd.domain) details.domain = cmd.domain;
if (cmd.url) details.url = cmd.url;
const data = (await chrome.cookies.getAll(details)).map((c) => ({
name: c.name,
value: c.value,
domain: c.domain,
path: c.path,
secure: c.secure,
httpOnly: c.httpOnly,
expirationDate: c.expirationDate
}));
return {
id: cmd.id,
ok: true,
data
};
}
async function handleScreenshot(cmd, workspace) {
const tabId = await resolveTabId(cmd.tabId, workspace);
try {
const data = await screenshot(tabId, {
format: cmd.format,
quality: cmd.quality,
fullPage: cmd.fullPage
});
return {
id: cmd.id,
ok: true,
data
};
} catch (err) {
return {
id: cmd.id,
ok: false,
error: err instanceof Error ? err.message : String(err)
};
}
}
async function handleCloseWindow(cmd, workspace) {
const session = automationSessions.get(workspace);
if (session) {
try {
await chrome.windows.remove(session.windowId);
} catch {}
if (session.idleTimer) clearTimeout(session.idleTimer);
automationSessions.delete(workspace);
}
return {
id: cmd.id,
ok: true,
data: { closed: true }
};
}
async function handleSessions(cmd) {
const now = Date.now();
const data = await Promise.all([...automationSessions.entries()].map(async ([workspace, session]) => ({
workspace,
windowId: session.windowId,
tabCount: (await chrome.tabs.query({ windowId: session.windowId })).filter((tab) => isDebuggableUrl(tab.url)).length,
idleMsRemaining: Math.max(0, session.idleDeadlineAt - now)
})));
return {
id: cmd.id,
ok: true,
data
};
}
//#endregion
+2 -10
View File
@@ -1,19 +1,15 @@
{
"manifest_version": 3,
"name": "OpenCLI",
"version": "1.5.5",
"description": "Browser automation bridge for the OpenCLI CLI tool. Executes commands in isolated Chrome windows via a local daemon.",
"version": "1.2.6",
"description": "Bridge between opencli CLI and your browser — execute commands, read cookies, manage tabs.",
"permissions": [
"debugger",
"scripting",
"tabs",
"cookies",
"activeTab",
"alarms"
],
"host_permissions": [
"<all_urls>"
],
"background": {
"service_worker": "dist/background.js",
"type": "module"
@@ -26,14 +22,10 @@
},
"action": {
"default_title": "OpenCLI",
"default_popup": "popup.html",
"default_icon": {
"16": "icons/icon-16.png",
"32": "icons/icon-32.png"
}
},
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'"
},
"homepage_url": "https://github.com/jackwener/opencli"
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "opencli-extension",
"version": "1.5.5",
"version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opencli-extension",
"version": "1.5.5",
"version": "0.2.0",
"devDependencies": {
"@types/chrome": "^0.0.287",
"typescript": "^5.7.0",
+1 -2
View File
@@ -1,12 +1,11 @@
{
"name": "opencli-extension",
"version": "1.5.5",
"version": "1.2.6",
"private": true,
"type": "module",
"scripts": {
"dev": "vite build --watch",
"build": "vite build",
"package:release": "node scripts/package-release.mjs",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
-84
View File
@@ -1,84 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
width: 280px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 13px;
color: #333;
background: #fff;
padding: 16px;
}
.header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 14px;
}
.header img { width: 24px; height: 24px; }
.header h1 { font-size: 15px; font-weight: 600; }
.status-row {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
border-radius: 8px;
background: #f5f5f5;
}
.dot {
width: 8px; height: 8px;
border-radius: 50%;
flex-shrink: 0;
}
.dot.connected { background: #34c759; }
.dot.disconnected { background: #ff3b30; }
.dot.connecting { background: #ff9500; }
.status-text { font-size: 13px; color: #555; }
.status-text strong { color: #333; }
.hint {
margin-top: 10px;
padding: 8px 10px;
border-radius: 6px;
background: #f0f4ff;
font-size: 11px;
color: #666;
line-height: 1.5;
display: none;
}
.hint code {
background: #e8ecf1;
padding: 1px 4px;
border-radius: 3px;
font-size: 11px;
}
.footer {
margin-top: 14px;
text-align: center;
font-size: 11px;
color: #999;
}
.footer a { color: #007aff; text-decoration: none; }
.footer a:hover { text-decoration: underline; }
</style>
</head>
<body>
<div class="header">
<img src="icons/icon-48.png" alt="OpenCLI">
<h1>OpenCLI</h1>
</div>
<div class="status-row">
<span class="dot disconnected" id="dot"></span>
<span class="status-text" id="status">Checking...</span>
</div>
<div class="hint" id="hint">
This is normal. The extension connects automatically when you run any <code>opencli</code> command.
</div>
<div class="footer">
<a href="https://github.com/jackwener/opencli" target="_blank">Documentation</a>
</div>
<script src="popup.js"></script>
</body>
</html>
-25
View File
@@ -1,25 +0,0 @@
// Query connection status from background service worker
chrome.runtime.sendMessage({ type: 'getStatus' }, (resp) => {
const dot = document.getElementById('dot');
const status = document.getElementById('status');
const hint = document.getElementById('hint');
if (chrome.runtime.lastError || !resp) {
dot.className = 'dot disconnected';
status.innerHTML = '<strong>No daemon connected</strong>';
hint.style.display = 'block';
return;
}
if (resp.connected) {
dot.className = 'dot connected';
status.innerHTML = '<strong>Connected to daemon</strong>';
hint.style.display = 'none';
} else if (resp.reconnecting) {
dot.className = 'dot connecting';
status.innerHTML = '<strong>Reconnecting...</strong>';
hint.style.display = 'none';
} else {
dot.className = 'dot disconnected';
status.innerHTML = '<strong>No daemon connected</strong>';
hint.style.display = 'block';
}
});
-179
View File
@@ -1,179 +0,0 @@
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const extensionDir = path.resolve(__dirname, '..');
const repoRoot = path.resolve(extensionDir, '..');
function parseArgs(argv) {
const args = { outDir: path.join(repoRoot, 'extension-package') };
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--out' && argv[i + 1]) {
const outDir = argv[++i];
args.outDir = path.isAbsolute(outDir)
? outDir
: path.resolve(process.cwd(), outDir);
}
}
return args;
}
async function exists(targetPath) {
try {
await fs.access(targetPath);
return true;
} catch {
return false;
}
}
function isLocalAsset(ref) {
return typeof ref === 'string'
&& ref.length > 0
&& !ref.startsWith('http://')
&& !ref.startsWith('https://')
&& !ref.startsWith('//')
&& !ref.startsWith('chrome://')
&& !ref.startsWith('chrome-extension://')
&& !ref.startsWith('data:')
&& !ref.startsWith('#');
}
function addLocalAsset(files, ref) {
if (isLocalAsset(ref)) files.add(ref);
}
function collectManifestEntrypoints(manifest) {
const files = new Set(['manifest.json']);
addLocalAsset(files, manifest.background?.service_worker);
addLocalAsset(files, manifest.action?.default_popup);
addLocalAsset(files, manifest.options_page);
addLocalAsset(files, manifest.devtools_page);
addLocalAsset(files, manifest.side_panel?.default_path);
for (const ref of Object.values(manifest.icons ?? {})) addLocalAsset(files, ref);
for (const ref of Object.values(manifest.action?.default_icon ?? {})) addLocalAsset(files, ref);
for (const contentScript of manifest.content_scripts ?? []) {
for (const jsFile of contentScript.js ?? []) addLocalAsset(files, jsFile);
for (const cssFile of contentScript.css ?? []) addLocalAsset(files, cssFile);
}
for (const page of manifest.sandbox?.pages ?? []) addLocalAsset(files, page);
for (const overridePage of Object.values(manifest.chrome_url_overrides ?? {})) addLocalAsset(files, overridePage);
for (const entry of manifest.web_accessible_resources ?? []) {
for (const resource of entry.resources ?? []) addLocalAsset(files, resource);
}
if (manifest.default_locale) files.add('_locales');
return [...files];
}
async function collectHtmlDependencies(relativeHtmlPath, files, visited) {
if (visited.has(relativeHtmlPath)) return;
visited.add(relativeHtmlPath);
const htmlPath = path.join(extensionDir, relativeHtmlPath);
const html = await fs.readFile(htmlPath, 'utf8');
const attrRe = /\b(?:src|href)=["']([^"'#?]+(?:\?[^"']*)?)["']/gi;
for (const match of html.matchAll(attrRe)) {
const rawRef = match[1];
const cleanRef = rawRef.split('?')[0];
if (!isLocalAsset(cleanRef)) continue;
const resolvedRelativePath = cleanRef.startsWith('/')
? cleanRef.slice(1)
: path.posix.normalize(path.posix.join(path.posix.dirname(relativeHtmlPath), cleanRef));
addLocalAsset(files, resolvedRelativePath);
if (resolvedRelativePath.endsWith('.html')) {
await collectHtmlDependencies(resolvedRelativePath, files, visited);
}
}
}
async function collectManifestAssets(manifest) {
const files = new Set(collectManifestEntrypoints(manifest));
const htmlPages = [];
if (manifest.action?.default_popup) {
htmlPages.push(manifest.action.default_popup);
}
if (manifest.options_page) htmlPages.push(manifest.options_page);
if (manifest.devtools_page) htmlPages.push(manifest.devtools_page);
if (manifest.side_panel?.default_path) htmlPages.push(manifest.side_panel.default_path);
for (const page of manifest.sandbox?.pages ?? []) htmlPages.push(page);
for (const overridePage of Object.values(manifest.chrome_url_overrides ?? {})) htmlPages.push(overridePage);
const visited = new Set();
for (const htmlPage of htmlPages) {
if (isLocalAsset(htmlPage)) {
await collectHtmlDependencies(htmlPage, files, visited);
}
}
return [...files];
}
async function copyEntry(relativePath, outDir) {
const fromPath = path.join(extensionDir, relativePath);
const toPath = path.join(outDir, relativePath);
const stats = await fs.stat(fromPath);
if (stats.isDirectory()) {
await fs.cp(fromPath, toPath, { recursive: true });
return;
}
await fs.mkdir(path.dirname(toPath), { recursive: true });
await fs.copyFile(fromPath, toPath);
}
async function findMissingEntries(baseDir, entries) {
const missingEntries = [];
for (const relativePath of entries) {
const absolutePath = path.join(baseDir, relativePath);
if (!(await exists(absolutePath))) {
missingEntries.push(relativePath);
}
}
return missingEntries;
}
async function main() {
const { outDir } = parseArgs(process.argv.slice(2));
const manifestPath = path.join(extensionDir, 'manifest.json');
const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
const requiredEntries = await collectManifestAssets(manifest);
const missingEntries = await findMissingEntries(extensionDir, requiredEntries);
if (missingEntries.length > 0) {
console.error('Missing files referenced by the extension package:');
for (const missingEntry of missingEntries) console.error(`- ${missingEntry}`);
process.exit(1);
}
await fs.rm(outDir, { recursive: true, force: true });
await fs.mkdir(outDir, { recursive: true });
for (const relativePath of requiredEntries) {
await copyEntry(relativePath, outDir);
}
// Guard against regressions where manifest entry files (e.g. action.default_popup)
// are accidentally omitted from the packaged directory.
const packagedEntrypoints = collectManifestEntrypoints(manifest);
const missingPackagedEntrypoints = await findMissingEntries(outDir, packagedEntrypoints);
if (missingPackagedEntrypoints.length > 0) {
console.error('Packaged extension is missing files referenced by manifest.json:');
for (const missingEntry of missingPackagedEntrypoints) console.error(`- ${missingEntry}`);
process.exit(1);
}
console.log(`Extension package prepared at ${path.relative(repoRoot, outDir) || outDir}`);
}
await main();
+3 -92
View File
@@ -1,4 +1,4 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
type Listener<T extends (...args: any[]) => void> = { addListener: (fn: T) => void };
@@ -35,12 +35,8 @@ function createChromeMock() {
{ id: 3, windowId: 1, url: 'chrome://extensions', title: 'chrome', active: false, status: 'complete' },
];
const query = vi.fn(async (queryInfo: { windowId?: number; active?: boolean } = {}) => {
return tabs.filter((tab) => {
if (queryInfo.windowId !== undefined && tab.windowId !== queryInfo.windowId) return false;
if (queryInfo.active !== undefined && !!tab.active !== queryInfo.active) return false;
return true;
});
const query = vi.fn(async (queryInfo: { windowId?: number } = {}) => {
return tabs.filter((tab) => queryInfo.windowId === undefined || tab.windowId === queryInfo.windowId);
});
const create = vi.fn(async ({ windowId, url, active }: { windowId?: number; url?: string; active?: boolean }) => {
const tab: MockTab = {
@@ -88,8 +84,6 @@ function createChromeMock() {
runtime: {
onInstalled: { addListener: vi.fn() } as Listener<() => void>,
onStartup: { addListener: vi.fn() } as Listener<() => void>,
onMessage: { addListener: vi.fn() } as Listener<(msg: unknown, sender: unknown, sendResponse: (value: unknown) => void) => void>,
getManifest: vi.fn(() => ({ version: 'test-version' })),
},
cookies: {
getAll: vi.fn(async () => []),
@@ -102,15 +96,9 @@ function createChromeMock() {
describe('background tab isolation', () => {
beforeEach(() => {
vi.resetModules();
vi.useRealTimers();
vi.stubGlobal('WebSocket', MockWebSocket);
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it('lists only automation-window web tabs', async () => {
const { chrome } = createChromeMock();
vi.stubGlobal('chrome', chrome);
@@ -145,45 +133,6 @@ describe('background tab isolation', () => {
expect(create).toHaveBeenCalledWith({ windowId: 1, url: 'https://new.example', active: true });
});
it('treats normalized same-url navigate as already complete', async () => {
const { chrome, tabs, update } = createChromeMock();
tabs[0].url = 'https://www.bilibili.com/';
tabs[0].title = 'bilibili';
tabs[0].status = 'complete';
vi.stubGlobal('chrome', chrome);
const mod = await import('./background');
mod.__test__.setAutomationWindowId('site:bilibili', 1);
const result = await mod.__test__.handleNavigate(
{ id: 'same-url', action: 'navigate', url: 'https://www.bilibili.com', workspace: 'site:bilibili' },
'site:bilibili',
);
expect(result).toEqual({
id: 'same-url',
ok: true,
data: {
title: 'bilibili',
url: 'https://www.bilibili.com/',
tabId: 1,
timedOut: false,
},
});
expect(update).not.toHaveBeenCalled();
});
it('keeps hash routes distinct when comparing target URLs', async () => {
const { chrome } = createChromeMock();
vi.stubGlobal('chrome', chrome);
const mod = await import('./background');
expect(mod.__test__.isTargetUrl('https://example.com/', 'https://example.com')).toBe(true);
expect(mod.__test__.isTargetUrl('https://example.com/#feed', 'https://example.com/#settings')).toBe(false);
expect(mod.__test__.isTargetUrl('https://example.com/app/', 'https://example.com/app')).toBe(false);
});
it('reports sessions per workspace', async () => {
const { chrome } = createChromeMock();
vi.stubGlobal('chrome', chrome);
@@ -199,42 +148,4 @@ describe('background tab isolation', () => {
expect.objectContaining({ workspace: 'site:zhihu', windowId: 2 }),
]));
});
it('keeps site:notebooklm inside its owned automation window instead of rebinding to a user tab', async () => {
const { chrome, tabs } = createChromeMock();
tabs[0].url = 'https://notebooklm.google.com/';
tabs[0].title = 'NotebookLM Home';
tabs[1].url = 'https://notebooklm.google.com/notebook/nb-live';
tabs[1].title = 'Live Notebook';
vi.stubGlobal('chrome', chrome);
const mod = await import('./background');
mod.__test__.setAutomationWindowId('site:notebooklm', 1);
const tabId = await mod.__test__.resolveTabId(undefined, 'site:notebooklm');
expect(tabId).toBe(1);
expect(mod.__test__.getSession('site:notebooklm')).toEqual(expect.objectContaining({
windowId: 1,
}));
});
it('idle timeout closes the automation window for site:notebooklm', async () => {
const { chrome, tabs } = createChromeMock();
tabs[0].url = 'https://notebooklm.google.com/';
tabs[0].title = 'NotebookLM Home';
tabs[0].active = true;
vi.useFakeTimers();
vi.stubGlobal('chrome', chrome);
const mod = await import('./background');
mod.__test__.setAutomationWindowId('site:notebooklm', 1);
mod.__test__.resetWindowIdleTimer('site:notebooklm');
await vi.advanceTimersByTimeAsync(30001);
expect(chrome.windows.remove).toHaveBeenCalledWith(1);
expect(mod.__test__.getSession('site:notebooklm')).toBeNull();
});
});
+42 -223
View File
@@ -6,7 +6,7 @@
*/
import type { Command, Result } from './protocol';
import { DAEMON_WS_URL, DAEMON_PING_URL, WS_RECONNECT_BASE_DELAY, WS_RECONNECT_MAX_DELAY } from './protocol';
import { DAEMON_WS_URL, WS_RECONNECT_BASE_DELAY, WS_RECONNECT_MAX_DELAY } from './protocol';
import * as executor from './cdp';
let ws: WebSocket | null = null;
@@ -34,23 +34,9 @@ console.error = (...args: unknown[]) => { _origError(...args); forwardLog('error
// ─── WebSocket connection ────────────────────────────────────────────
/**
* Probe the daemon via its /ping HTTP endpoint before attempting a WebSocket
* connection. fetch() failures are silently catchable; new WebSocket() is not
* — Chrome logs ERR_CONNECTION_REFUSED to the extension error page before any
* JS handler can intercept it. By keeping the probe inside connect() every
* call site remains unchanged and the guard can never be accidentally skipped.
*/
async function connect(): Promise<void> {
function connect(): void {
if (ws?.readyState === WebSocket.OPEN || ws?.readyState === WebSocket.CONNECTING) return;
try {
const res = await fetch(DAEMON_PING_URL, { signal: AbortSignal.timeout(1000) });
if (!res.ok) return; // unexpected response — not our daemon
} catch {
return; // daemon not running — skip WebSocket to avoid console noise
}
try {
ws = new WebSocket(DAEMON_WS_URL);
} catch {
@@ -65,8 +51,6 @@ async function connect(): Promise<void> {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
// Send version so the daemon can report mismatches to the CLI
ws?.send(JSON.stringify({ type: 'hello', version: chrome.runtime.getManifest().version }));
};
ws.onmessage = async (event) => {
@@ -90,21 +74,14 @@ async function connect(): Promise<void> {
};
}
/**
* After MAX_EAGER_ATTEMPTS (reaching 60s backoff), stop scheduling reconnects.
* The keepalive alarm (~24s) will still call connect() periodically, but at a
* much lower frequency — reducing console noise when the daemon is not running.
*/
const MAX_EAGER_ATTEMPTS = 6; // 2s, 4s, 8s, 16s, 32s, 60s — then stop
function scheduleReconnect(): void {
if (reconnectTimer) return;
reconnectAttempts++;
if (reconnectAttempts > MAX_EAGER_ATTEMPTS) return; // let keepalive alarm handle it
// Exponential backoff: 2s, 4s, 8s, 16s, ..., capped at 60s
const delay = Math.min(WS_RECONNECT_BASE_DELAY * Math.pow(2, reconnectAttempts - 1), WS_RECONNECT_MAX_DELAY);
reconnectTimer = setTimeout(() => {
reconnectTimer = null;
void connect();
connect();
}, delay);
}
@@ -120,7 +97,7 @@ type AutomationSession = {
};
const automationSessions = new Map<string, AutomationSession>();
const WINDOW_IDLE_TIMEOUT = 30000; // 30s — quick cleanup after command finishes
const WINDOW_IDLE_TIMEOUT = 120000; // 120s — longer to survive slow pipelines
function getWorkspaceKey(workspace?: string): string {
return workspace?.trim() || 'default';
@@ -160,10 +137,8 @@ async function getAutomationWindow(workspace: string): Promise<number> {
// Create a new window with a data: URI that New Tab Override extensions cannot intercept.
// Using about:blank would be hijacked by extensions like "New Tab Override".
// Note: Do NOT set `state` parameter here. Chrome 146+ rejects 'normal' as an invalid
// state value for windows.create(). The window defaults to 'normal' state anyway.
const win = await chrome.windows.create({
url: BLANK_PAGE,
url: 'data:text/html,<html></html>',
focused: false,
width: 1280,
height: 900,
@@ -202,7 +177,7 @@ function initialize(): void {
initialized = true;
chrome.alarms.create('keepalive', { periodInMinutes: 0.4 }); // ~24 seconds
executor.registerListeners();
void connect();
connect();
console.log('[opencli] OpenCLI extension initialized');
}
@@ -215,19 +190,7 @@ chrome.runtime.onStartup.addListener(() => {
});
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'keepalive') void connect();
});
// ─── Popup status API ───────────────────────────────────────────────
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg?.type === 'getStatus') {
sendResponse({
connected: ws?.readyState === WebSocket.OPEN,
reconnecting: reconnectTimer !== null,
});
}
return false;
if (alarm.name === 'keepalive') connect();
});
// ─── Command dispatcher ─────────────────────────────────────────────
@@ -250,12 +213,8 @@ async function handleCommand(cmd: Command): Promise<Result> {
return await handleScreenshot(cmd, workspace);
case 'close-window':
return await handleCloseWindow(cmd, workspace);
case 'cdp':
return await handleCdp(cmd, workspace);
case 'sessions':
return await handleSessions(cmd);
case 'set-file-input':
return await handleSetFileInput(cmd, workspace);
default:
return { id: cmd.id, ok: false, error: `Unknown action: ${cmd.action}` };
}
@@ -270,47 +229,10 @@ async function handleCommand(cmd: Command): Promise<Result> {
// ─── Action handlers ─────────────────────────────────────────────────
/** Internal blank page used when no user URL is provided. */
const BLANK_PAGE = 'about:blank';
/** Check if a URL can be attached via CDP — only allow http(s) and blank pages. */
/** Check if a URL can be attached via CDP (not chrome:// or chrome-extension://) */
function isDebuggableUrl(url?: string): boolean {
if (!url) return true; // empty/undefined = tab still loading, allow it
return url.startsWith('http://') || url.startsWith('https://') || url === 'about:blank' || url.startsWith('data:');
}
/** Check if a URL is safe for user-facing navigation (http/https only). */
function isSafeNavigationUrl(url: string): boolean {
return url.startsWith('http://') || url.startsWith('https://');
}
/** Minimal URL normalization for same-page comparison: root slash + default port only. */
function normalizeUrlForComparison(url?: string): string {
if (!url) return '';
try {
const parsed = new URL(url);
if ((parsed.protocol === 'https:' && parsed.port === '443') || (parsed.protocol === 'http:' && parsed.port === '80')) {
parsed.port = '';
}
const pathname = parsed.pathname === '/' ? '' : parsed.pathname;
return `${parsed.protocol}//${parsed.host}${pathname}${parsed.search}${parsed.hash}`;
} catch {
return url;
}
}
function isTargetUrl(currentUrl: string | undefined, targetUrl: string): boolean {
return normalizeUrlForComparison(currentUrl) === normalizeUrlForComparison(targetUrl);
}
function setWorkspaceSession(workspace: string, session: Pick<AutomationSession, 'windowId'>): void {
const existing = automationSessions.get(workspace);
if (existing?.idleTimer) clearTimeout(existing.idleTimer);
automationSessions.set(workspace, {
...session,
idleTimer: null,
idleDeadlineAt: Date.now() + WINDOW_IDLE_TIMEOUT,
});
return !url.startsWith('chrome://') && !url.startsWith('chrome-extension://');
}
/**
@@ -325,15 +247,9 @@ async function resolveTabId(tabId: number | undefined, workspace: string): Promi
if (tabId !== undefined) {
try {
const tab = await chrome.tabs.get(tabId);
const session = automationSessions.get(workspace);
const matchesSession = session ? tab.windowId === session.windowId : false;
if (isDebuggableUrl(tab.url) && matchesSession) return tabId;
if (session && !matchesSession) {
console.warn(`[opencli] Tab ${tabId} is not bound to workspace ${workspace}, re-resolving`);
} else if (!isDebuggableUrl(tab.url)) {
// Tab exists but URL is not debuggable — fall through to auto-resolve
console.warn(`[opencli] Tab ${tabId} URL is not debuggable (${tab.url}), re-resolving`);
}
if (isDebuggableUrl(tab.url)) return tabId;
// Tab exists but URL is not debuggable — fall through to auto-resolve
console.warn(`[opencli] Tab ${tabId} URL is not debuggable (${tab.url}), re-resolving`);
} catch {
// Tab was closed — fall through to auto-resolve
console.warn(`[opencli] Tab ${tabId} no longer exists, re-resolving`);
@@ -352,7 +268,7 @@ async function resolveTabId(tabId: number | undefined, workspace: string): Promi
// Try to reuse by navigating to a data: URI (not interceptable by New Tab Override).
const reuseTab = tabs.find(t => t.id);
if (reuseTab?.id) {
await chrome.tabs.update(reuseTab.id, { url: BLANK_PAGE });
await chrome.tabs.update(reuseTab.id, { url: 'data:text/html,<html></html>' });
await new Promise(resolve => setTimeout(resolve, 300));
try {
const updated = await chrome.tabs.get(reuseTab.id);
@@ -364,7 +280,7 @@ async function resolveTabId(tabId: number | undefined, workspace: string): Promi
}
// Fallback: create a new tab
const newTab = await chrome.tabs.create({ windowId, url: BLANK_PAGE, active: true });
const newTab = await chrome.tabs.create({ windowId, url: 'data:text/html,<html></html>', active: true });
if (!newTab.id) throw new Error('Failed to create tab in automation window');
return newTab.id;
}
@@ -389,8 +305,7 @@ async function handleExec(cmd: Command, workspace: string): Promise<Result> {
if (!cmd.code) return { id: cmd.id, ok: false, error: 'Missing code' };
const tabId = await resolveTabId(cmd.tabId, workspace);
try {
const aggressive = workspace.startsWith('operate:');
const data = await executor.evaluateAsync(tabId, cmd.code, aggressive);
const data = await executor.evaluateAsync(tabId, cmd.code);
return { id: cmd.id, ok: true, data };
} catch (err) {
return { id: cmd.id, ok: false, error: err instanceof Error ? err.message : String(err) };
@@ -399,24 +314,13 @@ async function handleExec(cmd: Command, workspace: string): Promise<Result> {
async function handleNavigate(cmd: Command, workspace: string): Promise<Result> {
if (!cmd.url) return { id: cmd.id, ok: false, error: 'Missing url' };
if (!isSafeNavigationUrl(cmd.url)) {
return { id: cmd.id, ok: false, error: 'Blocked URL scheme -- only http:// and https:// are allowed' };
}
const tabId = await resolveTabId(cmd.tabId, workspace);
// Capture the current URL before navigation to detect actual URL change
const beforeTab = await chrome.tabs.get(tabId);
const beforeNormalized = normalizeUrlForComparison(beforeTab.url);
const beforeUrl = beforeTab.url ?? '';
const targetUrl = cmd.url;
// Fast-path: tab is already at the target URL and fully loaded.
if (beforeTab.status === 'complete' && isTargetUrl(beforeTab.url, targetUrl)) {
return {
id: cmd.id,
ok: true,
data: { title: beforeTab.title, url: beforeTab.url, tabId, timedOut: false },
};
}
// Detach any existing debugger before top-level navigation.
// Some sites (observed on creator.xiaohongshu.com flows) can invalidate the
// current inspected target during navigation, which leaves a stale CDP attach
@@ -427,51 +331,45 @@ async function handleNavigate(cmd: Command, workspace: string): Promise<Result>
await chrome.tabs.update(tabId, { url: targetUrl });
// Wait until navigation completes. Resolve when status is 'complete' AND either:
// - the URL matches the target (handles same-URL / canonicalized navigations), OR
// - the URL differs from the pre-navigation URL (handles redirects).
// Wait for: 1) URL to change from the old URL, 2) tab.status === 'complete'
// This avoids the race where 'complete' fires for the OLD URL (e.g. about:blank)
let timedOut = false;
await new Promise<void>((resolve) => {
let settled = false;
let checkTimer: ReturnType<typeof setTimeout> | null = null;
let timeoutTimer: ReturnType<typeof setTimeout> | null = null;
const finish = () => {
if (settled) return;
settled = true;
chrome.tabs.onUpdated.removeListener(listener);
if (checkTimer) clearTimeout(checkTimer);
if (timeoutTimer) clearTimeout(timeoutTimer);
resolve();
};
const isNavigationDone = (url: string | undefined): boolean => {
return isTargetUrl(url, targetUrl) || normalizeUrlForComparison(url) !== beforeNormalized;
};
let urlChanged = false;
const listener = (id: number, info: chrome.tabs.TabChangeInfo, tab: chrome.tabs.Tab) => {
if (id !== tabId) return;
if (info.status === 'complete' && isNavigationDone(tab.url ?? info.url)) {
finish();
// Track URL change (new URL differs from the one before navigation)
if (info.url && info.url !== beforeUrl) {
urlChanged = true;
}
// Only resolve when both URL has changed AND status is complete
if (urlChanged && info.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
};
chrome.tabs.onUpdated.addListener(listener);
// Also check if the tab already navigated (e.g. instant cache hit)
checkTimer = setTimeout(async () => {
setTimeout(async () => {
try {
const currentTab = await chrome.tabs.get(tabId);
if (currentTab.status === 'complete' && isNavigationDone(currentTab.url)) {
finish();
if (currentTab.url !== beforeUrl && currentTab.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
} catch { /* tab gone */ }
}, 100);
// Timeout fallback with warning
timeoutTimer = setTimeout(() => {
setTimeout(() => {
chrome.tabs.onUpdated.removeListener(listener);
timedOut = true;
console.warn(`[opencli] Navigate to ${targetUrl} timed out after 15s`);
finish();
resolve();
}, 15000);
});
@@ -498,11 +396,8 @@ async function handleTabs(cmd: Command, workspace: string): Promise<Result> {
return { id: cmd.id, ok: true, data };
}
case 'new': {
if (cmd.url && !isSafeNavigationUrl(cmd.url)) {
return { id: cmd.id, ok: false, error: 'Blocked URL scheme -- only http:// and https:// are allowed' };
}
const windowId = await getAutomationWindow(workspace);
const tab = await chrome.tabs.create({ windowId, url: cmd.url ?? BLANK_PAGE, active: true });
const tab = await chrome.tabs.create({ windowId, url: cmd.url ?? 'data:text/html,<html></html>', active: true });
return { id: cmd.id, ok: true, data: { tabId: tab.id, url: tab.url } };
}
case 'close': {
@@ -523,16 +418,6 @@ async function handleTabs(cmd: Command, workspace: string): Promise<Result> {
if (cmd.index === undefined && cmd.tabId === undefined)
return { id: cmd.id, ok: false, error: 'Missing index or tabId' };
if (cmd.tabId !== undefined) {
const session = automationSessions.get(workspace);
let tab: chrome.tabs.Tab;
try {
tab = await chrome.tabs.get(cmd.tabId);
} catch {
return { id: cmd.id, ok: false, error: `Tab ${cmd.tabId} no longer exists` };
}
if (!session || tab.windowId !== session.windowId) {
return { id: cmd.id, ok: false, error: `Tab ${cmd.tabId} is not in the automation window` };
}
await chrome.tabs.update(cmd.tabId, { active: true });
return { id: cmd.id, ok: true, data: { selected: cmd.tabId } };
}
@@ -548,9 +433,6 @@ async function handleTabs(cmd: Command, workspace: string): Promise<Result> {
}
async function handleCookies(cmd: Command): Promise<Result> {
if (!cmd.domain && !cmd.url) {
return { id: cmd.id, ok: false, error: 'Cookie scope required: provide domain or url to avoid dumping all cookies' };
}
const details: chrome.cookies.GetAllDetails = {};
if (cmd.domain) details.domain = cmd.domain;
if (cmd.url) details.url = cmd.url;
@@ -581,50 +463,6 @@ async function handleScreenshot(cmd: Command, workspace: string): Promise<Result
}
}
/** CDP methods permitted via the 'cdp' passthrough action. */
const CDP_ALLOWLIST = new Set([
// Agent DOM context
'Accessibility.getFullAXTree',
'DOM.getDocument',
'DOM.getBoxModel',
'DOM.getContentQuads',
'DOM.querySelectorAll',
'DOM.scrollIntoViewIfNeeded',
'DOMSnapshot.captureSnapshot',
// Native input events
'Input.dispatchMouseEvent',
'Input.dispatchKeyEvent',
'Input.insertText',
// Page metrics & screenshots
'Page.getLayoutMetrics',
'Page.captureScreenshot',
// Runtime.enable needed for CDP attach setup (Runtime.evaluate goes through 'exec' action)
'Runtime.enable',
// Emulation (used by screenshot full-page)
'Emulation.setDeviceMetricsOverride',
'Emulation.clearDeviceMetricsOverride',
]);
async function handleCdp(cmd: Command, workspace: string): Promise<Result> {
if (!cmd.cdpMethod) return { id: cmd.id, ok: false, error: 'Missing cdpMethod' };
if (!CDP_ALLOWLIST.has(cmd.cdpMethod)) {
return { id: cmd.id, ok: false, error: `CDP method not permitted: ${cmd.cdpMethod}` };
}
const tabId = await resolveTabId(cmd.tabId, workspace);
try {
const aggressive = workspace.startsWith('operate:');
await executor.ensureAttached(tabId, aggressive);
const data = await chrome.debugger.sendCommand(
{ tabId },
cmd.cdpMethod,
cmd.cdpParams ?? {},
);
return { id: cmd.id, ok: true, data };
} catch (err) {
return { id: cmd.id, ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
async function handleCloseWindow(cmd: Command, workspace: string): Promise<Result> {
const session = automationSessions.get(workspace);
if (session) {
@@ -639,19 +477,6 @@ async function handleCloseWindow(cmd: Command, workspace: string): Promise<Resul
return { id: cmd.id, ok: true, data: { closed: true } };
}
async function handleSetFileInput(cmd: Command, workspace: string): Promise<Result> {
if (!cmd.files || !Array.isArray(cmd.files) || cmd.files.length === 0) {
return { id: cmd.id, ok: false, error: 'Missing or empty files array' };
}
const tabId = await resolveTabId(cmd.tabId, workspace);
try {
await executor.setFileInputFiles(tabId, cmd.files, cmd.selector);
return { id: cmd.id, ok: true, data: { count: cmd.files.length } };
} catch (err) {
return { id: cmd.id, ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
async function handleSessions(cmd: Command): Promise<Result> {
const now = Date.now();
const data = await Promise.all([...automationSessions.entries()].map(async ([workspace, session]) => ({
@@ -664,13 +489,8 @@ async function handleSessions(cmd: Command): Promise<Result> {
}
export const __test__ = {
handleNavigate,
isTargetUrl,
handleTabs,
handleSessions,
resolveTabId,
resetWindowIdleTimer,
getSession: (workspace: string = 'default') => automationSessions.get(workspace) ?? null,
getAutomationWindowId: (workspace: string = 'default') => automationSessions.get(workspace)?.windowId ?? null,
setAutomationWindowId: (workspace: string, windowId: number | null) => {
if (windowId === null) {
@@ -679,11 +499,10 @@ export const __test__ = {
automationSessions.delete(workspace);
return;
}
setWorkspaceSession(workspace, {
automationSessions.set(workspace, {
windowId,
idleTimer: null,
idleDeadlineAt: Date.now() + WINDOW_IDLE_TIMEOUT,
});
},
setSession: (workspace: string, session: { windowId: number }) => {
setWorkspaceSession(workspace, session);
},
};
-75
View File
@@ -1,75 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
function createChromeMock() {
const tabs = {
get: vi.fn(async (_tabId: number) => ({
id: 1,
windowId: 1,
url: 'https://x.com/home',
})),
onRemoved: { addListener: vi.fn() },
onUpdated: { addListener: vi.fn() },
};
const debuggerApi = {
attach: vi.fn(async () => {}),
detach: vi.fn(async () => {}),
sendCommand: vi.fn(async (_target: unknown, method: string) => {
if (method === 'Runtime.evaluate') return { result: { value: 'ok' } };
return {};
}),
onDetach: { addListener: vi.fn() },
};
const scripting = {
executeScript: vi.fn(async () => [{ result: { removed: 1 } }]),
};
return {
chrome: {
tabs,
debugger: debuggerApi,
scripting,
runtime: { id: 'opencli-test' },
},
debuggerApi,
scripting,
};
}
describe('cdp attach recovery', () => {
beforeEach(() => {
vi.resetModules();
});
afterEach(() => {
vi.unstubAllGlobals();
});
it('does not mutate the DOM before a successful attach', async () => {
const { chrome, debuggerApi, scripting } = createChromeMock();
vi.stubGlobal('chrome', chrome);
const mod = await import('./cdp');
const result = await mod.evaluate(1, '1');
expect(result).toBe('ok');
expect(debuggerApi.attach).toHaveBeenCalledTimes(1);
expect(scripting.executeScript).not.toHaveBeenCalled();
});
it('retries after cleanup when attach fails with a foreign extension error', async () => {
const { chrome, debuggerApi, scripting } = createChromeMock();
debuggerApi.attach
.mockRejectedValueOnce(new Error('Cannot access a chrome-extension:// URL of different extension'))
.mockResolvedValueOnce(undefined);
vi.stubGlobal('chrome', chrome);
const mod = await import('./cdp');
const result = await mod.evaluate(1, '1');
expect(result).toBe('ok');
expect(scripting.executeScript).toHaveBeenCalledTimes(1);
expect(debuggerApi.attach).toHaveBeenCalledTimes(2);
});
});
+35 -119
View File
@@ -8,13 +8,13 @@
const attached = new Set<number>();
/** Check if a URL can be attached via CDP — only allow http(s) and blank pages. */
/** Check if a URL can be attached via CDP */
function isDebuggableUrl(url?: string): boolean {
if (!url) return true; // empty/undefined = tab still loading, allow it
return url.startsWith('http://') || url.startsWith('https://') || url === 'about:blank' || url.startsWith('data:');
return !url.startsWith('chrome://') && !url.startsWith('chrome-extension://');
}
export async function ensureAttached(tabId: number, aggressiveRetry: boolean = false): Promise<void> {
async function ensureAttached(tabId: number): Promise<void> {
// Verify the tab URL is debuggable before attempting attach
try {
const tab = await chrome.tabs.get(tabId);
@@ -43,46 +43,23 @@ export async function ensureAttached(tabId: number, aggressiveRetry: boolean = f
}
}
// Retry attach up to 3 times — other extensions (1Password, Playwright MCP Bridge)
// can temporarily interfere with chrome.debugger. A short delay usually resolves it.
// Normal commands: 2 retries, 500ms delay (fast fail for non-operate use)
// Operate commands: 5 retries, 1500ms delay (aggressive, tolerates extension interference)
const MAX_ATTACH_RETRIES = aggressiveRetry ? 5 : 2;
const RETRY_DELAY_MS = aggressiveRetry ? 1500 : 500;
let lastError = '';
for (let attempt = 1; attempt <= MAX_ATTACH_RETRIES; attempt++) {
try {
// Force detach first to clear any stale state from other extensions
try { await chrome.debugger.detach({ tabId }); } catch { /* ignore */ }
await chrome.debugger.attach({ tabId }, '1.3');
lastError = '';
break; // Success
} catch (e: unknown) {
lastError = e instanceof Error ? e.message : String(e);
if (attempt < MAX_ATTACH_RETRIES) {
console.warn(`[opencli] attach attempt ${attempt}/${MAX_ATTACH_RETRIES} failed: ${lastError}, retrying in ${RETRY_DELAY_MS}ms...`);
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
// Re-verify tab URL before retrying (it may have changed)
try {
const tab = await chrome.tabs.get(tabId);
if (!isDebuggableUrl(tab.url)) {
lastError = `Tab URL changed to ${tab.url} during retry`;
break; // Don't retry if URL became un-debuggable
}
} catch {
lastError = `Tab ${tabId} no longer exists`;
break;
}
}
}
}
if (lastError) {
const hint = lastError.includes('chrome-extension://')
try {
await chrome.debugger.attach({ tabId }, '1.3');
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
const hint = msg.includes('chrome-extension://')
? '. Tip: another Chrome extension may be interfering — try disabling other extensions'
: '';
throw new Error(`attach failed: ${lastError}${hint}`);
if (msg.includes('Another debugger is already attached')) {
try { await chrome.debugger.detach({ tabId }); } catch { /* ignore */ }
try {
await chrome.debugger.attach({ tabId }, '1.3');
} catch {
throw new Error(`attach failed: ${msg}${hint}`);
}
} else {
throw new Error(`attach failed: ${msg}${hint}`);
}
}
attached.add(tabId);
@@ -93,45 +70,26 @@ export async function ensureAttached(tabId: number, aggressiveRetry: boolean = f
}
}
export async function evaluate(tabId: number, expression: string, aggressiveRetry: boolean = false): Promise<unknown> {
// Retry the entire evaluate (attach + command).
// Normal: 2 retries. Operate: 3 retries (tolerates extension interference).
const MAX_EVAL_RETRIES = aggressiveRetry ? 3 : 2;
for (let attempt = 1; attempt <= MAX_EVAL_RETRIES; attempt++) {
try {
await ensureAttached(tabId, aggressiveRetry);
export async function evaluate(tabId: number, expression: string): Promise<unknown> {
await ensureAttached(tabId);
const result = await chrome.debugger.sendCommand({ tabId }, 'Runtime.evaluate', {
expression,
returnByValue: true,
awaitPromise: true,
}) as {
result?: { type: string; value?: unknown; description?: string; subtype?: string };
exceptionDetails?: { exception?: { description?: string }; text?: string };
};
const result = await chrome.debugger.sendCommand({ tabId }, 'Runtime.evaluate', {
expression,
returnByValue: true,
awaitPromise: true,
}) as {
result?: { type: string; value?: unknown; description?: string; subtype?: string };
exceptionDetails?: { exception?: { description?: string }; text?: string };
};
if (result.exceptionDetails) {
const errMsg = result.exceptionDetails.exception?.description
|| result.exceptionDetails.text
|| 'Eval error';
throw new Error(errMsg);
}
return result.result?.value;
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
// Only retry on attach/debugger errors, not on JS eval errors
const isAttachError = msg.includes('attach failed') || msg.includes('Debugger is not attached')
|| msg.includes('chrome-extension://') || msg.includes('Target closed');
if (isAttachError && attempt < MAX_EVAL_RETRIES) {
attached.delete(tabId); // Force re-attach on next attempt
await new Promise(resolve => setTimeout(resolve, 1000));
continue;
}
throw e;
}
if (result.exceptionDetails) {
const errMsg = result.exceptionDetails.exception?.description
|| result.exceptionDetails.text
|| 'Eval error';
throw new Error(errMsg);
}
throw new Error('evaluate: max retries exhausted');
return result.result?.value;
}
export const evaluateAsync = evaluate;
@@ -186,48 +144,6 @@ export async function screenshot(
}
}
/**
* Set local file paths on a file input element via CDP DOM.setFileInputFiles.
* This bypasses the need to send large base64 payloads through the message channel —
* Chrome reads the files directly from the local filesystem.
*
* @param tabId - Target tab ID
* @param files - Array of absolute local file paths
* @param selector - CSS selector to find the file input (optional, defaults to first file input)
*/
export async function setFileInputFiles(
tabId: number,
files: string[],
selector?: string,
): Promise<void> {
await ensureAttached(tabId);
// Enable DOM domain (required for DOM.querySelector and DOM.setFileInputFiles)
await chrome.debugger.sendCommand({ tabId }, 'DOM.enable');
// Get the document root
const doc = await chrome.debugger.sendCommand({ tabId }, 'DOM.getDocument') as {
root: { nodeId: number };
};
// Find the file input element
const query = selector || 'input[type="file"]';
const result = await chrome.debugger.sendCommand({ tabId }, 'DOM.querySelector', {
nodeId: doc.root.nodeId,
selector: query,
}) as { nodeId: number };
if (!result.nodeId) {
throw new Error(`No element found matching selector: ${query}`);
}
// Set files directly via CDP — Chrome reads from local filesystem
await chrome.debugger.sendCommand({ tabId }, 'DOM.setFileInputFiles', {
files,
nodeId: result.nodeId,
});
}
export async function detach(tabId: number): Promise<void> {
if (!attached.has(tabId)) return;
attached.delete(tabId);
+6 -13
View File
@@ -5,7 +5,7 @@
* Everything else is just JS code sent via 'exec'.
*/
export type Action = 'exec' | 'navigate' | 'tabs' | 'cookies' | 'screenshot' | 'close-window' | 'sessions' | 'set-file-input' | 'cdp';
export type Action = 'exec' | 'navigate' | 'tabs' | 'cookies' | 'screenshot' | 'close-window' | 'sessions';
export interface Command {
/** Unique request ID */
@@ -32,14 +32,6 @@ export interface Command {
quality?: number;
/** Whether to capture full page (not just viewport) */
fullPage?: boolean;
/** Local file paths for set-file-input action */
files?: string[];
/** CSS selector for file input element (set-file-input action) */
selector?: string;
/** CDP method name for 'cdp' action (e.g. 'Accessibility.getFullAXTree') */
cdpMethod?: string;
/** CDP method params for 'cdp' action */
cdpParams?: Record<string, unknown>;
}
export interface Result {
@@ -57,10 +49,11 @@ export interface Result {
export const DAEMON_PORT = 19825;
export const DAEMON_HOST = 'localhost';
export const DAEMON_WS_URL = `ws://${DAEMON_HOST}:${DAEMON_PORT}/ext`;
/** Lightweight health-check endpoint — probed before each WebSocket attempt. */
export const DAEMON_PING_URL = `http://${DAEMON_HOST}:${DAEMON_PORT}/ping`;
export const DAEMON_HTTP_URL = `http://${DAEMON_HOST}:${DAEMON_PORT}`;
/** Base reconnect delay for extension WebSocket (ms) */
export const WS_RECONNECT_BASE_DELAY = 2000;
/** Max reconnect delay (ms) — kept short since daemon is long-lived */
export const WS_RECONNECT_MAX_DELAY = 5000;
/** Max reconnect delay (ms) */
export const WS_RECONNECT_MAX_DELAY = 60000;
/** Idle timeout before daemon auto-exits (ms) */
export const DAEMON_IDLE_TIMEOUT = 5 * 60 * 1000;
+2 -22
View File
@@ -1,12 +1,12 @@
{
"name": "@jackwener/opencli",
"version": "1.6.1",
"version": "1.3.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@jackwener/opencli",
"version": "1.6.1",
"version": "1.3.3",
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
@@ -15,7 +15,6 @@
"commander": "^14.0.3",
"js-yaml": "^4.1.0",
"turndown": "^7.2.2",
"undici": "^7.24.6",
"ws": "^8.18.0"
},
"bin": {
@@ -196,7 +195,6 @@
"integrity": "sha512-y1IOpG6OSmTpGg/CT0YBb/EAhR2nsC18QWp9Jy8HO9iGySpcwaTvs5kHa17daP3BMTwWyaX9/1tDTDQshZzXdg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@algolia/client-common": "5.49.2",
"@algolia/requester-browser-xhr": "5.49.2",
@@ -2164,7 +2162,6 @@
"integrity": "sha512-1K0wtDaRONwfhL4h8bbJ9qTjmY6rhGgRvvagXkMBsAOMNr+3Q2SffHECh9DIuNVrMA1JwA0zCwhyepgBZVakng==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@algolia/abtesting": "1.15.2",
"@algolia/client-abtesting": "5.49.2",
@@ -2493,7 +2490,6 @@
"integrity": "sha512-/yNdlIkpWbM0ptxno3ONTuf+2g318kh2ez3KSeZN5dZ8YC6AAmgeWz+GasYYiBJPFaYcSAPeu4GfhUaChzIJXA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"tabbable": "^6.4.0"
}
@@ -2622,7 +2618,6 @@
"integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",
"dev": true,
"license": "MPL-2.0",
"peer": true,
"dependencies": {
"detect-libc": "^2.0.3"
},
@@ -3094,7 +3089,6 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -3483,7 +3477,6 @@
"integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "~0.27.0",
"get-tsconfig": "^4.7.5"
@@ -3513,7 +3506,6 @@
"integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==",
"dev": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -3522,15 +3514,6 @@
"node": ">=14.17"
}
},
"node_modules/undici": {
"version": "7.24.6",
"resolved": "https://registry.npmjs.org/undici/-/undici-7.24.6.tgz",
"integrity": "sha512-Xi4agocCbRzt0yYMZGMA6ApD7gvtUFaxm4ZmeacWI4cZxaF6C+8I8QfofC20NAePiB/IcvZmzkJ7XPa471AEtA==",
"license": "MIT",
"engines": {
"node": ">=20.18.1"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
@@ -3647,7 +3630,6 @@
"integrity": "sha512-1gFhNi+bHhRE/qKZOJXACm6tX4bA3Isy9KuKF15AgSRuRazNBOJfdDemPBU16/mpMxApDPrWvZ08DcLPEoRnuA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"lightningcss": "^1.32.0",
"picomatch": "^4.0.3",
@@ -4212,7 +4194,6 @@
"integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.21.3",
"postcss": "^8.4.43",
@@ -4355,7 +4336,6 @@
"integrity": "sha512-hTHLc6VNZyzzEH/l7PFGjpcTvUgiaPK5mdLkbjrTeWSRcEfxFrv56g/XckIYlE9ckuobsdwqd5mk2g1sBkMewg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-dom": "3.5.30",
"@vue/compiler-sfc": "3.5.30",
+2 -6
View File
@@ -1,10 +1,10 @@
{
"name": "@jackwener/opencli",
"version": "1.6.1",
"version": "1.3.3",
"publishConfig": {
"access": "public"
},
"description": "Make any website or Electron App your CLI. AI-powered.",
"description": "Make any website your CLI. AI-powered.",
"engines": {
"node": ">=20.0.0"
},
@@ -19,20 +19,17 @@
},
"scripts": {
"dev": "tsx src/main.ts",
"dev:bun": "bun src/main.ts",
"build": "npm run clean-dist && tsc && npm run clean-yaml && npm run copy-yaml && npm run build-manifest",
"build-manifest": "node dist/build-manifest.js",
"clean-dist": "node scripts/clean-dist.cjs",
"clean-yaml": "node scripts/clean-yaml.cjs",
"copy-yaml": "node scripts/copy-yaml.cjs",
"start": "node dist/main.js",
"start:bun": "bun dist/main.js",
"postinstall": "node scripts/postinstall.js || true",
"typecheck": "tsc --noEmit",
"lint": "tsc --noEmit",
"prepublishOnly": "npm run build",
"test": "vitest run --project unit",
"test:bun": "bun vitest run --project unit",
"test:adapter": "vitest run --project adapter",
"test:all": "vitest run",
"test:e2e": "vitest run --project e2e",
@@ -58,7 +55,6 @@
"commander": "^14.0.3",
"js-yaml": "^4.1.0",
"turndown": "^7.2.2",
"undici": "^7.24.6",
"ws": "^8.18.0"
},
"devDependencies": {
-26
View File
@@ -195,32 +195,6 @@ function main() {
console.error(`Warning: Could not install shell completion: ${err.message}`);
}
}
// ── Spotify credentials template ────────────────────────────────────
const opencliDir = join(home, '.opencli');
const spotifyEnvFile = join(opencliDir, 'spotify.env');
ensureDir(opencliDir);
if (!existsSync(spotifyEnvFile)) {
writeFileSync(spotifyEnvFile,
`# Spotify credentials — get them at https://developer.spotify.com/dashboard\n` +
`# Add http://127.0.0.1:8888/callback as a Redirect URI in your Spotify app\n` +
`SPOTIFY_CLIENT_ID=your_spotify_client_id_here\n` +
`SPOTIFY_CLIENT_SECRET=your_spotify_client_secret_here\n`,
'utf8'
);
console.log(`✓ Spotify credentials template created at ${spotifyEnvFile}`);
console.log(` Edit the file and add your Client ID and Secret, then run: opencli spotify auth`);
}
// ── Browser Bridge setup hint ───────────────────────────────────────
console.log('');
console.log(' \x1b[1mNext step — Browser Bridge setup\x1b[0m');
console.log(' Browser commands (bilibili, zhihu, twitter...) require the extension:');
console.log(' 1. Download: https://github.com/jackwener/opencli/releases');
console.log(' 2. Open chrome://extensions → enable Developer Mode → Load unpacked');
console.log('');
console.log(' Then run \x1b[36mopencli doctor\x1b[0m to verify.');
console.log('');
}
main();
-853
View File
@@ -1,853 +0,0 @@
---
name: opencli-explorer
description: Use when creating a new OpenCLI adapter from scratch, adding support for a new website or platform, or exploring a site's API endpoints via browser DevTools. Covers API discovery workflow, authentication strategy selection, YAML/TS adapter writing, and testing.
tags: [opencli, adapter, browser, api-discovery, cli, web-scraping, automation]
---
# CLI-EXPLORER — 适配器探索式开发完全指南
> 本文档教你(或 AI Agent)如何为 OpenCLI 添加一个新网站的命令。
> 从零到发布,覆盖 API 发现、方案选择、适配器编写、测试验证全流程。
> [!TIP]
> **只想为一个具体页面快速生成一个命令?** 看 [CLI-ONESHOT.md](./CLI-ONESHOT.md)~150 行,4 步搞定)。
> 本文档适合从零探索一个新站点的完整流程。
---
## AI Agent 开发者必读:用浏览器探索
> [!CAUTION]
> **你(AI Agent)必须通过浏览器打开目标网站去探索!**
> 不要只靠 `opencli explore` 命令或静态分析来发现 API。
> 你拥有浏览器工具,必须主动用它们浏览网页、观察网络请求、模拟用户交互。
### 为什么?
很多 API 是**懒加载**的(用户必须点击某个按钮/标签才会触发网络请求)。字幕、评论、关注列表等深层数据不会在页面首次加载时出现在 Network 面板中。**如果你不主动去浏览和交互页面,你永远发现不了这些 API。**
### AI Agent 探索工作流(必须遵循)
| 步骤 | 工具 | 做什么 |
|------|------|--------|
| 0. 打开浏览器 | `browser_navigate` | 导航到目标页面 |
| 1. 观察页面 | `browser_snapshot` | 观察可交互元素(按钮/标签/链接) |
| 2. 首次抓包 | `browser_network_requests` | 筛选 JSON API 端点,记录 URL pattern |
| 3. 模拟交互 | `browser_click` + `browser_wait_for` | 点击"字幕""评论""关注"等按钮 |
| 4. 二次抓包 | `browser_network_requests` | 对比步骤 2,找出新触发的 API |
| 5. 验证 API | `browser_evaluate` | `fetch(url, {credentials:'include'})` 测试返回结构 |
| 6. 写代码 | — | 基于确认的 API 写适配器 |
### 常犯错误
| ❌ 错误做法 | ✅ 正确做法 |
|------------|------------|
| 只用 `opencli explore` 命令,等结果自动出来 | 用浏览器工具打开页面,主动浏览 |
| 直接在代码里 `fetch(url)`,不看浏览器实际请求 | 先在浏览器中确认 API 可用,再写代码 |
| 页面打开后直接抓包,期望所有 API 都出现 | 模拟点击交互(展开评论/切换标签/加载更多) |
| 遇到 HTTP 200 但空数据就放弃 | 检查是否需要 Wbi 签名或 Cookie 鉴权 |
| 完全依赖 `__INITIAL_STATE__` 拿所有数据 | `__INITIAL_STATE__` 只有首屏数据,深层数据要调 API |
### 实战成功案例:5 分钟实现「关注列表」适配器
以下是用上述工作流实际发现 Bilibili 关注列表 API 的完整过程:
```
1. browser_navigate → https://space.bilibili.com/{uid}/fans/follow
2. browser_network_requests → 发现:
GET /x/relation/followings?vmid={uid}&pn=1&ps=24 → [200]
GET /x/relation/stat?vmid={uid} → [200]
3. browser_evaluate → 验证 API:
fetch('/x/relation/followings?vmid=137702077&pn=1&ps=5', {credentials:'include'})
→ { code: 0, data: { total: 1342, list: [{mid, uname, sign, ...}] } }
4. 结论:标准 Cookie API,无需 Wbi 签名
5. 写 following.ts → 一次构建通过
```
**关键决策点**
- 直接访问 `fans/follow` 页面(不是首页),页面加载就会触发 following API
- 看到 URL 里没有 `/wbi/` → 不需要签名 → 直接用 `fetchJson` 而非 `apiGet`
- API 返回 `code: 0` + 非空 `list` → Tier 2 Cookie 策略确认
---
## 核心流程
```
┌─────────────┐ ┌─────────────┐ ┌──────────────┐ ┌────────┐
│ 1. 发现 API │ ──▶ │ 2. 选择策略 │ ──▶ │ 3. 写适配器 │ ──▶ │ 4. 测试 │
└─────────────┘ └─────────────┘ └──────────────┘ └────────┘
explore cascade YAML / TS run + verify
```
---
## Step 1: 发现 API
### 1a. 自动化发现(推荐)
OpenCLI 内置 Deep Explore,自动分析网站网络请求:
```bash
opencli explore https://www.example.com --site mysite
```
输出到 `.opencli/explore/mysite/`
| 文件 | 内容 |
|------|------|
| `manifest.json` | 站点元数据、框架检测(Vue2/3、React、Next.js、Pinia、Vuex |
| `endpoints.json` | 已发现的 API 端点,按评分排序,含 URL pattern、方法、响应类型 |
| `capabilities.json` | 推理出的功能(`hot``search``feed`…),含置信度和推荐参数 |
| `auth.json` | 认证方式检测(Cookie/Header/无认证),策略候选列表 |
### 1b. 手动抓包验证
Explore 的自动分析可能不完美,用 verbose 模式手动确认:
```bash
# 在浏览器中打开目标页面,观察网络请求
opencli explore https://www.example.com --site mysite -v
# 或直接用 evaluate 测试 API
opencli bilibili hot -v # 查看已有命令的 pipeline 每步数据流
```
关注抓包结果中的关键信息:
- **URL pattern**: `/api/v2/hot?limit=20` → 这就是你要调用的端点
- **Method**: `GET` / `POST`
- **Request Headers**: Cookie? Bearer? 自定义签名头(X-s、X-t?
- **Response Body**: JSON 结构,特别是数据在哪个路径(`data.items``data.list`
### 1c. 高阶 API 发现捷径法则 (Heuristics)
在开始死磕复杂的抓包拦截之前,按照以下优先级进行尝试:
1. **后缀爆破法 (`.json`)**: 像 Reddit 这样复杂的网站,只要在其 URL 后加上 `.json`(例如 `/r/all.json`),就能在带 Cookie 的情况下直接利用 `fetch` 拿到极其干净的 REST 数据(Tier 2 Cookie 策略极速秒杀)。另外如功能完备的**雪球 (xueqiu)** 也可以走这种纯 API 的方式极简获取,成为你构建简单 YAML 的黄金标杆。
2. **全局状态查找法 (`__INITIAL_STATE__`)**: 许多服务端渲染 (SSR) 的网站(如小红书、Bilibili)会将首页或详情页的完整数据挂载到全局 window 对象上。与其去拦截网络请求,不如直接 `page.evaluate('() => window.__INITIAL_STATE__')` 获取整个数据树。
3. **主动交互触发法 (Active Interaction)**: 很多深层 API(如视频字幕、评论下的回复)是懒加载的。在静态抓包找不到数据时,尝试在 `evaluate` 步骤或手动打断点时,主动去**点击(Click)页面上的对应按钮**(如"CC"、"展开全部"),从而诱发隐藏的 Network Fetch。
4. **框架探测与 Store Action 截断**: 如果站点使用 Vue + Pinia,可以使用 `tap` 步骤调用 action,让前端框架代替你完成复杂的鉴权签名封装。
5. **底层 XHR/Fetch 拦截**: 最后手段,当上述都不行时,使用 TypeScript 适配器进行无侵入式的请求抓取。
### 1d. 框架检测
Explore 自动检测前端框架。如果需要手动确认:
```bash
# 在已打开目标网站的情况下
opencli evaluate "(()=>{
const vue3 = !!document.querySelector('#app')?.__vue_app__;
const vue2 = !!document.querySelector('#app')?.__vue__;
const react = !!window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
const pinia = vue3 && !!document.querySelector('#app').__vue_app__.config.globalProperties.\$pinia;
return JSON.stringify({vue3, vue2, react, pinia});
})()"
```
Vue + Pinia 的站点(如小红书)可以直接通过 Store Action 绕过签名。
---
## Step 2: 选择认证策略
OpenCLI 提供 5 级认证策略。使用 `cascade` 命令自动探测:
```bash
opencli cascade https://api.example.com/hot
```
### 策略决策树
```
直接 fetch(url) 能拿到数据?
→ ✅ Tier 1: public(公开 API,不需要浏览器)
→ ❌ fetch(url, {credentials:'include'}) 带 Cookie 能拿到?
→ ✅ Tier 2: cookie(最常见,evaluate 步骤内 fetch
→ ❌ → 加上 Bearer / CSRF header 后能拿到?
→ ✅ Tier 3: header(如 Twitter ct0 + Bearer
→ ❌ → 网站有 Pinia/Vuex Store
→ ✅ Tier 4: interceptStore Action + XHR 拦截)
→ ❌ Tier 5: ui(UI 自动化,最后手段)
```
### 各策略对比
| Tier | 策略 | 速度 | 复杂度 | 适用场景 | 实例 |
|------|------|------|--------|---------|------|
| 1 | `public` | ⚡ ~1s | 最简 | 公开 API,无需登录 | Hacker News, V2EX |
| 2 | `cookie` | 🔄 ~7s | 简单 | Cookie 认证即可 | Bilibili, Zhihu, Reddit |
| 3 | `header` | 🔄 ~7s | 中等 | 需要 CSRF token 或 Bearer | Twitter GraphQL |
| 4 | `intercept` | 🔄 ~10s | 较高 | 请求有复杂签名 | 小红书 (Pinia + XHR) |
| 5 | `ui` | 🐌 ~15s+ | 最高 | 无 API,纯 DOM 解析 | 遗留网站 |
---
## Step 2.5: 准备工作(写代码之前)
### 先找模板:从最相似的现有适配器开始
**不要从零开始写**。先看看同站点已有哪些适配器:
```bash
ls src/clis/<site>/ # 看看已有什么
cat src/clis/<site>/feed.ts # 读最相似的那个
```
最高效的方式是 **复制最相似的适配器,然后改 3 个地方**
1. `name` → 新命令名
2. API URL → 你在 Step 1 发现的端点
3. 字段映射 → 对应新 API 的字段
### 平台 SDK 速查表
写 TS 适配器之前,先看看你的目标站点有没有**现成的 helper 函数**可以复用:
#### Bilibili (`src/clis/bilibili/utils.ts`)
| 函数 | 用途 | 何时使用 |
|------|------|----------|
| `fetchJson(page, url)` | 带 Cookie 的 fetch + JSON 解析 | 普通 Cookie-tier API |
| `apiGet(page, path, {signed, params})` | 带 Wbi 签名的 API 调用 | URL 含 `/wbi/` 的接口 |
| `getSelfUid(page)` | 获取当前登录用户的 UID | "我的xxx" 类命令 |
| `resolveUid(page, input)` | 解析用户输入的 UID(支持数字/URL) | `--uid` 参数处理 |
| `wbiSign(page, params)` | 底层 Wbi 签名生成 | 通常不直接用,`apiGet` 已封装 |
| `stripHtml(s)` | 去除 HTML 标签 | 清理富文本字段 |
**如何判断需不需要 `apiGet`**?看 Network 请求 URL
-`/wbi/``w_rid=` → 必须用 `apiGet(..., { signed: true })`
- 不含 → 直接用 `fetchJson`
> 其他站点(Twitter、小红书等)暂无专用 SDK,直接用 `page.evaluate` + `fetch` 即可。
---
## Step 3: 编写适配器
### YAML vs TS?先看决策树
```
你的 pipeline 里有 evaluate 步骤(内嵌 JS 代码)?
→ ✅ 用 TypeScript (src/clis/<site>/<name>.ts),保存即自动动态注册
→ ❌ 纯声明式(navigate + tap + map + limit)?
→ ✅ 用 YAML (src/clis/<site>/<name>.yaml),保存即自动注册
```
| 场景 | 选择 | 示例 |
|------|------|------|
| 纯 fetch/select/map/limit | YAML | `v2ex/hot.yaml`, `hackernews/top.yaml` |
| navigate + evaluate(fetch) + map | YAML(评估复杂度) | `zhihu/hot.yaml` |
| navigate + tap + map | YAML ✅ | `xiaohongshu/feed.yaml`, `xiaohongshu/notifications.yaml` |
| 有复杂 JS 逻辑(Pinia state 读取、条件分支) | TS | `xiaohongshu/me.ts`, `bilibili/me.ts` |
| XHR 拦截 + 签名 | TS | `xiaohongshu/search.ts` |
| GraphQL / 分页 / Wbi 签名 | TS | `bilibili/search.ts`, `twitter/search.ts` |
> **经验法则**:如果你发现 YAML 里嵌了超过 10 行 JS,改用 TS 更可维护。
### 通用模式:分页 API
很多 API 使用 `pn`(页码)+ `ps`(每页数量)分页。标准处理模式:
```typescript
args: [
{ name: 'page', type: 'int', required: false, default: 1, help: '页码' },
{ name: 'limit', type: 'int', required: false, default: 50, help: '每页数量 (最大 50)' },
],
func: async (page, kwargs) => {
const pn = kwargs.page ?? 1;
const ps = Math.min(kwargs.limit ?? 50, 50); // 尊重 API 的 ps 上限
const payload = await fetchJson(page,
`https://api.example.com/list?pn=${pn}&ps=${ps}`
);
return payload.data?.list || [];
},
```
> 大多数站点的 `ps` 上限是 20~50。超过会被静默截断或返回错误。
### 方式 A: YAML Pipeline(声明式,推荐)
文件路径: `src/clis/<site>/<name>.yaml`,放入即自动注册。
#### Tier 1 — 公开 API 模板
```yaml
# src/clis/v2ex/hot.yaml
site: v2ex
name: hot
description: V2EX 热门话题
domain: www.v2ex.com
strategy: public
browser: false
args:
limit:
type: int
default: 20
pipeline:
- fetch:
url: https://www.v2ex.com/api/topics/hot.json
- map:
rank: ${{ index + 1 }}
title: ${{ item.title }}
replies: ${{ item.replies }}
- limit: ${{ args.limit }}
columns: [rank, title, replies]
```
#### Tier 2 — Cookie 认证模板(最常用)
```yaml
# src/clis/zhihu/hot.yaml
site: zhihu
name: hot
description: 知乎热榜
domain: www.zhihu.com
pipeline:
- navigate: https://www.zhihu.com # 先加载页面建立 session
- evaluate: | # 在浏览器内发请求,自动带 Cookie
(async () => {
const res = await fetch('/api/v3/feed/topstory/hot-lists/total?limit=50', {
credentials: 'include'
});
const d = await res.json();
return (d?.data || []).map(item => {
const t = item.target || {};
return {
title: t.title,
heat: item.detail_text || '',
answers: t.answer_count,
};
});
})()
- map:
rank: ${{ index + 1 }}
title: ${{ item.title }}
heat: ${{ item.heat }}
answers: ${{ item.answers }}
- limit: ${{ args.limit }}
columns: [rank, title, heat, answers]
```
> **关键**: `evaluate` 步骤内的 `fetch` 运行在浏览器页面内,自动携带 `credentials: 'include'`,无需手动处理 Cookie。
#### 进阶 — 带搜索参数
```yaml
# src/clis/zhihu/search.yaml
site: zhihu
name: search
description: 知乎搜索
args:
query:
type: str
required: true
positional: true
description: Search query
limit:
type: int
default: 10
pipeline:
- navigate: https://www.zhihu.com
- evaluate: |
(async () => {
const q = encodeURIComponent('${{ args.query }}');
const res = await fetch('/api/v4/search_v3?q=' + q + '&t=general&limit=${{ args.limit }}', {
credentials: 'include'
});
const d = await res.json();
return (d?.data || [])
.filter(item => item.type === 'search_result')
.map(item => ({
title: (item.object?.title || '').replace(/<[^>]+>/g, ''),
type: item.object?.type || '',
author: item.object?.author?.name || '',
votes: item.object?.voteup_count || 0,
}));
})()
- map:
rank: ${{ index + 1 }}
title: ${{ item.title }}
type: ${{ item.type }}
author: ${{ item.author }}
votes: ${{ item.votes }}
- limit: ${{ args.limit }}
columns: [rank, title, type, author, votes]
```
#### Tier 4 — Store Action Bridge`tap` 步骤,intercept 策略推荐)
适用于 Vue + Pinia/Vuex 的网站(如小红书),无须手动写 XHR 拦截代码:
```yaml
# src/clis/xiaohongshu/notifications.yaml
site: xiaohongshu
name: notifications
description: "小红书通知"
domain: www.xiaohongshu.com
strategy: intercept
browser: true
args:
type:
type: str
default: mentions
description: "Notification type: mentions, likes, or connections"
limit:
type: int
default: 20
columns: [rank, user, action, content, note, time]
pipeline:
- navigate: https://www.xiaohongshu.com/notification
- wait: 3
- tap:
store: notification # Pinia store name
action: getNotification # Store action to call
args: # Action arguments
- ${{ args.type | default('mentions') }}
capture: /you/ # URL pattern to capture response
select: data.message_list # Extract sub-path from response
timeout: 8
- map:
rank: ${{ index + 1 }}
user: ${{ item.user_info.nickname }}
action: ${{ item.title }}
content: ${{ item.comment_info.content }}
- limit: ${{ args.limit | default(20) }}
```
> **`tap` 步骤自动完成**:注入 fetch+XHR 双拦截 → 查找 Pinia/Vuex store → 调用 action → 捕获匹配 URL 的响应 → 清理拦截。
> 如果 store 或 action 找不到,会返回 `hint` 列出所有可用的 store actions,方便调试。
| tap 参数 | 必填 | 说明 |
|---------|------|------|
| `store` | ✅ | Pinia store 名称(如 `feed`, `search`, `notification` |
| `action` | ✅ | Store action 方法名 |
| `capture` | ✅ | URL 子串匹配(匹配网络请求 URL) |
| `args` | ❌ | 传给 action 的参数数组 |
| `select` | ❌ | 从 captured JSON 中提取的路径(如 `data.items` |
| `timeout` | ❌ | 等待网络响应的超时秒数(默认 5s) |
| `framework` | ❌ | `pinia``vuex`(默认自动检测) |
### 方式 B: TypeScript 适配器(编程式)
适用于需要嵌入 JS 代码读取 Pinia state、XHR 拦截、GraphQL、分页、复杂数据转换等场景。
文件路径: `src/clis/<site>/<name>.ts`。文件将会在运行时被动态扫描并注册(切勿在 `index.ts` 中手动 `import`)。
#### Tier 3 — Header 认证(Twitter
```typescript
// src/clis/twitter/search.ts
import { cli, Strategy } from '../../registry.js';
cli({
site: 'twitter',
name: 'search',
description: 'Search tweets',
strategy: Strategy.HEADER,
args: [{ name: 'query', required: true, positional: true }],
columns: ['rank', 'author', 'text', 'likes'],
func: async (page, kwargs) => {
await page.goto('https://x.com');
const data = await page.evaluate(`
(async () => {
// 从 Cookie 提取 CSRF token
const ct0 = document.cookie.split(';')
.map(c => c.trim())
.find(c => c.startsWith('ct0='))?.split('=')[1];
if (!ct0) return { error: 'Not logged in' };
const bearer = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D...';
const headers = {
'Authorization': 'Bearer ' + decodeURIComponent(bearer),
'X-Csrf-Token': ct0,
'X-Twitter-Auth-Type': 'OAuth2Session',
};
const variables = JSON.stringify({ rawQuery: '${kwargs.query}', count: 20 });
const url = '/i/api/graphql/xxx/SearchTimeline?variables=' + encodeURIComponent(variables);
const res = await fetch(url, { headers, credentials: 'include' });
return await res.json();
})()
`);
// ... 解析 data
},
});
```
#### Tier 4 — XHR/Fetch 双重拦截 (Twitter/小红书 通用模式)
```typescript
// src/clis/xiaohongshu/user.ts
import { cli, Strategy } from '../../registry.js';
cli({
site: 'xiaohongshu',
name: 'user',
description: '获取用户笔记',
strategy: Strategy.INTERCEPT,
args: [{ name: 'id', required: true }],
columns: ['rank', 'title', 'likes', 'url'],
func: async (page, kwargs) => {
await page.goto(`https://www.xiaohongshu.com/user/profile/${kwargs.id}`);
await page.wait(5);
// XHR/Fetch 底层拦截:捕获所有包含 'v1/user/posted' 的请求
await page.installInterceptor('v1/user/posted');
// 触发后端 API:模拟人类用户向底部滚动2次
await page.autoScroll({ times: 2, delayMs: 2000 });
// 提取所有被拦截捕获的 JSON 响应体
const requests = await page.getInterceptedRequests();
if (!requests || requests.length === 0) return [];
let results = [];
for (const req of requests) {
if (req.data?.data?.notes) {
for (const note of req.data.data.notes) {
results.push({
title: note.display_title || '',
likes: note.interact_info?.liked_count || '0',
url: `https://explore/${note.note_id || note.id}`
});
}
}
}
return results.slice(0, 20).map((item, i) => ({
rank: i + 1, ...item,
}));
},
});
```
> **拦截核心思路**:不自己构造签名,而是利用 `installInterceptor` 劫持网站自己的 `XMLHttpRequest` 和 `fetch`,让网站发请求,我们直接在底层取出解析好的 `response.json()`。
> **级联请求**(如 BVID→CID→字幕)的完整模板和要点见下方[进阶模式: 级联请求](#进阶模式-级联请求-cascading-requests)章节。
---
## Step 4: 测试
> **构建通过 ≠ 功能正常**。`npm run build` 只验证 TypeScript / YAML 语法,不验证运行时行为。
> 每个新命令 **必须实际运行** 并确认输出正确后才算完成。
### 必做清单
```bash
# 1. 构建(确认语法无误)
npm run build
# 2. 确认命令已注册
opencli list | grep mysite
# 3. 实际运行命令(最关键!)
opencli mysite hot --limit 3 -v # verbose 查看每步数据流
opencli mysite hot --limit 3 -f json # JSON 输出确认字段完整
```
### tap 步骤调试(intercept 策略专用)
> **不要猜 store name / action name**。先用 evaluate 探索,再写 YAML。
#### Step 1: 列出所有 Pinia store
在浏览器中打开目标网站后:
```bash
opencli evaluate "(() => {
const app = document.querySelector('#app')?.__vue_app__;
const pinia = app?.config?.globalProperties?.\$pinia;
return [...pinia._s.keys()];
})()"
# 输出: ["user", "feed", "search", "notification", ...]
```
#### Step 2: 查看 store 的 action 名称
故意写一个错误 action 名,tap 会返回所有可用 actions
```
⚠ tap: Action not found: wrongName on store notification
💡 Available: getNotification, replyComment, getNotificationCount, reset
```
#### Step 3: 用 network requests 确认 capture 模式
```bash
# 在浏览器打开目标页面,查看网络请求
# 找到目标 API 的 URL 特征(如 "/you/mentions"、"homefeed"
```
#### 完整流程
```
┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌────────┐
│ 1. navigate │ ──▶ │ 2. 探索 store │ ──▶ │ 3. 写 YAML │ ──▶ │ 4. 测试 │
│ 到目标页面 │ │ name/action │ │ tap 步骤 │ │ 运行验证 │
└──────────────┘ └──────────────┘ └──────────────┘ └────────┘
```
### Verbose 模式 & 输出验证
```bash
opencli bilibili hot --limit 1 -v # 查看 pipeline 每步数据流
opencli mysite hot -f json | jq '.[0]' # 确认 JSON 可被解析
opencli mysite hot -f csv > data.csv # 确认 CSV 可导入
```
---
## Step 5: 提交发布
文件放入 `src/clis/<site>/` 即自动注册(YAML 或 TS 无需手动 import),然后:
```bash
opencli list | grep mysite # 确认注册
git add src/clis/mysite/ && git commit -m "feat(mysite): add hot" && git push
```
> **架构理念**OpenCLI 内建 **Zero-Dependency jq** 数据流 — 所有解析在 `evaluate` 的原生 JS 内完成,外层 YAML 用 `select`/`map` 提取,无需依赖系统 `jq` 二进制。
---
## 进阶模式: 级联请求 (Cascading Requests)
当目标数据需要多步 API 链式获取时(如 `BVID → CID → 字幕列表 → 字幕内容`),必须使用 **TS 适配器**。YAML 无法处理这种多步逻辑。
### 模板代码
```typescript
import { cli, Strategy } from '../../registry.js';
import type { IPage } from '../../types.js';
import { apiGet } from './utils.js'; // 复用平台 SDK
cli({
site: 'bilibili',
name: 'subtitle',
strategy: Strategy.COOKIE,
args: [{ name: 'bvid', required: true }],
columns: ['index', 'from', 'to', 'content'],
func: async (page: IPage | null, kwargs: any) => {
if (!page) throw new Error('Requires browser');
// Step 1: 建立 Session
await page.goto(`https://www.bilibili.com/video/${kwargs.bvid}/`);
// Step 2: 从页面提取中间 ID (__INITIAL_STATE__)
const cid = await page.evaluate(`(async () => {
return window.__INITIAL_STATE__?.videoData?.cid;
})()`);
if (!cid) throw new Error('无法提取 CID');
// Step 3: 用中间 ID 调用下一级 API (自动 Wbi 签名)
const payload = await apiGet(page, '/x/player/wbi/v2', {
params: { bvid: kwargs.bvid, cid },
signed: true, // ← 自动生成 w_rid
});
// Step 4: 检测风控降级 (空值断言)
const subtitles = payload.data?.subtitle?.subtitles || [];
const url = subtitles[0]?.subtitle_url;
if (!url) throw new Error('subtitle_url 为空,疑似风控降级');
// Step 5: 拉取最终数据 (CDN JSON)
const items = await page.evaluate(`(async () => {
const res = await fetch(${JSON.stringify('https:' + url)});
const json = await res.json();
return { data: json.body || json };
})()`);
return items.data.map((item, idx) => ({ ... }));
},
});
```
### 关键要点
| 步骤 | 注意事项 |
|------|----------|
| 提取中间 ID | 优先从 `__INITIAL_STATE__` 拿,避免额外 API 调用 |
| Wbi 签名 | B 站 `/wbi/` 接口**强制校验** `w_rid`,纯 `fetch` 会被 403 |
| 空值断言 | 即使 HTTP 200,核心字段可能为空串(风控降级) |
| CDN URL | 常以 `//` 开头,记得补 `https:` |
| `JSON.stringify` | 拼接 URL 到 evaluate 时必须用它转义,避免注入 |
---
## 常见陷阱
| 陷阱 | 表现 | 解决方案 |
|------|------|---------|
| 缺少 `navigate` | evaluate 报 `Target page context` 错误 | 在 evaluate 前加 `navigate:` 步骤 |
| 嵌套字段访问 | `${{ item.node?.title }}` 不工作 | 在 evaluate 中 flatten 数据,不在模板中用 optional chaining |
| 缺少 `strategy: public` | 公开 API 也启动浏览器,7s → 1s | 公开 API 加上 `strategy: public` + `browser: false` |
| evaluate 返回字符串 | map 步骤收到 `""` 而非数组 | pipeline 有 auto-parse,但建议在 evaluate 内 `.map()` 整形 |
| 搜索参数被 URL 编码 | `${{ args.query }}` 被浏览器二次编码 | 在 evaluate 内用 `encodeURIComponent()` 手动编码 |
| Cookie 过期 | 返回 401 / 空数据 | 在浏览器里重新登录目标站点 |
| Extension tab 残留 | Chrome 多出 `chrome-extension://` tab | 已自动清理;若残留,手动关闭即可 |
| TS evaluate 格式 | `() => {}``result is not a function` | TS 中 `page.evaluate()` 必须用 IIFE`(async () => { ... })()` |
| 页面异步加载 | evaluate 拿到空数据(store state 还没更新) | 在 evaluate 内用 polling 等待数据出现,或增加 `wait` 时间 |
| YAML 内嵌大段 JS | 调试困难,字符串转义问题 | 超过 10 行 JS 的命令改用 TS adapter |
| **风控被拦截(伪200)** | 获取到的 JSON 里核心数据是 `""` (空串) | 极易被误判。必须添加断言!无核心数据立刻要求升级鉴权 Tier 并重新配置 Cookie |
| **API 没找见** | `explore` 工具打分出来的都拿不到深层数据 | 点击页面按钮诱发懒加载数据,再结合 `getInterceptedRequests` 获取 |
---
## 用 AI Agent 自动生成适配器
最快的方式是让 AI Agent 完成全流程:
```bash
# 一键:探索 → 分析 → 合成 → 注册
opencli generate https://www.example.com --goal "hot"
# 或分步执行:
opencli explore https://www.example.com --site mysite # 发现 API
opencli explore https://www.example.com --auto --click "字幕,CC" # 模拟点击触发懒加载 API
opencli synthesize mysite # 生成候选 YAML
opencli verify mysite/hot --smoke # 冒烟测试
```
生成的候选 YAML 保存在 `.opencli/explore/mysite/candidates/`,可直接复制到 `src/clis/mysite/` 并微调。
## Record Workflow
`record` 是为「无法用 `explore` 自动发现」的页面(需要登录操作、复杂交互、SPA 内路由)准备的手动录制方案。
### 工作原理
```
opencli record <url>
→ 打开 automation window 并导航到目标 URL
→ 向所有 tab 注入 fetch/XHR 拦截器(幂等,可重复注入)
→ 每 2s 轮询一次:发现新 tab 自动注入,drain 所有 tab 的捕获缓冲区
→ 超时(默认 60s)或按 Enter 停止
→ 分析捕获到的 JSON 请求:去重 → 评分 → 生成候选 YAML
```
**拦截器特性**
- 同时 patch `window.fetch``XMLHttpRequest`
- 只捕获 `Content-Type: application/json` 的响应
- 过滤纯对象少于 2 个 key 的响应(避免 tracking/ping
- 跨 tab 隔离:每个 tab 独立缓冲区,轮询时分别 drain
- 幂等注入:同一 tab 二次注入时先 restore 原始函数再重新 patch,不丢失已捕获数据
### 使用步骤
```bash
# 1. 启动录制(建议 --timeout 给足操作时间)
opencli record "https://example.com/page" --timeout 120000
# 2. 在弹出的 automation window 里正常操作页面:
# - 打开列表、搜索、点击条目、切换 Tab
# - 凡是触发网络请求的操作都会被捕获
# 3. 完成操作后按 Enter 停止(或等超时自动停止)
# 4. 查看结果
cat .opencli/record/<site>/captured.json # 原始捕获
ls .opencli/record/<site>/candidates/ # 候选 YAML
```
### 页面类型与捕获预期
| 页面类型 | 预期捕获量 | 说明 |
|---------|-----------|------|
| 列表/搜索页 | 多(5~20+) | 每次搜索/翻页都会触发新请求 |
| 详情页(只读) | 少(1~5) | 首屏数据一次性返回,后续操作走 form/redirect |
| SPA 内路由跳转 | 中等 | 路由切换会触发新接口,但首屏请求在注入前已发出 |
| 需要登录的页面 | 视操作而定 | 确保 Chrome 已登录目标网站 |
> **注意**:如果页面在导航完成前就发出了大部分请求(服务端渲染 / SSR 注水),拦截器会错过这些请求。
> 解决方案:在页面加载完成后,手动触发能产生新请求的操作(搜索、翻页、切 Tab、展开折叠项等)。
### 候选 YAML → TS CLI 转换
生成的候选 YAML 是起点,通常需要转换为 TypeScript(尤其是 tae 等内部系统):
**候选 YAML 结构**(自动生成):
```yaml
site: tae
name: getList # 从 URL path 推断的名称
strategy: cookie
browser: true
pipeline:
- navigate: https://...
- evaluate: |
(async () => {
const res = await fetch('/approval/getList.json?procInsId=...', { credentials: 'include' });
const data = await res.json();
return (data?.content?.operatorRecords || []).map(item => ({ ... }));
})()
```
**转换为 TS CLI**(参考 `src/clis/tae/add-expense.ts` 风格):
```typescript
import { cli, Strategy } from '../../registry.js';
cli({
site: 'tae',
name: 'get-approval',
description: '查看报销单审批流程和操作记录',
domain: 'tae.alibaba-inc.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'proc_ins_id', type: 'string', required: true, positional: true, help: '流程实例 IDprocInsId' },
],
columns: ['step', 'operator', 'action', 'time'],
func: async (page, kwargs) => {
await page.goto('https://tae.alibaba-inc.com/expense/pc.html?_authType=SAML');
await page.wait(2);
const result = await page.evaluate(`(async () => {
const res = await fetch('/approval/getList.json?taskId=&procInsId=${kwargs.proc_ins_id}', {
credentials: 'include'
});
const data = await res.json();
return data?.content?.operatorRecords || [];
})()`);
return (result as any[]).map((r, i) => ({
step: i + 1,
operator: r.operatorName || r.userId,
action: r.operationType,
time: r.operateTime,
}));
},
});
```
**转换要点**
1. URL 中的动态 ID`procInsId``taskId` 等)提取为 `args`
2. `captured.json` 里的真实 body 结构用于确定正确的数据路径(如 `content.operatorRecords`
3. tae 系统统一用 `{ success, content, errorCode, errorMsg }` 外层包裹,取数据要走 `content.*`
4. 认证方式:cookie`credentials: 'include'`),不需要额外 header
5. 文件放入 `src/clis/<site>/`,无需手动注册,`npm run build` 后自动发现
### 故障排查
| 现象 | 原因 | 解法 |
|------|------|------|
| 捕获 0 条请求 | 拦截器注入失败,或页面无 JSON API | 检查 daemon 是否运行:`curl localhost:19825/status` |
| 捕获量少(1~3 条) | 页面是只读详情页,首屏数据已在注入前发出 | 手动操作触发更多请求(搜索/翻页),或换用列表页 |
| 候选 YAML 为 0 | 捕获到的 JSON 都没有 array 结构 | 直接看 `captured.json` 手写 TS CLI |
| 新开的 tab 没有被拦截 | 轮询间隔内 tab 已关闭 | 缩短 `--poll 500` |
| 二次运行 record 时数据不连续 | 正常,每次 `record` 启动都是新的 automation window | 无需处理 |
-222
View File
@@ -1,222 +0,0 @@
---
name: opencli-oneshot
description: Use when quickly generating a single OpenCLI command from a specific URL and goal description. 4-step process — open page, capture API, write YAML adapter, test. For full site exploration, use opencli-explorer instead.
tags: [opencli, adapter, quick-start, yaml, cli, one-shot, automation]
---
# CLI-ONESHOT — 单点快速 CLI 生成
> 给一个 URL + 一句话描述,4 步生成一个 CLI 命令。
> 完整探索式开发请看 [CLI-EXPLORER.md](./CLI-EXPLORER.md)。
---
## 输入
| 项目 | 示例 |
|------|------|
| **URL** | `https://x.com/jakevin7/lists` |
| **Goal** | 获取我的 Twitter Lists |
---
## 流程
### Step 1: 打开页面 + 抓包
```
1. browser_navigate → 打开目标 URL
2. 等待 3-5 秒(让页面加载完、API 请求触发)
3. browser_network_requests → 筛选 JSON API
```
**关键**:只关注返回 `application/json` 的请求,忽略静态资源。
如果没有自动触发 API,手动点击目标按钮/标签再抓一次。
### Step 2: 锁定一个接口
从抓包结果中找到**那个**目标 API。看这几个字段:
| 字段 | 关注什么 |
|------|----------|
| URL | API 路径 pattern(如 `/i/api/graphql/xxx/ListsManagePinTimeline` |
| Method | GET / POST |
| Headers | 有 Cookie? Bearer? CSRF? 自定义签名? |
| Response | 数据在哪个路径(如 `data.list.lists` |
### Step 3: 验证接口能复现
`browser_evaluate` 中用 `fetch` 复现请求:
```javascript
// Tier 2 (Cookie): 大多数情况
fetch('/api/endpoint', { credentials: 'include' }).then(r => r.json())
// Tier 3 (Header): 如 Twitter 需要额外 header
const ct0 = document.cookie.match(/ct0=([^;]+)/)?.[1];
fetch('/api/endpoint', {
headers: { 'Authorization': 'Bearer ...', 'X-Csrf-Token': ct0 },
credentials: 'include'
}).then(r => r.json())
```
如果 fetch 能拿到数据 → 用 YAML 或简单 TS adapter。
如果 fetch 拿不到(签名/风控)→ 用 intercept 策略。
### Step 4: 套模板,生成 adapter
根据 Step 3 判定的策略,选一个模板生成文件。
---
## 认证速查
```
fetch(url) 直接能拿到? → Tier 1: public (YAML, browser: false)
fetch(url, {credentials:'include'}) → Tier 2: cookie (YAML)
加 Bearer/CSRF header 后拿到? → Tier 3: header (TS)
都不行,但页面自己能请求成功? → Tier 4: intercept (TS, installInterceptor)
```
---
## 模板
### YAML — Cookie/Public(最简)
```yaml
# src/clis/<site>/<name>.yaml
site: mysite
name: mycommand
description: "一句话描述"
domain: www.example.com
strategy: cookie # 或 public (加 browser: false)
args:
limit:
type: int
default: 20
pipeline:
- navigate: https://www.example.com/target-page
- evaluate: |
(async () => {
const res = await fetch('/api/target', { credentials: 'include' });
const d = await res.json();
return (d.data?.items || []).map(item => ({
title: item.title,
value: item.value,
}));
})()
- map:
rank: ${{ index + 1 }}
title: ${{ item.title }}
value: ${{ item.value }}
- limit: ${{ args.limit }}
columns: [rank, title, value]
```
### TS — Intercept(抓包模式)
```typescript
// src/clis/<site>/<name>.ts
import { cli, Strategy } from '../../registry.js';
cli({
site: 'mysite',
name: 'mycommand',
description: '一句话描述',
domain: 'www.example.com',
strategy: Strategy.INTERCEPT,
browser: true,
args: [
{ name: 'limit', type: 'int', default: 20 },
],
columns: ['rank', 'title', 'value'],
func: async (page, kwargs) => {
// 1. 导航
await page.goto('https://www.example.com/target-page');
await page.wait(3);
// 2. 注入拦截器(URL 子串匹配)
await page.installInterceptor('target-api-keyword');
// 3. 触发 API(滚动/点击)
await page.autoScroll({ times: 2, delayMs: 2000 });
// 4. 读取拦截的响应
const requests = await page.getInterceptedRequests();
if (!requests?.length) return [];
let results: any[] = [];
for (const req of requests) {
const items = req.data?.data?.items || [];
results.push(...items);
}
return results.slice(0, kwargs.limit).map((item, i) => ({
rank: i + 1,
title: item.title || '',
value: item.value || '',
}));
},
});
```
### TS — Header(如 Twitter GraphQL
```typescript
import { cli, Strategy } from '../../registry.js';
cli({
site: 'twitter',
name: 'mycommand',
description: '一句话描述',
domain: 'x.com',
strategy: Strategy.HEADER,
browser: true,
args: [
{ name: 'limit', type: 'int', default: 20 },
],
columns: ['rank', 'name', 'value'],
func: async (page, kwargs) => {
await page.goto('https://x.com');
const data = await page.evaluate(`(async () => {
const ct0 = document.cookie.match(/ct0=([^;]+)/)?.[1];
if (!ct0) return { error: 'Not logged in' };
const bearer = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D...';
const res = await fetch('/i/api/graphql/QUERY_ID/Endpoint', {
headers: {
'Authorization': 'Bearer ' + decodeURIComponent(bearer),
'X-Csrf-Token': ct0,
'X-Twitter-Auth-Type': 'OAuth2Session',
},
credentials: 'include',
});
return res.json();
})()`);
// 解析 data...
return [];
},
});
```
---
## 测试(必做)
```bash
npm run build # 语法检查
opencli list | grep mysite # 确认注册
opencli mysite mycommand --limit 3 -v # 实际运行
```
---
## 就这样,没了
写完文件 → build → run → 提交。有问题再看 [CLI-EXPLORER.md](./CLI-EXPLORER.md)。
-250
View File
@@ -1,250 +0,0 @@
---
name: opencli-operate
description: Make websites accessible for AI agents. Navigate, click, type, extract, wait — using Chrome with existing login sessions. No LLM API key needed.
allowed-tools: Bash(opencli:*), Read, Edit, Write
---
# OpenCLI Operate — Browser Automation for AI Agents
Control Chrome step-by-step via CLI. Reuses existing login sessions — no passwords needed.
## Prerequisites
```bash
opencli doctor # Verify extension + daemon connectivity
```
Requires: Chrome running + OpenCLI Browser Bridge extension installed.
## Critical Rules
1. **ALWAYS use `state` to inspect the page, NEVER use `screenshot`**`state` returns structured DOM with `[N]` element indices, is instant and costs zero tokens. `screenshot` requires vision processing and is slow. Only use `screenshot` when the user explicitly asks to save a visual.
2. **ALWAYS use `click`/`type`/`select` for interaction, NEVER use `eval` to click or type**`eval "el.click()"` bypasses scrollIntoView and CDP click pipeline, causing failures on off-screen elements. Use `state` to find the `[N]` index, then `click <N>`.
3. **Verify inputs with `get value`, not screenshots** — after `type`, run `get value <index>` to confirm.
4. **Run `state` after every page change** — after `open`, `click` (on links), `scroll`, always run `state` to see the new elements and their indices. Never guess indices.
5. **Chain safe commands with `&&`**`type 3 "a" && type 4 "b" && click 7` is one call instead of three. But always run `state` first to get correct indices before chaining.
6. **`eval` is read-only** — use `eval` ONLY for data extraction (`JSON.stringify(...)`), never for clicking, typing, or navigating. Always wrap in IIFE to avoid variable conflicts: `eval "(function(){ const x = ...; return JSON.stringify(x); })()"`.
7. **Prefer `network` to discover APIs** — most sites have JSON APIs. API-based adapters are more reliable than DOM scraping.
## Command Cost Guide
| Cost | Commands | When to use |
|------|----------|-------------|
| **Free & instant** | `state`, `get *`, `eval`, `network`, `scroll`, `keys` | Default — use these |
| **Free but changes page** | `open`, `click`, `type`, `select`, `back` | Interaction — run `state` after |
| **Expensive (vision tokens)** | `screenshot` | ONLY when user needs a saved image |
## Action Chaining Rules
Commands can be chained with `&&`. The browser persists via daemon, so chaining is safe.
**Safe to chain** — these don't change the page structure:
```bash
# Fill multiple fields then submit
opencli operate type 3 "hello" && opencli operate type 4 "world" && opencli operate click 7
# Open and inspect
opencli operate open https://example.com && opencli operate state
```
**Page-changing — always put last** in a chain (subsequent commands see stale indices):
- `open <url>`, `back`, `click <link/button that navigates>`
**Rule**: Chain when you already know the indices. Run `state` separately when you need to discover indices first.
## Core Workflow
1. **Navigate**: `opencli operate open <url>`
2. **Inspect**: `opencli operate state` → elements with `[N]` indices
3. **Interact**: use indices — `click`, `type`, `select`, `keys`
4. **Wait** (if needed): `opencli operate wait selector ".loaded"` or `wait text "Success"`
5. **Verify**: `opencli operate state` or `opencli operate get value <N>`
6. **Repeat**: browser stays open between commands
7. **Save**: write a TS adapter to `~/.opencli/clis/<site>/<command>.ts`
## Commands
### Navigation
```bash
opencli operate open <url> # Open URL (page-changing)
opencli operate back # Go back (page-changing)
opencli operate scroll down # Scroll (up/down, --amount N)
opencli operate scroll up --amount 1000
```
### Inspect (free & instant)
```bash
opencli operate state # Structured DOM with [N] indices — PRIMARY tool
opencli operate screenshot [path.png] # Save visual to file — ONLY for user deliverables
```
### Get (free & instant)
```bash
opencli operate get title # Page title
opencli operate get url # Current URL
opencli operate get text <index> # Element text content
opencli operate get value <index> # Input/textarea value (use to verify after type)
opencli operate get html # Full page HTML
opencli operate get html --selector "h1" # Scoped HTML
opencli operate get attributes <index> # Element attributes
```
### Interact
```bash
opencli operate click <index> # Click element [N]
opencli operate type <index> "text" # Type into element [N]
opencli operate select <index> "option" # Select dropdown
opencli operate keys "Enter" # Press key (Enter, Escape, Tab, Control+a)
```
### Wait
```bash
opencli operate wait selector ".loaded" # Wait for element
opencli operate wait selector ".spinner" --timeout 5000 # With timeout
opencli operate wait text "Success" # Wait for text
opencli operate wait time 3 # Wait N seconds
```
### Extract (free & instant, read-only)
Use `eval` ONLY for reading data. Never use it to click, type, or navigate.
```bash
opencli operate eval "document.title"
opencli operate eval "JSON.stringify([...document.querySelectorAll('h2')].map(e => e.textContent))"
# IMPORTANT: wrap complex logic in IIFE to avoid "already declared" errors
opencli operate eval "(function(){ const items = [...document.querySelectorAll('.item')]; return JSON.stringify(items.map(e => e.textContent)); })()"
```
### Network (API Discovery)
```bash
opencli operate network # Show captured API requests (auto-captured since open)
opencli operate network --detail 3 # Show full response body of request #3
opencli operate network --all # Include static resources
```
### Sedimentation (Save as CLI)
```bash
opencli operate init hn/top # Generate adapter scaffold
opencli operate verify hn/top # Test the adapter
```
### Session
```bash
opencli operate close # Close automation window
```
## Example: Extract HN Stories
```bash
opencli operate open https://news.ycombinator.com
opencli operate state # See [1] a "Story 1", [2] a "Story 2"...
opencli operate eval "JSON.stringify([...document.querySelectorAll('.titleline a')].slice(0,5).map(a => ({title: a.textContent, url: a.href})))"
opencli operate close
```
## Example: Fill a Form
```bash
opencli operate open https://httpbin.org/forms/post
opencli operate state # See [3] input "Customer Name", [4] input "Telephone"
opencli operate type 3 "OpenCLI" && opencli operate type 4 "555-0100"
opencli operate get value 3 # Verify: "OpenCLI"
opencli operate close
```
## Saving as Reusable CLI — Complete Workflow
### Step-by-step sedimentation flow:
```bash
# 1. Explore the website
opencli operate open https://news.ycombinator.com
opencli operate state # Understand DOM structure
# 2. Discover APIs (crucial for high-quality adapters)
opencli operate eval "fetch('/api/...').then(r=>r.json())" # Trigger API calls
opencli operate network # See captured API requests
opencli operate network --detail 0 # Inspect response body
# 3. Generate scaffold
opencli operate init hn/top # Creates ~/.opencli/clis/hn/top.ts
# 4. Edit the adapter (fill in func logic)
# - If API found: use fetch() directly (Strategy.PUBLIC or COOKIE)
# - If no API: use page.evaluate() for DOM extraction (Strategy.UI)
# 5. Verify
opencli operate verify hn/top # Runs the adapter and shows output
# 6. If verify fails, edit and retry
# 7. Close when done
opencli operate close
```
### Example adapter:
```typescript
// ~/.opencli/clis/hn/top.ts
import { cli, Strategy } from '@jackwener/opencli/registry';
cli({
site: 'hn',
name: 'top',
description: 'Top Hacker News stories',
domain: 'news.ycombinator.com',
strategy: Strategy.PUBLIC,
browser: false,
args: [{ name: 'limit', type: 'int', default: 5 }],
columns: ['rank', 'title', 'score', 'url'],
func: async (_page, kwargs) => {
const limit = Math.min(Math.max(1, kwargs.limit ?? 5), 50);
const resp = await fetch('https://hacker-news.firebaseio.com/v0/topstories.json');
const ids = await resp.json();
return Promise.all(
ids.slice(0, limit).map(async (id: number, i: number) => {
const item = await (await fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)).json();
return { rank: i + 1, title: item.title, score: item.score, url: item.url ?? '' };
})
);
},
});
```
Save to `~/.opencli/clis/<site>/<command>.ts` → immediately available as `opencli <site> <command>`.
### Strategy Guide
| Strategy | When | browser: |
|----------|------|----------|
| `Strategy.PUBLIC` | Public API, no auth | `false` |
| `Strategy.COOKIE` | Needs login cookies | `true` |
| `Strategy.UI` | Direct DOM interaction | `true` |
**Always prefer API over UI** — if you discovered an API during browsing, use `fetch()` directly.
## Tips
1. **Always `state` first** — never guess element indices, always inspect first
2. **Sessions persist** — browser stays open between commands, no need to re-open
3. **Use `eval` for data extraction**`eval "JSON.stringify(...)"` is faster than multiple `get` calls
4. **Use `network` to find APIs** — JSON APIs are more reliable than DOM scraping
5. **Alias**: `opencli op` is shorthand for `opencli operate`
## Troubleshooting
| Error | Fix |
|-------|-----|
| "Browser not connected" | Run `opencli doctor` |
| "attach failed: chrome-extension://" | Disable 1Password temporarily |
| Element not found | `opencli operate scroll down && opencli operate state` |
| Stale indices after page change | Run `opencli operate state` again to get fresh indices |

Some files were not shown because too many files have changed in this diff Show More