Metadata-Version: 2.4
Name: kimix
Version: 0.1.21
Summary: Kimi Agent Tools - Custom tool collection for Kimi Agent SDK
License: MIT
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.14
Requires-Dist: fastapi>=0.115.0
Requires-Dist: httpx>=0.28.0
Requires-Dist: kimi-cli-x>=1.44.7
Requires-Dist: markdownify
Requires-Dist: numpy
Requires-Dist: opencc-python-reimplemented>=0.1.7
Requires-Dist: orjson>=3.10.0
Requires-Dist: playwright
Requires-Dist: pydantic>=2.0.0
Requires-Dist: sse-starlette>=2.0.0
Requires-Dist: uvicorn>=0.34.0
Provides-Extra: all
Requires-Dist: inline-snapshot>=0.33.0; extra == 'all'
Requires-Dist: mypy>=1.5.0; extra == 'all'
Requires-Dist: pdfplumber>=0.10.0; extra == 'all'
Requires-Dist: pillow>=10.0.0; extra == 'all'
Requires-Dist: pymupdf>=1.23.0; extra == 'all'
Requires-Dist: pytesseract>=0.3.10; extra == 'all'
Requires-Dist: pytest-asyncio>=1.3.0; extra == 'all'
Requires-Dist: pytest-cov>=7.1.0; extra == 'all'
Requires-Dist: pytest-xdist>=3.0.0; extra == 'all'
Requires-Dist: pytest>=9.0.3; extra == 'all'
Requires-Dist: python-docx>=1.1.0; extra == 'all'
Requires-Dist: ruff>=0.1.0; extra == 'all'
Provides-Extra: image-process
Requires-Dist: pillow>=10.0.0; extra == 'image-process'
Requires-Dist: pytesseract>=0.3.10; extra == 'image-process'
Provides-Extra: office
Requires-Dist: pdfplumber>=0.10.0; extra == 'office'
Requires-Dist: pymupdf>=1.23.0; extra == 'office'
Requires-Dist: python-docx>=1.1.0; extra == 'office'
Description-Content-Type: text/markdown

# Kimi-CLI-X

> [中文文档](README_zh.md)

## Install from Source
```bash
python install.py
```

## pip Install
```bash
pip install kimix
python -m kimix.cli
# or
kimix
python -m kimix
```

> **Note:** This repo supports not only KIMI LLM but also various API keys! Like OpenAI, Anthropic, etc. Default config templates are in `docs/`; use `kimix --config xx.json` after setup.

![teasor](teasor.png)

## Why Kimi-CLI-X?

Kimi-CLI-X is a deep optimization of the original Kimi-CLI, focusing on **prompt efficiency**, **tool reliability**, and **extensibility**, plus new tools for real-world development.

### Optimizations

1. **Lean system prompts** — Compressed initial prompts and tool descriptions down to ~2000 tokens while covering nearly all built-in tools.
2. **Hardened permissions & validation** — Properly handles Shell, Glob, and other tool validations to reduce retry loops from failures.
3. **Better subprocess output** — Redirects large outputs to temp files and filters redundant logs for easier backend retrieval.
4. **Simpler concurrency** — Streamlined design for subprocesses, sub-agents, and background tasks.
5. **Programmable prompts** — Allows custom system prompt injection at the upper layer for flexible scenarios.
6. **Explicit conversation management** — Clearer multi-task orchestration and state tracking.
7. **Write-and-validate** — Auto format checks and warnings on strict config files to prevent model-hallucinated errors.
8. **Multi-API support** — Import custom configs compatible with OpenAI, Anthropic, and more.
9. **Verified backends** — Tested against kimi, anthropic, openai_legacy, openai_responses, google_genai, vertexai, etc. See `kimi-cli/tests/core/test_create_llm.py`.

### New Capabilities

| Capability | Description |
|------------|-------------|
| **Input tool** | TUI interaction with running processes. |
| **Docx / PDF conversion** | Built-in document conversion without external deps. |
| **Python script execution** | Agent can run Python scripts directly. |
| **Error logging** | Records tool-call errors for model backtracking and improvement. |
| **Script system** | Combines prompts with Python logic to orchestrate complex tasks. |
| **Enhanced web fetch (FetchURL)** | Headless-browser-based Markdown output (not plain text), supports `output_path` and auto-truncation for超长 content; zero external service dependency. |

### Scriptable Workflows (Core Advantage)

Unlike traditional CLI interaction where you type commands one by one, **Kimi-CLI-X lets you write Python scripts to orchestrate entire workflows**. You can combine prompts, loops, conditionals, and tool calls into fully automated, reproducible task pipelines:

```python
from kimix import *
from pathlib import Path

clear_default_context()

for i in Path('docs').glob('*.md'):
    prompt(f'''According to the new git commits, update document `{i}`''')
```

Benefits:

- **Batch automation**: Use native Python syntax (`for` loops, file globbing) to fire tasks at multiple files at once.
- **Complex orchestration**: Freely compose mode switches, tool calls, and logic into multi-stage, multi-branch workflows.
- **Reproducible & maintainable**: Workflows live as version-controlled scripts, not ephemeral chat history.

---

### Context Memory Architecture

Kimi-CLI-X embeds an **automatic context memory system** inside the `KimiSoul` core loop, keeping long conversations coherent without manual intervention. Three layers work together:

#### 1. Conversation History Index (HistoryIndex)

Every user/assistant message is automatically indexed by **BM25 inverted index** (N-gram, n=2) on append, persisted to `<session>/history_index/<id>.json`, and survives process restarts. Cap at 500 rounds; oldest evicted automatically.

#### 2. Automatic Context Compaction (SimpleCompaction)

Triggered when context token ratio hits `compaction_trigger_ratio` or free space falls below `reserved_context_size`:

- **Retention policy**: Recent N rounds kept verbatim (depth adapted by `adaptive_preserve_depth` — deepened on errors, thinking, multi-file edits, etc.); first message always kept (primacy effect).
- **LLM summarization**: Old messages compressed into structured summaries via a lightweight LLM call; thinking blocks discarded.
- **Cascade handling**: When already-compacted content is compressed again (depth ≥3), switches to `COMPACT_CASCADE` prompt to prevent information degradation.
- Post-compaction, all rounds marked `is_compacted` in HistoryIndex for future retrieval.

#### 3. Auto History Retrieval + On-Demand Recall

- **Auto retrieval** (`_maybe_auto_retrieve_history`): Each round, if user input ≥10 chars, BM25-searches HistoryIndex for matching compacted rounds; injects matches above `auto_retrieve_history_threshold` as `[Auto-retrieved from past conversation]`.
- **ContextRetrieval tool**: Agent can actively search all archived history (including compacted rounds) by natural-language query, returning verbatim excerpts with relevance scores.

```
┌──────────────┐    append     ┌──────────────┐    overflow    ┌──────────────────┐
│   Context    │ ───────────► │ HistoryIndex │ ────────────► │ SimpleCompaction │
│ (live window)│              │ (BM25 index) │               │ (LLM summary)    │
└──────────────┘              └──────────────┘               └──────────────────┘
       ▲                            │                               │
       │       auto-retrieve        │                               │
       └────────────────────────────┘                               │
       │              ContextRetrieval (agent主动recall)            │
       └────────────────────────────────────────────────────────────┘
```

---

## Documentation Index

### Tutorials

| Document | Description |
|----------|-------------|
| [`docs/tutorials/1_quick_start_en.md`](docs/tutorials/1_quick_start_en.md) | Quick start guide: Git submodules, `uv` env setup, CLI args, and interactive commands. |
| [`docs/tutorials/2_long_task_en.md`](docs/tutorials/2_long_task_en.md) | Long task strategy in KimiX. |
| [`docs/tutorials/3_builtin_tools_en.md`](docs/tutorials/3_builtin_tools_en.md) | Complete built-in tool guide: file I/O, search, code execution, process management, doc conversion, plan mode, sub-agents, plus prompt strategies and best practices. |
| [`docs/tutorials/4_skills_en.md`](docs/tutorials/4_skills_en.md) | Custom skill authoring: design principles, directory structure, `SKILL.md` spec, resource organization, testing, packaging, and installation. |
| [`docs/tutorials/5_server_en.md`](docs/tutorials/5_server_en.md) | HTTP server tutorial: FastAPI + SSE, OpenCode-compatible REST API, session management, event streaming, SSE CLI debugger, dummy mode, and client implementation. |

### Config Reference

| File | Description |
|------|-------------|
| [`docs/config.json`](docs/config.json) | Sample model config with `model`, `url`, `api_key`, `capabilities`, etc. |
| [`.kimix/config.json`](.kimix/config.json) | Workspace behavior config: `protected_write_paths`, `protected_read_paths`, `forbidden_commands`, etc. |
| [`.kimix/skill.json`](.kimix/skill.json) | Workspace skill directory config: `skill_dir` field (string or array) for extra skill directories, resolved relative to workspace. |
