@aide-family/dsh-remote 0.0.0-stage → 0.6.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.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +793 -2
  3. package/bin/dsh-remote-terminal +82 -0
  4. package/cordis.patch.yml +3 -0
  5. package/docs/TERMINAL_ACTIONS.md +39 -0
  6. package/docs/assets/host-audit.png +0 -0
  7. package/docs/assets/host-manager.png +0 -0
  8. package/docs/assets/live-terminal.png +0 -0
  9. package/docs/assets/remote-ops.png +0 -0
  10. package/docs/assets/remote-terminal.png +0 -0
  11. package/docs/icon.svg +11 -0
  12. package/lib/api-helpers.js +325 -0
  13. package/lib/api.js +715 -0
  14. package/lib/approval.js +238 -0
  15. package/lib/audit.js +224 -0
  16. package/lib/client.js +4919 -0
  17. package/lib/config.js +762 -0
  18. package/lib/connection-profile.js +65 -0
  19. package/lib/host-registry.js +703 -0
  20. package/lib/host-store.js +139 -0
  21. package/lib/hosts.js +442 -0
  22. package/lib/index.js +419 -0
  23. package/lib/live-stream.js +121 -0
  24. package/lib/live.js +245 -0
  25. package/lib/policy/argv.js +77 -0
  26. package/lib/policy/command-guard.js +404 -0
  27. package/lib/policy/docker.js +140 -0
  28. package/lib/policy/index.js +21 -0
  29. package/lib/policy/inspection.js +111 -0
  30. package/lib/policy/kubectl.js +128 -0
  31. package/lib/policy/shell-command.js +525 -0
  32. package/lib/policy/shell-wrappers.js +143 -0
  33. package/lib/policy/ssh.js +53 -0
  34. package/lib/policy/sudo.js +38 -0
  35. package/lib/policy/systemctl.js +22 -0
  36. package/lib/policy/types.js +12 -0
  37. package/lib/prompt.js +29 -0
  38. package/lib/render.js +442 -0
  39. package/lib/runtime-deps.js +50 -0
  40. package/lib/ssh/auth.js +256 -0
  41. package/lib/ssh/connection.js +504 -0
  42. package/lib/ssh/errors.js +209 -0
  43. package/lib/ssh/exec.js +394 -0
  44. package/lib/ssh/known-hosts.js +313 -0
  45. package/lib/ssh/pty.js +472 -0
  46. package/lib/ssh/sftp.js +589 -0
  47. package/lib/ssh/transport.js +801 -0
  48. package/lib/ssh-config.js +395 -0
  49. package/lib/terminal/bridge.cjs +305 -0
  50. package/lib/terminal/connection-login.js +188 -0
  51. package/lib/terminal/manager.js +656 -0
  52. package/lib/terminal/node-launcher.js +211 -0
  53. package/lib/terminal/pty-session.js +673 -0
  54. package/lib/terminal/relay-socket.js +605 -0
  55. package/lib/terminal/relay.js +905 -0
  56. package/lib/terminal/scrollback.js +588 -0
  57. package/lib/terminal/tools.js +532 -0
  58. package/lib/tools.js +751 -0
  59. package/package.json +90 -4
@@ -0,0 +1,532 @@
1
+ /**
2
+ * Model-facing tools for persistent remote shell (PTY) sessions.
3
+ *
4
+ * Six tools wrap the owner-scoped shell manager:
5
+ * remote_shell_open / send / read / signal / close / list
6
+ *
7
+ * Safety: opening a shell is not a mutation, but every *submitted* input line is
8
+ * risk-reviewed exactly like `remote_exec` (static classifier -> approval policy
9
+ * -> fail closed), signals are mutating actions, and read-only hosts deny
10
+ * mutating input. Raw input (`submit: false`, e.g. control characters) is not
11
+ * classified because it does not execute a line by itself.
12
+ */
13
+
14
+ import {
15
+ MAX_TITLE_CHARS,
16
+ describeError,
17
+ oneLine,
18
+ shortText,
19
+ splitLines,
20
+ throwIfAborted,
21
+ } from "../render.js";
22
+
23
+ /** Default render budget for one shell result (bytes of model-facing text). */
24
+ const DEFAULT_RENDER_BYTES = 262_144;
25
+
26
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGKILL", "SIGTSTP", "SIGHUP"];
27
+
28
+ /**
29
+ * @param {object} deps
30
+ * @param {Function} deps.defineTool `@deepseek-ai/dsh-tools` factory.
31
+ * @param {object} deps.config Normalized plugin config.
32
+ * @param {object} deps.manager `createShellManager()` instance.
33
+ * @param {object} deps.approval Approval gate (`lib/approval.js`).
34
+ * @param {object} deps.hosts Host store (`lib/host-store.js`).
35
+ * @param {{ warn?: (message: string) => void, info?: (message: string) => void }} [deps.logger]
36
+ * @returns {any[]} ToolDefinitions in protocol order.
37
+ */
38
+ export function createShellTools({ defineTool, config, manager, approval, hosts, live, logger }) {
39
+ if (typeof defineTool !== "function") throw new Error("createShellTools: defineTool is required");
40
+ if (manager === undefined || manager === null) throw new Error("createShellTools: manager is required");
41
+ if (approval === undefined || approval === null) throw new Error("createShellTools: approval is required");
42
+ if (hosts === undefined || hosts === null) throw new Error("createShellTools: hosts is required");
43
+
44
+ const maxBytes = positiveInt(config?.terminalMaxReadBytes, DEFAULT_RENDER_BYTES);
45
+
46
+ /** Resolve the host object behind a live session for reasons and policy. */
47
+ async function hostOf(agent, sessionId) {
48
+ const described = manager.describe(agent, sessionId);
49
+ return { described, host: await hosts.find(described.host) };
50
+ }
51
+
52
+ /** Bound one rendered text value at a UTF-8 safe boundary. */
53
+ function bounded(text) {
54
+ const value = String(text ?? "");
55
+ if (Buffer.byteLength(value, "utf8") <= maxBytes) return value;
56
+ let cut = maxBytes;
57
+ let slice = Buffer.from(value, "utf8").subarray(0, cut).toString("utf8");
58
+ while (Buffer.byteLength(slice, "utf8") > maxBytes && cut > 0) {
59
+ cut -= 1;
60
+ slice = Buffer.from(value, "utf8").subarray(0, cut).toString("utf8");
61
+ }
62
+ return `${slice}\n[output truncated at ${maxBytes} bytes]`;
63
+ }
64
+
65
+ /** Render a session status line. */
66
+ function statusLine(status) {
67
+ if (status?.kind === "exited") {
68
+ return `session exited: ${status.exitCode ?? status.signal ?? "unknown"}`;
69
+ }
70
+ return "session running";
71
+ }
72
+
73
+ const tools = [];
74
+
75
+ tools.push(
76
+ defineTool({
77
+ name: "remote_shell_open",
78
+ description:
79
+ "Open or reuse this conversation's persistent interactive shell (PTY) on a remote host. When the DSH native terminal is enabled, this is the same PTY shown in the terminal, so a human can type or send Ctrl-C there and you can continue with remote_shell_read/send. The session is owned by this agent; close it with remote_shell_close when done. Use it only when you need persistent shell state or interactive input — prefer remote_exec/remote_read/remote_write for bounded work. Returns the sessionId, startup output, and status. An exited shared session is not silently reconnected; reopening starts a fresh shell.",
80
+ parameters: {
81
+ host: {
82
+ type: "string",
83
+ required: true,
84
+ description: "Host name from remote_hosts.",
85
+ },
86
+ cwd: {
87
+ type: "string",
88
+ description: "Optional remote directory to enter after the shell starts (~ allowed).",
89
+ },
90
+ name: {
91
+ type: "string",
92
+ description: "Optional owner-local label for the session.",
93
+ },
94
+ },
95
+ output: {
96
+ schema: { type: "json" },
97
+ render: (_args, value) => [
98
+ {
99
+ type: "text",
100
+ text: bounded(
101
+ `started remote shell ${value.sessionId} on ${value.host} (${statusLine(value.status)})${value.sharedTerminal === true ? " — shared with this conversation's DSH terminal" : ""}\n${value.motd ?? ""}`.trimEnd(),
102
+ ),
103
+ },
104
+ ],
105
+ },
106
+ presentCall(args) {
107
+ return {
108
+ card: "generic",
109
+ kind: "execute",
110
+ title: `Open remote shell on ${shortText(args.host, "host", MAX_TITLE_CHARS)}`,
111
+ };
112
+ },
113
+ async execute(args, exec) {
114
+ throwIfAborted(exec.signal);
115
+ const query = requireText(args.host, "host");
116
+ const host = await hosts.find(query);
117
+ if (!hosts.isAllowed(host)) {
118
+ throw new Error(`Host ${host.name} is not allowed by the allowHosts policy.`);
119
+ }
120
+ const liveCommand = beginLive(live, {
121
+ sessionId: sessionIdOf(exec),
122
+ tool: "remote_shell_open",
123
+ host: host.name,
124
+ command: `open persistent shell${args.cwd === undefined ? "" : ` in ${args.cwd}`}`,
125
+ kind: "shell-open",
126
+ });
127
+ try {
128
+ const decision = await approval.authorize({
129
+ toolName: "remote_shell_open",
130
+ exec,
131
+ host,
132
+ action: "execute",
133
+ subject: `open persistent shell${args.cwd === undefined ? "" : ` in ${args.cwd}`}`,
134
+ mutating: false,
135
+ description: "open a persistent remote shell session",
136
+ readonlyHost: hosts.isReadonly(host),
137
+ });
138
+ if (!decision.allowed) throw new Error(decision.reason);
139
+ const opened = await manager.open({
140
+ agent: exec.agent,
141
+ host,
142
+ ...(args.cwd === undefined ? {} : { cwd: String(args.cwd) }),
143
+ ...(args.name === undefined ? {} : { name: String(args.name) }),
144
+ signal: exec.signal,
145
+ });
146
+ liveCommand?.note(`shell ${opened.sessionId} started on ${host.name}\n`);
147
+ liveCommand?.end({ code: 0 });
148
+ return {
149
+ kind: "open",
150
+ sessionId: opened.sessionId,
151
+ host: host.name,
152
+ status: opened.status,
153
+ motd: opened.motd ?? "",
154
+ sharedTerminal: opened.sharedTerminal === true,
155
+ };
156
+ } catch (error) {
157
+ liveCommand?.end({ error: describeError(error) });
158
+ throw error;
159
+ }
160
+ },
161
+ }),
162
+ );
163
+
164
+ tools.push(
165
+ defineTool({
166
+ name: "remote_shell_send",
167
+ description:
168
+ "Write text to a persistent remote shell session and wait for it to settle. By default Enter is submitted and every submitted line is risk-reviewed like remote_exec: read-only input runs, mutating or unknown input needs approval and is denied under policy never or on read-only hosts. Set submit=false for raw control input (e.g. Ctrl-C or an incomplete REPL line). Returns the output produced by this send, the wait reason (inferred_idle/timeout/session_exit), and the session status. Only one send may be active per session; inferred_idle or timeout never prove the command exited.",
169
+ parameters: {
170
+ sessionId: {
171
+ type: "string",
172
+ required: true,
173
+ description: "Session id returned by remote_shell_open or remote_shell_list.",
174
+ },
175
+ text: {
176
+ type: "string",
177
+ required: true,
178
+ description: "UTF-8 text to write to the shell.",
179
+ },
180
+ submit: {
181
+ type: "boolean",
182
+ description: "Submit Enter after the text (default true).",
183
+ },
184
+ },
185
+ output: {
186
+ schema: { type: "json" },
187
+ render: (_args, value) => [
188
+ {
189
+ type: "text",
190
+ text: bounded(
191
+ [
192
+ value.viewport ?? "",
193
+ `[wait: ${value.waitReason}] [${statusLine(value.sessionStatus)}]`,
194
+ value.truncated ? "[output truncated]" : "",
195
+ ]
196
+ .filter((line) => line.length > 0)
197
+ .join("\n"),
198
+ ),
199
+ },
200
+ ],
201
+ },
202
+ presentCall(args) {
203
+ return {
204
+ card: "generic",
205
+ kind: "execute",
206
+ title: `Send to remote shell: ${oneLine(args.text, 60)}`,
207
+ };
208
+ },
209
+ async execute(args, exec) {
210
+ throwIfAborted(exec.signal);
211
+ const sessionId = requireText(args.sessionId, "sessionId");
212
+ const text = typeof args.text === "string" ? args.text : "";
213
+ if (text.length === 0) throw new Error("text must be a non-empty string");
214
+ const submit = args.submit ?? true;
215
+ const { described, host } = await hostOf(exec.agent, sessionId);
216
+ const liveCommand = beginLive(live, {
217
+ sessionId: sessionIdOf(exec),
218
+ tool: "remote_shell_send",
219
+ host: described.host,
220
+ command: text,
221
+ kind: "shell",
222
+ });
223
+ const startedAt = Date.now();
224
+ try {
225
+ if (submit) {
226
+ const risk = approval.assessCommand(text);
227
+ if (risk.denied !== undefined) throw new Error(risk.denied);
228
+ const mutating = risk.level === "high";
229
+ const unproven = risk.level === "gray";
230
+ const decision = await approval.authorize({
231
+ toolName: "remote_shell_send",
232
+ exec,
233
+ host,
234
+ action: "execute",
235
+ subject: text,
236
+ mutating,
237
+ unproven,
238
+ verb: risk.verb,
239
+ description: "interactive shell input",
240
+ readonlyHost: hosts.isReadonly(host),
241
+ });
242
+ if (!decision.allowed) throw new Error(decision.reason);
243
+ }
244
+
245
+ const result = await manager.send({
246
+ agent: exec.agent,
247
+ sessionId,
248
+ text,
249
+ submit,
250
+ signal: exec.signal,
251
+ ...(liveCommand === undefined
252
+ ? {}
253
+ : { onData: (event) => liveCommand.output(event?.stream, event?.chunk) }),
254
+ });
255
+ liveCommand?.note(`[${result.waitReason}]\n`);
256
+ liveCommand?.end({
257
+ code: result.sessionStatus?.kind === "exited" ? result.sessionStatus.exitCode ?? -1 : 0,
258
+ durationMs: Date.now() - startedAt,
259
+ });
260
+ return {
261
+ kind: "send",
262
+ sessionId,
263
+ host: described.host,
264
+ viewport: result.viewport ?? "",
265
+ waitReason: result.waitReason,
266
+ sessionStatus: result.sessionStatus,
267
+ truncated: result.truncated === true,
268
+ };
269
+ } catch (error) {
270
+ liveCommand?.end({ error: describeError(error), durationMs: Date.now() - startedAt });
271
+ throw error;
272
+ }
273
+ },
274
+ }),
275
+ );
276
+
277
+ tools.push(
278
+ defineTool({
279
+ name: "remote_shell_read",
280
+ description:
281
+ "Read a bounded page from a persistent remote shell session's retained scrollback without sending anything. Offsets are newest-relative (0 = newest retained line). Use it to inspect output produced after a previous send settled or after a timeout.",
282
+ parameters: {
283
+ sessionId: {
284
+ type: "string",
285
+ required: true,
286
+ description: "Session id returned by remote_shell_open or remote_shell_list.",
287
+ },
288
+ offset: {
289
+ type: "integer",
290
+ description: "Newest-relative line offset; 0 is the newest retained line.",
291
+ },
292
+ count: {
293
+ type: "integer",
294
+ description: "Number of lines to return; the backend caps it.",
295
+ },
296
+ },
297
+ output: {
298
+ schema: { type: "json" },
299
+ render: (_args, value) => [
300
+ {
301
+ type: "text",
302
+ text: bounded(
303
+ [
304
+ `scrollback ${value.sessionId}: lines ${value.lineBegin}-${value.lineEnd - 1} of ${value.totalLines}${value.truncated ? " (truncated)" : ""}`,
305
+ value.text ?? "",
306
+ ].join("\n"),
307
+ ),
308
+ },
309
+ ],
310
+ },
311
+ presentCall(args) {
312
+ return {
313
+ card: "generic",
314
+ kind: "read",
315
+ title: `Read remote shell ${shortText(args.sessionId, "session", MAX_TITLE_CHARS)}`,
316
+ };
317
+ },
318
+ async execute(args, exec) {
319
+ throwIfAborted(exec.signal);
320
+ const sessionId = requireText(args.sessionId, "sessionId");
321
+ const page = manager.read({
322
+ agent: exec.agent,
323
+ sessionId,
324
+ ...(args.offset === undefined ? {} : { offset: Number(args.offset) }),
325
+ ...(args.count === undefined ? {} : { count: Number(args.count) }),
326
+ });
327
+ return {
328
+ kind: "read",
329
+ sessionId,
330
+ text: page.text ?? "",
331
+ totalLines: page.totalLines ?? 0,
332
+ lineBegin: page.lineBegin ?? 0,
333
+ lineEnd: page.lineEnd ?? 0,
334
+ truncated: page.truncated === true,
335
+ };
336
+ },
337
+ }),
338
+ );
339
+
340
+ tools.push(
341
+ defineTool({
342
+ name: "remote_shell_signal",
343
+ description:
344
+ "Deliver one POSIX signal to the foreground process group of a remote shell session (SIGINT, SIGTERM, SIGKILL, SIGTSTP, SIGHUP). Mutating: needs approval under auto/always, is denied under policy never and on read-only hosts. Use SIGINT to interrupt a running command instead of guessing.",
345
+ parameters: {
346
+ sessionId: {
347
+ type: "string",
348
+ required: true,
349
+ description: "Session id returned by remote_shell_open or remote_shell_list.",
350
+ },
351
+ signal: {
352
+ type: "string",
353
+ required: true,
354
+ enum: SIGNALS,
355
+ description: "POSIX signal to deliver to the foreground process group.",
356
+ },
357
+ },
358
+ output: {
359
+ schema: { type: "json" },
360
+ render: (_args, value) => [
361
+ {
362
+ type: "text",
363
+ text: `delivered ${value.signal} to ${value.sessionId} (target process group ${value.targetPgid})`,
364
+ },
365
+ ],
366
+ },
367
+ presentCall(args) {
368
+ return {
369
+ card: "generic",
370
+ kind: "delete",
371
+ title: `Signal remote shell ${shortText(args.sessionId, "session", MAX_TITLE_CHARS)} (${String(args.signal ?? "")})`,
372
+ };
373
+ },
374
+ async execute(args, exec) {
375
+ throwIfAborted(exec.signal);
376
+ const sessionId = requireText(args.sessionId, "sessionId");
377
+ const signal = requireText(args.signal, "signal");
378
+ if (!SIGNALS.includes(signal)) {
379
+ throw new Error(`signal must be one of ${SIGNALS.join(", ")} (got ${JSON.stringify(signal)})`);
380
+ }
381
+ const { host } = await hostOf(exec.agent, sessionId);
382
+ const liveCommand = beginLive(live, {
383
+ sessionId: sessionIdOf(exec),
384
+ tool: "remote_shell_signal",
385
+ host: host.name,
386
+ command: `${signal} ${sessionId}`,
387
+ kind: "shell-signal",
388
+ });
389
+ try {
390
+ const decision = await approval.authorize({
391
+ toolName: "remote_shell_signal",
392
+ exec,
393
+ host,
394
+ action: "execute",
395
+ subject: `send ${signal} to the foreground process group`,
396
+ mutating: true,
397
+ verb: signal.toLowerCase(),
398
+ description: "interrupt a remote shell command",
399
+ readonlyHost: hosts.isReadonly(host),
400
+ });
401
+ if (!decision.allowed) throw new Error(decision.reason);
402
+ const delivered = await manager.signal({ agent: exec.agent, sessionId, signal });
403
+ liveCommand?.note(`${signal} delivered\n`);
404
+ liveCommand?.end({ code: 0 });
405
+ return { kind: "signal", sessionId, signal, ...delivered };
406
+ } catch (error) {
407
+ liveCommand?.end({ error: describeError(error) });
408
+ throw error;
409
+ }
410
+ },
411
+ }),
412
+ );
413
+
414
+ tools.push(
415
+ defineTool({
416
+ name: "remote_shell_close",
417
+ description:
418
+ "Close a persistent remote shell session and wait for its process tree to end. Track and close sessions you no longer need; sessions also end when the harness restarts.",
419
+ parameters: {
420
+ sessionId: {
421
+ type: "string",
422
+ required: true,
423
+ description: "Session id returned by remote_shell_open or remote_shell_list.",
424
+ },
425
+ },
426
+ output: {
427
+ schema: { type: "json" },
428
+ render: (_args, value) => [
429
+ { type: "text", text: `closed remote shell ${value.sessionId}` },
430
+ ],
431
+ },
432
+ presentCall(args) {
433
+ return {
434
+ card: "generic",
435
+ kind: "delete",
436
+ title: `Close remote shell ${shortText(args.sessionId, "session", MAX_TITLE_CHARS)}`,
437
+ };
438
+ },
439
+ async execute(args, exec) {
440
+ throwIfAborted(exec.signal);
441
+ const sessionId = requireText(args.sessionId, "sessionId");
442
+ const liveCommand = beginLive(live, {
443
+ sessionId: sessionIdOf(exec),
444
+ tool: "remote_shell_close",
445
+ host: "—",
446
+ command: `close ${sessionId}`,
447
+ kind: "shell-close",
448
+ });
449
+ try {
450
+ const closed = await manager.close({ agent: exec.agent, sessionId, reason: "closed by the agent" });
451
+ liveCommand?.end({ code: 0 });
452
+ return { kind: "close", sessionId, closed: closed !== false };
453
+ } catch (error) {
454
+ liveCommand?.end({ error: describeError(error) });
455
+ throw error;
456
+ }
457
+ },
458
+ }),
459
+ );
460
+
461
+ tools.push(
462
+ defineTool({
463
+ name: "remote_shell_list",
464
+ description:
465
+ "List the persistent remote shell sessions owned by this agent (sessionId, host, status). Call it before closing or reusing a session you opened earlier.",
466
+ parameters: {},
467
+ output: {
468
+ schema: { type: "json" },
469
+ render: (_args, value) => [
470
+ {
471
+ type: "text",
472
+ text:
473
+ value.sessions.length === 0
474
+ ? "no live remote shell sessions"
475
+ : [
476
+ `${value.sessions.length} remote shell session${value.sessions.length === 1 ? "" : "s"}:`,
477
+ ...value.sessions.map(
478
+ (session) =>
479
+ `${session.sessionId} ${session.host} ${statusLine(session.status)}${session.name === undefined ? "" : ` (${session.name})`}`,
480
+ ),
481
+ ].join("\n"),
482
+ },
483
+ ],
484
+ },
485
+ presentCall() {
486
+ return { card: "generic", kind: "read", title: "List remote shell sessions" };
487
+ },
488
+ async execute(_args, exec) {
489
+ throwIfAborted(exec.signal);
490
+ const sessions = manager.list(exec.agent).map((session) => ({
491
+ sessionId: session.sessionId,
492
+ host: session.host,
493
+ ...(session.name === undefined ? {} : { name: session.name }),
494
+ status: session.status,
495
+ }));
496
+ return { kind: "list", sessions };
497
+ },
498
+ }),
499
+ );
500
+
501
+ return tools;
502
+ }
503
+
504
+ /** @param {unknown} value @param {string} field @returns {string} */
505
+ function requireText(value, field) {
506
+ if (typeof value !== "string" || value.trim().length === 0) {
507
+ throw new Error(`${field} must be a non-empty string`);
508
+ }
509
+ return value;
510
+ }
511
+
512
+ /** @param {unknown} value @param {number} fallback @returns {number} */
513
+ function positiveInt(value, fallback) {
514
+ return Number.isSafeInteger(value) && value > 0 ? value : fallback;
515
+ }
516
+
517
+ /** @param {any} exec @returns {string|null} */
518
+ function sessionIdOf(exec) {
519
+ const session = exec?.agent?.session ?? exec?.agent;
520
+ const id = session?.id;
521
+ return typeof id === "string" && id.length > 0 ? id : null;
522
+ }
523
+
524
+ /** @param {any} live @param {object} input */
525
+ function beginLive(live, input) {
526
+ if (live === undefined || live === null || typeof live.begin !== "function") return undefined;
527
+ try {
528
+ return live.begin(input);
529
+ } catch {
530
+ return undefined;
531
+ }
532
+ }