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