Metadata-Version: 2.4
Name: memocode
Version: 0.6.1
Summary: Personal AI coding agent with memory, tool execution, and safety controls
Author: AssassinCHN
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: openai>=1.0
Requires-Dist: rich>=13.0
Requires-Dist: prompt_toolkit>=3.0
Requires-Dist: certifi>=2024.0
Requires-Dist: httpx>=0.24
Requires-Dist: pdfplumber>=0.10
Requires-Dist: pdfminer.six>=20221105
Dynamic: license-file

```
  __  __               _
 |  \/  | ___ ___   __| | ___
 | |\/| |/ __/ _ \ / _` |/ _ \
 | |  | | (_| (_) | (_| |  __/
 |_|  |_|\___\___/ \__,_|\___|
 ──────────────────────────────────────────────────────────────────────
  Mcode  —  Your local AI coding agent
  › /help for commands
  › Project: default  —  /project rename <name> to name this session
  › Model:   minimax  (MiniMax-M2.7)  —  /model to switch
 ──────────────────────────────────────────────────────────────────────
```

<div align="center">

[![PyPI](https://img.shields.io/pypi/v/memocode?color=blue&label=PyPI)](https://pypi.org/project/memocode/)
[![Python](https://img.shields.io/pypi/pyversions/memocode)](https://pypi.org/project/memocode/)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)
[![Language](https://img.shields.io/github/languages/top/hankwangcn/mcode?color=3572A5)](https://github.com/hankwangcn/mcode)

**Personal AI coding agent CLI — persistent memory, tool execution, and safety controls.**

</div>

---

## Features

| | |
|---|---|
| **Agentic loop** | Native function calling, stuck detection, fully autonomous auto mode |
| **Memory** | 4-layer cross-session memory with compression, recall, and Ebbinghaus forgetting |
| **Projects** | Multiple projects, each with isolated memory DB and working directory |
| **Resource registry** | Index local files by topic; reference them with `@name` in any message |
| **Image support** | Attach images via `@path` for multimodal turns with vision-capable models |
| **Safety** | Human / Auto / Bypass modes with zone checks, whitelists, and file backups |
| **Extensible** | Drop `.py` files into `~/.mcode/tools/` to add custom tools |

---

## Installation

```bash
pip install memocode
```

On first run, `~/.mcode/agent.json` is created. Add your model:

```json
{
  "active_model": "gpt4o",
  "models": {
    "gpt4o": {
      "provider": "openai",
      "model": "gpt-4o",
      "api_key_env": "OPENAI_API_KEY",
      "context_window": 128000
    }
  }
}
```

```bash
export OPENAI_API_KEY=your_key_here
mcode
```

Any OpenAI-compatible endpoint works — OpenAI, Anthropic, DeepSeek, local models via vLLM/Ollama, etc. Multiple models can be defined and switched with `/model`.

---

## Quick Start

```bash
mcode                      # Start (auto-resumes last project)
mcode --project myapp      # Start with a specific project
mcode --verbose            # Show full tracebacks on errors
```

Type naturally. Use `/help` to see all commands.

---

## Slash Commands

**Session**

| Command | Description |
|---------|-------------|
| `/help` | Show all commands |
| `/status` | Show current settings |
| `/end` | End session and save to memory |
| `/quit` / `/exit` | Exit |

**Conversation**

| Command | Description |
|---------|-------------|
| `/btw <question>` | Quick one-shot question — no memory, no tools |
| `/undo` | Undo last turn — restore files and/or rewind conversation |
| `/rewind [N]` | Rewind to turn N; `/rewind 0` clears conversation |
| `/rollback` | Restore a specific backed-up file version |
| `/history [N]` | Show audit log |

**Auto mode**

| Command | Description |
|---------|-------------|
| `/auto [on\|off]` | Toggle autonomous mode |
| `/auto whitelist [list\|add\|remove\|reset]` | Manage whitelisted shell commands |
| `/template [example]` | Show recommended task prompt template |

**Projects**

| Command | Description |
|---------|-------------|
| `/project new [name]` | Create a new project |
| `/project switch <name>` | Switch to another project |
| `/project list` | List all projects |
| `/project workdir [path]` | Set working directory |
| `/project rename [<old>] <new>` | Rename a project |
| `/project delete <name>` | Delete a project |

**Memory**

| Command | Description |
|---------|-------------|
| `/memory` | Show core memory (user profile) |
| `/memory set <key> <value>` | Write an entry |
| `/memory del <key>` | Delete an entry |
| `/memory pin <key>` | Pin an entry (never forgets) |

**Resources**

| Command | Description |
|---------|-------------|
| `/resource add [-r] <path\|dir>` | Register a file or directory (recursive with `-r`) |
| `/resource search <query>` | Search registered resources |
| `/resource list` | List all resources |
| `/resource tree [path]` | Directory tree view of all resources |
| `/resource sync [name]` | Re-classify changed files |
| `/resource del <index\|name>` | Delete a resource |
| `/resource watch` | List watched directories |
| `/resource unwatch <dir>` | Stop watching a directory |

**Other**

| Command | Description |
|---------|-------------|
| `/model [name]` | Show or switch LLM model |
| `/tools` | List all loaded tools |
| `/safety [on\|off]` | Toggle safety bypass (DANGEROUS, session-only) |
| `!<command>` | Run a shell command directly (safety-checked) |
| `@<path or name>` | Attach a file or registered resource inline |
| `@*<query>` | Inject all resources matching a search query |
| `@<dir>/` | Inject a directory file listing |
| `@<N>` | Reference resource by global index number |

---

## Memory System

mcode maintains four memory layers across sessions:

| Layer | Scope | Contents |
|-------|-------|----------|
| **Core memory** | Global | User traits: interaction style, delegation preference |
| **Project memory** | Per-project | Decisions, architecture, conventions, progress |
| **Recent memory** | Per-project | Compressed summaries of past sessions |
| **Session history** | Per-project | Current session verbatim; older turns compressed in-place |

**Recall** — Recent summaries are injected every turn (newest-first, 4k token cap) with timestamps. `memory_search` is called automatically when context is missing. Core and project memory are always in the system prefix (prompt-cache eligible).

**Compression** — When context reaches 50% of `context_window`, old turns are summarised with explicit markers (`Rejected X — reason`, `Changed from X to Y — reason`) so negations and reversals remain retrievable. Mode is auto-detected: **plan mode** for conversations without code (preserves dates, values, identifiers), **code mode** for code-heavy sessions (focuses on decisions and rationale).

**Forgetting** — Core memory decays via the Ebbinghaus curve. Frequently confirmed traits resist forgetting; entries never reinforced eventually fade below threshold and are dropped. Project memory does not decay.

---

## Resource Registry

Register local files once; reference them by name from any message.

```
/resource add ~/Documents/specs      # register a directory (also auto-watches for new files)
/resource add -r ~/Documents         # recursive
/resource search kubernetes          # find by keyword
```

After searching, reference a result directly in your message:

```
@API设计规范 根据规范帮我 review 这段代码
```

The file content is injected automatically — no copy-paste needed. New files added to a watched directory are auto-registered on the next startup.

---

## Auto Mode

Auto mode runs the agent fully autonomously — no confirmation prompts, hard sandbox boundaries (whitelist-only shell commands, writes restricted to `work_dir`).

Enable with `/auto on`, then use `/template` for the recommended task structure:

```
Task: <one-line goal>
Context: work_dir, language/framework, entry point
Acceptance criteria: 1) ... 2) ... 3) ...
Constraints: do NOT modify <files>
Verify by running: <test command>
```

---

## Safety Modes

| Mode | Behavior |
|------|----------|
| **Human** (default) | Prompts before risky ops; backs up files before destructive edits |
| **Auto** (`/auto on`) | No prompts; blocks non-whitelisted commands and out-of-`work_dir` writes |
| **Bypass** (`/safety off`) | Skips all checks; session-only; requires typing `yes` to confirm |

---

## Built-in Tools

| Tool | Description |
|------|-------------|
| `shell_exec` | Run shell commands with streaming output |
| `file_read` | Read file with optional pagination |
| `file_write` | Write or append to a file |
| `file_edit` | Targeted string replacement |
| `glob` | Find files by pattern (`**/*.py`) |
| `grep` | Search file content by regex |
| `web_fetch` | Fetch a URL — GET/POST/PUT/PATCH/DELETE, custom headers, JSON body |
| `web_search` | Search the web via DuckDuckGo — no API key required |
| `pdf_read` | Extract text from PDF files |
| `excel_read` | Read Excel / CSV files as formatted table |
| `excel_write` | Write data to Excel / CSV files |
| `calc` | Safe arithmetic evaluator |
| `memory_search` | Search past session summaries |
| `activity_log_query` | Query recent activity log |
| `project_query` | Read structured project memory |

---

## Custom Tools

Drop a `.py` file in `~/.mcode/tools/`:

```python
from tools.registry import Tool, ToolSchema

def _my_tool(param: str) -> str:
    return f"result: {param}"

MY_TOOL = Tool(
    schema=ToolSchema(
        name="my_tool",
        description="Description shown to the model",
        parameters={
            "type": "object",
            "properties": {"param": {"type": "string"}},
            "required": ["param"],
        },
    ),
    fn=_my_tool,
)
```

---

## Project Structure

```
mcode/
├── run.py                       # CLI entry point (~1035 lines)
├── cmds/                        # Slash command handlers
│   ├── memory.py                # /memory
│   ├── tasks.py                 # /tasks
│   ├── rewind.py                # /rewind, /context
│   ├── email.py                 # /email
│   ├── project.py               # /project
│   ├── resource.py              # /resource
│   ├── at_expand.py             # @mention expansion
│   └── _utils.py                # shared utilities
├── control/
│   ├── brain.py                 # Agent loop, tool dispatch, safety
│   ├── llm.py                   # LLM adapter (OpenAI-compatible + Anthropic)
│   ├── project_manager.py       # Project registry
│   ├── audit.py                 # Audit log
│   ├── resources/               # Local resource registry
│   │   ├── manager.py           # ResourceManager
│   │   ├── db.py                # SQLite storage + BM25 search
│   │   └── scanner.py           # File content extraction
│   └── chatmem/                 # Memory system
│       ├── context_manager.py   # History, compression, injection
│       ├── compressor.py        # LLM-based summarization
│       └── memory/
│           ├── core_memory.py   # User traits (global, Ebbinghaus forgetting)
│           ├── recent_memory.py # Cross-session summaries (per-project)
│           ├── consolidation.py # Pattern extraction → core memory
│           └── forgetting.py    # Decay engine
├── tools/
│   ├── file.py                  # file_read/write/edit, glob, grep
│   ├── shell.py                 # shell_exec
│   ├── web.py                   # web_fetch, web_search
│   ├── calc.py                  # safe arithmetic evaluator
│   └── registry.py              # Tool registry + loader
└── safety/
    ├── safety.py                # Zone checks, auto mode rules
    ├── backup.py                # File backup
    └── policy.py                # Persistent always-allow policies
```

---

## License

Apache License 2.0 — see [LICENSE](LICENSE).
