From 7d6cc1c83ec1d5bc5acee848c02a421afa73e588 Mon Sep 17 00:00:00 2001 From: Mikhail Date: Fri, 3 Jul 2026 20:51:36 +0300 Subject: [PATCH] Initial project blueprint --- README.md | 68 +++++ configs/examples/confirm_mode.yaml | 10 + configs/examples/full_auto.yaml | 10 + configs/examples/local_only.yaml | 38 +++ configs/examples/local_plus_external.yaml | 37 +++ docs/ROADMAP.md | 58 ++++ docs/architecture/01_overview.md | 116 ++++++++ docs/architecture/02_components.md | 127 +++++++++ docs/architecture/03_no_hardcoded_bans.md | 99 +++++++ docs/codex/CODEX_TASK.md | 182 ++++++++++++ docs/contracts/API_CONTRACTS.md | 106 +++++++ docs/contracts/LOCAL_WORKER_PROTOCOL.md | 148 ++++++++++ docs/contracts/MCP_CLIENT.md | 60 ++++ docs/contracts/MODEL_ROUTER.md | 78 ++++++ docs/ui/USER_INTERFACE.md | 324 ++++++++++++++++++++++ src/agent_runtime/README.md | 1 + src/api/README.md | 1 + src/local_worker_protocol/README.md | 1 + src/logging/README.md | 1 + src/mcp_client/README.md | 1 + src/model_router/README.md | 1 + src/orchestrator/README.md | 1 + src/policy/README.md | 1 + src/storage/README.md | 1 + tests/smoke/SMOKE_TESTS.md | 16 ++ 25 files changed, 1486 insertions(+) create mode 100644 README.md create mode 100644 configs/examples/confirm_mode.yaml create mode 100644 configs/examples/full_auto.yaml create mode 100644 configs/examples/local_only.yaml create mode 100644 configs/examples/local_plus_external.yaml create mode 100644 docs/ROADMAP.md create mode 100644 docs/architecture/01_overview.md create mode 100644 docs/architecture/02_components.md create mode 100644 docs/architecture/03_no_hardcoded_bans.md create mode 100644 docs/codex/CODEX_TASK.md create mode 100644 docs/contracts/API_CONTRACTS.md create mode 100644 docs/contracts/LOCAL_WORKER_PROTOCOL.md create mode 100644 docs/contracts/MCP_CLIENT.md create mode 100644 docs/contracts/MODEL_ROUTER.md create mode 100644 docs/ui/USER_INTERFACE.md create mode 100644 src/agent_runtime/README.md create mode 100644 src/api/README.md create mode 100644 src/local_worker_protocol/README.md create mode 100644 src/logging/README.md create mode 100644 src/mcp_client/README.md create mode 100644 src/model_router/README.md create mode 100644 src/orchestrator/README.md create mode 100644 src/policy/README.md create mode 100644 src/storage/README.md create mode 100644 tests/smoke/SMOKE_TESTS.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..bc47a15 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +# AI Orchestrator + +Отдельный проект для серверного AI-orchestrator, который управляет задачами, моделями, MCP-tools и local workers. + +## Главная идея + +Этот проект не является частью `Local LLM Platform`. + +`Local LLM Platform` отвечает за: +- локальные модели; +- inference; +- registry; +- GPU profiles; +- model deployment; +- smoke tests моделей. + +`AI Orchestrator` отвечает за: +- общение с пользователем; +- построение плана/графа выполнения; +- вызов моделей; +- вызов MCP-инструментов; +- работу с local worker; +- подтверждения действий; +- логи; +- fallback между weak/strong/vision моделями. + +## Ключевой принцип + +В коде нет жестких запретов на действия. + +Система должна работать через настраиваемую политику проекта: + +- `full_auto` — выполнять без подтверждений; +- `confirm` — спрашивать подтверждение для действий, отмеченных политикой; +- `manual` — всегда показывать план и ждать запуска; +- `disabled` — компонент отключен настройкой. + +Важно: `disabled` — это не hardcoded ban, а выбранная настройка проекта. + +## Базовая схема + +```text +User UI / API + ↓ +Conversation Manager + ↓ +Server Orchestrator + ↓ +Execution Graph + ├─ Planner + ├─ Workers + ├─ Reviewer + └─ Finalizer + ↓ +Model Router + ├─ weak model: local + ├─ strong model: local or external + └─ vision model: local or external + ↓ +Tools + ├─ MCP client + ├─ remote MCP servers + └─ local worker protocol +``` + +## Что должен сделать Codex + +Начать с документа `docs/codex/CODEX_TASK.md`. diff --git a/configs/examples/confirm_mode.yaml b/configs/examples/confirm_mode.yaml new file mode 100644 index 0000000..c51e736 --- /dev/null +++ b/configs/examples/confirm_mode.yaml @@ -0,0 +1,10 @@ +policy: + default_mode: confirm + resources: + filesystem: confirm + shell: confirm + sql: confirm + mcp: confirm + external_models: confirm + desktop: confirm + browser: confirm diff --git a/configs/examples/full_auto.yaml b/configs/examples/full_auto.yaml new file mode 100644 index 0000000..abe421b --- /dev/null +++ b/configs/examples/full_auto.yaml @@ -0,0 +1,10 @@ +policy: + default_mode: full_auto + resources: + filesystem: full_auto + shell: full_auto + sql: full_auto + mcp: full_auto + external_models: full_auto + desktop: full_auto + browser: full_auto diff --git a/configs/examples/local_only.yaml b/configs/examples/local_only.yaml new file mode 100644 index 0000000..144797d --- /dev/null +++ b/configs/examples/local_only.yaml @@ -0,0 +1,38 @@ +project: + id: default + name: Local Only Project + +models: + weak: + provider: local + model: qwen-coder-small + base_url: http://localhost:8001/v1 + strong: + provider: local + model: qwen-coder-large + base_url: http://localhost:8002/v1 + vision: + provider: disabled + model: null + embedding: + provider: local + model: bge-m3 + base_url: http://localhost:8003/v1 + +execution: + max_graph_nodes: 20 + max_agent_steps: 8 + max_local_retries: 2 + allow_external_models: false + allow_paid_fallback: false + +policy: + default_mode: confirm + resources: + filesystem: confirm + shell: confirm + sql: confirm + mcp: confirm + external_models: disabled + desktop: confirm + browser: confirm diff --git a/configs/examples/local_plus_external.yaml b/configs/examples/local_plus_external.yaml new file mode 100644 index 0000000..70a7248 --- /dev/null +++ b/configs/examples/local_plus_external.yaml @@ -0,0 +1,37 @@ +project: + id: hybrid + name: Local Plus External + +models: + weak: + provider: local + model: qwen-coder-small + base_url: http://localhost:8001/v1 + strong: + provider: external + model: gpt-strong + base_url: https://api.example.com/v1 + api_key_env: EXTERNAL_MODEL_API_KEY + vision: + provider: external + model: gpt-vision + base_url: https://api.example.com/v1 + api_key_env: EXTERNAL_MODEL_API_KEY + +execution: + max_graph_nodes: 20 + max_agent_steps: 8 + max_local_retries: 2 + allow_external_models: true + allow_paid_fallback: true + +policy: + default_mode: confirm + resources: + filesystem: confirm + shell: confirm + sql: confirm + mcp: full_auto + external_models: confirm + desktop: confirm + browser: confirm diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..0f03cb1 --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,58 @@ +# Roadmap + +## Phase 1: Skeleton + +- project structure +- config loader +- API skeleton +- task storage in memory +- event log in memory +- model router mock +- policy engine +- execution graph engine + +## Phase 2: Local model + MCP + +- local OpenAI-compatible provider +- MCP client initialize/tools/list/tools/call +- simple agent graph +- confirmation flow + +## Phase 3: Local Worker + +- worker registration +- WebSocket connection +- capabilities +- command dispatch +- command result +- file tools + +## Phase 4: 1C usage + +- connect 1C MCP server +- read schema +- run SQL +- validate queries +- generate query +- apply controlled changes via confirmation + +## Phase 5: UI + +- chat/task console +- plan card +- progress card +- confirmation card +- artifact card +- worker status screen +- model settings +- policy settings + +## Phase 6: Advanced + +- parallel graph nodes +- reviewer +- vision model slot +- cost tracking +- persistent storage +- audit logs +- replay tasks diff --git a/docs/architecture/01_overview.md b/docs/architecture/01_overview.md new file mode 100644 index 0000000..f70df2c --- /dev/null +++ b/docs/architecture/01_overview.md @@ -0,0 +1,116 @@ +# Архитектура AI Orchestrator + +## Почему отдельный проект + +Оркестратор должен быть независимым от текущей Local LLM Platform. + +Он должен уметь работать: +- с локальными моделями из Local LLM Platform; +- с внешними моделями; +- с любыми MCP-серверами; +- с local worker на компьютере пользователя; +- с будущими инструментами: файлы, браузер, 1С, SQL, desktop, image, audio, video. + +## Разделение ответственности + +### Local LLM Platform + +Провайдер моделей: + +```text +GET /models +POST /v1/chat/completions +POST /v1/embeddings +POST /v1/vision/analyze +``` + +### AI Orchestrator + +Runtime управления задачами: + +```text +POST /chat +POST /tasks +POST /confirmations/{id}/approve +POST /confirmations/{id}/reject +GET /tasks/{id} +GET /tasks/{id}/events +``` + +### 1C MCP Server + +Источник инструментов: + +```text +tools/list +tools/call +resources/list +resources/read +prompts/list +prompts/get +``` + +### Local Worker + +Исполнитель на локальном компьютере: + +```text +file.read +file.write +file.search +file.apply_patch +command.run +desktop.screenshot +browser.open +mcp.proxy +``` + +## Оркестратор и агент + +В системе нет отдельной магической сущности “главный агент”. + +Есть: + +```text +Orchestrator = управляет выполнением +Execution Graph = план задачи +Planner = строит граф +Worker = выполняет конкретный узел графа +Reviewer = проверяет результат +Finalizer = формирует итог пользователю +``` + +Agent — это технический профиль выполнения: + +```text +AgentProfile = prompt + model_slot + tools + limits + output_schema +``` + +## Правильная модель + +Не так: + +```text +agent запускает agent + agent запускает agent + agent запускает agent +``` + +А так: + +```text +Orchestrator + ↓ +Planner + ↓ +Execution Graph + ├─ worker: sql + ├─ worker: 1c + ├─ worker: file + ├─ worker: vision + └─ reviewer +``` + +Workers не создают других workers. +Они возвращают предложения или результаты orchestrator. +Только orchestrator запускает следующие узлы. diff --git a/docs/architecture/02_components.md b/docs/architecture/02_components.md new file mode 100644 index 0000000..09c8893 --- /dev/null +++ b/docs/architecture/02_components.md @@ -0,0 +1,127 @@ +# Компоненты + +## 1. Conversation Manager + +Отвечает за пользовательский контекст: + +- диалоги; +- сообщения; +- вложения; +- выбранный проект; +- активные workers; +- выбранные режимы доступа; +- настройки моделей; +- историю подтверждений. + +Не выполняет tools напрямую. + +## 2. Orchestrator + +Главный серверный компонент. + +Функции: + +- принять задачу; +- определить тип задачи; +- выбрать execution mode; +- запустить planner; +- создать execution graph; +- запускать узлы графа; +- вызывать model router; +- вызывать MCP tools; +- отправлять команды local worker; +- обрабатывать подтверждения; +- логировать; +- собирать финальный результат. + +## 3. Model Router + +Единый интерфейс к моделям. + +Слоты: + +```text +weak +strong +vision +embedding +reranker +``` + +Каждый слот настраивается: + +```text +provider = local | external | disabled +model = string +base_url = string +api_key_env = string +``` + +## 4. MCP Client + +Универсальный клиент к MCP-серверам. + +Не должен знать про 1С. + +Поддержать: + +- initialize; +- tools/list; +- tools/call; +- resources/list; +- resources/read; +- prompts/list; +- prompts/get. + +## 5. Local Worker Gateway + +Серверная часть для связи с local workers. + +Local worker сам открывает исходящее соединение: + +```text +Local Worker → WebSocket/gRPC stream → Server +``` + +Сервер не открывает входящий порт на ПК пользователя. + +## 6. Policy Engine + +Не содержит жестких запретов. + +Он читает настройки проекта и решает: + +- выполнять сразу; +- запросить подтверждение; +- показать preview; +- поставить задачу в ручной режим; +- пропустить, если выбран full_auto. + +## 7. Execution Graph Engine + +Хранит и исполняет граф: + +```text +nodes: + - id + - type + - input + - output + - status + - dependencies + - assigned_runner + - attempts + - logs +``` + +Статусы: + +```text +pending +running +waiting_confirmation +completed +failed +cancelled +skipped +``` diff --git a/docs/architecture/03_no_hardcoded_bans.md b/docs/architecture/03_no_hardcoded_bans.md new file mode 100644 index 0000000..eaf95d0 --- /dev/null +++ b/docs/architecture/03_no_hardcoded_bans.md @@ -0,0 +1,99 @@ +# Принцип: нет жестких запретов в коде + +## Требование + +В проекте не должно быть hardcoded-запретов вида: + +```text +if tool == "command.run": deny +if sql contains "DELETE": deny +if action == "filesystem": deny +``` + +Так делать нельзя. + +## Правильный подход + +Код должен классифицировать действие и спросить policy engine. + +```text +action → classify → policy.check → decision +``` + +Policy decision: + +```json +{ + "decision": "allow | confirm | manual | disabled_by_config", + "reason": "string", + "requires_confirmation": true, + "preview": {} +} +``` + +## Пример + +Команда: + +```text +file.write D:/Projects/test.txt +``` + +Tool возвращает metadata: + +```json +{ + "risk_level": "write", + "resource": "filesystem", + "preview_available": true +} +``` + +Policy проекта: + +```json +{ + "filesystem": { + "mode": "confirm" + } +} +``` + +Результат: + +```text +Нужно подтверждение. +``` + +Если policy: + +```json +{ + "filesystem": { + "mode": "full_auto" + } +} +``` + +Результат: + +```text +Выполнить сразу. +``` + +## Режимы + +```text +full_auto — выполнять без подтверждения +confirm — спросить подтверждение +manual — показать план и ждать ручного запуска +disabled — отключено настройкой +``` + +`disabled` допустим только как настройка проекта, а не как зашитый запрет. + +## Зачем + +Пользователь сам выбирает уровень риска. + +Система не должна становиться бесполезной из-за того, что разработчик заранее запретил все потенциально опасные действия. diff --git a/docs/codex/CODEX_TASK.md b/docs/codex/CODEX_TASK.md new file mode 100644 index 0000000..05859bf --- /dev/null +++ b/docs/codex/CODEX_TASK.md @@ -0,0 +1,182 @@ +# Задача для Codex + +## Цель + +Создать отдельный проект `ai-orchestrator`. + +Это серверный orchestrator/runtime для управления AI-задачами, моделями, MCP-tools и local workers. + +Проект не должен быть частью текущего `Local LLM Platform`. + +## Основные принципы + +1. Orchestrator — главный сервис. +2. Agent — не отдельная сущность, а execution profile. +3. Сложные задачи выполняются через execution graph. +4. Workers не создают других workers. +5. Local Worker — тонкий исполнитель на компьютере пользователя. +6. В коде нет hardcoded bans. +7. Все ограничения — через настраиваемую policy. +8. Система должна работать без внешнего ИИ. +9. Strong model может быть локальной или внешней. +10. Vision model — отдельный слот. + +## Реализовать структуру + +```text +src/ + orchestrator/ + agent_runtime/ + model_router/ + mcp_client/ + local_worker_protocol/ + policy/ + api/ + logging/ + storage/ +``` + +## MVP функции + +### 1. API + +Реализовать: + +```text +POST /chat +POST /tasks +GET /tasks/{id} +GET /tasks/{id}/events +POST /confirmations/{id}/approve +POST /confirmations/{id}/reject +GET /workers +``` + +### 2. Orchestrator + +Должен: + +```text +- принимать task; +- создавать execution graph; +- запускать nodes; +- вызывать model router; +- вызывать MCP client; +- отправлять команды local worker; +- обрабатывать confirmation_required; +- писать event log. +``` + +### 3. Execution Graph + +Node types: + +```text +planner +model_call +tool_call +local_worker_call +reviewer +finalizer +confirmation +``` + +### 4. Model Router + +Слоты: + +```text +weak +strong +vision +embedding +``` + +Provider: + +```text +local +external +disabled +``` + +### 5. Policy Engine + +Без hardcoded bans. + +Policy читает конфиг и возвращает: + +```text +allow +confirm +manual +disabled_by_config +``` + +### 6. Local Worker Gateway + +Поддержать: + +```text +worker registration +capabilities +command dispatch +command result +progress events +heartbeat +disconnect +``` + +### 7. MCP Client + +Поддержать базовый MCP flow: + +```text +initialize +tools/list +tools/call +``` + +### 8. UI contracts + +Подготовить backend ответы для карточек: + +```text +plan_card +confirmation_card +progress_card +artifact_card +error_card +``` + +## Smoke tests + +Добавить тесты: + +```text +1. simple chat without tools +2. task creates execution graph +3. model fallback weak → strong +4. policy confirm returns confirmation request +5. policy full_auto executes immediately +6. local worker command result is stored +7. MCP tool call result is stored +8. task event stream emits node_started/node_completed +``` + +## Конфиги + +Создать примеры: + +```text +configs/examples/local_only.yaml +configs/examples/local_plus_external.yaml +configs/examples/full_auto.yaml +configs/examples/confirm_mode.yaml +``` + +## Важно + +Не добавлять 1С-логику в ядро orchestrator. + +1С должна подключаться как MCP server или tool provider. diff --git a/docs/contracts/API_CONTRACTS.md b/docs/contracts/API_CONTRACTS.md new file mode 100644 index 0000000..082db51 --- /dev/null +++ b/docs/contracts/API_CONTRACTS.md @@ -0,0 +1,106 @@ +# API Contracts + +## POST /chat + +Вход: + +```json +{ + "project_id": "default", + "conversation_id": "optional", + "message": "Найди файл и исправь запрос", + "attachments": [], + "mode": "auto", + "preferences": { + "local_only": true, + "show_plan": true + } +} +``` + +Выход: + +```json +{ + "conversation_id": "conv_1", + "task_id": "task_1", + "response_type": "answer | task_started | confirmation_required | error", + "message": "string", + "cards": [] +} +``` + +## POST /tasks + +Создать задачу без chat-интерфейса. + +```json +{ + "project_id": "default", + "goal": "Исправить модуль", + "inputs": {}, + "execution_mode": "agent_graph" +} +``` + +## GET /tasks/{task_id} + +```json +{ + "task_id": "task_1", + "status": "running", + "current_node": "node_3", + "progress": { + "completed": 2, + "total": 5 + } +} +``` + +## GET /tasks/{task_id}/events + +SSE/WebSocket stream событий: + +```json +{ + "event": "node_started", + "task_id": "task_1", + "node_id": "node_3", + "timestamp": "..." +} +``` + +## POST /confirmations/{id}/approve + +```json +{ + "scope": "once | task | project", + "comment": "approved" +} +``` + +## POST /confirmations/{id}/reject + +```json +{ + "reason": "not now" +} +``` + +## POST /workers/register + +Local worker регистрируется на сервере. + +```json +{ + "worker_id": "worker_home_pc", + "name": "Home PC", + "capabilities": [ + "file.read", + "file.write", + "file.search", + "command.run" + ], + "version": "0.1.0" +} +``` diff --git a/docs/contracts/LOCAL_WORKER_PROTOCOL.md b/docs/contracts/LOCAL_WORKER_PROTOCOL.md new file mode 100644 index 0000000..7f7b985 --- /dev/null +++ b/docs/contracts/LOCAL_WORKER_PROTOCOL.md @@ -0,0 +1,148 @@ +# Local Worker Protocol + +## Назначение + +Local Worker — тонкий исполнитель команд на локальном компьютере. + +Он не планирует задачу и не принимает интеллектуальных решений. + +Он: + +```text +- подключается к серверу; +- сообщает capabilities; +- получает команды; +- выполняет; +- возвращает статус, результат, ошибки, артефакты. +``` + +## Соединение + +Предпочтительно: + +```text +Local Worker → outbound WebSocket → Server +``` + +## Capabilities + +Пример: + +```json +{ + "worker_id": "home_pc", + "machine": "DESKTOP-1", + "os": "windows", + "version": "0.1.0", + "capabilities": [ + "file.read", + "file.write", + "file.search", + "file.apply_patch", + "command.run", + "process.status", + "task.cancel" + ] +} +``` + +## Command envelope + +```json +{ + "command_id": "cmd_123", + "task_id": "task_456", + "tool": "file.read", + "args": { + "path": "D:/Projects/test.bsl" + }, + "timeout_ms": 30000, + "policy_context": { + "approved": true, + "approval_id": "conf_1" + } +} +``` + +## Result envelope + +```json +{ + "command_id": "cmd_123", + "task_id": "task_456", + "tool": "file.read", + "status": "success", + "started_at": "2026-07-03T10:00:00Z", + "finished_at": "2026-07-03T10:00:01Z", + "duration_ms": 1000, + "stdout": "", + "stderr": "", + "result": { + "content": "...", + "encoding": "utf-8", + "size": 1024, + "sha256": "..." + }, + "artifacts": [], + "error": null +} +``` + +## Error result + +```json +{ + "command_id": "cmd_123", + "status": "error", + "error": { + "code": "FILE_NOT_FOUND", + "message": "File not found", + "details": { + "path": "D:/Projects/test.bsl" + } + } +} +``` + +## Progress events + +```json +{ + "event": "progress", + "command_id": "cmd_123", + "progress": { + "percent": 45, + "message": "Searching files" + } +} +``` + +## Минимальный набор tools + +```text +worker.ping +worker.capabilities +file.read +file.write +file.search +file.apply_patch +command.run +process.status +task.cancel +``` + +## Важное правило + +Local Worker не должен сам вызывать модель и не должен сам решать следующий шаг. + +Он может выполнять локальные проверки: + +```text +- проверить существование файла; +- сделать backup; +- посчитать hash; +- применить patch; +- вернуть diff; +- выполнить command timeout; +- вернуть stdout/stderr. +``` diff --git a/docs/contracts/MCP_CLIENT.md b/docs/contracts/MCP_CLIENT.md new file mode 100644 index 0000000..4960c1c --- /dev/null +++ b/docs/contracts/MCP_CLIENT.md @@ -0,0 +1,60 @@ +# MCP Client + +## Назначение + +AI Orchestrator должен работать с любыми MCP-серверами. + +MCP client — универсальный слой, не содержащий 1С-логики. + +## Поддержать методы + +```text +initialize +tools/list +tools/call +resources/list +resources/read +prompts/list +prompts/get +``` + +## Tool metadata + +Каждый tool должен иметь metadata: + +```json +{ + "name": "1c.run_sql", + "description": "Execute SQL through 1C adapter", + "input_schema": {}, + "risk": { + "resource": "sql", + "level": "safe | write | destructive | cost | system", + "preview_supported": true + } +} +``` + +## Tool call + +```json +{ + "server_id": "one_c", + "tool": "1c.run_sql", + "args": { + "query": "select * from ..." + } +} +``` + +## Tool result + +```json +{ + "status": "success", + "content": {}, + "artifacts": [], + "logs": [], + "error": null +} +``` diff --git a/docs/contracts/MODEL_ROUTER.md b/docs/contracts/MODEL_ROUTER.md new file mode 100644 index 0000000..adac12d --- /dev/null +++ b/docs/contracts/MODEL_ROUTER.md @@ -0,0 +1,78 @@ +# Model Router + +## Цель + +Единый интерфейс к разным моделям: + +- локальным; +- внешним; +- отключенным; +- vision; +- embedding. + +## Слоты + +```text +weak +strong +vision +embedding +reranker +``` + +## Provider types + +```text +local +external +disabled +``` + +## Вызов + +```json +{ + "slot": "weak", + "messages": [], + "tools": [], + "response_format": "json_schema | text", + "task_context": { + "task_id": "task_1", + "node_id": "node_2" + } +} +``` + +## Ответ + +```json +{ + "slot": "weak", + "provider": "local", + "model": "qwen-coder-7b", + "status": "success", + "message": {}, + "tool_calls": [], + "usage": { + "input_tokens": 100, + "output_tokens": 200, + "cost": 0 + }, + "error": null +} +``` + +## Fallback + +Алгоритм: + +```text +1. вызвать weak; +2. если результат валиден — продолжить; +3. если результат невалиден — retry weak; +4. если strong доступна — вызвать strong; +5. если strong disabled — вернуть partial result и ошибку качества; +6. если external выключен настройкой — не вызывать external. +``` + +Важно: external не запрещен в коде. Он включается/выключается настройкой. diff --git a/docs/ui/USER_INTERFACE.md b/docs/ui/USER_INTERFACE.md new file mode 100644 index 0000000..83d3767 --- /dev/null +++ b/docs/ui/USER_INTERFACE.md @@ -0,0 +1,324 @@ +# Интерфейс работы с пользователем + +## Цель интерфейса + +Интерфейс должен быть не просто чатом. + +Он должен позволять пользователю: + +- поставить задачу; +- увидеть, как система поняла задачу; +- увидеть план/граф выполнения; +- выбрать режим доступа; +- подключить local worker; +- подтвердить действия; +- наблюдать прогресс; +- посмотреть логи; +- открыть артефакты; +- продолжить задачу после ошибки; +- повторить задачу с другой моделью. + +## Основные экраны + +### 1. Chat / Task Console + +Главный экран. + +Слева: + +- список диалогов; +- проекты; +- активные задачи; +- подключенные workers. + +Центр: + +- чат; +- сообщения пользователя; +- ответы assistant; +- карточки планов; +- карточки подтверждений; +- статусы выполнения. + +Справа: + +- execution graph; +- используемые tools; +- выбранные модели; +- стоимость; +- логи; +- артефакты. + +## 2. Project Settings + +Настройки проекта: + +```text +Project name +Default model slots +Available MCP servers +Available local workers +Policy modes +Cost limits +Log level +Storage paths +``` + +## 3. Model Settings + +Пользователь может настроить: + +```text +weak model +strong model +vision model +embedding model +``` + +Пример: + +```text +weak: local/qwen-coder-7b +strong: local/qwen-coder-32b +vision: external/gpt-vision +``` + +Или полностью локально: + +```text +weak: local/qwen-coder-7b +strong: local/qwen-coder-32b +vision: local/qwen-vl +``` + +Или без strong: + +```text +weak: local/model +strong: disabled +vision: disabled +``` + +## 4. Access Modes + +Важно: это не запреты в коде, а выбор пользователя. + +Для каждого класса действий: + +```text +models.external +mcp.remote +filesystem +shell +sql +1c +browser +desktop +network +cost +``` + +режим: + +```text +full_auto +confirm +manual +disabled +``` + +Пример: + +```text +filesystem = confirm +shell = confirm +sql = full_auto +1c = confirm +external_models = manual +desktop = disabled +``` + +## 5. Local Worker Screen + +Показывает: + +```text +Worker name +Machine name +OS +Status: online/offline +Capabilities +Allowed paths +Available commands +Last heartbeat +Current task +Version +``` + +Кнопки: + +```text +Connect worker +Disconnect +Edit capabilities +View logs +Run diagnostic +``` + +## 6. Task Plan Card + +Когда пользователь отправляет сложную задачу, система показывает: + +```text +Я понял задачу так: +- найти файл +- прочитать код +- проверить запрос +- предложить исправление +- применить patch +- запустить проверку +``` + +Кнопки: + +```text +Run +Edit plan +Run step by step +Use strong model +Use local only +``` + +## 7. Confirmation Card + +Если нужно подтверждение: + +```text +Система хочет выполнить действие: + +Tool: file.write +Path: D:/Projects/1C/module.bsl +Risk: write + +Preview: +- будет изменено 12 строк +- будет создан backup +``` + +Кнопки: + +```text +Approve once +Approve for this task +Approve always for this project +Reject +Edit policy +``` + +## 8. Progress View + +Показывает выполнение: + +```text +[done] analyze request +[done] build plan +[running] search files +[pending] read file +[pending] apply patch +[pending] validate +``` + +Для каждого шага: + +```text +input +output +model used +tool used +duration +logs +errors +artifacts +``` + +## 9. Result View + +Итог должен быть не только текстом. + +Типы результата: + +```text +chat_answer +file_created +file_modified +patch_generated +sql_executed +report_created +task_failed +confirmation_required +manual_action_required +``` + +Пример: + +```text +Задача выполнена. +Изменен файл: +D:/Projects/1C/CommonModule/Exchange.bsl + +Создан backup: +D:/Projects/1C/.backups/Exchange_2026-07-03.bsl + +Проверка: +validate_sql: success +syntax_check: success +``` + +## 10. Error Recovery + +Если задача упала: + +```text +Ошибка на шаге: validate_sql +Причина: поле Номенклатура.Артикул не найдено + +Варианты: +- исправить автоматически +- запустить strong model +- показать подробный лог +- изменить запрос вручную +- остановить задачу +``` + +## Интерфейс сообщения + +Каждое сообщение assistant может содержать: + +```json +{ + "type": "assistant_message", + "text": "...", + "task_id": "...", + "cards": [ + "plan", + "confirmation", + "progress", + "artifact", + "error" + ] +} +``` + +## Принцип + +Пользователь должен всегда понимать: + +```text +что система собирается делать +что она уже сделала +какие данные использовала +какая модель была вызвана +какой tool был вызван +что изменилось в системе +как откатить действие +``` diff --git a/src/agent_runtime/README.md b/src/agent_runtime/README.md new file mode 100644 index 0000000..21a7f5e --- /dev/null +++ b/src/agent_runtime/README.md @@ -0,0 +1 @@ +Agent = execution profile: prompt + model_slot + tools + limits + output_schema. Workers не создают workers. diff --git a/src/api/README.md b/src/api/README.md new file mode 100644 index 0000000..419316a --- /dev/null +++ b/src/api/README.md @@ -0,0 +1 @@ +HTTP/WebSocket API layer for chat, tasks, confirmations, workers, events. diff --git a/src/local_worker_protocol/README.md b/src/local_worker_protocol/README.md new file mode 100644 index 0000000..20ccf27 --- /dev/null +++ b/src/local_worker_protocol/README.md @@ -0,0 +1 @@ +Local Worker is a thin executor: connects outward, executes commands, returns result/progress/artifacts. diff --git a/src/logging/README.md b/src/logging/README.md new file mode 100644 index 0000000..20ef1a7 --- /dev/null +++ b/src/logging/README.md @@ -0,0 +1 @@ +Structured event log for every model call, tool call, confirmation, fallback, worker result. diff --git a/src/mcp_client/README.md b/src/mcp_client/README.md new file mode 100644 index 0000000..20375b3 --- /dev/null +++ b/src/mcp_client/README.md @@ -0,0 +1 @@ +Universal MCP client: initialize, tools/list, tools/call, resources, prompts. diff --git a/src/model_router/README.md b/src/model_router/README.md new file mode 100644 index 0000000..c2a8895 --- /dev/null +++ b/src/model_router/README.md @@ -0,0 +1 @@ +Unified access to weak/strong/vision/embedding slots. Providers: local/external/disabled. diff --git a/src/orchestrator/README.md b/src/orchestrator/README.md new file mode 100644 index 0000000..1fcba3e --- /dev/null +++ b/src/orchestrator/README.md @@ -0,0 +1 @@ +Главный runtime: task intake, graph scheduling, model/tool/worker calls, confirmations, event logs. diff --git a/src/policy/README.md b/src/policy/README.md new file mode 100644 index 0000000..7c86343 --- /dev/null +++ b/src/policy/README.md @@ -0,0 +1 @@ +No hardcoded bans. Policy returns allow/confirm/manual/disabled_by_config based on project config. diff --git a/src/storage/README.md b/src/storage/README.md new file mode 100644 index 0000000..b723dcb --- /dev/null +++ b/src/storage/README.md @@ -0,0 +1 @@ +Task storage, conversation storage, event storage. Start in-memory, later DB. diff --git a/tests/smoke/SMOKE_TESTS.md b/tests/smoke/SMOKE_TESTS.md new file mode 100644 index 0000000..9419145 --- /dev/null +++ b/tests/smoke/SMOKE_TESTS.md @@ -0,0 +1,16 @@ +# Smoke tests + +Required tests: + +1. simple chat without tools +2. task creates execution graph +3. weak model response success +4. weak model invalid → retry +5. weak invalid → strong fallback +6. external disabled by config → no external call +7. policy confirm → confirmation card +8. policy full_auto → execute immediately +9. MCP tool result stored +10. local worker command result stored +11. event stream emits task/node events +12. finalizer creates user result