Skip to main content

oxdock_ssh_plugin/
funcs.rs

1//! The `SSH` host module: `SERVE`, `ACCEPT` / `DEQUEUE` + `PUMP_CHANNEL`,
2//! `CLOSE`, `CONNECT`, `PUMP`.
3//!
4//! Pipe direction convention (fixed for every func): `out_pipe` carries
5//! bytes produced by the wire side (the DSL reads them), `in_pipe`
6//! carries bytes consumed by the wire side (the DSL writes them).
7
8use std::collections::BTreeMap;
9use std::sync::Arc;
10use std::sync::atomic::AtomicBool;
11
12use anyhow::Result;
13
14use crate::diagnostics as ssh_diag;
15use oxdock_core::{Field, HostModule, OxDockFn, OxDockType, RecordSchema, StepCtx, TypeTag, Value};
16use oxdock_func_macro::oxdock_func;
17use oxdock_net_plugin::{
18    AcquiredListener, EndpointKey, EndpointRegistry, ServiceTarget, SocketRequirement,
19    acquire_listener, no_cli_mapping, parse_virtual_endpoint, resolve_service_target,
20};
21use oxdock_pipe::PipeHandle;
22use oxdock_process::ProcessManager;
23use russh::keys::{Algorithm, PrivateKey};
24
25use crate::bridge::{pump_pipe_to_pipe, pump_session};
26use crate::keys::load_or_create_host_key;
27use crate::runtime::{connect_runtime, connect_session};
28use crate::state::{
29    CLOSE_JOIN_TIMEOUT, Dequeue, PendingSession, ServerState, SessionQueue, ShutdownSignal,
30};
31use crate::types::{SshServerTag, SshSessionTag};
32use crate::validate::parse_serve_endpoint;
33
34/// Result map keys for SSH session outcomes. Single source for the
35/// `Field` schemas below and every `map.insert` site, so a rename
36/// cannot drift one side silent.
37const FIELD_CLOSED: &str = "closed";
38const FIELD_COMMAND: &str = "command";
39const FIELD_EXIT_STATUS: &str = "exit_status";
40const FIELD_SERVER: &str = "server";
41const FIELD_ADDR: &str = "addr";
42const FIELD_USERNAME: &str = "username";
43const FIELD_PASSWORD: &str = "password";
44const FIELD_VIRTUAL: &str = "virtual";
45const FIELD_SESSION: &str = "session";
46const FIELD_EXIT: &str = "exit";
47const FIELD_TRUNCATED: &str = "truncated";
48const FIELD_TIMED_OUT: &str = "timed_out";
49
50/// Option map keys for SSH calls. `username` and `password` reuse the
51/// `FIELD_*` spellings above (same words, same meaning); the rest live
52/// here so every lookup matches its `#[options]` spelling.
53const OPT_KEY_PATH: &str = "key_path";
54const OPT_IDLE_TIMEOUT: &str = "idle_timeout";
55const OPT_TIMEOUT: &str = "timeout";
56const OPT_MAX_BYTES: &str = "max_bytes";
57
58/// Shared DSL func labels passed as caller tags. One spelling for
59/// the whole crate, so a func rename is one edit. Single-use labels
60/// (`SSH_ACCEPT`, `SSH_DEQUEUE`, `SSH_CLOSE`), message templates,
61/// type names, and doc examples stay inline per Section F.
62pub(crate) const FUNC_EXEC: &str = "SSH_EXEC";
63pub(crate) const FUNC_CONNECT: &str = "SSH_CONNECT";
64pub(crate) const FUNC_SERVE: &str = "SSH_SERVE";
65
66/// Host-module name for the endpoint-registry slot, the pre-run
67/// check, and the registration. One spelling, so a rename is one
68/// edit.
69pub(crate) const MODULE_SSH: &str = "SSH";
70
71/// Unique server ids per process.
72static SERVER_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
73
74/// Block until the queue yields an authenticated session (or teardown).
75/// Shared by `SSH_DEQUEUE` and the `SSH_ACCEPT` wrapper. No timeout:
76/// a waiter parks in the queue condvar while a bridge thread parks on
77/// the task hub; on hub fire the bridge pokes the queue awake and the
78/// waiter ends with `Cancelled`. One transient thread per call, spent
79/// only on wakeups, never on ticks.
80fn dequeue_session<P: ProcessManager>(
81    cx: &StepCtx<P>,
82    queue: &Arc<SessionQueue>,
83    func: &str,
84) -> Result<PendingSession> {
85    let hub = cx.cancel_hub();
86    let bridge_queue = Arc::clone(queue);
87    let bridge_hub = Arc::clone(&hub);
88    let (started_tx, started_rx) = std::sync::mpsc::channel::<()>();
89    std::thread::scope(|scope| {
90        let bridge = scope.spawn(move || {
91            // Rendezvous: read the sequence, then signal, then park,
92            // so the release below can never land before the wait.
93            let seen = bridge_hub.sequence();
94            let _ = started_tx.send(());
95            let (cancelled, _) = bridge_hub.wait(seen);
96            if cancelled {
97                bridge_queue.poke();
98            }
99        });
100        let result = loop {
101            if hub.is_cancelled() || cx.is_cancelled() {
102                break Err(anyhow::Error::from(ssh_diag::dequeue_task_cancelled(func)));
103            }
104            match queue.try_pop() {
105                Dequeue::Session(session) => break Ok(session),
106                Dequeue::Shutdown => {
107                    break Err(anyhow::Error::from(ssh_diag::dequeue_server_closed(func)));
108                }
109                Dequeue::Empty | Dequeue::Cancelled => {}
110            }
111            match queue.wait_blocking(&hub) {
112                Dequeue::Session(session) => break Ok(session),
113                Dequeue::Shutdown => {
114                    break Err(anyhow::Error::from(ssh_diag::dequeue_server_closed(func)));
115                }
116                Dequeue::Cancelled | Dequeue::Empty => {}
117            }
118        };
119        // Release the bridge (rendezvous first so the poke cannot
120        // land before its wait, then poke, never cancel: the dequeue
121        // may have ended cleanly) and join it: no thread outlives the
122        // call.
123        let _ = started_rx.recv();
124        hub.poke();
125        let _ = bridge.join();
126        result
127    })
128}
129
130/// Dequeue one authenticated session for routing before any byte
131/// pumping starts. Must run inside `ASYNC`.
132///
133/// The server sends first: the client side never EOFs its input, so a
134/// synthetic reply cannot race teardown.
135///
136#[oxdock_func(
137    returns = TypeTag::Record(dequeue_result_fields()),
138    summary = "Dequeue one SSH session with its metadata."
139)]
140#[example(
141    name = "route one session",
142    code = r###"
143    IMPORT [STD, SSH]
144    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-route", {username: "u", password: "p"})
145
146    # Serve: dequeue one session and pump a synthetic reply.
147    LET $in: PIPE
148    LET $out: PIPE
149    LET $w: HANDLE<VOID> = ASYNC {
150        LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
151        ASSERT_EQ $sess.username "u"
152        SSH_PUMP_CHANNEL($sess.session, $in, $out)
153    }
154
155    # Connect a client to the server.
156    LET $cin: PIPE
157    LET $cout: PIPE
158    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-route", "u", "p", $cin, $cout) }
159
160    # Close both inputs: each pump observes EOF, half-closes, and every
161    # task returns with no cancellation.
162    WITH_IO [stdout=$cin] ECHO "client-hello"
163    WITH_IO [stdout=$in] ECHO "server-greeting"
164    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
165    ASSERT_EQ $cDone.closed true
166    AWAIT $w
167    SSH_CLOSE($m.server)
168    "###
169)]
170fn ssh_dequeue<P: ProcessManager>(
171    cx: &mut StepCtx<P>,
172    /// Server handle from `SSH_SERVE`.
173    server: SshServerTag,
174) -> Result<Value> {
175    if !cx.is_async_task() {
176        return Err(anyhow::Error::from(ssh_diag::dequeue_requires_async()));
177    }
178    let state = Arc::clone(server.state());
179    let session = dequeue_session(cx, state.queue(), "SSH_DEQUEUE")?;
180    let command = session.exec_command.clone().unwrap_or_default();
181    let username = session.username.clone().unwrap_or_default();
182    let addr = session
183        .peer_addr
184        .map(|addr| addr.to_string())
185        .unwrap_or_default();
186    let tag = SshSessionTag::new(
187        session.exec_command,
188        session.username,
189        session.peer_addr,
190        session.pty_size,
191        session.up_rx,
192        session.down_tx,
193    );
194    let mut map = BTreeMap::new();
195    map.insert(
196        "session".to_string(),
197        Value::mint_heap(SshSessionTag::descriptor(), tag),
198    );
199    map.insert(FIELD_COMMAND.to_string(), Value::string(command));
200    map.insert(FIELD_USERNAME.to_string(), Value::string(username));
201    map.insert(FIELD_ADDR.to_string(), Value::string(addr));
202    Ok(Value::map(map))
203}
204
205/// Spin up an SSH server on a runner-mapped service. Unmapped and
206/// memory services bail: SSH needs a TCP socket.
207/// `options` takes required `username`/`password` STRINGs plus the
208/// optional `key_path` STRING (workspace-relative Ed25519 file,
209/// load-or-create; blank keeps the ephemeral key) and the optional
210/// `idle_timeout` DURATION (quiet-connection kill, default 5m; zero
211/// disables it for persistent sessions).
212#[oxdock_func(returns = TypeTag::Record(serve_result_fields()), summary = "Serve SSH on a virtual service endpoint.")]
213#[example(
214    name = "serve and close",
215    code = r###"
216    IMPORT [STD, SSH]
217    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-serve", {username: "u", password: "p"})
218    ASSERT_EQ $m.virtual "doc-ssh-serve"
219    SSH_CLOSE($m.server)
220    "###
221)]
222fn ssh_serve<P: ProcessManager>(
223    cx: &mut StepCtx<P>,
224    /// Service name to serve; the runner maps it with -p/--listen.
225    bind: String,
226    /// Server credentials and host key.
227    #[options(
228        "username: STRING",
229        "password: STRING",
230        "key_path?: STRING",
231        "idle_timeout?: DURATION|STRING"
232    )]
233    options: BTreeMap<String, Value>,
234) -> Result<Value> {
235    let map = &options;
236    let username = match map.get(FIELD_USERNAME) {
237        Some(value) => {
238            let text = value.as_str().expect("check_options verified STRING");
239            if text.trim().is_empty() {
240                return Err(anyhow::Error::from(ssh_diag::serve_option_empty(
241                    FIELD_USERNAME,
242                )));
243            }
244            text.to_string()
245        }
246        None => {
247            return Err(anyhow::Error::from(ssh_diag::serve_option_required(
248                FIELD_USERNAME,
249            )));
250        }
251    };
252    let password = match map.get(FIELD_PASSWORD) {
253        Some(value) => {
254            let text = value.as_str().expect("check_options verified STRING");
255            if text.trim().is_empty() {
256                return Err(anyhow::Error::from(ssh_diag::serve_option_empty(
257                    FIELD_PASSWORD,
258                )));
259            }
260            text.to_string()
261        }
262        None => {
263            return Err(anyhow::Error::from(ssh_diag::serve_option_required(
264                FIELD_PASSWORD,
265            )));
266        }
267    };
268    let key_path = match map.get(OPT_KEY_PATH) {
269        Some(value) => {
270            let text = value.as_str().expect("check_options verified STRING");
271            if text.trim().is_empty() {
272                None
273            } else {
274                Some(text.to_string())
275            }
276        }
277        None => None,
278    };
279    // Idle kill override: absent keeps the default, zero disables the
280    // timeout entirely (persistent sessions must opt out explicitly).
281    let idle_timeout = match map.get(OPT_IDLE_TIMEOUT) {
282        Some(value) => {
283            // `check_options` verified `DURATION|STRING`; narrow directly.
284            let timeout = if let Some(duration) = value.as_duration() {
285                duration
286            } else {
287                let text = value
288                    .as_str()
289                    .expect("check_options verified DURATION|STRING");
290                oxdock_parser::command::parse_duration(text).map_err(|e| {
291                    ssh_diag::option_must_be_duration(FUNC_SERVE, OPT_IDLE_TIMEOUT, text, e)
292                })?
293            };
294            (!timeout.is_zero()).then_some(timeout)
295        }
296        None => Some(crate::runtime::DEFAULT_INACTIVITY_TIMEOUT),
297    };
298    let registry = cx
299        .module_state::<EndpointRegistry>(MODULE_SSH)
300        .expect("SSH module registers its endpoint registry as module state");
301    let endpoint = parse_serve_endpoint(&bind)?;
302    let key = EndpointKey::tcp(endpoint);
303    let (acquired, registry) = acquire_listener(
304        &registry,
305        &key,
306        FUNC_SERVE,
307        SocketRequirement::SocketRequired,
308    )?;
309    let host_key = match load_or_create_host_key(cx, FUNC_SERVE, key_path)? {
310        Some(key) => key,
311        None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
312            .map_err(ssh_diag::ephemeral_key_generate_failed)?,
313    };
314    let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
315    let id = format!("ssh-{pid}-{id}", pid = std::process::id());
316    let queue = Arc::new(SessionQueue::new());
317    let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
318    let (local_addr, addr_text, thread) = match acquired {
319        AcquiredListener::Tcp { listener, addr } => {
320            // The runtime owns a clone; the slot keeps the backlog socket.
321            let owned = listener
322                .try_clone()
323                .map_err(ssh_diag::serve_listener_clone_failed)?;
324            let thread_queue = Arc::clone(&queue);
325            let thread_user = username.clone();
326            let thread_pass = password.clone();
327            let thread = std::thread::Builder::new()
328                .name(id.clone())
329                .spawn(move || {
330                    crate::runtime::serve(
331                        owned,
332                        host_key,
333                        thread_user,
334                        thread_pass,
335                        thread_queue,
336                        shutdown_rx,
337                        idle_timeout,
338                    )
339                })
340                .map_err(ssh_diag::serve_spawn_failed)?;
341            (addr, addr.to_string(), Some(thread))
342        }
343        AcquiredListener::Memory => {
344            // Unreachable: `SocketRequired` already bailed; same text.
345            drop(shutdown_rx);
346            return Err(anyhow::Error::from(no_cli_mapping(
347                FUNC_SERVE,
348                &key.endpoint,
349            )));
350        }
351        AcquiredListener::Offline => {
352            // No thread: dropping the receiver makes shutdown a no-op.
353            drop(shutdown_rx);
354            (
355                std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
356                key.endpoint.to_string(),
357                None,
358            )
359        }
360    };
361    let state = Arc::new(ServerState::new(crate::state::ServerConfig {
362        id,
363        local_addr,
364        addr_text: addr_text.clone(),
365        queue,
366        shutdown_tx,
367        thread,
368        registry: Arc::clone(&registry),
369        endpoint: key.clone(),
370    }));
371    let mut map = BTreeMap::new();
372    map.insert(
373        "server".to_string(),
374        Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
375    );
376    map.insert(FIELD_ADDR.to_string(), Value::string(addr_text));
377    map.insert(FIELD_USERNAME.to_string(), Value::string(username));
378    map.insert(FIELD_PASSWORD.to_string(), Value::string(password));
379    map.insert(
380        "virtual".to_string(),
381        Value::string(key.endpoint.to_string()),
382    );
383    Ok(Value::map(map))
384}
385
386/// `SSH_DEQUEUE` + `SSH_PUMP_CHANNEL` in one call, for worker loops
387/// that need no pre-pump inspection. Must run inside `ASYNC`.
388///
389/// The server sends first: the client side never EOFs its input, so
390/// the reply cannot race teardown.
391///
392#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
393    name: FIELD_CLOSED.to_string(),
394    ty: TypeTag::Bool,
395    docs: "True when the session closed cleanly.",
396    optional: false,
397    default: None,
398
399    alias: None,}, Field {
400    name: FIELD_COMMAND.to_string(),
401    ty: TypeTag::String,
402    docs: "Executed command, empty for shells.",
403    optional: false,
404    default: None,
405
406    alias: None,}])), summary = "Accept one SSH session into pipes.")]
407#[example(
408    name = "accept and close",
409    code = r###"
410    IMPORT [STD, SSH]
411    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-accept", {username: "u", password: "p"})
412    LET $in: PIPE
413    LET $out: PIPE
414    LET $acc: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_ACCEPT($m.server, $in, $out) }
415    LET $cin: PIPE
416    LET $cout: PIPE
417    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-accept", "u", "p", $cin, $cout) }
418
419    # Close both inputs: each pump observes EOF, half-closes, and both
420    # tasks return their result maps with no cancellation.
421    WITH_IO [stdout=$cin] ECHO "client-hello"
422    WITH_IO [stdout=$in] ECHO "server-greeting"
423    LET $done: MAP<ANY> = AWAIT $acc
424    ASSERT_EQ $done.closed true
425    ASSERT_CONTAINS $done "command"
426    LET $cDone: MAP<ANY> = AWAIT $c
427    ASSERT_EQ $cDone.closed true
428    SSH_CLOSE($m.server)
429    "###
430)]
431fn ssh_accept<P: ProcessManager>(
432    cx: &mut StepCtx<P>,
433    /// Server handle from `SSH_SERVE`.
434    server: SshServerTag,
435    /// Pipe carrying bytes consumed by the wire side.
436    in_pipe: PipeHandle,
437    /// Pipe carrying bytes produced by the wire side.
438    out_pipe: PipeHandle,
439) -> Result<Value> {
440    if !cx.is_async_task() {
441        return Err(anyhow::Error::from(ssh_diag::accept_requires_async()));
442    }
443    let in_pipe = Value::pipe_handle(in_pipe);
444    let out_pipe = Value::pipe_handle(out_pipe);
445    let state = Arc::clone(server.state());
446    let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
447    pump_session(
448        cx,
449        &in_pipe,
450        &out_pipe,
451        session.up_rx,
452        session.down_tx,
453        true,
454    )?;
455    let mut map = BTreeMap::new();
456    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
457    map.insert(
458        "command".to_string(),
459        Value::string(session.exec_command.unwrap_or_default()),
460    );
461    Ok(Value::map(map))
462}
463
464/// Pump a dequeued session through explicit pipes until the channel
465/// closes. Must run inside `ASYNC`. Pump ends take once: a second
466/// pump bails instead of splitting bytes.
467///
468#[oxdock_func(
469    returns = TypeTag::Record(std::sync::Arc::from([Field {
470        name: FIELD_CLOSED.to_string(),
471        ty: TypeTag::Bool,
472        docs: "True when the session closed cleanly.",
473        optional: false,
474        default: None,
475
476        alias: None,}])),
477    summary = "Pump a dequeued SSH session through pipes."
478)]
479#[example(
480    name = "pump a session",
481    code = r###"
482    IMPORT [STD, SSH]
483    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pump", {username: "u", password: "p"})
484    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
485    LET $cin: PIPE
486    LET $cout: PIPE
487    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-pump", "u", "p", $cin, $cout) }
488    WITH_IO [stdout=$cin] ECHO "client-hello"
489    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
490    LET $sin: PIPE
491    LET $sout: PIPE
492    LET $p: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
493    WITH_IO [stdout=$sin] ECHO "server-greeting"
494    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
495    ASSERT_EQ $cDone.closed true
496    LET $pDone: MAP<ANY> = AWAIT $p
497    ASSERT_EQ $pDone.closed true
498    SSH_CLOSE($m.server)
499    "###
500)]
501fn ssh_pump_channel<P: ProcessManager>(
502    cx: &mut StepCtx<P>,
503    /// Session handle from `SSH_DEQUEUE` (pump ends take once).
504    session: SshSessionTag,
505    /// Pipe carrying bytes consumed by the wire side.
506    in_pipe: PipeHandle,
507    /// Pipe carrying bytes produced by the wire side.
508    out_pipe: PipeHandle,
509) -> Result<Value> {
510    if !cx.is_async_task() {
511        return Err(anyhow::Error::from(ssh_diag::pump_channel_requires_async()));
512    }
513    let in_pipe = Value::pipe_handle(in_pipe);
514    let out_pipe = Value::pipe_handle(out_pipe);
515    let (up_rx, down_tx) = session.take_pump_ends()?;
516    // Release the control sender when the pump ends (pass or fail):
517    // the wire writer must observe the drain and close then, not when
518    // the last session clone drops long after.
519    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, true);
520    session.finish_pump();
521    pump?;
522    let mut map = BTreeMap::new();
523    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
524    Ok(Value::map(map))
525}
526
527/// Report the session's exit status to the client (RFC 4254 6.10),
528/// ahead of the channel close. Survives the take-once pump ends, so
529/// call it before the pump drains. `SSH_PTY_RUN` reports by itself;
530/// this covers other legs (`RUN`, synthetic replies).
531#[oxdock_func(returns = TypeTag::Bool, summary = "Send the session exit status to the client.")]
532#[example(
533    name = "report exit status",
534    code = r###"
535    IMPORT [STD, SSH]
536    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exit-status", {username: "u", password: "p"})
537    LET $srv: HANDLE<VOID> = ASYNC {
538        LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
539        LET $sin: PIPE
540        LET $sout: PIPE
541        LET $p: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
542        SSH_SEND_EXIT_STATUS($sess.session, 3)
543        WITH_IO [stdout=$sin] ECHO "server-greeting"
544        AWAIT $p
545    }
546    LET $cin: PIPE
547    LET $cout: PIPE
548    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-exit-status", "u", "p", $cin, $cout) }
549    # Close the client input: its pump observes EOF and half-closes, so
550    # both pumps drain instead of idling on an empty pipe.
551    WITH_IO [stdout=$cin] ECHO "client-hello"
552    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
553    ASSERT_EQ $cDone.closed true
554    ASSERT_EQ $cDone.exit_status 3
555    AWAIT $srv
556    SSH_CLOSE($m.server)
557    "###
558)]
559fn ssh_send_exit_status<P: ProcessManager>(
560    cx: &mut StepCtx<P>,
561    /// Session handle from `SSH_DEQUEUE`.
562    session: SshSessionTag,
563    /// Exit status to report (0 to 4294967295).
564    code: i64,
565) -> Result<Value> {
566    let _ = cx;
567    if code < 0 {
568        return Err(anyhow::Error::from(ssh_diag::send_exit_status_negative(
569            code,
570        )));
571    }
572    let code = u32::try_from(code)
573        .map_err(|_| anyhow::Error::from(ssh_diag::send_exit_status_out_of_range(code)))?;
574    session.send_exit_status(code)?;
575    Ok(Value::bool(true))
576}
577
578/// Shut a server down and join its runtime thread (bounded).
579/// Idempotent.
580///
581#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
582#[example(
583    name = "shut down",
584    code = r###"
585    IMPORT [STD, SSH]
586    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-close", {username: "u", password: "p"})
587    LET $ok: BOOL = SSH_CLOSE($m.server)
588    ASSERT_EQ $ok true
589    "###
590)]
591fn ssh_close<P: ProcessManager>(
592    cx: &mut StepCtx<P>,
593    /// Server handle from `SSH_SERVE`.
594    server: SshServerTag,
595) -> Result<Value> {
596    let _ = cx;
597    let state = Arc::clone(server.state());
598    state.request_shutdown();
599    Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
600}
601
602/// Open an SSH client session and pump its shell channel through
603/// explicit pipes until it closes. Must run inside `ASYNC`, beside
604/// the pump tasks. Under `--offline` the dial bails before any
605/// socket work. The result MAP carries `exit_status`, or -1 when the
606/// server sent none.
607#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
608    name: FIELD_CLOSED.to_string(),
609    ty: TypeTag::Bool,
610    docs: "True when the session closed cleanly.",
611    optional: false,
612    default: None,
613
614    alias: None,}, Field {
615    name: FIELD_EXIT_STATUS.to_string(),
616    ty: TypeTag::Int,
617    docs: "Remote exit status, or -1 when none arrived.",
618    optional: false,
619    default: None,
620
621    alias: None,}])), summary = "Open an SSH client session into pipes.")]
622#[example(
623    name = "connect and close",
624    code = r###"
625    IMPORT [STD, SSH]
626    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-connect", {username: "u", password: "p"})
627    LET $in: PIPE
628    LET $out: PIPE
629    LET $acc: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_ACCEPT($m.server, $in, $out) }
630    LET $cin: PIPE
631    LET $cout: PIPE
632    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-connect", "u", "p", $cin, $cout) }
633
634    # Close both inputs: each pump observes EOF, half-closes, and both
635    # tasks return their result maps with no cancellation.
636    WITH_IO [stdout=$cin] ECHO "client-hello"
637    WITH_IO [stdout=$in] ECHO "server-greeting"
638    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
639    ASSERT_EQ $cDone.closed true
640    LET $adone: MAP<ANY> = AWAIT $acc
641    ASSERT_EQ $adone.closed true
642    SSH_CLOSE($m.server)
643    "###
644)]
645fn ssh_connect<P: ProcessManager>(
646    cx: &mut StepCtx<P>,
647    /// Dial target: a service name resolved through runner mappings.
648    target: String,
649    /// Inner credentials for the SSH session.
650    username: String,
651    /// Inner credentials for the SSH session.
652    password: String,
653    /// Pipe carrying bytes consumed by the wire side.
654    in_pipe: PipeHandle,
655    /// Pipe carrying bytes produced by the wire side.
656    out_pipe: PipeHandle,
657) -> Result<Value> {
658    if !cx.is_async_task() {
659        return Err(anyhow::Error::from(ssh_diag::connect_requires_async()));
660    }
661    // Registry travels as module state.
662    let registry = cx
663        .module_state::<EndpointRegistry>(MODULE_SSH)
664        .expect("SSH module registers its endpoint registry as module state");
665    let in_pipe = Value::pipe_handle(in_pipe);
666    let out_pipe = Value::pipe_handle(out_pipe);
667    if registry.is_offline() {
668        return Err(anyhow::Error::from(ssh_diag::connect_offline()));
669    }
670    if username.is_empty() {
671        return Err(anyhow::Error::from(ssh_diag::connect_username_empty()));
672    }
673    // Symbolic only: physical shapes already failed in the parser.
674    let endpoint = parse_virtual_endpoint(&target, FUNC_CONNECT)?;
675    let key = EndpointKey::tcp(endpoint);
676    let addr = match resolve_service_target(
677        &registry,
678        &key,
679        FUNC_CONNECT,
680        SocketRequirement::SocketRequired,
681    )? {
682        ServiceTarget::Tcp(addr) => addr,
683        // Unreachable: the shared resolver already bailed; same text.
684        ServiceTarget::Memory => {
685            return Err(anyhow::Error::from(no_cli_mapping(
686                FUNC_CONNECT,
687                &key.endpoint,
688            )));
689        }
690    };
691    let runtime = connect_runtime()?;
692    let session = runtime
693        .block_on(connect_session(&addr, &username, &password))
694        .map_err(ssh_diag::connect_failed)?;
695    let crate::runtime::OutboundSession {
696        up_rx,
697        down_tx,
698        exit_status,
699        wire_done,
700        handle,
701        ..
702    } = session;
703    // Client linger: the reply and the exit-status arrive after the
704    // client's own stdin EOF, so never cut the output wait short.
705    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, false);
706    let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
707    pump?;
708    // Joined after disconnect: a post-EOF status records before this read.
709    let _ = runtime.block_on(wire_done);
710    let mut map = BTreeMap::new();
711    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
712    let status = exit_status
713        .lock()
714        .map(|slot| slot.map(i64::from))
715        .unwrap_or(None);
716    map.insert(
717        FIELD_EXIT_STATUS.to_string(),
718        Value::int(status.unwrap_or(-1)),
719    );
720    Ok(Value::map(map))
721}
722
723/// Copy one pipe into another until EOF, then close the target.
724/// Either task placement works, as long as the other end is live.
725///
726#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
727#[example(
728    name = "copy",
729    code = r###"
730    # Closing the source ends the copy: the count proves the bytes moved.
731    IMPORT [STD, SSH]
732    LET $in: PIPE
733    WITH_IO [stdout=$in] ECHO "pump-me"
734    LET $out: PIPE
735    LET $n: INT = SSH_PUMP($in, $out)
736    ASSERT_EQ $n 8
737    WITH_IO [stdin=$out] READ_LINE $got
738    ASSERT_EQ $got "pump-me"
739    "###
740)]
741fn ssh_pump<P: ProcessManager>(
742    cx: &mut StepCtx<P>,
743    /// Source pipe to drain.
744    from_pipe: PipeHandle,
745    /// Target pipe receiving the bytes (closed at EOF).
746    to_pipe: PipeHandle,
747) -> Result<Value> {
748    let from_pipe = Value::pipe_handle(from_pipe);
749    let to_pipe = Value::pipe_handle(to_pipe);
750    let cancel = AtomicBool::new(false);
751    let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
752    Ok(Value::int(total))
753}
754
755/// Run `argv` under a local pseudo-terminal and pump it through
756/// explicit pipes until the child exits. Must run inside `ASYNC`.
757/// Returns the INT exit code.
758///
759/// `rows`/`cols` seed the initial size when positive, else the
760/// session's requested size (24x80 default). Outer window-changes
761/// resize live; each session owns its cell.
762///
763/// The code also reports as the wire `exit-status` at child exit, so
764/// stock clients see the real code instead of 255.
765///
766/// Every session opens cleared and homed, like Win32-OpenSSH, so the
767/// child renders onto a known blank screen.
768///
769/// Windows joining follows MSVCRT rules, so CRT programs parse back
770/// exactly `argv`. `cmd /c` is the exception (its tail is a command,
771/// not `argv`): route command text via `ENV SSH_COMMAND="..."` with
772/// `["cmd", "/c", "%SSH_COMMAND%"]` instead.
773///
774/// Stdin arrives with console line endings handled: the pump expands
775/// a lone `\n` to `\r\n` on Windows, so portable lines submit as-is
776/// and an explicit `\r` passes through untouched. Real terminals
777/// already send CR for Enter.
778///
779/// Environment is exactly the script environment like `RUN`:
780/// block-scoped `ENV` (such as the session's `SSH_USER` / `SSH_CLIENT` /
781/// `SSH_SERVER` / `SSH_COMMAND` relay) reaches the child; host names
782/// arrive only through `INHERIT_ENV`, including `TERM` for terminal
783/// definitions. The working directory comes from the script.
784///
785/// `WITH_IO [tty]` shares the same pump core and covers terminal
786/// runs with host or static sizing and step-local reporting. This
787/// function covers the two session-bound cases a script assembly
788/// cannot reproduce: a rendered run with static geometry observes
789/// the opener but never an outer resize (no script primitive
790/// subscribes a running pty to the session cell), and a failing DSL
791/// `RUN` aborts its task before any script-level status report could
792/// follow (there is no try/catch; the close race after that would be
793/// the second problem). If a second consumer ever needs
794/// session-driven sizing or reaper-ordered reporting, that is the
795/// point to revisit unifying the two.
796///
797#[oxdock_func(
798    returns = TypeTag::Int,
799    summary = "Run a command under a sized local terminal into pipes."
800)]
801#[example(
802    name = "run under a terminal",
803    code = r###"
804    IMPORT [STD, SSH]
805    INHERIT_ENV [PATH]
806    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pty", {username: "u", password: "p"})
807    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
808    LET $cin: PIPE
809    LET $cout: PIPE
810    LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("doc-ssh-pty", "u", "p", $cin, $cout) }
811    WITH_IO [stdout=$cin] ECHO "client-hello"
812    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
813
814    # The client task only proved the session live: cancel it before the
815    # terminal run, so no two pumps share the session.
816    CANCEL $c
817    LET $pin: PIPE
818    LET $pout: PIPE
819    # Assert on the whole pipe: terminal streams carry setup noise ahead
820    # of child output, so line reads are version-dependent.
821    [family:unix] {
822        LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($sess.session, ["sh", "-c", "echo pty-hi"], 0, 0, $pin, $pout) }
823        LET $code: INT = AWAIT $t
824        ASSERT_EQ $code 0
825        ASSERT_CONTAINS $pout "pty-hi"
826    }
827    [family:windows] {
828        LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($sess.session, ["cmd", "/c", "echo pty-hi"], 0, 0, $pin, $pout) }
829        LET $code: INT = AWAIT $t
830        ASSERT_EQ $code 0
831        ASSERT_CONTAINS $pout "pty-hi"
832    }
833    SSH_CLOSE($m.server)
834    "###
835)]
836fn ssh_pty_run<P: ProcessManager>(
837    cx: &mut StepCtx<P>,
838    /// Session handle from `SSH_DEQUEUE`.
839    session: SshSessionTag,
840    /// Program and arguments to run.
841    argv: Vec<String>,
842    /// Terminal rows when positive, session size otherwise.
843    rows: i64,
844    /// Terminal columns when positive, session size otherwise.
845    cols: i64,
846    /// Pipe carrying bytes consumed by the child.
847    in_pipe: PipeHandle,
848    /// Pipe carrying bytes produced by the child.
849    out_pipe: PipeHandle,
850) -> Result<Value> {
851    if !cx.is_async_task() {
852        return Err(anyhow::Error::from(ssh_diag::pty_run_requires_async()));
853    }
854    let in_pipe = Value::pipe_handle(in_pipe);
855    let out_pipe = Value::pipe_handle(out_pipe);
856    let initial = if rows > 0 && cols > 0 {
857        crate::state::PtySize::new(rows as u32, cols as u32)
858    } else {
859        session.pty_size()
860    };
861    // Best effort: an unpumped session has no reader. Owned clone:
862    // the reaper runs detached, so the callback must be `'static`.
863    let session_report = session.clone();
864    let report = move |code: u32| {
865        let _ = session_report.send_exit_status(code);
866    };
867    let code = crate::pty::pump_pty_session(
868        cx,
869        &argv,
870        initial,
871        &session.pty_size_handle(),
872        &in_pipe,
873        &out_pipe,
874        Some(std::sync::Arc::new(report)),
875    )?;
876    Ok(Value::int(code))
877}
878
879/// Run `argv` directly (no terminal) and pump it through explicit pipes
880/// until the child exits. Must run inside `ASYNC`. Returns the INT exit
881/// code (-1 when the child died by signal).
882///
883/// Bytes travel untouched: no init sequence, no newline translation, no
884/// setup handshake. This is the binary-safe leg `scp`-style protocols
885/// need; `SSH_PTY_RUN` owns the interactive side instead.
886///
887/// The code reports as the wire `exit-status` at child exit, so stock
888/// clients see the real code instead of 255. Signaled children report
889/// nothing: clients observe the close without a status.
890///
891/// Stdin EOF closes the child's stdin, so stdin-driven children like
892/// `cat` exit on their own. Standard output and error ride separate
893/// pipes: diagnostics must never pollute the byte stream.
894///
895/// Environment is exactly the script environment like `RUN`:
896/// block-scoped `ENV` reaches the child; host names arrive only through
897/// `INHERIT_ENV`. The working directory comes from the script.
898///
899/// Windows joining follows MSVCRT rules, so CRT programs parse back
900/// exactly `argv`. `cmd /c` is the exception (its tail is a command,
901/// not `argv`): route command text via `ENV SSH_COMMAND="..."` with
902/// `["cmd", "/c", "%SSH_COMMAND%"]` instead.
903#[oxdock_func(
904    returns = TypeTag::Int,
905    summary = "Run a command with piped stdio into explicit pipes."
906)]
907#[example(
908    name = "run with piped stdio",
909    code = r###"
910    IMPORT [STD, SSH]
911    INHERIT_ENV [PATH]
912    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-run", {username: "u", password: "p"})
913    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
914    LET $cin: PIPE
915    LET $cout: PIPE
916    LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("doc-ssh-run", "u", "p", $cin, $cout) }
917    WITH_IO [stdout=$cin] ECHO "client-hello"
918    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
919
920    # The client task only proved the session live: cancel it before the
921    # run, so no two pumps share the session.
922    CANCEL $c
923    LET $pin: PIPE
924    LET $pout: PIPE
925    LET $perr: PIPE
926    LET $argv: LIST<STRING> = ["sh", "-c", "echo run-hi"]
927    [family:windows] {
928        $argv = ["cmd", "/c", "echo run-hi"]
929    }
930    LET $t: HANDLE<INT> = ASYNC { RETURN SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
931    LET $code: INT = AWAIT $t
932    ASSERT_EQ $code 0
933    ASSERT_CONTAINS $pout "run-hi"
934    SSH_CLOSE($m.server)
935    "###
936)]
937fn ssh_run<P: ProcessManager>(
938    cx: &mut StepCtx<P>,
939    /// Session handle from `SSH_DEQUEUE`.
940    session: SshSessionTag,
941    /// Program and arguments to run.
942    argv: Vec<String>,
943    /// Pipe carrying bytes consumed by the child on stdin.
944    in_pipe: PipeHandle,
945    /// Pipe carrying bytes produced by the child on stdout.
946    out_pipe: PipeHandle,
947    /// Pipe carrying bytes produced by the child on stderr.
948    err_pipe: PipeHandle,
949) -> Result<Value> {
950    if !cx.is_async_task() {
951        return Err(anyhow::Error::from(ssh_diag::run_requires_async()));
952    }
953    let in_pipe = Value::pipe_handle(in_pipe);
954    let out_pipe = Value::pipe_handle(out_pipe);
955    let err_pipe = Value::pipe_handle(err_pipe);
956    // Best effort: an unpumped session has no reader. Owned clone:
957    // the reaper runs detached, so the callback must be `'static`.
958    let session_report = session.clone();
959    let report = move |code: u32| {
960        let _ = session_report.send_exit_status(code);
961    };
962    let code = crate::run::pump_run_session(
963        cx,
964        &argv,
965        &in_pipe,
966        &out_pipe,
967        &err_pipe,
968        Some(std::sync::Arc::new(report)),
969    )?;
970    Ok(Value::int(code))
971}
972
973/// Run one argv vector on a remote host over SSH and collect the
974/// result. Stateless by design: every call carries its target,
975/// credentials, and argv, holds no session, and returns one MAP with
976/// `exit`, `stdout`, `stderr`, `truncated`, and `timed_out`. A retry
977/// after a dropped channel repeats the same bytes, so idempotent
978/// commands make retries boring.
979///
980/// The argv never becomes a shell string in script hands: it joins
981/// once here through `shell_words::join`, the same vetted
982/// implementation behind `SHELL_SPLIT_ARGS`/`SHELL_JOIN_ARGS` and the
983/// remote plugins. Quoting `$HOME`, backticks, and redirects arrive as
984/// literal arguments because no layer between the caller and this join
985/// re-parses them.
986///
987/// Output caps apply while reading: past `max_bytes` per stream the
988/// buffers stop growing but the drain continues, so a flood still
989/// learns its exit status and reports `truncated`. A timeout kills
990/// the wait and returns whatever arrived with `timed_out`. `exit` is
991/// -1 when the server never sent a status.
992#[oxdock_func(returns = TypeTag::Map, summary = "Run argv on a remote host over SSH and collect the result.")]
993#[example(
994    name = "exec collects remote output",
995    code = r###"
996    # The server side answers exec with a local run: dequeue the
997    # session, split the joined command back into argv, run it, and
998    # pump the child output into the channel. The exit status rides
999    # the wire through the session report.
1000    IMPORT [STD, SSH]
1001    INHERIT_ENV [PATH]
1002    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exec", {username: "u", password: "p"})
1003    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
1004    LET $runner: HANDLE<VOID> = ASYNC {
1005        LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
1006        LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS($sess.command)
1007        LET $wire: PIPE
1008        LET $drain: PIPE
1009        LET $pump: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_PUMP_CHANNEL($sess.session, $wire, $drain) }
1010        LET $pin: PIPE
1011        LET $pout: PIPE
1012        LET $perr: PIPE
1013        LET $run: HANDLE<INT> = ASYNC { RETURN SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
1014        LET $n: INT = SSH_PUMP($pout, $wire)
1015        LET $code: INT = AWAIT $run
1016        LET $pDone: MAP<ANY> = AWAIT $pump
1017        ASSERT_EQ $code 0
1018    }
1019
1020    # One call, one MAP: argv in, collected streams out.
1021    [family:unix] {
1022        LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["echo", "exec-hi"], {})
1023        ASSERT_EQ $res.timed_out false
1024        ASSERT_EQ $res.exit 0
1025        ASSERT_CONTAINS $res.stdout "exec-hi"
1026    }
1027    [family:windows] {
1028        LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["cmd", "/c", "echo exec-hi"], {})
1029        ASSERT_EQ $res.timed_out false
1030        ASSERT_EQ $res.exit 0
1031        ASSERT_CONTAINS $res.stdout "exec-hi"
1032    }
1033    AWAIT $runner
1034    SSH_CLOSE($m.server)
1035    "###
1036)]
1037fn ssh_exec<P: ProcessManager>(
1038    cx: &mut StepCtx<P>,
1039    /// Dial target: a service name resolved through runner mappings.
1040    target: String,
1041    /// Inner credentials for the SSH session.
1042    username: String,
1043    /// Inner credentials for the SSH session.
1044    password: String,
1045    /// Program and arguments to run remotely; joined once, by the
1046    /// plugin, with POSIX shell quoting.
1047    argv: Vec<String>,
1048    /// `timeout` DURATION|STRING (default 60s) and `max_bytes` INT
1049    /// (default 8 MiB per stream).
1050    #[options("timeout?: DURATION|STRING", "max_bytes?: INT")]
1051    options: BTreeMap<String, Value>,
1052) -> Result<Value> {
1053    if argv.is_empty() {
1054        return Err(anyhow::Error::from(ssh_diag::exec_needs_program()));
1055    }
1056    if username.is_empty() {
1057        return Err(anyhow::Error::from(ssh_diag::exec_username_empty()));
1058    }
1059    let registry = cx
1060        .module_state::<EndpointRegistry>(MODULE_SSH)
1061        .expect("SSH module registers its endpoint registry as module state");
1062    if registry.is_offline() {
1063        return Err(anyhow::Error::from(ssh_diag::exec_offline()));
1064    }
1065    // Symbolic only: physical shapes already failed in the parser.
1066    let endpoint = parse_virtual_endpoint(&target, FUNC_EXEC)?;
1067    let key = EndpointKey::tcp(endpoint);
1068    let addr = match resolve_service_target(
1069        &registry,
1070        &key,
1071        FUNC_EXEC,
1072        SocketRequirement::SocketRequired,
1073    )? {
1074        ServiceTarget::Tcp(addr) => addr,
1075        // Unreachable: the shared resolver already bailed; same text.
1076        ServiceTarget::Memory => {
1077            return Err(anyhow::Error::from(no_cli_mapping(
1078                FUNC_EXEC,
1079                &key.endpoint,
1080            )));
1081        }
1082    };
1083    let timeout = match options.get(OPT_TIMEOUT) {
1084        None => crate::runtime::DEFAULT_EXEC_TIMEOUT,
1085        Some(value) => {
1086            // `check_options` verified `DURATION|STRING`; narrow directly.
1087            let timeout = if let Some(duration) = value.as_duration() {
1088                duration
1089            } else {
1090                let text = value
1091                    .as_str()
1092                    .expect("check_options verified DURATION|STRING");
1093                oxdock_parser::command::parse_duration(text).map_err(|e| {
1094                    ssh_diag::option_must_be_duration(FUNC_EXEC, OPT_TIMEOUT, text, e)
1095                })?
1096            };
1097            if timeout.is_zero() {
1098                return Err(anyhow::Error::from(ssh_diag::exec_option_must_be_positive(
1099                    OPT_TIMEOUT,
1100                )));
1101            }
1102            timeout
1103        }
1104    };
1105    let max_bytes = match options.get(OPT_MAX_BYTES) {
1106        None => crate::runtime::DEFAULT_EXEC_MAX_BYTES,
1107        Some(value) => {
1108            let bytes = value.as_i64().expect("check_options verified INT");
1109            if bytes <= 0 {
1110                return Err(anyhow::Error::from(ssh_diag::exec_option_must_be_positive(
1111                    OPT_MAX_BYTES,
1112                )));
1113            }
1114            bytes as usize
1115        }
1116    };
1117    // The single shell encoding in the pipeline: argv becomes one
1118    // string here, and only here.
1119    let command = shell_words::join(&argv).into_bytes();
1120    let runtime = connect_runtime()?;
1121    let outcome = runtime
1122        .block_on(crate::runtime::run_remote_exec(
1123            &addr, &username, &password, command, timeout, max_bytes,
1124        ))
1125        .map_err(ssh_diag::exec_failed)?;
1126    let mut map = BTreeMap::new();
1127    map.insert(
1128        FIELD_EXIT.to_string(),
1129        Value::int(outcome.exit.unwrap_or(-1)),
1130    );
1131    map.insert(
1132        "stdout".to_string(),
1133        Value::string(String::from_utf8_lossy(&outcome.stdout).into_owned()),
1134    );
1135    map.insert(
1136        "stderr".to_string(),
1137        Value::string(String::from_utf8_lossy(&outcome.stderr).into_owned()),
1138    );
1139    map.insert(FIELD_TRUNCATED.to_string(), Value::bool(outcome.truncated));
1140    map.insert(FIELD_TIMED_OUT.to_string(), Value::bool(outcome.timed_out));
1141    Ok(Value::map(map))
1142}
1143
1144/// Mint a random server password (256 bits, hex).
1145///
1146/// Each call draws fresh OS-RNG key material and renders 64
1147/// lowercase hex chars, so committed scripts carry no usable
1148/// credential: mint at runtime, hand the value to both sides, drop
1149/// it after. Pure (no step context), so it runs anywhere a STRING
1150/// binds, including option maps and placeholders.
1151#[oxdock_func(pure, returns = TypeTag::String)]
1152#[example(
1153    name = "mint and serve",
1154    code = r###"
1155    IMPORT [STD, SSH]
1156
1157    # Fresh draws mint 64 hex chars with no committed secret.
1158    LET $pass: STRING = SSH_GENERATE_PASSWORD()
1159    LET $len: INT = LEN($pass)
1160    ASSERT_EQ $len 64
1161
1162    # The minted value serves directly as a server password.
1163    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-gen-pass", {username: "u", password: $pass})
1164    SSH_CLOSE($m.server)
1165    "###
1166)]
1167fn ssh_generate_password() -> Result<Value> {
1168    Ok(Value::string(crate::generate_password()))
1169}
1170
1171/// Field table backing the `SSH_SERVE_INFO` schema and return tag.
1172fn serve_result_fields() -> Arc<[Field]> {
1173    Arc::from(vec![
1174        Field {
1175            name: FIELD_SERVER.to_string(),
1176            ty: TypeTag::Custom(SshServerTag::descriptor()),
1177            docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
1178            optional: false,
1179            default: None,
1180
1181            alias: None,
1182        },
1183        Field {
1184            name: FIELD_ADDR.to_string(),
1185            ty: TypeTag::String,
1186            docs: "Bound socket address (`ip:port`) of the server.",
1187            optional: false,
1188            default: None,
1189
1190            alias: None,
1191        },
1192        Field {
1193            name: FIELD_USERNAME.to_string(),
1194            ty: TypeTag::String,
1195            docs: "Configured username.",
1196            optional: false,
1197            default: None,
1198
1199            alias: None,
1200        },
1201        Field {
1202            name: FIELD_PASSWORD.to_string(),
1203            ty: TypeTag::String,
1204            docs: "Configured password.",
1205            optional: false,
1206            default: None,
1207
1208            alias: None,
1209        },
1210        Field {
1211            name: FIELD_VIRTUAL.to_string(),
1212            ty: TypeTag::String,
1213            docs: "Virtual endpoint echo of the claimed slot.",
1214            optional: false,
1215            default: None,
1216
1217            alias: None,
1218        },
1219    ])
1220}
1221
1222/// Field table backing the `SSH_DEQUEUE_INFO` schema and return tag.
1223fn dequeue_result_fields() -> Arc<[Field]> {
1224    Arc::from(vec![
1225        Field {
1226            name: FIELD_SESSION.to_string(),
1227            ty: TypeTag::Custom(SshSessionTag::descriptor()),
1228            docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
1229            optional: false,
1230            default: None,
1231
1232            alias: None,
1233        },
1234        Field {
1235            name: FIELD_COMMAND.to_string(),
1236            ty: TypeTag::String,
1237            docs: "Executed command, empty for shells.",
1238            optional: false,
1239            default: None,
1240
1241            alias: None,
1242        },
1243        Field {
1244            name: FIELD_USERNAME.to_string(),
1245            ty: TypeTag::String,
1246            docs: "Authenticated username, empty when unset.",
1247            optional: false,
1248            default: None,
1249
1250            alias: None,
1251        },
1252        Field {
1253            name: FIELD_ADDR.to_string(),
1254            ty: TypeTag::String,
1255            docs: "Peer address, empty when unset.",
1256            optional: false,
1257            default: None,
1258
1259            alias: None,
1260        },
1261    ])
1262}
1263
1264/// The `SSH` host module: virtual-endpoint server plus client, bridged
1265/// to DSL pipes. Generic over the process manager like every host module.
1266pub fn module_with<P: ProcessManager>() -> HostModule<P> {
1267    module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
1268}
1269
1270/// The `SSH` host module resolving through `registry`: the registry
1271/// travels as module state (`HostModule::with_state`) for bodies to
1272/// fetch from `cx`, so every entry stays `#[oxdock_func]`. Everything
1273/// else reaches the same registry through its `SSH_SERVER` handle. A
1274/// pre-run service check rides along: every service the steps name must
1275/// be fully bound before execution starts.
1276pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
1277    let check = registry.pre_run_check(MODULE_SSH);
1278    HostModule {
1279        name: MODULE_SSH.to_string(),
1280        funcs: vec![
1281            SshServe::registration(),
1282            SshAccept::registration(),
1283            SshDequeue::registration(),
1284            SshPumpChannel::registration(),
1285            SshSendExitStatus::registration(),
1286            SshClose::registration(),
1287            SshConnect::registration(),
1288            SshExec::registration(),
1289            SshPump::registration(),
1290            SshPtyRun::registration(),
1291            SshRun::registration(),
1292            SshGeneratePassword::registration(),
1293        ],
1294        types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
1295        record_schemas: vec![
1296            RecordSchema {
1297                name: "SSH_SERVE_INFO",
1298                fields: serve_result_fields(),
1299            },
1300            RecordSchema {
1301                name: "SSH_DEQUEUE_INFO",
1302                fields: dequeue_result_fields(),
1303            },
1304        ],
1305        states: Vec::new(),
1306    }
1307    .with_state(registry)
1308    .with_state(Arc::new(check))
1309}