gemini-computer-use 0.1.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,196 +1,377 @@
1
- # 🚀 Gemini Computer Use (Web & Mobile App) — FREE & Open Source
1
+ # 📱 Gemini Computer Use — control any PC from Gemini Spark (App & Web)
2
2
 
3
- > **Turn your PC, Laptop, or Server into an autonomous execution node for Google Gemini (Web & Mobile App) via Native Model Context Protocol (MCP).**
3
+ > **An MCP server that turns Google Gemini from a chatbot into a full-fledged mobile agent.**
4
+ > Type a task in the Gemini app on your phone — your PC, laptop or server executes it, and Gemini reports back with real results.
4
5
 
5
6
  [English](README.md) | [🇷🇺 Русская версия](#-русская-версия)
6
7
 
7
8
  ---
8
9
 
9
- ## 💡 What is Gemini Computer Use?
10
+ ## 💡 The idea
11
+
12
+ Gemini in a browser or on a phone can talk, but it cannot *do* anything on your computer.
13
+ **Gemini Computer Use** closes that gap. It is a free, open-source **Model Context Protocol (MCP)** server that you connect to **Gemini Spark** ([gemini.google.com/spark/apps](https://gemini.google.com/spark/apps) or the Gemini mobile app) with a single link. After that, Gemini gets hands:
14
+
15
+ - runs shell commands, builds and tests code, manages git;
16
+ - reads, writes and edits files;
17
+ - searches the file system;
18
+ - starts long-running jobs and checks on them later;
19
+ - watches CPU, RAM and disk.
20
+
21
+ ```text
22
+ 📱 Gemini app / 🌐 gemini.google.com (Spark)
23
+ │ MCP (SSE / Streamable HTTP)
24
+ ▼
25
+ ☁️ Gateway smart-server.online ← relay only, TLS
26
+ │ outbound WebSocket tunnel (no open ports)
27
+ ▼
28
+ 💻 Your PC · laptop · VPS · home server → executes the task
29
+ ```
30
+
31
+ **Result:** your phone becomes a remote control for every machine you own — and Gemini is the agent that operates them.
32
+
33
+ ---
34
+
35
+ ## 🔥 What you can do with it
10
36
 
11
- **Gemini Computer Use** is an open-source, free solution that gives **Google Gemini** direct, autonomous command-execution capability on your local machine, laptop, or remote cloud server directly from the chat interface of [gemini.google.com](https://gemini.google.com), the official Gemini mobile app, or Google AI Studio.
37
+ Just ask Gemini in plain language, from anywhere:
12
38
 
13
- Unlike proprietary paid alternatives, this project uses the official open **Model Context Protocol (MCP)** specification from Google. It operates over a secure, outbound WebSocket reverse tunnel (no open router ports or public IPs required) or in a pure local standalone mode.
39
+ - *"Check why my home server is slow and show the top processes"*
40
+ - *"Pull the latest changes in ~/projects/api, run the tests and tell me what failed"*
41
+ - *"Fix the typo in config.yaml and restart the service"*
42
+ - *"Start a full backup in the background and tell me when it's done"*
43
+ - *"How much free disk space is left on my laptop?"*
44
+
45
+ No SSH client, no terminal on your phone, no VPN — only a chat.
14
46
 
15
47
  ---
16
48
 
17
- ## ✨ Key Features
49
+ ## ✨ Why it works this way
18
50
 
19
- - 🆓 **100% Free**: Operates directly with the free tier of Google Gemini (Web & Mobile app).
20
- - ⚡ **Zero-Config One-Line Install**: Auto-detects device type (laptop, desktop, VPS, container), OS, and architecture.
21
- - 🌐 **Two Deployment Modes**:
22
- 1. **Cloud Gateway + Reverse Tunnel (Recommended)**: Works behind NAT, firewalls, and dynamic IPs. No inbound ports required.
23
- 2. **Local Standalone**: Pure localhost FastMCP server on `localhost:8096` with zero external dependencies.
24
- - 🛡️ **Cryptographic Token Security**: Every tool invocation is secured by a 128-bit secret token (`?token=...`). Unauthorized requests are strictly blocked with HTTP 401.
25
- - 📡 **Remote SSH Deployment**: Deploy nodes to remote Linux servers in one command directly from your terminal (`--ssh=user@host`).
26
- - 🔄 **Native Background Autostart**: Installs and enables system background services (`systemd` on Linux, `launchd` on macOS, background task on Windows).
27
- - 📱 **Mobile & Web Ready**: Prompt Gemini from your smartphone on the go — your home laptop or cloud server will execute tasks in real time!
28
- - 💻 **Cross-Platform**: Fully supports Linux, macOS, and Windows.
51
+ | | |
52
+ | :--- | :--- |
53
+ | 📱 **Mobile-first agent** | Works in the official Gemini mobile app and on the web through Gemini Spark. |
54
+ | 🖥️ **Any PC** | Linux, macOS, Windows — desktops, laptops, VPS, containers. |
55
+ | 🌐 **Behind any NAT** | The node opens an *outbound* WebSocket tunnel. No public IP, no port forwarding, no router setup. |
56
+ | ⚡ **One-line install** | Detects OS, architecture and device type; installs autostart (`systemd` / `launchd` / Windows task); copies your connection link to the clipboard. |
57
+ | 🛡️ **Token-gated** | Every call needs a personal 128-bit token (`?token=…` or `Authorization: Bearer`). Everything else gets HTTP 401. |
58
+ | 🔁 **Many machines, one gateway** | Each node is addressed by `?user=<node-name>` on one shared domain. |
59
+ | 🆓 **Free & open source** | MIT license, works with the free Gemini tier. |
29
60
 
30
61
  ---
31
62
 
32
- ## 🛠️ Available MCP Tools
63
+ ## 🛠️ What Gemini can do on your machine (MCP tools)
64
+
65
+ | Category | Tools |
66
+ | :--- | :--- |
67
+ | Terminal | `bash_exec(command)` |
68
+ | Files | `list_dir(path)` · `read_file(path, start_line, end_line)` · `write_file(path, content)` · `edit_file(path, old_string, new_string)` |
69
+ | Search | `grep_search(pattern, path)` · `glob_find(pattern, path)` |
70
+ | Long-running jobs | `run_job(command)` → `job_output(job_id)` · `job_kill(job_id)` · `job_list()` |
71
+ | Status | `system_vitals()` · `system_info()` · `mesh_status()` |
72
+ | Agent behaviour | `get_orchestration_skill()` — loads the agent's operating rules |
33
73
 
34
- Once connected, Google Gemini gains direct native access to:
35
- - `bash_exec(command)`: Execute shell commands, build code, run test suites, manage git repositories.
36
- - `system_vitals()`: Real-time telemetry monitoring: CPU load, RAM usage, and disk space.
37
- - `get_orchestration_skill()`: Dynamic delivery of infrastructure orchestrator personas and operational guidelines.
74
+ > [!TIP]
75
+ > Gemini gives a single tool call roughly 30 seconds. For anything longer (builds, backups, downloads) the agent uses `run_job` and polls `job_output`, so tasks never get cut off.
38
76
 
39
77
  ---
40
78
 
41
- ## 🚀 Quick Start (One-Liner Install)
79
+ ## 🚀 Quick start — 2 minutes
42
80
 
43
- ### 🐧 Linux & 🍎 macOS (via curl)
81
+ ### 1. Install the node on the PC you want to control
82
+
83
+ **🐧 Linux / 🍎 macOS**
44
84
  ```bash
45
85
  curl -fsSL https://smart-server.online/install.sh | bash
46
86
  ```
47
87
 
48
- ### 🪟 Windows (via PowerShell)
88
+ **🪟 Windows (PowerShell)**
49
89
  ```powershell
50
90
  irm https://smart-server.online/install.ps1 | iex
51
91
  ```
52
92
 
53
- ### 📦 Node.js / NPM (Cross-platform)
93
+ **📦 Node.js (any OS)**
54
94
  ```bash
55
95
  npx gemini-computer-use
56
96
  ```
57
97
 
58
- ### 🛠️ Or clone via Git
98
+ **🛠️ From source**
59
99
  ```bash
60
100
  git clone https://github.com/LevRa7/Computer-use-for-Gemini-App-Web.git
61
101
  cd Computer-use-for-Gemini-App-Web
62
102
  ./install.sh --quick
63
103
  ```
64
104
 
105
+ At the end the installer prints your personal MCP link and copies it to the clipboard:
106
+ ```text
107
+ https://smart-server.online/sse?user=<your-node-name>&token=<your_secret_token>
108
+ ```
109
+
110
+ ### 2. Connect it to Gemini Spark
111
+
112
+ 1. Open **[gemini.google.com/spark/apps](https://gemini.google.com/spark/apps)** in a browser or in the Gemini mobile app.
113
+ 2. Tap **Add App** (or **Settings ⚙️ → Tools / Extensions (MCP)**).
114
+ 3. Paste the link (**Ctrl+V**) and save.
115
+
116
+ ### 3. Give it a task
117
+
118
+ > *"Show system_vitals and list the 5 biggest folders in my home directory."*
119
+
120
+ That's it — Gemini is now an agent running on your machine. Repeat step 1 on other computers to control all of them from the same phone.
121
+
65
122
  ---
66
123
 
67
- ## 📱 Connecting to Google Gemini
124
+ ## 🖥️ Deployment modes
68
125
 
69
- 1. Open **[gemini.google.com/spark/apps](https://gemini.google.com/spark/apps)** (or the Gemini mobile app).
70
- 2. Click **Add App** (or go to **Settings ⚙️ ➔ Tools / Extensions (MCP)**).
71
- 3. The MCP SSE URL is **automatically copied to your clipboard** during install — just paste it (**Ctrl+V**):
72
- ```text
73
- https://<your-device-name>.smart-server.online/sse?token=<your_secret_token>
74
- ```
75
- 4. Done! You can now prompt Gemini:
76
- - *"Check system resources using system_vitals"*
77
- - *"Create a FastAPI application and run test coverage via bash_exec"*
78
- - *"Git commit and push changes"*
126
+ | Mode | Command | When to use |
127
+ | :--- | :--- | :--- |
128
+ | **Gateway + tunnel** (recommended) | `./install.sh --quick` | Home PCs and laptops behind NAT — the mobile-agent scenario. |
129
+ | **Remote over SSH** | `./install.sh --ssh=user@host` | Deploy a node onto a remote Linux server from your terminal. |
130
+ | **Local standalone** | `./install.sh --mode=standalone --port=8096` | Pure localhost FastMCP server at `http://localhost:8096/sse`, no cloud relay. |
79
131
 
80
132
  ---
81
133
 
82
- ## 🖥️ Deployment Modes
134
+ ## 🔗 One shared domain (canonical URL contract)
83
135
 
84
- ### Mode 1: Cloud Gateway + Tunnel (Recommended)
85
- ```bash
86
- ./install.sh --quick
87
- ```
88
- Perfect for personal laptops and home workstations behind NAT. The connection is maintained via an outbound secure WebSocket tunnel.
136
+ A node is **never** addressed by its own hostname. The gateway publishes a single shared domain, and the node name travels as a query parameter:
89
137
 
90
- ### Mode 2: Local Standalone
91
- ```bash
92
- ./install.sh --mode=standalone --port=8096
93
- ```
94
- Runs an isolated, local FastMCP server on `http://localhost:8096/sse` without cloud relaying.
138
+ | Purpose | Canonical URL |
139
+ | :--- | :--- |
140
+ | MCP over SSE | `https://<shared-domain>/sse?user=<node-name>&token=<token>` |
141
+ | MCP Streamable HTTP | `https://<shared-domain>/mcp?user=<node-name>&token=<token>` |
142
+ | Reverse tunnel (agent) | `wss://<shared-domain>/ws/tunnel?user=<node-name>&token=<token>` |
143
+
144
+ Why: every extra hostname would need its own DNS record *and* its own SAN in the TLS certificate. A node whose name is missing from the certificate fails the TLS handshake, and the Gemini client then reports an opaque "cannot connect to host". With one shared domain the certificate covers every node forever, and adding a node is only a registration call.
145
+
146
+ - The shared domain defaults to `smart-server.online`; override it with `./install.sh --domain=<shared-domain>` (node side) or `MESH_PUBLIC_URL` (gateway side).
147
+ - Legacy per-device subdomain URLs still resolve for backwards compatibility and log a deprecation warning; set `MESH_LEGACY_SUBDOMAIN=0` on the gateway to reject them outright.
148
+
149
+ ---
150
+
151
+ ## 🔒 Security
152
+
153
+ - **Token-gated endpoints** — every request must carry the node's secret token.
154
+ - **Outbound-only tunnel** — nodes never listen on public ports; the agent dials out to the gateway.
155
+ - **Gateway is a relay** — it terminates TLS and forwards calls; commands run only on your node.
156
+ - **Unprivileged by default** — the agent runs in user space, without root.
157
+
158
+ > [!WARNING]
159
+ > Whoever has your MCP link can run commands on that machine. Treat it like a password: don't publish it, and reinstall the node to rotate the token if it leaks.
160
+
161
+ ---
162
+
163
+ ## 🚢 Self-hosting the gateway
164
+
165
+ The gateway is a single host serving every node. Publish it only through the deploy script, so the running gateway, the served installers and the node bootstrap payload cannot drift apart:
95
166
 
96
- ### Mode 3: Remote SSH Install
97
167
  ```bash
98
- ./install.sh --ssh=user@my-remote-server.com
168
+ MESH_GATEWAY_SSH=root@<gateway-ip> ./deploy_gateway.sh # deploy
169
+ MESH_GATEWAY_SSH=root@<gateway-ip> ./deploy_gateway.sh --dry-run # preview
170
+ MESH_GATEWAY_SSH=root@<gateway-ip> MESH_GATEWAY_SSH_PASS_FILE=~/.ssh/gw-pass \
171
+ ./deploy_gateway.sh # password auth
99
172
  ```
100
- Automatically transfers files and configures the node on your remote server via SSH.
173
+ It verifies every upload with an sha256 manifest on the host, takes a timestamped backup, installs with the right owner, restarts the service and finishes with a public health check. Nothing is installed if verification fails.
101
174
 
102
- ---
175
+ **TLS certificate policy — one name, no per-device SANs.** The certificate must cover the shared domain only; a node is selected by `?user=`, never by a hostname:
103
176
 
104
- ## 🔒 Security Architecture
177
+ ```bash
178
+ # what the certificate currently covers
179
+ sudo certbot certificates | grep -A1 'Certificate Name: smart-server.online'
105
180
 
106
- - **Token-Gated Endpoints**: Every incoming request must contain the cryptographic token via `?token=...` or `Authorization: Bearer`.
107
- - **Outbound-Only Tunnel**: Local nodes do not open listening public ports. The agent initiates an outbound WebSocket connection to the gateway.
108
- - **Unprivileged Execution**: Agents execute in user-space by default without requiring root privileges.
181
+ # canonical renewal check (staging, does not touch the live certificate)
182
+ sudo certbot renew --dry-run --cert-name smart-server.online
183
+ ```
184
+ Legacy per-device SANs may still be present from before this contract. They are harmless and keep old bookmarked URLs working; drop them at the next renewal once no client uses subdomain URLs any more (see the `domains =` line in `/etc/letsencrypt/renewal/<name>.conf`, or re-issue with a single `-d`).
109
185
 
110
186
  ---
111
187
 
112
188
  ## 📄 License
113
189
 
114
- This project is licensed under the **MIT License**. See [LICENSE](LICENSE) for details.
190
+ **MIT** — see [LICENSE](LICENSE).
115
191
 
116
192
  ---
117
193
  ---
118
194
 
119
195
  # 🇷🇺 Русская версия
120
196
 
121
- > **Превратите свой ПК, ноутбук или сервер в автономный исполнительный узел для Google Gemini (Web и Mobile App) через нативный протокол Model Context Protocol (MCP).**
197
+ > **MCP-сервер, который превращает Google Gemini из чат-бота в полноценного мобильного агента.**
198
+ > Напишите задачу в приложении Gemini на телефоне — ваш ПК, ноутбук или сервер выполнит её, а Gemini вернётся с реальным результатом.
199
+
200
+ ---
201
+
202
+ ## 💡 Идея
203
+
204
+ Gemini в браузере или на телефоне умеет разговаривать, но ничего не может *сделать* на вашем компьютере.
205
+ **Gemini Computer Use** устраняет этот разрыв. Это бесплатный open-source сервер **Model Context Protocol (MCP)**, который подключается к **Gemini Spark** ([gemini.google.com/spark/apps](https://gemini.google.com/spark/apps) или мобильное приложение Gemini) одной ссылкой. После этого у Gemini появляются «руки»:
206
+
207
+ - выполняет команды терминала, собирает и тестирует код, работает с git;
208
+ - читает, создаёт и редактирует файлы;
209
+ - ищет по файловой системе;
210
+ - запускает долгие задачи в фоне и проверяет их позже;
211
+ - следит за CPU, RAM и диском.
212
+
213
+ ```text
214
+ 📱 Приложение Gemini / 🌐 gemini.google.com (Spark)
215
+ │ MCP (SSE / Streamable HTTP)
216
+ ▼
217
+ ☁️ Шлюз smart-server.online ← только релей, TLS
218
+ │ исходящий WebSocket-туннель (без открытых портов)
219
+ ▼
220
+ 💻 Ваш ПК · ноутбук · VPS · домашний сервер → выполняет задачу
221
+ ```
222
+
223
+ **Итог:** телефон становится пультом управления всеми вашими машинами, а Gemini — агентом, который ими управляет.
122
224
 
123
225
  ---
124
226
 
125
- ## 💡 Что это такое?
227
+ ## 🔥 Что можно делать
126
228
 
127
- **Gemini Computer Use** — это открытое и бесплатное решение для прямого управления вашим компьютером, ноутбуком или удалённым сервером из диалогового окна **Google Gemini** (включая веб-версию [gemini.google.com](https://gemini.google.com), мобильное приложение Gemini и Google AI Studio).
229
+ Просто попросите Gemini обычным языком, откуда угодно:
128
230
 
129
- Проект использует официальный протокол **Model Context Protocol (MCP)** от Google и работает поверх защищённого WebSocket-туннеля или в локальном автономном режиме.
231
+ - *«Посмотри, почему тормозит домашний сервер, и покажи топ процессов»*
232
+ - *«Подтяни последние изменения в ~/projects/api, прогони тесты и скажи, что упало»*
233
+ - *«Исправь опечатку в config.yaml и перезапусти сервис»*
234
+ - *«Запусти полный бэкап в фоне и сообщи, когда закончится»*
235
+ - *«Сколько свободного места осталось на ноутбуке?»*
236
+
237
+ Без SSH-клиента, без терминала на телефоне, без VPN — только чат.
130
238
 
131
239
  ---
132
240
 
133
- ## ✨ Ключевые возможности
241
+ ## ✨ Почему это удобно
134
242
 
135
- - 🆓 **100% Бесплатно**: Работает со стандартным бесплатным тарифом Google Gemini (Web и Mobile App).
136
- - ⚡ **Установка в одну команду (One-Line Setup)**: Скрипт автоматически определяет тип устройства (ноутбук/десктоп/VPS/сервер), ОС и архитектуру.
137
- - 🌐 **Два режима работы**:
138
- 1. **Cloud Gateway + Reverse Tunnel**: Работает из-за любого «серого» IP, роутера и NAT без белого IP и проброса портов.
139
- 2. **Local Standalone**: Полностью локальный FastMCP-сервер на `localhost:8096` без внешних зависимостей.
140
- - 🛡️ **Строгая безопасность**: Каждый запрос к инструментам защищён персональным криптографическим токеном (`?token=...`). Доступ посторонних строго отсекается (HTTP 401).
141
- - 📡 **Удалённая установка через SSH**: Развёртывание узла на удалённом сервере одной командой (`--ssh=user@host`).
142
- - 🔄 **Автозапуск**: Интеграция со службами автозапуска (`systemd` в Linux, `launchd` в macOS, автозапуск в Windows).
143
- - 📱 **Управление со смартфона**: Пишите команды в мобильном приложении Gemini — ваша домашняя машина выполнит их в реальном времени!
144
- - 💻 **Кроссплатформенность**: Полная поддержка Linux, macOS и Windows.
243
+ | | |
244
+ | :--- | :--- |
245
+ | 📱 **Мобильный агент** | Работает в официальном приложении Gemini и в вебе через Gemini Spark. |
246
+ | 🖥️ **Любой ПК** | Linux, macOS, Windows — десктопы, ноутбуки, VPS, контейнеры. |
247
+ | 🌐 **За любым NAT** | Узел сам открывает *исходящий* WebSocket-туннель. Не нужны белый IP, проброс портов и настройка роутера. |
248
+ | ⚡ **Установка одной командой** | Определяет ОС, архитектуру и тип устройства; ставит автозапуск (`systemd` / `launchd` / задача Windows); копирует ссылку подключения в буфер обмена. |
249
+ | 🛡️ **Доступ по токену** | Каждый вызов требует личный 128-битный токен (`?token=…` или `Authorization: Bearer`). Остальным — HTTP 401. |
250
+ | 🔁 **Много машин, один шлюз** | Каждый узел выбирается параметром `?user=<имя-узла>` на одном общем домене. |
251
+ | 🆓 **Бесплатно и открыто** | Лицензия MIT, работает на бесплатном тарифе Gemini. |
145
252
 
146
253
  ---
147
254
 
148
- ## 🛠️ Доступные MCP-инструменты
255
+ ## 🛠️ Что Gemini может делать на вашей машине (MCP-инструменты)
256
+
257
+ | Категория | Инструменты |
258
+ | :--- | :--- |
259
+ | Терминал | `bash_exec(command)` |
260
+ | Файлы | `list_dir(path)` · `read_file(path, start_line, end_line)` · `write_file(path, content)` · `edit_file(path, old_string, new_string)` |
261
+ | Поиск | `grep_search(pattern, path)` · `glob_find(pattern, path)` |
262
+ | Долгие задачи | `run_job(command)` → `job_output(job_id)` · `job_kill(job_id)` · `job_list()` |
263
+ | Состояние | `system_vitals()` · `system_info()` · `mesh_status()` |
264
+ | Поведение агента | `get_orchestration_skill()` — загружает рабочие правила агента |
149
265
 
150
- - `bash_exec(command)` — автономное выполнение команд терминала, компиляция кода, тесты, git-операции.
151
- - `system_vitals()` — мониторинг нагрузки в реальном времени (CPU, RAM, диск).
152
- - `get_orchestration_skill()` — системные правила и скилл автономного оркестратора инфраструктуры.
266
+ > [!TIP]
267
+ > Gemini даёт одному вызову инструмента около 30 секунд. Всё, что дольше (сборки, бэкапы, загрузки), агент запускает через `run_job` и забирает результат через `job_output` — задачи не обрываются.
153
268
 
154
269
  ---
155
270
 
156
- ## 🚀 Быстрый старт (Установка в 1 команду)
271
+ ## 🚀 Быстрый старт — 2 минуты
157
272
 
158
- #### 🐧 Linux & 🍎 macOS (через curl):
273
+ ### 1. Установите узел на ПК, которым хотите управлять
274
+
275
+ **🐧 Linux / 🍎 macOS**
159
276
  ```bash
160
277
  curl -fsSL https://smart-server.online/install.sh | bash
161
278
  ```
162
279
 
163
- #### 🪟 Windows (через PowerShell):
280
+ **🪟 Windows (PowerShell)**
164
281
  ```powershell
165
282
  irm https://smart-server.online/install.ps1 | iex
166
283
  ```
167
284
 
168
- #### 📦 Node.js / NPM (Кроссплатформенно):
285
+ **📦 Node.js (любая ОС)**
169
286
  ```bash
170
287
  npx gemini-computer-use
171
288
  ```
172
289
 
173
- #### 🛠️ Либо вручную через Git:
290
+ **🛠️ Из исходников**
174
291
  ```bash
175
292
  git clone https://github.com/LevRa7/Computer-use-for-Gemini-App-Web.git
176
293
  cd Computer-use-for-Gemini-App-Web
177
294
  ./install.sh --quick
178
295
  ```
179
296
 
297
+ В конце установщик выведет вашу личную MCP-ссылку и скопирует её в буфер обмена:
298
+ ```text
299
+ https://smart-server.online/sse?user=<имя-вашего-узла>&token=<ваш_секретный_токен>
300
+ ```
301
+
302
+ ### 2. Подключите её к Gemini Spark
303
+
304
+ 1. Откройте **[gemini.google.com/spark/apps](https://gemini.google.com/spark/apps)** в браузере или в мобильном приложении Gemini.
305
+ 2. Нажмите **Добавить приложение** (или **Настройки ⚙️ → Инструменты / Расширения (MCP)**).
306
+ 3. Вставьте ссылку (**Ctrl+V**) и сохраните.
307
+
308
+ ### 3. Дайте задачу
309
+
310
+ > *«Покажи system_vitals и 5 самых больших папок в домашнем каталоге.»*
311
+
312
+ Готово — Gemini теперь агент, работающий на вашей машине. Повторите шаг 1 на других компьютерах, чтобы управлять ими всеми с одного телефона.
313
+
314
+ ---
315
+
316
+ ## 🖥️ Режимы развёртывания
317
+
318
+ | Режим | Команда | Когда использовать |
319
+ | :--- | :--- | :--- |
320
+ | **Шлюз + туннель** (рекомендуется) | `./install.sh --quick` | Домашние ПК и ноутбуки за NAT — сценарий мобильного агента. |
321
+ | **Удалённо через SSH** | `./install.sh --ssh=user@host` | Развернуть узел на удалённом Linux-сервере прямо из терминала. |
322
+ | **Локальный автономный** | `./install.sh --mode=standalone --port=8096` | Чисто локальный FastMCP-сервер на `http://localhost:8096/sse`, без облачного релея. |
323
+
324
+ ---
325
+
326
+ ## 🔗 Один общий домен (канонический формат URL)
327
+
328
+ Узел **никогда** не адресуется собственным именем хоста. Шлюз публикует один общий домен, а имя узла передаётся параметром:
329
+
330
+ | Назначение | Канонический URL |
331
+ | :--- | :--- |
332
+ | MCP через SSE | `https://<общий-домен>/sse?user=<имя-узла>&token=<токен>` |
333
+ | MCP Streamable HTTP | `https://<общий-домен>/mcp?user=<имя-узла>&token=<токен>` |
334
+ | Обратный туннель (агент) | `wss://<общий-домен>/ws/tunnel?user=<имя-узла>&token=<токен>` |
335
+
336
+ Почему так: каждому дополнительному имени хоста нужна своя DNS-запись **и** свой SAN в TLS-сертификате. Если имени нет в сертификате, TLS-рукопожатие падает, и клиент Gemini показывает невнятную ошибку «не удаётся подключиться к хосту». С одним общим доменом сертификат покрывает все узлы сразу, а добавление узла — это только вызов регистрации.
337
+
338
+ - Общий домен по умолчанию `smart-server.online`; переопределяется через `./install.sh --domain=<общий-домен>` (на стороне узла) или `MESH_PUBLIC_URL` (на стороне шлюза).
339
+ - Старые ссылки с субдоменами устройства продолжают работать для совместимости и пишут предупреждение в лог; `MESH_LEGACY_SUBDOMAIN=0` на шлюзе отключает их.
340
+
341
+ ---
342
+
343
+ ## 🔒 Безопасность
344
+
345
+ - **Доступ только по токену** — каждый запрос должен содержать секретный токен узла.
346
+ - **Только исходящий туннель** — узлы не слушают публичные порты; агент сам подключается к шлюзу.
347
+ - **Шлюз — только релей** — он терминирует TLS и передаёт вызовы; команды выполняются только на вашем узле.
348
+ - **Без root по умолчанию** — агент работает в пространстве пользователя.
349
+
350
+ > [!WARNING]
351
+ > Любой, у кого есть ваша MCP-ссылка, может выполнять команды на этой машине. Храните её как пароль: не публикуйте, а при утечке переустановите узел, чтобы сменить токен.
352
+
180
353
  ---
181
354
 
182
- ## 📱 Подключение к Google Gemini
355
+ ## 🚢 Свой шлюз (self-hosting)
356
+
357
+ Шлюз — один хост на все узлы. Публикуйте его только скриптом, чтобы работающий шлюз, отдаваемые установщики и bootstrap-код узлов не расходились:
183
358
 
184
- 1. Откройте страницу **[gemini.google.com/spark/apps](https://gemini.google.com/spark/apps)** (в браузере или приложении).
185
- 2. Нажмите **Добавить приложение** (Add App / Настройки ➔ MCP).
186
- 3. Ссылка на ваш MCP-сервер **автоматически скопирована в буфер обмена** при установке — просто вставьте её (**Ctrl+V**):
187
- ```text
188
- https://<имя-вашего-пк>.smart-server.online/sse?token=<ваш_секретный_токен>
189
- ```
190
- 4. Готово! Теперь Gemini может выполнять команды прямо на вашей машине.
359
+ ```bash
360
+ MESH_GATEWAY_SSH=root@<ip-шлюза> ./deploy_gateway.sh # задеплоить
361
+ MESH_GATEWAY_SSH=root@<ip-шлюза> ./deploy_gateway.sh --dry-run # предпросмотр
362
+ ```
363
+ Скрипт проверяет каждую загрузку манифестом sha256 на хосте, делает бэкап с меткой времени, ставит файлы с нужным владельцем, перезапускает службу и завершает публичной проверкой здоровья. При несовпадении хэшей ничего не устанавливается.
364
+
365
+ **Политика TLS-сертификата: только общий домен, без SAN на устройства.** Имена узлов в сертификат не добавляются никогда — узел выбирается `?user=`:
366
+
367
+ ```bash
368
+ sudo certbot certificates | grep -A1 'Certificate Name: smart-server.online'
369
+ sudo certbot renew --dry-run --cert-name smart-server.online # проверка продления
370
+ ```
371
+ Старые SAN'ы устройств могут остаться с прежнего контракта: они безвредны и поддерживают совместимость старых ссылок. Убрать их можно при следующем продлении, когда субдоменными ссылками никто не пользуется.
191
372
 
192
373
  ---
193
374
 
194
375
  ## 📄 Лицензия
195
376
 
196
- Распространяется под свободной лицензией **MIT**. Подробности в файле [LICENSE](LICENSE).
377
+ **MIT** — подробности в файле [LICENSE](LICENSE).