dsh-ssh-file 0.0.0-stage → 1.2.2
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 +21 -0
- package/README.md +73 -2
- package/cordis.patch.yml +4 -0
- package/icon.svg +7 -0
- package/lib/client.js +1364 -0
- package/lib/descriptors.js +63 -0
- package/lib/index.js +1235 -0
- package/lib/remote.js +9 -0
- package/lib/schemas.js +130 -0
- package/lib/typert.js +81 -0
- package/locale/en.json +4 -0
- package/locale/zh.json +4 -0
- package/package.json +77 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,1235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-remote-workspace — host half.
|
|
3
|
+
*
|
|
4
|
+
* Service-class plugin: saved SSH server profiles, SFTP directory browsing,
|
|
5
|
+
* DSH-workspace→remote-path bindings, and agent tools that operate on the
|
|
6
|
+
* binding of the current session (remote_list/read/write/mkdir/exec/bindings).
|
|
7
|
+
* Secrets never leave the host: passwords/keys are stored via the DSH
|
|
8
|
+
* credentials service, profiles and bindings via a storage domain.
|
|
9
|
+
*/
|
|
10
|
+
import { createRequire as __dshCreateRequire } from 'node:module';
|
|
11
|
+
const require = __dshCreateRequire(import.meta.url);
|
|
12
|
+
import { randomUUID } from 'node:crypto';
|
|
13
|
+
import { appendFileSync, mkdirSync } from 'node:fs';
|
|
14
|
+
import { mkdir as fsMkdir } from 'node:fs/promises';
|
|
15
|
+
import { homedir as osHomedir } from 'node:os';
|
|
16
|
+
import { PassThrough } from 'node:stream';
|
|
17
|
+
import { isAbsolute, posix, relative as hostRelative, join, sep } from 'node:path';
|
|
18
|
+
import { Service } from '@deepseek-ai/cordis';
|
|
19
|
+
import { credentialRef } from '@deepseek-ai/dsh-credentials';
|
|
20
|
+
import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
|
|
21
|
+
import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
|
|
22
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
23
|
+
import ssh2 from 'ssh2';
|
|
24
|
+
import { z as zod } from 'zod';
|
|
25
|
+
|
|
26
|
+
const PACKAGE = 'dsh-remote-workspace';
|
|
27
|
+
const NS = 'remoteWorkspace';
|
|
28
|
+
const CONNECT_TIMEOUT_MS = 20000;
|
|
29
|
+
const MAX_COMMAND_OUTPUT_BYTES = 64 * 1024;
|
|
30
|
+
const MAX_FILE_READ_BYTES = 256 * 1024;
|
|
31
|
+
const EXEC_DEFAULT_TIMEOUT_MS = 30000;
|
|
32
|
+
const EXEC_MAX_TIMEOUT_MS = 10 * 60 * 1000;
|
|
33
|
+
const MAX_EDITOR_READ_BYTES = 1024 * 1024;
|
|
34
|
+
|
|
35
|
+
/** Monotonic stand-in pid for SSH-backed terminal handles (display/telemetry only). */
|
|
36
|
+
let SSH_TERMINAL_FAKE_PID = 400000;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Terminal handle that satisfies the `subprocess.spawnTerminal` contract using
|
|
40
|
+
* an ssh2 shell channel. Consumed members of LocalTerminalHandle (verified
|
|
41
|
+
* against dsh-api-terminal-controller's BrowserTerminal): pid, running, done,
|
|
42
|
+
* output (async-iterable byte stream), write, resize, terminate,
|
|
43
|
+
* inspectActivity, inspectForeground, signalForeground.
|
|
44
|
+
*/
|
|
45
|
+
class SshTerminalHandle {
|
|
46
|
+
constructor(stream, onQuiescence) {
|
|
47
|
+
this.stream = stream;
|
|
48
|
+
this.pid = ++SSH_TERMINAL_FAKE_PID;
|
|
49
|
+
this.exited = false;
|
|
50
|
+
this.exitCode = undefined;
|
|
51
|
+
this.output = new PassThrough();
|
|
52
|
+
this.outcome = Promise.withResolvers();
|
|
53
|
+
this.done = this.outcome.promise;
|
|
54
|
+
this.cleanupDone = undefined;
|
|
55
|
+
this._onQuiescence = onQuiescence;
|
|
56
|
+
stream.on('data', (data) => {
|
|
57
|
+
try { this.output.write(Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8')); } catch { /* consumer gone */ }
|
|
58
|
+
});
|
|
59
|
+
stream.on('exit', (code) => { this.exitCode = typeof code === 'number' ? code : 0; });
|
|
60
|
+
const finish = () => {
|
|
61
|
+
if (this.exited) return;
|
|
62
|
+
this.exited = true;
|
|
63
|
+
try { this.output.end(); } catch { /* ignore */ }
|
|
64
|
+
this.outcome.resolve({ exitCode: this.exitCode ?? 0, signal: null });
|
|
65
|
+
try { this._onQuiescence?.(); } catch { /* ignore */ }
|
|
66
|
+
};
|
|
67
|
+
stream.on('close', finish);
|
|
68
|
+
stream.on('error', () => { if (this.exitCode === undefined) this.exitCode = 1; finish(); });
|
|
69
|
+
this.output.on('close', () => { try { stream.end(); } catch { /* ignore */ } });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
get running() {
|
|
73
|
+
return !this.exited;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async write(data) {
|
|
77
|
+
if (this.exited) throw new Error('terminal process has exited');
|
|
78
|
+
this.stream.write(data);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async resize(cols, rows) {
|
|
82
|
+
if (this.exited) throw new Error('terminal process has exited');
|
|
83
|
+
try { this.stream.setWindow(rows, cols, 0, 0); } catch { /* older ssh2 without setWindow */ }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** No local process tree exists for an SSH channel; activity stays "unknown". */
|
|
87
|
+
async inspectForeground() {
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async inspectActivity() {
|
|
92
|
+
return { state: this.exited ? 'idle' : 'unknown', revision: 0 };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async signalForeground(signalName) {
|
|
96
|
+
if (signalName === 'SIGINT') {
|
|
97
|
+
await this.write('\x03');
|
|
98
|
+
return this.pid;
|
|
99
|
+
}
|
|
100
|
+
throw new Error(`remote terminal does not support signal ${signalName}; close the terminal instead`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async terminate() {
|
|
104
|
+
if (this.cleanupDone !== undefined) return this.cleanupDone;
|
|
105
|
+
this.cleanupDone = (async () => {
|
|
106
|
+
try { this.stream.signal?.('KILL'); } catch { /* ignore */ }
|
|
107
|
+
try { this.stream.end(); } catch { /* ignore */ }
|
|
108
|
+
if (!this.exited) await Promise.race([this.done, new Promise((resolve) => setTimeout(resolve, 3000))]);
|
|
109
|
+
try { this.output.end(); } catch { /* ignore */ }
|
|
110
|
+
})();
|
|
111
|
+
return this.cleanupDone;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function fail(code, message) {
|
|
116
|
+
return { code, message };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// append-only debug trace so the agent can read Host-side ground truth itself
|
|
120
|
+
const DEBUG_LOG_DIR = join(osHomedir(), '.dsh', 'remote-workspace-logs');
|
|
121
|
+
const DEBUG_LOG_PATH = join(DEBUG_LOG_DIR, 'debug.log');
|
|
122
|
+
function debugLog(message) {
|
|
123
|
+
try {
|
|
124
|
+
mkdirSync(DEBUG_LOG_DIR, { recursive: true });
|
|
125
|
+
appendFileSync(DEBUG_LOG_PATH, `${new Date().toISOString()} ${message}\n`, 'utf8');
|
|
126
|
+
} catch { /* best effort */ }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ── domain ──────────────────────────────────────────────────────────────────
|
|
130
|
+
|
|
131
|
+
const profileRecordSchema = zod.object({
|
|
132
|
+
profileId: zod.string(),
|
|
133
|
+
name: zod.string(),
|
|
134
|
+
host: zod.string(),
|
|
135
|
+
port: zod.number(),
|
|
136
|
+
username: zod.string(),
|
|
137
|
+
authKind: zod.union([zod.literal('password'), zod.literal('key')]),
|
|
138
|
+
defaultProjectPath: zod.string().optional(),
|
|
139
|
+
createdAt: zod.string(),
|
|
140
|
+
updatedAt: zod.string(),
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
const bindingRecordSchema = zod.object({
|
|
144
|
+
workspacePath: zod.string(),
|
|
145
|
+
profileId: zod.string(),
|
|
146
|
+
remotePath: zod.string(),
|
|
147
|
+
autoConnect: zod.boolean().optional(),
|
|
148
|
+
createdAt: zod.string(),
|
|
149
|
+
updatedAt: zod.string(),
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
const storeDomainSpec = defineDomain({
|
|
153
|
+
name: 'remote_workspace_store',
|
|
154
|
+
version: 1,
|
|
155
|
+
tables: {
|
|
156
|
+
profiles: domainTable(profileRecordSchema),
|
|
157
|
+
bindings: domainTable(bindingRecordSchema),
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// ── remote path safety (same rules as the ssh-ops bindings this replaces) ──
|
|
162
|
+
|
|
163
|
+
function normalizeRemoteRoot(input) {
|
|
164
|
+
if (typeof input !== 'string') throw new Error('remote path must be a string');
|
|
165
|
+
if (/[\x00-\x1f\x7f]/.test(input)) throw new Error('remote path must not contain control characters');
|
|
166
|
+
const raw = input.trim();
|
|
167
|
+
if (raw.length === 0) throw new Error('remote path must not be empty');
|
|
168
|
+
if (!raw.startsWith('/')) throw new Error(`remote path must be absolute: ${JSON.stringify(raw)}`);
|
|
169
|
+
const normalized = posix.normalize(raw);
|
|
170
|
+
return normalized.length > 1 && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function isRemotePathInside(root, candidate) {
|
|
174
|
+
const base = normalizeRemoteRoot(root);
|
|
175
|
+
const target = normalizeRemoteRoot(candidate);
|
|
176
|
+
if (base === '/') return true;
|
|
177
|
+
return target === base || target.startsWith(`${base}/`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function resolveRemotePath(basePath, input) {
|
|
181
|
+
const base = normalizeRemoteRoot(basePath);
|
|
182
|
+
if (typeof input !== 'string' || input.trim().length === 0) throw new Error('path must not be empty');
|
|
183
|
+
if (/[\x00-\x1f\x7f]/.test(input)) throw new Error('path must not contain control characters');
|
|
184
|
+
const raw = input.trim();
|
|
185
|
+
const joined = raw.startsWith('/') ? raw : posix.join(base, raw);
|
|
186
|
+
const normalized = posix.normalize(joined);
|
|
187
|
+
if (!isRemotePathInside(base, normalized)) {
|
|
188
|
+
throw new Error(`path escapes the remote workspace root ${JSON.stringify(base)}: ${JSON.stringify(raw)}`);
|
|
189
|
+
}
|
|
190
|
+
return normalized;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function workspaceRelativePart(workspacePath, candidatePath) {
|
|
194
|
+
if (typeof workspacePath !== 'string' || typeof candidatePath !== 'string') return null;
|
|
195
|
+
const rel = hostRelative(workspacePath, candidatePath);
|
|
196
|
+
if (rel === '') return '';
|
|
197
|
+
if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return null;
|
|
198
|
+
return rel.split(sep).join('/');
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// ── credentials ─────────────────────────────────────────────────────────────
|
|
202
|
+
|
|
203
|
+
function safeFolderName(text) {
|
|
204
|
+
const cleaned = String(text || 'remote').replace(/[^\w.\-\u4e00-\u9fa5]+/g, '-').replace(/^-+|-+$/g, '');
|
|
205
|
+
return cleaned || 'remote';
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function profileCredentialRefs(profileId) { // credentialRef() requires a POSIX shell identifier — no slashes, no dashes
|
|
209
|
+
// beyond the identifier grammar. Follow the ssh-ops convention.
|
|
210
|
+
const stem = String(profileId).replaceAll('-', '').toUpperCase();
|
|
211
|
+
return {
|
|
212
|
+
password: `DSH_REMOTE_WORKSPACE_${stem}_PASSWORD`,
|
|
213
|
+
key: `DSH_REMOTE_WORKSPACE_${stem}_PRIVATE_KEY`,
|
|
214
|
+
passphrase: `DSH_REMOTE_WORKSPACE_${stem}_PASSPHRASE`,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ── service ─────────────────────────────────────────────────────────────────
|
|
219
|
+
|
|
220
|
+
const RemoteWorkspaceService = class extends TypertRemoteService {
|
|
221
|
+
static inject = ['tools', 'storageDomain', 'credentials', 'systemPrompt', 'agents'];
|
|
222
|
+
|
|
223
|
+
/** connectionId -> live ssh2 connection record */
|
|
224
|
+
connections = new Map();
|
|
225
|
+
profileTable = null;
|
|
226
|
+
bindingTable = null;
|
|
227
|
+
/** Live SSH-backed terminal handles created by the spawnTerminal reroute. */
|
|
228
|
+
sshTerminalHandles = new Set();
|
|
229
|
+
|
|
230
|
+
constructor(ctx) {
|
|
231
|
+
super(ctx, NS);
|
|
232
|
+
ctx.effect(() => () => {
|
|
233
|
+
for (const record of this.connections.values()) {
|
|
234
|
+
record.closing = true;
|
|
235
|
+
try { record.client?.end(); } catch { /* ignore */ }
|
|
236
|
+
}
|
|
237
|
+
this.connections.clear();
|
|
238
|
+
}, 'dsh-remote-workspace: cleanup');
|
|
239
|
+
this.registerTools(ctx);
|
|
240
|
+
this.registerPromptHint(ctx);
|
|
241
|
+
this.installTerminalReroute(ctx);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Tell each bound session's agent that file/command work belongs on the server. */
|
|
245
|
+
registerPromptHint(ctx) {
|
|
246
|
+
ctx.inject(['systemPrompt'], (promptCtx) => {
|
|
247
|
+
promptCtx.effect(() => promptCtx.systemPrompt.context({
|
|
248
|
+
name: 'remote-workspace:binding',
|
|
249
|
+
order: promptCtx.systemPrompt.getContextOrder('WORKING_DIRECTORY') + 1,
|
|
250
|
+
required: false,
|
|
251
|
+
interpolate: false,
|
|
252
|
+
text: (context) => {
|
|
253
|
+
try { return this.remoteWorkspacePromptFor(context?.agent?.session); }
|
|
254
|
+
catch { return ''; }
|
|
255
|
+
},
|
|
256
|
+
}), 'remote-workspace: binding prompt');
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
remoteWorkspacePromptFor(session) {
|
|
261
|
+
const directory = this.sessionDirectory(session);
|
|
262
|
+
const binding = this.bindingFor(directory);
|
|
263
|
+
if (binding === undefined) return '';
|
|
264
|
+
const pub = this.bindingPublic(binding.record);
|
|
265
|
+
const subdirectory = binding.relative ? `(会话子目录:/${binding.relative})` : '';
|
|
266
|
+
return [
|
|
267
|
+
`当前会话的工作区已绑定远程服务器 ${pub.username ? pub.username + '@' : ''}${pub.host}:${pub.port}(SSH 资源「${pub.profileName}」)。`,
|
|
268
|
+
`远程根目录:${pub.remotePath}${subdirectory}。`,
|
|
269
|
+
'读写远程文件、列出远程目录、创建目录、执行远程命令,请使用 remote_read / remote_write / remote_list / remote_mkdir / remote_exec 工具——它们直接作用于远程服务器。',
|
|
270
|
+
'本地工作区文件夹只是绑定锚点,不保存远程文件的副本;不要试图通过本地文件工具修改远程内容。',
|
|
271
|
+
].join('\n');
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async [Service.init]() {
|
|
275
|
+
const domain = await this.ctx.storageDomain.open(storeDomainSpec);
|
|
276
|
+
this.profileTable = domain.table('profiles');
|
|
277
|
+
this.bindingTable = domain.table('bindings');
|
|
278
|
+
this.ctx.effect(() => () => domain.close(), 'dsh-remote-workspace: domain close');
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
requireProfileTable() {
|
|
282
|
+
if (this.profileTable === null) throw new Error('storage is not ready');
|
|
283
|
+
return this.profileTable;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
requireBindingTable() {
|
|
287
|
+
if (this.bindingTable === null) throw new Error('storage is not ready');
|
|
288
|
+
return this.bindingTable;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// ── session directory + binding lookup ──────────────────────────────────
|
|
292
|
+
|
|
293
|
+
/** The committed working directory of one Agent Session. */
|
|
294
|
+
sessionDirectory(session) {
|
|
295
|
+
if (session === undefined || session === null) return undefined;
|
|
296
|
+
const directories = this.ctx.get('workingDirectory');
|
|
297
|
+
if (typeof directories?.get === 'function') {
|
|
298
|
+
try {
|
|
299
|
+
const current = directories.get(session);
|
|
300
|
+
if (typeof current === 'string' && current !== '') return current;
|
|
301
|
+
} catch { /* fall through */ }
|
|
302
|
+
}
|
|
303
|
+
return typeof session.header?.cwd === 'string' && session.header.cwd !== '' ? session.header.cwd : undefined;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** The binding that governs one host directory, deepest workspace wins. */
|
|
307
|
+
bindingFor(directory) {
|
|
308
|
+
if (typeof directory !== 'string') return undefined;
|
|
309
|
+
let best;
|
|
310
|
+
for (const record of this.listBindings()) {
|
|
311
|
+
const relative = workspaceRelativePart(record.workspacePath, directory);
|
|
312
|
+
if (relative === null) continue;
|
|
313
|
+
if (best === undefined || record.workspacePath.length > best.record.workspacePath.length) {
|
|
314
|
+
best = { record, relative };
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return best;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
listBindings() {
|
|
321
|
+
return [...this.requireBindingTable().entries()]
|
|
322
|
+
.map(([workspacePath, record]) => ({ ...record, workspacePath }))
|
|
323
|
+
.sort((left, right) => left.workspacePath.localeCompare(right.workspacePath));
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
async credentialConfiguredFor(profile) {
|
|
327
|
+
const refs = profileCredentialRefs(profile.profileId);
|
|
328
|
+
try {
|
|
329
|
+
const ref = credentialRef(profile.authKind === 'password' ? refs.password : refs.key);
|
|
330
|
+
const info = await this.ctx.credentials.describe(ref);
|
|
331
|
+
return info?.configured === true;
|
|
332
|
+
} catch {
|
|
333
|
+
return false;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
profilePublic(record, connectedProfileIds, credentialConfigured) {
|
|
338
|
+
const value = {
|
|
339
|
+
profileId: record.profileId,
|
|
340
|
+
name: record.name,
|
|
341
|
+
host: record.host,
|
|
342
|
+
port: record.port,
|
|
343
|
+
username: record.username,
|
|
344
|
+
authKind: record.authKind,
|
|
345
|
+
connected: connectedProfileIds.has(record.profileId),
|
|
346
|
+
...(credentialConfigured === undefined ? {} : { credentialConfigured }),
|
|
347
|
+
};
|
|
348
|
+
if (record.defaultProjectPath !== undefined) value.defaultProjectPath = record.defaultProjectPath;
|
|
349
|
+
return value;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
bindingPublic(record) {
|
|
353
|
+
const profile = this.requireProfileTable().get(record.profileId);
|
|
354
|
+
const connectedProfileIds = new Set(
|
|
355
|
+
[...this.connections.values()].map((connection) => connection.profileId).filter(Boolean),
|
|
356
|
+
);
|
|
357
|
+
return {
|
|
358
|
+
workspacePath: record.workspacePath,
|
|
359
|
+
remotePath: record.remotePath,
|
|
360
|
+
profileId: record.profileId,
|
|
361
|
+
profileName: profile?.name ?? '',
|
|
362
|
+
host: profile?.host ?? '',
|
|
363
|
+
port: profile?.port ?? 22,
|
|
364
|
+
username: profile?.username ?? '',
|
|
365
|
+
autoConnect: record.autoConnect === true,
|
|
366
|
+
connected: connectedProfileIds.has(record.profileId),
|
|
367
|
+
...(profile === undefined ? { missingResource: true } : {}),
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// ── wire methods: profiles ──────────────────────────────────────────────
|
|
372
|
+
|
|
373
|
+
async profileList() {
|
|
374
|
+
try {
|
|
375
|
+
const connectedProfileIds = new Set(
|
|
376
|
+
[...this.connections.values()].map((connection) => connection.profileId).filter(Boolean),
|
|
377
|
+
);
|
|
378
|
+
const profiles = await Promise.all([...this.requireProfileTable().entries()]
|
|
379
|
+
.map(([, record]) => record)
|
|
380
|
+
.sort((left, right) => left.name.localeCompare(right.name))
|
|
381
|
+
.map(async (record) => this.profilePublic(
|
|
382
|
+
record,
|
|
383
|
+
connectedProfileIds,
|
|
384
|
+
await this.credentialConfiguredFor(record),
|
|
385
|
+
)));
|
|
386
|
+
debugLog(`profileList → ${JSON.stringify({ ok: true, count: profiles.length })}`);
|
|
387
|
+
return { ok: true, value: { profiles } };
|
|
388
|
+
} catch (error) {
|
|
389
|
+
debugLog(`profileList FAILED → ${error.message}`);
|
|
390
|
+
return { ok: false, error: fail('profile-list-failed', error.message) };
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
async profileSave(request) {
|
|
395
|
+
try {
|
|
396
|
+
const table = this.requireProfileTable();
|
|
397
|
+
const now = new Date().toISOString();
|
|
398
|
+
const profileId = request.profileId ?? randomUUID();
|
|
399
|
+
const previous = request.profileId === undefined ? undefined : table.get(request.profileId);
|
|
400
|
+
if (request.profileId !== undefined && previous === undefined) {
|
|
401
|
+
return { ok: false, error: fail('no-profile', `SSH server "${request.profileId}" does not exist`) };
|
|
402
|
+
}
|
|
403
|
+
const record = {
|
|
404
|
+
...(previous ?? {}),
|
|
405
|
+
profileId,
|
|
406
|
+
name: request.name,
|
|
407
|
+
host: request.host,
|
|
408
|
+
port: request.port ?? 22,
|
|
409
|
+
username: request.username,
|
|
410
|
+
authKind: request.authKind,
|
|
411
|
+
...(request.defaultProjectPath === undefined ? {} : { defaultProjectPath: request.defaultProjectPath }),
|
|
412
|
+
...(previous === undefined ? { createdAt: now } : {}),
|
|
413
|
+
updatedAt: now,
|
|
414
|
+
};
|
|
415
|
+
await table.put(profileId, record);
|
|
416
|
+
// Secrets: write only when provided, so editing a profile without
|
|
417
|
+
// retyping the password/key keeps the stored credential.
|
|
418
|
+
const refs = profileCredentialRefs(profileId);
|
|
419
|
+
if (request.password !== undefined && request.password !== '') {
|
|
420
|
+
await this.ctx.credentials.set(credentialRef(refs.password), request.password);
|
|
421
|
+
}
|
|
422
|
+
if (request.privateKey !== undefined && request.privateKey !== '') {
|
|
423
|
+
await this.ctx.credentials.set(credentialRef(refs.key), request.privateKey);
|
|
424
|
+
}
|
|
425
|
+
if (request.passphrase !== undefined && request.passphrase !== '') {
|
|
426
|
+
await this.ctx.credentials.set(credentialRef(refs.passphrase), request.passphrase);
|
|
427
|
+
}
|
|
428
|
+
const connectedProfileIds2 = new Set(
|
|
429
|
+
[...this.connections.values()].map((connection) => connection.profileId).filter(Boolean),
|
|
430
|
+
);
|
|
431
|
+
return { ok: true, value: { profile: this.profilePublic(record, connectedProfileIds2) } };
|
|
432
|
+
} catch (error) {
|
|
433
|
+
return { ok: false, error: fail('profile-save-failed', error.message) };
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
async profileDelete(request) {
|
|
438
|
+
try {
|
|
439
|
+
const table = this.requireProfileTable();
|
|
440
|
+
const record = table.get(request.profileId);
|
|
441
|
+
if (record === undefined) return { ok: false, error: fail('no-profile', `SSH server "${request.profileId}" does not exist`) };
|
|
442
|
+
await table.delete(request.profileId);
|
|
443
|
+
const refs = profileCredentialRefs(request.profileId);
|
|
444
|
+
for (const ref of Object.values(refs)) {
|
|
445
|
+
await this.ctx.credentials.unset(credentialRef(ref)).catch(() => {});
|
|
446
|
+
}
|
|
447
|
+
// Drop live connections for this profile.
|
|
448
|
+
for (const connection of [...this.connections.values()]) {
|
|
449
|
+
if (connection.profileId === request.profileId) await this.killConnection(connection.id);
|
|
450
|
+
}
|
|
451
|
+
return { ok: true, value: { deleted: true } };
|
|
452
|
+
} catch (error) {
|
|
453
|
+
return { ok: false, error: fail('profile-delete-failed', error.message) };
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async profileConnect(request) {
|
|
458
|
+
try {
|
|
459
|
+
const record = this.requireProfileTable().get(request.profileId);
|
|
460
|
+
if (record === undefined) return { ok: false, error: fail('no-profile', `SSH server "${request.profileId}" does not exist`) };
|
|
461
|
+
if (request.reuseExisting !== false) {
|
|
462
|
+
const reusable = this.findReusableConnection(request.profileId);
|
|
463
|
+
if (reusable !== null) {
|
|
464
|
+
const value = { connectionId: reusable.id, host: reusable.host, port: reusable.port, username: reusable.username };
|
|
465
|
+
if (reusable.name !== undefined) value.name = reusable.name;
|
|
466
|
+
return { ok: true, value };
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
const refs = profileCredentialRefs(request.profileId);
|
|
470
|
+
const config = {
|
|
471
|
+
host: record.host,
|
|
472
|
+
port: record.port,
|
|
473
|
+
username: record.username,
|
|
474
|
+
readyTimeout: CONNECT_TIMEOUT_MS,
|
|
475
|
+
keepaliveInterval: 15000,
|
|
476
|
+
keepaliveCountMax: 4,
|
|
477
|
+
};
|
|
478
|
+
if (record.authKind === 'password') {
|
|
479
|
+
const secret = await this.ctx.credentials.resolve(credentialRef(refs.password));
|
|
480
|
+
if (secret === undefined) {
|
|
481
|
+
return { ok: false, error: fail('credential-missing', `SSH server "${record.name}" has no saved password`) };
|
|
482
|
+
}
|
|
483
|
+
config.password = secret.value;
|
|
484
|
+
} else {
|
|
485
|
+
const key = await this.ctx.credentials.resolve(credentialRef(refs.key));
|
|
486
|
+
if (key === undefined) {
|
|
487
|
+
return { ok: false, error: fail('credential-missing', `SSH server "${record.name}" has no saved private key`) };
|
|
488
|
+
}
|
|
489
|
+
config.privateKey = key.value;
|
|
490
|
+
const passphrase = await this.ctx.credentials.resolve(credentialRef(refs.passphrase));
|
|
491
|
+
if (passphrase !== undefined) config.passphrase = passphrase.value;
|
|
492
|
+
}
|
|
493
|
+
const connection = await this.openSshConnection({
|
|
494
|
+
name: record.name,
|
|
495
|
+
host: config.host,
|
|
496
|
+
port: config.port,
|
|
497
|
+
username: config.username,
|
|
498
|
+
config,
|
|
499
|
+
profileId: request.profileId,
|
|
500
|
+
});
|
|
501
|
+
const value = { connectionId: connection.id, host: connection.host, port: connection.port, username: connection.username };
|
|
502
|
+
if (record.name !== undefined) value.name = record.name;
|
|
503
|
+
return { ok: true, value };
|
|
504
|
+
} catch (error) {
|
|
505
|
+
return { ok: false, error: fail('profile-connect-failed', error?.message ?? String(error)) };
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
async profileDisconnect(request) {
|
|
510
|
+
try {
|
|
511
|
+
const targets = [...this.connections.values()].filter((connection) => connection.profileId === request.profileId);
|
|
512
|
+
for (const connection of targets) await this.killConnection(connection.id);
|
|
513
|
+
return { ok: true, value: { disconnected: targets.length } };
|
|
514
|
+
} catch (error) {
|
|
515
|
+
return { ok: false, error: fail('profile-disconnect-failed', error.message) };
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
findReusableConnection(profileId) {
|
|
520
|
+
for (const connection of this.connections.values()) {
|
|
521
|
+
if (connection.profileId === profileId && !connection.dead && !connection.closing) return connection;
|
|
522
|
+
}
|
|
523
|
+
return null;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
async openSshConnection({ name, host, port, username, config, profileId }) {
|
|
527
|
+
const id = randomUUID();
|
|
528
|
+
const client = await new Promise((resolve, reject) => {
|
|
529
|
+
const ssh = new ssh2.Client();
|
|
530
|
+
const timer = setTimeout(() => {
|
|
531
|
+
try { ssh.end(); } catch { /* ignore */ }
|
|
532
|
+
reject(new Error(`connect to ${host}:${port} timed out`));
|
|
533
|
+
}, CONNECT_TIMEOUT_MS + 2000);
|
|
534
|
+
ssh.on('ready', () => { clearTimeout(timer); resolve(ssh); });
|
|
535
|
+
ssh.on('error', (error) => { clearTimeout(timer); reject(error); });
|
|
536
|
+
try {
|
|
537
|
+
ssh.connect(config);
|
|
538
|
+
} catch (error) {
|
|
539
|
+
clearTimeout(timer);
|
|
540
|
+
reject(error);
|
|
541
|
+
}
|
|
542
|
+
});
|
|
543
|
+
const record = {
|
|
544
|
+
id,
|
|
545
|
+
client,
|
|
546
|
+
host,
|
|
547
|
+
port,
|
|
548
|
+
username,
|
|
549
|
+
name,
|
|
550
|
+
profileId,
|
|
551
|
+
sftp: null,
|
|
552
|
+
dead: false,
|
|
553
|
+
closing: false,
|
|
554
|
+
};
|
|
555
|
+
client.on('end', () => { record.dead = true; });
|
|
556
|
+
client.on('close', () => { record.dead = true; });
|
|
557
|
+
client.on('error', () => { record.dead = true; });
|
|
558
|
+
this.connections.set(id, record);
|
|
559
|
+
return record;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async killConnection(connectionId) {
|
|
563
|
+
const record = this.connections.get(connectionId);
|
|
564
|
+
if (record === undefined) return;
|
|
565
|
+
record.closing = true;
|
|
566
|
+
try { record.client?.end(); } catch { /* ignore */ }
|
|
567
|
+
this.connections.delete(connectionId);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
resolveConnection(connectionId) {
|
|
571
|
+
const record = this.connections.get(connectionId);
|
|
572
|
+
if (record === undefined) return { ok: false, error: fail('no-connection', `connection "${connectionId}" does not exist (connect first)`) };
|
|
573
|
+
if (record.dead || record.closing) {
|
|
574
|
+
this.connections.delete(connectionId);
|
|
575
|
+
return { ok: false, error: fail('connection-lost', `connection "${connectionId}" is no longer alive; reconnect`) };
|
|
576
|
+
}
|
|
577
|
+
return { ok: true, connection: record };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
async requireSftp(connection) {
|
|
581
|
+
if (connection.sftp !== null && !connection.sftpDead) return { ok: true, sftp: connection.sftp };
|
|
582
|
+
try {
|
|
583
|
+
const sftp = await new Promise((resolve, reject) => {
|
|
584
|
+
connection.client.sftp((error, s) => (error ? reject(error) : resolve(s)));
|
|
585
|
+
});
|
|
586
|
+
connection.sftp = sftp;
|
|
587
|
+
connection.sftpDead = false;
|
|
588
|
+
sftp.on('close', () => { connection.sftpDead = true; });
|
|
589
|
+
return { ok: true, sftp };
|
|
590
|
+
} catch (error) {
|
|
591
|
+
return { ok: false, error: fail('sftp-failed', `could not open SFTP subsystem: ${error.message}`) };
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
sftpCall(sftp, run) {
|
|
596
|
+
return new Promise((resolve, reject) => run((error, value) => (error ? reject(error) : resolve(value))));
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// ── wire methods: sftp ──────────────────────────────────────────────────
|
|
600
|
+
|
|
601
|
+
async sftpList(request) {
|
|
602
|
+
const selected = this.resolveConnection(request.connectionId);
|
|
603
|
+
if (!selected.ok) return selected;
|
|
604
|
+
const sftp = await this.requireSftp(selected.connection);
|
|
605
|
+
if (!sftp.ok) return sftp;
|
|
606
|
+
const remotePath = request.path || '/';
|
|
607
|
+
try {
|
|
608
|
+
const entries = await this.sftpCall(sftp.sftp, (cb) => sftp.sftp.readdir(remotePath, cb));
|
|
609
|
+
const items = await Promise.all(entries.map(async (entry) => {
|
|
610
|
+
const kind = entry.attrs.mode & 0o170000;
|
|
611
|
+
let isDirectory = kind === 0o040000;
|
|
612
|
+
if (kind === 0o120000) {
|
|
613
|
+
const entryPath = remotePath === '/' ? `/${entry.filename}` : `${remotePath.replace(/\/+$/, '')}/${entry.filename}`;
|
|
614
|
+
try {
|
|
615
|
+
const attrs = await this.sftpCall(sftp.sftp, (cb) => sftp.sftp.stat(entryPath, cb));
|
|
616
|
+
isDirectory = (attrs.mode & 0o170000) === 0o040000;
|
|
617
|
+
} catch { /* dangling symlink */ }
|
|
618
|
+
}
|
|
619
|
+
return {
|
|
620
|
+
name: entry.filename,
|
|
621
|
+
isDirectory,
|
|
622
|
+
size: entry.attrs.size,
|
|
623
|
+
mtime: entry.attrs.mtime * 1000,
|
|
624
|
+
mode: entry.attrs.mode,
|
|
625
|
+
};
|
|
626
|
+
}));
|
|
627
|
+
return { ok: true, value: { path: remotePath, entries: items } };
|
|
628
|
+
} catch (error) {
|
|
629
|
+
return { ok: false, error: fail('sftp-list-failed', `${remotePath}: ${error.message}`) };
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
async sftpMkdir(request) {
|
|
634
|
+
const selected = this.resolveConnection(request.connectionId);
|
|
635
|
+
if (!selected.ok) return selected;
|
|
636
|
+
const sftp = await this.requireSftp(selected.connection);
|
|
637
|
+
if (!sftp.ok) return sftp;
|
|
638
|
+
try {
|
|
639
|
+
const remotePath = normalizeRemoteRoot(request.path);
|
|
640
|
+
await this.sftpCall(sftp.sftp, (cb) => sftp.sftp.mkdir(remotePath, cb));
|
|
641
|
+
return { ok: true, value: { path: remotePath } };
|
|
642
|
+
} catch (error) {
|
|
643
|
+
return { ok: false, error: fail('sftp-mkdir-failed', `${request.path}: ${error.message}`) };
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// ── wire methods: bindings ──────────────────────────────────────────────
|
|
648
|
+
|
|
649
|
+
async bindingList() {
|
|
650
|
+
try {
|
|
651
|
+
const bindings = this.listBindings().map((record) => this.bindingPublic(record));
|
|
652
|
+
const registry = this.ctx.get('workspaceRegistry');
|
|
653
|
+
const workspaces = (registry?.list?.() ?? []).map((workspace) => ({
|
|
654
|
+
path: workspace.path,
|
|
655
|
+
title: workspace.title ?? workspace.path,
|
|
656
|
+
workspaceId: workspace.id,
|
|
657
|
+
}));
|
|
658
|
+
return { ok: true, value: { bindings, workspaces } };
|
|
659
|
+
} catch (error) {
|
|
660
|
+
return { ok: false, error: fail('binding-list-failed', error.message) };
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* All bindings plus the one matching the given session's working directory
|
|
666
|
+
* (so the files panel can default-select the right binding per session).
|
|
667
|
+
*/
|
|
668
|
+
async sessionBinding(request) {
|
|
669
|
+
try {
|
|
670
|
+
const agents = this.ctx.get('agents');
|
|
671
|
+
const agent = typeof agents?.get === 'function' ? agents.get(request.sessionId) : undefined;
|
|
672
|
+
const session = agent?.session ?? agent;
|
|
673
|
+
const directory = this.sessionDirectory(session);
|
|
674
|
+
const bindings = this.listBindings().map((record) => this.bindingPublic(record));
|
|
675
|
+
const match = typeof directory === 'string' ? this.bindingFor(directory) : undefined;
|
|
676
|
+
debugLog(`sessionBinding: sessionId=${request.sessionId} cwd=${String(directory)} match=${match ? match.record.workspacePath : 'none'}`);
|
|
677
|
+
return {
|
|
678
|
+
ok: true,
|
|
679
|
+
value: {
|
|
680
|
+
bindings,
|
|
681
|
+
matchWorkspacePath: match ? match.record.workspacePath : null,
|
|
682
|
+
cwd: typeof directory === 'string' ? directory : null,
|
|
683
|
+
},
|
|
684
|
+
};
|
|
685
|
+
} catch (error) {
|
|
686
|
+
return { ok: false, error: fail('session-binding-failed', error.message) };
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
async bindingSave(request) {
|
|
691
|
+
try {
|
|
692
|
+
const profile = this.requireProfileTable().get(request.profileId);
|
|
693
|
+
if (profile === undefined) return { ok: false, error: fail('no-profile', `SSH server "${request.profileId}" does not exist`) };
|
|
694
|
+
const registry = this.ctx.get('workspaceRegistry');
|
|
695
|
+
const known = new Set((registry?.list?.() ?? []).map((workspace) => workspace.path));
|
|
696
|
+
if (known.size > 0 && !known.has(request.workspacePath)) {
|
|
697
|
+
return { ok: false, error: fail('no-workspace', `workspace "${request.workspacePath}" is not registered in DSH`) };
|
|
698
|
+
}
|
|
699
|
+
let remotePath;
|
|
700
|
+
try {
|
|
701
|
+
remotePath = normalizeRemoteRoot(request.remotePath);
|
|
702
|
+
} catch (error) {
|
|
703
|
+
return { ok: false, error: fail('bad-remote-path', error.message) };
|
|
704
|
+
}
|
|
705
|
+
const now = new Date().toISOString();
|
|
706
|
+
const previous = this.requireBindingTable().get(request.workspacePath);
|
|
707
|
+
const record = {
|
|
708
|
+
...(previous ?? {}),
|
|
709
|
+
workspacePath: request.workspacePath,
|
|
710
|
+
profileId: request.profileId,
|
|
711
|
+
remotePath,
|
|
712
|
+
autoConnect: request.autoConnect === true,
|
|
713
|
+
...(previous === undefined ? { createdAt: now } : {}),
|
|
714
|
+
updatedAt: now,
|
|
715
|
+
};
|
|
716
|
+
await this.requireBindingTable().put(request.workspacePath, record);
|
|
717
|
+
return { ok: true, value: { binding: this.bindingPublic(record) } };
|
|
718
|
+
} catch (error) {
|
|
719
|
+
return { ok: false, error: fail('binding-save-failed', error.message) };
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
async bindingDelete(request) {
|
|
724
|
+
try {
|
|
725
|
+
const table = this.requireBindingTable();
|
|
726
|
+
if (table.get(request.workspacePath) === undefined) {
|
|
727
|
+
return { ok: false, error: fail('no-binding', `workspace "${request.workspacePath}" has no remote binding`) };
|
|
728
|
+
}
|
|
729
|
+
await table.delete(request.workspacePath);
|
|
730
|
+
return { ok: true, value: { removed: true } };
|
|
731
|
+
} catch (error) {
|
|
732
|
+
return { ok: false, error: fail('binding-delete-failed', error.message) };
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* Create (or reuse) the local mirror folder a remote-bound workspace points
|
|
738
|
+
* at: `~/.dsh/remote-workspaces/<safe name>`. The Host owns the filesystem;
|
|
739
|
+
* the browser never needs the directory picker's browse capability for this.
|
|
740
|
+
*/
|
|
741
|
+
async ensureLocalMirrorFolder(request) {
|
|
742
|
+
try {
|
|
743
|
+
const root = join(osHomedir(), '.dsh', 'remote-workspaces');
|
|
744
|
+
await fsMkdir(root, { recursive: true });
|
|
745
|
+
const folder = safeFolderName(request.name);
|
|
746
|
+
const target = join(root, folder);
|
|
747
|
+
await fsMkdir(target, { recursive: true });
|
|
748
|
+
debugLog(`ensureLocalMirrorFolder → ${target}`);
|
|
749
|
+
return { ok: true, value: { path: target } };
|
|
750
|
+
} catch (error) {
|
|
751
|
+
return { ok: false, error: fail('mirror-create-failed', error.message) };
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// ── remote terminal: reroute official new-terminal spawns ───────────────
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* Wrap `subprocess.spawnTerminal` so a session whose working directory is
|
|
759
|
+
* bound to a remote workspace gets an SSH shell (cwd = the bound remote
|
|
760
|
+
* directory, or the session subdirectory of it) instead of a local PTY.
|
|
761
|
+
* Unbound sessions fall through to the original local spawn, unchanged.
|
|
762
|
+
*/
|
|
763
|
+
installTerminalReroute(ctx) {
|
|
764
|
+
const subprocess = this.ctx.get('subprocess');
|
|
765
|
+
if (subprocess === undefined || typeof subprocess.spawnTerminal !== 'function') {
|
|
766
|
+
debugLog('terminal reroute: subprocess service unavailable; remote terminals disabled');
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
if (subprocess.spawnTerminal.__dshSshFilePatched === true) {
|
|
770
|
+
debugLog('terminal reroute: already patched; skipping');
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
const service = this;
|
|
774
|
+
const original = subprocess.spawnTerminal;
|
|
775
|
+
const patched = function spawnTerminal(spec) {
|
|
776
|
+
let binding;
|
|
777
|
+
try {
|
|
778
|
+
binding = service.bindingFor(spec?.cwd);
|
|
779
|
+
} catch {
|
|
780
|
+
binding = undefined; // storage not ready -> local shell, never block boot paths
|
|
781
|
+
}
|
|
782
|
+
if (binding === undefined) return original.call(this, spec);
|
|
783
|
+
return service.spawnSshTerminal(binding, spec);
|
|
784
|
+
};
|
|
785
|
+
patched.__dshSshFilePatched = true;
|
|
786
|
+
subprocess.spawnTerminal = patched;
|
|
787
|
+
ctx.effect(() => () => {
|
|
788
|
+
try {
|
|
789
|
+
if (subprocess.spawnTerminal === patched) subprocess.spawnTerminal = original;
|
|
790
|
+
} catch { /* ignore */ }
|
|
791
|
+
for (const handle of this.sshTerminalHandles) {
|
|
792
|
+
try { handle.terminate(); } catch { /* ignore */ }
|
|
793
|
+
}
|
|
794
|
+
this.sshTerminalHandles.clear();
|
|
795
|
+
}, 'dsh-ssh-file: terminal reroute restore');
|
|
796
|
+
debugLog('terminal reroute: installed');
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** Open an SSH shell for a bound spawn request (cwd-keyed). */
|
|
800
|
+
async spawnSshTerminal(binding, spec) {
|
|
801
|
+
const record = binding.record;
|
|
802
|
+
const connection = await this.ensureBindingConnection(record);
|
|
803
|
+
const subdirectory = binding.relative === undefined
|
|
804
|
+
? (workspaceRelativePart(record.workspacePath, spec?.cwd) ?? '')
|
|
805
|
+
: binding.relative;
|
|
806
|
+
const base = subdirectory === '' ? record.remotePath : `${record.remotePath}/${subdirectory}`;
|
|
807
|
+
const remoteDir = normalizeRemoteRoot(base);
|
|
808
|
+
const shellStream = await new Promise((resolve, reject) => {
|
|
809
|
+
const timer = setTimeout(() => reject(new Error('SSH shell handshake timed out')), CONNECT_TIMEOUT_MS);
|
|
810
|
+
try {
|
|
811
|
+
connection.client.shell({
|
|
812
|
+
term: typeof spec?.terminalType === 'string' && spec.terminalType !== '' ? spec.terminalType : 'xterm-256color',
|
|
813
|
+
cols: Number.isSafeInteger(spec?.cols) ? spec.cols : 80,
|
|
814
|
+
rows: Number.isSafeInteger(spec?.rows) ? spec.rows : 24,
|
|
815
|
+
}, (error, stream) => {
|
|
816
|
+
clearTimeout(timer);
|
|
817
|
+
if (error) reject(error);
|
|
818
|
+
else resolve(stream);
|
|
819
|
+
});
|
|
820
|
+
} catch (error) {
|
|
821
|
+
clearTimeout(timer);
|
|
822
|
+
reject(error);
|
|
823
|
+
}
|
|
824
|
+
});
|
|
825
|
+
const handle = new SshTerminalHandle(shellStream, () => this.sshTerminalHandles.delete(handle));
|
|
826
|
+
this.sshTerminalHandles.add(handle);
|
|
827
|
+
// Land in the bound remote directory once the shell is up.
|
|
828
|
+
setTimeout(() => {
|
|
829
|
+
try { shellStream.write(`cd ${shellSingleQuote(remoteDir)}; clear\n`); } catch { /* stream closed */ }
|
|
830
|
+
}, 150);
|
|
831
|
+
debugLog(`terminal reroute: ${spec?.cwd} -> ${remoteDir} (${connection.host})`);
|
|
832
|
+
return handle;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
// ── wire methods: remote file panel editor ──────────────────────────────
|
|
836
|
+
|
|
837
|
+
async fileRead(request) {
|
|
838
|
+
const selected = this.resolveConnection(request.connectionId);
|
|
839
|
+
if (!selected.ok) return selected;
|
|
840
|
+
let remotePath;
|
|
841
|
+
try {
|
|
842
|
+
remotePath = normalizeRemoteRoot(request.path);
|
|
843
|
+
} catch (error) {
|
|
844
|
+
return { ok: false, error: fail('bad-remote-path', error.message) };
|
|
845
|
+
}
|
|
846
|
+
try {
|
|
847
|
+
const read = await this.readFileBounded(selected.connection, remotePath, MAX_EDITOR_READ_BYTES);
|
|
848
|
+
return {
|
|
849
|
+
ok: true,
|
|
850
|
+
value: { path: remotePath, data: read.buffer.toString('utf8'), bytes: read.buffer.length, truncated: read.truncated },
|
|
851
|
+
};
|
|
852
|
+
} catch (error) {
|
|
853
|
+
return { ok: false, error: fail('file-read-failed', `${remotePath}: ${error.message}`) };
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
async fileWrite(request) {
|
|
858
|
+
const selected = this.resolveConnection(request.connectionId);
|
|
859
|
+
if (!selected.ok) return selected;
|
|
860
|
+
let remotePath;
|
|
861
|
+
try {
|
|
862
|
+
remotePath = normalizeRemoteRoot(request.path);
|
|
863
|
+
} catch (error) {
|
|
864
|
+
return { ok: false, error: fail('bad-remote-path', error.message) };
|
|
865
|
+
}
|
|
866
|
+
const sftp = await this.requireSftp(selected.connection);
|
|
867
|
+
if (!sftp.ok) return sftp;
|
|
868
|
+
try {
|
|
869
|
+
const data = Buffer.from(String(request.data ?? ''), 'utf8');
|
|
870
|
+
await new Promise((resolve, reject) => {
|
|
871
|
+
const stream = sftp.sftp.createWriteStream(remotePath);
|
|
872
|
+
stream.on('error', reject);
|
|
873
|
+
stream.on('close', resolve);
|
|
874
|
+
stream.end(data);
|
|
875
|
+
});
|
|
876
|
+
return { ok: true, value: { path: remotePath, bytes: data.length } };
|
|
877
|
+
} catch (error) {
|
|
878
|
+
return { ok: false, error: fail('file-write-failed', `${remotePath}: ${error.message}`) };
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
// ── agent-tool plumbing ─────────────────────────────────────────────────
|
|
883
|
+
|
|
884
|
+
/**
|
|
885
|
+
* Resolve the binding + live connection for the session that issued a tool
|
|
886
|
+
* call. Auto-connects when the binding allows it. Relative paths resolve
|
|
887
|
+
* under the bound remote root, shifted by the session's subdirectory.
|
|
888
|
+
*/
|
|
889
|
+
async resolveSessionTarget(exec, path) {
|
|
890
|
+
const directory = this.sessionDirectory(exec?.agent?.session);
|
|
891
|
+
const binding = this.bindingFor(directory);
|
|
892
|
+
if (binding === undefined) {
|
|
893
|
+
throw new Error(
|
|
894
|
+
'no remote workspace is bound for this directory. ' +
|
|
895
|
+
'Open the workspace picker (sidebar 「+」 or the chat workspace selector), choose 「远程 SSH 目录」, ' +
|
|
896
|
+
'and bind this workspace to a remote directory first — or use remote_bindings to list existing bindings.',
|
|
897
|
+
);
|
|
898
|
+
}
|
|
899
|
+
const record = binding.record;
|
|
900
|
+
const connection = await this.ensureBindingConnection(record);
|
|
901
|
+
const subdirectory = binding.relative === undefined
|
|
902
|
+
? (workspaceRelativePart(record.workspacePath, directory) ?? '')
|
|
903
|
+
: binding.relative;
|
|
904
|
+
const base = subdirectory === '' ? record.remotePath : `${record.remotePath}/${subdirectory}`;
|
|
905
|
+
const resolved = resolveRemotePath(base, path ?? '.');
|
|
906
|
+
return { connection, record, path: resolved };
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/** Live connection for a binding: reuse, or auto-connect when allowed. */
|
|
910
|
+
async ensureBindingConnection(record) {
|
|
911
|
+
const reusable = this.findReusableConnection(record.profileId);
|
|
912
|
+
if (reusable !== null) return reusable;
|
|
913
|
+
const profile = this.requireProfileTable().get(record.profileId);
|
|
914
|
+
if (profile === undefined) throw new Error('the SSH server bound to this workspace no longer exists');
|
|
915
|
+
if (record.autoConnect !== true) {
|
|
916
|
+
throw new Error(
|
|
917
|
+
`remote workspace is offline: connect "${profile.name}" via the Remote Workspace UI, ` +
|
|
918
|
+
'or re-bind the workspace with autoConnect enabled',
|
|
919
|
+
);
|
|
920
|
+
}
|
|
921
|
+
const connected = await this.profileConnect({ profileId: record.profileId, reuseExisting: true });
|
|
922
|
+
if (!connected.ok) throw new Error(`remote workspace is offline: ${connected.error.message}`);
|
|
923
|
+
const connection = this.connections.get(connected.value.connectionId);
|
|
924
|
+
if (connection === undefined) throw new Error('remote workspace connection disappeared while connecting');
|
|
925
|
+
return connection;
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
async readFileBounded(connection, path, maxBytes) {
|
|
929
|
+
const sftp = await this.requireSftp(connection);
|
|
930
|
+
if (!sftp.ok) throw new Error(sftp.error.message);
|
|
931
|
+
const chunks = [];
|
|
932
|
+
let total = 0;
|
|
933
|
+
await new Promise((resolve, reject) => {
|
|
934
|
+
const stream = sftp.sftp.createReadStream(path);
|
|
935
|
+
stream.on('data', (chunk) => {
|
|
936
|
+
const remaining = maxBytes - total;
|
|
937
|
+
if (remaining > 0) chunks.push(chunk.length <= remaining ? chunk : chunk.subarray(0, remaining));
|
|
938
|
+
total += chunk.length;
|
|
939
|
+
});
|
|
940
|
+
stream.on('end', resolve);
|
|
941
|
+
stream.on('error', reject);
|
|
942
|
+
});
|
|
943
|
+
return { buffer: Buffer.concat(chunks), total, truncated: total > maxBytes };
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
execOnConnection(connection, command, timeoutMs) {
|
|
947
|
+
const maxBytes = MAX_COMMAND_OUTPUT_BYTES;
|
|
948
|
+
return new Promise((resolve) => {
|
|
949
|
+
let settled = false;
|
|
950
|
+
const finish = (value) => {
|
|
951
|
+
if (settled) return;
|
|
952
|
+
settled = true;
|
|
953
|
+
clearTimeout(timer);
|
|
954
|
+
resolve(value);
|
|
955
|
+
};
|
|
956
|
+
const timer = setTimeout(() => finish({ stdout, stderr, exitCode: null, truncated: true, timedOut: true, stdoutBytes, stderrBytes }), timeoutMs);
|
|
957
|
+
const stdoutParts = [];
|
|
958
|
+
const stderrParts = [];
|
|
959
|
+
let stdoutBytes = 0;
|
|
960
|
+
let stderrBytes = 0;
|
|
961
|
+
let exitCode = null;
|
|
962
|
+
try {
|
|
963
|
+
connection.client.exec(command, (error, stream) => {
|
|
964
|
+
if (error) {
|
|
965
|
+
finish({ stdout: '', stderr: error.message, exitCode: null, truncated: false, timedOut: false, stdoutBytes: 0, stderrBytes: 0, execError: error.message });
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
stream.on('data', (chunk) => {
|
|
969
|
+
if (stdoutBytes < maxBytes) stdoutParts.push(chunk.length <= maxBytes - stdoutBytes ? chunk : chunk.subarray(0, maxBytes - stdoutBytes));
|
|
970
|
+
stdoutBytes += chunk.length;
|
|
971
|
+
});
|
|
972
|
+
stream.stderr.on('data', (chunk) => {
|
|
973
|
+
if (stderrBytes < maxBytes) stderrParts.push(chunk.length <= maxBytes - stderrBytes ? chunk : chunk.subarray(0, maxBytes - stderrBytes));
|
|
974
|
+
stderrBytes += chunk.length;
|
|
975
|
+
});
|
|
976
|
+
stream.on('exit', (code) => { exitCode = typeof code === 'number' ? code : null; });
|
|
977
|
+
stream.on('close', () => {
|
|
978
|
+
finish({
|
|
979
|
+
stdout: Buffer.concat(stdoutParts).toString('utf8'),
|
|
980
|
+
stderr: Buffer.concat(stderrParts).toString('utf8'),
|
|
981
|
+
exitCode,
|
|
982
|
+
truncated: stdoutBytes > maxBytes || stderrBytes > maxBytes,
|
|
983
|
+
timedOut: false,
|
|
984
|
+
stdoutBytes,
|
|
985
|
+
stderrBytes,
|
|
986
|
+
});
|
|
987
|
+
});
|
|
988
|
+
});
|
|
989
|
+
} catch (error) {
|
|
990
|
+
finish({ stdout: '', stderr: error.message, exitCode: null, truncated: false, timedOut: false, stdoutBytes: 0, stderrBytes: 0, execError: error.message });
|
|
991
|
+
}
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
// ── agent tools ─────────────────────────────────────────────────────────
|
|
996
|
+
|
|
997
|
+
registerTools(ctx) {
|
|
998
|
+
const entry = (name, description, parameters, outputSchema, render, execute) => ctx.tools.register(defineTool({
|
|
999
|
+
name,
|
|
1000
|
+
description,
|
|
1001
|
+
parameters,
|
|
1002
|
+
output: { schema: outputSchema, render },
|
|
1003
|
+
execute,
|
|
1004
|
+
}));
|
|
1005
|
+
|
|
1006
|
+
entry(
|
|
1007
|
+
'remote_bindings',
|
|
1008
|
+
'List the remote-workspace bindings known to the plugin and which one (if any) governs the current session directory. Use this first to discover which server and remote root the other remote_* tools will act on.',
|
|
1009
|
+
{},
|
|
1010
|
+
{
|
|
1011
|
+
type: 'object', additionalProperties: false, properties: {
|
|
1012
|
+
bindings: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: {
|
|
1013
|
+
workspacePath: { type: 'string', required: true },
|
|
1014
|
+
remotePath: { type: 'string', required: true },
|
|
1015
|
+
server: { type: 'string', required: true },
|
|
1016
|
+
autoConnect: { type: 'boolean', required: true },
|
|
1017
|
+
connected: { type: 'boolean', required: true },
|
|
1018
|
+
} } },
|
|
1019
|
+
currentDirectory: { type: 'string' },
|
|
1020
|
+
currentBinding: { type: 'string' },
|
|
1021
|
+
},
|
|
1022
|
+
},
|
|
1023
|
+
(args, value) => {
|
|
1024
|
+
const lines = value.bindings.map((b) => `${b.connected ? '*' : ' '} ${b.workspacePath} -> ${b.server}:${b.remotePath}${b.autoConnect ? ' (auto-connect)' : ''}`);
|
|
1025
|
+
const current = value.currentBinding ? `\nCurrent session binding: ${value.currentBinding}` : '\nNo binding for the current session directory.';
|
|
1026
|
+
return [{ type: 'text', text: (lines.length ? lines.join('\n') : '(no bindings)') + current }];
|
|
1027
|
+
},
|
|
1028
|
+
async (args, exec) => {
|
|
1029
|
+
const directory = this.sessionDirectory(exec?.agent?.session);
|
|
1030
|
+
const binding = this.bindingFor(directory);
|
|
1031
|
+
const bindings = this.listBindings().map((record) => {
|
|
1032
|
+
const pub = this.bindingPublic(record);
|
|
1033
|
+
return {
|
|
1034
|
+
workspacePath: pub.workspacePath,
|
|
1035
|
+
remotePath: pub.remotePath,
|
|
1036
|
+
server: `${pub.username ? pub.username + '@' : ''}${pub.host}:${pub.port}`,
|
|
1037
|
+
autoConnect: pub.autoConnect,
|
|
1038
|
+
connected: pub.connected,
|
|
1039
|
+
};
|
|
1040
|
+
});
|
|
1041
|
+
const value = { bindings };
|
|
1042
|
+
if (typeof directory === 'string') value.currentDirectory = directory;
|
|
1043
|
+
if (binding !== undefined) {
|
|
1044
|
+
const pub = this.bindingPublic(binding.record);
|
|
1045
|
+
value.currentBinding = `${pub.workspacePath} -> ${pub.host}:${pub.remotePath}`;
|
|
1046
|
+
}
|
|
1047
|
+
return value;
|
|
1048
|
+
},
|
|
1049
|
+
);
|
|
1050
|
+
|
|
1051
|
+
entry(
|
|
1052
|
+
'remote_list',
|
|
1053
|
+
'List a remote directory over SFTP on the server bound to the current session\'s workspace. Relative paths resolve under the bound remote root; absolute paths must stay inside it. Returns entries with type, size, and mtime.',
|
|
1054
|
+
{
|
|
1055
|
+
path: { type: 'string', required: true, description: 'Remote directory path; "." or a relative path resolves under the remote workspace root (or the session subdirectory of it).' },
|
|
1056
|
+
},
|
|
1057
|
+
{
|
|
1058
|
+
type: 'object', additionalProperties: false, properties: {
|
|
1059
|
+
path: { type: 'string', required: true },
|
|
1060
|
+
entries: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: {
|
|
1061
|
+
name: { type: 'string', required: true },
|
|
1062
|
+
isDirectory: { type: 'boolean', required: true },
|
|
1063
|
+
size: { type: 'number', required: true },
|
|
1064
|
+
mtime: { type: 'number', required: true },
|
|
1065
|
+
} } },
|
|
1066
|
+
},
|
|
1067
|
+
},
|
|
1068
|
+
(args, value) => {
|
|
1069
|
+
if (!value.entries.length) return [{ type: 'text', text: `(empty directory ${value.path})` }];
|
|
1070
|
+
const lines = value.entries.map((e) => `${e.isDirectory ? 'd' : '-'} ${e.isDirectory ? '' : String(e.size).padStart(10)} ${new Date(e.mtime).toISOString().slice(0, 16).replace('T', ' ')} ${e.name}`);
|
|
1071
|
+
return [{ type: 'text', text: `Directory ${value.path} (${value.entries.length} entries):\n` + lines.join('\n') }];
|
|
1072
|
+
},
|
|
1073
|
+
async (args, exec) => {
|
|
1074
|
+
const { connection, path } = await this.resolveSessionTarget(exec, args.path);
|
|
1075
|
+
const sftp = await this.requireSftp(connection);
|
|
1076
|
+
if (!sftp.ok) throw new Error(`remote_list failed: ${sftp.error.message}`);
|
|
1077
|
+
const entries = await this.sftpCall(sftp.sftp, (cb) => sftp.sftp.readdir(path, cb));
|
|
1078
|
+
return {
|
|
1079
|
+
path,
|
|
1080
|
+
entries: entries.map((e) => ({
|
|
1081
|
+
name: e.filename,
|
|
1082
|
+
isDirectory: (e.attrs.mode & 0o170000) === 0o040000,
|
|
1083
|
+
size: e.attrs.size,
|
|
1084
|
+
mtime: e.attrs.mtime * 1000,
|
|
1085
|
+
})),
|
|
1086
|
+
};
|
|
1087
|
+
},
|
|
1088
|
+
);
|
|
1089
|
+
|
|
1090
|
+
entry(
|
|
1091
|
+
'remote_read',
|
|
1092
|
+
'Read a remote text file over SFTP from the server bound to the current session\'s workspace. Output is capped at 256 KB with a truncation flag; use remote_exec (head/tail/grep) for larger files.',
|
|
1093
|
+
{
|
|
1094
|
+
path: { type: 'string', required: true, description: 'Remote file path; relative paths resolve under the remote workspace root.' },
|
|
1095
|
+
max_bytes: { type: 'integer', description: 'Maximum bytes to return, up to 262144. Default 262144.' },
|
|
1096
|
+
},
|
|
1097
|
+
{
|
|
1098
|
+
type: 'object', additionalProperties: false, properties: {
|
|
1099
|
+
path: { type: 'string', required: true },
|
|
1100
|
+
data: { type: 'string', required: true },
|
|
1101
|
+
bytes: { type: 'number', required: true },
|
|
1102
|
+
truncated: { type: 'boolean', required: true },
|
|
1103
|
+
remoteRoot: { type: 'string' },
|
|
1104
|
+
},
|
|
1105
|
+
},
|
|
1106
|
+
(args, value) => [{
|
|
1107
|
+
type: 'text',
|
|
1108
|
+
text: (value.data || '(empty file)') + (value.truncated ? `\n[truncated after ${value.bytes} bytes]` : ''),
|
|
1109
|
+
}],
|
|
1110
|
+
async (args, exec) => {
|
|
1111
|
+
const maxBytes = Math.max(1, Math.min(Number(args.max_bytes) || MAX_FILE_READ_BYTES, MAX_FILE_READ_BYTES));
|
|
1112
|
+
const { connection, record, path } = await this.resolveSessionTarget(exec, args.path);
|
|
1113
|
+
const read = await this.readFileBounded(connection, path, maxBytes);
|
|
1114
|
+
return {
|
|
1115
|
+
path,
|
|
1116
|
+
data: read.buffer.toString('utf8'),
|
|
1117
|
+
bytes: read.buffer.length,
|
|
1118
|
+
truncated: read.truncated,
|
|
1119
|
+
remoteRoot: record.remotePath,
|
|
1120
|
+
};
|
|
1121
|
+
},
|
|
1122
|
+
);
|
|
1123
|
+
|
|
1124
|
+
entry(
|
|
1125
|
+
'remote_write',
|
|
1126
|
+
'Write (create or overwrite) a text file on the server bound to the current session\'s workspace. Paths must stay inside the bound remote root.',
|
|
1127
|
+
{
|
|
1128
|
+
path: { type: 'string', required: true, description: 'Remote file path to write; relative paths resolve under the remote workspace root.' },
|
|
1129
|
+
data: { type: 'string', required: true, description: 'UTF-8 text content to write.' },
|
|
1130
|
+
},
|
|
1131
|
+
{
|
|
1132
|
+
type: 'object', additionalProperties: false, properties: {
|
|
1133
|
+
path: { type: 'string', required: true },
|
|
1134
|
+
bytes: { type: 'number', required: true },
|
|
1135
|
+
},
|
|
1136
|
+
},
|
|
1137
|
+
(args, value) => [{ type: 'text', text: `Wrote ${value.bytes} bytes to ${value.path}` }],
|
|
1138
|
+
async (args, exec) => {
|
|
1139
|
+
const { connection, path } = await this.resolveSessionTarget(exec, args.path);
|
|
1140
|
+
const sftp = await this.requireSftp(connection);
|
|
1141
|
+
if (!sftp.ok) throw new Error(`remote_write failed: ${sftp.error.message}`);
|
|
1142
|
+
const data = Buffer.from(String(args.data ?? ''), 'utf8');
|
|
1143
|
+
await new Promise((resolve, reject) => {
|
|
1144
|
+
const stream = sftp.sftp.createWriteStream(path);
|
|
1145
|
+
stream.on('error', reject);
|
|
1146
|
+
stream.on('close', resolve);
|
|
1147
|
+
stream.end(data);
|
|
1148
|
+
});
|
|
1149
|
+
return { path, bytes: data.length };
|
|
1150
|
+
},
|
|
1151
|
+
);
|
|
1152
|
+
|
|
1153
|
+
entry(
|
|
1154
|
+
'remote_mkdir',
|
|
1155
|
+
'Create a directory on the server bound to the current session\'s workspace. Paths must stay inside the bound remote root. Parent directories are created as needed.',
|
|
1156
|
+
{
|
|
1157
|
+
path: { type: 'string', required: true, description: 'Remote directory to create; relative paths resolve under the remote workspace root.' },
|
|
1158
|
+
},
|
|
1159
|
+
{
|
|
1160
|
+
type: 'object', additionalProperties: false, properties: {
|
|
1161
|
+
path: { type: 'string', required: true },
|
|
1162
|
+
},
|
|
1163
|
+
},
|
|
1164
|
+
(args, value) => [{ type: 'text', text: `Created ${value.path}` }],
|
|
1165
|
+
async (args, exec) => {
|
|
1166
|
+
const { connection, path } = await this.resolveSessionTarget(exec, args.path);
|
|
1167
|
+
const sftp = await this.requireSftp(connection);
|
|
1168
|
+
if (!sftp.ok) throw new Error(`remote_mkdir failed: ${sftp.error.message}`);
|
|
1169
|
+
// mkdir -p semantics: walk the chain, ignoring "already exists".
|
|
1170
|
+
const parts = path.split('/').filter(Boolean);
|
|
1171
|
+
let current = '';
|
|
1172
|
+
for (const part of parts) {
|
|
1173
|
+
current += `/${part}`;
|
|
1174
|
+
await this.sftpCall(sftp.sftp, (cb) => sftp.sftp.mkdir(current, cb)).catch(() => { /* exists or failed at the last leg */ });
|
|
1175
|
+
}
|
|
1176
|
+
return { path };
|
|
1177
|
+
},
|
|
1178
|
+
);
|
|
1179
|
+
|
|
1180
|
+
entry(
|
|
1181
|
+
'remote_exec',
|
|
1182
|
+
'Run a shell command on the server bound to the current session\'s workspace over SSH exec and capture stdout/stderr/exit code. Output is capped at 64 KB per stream. Runs in the session\'s remote subdirectory when possible.',
|
|
1183
|
+
{
|
|
1184
|
+
command: { type: 'string', required: true, description: 'Shell command to run on the remote server.' },
|
|
1185
|
+
timeout_ms: { type: 'integer', description: 'Kill the command after this many milliseconds (default 30000, max 600000).' },
|
|
1186
|
+
},
|
|
1187
|
+
{
|
|
1188
|
+
type: 'object', additionalProperties: false, properties: {
|
|
1189
|
+
command: { type: 'string', required: true },
|
|
1190
|
+
stdout: { type: 'string', required: true },
|
|
1191
|
+
stderr: { type: 'string', required: true },
|
|
1192
|
+
exitCode: { type: 'number' },
|
|
1193
|
+
truncated: { type: 'boolean', required: true },
|
|
1194
|
+
timedOut: { type: 'boolean', required: true },
|
|
1195
|
+
cwd: { type: 'string' },
|
|
1196
|
+
},
|
|
1197
|
+
},
|
|
1198
|
+
(args, value) => {
|
|
1199
|
+
const parts = [`$ ${value.command}`];
|
|
1200
|
+
if (value.stdout) parts.push(value.stdout);
|
|
1201
|
+
if (value.stderr) parts.push(`[stderr]\n${value.stderr}`);
|
|
1202
|
+
const tail = [];
|
|
1203
|
+
if (value.exitCode !== null && value.exitCode !== undefined) tail.push(`exit ${value.exitCode}`);
|
|
1204
|
+
if (value.timedOut) tail.push('timed out');
|
|
1205
|
+
if (value.truncated) tail.push('output truncated');
|
|
1206
|
+
if (tail.length) parts.push(`[${tail.join(', ')}]`);
|
|
1207
|
+
return [{ type: 'text', text: parts.join('\n') }];
|
|
1208
|
+
},
|
|
1209
|
+
async (args, exec) => {
|
|
1210
|
+
const command = String(args.command ?? '');
|
|
1211
|
+
if (command.trim().length === 0) throw new Error('remote_exec: command must not be empty');
|
|
1212
|
+
const timeoutMs = Math.max(1000, Math.min(Number(args.timeout_ms) || EXEC_DEFAULT_TIMEOUT_MS, EXEC_MAX_TIMEOUT_MS));
|
|
1213
|
+
const { connection, path } = await this.resolveSessionTarget(exec, '.');
|
|
1214
|
+
// Best-effort cd into the resolved remote directory, then run the raw command.
|
|
1215
|
+
const result = await this.execOnConnection(connection, `cd ${shellSingleQuote(path)} 2>/dev/null || true; ${command}`, timeoutMs);
|
|
1216
|
+
return {
|
|
1217
|
+
command,
|
|
1218
|
+
stdout: result.stdout,
|
|
1219
|
+
stderr: result.stderr,
|
|
1220
|
+
exitCode: result.exitCode,
|
|
1221
|
+
truncated: result.truncated,
|
|
1222
|
+
timedOut: result.timedOut === true,
|
|
1223
|
+
cwd: path,
|
|
1224
|
+
};
|
|
1225
|
+
},
|
|
1226
|
+
);
|
|
1227
|
+
}
|
|
1228
|
+
};
|
|
1229
|
+
|
|
1230
|
+
function shellSingleQuote(text) {
|
|
1231
|
+
return `'${String(text).replace(/'/g, `'\\''`)}'`;
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
export default RemoteWorkspaceService;
|
|
1235
|
+
export { RemoteWorkspaceService, PACKAGE, NS };
|