Spaces:
Sleeping
Sleeping
| # 🔥 HANDOFF: Claw Web — Полная документация для следующего агента | |
| ## Что это за проект | |
| **Claw Web** — это веб-версия Claude Code (claw-code), AI coding agent с полным набором инструментов, работающий в браузере. Оригинальный проект написан на Rust + TypeScript (CLI/TUI), мы портировали его в веб-приложение на React + Express + tRPC. | |
| **Оригинальный репо**: `/home/ubuntu/claw-code-original/` (14MB, полный клон с GitHub) | |
| **Наш проект**: `/home/ubuntu/claw-web/` (webdev проект на Manus) | |
| **Деплой**: https://clawweb-sfvpumtx.manus.space | |
| --- | |
| ## Архитектура проекта | |
| ``` | |
| claw-web/ | |
| ├── client/ # React 19 + Tailwind 4 фронтенд | |
| │ ├── src/ | |
| │ │ ├── pages/ | |
| │ │ │ ├── Home.tsx # Главная страница — чат интерфейс (973 строк) | |
| │ │ │ ├── ComponentShowcase.tsx # Демо компонентов (1437 строк) | |
| │ │ │ └── NotFound.tsx # 404 страница | |
| │ │ ├── components/ | |
| │ │ │ ├── Sidebar.tsx # Боковая панель с сессиями (303 строк) | |
| │ │ │ ├── ChatInput.tsx # Поле ввода с / командами (191 строк) | |
| │ │ │ ├── MessageBubble.tsx # Рендер сообщений (219 строк) | |
| │ │ │ ├── ToolCallCard.tsx # Карточки tool calls (470 строк) | |
| │ │ │ ├── ThinkingBlock.tsx # Блок "думает..." (65 строк) | |
| │ │ │ ├── SettingsPanel.tsx # Панель настроек (615 строк) | |
| │ │ │ ├── TerminalPanel.tsx # Встроенный терминал (269 строк) | |
| │ │ │ ├── FileManagerPanel.tsx # Файловый менеджер (604 строк) | |
| │ │ │ ├── PluginMarketplace.tsx# Маркетплейс плагинов (190 строк) | |
| │ │ │ ├── TaskManagerPanel.tsx # Менеджер задач (119 строк) | |
| │ │ │ ├── CronManagerPanel.tsx # Менеджер cron задач (121 строк) | |
| │ │ │ ├── BuddySprite.tsx # Анимированный маскот (119 строк) | |
| │ │ │ ├── ErrorBoundary.tsx # Error boundary (62 строк) | |
| │ │ │ └── ManusDialog.tsx # Диалоговое окно (89 строк) | |
| │ │ ├── hooks/ | |
| │ │ │ ├── useChat.ts # SSE чат хук (531 строк) — КЛЮЧЕВОЙ | |
| │ │ │ ├── useComposition.ts # IME composition (81 строк) | |
| │ │ │ └── usePersistFn.ts # Persistent callback (20 строк) | |
| │ │ ├── contexts/ | |
| │ │ │ └── ThemeContext.tsx # Тема (dark/light) | |
| │ │ ├── lib/ | |
| │ │ │ ├── trpc.ts # tRPC клиент | |
| │ │ │ └── utils.ts # Утилиты | |
| │ │ ├── App.tsx # Роутинг | |
| │ │ ├── main.tsx # Entry point | |
| │ │ └── index.css # Глобальные стили (тёмная тема) | |
| │ └── index.html | |
| │ | |
| ├── server/ # Express + tRPC бэкенд | |
| │ ├── runtime/ # ← ЯДРО АГЕНТА | |
| │ │ ├── agent.ts # Agentic loop — run_turn (658 строк) | |
| │ │ ├── system-prompt.ts # System prompt builder (1038 строк) | |
| │ │ ├── chat-endpoint.ts # SSE endpoint + 114 slash commands (2269 строк) | |
| │ │ ├── compact.ts # Context compaction (527 строк) | |
| │ │ ├── config.ts # RuntimeConfig + ConfigLoader (599 строк) | |
| │ │ ├── mcp-client.ts # MCP клиент + 6 транспортов (686 строк) | |
| │ │ ├── plugins.ts # PluginManager (932 строк) | |
| │ │ ├── lsp-client.ts # LSP клиент (616 строк) | |
| │ │ ├── usage.ts # UsageTracker + pricing (225 строк) | |
| │ │ ├── session.ts # Session serialization (191 строк) | |
| │ │ └── bootstrap.ts # Bootstrap phases (71 строк) | |
| │ ├── tools/ | |
| │ │ └── executor.ts # 41 tool handlers (1875 строк) | |
| │ ├── db.ts # Database queries (242 строк) | |
| │ ├── routers.ts # tRPC routers (262 строк) | |
| │ ├── storage.ts # S3 storage (102 строк) | |
| │ ├── agent-runtime.test.ts # Agent tests (828 строк) | |
| │ ├── compact-config.test.ts # Compact/config tests (777 строк) | |
| │ ├── routers.test.ts # Router tests (258 строк) | |
| │ ├── slash-commands.test.ts # Command tests (155 строк) | |
| │ └── auth.logout.test.ts # Auth tests (62 строк) | |
| │ | |
| ├── shared/ | |
| │ ├── claw-types.ts # Все типы + модели + команды (281 строк) | |
| │ ├── const.ts # Константы | |
| │ └── types.ts # Общие типы | |
| │ | |
| ├── drizzle/ # Database schema + migrations | |
| │ ├── schema.ts # Таблицы: users, sessions, messages, tasks, cron_jobs | |
| │ └── *.sql # Миграции | |
| │ | |
| ├── todo.md # Полный трекер всех фич (596 строк) | |
| ├── PARITY_REPORT.md # Отчёт о паритете с оригиналом | |
| └── critical-understanding.txt # Заметки по архитектуре | |
| ``` | |
| --- | |
| ## Как работает агентский цикл | |
| ``` | |
| Пользователь → ChatInput → POST /api/chat (SSE) → chat-endpoint.ts | |
| ↓ | |
| runAgentLoop() в agent.ts | |
| ↓ | |
| ┌─── buildSystemPrompt() | |
| ├─── LLM API call (streaming) | |
| ├─── Parse tool_use blocks | |
| ├─── runPreToolHooks() | |
| ├─── executeTool() в executor.ts | |
| ├─── runPostToolHooks() | |
| ├─── compactMessagesIfNeeded() | |
| └─── Loop until done or max_iterations | |
| ↓ | |
| SSE events → useChat.ts → UI | |
| ``` | |
| --- | |
| ## Текущее состояние (на 2 апреля 2026) | |
| ### Что работает на 85-100%: | |
| - **41 инструмент** (Bash, FileRead, FileWrite, FileEdit, Grep, Glob, WebSearch, WebFetch, Agent sub-agent, TaskCreate, CronCreate, и т.д.) | |
| - **114 slash commands** (/help, /model, /cost, /compact, /export, /resume, /config, /plugins, /mcp, /doctor, и т.д.) | |
| - **System prompt** — все секции из оригинала | |
| - **Auto-compaction** — compact_after_turns=12 | |
| - **Usage tracking** — cost per model, format_usd | |
| - **Session management** — create/switch/delete/export/resume | |
| - **Hooks** — pre/post tool hooks с exit code 2=deny | |
| - **Streaming SSE** — real-time tool execution | |
| - **Dark theme UI** — sidebar, chat, terminal, file manager, settings | |
| ### Что работает на 35-65% (НУЖНО ДОДЕЛАТЬ): | |
| - **Plugins** (35%) — класс есть, нет persistence и sandbox | |
| - **MCP** (40%) — типы есть, нет реального stdio spawn | |
| - **Permissions** (50%) — базовый, нет glob matching | |
| - **Config** (55%) — нет schema validation, file watcher | |
| - **LSP** (55%) — grep-fallback, нет реального LSP | |
| - **Tools depth** (55%) — happy path, нет edge cases | |
| - **Session** (60%) — нет file-based storage | |
| - **File ops** (65%) — нет apply_diff, detect_binary | |
| ### Что полностью отсутствует: | |
| - **sandbox.rs** (364 строк) — container detection, Linux namespaces | |
| - **remote.rs** (401 строк) — upstream proxy, WebSocket bridge | |
| - **oauth.rs** (589 строк) — PKCE flow | |
| --- | |
| ## ПЛАН ДЕЙСТВИЙ ДЛЯ СЛЕДУЮЩЕГО АГЕНТА | |
| ### Приоритет 1: Plugins (35% → 95%) — ~2000 строк | |
| **Файл**: `server/runtime/plugins.ts` (932 строк → ~2500 строк) | |
| **Оригинал**: `rust/crates/plugins/src/lib.rs` (2943 строк) + `hooks.rs` (395 строк) | |
| Что нужно добавить: | |
| 1. **PluginRegistry persistence** — сохранение/загрузка registry.json на диск (или в DB) | |
| 2. **PluginTool.execute()** — реальное выполнение plugin tools с sandbox isolation | |
| 3. **validate_plugin_source()** — валидация git URL, загрузка manifest | |
| 4. **builtin_plugins()** — реальная загрузка 8 bundled плагинов из директории | |
| 5. **PluginSummary** — полное форматирование с version, author, enabled status | |
| 6. **Plugin settings** — per-plugin configuration persistence | |
| 7. **Plugin trust verification** — проверка подписей и trusted sources | |
| 8. **aggregated_hooks()** — реальная агрегация хуков из всех плагинов | |
| 9. **aggregated_tools()** — реальная агрегация tools из всех плагинов | |
| Как делать: | |
| - Читай `rust/crates/plugins/src/lib.rs` строка за строкой | |
| - Каждый `pub fn` → TypeScript метод | |
| - Каждый `struct` → TypeScript interface | |
| - Каждый `enum` → TypeScript enum | |
| ### Приоритет 2: MCP Client (40% → 95%) — ~1500 строк | |
| **Файл**: `server/runtime/mcp-client.ts` (686 строк → ~2000 строк) | |
| **Оригинал**: `rust/crates/runtime/src/mcp_stdio.rs` (1720 строк) + `mcp.rs` (300) + `mcp_client.rs` (234) | |
| Что нужно добавить: | |
| 1. **Реальный stdio spawn** — `child_process.spawn()` с pipe для stdin/stdout | |
| 2. **Frame-based protocol** — `encode_frame()` / `read_frame()` для JSON-RPC over stdio | |
| 3. **Reconnection с backoff** — exponential backoff при disconnect | |
| 4. **McpServerHealth** — мониторинг здоровья каждого сервера | |
| 5. **discover_tools с кешированием** — кеш tool definitions per server | |
| 6. **SSE transport** — реальный EventSource клиент | |
| 7. **HTTP transport** — реальный fetch-based JSON-RPC | |
| 8. **Resource templates** — `resources/templates/list` MCP метод | |
| 9. **Prompts** — `prompts/list` и `prompts/get` MCP методы | |
| 10. **Sampling** — `sampling/createMessage` MCP метод | |
| Как делать: | |
| - Используй `@modelcontextprotocol/sdk` npm пакет для MCP клиента | |
| - Или реализуй вручную JSON-RPC over stdio как в оригинале | |
| - Читай `mcp_stdio.rs` для frame protocol | |
| ### Приоритет 3: Config System (55% → 95%) — ~700 строк | |
| **Файл**: `server/runtime/config.ts` (599 строк → ~1200 строк) | |
| **Оригинал**: `rust/crates/runtime/src/config.rs` (1294 строк) | |
| Что нужно добавить: | |
| 1. **JSON Schema validation** — validate config against schema | |
| 2. **config_watch()** — chokidar file watcher для auto-reload | |
| 3. **config_diff()** — diff между двумя конфигами | |
| 4. **resolve_config_path()** — XDG-compatible path resolution | |
| 5. **~40 accessor методов** — каждое поле конфига через getter | |
| 6. **Config migration** — upgrade old config format to new | |
| 7. **Config templates** — preset configurations | |
| ### Приоритет 4: LSP Client (55% → 90%) — ~600 строк | |
| **Файл**: `server/runtime/lsp-client.ts` (616 строк → ~1100 строк) | |
| **Оригинал**: `rust/crates/lsp/src/` (1185 строк) | |
| Что нужно добавить: | |
| 1. **Реальный LSP stdio клиент** — spawn language server, JSON-RPC | |
| 2. **LspManager** — multi-server management (TypeScript, Python, Go, etc.) | |
| 3. **initialize handshake** — LSP protocol initialization | |
| 4. **textDocument/didOpen** — file open notifications | |
| 5. **workspace/symbol** — workspace-wide symbol search | |
| 6. **Fallback to grep** — когда LSP недоступен (уже есть) | |
| ### Приоритет 5: Tools Depth (55% → 85%) — ~1500 строк | |
| **Файл**: `server/tools/executor.ts` (1875 строк → ~3500 строк) | |
| **Оригинал**: `rust/crates/tools/src/lib.rs` (4469 строк) | |
| Что нужно добавить для каждого tool: | |
| 1. **Полная валидация входных параметров** — type checking, bounds checking | |
| 2. **Structured error types** — FileOperationError, BashError, etc. | |
| 3. **Edge case handling** — binary files, symlinks, large files, encoding issues | |
| 4. **apply_diff()** — для FileEdit tool | |
| 5. **detect_binary()** — для FileRead tool | |
| 6. **resolve_symlinks()** — для file operations | |
| 7. **validate_utf8()** — для text operations | |
| 8. **Output truncation** — consistent 30000 char limit with smart truncation | |
| ### Приоритет 6: Permissions (50% → 90%) — ~200 строк | |
| **Файл**: `server/tools/executor.ts` (permissions section) | |
| **Оригинал**: `rust/crates/runtime/src/permissions.rs` (232 строк) | |
| Что нужно добавить: | |
| 1. **PermissionRule struct** — glob patterns for tool matching | |
| 2. **PermissionEvaluator** — evaluate rules against tool calls | |
| 3. **glob_match_tool_name()** — wildcard matching | |
| 4. **permission_prompt_text()** — human-readable permission descriptions | |
| 5. **Permission persistence** — save/load permission decisions | |
| ### Приоритет 7: Session (60% → 90%) — ~250 строк | |
| **Файл**: `server/runtime/session.ts` (191 строк → ~400 строк) | |
| **Оригинал**: `rust/crates/runtime/src/session.rs` (436 строк) | |
| Что нужно добавить: | |
| 1. **load_from_path()** — загрузка сессии из файла | |
| 2. **save_to_path()** — сохранение сессии в файл | |
| 3. **session_storage_dir()** — директория для хранения сессий | |
| 4. **list_sessions()** — список всех сохранённых сессий | |
| 5. **SessionMetadata** — метаданные сессии (created_at, model, message_count) | |
| ### Приоритет 8: Отсутствующие модули | |
| #### sandbox.ts (~300 строк) — НИЗКИЙ ПРИОРИТЕТ | |
| - detect_container_environment() | |
| - resolve_sandbox_status() | |
| - build_linux_sandbox_command() | |
| - В веб-версии sandbox — это сам сервер, поэтому большая часть не нужна | |
| #### remote.ts (~300 строк) — НИЗКИЙ ПРИОРИТЕТ | |
| - UpstreamProxyConfig | |
| - WebSocket bridge | |
| - subprocess_env | |
| - Специфично для CLI, в веб-версии не критично | |
| --- | |
| ## Как запустить проект | |
| ```bash | |
| cd /home/ubuntu/claw-web | |
| pnpm install | |
| pnpm dev # Dev server на порту 3000 | |
| pnpm test # 173 теста | |
| npx tsc --noEmit # Type checking (0 ошибок) | |
| ``` | |
| ## Как запустить тесты | |
| ```bash | |
| cd /home/ubuntu/claw-web | |
| pnpm test # Все 173 теста | |
| pnpm test -- --grep "agent" # Только agent тесты | |
| pnpm test -- --grep "compact" # Только compact тесты | |
| ``` | |
| ## Как сравнивать с оригиналом | |
| ```bash | |
| # Оригинальный репо | |
| ls /home/ubuntu/claw-code-original/rust/crates/ | |
| # Ключевые файлы оригинала: | |
| cat /home/ubuntu/claw-code-original/rust/crates/runtime/src/conversation.rs # → agent.ts | |
| cat /home/ubuntu/claw-code-original/rust/crates/tools/src/lib.rs # → executor.ts | |
| cat /home/ubuntu/claw-code-original/rust/crates/commands/src/lib.rs # → chat-endpoint.ts | |
| cat /home/ubuntu/claw-code-original/rust/crates/plugins/src/lib.rs # → plugins.ts | |
| cat /home/ubuntu/claw-code-original/rust/crates/runtime/src/mcp_stdio.rs # → mcp-client.ts | |
| cat /home/ubuntu/claw-code-original/rust/crates/runtime/src/config.rs # → config.ts | |
| cat /home/ubuntu/claw-code-original/rust/crates/lsp/src/ # → lsp-client.ts | |
| ``` | |
| ## Ключевые зависимости | |
| - **LLM API**: через `server/_core/llm.ts` (invokeLLM) — Manus built-in | |
| - **Database**: MySQL/TiDB через Drizzle ORM | |
| - **Auth**: Manus OAuth через `server/_core/oauth.ts` | |
| - **Storage**: S3 через `server/storage.ts` | |
| - **Frontend**: React 19 + Tailwind 4 + shadcn/ui + wouter (routing) | |
| ## Важные замечания | |
| 1. **НЕ трогай файлы в `server/_core/`** — это фреймворк Manus | |
| 2. **Все статические файлы** загружай через `manus-upload-file --webdev` | |
| 3. **Database миграции** через `pnpm drizzle-kit generate` + `webdev_execute_sql` | |
| 4. **Тесты обязательны** перед каждым checkpoint | |
| 5. **Оригинальный репо** в `/home/ubuntu/claw-code-original/` — используй для справки | |
| --- | |
| ## Общая оценка паритета | |
| | Метрика | Значение | | |
| |---------|----------| | |
| | Фичи (количество) | **~88%** | | |
| | Глубина реализации | **~62%** | | |
| | Строк кода (сервер) | 10,191 vs 34,065 оригинал | | |
| | Инструменты | 41/41 (100%) | | |
| | Команды | 114/~101 (113%) | | |
| | Тесты | 173 | | |
| | TS ошибки | 0 | | |
| **Цель: довести глубину реализации до 90%+** | |