@goodandready/dsh-remote-workspace 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GooDAnDReaDY
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,238 @@
1
+ # 📦 @goodandready/dsh-remote-workspace
2
+
3
+ <div align="center">
4
+
5
+ <h3>Enterprise Remote Workspace for DeepSeek Harness: SSH, SFTP File Sync & Tunneling</h3>
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/@goodandready/dsh-remote-workspace"><img src="https://img.shields.io/npm/v/@goodandready/dsh-remote-workspace.svg?style=for-the-badge&color=6366f1&labelColor=1e1b4b" alt="npm version"></a>
9
+ <a href="LICENSE"><img src="https://img.shields.io/github/license/GooDAnDReaDY/dsh-remote-workspace.svg?style=for-the-badge&color=10b981&labelColor=064e3b" alt="license"></a>
10
+ <a href="https://github.com/topics/dsh-plugin"><img src="https://img.shields.io/badge/DSH-Plugin-8b5cf6.svg?style=for-the-badge&labelColor=2e1065" alt="DSH Plugin"></a>
11
+ <a href="https://nodejs.org"><img src="https://img.shields.io/badge/Node-20%2B-f59e0b.svg?style=for-the-badge&labelColor=451a03" alt="Node version"></a>
12
+ </p>
13
+
14
+ <!-- Author Showcase Badge -->
15
+ <p align="center">
16
+ <a href="https://goodandready.app/"><img src="https://img.shields.io/badge/Все_проекты_автора-goodandready.app-ff4500.svg?style=for-the-badge&logo=rocket&logoColor=white&labelColor=1a1a2e" alt="GoodAndReady Showcase"></a>
17
+ </p>
18
+
19
+ <p align="center">
20
+ <a href="README.md"><b>🇬🇧 English</b></a> •
21
+ <a href="README.ru.md"><b>🇷🇺 Русский</b></a> •
22
+ <a href="README.zh.md"><b>🇨🇳 中文说明</b></a>
23
+ </p>
24
+
25
+ </div>
26
+
27
+ ---
28
+
29
+ ## ⚡ Overview & The Problem
30
+
31
+ In modern software engineering and agentic workflows, AI agents orchestrating code within **DeepSeek Harness (DSH)** frequently need to work across remote environments: cloud virtual machines, high-performance GPU instances, containerized remote clusters, and staging servers.
32
+
33
+ Without `@goodandready/dsh-remote-workspace`, developers face critical roadblocks:
34
+ 1. **Local Boundary Limitation**: Standard DSH operations and agent tools run exclusively against the local machine where DSH is deployed.
35
+ 2. **Fragile Ad-Hoc Scripts**: Manual SSH wrappers and ad-hoc SCP uploads lack robust connection pooling, causing connection drops, hangs under network latency, and high resource overhead.
36
+ 3. **Silent File Overwrites**: Naive file copies risk corrupting data during network interruptions or overwriting concurrent modifications made by remote teams.
37
+ 4. **Port Accessibility**: Accessing remote web servers, inference APIs, or debuggers typically requires manual external SSH tunneling configuration.
38
+
39
+ `@goodandready/dsh-remote-workspace` solves these challenges directly within the Cordis framework. It provides an enterprise-grade remote development subsystem with persistent SSH2 connection pooling, atomic SFTP file operations, conflict-aware 3-way synchronization, dynamic port tunneling, and an interactive Web UI settings card styled after `dsh-clinebot`.
40
+
41
+ ---
42
+
43
+ ## 🏗️ Architecture
44
+
45
+ ```mermaid
46
+ graph LR
47
+ subgraph DSH["DeepSeek Harness (Cordis Architecture)"]
48
+ UI["Web UI Client Card<br/>(dsh-clinebot style)"]
49
+ Routes["REST API Routes<br/>(/state, /browse, /test, /sync)"]
50
+ Tools["Model Tools<br/>(remote_exec, remote_fs, sync, tunnel)"]
51
+ Ssh["SshService<br/>(Connection Pool & Keepalive)"]
52
+ SFTP["RemoteFsService<br/>(Atomic SFTP Streaming)"]
53
+ Sync["MirrorSyncService<br/>(3-Way SHA-256 Engine)"]
54
+ Tunnel["TunnelService<br/>(Port Forwarding)"]
55
+ end
56
+
57
+ subgraph RemoteNode["Remote Environment (Cloud VM / GPU Node)"]
58
+ SSHD["SSH Server (:22)"]
59
+ FS["Remote Filesystem"]
60
+ AppPort["Remote Dev Server / Service"]
61
+ end
62
+
63
+ UI -->|REST API| Routes
64
+ Routes --> Ssh
65
+ Routes --> SFTP
66
+ Routes --> Sync
67
+ Tools --> Ssh
68
+ Tools --> SFTP
69
+ Tools --> Sync
70
+ Tools --> Tunnel
71
+ Ssh -->|SSH2 Channel / Key or Password| SSHD
72
+ SFTP -->|SFTP Subsystem| FS
73
+ Sync -->|Pull / Push Differential| FS
74
+ Tunnel -->|Local Port Forwarding| AppPort
75
+
76
+ classDef default fill:#1e1e2e,stroke:#6366f1,stroke-width:1px,color:#cdd6f4;
77
+ classDef accent fill:#313244,stroke:#a6e3a1,stroke-width:2px,color:#a6e3a1;
78
+ class DSH,RemoteNode accent;
79
+ ```
80
+
81
+ ---
82
+
83
+ ## ✨ Full Feature Breakdown
84
+
85
+ ### 1. `SshService` — High-Performance Connection Pool & Authentication
86
+ - **Connection Pooling**: Maintains reusable, authenticated SSH2 client sessions keyed by `host:port:username`.
87
+ - **Dual Authentication Modes**:
88
+ - **SSH Private Key**: Path to local key (`~/.ssh/id_ed25519`), raw PEM string, and optional passphrase decryption.
89
+ - **Password Authentication**: Direct secure password authentication.
90
+ - **Diagnostic Health Probing**: Built-in `testConnection` executes latency measurements (ping in milliseconds) and detects remote OS architecture (`uname -srm`).
91
+ - **Resilience**: Heartbeat keep-alive packets prevent timeout disconnects from aggressive firewalls.
92
+
93
+ ### 2. `RemoteFsService` — Resilient SFTP Operations
94
+ - **Atomic File Writing**: Writes content to an ephemeral temporary file (`.tmp.<timestamp>.<hash>`) and renames it atomically upon complete upload, preventing partial or corrupted files.
95
+ - **Streaming Reads**: High-speed chunked stream reader supporting large files with selectable encoding.
96
+ - **Filesystem Primitives**: Provides `stat`, `listDir`, recursive `mkdir` (like `mkdir -p`), and recursive `remove` directly over the SFTP subsystem.
97
+
98
+ ### 3. `MirrorSyncService` — Conflict-Aware 3-Way Synchronization
99
+ - **State Manifest Tracking**: Maintains baseline SHA-256 hash digests in `.dsh-sync-manifest.json` for all tracked files.
100
+ - **Conflict Prevention**: Detects when both local and remote files have diverged since the last synchronization baseline, halting operations with a detailed conflict report rather than silently overwriting changes.
101
+ - **Selective Sync**: Supports directional `pull` (remote → local) and `push` (local → remote) with optional `force` override.
102
+ - **Dry-Run Inspection**: Allows agents or developers to preview affected files, additions, modifications, and deletions before applying changes.
103
+ - **Smart Exclusion**: Built-in default ignore patterns for version control, dependencies, and temporary files (`.git`, `node_modules`, `.dsh`, `.worktrees`, `.DS_Store`).
104
+
105
+ ### 4. `TunnelService` — Integrated SSH Port Forwarding
106
+ - **Local Port Forwarding**: Binds a local port on the DSH host and securely forwards all incoming TCP traffic over the encrypted SSH channel to any target port on the remote host (e.g. `127.0.0.1:8080` → remote `127.0.0.1:8080`).
107
+ - **Dynamic Lifecycle**: Start, stop, and enumerate active tunnels programmatically or via UI.
108
+
109
+ ### 5. `tools.js` — Ergonomic Agent Tools
110
+ Four orthogonal, high-leverage tools exposed directly to LLM agents:
111
+ - `remote_exec`: Execute shell commands on the remote workspace with custom working directory and exit code capture.
112
+ - `remote_fs`: Read, write, inspect, list, create directories, or delete files on the remote filesystem.
113
+ - `remote_sync`: Synchronize files between the local mirror and remote server with conflict awareness and dry-run mode.
114
+ - `remote_tunnel`: Start, stop, or list SSH port-forwarding tunnels.
115
+
116
+ ### 6. `client.js` — Native DSH Settings Card UI
117
+ - Designed strictly to DSH UX guidelines and styled after `dsh-clinebot`.
118
+ - **Segmented Auth Switcher**: Clean tabbed toggle between Private Key and Password authentication.
119
+ - **Remote Directory Browser Modal**: Interactive remote file browser with breadcrumb navigation and one-click path selection.
120
+ - **Connection Diagnostic Badge**: Real-time ping testing with visual latency indicators and remote OS display.
121
+ - **Action Triggers**: Quick buttons for directional synchronization and tunnel monitoring.
122
+
123
+ ---
124
+
125
+ ## 📦 Installation
126
+
127
+ Install into your DSH `web` profile:
128
+
129
+ ```bash
130
+ dsh plugin --profile web add @goodandready/dsh-remote-workspace
131
+ ```
132
+
133
+ Or install using the DSH CLI:
134
+
135
+ ```bash
136
+ dsh plugin add @goodandready/dsh-remote-workspace
137
+ ```
138
+
139
+ ---
140
+
141
+ ## ⚙️ Configuration Reference
142
+
143
+ Configuration can be managed either via the Web UI Settings card or defined in your DSH configuration files (`settings.yaml` / Cordis config):
144
+
145
+ ```yaml
146
+ dsh-remote-workspace:
147
+ activeProfileId: "prod-cloud-gpu"
148
+ profiles:
149
+ - id: "prod-cloud-gpu"
150
+ name: "Cloud GPU VM"
151
+ host: "remote.example.com"
152
+ port: 22
153
+ username: "deploy"
154
+ authType: "key" # "key" or "password"
155
+ privateKeyPath: "/home/user/.ssh/id_ed25519"
156
+ passphrase: ""
157
+ password: ""
158
+ remoteWorkspace: "/var/www/my-project"
159
+ localMirrorPath: "/home/user/projects/my-project"
160
+ ```
161
+
162
+ ### Parameters Table
163
+
164
+ | Parameter | Type | Default | Description |
165
+ |---|---|---|---|
166
+ | `profiles` | `Array<Profile>` | `[]` | List of configured remote server profiles. |
167
+ | `activeProfileId` | `string` | `""` | ID of the currently active remote host profile. |
168
+ | `profile.id` | `string` | `""` | Unique identifier for the profile. |
169
+ | `profile.name` | `string` | `""` | Human-readable label displayed in UI. |
170
+ | `profile.host` | `string` | `""` | Hostname, FQDN, or IP address of the remote host. |
171
+ | `profile.port` | `number` | `22` | Remote SSH port. |
172
+ | `profile.username` | `string` | `""` | SSH login username. |
173
+ | `profile.authType` | `string` | `"key"` | Authentication method: `"key"` or `"password"`. |
174
+ | `profile.privateKeyPath`| `string` | `""` | Path to local OpenSSH private key file. |
175
+ | `profile.privateKey` | `string` | `""` | Raw PEM/OpenSSH private key content (alternative to path). |
176
+ | `profile.passphrase` | `string` | `""` | Passphrase for encrypted private keys. |
177
+ | `profile.password` | `string` | `""` | Password for password-based authentication. |
178
+ | `profile.remoteWorkspace` | `string` | `""` | Base directory of the project on the remote machine. |
179
+ | `profile.localMirrorPath` | `string` | `""` | Local directory for mirror synchronization. |
180
+
181
+ ---
182
+
183
+ ## 🔌 Model Tools Reference
184
+
185
+ ### `remote_exec`
186
+ Executes a bash or shell command on the active remote host.
187
+ - **Parameters**:
188
+ - `command` (`string`, required): Shell command line to execute.
189
+ - `cwd` (`string`, optional): Working directory on remote host. Defaults to `remoteWorkspace`.
190
+ - **Returns**: `{ exitCode: number, stdout: string, stderr: string }`
191
+
192
+ ### `remote_fs`
193
+ Performs filesystem operations over SFTP.
194
+ - **Parameters**:
195
+ - `action` (`string`, required): One of `"read"`, `"write"`, `"stat"`, `"list"`, `"mkdir"`, `"remove"`.
196
+ - `path` (`string`, required): Target remote path (absolute or relative to workspace).
197
+ - `content` (`string`, optional): Required for `"write"` action.
198
+ - `recursive` (`boolean`, optional): Recursive flag for `"remove"` action.
199
+ - **Returns**: Result object depending on action (`{ content }`, `{ stat }`, `{ entries }`, `{ ok: true }`).
200
+
201
+ ### `remote_sync`
202
+ Runs 3-way conflict-aware synchronization between local and remote directories.
203
+ - **Parameters**:
204
+ - `direction` (`string`, required): `"pull"` (remote → local) or `"push"` (local → remote).
205
+ - `force` (`boolean`, optional): Overwrite conflicts if true.
206
+ - `dryRun` (`boolean`, optional): Simulate changes without writing to disk.
207
+ - **Returns**: Sync summary object with applied actions, changed files, and any detected conflicts.
208
+
209
+ ### `remote_tunnel`
210
+ Manages SSH local port forwarding tunnels.
211
+ - **Parameters**:
212
+ - `action` (`string`, required): `"start"`, `"stop"`, or `"list"`.
213
+ - `localPort` (`number`, optional): Local port to bind (for `"start"`).
214
+ - `remotePort` (`number`, optional): Remote destination port (for `"start"`).
215
+ - `tunnelId` (`string`, optional): Identifier of the tunnel to terminate (for `"stop"`).
216
+ - **Returns**: `{ tunnelId, localPort, remotePort }` or `{ tunnels: [...] }` or `{ success: boolean }`.
217
+
218
+ ---
219
+
220
+ ## 🌐 HTTP API Routes Reference
221
+
222
+ All endpoints are hosted under `/dsh-remote-workspace`:
223
+
224
+ | Method | Route | Description | Request Body |
225
+ |---|---|---|---|
226
+ | `GET` | `/dsh-remote-workspace/state` | Returns profiles, active profile ID, and active tunnels. | — |
227
+ | `POST` | `/dsh-remote-workspace/profiles/save` | Create or update a profile. | Profile JSON object |
228
+ | `POST` | `/dsh-remote-workspace/profiles/delete` | Delete a profile by ID. | `{ id: string }` |
229
+ | `POST` | `/dsh-remote-workspace/profiles/active` | Set active profile. | `{ id: string }` |
230
+ | `POST` | `/dsh-remote-workspace/test` | Test SSH connectivity and latency. | Profile JSON object |
231
+ | `POST` | `/dsh-remote-workspace/browse` | List directory contents for remote browser modal. | `{ profile: object, path: string }` |
232
+ | `POST` | `/dsh-remote-workspace/sync` | Trigger manual pull or push synchronization. | `{ direction: "pull" \| "push", dryRun?: boolean, force?: boolean }` |
233
+
234
+ ---
235
+
236
+ ## 📄 License
237
+
238
+ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
package/README.ru.md ADDED
@@ -0,0 +1,238 @@
1
+ # 📦 @goodandready/dsh-remote-workspace
2
+
3
+ <div align="center">
4
+
5
+ <h3>Корпоративный плагин удалённой разработки для DeepSeek Harness: SSH, SFTP-синхронизация и туннелирование</h3>
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/@goodandready/dsh-remote-workspace"><img src="https://img.shields.io/npm/v/@goodandready/dsh-remote-workspace.svg?style=for-the-badge&color=6366f1&labelColor=1e1b4b" alt="npm version"></a>
9
+ <a href="LICENSE"><img src="https://img.shields.io/github/license/GooDAnDReaDY/dsh-remote-workspace.svg?style=for-the-badge&color=10b981&labelColor=064e3b" alt="license"></a>
10
+ <a href="https://github.com/topics/dsh-plugin"><img src="https://img.shields.io/badge/DSH-Plugin-8b5cf6.svg?style=for-the-badge&labelColor=2e1065" alt="DSH Plugin"></a>
11
+ <a href="https://nodejs.org"><img src="https://img.shields.io/badge/Node-20%2B-f59e0b.svg?style=for-the-badge&labelColor=451a03" alt="Node version"></a>
12
+ </p>
13
+
14
+ <!-- Обязательная кнопка перехода на витрину всех проектов -->
15
+ <p align="center">
16
+ <a href="https://goodandready.app/"><img src="https://img.shields.io/badge/Все_проекты_автора-goodandready.app-ff4500.svg?style=for-the-badge&logo=rocket&logoColor=white&labelColor=1a1a2e" alt="Все проекты автора"></a>
17
+ </p>
18
+
19
+ <p align="center">
20
+ <a href="README.md"><b>🇬🇧 English</b></a> •
21
+ <a href="README.ru.md"><b>🇷🇺 Русский</b></a> •
22
+ <a href="README.zh.md"><b>🇨🇳 中文说明</b></a>
23
+ </p>
24
+
25
+ </div>
26
+
27
+ ---
28
+
29
+ ## ⚡ Обзор и решаемая проблема
30
+
31
+ В современной программной инженерии и агентных сценариях автономные AI-агенты платформы **DeepSeek Harness (DSH)** регулярно сталкиваются с необходимостью вести разработку на удалённых серверах: мощных GPU-нодах, облачных виртуальных машинах, staging-контурах и контейнерных кластерах.
32
+
33
+ Без плагина `@goodandready/dsh-remote-workspace` возникают фундаментальные ограничения:
34
+ 1. **Замкнутость на локальной машине**: Все стандартные операции DSH и инструменты агента исполняются строго локально, там где физически запущен процесс DSH.
35
+ 2. **Ненадёжность самодельных скриптов**: Прямой вызов SSH/SCP через системные утилиты не имеет пула соединений, рвёт сессии при задержках сети и создаёт избыточный оверхед на постоянные рукопожатия.
36
+ 3. **Риск затирания кода и повреждения файлов**: Обычное копирование файлов поверх существующих не отслеживает одновременные изменения и может повредить файл при разрыве соединения в момент записи.
37
+ 4. **Изолированность портов**: Чтобы получить доступ к удалённому веб-серверу, базе данных или тестовому сервису, разработчику приходится вручную настраивать сторонние SSH-туннели.
38
+
39
+ `@goodandready/dsh-remote-workspace` решает эти задачи на уровне экосистемы Cordis: он добавляет высокопроизводительный пул соединений SSH2, потоковую работу с SFTP с атомарной защитой записи, 3-стороннюю синхронизацию с контролем конфликтов по SHA-256, динамический проброс портов и нативную карточку настроек в Web UI в стиле `dsh-clinebot`.
40
+
41
+ ---
42
+
43
+ ## 🏗️ Архитектура
44
+
45
+ ```mermaid
46
+ graph LR
47
+ subgraph DSH["DeepSeek Harness (Контекст Cordis)"]
48
+ UI["Web UI Карточка настроек<br/>(стиль dsh-clinebot)"]
49
+ Routes["REST API Маршруты<br/>(/state, /browse, /test, /sync)"]
50
+ Tools["Инструменты агента<br/>(remote_exec, remote_fs, sync, tunnel)"]
51
+ Ssh["SshService<br/>(Пул SSH2 и Keepalive)"]
52
+ SFTP["RemoteFsService<br/>(Атомарный SFTP-поток)"]
53
+ Sync["MirrorSyncService<br/>(3-сторонний движок SHA-256)"]
54
+ Tunnel["TunnelService<br/>(Проброс портов)"]
55
+ end
56
+
57
+ subgraph RemoteNode["Удалённый сервер (Облачный VM / GPU Нода)"]
58
+ SSHD["SSH Сервер (:22)"]
59
+ FS["Файловая система хоста"]
60
+ AppPort["Сервис / Dev-сервер"]
61
+ end
62
+
63
+ UI -->|REST API| Routes
64
+ Routes --> Ssh
65
+ Routes --> SFTP
66
+ Routes --> Sync
67
+ Tools --> Ssh
68
+ Tools --> SFTP
69
+ Tools --> Sync
70
+ Tools --> Tunnel
71
+ Ssh -->|SSH2-канал / Ключ или Пароль| SSHD
72
+ SFTP -->|SFTP-подсистема| FS
73
+ Sync -->|Дифференциальный Pull / Push| FS
74
+ Tunnel -->|Локальный проброс портов| AppPort
75
+
76
+ classDef default fill:#1e1e2e,stroke:#6366f1,stroke-width:1px,color:#cdd6f4;
77
+ classDef accent fill:#313244,stroke:#a6e3a1,stroke-width:2px,color:#a6e3a1;
78
+ class DSH,RemoteNode accent;
79
+ ```
80
+
81
+ ---
82
+
83
+ ## ✨ Исчерпывающий разбор возможностей
84
+
85
+ ### 1. `SshService` — Пул соединений и универсальная аутентификация
86
+ - **Пул соединений**: Поддерживает постоянные авторизованные сессии SSH2, индексированные по `host:port:username`.
87
+ - **Два метода аутентификации**:
88
+ - **SSH-ключ (Private Key)**: Поддержка путей к локальным файлам (`~/.ssh/id_ed25519`), прямых PEM-строк и парольных фраз (passphrase).
89
+ - **Пароль (Password)**: Прямая безопасная аутентификация по логину и паролю.
90
+ - **Диагностический зонд**: Метод `testConnection` измеряет пинг в миллисекундах и определяет платформу удалённого хоста (`uname -srm`).
91
+ - **Защита от таймаутов**: Пакеты keep-alive предотвращают разрыв соединения корпоративными фаерволами.
92
+
93
+ ### 2. `RemoteFsService` — Отказоустойчивый SFTP
94
+ - **Атомарная запись файлов**: Загрузка производится во временный файл (`.tmp.<timestamp>.<hash>`) с последующим атомарным переименованием. Разрыв соединения не повреждает целевой файл.
95
+ - **Потоковое чтение**: Высокоскоростное чтение фрагментами без переполнения оперативной памяти.
96
+ - **Файловые операции**: Полный набор примитивов: `stat`, `listDir`, рекурсивное создание каталогов `mkdir -p` и рекурсивное удаление `remove`.
97
+
98
+ ### 3. `MirrorSyncService` — 3-сторонняя синхронизация с контролем конфликтов
99
+ - **Учёт контрольных сумм**: Сохраняет базовые слепки SHA-256 в файле `.dsh-sync-manifest.json`.
100
+ - **Обнаружение конфликтов**: Если файл изменился одновременно и на удалённом сервере, и в локальном зеркале с момента последней синхронизации, операция останавливается с подробным отчётом о конфликте.
101
+ - **Направленная синхронизация**: Поддерживает режимы `pull` (сервер → локально) и `push` (локально → сервер) с флагом принудительной перезаписи `force`.
102
+ - **Предпросмотр (Dry-Run)**: Возможность оценить состав изменяемых, добавляемых и удаляемых файлов до реального применения.
103
+ - **Умная фильтрация**: Игнорирование служебных каталогов и артефактов сборки (`.git`, `node_modules`, `.dsh`, `.worktrees`, `.DS_Store`).
104
+
105
+ ### 4. `TunnelService` — Встроенные SSH-туннели
106
+ - **Прямой проброс портов (Local Port Forwarding)**: Открывает локальный порт на машине с DSH и перенаправляет трафик через защищённый SSH-туннель к любому порту на удалённой машине (например, `127.0.0.1:8080` → удалённый `127.0.0.1:8080`).
107
+ - **Управление жизненным циклом**: Программный запуск, остановка и получение списка активных туннелей.
108
+
109
+ ### 5. `tools.js` — Инструменты для AI-моделей
110
+ 4 чётких ортогональных инструмента для агента:
111
+ - `remote_exec`: Выполнение bash-команд на удалённом сервере с фиксацией кода возврата, stdout и stderr.
112
+ - `remote_fs`: Операции чтения, записи, stat, листинга, создания директорий и удаления.
113
+ - `remote_sync`: Синхронизация между локальным зеркалом и сервером с отчётом о конфликтах и режимом dry-run.
114
+ - `remote_tunnel`: Управление SSH-туннелями (запуск, остановка, список).
115
+
116
+ ### 6. `client.js` — Нативный UI карточки настроек
117
+ - Полноценная интеграция в слот `settings.plugin.item` с ключом `dsh-remote-workspace`.
118
+ - **Сегментированный переключатель авторизации**: Удобное переключение между SSH-ключом и паролем.
119
+ - **Интерактивный браузер удалённых папок**: Модальное окно с навигацией по каталогам и выбором рабочей директории в один клик.
120
+ - **Индикатор статуса и задержки**: Проверка связи с отображением пинга и ОС удалённого узла.
121
+ - **Кнопки действий**: Быстрый запуск синхронизации и контроль туннелей прямо из настроек.
122
+
123
+ ---
124
+
125
+ ## 📦 Быстрая установка
126
+
127
+ Установка в профиль `web`:
128
+
129
+ ```bash
130
+ dsh plugin --profile web add @goodandready/dsh-remote-workspace
131
+ ```
132
+
133
+ Либо стандартная команда DSH:
134
+
135
+ ```bash
136
+ dsh plugin add @goodandready/dsh-remote-workspace
137
+ ```
138
+
139
+ ---
140
+
141
+ ## ⚙️ Полная таблица конфигурации
142
+
143
+ Настройки могут задаваться через карточку в Web UI или в файле конфигурации DSH (`settings.yaml`):
144
+
145
+ ```yaml
146
+ dsh-remote-workspace:
147
+ activeProfileId: "prod-cloud-gpu"
148
+ profiles:
149
+ - id: "prod-cloud-gpu"
150
+ name: "Cloud GPU VM"
151
+ host: "remote.example.com"
152
+ port: 22
153
+ username: "deploy"
154
+ authType: "key" # "key" или "password"
155
+ privateKeyPath: "/home/user/.ssh/id_ed25519"
156
+ passphrase: ""
157
+ password: ""
158
+ remoteWorkspace: "/var/www/my-project"
159
+ localMirrorPath: "/home/user/projects/my-project"
160
+ ```
161
+
162
+ ### Таблица параметров
163
+
164
+ | Параметр | Тип | По умолчанию | Описание |
165
+ |---|---|---|---|
166
+ | `profiles` | `Array<Profile>` | `[]` | Список настроенных профилей удалённых хостов. |
167
+ | `activeProfileId` | `string` | `""` | Идентификатор активного профиля. |
168
+ | `profile.id` | `string` | `""` | Уникальный ID профиля. |
169
+ | `profile.name` | `string` | `""` | Отображаемое имя в интерфейсе. |
170
+ | `profile.host` | `string` | `""` | Доменное имя или IP-адрес сервера. |
171
+ | `profile.port` | `number` | `22` | Порт SSH. |
172
+ | `profile.username` | `string` | `""` | Имя пользователя для входа. |
173
+ | `profile.authType` | `string` | `"key"` | Метод аутентификации: `"key"` или `"password"`. |
174
+ | `profile.privateKeyPath`| `string` | `""` | Путь к файлу приватного SSH-ключа. |
175
+ | `profile.privateKey` | `string` | `""` | Содержимое приватного ключа в формате PEM. |
176
+ | `profile.passphrase` | `string` | `""` | Пароль для расшифровки приватного ключа. |
177
+ | `profile.password` | `string` | `""` | Пароль для входа по логину и паролю. |
178
+ | `profile.remoteWorkspace` | `string` | `""` | Путь к каталогу проекта на удалённом сервере. |
179
+ | `profile.localMirrorPath` | `string` | `""` | Путь к локальному зеркалу проекта. |
180
+
181
+ ---
182
+
183
+ ## 🔌 Справочник инструментов агента
184
+
185
+ ### `remote_exec`
186
+ Выполняет shell-команду на активном удалённом сервере.
187
+ - **Параметры**:
188
+ - `command` (`string`, обязательно): Текст команды.
189
+ - `cwd` (`string`, опционально): Рабочий каталог на сервере (по умолчанию `remoteWorkspace`).
190
+ - **Возвращает**: `{ exitCode: number, stdout: string, stderr: string }`
191
+
192
+ ### `remote_fs`
193
+ Файловые операции через SFTP.
194
+ - **Параметры**:
195
+ - `action` (`string`, обязательно): `"read"`, `"write"`, `"stat"`, `"list"`, `"mkdir"`, `"remove"`.
196
+ - `path` (`string`, обязательно): Путь к файлу или каталогу.
197
+ - `content` (`string`, для записи): Содержимое файла при action `"write"`.
198
+ - `recursive` (`boolean`, для удаления): Рекурсивное удаление.
199
+ - **Возвращает**: Объект результата в зависимости от действия (`{ content }`, `{ stat }`, `{ entries }`, `{ ok: true }`).
200
+
201
+ ### `remote_sync`
202
+ 3-сторонняя синхронизация между локальным зеркалом и сервером.
203
+ - **Параметры**:
204
+ - `direction` (`string`, обязательно): `"pull"` (сервер → локально) или `"push"` (локально → сервер).
205
+ - `force` (`boolean`, опционально): Принудительная перезапись при конфликтах.
206
+ - `dryRun` (`boolean`, опционально): Симуляция изменений без записи на диск.
207
+ - **Возвращает**: Сводку синхронизации со списком изменённых файлов и конфликтов.
208
+
209
+ ### `remote_tunnel`
210
+ Управление SSH-туннелями проброса портов.
211
+ - **Параметры**:
212
+ - `action` (`string`, обязательно): `"start"`, `"stop"` или `"list"`.
213
+ - `localPort` (`number`, для start): Локальный порт прослушивания.
214
+ - `remotePort` (`number`, для start): Целевой удалённый порт.
215
+ - `tunnelId` (`string`, для stop): Идентификатор туннеля для закрытия.
216
+ - **Возвращает**: `{ tunnelId, localPort, remotePort }` или список туннелей `{ tunnels: [...] }`.
217
+
218
+ ---
219
+
220
+ ## 🌐 Справочник HTTP API
221
+
222
+ Все маршруты зарегистрированы с префиксом `/dsh-remote-workspace`:
223
+
224
+ | Метод | Путь | Описание | Тело запроса |
225
+ |---|---|---|---|
226
+ | `GET` | `/dsh-remote-workspace/state` | Возвращает профили, активный профиль и туннели. | — |
227
+ | `POST` | `/dsh-remote-workspace/profiles/save` | Создание или сохранение профиля. | JSON профиля |
228
+ | `POST` | `/dsh-remote-workspace/profiles/delete` | Удаление профиля. | `{ id: string }` |
229
+ | `POST` | `/dsh-remote-workspace/profiles/active` | Установка активного профиля. | `{ id: string }` |
230
+ | `POST` | `/dsh-remote-workspace/test` | Проверка связи и замер пинга. | JSON профиля |
231
+ | `POST` | `/dsh-remote-workspace/browse` | Получение списка файлов для браузера папок. | `{ profile: object, path: string }` |
232
+ | `POST` | `/dsh-remote-workspace/sync` | Запуск синхронизации. | `{ direction: "pull" \| "push", dryRun?: boolean, force?: boolean }` |
233
+
234
+ ---
235
+
236
+ ## 📄 Лицензия
237
+
238
+ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)