oxdock-ssh-plugin 0.46.0-alpha

Ephemeral user-space SSH server and client for OxDock scripts, bridged to stdio pipelines through the Engine facade.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
//! The `SSH` host module: `SERVE`, `ACCEPT` / `DEQUEUE` + `PUMP_CHANNEL`,
//! `CLOSE`, `CONNECT`, `PUMP`.
//!
//! Pipe direction convention (fixed for every func): `out_pipe` carries
//! bytes produced by the wire side (the DSL reads them), `in_pipe`
//! carries bytes consumed by the wire side (the DSL writes them).

use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;

use anyhow::Result;

use crate::diagnostics as ssh_diag;
use oxdock_core::{Field, HostModule, OxDockFn, OxDockType, RecordSchema, StepCtx, TypeTag, Value};
use oxdock_func_macro::oxdock_func;
use oxdock_net_plugin::{
    AcquiredListener, EndpointKey, EndpointRegistry, ServiceTarget, SocketRequirement,
    acquire_listener, no_cli_mapping, parse_virtual_endpoint, resolve_service_target,
};
use oxdock_pipe::PipeHandle;
use oxdock_process::ProcessManager;
use russh::keys::{Algorithm, PrivateKey};

use crate::bridge::{pump_pipe_to_pipe, pump_session};
use crate::keys::load_or_create_host_key;
use crate::runtime::{connect_runtime, connect_session};
use crate::state::{
    CLOSE_JOIN_TIMEOUT, Dequeue, PendingSession, ServerState, SessionQueue, ShutdownSignal,
};
use crate::types::{SshServerTag, SshSessionTag};
use crate::validate::parse_serve_endpoint;

/// Result map keys for SSH session outcomes. Single source for the
/// `Field` schemas below and every `map.insert` site, so a rename
/// cannot drift one side silent.
const FIELD_CLOSED: &str = "closed";
const FIELD_COMMAND: &str = "command";
const FIELD_EXIT_STATUS: &str = "exit_status";
const FIELD_SERVER: &str = "server";
const FIELD_ADDR: &str = "addr";
const FIELD_USERNAME: &str = "username";
const FIELD_PASSWORD: &str = "password";
const FIELD_VIRTUAL: &str = "virtual";
const FIELD_SESSION: &str = "session";
const FIELD_EXIT: &str = "exit";
const FIELD_TRUNCATED: &str = "truncated";
const FIELD_TIMED_OUT: &str = "timed_out";

/// Option map keys for SSH calls. `username` and `password` reuse the
/// `FIELD_*` spellings above (same words, same meaning); the rest live
/// here so every lookup matches its `#[options]` spelling.
const OPT_KEY_PATH: &str = "key_path";
const OPT_IDLE_TIMEOUT: &str = "idle_timeout";
const OPT_TIMEOUT: &str = "timeout";
const OPT_MAX_BYTES: &str = "max_bytes";

/// Shared DSL func labels passed as caller tags. One spelling for
/// the whole crate, so a func rename is one edit. Single-use labels
/// (`SSH_ACCEPT`, `SSH_DEQUEUE`, `SSH_CLOSE`), message templates,
/// type names, and doc examples stay inline per Section F.
pub(crate) const FUNC_EXEC: &str = "SSH_EXEC";
pub(crate) const FUNC_CONNECT: &str = "SSH_CONNECT";
pub(crate) const FUNC_SERVE: &str = "SSH_SERVE";

/// Host-module name for the endpoint-registry slot, the pre-run
/// check, and the registration. One spelling, so a rename is one
/// edit.
pub(crate) const MODULE_SSH: &str = "SSH";

/// Unique server ids per process.
static SERVER_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

/// Block until the queue yields an authenticated session (or teardown).
/// Shared by `SSH_DEQUEUE` and the `SSH_ACCEPT` wrapper. No timeout:
/// a waiter parks in the queue condvar while a bridge thread parks on
/// the task hub; on hub fire the bridge pokes the queue awake and the
/// waiter ends with `Cancelled`. One transient thread per call, spent
/// only on wakeups, never on ticks.
fn dequeue_session<P: ProcessManager>(
    cx: &StepCtx<P>,
    queue: &Arc<SessionQueue>,
    func: &str,
) -> Result<PendingSession> {
    let hub = cx.cancel_hub();
    let bridge_queue = Arc::clone(queue);
    let bridge_hub = Arc::clone(&hub);
    let (started_tx, started_rx) = std::sync::mpsc::channel::<()>();
    std::thread::scope(|scope| {
        let bridge = scope.spawn(move || {
            // Rendezvous: read the sequence, then signal, then park,
            // so the release below can never land before the wait.
            let seen = bridge_hub.sequence();
            let _ = started_tx.send(());
            let (cancelled, _) = bridge_hub.wait(seen);
            if cancelled {
                bridge_queue.poke();
            }
        });
        let result = loop {
            if hub.is_cancelled() || cx.is_cancelled() {
                break Err(anyhow::Error::from(ssh_diag::dequeue_task_cancelled(func)));
            }
            match queue.try_pop() {
                Dequeue::Session(session) => break Ok(session),
                Dequeue::Shutdown => {
                    break Err(anyhow::Error::from(ssh_diag::dequeue_server_closed(func)));
                }
                Dequeue::Empty | Dequeue::Cancelled => {}
            }
            match queue.wait_blocking(&hub) {
                Dequeue::Session(session) => break Ok(session),
                Dequeue::Shutdown => {
                    break Err(anyhow::Error::from(ssh_diag::dequeue_server_closed(func)));
                }
                Dequeue::Cancelled | Dequeue::Empty => {}
            }
        };
        // Release the bridge (rendezvous first so the poke cannot
        // land before its wait, then poke, never cancel: the dequeue
        // may have ended cleanly) and join it: no thread outlives the
        // call.
        let _ = started_rx.recv();
        hub.poke();
        let _ = bridge.join();
        result
    })
}

/// Dequeue one authenticated session for routing before any byte
/// pumping starts. Must run inside `ASYNC`.
///
/// The server sends first: the client side never EOFs its input, so a
/// synthetic reply cannot race teardown.
///
#[oxdock_func(
    returns = TypeTag::Record(dequeue_result_fields()),
    summary = "Dequeue one SSH session with its metadata."
)]
#[example(
    name = "route one session",
    code = r###"
    IMPORT [STD, SSH]
    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-route", {username: "u", password: "p"})

    # Serve: dequeue one session and pump a synthetic reply.
    LET $in: PIPE
    LET $out: PIPE
    LET $w: HANDLE<VOID> = ASYNC {
        LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
        ASSERT_EQ $sess.username "u"
        SSH_PUMP_CHANNEL($sess.session, $in, $out)
    }

    # Connect a client to the server.
    LET $cin: PIPE
    LET $cout: PIPE
    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-route", "u", "p", $cin, $cout) }

    # Close both inputs: each pump observes EOF, half-closes, and every
    # task returns with no cancellation.
    WITH_IO [stdout=$cin] ECHO "client-hello"
    WITH_IO [stdout=$in] ECHO "server-greeting"
    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
    ASSERT_EQ $cDone.closed true
    AWAIT $w
    SSH_CLOSE($m.server)
    "###
)]
fn ssh_dequeue<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Server handle from `SSH_SERVE`.
    server: SshServerTag,
) -> Result<Value> {
    if !cx.is_async_task() {
        return Err(anyhow::Error::from(ssh_diag::dequeue_requires_async()));
    }
    let state = Arc::clone(server.state());
    let session = dequeue_session(cx, state.queue(), "SSH_DEQUEUE")?;
    let command = session.exec_command.clone().unwrap_or_default();
    let username = session.username.clone().unwrap_or_default();
    let addr = session
        .peer_addr
        .map(|addr| addr.to_string())
        .unwrap_or_default();
    let tag = SshSessionTag::new(
        session.exec_command,
        session.username,
        session.peer_addr,
        session.pty_size,
        session.up_rx,
        session.down_tx,
    );
    let mut map = BTreeMap::new();
    map.insert(
        "session".to_string(),
        Value::mint_heap(SshSessionTag::descriptor(), tag),
    );
    map.insert(FIELD_COMMAND.to_string(), Value::string(command));
    map.insert(FIELD_USERNAME.to_string(), Value::string(username));
    map.insert(FIELD_ADDR.to_string(), Value::string(addr));
    Ok(Value::map(map))
}

/// Spin up an SSH server on a runner-mapped service. Unmapped and
/// memory services bail: SSH needs a TCP socket.
/// `options` takes required `username`/`password` STRINGs plus the
/// optional `key_path` STRING (workspace-relative Ed25519 file,
/// load-or-create; blank keeps the ephemeral key) and the optional
/// `idle_timeout` DURATION (quiet-connection kill, default 5m; zero
/// disables it for persistent sessions).
#[oxdock_func(returns = TypeTag::Record(serve_result_fields()), summary = "Serve SSH on a virtual service endpoint.")]
#[example(
    name = "serve and close",
    code = r###"
    IMPORT [STD, SSH]
    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-serve", {username: "u", password: "p"})
    ASSERT_EQ $m.virtual "doc-ssh-serve"
    SSH_CLOSE($m.server)
    "###
)]
fn ssh_serve<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Service name to serve; the runner maps it with -p/--listen.
    bind: String,
    /// Server credentials and host key.
    #[options(
        "username: STRING",
        "password: STRING",
        "key_path?: STRING",
        "idle_timeout?: DURATION|STRING"
    )]
    options: BTreeMap<String, Value>,
) -> Result<Value> {
    let map = &options;
    let username = match map.get(FIELD_USERNAME) {
        Some(value) => {
            let text = value.as_str().expect("check_options verified STRING");
            if text.trim().is_empty() {
                return Err(anyhow::Error::from(ssh_diag::serve_option_empty(
                    FIELD_USERNAME,
                )));
            }
            text.to_string()
        }
        None => {
            return Err(anyhow::Error::from(ssh_diag::serve_option_required(
                FIELD_USERNAME,
            )));
        }
    };
    let password = match map.get(FIELD_PASSWORD) {
        Some(value) => {
            let text = value.as_str().expect("check_options verified STRING");
            if text.trim().is_empty() {
                return Err(anyhow::Error::from(ssh_diag::serve_option_empty(
                    FIELD_PASSWORD,
                )));
            }
            text.to_string()
        }
        None => {
            return Err(anyhow::Error::from(ssh_diag::serve_option_required(
                FIELD_PASSWORD,
            )));
        }
    };
    let key_path = match map.get(OPT_KEY_PATH) {
        Some(value) => {
            let text = value.as_str().expect("check_options verified STRING");
            if text.trim().is_empty() {
                None
            } else {
                Some(text.to_string())
            }
        }
        None => None,
    };
    // Idle kill override: absent keeps the default, zero disables the
    // timeout entirely (persistent sessions must opt out explicitly).
    let idle_timeout = match map.get(OPT_IDLE_TIMEOUT) {
        Some(value) => {
            // `check_options` verified `DURATION|STRING`; narrow directly.
            let timeout = if let Some(duration) = value.as_duration() {
                duration
            } else {
                let text = value
                    .as_str()
                    .expect("check_options verified DURATION|STRING");
                oxdock_parser::command::parse_duration(text).map_err(|e| {
                    ssh_diag::option_must_be_duration(FUNC_SERVE, OPT_IDLE_TIMEOUT, text, e)
                })?
            };
            (!timeout.is_zero()).then_some(timeout)
        }
        None => Some(crate::runtime::DEFAULT_INACTIVITY_TIMEOUT),
    };
    let registry = cx
        .module_state::<EndpointRegistry>(MODULE_SSH)
        .expect("SSH module registers its endpoint registry as module state");
    let endpoint = parse_serve_endpoint(&bind)?;
    let key = EndpointKey::tcp(endpoint);
    let (acquired, registry) = acquire_listener(
        &registry,
        &key,
        FUNC_SERVE,
        SocketRequirement::SocketRequired,
    )?;
    let host_key = match load_or_create_host_key(cx, FUNC_SERVE, key_path)? {
        Some(key) => key,
        None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
            .map_err(ssh_diag::ephemeral_key_generate_failed)?,
    };
    let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    let id = format!("ssh-{pid}-{id}", pid = std::process::id());
    let queue = Arc::new(SessionQueue::new());
    let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
    let (local_addr, addr_text, thread) = match acquired {
        AcquiredListener::Tcp { listener, addr } => {
            // The runtime owns a clone; the slot keeps the backlog socket.
            let owned = listener
                .try_clone()
                .map_err(ssh_diag::serve_listener_clone_failed)?;
            let thread_queue = Arc::clone(&queue);
            let thread_user = username.clone();
            let thread_pass = password.clone();
            let thread = std::thread::Builder::new()
                .name(id.clone())
                .spawn(move || {
                    crate::runtime::serve(
                        owned,
                        host_key,
                        thread_user,
                        thread_pass,
                        thread_queue,
                        shutdown_rx,
                        idle_timeout,
                    )
                })
                .map_err(ssh_diag::serve_spawn_failed)?;
            (addr, addr.to_string(), Some(thread))
        }
        AcquiredListener::Memory => {
            // Unreachable: `SocketRequired` already bailed; same text.
            drop(shutdown_rx);
            return Err(anyhow::Error::from(no_cli_mapping(
                FUNC_SERVE,
                &key.endpoint,
            )));
        }
        AcquiredListener::Offline => {
            // No thread: dropping the receiver makes shutdown a no-op.
            drop(shutdown_rx);
            (
                std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
                key.endpoint.to_string(),
                None,
            )
        }
    };
    let state = Arc::new(ServerState::new(crate::state::ServerConfig {
        id,
        local_addr,
        addr_text: addr_text.clone(),
        queue,
        shutdown_tx,
        thread,
        registry: Arc::clone(&registry),
        endpoint: key.clone(),
    }));
    let mut map = BTreeMap::new();
    map.insert(
        "server".to_string(),
        Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
    );
    map.insert(FIELD_ADDR.to_string(), Value::string(addr_text));
    map.insert(FIELD_USERNAME.to_string(), Value::string(username));
    map.insert(FIELD_PASSWORD.to_string(), Value::string(password));
    map.insert(
        "virtual".to_string(),
        Value::string(key.endpoint.to_string()),
    );
    Ok(Value::map(map))
}

/// `SSH_DEQUEUE` + `SSH_PUMP_CHANNEL` in one call, for worker loops
/// that need no pre-pump inspection. Must run inside `ASYNC`.
///
/// The server sends first: the client side never EOFs its input, so
/// the reply cannot race teardown.
///
#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
    name: FIELD_CLOSED.to_string(),
    ty: TypeTag::Bool,
    docs: "True when the session closed cleanly.",
    optional: false,
    default: None,

    alias: None,}, Field {
    name: FIELD_COMMAND.to_string(),
    ty: TypeTag::String,
    docs: "Executed command, empty for shells.",
    optional: false,
    default: None,

    alias: None,}])), summary = "Accept one SSH session into pipes.")]
#[example(
    name = "accept and close",
    code = r###"
    IMPORT [STD, SSH]
    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-accept", {username: "u", password: "p"})
    LET $in: PIPE
    LET $out: PIPE
    LET $acc: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_ACCEPT($m.server, $in, $out) }
    LET $cin: PIPE
    LET $cout: PIPE
    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-accept", "u", "p", $cin, $cout) }

    # Close both inputs: each pump observes EOF, half-closes, and both
    # tasks return their result maps with no cancellation.
    WITH_IO [stdout=$cin] ECHO "client-hello"
    WITH_IO [stdout=$in] ECHO "server-greeting"
    LET $done: MAP<ANY> = AWAIT $acc
    ASSERT_EQ $done.closed true
    ASSERT_CONTAINS $done "command"
    LET $cDone: MAP<ANY> = AWAIT $c
    ASSERT_EQ $cDone.closed true
    SSH_CLOSE($m.server)
    "###
)]
fn ssh_accept<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Server handle from `SSH_SERVE`.
    server: SshServerTag,
    /// Pipe carrying bytes consumed by the wire side.
    in_pipe: PipeHandle,
    /// Pipe carrying bytes produced by the wire side.
    out_pipe: PipeHandle,
) -> Result<Value> {
    if !cx.is_async_task() {
        return Err(anyhow::Error::from(ssh_diag::accept_requires_async()));
    }
    let in_pipe = Value::pipe_handle(in_pipe);
    let out_pipe = Value::pipe_handle(out_pipe);
    let state = Arc::clone(server.state());
    let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
    pump_session(
        cx,
        &in_pipe,
        &out_pipe,
        session.up_rx,
        session.down_tx,
        true,
    )?;
    let mut map = BTreeMap::new();
    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
    map.insert(
        "command".to_string(),
        Value::string(session.exec_command.unwrap_or_default()),
    );
    Ok(Value::map(map))
}

/// Pump a dequeued session through explicit pipes until the channel
/// closes. Must run inside `ASYNC`. Pump ends take once: a second
/// pump bails instead of splitting bytes.
///
#[oxdock_func(
    returns = TypeTag::Record(std::sync::Arc::from([Field {
        name: FIELD_CLOSED.to_string(),
        ty: TypeTag::Bool,
        docs: "True when the session closed cleanly.",
        optional: false,
        default: None,

        alias: None,}])),
    summary = "Pump a dequeued SSH session through pipes."
)]
#[example(
    name = "pump a session",
    code = r###"
    IMPORT [STD, SSH]
    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pump", {username: "u", password: "p"})
    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
    LET $cin: PIPE
    LET $cout: PIPE
    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-pump", "u", "p", $cin, $cout) }
    WITH_IO [stdout=$cin] ECHO "client-hello"
    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
    LET $sin: PIPE
    LET $sout: PIPE
    LET $p: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
    WITH_IO [stdout=$sin] ECHO "server-greeting"
    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
    ASSERT_EQ $cDone.closed true
    LET $pDone: MAP<ANY> = AWAIT $p
    ASSERT_EQ $pDone.closed true
    SSH_CLOSE($m.server)
    "###
)]
fn ssh_pump_channel<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Session handle from `SSH_DEQUEUE` (pump ends take once).
    session: SshSessionTag,
    /// Pipe carrying bytes consumed by the wire side.
    in_pipe: PipeHandle,
    /// Pipe carrying bytes produced by the wire side.
    out_pipe: PipeHandle,
) -> Result<Value> {
    if !cx.is_async_task() {
        return Err(anyhow::Error::from(ssh_diag::pump_channel_requires_async()));
    }
    let in_pipe = Value::pipe_handle(in_pipe);
    let out_pipe = Value::pipe_handle(out_pipe);
    let (up_rx, down_tx) = session.take_pump_ends()?;
    // Release the control sender when the pump ends (pass or fail):
    // the wire writer must observe the drain and close then, not when
    // the last session clone drops long after.
    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, true);
    session.finish_pump();
    pump?;
    let mut map = BTreeMap::new();
    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
    Ok(Value::map(map))
}

/// Report the session's exit status to the client (RFC 4254 6.10),
/// ahead of the channel close. Survives the take-once pump ends, so
/// call it before the pump drains. `SSH_PTY_RUN` reports by itself;
/// this covers other legs (`RUN`, synthetic replies).
#[oxdock_func(returns = TypeTag::Bool, summary = "Send the session exit status to the client.")]
#[example(
    name = "report exit status",
    code = r###"
    IMPORT [STD, SSH]
    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exit-status", {username: "u", password: "p"})
    LET $srv: HANDLE<VOID> = ASYNC {
        LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
        LET $sin: PIPE
        LET $sout: PIPE
        LET $p: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
        SSH_SEND_EXIT_STATUS($sess.session, 3)
        WITH_IO [stdout=$sin] ECHO "server-greeting"
        AWAIT $p
    }
    LET $cin: PIPE
    LET $cout: PIPE
    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-exit-status", "u", "p", $cin, $cout) }
    # Close the client input: its pump observes EOF and half-closes, so
    # both pumps drain instead of idling on an empty pipe.
    WITH_IO [stdout=$cin] ECHO "client-hello"
    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
    ASSERT_EQ $cDone.closed true
    ASSERT_EQ $cDone.exit_status 3
    AWAIT $srv
    SSH_CLOSE($m.server)
    "###
)]
fn ssh_send_exit_status<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Session handle from `SSH_DEQUEUE`.
    session: SshSessionTag,
    /// Exit status to report (0 to 4294967295).
    code: i64,
) -> Result<Value> {
    let _ = cx;
    if code < 0 {
        return Err(anyhow::Error::from(ssh_diag::send_exit_status_negative(
            code,
        )));
    }
    let code = u32::try_from(code)
        .map_err(|_| anyhow::Error::from(ssh_diag::send_exit_status_out_of_range(code)))?;
    session.send_exit_status(code)?;
    Ok(Value::bool(true))
}

/// Shut a server down and join its runtime thread (bounded).
/// Idempotent.
///
#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
#[example(
    name = "shut down",
    code = r###"
    IMPORT [STD, SSH]
    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-close", {username: "u", password: "p"})
    LET $ok: BOOL = SSH_CLOSE($m.server)
    ASSERT_EQ $ok true
    "###
)]
fn ssh_close<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Server handle from `SSH_SERVE`.
    server: SshServerTag,
) -> Result<Value> {
    let _ = cx;
    let state = Arc::clone(server.state());
    state.request_shutdown();
    Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
}

/// Open an SSH client session and pump its shell channel through
/// explicit pipes until it closes. Must run inside `ASYNC`, beside
/// the pump tasks. Under `--offline` the dial bails before any
/// socket work. The result MAP carries `exit_status`, or -1 when the
/// server sent none.
#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
    name: FIELD_CLOSED.to_string(),
    ty: TypeTag::Bool,
    docs: "True when the session closed cleanly.",
    optional: false,
    default: None,

    alias: None,}, Field {
    name: FIELD_EXIT_STATUS.to_string(),
    ty: TypeTag::Int,
    docs: "Remote exit status, or -1 when none arrived.",
    optional: false,
    default: None,

    alias: None,}])), summary = "Open an SSH client session into pipes.")]
#[example(
    name = "connect and close",
    code = r###"
    IMPORT [STD, SSH]
    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-connect", {username: "u", password: "p"})
    LET $in: PIPE
    LET $out: PIPE
    LET $acc: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_ACCEPT($m.server, $in, $out) }
    LET $cin: PIPE
    LET $cout: PIPE
    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-connect", "u", "p", $cin, $cout) }

    # Close both inputs: each pump observes EOF, half-closes, and both
    # tasks return their result maps with no cancellation.
    WITH_IO [stdout=$cin] ECHO "client-hello"
    WITH_IO [stdout=$in] ECHO "server-greeting"
    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
    ASSERT_EQ $cDone.closed true
    LET $adone: MAP<ANY> = AWAIT $acc
    ASSERT_EQ $adone.closed true
    SSH_CLOSE($m.server)
    "###
)]
fn ssh_connect<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Dial target: a service name resolved through runner mappings.
    target: String,
    /// Inner credentials for the SSH session.
    username: String,
    /// Inner credentials for the SSH session.
    password: String,
    /// Pipe carrying bytes consumed by the wire side.
    in_pipe: PipeHandle,
    /// Pipe carrying bytes produced by the wire side.
    out_pipe: PipeHandle,
) -> Result<Value> {
    if !cx.is_async_task() {
        return Err(anyhow::Error::from(ssh_diag::connect_requires_async()));
    }
    // Registry travels as module state.
    let registry = cx
        .module_state::<EndpointRegistry>(MODULE_SSH)
        .expect("SSH module registers its endpoint registry as module state");
    let in_pipe = Value::pipe_handle(in_pipe);
    let out_pipe = Value::pipe_handle(out_pipe);
    if registry.is_offline() {
        return Err(anyhow::Error::from(ssh_diag::connect_offline()));
    }
    if username.is_empty() {
        return Err(anyhow::Error::from(ssh_diag::connect_username_empty()));
    }
    // Symbolic only: physical shapes already failed in the parser.
    let endpoint = parse_virtual_endpoint(&target, FUNC_CONNECT)?;
    let key = EndpointKey::tcp(endpoint);
    let addr = match resolve_service_target(
        &registry,
        &key,
        FUNC_CONNECT,
        SocketRequirement::SocketRequired,
    )? {
        ServiceTarget::Tcp(addr) => addr,
        // Unreachable: the shared resolver already bailed; same text.
        ServiceTarget::Memory => {
            return Err(anyhow::Error::from(no_cli_mapping(
                FUNC_CONNECT,
                &key.endpoint,
            )));
        }
    };
    let runtime = connect_runtime()?;
    let session = runtime
        .block_on(connect_session(&addr, &username, &password))
        .map_err(ssh_diag::connect_failed)?;
    let crate::runtime::OutboundSession {
        up_rx,
        down_tx,
        exit_status,
        wire_done,
        handle,
        ..
    } = session;
    // Client linger: the reply and the exit-status arrive after the
    // client's own stdin EOF, so never cut the output wait short.
    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, false);
    let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
    pump?;
    // Joined after disconnect: a post-EOF status records before this read.
    let _ = runtime.block_on(wire_done);
    let mut map = BTreeMap::new();
    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
    let status = exit_status
        .lock()
        .map(|slot| slot.map(i64::from))
        .unwrap_or(None);
    map.insert(
        FIELD_EXIT_STATUS.to_string(),
        Value::int(status.unwrap_or(-1)),
    );
    Ok(Value::map(map))
}

/// Copy one pipe into another until EOF, then close the target.
/// Either task placement works, as long as the other end is live.
///
#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
#[example(
    name = "copy",
    code = r###"
    # Closing the source ends the copy: the count proves the bytes moved.
    IMPORT [STD, SSH]
    LET $in: PIPE
    WITH_IO [stdout=$in] ECHO "pump-me"
    LET $out: PIPE
    LET $n: INT = SSH_PUMP($in, $out)
    ASSERT_EQ $n 8
    WITH_IO [stdin=$out] READ_LINE $got
    ASSERT_EQ $got "pump-me"
    "###
)]
fn ssh_pump<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Source pipe to drain.
    from_pipe: PipeHandle,
    /// Target pipe receiving the bytes (closed at EOF).
    to_pipe: PipeHandle,
) -> Result<Value> {
    let from_pipe = Value::pipe_handle(from_pipe);
    let to_pipe = Value::pipe_handle(to_pipe);
    let cancel = AtomicBool::new(false);
    let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
    Ok(Value::int(total))
}

/// Run `argv` under a local pseudo-terminal and pump it through
/// explicit pipes until the child exits. Must run inside `ASYNC`.
/// Returns the INT exit code.
///
/// `rows`/`cols` seed the initial size when positive, else the
/// session's requested size (24x80 default). Outer window-changes
/// resize live; each session owns its cell.
///
/// The code also reports as the wire `exit-status` at child exit, so
/// stock clients see the real code instead of 255.
///
/// Every session opens cleared and homed, like Win32-OpenSSH, so the
/// child renders onto a known blank screen.
///
/// Windows joining follows MSVCRT rules, so CRT programs parse back
/// exactly `argv`. `cmd /c` is the exception (its tail is a command,
/// not `argv`): route command text via `ENV SSH_COMMAND="..."` with
/// `["cmd", "/c", "%SSH_COMMAND%"]` instead.
///
/// Stdin arrives with console line endings handled: the pump expands
/// a lone `\n` to `\r\n` on Windows, so portable lines submit as-is
/// and an explicit `\r` passes through untouched. Real terminals
/// already send CR for Enter.
///
/// Environment is exactly the script environment like `RUN`:
/// block-scoped `ENV` (such as the session's `SSH_USER` / `SSH_CLIENT` /
/// `SSH_SERVER` / `SSH_COMMAND` relay) reaches the child; host names
/// arrive only through `INHERIT_ENV`, including `TERM` for terminal
/// definitions. The working directory comes from the script.
///
/// `WITH_IO [tty]` shares the same pump core and covers terminal
/// runs with host or static sizing and step-local reporting. This
/// function covers the two session-bound cases a script assembly
/// cannot reproduce: a rendered run with static geometry observes
/// the opener but never an outer resize (no script primitive
/// subscribes a running pty to the session cell), and a failing DSL
/// `RUN` aborts its task before any script-level status report could
/// follow (there is no try/catch; the close race after that would be
/// the second problem). If a second consumer ever needs
/// session-driven sizing or reaper-ordered reporting, that is the
/// point to revisit unifying the two.
///
#[oxdock_func(
    returns = TypeTag::Int,
    summary = "Run a command under a sized local terminal into pipes."
)]
#[example(
    name = "run under a terminal",
    code = r###"
    IMPORT [STD, SSH]
    INHERIT_ENV [PATH]
    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pty", {username: "u", password: "p"})
    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
    LET $cin: PIPE
    LET $cout: PIPE
    LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("doc-ssh-pty", "u", "p", $cin, $cout) }
    WITH_IO [stdout=$cin] ECHO "client-hello"
    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d

    # The client task only proved the session live: cancel it before the
    # terminal run, so no two pumps share the session.
    CANCEL $c
    LET $pin: PIPE
    LET $pout: PIPE
    # Assert on the whole pipe: terminal streams carry setup noise ahead
    # of child output, so line reads are version-dependent.
    [family:unix] {
        LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($sess.session, ["sh", "-c", "echo pty-hi"], 0, 0, $pin, $pout) }
        LET $code: INT = AWAIT $t
        ASSERT_EQ $code 0
        ASSERT_CONTAINS $pout "pty-hi"
    }
    [family:windows] {
        LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($sess.session, ["cmd", "/c", "echo pty-hi"], 0, 0, $pin, $pout) }
        LET $code: INT = AWAIT $t
        ASSERT_EQ $code 0
        ASSERT_CONTAINS $pout "pty-hi"
    }
    SSH_CLOSE($m.server)
    "###
)]
fn ssh_pty_run<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Session handle from `SSH_DEQUEUE`.
    session: SshSessionTag,
    /// Program and arguments to run.
    argv: Vec<String>,
    /// Terminal rows when positive, session size otherwise.
    rows: i64,
    /// Terminal columns when positive, session size otherwise.
    cols: i64,
    /// Pipe carrying bytes consumed by the child.
    in_pipe: PipeHandle,
    /// Pipe carrying bytes produced by the child.
    out_pipe: PipeHandle,
) -> Result<Value> {
    if !cx.is_async_task() {
        return Err(anyhow::Error::from(ssh_diag::pty_run_requires_async()));
    }
    let in_pipe = Value::pipe_handle(in_pipe);
    let out_pipe = Value::pipe_handle(out_pipe);
    let initial = if rows > 0 && cols > 0 {
        crate::state::PtySize::new(rows as u32, cols as u32)
    } else {
        session.pty_size()
    };
    // Best effort: an unpumped session has no reader. Owned clone:
    // the reaper runs detached, so the callback must be `'static`.
    let session_report = session.clone();
    let report = move |code: u32| {
        let _ = session_report.send_exit_status(code);
    };
    let code = crate::pty::pump_pty_session(
        cx,
        &argv,
        initial,
        &session.pty_size_handle(),
        &in_pipe,
        &out_pipe,
        Some(std::sync::Arc::new(report)),
    )?;
    Ok(Value::int(code))
}

/// Run `argv` directly (no terminal) and pump it through explicit pipes
/// until the child exits. Must run inside `ASYNC`. Returns the INT exit
/// code (-1 when the child died by signal).
///
/// Bytes travel untouched: no init sequence, no newline translation, no
/// setup handshake. This is the binary-safe leg `scp`-style protocols
/// need; `SSH_PTY_RUN` owns the interactive side instead.
///
/// The code reports as the wire `exit-status` at child exit, so stock
/// clients see the real code instead of 255. Signaled children report
/// nothing: clients observe the close without a status.
///
/// Stdin EOF closes the child's stdin, so stdin-driven children like
/// `cat` exit on their own. Standard output and error ride separate
/// pipes: diagnostics must never pollute the byte stream.
///
/// Environment is exactly the script environment like `RUN`:
/// block-scoped `ENV` reaches the child; host names arrive only through
/// `INHERIT_ENV`. The working directory comes from the script.
///
/// Windows joining follows MSVCRT rules, so CRT programs parse back
/// exactly `argv`. `cmd /c` is the exception (its tail is a command,
/// not `argv`): route command text via `ENV SSH_COMMAND="..."` with
/// `["cmd", "/c", "%SSH_COMMAND%"]` instead.
#[oxdock_func(
    returns = TypeTag::Int,
    summary = "Run a command with piped stdio into explicit pipes."
)]
#[example(
    name = "run with piped stdio",
    code = r###"
    IMPORT [STD, SSH]
    INHERIT_ENV [PATH]
    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-run", {username: "u", password: "p"})
    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
    LET $cin: PIPE
    LET $cout: PIPE
    LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("doc-ssh-run", "u", "p", $cin, $cout) }
    WITH_IO [stdout=$cin] ECHO "client-hello"
    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d

    # The client task only proved the session live: cancel it before the
    # run, so no two pumps share the session.
    CANCEL $c
    LET $pin: PIPE
    LET $pout: PIPE
    LET $perr: PIPE
    LET $argv: LIST<STRING> = ["sh", "-c", "echo run-hi"]
    [family:windows] {
        $argv = ["cmd", "/c", "echo run-hi"]
    }
    LET $t: HANDLE<INT> = ASYNC { RETURN SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
    LET $code: INT = AWAIT $t
    ASSERT_EQ $code 0
    ASSERT_CONTAINS $pout "run-hi"
    SSH_CLOSE($m.server)
    "###
)]
fn ssh_run<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Session handle from `SSH_DEQUEUE`.
    session: SshSessionTag,
    /// Program and arguments to run.
    argv: Vec<String>,
    /// Pipe carrying bytes consumed by the child on stdin.
    in_pipe: PipeHandle,
    /// Pipe carrying bytes produced by the child on stdout.
    out_pipe: PipeHandle,
    /// Pipe carrying bytes produced by the child on stderr.
    err_pipe: PipeHandle,
) -> Result<Value> {
    if !cx.is_async_task() {
        return Err(anyhow::Error::from(ssh_diag::run_requires_async()));
    }
    let in_pipe = Value::pipe_handle(in_pipe);
    let out_pipe = Value::pipe_handle(out_pipe);
    let err_pipe = Value::pipe_handle(err_pipe);
    // Best effort: an unpumped session has no reader. Owned clone:
    // the reaper runs detached, so the callback must be `'static`.
    let session_report = session.clone();
    let report = move |code: u32| {
        let _ = session_report.send_exit_status(code);
    };
    let code = crate::run::pump_run_session(
        cx,
        &argv,
        &in_pipe,
        &out_pipe,
        &err_pipe,
        Some(std::sync::Arc::new(report)),
    )?;
    Ok(Value::int(code))
}

/// Run one argv vector on a remote host over SSH and collect the
/// result. Stateless by design: every call carries its target,
/// credentials, and argv, holds no session, and returns one MAP with
/// `exit`, `stdout`, `stderr`, `truncated`, and `timed_out`. A retry
/// after a dropped channel repeats the same bytes, so idempotent
/// commands make retries boring.
///
/// The argv never becomes a shell string in script hands: it joins
/// once here through `shell_words::join`, the same vetted
/// implementation behind `SHELL_SPLIT_ARGS`/`SHELL_JOIN_ARGS` and the
/// remote plugins. Quoting `$HOME`, backticks, and redirects arrive as
/// literal arguments because no layer between the caller and this join
/// re-parses them.
///
/// Output caps apply while reading: past `max_bytes` per stream the
/// buffers stop growing but the drain continues, so a flood still
/// learns its exit status and reports `truncated`. A timeout kills
/// the wait and returns whatever arrived with `timed_out`. `exit` is
/// -1 when the server never sent a status.
#[oxdock_func(returns = TypeTag::Map, summary = "Run argv on a remote host over SSH and collect the result.")]
#[example(
    name = "exec collects remote output",
    code = r###"
    # The server side answers exec with a local run: dequeue the
    # session, split the joined command back into argv, run it, and
    # pump the child output into the channel. The exit status rides
    # the wire through the session report.
    IMPORT [STD, SSH]
    INHERIT_ENV [PATH]
    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exec", {username: "u", password: "p"})
    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
    LET $runner: HANDLE<VOID> = ASYNC {
        LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
        LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS($sess.command)
        LET $wire: PIPE
        LET $drain: PIPE
        LET $pump: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_PUMP_CHANNEL($sess.session, $wire, $drain) }
        LET $pin: PIPE
        LET $pout: PIPE
        LET $perr: PIPE
        LET $run: HANDLE<INT> = ASYNC { RETURN SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
        LET $n: INT = SSH_PUMP($pout, $wire)
        LET $code: INT = AWAIT $run
        LET $pDone: MAP<ANY> = AWAIT $pump
        ASSERT_EQ $code 0
    }

    # One call, one MAP: argv in, collected streams out.
    [family:unix] {
        LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["echo", "exec-hi"], {})
        ASSERT_EQ $res.timed_out false
        ASSERT_EQ $res.exit 0
        ASSERT_CONTAINS $res.stdout "exec-hi"
    }
    [family:windows] {
        LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["cmd", "/c", "echo exec-hi"], {})
        ASSERT_EQ $res.timed_out false
        ASSERT_EQ $res.exit 0
        ASSERT_CONTAINS $res.stdout "exec-hi"
    }
    AWAIT $runner
    SSH_CLOSE($m.server)
    "###
)]
fn ssh_exec<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Dial target: a service name resolved through runner mappings.
    target: String,
    /// Inner credentials for the SSH session.
    username: String,
    /// Inner credentials for the SSH session.
    password: String,
    /// Program and arguments to run remotely; joined once, by the
    /// plugin, with POSIX shell quoting.
    argv: Vec<String>,
    /// `timeout` DURATION|STRING (default 60s) and `max_bytes` INT
    /// (default 8 MiB per stream).
    #[options("timeout?: DURATION|STRING", "max_bytes?: INT")]
    options: BTreeMap<String, Value>,
) -> Result<Value> {
    if argv.is_empty() {
        return Err(anyhow::Error::from(ssh_diag::exec_needs_program()));
    }
    if username.is_empty() {
        return Err(anyhow::Error::from(ssh_diag::exec_username_empty()));
    }
    let registry = cx
        .module_state::<EndpointRegistry>(MODULE_SSH)
        .expect("SSH module registers its endpoint registry as module state");
    if registry.is_offline() {
        return Err(anyhow::Error::from(ssh_diag::exec_offline()));
    }
    // Symbolic only: physical shapes already failed in the parser.
    let endpoint = parse_virtual_endpoint(&target, FUNC_EXEC)?;
    let key = EndpointKey::tcp(endpoint);
    let addr = match resolve_service_target(
        &registry,
        &key,
        FUNC_EXEC,
        SocketRequirement::SocketRequired,
    )? {
        ServiceTarget::Tcp(addr) => addr,
        // Unreachable: the shared resolver already bailed; same text.
        ServiceTarget::Memory => {
            return Err(anyhow::Error::from(no_cli_mapping(
                FUNC_EXEC,
                &key.endpoint,
            )));
        }
    };
    let timeout = match options.get(OPT_TIMEOUT) {
        None => crate::runtime::DEFAULT_EXEC_TIMEOUT,
        Some(value) => {
            // `check_options` verified `DURATION|STRING`; narrow directly.
            let timeout = if let Some(duration) = value.as_duration() {
                duration
            } else {
                let text = value
                    .as_str()
                    .expect("check_options verified DURATION|STRING");
                oxdock_parser::command::parse_duration(text).map_err(|e| {
                    ssh_diag::option_must_be_duration(FUNC_EXEC, OPT_TIMEOUT, text, e)
                })?
            };
            if timeout.is_zero() {
                return Err(anyhow::Error::from(ssh_diag::exec_option_must_be_positive(
                    OPT_TIMEOUT,
                )));
            }
            timeout
        }
    };
    let max_bytes = match options.get(OPT_MAX_BYTES) {
        None => crate::runtime::DEFAULT_EXEC_MAX_BYTES,
        Some(value) => {
            let bytes = value.as_i64().expect("check_options verified INT");
            if bytes <= 0 {
                return Err(anyhow::Error::from(ssh_diag::exec_option_must_be_positive(
                    OPT_MAX_BYTES,
                )));
            }
            bytes as usize
        }
    };
    // The single shell encoding in the pipeline: argv becomes one
    // string here, and only here.
    let command = shell_words::join(&argv).into_bytes();
    let runtime = connect_runtime()?;
    let outcome = runtime
        .block_on(crate::runtime::run_remote_exec(
            &addr, &username, &password, command, timeout, max_bytes,
        ))
        .map_err(ssh_diag::exec_failed)?;
    let mut map = BTreeMap::new();
    map.insert(
        FIELD_EXIT.to_string(),
        Value::int(outcome.exit.unwrap_or(-1)),
    );
    map.insert(
        "stdout".to_string(),
        Value::string(String::from_utf8_lossy(&outcome.stdout).into_owned()),
    );
    map.insert(
        "stderr".to_string(),
        Value::string(String::from_utf8_lossy(&outcome.stderr).into_owned()),
    );
    map.insert(FIELD_TRUNCATED.to_string(), Value::bool(outcome.truncated));
    map.insert(FIELD_TIMED_OUT.to_string(), Value::bool(outcome.timed_out));
    Ok(Value::map(map))
}

/// Mint a random server password (256 bits, hex).
///
/// Each call draws fresh OS-RNG key material and renders 64
/// lowercase hex chars, so committed scripts carry no usable
/// credential: mint at runtime, hand the value to both sides, drop
/// it after. Pure (no step context), so it runs anywhere a STRING
/// binds, including option maps and placeholders.
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "mint and serve",
    code = r###"
    IMPORT [STD, SSH]

    # Fresh draws mint 64 hex chars with no committed secret.
    LET $pass: STRING = SSH_GENERATE_PASSWORD()
    LET $len: INT = LEN($pass)
    ASSERT_EQ $len 64

    # The minted value serves directly as a server password.
    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-gen-pass", {username: "u", password: $pass})
    SSH_CLOSE($m.server)
    "###
)]
fn ssh_generate_password() -> Result<Value> {
    Ok(Value::string(crate::generate_password()))
}

/// Field table backing the `SSH_SERVE_INFO` schema and return tag.
fn serve_result_fields() -> Arc<[Field]> {
    Arc::from(vec![
        Field {
            name: FIELD_SERVER.to_string(),
            ty: TypeTag::Custom(SshServerTag::descriptor()),
            docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: FIELD_ADDR.to_string(),
            ty: TypeTag::String,
            docs: "Bound socket address (`ip:port`) of the server.",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: FIELD_USERNAME.to_string(),
            ty: TypeTag::String,
            docs: "Configured username.",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: FIELD_PASSWORD.to_string(),
            ty: TypeTag::String,
            docs: "Configured password.",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: FIELD_VIRTUAL.to_string(),
            ty: TypeTag::String,
            docs: "Virtual endpoint echo of the claimed slot.",
            optional: false,
            default: None,

            alias: None,
        },
    ])
}

/// Field table backing the `SSH_DEQUEUE_INFO` schema and return tag.
fn dequeue_result_fields() -> Arc<[Field]> {
    Arc::from(vec![
        Field {
            name: FIELD_SESSION.to_string(),
            ty: TypeTag::Custom(SshSessionTag::descriptor()),
            docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: FIELD_COMMAND.to_string(),
            ty: TypeTag::String,
            docs: "Executed command, empty for shells.",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: FIELD_USERNAME.to_string(),
            ty: TypeTag::String,
            docs: "Authenticated username, empty when unset.",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: FIELD_ADDR.to_string(),
            ty: TypeTag::String,
            docs: "Peer address, empty when unset.",
            optional: false,
            default: None,

            alias: None,
        },
    ])
}

/// The `SSH` host module: virtual-endpoint server plus client, bridged
/// to DSL pipes. Generic over the process manager like every host module.
pub fn module_with<P: ProcessManager>() -> HostModule<P> {
    module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
}

/// The `SSH` host module resolving through `registry`: the registry
/// travels as module state (`HostModule::with_state`) for bodies to
/// fetch from `cx`, so every entry stays `#[oxdock_func]`. Everything
/// else reaches the same registry through its `SSH_SERVER` handle. A
/// pre-run service check rides along: every service the steps name must
/// be fully bound before execution starts.
pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
    let check = registry.pre_run_check(MODULE_SSH);
    HostModule {
        name: MODULE_SSH.to_string(),
        funcs: vec![
            SshServe::registration(),
            SshAccept::registration(),
            SshDequeue::registration(),
            SshPumpChannel::registration(),
            SshSendExitStatus::registration(),
            SshClose::registration(),
            SshConnect::registration(),
            SshExec::registration(),
            SshPump::registration(),
            SshPtyRun::registration(),
            SshRun::registration(),
            SshGeneratePassword::registration(),
        ],
        types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
        record_schemas: vec![
            RecordSchema {
                name: "SSH_SERVE_INFO",
                fields: serve_result_fields(),
            },
            RecordSchema {
                name: "SSH_DEQUEUE_INFO",
                fields: dequeue_result_fields(),
            },
        ],
        states: Vec::new(),
    }
    .with_state(registry)
    .with_state(Arc::new(check))
}