Metadata-Version: 2.4
Name: mindcode
Version: 0.2.0
Summary: codex-style interactive coding agent on top of mindagent
Author: mindcode
License: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: mindagent
Requires-Dist: rich>=13
Requires-Dist: openai>=1.0
Requires-Dist: python-dotenv>=1.0
Requires-Dist: typer>=0.12
Requires-Dist: prompt-toolkit>=3.0.30

# mindcode

codex 风格的交互式 Coding Agent CLI，构建在 [mindagent](../) 之上。

## 核心能力

- workspace 内的代码读取、编辑和命令执行
- 交互式会话与一次性任务
- 前台/后台任务记录和进程重启后的语义恢复
- 本地持久终端和 SSH 远程命令
- mini、SWE-bench 和 Terminal-Bench 评测入口

## 特性

- **typer 多子命令**：`mindcode shell` / `chat` / `status` / `config`（默认 `mindcode` 等于 `mindcode shell`）
- **可选 Subagent 模式**：`mindcode shell --subagents` 启用受限的 master/coder 协作；master 仅能委派，coder 才能访问 workspace
- 全屏 TUI：顶部 logo/会话信息、可滚动 Markdown 消息区、固定带边框多行输入框与状态栏
- 顶部信息栏显示本会话累计 token 消耗；provider 未返回 usage 时显示 `tokens —`
- Rich 富渲染：Markdown、彩色工具面板、file_edit diff 高亮和流式 LLM 输出
- TUI 内选择菜单：`/models`、`/permissions` 用方向键选择
- REPL 权限模式：`ask_user`（默认，逐项询问）/ `full_accept`（全部接受）
- 会话持久化与恢复：基于 `LocalConversationStore`，存到 `~/.cache/mindcode/sessions/`
- OpenAI-compatible Provider 配置：首次启动时在 `~/.cache/mindcode/config.toml` 生成 rotor 示例
- 丰富 slash 命令：`/models` `/compact` `/permissions` `/status` `/config` `/sessions` `/history` `/diff` `/clear` `/help` `/exit`

## VS Code 插件

与 CLI 配套的 VS Code 聊天插件位于 [`vscode-extension/`](vscode-extension/)。
进入该目录并按其 README 构建后，可在 VS Code 中按 `F5` 启动 Extension Development Host。

## 安装

先确保父项目 `mindagent` 已经以 editable 模式安装：

```bash
cd /path/to/mindagent
pip install -e ".[openai]"
```

然后安装 mindcode：

```bash
cd app/mindcode
pip install -e .
```

## 命令结构

```
mindcode                              # 默认 = mindcode shell
mindcode shell [PROMPT] [选项]        # 交互式 REPL（默认子命令）
mindcode chat -m "..." [选项]         # 一次性 prompt
mindcode status                       # 显示全局状态
mindcode task <subcmd>                # 运行、恢复、查看和取消任务
mindcode terminal <subcmd>            # 管理本地持久终端
mindcode remote <subcmd>              # 管理 SSH 目标并执行命令
mindcode bench <subcmd>               # 运行或查看 benchmark
mindcode config <subcmd>              # 配置管理
  mindcode config providers           # 列出所有 provider
  mindcode config models <provider>   # 列出 provider 的模型
  mindcode config api-key <p> <k>     # 设置 api_key
  mindcode config get <p> <field>     # 读取字段
  mindcode config set <p> <f> <v>     # 修改字段
  mindcode config list                # 显示完整配置（脱敏）
  mindcode config path                # 显示配置文件路径
mindcode --version
mindcode --help
```

## 配置

首次启动 `mindcode` 会自动在 `~/.cache/mindcode/config.toml` 创建一个
OpenAI-compatible rotor 示例。默认地址是本机 `http://127.0.0.1:8000/v1`，使用前应按实际网关修改。

模板节选：

```toml
default_provider = "rotor"

[providers.rotor]
protocol = "openai"
api_key = ""
base_url = "http://127.0.0.1:8000/v1"
default_model = "glm-5.2"
models = ["glm-5.2", "glm-5.1", "glm-4.7"]
```

### 方式 A：命令行（脚本化）

```bash
mindcode config api-key rotor sk-xxxxxxxxxxxx     # 设置密钥
mindcode config providers                         # 列出所有 provider
mindcode config models rotor                      # 列出 rotor 的模型
mindcode config set rotor default_model glm-5.1
mindcode config list                              # 完整配置（脱敏）
```

### 方式 B：REPL 内 slash 命令（交互式）

```
/models                                         # 方向键选择切换
/compact                                        # 生成摘要以压缩会话上下文
/permissions                                    # Ask User / Full Accept
/config                                         # 显示当前配置
/status                                         # Rich Panel 状态
/help                                           # 完整命令列表
```

也可直接编辑 `~/.cache/mindcode/config.toml`。

## 使用

### 一次性模式

```bash
mindcode chat -m "读取 README.md 的前 5 行并总结"
# 或
mindcode shell "读取 README.md 的前 5 行并总结"
# 需要 master/coder 协作时（默认仍为单 agent）
mindcode shell --subagents "审查当前改动并运行相关测试"
```

### 交互模式

- `Enter` 发送；`Esc` + `Enter` 插入换行；多行输入框会自动增高。
- 输入 `/` 显示全部 slash 命令；继续输入会筛选。`↑` / `↓` 选择，`Enter` 先填入默认第一项，再按一次才执行。
- `/models` 与 `/permissions` 使用统一的灰阶选择框：`↑` / `↓` 切换，`Enter` 应用，`Esc` 取消；需要自由输入参数时仍在底部输入框内编辑和粘贴。
- `Page Up` / `Page Down` 或鼠标滚轮滚动消息；`End` 回到底部。
- 鼠标拖选消息会复制所选文本；`Ctrl` + `Y` 复制最新一条助手回复。
- 单行文字在输入框和用户消息卡片内上下居中；多行内容向下撑开。
- 用户消息会以与输入框相同的边框卡片进入对话，助手消息保留 Markdown 排版。
- Agent 运行时显示 `Working…`，输入框仍可提交后续消息并按顺序排队。
- 工具状态使用简洁标签：`Edit`、`Command`、`Read`、`Search`、`Context`、`Memory`、`Image`、`Time`、`Calculate`、`Delegate`；完成或失败时原地更新。

```bash
mindcode                                     # 默认进 shell
› 在 workspace 创建 hello.txt 写入 hi
   › file_edit (create) hello.txt [WRITE]
   ask_user 将在执行前询问；也可切换到 /permissions full_accept
   ┌─ diff: hello.txt ──────────────────────┐
   │ +hi                                     │
   └─────────────────────────────────────────┘
› /diff
› /sessions
› /exit
```

### 恢复会话

```bash
mindcode shell -r sess-1718530000
› 我刚才创建了什么文件？
```

### `mindcode shell` 参数

```
mindcode shell [PROMPT] [-w WORKSPACE] [-a {ask_user,full_accept}]
                       [-p PROVIDER] [-m MODEL]
                       [-r SESSION_ID] [-s SESSION_ID] [--no-stream] [--subagents]
```

| 参数 | 说明 |
|---|---|
| `PROMPT` | 一次性 prompt；省略进入交互模式 |
| `-w, --workspace` | workspace 根目录（默认 `.`） |
| `-a, --approve-mode` | 权限模式：`ask_user`（默认，逐项询问）或 `full_accept`（全部接受）；`ask`/`full`/`auto` 为兼容别名 |
| `-p, --provider` | 覆盖 config.toml 中的 default_provider |
| `-m, --model` | 覆盖 provider 中的 default_model |
| `-r, --resume` | 恢复指定 session_id |
| `-s, --session` | 指定新 session_id |
| `--no-stream` | 关闭流式输出 |
| `--subagents` | 启用 master/coder 委派模式。master 只允许 `agent_delegate`，coder 负责 workspace 工具调用；委派固定等待结果，不会启动后台任务。 |

## 测试

```bash
PYTHONPATH=src:app/mindcode python -m pytest -q app/mindcode/tests
```

## 模块结构（对齐 mindbot/src/mindbot/cli/）

```
mindcode/
├── _version.py             # __version__, __logo__
├── config.py               # MindcodeConfig + ProviderConfig + load/save
├── runtime.py              # build_runtime/build_master_worker_system + DiffingFileEditTool
├── subagents.py            # MasterWorkerSystem 生命周期边界
├── policy.py               # ApprovalMode + AskUserPolicy/FullAcceptPolicy
├── render.py               # RichRenderer（event handler）
├── tasking.py              # 本地任务记录与事件持久化
├── terminal_core.py        # 本地持久终端
├── remote.py               # SSH 配置与命令执行
├── bench/                  # benchmark adapter、runner 和 scorer
└── cli/
    ├── __init__.py         # typer app + 命令注册
    ├── _shared.py          # 共享 console + find_config_file
    ├── commands/
    │   ├── shell.py        # `mindcode shell`
    │   ├── chat.py         # `mindcode chat -m "..."`
    │   ├── status.py       # `mindcode status`
    │   ├── config_cmd.py   # `mindcode config providers/models/api-key/...`
    │   ├── task.py         # `mindcode task ...`
    │   ├── terminal.py     # `mindcode terminal ...`
    │   ├── remote.py       # `mindcode remote ...`
    │   └── bench.py        # `mindcode bench ...`
    └── shell/
    ├── repl.py         # Shell 类 + REPL 主循环
    ├── slash.py        # slash 命令分发
    ├── tui.py          # 全屏布局、Markdown 消息流与状态栏
    ├── menu.py         # interactive_menu（ChoiceInput 包装）
        └── startup.py      # build_welcome_banner（Rich Panel）
```

## 设计要点

- `DiffingFileEditTool` 包装 mindagent 的 `FileEditTool`，在调用前后捕获文件内容，生成 unified diff 注入到 `Observation.result["mindcode_diff"]`。
- diff 渲染监听 `OBSERVATION_CREATED` 事件而非 `ACTION_FINISHED`，因为 result payload 只在前者。
- REPL 的 `/permissions` 通过重建当前 runtime 切换 `ask_user` 与 `full_accept`；前者逐项询问，后者全部接受，切换只影响当前会话。
- typer app 用自定义 `TyperGroup.parse_args`：`mindcode` 无参数或第一参数是 shell 的 flag → 自动注入 `shell` 子命令，复用完整参数解析。
- 全屏 TUI 用 Prompt Toolkit 管理固定输入框和消息视口；Rich 负责 Markdown 与工具输出渲染。
- ChoiceInput 失败时（旧版 prompt_toolkit）会自动 fallback 到序号输入。

## 局限

- 不支持 `/undo`：`exec_command` 的副作用可能不可逆，回滚复杂。
- 会话恢复只续聊 user/assistant 历史，不恢复 TaskState / Evidence / pending continuation。
- `task resume` 是重新观察 workspace 后创建新 Run，不会重放未确认的旧 Action。
- 后台任务目前依赖本机 PID；不提供跨主机监督或精确进程身份恢复。
