pi-remote-mesh 0.0.0-stage → 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 +21 -0
- package/README.md +186 -2
- package/dist/index.d.ts +149 -0
- package/dist/index.js +1183 -0
- package/dist/index.js.map +1 -0
- package/package.json +79 -4
- package/src/commands.ts +116 -0
- package/src/config.ts +196 -0
- package/src/index.ts +31 -0
- package/src/ssh-engine.ts +553 -0
- package/src/status-bar.ts +82 -0
- package/src/tool-registry.ts +352 -0
- package/src/types.ts +64 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1183 @@
|
|
|
1
|
+
// src/config.ts
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as path from "path";
|
|
4
|
+
import * as os from "os";
|
|
5
|
+
var DEFAULT_CONFIG_FILENAME = "remote-mesh.json";
|
|
6
|
+
var LEGACY_CONFIG_FILENAME = "remote-devices.json";
|
|
7
|
+
function resolveUserPath(filepath) {
|
|
8
|
+
if (!filepath) return filepath;
|
|
9
|
+
if (filepath.startsWith("~")) {
|
|
10
|
+
return path.join(os.homedir(), filepath.slice(1).replace(/^[/\\]+/, ""));
|
|
11
|
+
}
|
|
12
|
+
return path.resolve(filepath);
|
|
13
|
+
}
|
|
14
|
+
function getConfigPaths() {
|
|
15
|
+
const envPath = process.env.PI_REMOTE_MESH_CONFIG;
|
|
16
|
+
const paths = [];
|
|
17
|
+
if (envPath) {
|
|
18
|
+
paths.push(resolveUserPath(envPath));
|
|
19
|
+
}
|
|
20
|
+
const piDir = path.join(os.homedir(), ".pi");
|
|
21
|
+
paths.push(path.join(piDir, DEFAULT_CONFIG_FILENAME));
|
|
22
|
+
paths.push(path.join(piDir, LEGACY_CONFIG_FILENAME));
|
|
23
|
+
return paths;
|
|
24
|
+
}
|
|
25
|
+
function findConfigFile() {
|
|
26
|
+
for (const candidate of getConfigPaths()) {
|
|
27
|
+
if (fs.existsSync(candidate)) {
|
|
28
|
+
return candidate;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
function normalizeDeviceConfig(id, raw) {
|
|
34
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id)) {
|
|
35
|
+
throw new Error(`Invalid device id "${id}". Use letters, numbers, ".", "_" or "-".`);
|
|
36
|
+
}
|
|
37
|
+
if (raw.port !== void 0 && (!Number.isInteger(raw.port) || raw.port < 1 || raw.port > 65535)) {
|
|
38
|
+
throw new Error(`Invalid SSH port for device "${id}".`);
|
|
39
|
+
}
|
|
40
|
+
for (const [name, value] of [
|
|
41
|
+
["connectTimeoutMs", raw.connectTimeoutMs],
|
|
42
|
+
["keepaliveIntervalMs", raw.keepaliveIntervalMs],
|
|
43
|
+
["keepaliveCountMax", raw.keepaliveCountMax],
|
|
44
|
+
["maxOutputBytes", raw.maxOutputBytes],
|
|
45
|
+
["maxOutputLines", raw.maxOutputLines]
|
|
46
|
+
]) {
|
|
47
|
+
if (value !== void 0 && (!Number.isFinite(value) || value <= 0)) {
|
|
48
|
+
throw new Error(`Invalid ${name} for device "${id}".`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const auth = raw.auth || {};
|
|
52
|
+
const privateKeyPath = resolveUserPath(raw.privateKeyPath || auth.privateKeyPath || "");
|
|
53
|
+
return {
|
|
54
|
+
id,
|
|
55
|
+
name: raw.name || id,
|
|
56
|
+
host: raw.host || "127.0.0.1",
|
|
57
|
+
port: raw.port || 22,
|
|
58
|
+
username: raw.username || os.userInfo().username || "root",
|
|
59
|
+
auth: {
|
|
60
|
+
type: raw.auth?.type || (privateKeyPath ? "key" : "agent"),
|
|
61
|
+
privateKeyPath: privateKeyPath || void 0,
|
|
62
|
+
passphrase: raw.passphrase || auth.passphrase,
|
|
63
|
+
password: raw.password || auth.password,
|
|
64
|
+
agent: raw.auth?.agent
|
|
65
|
+
},
|
|
66
|
+
hostFingerprint: raw.hostFingerprint,
|
|
67
|
+
privateKeyPath: privateKeyPath || void 0,
|
|
68
|
+
persistent: raw.persistent !== false,
|
|
69
|
+
// default true
|
|
70
|
+
features: raw.features || ["exec", "sftp", "status"],
|
|
71
|
+
defaultCwd: raw.defaultCwd || "~",
|
|
72
|
+
connectTimeoutMs: raw.connectTimeoutMs || 1e4,
|
|
73
|
+
hostKeySha256: raw.hostKeySha256,
|
|
74
|
+
keepaliveIntervalMs: raw.keepaliveIntervalMs || 1e4,
|
|
75
|
+
keepaliveCountMax: raw.keepaliveCountMax || 3,
|
|
76
|
+
maxOutputBytes: raw.maxOutputBytes || 32768,
|
|
77
|
+
maxOutputLines: raw.maxOutputLines || 300,
|
|
78
|
+
env: raw.env || {},
|
|
79
|
+
localBypass: raw.localBypass ?? false,
|
|
80
|
+
localHostnames: raw.localHostnames || [],
|
|
81
|
+
toolPrefix: raw.toolPrefix
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function loadMeshConfig() {
|
|
85
|
+
const configPath = findConfigFile();
|
|
86
|
+
if (!configPath) {
|
|
87
|
+
return {
|
|
88
|
+
config: {
|
|
89
|
+
version: "1.0",
|
|
90
|
+
toolNamingStyle: "compact",
|
|
91
|
+
onDemandExposure: true,
|
|
92
|
+
devices: {}
|
|
93
|
+
},
|
|
94
|
+
loadedFrom: null
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
const rawContent = fs.readFileSync(configPath, "utf-8");
|
|
99
|
+
const parsed = JSON.parse(rawContent);
|
|
100
|
+
const devices = {};
|
|
101
|
+
if (parsed.devices && typeof parsed.devices === "object") {
|
|
102
|
+
for (const [id, dev] of Object.entries(parsed.devices)) {
|
|
103
|
+
devices[id] = normalizeDeviceConfig(id, dev);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
config: {
|
|
108
|
+
version: parsed.version || "1.0",
|
|
109
|
+
toolNamingStyle: parsed.toolNamingStyle || "compact",
|
|
110
|
+
onDemandExposure: parsed.onDemandExposure !== false,
|
|
111
|
+
devices
|
|
112
|
+
},
|
|
113
|
+
loadedFrom: configPath
|
|
114
|
+
};
|
|
115
|
+
} catch (err) {
|
|
116
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
117
|
+
throw new Error(`[pi-remote-mesh] Failed to parse config file at ${configPath}: ${reason}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function isLocalHost(device) {
|
|
121
|
+
if (!device.localBypass) return false;
|
|
122
|
+
const currentHost = os.hostname().toLowerCase();
|
|
123
|
+
const targetHost = device.host.toLowerCase();
|
|
124
|
+
if (targetHost === "localhost" || targetHost === "127.0.0.1" || targetHost === "::1") {
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
const localAddresses = Object.values(os.networkInterfaces()).flatMap((items) => items ?? []);
|
|
128
|
+
if (localAddresses.some((item) => item.address.toLowerCase() === targetHost)) return true;
|
|
129
|
+
if (currentHost === targetHost || currentHost.split(".")[0] === targetHost.split(".")[0]) {
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
if (device.localHostnames && device.localHostnames.length > 0) {
|
|
133
|
+
const match = device.localHostnames.some(
|
|
134
|
+
(h) => {
|
|
135
|
+
const hostname2 = h.toLowerCase().replace(/\.$/, "");
|
|
136
|
+
return hostname2 === currentHost || hostname2 === currentHost.split(".")[0];
|
|
137
|
+
}
|
|
138
|
+
);
|
|
139
|
+
if (match) return true;
|
|
140
|
+
}
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
function generateTemplateConfig() {
|
|
144
|
+
return {
|
|
145
|
+
version: "1.0",
|
|
146
|
+
toolNamingStyle: "compact",
|
|
147
|
+
onDemandExposure: true,
|
|
148
|
+
devices: {
|
|
149
|
+
vps: {
|
|
150
|
+
id: "vps",
|
|
151
|
+
name: "Cloud VPS Server",
|
|
152
|
+
host: "1.2.3.4",
|
|
153
|
+
port: 22,
|
|
154
|
+
username: "ubuntu",
|
|
155
|
+
privateKeyPath: "~/.ssh/id_rsa",
|
|
156
|
+
hostKeySha256: "SHA256:REPLACE_WITH_INDEPENDENTLY_VERIFIED_FINGERPRINT",
|
|
157
|
+
features: ["exec", "sftp", "status"],
|
|
158
|
+
persistent: true,
|
|
159
|
+
defaultCwd: "/home/ubuntu"
|
|
160
|
+
},
|
|
161
|
+
mac: {
|
|
162
|
+
id: "mac",
|
|
163
|
+
name: "Mac mini Workstation",
|
|
164
|
+
host: "mac-mini.local",
|
|
165
|
+
port: 22,
|
|
166
|
+
username: "developer",
|
|
167
|
+
privateKeyPath: "~/.ssh/id_ed25519",
|
|
168
|
+
hostKeySha256: "SHA256:REPLACE_WITH_INDEPENDENTLY_VERIFIED_FINGERPRINT",
|
|
169
|
+
features: ["exec", "status"],
|
|
170
|
+
persistent: false,
|
|
171
|
+
localBypass: true,
|
|
172
|
+
localHostnames: ["mac-mini", "mac-mini.local"]
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// src/ssh-engine.ts
|
|
179
|
+
import { Client } from "ssh2";
|
|
180
|
+
import * as fs2 from "fs";
|
|
181
|
+
import * as path2 from "path";
|
|
182
|
+
import { createHash, randomBytes, timingSafeEqual } from "crypto";
|
|
183
|
+
function quotePosixShell(value) {
|
|
184
|
+
if (value.includes("\0")) throw new Error("NUL is not allowed in a remote working directory");
|
|
185
|
+
return `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
186
|
+
}
|
|
187
|
+
async function awaitAbortable(promise, signal, onLate) {
|
|
188
|
+
if (!signal) return promise;
|
|
189
|
+
return new Promise((resolve2, reject) => {
|
|
190
|
+
let finished = false;
|
|
191
|
+
const onAbort = () => {
|
|
192
|
+
if (!finished) {
|
|
193
|
+
finished = true;
|
|
194
|
+
reject(signal.reason ?? new Error("Aborted"));
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
198
|
+
if (signal.aborted) onAbort();
|
|
199
|
+
promise.then((value) => {
|
|
200
|
+
signal.removeEventListener("abort", onAbort);
|
|
201
|
+
if (finished) {
|
|
202
|
+
onLate?.(value);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
finished = true;
|
|
206
|
+
resolve2(value);
|
|
207
|
+
}, (error) => {
|
|
208
|
+
signal.removeEventListener("abort", onAbort);
|
|
209
|
+
if (!finished) {
|
|
210
|
+
finished = true;
|
|
211
|
+
reject(error);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
var SshEngine = class {
|
|
217
|
+
constructor(devices) {
|
|
218
|
+
this.devices = devices;
|
|
219
|
+
}
|
|
220
|
+
devices;
|
|
221
|
+
clients = /* @__PURE__ */ new Map();
|
|
222
|
+
sftpWrappers = /* @__PURE__ */ new Map();
|
|
223
|
+
connecting = /* @__PURE__ */ new Map();
|
|
224
|
+
pendingClients = /* @__PURE__ */ new Map();
|
|
225
|
+
ephemeralSftpClients = /* @__PURE__ */ new WeakMap();
|
|
226
|
+
generations = /* @__PURE__ */ new Map();
|
|
227
|
+
updateDevices(devices) {
|
|
228
|
+
this.devices = devices;
|
|
229
|
+
}
|
|
230
|
+
getDevice(id) {
|
|
231
|
+
const dev = this.devices[id];
|
|
232
|
+
if (!dev) {
|
|
233
|
+
throw new Error(`Device "${id}" is not configured in remote-mesh.`);
|
|
234
|
+
}
|
|
235
|
+
return dev;
|
|
236
|
+
}
|
|
237
|
+
isConnected(id) {
|
|
238
|
+
const client = this.clients.get(id);
|
|
239
|
+
return !!client;
|
|
240
|
+
}
|
|
241
|
+
buildConnectConfig(device) {
|
|
242
|
+
const config = {
|
|
243
|
+
host: device.host,
|
|
244
|
+
port: device.port || 22,
|
|
245
|
+
username: device.username,
|
|
246
|
+
readyTimeout: device.connectTimeoutMs || 1e4,
|
|
247
|
+
keepaliveInterval: device.keepaliveIntervalMs || 1e4,
|
|
248
|
+
keepaliveCountMax: device.keepaliveCountMax || 3
|
|
249
|
+
};
|
|
250
|
+
let pinned;
|
|
251
|
+
if (device.hostKeySha256) {
|
|
252
|
+
const expected = device.hostKeySha256.replace(/^SHA256:/, "").replace(/=+$/, "");
|
|
253
|
+
if (!/^[A-Za-z0-9+/]{43}$/.test(expected)) {
|
|
254
|
+
throw new Error(`Invalid SHA256 host key fingerprint for device "${device.id}"`);
|
|
255
|
+
}
|
|
256
|
+
pinned = Buffer.from(expected, "base64");
|
|
257
|
+
} else if (device.hostFingerprint) {
|
|
258
|
+
const expected = device.hostFingerprint.replace(/:/g, "");
|
|
259
|
+
if (!/^[a-fA-F0-9]{64}$/.test(expected)) {
|
|
260
|
+
throw new Error(`Invalid SHA256 host key fingerprint for device "${device.id}"`);
|
|
261
|
+
}
|
|
262
|
+
pinned = Buffer.from(expected, "hex");
|
|
263
|
+
} else {
|
|
264
|
+
throw new Error(`Missing hostKeySha256 or hostFingerprint for device "${device.id}". Verify the host fingerprint independently before connecting.`);
|
|
265
|
+
}
|
|
266
|
+
config.hostVerifier = (key) => {
|
|
267
|
+
const actual = createHash("sha256").update(key).digest();
|
|
268
|
+
return pinned.length === actual.length && timingSafeEqual(actual, pinned);
|
|
269
|
+
};
|
|
270
|
+
const privateKeyPath = device.privateKeyPath || device.auth?.privateKeyPath;
|
|
271
|
+
if (privateKeyPath) {
|
|
272
|
+
const resolvedKeyPath = resolveUserPath(privateKeyPath);
|
|
273
|
+
if (fs2.existsSync(resolvedKeyPath)) {
|
|
274
|
+
config.privateKey = fs2.readFileSync(resolvedKeyPath);
|
|
275
|
+
} else {
|
|
276
|
+
throw new Error(`Private key file not found at: ${resolvedKeyPath} for device "${device.id}"`);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (device.passphrase || device.auth?.passphrase) {
|
|
280
|
+
config.passphrase = device.passphrase || device.auth?.passphrase;
|
|
281
|
+
}
|
|
282
|
+
if (device.password || device.auth?.password) {
|
|
283
|
+
config.password = device.password || device.auth?.password;
|
|
284
|
+
}
|
|
285
|
+
if (device.auth?.agent || !config.privateKey && !config.password) {
|
|
286
|
+
config.agent = device.auth?.agent || process.env.SSH_AUTH_SOCK;
|
|
287
|
+
}
|
|
288
|
+
return config;
|
|
289
|
+
}
|
|
290
|
+
async getClient(id) {
|
|
291
|
+
const device = this.getDevice(id);
|
|
292
|
+
if (isLocalHost(device)) {
|
|
293
|
+
throw new Error(`Device "${id}" is marked as local machine. Use local bash/tools instead of SSH.`);
|
|
294
|
+
}
|
|
295
|
+
if (device.persistent && this.clients.has(id)) {
|
|
296
|
+
return this.clients.get(id);
|
|
297
|
+
}
|
|
298
|
+
if (device.persistent && this.connecting.has(id)) {
|
|
299
|
+
return this.connecting.get(id);
|
|
300
|
+
}
|
|
301
|
+
const generation = this.generations.get(id) ?? 0;
|
|
302
|
+
let connectPromise;
|
|
303
|
+
connectPromise = new Promise((resolve2, reject) => {
|
|
304
|
+
const client = new Client();
|
|
305
|
+
if (device.persistent) this.pendingClients.set(id, client);
|
|
306
|
+
let connected = false;
|
|
307
|
+
client.on("ready", () => {
|
|
308
|
+
if (this.pendingClients.get(id) === client) this.pendingClients.delete(id);
|
|
309
|
+
if ((this.generations.get(id) ?? 0) !== generation) {
|
|
310
|
+
client.end();
|
|
311
|
+
reject(new Error(`Connection to "${id}" was cancelled by disconnect.`));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
connected = true;
|
|
315
|
+
if (device.persistent) {
|
|
316
|
+
this.clients.set(id, client);
|
|
317
|
+
if (this.connecting.get(id) === connectPromise) this.connecting.delete(id);
|
|
318
|
+
}
|
|
319
|
+
resolve2(client);
|
|
320
|
+
}).on("error", (err) => {
|
|
321
|
+
if (device.persistent) {
|
|
322
|
+
if (this.pendingClients.get(id) === client) this.pendingClients.delete(id);
|
|
323
|
+
if (this.connecting.get(id) === connectPromise) this.connecting.delete(id);
|
|
324
|
+
if (this.clients.get(id) === client) {
|
|
325
|
+
this.clients.delete(id);
|
|
326
|
+
this.sftpWrappers.delete(id);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (!connected) {
|
|
330
|
+
reject(err);
|
|
331
|
+
}
|
|
332
|
+
}).on("close", () => {
|
|
333
|
+
if (this.pendingClients.get(id) === client) this.pendingClients.delete(id);
|
|
334
|
+
if (!connected) reject(new Error(`SSH connection closed before ready for "${id}".`));
|
|
335
|
+
if (this.clients.get(id) === client) {
|
|
336
|
+
this.clients.delete(id);
|
|
337
|
+
this.sftpWrappers.delete(id);
|
|
338
|
+
}
|
|
339
|
+
}).on("end", () => {
|
|
340
|
+
if (this.clients.get(id) === client) {
|
|
341
|
+
this.clients.delete(id);
|
|
342
|
+
this.sftpWrappers.delete(id);
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
try {
|
|
346
|
+
const connectConfig = this.buildConnectConfig(device);
|
|
347
|
+
client.connect(connectConfig);
|
|
348
|
+
} catch (err) {
|
|
349
|
+
if (this.pendingClients.get(id) === client) this.pendingClients.delete(id);
|
|
350
|
+
reject(err);
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
if (device.persistent) {
|
|
354
|
+
this.connecting.set(id, connectPromise);
|
|
355
|
+
void connectPromise.catch(() => {
|
|
356
|
+
if (this.connecting.get(id) === connectPromise) this.connecting.delete(id);
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
return connectPromise;
|
|
360
|
+
}
|
|
361
|
+
async exec(id, command, customCwd, signal) {
|
|
362
|
+
signal?.throwIfAborted();
|
|
363
|
+
const device = this.getDevice(id);
|
|
364
|
+
const client = await awaitAbortable(this.getClient(id), signal, (late) => {
|
|
365
|
+
if (!device.persistent) late.end();
|
|
366
|
+
});
|
|
367
|
+
const startTime = Date.now();
|
|
368
|
+
const cwd = customCwd || device.defaultCwd;
|
|
369
|
+
let fullCommand = command;
|
|
370
|
+
if (cwd && cwd !== "~") {
|
|
371
|
+
const quotedCwd = quotePosixShell(cwd);
|
|
372
|
+
fullCommand = `cd -- ${quotedCwd} && (${command})`;
|
|
373
|
+
}
|
|
374
|
+
if (signal?.aborted) {
|
|
375
|
+
if (!device.persistent) client.end();
|
|
376
|
+
signal.throwIfAborted();
|
|
377
|
+
}
|
|
378
|
+
return new Promise((resolve2, reject) => {
|
|
379
|
+
let pendingAborted = false;
|
|
380
|
+
const onPendingAbort = () => {
|
|
381
|
+
pendingAborted = true;
|
|
382
|
+
signal?.removeEventListener("abort", onPendingAbort);
|
|
383
|
+
if (!device.persistent) client.end();
|
|
384
|
+
reject(new Error("Command request aborted; remote execution may have started."));
|
|
385
|
+
};
|
|
386
|
+
signal?.addEventListener("abort", onPendingAbort, { once: true });
|
|
387
|
+
if (signal?.aborted) {
|
|
388
|
+
onPendingAbort();
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
client.exec(fullCommand, { env: device.env }, (err, stream) => {
|
|
392
|
+
signal?.removeEventListener("abort", onPendingAbort);
|
|
393
|
+
if (pendingAborted) {
|
|
394
|
+
if (stream) {
|
|
395
|
+
try {
|
|
396
|
+
stream.signal("INT");
|
|
397
|
+
stream.close();
|
|
398
|
+
} catch {
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (err) {
|
|
404
|
+
if (!device.persistent) client.end();
|
|
405
|
+
return reject(err);
|
|
406
|
+
}
|
|
407
|
+
let stdoutBuf = "";
|
|
408
|
+
let stderrBuf = "";
|
|
409
|
+
let isTruncated = false;
|
|
410
|
+
let isAborted = false;
|
|
411
|
+
const maxBytes = device.maxOutputBytes || 32768;
|
|
412
|
+
const onAbort = () => {
|
|
413
|
+
isAborted = true;
|
|
414
|
+
try {
|
|
415
|
+
stream.signal("INT");
|
|
416
|
+
} catch {
|
|
417
|
+
}
|
|
418
|
+
setTimeout(() => {
|
|
419
|
+
try {
|
|
420
|
+
stream.close();
|
|
421
|
+
stream.destroy();
|
|
422
|
+
} catch {
|
|
423
|
+
}
|
|
424
|
+
}, 150);
|
|
425
|
+
if (!device.persistent) {
|
|
426
|
+
client.end();
|
|
427
|
+
}
|
|
428
|
+
reject(new Error(`Command aborted on remote device "${id}"; interruption requested, remote processes may continue.`));
|
|
429
|
+
};
|
|
430
|
+
if (signal) {
|
|
431
|
+
if (signal.aborted) {
|
|
432
|
+
onAbort();
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
436
|
+
}
|
|
437
|
+
stream.on("close", (code, exitSignal) => {
|
|
438
|
+
if (signal) signal.removeEventListener("abort", onAbort);
|
|
439
|
+
if (isAborted) return;
|
|
440
|
+
if (!device.persistent) {
|
|
441
|
+
client.end();
|
|
442
|
+
}
|
|
443
|
+
const maxLines = device.maxOutputLines || 300;
|
|
444
|
+
const lines = stdoutBuf.split("\n");
|
|
445
|
+
let finalStdout = stdoutBuf;
|
|
446
|
+
if (lines.length > maxLines) {
|
|
447
|
+
finalStdout = lines.slice(-maxLines).join("\n");
|
|
448
|
+
isTruncated = true;
|
|
449
|
+
}
|
|
450
|
+
resolve2({
|
|
451
|
+
stdout: finalStdout,
|
|
452
|
+
stderr: stderrBuf,
|
|
453
|
+
exitCode: typeof code === "number" ? code : -1,
|
|
454
|
+
durationMs: Date.now() - startTime,
|
|
455
|
+
isTruncated,
|
|
456
|
+
exitSignal
|
|
457
|
+
});
|
|
458
|
+
}).on("data", (data) => {
|
|
459
|
+
if (Buffer.byteLength(stdoutBuf, "utf-8") < maxBytes) {
|
|
460
|
+
const remaining = maxBytes - Buffer.byteLength(stdoutBuf, "utf-8");
|
|
461
|
+
stdoutBuf += data.subarray(0, remaining).toString("utf-8");
|
|
462
|
+
if (data.length > remaining) {
|
|
463
|
+
stdoutBuf += "\n... [output truncated by pi-remote-mesh]";
|
|
464
|
+
isTruncated = true;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}).stderr.on("data", (data) => {
|
|
468
|
+
if (Buffer.byteLength(stderrBuf, "utf-8") < maxBytes) {
|
|
469
|
+
const remaining = maxBytes - Buffer.byteLength(stderrBuf, "utf-8");
|
|
470
|
+
stderrBuf += data.subarray(0, remaining).toString("utf-8");
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
});
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
async getSftp(id) {
|
|
477
|
+
const device = this.getDevice(id);
|
|
478
|
+
if (device.persistent && this.sftpWrappers.has(id)) {
|
|
479
|
+
return this.sftpWrappers.get(id);
|
|
480
|
+
}
|
|
481
|
+
const client = await this.getClient(id);
|
|
482
|
+
return new Promise((resolve2, reject) => {
|
|
483
|
+
client.sftp((err, sftp) => {
|
|
484
|
+
if (err) {
|
|
485
|
+
if (!device.persistent) client.end();
|
|
486
|
+
return reject(err);
|
|
487
|
+
}
|
|
488
|
+
if (device.persistent) {
|
|
489
|
+
this.sftpWrappers.set(id, sftp);
|
|
490
|
+
} else {
|
|
491
|
+
this.ephemeralSftpClients.set(sftp, client);
|
|
492
|
+
}
|
|
493
|
+
resolve2(sftp);
|
|
494
|
+
});
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
releaseSftp(sftp) {
|
|
498
|
+
const client = this.ephemeralSftpClients.get(sftp);
|
|
499
|
+
if (!client) return;
|
|
500
|
+
this.ephemeralSftpClients.delete(sftp);
|
|
501
|
+
try {
|
|
502
|
+
sftp.end();
|
|
503
|
+
} finally {
|
|
504
|
+
client.end();
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
async readFile(id, remotePath, maxBytes = 64 * 1024, signal) {
|
|
508
|
+
signal?.throwIfAborted();
|
|
509
|
+
if (!Number.isFinite(maxBytes) || maxBytes <= 0) {
|
|
510
|
+
throw new Error("maxBytes must be a positive finite number");
|
|
511
|
+
}
|
|
512
|
+
const sftp = await awaitAbortable(this.getSftp(id), signal, (late) => this.releaseSftp(late));
|
|
513
|
+
try {
|
|
514
|
+
signal?.throwIfAborted();
|
|
515
|
+
return await new Promise((resolve2, reject) => {
|
|
516
|
+
let settled = false;
|
|
517
|
+
let stream;
|
|
518
|
+
const finish = (error, result) => {
|
|
519
|
+
if (settled) return;
|
|
520
|
+
settled = true;
|
|
521
|
+
signal?.removeEventListener("abort", onAbort);
|
|
522
|
+
if (error) reject(error);
|
|
523
|
+
else resolve2(result);
|
|
524
|
+
};
|
|
525
|
+
const onAbort = () => {
|
|
526
|
+
stream?.destroy();
|
|
527
|
+
finish(new Error("Read aborted by user"));
|
|
528
|
+
};
|
|
529
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
530
|
+
if (signal?.aborted) {
|
|
531
|
+
onAbort();
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
sftp.stat(remotePath, (err, stats) => {
|
|
535
|
+
if (settled) return;
|
|
536
|
+
if (err) return finish(new Error(`Remote file stat failed: ${remotePath} (${err.message})`));
|
|
537
|
+
if (stats.size > maxBytes) return finish(new Error(`Remote file is too large (${stats.size} bytes > limit ${maxBytes} bytes)`));
|
|
538
|
+
stream = sftp.createReadStream(remotePath);
|
|
539
|
+
const chunks = [];
|
|
540
|
+
let bytes = 0;
|
|
541
|
+
stream.on("data", (chunk) => {
|
|
542
|
+
if (settled) return;
|
|
543
|
+
bytes += chunk.length;
|
|
544
|
+
if (bytes > maxBytes) {
|
|
545
|
+
stream?.destroy();
|
|
546
|
+
return finish(new Error(`Remote file exceeded the ${maxBytes}-byte limit while reading`));
|
|
547
|
+
}
|
|
548
|
+
chunks.push(chunk);
|
|
549
|
+
});
|
|
550
|
+
stream.on("end", () => finish(void 0, { content: Buffer.concat(chunks).toString("utf8"), bytes }));
|
|
551
|
+
stream.on("error", (error) => finish(error));
|
|
552
|
+
});
|
|
553
|
+
});
|
|
554
|
+
} finally {
|
|
555
|
+
this.releaseSftp(sftp);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
async ensureRemoteDir(sftp, remoteDir, signal) {
|
|
559
|
+
const normalized = remoteDir.replace(/\\/g, "/");
|
|
560
|
+
const isAbsolute = normalized.startsWith("/");
|
|
561
|
+
const parts = normalized.split("/").filter(Boolean);
|
|
562
|
+
let current = isAbsolute ? "" : ".";
|
|
563
|
+
for (const part of parts) {
|
|
564
|
+
signal?.throwIfAborted();
|
|
565
|
+
current = isAbsolute ? `${current}/${part}` : `${current}/${part}`;
|
|
566
|
+
await new Promise((resolve2, reject) => {
|
|
567
|
+
sftp.stat(current, (err, stats) => {
|
|
568
|
+
if (signal?.aborted) return reject(signal.reason ?? new Error("Aborted"));
|
|
569
|
+
if (!err && stats?.isDirectory()) {
|
|
570
|
+
return resolve2();
|
|
571
|
+
}
|
|
572
|
+
sftp.mkdir(current, (mkdirErr) => {
|
|
573
|
+
if (signal?.aborted) return reject(signal.reason ?? new Error("Aborted"));
|
|
574
|
+
if (!mkdirErr) return resolve2();
|
|
575
|
+
sftp.stat(current, (retryErr, retryStats) => {
|
|
576
|
+
if (!retryErr && retryStats?.isDirectory()) return resolve2();
|
|
577
|
+
reject(mkdirErr);
|
|
578
|
+
});
|
|
579
|
+
});
|
|
580
|
+
});
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
async writeFile(id, remotePath, content, signal) {
|
|
585
|
+
signal?.throwIfAborted();
|
|
586
|
+
const sftp = await awaitAbortable(this.getSftp(id), signal, (late) => this.releaseSftp(late));
|
|
587
|
+
try {
|
|
588
|
+
const buffer = Buffer.from(content, "utf-8");
|
|
589
|
+
const normalizedPath = remotePath.replace(/\\/g, "/");
|
|
590
|
+
const parentDir = path2.posix.dirname(normalizedPath);
|
|
591
|
+
if (parentDir && parentDir !== "." && parentDir !== "/") {
|
|
592
|
+
await awaitAbortable(this.ensureRemoteDir(sftp, parentDir, signal), signal);
|
|
593
|
+
}
|
|
594
|
+
signal?.throwIfAborted();
|
|
595
|
+
return await new Promise((resolve2, reject) => {
|
|
596
|
+
const tempPath = `${remotePath}.pi-remote-mesh-${randomBytes(16).toString("hex")}`;
|
|
597
|
+
const writeStream = sftp.createWriteStream(tempPath, { flags: "wx", mode: 384 });
|
|
598
|
+
let settled = false;
|
|
599
|
+
let opened = false;
|
|
600
|
+
let committing = false;
|
|
601
|
+
const cleanup = () => signal?.removeEventListener("abort", onAbort);
|
|
602
|
+
const fail = (err) => {
|
|
603
|
+
if (settled) return;
|
|
604
|
+
settled = true;
|
|
605
|
+
cleanup();
|
|
606
|
+
if (opened) sftp.unlink(tempPath, () => reject(err));
|
|
607
|
+
else reject(err);
|
|
608
|
+
};
|
|
609
|
+
const onAbort = () => {
|
|
610
|
+
if (settled || committing) return;
|
|
611
|
+
writeStream.destroy();
|
|
612
|
+
fail(new Error("Write aborted by user; temporary-file cleanup is best effort"));
|
|
613
|
+
};
|
|
614
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
615
|
+
writeStream.on("open", () => {
|
|
616
|
+
opened = true;
|
|
617
|
+
if (settled) sftp.unlink(tempPath, () => void 0);
|
|
618
|
+
});
|
|
619
|
+
writeStream.on("close", () => {
|
|
620
|
+
if (settled) return;
|
|
621
|
+
if (signal?.aborted) return onAbort();
|
|
622
|
+
committing = true;
|
|
623
|
+
cleanup();
|
|
624
|
+
sftp.rename(tempPath, remotePath, (err) => {
|
|
625
|
+
if (err) return fail(err);
|
|
626
|
+
settled = true;
|
|
627
|
+
resolve2({ bytes: buffer.length });
|
|
628
|
+
});
|
|
629
|
+
});
|
|
630
|
+
writeStream.on("error", (err) => fail(err));
|
|
631
|
+
if (signal?.aborted) onAbort();
|
|
632
|
+
else writeStream.end(buffer);
|
|
633
|
+
});
|
|
634
|
+
} finally {
|
|
635
|
+
this.releaseSftp(sftp);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
async disconnect(id) {
|
|
639
|
+
this.generations.set(id, (this.generations.get(id) ?? 0) + 1);
|
|
640
|
+
this.connecting.delete(id);
|
|
641
|
+
const client = this.clients.get(id) ?? this.pendingClients.get(id);
|
|
642
|
+
this.pendingClients.delete(id);
|
|
643
|
+
if (!client) return false;
|
|
644
|
+
return new Promise((resolve2, reject) => {
|
|
645
|
+
this.sftpWrappers.delete(id);
|
|
646
|
+
this.clients.delete(id);
|
|
647
|
+
const timer = setTimeout(() => reject(new Error(`SSH disconnect timed out for "${id}"; closure is unconfirmed.`)), 1500);
|
|
648
|
+
client.once("close", () => {
|
|
649
|
+
clearTimeout(timer);
|
|
650
|
+
resolve2(true);
|
|
651
|
+
});
|
|
652
|
+
client.end();
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
async disconnectAll() {
|
|
656
|
+
const results = {};
|
|
657
|
+
for (const id of /* @__PURE__ */ new Set([...this.clients.keys(), ...this.connecting.keys()])) {
|
|
658
|
+
results[id] = await this.disconnect(id);
|
|
659
|
+
}
|
|
660
|
+
return results;
|
|
661
|
+
}
|
|
662
|
+
getStatus(id, activeTools = [], availableTools = []) {
|
|
663
|
+
const dev = this.getDevice(id);
|
|
664
|
+
const isLocal = isLocalHost(dev);
|
|
665
|
+
const isConnected = this.isConnected(id);
|
|
666
|
+
return {
|
|
667
|
+
id: dev.id,
|
|
668
|
+
name: dev.name || dev.id,
|
|
669
|
+
host: dev.host,
|
|
670
|
+
port: dev.port || 22,
|
|
671
|
+
username: dev.username,
|
|
672
|
+
isLocal,
|
|
673
|
+
isConnected,
|
|
674
|
+
persistent: dev.persistent ?? true,
|
|
675
|
+
features: dev.features || ["exec", "sftp", "status"],
|
|
676
|
+
activeTools,
|
|
677
|
+
availableTools
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
};
|
|
681
|
+
|
|
682
|
+
// src/tool-registry.ts
|
|
683
|
+
import { Type } from "typebox";
|
|
684
|
+
|
|
685
|
+
// src/status-bar.ts
|
|
686
|
+
function getLegacyStatusKey(id) {
|
|
687
|
+
const cleanId = id.toLowerCase();
|
|
688
|
+
if (cleanId === "vps" || cleanId.includes("tokyo")) {
|
|
689
|
+
return "or-tokyo-ssh";
|
|
690
|
+
}
|
|
691
|
+
if (cleanId === "win" || cleanId.includes("pc")) {
|
|
692
|
+
return "win-pc-ssh";
|
|
693
|
+
}
|
|
694
|
+
if (cleanId === "phone" || cleanId.includes("termux")) {
|
|
695
|
+
return "phone-termux-ssh";
|
|
696
|
+
}
|
|
697
|
+
if (cleanId === "mac") {
|
|
698
|
+
return "mac-mini-ssh";
|
|
699
|
+
}
|
|
700
|
+
return `mesh-${id}`;
|
|
701
|
+
}
|
|
702
|
+
function getDeviceDisplayLabel(id, name) {
|
|
703
|
+
const cleanId = id.toLowerCase();
|
|
704
|
+
if (cleanId === "vps" || cleanId.includes("tokyo")) {
|
|
705
|
+
return "VPS: or-tokyo";
|
|
706
|
+
}
|
|
707
|
+
if (cleanId === "win" || cleanId.includes("pc")) {
|
|
708
|
+
return "Win: win-pc";
|
|
709
|
+
}
|
|
710
|
+
if (cleanId === "phone" || cleanId.includes("termux")) {
|
|
711
|
+
return "\u624B\u673A: phone-termux";
|
|
712
|
+
}
|
|
713
|
+
if (cleanId === "mac") {
|
|
714
|
+
return "Mac: mini";
|
|
715
|
+
}
|
|
716
|
+
const short = (name || id).replace(/\s+(VPS|Host|PC)$/i, "").trim();
|
|
717
|
+
return `${id.toUpperCase()}: ${short}`;
|
|
718
|
+
}
|
|
719
|
+
function updateMeshStatusBar(ctx, config, engine) {
|
|
720
|
+
if (!ctx?.ui) return;
|
|
721
|
+
for (const [id, dev] of Object.entries(config.devices)) {
|
|
722
|
+
const statusKey = getLegacyStatusKey(id);
|
|
723
|
+
if (isLocalHost(dev)) {
|
|
724
|
+
ctx.ui.setStatus(statusKey, void 0);
|
|
725
|
+
continue;
|
|
726
|
+
}
|
|
727
|
+
const isConnected = engine.isConnected(id);
|
|
728
|
+
const label = getDeviceDisplayLabel(id, dev.name);
|
|
729
|
+
const isPrimaryDevice = /vps|win|tokyo|pc/i.test(id);
|
|
730
|
+
if (!isPrimaryDevice && !isConnected) {
|
|
731
|
+
ctx.ui.setStatus(statusKey, void 0);
|
|
732
|
+
continue;
|
|
733
|
+
}
|
|
734
|
+
const text = isConnected ? `${label} \u5DF2\u8FDE\u63A5` : `${label} \u6309\u9700\u8FDE\u63A5`;
|
|
735
|
+
const color = isConnected ? "success" : "dim";
|
|
736
|
+
ctx.ui.setStatus(statusKey, ctx.ui.theme.fg(color, text));
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
function clearMeshStatusBar(ctx, config) {
|
|
740
|
+
if (!ctx?.ui) return;
|
|
741
|
+
for (const id of Object.keys(config.devices)) {
|
|
742
|
+
ctx.ui.setStatus(getLegacyStatusKey(id), void 0);
|
|
743
|
+
ctx.ui.setStatus(`mesh-${id}`, void 0);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// src/tool-registry.ts
|
|
748
|
+
function getToolNamesForDevice(device, style = "compact") {
|
|
749
|
+
const prefix = device.toolPrefix || (style === "compact" ? `${device.id}_` : `remote_${device.id}_`);
|
|
750
|
+
const features = new Set(device.features || ["exec", "sftp", "status"]);
|
|
751
|
+
const names = {
|
|
752
|
+
all: []
|
|
753
|
+
};
|
|
754
|
+
if (features.has("exec")) {
|
|
755
|
+
names.exec = `${prefix}exec`;
|
|
756
|
+
names.all.push(names.exec);
|
|
757
|
+
}
|
|
758
|
+
if (features.has("sftp")) {
|
|
759
|
+
names.read = `${prefix}read`;
|
|
760
|
+
names.write = `${prefix}write`;
|
|
761
|
+
names.all.push(names.read, names.write);
|
|
762
|
+
}
|
|
763
|
+
if (features.has("status")) {
|
|
764
|
+
names.status = `${prefix}status`;
|
|
765
|
+
names.all.push(names.status);
|
|
766
|
+
}
|
|
767
|
+
return names;
|
|
768
|
+
}
|
|
769
|
+
function registerMeshTools(pi, config, engine) {
|
|
770
|
+
const allMeshToolNames = /* @__PURE__ */ new Set();
|
|
771
|
+
const deviceToolMap = /* @__PURE__ */ new Map();
|
|
772
|
+
const approved = /* @__PURE__ */ new Set();
|
|
773
|
+
let sessionGeneration = 0;
|
|
774
|
+
const deviceGenerations = /* @__PURE__ */ new Map();
|
|
775
|
+
let approvalQueue = Promise.resolve();
|
|
776
|
+
const requireApproval = (id) => {
|
|
777
|
+
if (!approved.has(id)) throw new Error(`Device "${id}" is not authorized in this session. Enable it and approve first.`);
|
|
778
|
+
};
|
|
779
|
+
for (const [id, dev] of Object.entries(config.devices)) {
|
|
780
|
+
const toolNames = getToolNamesForDevice(dev, config.toolNamingStyle);
|
|
781
|
+
deviceToolMap.set(id, toolNames.all);
|
|
782
|
+
for (const name of toolNames.all) {
|
|
783
|
+
if (allMeshToolNames.has(name)) {
|
|
784
|
+
throw new Error(`Duplicate remote tool name "${name}". Set unique toolPrefix values.`);
|
|
785
|
+
}
|
|
786
|
+
allMeshToolNames.add(name);
|
|
787
|
+
}
|
|
788
|
+
if (toolNames.exec) {
|
|
789
|
+
pi.registerTool({
|
|
790
|
+
name: toolNames.exec,
|
|
791
|
+
defaultActive: false,
|
|
792
|
+
label: `${dev.name || id} Exec`,
|
|
793
|
+
description: `Execute a shell command on remote machine "${dev.name || id}" (${dev.host}). Returns stdout, stderr and exit code.`,
|
|
794
|
+
parameters: Type.Object({
|
|
795
|
+
command: Type.String({ description: "The shell command to execute remotely" }),
|
|
796
|
+
cwd: Type.Optional(Type.String({ description: "Working directory on the remote machine (optional)" }))
|
|
797
|
+
}),
|
|
798
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
799
|
+
async execute(_id, params, signal, _onUpdate, _ctx) {
|
|
800
|
+
try {
|
|
801
|
+
requireApproval(id);
|
|
802
|
+
const res = await engine.exec(id, params.command, params.cwd, signal);
|
|
803
|
+
if (_ctx?.ui) updateMeshStatusBar(_ctx, config, engine);
|
|
804
|
+
let text = res.stdout;
|
|
805
|
+
if (res.stderr) {
|
|
806
|
+
text += (text ? "\n" : "") + `[stderr]
|
|
807
|
+
${res.stderr}`;
|
|
808
|
+
}
|
|
809
|
+
if (res.exitCode !== 0) {
|
|
810
|
+
text += (text ? "\n" : "") + `[Process exited with code ${res.exitCode}]`;
|
|
811
|
+
}
|
|
812
|
+
return {
|
|
813
|
+
content: [{ type: "text", text: text || "(command completed with empty output)" }],
|
|
814
|
+
details: res,
|
|
815
|
+
isError: res.exitCode !== 0
|
|
816
|
+
};
|
|
817
|
+
} catch (err) {
|
|
818
|
+
return {
|
|
819
|
+
content: [{ type: "text", text: `SSH Error on ${id}: ${err instanceof Error ? err.message : String(err)}` }],
|
|
820
|
+
details: { error: err instanceof Error ? err.message : String(err) },
|
|
821
|
+
isError: true
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
if (toolNames.read) {
|
|
828
|
+
pi.registerTool({
|
|
829
|
+
name: toolNames.read,
|
|
830
|
+
defaultActive: false,
|
|
831
|
+
label: `${dev.name || id} Read`,
|
|
832
|
+
description: `Read text content of a remote file on "${dev.name || id}" (${dev.host}) via SFTP.`,
|
|
833
|
+
parameters: Type.Object({
|
|
834
|
+
path: Type.String({ description: "Remote absolute or relative file path" }),
|
|
835
|
+
maxBytes: Type.Optional(Type.Number({ description: "Maximum bytes to read (default 64KB)", minimum: 1 }))
|
|
836
|
+
}),
|
|
837
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
838
|
+
async execute(_id, params, signal, _onUpdate, _ctx) {
|
|
839
|
+
try {
|
|
840
|
+
requireApproval(id);
|
|
841
|
+
const res = await engine.readFile(id, params.path, params.maxBytes, signal);
|
|
842
|
+
if (_ctx?.ui) updateMeshStatusBar(_ctx, config, engine);
|
|
843
|
+
return {
|
|
844
|
+
content: [{ type: "text", text: res.content }],
|
|
845
|
+
details: { bytes: res.bytes, path: params.path },
|
|
846
|
+
isError: false
|
|
847
|
+
};
|
|
848
|
+
} catch (err) {
|
|
849
|
+
return {
|
|
850
|
+
content: [{ type: "text", text: `SFTP Read Error on ${id}: ${err instanceof Error ? err.message : String(err)}` }],
|
|
851
|
+
details: { error: err instanceof Error ? err.message : String(err), path: params.path },
|
|
852
|
+
isError: true
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
if (toolNames.write) {
|
|
859
|
+
pi.registerTool({
|
|
860
|
+
name: toolNames.write,
|
|
861
|
+
defaultActive: false,
|
|
862
|
+
label: `${dev.name || id} Write`,
|
|
863
|
+
description: `Write text content to a remote file on "${dev.name || id}" (${dev.host}) via SFTP.`,
|
|
864
|
+
parameters: Type.Object({
|
|
865
|
+
path: Type.String({ description: "Remote destination file path" }),
|
|
866
|
+
content: Type.String({ description: "Content to write" })
|
|
867
|
+
}),
|
|
868
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
|
|
869
|
+
async execute(_id, params, signal, _onUpdate, _ctx) {
|
|
870
|
+
try {
|
|
871
|
+
requireApproval(id);
|
|
872
|
+
const res = await engine.writeFile(id, params.path, params.content, signal);
|
|
873
|
+
if (_ctx?.ui) updateMeshStatusBar(_ctx, config, engine);
|
|
874
|
+
return {
|
|
875
|
+
content: [{ type: "text", text: `Successfully wrote ${res.bytes} bytes to ${params.path} on ${id}.` }],
|
|
876
|
+
details: { bytes: res.bytes, path: params.path },
|
|
877
|
+
isError: false
|
|
878
|
+
};
|
|
879
|
+
} catch (err) {
|
|
880
|
+
return {
|
|
881
|
+
content: [{ type: "text", text: `SFTP Write Error on ${id}: ${err instanceof Error ? err.message : String(err)}` }],
|
|
882
|
+
details: { error: err instanceof Error ? err.message : String(err), path: params.path },
|
|
883
|
+
isError: true
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
if (toolNames.status) {
|
|
890
|
+
pi.registerTool({
|
|
891
|
+
name: toolNames.status,
|
|
892
|
+
defaultActive: false,
|
|
893
|
+
label: `${dev.name || id} Status`,
|
|
894
|
+
description: `Check connection and reachability status for remote machine "${dev.name || id}".`,
|
|
895
|
+
parameters: Type.Object({}),
|
|
896
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
897
|
+
async execute(_id, _params, _signal, _onUpdate, _ctx) {
|
|
898
|
+
const active = pi.getActiveTools();
|
|
899
|
+
const status = engine.getStatus(id, active.filter((t) => toolNames.all.includes(t)), toolNames.all);
|
|
900
|
+
if (_ctx?.ui) updateMeshStatusBar(_ctx, config, engine);
|
|
901
|
+
return {
|
|
902
|
+
content: [{ type: "text", text: JSON.stringify(status, null, 2) }],
|
|
903
|
+
details: status,
|
|
904
|
+
isError: false
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
pi.on("session_start", () => {
|
|
911
|
+
sessionGeneration++;
|
|
912
|
+
approved.clear();
|
|
913
|
+
if (config.onDemandExposure) {
|
|
914
|
+
const currentActive = pi.getActiveTools();
|
|
915
|
+
pi.setActiveTools(currentActive.filter((t) => !allMeshToolNames.has(t)));
|
|
916
|
+
}
|
|
917
|
+
});
|
|
918
|
+
pi.on("session_shutdown", async () => {
|
|
919
|
+
sessionGeneration++;
|
|
920
|
+
approved.clear();
|
|
921
|
+
await engine.disconnectAll();
|
|
922
|
+
});
|
|
923
|
+
const handleControl = async (targetDevice, action, ctx) => {
|
|
924
|
+
if (targetDevice !== "all" && !Object.hasOwn(config.devices, targetDevice)) throw new Error(`Unknown device: ${targetDevice}`);
|
|
925
|
+
if (!["enable", "disable", "disconnect", "status"].includes(action)) throw new Error(`Unknown action: ${action}`);
|
|
926
|
+
const targets = targetDevice === "all" ? Object.keys(config.devices) : [targetDevice];
|
|
927
|
+
if (action === "enable") {
|
|
928
|
+
const generation = sessionGeneration;
|
|
929
|
+
const deviceSnapshot = targets.map((id) => deviceGenerations.get(id) ?? 0);
|
|
930
|
+
const requestApproval = approvalQueue.then(async () => {
|
|
931
|
+
ctx?.signal?.throwIfAborted();
|
|
932
|
+
if (generation !== sessionGeneration || targets.some((id, i) => (deviceGenerations.get(id) ?? 0) !== deviceSnapshot[i])) {
|
|
933
|
+
throw new Error("Session or device authorization changed while awaiting remote approval.");
|
|
934
|
+
}
|
|
935
|
+
const pending = targets.filter((id) => !approved.has(id));
|
|
936
|
+
if (!pending.length) return;
|
|
937
|
+
if (!ctx?.hasUI) throw new Error("Interactive approval required; no UI is available.");
|
|
938
|
+
const description = pending.map((id) => `${id}: ${config.devices[id].username}@${config.devices[id].host}:${config.devices[id].port ?? 22}`).join("\n");
|
|
939
|
+
const ok = await ctx.ui.confirm("Authorize remote devices for this session?", `${description}
|
|
940
|
+
|
|
941
|
+
After approval, commands and file writes are permitted without further prompts until disconnect or session restart.`);
|
|
942
|
+
ctx.signal?.throwIfAborted();
|
|
943
|
+
if (generation !== sessionGeneration || targets.some((id, i) => (deviceGenerations.get(id) ?? 0) !== deviceSnapshot[i])) {
|
|
944
|
+
throw new Error("Session or device authorization changed while awaiting remote approval.");
|
|
945
|
+
}
|
|
946
|
+
if (!ok) throw new Error("Remote device authorization declined.");
|
|
947
|
+
for (const id of pending) approved.add(id);
|
|
948
|
+
});
|
|
949
|
+
approvalQueue = requestApproval.catch(() => {
|
|
950
|
+
});
|
|
951
|
+
await requestApproval;
|
|
952
|
+
}
|
|
953
|
+
const activeSet = new Set(pi.getActiveTools());
|
|
954
|
+
const validDeviceIds = Object.keys(config.devices);
|
|
955
|
+
if (action === "status") {
|
|
956
|
+
const summary = {};
|
|
957
|
+
const targets2 = targetDevice === "all" ? validDeviceIds : [targetDevice];
|
|
958
|
+
for (const devId of targets2) {
|
|
959
|
+
if (!config.devices[devId]) continue;
|
|
960
|
+
const tools = deviceToolMap.get(devId) || [];
|
|
961
|
+
summary[devId] = engine.getStatus(
|
|
962
|
+
devId,
|
|
963
|
+
tools.filter((t) => activeSet.has(t)),
|
|
964
|
+
tools
|
|
965
|
+
);
|
|
966
|
+
}
|
|
967
|
+
return { action, summary, isError: false };
|
|
968
|
+
}
|
|
969
|
+
const devicesToActOn = targetDevice === "all" ? validDeviceIds : [targetDevice];
|
|
970
|
+
const affectedTools = [];
|
|
971
|
+
const disconnectResults = {};
|
|
972
|
+
for (const devId of devicesToActOn) {
|
|
973
|
+
const tools = deviceToolMap.get(devId) || [];
|
|
974
|
+
affectedTools.push(...tools);
|
|
975
|
+
if (action === "enable") {
|
|
976
|
+
for (const t of tools) activeSet.add(t);
|
|
977
|
+
} else if (action === "disable" || action === "disconnect") {
|
|
978
|
+
for (const t of tools) activeSet.delete(t);
|
|
979
|
+
}
|
|
980
|
+
if (action === "disconnect") {
|
|
981
|
+
approved.delete(devId);
|
|
982
|
+
deviceGenerations.set(devId, (deviceGenerations.get(devId) ?? 0) + 1);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
pi.setActiveTools([...activeSet]);
|
|
986
|
+
if (action === "disconnect") {
|
|
987
|
+
for (const devId of devicesToActOn) disconnectResults[devId] = await engine.disconnect(devId);
|
|
988
|
+
}
|
|
989
|
+
return {
|
|
990
|
+
target: targetDevice,
|
|
991
|
+
action,
|
|
992
|
+
activeToolsCount: activeSet.size,
|
|
993
|
+
affectedTools,
|
|
994
|
+
disconnectResults: action === "disconnect" ? disconnectResults : void 0,
|
|
995
|
+
isError: false
|
|
996
|
+
};
|
|
997
|
+
};
|
|
998
|
+
const deviceLiterals = Object.keys(config.devices).map((d) => Type.Literal(d));
|
|
999
|
+
deviceLiterals.push(Type.Literal("all"));
|
|
1000
|
+
const deviceSchema = deviceLiterals.length > 0 ? Type.Union(deviceLiterals) : Type.String();
|
|
1001
|
+
pi.registerTool({
|
|
1002
|
+
name: "remote_enable",
|
|
1003
|
+
label: "Remote Devices Mesh Dispatcher",
|
|
1004
|
+
description: `Manage SSH mesh device tools (${Object.keys(config.devices).join(", ") || "none configured"}).
|
|
1005
|
+
- action="enable": Expose the device tools to the model for the next request without reload.
|
|
1006
|
+
- action="disable": Hide device tools to save prompt tokens.
|
|
1007
|
+
- action="disconnect": Close persistent SSH connection and hide tools.
|
|
1008
|
+
- action="status": Query device connectivity and tool activation states.`,
|
|
1009
|
+
parameters: Type.Object({
|
|
1010
|
+
device: deviceSchema,
|
|
1011
|
+
action: Type.Optional(
|
|
1012
|
+
Type.Union(
|
|
1013
|
+
[
|
|
1014
|
+
Type.Literal("enable"),
|
|
1015
|
+
Type.Literal("disable"),
|
|
1016
|
+
Type.Literal("disconnect"),
|
|
1017
|
+
Type.Literal("status")
|
|
1018
|
+
],
|
|
1019
|
+
{ description: "Default is 'enable'" }
|
|
1020
|
+
)
|
|
1021
|
+
)
|
|
1022
|
+
}),
|
|
1023
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
1024
|
+
async execute(_id, params, _signal, _onUpdate, _ctx) {
|
|
1025
|
+
try {
|
|
1026
|
+
const result = await handleControl(params.device, params.action || "enable", _ctx);
|
|
1027
|
+
if (_ctx?.ui) updateMeshStatusBar(_ctx, config, engine);
|
|
1028
|
+
return {
|
|
1029
|
+
content: [
|
|
1030
|
+
{
|
|
1031
|
+
type: "text",
|
|
1032
|
+
text: JSON.stringify(result, null, 2) + `
|
|
1033
|
+
[Notice: If enabled, targeted device tools will be accessible on the next turn. Tokens saved when inactive.]`
|
|
1034
|
+
}
|
|
1035
|
+
],
|
|
1036
|
+
details: result,
|
|
1037
|
+
isError: false
|
|
1038
|
+
};
|
|
1039
|
+
} catch (err) {
|
|
1040
|
+
return {
|
|
1041
|
+
content: [{ type: "text", text: `Control error: ${err instanceof Error ? err.message : String(err)}` }],
|
|
1042
|
+
details: { error: err instanceof Error ? err.message : String(err) },
|
|
1043
|
+
isError: true
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
});
|
|
1048
|
+
return {
|
|
1049
|
+
handleControl,
|
|
1050
|
+
allMeshToolNames,
|
|
1051
|
+
deviceToolMap
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
// src/commands.ts
|
|
1056
|
+
import * as fs3 from "fs";
|
|
1057
|
+
import * as path3 from "path";
|
|
1058
|
+
import * as os2 from "os";
|
|
1059
|
+
function registerMeshCommands(pi, config, loadedFrom, engine, handleControl) {
|
|
1060
|
+
const deviceList = Object.keys(config.devices);
|
|
1061
|
+
const commandHandler = async (args, ctx) => {
|
|
1062
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
1063
|
+
const action = parts[0] || "status";
|
|
1064
|
+
const target = parts[1] || "all";
|
|
1065
|
+
if (action === "init") {
|
|
1066
|
+
const targetDir = path3.join(os2.homedir(), ".pi");
|
|
1067
|
+
const targetFile = path3.join(targetDir, DEFAULT_CONFIG_FILENAME);
|
|
1068
|
+
if (fs3.existsSync(targetFile)) {
|
|
1069
|
+
ctx.ui.notify(`Config file already exists at: ${targetFile}`, "warning");
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
fs3.mkdirSync(targetDir, { recursive: true });
|
|
1073
|
+
const template = generateTemplateConfig();
|
|
1074
|
+
fs3.writeFileSync(targetFile, JSON.stringify(template, null, 2), { encoding: "utf-8", mode: 384 });
|
|
1075
|
+
ctx.ui.notify(`Generated template configuration at: ${targetFile}`, "info");
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
if (action === "test") {
|
|
1079
|
+
if (!parts[1]) {
|
|
1080
|
+
ctx.ui.notify(`Usage: /remote-mesh test <device_id>`, "warning");
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
const devId = parts[1];
|
|
1084
|
+
if (!config.devices[devId]) {
|
|
1085
|
+
ctx.ui.notify(`Device "${devId}" not found in config. Available: ${deviceList.join(", ")}`, "error");
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
ctx.ui.notify(`Testing SSH connection to "${devId}" (${config.devices[devId].host})...`, "info");
|
|
1089
|
+
try {
|
|
1090
|
+
await handleControl(devId, "enable", ctx);
|
|
1091
|
+
const res = await engine.exec(devId, "echo 'SSH_CONNECTION_SUCCESS' && uname -a || ver");
|
|
1092
|
+
if (res.exitCode !== 0) throw new Error(`Connection test exited with code ${res.exitCode}: ${res.stderr}`);
|
|
1093
|
+
ctx.ui.notify(`[${devId}] Connected successfully!
|
|
1094
|
+
${res.stdout.trim()}`, "info");
|
|
1095
|
+
} catch (err) {
|
|
1096
|
+
ctx.ui.notify(`[${devId}] Connection failed: ${err instanceof Error ? err.message : String(err)}`, "error");
|
|
1097
|
+
}
|
|
1098
|
+
return;
|
|
1099
|
+
}
|
|
1100
|
+
if (["enable", "disable", "disconnect", "status"].includes(action)) {
|
|
1101
|
+
try {
|
|
1102
|
+
const res = await handleControl(target, action, ctx);
|
|
1103
|
+
updateMeshStatusBar(ctx, config, engine);
|
|
1104
|
+
if (action === "status") {
|
|
1105
|
+
const configInfo = loadedFrom ? `Config: ${loadedFrom}` : "Config: (none loaded, run /remote-mesh init)";
|
|
1106
|
+
const statusOutput = JSON.stringify(res.summary, null, 2);
|
|
1107
|
+
ctx.ui.notify(`${configInfo}
|
|
1108
|
+
${statusOutput}`, "info");
|
|
1109
|
+
} else {
|
|
1110
|
+
ctx.ui.notify(`[Remote Mesh] ${action} on "${target}" completed.`, "info");
|
|
1111
|
+
}
|
|
1112
|
+
} catch (err) {
|
|
1113
|
+
ctx.ui.notify(`Error: ${err instanceof Error ? err.message : String(err)}`, "error");
|
|
1114
|
+
}
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
ctx.ui.notify(
|
|
1118
|
+
`Usage: /remote-mesh [status | enable | disable | disconnect | test | init] [device | all]`,
|
|
1119
|
+
"warning"
|
|
1120
|
+
);
|
|
1121
|
+
};
|
|
1122
|
+
const completions = [
|
|
1123
|
+
{ value: "status", label: "status - Show device and tool status" },
|
|
1124
|
+
{ value: "init", label: "init - Create ~/.pi/remote-mesh.json template" },
|
|
1125
|
+
...deviceList.flatMap((d) => [
|
|
1126
|
+
{ value: `enable ${d}`, label: `enable ${d} - Expose ${d} tools to model` },
|
|
1127
|
+
{ value: `disable ${d}`, label: `disable ${d} - Hide ${d} tools` },
|
|
1128
|
+
{ value: `disconnect ${d}`, label: `disconnect ${d} - Disconnect persistent SSH` },
|
|
1129
|
+
{ value: `test ${d}`, label: `test ${d} - Test connectivity` }
|
|
1130
|
+
]),
|
|
1131
|
+
{ value: "enable all", label: "enable all - Expose all tools" },
|
|
1132
|
+
{ value: "disable all", label: "disable all - Hide all tools" },
|
|
1133
|
+
{ value: "disconnect all", label: "disconnect all - Disconnect all devices" }
|
|
1134
|
+
];
|
|
1135
|
+
pi.registerCommand("remote-mesh", {
|
|
1136
|
+
description: "Manage multi-device SSH mesh: /remote-mesh [status|enable|disable|disconnect|test|init]",
|
|
1137
|
+
getArgumentCompletions(prefix) {
|
|
1138
|
+
return completions.filter((c) => c.value.startsWith(prefix));
|
|
1139
|
+
},
|
|
1140
|
+
handler: commandHandler
|
|
1141
|
+
});
|
|
1142
|
+
pi.registerCommand("remote-tools", {
|
|
1143
|
+
description: "Manage SSH tools (alias for /remote-mesh)",
|
|
1144
|
+
getArgumentCompletions(prefix) {
|
|
1145
|
+
return completions.filter((c) => c.value.startsWith(prefix));
|
|
1146
|
+
},
|
|
1147
|
+
handler: commandHandler
|
|
1148
|
+
});
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
// src/index.ts
|
|
1152
|
+
function index_default(pi) {
|
|
1153
|
+
const { config, loadedFrom } = loadMeshConfig();
|
|
1154
|
+
const engine = new SshEngine(config.devices);
|
|
1155
|
+
const { handleControl } = registerMeshTools(pi, config, engine);
|
|
1156
|
+
registerMeshCommands(pi, config, loadedFrom, engine, handleControl);
|
|
1157
|
+
pi.on("session_start", (_event, ctx) => {
|
|
1158
|
+
updateMeshStatusBar(ctx, config, engine);
|
|
1159
|
+
});
|
|
1160
|
+
pi.on("session_shutdown", async (_event, ctx) => {
|
|
1161
|
+
clearMeshStatusBar(ctx, config);
|
|
1162
|
+
});
|
|
1163
|
+
}
|
|
1164
|
+
export {
|
|
1165
|
+
DEFAULT_CONFIG_FILENAME,
|
|
1166
|
+
LEGACY_CONFIG_FILENAME,
|
|
1167
|
+
SshEngine,
|
|
1168
|
+
clearMeshStatusBar,
|
|
1169
|
+
index_default as default,
|
|
1170
|
+
findConfigFile,
|
|
1171
|
+
generateTemplateConfig,
|
|
1172
|
+
getConfigPaths,
|
|
1173
|
+
getToolNamesForDevice,
|
|
1174
|
+
isLocalHost,
|
|
1175
|
+
loadMeshConfig,
|
|
1176
|
+
normalizeDeviceConfig,
|
|
1177
|
+
quotePosixShell,
|
|
1178
|
+
registerMeshCommands,
|
|
1179
|
+
registerMeshTools,
|
|
1180
|
+
resolveUserPath,
|
|
1181
|
+
updateMeshStatusBar
|
|
1182
|
+
};
|
|
1183
|
+
//# sourceMappingURL=index.js.map
|