Metadata-Version: 2.4
Name: aicd
Version: 1.4.2
Summary: CLI AI Agent for code and documentation
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: typer>=0.9.0
Requires-Dist: textual>=0.47.0
Requires-Dist: rich>=13.0.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: openai>=1.40.0
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: aiosqlite>=0.19.0
Requires-Dist: pymupdf>=1.24.0
Requires-Dist: python-docx>=1.1.0
Requires-Dist: openpyxl>=3.1.0
Requires-Dist: python-pptx>=0.6.23
Requires-Dist: Pillow>=10.0.0
Requires-Dist: numpy>=1.24.0
Requires-Dist: mammoth>=1.8.0
Requires-Dist: markdownify>=0.13.0
Requires-Dist: markdown>=3.5.0
Requires-Dist: playwright>=1.45.0
Requires-Dist: cryptography>=42.0.0
Requires-Dist: filelock>=3.13.0
Requires-Dist: charset-normalizer>=3.3.0
Requires-Dist: beautifulsoup4>=4.12.0
Requires-Dist: tree-sitter-language-pack
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: build>=1.2.0; extra == "dev"
Requires-Dist: fastapi>=0.115.0; extra == "dev"
Requires-Dist: uvicorn[standard]>=0.32.0; extra == "dev"
Requires-Dist: XlsxWriter>=3.2.0; extra == "dev"
Requires-Dist: markitdown[docx,pdf,pptx,xls,xlsx]>=0.1.0; extra == "dev"
Provides-Extra: db
Requires-Dist: asyncpg>=0.29.0; extra == "db"
Requires-Dist: aiomysql>=0.2.0; extra == "db"
Provides-Extra: api
Requires-Dist: fastapi>=0.115.0; extra == "api"
Requires-Dist: uvicorn[standard]>=0.32.0; extra == "api"
Provides-Extra: ocr
Requires-Dist: pytesseract>=0.3.10; extra == "ocr"
Provides-Extra: opencv
Requires-Dist: opencv-python-headless>=4.8.0; extra == "opencv"
Provides-Extra: pdf
Requires-Dist: docx2pdf>=0.1.8; extra == "pdf"
Requires-Dist: reportlab>=4.0.0; extra == "pdf"
Provides-Extra: visio
Requires-Dist: vsdx>=0.6.1; extra == "visio"
Provides-Extra: desktop
Requires-Dist: pyautogui>=0.9.54; extra == "desktop"
Requires-Dist: mss>=9.0.0; extra == "desktop"
Provides-Extra: code-tree
Requires-Dist: tree-sitter>=0.21.0; extra == "code-tree"
Requires-Dist: tree-sitter-language-pack>=1.0.0; extra == "code-tree"
Provides-Extra: web
Requires-Dist: trafilatura>=1.6.0; extra == "web"
Requires-Dist: lxml>=5.0.0; extra == "web"
Provides-Extra: xlsxwriter
Requires-Dist: XlsxWriter>=3.2.0; extra == "xlsxwriter"
Provides-Extra: markitdown
Requires-Dist: markitdown[docx,pdf,pptx,xls,xlsx]>=0.1.0; extra == "markitdown"

# aicd

命令行 AI Agent：聊天驱动文件、进程、HTTP、任务与子 Agent。Windows 优先，预留 Linux。

本工具借助大模型，在对话中完成**由代码生成文档**与**由文档生成代码**的闭环，并对项目中的文档与源码做**深入分析与理解**，便于梳理设计、落地实现与持续维护。

## 技术文档（功能与插件）

- **[docs/AICD_FEATURES.md](docs/AICD_FEATURES.md)**：运行时、入口（TUI / GUI / noui）、Agent / 工具、任务、插件、配置与源码索引。
- **[docs/AICD_ARCHITECTURE.md](docs/AICD_ARCHITECTURE.md)**：技术分层、`RuntimeContext` 与工具路由、数据流、子进程与联网信任边界、扩展点。
- **[docs/AICD_CAPABILITIES.md](docs/AICD_CAPABILITIES.md)**：能力矩阵（FS / Shell / 密码学 / 媒体 / 块 I/O 等）与实现状态。
- **[docs/AICD_REQUIREMENTS_MEDIA_CRYPTO.md](docs/AICD_REQUIREMENTS_MEDIA_CRYPTO.md)**：媒体与加密相关需求、合规边界、块读写目标与 **P0–P3** 待办。
- **[docs/PLUGIN_AUTHORING_SPEC.md](docs/PLUGIN_AUTHORING_SPEC.md)**：插件清单、工具与 handler 约定、加载失败与日志、AI 生成插件时的自检要点（随实现变更需同步维护）。
- **[docs/RELEASE_PUBLISH.md](docs/RELEASE_PUBLISH.md)**：版本号、`CHANGELOG`、pytest / `release_precheck`、`build` + `twine` 上传 PyPI（含 Windows UTF-8 注意）；供发版与 AI 按清单执行。

## Python 版本

`pyproject.toml` 中 **`requires-python = ">=3.10"`**。实现上避免依赖仅 3.11+ 的标准库（例如用 **`datetime.timezone.utc`**，而不用 **`datetime.UTC`**）。**CI**（`.github/workflows/tests.yml`）在 **Python 3.10** 与 **3.12** 上跑 **`pytest`**。部分可选能力仍依赖第三方（Playwright、Tree-sitter、`aicd[code-tree]` 等）在对应版本上的 wheels 与本机环境，以各包文档为准。

## 文档库与版本迭代（约定）

Agent 在 **AI 输出根**（默认 `<workspace>/aicd/`）下使用 **`output/library/<doc_slug>/`** 存放可复用素材（`apis/`、`diagrams/`（含 **`.mmd`、`.drawio`、`.vsdx`** 等）、`outlines/`、`markdown/` 等），并建议维护 **`INDEX.md`**（含 **`latest:`** 指向当前正文、**`## Revisions`** 变更记录）。**首次成稿后**你仍可继续提修改需求；模型应在**已读 `latest` 或最高 `_vNNN` 文件**的基础上**另存为新版本**（如 `_v004`），**不覆盖**旧版，除非明确要求替换。对外交付可复制到 **`output/deliverables/<topic_slug>/`**。细则见源码中 `DOC_AUTHORING_ITERATION_DIRECTIVES` 与 `.cursor/skills/aicd-ai-output/SKILL.md`。

## 环境

```powershell
cd <本仓库根目录>
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -e .
# 可选：Agent 访问 PostgreSQL / MySQL（db_inspect / db_query）
pip install -e ".[db]"
# 可选：只读聊天历史 HTTP API（aicd serve）
pip install -e ".[api]"
# 可选：PDF 整页 OCR（doc_extract use_ocr）
pip install -e ".[ocr]"
# 可选：Microsoft Visio .vsdx 流程图（visio_flowchart_write / visio_vsdx_summarize）
pip install -e ".[visio]"
# 可选：doc_extract / doc_normalize 使用 MarkItDown（PDF / Office 含 .xls；.doc/.ppt 需 LibreOffice → Markdown）
pip install -e ".[markitdown]"
# 可选：复杂格式写 Excel（列宽/冻结窗格/合并等，工具 xlsx_write_xlsxwriter；读补丁仍用 openpyxl）
pip install -e ".[xlsxwriter]"
# 可选：浏览器自动化
playwright install chromium
```

**图形界面（可选）**：`aicd gui` 或 `aicd --gui` 使用 Python 自带 **tkinter**。**Linux** 若报缺少 `_tkinter`，请安装系统包，例如 Debian/Ubuntu：`sudo apt install python3-tk`。

## Windows 下 TUI 显示（cmd / conhost）

**助手回复排版**：默认用 **Rich Markdown** 渲染助手消息，将 **`**加粗**`**、**`##` 标题**、行内 **`` `代码` ``** 等转为终端粗体/样式，而不是显示原始 `**` 符号。若需**完全纯文本**（不解析 Markdown），设 **`AICD_TUI_ASSISTANT_MARKDOWN=0`**，或在 **`HOME/data/tui_prefs.json`** 写入 **`"assistant_markdown_chat": false`**（环境变量 0/1 优先于该键）。无论是否开启 Markdown，若助手回复中含 **GFM 管道表格**（`| ... |`），TUI 会先将其**转成等宽文本表**再显示；列较多时可设 **`AICD_TUI_TABLE_WIDTH`**（像素列宽近似为字符宽度，默认 **100**，范围约 **40–260**）以减轻折行。

Textual 界面依赖 **VT100 转义与备用屏幕**。**Windows 10 自带「命令提示符」窗口（经典 conhost）** 在鼠标事件、子进程往同一控制台打印（例如 **Playwright 首次下载浏览器** 的进度条）时容易出现**花屏、重影、布局错位**。建议：

0. **传统字符界面（推荐在仍花屏时使用）**：`aicd tui --console` 或 `set AICD_CONSOLE=1` 后 `aicd tui` —— **不启动 Textual**，仅用 **stdin/stdout** 多轮对话（工具行以 `[tool …]` 打印；多行输入时在正文后**再敲一个空行**表示本条发送）。无全屏备用缓冲、无框线绘制。**无 TUI 侧任务面板**（后台 `task_ai` 等仍可用，但无图形任务表）。
1. 使用 [**Windows Terminal**](https://aka.ms/terminal) 或 **VS Code 集成终端** 再执行 `aicd tui`（体验与 Textual 官方推荐一致）。
2. **Playwright**：在**另开**的命令行先执行 `python -m playwright install chromium`，避免在 TUI 会话内向同一窗口刷安装进度。
3. 若必须在经典 cmd 中使用，本版本会尽量**提前打开控制台虚拟终端模式**。**TUI 默认始终启用鼠标**（与各终端一致）；若在经典 conhost 中出现错位或乱码，可设 **`AICD_TUI_MOUSE=0`** 关闭鼠标。其它微调：
   - **`AICD_TUI_ANSI_COLOR=1`**：尝试让 Textual 走原始 ANSI 色彩路径（个别旧控制台可略好）。
   - **`AICD_SKIP_WIN_VT=1`**：跳过启动时对 stdout/stderr 的 VT 预处理（一般无需设置）。

## 配置（config.yaml）

- **`llm`**：`apiKey` / `baseUrl` / `modelId`；可选 **`visionModel`**（多模态专用，缺省沿用主模型）；**`timeoutSec`**；**`maxRetries`**（单次请求失败后额外重试次数，0–20，默认 3）；**`retryBaseDelaySec`**（退避基数秒，默认 1.0）；采样字段 `temperature`、`topP` 等。
- **`agent`**：**`maxToolRounds`** / **`subAgentMaxToolRounds`** 各 **1–500**（超出会截断）；**`contextBudgetTokens`**、**`chatHistoryMaxMessages`**（启动时从 SQLite 恢复尾部消息再按 **有效** token 预算裁剪；**`chat_session_info`** 返回 **`context_adaptive`**：工具回传 **`tool_result_max_chars`**、hydrate 行预览长度、**`effective_recent_full_rows`**、多模态 **`vision_image_token_budget_per_image`** 等均由**连续公式 + clamp** 随 **`model_context_window_tokens` / `effective_context_budget_tokens`** 伸缩，**非枚举档位**）。可选 **`visionImageTokenBudgetPerImage`**（2000–32000）覆盖默认 vision 粗估。**`interactiveProcessIdleSec`**（可选，秒）：**`interactive_process`** 会话在无 **start/write/read** 活动超过该时长后自动结束，**0** 表示关闭（YAML 驼峰同 `docs/AICD_FEATURES.md`）。**`blockExternalNetwork`**（默认 **false**）：为 **true** 时 Aicd **内置工具**不得访问**非回环**外网 HTTP(S)/WS(S)，**LLM 请求**除外；也可用环境变量 **`AICD_BLOCK_EXTERNAL_NETWORK=1`** 或启动参数 **`--block-external-network`**（与子命令连写：**`aicd --block-external-network tui`**）。**`run_command` 等不受此限制**。详见 **`CHANGELOG.md` 0.3.4** 与 **`docs/AICD_FEATURES.md`**。
- **`paths`**：`full_disk`、`allowed_roots` 等（见代码内默认值）。
- **`plugins`**（可选）：**`allowPythonHandlers`**；**`maxPlugins`**；**`backupKeep`**；**`logRetentionDays`**（各插件 **logs/** 按 UTC 日期分文件，保留天数，默认 7）。扩展目录：**`AICD_HOME/plugins/<id>/`**（**plugin.yaml**：**name**、可选 **display_name**/**title**、**description**、**version** 等）。详见 **plugins/README.md**。管理工具：**plugin_list**、**plugin_info**、**plugin_read_log**、**plugin_reload**、**plugin_backup_now** / **plugin_restore_backup** 等。

环境变量 **`AICD_HOME`**：应用数据目录。未设置且未使用 `--home` 时，使用 **`%USERPROFILE%\.aicd`**（Windows）。其下 **`logs/`** 每次 `aicd tui` 会新建时间戳日志；LLM 重试会写入会话日志。

缺依赖时 Agent 会说明缺少的组件与推荐安装命令；若你在对话中明确说 **「帮我安装」** 等，模型可按 **`runtime_env.yaml`** 中的 **`python.executable`** 执行 **`python -m pip install …`**（与当前 Aicd 同一解释器），并调用 **`runtime_env_refresh`** 刷新环境快照。

**环境自检（模型侧）**：工具 **`agent_environment_digest`** 返回紧凑 JSON（常用 CLI、可选 Python 模块、LLM 协议/模型名、是否已配置 API Key——**不含密钥**、主/子 Agent 工具轮次上限等）；可选 **`include_capabilities_text`** 附带 `env_capabilities_summary.txt` 节选。安装新软件或 pip 依赖后可用 **`refresh_first`: true** 或先 **`runtime_env_refresh`**。系统提示中的 **Agent introspection** 约定：开工前或遇 **`ok: false`** 时核对环境，指令模糊或多方案时与用户对齐后再执行。

## 命令行

| 命令 | 说明 |
|------|------|
| `aicd init [--home DIR]` | 初始化 HOME、`config.yaml`、SQLite |
| `aicd tui [--home DIR] [--work DIR]` | TUI；**`--work`** 启动后立刻将 AI 工作区设为该目录（等同 `/work`） |
| `aicd --ai "…"`（可省略 `tui`） | 与 **`aicd tui --ai`** 相同；另支持顶层 **`--noui` / `-w` / `-o` / `--home` / `--skip-setup`** |
| `aicd tui --console` | **纯文本多轮**（无 Textual）；顶层可 **`aicd --console`**；等价环境变量 **`AICD_CONSOLE=1`** |
| `aicd gui` | **Tk 图形窗口**（Win/Linux，`tkinter`）；顶层可 **`aicd --gui`**；支持 **`--home` / `-w` / `-o` / `--ai` / `--skip-setup`** |
| `aicd serve …` | HTTP API（需 **`pip install -e ".[api]"`**）：默认可只读聊天历史；**`--runtime-api`** 时多连接 **invoke**（与 **`aicd host`** 同款 JSON）；鉴权见下文 |
| `aicd host` | stdin/stdout **一行一 JSON**：**`main_chat`**、**`main_inbox_continue`**（主收件箱未读时跑一轮接续，见 **`docs/AICD_FEATURES.md`**）、**`task_ai`** 等；**`--require-nonce`** 或 **`AICD_HOST_REQUIRE_NONCE=1`** 时须 **`auth.nonce`** |
| `aicd version` | 打印版本 |

**联网策略（可选）**：多数字命令支持 **`--block-external-network`**（等价 **`AICD_BLOCK_EXTERNAL_NETWORK=1`**）：仅限制 **Aicd 内置工具** 的外向 HTTP(S)/WS(S)（回环与 **file:** 除外），不限 **LLM** 与你在 shell 里跑的命令。根命令可写 **`aicd --block-external-network tui`**。

TUI 斜杠：**`/work`**、**`/doc`**、**`/agent`**、**`/llm`**（含 `maxRetries`、`retryBaseDelaySec`）、**`/task`**、**`/exit`**。

## Agent 能力与工具（摘要）

- **子进程（`run_command` / `task_shell` / `script_run`）**：子进程**不**挂载用户聊天输入为交互式 TTY；适合**一次性 CLI**、带 **`-y` / `--yes`** 的安装、或用 **`stdin_mode`**（**`devnull`** / **`auto_yes`**）与 **`noninteractive_env`** 做非交互跑批。**`stdin_mode=inherit`** 在未指定 **`output_idle_timeout_sec`** 时，默认若 **900s** 内 stdout/stderr 无**新行**则终止（防等 stdin 卡死）；**`auto_yes`** 默认 **600s**；**`0`** 可关闭该守卫。**`timeout_sec`** 为总时长（墙钟）硬上限。密码类提示会返回 **`interactive_password_or_secret_prompt`**。**vim / less / pdb / 交互式 REPL** 等应请用户在本机终端执行。详见 **`prompts.py`** 中 **`SHELL_EXECUTION_DIRECTIVES`**、**`.cursor/skills/aicd-shell-execution/SKILL.md`**。
- **工作区**：主会话须用工具 **`ai_workspace_set`** 切换项目目录（**`run_command cd` 无效**）；TUI 用 **`/work`**。
- **环境与自省**：**`agent_environment_digest`**（可选 **`refresh_first`**）、**`runtime_env_refresh`**；完整探测见 **`$AICD_HOME/data/runtime_env.yaml`** 与 **`env_capabilities_summary.txt`**。详见 **`src/aicd/agent/prompts.py`** 中 **`AGENT_INTROSPECTION_DIRECTIVES`**。
- **多模态**：**`vision_analyze_image`** — 将本地图片送视觉模型解析图表/图中文字；默认 **`save_report`** 把结果写入 **AI tmp**（`ai_output_dir/tmp`），便于后续 **`fs_read_file`**。发送前会对大图做长边与体积压缩（默认长边 ≤1920、编码目标 ≤1MiB 等，见 `llm.image_file_to_data_url`）。
- **文档**：**`doc_extract`** / **`doc_normalize`**（PDF、DOCX/PPTX/XLSX、旧版 XLS、**`markdown_engine=markitdown`** 时另支持 **.doc/.ppt** 经 LibreOffice 预处理）；可选 **`markdown_engine=markitdown`**（**`pip install -e ".[markitdown]"`**）。**`document_outline`** — 对 `.md`/`.html`/`.txt` 提取标题树、**行号**与 **UTF-8 字节偏移**，默认写入 **`tmp/outlines/<stem>.json`**，便于大文档分块阅读。
- **超大上下文策略**：系统提示中的 **LARGE_CONTEXT** 约定：先检索/提纲（**`document_outline`**）再 **`fs_search_regex` / `run_command` 切片**（**`fs_read_file`** 当前**无**字节 **offset**，整文件读入后按 **`max_read_bytes` 截断**）；在 **`ai_tmp`** 写清单与 **`session_focus.md`**（稳定事实 vs 工作假设）、大输出落盘、必要时 **`task_ai`** / **`chat_save_summary`** / **`chat_history_*`**。详见 **`docs/AICD_FEATURES.md`** / **`docs/AICD_CAPABILITIES.md`**。
- **聊天持久化**：消息与摘要存 SQLite；**`aicd serve`** 提供 HTTP 拉取（只读历史；可选 **`--runtime-api`** 全时调用 **`main_chat` / plugin_load** 等与 stdio Host 相同语义，与 TUI 共用同一库）。
- **主 / 子任务闭环**：复杂工作优先 **`task_ai`**。主会话可在旧子任务仍 **`running`** 时继续发话；若新意图属于同一子任务，主 AI 应 **`task_message_send`**（**`kind`**: **`directive`**，**`body`**: `{"text":"..."}`，主会话可省略 **`from_task_id`**，库内记为 **`main-<session_id>`**）。子 Agent 在每段 LLM 工具循环结束后**自动拉取收件箱**；有未读则合并为新的 **user** 轮次并继续，**无新消息则任务结束**。累计 LLM 轮次有上限（约 `max(subAgentMaxToolRounds*6, 300)`），防无限循环。相关工具：**`task_list`** / **`task_result`**（**timeline**）、**`task_thread_stats`**。
- **`script_run` 脚本备份**：每次运行会在 **`AICD_HOME/tmp/scripts/`** 写入规范化临时文件，执行结束后**复制**到 **`<workspace>/aicd/bak/`**（同名），便于审查与复用；工具返回 **`script_bak_path`**。建议传 **`related_doc`**（如当前文档/交付物简称）以便文件名对齐上下文。详见 `prompts.py` 与 **`.cursor/skills/aicd-ai-output/SKILL.md`**。
- **图表 HTML → 栅格 → Word/PPT**：**`viz_export_html` / `viz_data_chart`** 的 **`.html` + `res/`须保留**；嵌入 **`docx_compose` / `pptx_compose`** 前用 **`viz_html_to_png`** 生成 **`.png`**，勿把 `.html` 当图片路径。**整册精美 PPT** 推荐 **`pptx_from_html_deck`**（每页 HTML → 固定视口截图 → 全幅幻灯片，并写 **`pptx_deck_source.json`** 保留源页清单以便插页与改版）。
- **Visio 流程图（`.vsdx`）**：需 **`pip install -e ".[visio]"`** 或 **`pip install "vsdx>=0.6.1"`**（PyPI 包名是 **`vsdx`**，**不是** `python-visio`——后者在 PyPI 上不可用，会导致 *No matching distribution*）。Agent 应使用内置工具 **`visio_flowchart_write`** / **`visio_vsdx_summarize`**，**不要**用 **`script_run`** 手写 `.vsdx` 的 ZIP/XML 目录树（易出现 `visio/_rels` 等路径错误）。用户**明确要求 Visio / `.vsdx`** 时，须生成并**长期保留**源文件（建议 **`output/library/<doc_slug>/diagrams/`** 或 **`output/deliverables/`**）。来自**图片**的流程图可先 **`vision_analyze_image`** 抽取 **`nodes`/`edges`**，再 **`visio_flowchart_write`**。详见 **`src/aicd/agent/prompts.py`** 的 **`VISIO_DIRECTIVES`**。
- **PDF 生成**：**`markdown_to_pdf`** — 默认 **`engine=pymupdf`**（Markdown→HTML→**PyMuPDF Story**，支持表格/代码块/插图，**`archive_path`** 解析相对图片）；可选 **`engine=pandoc`**（需本机 **pandoc**，适合 LaTeX/复杂模板）。**`pdf_compose`** — **ReportLab** 块式排版（**`pip install aicd[pdf]`**）：标题/段落/图片/表格/分页，**`cjk_font_path`** 传入 TTF 以正确排中文。**Word 章节转 PDF**：**`docx_compose`** → **`docx_export_pdf`**（LibreOffice 或 Word+docx2pdf）。
- **样式与 Office**：**`style_reference_scan`**；**`docx_compose`**（可选 **`style_profile_path`**）；**Excel（`.xlsx`）**：**`xlsx_read_workbook`**（多表，**`value_mode`**：`cached` / `raw` / **both**）、**`xlsx_patch_workbook`**（按行列补丁）、**`xlsx_write_workbook`**（整表写入；**openpyxl** 不在 Python 中验算公式）；**`doc_extract`** 可将 xlsx 转为 Markdown 表。**`pptx_inspect_template`** + **`pptx_compose`**。示例配置：**`examples/style_ref/docx_style.example.yaml`**。

## HTTP API（`aicd serve`）

需安装 **`aicd[api]`**。默认监听 **`127.0.0.1:8765`**（可用 `--host` / `--port` 修改）。

**只读（默认开启）**

- **`GET /health`** → `{"ok": true}`；若启用 runtime，另有 **`runtime_api`**、**`connections`**。
- **`GET /v1/sessions/{session_id}/messages?limit=&offset=`** — 分页消息（`limit` 1–2000；此处的 **`session_id`** 为 SQLite 主会话 id）
- **`GET /v1/sessions/{session_id}/summaries?limit=`** — 会话摘要列表

**全功能 Runtime（`--runtime-api`）**

- **`POST /v1/connections`** — 可选 body：`chat_session_id`（延续某条 SQLite 会话）、`no_plugins`、`plugin_policy`；返回 **`connection_id`** 与 **`chat_session_id`**。并行会话请建立多个 connection。
- **`DELETE /v1/connections/{connection_id}`** — 关闭该 Runtime。
- **`POST /v1/connections/{connection_id}/invoke`** — 请求体与 **`aicd host`** **一行 JSON** 相同：`method`、`params`、可选 `id`、**`auth.nonce`**（若使用 **`--require-invoke-nonce`** 或环境变量 **`AICD_HTTP_REQUIRE_INVOKE_NONCE=1`**；stdio **`aicd host`** 侧对应 **`--require-nonce`** 或 **`AICD_HOST_REQUIRE_NONCE=1`**）。常用 method：`ping`、`capabilities`、`main_chat`、**`main_inbox_continue`**、`main_chat_session_attach`、`workspace_set`、`plugin_load`、`task_ai` 等，详见 **`aicd dump-capabilities`** 中的 **`host_ipc`** / **`http_serve`**。

其它 CLI：**`--max-connections`**、**`--require-invoke-nonce`**、**`--skip-setup`**、**`--no-plugins`**、**`--plugin-policy`**（新建连接的默认策略）。

若传入 **`--api-key`** 或环境变量 **`AICD_API_KEY`**，则上述路由须带 **`X-API-Key`** 或 **`Authorization: Bearer <token>`**。

## 离线可视化（导出 HTML）

包内自带 `src/aicd/res/`：**Chart.js**、**Mermaid**、**vis-network**（含 CSS）。升级或重装依赖可执行：

```powershell
python scripts/download_viz_res.py
```

Agent 工具：`viz_export_html`、`viz_data_chart`、`viz_copy_resources`、`viz_list_bundled_assets`；导出前可用 **`viz_spec_validate`**。

## 分析函数库（kit）

`src/aicd/kit/` 提供 JSON 友好的纯函数，并由聚合工具暴露：`data_stats`、`data_text`、`data_time`、`script_template`（骨架 + `script_run`）。实现与路由见 `src/aicd/agent/handlers/`。

## Cursor 技能（`.cursor/skills/`）

仓库内包含若干 **SKILL.md**（工作区、输出目录、聊天历史、大仓库索引 **aicd-code-index**、子进程/`run_command` 交互策略 **aicd-shell-execution**、Draw.io、Visio `.vsdx`（见 **`aicd-ai-output`** 与 **`prompts.py`**）、可视化校验、Analytics、DB 等），便于在 Cursor 中改代码时对齐行为。

## 版本号

- 当前版本见 `src/aicd/version.py` 中的 **`VERSION`**（`pyproject.toml` 动态读取）。**变更摘要**：根目录 **`CHANGELOG.md`**。
- **每次合入/发布前**在仓库根目录执行：`python scripts/bump_version.py`。
- **上传 PyPI 前**先构建再自检：`python scripts/package.py --clean`，然后 `python scripts/release_precheck.py`（可加 `--strict` 做更严的 apiKey 字面量检查）；通过后再上传（需配置 PyPI **API token** 或 `~/.pypirc`，勿将 token 写入仓库）。**Windows** 若 `twine upload` 因控制台编码报错，可：`$env:PYTHONUTF8=1; python -m twine upload dist\aicd-* --non-interactive --disable-progress-bar`。安装校验工具：`pip install twine`。

## 代码结构（速查）

| 路径 | 作用 |
|------|------|
| `src/aicd/app.py` | Typer 入口：`tui` / `init` / `serve` / `version` |
| `src/aicd/runtime.py` | `build_runtime`、工作区/输出目录、`set_vision_llm` / `attach_session_log` |
| `src/aicd/agent/loop.py` | 主对话与子 Agent 工具循环 |
| `src/aicd/agent/llm.py` | OpenAI 兼容客户端、**重试**、**vision 图片编码** |
| `src/aicd/agent/prompts.py` | 系统提示（含 **LARGE_CONTEXT**） |
| `src/aicd/api_serve.py`、`api_runtime.py` | FastAPI：只读历史 + 可选多连接 Runtime |
| `src/aicd/host_dispatch.py` | Host / HTTP 共用的 `dispatch_host_request` |
| `src/aicd/tools/document_outline.py` | 文档标题索引 |
| `src/aicd/tools/visio_flowchart.py` | Visio **`.vsdx`** 写入与摘要（可选依赖 **`vsdx`**） |
| `src/aicd/tools/markdown_to_pdf.py` | Markdown → PDF（PyMuPDF Story / 可选 pandoc） |
| `src/aicd/tools/pdf_compose_rl.py` | 块式 PDF（**ReportLab**，**`aicd[pdf]`**） |
| `src/aicd/config.py` | **`MAX_AGENT_TOOL_ROUNDS`**、**`LLMConfig`**、**`AgentConfig.block_external_network`** |
| `src/aicd/network_policy.py` | 工具出站 URL 策略、**`AICD_BLOCK_EXTERNAL_NETWORK`**、**`runtime_env`** 的 **`aicd_runtime`** 标记 |
