better-dsh 0.3.1 → 0.3.2-d
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -5
- package/cordis.patch.yml +14 -9
- package/docs/20_specs/kernel-provisioning/spec.md +2 -0
- package/docs/remote-tools.md +36 -14
- package/docs/specs/kernel-provisioning/spec.md +12 -40
- package/docs/specs/omp-python-repl-port/runtime-guide.md +3 -1
- package/docs/specs/omp-python-repl-port/spec.md +7 -0
- package/docs/specs/remote-pty-label/spec.md +2 -0
- package/docs/specs/remote-tool-enhancement/spec.md +2 -0
- package/lib/BrowserWebSocketTransport.js +4 -0
- package/lib/{BrowserWebSocketTransport-wm99h94r.js → BrowserWebSocketTransport2.js} +1 -1
- package/lib/LaunchOptions.js +4 -0
- package/lib/{LaunchOptions-5eg7E0ye.js → LaunchOptions2.js} +1 -1
- package/lib/{NodeWebSocketTransport-D9ysYGLM.js → NodeWebSocketTransport.js} +2 -2
- package/lib/NodeWebSocketTransport2.js +4 -0
- package/lib/{bidi-CwabFH07.js → bidi.js} +4 -4
- package/lib/client/index.js +59 -6
- package/lib/compaction/index.d.ts +1 -1
- package/lib/compaction/index.js +1 -1
- package/lib/failover/index.d.ts +1 -1
- package/lib/failover/index.js +1 -1
- package/lib/fs-aware/sandbox-plugin.js +1 -1
- package/lib/{index-browser-B-9jm12n.js → index-browser.js} +6 -6
- package/lib/index.d.ts +2 -12
- package/lib/index.js +58 -62
- package/lib/kernel-env.d.ts +5 -15
- package/lib/kernel-env.js +2 -2
- package/lib/kernel-env2.js +76 -0
- package/lib/{lsp-server-registry-BcdkHROD.js → lsp-server-registry2.js} +1 -1
- package/lib/{main-BeCgUd20.js → main.js} +1 -1
- package/lib/{main-Dv_UQqG2.js → main2.js} +1 -1
- package/lib/mobile/plugin.d.ts +2 -2
- package/lib/mobile/plugin.js +2 -2
- package/lib/{puppeteer-core-Dnd7eqel.js → puppeteer-core.js} +9 -9
- package/lib/py-sdk.js +1 -1
- package/lib/remote/helper-bin/MANIFEST.json +35 -0
- package/lib/remote/helper-bin/aarch64-apple-darwin/BUILT-VER +1 -0
- package/lib/remote/helper-bin/aarch64-apple-darwin/superd-run +0 -0
- package/lib/remote/helper-bin/aarch64-unknown-linux-musl/BUILT-VER +1 -0
- package/lib/remote/helper-bin/aarch64-unknown-linux-musl/superd-run +0 -0
- package/lib/remote/helper-bin/x86_64-pc-windows-gnu/BUILT-VER +1 -0
- package/lib/remote/helper-bin/x86_64-pc-windows-gnu/superd-run.exe +0 -0
- package/lib/remote/helper-bin/x86_64-unknown-linux-musl/BUILT-VER +1 -0
- package/lib/remote/helper-bin/x86_64-unknown-linux-musl/superd-run +0 -0
- package/lib/remote/hub-pty-pump.mjs +97 -0
- package/lib/remote/plugin.d.ts +519 -197
- package/lib/remote/plugin.js +2513 -751
- package/lib/url-schemes/index.js +12 -12
- package/lib/{wasm_bg-CNXhHjVg.js → wasm_bg.js} +1 -1
- package/lib/web-password.js +1 -1
- package/lib/web-trust.d.ts +1 -1
- package/lib/web-trust.js +2 -2
- package/lib/{web-trust-CwZrTBcl.d.ts → web-trust2.d.ts} +11 -11
- package/lib/{web-trust-D6gJpUMf.js → web-trust2.js} +20 -8
- package/lib/welcome-notice.d.ts +3 -3
- package/lib/welcome-notice.js +1 -1
- package/package.json +4 -4
- package/scripts/kernel-check.mjs +5 -0
- package/lib/BrowserWebSocketTransport-D1aFReu_.js +0 -4
- package/lib/LaunchOptions-DxQQ0s-A.js +0 -4
- package/lib/NodeWebSocketTransport-BRLjmu2R.js +0 -4
- package/lib/kernel-env-BOF0fNHn.js +0 -91
- package/scripts/kernel-provision.mjs +0 -5
- /package/lib/{chunk-DQxbwPpZ.js → chunk.js} +0 -0
- /package/lib/{index-DTDXUe6m.d.ts → index2.d.ts} +0 -0
- /package/lib/{lib-C8_jXvwA.js → lib.js} +0 -0
- /package/lib/{lsp-server-registry-D4VLs1Sm.js → lsp-server-registry.js} +0 -0
- /package/lib/{native-capture-BEByDXYM.js → native-capture.js} +0 -0
- /package/lib/{py-sdk-D7klhpWb.js → py-sdk2.js} +0 -0
- /package/lib/{util-BHL_dfV_.js → util.js} +0 -0
- /package/lib/{web-tree-sitter-CPrPD4J2.js → web-tree-sitter.js} +0 -0
- /package/lib/{wrap-0VA0uFx8.js → wrap.js} +0 -0
package/lib/remote/plugin.js
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
|
-
import { t as Schema } from "../lib
|
|
1
|
+
import { t as Schema } from "../lib.js";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
2
3
|
import { Context } from "@deepseek-ai/cordis";
|
|
3
4
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
4
|
-
import { constants, createReadStream, createWriteStream, mkdirSync, statSync } from "node:fs";
|
|
5
|
+
import { constants, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
|
|
5
6
|
import { dirname, isAbsolute, join, posix, resolve } from "node:path";
|
|
6
7
|
import { spawn } from "node:child_process";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { homedir, tmpdir } from "node:os";
|
|
7
10
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
8
|
-
import { chmod, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
|
|
11
|
+
import { chmod, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
|
|
9
12
|
import { pipeline } from "node:stream/promises";
|
|
10
13
|
import { Readable } from "node:stream";
|
|
11
|
-
import { homedir, tmpdir } from "node:os";
|
|
12
14
|
import { createConnection, createServer } from "node:net";
|
|
15
|
+
import { Buffer as Buffer$1 } from "node:buffer";
|
|
13
16
|
|
|
14
17
|
//#region src/remote/archive.ts
|
|
15
18
|
const FILE_FRAME_BYTES = 64 * 1024;
|
|
@@ -317,17 +320,18 @@ async function copyTree(request, source, destination, signal, scratchRoot = join
|
|
|
317
320
|
signal.throwIfAborted();
|
|
318
321
|
if (request.argv !== void 0 || request.pullArgv !== void 0 || request.pushArgv !== void 0) throw new Error("copy: argv/pullArgv/pushArgv are native CLI options; the Hub/local staged lane does not accept CLI options");
|
|
319
322
|
await mkdir(scratchRoot, { recursive: true });
|
|
320
|
-
signal.throwIfAborted();
|
|
321
|
-
const scratch = await mkdtemp(join(scratchRoot, "remote-copy-")), payload = join(scratch, "payload.bin");
|
|
322
323
|
const receipt = {
|
|
323
324
|
action: "copy",
|
|
325
|
+
route: "hub-staged",
|
|
324
326
|
src: request.src,
|
|
325
327
|
dst: request.dst,
|
|
326
|
-
|
|
328
|
+
ok: false,
|
|
329
|
+
verification: "not-applicable",
|
|
327
330
|
bytes: 0,
|
|
328
331
|
entries: 0,
|
|
329
332
|
scope: "transferred entries"
|
|
330
333
|
};
|
|
334
|
+
const scratch = await mkdtemp(join(scratchRoot, "remote-copy-")), payload = join(scratch, "payload.bin");
|
|
331
335
|
try {
|
|
332
336
|
await pipeline(await source.endpoint.exportTree(source.path, signal), createWriteStream(payload, {
|
|
333
337
|
flags: "wx",
|
|
@@ -351,24 +355,91 @@ async function copyTree(request, source, destination, signal, scratchRoot = join
|
|
|
351
355
|
const dest = await destination.endpoint.digest(destination.path, signal, selection);
|
|
352
356
|
receipt.destinationDigest = dest.sha256;
|
|
353
357
|
if (dest.sha256 !== receipt.sourceDigest) throw new Error("destination digest mismatch");
|
|
354
|
-
receipt.
|
|
358
|
+
receipt.verification = "sha256";
|
|
355
359
|
}
|
|
356
360
|
signal.throwIfAborted();
|
|
357
361
|
await rm(scratch, {
|
|
358
362
|
recursive: true,
|
|
359
363
|
force: true
|
|
360
364
|
});
|
|
365
|
+
receipt.ok = true;
|
|
361
366
|
return receipt;
|
|
362
367
|
} catch (error) {
|
|
368
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
369
|
+
const reason = signal.aborted ? "aborted" : /mismatch/i.test(message) ? "digest-mismatch" : "staging-error";
|
|
363
370
|
throw new CopyError({
|
|
364
371
|
...receipt,
|
|
365
|
-
|
|
372
|
+
ok: false,
|
|
373
|
+
reason,
|
|
366
374
|
scratch,
|
|
367
|
-
error:
|
|
375
|
+
error: message
|
|
368
376
|
});
|
|
369
377
|
}
|
|
370
378
|
}
|
|
371
379
|
|
|
380
|
+
//#endregion
|
|
381
|
+
//#region src/remote/ssh-argv.ts
|
|
382
|
+
/**
|
|
383
|
+
* ONE identity-assembly policy for every SSH-speaking lane (user close-out
|
|
384
|
+
* ruling 2026-10-17: "four builders necessarily mean four identity
|
|
385
|
+
* semantics" — the structural root of F1).
|
|
386
|
+
*
|
|
387
|
+
* Assembly: explicit connection fields (byossh registrations; caller options
|
|
388
|
+
* may override later by the CLI's own last-option-wins) in ONE order —
|
|
389
|
+
* user, port, key, proxyJump — spoken in the target CLI's dialect.
|
|
390
|
+
*
|
|
391
|
+
* Resolution: config-side identity (aliases, config-only IdentityFile paths)
|
|
392
|
+
* is read from the ORIGIN's own ssh config natively by every lane. The single
|
|
393
|
+
* exception is the scp -3 temp config (ssh -F sees no user config), where
|
|
394
|
+
* tempSshConfig inlines the `ssh -G`-resolved fields — paths only, never key
|
|
395
|
+
* material (F1, 2026-10-14). That policy lives beside this builder in
|
|
396
|
+
* native-copy.ts and must stay the only such inline site.
|
|
397
|
+
*
|
|
398
|
+
* Former duplicate builders now reduced here: sshArgv (execution/probes),
|
|
399
|
+
* identityArgv (scp routes), rsyncRsh (RSYNC_RSH wiring), relaySsh
|
|
400
|
+
* (dual-SSH relay). Behavior is byte-identical to each former site.
|
|
401
|
+
*/
|
|
402
|
+
/** Identity options ONLY for one connection, in the target CLI's dialect:
|
|
403
|
+
* user, port, key, proxyJump — conditional, one order, NO base flags (each
|
|
404
|
+
* lane's dialect base — BatchMode, -T, hardening — stays at its call site).
|
|
405
|
+
* scp carries the user inside its user@host operand, so the scp dialect
|
|
406
|
+
* never emits -l; its port flag is -P. */
|
|
407
|
+
function sshIdentityArgv(connection, dialect) {
|
|
408
|
+
const args = [];
|
|
409
|
+
if (dialect === "ssh" && connection.user !== void 0) args.push("-l", connection.user);
|
|
410
|
+
if (connection.port !== void 0) args.push(dialect === "scp" ? "-P" : "-p", String(connection.port));
|
|
411
|
+
if (connection.key !== void 0) args.push("-i", connection.key);
|
|
412
|
+
if (connection.proxyJump !== void 0) args.push("-J", connection.proxyJump);
|
|
413
|
+
return args;
|
|
414
|
+
}
|
|
415
|
+
/** Full ssh invocation around the shared identity core. base and extra are
|
|
416
|
+
* trusted internal argv (dialect flags incl. BatchMode, forwarding options)
|
|
417
|
+
* — never a model-provided shell string. */
|
|
418
|
+
/** SSH keepalive for PERSISTENT lanes (pty ruling 2026-10-19): client-owned,
|
|
419
|
+
* fixed cadence — OpenSSH has NO protocol-default keepalive unit (default is
|
|
420
|
+
* disabled), so we set our own in our own argv. Control-channel probes never
|
|
421
|
+
* touch the PTY byte stream; NAT/WiFi idle expiry (~5min) would otherwise
|
|
422
|
+
* silently kill an idle-but-wanted session inside the 15min TTL. CountMax=2
|
|
423
|
+
* gives ~6min honest dead-detection instead of a hang on next write. */
|
|
424
|
+
const SSH_PERSISTENT_KEEPALIVE = [
|
|
425
|
+
"-o",
|
|
426
|
+
"ServerAliveInterval=180",
|
|
427
|
+
"-o",
|
|
428
|
+
"ServerAliveCountMax=2"
|
|
429
|
+
];
|
|
430
|
+
function sshCommandArgv(connection, base, extra, command) {
|
|
431
|
+
const args = [
|
|
432
|
+
"ssh",
|
|
433
|
+
...base,
|
|
434
|
+
...sshIdentityArgv(connection, "ssh"),
|
|
435
|
+
...extra,
|
|
436
|
+
"--",
|
|
437
|
+
connection.host
|
|
438
|
+
];
|
|
439
|
+
if (command !== void 0) args.push(command);
|
|
440
|
+
return args;
|
|
441
|
+
}
|
|
442
|
+
|
|
372
443
|
//#endregion
|
|
373
444
|
//#region src/remote/output-ring.ts
|
|
374
445
|
const continuation = (byte) => (byte & 192) === 128;
|
|
@@ -674,15 +745,17 @@ function scpSpec(connection, path$1) {
|
|
|
674
745
|
const host = connection.host.includes(":") ? `[${connection.host}]` : connection.host;
|
|
675
746
|
return `${connection.user !== void 0 ? `${connection.user}@${host}` : host}:${path$1}`;
|
|
676
747
|
}
|
|
677
|
-
/** Connection identity as scp options
|
|
678
|
-
*
|
|
679
|
-
* precedence (last option wins).
|
|
748
|
+
/** Connection identity as scp options, placed BEFORE caller argv so an
|
|
749
|
+
* explicit caller -F/-i/-P/-J overrides the registered identity by scp's own
|
|
750
|
+
* precedence (last option wins). Assembly itself lives in ssh-argv.ts
|
|
751
|
+
* (the ONE identity policy — 2026-10-17 ruling); only the scp dialect
|
|
752
|
+
* placement rule is local. */
|
|
680
753
|
function identityArgv(connection) {
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
754
|
+
return [
|
|
755
|
+
"-o",
|
|
756
|
+
"BatchMode=yes",
|
|
757
|
+
...sshIdentityArgv(connection, "scp")
|
|
758
|
+
];
|
|
686
759
|
}
|
|
687
760
|
function sshEndpoint(plan) {
|
|
688
761
|
if (plan.kind !== "ssh") throw new Error("remote: native copy endpoint is not an SSH target");
|
|
@@ -721,24 +794,30 @@ async function nativeCopy(request, endpoints, signal, options = {}) {
|
|
|
721
794
|
stdout: [],
|
|
722
795
|
stderr: [],
|
|
723
796
|
outputTruncated: false,
|
|
724
|
-
|
|
797
|
+
verification: "native-exit-only",
|
|
798
|
+
ok: true,
|
|
725
799
|
cleanup: "none-required"
|
|
726
800
|
};
|
|
727
|
-
const finish = (route, argvs, results) => {
|
|
801
|
+
const finish = (route, argvs, results, internal = []) => {
|
|
728
802
|
receipt.route = route;
|
|
729
|
-
receipt.argv = argvs;
|
|
803
|
+
receipt.argv = argvs.map((argv) => argv.map((token) => internal.find(([secret]) => secret === token)?.[1] ?? token));
|
|
730
804
|
receipt.exits = results.map((result) => result.exit);
|
|
731
805
|
receipt.stdout = results.map((result) => result.stdout);
|
|
732
806
|
receipt.stderr = results.map((result) => result.stderr);
|
|
733
807
|
receipt.outputTruncated = results.some((result) => result.outputTruncated);
|
|
808
|
+
receipt.ok = !signal.aborted && receipt.exits.every((exit) => exit === 0);
|
|
809
|
+
if (!receipt.ok) receipt.reason = signal.aborted ? "aborted" : "non-zero-exit";
|
|
734
810
|
return receipt;
|
|
735
811
|
};
|
|
812
|
+
if (request.mkdir !== false) await ensureDestinationDir(endpoints.dst, signal, options.execArgvFor, wrap, receipt);
|
|
813
|
+
else receipt.created = "n-a";
|
|
736
814
|
if (s === "local" && t === "ssh") {
|
|
737
815
|
rejectRemoteToRemoteScp(oneShot);
|
|
738
816
|
const connection = sshEndpoint(endpoints.dst.plan).connection;
|
|
739
817
|
const argv = [
|
|
740
818
|
"scp",
|
|
741
819
|
...identityArgv(connection),
|
|
820
|
+
...await recursiveFlag(endpoints.src.path, oneShot, "-r"),
|
|
742
821
|
...oneShot,
|
|
743
822
|
endpoints.src.path,
|
|
744
823
|
scpSpec(connection, endpoints.dst.path)
|
|
@@ -771,7 +850,7 @@ async function nativeCopy(request, endpoints, signal, options = {}) {
|
|
|
771
850
|
dstSpec = scpSpec(destination, endpoints.dst.path);
|
|
772
851
|
extra = identityArgv(source);
|
|
773
852
|
} else {
|
|
774
|
-
config = await tempSshConfig(source, destination);
|
|
853
|
+
config = await tempSshConfig(source, destination, runNative);
|
|
775
854
|
extra = ["-F", config.path];
|
|
776
855
|
srcSpec = `superd-scp3-source:${endpoints.src.path}`;
|
|
777
856
|
dstSpec = `superd-scp3-destination:${endpoints.dst.path}`;
|
|
@@ -784,7 +863,7 @@ async function nativeCopy(request, endpoints, signal, options = {}) {
|
|
|
784
863
|
srcSpec,
|
|
785
864
|
dstSpec
|
|
786
865
|
];
|
|
787
|
-
return finish("scp
|
|
866
|
+
return finish("scp-3", [argv], [await runNative(wrap(argv), signal)], config !== void 0 ? [[config.path, "<temp-ssh-config>"]] : []);
|
|
788
867
|
} catch (error) {
|
|
789
868
|
if (signal.aborted) unknown = true;
|
|
790
869
|
throw error;
|
|
@@ -803,7 +882,9 @@ async function nativeCopy(request, endpoints, signal, options = {}) {
|
|
|
803
882
|
endpoints.src.path,
|
|
804
883
|
`${containerOf(endpoints.dst.plan)}:${endpoints.dst.path}`
|
|
805
884
|
];
|
|
806
|
-
|
|
885
|
+
const result = await runNative(wrap(argv), signal);
|
|
886
|
+
withSymlinkHint(result);
|
|
887
|
+
return finish("docker-cp", [argv], [result]);
|
|
807
888
|
}
|
|
808
889
|
if (s === "docker" && t === "local") {
|
|
809
890
|
const argv = [
|
|
@@ -813,18 +894,21 @@ async function nativeCopy(request, endpoints, signal, options = {}) {
|
|
|
813
894
|
`${containerOf(endpoints.src.plan)}:${endpoints.src.path}`,
|
|
814
895
|
endpoints.dst.path
|
|
815
896
|
];
|
|
816
|
-
|
|
897
|
+
const result = await runNative(wrap(argv), signal);
|
|
898
|
+
withSymlinkHint(result);
|
|
899
|
+
return finish("docker-cp", [argv], [result]);
|
|
817
900
|
}
|
|
818
901
|
if (s === "local" && t === "incus") {
|
|
819
902
|
const argv = [
|
|
820
903
|
"incus",
|
|
821
904
|
"file",
|
|
822
905
|
"push",
|
|
906
|
+
...await recursiveFlag(endpoints.src.path, oneShot, "-r"),
|
|
823
907
|
...oneShot,
|
|
824
908
|
endpoints.src.path,
|
|
825
909
|
`${containerOf(endpoints.dst.plan)}${endpoints.dst.path}`
|
|
826
910
|
];
|
|
827
|
-
return finish("incus
|
|
911
|
+
return finish("incus-file-push", [argv], [await runNative(wrap(argv), signal)]);
|
|
828
912
|
}
|
|
829
913
|
if (s === "incus" && t === "local") {
|
|
830
914
|
const argv = [
|
|
@@ -835,7 +919,7 @@ async function nativeCopy(request, endpoints, signal, options = {}) {
|
|
|
835
919
|
`${containerOf(endpoints.src.plan)}${endpoints.src.path}`,
|
|
836
920
|
endpoints.dst.path
|
|
837
921
|
];
|
|
838
|
-
return finish("incus
|
|
922
|
+
return finish("incus-file-pull", [argv], [await runNative(wrap(argv), signal)]);
|
|
839
923
|
}
|
|
840
924
|
if (s === "local" || t === "local") throw new Error("remote: this endpoint pair is a single native command route; pullArgv/pushArgv apply to cross-endpoint pairs only");
|
|
841
925
|
const pullOptions = request.pullArgv !== void 0 ? pull : oneShot;
|
|
@@ -848,9 +932,12 @@ async function nativeCopy(request, endpoints, signal, options = {}) {
|
|
|
848
932
|
const pullArgv = segmentArgv(endpoints.src.plan, endpoints.src.path, staged, pullOptions, "pull");
|
|
849
933
|
const pushArgv = segmentArgv(endpoints.dst.plan, endpoints.dst.path, staged, pushOptions, "push");
|
|
850
934
|
const first = await runNative(wrap(pullArgv), signal);
|
|
851
|
-
if (first.exit !== 0)
|
|
935
|
+
if (first.exit !== 0) {
|
|
936
|
+
receipt.note = "push not started: pull failed";
|
|
937
|
+
return finish("staged-pull-push", [pullArgv], [first], [[staged, "<staging>"]]);
|
|
938
|
+
}
|
|
852
939
|
const second = await runNative(wrap(pushArgv), signal);
|
|
853
|
-
return finish("
|
|
940
|
+
return finish("staged-pull-push", [pullArgv, pushArgv], [first, second], [[staged, "<staging>"]]);
|
|
854
941
|
} finally {
|
|
855
942
|
receipt.cleanup = await rm(scratch, {
|
|
856
943
|
recursive: true,
|
|
@@ -911,40 +998,162 @@ function segmentArgv(plan, remote, staged, opts, leg) {
|
|
|
911
998
|
spec
|
|
912
999
|
];
|
|
913
1000
|
}
|
|
1001
|
+
/** D3 mkdir pre-hop: ensure the destination's PARENT directory exists before
|
|
1002
|
+
* the transfer (never the operand itself — see parent-only note below).
|
|
1003
|
+
* transfer. Local dst is node-side; remote dst runs ONE exec `mkdir -p` probe
|
|
1004
|
+
* whose stdout discloses created-vs-existed. Best-effort by contract: any
|
|
1005
|
+
* failure records created:'n-a' + note and lets the copy proceed so the native
|
|
1006
|
+
* CLI surfaces the real error (and stopped-container docker cp keeps working). */
|
|
1007
|
+
async function ensureDestinationDir(dst, signal, execArgvFor, wrap, receipt) {
|
|
1008
|
+
const dir = dirname(dst.path);
|
|
1009
|
+
if (dir === "/" || dir === ".") {
|
|
1010
|
+
receipt.created = false;
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
if (dst.plan.kind === "local") {
|
|
1014
|
+
try {
|
|
1015
|
+
if (existsSync(dir)) {
|
|
1016
|
+
receipt.created = false;
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
mkdirSync(dir, { recursive: true });
|
|
1020
|
+
receipt.created = true;
|
|
1021
|
+
} catch (error) {
|
|
1022
|
+
receipt.created = "n-a";
|
|
1023
|
+
receipt.note = `mkdir pre-hop failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
1024
|
+
}
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
if (execArgvFor === void 0) {
|
|
1028
|
+
receipt.created = "n-a";
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
if (/[\r\n]/.test(dir)) {
|
|
1032
|
+
receipt.created = "n-a";
|
|
1033
|
+
receipt.note = "mkdir pre-hop skipped: newline-bearing destination path";
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
const quoted = `'${dir.replaceAll("'", "'\\\\''")}'`;
|
|
1037
|
+
const script = `if [ -d ${quoted} ]; then echo existed; else mkdir -p ${quoted} && echo created; fi`;
|
|
1038
|
+
try {
|
|
1039
|
+
const result = await runNative(wrap(execArgvFor(dst.plan, script)), signal);
|
|
1040
|
+
const word = result.stdout.trim().split("\n").pop();
|
|
1041
|
+
if (result.exit === 0 && word === "created") receipt.created = true;
|
|
1042
|
+
else if (result.exit === 0 && word === "existed") receipt.created = false;
|
|
1043
|
+
else {
|
|
1044
|
+
receipt.created = "n-a";
|
|
1045
|
+
const tail = result.stderr.trim().split("\n").filter((line) => line.length > 0).pop();
|
|
1046
|
+
receipt.note = `mkdir pre-hop unavailable (exit ${result.exit})${tail !== void 0 ? `: ${tail}` : ""}`;
|
|
1047
|
+
}
|
|
1048
|
+
} catch (error) {
|
|
1049
|
+
receipt.created = "n-a";
|
|
1050
|
+
receipt.note = `mkdir pre-hop failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
914
1053
|
/** Distinguishing identities for scp -3: an origin-only temp config maps two
|
|
915
1054
|
* synthetic aliases; keys are referenced in place, never copied to any remote. */
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
1055
|
+
/** D8 (2026-10-14 user adoption, third acceptance round): a LOCAL directory source gets
|
|
1056
|
+
* the route's recursive flag appended automatically — scp / incus file push refuse
|
|
1057
|
+
* directories without it. The appended flag lands in the executed argv, which the
|
|
1058
|
+
* receipt shows verbatim: disclosure by receipt, never silent. Remote sources stay
|
|
1059
|
+
* caller-explicit (we do not dial just to stat); an explicit caller flag wins. */
|
|
1060
|
+
async function recursiveFlag(localPath, callerArgv, flag) {
|
|
1061
|
+
if (callerArgv.includes(flag) || callerArgv.includes("--recursive")) return [];
|
|
1062
|
+
try {
|
|
1063
|
+
if ((await stat(localPath)).isDirectory()) return [flag];
|
|
1064
|
+
} catch {}
|
|
1065
|
+
return [];
|
|
1066
|
+
}
|
|
1067
|
+
/** docker cp follows symlinks only with -L; its native error ("invalid symlink")
|
|
1068
|
+
* names no remedy. Append the one-line hint on that failure path (F5, 2026-10-14). */
|
|
1069
|
+
function withSymlinkHint(result) {
|
|
1070
|
+
if (result.exit !== 0 && /invalid symlink/i.test(result.stderr)) result.stderr = `${result.stderr}\nhint: docker cp follows symlinks only with -L — pass argv:["-L"] (e.g. /etc/os-release is a symlink)`;
|
|
1071
|
+
}
|
|
1072
|
+
async function tempSshConfig(source, destination, runNative$1) {
|
|
1073
|
+
const resolvedSource = await resolveThroughOriginConfig(source, runNative$1);
|
|
1074
|
+
const resolvedDestination = await resolveThroughOriginConfig(destination, runNative$1);
|
|
1075
|
+
for (const { connection: c, identityFiles } of [resolvedSource, resolvedDestination]) {
|
|
1076
|
+
for (const [field, value] of [
|
|
1077
|
+
["host", c.host],
|
|
1078
|
+
["user", c.user],
|
|
1079
|
+
["key", c.key],
|
|
1080
|
+
["proxyJump", c.proxyJump]
|
|
1081
|
+
]) if (value !== void 0 && /[\r\n]/.test(value)) throw new Error(`remote: scp -3 temp config rejects newline in SSH ${field} (no config injection)`);
|
|
1082
|
+
for (const idFile of identityFiles) if (/[\r\n]/.test(idFile)) throw new Error("remote: scp -3 temp config rejects newline in resolved IdentityFile (no config injection)");
|
|
1083
|
+
}
|
|
923
1084
|
const dir = await mkdtemp(join(tmpdir(), "superd-scp3-"));
|
|
924
1085
|
const path$1 = join(dir, "config");
|
|
925
|
-
const block = (name$1, c) => {
|
|
1086
|
+
const block = (name$1, c, identityFiles) => {
|
|
926
1087
|
const lines = [`Host ${name$1}`, ` HostName ${c.host.replace(/^.*@/, "")}`];
|
|
927
1088
|
if (c.user !== void 0) lines.push(` User ${c.user}`);
|
|
928
1089
|
if (c.port !== void 0) lines.push(` Port ${String(c.port)}`);
|
|
929
|
-
|
|
1090
|
+
for (const idFile of [c.key !== void 0 ? [c.key] : [], identityFiles].flat()) lines.push(` IdentityFile ${idFile}`);
|
|
930
1091
|
if (c.proxyJump !== void 0) lines.push(` ProxyJump ${c.proxyJump}`);
|
|
931
1092
|
return lines.join("\n");
|
|
932
1093
|
};
|
|
933
|
-
await writeFile(path$1, `${block("superd-scp3-source",
|
|
1094
|
+
await writeFile(path$1, `${block("superd-scp3-source", resolvedSource.connection, resolvedSource.identityFiles)}\n${block("superd-scp3-destination", resolvedDestination.connection, resolvedDestination.identityFiles)}\n`, { mode: 384 });
|
|
934
1095
|
await chmod(path$1, 384);
|
|
935
1096
|
return {
|
|
936
1097
|
path: path$1,
|
|
937
1098
|
dir
|
|
938
1099
|
};
|
|
939
1100
|
}
|
|
1101
|
+
/** Effective fields for one connection per the origin's own ssh config (ssh -G,
|
|
1102
|
+
* prints resolved settings without dialing). Explicit fields win; empty/none
|
|
1103
|
+
* proxyjump is dropped. IdentityFile PATHS from the config are returned separately
|
|
1104
|
+
* for inlining into the temp config — a path is not key material and stays on the
|
|
1105
|
+
* origin (F1, 2026-10-14: dev4's only authorized key lived in config, not the agent;
|
|
1106
|
+
* dropping it made scp -3 fail with a bare Permission denied). */
|
|
1107
|
+
async function resolveThroughOriginConfig(c, runNative$1) {
|
|
1108
|
+
let probe;
|
|
1109
|
+
try {
|
|
1110
|
+
probe = await runNative$1([
|
|
1111
|
+
"ssh",
|
|
1112
|
+
"-G",
|
|
1113
|
+
c.host
|
|
1114
|
+
], new AbortController().signal);
|
|
1115
|
+
} catch {
|
|
1116
|
+
probe = void 0;
|
|
1117
|
+
}
|
|
1118
|
+
if (probe === void 0 || probe.exit !== 0) return {
|
|
1119
|
+
connection: c,
|
|
1120
|
+
identityFiles: []
|
|
1121
|
+
};
|
|
1122
|
+
const lines = probe.stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
|
|
1123
|
+
const pick = (key) => lines.find((line) => line.startsWith(`${key} `))?.slice(key.length + 1).trim() || void 0;
|
|
1124
|
+
const home = process.env.HOME ?? "";
|
|
1125
|
+
const compiledDefault = (path$1) => path$1 === "none" || [
|
|
1126
|
+
"id_rsa",
|
|
1127
|
+
"id_ecdsa",
|
|
1128
|
+
"id_ecdsa_sk",
|
|
1129
|
+
"id_ed25519",
|
|
1130
|
+
"id_ed25519_sk"
|
|
1131
|
+
].some((name$1) => path$1 === `~/.ssh/${name$1}` || home !== "" && path$1 === `${home}/.ssh/${name$1}`);
|
|
1132
|
+
const identityFiles = [...new Set(lines.filter((line) => line.startsWith("identityfile ")).map((line) => line.slice(13).trim()).filter((path$1) => path$1 !== "" && !compiledDefault(path$1)))];
|
|
1133
|
+
const host = (pick("hostname") ?? c.host).replace(/^.*@/, "");
|
|
1134
|
+
const user = c.user ?? pick("user");
|
|
1135
|
+
const portText = pick("port");
|
|
1136
|
+
const port = c.port ?? (portText !== void 0 && /^\d+$/.test(portText) ? Number(portText) : void 0);
|
|
1137
|
+
const proxyJumpRaw = c.proxyJump ?? pick("proxyjump");
|
|
1138
|
+
return {
|
|
1139
|
+
connection: {
|
|
1140
|
+
host,
|
|
1141
|
+
...user !== void 0 && user !== "" ? { user } : {},
|
|
1142
|
+
...port !== void 0 && Number.isInteger(port) && port > 0 ? { port } : {},
|
|
1143
|
+
...c.key !== void 0 ? { key: c.key } : {},
|
|
1144
|
+
...proxyJumpRaw !== void 0 && proxyJumpRaw !== "" && proxyJumpRaw.toLowerCase() !== "none" ? { proxyJump: proxyJumpRaw } : {}
|
|
1145
|
+
},
|
|
1146
|
+
identityFiles
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
940
1149
|
|
|
941
1150
|
//#endregion
|
|
942
1151
|
//#region src/remote/ssh-rsync-native-relay.ts
|
|
943
1152
|
/** ssh argv for the relay: batch, no agent, no multiplexing. `command` is the
|
|
944
|
-
* remote command; forwarding options go before `--`, the host after it.
|
|
1153
|
+
* remote command; forwarding options go before `--`, the host after it.
|
|
1154
|
+
* Identity core comes from ssh-argv.ts (the ONE policy — 2026-10-17 ruling). */
|
|
945
1155
|
function relaySsh(connection, extra, command) {
|
|
946
|
-
|
|
947
|
-
"ssh",
|
|
1156
|
+
return sshCommandArgv(connection, [
|
|
948
1157
|
"-o",
|
|
949
1158
|
"BatchMode=yes",
|
|
950
1159
|
"-T",
|
|
@@ -961,14 +1170,7 @@ function relaySsh(connection, extra, command) {
|
|
|
961
1170
|
"ServerAliveInterval=5",
|
|
962
1171
|
"-o",
|
|
963
1172
|
"ServerAliveCountMax=2"
|
|
964
|
-
];
|
|
965
|
-
if (connection.user !== void 0) args.push("-l", connection.user);
|
|
966
|
-
if (connection.port !== void 0) args.push("-p", String(connection.port));
|
|
967
|
-
if (connection.key !== void 0) args.push("-i", connection.key);
|
|
968
|
-
if (connection.proxyJump !== void 0) args.push("-J", connection.proxyJump);
|
|
969
|
-
args.push(...extra, "--", connection.host);
|
|
970
|
-
if (command !== void 0) args.push(command);
|
|
971
|
-
return args;
|
|
1173
|
+
], extra, command);
|
|
972
1174
|
}
|
|
973
1175
|
async function freePorts(count) {
|
|
974
1176
|
const servers = [];
|
|
@@ -1123,12 +1325,16 @@ async function forwardRoute(argv, source, destination, signal, options) {
|
|
|
1123
1325
|
return await removeRemoteTemp(destination.connection, temp, wrap) ? "released" : "unknown";
|
|
1124
1326
|
};
|
|
1125
1327
|
try {
|
|
1328
|
+
signal.throwIfAborted();
|
|
1329
|
+
const daemonState = await waitForDaemonReady(destinationChild, 5e3);
|
|
1330
|
+
if (daemonState === "exited") throw new Error(`dual-SSH rsync destination daemon exited before serving${relayDetail(destinationChild, sourceHold)}`);
|
|
1331
|
+
if (daemonState === "timeout") throw new Error(`dual-SSH rsync destination daemon never announced readiness${relayDetail(destinationChild, sourceHold)}`);
|
|
1126
1332
|
signal.throwIfAborted();
|
|
1127
1333
|
if (!await originPortOpen(originPort, 15e3)) throw new Error(`dual-SSH rsync destination daemon never became reachable${relayDetail(destinationChild, sourceHold)}`);
|
|
1128
1334
|
signal.throwIfAborted();
|
|
1129
1335
|
const runArgv = relaySsh(source.connection, [], rsyncClientCommand(argv, source.path, sourcePort));
|
|
1130
1336
|
const result = await runNative(wrap(runArgv), signal);
|
|
1131
|
-
if (result.exit
|
|
1337
|
+
if (result.exit !== 0) result.stderr = (result.stderr + relayDetail(destinationChild, sourceHold)).slice(-OUTPUT_LIMIT);
|
|
1132
1338
|
if (result.exit !== 0 && /remote port forwarding failed|administratively prohibited|could not request (local|remote) forwarding/.test(relayDetail(destinationChild, sourceHold))) throw new Error(`dual-SSH rsync forwarding route refused by an endpoint: ${relayDetail(destinationChild, sourceHold)}`);
|
|
1133
1339
|
return {
|
|
1134
1340
|
...result,
|
|
@@ -1153,6 +1359,19 @@ async function forwardRoute(argv, source, destination, signal, options) {
|
|
|
1153
1359
|
await Promise.allSettled([destinationChild.stop(), sourceHold.stop()]);
|
|
1154
1360
|
}
|
|
1155
1361
|
}
|
|
1362
|
+
/** Wait until the destination daemon script announces itself (stderr marker,
|
|
1363
|
+
* printed after its directory check and right before the daemon exec) or exits.
|
|
1364
|
+
* 'ready' only when the daemon is actually about to serve — closes the 0.3.1-e
|
|
1365
|
+
* race where -L opens at session start but the script dies ~150ms later. */
|
|
1366
|
+
async function waitForDaemonReady(held, budgetMs) {
|
|
1367
|
+
const deadline = Date.now() + budgetMs;
|
|
1368
|
+
for (;;) {
|
|
1369
|
+
if (/^SUPERD-RSYNC-TMP \S+$/m.test(held.stderrSink.text)) return "ready";
|
|
1370
|
+
if (held.child.exitCode !== null) return "exited";
|
|
1371
|
+
if (Date.now() >= deadline) return "timeout";
|
|
1372
|
+
await new Promise((resolve$1) => setTimeout(resolve$1, 50));
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1156
1375
|
function relayDetail(...held) {
|
|
1157
1376
|
const detail = held.map((child) => child.stderrSink.text).filter(Boolean).join("\n");
|
|
1158
1377
|
return detail ? `\n[relay stderr]\n${detail}` : "";
|
|
@@ -1234,14 +1453,7 @@ async function runRsync(request, source, destination, signal, options = {}) {
|
|
|
1234
1453
|
checkAbsolute(destination.path);
|
|
1235
1454
|
const argv = checkArgv("argv", request.argv);
|
|
1236
1455
|
if ("pullArgv" in request || "pushArgv" in request) throw new Error("remote: rsync takes argv only; pullArgv/pushArgv are copy-only fields");
|
|
1237
|
-
for (const
|
|
1238
|
-
"dryRun",
|
|
1239
|
-
"delete",
|
|
1240
|
-
"excludes",
|
|
1241
|
-
"preserve",
|
|
1242
|
-
"verify",
|
|
1243
|
-
"mkdir"
|
|
1244
|
-
]) if (legacy in request) throw new Error(`remote: rsync field "${legacy}" was removed — pass native options through argv instead (e.g. "--dry-run", "--delete", "--exclude=<pattern>", "-a"/"-r"; verify/mkdir belong to the copy Hub/local lane)`);
|
|
1456
|
+
for (const key of Object.keys(request)) if (key !== "src" && key !== "dst" && key !== "argv") throw new Error(`remote: rsync rejects unknown field "${key}" — native options go through argv (verify is a copy Hub-lane option; mkdir is copy-only; for destination parents pass --mkpath yourself)`);
|
|
1245
1457
|
if (!source.connection && !destination.connection) throw new Error("rsync requires at least one SSH endpoint; local-only is unsupported");
|
|
1246
1458
|
let result;
|
|
1247
1459
|
let route;
|
|
@@ -1289,6 +1501,9 @@ async function runRsync(request, source, destination, signal, options = {}) {
|
|
|
1289
1501
|
dst: request.dst,
|
|
1290
1502
|
argv,
|
|
1291
1503
|
route,
|
|
1504
|
+
verification: "native-exit-only",
|
|
1505
|
+
ok: result.exit === 0,
|
|
1506
|
+
...result.exit === 0 ? {} : { reason: signal.aborted ? "aborted" : "non-zero-exit" },
|
|
1292
1507
|
command: `rsync ${argv.join(" ")}`,
|
|
1293
1508
|
...itemized.length > 0 || argv.includes("--itemize-changes") || argv.includes("-i") ? { itemizedChanges: itemized } : {},
|
|
1294
1509
|
...literalBytes === void 0 ? {} : { literalBytes },
|
|
@@ -1303,21 +1518,14 @@ async function runRsync(request, source, destination, signal, options = {}) {
|
|
|
1303
1518
|
* placeholder host rsync appends and execs the canonical SSH argv. All tokens
|
|
1304
1519
|
* are tool-built argv (identity options/aliases), never model text. */
|
|
1305
1520
|
function rsyncRsh(connection, wrap) {
|
|
1306
|
-
const args = [
|
|
1307
|
-
"ssh",
|
|
1308
|
-
"-o",
|
|
1309
|
-
"BatchMode=yes",
|
|
1310
|
-
"-T"
|
|
1311
|
-
];
|
|
1312
|
-
if (connection.user !== void 0) args.push("-l", connection.user);
|
|
1313
|
-
if (connection.port !== void 0) args.push("-p", String(connection.port));
|
|
1314
|
-
if (connection.key !== void 0) args.push("-i", connection.key);
|
|
1315
|
-
if (connection.proxyJump !== void 0) args.push("-J", connection.proxyJump);
|
|
1316
|
-
args.push("--", connection.host);
|
|
1317
1521
|
return [
|
|
1318
1522
|
"bash",
|
|
1319
1523
|
"-c",
|
|
1320
|
-
`shift; exec ${wrap(
|
|
1524
|
+
`shift; exec ${wrap(sshCommandArgv(connection, [
|
|
1525
|
+
"-o",
|
|
1526
|
+
"BatchMode=yes",
|
|
1527
|
+
"-T"
|
|
1528
|
+
], [])).map(rshQuote).join(" ")} "$@"`,
|
|
1321
1529
|
"rsync-rsh"
|
|
1322
1530
|
].map(rshQuote).join(" ");
|
|
1323
1531
|
}
|
|
@@ -1336,7 +1544,7 @@ function parseFileEndpoint(value) {
|
|
|
1336
1544
|
if (split < 1) throw new Error("file endpoint must be [target:]absolute/path");
|
|
1337
1545
|
const target = value.slice(0, split), path$1 = value.slice(split + 1);
|
|
1338
1546
|
checkAbsolute(path$1);
|
|
1339
|
-
if (target.startsWith("
|
|
1547
|
+
if (target.startsWith("pty:")) throw new Error("a PTY session is not a filesystem endpoint; select SSH/Docker/Incus/Hub");
|
|
1340
1548
|
return {
|
|
1341
1549
|
target,
|
|
1342
1550
|
path: path$1
|
|
@@ -1345,13 +1553,9 @@ function parseFileEndpoint(value) {
|
|
|
1345
1553
|
|
|
1346
1554
|
//#endregion
|
|
1347
1555
|
//#region src/remote/ssh-targets.ts
|
|
1348
|
-
const LABEL = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
1349
1556
|
const USER = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
|
|
1350
1557
|
const HOST = /^(?:[A-Za-z0-9_][A-Za-z0-9_.-]*@)?(?:[A-Za-z0-9_][A-Za-z0-9_.-]*|\[[A-Fa-f0-9:.]+\]|[A-Fa-f0-9:]+)$/;
|
|
1351
1558
|
const JUMP = /^(?:[A-Za-z0-9_][A-Za-z0-9_.-]*@)?(?:[A-Za-z0-9_][A-Za-z0-9_.-]*|\[[A-Fa-f0-9:.]+\])(?::([0-9]+))?$/;
|
|
1352
|
-
function validateSshLabel(label) {
|
|
1353
|
-
if (!LABEL.test(label)) throw new Error("[E_BAD_LABEL] remote: BYO-SSH label must use letters, digits, dot, underscore or hyphen and start with a letter/digit");
|
|
1354
|
-
}
|
|
1355
1559
|
function bad(field) {
|
|
1356
1560
|
throw new Error(`[E_SSH_PARAMS] remote: invalid SSH ${field} — use host/user/port, an existing origin key file path, and optional ProxyJump aliases or [user@]host[:port] hops; no inline keys or shell options`);
|
|
1357
1561
|
}
|
|
@@ -1391,48 +1595,20 @@ function normalizeSshConnection(input) {
|
|
|
1391
1595
|
...input.proxyJump === void 0 ? {} : { proxyJump: input.proxyJump }
|
|
1392
1596
|
});
|
|
1393
1597
|
}
|
|
1394
|
-
/** One instance per Agent-owned driver; destroyed with its Agent/plugin owners. */
|
|
1395
|
-
var SshTargets = class {
|
|
1396
|
-
targets = /* @__PURE__ */ new Map();
|
|
1397
|
-
register(label, connection) {
|
|
1398
|
-
validateSshLabel(label);
|
|
1399
|
-
const normalized = normalizeSshConnection(connection), existing = this.targets.get(label);
|
|
1400
|
-
if (existing && JSON.stringify(existing) !== JSON.stringify(normalized)) throw new Error(`[E_LABEL_CONFLICT] remote: byossh:${label} SSH identity conflict — nothing was run. Reuse the label without ssh, or choose another label; existing credentials were not replaced`);
|
|
1401
|
-
if (!existing) this.targets.set(label, normalized);
|
|
1402
|
-
return existing ?? normalized;
|
|
1403
|
-
}
|
|
1404
|
-
get(label) {
|
|
1405
|
-
validateSshLabel(label);
|
|
1406
|
-
return this.targets.get(label);
|
|
1407
|
-
}
|
|
1408
|
-
entries() {
|
|
1409
|
-
return [...this.targets.entries()];
|
|
1410
|
-
}
|
|
1411
|
-
clear() {
|
|
1412
|
-
this.targets.clear();
|
|
1413
|
-
}
|
|
1414
|
-
};
|
|
1415
1598
|
/** Shared by execution, probes and file/relay consumers. extraArgs is trusted
|
|
1416
|
-
* internal SSH argv (e.g. forwarding), never a model-provided shell string.
|
|
1599
|
+
* internal SSH argv (e.g. forwarding), never a model-provided shell string.
|
|
1600
|
+
* Identity assembly lives in ssh-argv.ts (the ONE policy — 2026-10-17 ruling);
|
|
1601
|
+
* this wrapper only picks the tty/batch dialect base. */
|
|
1417
1602
|
function sshArgv(connection, options = {}) {
|
|
1418
|
-
|
|
1419
|
-
"ssh",
|
|
1603
|
+
return sshCommandArgv(connection, options.tty ? [
|
|
1420
1604
|
"-tt",
|
|
1421
1605
|
"-o",
|
|
1422
1606
|
"BatchMode=yes"
|
|
1423
1607
|
] : [
|
|
1424
|
-
"ssh",
|
|
1425
1608
|
"-o",
|
|
1426
1609
|
"BatchMode=yes",
|
|
1427
1610
|
"-T"
|
|
1428
|
-
];
|
|
1429
|
-
if (connection.user !== void 0) args.push("-l", connection.user);
|
|
1430
|
-
if (connection.port !== void 0) args.push("-p", String(connection.port));
|
|
1431
|
-
if (connection.key !== void 0) args.push("-i", connection.key);
|
|
1432
|
-
if (connection.proxyJump !== void 0) args.push("-J", connection.proxyJump);
|
|
1433
|
-
args.push(...options.extraArgs ?? [], "--", connection.host);
|
|
1434
|
-
if (options.command !== void 0) args.push(options.command);
|
|
1435
|
-
return args;
|
|
1611
|
+
], options.extraArgs ?? [], options.command);
|
|
1436
1612
|
}
|
|
1437
1613
|
|
|
1438
1614
|
//#endregion
|
|
@@ -1440,17 +1616,17 @@ function sshArgv(connection, options = {}) {
|
|
|
1440
1616
|
/** Local carrier validation precedes any target discovery, connection or spawn. */
|
|
1441
1617
|
async function prepareRemoteInput(input) {
|
|
1442
1618
|
if (input.mode !== void 0 && input.mode !== "oneshot" && input.mode !== "pty") throw new Error("[E_BAD_MODE] remote: mode must be oneshot or pty");
|
|
1443
|
-
if (input.
|
|
1444
|
-
if (input.cmd !== void 0 || input.stdin !== void 0 || input.mode === "pty" || input.spawn !== void 0
|
|
1445
|
-
if (typeof input.
|
|
1619
|
+
if (input.scriptPath !== void 0) {
|
|
1620
|
+
if (input.cmd !== void 0 || input.stdin !== void 0 || input.mode === "pty" || input.spawn !== void 0) throw new Error("[E_SCRIPT_PARAMS] remote: script is oneshot-only and cannot be combined with cmd, stdin, spawn or PTY lanes");
|
|
1621
|
+
if (typeof input.scriptPath !== "string" || !isAbsolute(input.scriptPath) || input.scriptPath.includes("\0")) throw new Error("[E_SCRIPT_PATH] remote: script must be a local absolute path without NUL");
|
|
1446
1622
|
}
|
|
1447
|
-
if (!input.target) throw new Error("[E_PARAMS] remote: target is required
|
|
1448
|
-
if (input.
|
|
1623
|
+
if (!input.target && input.spawn === void 0 && input.ssh === void 0) throw new Error("[E_PARAMS] remote: target is required (spawn / ssh are BYO entry points and may stand alone)");
|
|
1624
|
+
if (input.scriptPath !== void 0) {
|
|
1449
1625
|
let stdin;
|
|
1450
1626
|
try {
|
|
1451
|
-
stdin = await readFile(input.
|
|
1627
|
+
stdin = await readFile(input.scriptPath, "utf8");
|
|
1452
1628
|
} catch (error) {
|
|
1453
|
-
throw new Error(`[E_SCRIPT_READ] remote: cannot read local script ${JSON.stringify(input.
|
|
1629
|
+
throw new Error(`[E_SCRIPT_READ] remote: cannot read local script ${JSON.stringify(input.scriptPath)} — ${error instanceof Error ? error.message : String(error)}`);
|
|
1454
1630
|
}
|
|
1455
1631
|
return {
|
|
1456
1632
|
target: input.target,
|
|
@@ -1489,6 +1665,96 @@ async function runOneShot(argv, opts = {}) {
|
|
|
1489
1665
|
};
|
|
1490
1666
|
}
|
|
1491
1667
|
|
|
1668
|
+
//#endregion
|
|
1669
|
+
//#region src/remote/helper.ts
|
|
1670
|
+
/** Reads helper-bin/MANIFEST.json next to the compiled module (lib/remote in the npm
|
|
1671
|
+
* package, super-dsh/remote in the Super closure — same relative layout). Missing or
|
|
1672
|
+
* malformed assets ⇒ null ⇒ shim-only mode; never throws. */
|
|
1673
|
+
function helperAssets(baseDir) {
|
|
1674
|
+
const dir = baseDir ?? join(dirname(fileURLToPath(import.meta.url)), "helper-bin");
|
|
1675
|
+
try {
|
|
1676
|
+
const manifest = JSON.parse(readFileSync(join(dir, "MANIFEST.json"), "utf8"));
|
|
1677
|
+
if (manifest?.format !== 1 || typeof manifest.ver !== "string" || typeof manifest.protocol !== "number" || !manifest.targets || typeof manifest.targets !== "object") return null;
|
|
1678
|
+
return {
|
|
1679
|
+
dir,
|
|
1680
|
+
manifest
|
|
1681
|
+
};
|
|
1682
|
+
} catch {
|
|
1683
|
+
return null;
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
/** `uname -s`/`uname -m` → shipped target triple. Unknown combos ⇒ null (shim). */
|
|
1687
|
+
function archTriple(sys, machine, shipped) {
|
|
1688
|
+
const s = sys.trim().toLowerCase(), m = machine.trim().toLowerCase();
|
|
1689
|
+
const candidates = s === "linux" ? m === "x86_64" || m === "amd64" ? "x86_64-unknown-linux-musl" : m === "aarch64" || m === "arm64" ? "aarch64-unknown-linux-musl" : null : s === "darwin" ? m === "arm64" || m === "aarch64" ? "aarch64-apple-darwin" : null : null;
|
|
1690
|
+
if (candidates === null) return null;
|
|
1691
|
+
return shipped.has(candidates) ? candidates : null;
|
|
1692
|
+
}
|
|
1693
|
+
function planKey(plan) {
|
|
1694
|
+
switch (plan.kind) {
|
|
1695
|
+
case "ssh": {
|
|
1696
|
+
const c = plan.connection;
|
|
1697
|
+
const host = c?.host ?? plan.host;
|
|
1698
|
+
return `ssh|${c?.user ? c.user + "@" : ""}${host}${c?.port ? ":" + c.port : ""}${c?.proxyJump ? "|" + c.proxyJump : ""}`;
|
|
1699
|
+
}
|
|
1700
|
+
case "docker": return `docker|${plan.container}`;
|
|
1701
|
+
case "incus": return `incus|${plan.container}`;
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
const PROBE_RE = /^SUPERD-PROBE (\S+) (\S+)$/m;
|
|
1705
|
+
const READY_RE = /^SUPERD-READY (\S+)$/m;
|
|
1706
|
+
var HelperRegistry = class {
|
|
1707
|
+
states = /* @__PURE__ */ new Map();
|
|
1708
|
+
constructor(assets, exec, probeArgv, uploadArgv) {
|
|
1709
|
+
this.assets = assets;
|
|
1710
|
+
this.exec = exec;
|
|
1711
|
+
this.probeArgv = probeArgv;
|
|
1712
|
+
this.uploadArgv = uploadArgv;
|
|
1713
|
+
}
|
|
1714
|
+
/** Never throws: any bootstrap failure resolves null (sticky) and the caller stays on the shim. */
|
|
1715
|
+
ensure(plan) {
|
|
1716
|
+
if (plan.kind !== "ssh" && plan.kind !== "docker" && plan.kind !== "incus") return Promise.resolve(null);
|
|
1717
|
+
const key = planKey(plan);
|
|
1718
|
+
let entry = this.states.get(key);
|
|
1719
|
+
if (entry === void 0) {
|
|
1720
|
+
entry = this.bootstrap(plan).catch(() => null);
|
|
1721
|
+
entry.catch(() => {});
|
|
1722
|
+
this.states.set(key, entry);
|
|
1723
|
+
}
|
|
1724
|
+
return entry;
|
|
1725
|
+
}
|
|
1726
|
+
async bootstrap(plan) {
|
|
1727
|
+
const { manifest } = this.assets;
|
|
1728
|
+
const first = await this.exec(this.probeArgv(plan, this.assets), { timeoutSec: 15 });
|
|
1729
|
+
const ready = this.parseReady(first.stdout, manifest.ver, manifest.protocol);
|
|
1730
|
+
if (ready !== null) return ready;
|
|
1731
|
+
const probe = PROBE_RE.exec(first.stdout);
|
|
1732
|
+
if (probe === null || first.exit !== 90 && first.exit !== 0) return null;
|
|
1733
|
+
const triple = archTriple(probe[1], probe[2], new Set(Object.keys(manifest.targets)));
|
|
1734
|
+
if (triple === null) return null;
|
|
1735
|
+
const target = manifest.targets[triple];
|
|
1736
|
+
const binary = await readFile(join(this.assets.dir, triple, target.file));
|
|
1737
|
+
if ((await this.exec(this.uploadArgv(plan, triple, target.file, this.assets), {
|
|
1738
|
+
stdin: binary,
|
|
1739
|
+
timeoutSec: 60
|
|
1740
|
+
})).exit !== 0) return null;
|
|
1741
|
+
const second = await this.exec(this.probeArgv(plan, this.assets), { timeoutSec: 15 });
|
|
1742
|
+
return this.parseReady(second.stdout, manifest.ver, manifest.protocol);
|
|
1743
|
+
}
|
|
1744
|
+
parseReady(stdout, ver, protocol) {
|
|
1745
|
+
const ready = READY_RE.exec(stdout);
|
|
1746
|
+
const banner = /^SUPERD-RUN proto=(\d+) name=superd-run ver=(\S+) target=(\S+)/m.exec(stdout);
|
|
1747
|
+
if (ready === null || banner === null) return null;
|
|
1748
|
+
if (banner[1] !== String(protocol) || banner[2] !== ver) return null;
|
|
1749
|
+
return {
|
|
1750
|
+
binPath: ready[1],
|
|
1751
|
+
triple: banner[3],
|
|
1752
|
+
ver,
|
|
1753
|
+
protocol
|
|
1754
|
+
};
|
|
1755
|
+
}
|
|
1756
|
+
};
|
|
1757
|
+
|
|
1492
1758
|
//#endregion
|
|
1493
1759
|
//#region src/remote/transports.ts
|
|
1494
1760
|
/** POSIX 单引号机械转义(唯一一层转义,spec §三"一层机械转义")。 */
|
|
@@ -1536,12 +1802,15 @@ bash -lc ${shQuote(cmd)}`;
|
|
|
1536
1802
|
];
|
|
1537
1803
|
}
|
|
1538
1804
|
}
|
|
1539
|
-
/** Persistent pty(Ruling 2):ssh/incus 走宿主管道,docker 经 script(1) 托管宿主 PTY。
|
|
1805
|
+
/** Persistent pty(Ruling 2):ssh/incus 走宿主管道,docker 经 script(1) 托管宿主 PTY。
|
|
1806
|
+
* ssh 基座常驻固定 keepalive(2026-10-19 裁决):客户端自有、零对端依赖,控制消息
|
|
1807
|
+
* 不触碰 PTY 字节流;oneshot 短命连接不带。 */
|
|
1540
1808
|
function buildPtyArgv(plan) {
|
|
1541
1809
|
switch (plan.kind) {
|
|
1542
1810
|
case "ssh": return sshArgv(plan.connection ?? { host: plan.host }, {
|
|
1543
1811
|
tty: true,
|
|
1544
|
-
command: "bash"
|
|
1812
|
+
command: "bash",
|
|
1813
|
+
extraArgs: SSH_PERSISTENT_KEEPALIVE
|
|
1545
1814
|
});
|
|
1546
1815
|
case "docker": return [
|
|
1547
1816
|
"script",
|
|
@@ -1568,6 +1837,121 @@ function buildSpawnArgv(spawnCommand) {
|
|
|
1568
1837
|
"/dev/null"
|
|
1569
1838
|
];
|
|
1570
1839
|
}
|
|
1840
|
+
/** Hub PTY(0.3.2-c;0.3.2-d F4 修正):会话子进程 = 本地 `script` PTY 托管的 WS 字节泵
|
|
1841
|
+
* (hub-pty-pump.mjs)。与 docker exec 的嵌套 PTY 同形,但泵是哑 node 子进程、不像
|
|
1842
|
+
* `ssh -tt` / `docker exec -it` 那样作为前台子进程自己把本地 tty 置 raw——所以本地包装必须
|
|
1843
|
+
* `stty raw`:canonical+ISIG 下 0x03 在本地变 SIGINT 杀泵、0x04 变 EOF 结束泵 stdin
|
|
1844
|
+
* (F4:input ^C/^D 与 job_kill 会打死整条会话)。raw 只作用于本地半段;对端 script PTY
|
|
1845
|
+
* 保持 canonical,^C/^D 在对端产生 SIGINT/EOF 正是我们要的语义(字节原样过线,解释权在
|
|
1846
|
+
* 对端)。kill 链 session 组杀 → 泵死 → WS 关 → 对端组杀,双向自然闭合。连接事实走 wrapper
|
|
1847
|
+
* 内 env 赋值(cookie 不进 argv、不落 ps)。 */
|
|
1848
|
+
function buildHubPtyArgv(endpoint, assets) {
|
|
1849
|
+
const node = assets.nodePath ?? process.execPath;
|
|
1850
|
+
return [
|
|
1851
|
+
"script",
|
|
1852
|
+
"-qfec",
|
|
1853
|
+
`stty raw -echo 2>/dev/null ; ${`export SUPERD_HUB_PTY_URL=${shQuote(endpoint.url)} SUPERD_HUB_PTY_COOKIE=${shQuote(endpoint.cookie)} SUPERD_HUB_PTY_WS=${shQuote(endpoint.wsPath)}`} ; exec ${shQuote(node)} ${shQuote(assets.pumpPath)}`,
|
|
1854
|
+
"/dev/null"
|
|
1855
|
+
];
|
|
1856
|
+
}
|
|
1857
|
+
/** superd-run helper argv (spec: docs/specs/remote-rescope §5). Probe and upload are single
|
|
1858
|
+
* `sh -c` hops (busybox/alpine/darwin-safe); run/killgroup over ssh go through exactly one
|
|
1859
|
+
* remote-shell parse, same discipline as buildOneShotArgv. */
|
|
1860
|
+
function buildHelperProbeArgv(plan, assets) {
|
|
1861
|
+
const { ver, targets } = assets.manifest;
|
|
1862
|
+
return helperShellArgv(plan, `${Object.entries(targets).map(([triple, t]) => `d="$HOME/.cache/superd/run/${triple}-${ver}"; [ -x "$d/${t.file}" ] && { echo "SUPERD-READY $d/${t.file}"; "$d/${t.file}" banner; exit 0; };`).join(" ")} echo "SUPERD-PROBE $(uname -s 2>/dev/null || echo unknown) $(uname -m 2>/dev/null || echo unknown)"; exit 90`);
|
|
1863
|
+
}
|
|
1864
|
+
function buildHelperUploadArgv(plan, triple, file, assets) {
|
|
1865
|
+
const dir = `$HOME/.cache/superd/run/${triple}-${assets.manifest.ver}`;
|
|
1866
|
+
return helperShellArgv(plan, `mkdir -p "${dir}" && cat > "${dir}/${file}.tmp" && chmod 0755 "${dir}/${file}.tmp" && mv -f "${dir}/${file}.tmp" "${dir}/${file}"`);
|
|
1867
|
+
}
|
|
1868
|
+
function buildHelperOneShotArgv(plan, binPath, options) {
|
|
1869
|
+
const { tag, cmd } = options;
|
|
1870
|
+
switch (plan.kind) {
|
|
1871
|
+
case "ssh": return sshArgv(plan.connection ?? { host: plan.host }, { command: `exec ${shQuote(binPath)} run --tag ${shQuote(tag)} -- bash -lc ${shQuote(cmd)}` });
|
|
1872
|
+
case "docker": return [
|
|
1873
|
+
"docker",
|
|
1874
|
+
"exec",
|
|
1875
|
+
"-i",
|
|
1876
|
+
"--",
|
|
1877
|
+
plan.container,
|
|
1878
|
+
binPath,
|
|
1879
|
+
"run",
|
|
1880
|
+
"--tag",
|
|
1881
|
+
tag,
|
|
1882
|
+
"--",
|
|
1883
|
+
"bash",
|
|
1884
|
+
"-lc",
|
|
1885
|
+
cmd
|
|
1886
|
+
];
|
|
1887
|
+
case "incus": return [
|
|
1888
|
+
"incus",
|
|
1889
|
+
"exec",
|
|
1890
|
+
"--force-noninteractive",
|
|
1891
|
+
plan.container,
|
|
1892
|
+
"--",
|
|
1893
|
+
binPath,
|
|
1894
|
+
"run",
|
|
1895
|
+
"--tag",
|
|
1896
|
+
tag,
|
|
1897
|
+
"--",
|
|
1898
|
+
"bash",
|
|
1899
|
+
"-lc",
|
|
1900
|
+
cmd
|
|
1901
|
+
];
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
function buildHelperKillgroupArgv(plan, binPath, tag) {
|
|
1905
|
+
switch (plan.kind) {
|
|
1906
|
+
case "ssh": return sshArgv(plan.connection ?? { host: plan.host }, { command: `${shQuote(binPath)} killgroup --tag ${shQuote(tag)}` });
|
|
1907
|
+
case "docker": return [
|
|
1908
|
+
"docker",
|
|
1909
|
+
"exec",
|
|
1910
|
+
"--",
|
|
1911
|
+
plan.container,
|
|
1912
|
+
binPath,
|
|
1913
|
+
"killgroup",
|
|
1914
|
+
"--tag",
|
|
1915
|
+
tag
|
|
1916
|
+
];
|
|
1917
|
+
case "incus": return [
|
|
1918
|
+
"incus",
|
|
1919
|
+
"exec",
|
|
1920
|
+
"--force-noninteractive",
|
|
1921
|
+
plan.container,
|
|
1922
|
+
"--",
|
|
1923
|
+
binPath,
|
|
1924
|
+
"killgroup",
|
|
1925
|
+
"--tag",
|
|
1926
|
+
tag
|
|
1927
|
+
];
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1930
|
+
function helperShellArgv(plan, script) {
|
|
1931
|
+
switch (plan.kind) {
|
|
1932
|
+
case "ssh": return sshArgv(plan.connection ?? { host: plan.host }, { command: script });
|
|
1933
|
+
case "docker": return [
|
|
1934
|
+
"docker",
|
|
1935
|
+
"exec",
|
|
1936
|
+
"-i",
|
|
1937
|
+
"--",
|
|
1938
|
+
plan.container,
|
|
1939
|
+
"sh",
|
|
1940
|
+
"-c",
|
|
1941
|
+
script
|
|
1942
|
+
];
|
|
1943
|
+
case "incus": return [
|
|
1944
|
+
"incus",
|
|
1945
|
+
"exec",
|
|
1946
|
+
"--force-noninteractive",
|
|
1947
|
+
plan.container,
|
|
1948
|
+
"--",
|
|
1949
|
+
"sh",
|
|
1950
|
+
"-c",
|
|
1951
|
+
script
|
|
1952
|
+
];
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1571
1955
|
|
|
1572
1956
|
//#endregion
|
|
1573
1957
|
//#region src/remote/nonce-framing.ts
|
|
@@ -1577,11 +1961,11 @@ function genNonce(bytes = 8) {
|
|
|
1577
1961
|
}
|
|
1578
1962
|
/** 命令整行:花括号复合体 + Nonce 收帧尾(spec §五.2 的 printf 逐字落地 + cwd 第三字段)。 */
|
|
1579
1963
|
function wrapPtyCommand(cmd, nonce) {
|
|
1580
|
-
return `{\n${cmd}\n} ; printf '\\033]133;D;${nonce};%s;%s\\007' "
|
|
1964
|
+
return `{\n${cmd}\n} ; __superd_e=$? ; printf '\\033]133;E;${nonce};%s\\007' "$(env -0 | base64 | tr -d '\\n\\r')" ; printf '\\033]133;D;${nonce};%s;%s\\007' "$__superd_e" "$PWD" ; unset __superd_e\n`;
|
|
1581
1965
|
}
|
|
1582
1966
|
/** init 整行:哑终端(echo/PS1/PS2/TERM)+ 固定 40×120(Non-Goal ③)+ INIT 帧。 */
|
|
1583
1967
|
function buildInitCommand(nonce) {
|
|
1584
|
-
return `stty -echo 2>/dev/null ; stty rows 40 cols 120 2>/dev/null ; PS1='' ; PS2='' ; export TERM=dumb ; printf '\\033]133;D;${nonce};0;%s\\007' "$PWD"\n`;
|
|
1968
|
+
return `stty -echo 2>/dev/null ; stty rows 40 cols 120 2>/dev/null ; PS1='' ; PS2='' ; export TERM=dumb ; printf '\\033]133;E;${nonce};%s\\007' "$(env -0 | base64 | tr -d '\\n\\r')" ; printf '\\033]133;D;${nonce};0;%s\\007' "$PWD"\n`;
|
|
1585
1969
|
}
|
|
1586
1970
|
const ANSI_RE = /\x1b(?:\][^\x07\x1b]*(?:\x07|\x1b\\)?|\[[0-9;?]*[ -/]*[@-~]|[@-Z\\-_])/g;
|
|
1587
1971
|
function stripAnsi(s) {
|
|
@@ -1610,6 +1994,7 @@ function tailWindow(text, cap, stats) {
|
|
|
1610
1994
|
};
|
|
1611
1995
|
}
|
|
1612
1996
|
const FRAME_BODY_RE = /^(\d+);([^\x07\x1b]*)(?:\x07|\x1b\\)/;
|
|
1997
|
+
const ENV_BODY_RE = /^([A-Za-z0-9+/=]*)\x07/;
|
|
1613
1998
|
/**
|
|
1614
1999
|
* 单 nonce、单帧解析器:一轮 dispatch 一个实例。只认 `\x1b]133;D;<nonce>;`,
|
|
1615
2000
|
* 错误 nonce 的静态/伪造 marker 永不匹配,按普通输出流过(再经 ANSI 剥洗)。
|
|
@@ -1617,31 +2002,60 @@ const FRAME_BODY_RE = /^(\d+);([^\x07\x1b]*)(?:\x07|\x1b\\)/;
|
|
|
1617
2002
|
*/
|
|
1618
2003
|
function createNonceFrameParser(nonce, events) {
|
|
1619
2004
|
const prefix = `\x1b]133;D;${nonce};`;
|
|
2005
|
+
const prefixE = `\x1b]133;E;${nonce};`;
|
|
2006
|
+
const prefixes = [prefix, prefixE];
|
|
1620
2007
|
let buf = "";
|
|
1621
2008
|
let done = false;
|
|
1622
2009
|
const emit = (raw) => {
|
|
1623
2010
|
const text = normalizePtyText(raw);
|
|
1624
2011
|
if (text.length > 0) events.onOutput?.(text);
|
|
1625
2012
|
};
|
|
2013
|
+
/** 缓冲尾若是任一候选前缀的真前缀则扣留(D/E 共用);flush() 放出残余。 */
|
|
1626
2014
|
const holdback = () => {
|
|
1627
|
-
|
|
1628
|
-
for (
|
|
1629
|
-
|
|
2015
|
+
let best = 0;
|
|
2016
|
+
for (const p of prefixes) {
|
|
2017
|
+
const max = Math.min(buf.length, p.length - 1);
|
|
2018
|
+
for (let k = max; k > best; k--) if (buf.endsWith(p.slice(0, k))) {
|
|
2019
|
+
best = k;
|
|
2020
|
+
break;
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
return best;
|
|
1630
2024
|
};
|
|
2025
|
+
/** 扫描最早出现的帧:E(env 侧信道)先于 D 下发;D = settle,帧后字节丢弃。 */
|
|
1631
2026
|
const consume = () => {
|
|
1632
2027
|
if (done) return;
|
|
1633
|
-
|
|
1634
|
-
|
|
2028
|
+
let idx = -1;
|
|
2029
|
+
let isEnv = false;
|
|
2030
|
+
for (const p of prefixes) {
|
|
2031
|
+
const i = buf.indexOf(p);
|
|
2032
|
+
if (i >= 0 && (idx === -1 || i < idx)) {
|
|
2033
|
+
idx = i;
|
|
2034
|
+
isEnv = p === prefixE;
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
if (idx < 0) {
|
|
1635
2038
|
const keep = holdback();
|
|
1636
2039
|
emit(buf.slice(0, buf.length - keep));
|
|
1637
2040
|
buf = buf.slice(buf.length - keep);
|
|
1638
2041
|
return;
|
|
1639
2042
|
}
|
|
1640
|
-
emit(buf.slice(0,
|
|
1641
|
-
const rest = buf.slice(
|
|
2043
|
+
emit(buf.slice(0, idx));
|
|
2044
|
+
const rest = buf.slice(idx + (isEnv ? prefixE.length : prefix.length));
|
|
2045
|
+
if (isEnv) {
|
|
2046
|
+
const m$1 = ENV_BODY_RE.exec(rest);
|
|
2047
|
+
if (m$1 === null) {
|
|
2048
|
+
buf = buf.slice(idx);
|
|
2049
|
+
return;
|
|
2050
|
+
}
|
|
2051
|
+
if (m$1[1].length > 0) events.onEnv?.(m$1[1]);
|
|
2052
|
+
buf = rest.slice(m$1[0].length);
|
|
2053
|
+
consume();
|
|
2054
|
+
return;
|
|
2055
|
+
}
|
|
1642
2056
|
const m = FRAME_BODY_RE.exec(rest);
|
|
1643
2057
|
if (m === null) {
|
|
1644
|
-
buf = buf.slice(
|
|
2058
|
+
buf = buf.slice(idx);
|
|
1645
2059
|
return;
|
|
1646
2060
|
}
|
|
1647
2061
|
events.onFrame({
|
|
@@ -1662,33 +2076,90 @@ function createNonceFrameParser(nonce, events) {
|
|
|
1662
2076
|
}
|
|
1663
2077
|
};
|
|
1664
2078
|
}
|
|
2079
|
+
/** E 帧 payload → name→value-hash(值不离开端点;hash 只为 changed 判定)。空/坏 payload → undefined。 */
|
|
2080
|
+
function decodeEnvSnapshot(b64) {
|
|
2081
|
+
if (b64.length === 0) return void 0;
|
|
2082
|
+
let text;
|
|
2083
|
+
try {
|
|
2084
|
+
text = Buffer.from(b64, "base64").toString("utf8");
|
|
2085
|
+
} catch {
|
|
2086
|
+
return;
|
|
2087
|
+
}
|
|
2088
|
+
const map = /* @__PURE__ */ new Map();
|
|
2089
|
+
for (const entry of text.split("\0")) {
|
|
2090
|
+
if (entry.length === 0) continue;
|
|
2091
|
+
const eq = entry.indexOf("=");
|
|
2092
|
+
const name$1 = eq === -1 ? entry : entry.slice(0, eq);
|
|
2093
|
+
if (name$1.startsWith("__superd")) continue;
|
|
2094
|
+
let h = 5381;
|
|
2095
|
+
const value = eq === -1 ? "" : entry.slice(eq + 1);
|
|
2096
|
+
for (let i = 0; i < value.length; i++) h = (h * 33 ^ value.charCodeAt(i)) >>> 0;
|
|
2097
|
+
map.set(name$1, h);
|
|
2098
|
+
}
|
|
2099
|
+
return map.size > 0 ? map : void 0;
|
|
2100
|
+
}
|
|
2101
|
+
/** prev 未知(init 侧信道失败)时返回 undefined——不报告假 delta。 */
|
|
2102
|
+
function diffEnv(prev, next) {
|
|
2103
|
+
if (prev === void 0) return void 0;
|
|
2104
|
+
const added = [], changed = [], removed = [];
|
|
2105
|
+
for (const [name$1, h] of next) if (!prev.has(name$1)) added.push(name$1);
|
|
2106
|
+
else if (prev.get(name$1) !== h) changed.push(name$1);
|
|
2107
|
+
for (const name$1 of prev.keys()) if (!next.has(name$1)) removed.push(name$1);
|
|
2108
|
+
added.sort();
|
|
2109
|
+
changed.sort();
|
|
2110
|
+
removed.sort();
|
|
2111
|
+
return {
|
|
2112
|
+
added,
|
|
2113
|
+
changed,
|
|
2114
|
+
removed
|
|
2115
|
+
};
|
|
2116
|
+
}
|
|
1665
2117
|
|
|
1666
2118
|
//#endregion
|
|
1667
2119
|
//#region src/remote/pty-session.ts
|
|
1668
2120
|
/** spec §五.2 逐字。 */
|
|
1669
2121
|
const RECONNECT_NOTICE = "[remote: session reconnected to fresh shell; cwd reset to default]";
|
|
1670
|
-
/** 池键 → 模型面名字:剥掉 agent 前缀与内部标记(`
|
|
1671
|
-
*
|
|
1672
|
-
*
|
|
2122
|
+
/** 池键 → 模型面名字:剥掉 agent 前缀与内部标记(`p:` → `pty:<id>`)。
|
|
2123
|
+
* 这是**唯一**的 key→名字映射规则,roster 与错误面共用——错误面不得回吐内部键:
|
|
2124
|
+
* 2026-10-03 实测报告 F1,`E_SESSION_*` 曾把 `session-<uuid>|p:<label>` 整条吐给模型。 */
|
|
1673
2125
|
function displayKey(key) {
|
|
1674
2126
|
const raw = key.includes("|") ? key.slice(key.indexOf("|") + 1) : key;
|
|
1675
|
-
return raw.startsWith("
|
|
2127
|
+
return raw.startsWith("p:") ? `pty:${raw.slice(2)}` : raw;
|
|
1676
2128
|
}
|
|
2129
|
+
const LEDGER_MAX = 20;
|
|
2130
|
+
const summaryOf = (cmd) => {
|
|
2131
|
+
const first = cmd.trim().split(/\r?\n/, 1)[0] ?? "";
|
|
2132
|
+
return first.length > 72 ? `${first.slice(0, 71)}…` : first;
|
|
2133
|
+
};
|
|
1677
2134
|
const DEFAULT_INIT_TIMEOUT_SEC = 30;
|
|
1678
2135
|
const INTERRUPT_GRACE_MS = 3e3;
|
|
2136
|
+
/** F2(0.3.2-d):\x03 触发 ISIG 时内核 flush 输入队列——130-marker 必须等 flush 完成
|
|
2137
|
+
* 再入队,否则首字节被吞(实测 'rintf' not found → 会话死)。 */
|
|
2138
|
+
const MARKER_SETTLE_MS = 80;
|
|
1679
2139
|
/** pty 收集内存安全帽(Ruling P15,与 oneshot HARD_CAP 对齐):模型面只见尾窗,保留尾部。 */
|
|
1680
2140
|
const OUTPUT_HARD_CAP = 4e6;
|
|
1681
2141
|
var PtySession = class {
|
|
1682
2142
|
proc = null;
|
|
1683
2143
|
state = "cold";
|
|
1684
2144
|
startPromise = null;
|
|
1685
|
-
queue = Promise.resolve();
|
|
1686
2145
|
idleTimer = null;
|
|
1687
2146
|
onChunk = null;
|
|
1688
2147
|
deathWaiters = [];
|
|
1689
2148
|
diag = "";
|
|
1690
2149
|
inFlight = 0;
|
|
1691
|
-
|
|
2150
|
+
/** P4/P5:当前占用前台的 detached job(background/超时 handoff)。非 null 时新命令拒绝(Q6)。 */
|
|
2151
|
+
detachedJob = null;
|
|
2152
|
+
/** §3.2(2026-10-25):当前占用会话的命令——dispatch 同步占位,settle/cleanup 释放;input 的唯一写入对象。 */
|
|
2153
|
+
activeCommand = null;
|
|
2154
|
+
/** 账本(§5):本会话最近 20 条命令(FIFO,超出丢最旧)。 */
|
|
2155
|
+
ledger = [];
|
|
2156
|
+
/** env 侧信道基线(init E 帧);undefined = 侧信道不可用(不报假 delta)。 */
|
|
2157
|
+
envBaseline;
|
|
2158
|
+
/** idle 起点(ready / settle 时重置);null = 尚无 idle 时钟(cold 或已 dispose)。 */
|
|
2159
|
+
idleSince = null;
|
|
2160
|
+
/** 意外死亡后的回收定时器(R2):ready 过的会话先留池供 reconnect,超时仍无人寻址则出池。 */
|
|
2161
|
+
deathTimer = null;
|
|
2162
|
+
lastCwdSeen = null;
|
|
1692
2163
|
/** 是否曾成功初始化(ready 过)。决定死亡语义:ready 过 → reconnect(留池);从未 ready → 出池(见 start())。 */
|
|
1693
2164
|
everReady = false;
|
|
1694
2165
|
disposal;
|
|
@@ -1700,7 +2171,39 @@ var PtySession = class {
|
|
|
1700
2171
|
get sessionState() {
|
|
1701
2172
|
return this.state;
|
|
1702
2173
|
}
|
|
1703
|
-
/**
|
|
2174
|
+
/** 池键(driver 的 ttl/inspect 用)。 */
|
|
2175
|
+
get key() {
|
|
2176
|
+
return this.opts.key;
|
|
2177
|
+
}
|
|
2178
|
+
/** 最近帧 cwd(card 面);从未执行过 = null。 */
|
|
2179
|
+
get lastCwd() {
|
|
2180
|
+
return this.lastCwdSeen;
|
|
2181
|
+
}
|
|
2182
|
+
/** 占用前台的 detached job 的 commandId(无 = null;close 拒绝与 busy 文案共用)。 */
|
|
2183
|
+
get detachedCommandId() {
|
|
2184
|
+
return this.detachedJob?.commandId ?? null;
|
|
2185
|
+
}
|
|
2186
|
+
/** job 通道收养后回填 jobId(timeout handoff 时 registry id ≠ commandId,账本如实记录两者);运行中的命令同步携带(input 回执用)。 */
|
|
2187
|
+
attachJob(commandId, jobId) {
|
|
2188
|
+
const entry = [...this.ledger].reverse().find((e) => e.commandId === commandId);
|
|
2189
|
+
if (entry !== void 0) entry.jobId = jobId;
|
|
2190
|
+
if (this.activeCommand !== null && this.activeCommand.commandId === commandId) this.activeCommand.jobId = jobId;
|
|
2191
|
+
}
|
|
2192
|
+
/** Workbench 身份(§3):id + 可选 label + connection + byo 标记。 */
|
|
2193
|
+
get identity() {
|
|
2194
|
+
return {
|
|
2195
|
+
id: this.opts.id,
|
|
2196
|
+
...this.opts.label !== void 0 ? { label: this.opts.label } : {},
|
|
2197
|
+
connection: this.opts.connection,
|
|
2198
|
+
byo: this.opts.byo === true,
|
|
2199
|
+
builtOn: this.opts.builtOn === true
|
|
2200
|
+
};
|
|
2201
|
+
}
|
|
2202
|
+
/** 账本快照(session card 面,只读)。 */
|
|
2203
|
+
ledgerSnapshot() {
|
|
2204
|
+
return this.ledger;
|
|
2205
|
+
}
|
|
2206
|
+
/** spawn 创建原文(仅 BYO 会话;v2 起仅存档,不参与复用判定)。 */
|
|
1704
2207
|
get origin() {
|
|
1705
2208
|
return this.opts.origin;
|
|
1706
2209
|
}
|
|
@@ -1709,93 +2212,226 @@ var PtySession = class {
|
|
|
1709
2212
|
return {
|
|
1710
2213
|
state: this.state,
|
|
1711
2214
|
busy: this.inFlight > 0,
|
|
1712
|
-
idleMs: this.
|
|
2215
|
+
idleMs: this.idleSince === null ? null : Date.now() - this.idleSince,
|
|
1713
2216
|
pid: this.proc?.pid ?? null
|
|
1714
2217
|
};
|
|
1715
2218
|
}
|
|
1716
|
-
/**
|
|
1717
|
-
|
|
2219
|
+
/** 预热创建(创建形无 cmd):真正拨号到 init 帧——「会话已就绪」必须是真的,
|
|
2220
|
+
* 而且只有 ready 过才挂 idle 回收(cold 会话没有 timer,会永远占配额)。 */
|
|
2221
|
+
async warm() {
|
|
2222
|
+
await this.start();
|
|
2223
|
+
}
|
|
2224
|
+
/** 同一会话命令占位制(2026-10-25 interactive-stdin 轮):dispatch 入口**同步**建立
|
|
2225
|
+
* 命令占位(activeCommand + inFlight + 账本条目)——上一条命令仍在运行(同步等待 /
|
|
2226
|
+
* 等输入 / detached job)时新 cmd 立即 E_SESSION_BUSY;原「纯同步并发排 FIFO」语义
|
|
2227
|
+
* 废除(排队会让等输入的命令与补输入动作互相卡死,也给 busy 留下绕行窗口)。
|
|
2228
|
+
* P4/P5:超时不杀命令而是 handoff 成 running job;background 立即回执;P8 显式
|
|
2229
|
+
* interrupt 保留在 job.interrupt;死亡/冷态先重启(reconnect 语义不变)。 */
|
|
2230
|
+
dispatch(cmd, dOpts) {
|
|
2231
|
+
if (this.state === "disposed") return Promise.reject(/* @__PURE__ */ new Error(`[E_SESSION_DISPOSED] remote pty session '${this.opts.id}' was disposed before dispatch`));
|
|
2232
|
+
if (this.activeCommand !== null) {
|
|
2233
|
+
const handle = this.activeCommand.jobId ?? this.activeCommand.commandId;
|
|
2234
|
+
return Promise.reject(/* @__PURE__ */ new Error(`[E_SESSION_BUSY] remote: pty session '${this.opts.id}' still runs a command (${this.activeCommand.commandId}) — send it more stdin with the input action, follow its output via job_output ${handle} (a synchronous exec hands its job off there on timeout), cancel with job_kill ${handle}, or address other work to another session / oneshot`));
|
|
2235
|
+
}
|
|
2236
|
+
const commandId = dOpts.commandId;
|
|
2237
|
+
const entry = {
|
|
2238
|
+
commandId,
|
|
2239
|
+
summary: summaryOf(cmd),
|
|
2240
|
+
exit: null,
|
|
2241
|
+
durationMs: 0,
|
|
2242
|
+
running: true,
|
|
2243
|
+
...dOpts.jobId !== void 0 ? { jobId: dOpts.jobId } : {}
|
|
2244
|
+
};
|
|
2245
|
+
this.ledger.push(entry);
|
|
2246
|
+
if (this.ledger.length > LEDGER_MAX) this.ledger.shift();
|
|
2247
|
+
this.activeCommand = {
|
|
2248
|
+
commandId,
|
|
2249
|
+
...dOpts.jobId !== void 0 ? { jobId: dOpts.jobId } : {}
|
|
2250
|
+
};
|
|
2251
|
+
this.inFlight++;
|
|
1718
2252
|
const attempt = async () => {
|
|
1719
2253
|
const started = Date.now();
|
|
1720
2254
|
const reconnected = this.state === "dead";
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
2255
|
+
/** 占位撤销:命令从未真正启动(建连失败 / 建连中被 dispose)——释放 busy 与计数,
|
|
2256
|
+
* 撤掉账本条目(与旧时序等价:条目原本在 start 成功之后才建立)。 */
|
|
2257
|
+
const abandon = () => {
|
|
2258
|
+
this.activeCommand = null;
|
|
2259
|
+
this.inFlight--;
|
|
2260
|
+
const index = this.ledger.indexOf(entry);
|
|
2261
|
+
if (index >= 0) this.ledger.splice(index, 1);
|
|
2262
|
+
};
|
|
2263
|
+
if (this.state !== "ready") try {
|
|
2264
|
+
await this.start();
|
|
2265
|
+
} catch (error) {
|
|
2266
|
+
abandon();
|
|
2267
|
+
throw error;
|
|
2268
|
+
}
|
|
2269
|
+
if (this.state === "disposed") {
|
|
2270
|
+
abandon();
|
|
2271
|
+
throw new Error(`[E_SESSION_DISPOSED] remote pty session '${this.opts.id}' was disposed before dispatch`);
|
|
2272
|
+
}
|
|
1724
2273
|
return await new Promise((resolve$1) => {
|
|
1725
2274
|
const nonce = genNonce();
|
|
1726
2275
|
const ring = new Utf16TailRing(OUTPUT_HARD_CAP);
|
|
1727
2276
|
let interrupted = false;
|
|
1728
2277
|
let settled = false;
|
|
2278
|
+
let jobSettled = false;
|
|
1729
2279
|
let interruptTimer;
|
|
1730
2280
|
let killTimer;
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
2281
|
+
let markerTimer;
|
|
2282
|
+
let jobDone = null;
|
|
2283
|
+
let envNext;
|
|
2284
|
+
const detach = () => {
|
|
2285
|
+
const job = {
|
|
2286
|
+
commandId,
|
|
2287
|
+
read: (fromByte) => ring.read(fromByte),
|
|
2288
|
+
stats: () => ring.stats(),
|
|
2289
|
+
interrupt: () => {
|
|
2290
|
+
if (!jobSettled) twoStage();
|
|
2291
|
+
},
|
|
2292
|
+
done: new Promise((res) => {
|
|
2293
|
+
jobDone = res;
|
|
2294
|
+
})
|
|
2295
|
+
};
|
|
2296
|
+
this.detachedJob = job;
|
|
2297
|
+
settled = true;
|
|
2298
|
+
resolve$1({
|
|
2299
|
+
output: ring.text,
|
|
2300
|
+
outputStats: { stdout: ring.stats() },
|
|
2301
|
+
exit: null,
|
|
2302
|
+
cwd: null,
|
|
2303
|
+
timedOut: false,
|
|
2304
|
+
running: true,
|
|
2305
|
+
job,
|
|
2306
|
+
commandId,
|
|
2307
|
+
reconnected,
|
|
2308
|
+
durationMs: Date.now() - started
|
|
2309
|
+
});
|
|
2310
|
+
return job;
|
|
2311
|
+
};
|
|
1737
2312
|
const cleanup = () => {
|
|
1738
2313
|
this.onChunk = null;
|
|
2314
|
+
this.detachedJob = null;
|
|
2315
|
+
this.activeCommand = null;
|
|
1739
2316
|
this.deathWaiters = this.deathWaiters.filter((w) => w !== deathWaiter);
|
|
1740
2317
|
if (interruptTimer !== void 0) clearTimeout(interruptTimer);
|
|
1741
2318
|
if (killTimer !== void 0) clearTimeout(killTimer);
|
|
2319
|
+
if (markerTimer !== void 0) clearTimeout(markerTimer);
|
|
1742
2320
|
};
|
|
1743
|
-
const
|
|
1744
|
-
if (
|
|
1745
|
-
|
|
2321
|
+
const settle = (r) => {
|
|
2322
|
+
if (jobSettled) return;
|
|
2323
|
+
jobSettled = true;
|
|
1746
2324
|
cleanup();
|
|
1747
2325
|
this.inFlight--;
|
|
1748
|
-
this.
|
|
2326
|
+
this.idleSince = Date.now();
|
|
1749
2327
|
this.resetIdleTimer();
|
|
1750
|
-
|
|
2328
|
+
if (r.cwd !== null) this.lastCwdSeen = r.cwd;
|
|
2329
|
+
const envDelta = envNext !== void 0 ? diffEnv(this.envBaseline, envNext) : void 0;
|
|
2330
|
+
if (envNext !== void 0) this.envBaseline = envNext;
|
|
2331
|
+
entry.exit = r.exit;
|
|
2332
|
+
entry.durationMs = Date.now() - started;
|
|
2333
|
+
entry.running = false;
|
|
2334
|
+
const full = {
|
|
1751
2335
|
...r,
|
|
1752
2336
|
outputStats: { stdout: ring.stats() },
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
}
|
|
2337
|
+
commandId,
|
|
2338
|
+
...envDelta !== void 0 ? { envDelta } : {}
|
|
2339
|
+
};
|
|
2340
|
+
jobDone?.(full);
|
|
2341
|
+
if (!settled) {
|
|
2342
|
+
settled = true;
|
|
2343
|
+
resolve$1({
|
|
2344
|
+
...full,
|
|
2345
|
+
reconnected,
|
|
2346
|
+
durationMs: Date.now() - started
|
|
2347
|
+
});
|
|
2348
|
+
}
|
|
1756
2349
|
};
|
|
2350
|
+
const deathWaiter = () => settle({
|
|
2351
|
+
output: ring.text,
|
|
2352
|
+
exit: null,
|
|
2353
|
+
cwd: null,
|
|
2354
|
+
timedOut: interrupted
|
|
2355
|
+
});
|
|
1757
2356
|
const parser = createNonceFrameParser(nonce, {
|
|
1758
2357
|
onOutput: (t) => {
|
|
1759
2358
|
ring.push(t);
|
|
1760
2359
|
},
|
|
1761
|
-
|
|
2360
|
+
onEnv: (b64) => {
|
|
2361
|
+
const m = decodeEnvSnapshot(b64);
|
|
2362
|
+
if (m !== void 0) envNext = m;
|
|
2363
|
+
},
|
|
2364
|
+
onFrame: ({ exit, cwd }) => settle({
|
|
1762
2365
|
output: ring.text,
|
|
1763
2366
|
exit,
|
|
1764
2367
|
cwd,
|
|
1765
2368
|
timedOut: interrupted
|
|
1766
2369
|
})
|
|
1767
2370
|
});
|
|
1768
|
-
|
|
1769
|
-
this.write(wrapPtyCommand(cmd, nonce));
|
|
1770
|
-
if (dOpts.stdin !== void 0) this.write(dOpts.stdin);
|
|
1771
|
-
interruptTimer = setTimeout(() => {
|
|
2371
|
+
const twoStage = () => {
|
|
1772
2372
|
interrupted = true;
|
|
1773
2373
|
this.write("");
|
|
1774
|
-
|
|
2374
|
+
markerTimer = setTimeout(() => {
|
|
2375
|
+
this.write(`printf '\\033]133;D;${nonce};130;%s\\007' "$PWD"\n`);
|
|
2376
|
+
}, MARKER_SETTLE_MS);
|
|
1775
2377
|
killTimer = setTimeout(() => {
|
|
1776
2378
|
this.killTree();
|
|
1777
2379
|
this.markDead();
|
|
1778
|
-
|
|
2380
|
+
settle({
|
|
1779
2381
|
output: ring.text,
|
|
1780
2382
|
exit: null,
|
|
1781
2383
|
cwd: null,
|
|
1782
2384
|
timedOut: true
|
|
1783
2385
|
});
|
|
1784
2386
|
}, INTERRUPT_GRACE_MS);
|
|
1785
|
-
}
|
|
2387
|
+
};
|
|
2388
|
+
this.onChunk = (c) => parser.feed(c);
|
|
2389
|
+
this.write(wrapPtyCommand(cmd, nonce));
|
|
2390
|
+
if (dOpts.stdin !== void 0) this.write(dOpts.stdin);
|
|
1786
2391
|
this.deathWaiters.push(deathWaiter);
|
|
2392
|
+
if (dOpts.background === true) {
|
|
2393
|
+
detach();
|
|
2394
|
+
return;
|
|
2395
|
+
}
|
|
2396
|
+
interruptTimer = setTimeout(() => detach(), dOpts.timeoutSec === void 0 ? 12e4 : dOpts.timeoutSec * 1e3);
|
|
1787
2397
|
});
|
|
1788
2398
|
};
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
2399
|
+
return attempt();
|
|
2400
|
+
}
|
|
2401
|
+
/** §3.1(2026-10-25)interactive-stdin:向当前运行中的命令追加 stdin——只写既有通道
|
|
2402
|
+
* 与身份,不新建命令、账本条目或输出游标;不重连、不重放(dead/disposed 明确拒绝)。
|
|
2403
|
+
* 校验与写入全同步:多次 input 按调用顺序整段写入不交错;写入失败如实抛错(私有
|
|
2404
|
+
* write() 的静默忽略不适用于回执语义)。stdin:"" 是零字节写入,不是 EOF。 */
|
|
2405
|
+
input(options) {
|
|
2406
|
+
const fail = (code, hint) => Promise.reject(/* @__PURE__ */ new Error(`${code} remote: ${hint}`));
|
|
2407
|
+
if (this.state === "disposed") return fail("[E_SESSION_DISPOSED]", `pty session '${displayKey(this.opts.key)}' was disposed — input never reaches a disposed session`);
|
|
2408
|
+
if (this.state === "dead") return fail("[E_SESSION_NOT_RUNNING]", `pty session '${displayKey(this.opts.key)}' died — input never reconnects or replays; start a new command (exec reconnects a fresh shell) and re-send only what is still needed`);
|
|
2409
|
+
if (this.state === "starting") return fail("[E_SESSION_NOT_READY]", `pty session '${displayKey(this.opts.key)}' is still initializing — wait for the exec receipt, then input`);
|
|
2410
|
+
const active = this.activeCommand;
|
|
2411
|
+
if (active === null) return fail("[E_SESSION_NOT_RUNNING]", `pty session '${displayKey(this.opts.key)}' has no running command (state ${this.state}) — input writes into a command started by exec; it is never an implicit shell command`);
|
|
2412
|
+
if (options.commandId !== void 0 && options.commandId !== active.commandId) return fail("[E_COMMAND_MISMATCH]", `commandId ${JSON.stringify(options.commandId)} does not match the running command ${active.commandId} — input aimed at an earlier prompt is never written to the next command`);
|
|
2413
|
+
const stdin = this.proc?.stdin;
|
|
2414
|
+
if (stdin?.writable !== true) return fail("[E_SESSION_WRITE_FAILED]", `pty session '${displayKey(this.opts.key)}' has no writable stdin channel (state ${this.state}) — follow the running command via job_output for its settled result`);
|
|
2415
|
+
try {
|
|
2416
|
+
stdin.write(options.stdin);
|
|
2417
|
+
} catch (error) {
|
|
2418
|
+
return fail("[E_SESSION_WRITE_FAILED]", `writing stdin to pty session '${displayKey(this.opts.key)}' failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
2419
|
+
}
|
|
2420
|
+
return Promise.resolve({
|
|
2421
|
+
session: displayKey(this.opts.key),
|
|
2422
|
+
commandId: active.commandId,
|
|
2423
|
+
...active.jobId !== void 0 ? { jobId: active.jobId } : {},
|
|
2424
|
+
writtenBytes: Buffer$1.byteLength(options.stdin, "utf8")
|
|
2425
|
+
});
|
|
1792
2426
|
}
|
|
1793
2427
|
/** TTL / row teardown:尽力 exit,1s 后杀组,出池。 */
|
|
1794
2428
|
dispose() {
|
|
1795
2429
|
if (this.disposal) return this.disposal;
|
|
1796
2430
|
this.clearIdleTimer();
|
|
2431
|
+
this.clearDeathTimer();
|
|
1797
2432
|
this.state = "disposed";
|
|
1798
2433
|
this.startPromise = null;
|
|
2434
|
+
this.detachedJob?.interrupt();
|
|
1799
2435
|
const proc = this.proc;
|
|
1800
2436
|
const close = this.procClose;
|
|
1801
2437
|
const group = this.reapGroup(proc?.pid, 1e3, close);
|
|
@@ -1806,7 +2442,7 @@ var PtySession = class {
|
|
|
1806
2442
|
]).then(() => {
|
|
1807
2443
|
if (this.proc === proc) this.proc = null;
|
|
1808
2444
|
});
|
|
1809
|
-
this.write("exit\n");
|
|
2445
|
+
if (this.detachedJob === null) this.write("exit\n");
|
|
1810
2446
|
this.opts.onDead?.();
|
|
1811
2447
|
return this.disposal;
|
|
1812
2448
|
}
|
|
@@ -1818,6 +2454,7 @@ var PtySession = class {
|
|
|
1818
2454
|
}
|
|
1819
2455
|
async start() {
|
|
1820
2456
|
if (this.state === "disposed") throw new Error(`[E_SESSION_DISPOSED] remote pty session '${displayKey(this.opts.key)}' was disposed — the pool replaces disposed sessions; this reference is stale`);
|
|
2457
|
+
this.clearDeathTimer();
|
|
1821
2458
|
if (this.startPromise === null) {
|
|
1822
2459
|
this.state = "starting";
|
|
1823
2460
|
this.startPromise = this.doStart().catch((err) => {
|
|
@@ -1846,6 +2483,9 @@ var PtySession = class {
|
|
|
1846
2483
|
proc.stderr.setEncoding("utf8").on("data", (d) => {
|
|
1847
2484
|
this.diag = (this.diag + d).slice(-2e3);
|
|
1848
2485
|
});
|
|
2486
|
+
proc.stdin.on("error", (err) => {
|
|
2487
|
+
this.diag = (this.diag + `\n[remote: stdin write failed: ${err.message}]`).slice(-2e3);
|
|
2488
|
+
});
|
|
1849
2489
|
this.procClose = new Promise((resolve$1) => {
|
|
1850
2490
|
proc.once("close", () => {
|
|
1851
2491
|
this.markDead();
|
|
@@ -1867,18 +2507,24 @@ var PtySession = class {
|
|
|
1867
2507
|
reject(/* @__PURE__ */ new Error(`[E_SESSION_DIED] remote pty session '${displayKey(this.opts.key)}' died before initializing` + (this.diag.length > 0 ? `; transport stderr tail: ${this.diag}` : "")));
|
|
1868
2508
|
};
|
|
1869
2509
|
this.deathWaiters.push(waiter);
|
|
1870
|
-
const parser = createNonceFrameParser(initNonce, {
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
2510
|
+
const parser = createNonceFrameParser(initNonce, {
|
|
2511
|
+
onEnv: (b64) => {
|
|
2512
|
+
const m = decodeEnvSnapshot(b64);
|
|
2513
|
+
if (m !== void 0) this.envBaseline = m;
|
|
2514
|
+
},
|
|
2515
|
+
onFrame: () => {
|
|
2516
|
+
clearTimeout(timer);
|
|
2517
|
+
this.deathWaiters = this.deathWaiters.filter((w) => w !== waiter);
|
|
2518
|
+
if (this.state === "disposed") {
|
|
2519
|
+
reject(/* @__PURE__ */ new Error(`[E_SESSION_DISPOSED] remote pty session '${displayKey(this.opts.key)}' disposed during init`));
|
|
2520
|
+
return;
|
|
2521
|
+
}
|
|
2522
|
+
this.everReady = true;
|
|
2523
|
+
this.state = "ready";
|
|
2524
|
+
this.resetIdleTimer();
|
|
2525
|
+
resolve$1();
|
|
1876
2526
|
}
|
|
1877
|
-
|
|
1878
|
-
this.state = "ready";
|
|
1879
|
-
this.resetIdleTimer();
|
|
1880
|
-
resolve$1();
|
|
1881
|
-
} });
|
|
2527
|
+
});
|
|
1882
2528
|
this.onChunk = (c) => parser.feed(c);
|
|
1883
2529
|
this.write(buildInitCommand(initNonce));
|
|
1884
2530
|
});
|
|
@@ -1893,6 +2539,7 @@ var PtySession = class {
|
|
|
1893
2539
|
this.state = "dead";
|
|
1894
2540
|
this.startPromise = null;
|
|
1895
2541
|
this.clearIdleTimer();
|
|
2542
|
+
this.armDeathReaper();
|
|
1896
2543
|
const waiters = this.deathWaiters;
|
|
1897
2544
|
this.deathWaiters = [];
|
|
1898
2545
|
for (const w of waiters) w();
|
|
@@ -1900,7 +2547,14 @@ var PtySession = class {
|
|
|
1900
2547
|
resetIdleTimer() {
|
|
1901
2548
|
this.clearIdleTimer();
|
|
1902
2549
|
if (this.state === "disposed") return;
|
|
1903
|
-
this.
|
|
2550
|
+
this.idleSince = Date.now();
|
|
2551
|
+
this.idleTimer = setTimeout(() => {
|
|
2552
|
+
if (this.inFlight > 0) {
|
|
2553
|
+
this.resetIdleTimer();
|
|
2554
|
+
return;
|
|
2555
|
+
}
|
|
2556
|
+
this.dispose();
|
|
2557
|
+
}, this.opts.idleTtlSec * 1e3);
|
|
1904
2558
|
this.idleTimer.unref();
|
|
1905
2559
|
}
|
|
1906
2560
|
clearIdleTimer() {
|
|
@@ -1909,6 +2563,22 @@ var PtySession = class {
|
|
|
1909
2563
|
this.idleTimer = null;
|
|
1910
2564
|
}
|
|
1911
2565
|
}
|
|
2566
|
+
/** 意外死亡后的回收:留池只换取一次 reconnect 机会,不得超过一段 idle TTL(R2 复核 P0)。
|
|
2567
|
+
* 否则死会话永久占 label + 永久计入 10 配额,Agent 再也开不出新会话。 */
|
|
2568
|
+
armDeathReaper() {
|
|
2569
|
+
this.clearDeathTimer();
|
|
2570
|
+
if (!this.everReady || this.state !== "dead") return;
|
|
2571
|
+
this.deathTimer = setTimeout(() => {
|
|
2572
|
+
this.dispose();
|
|
2573
|
+
}, this.opts.idleTtlSec * 1e3);
|
|
2574
|
+
this.deathTimer.unref();
|
|
2575
|
+
}
|
|
2576
|
+
clearDeathTimer() {
|
|
2577
|
+
if (this.deathTimer !== null) {
|
|
2578
|
+
clearTimeout(this.deathTimer);
|
|
2579
|
+
this.deathTimer = null;
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
1912
2582
|
killTree() {
|
|
1913
2583
|
const pid = this.proc?.pid;
|
|
1914
2584
|
this.proc = null;
|
|
@@ -1998,19 +2668,20 @@ var PtyPool = class {
|
|
|
1998
2668
|
const s = this.sessions.get(key);
|
|
1999
2669
|
return s === void 0 || s.sessionState === "disposed" ? void 0 : s;
|
|
2000
2670
|
}
|
|
2001
|
-
|
|
2671
|
+
/** v2:创建一律新建(「同 label 同来源复用」废除——复用只走 get/get by id);disposed 残留由这里替换。 */
|
|
2672
|
+
create(opts) {
|
|
2002
2673
|
if (this.disposed) throw new Error("[E_REMOTE_DISPOSED] remote: the owning Agent or plugin PTY pool was disposed");
|
|
2003
|
-
|
|
2004
|
-
if (
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
onDead
|
|
2011
|
-
}
|
|
2012
|
-
|
|
2013
|
-
|
|
2674
|
+
const existing = this.sessions.get(opts.key);
|
|
2675
|
+
if (existing !== void 0 && existing.sessionState !== "disposed") throw new Error(`[E_INTERNAL] remote: pty pool key collision for ${opts.id}`);
|
|
2676
|
+
const s = new PtySession({
|
|
2677
|
+
...opts,
|
|
2678
|
+
...this.defaults,
|
|
2679
|
+
onDead: () => {
|
|
2680
|
+
this.sessions.delete(opts.key);
|
|
2681
|
+
opts.onDead?.();
|
|
2682
|
+
}
|
|
2683
|
+
});
|
|
2684
|
+
this.sessions.set(opts.key, s);
|
|
2014
2685
|
return s;
|
|
2015
2686
|
}
|
|
2016
2687
|
disposeAll() {
|
|
@@ -2053,6 +2724,202 @@ function resolveTarget(target) {
|
|
|
2053
2724
|
host: raw
|
|
2054
2725
|
};
|
|
2055
2726
|
}
|
|
2727
|
+
const TRANSPORTS = [
|
|
2728
|
+
"ssh",
|
|
2729
|
+
"docker",
|
|
2730
|
+
"incus"
|
|
2731
|
+
];
|
|
2732
|
+
function parseTargetForm(target) {
|
|
2733
|
+
if (target === void 0 || target.length === 0) return { form: "empty" };
|
|
2734
|
+
if (target === "pty") return { form: "pty-selector" };
|
|
2735
|
+
if (target.startsWith("pty:")) {
|
|
2736
|
+
const rest = target.slice(4);
|
|
2737
|
+
if (rest.length === 0 || rest.includes(":")) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — the pty selector takes exactly one id or label ("pty:p-1a2b", "pty:build")`);
|
|
2738
|
+
return {
|
|
2739
|
+
form: "pty-selector",
|
|
2740
|
+
idOrLabel: rest
|
|
2741
|
+
};
|
|
2742
|
+
}
|
|
2743
|
+
if (target === "ssh") return { form: "ssh-prefix" };
|
|
2744
|
+
if (target === "docker" || target === "incus" || target === "hub") throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} is a transport prefix — pass ${target === "hub" ? "hub:<machine>" : `${target}:<name>`}`);
|
|
2745
|
+
if (target.startsWith("hub:")) {
|
|
2746
|
+
const segs = target.slice(4).split(":");
|
|
2747
|
+
if (segs[0] === void 0 || segs[0].length === 0) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — hub takes a machine id`);
|
|
2748
|
+
if (segs.length === 1) return {
|
|
2749
|
+
form: "hub",
|
|
2750
|
+
machine: segs[0]
|
|
2751
|
+
};
|
|
2752
|
+
if (segs.length === 2 && segs[1] === "pty") return {
|
|
2753
|
+
form: "hub-pty",
|
|
2754
|
+
machine: segs[0]
|
|
2755
|
+
};
|
|
2756
|
+
if (segs.length === 3 && segs[1] === "pty") {
|
|
2757
|
+
if (segs[2] === void 0 || segs[2].length === 0) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — empty label after ":pty:"`);
|
|
2758
|
+
return {
|
|
2759
|
+
form: "hub-pty",
|
|
2760
|
+
machine: segs[0],
|
|
2761
|
+
label: segs[2]
|
|
2762
|
+
};
|
|
2763
|
+
}
|
|
2764
|
+
throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — hub PTY is hub:<m4>:pty[:label]`);
|
|
2765
|
+
}
|
|
2766
|
+
for (const transport of TRANSPORTS) {
|
|
2767
|
+
if (!target.startsWith(`${transport}:`)) continue;
|
|
2768
|
+
const rest = target.slice(transport.length + 1);
|
|
2769
|
+
if (rest.length === 0) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — ${transport} takes a name`);
|
|
2770
|
+
const ptyAt = rest.lastIndexOf(":pty");
|
|
2771
|
+
if (ptyAt === -1) return {
|
|
2772
|
+
form: "direct",
|
|
2773
|
+
transport,
|
|
2774
|
+
name: rest
|
|
2775
|
+
};
|
|
2776
|
+
const base = rest.slice(0, ptyAt);
|
|
2777
|
+
if (base.length === 0) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — ":pty" needs a transport target before it ("ssh:pty" is the host named pty)`);
|
|
2778
|
+
const tail = rest.slice(ptyAt + 4);
|
|
2779
|
+
if (tail.startsWith(":")) {
|
|
2780
|
+
if (tail.length === 1) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — empty label after ":pty:"`);
|
|
2781
|
+
return {
|
|
2782
|
+
form: "create-pty",
|
|
2783
|
+
transport,
|
|
2784
|
+
name: base,
|
|
2785
|
+
label: tail.slice(1)
|
|
2786
|
+
};
|
|
2787
|
+
}
|
|
2788
|
+
if (tail.length > 0) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — unexpected ${JSON.stringify(tail)} after ":pty"`);
|
|
2789
|
+
return {
|
|
2790
|
+
form: "create-pty",
|
|
2791
|
+
transport,
|
|
2792
|
+
name: base
|
|
2793
|
+
};
|
|
2794
|
+
}
|
|
2795
|
+
if (target.includes(":")) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: unknown target ${JSON.stringify(target)} — transports are ssh: / docker: / incus: / hub:, the PTY selector is pty:<id|label>, creation appends :pty (roster lists names)`);
|
|
2796
|
+
return {
|
|
2797
|
+
form: "bare",
|
|
2798
|
+
name: target
|
|
2799
|
+
};
|
|
2800
|
+
}
|
|
2801
|
+
|
|
2802
|
+
//#endregion
|
|
2803
|
+
//#region src/remote/labels.ts
|
|
2804
|
+
/** label 字符集(与 BYO ssh label 同源);禁 `pty` 与会话 id 形态(防 selector 歧义)。 */
|
|
2805
|
+
const LABEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
2806
|
+
const PTY_ID_RE = /^pty-[a-z0-9]{4}$/;
|
|
2807
|
+
const RESERVED_LABELS = new Set(["pty"]);
|
|
2808
|
+
function validateLabel(label) {
|
|
2809
|
+
if (!LABEL_RE.test(label)) throw new Error(`[E_BAD_LABEL] remote: label must match ${LABEL_RE.source} (got ${JSON.stringify(label)})`);
|
|
2810
|
+
if (RESERVED_LABELS.has(label) || PTY_ID_RE.test(label)) throw new Error(`[E_BAD_LABEL] remote: ${JSON.stringify(label)} is reserved (session ids are auto-generated; pick a different label)`);
|
|
2811
|
+
}
|
|
2812
|
+
function describeEntry(e) {
|
|
2813
|
+
switch (e.kind) {
|
|
2814
|
+
case "ssh": return `ssh host ${e.name}`;
|
|
2815
|
+
case "ssh-byo": return `a BYO ssh identity (${e.name})`;
|
|
2816
|
+
case "docker": return `docker container ${e.container}`;
|
|
2817
|
+
case "incus": return `incus container ${e.container}`;
|
|
2818
|
+
case "hub": return `hub machine ${e.machine}`;
|
|
2819
|
+
case "pty": return `pty session ${e.id}${e.label !== void 0 ? ` (label ${e.label})` : ""}`;
|
|
2820
|
+
}
|
|
2821
|
+
}
|
|
2822
|
+
/** 机器身份键:同一实体重扫后名字保持稳定(按身份匹配,不按名字)。 */
|
|
2823
|
+
const machineId = (e) => e.kind === "ssh" ? `ssh:${e.host}` : e.kind === "docker" ? `docker:${e.container}` : e.kind === "incus" ? `incus:${e.container}` : e.kind === "hub" ? `hub:${e.machine}` : void 0;
|
|
2824
|
+
const ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
2825
|
+
var LabelPool = class {
|
|
2826
|
+
/** 每 agent session 一个注册表:name → entry(机器 + 认领,到达序)。 */
|
|
2827
|
+
sessions = /* @__PURE__ */ new Map();
|
|
2828
|
+
registry(agent) {
|
|
2829
|
+
let reg = this.sessions.get(agent);
|
|
2830
|
+
if (reg === void 0) {
|
|
2831
|
+
reg = /* @__PURE__ */ new Map();
|
|
2832
|
+
this.sessions.set(agent, reg);
|
|
2833
|
+
}
|
|
2834
|
+
return reg;
|
|
2835
|
+
}
|
|
2836
|
+
resolve(name$1, agent) {
|
|
2837
|
+
return this.sessions.get(agent)?.get(name$1);
|
|
2838
|
+
}
|
|
2839
|
+
/** 显式认领(BYO ssh / PTY label):任何已立名字占用即拒——名字是模型选的,不自动改名。 */
|
|
2840
|
+
claim(name$1, agent, claim) {
|
|
2841
|
+
const reg = this.registry(agent);
|
|
2842
|
+
const existing = reg.get(name$1);
|
|
2843
|
+
if (existing !== void 0) throw new Error(`[E_LABEL_IN_USE] remote: label ${JSON.stringify(name$1)} is already taken by ${describeEntry(existing)} — nothing was run.\n To address it: use the name directly (creation always claims a fresh name — spawn/ssh never adopt)\n` + (existing.kind === "pty" ? ` To free it: close ${existing.id} ({action:"close", target:"pty:${existing.id}"}) — a session that died still holds its label until it is closed or reaped\n` : "") + ` To create new: pick another label`);
|
|
2844
|
+
reg.set(name$1, claim);
|
|
2845
|
+
}
|
|
2846
|
+
/** 生成不撞本 session 的 id(`pty-` PTY 会话 / `ssh-` BYO ssh 身份)。 */
|
|
2847
|
+
freshId(prefix, agent) {
|
|
2848
|
+
const reg = this.registry(agent);
|
|
2849
|
+
for (;;) {
|
|
2850
|
+
let id = prefix;
|
|
2851
|
+
for (let i = 0; i < 4; i++) id += ID_ALPHABET[Math.floor(Math.random() * 36)];
|
|
2852
|
+
if (!reg.has(id)) return id;
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
/**
|
|
2856
|
+
* 现场采集 merge(roster / 裸名 miss 触发):按 ssh → docker → incus → hub 顺序并入。
|
|
2857
|
+
* 已立名字永不挪动:同一实体(身份键相同)保持原槽;新实体撞已立名字 = latecomer,
|
|
2858
|
+
* 自动加 `<transport>-<name>`(再冲突 -2/-3)——无论对方是认领还是更早的机器。
|
|
2859
|
+
* 本轮扫描里消失的机器出表(名字释放);认领永远保留。
|
|
2860
|
+
*/
|
|
2861
|
+
mergeScan(agent, scan) {
|
|
2862
|
+
const reg = this.registry(agent);
|
|
2863
|
+
const renamed = [];
|
|
2864
|
+
const present = /* @__PURE__ */ new Map();
|
|
2865
|
+
for (const [name$1, e] of [...reg]) {
|
|
2866
|
+
const id = machineId(e);
|
|
2867
|
+
if (id === void 0) continue;
|
|
2868
|
+
reg.delete(name$1);
|
|
2869
|
+
present.set(id, e);
|
|
2870
|
+
}
|
|
2871
|
+
const place = (transport, raw, make) => {
|
|
2872
|
+
const id = `${transport}:${raw}`;
|
|
2873
|
+
const known = present.get(id);
|
|
2874
|
+
if (known !== void 0) {
|
|
2875
|
+
reg.set(known.name, known);
|
|
2876
|
+
return;
|
|
2877
|
+
}
|
|
2878
|
+
const fresh = make(raw);
|
|
2879
|
+
if (!reg.has(raw)) {
|
|
2880
|
+
reg.set(raw, fresh);
|
|
2881
|
+
return;
|
|
2882
|
+
}
|
|
2883
|
+
let candidate = `${transport}-${raw}`, n = 2;
|
|
2884
|
+
while (reg.has(candidate)) candidate = `${transport}-${raw}-${n++}`;
|
|
2885
|
+
reg.set(candidate, make(candidate));
|
|
2886
|
+
renamed.push([fresh, candidate]);
|
|
2887
|
+
};
|
|
2888
|
+
for (const host of scan.sshHosts) place("ssh", host, (name$1) => ({
|
|
2889
|
+
kind: "ssh",
|
|
2890
|
+
name: name$1,
|
|
2891
|
+
host
|
|
2892
|
+
}));
|
|
2893
|
+
for (const c of scan.docker) place("docker", c, (name$1) => ({
|
|
2894
|
+
kind: "docker",
|
|
2895
|
+
name: name$1,
|
|
2896
|
+
container: c
|
|
2897
|
+
}));
|
|
2898
|
+
for (const c of scan.incus) place("incus", c, (name$1) => ({
|
|
2899
|
+
kind: "incus",
|
|
2900
|
+
name: name$1,
|
|
2901
|
+
container: c
|
|
2902
|
+
}));
|
|
2903
|
+
for (const m of scan.hub) place("hub", m, (name$1) => ({
|
|
2904
|
+
kind: "hub",
|
|
2905
|
+
name: name$1,
|
|
2906
|
+
machine: m
|
|
2907
|
+
}));
|
|
2908
|
+
return { renamed };
|
|
2909
|
+
}
|
|
2910
|
+
/** 认领释放(会话 dispose/TTL;BYO 身份随 session 存亡);幂等。 */
|
|
2911
|
+
release(name$1, agent) {
|
|
2912
|
+
this.sessions.get(agent)?.delete(name$1);
|
|
2913
|
+
}
|
|
2914
|
+
/** roster 面:本 session 的全部条目(机器 + 认领,插入序)。 */
|
|
2915
|
+
list(agent) {
|
|
2916
|
+
return [...this.sessions.get(agent)?.values() ?? []];
|
|
2917
|
+
}
|
|
2918
|
+
/** driver dispose:全部 session 注册表清空。 */
|
|
2919
|
+
clear() {
|
|
2920
|
+
this.sessions.clear();
|
|
2921
|
+
}
|
|
2922
|
+
};
|
|
2056
2923
|
|
|
2057
2924
|
//#endregion
|
|
2058
2925
|
//#region src/remote/status.ts
|
|
@@ -2128,21 +2995,11 @@ function renderProbe(p) {
|
|
|
2128
2995
|
case "container": return `probe: container ${p.status} (just now, on demand)`;
|
|
2129
2996
|
}
|
|
2130
2997
|
}
|
|
2131
|
-
/**
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
function renderSession(s) {
|
|
2137
|
-
if (s === void 0 || s.state === "cold" || s.state === "starting" || s.state === "disposed") return "session: none — dials on first exec";
|
|
2138
|
-
if (s.state === "dead") return "session: died — next exec cold-starts a fresh shell";
|
|
2139
|
-
if (s.busy) return "session: busy (a command is running)";
|
|
2140
|
-
return `session: idle ${Math.round((s.idleMs ?? 0) / 1e3)}s (connected)`;
|
|
2141
|
-
}
|
|
2142
|
-
/** PTY 会话状态行(BYO-PTY 面):无会话 = 这个 label 下没有活会话,且**不会自建**——
|
|
2143
|
-
* 与 transport target 的 "dials on first exec" 是两回事,故不复用那句。 */
|
|
2144
|
-
function renderPtySession(s) {
|
|
2145
|
-
return s === void 0 ? "session: none — no live PTY under this label" : renderSession(s);
|
|
2998
|
+
/** session card(§5.5,`pty:<id|label>` 无 cmd):connection/state/cwd/ttl 由调用方拼头行,这里渲染账本。 */
|
|
2999
|
+
function renderLedger(ledger) {
|
|
3000
|
+
if (ledger.length === 0) return "ledger: empty — no command has run in this session yet";
|
|
3001
|
+
const rows = [...ledger].reverse().map((e) => ` ${e.commandId}${e.jobId !== void 0 && e.jobId !== e.commandId ? ` (job ${e.jobId})` : ""} · ${e.running ? "running" : `exit ${e.exit}`}${e.running ? "" : ` · ${(e.durationMs / 1e3).toFixed(1)}s`} · ${e.summary}`);
|
|
3002
|
+
return `ledger (last ${ledger.length}):\n${rows.join("\n")}`;
|
|
2146
3003
|
}
|
|
2147
3004
|
|
|
2148
3005
|
//#endregion
|
|
@@ -2234,22 +3091,24 @@ function literalHosts(text) {
|
|
|
2234
3091
|
wildcardBlocks
|
|
2235
3092
|
};
|
|
2236
3093
|
}
|
|
2237
|
-
/**
|
|
2238
|
-
|
|
2239
|
-
* renders its native error (honest vocabulary: never invent, never hide).
|
|
2240
|
-
*/
|
|
2241
|
-
async function renderRoster(sessions, opts = {}) {
|
|
3094
|
+
/** 三段本地扫描(各自独立降级,错误如实带回给 roster 呈现)。 */
|
|
3095
|
+
async function scanLocal(opts = {}) {
|
|
2242
3096
|
const runner = opts.runner ?? runOneShot;
|
|
2243
3097
|
const readSshConfig = opts.readSshConfig ?? (async () => await readFile(join(homedir(), ".ssh", "config"), "utf8"));
|
|
2244
3098
|
const hard = opts.hardTimeoutSec ?? 10;
|
|
2245
|
-
|
|
3099
|
+
let ssh = {
|
|
3100
|
+
hosts: [],
|
|
3101
|
+
wildcardBlocks: 0
|
|
3102
|
+
};
|
|
2246
3103
|
try {
|
|
2247
|
-
|
|
2248
|
-
lines.push(`ssh hosts (~/.ssh/config): ${hosts.length > 0 ? hosts.join(", ") : "(none)"}${wildcardBlocks > 0 ? ` (+${wildcardBlocks} wildcard default blocks, not listed)` : ""}`);
|
|
3104
|
+
ssh = literalHosts(await readSshConfig());
|
|
2249
3105
|
} catch (error) {
|
|
2250
|
-
|
|
3106
|
+
ssh = {
|
|
3107
|
+
hosts: [],
|
|
3108
|
+
wildcardBlocks: 0,
|
|
3109
|
+
error: error instanceof Error ? error.message : String(error)
|
|
3110
|
+
};
|
|
2251
3111
|
}
|
|
2252
|
-
lines.push(`byossh labels (this Agent, in memory): ${opts.byosshLabels?.map((label) => `byossh:${label}`).join(", ") || "(none)"}`);
|
|
2253
3112
|
const docker = await runner([
|
|
2254
3113
|
"docker",
|
|
2255
3114
|
"ps",
|
|
@@ -2257,13 +3116,6 @@ async function renderRoster(sessions, opts = {}) {
|
|
|
2257
3116
|
"--format",
|
|
2258
3117
|
"{{.Names}} {{.State}}"
|
|
2259
3118
|
], { timeoutSec: hard });
|
|
2260
|
-
if (docker.exit === 0) {
|
|
2261
|
-
const rows = docker.stdout.trim().split(/\r?\n/).filter(Boolean).map((l) => {
|
|
2262
|
-
const [name$1, state] = l.split(" ");
|
|
2263
|
-
return `${name$1}${state !== void 0 && state !== "" ? ` (${state})` : ""}`;
|
|
2264
|
-
});
|
|
2265
|
-
lines.push(`docker containers: ${rows.length > 0 ? rows.join(", ") : "(none)"}`);
|
|
2266
|
-
} else lines.push(`docker containers: unavailable — ${docker.timedOut ? `scan timed out after ${hard}s` : oneLine(docker.stderr) || `docker exited ${docker.exit}`}`);
|
|
2267
3119
|
const incus = await runner([
|
|
2268
3120
|
"incus",
|
|
2269
3121
|
"list",
|
|
@@ -2272,35 +3124,97 @@ async function renderRoster(sessions, opts = {}) {
|
|
|
2272
3124
|
"--columns",
|
|
2273
3125
|
"ns"
|
|
2274
3126
|
], { timeoutSec: hard });
|
|
2275
|
-
|
|
2276
|
-
|
|
3127
|
+
return {
|
|
3128
|
+
ssh,
|
|
3129
|
+
docker: docker.exit === 0 ? { rows: docker.stdout.trim().split(/\r?\n/).filter(Boolean).map((l) => {
|
|
3130
|
+
const [name$1, state] = l.split(" ");
|
|
3131
|
+
return {
|
|
3132
|
+
name: (name$1 ?? "").trim(),
|
|
3133
|
+
state: (state ?? "").trim()
|
|
3134
|
+
};
|
|
3135
|
+
}).filter((r) => r.name.length > 0) } : {
|
|
3136
|
+
rows: [],
|
|
3137
|
+
error: oneLine(docker.stderr) || `docker exited ${docker.exit}`,
|
|
3138
|
+
...docker.timedOut ? { timedOut: true } : {}
|
|
3139
|
+
},
|
|
3140
|
+
incus: incus.exit === 0 ? { rows: incus.stdout.trim().split(/\r?\n/).filter(Boolean).map((l) => {
|
|
2277
3141
|
const [name$1, state] = l.split(",");
|
|
2278
|
-
return
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
3142
|
+
return {
|
|
3143
|
+
name: (name$1 ?? "").trim(),
|
|
3144
|
+
state: (state ?? "").trim()
|
|
3145
|
+
};
|
|
3146
|
+
}).filter((r) => r.name.length > 0) } : {
|
|
3147
|
+
rows: [],
|
|
3148
|
+
error: oneLine(incus.stderr) || `incus exited ${incus.exit}`,
|
|
3149
|
+
...incus.timedOut ? { timedOut: true } : {}
|
|
3150
|
+
}
|
|
3151
|
+
};
|
|
3152
|
+
}
|
|
3153
|
+
/** 统一池视图的 roster 呈现:机器三段 + BYO ssh 同位(built on)+ pty 会话段(caller-scoped)。 */
|
|
3154
|
+
function renderRoster(scan, entries, sessions, hubTargets) {
|
|
3155
|
+
const lines = [];
|
|
3156
|
+
if (hubTargets !== null) lines.push(`hub machines: ${hubTargets.map((t) => `hub:${t.id} (${t.label}${t.execEnabled ? "" : "; exec disabled"})`).join(", ") || "none"}`);
|
|
3157
|
+
if (scan.ssh.error !== void 0) lines.push(`ssh hosts: no readable ~/.ssh/config (${scan.ssh.error})`);
|
|
3158
|
+
else {
|
|
3159
|
+
const sshNames = entries.filter((e) => e.kind === "ssh").map((e) => e.name);
|
|
3160
|
+
const byoNames = entries.filter((e) => e.kind === "ssh-byo").map((e) => `${e.name} (built on)`);
|
|
3161
|
+
const all = [...sshNames, ...byoNames];
|
|
3162
|
+
lines.push(`ssh hosts (~/.ssh/config + registered): ${all.length > 0 ? all.join(", ") : "(none)"}${scan.ssh.wildcardBlocks > 0 ? ` (+${scan.ssh.wildcardBlocks} wildcard default blocks, not listed)` : ""}`);
|
|
3163
|
+
}
|
|
3164
|
+
const dockerStates = new Map(scan.docker.rows.map((r) => [r.name, r.state]));
|
|
3165
|
+
const dockerEntries = entries.filter((e) => e.kind === "docker");
|
|
3166
|
+
if (scan.docker.error !== void 0) lines.push(`docker containers: unavailable — ${scan.docker.timedOut ? `scan timed out` : scan.docker.error}`);
|
|
3167
|
+
else lines.push(`docker containers: ${dockerEntries.length > 0 ? dockerEntries.map((e) => e.kind === "docker" && `${e.name}${e.name !== e.container ? ` (= docker:${e.container}${dockerStates.get(e.container) ? `, ${dockerStates.get(e.container)}` : ""})` : dockerStates.get(e.container) !== void 0 && dockerStates.get(e.container) !== "" ? ` (${dockerStates.get(e.container)})` : ""}`).join(", ") : "(none)"}`);
|
|
3168
|
+
const incusStates = new Map(scan.incus.rows.map((r) => [r.name, r.state]));
|
|
3169
|
+
const incusEntries = entries.filter((e) => e.kind === "incus");
|
|
3170
|
+
if (scan.incus.error !== void 0) lines.push(`incus containers: unavailable — ${scan.incus.timedOut ? `scan timed out` : scan.incus.error}`);
|
|
3171
|
+
else lines.push(`incus containers: ${incusEntries.length > 0 ? incusEntries.map((e) => e.kind === "incus" && `${e.name}${e.name !== e.container ? ` (= incus:${e.container}${incusStates.get(e.container) ? `, ${incusStates.get(e.container)}` : ""})` : incusStates.get(e.container) !== void 0 && incusStates.get(e.container) !== "" ? ` (${incusStates.get(e.container)})` : ""}`).join(", ") : "(none)"}`);
|
|
3172
|
+
lines.push(sessions.length > 0 ? `pty sessions: ${sessions.map((s) => {
|
|
3173
|
+
const id = s.identity;
|
|
3174
|
+
const snap = s.snapshot;
|
|
3175
|
+
const state = snap.busy ? "busy" : snap.state === "dead" ? "died" : `idle ${Math.round((snap.idleMs ?? 0) / 1e3)}s`;
|
|
3176
|
+
return `pty:${id.id}${id.label !== void 0 ? ` (label ${id.label})` : ""} ${id.connection}${id.byo ? " (byo-pty)" : ""} [${state}]`;
|
|
3177
|
+
}).join(" · ")}` : "pty sessions: none");
|
|
2283
3178
|
return lines.join("\n");
|
|
2284
3179
|
}
|
|
2285
3180
|
|
|
2286
3181
|
//#endregion
|
|
2287
3182
|
//#region src/remote/driver.ts
|
|
2288
|
-
/**
|
|
2289
|
-
const
|
|
2290
|
-
/**
|
|
3183
|
+
/** R1:idle TTL 15 min——idle 随活动重置,在用会话永不超时(PtySession 双条件)。 */
|
|
3184
|
+
const REMOTE_PTY_IDLE_TTL_SEC = 900;
|
|
3185
|
+
/** P3(user 2026-10-19):每 agent 10 个 PTY 会话,跨所有 connection 统一计;仅 error message 披露。 */
|
|
3186
|
+
const REMOTE_PTY_SESSION_LIMIT = 10;
|
|
3187
|
+
/** hub 线 one-shot 监督披露(0.3.2-c):对端 = 我们自己的 hub server(bash -lc 于独立进程组,
|
|
3188
|
+
* Node 原生 TERM→2s→KILL + 输出环 + 租约生命周期);superd-run helper 是 dumb-pipe 专用物,
|
|
3189
|
+
* 从不经 hub 上传(non-goal,docs/10_plans/2026-10-25-hub-remote-parity.md §3 O1/O8)。 */
|
|
3190
|
+
const HUB_RUNNER = "hub-lease (peer bash -lc, peer Node supervision)";
|
|
3191
|
+
/** hub PTY 泵资产:pump 与本模块同目录(npm 包与 Super 闭包同构,helper.ts 同款纪律)。
|
|
3192
|
+
* ws 模块路径由 transport 侧(superd-hub 上下文,分叉的 proven 解析链)解析后经
|
|
3193
|
+
* ptyEndpoint 传入——闭包自身子树无可解析的 ws,按名解析不在闭包里做(0.3.2-c 定稿)。 */
|
|
3194
|
+
function hubPtyAssets() {
|
|
3195
|
+
return { pumpPath: join(dirname(fileURLToPath(import.meta.url)), "hub-pty-pump.mjs") };
|
|
3196
|
+
}
|
|
3197
|
+
/** 账本键与 jobId 同构(同格式 `<kind>-<16hex>`);background 通道预传入 registry id 时两者字面相等。 */
|
|
3198
|
+
const genCommandId = () => `remote-${randomUUID().replace(/-/g, "").slice(0, 16)}`;
|
|
3199
|
+
/** 双轨调度器:参数校验 → 目标语法(parseTargetForm)→ 统一 label 池 → oneshot 子进程 / pty 会话池。 */
|
|
2291
3200
|
var RemoteDriver = class {
|
|
2292
|
-
sshTargets = new SshTargets();
|
|
2293
3201
|
pool;
|
|
3202
|
+
labels = new LabelPool();
|
|
2294
3203
|
hubOwner = randomUUID();
|
|
2295
3204
|
hubProviders = /* @__PURE__ */ new Set();
|
|
2296
3205
|
processes = /* @__PURE__ */ new Set();
|
|
2297
3206
|
starting = /* @__PURE__ */ new Set();
|
|
2298
3207
|
fileAbort = new AbortController();
|
|
2299
3208
|
disposed = false;
|
|
3209
|
+
/** undefined = 未尝试;null = 资产缺失(shim-only);registry = 每 target sticky 状态机。 */
|
|
3210
|
+
helpers;
|
|
3211
|
+
runnerOf = /* @__PURE__ */ new WeakMap();
|
|
2300
3212
|
disposal;
|
|
3213
|
+
ptyIdleTtlSec;
|
|
2301
3214
|
constructor(opts = {}) {
|
|
2302
3215
|
this.opts = opts;
|
|
2303
|
-
this.
|
|
3216
|
+
this.ptyIdleTtlSec = opts.idleTtlSec ?? REMOTE_PTY_IDLE_TTL_SEC;
|
|
3217
|
+
this.pool = new PtyPool({ idleTtlSec: this.ptyIdleTtlSec });
|
|
2304
3218
|
}
|
|
2305
3219
|
async call(params, callCtx = {}) {
|
|
2306
3220
|
const started = Date.now();
|
|
@@ -2308,10 +3222,11 @@ var RemoteDriver = class {
|
|
|
2308
3222
|
this.assertOpen();
|
|
2309
3223
|
const prepared = await prepareRemoteInput(params);
|
|
2310
3224
|
this.assertOpen();
|
|
2311
|
-
const
|
|
2312
|
-
|
|
3225
|
+
const form = parseTargetForm(prepared.target);
|
|
3226
|
+
this.validate(form, prepared);
|
|
3227
|
+
const result = await this.execute(prepared, form, callCtx);
|
|
2313
3228
|
this.audit({
|
|
2314
|
-
target:
|
|
3229
|
+
target: result.target,
|
|
2315
3230
|
cmd: prepared.cmd,
|
|
2316
3231
|
cwd: result.cwd ?? void 0,
|
|
2317
3232
|
exit: result.exit,
|
|
@@ -2328,10 +3243,107 @@ var RemoteDriver = class {
|
|
|
2328
3243
|
throw error;
|
|
2329
3244
|
}
|
|
2330
3245
|
}
|
|
2331
|
-
/**
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
3246
|
+
/** 参数互斥矩阵(§2):spawn/ssh 是 BYO 入口(参数在场即 BYO),只与对应形态的 target 配对。 */
|
|
3247
|
+
validate(form, params) {
|
|
3248
|
+
if (params.timeout !== void 0 && (!Number.isFinite(params.timeout) || params.timeout <= 0)) throw new Error(`[E_BAD_TIMEOUT] remote: timeout must be a positive number of seconds (got ${JSON.stringify(params.timeout)})`);
|
|
3249
|
+
if (params.stdin !== void 0 && (params.cmd === void 0 || params.cmd.length === 0)) throw new Error("[E_STDIN_WITHOUT_CMD] remote: stdin requires cmd");
|
|
3250
|
+
const hasSpawn = params.spawn !== void 0 && params.spawn.length > 0;
|
|
3251
|
+
const hasSsh = params.ssh !== void 0;
|
|
3252
|
+
if (hasSpawn && hasSsh) throw new Error("[E_PARAMS] remote: spawn and ssh are two different BYO entry points — pass one, not both");
|
|
3253
|
+
const ptyForm = form.form === "pty-selector" || form.form === "empty" || form.form === "bare";
|
|
3254
|
+
const sshForm = form.form === "ssh-prefix" || form.form === "empty" || form.form === "bare" || form.form === "direct" && form.transport === "ssh" || form.form === "create-pty" && form.transport === "ssh";
|
|
3255
|
+
if (hasSpawn && !ptyForm) throw new Error("[E_PARAMS] remote: spawn pairs only with a pty target (pty, pty:<label>, or a bare label) — machines are dialed, not spawned");
|
|
3256
|
+
if (hasSsh && !sshForm) throw new Error("[E_PARAMS] remote: ssh registration pairs with ssh-form targets only (ssh, ssh:<label>, ssh:<label>:pty, a bare label, or no target)");
|
|
3257
|
+
}
|
|
3258
|
+
async execute(params, form, callCtx) {
|
|
3259
|
+
const timeoutSec = params.timeout ?? this.opts.execTimeoutSec ?? 120;
|
|
3260
|
+
const cap = this.opts.maxOutputChars ?? 3e4;
|
|
3261
|
+
const sessionKey = callCtx.sessionKey ?? "no-session";
|
|
3262
|
+
const hasCmd = params.cmd !== void 0 && params.cmd.length > 0;
|
|
3263
|
+
params.spawn !== void 0 && params.spawn.length;
|
|
3264
|
+
if (form.form === "hub") {
|
|
3265
|
+
const hub = this.requireHub();
|
|
3266
|
+
this.hubProviders.add(hub);
|
|
3267
|
+
const process$1 = this.own(await hub.start(form.machine, {
|
|
3268
|
+
...params,
|
|
3269
|
+
target: `hub:${form.machine}`,
|
|
3270
|
+
mode: "oneshot",
|
|
3271
|
+
timeout: timeoutSec
|
|
3272
|
+
}, this.hubOwner));
|
|
3273
|
+
if (this.disposed) process$1.cancel("owner disposed");
|
|
3274
|
+
const result = await process$1.done;
|
|
3275
|
+
const stdout = process$1.read("stdout", 0), stderr = process$1.read("stderr", 0);
|
|
3276
|
+
const out = tailWindow(stdout.text, cap, stdout.stats);
|
|
3277
|
+
const err = tailWindow(stderr.text, cap, stderr.stats);
|
|
3278
|
+
return {
|
|
3279
|
+
...result,
|
|
3280
|
+
mode: "oneshot",
|
|
3281
|
+
target: `hub:${form.machine}`,
|
|
3282
|
+
connection: `hub:${form.machine}`,
|
|
3283
|
+
cwd: null,
|
|
3284
|
+
reconnected: false,
|
|
3285
|
+
runner: HUB_RUNNER,
|
|
3286
|
+
stdout: (!stdout.stats && stdout.lossy ? "[truncated: peer returned only a tail; exact total/retained/dropped unavailable]\n" : "") + out.text,
|
|
3287
|
+
stderr: [err.text, stderr.diagnostic].filter(Boolean).join("\n"),
|
|
3288
|
+
...out.stats ? { outputStats: {
|
|
3289
|
+
stdout: out.stats,
|
|
3290
|
+
stderr: err.stats
|
|
3291
|
+
} } : { outputStatsUnavailable: true },
|
|
3292
|
+
...out.truncated === void 0 ? {} : { truncated: out.truncated }
|
|
3293
|
+
};
|
|
3294
|
+
}
|
|
3295
|
+
const lane = this.createPtyLane(params, form, sessionKey);
|
|
3296
|
+
if (lane !== void 0) {
|
|
3297
|
+
const session = lane.session;
|
|
3298
|
+
if (!hasCmd) {
|
|
3299
|
+
await session.warm();
|
|
3300
|
+
return this.warmReceipt(session);
|
|
3301
|
+
}
|
|
3302
|
+
return await this.dispatchPty(session, params, callCtx, timeoutSec, cap);
|
|
3303
|
+
}
|
|
3304
|
+
if (params.ssh !== void 0) {
|
|
3305
|
+
const label = form.form === "direct" || form.form === "bare" ? form.name : void 0;
|
|
3306
|
+
const name$1 = this.registerByoSsh(label, params.ssh, sessionKey);
|
|
3307
|
+
if (!hasCmd) return {
|
|
3308
|
+
mode: "oneshot",
|
|
3309
|
+
target: `ssh:${name$1}`,
|
|
3310
|
+
connection: `ssh:${name$1}`,
|
|
3311
|
+
byoTag: "byo-ssh",
|
|
3312
|
+
exit: null,
|
|
3313
|
+
cwd: null,
|
|
3314
|
+
timedOut: false,
|
|
3315
|
+
reconnected: false,
|
|
3316
|
+
stdout: `ssh:${name$1} registered (byo-ssh, no dialing). Reuse the label anywhere ssh: aliases work; a new Agent registers again.`,
|
|
3317
|
+
durationMs: 0
|
|
3318
|
+
};
|
|
3319
|
+
return await this.oneshot({
|
|
3320
|
+
kind: "ssh",
|
|
3321
|
+
host: normalizeSshConnection(params.ssh).host,
|
|
3322
|
+
connection: normalizeSshConnection(params.ssh)
|
|
3323
|
+
}, `ssh:${name$1}`, params, timeoutSec, cap);
|
|
3324
|
+
}
|
|
3325
|
+
if (form.form === "pty-selector" && form.idOrLabel === void 0) throw new Error("[E_PARAMS] remote: \"pty\" alone selects nothing — append an id/label (pty:pty-1a2b, pty:build) or pass spawn to create one");
|
|
3326
|
+
if (form.form === "pty-selector") {
|
|
3327
|
+
const session = this.resolvePty(form.idOrLabel, sessionKey);
|
|
3328
|
+
if (!hasCmd) return this.cardReceipt(session);
|
|
3329
|
+
return await this.dispatchPty(session, params, callCtx, timeoutSec, cap);
|
|
3330
|
+
}
|
|
3331
|
+
if (form.form === "direct") {
|
|
3332
|
+
const plan$1 = form.transport === "ssh" ? this.sshPlanFor(form.name, sessionKey) : resolveTarget(`${form.transport}:${form.name}`);
|
|
3333
|
+
return await this.oneshot(plan$1, `${form.transport}:${form.name}`, params, timeoutSec, cap);
|
|
3334
|
+
}
|
|
3335
|
+
if (form.form !== "bare") throw new Error("[E_INTERNAL] remote: unreachable target form after routing");
|
|
3336
|
+
const entry = await this.resolvePoolEntry(form.name, sessionKey);
|
|
3337
|
+
if (entry.kind === "pty") {
|
|
3338
|
+
const session = this.resolvePty(form.name, sessionKey);
|
|
3339
|
+
if (!hasCmd) return this.cardReceipt(session);
|
|
3340
|
+
return await this.dispatchPty(session, params, callCtx, timeoutSec, cap);
|
|
3341
|
+
}
|
|
3342
|
+
if (entry.kind === "hub") return await this.hubOneshot(entry.machine, `hub:${entry.machine}`, params, timeoutSec, cap);
|
|
3343
|
+
const plan = this.planOf(entry);
|
|
3344
|
+
return await this.oneshot(plan, form.name, params, timeoutSec, cap);
|
|
3345
|
+
}
|
|
3346
|
+
/** Native-first copy routing (spec: remote-native-shortcut) — unchanged by the workbench round. */
|
|
2335
3347
|
copy(request, signal, callCtx = {}) {
|
|
2336
3348
|
const combined = AbortSignal.any([signal, this.fileAbort.signal]);
|
|
2337
3349
|
const work = (async () => {
|
|
@@ -2403,13 +3415,18 @@ var RemoteDriver = class {
|
|
|
2403
3415
|
path: dst.path,
|
|
2404
3416
|
endpoint: localFileEndpoint()
|
|
2405
3417
|
}, combined);
|
|
2406
|
-
if (request.verify !== void 0
|
|
3418
|
+
if (request.verify !== void 0) throw new Error("copy: verify is a Hub/local staged lane option (independent SHA-256); native routes report exit-code-only verification — self-verify via oneshot digest commands when needed");
|
|
2407
3419
|
const planOf = (end) => end.kind === "cli" ? end.plan : end.kind === "local" ? { kind: "local" } : void 0;
|
|
2408
3420
|
const srcPlan = planOf(src), dstPlan = planOf(dst);
|
|
2409
3421
|
if (srcPlan === void 0 || dstPlan === void 0) throw new Error("copy: unreachable route resolution");
|
|
3422
|
+
const execArgvFor = (plan, script) => {
|
|
3423
|
+
const argv = helperShellArgv(plan, script);
|
|
3424
|
+
return this.opts.nativeArgvFor ? this.opts.nativeArgvFor(argv) : argv;
|
|
3425
|
+
};
|
|
2410
3426
|
return nativeCopy({
|
|
2411
3427
|
src: request.src,
|
|
2412
3428
|
dst: request.dst,
|
|
3429
|
+
...request.mkdir === void 0 ? {} : { mkdir: request.mkdir },
|
|
2413
3430
|
...request.argv === void 0 ? {} : { argv: request.argv },
|
|
2414
3431
|
...request.pullArgv === void 0 ? {} : { pullArgv: request.pullArgv },
|
|
2415
3432
|
...request.pushArgv === void 0 ? {} : { pushArgv: request.pushArgv }
|
|
@@ -2422,7 +3439,10 @@ var RemoteDriver = class {
|
|
|
2422
3439
|
plan: dstPlan,
|
|
2423
3440
|
path: dst.path
|
|
2424
3441
|
}
|
|
2425
|
-
}, combined, {
|
|
3442
|
+
}, combined, {
|
|
3443
|
+
wrapArgv: this.opts.nativeArgvFor,
|
|
3444
|
+
execArgvFor
|
|
3445
|
+
});
|
|
2426
3446
|
})();
|
|
2427
3447
|
this.starting.add(work);
|
|
2428
3448
|
work.then(() => this.starting.delete(work), () => this.starting.delete(work));
|
|
@@ -2436,7 +3456,8 @@ var RemoteDriver = class {
|
|
|
2436
3456
|
const endpoint = async (value) => {
|
|
2437
3457
|
const parsed = parseFileEndpoint(value);
|
|
2438
3458
|
if (!parsed.target) return { path: parsed.path };
|
|
2439
|
-
|
|
3459
|
+
const form = parseTargetForm(parsed.target);
|
|
3460
|
+
if (form.form === "hub" || form.form === "hub-pty" || form.form === "pty-selector") throw new Error("rsync supports SSH endpoints only (plus one local endpoint); no mixed-transport or copy fallback");
|
|
2440
3461
|
const plan = await this.resolveConnectionTarget(parsed.target, callCtx);
|
|
2441
3462
|
this.assertOpen();
|
|
2442
3463
|
combined.throwIfAborted();
|
|
@@ -2456,45 +3477,66 @@ var RemoteDriver = class {
|
|
|
2456
3477
|
return work;
|
|
2457
3478
|
}
|
|
2458
3479
|
/** Only called from JobSpec.run: admission precedes local file reads and discovery. */
|
|
2459
|
-
start(input, signal) {
|
|
2460
|
-
const work = this.startPrepared(input, AbortSignal.any([signal, this.fileAbort.signal]));
|
|
3480
|
+
start(input, signal, callCtx = {}) {
|
|
3481
|
+
const work = this.startPrepared(input, AbortSignal.any([signal, this.fileAbort.signal]), callCtx);
|
|
2461
3482
|
this.starting.add(work);
|
|
2462
3483
|
work.then(() => this.starting.delete(work), () => this.starting.delete(work));
|
|
2463
3484
|
return work;
|
|
2464
3485
|
}
|
|
2465
|
-
async startPrepared(input, signal) {
|
|
3486
|
+
async startPrepared(input, signal, callCtx = {}) {
|
|
2466
3487
|
this.assertOpen();
|
|
2467
3488
|
signal.throwIfAborted();
|
|
2468
3489
|
const params = await prepareRemoteInput(input);
|
|
2469
3490
|
this.assertOpen();
|
|
2470
3491
|
signal.throwIfAborted();
|
|
2471
|
-
const
|
|
2472
|
-
|
|
3492
|
+
const form = parseTargetForm(params.target);
|
|
3493
|
+
this.validate(form, params);
|
|
3494
|
+
if (form.form !== "direct" && form.form !== "bare" && form.form !== "hub") throw new Error("remote: background oneshot takes a machine target; PTY lanes go through the pty job channel");
|
|
3495
|
+
if (params.ssh !== void 0 && (form.form === "direct" || form.form === "bare") && form.transport !== "docker" && form.transport !== "incus") this.registerByoSsh(form.name, params.ssh, callCtx.sessionKey ?? "no-session");
|
|
2473
3496
|
let process$1;
|
|
2474
|
-
if (
|
|
2475
|
-
|
|
2476
|
-
this.
|
|
2477
|
-
process$1 = await hub.start(route.display.slice(4), {
|
|
2478
|
-
...params,
|
|
2479
|
-
mode: "oneshot"
|
|
2480
|
-
}, this.hubOwner);
|
|
2481
|
-
} else {
|
|
2482
|
-
const plan = route.plan ?? await this.resolveBareName(route.bare, "no-session", false);
|
|
3497
|
+
if (form.form === "hub") process$1 = await this.hubOneshotProcess(form.machine, params);
|
|
3498
|
+
else if (form.form === "direct") {
|
|
3499
|
+
const plan = form.transport === "ssh" ? this.sshPlanFor(form.name, callCtx.sessionKey ?? "no-session") : resolveTarget(`${form.transport}:${form.name}`);
|
|
2483
3500
|
this.assertOpen();
|
|
2484
3501
|
signal.throwIfAborted();
|
|
2485
|
-
if (plan.kind === "pty") throw new Error("remote: background requires oneshot");
|
|
2486
3502
|
process$1 = await this.nativeProcess(plan, params, params.timeout, signal);
|
|
2487
|
-
}
|
|
3503
|
+
} else if (form.form === "bare") {
|
|
3504
|
+
const entry = await this.resolvePoolEntry(form.name, callCtx.sessionKey ?? "no-session");
|
|
3505
|
+
this.assertOpen();
|
|
3506
|
+
signal.throwIfAborted();
|
|
3507
|
+
if (entry.kind === "pty" || entry.kind === "hub") throw new Error("remote: background requires an ssh/docker/incus target");
|
|
3508
|
+
process$1 = await this.nativeProcess(this.planOf(entry), params, params.timeout, signal);
|
|
3509
|
+
} else throw new Error("remote: background oneshot takes a machine target");
|
|
2488
3510
|
this.own(process$1);
|
|
2489
3511
|
if (signal.aborted || this.disposed) process$1.cancel("owner closed during start");
|
|
2490
3512
|
return process$1;
|
|
2491
3513
|
}
|
|
2492
|
-
nativeProcess(plan, params, timeoutSec, signal = this.fileAbort.signal) {
|
|
3514
|
+
async nativeProcess(plan, params, timeoutSec, signal = this.fileAbort.signal) {
|
|
2493
3515
|
const cleanupTag = randomUUID().slice(0, 8);
|
|
3516
|
+
const helper = await this.ensureHelper(plan);
|
|
3517
|
+
if (helper !== null && !this.disposed) {
|
|
3518
|
+
const process$2 = startOneShot(buildHelperOneShotArgv(plan, helper.binPath, {
|
|
3519
|
+
tag: cleanupTag,
|
|
3520
|
+
cmd: params.cmd
|
|
3521
|
+
}), {
|
|
3522
|
+
stdin: params.stdin,
|
|
3523
|
+
timeoutSec
|
|
3524
|
+
});
|
|
3525
|
+
this.runnerOf.set(process$2, `superd-run ${helper.ver} (${helper.triple})`);
|
|
3526
|
+
process$2.done.then((result) => {
|
|
3527
|
+
if (!result.cancelled && !result.timedOut) return;
|
|
3528
|
+
startOneShot(buildHelperKillgroupArgv(plan, helper.binPath, cleanupTag), { timeoutSec: 15 }).done.catch(() => {});
|
|
3529
|
+
}).catch(() => {});
|
|
3530
|
+
const tracked = Promise.resolve(process$2);
|
|
3531
|
+
this.starting.add(tracked);
|
|
3532
|
+
tracked.then(() => this.starting.delete(tracked), () => this.starting.delete(tracked));
|
|
3533
|
+
return tracked;
|
|
3534
|
+
}
|
|
2494
3535
|
const process$1 = startOneShot((this.opts.oneshotArgvFor ?? buildOneShotArgv)(plan, params.cmd, { cleanupTag }), {
|
|
2495
3536
|
stdin: params.stdin,
|
|
2496
3537
|
timeoutSec
|
|
2497
3538
|
});
|
|
3539
|
+
this.runnerOf.set(process$1, "posix-shim");
|
|
2498
3540
|
process$1.done.then((result) => {
|
|
2499
3541
|
if (!result.cancelled && !result.timedOut) return;
|
|
2500
3542
|
const pidfile = `"\${TMPDIR:-/tmp}/superd-oneshot-${cleanupTag}.pgid"`;
|
|
@@ -2506,296 +3548,395 @@ var RemoteDriver = class {
|
|
|
2506
3548
|
work.then(() => this.starting.delete(work), () => this.starting.delete(work));
|
|
2507
3549
|
return work;
|
|
2508
3550
|
}
|
|
3551
|
+
/** Helper bootstrap is best-effort and sticky: any failure parks null for this driver
|
|
3552
|
+
* lifetime and the shim stays the path. First call to a target pays probe (+ upload). */
|
|
3553
|
+
async ensureHelper(plan) {
|
|
3554
|
+
if (this.helpers === void 0) {
|
|
3555
|
+
const assets = this.opts.helperAssetsFor?.() ?? helperAssets();
|
|
3556
|
+
this.helpers = assets === null ? null : new HelperRegistry(assets, (argv, options) => this.helperExec(argv, options), buildHelperProbeArgv, buildHelperUploadArgv);
|
|
3557
|
+
}
|
|
3558
|
+
if (this.helpers === null || this.disposed) return null;
|
|
3559
|
+
try {
|
|
3560
|
+
return await this.helpers.ensure(plan);
|
|
3561
|
+
} catch {
|
|
3562
|
+
return null;
|
|
3563
|
+
}
|
|
3564
|
+
}
|
|
3565
|
+
async helperExec(argv, options) {
|
|
3566
|
+
this.assertOpen();
|
|
3567
|
+
const stdin = options?.stdin;
|
|
3568
|
+
if (stdin !== void 0) {
|
|
3569
|
+
const proc$1 = startBinaryProcess(argv, { timeoutSec: options?.timeoutSec });
|
|
3570
|
+
proc$1.stdin.on("error", () => {});
|
|
3571
|
+
proc$1.stdin.end(stdin);
|
|
3572
|
+
return {
|
|
3573
|
+
exit: (await proc$1.done).exit,
|
|
3574
|
+
stdout: ""
|
|
3575
|
+
};
|
|
3576
|
+
}
|
|
3577
|
+
const proc = startOneShot(argv, { timeoutSec: options?.timeoutSec });
|
|
3578
|
+
return {
|
|
3579
|
+
exit: (await proc.done).exit,
|
|
3580
|
+
stdout: proc.read("stdout", 0).text
|
|
3581
|
+
};
|
|
3582
|
+
}
|
|
2509
3583
|
own(process$1) {
|
|
2510
3584
|
this.processes.add(process$1);
|
|
2511
3585
|
process$1.done.then(() => this.processes.delete(process$1));
|
|
2512
3586
|
return process$1;
|
|
2513
3587
|
}
|
|
2514
|
-
/**
|
|
2515
|
-
|
|
2516
|
-
* Ruling P20 + PTY 候选表末位:裸名按名匹配——ssh config 字面 host → docker → incus(本地廉价扫描,
|
|
2517
|
-
* 撞名 ssh 优先),三段全不中再看池内活 PTY label,最后才是默认 ssh(交原生错误)。
|
|
2518
|
-
* 位置即优先级:现有三段一位不挪。选择器前缀的 target 不经此路径。
|
|
2519
|
-
*/
|
|
2520
|
-
async resolveBareName(name$1, sessionKey, usePtyLabels = true) {
|
|
3588
|
+
/** 现场采集机器面并 merge 进本 session 注册表(ssh → docker → incus → hub,迟到者加前缀)。错误逐段吞掉(roster 另行如实呈现)。 */
|
|
3589
|
+
async refreshMachines(sessionKey) {
|
|
2521
3590
|
const runner = this.opts.rosterRunner ?? runOneShot;
|
|
2522
3591
|
const readCfg = this.opts.sshConfigReader ?? (async () => await readFile(join(homedir(), ".ssh", "config"), "utf8"));
|
|
2523
|
-
let
|
|
3592
|
+
let sshHosts = [];
|
|
2524
3593
|
try {
|
|
2525
|
-
|
|
3594
|
+
sshHosts = literalHosts(await readCfg()).hosts;
|
|
2526
3595
|
} catch {}
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
};
|
|
2532
|
-
const docker = await
|
|
3596
|
+
const names = (argv) => (async () => {
|
|
3597
|
+
const r = await runner(argv, { timeoutSec: 10 });
|
|
3598
|
+
this.assertOpen();
|
|
3599
|
+
return r.exit === 0 ? r.stdout.trim().split(/\r?\n/).map((l) => l.split(/[\t,]/)[0].trim()).filter((n) => n.length > 0) : [];
|
|
3600
|
+
})().catch(() => []);
|
|
3601
|
+
const [docker, incus] = await Promise.all([names([
|
|
2533
3602
|
"docker",
|
|
2534
3603
|
"ps",
|
|
2535
3604
|
"-a",
|
|
2536
3605
|
"--format",
|
|
2537
3606
|
"{{.Names}}"
|
|
2538
|
-
],
|
|
2539
|
-
this.assertOpen();
|
|
2540
|
-
if (docker.exit === 0 && docker.stdout.trim().split(/\r?\n/).some((n) => n.trim().toLowerCase() === name$1.toLowerCase())) return {
|
|
2541
|
-
kind: "docker",
|
|
2542
|
-
container: name$1
|
|
2543
|
-
};
|
|
2544
|
-
const incus = await runner([
|
|
3607
|
+
]), names([
|
|
2545
3608
|
"incus",
|
|
2546
3609
|
"list",
|
|
2547
3610
|
"--format",
|
|
2548
3611
|
"csv",
|
|
2549
3612
|
"--columns",
|
|
2550
3613
|
"n"
|
|
2551
|
-
]
|
|
3614
|
+
])]);
|
|
3615
|
+
const hub = this.opts.getHub?.()?.listTargets().map((t) => t.id) ?? [];
|
|
3616
|
+
this.labels.mergeScan(sessionKey, {
|
|
3617
|
+
sshHosts,
|
|
3618
|
+
docker,
|
|
3619
|
+
incus,
|
|
3620
|
+
hub
|
|
3621
|
+
});
|
|
3622
|
+
}
|
|
3623
|
+
/** 池寻址:命中即回;miss 现场采集一次再寻址(docker 容器名不经 roster 也可达)。 */
|
|
3624
|
+
async resolvePoolEntry(name$1, sessionKey) {
|
|
3625
|
+
const hit = this.labels.resolve(name$1, sessionKey);
|
|
3626
|
+
if (hit !== void 0) return hit;
|
|
3627
|
+
await this.refreshMachines(sessionKey);
|
|
2552
3628
|
this.assertOpen();
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
3629
|
+
const after = this.labels.resolve(name$1, sessionKey);
|
|
3630
|
+
if (after !== void 0) return after;
|
|
3631
|
+
return {
|
|
3632
|
+
kind: "ssh",
|
|
3633
|
+
name: name$1,
|
|
3634
|
+
host: name$1
|
|
2556
3635
|
};
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
3636
|
+
}
|
|
3637
|
+
planOf(entry) {
|
|
3638
|
+
switch (entry.kind) {
|
|
3639
|
+
case "ssh": return {
|
|
3640
|
+
kind: "ssh",
|
|
3641
|
+
host: entry.host
|
|
3642
|
+
};
|
|
3643
|
+
case "ssh-byo": return {
|
|
3644
|
+
kind: "ssh",
|
|
3645
|
+
host: entry.connection.host,
|
|
3646
|
+
connection: entry.connection
|
|
3647
|
+
};
|
|
3648
|
+
case "docker": return {
|
|
3649
|
+
kind: "docker",
|
|
3650
|
+
container: entry.container
|
|
3651
|
+
};
|
|
3652
|
+
case "incus": return {
|
|
3653
|
+
kind: "incus",
|
|
3654
|
+
container: entry.container
|
|
3655
|
+
};
|
|
3656
|
+
case "pty": throw new Error("remote: a PTY session is not a connection target");
|
|
3657
|
+
case "hub": throw new Error("remote: hub machines are not connection targets");
|
|
3658
|
+
}
|
|
3659
|
+
}
|
|
3660
|
+
/** ssh:<name> 的池感知解析:BYO 身份 → 其 connection;否则按 config 别名/主机名。 */
|
|
3661
|
+
sshPlanFor(name$1, sessionKey) {
|
|
3662
|
+
const entry = this.labels.resolve(name$1, sessionKey);
|
|
3663
|
+
if (entry?.kind === "ssh-byo") return {
|
|
3664
|
+
kind: "ssh",
|
|
3665
|
+
host: entry.connection.host,
|
|
3666
|
+
connection: entry.connection
|
|
2560
3667
|
};
|
|
2561
3668
|
return {
|
|
2562
3669
|
kind: "ssh",
|
|
2563
3670
|
host: name$1
|
|
2564
3671
|
};
|
|
2565
3672
|
}
|
|
2566
|
-
/**
|
|
2567
|
-
|
|
2568
|
-
* 而活会话是**操作环境**——复用别的 agent 留下的 shell 等于继承未知状态,且两个 agent 各开一条线
|
|
2569
|
-
* 的代价可忽略。BYO-PTY 天然是活的,于是自然落进这个 scope,无需另立规则。 */
|
|
2570
|
-
async roster(callCtx = {}) {
|
|
3673
|
+
/** BYO ssh 注册(v2:无 spec 对比——label 占用即拒;注册成功才认领)。返回实际名(label 或 s-id)。 */
|
|
3674
|
+
registerByoSsh(label, connection, sessionKey) {
|
|
2571
3675
|
this.assertOpen();
|
|
2572
|
-
const
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
3676
|
+
const normalized = normalizeSshConnection(connection);
|
|
3677
|
+
if (label !== void 0) validateLabel(label);
|
|
3678
|
+
const name$1 = label ?? this.labels.freshId("ssh-", sessionKey);
|
|
3679
|
+
if (label !== void 0) {
|
|
3680
|
+
const existing = this.labels.resolve(label, sessionKey);
|
|
3681
|
+
if (existing !== void 0) throw new Error(`[E_LABEL_IN_USE] remote: label ${JSON.stringify(label)} is already taken by ${describeEntry(existing)} — nothing was run.\n To reuse it: address ssh:${label} without the ssh field\n To register new: pick another label`);
|
|
3682
|
+
this.labels.claim(label, sessionKey, {
|
|
3683
|
+
kind: "ssh-byo",
|
|
3684
|
+
name: label,
|
|
3685
|
+
connection: normalized
|
|
3686
|
+
});
|
|
3687
|
+
return label;
|
|
3688
|
+
}
|
|
3689
|
+
this.labels.claim(name$1, sessionKey, {
|
|
3690
|
+
kind: "ssh-byo",
|
|
3691
|
+
name: name$1,
|
|
3692
|
+
connection: normalized
|
|
3693
|
+
});
|
|
3694
|
+
return name$1;
|
|
2588
3695
|
}
|
|
2589
|
-
|
|
3696
|
+
/** PTY 会话创建(native/spawn 同一形状):上限 → label 认领 → 惰性会话(失败由 onDead 释放 label)。 */
|
|
3697
|
+
createSession(opts, sessionKey) {
|
|
2590
3698
|
this.assertOpen();
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
const
|
|
2594
|
-
|
|
2595
|
-
return `${target} — Hub remote machine (${row.label}); exec ${row.execEnabled ? "enabled" : "disabled"}; not probed`;
|
|
3699
|
+
const live = this.pool.list().filter(({ key: key$1 }) => key$1.startsWith(`${sessionKey}|`)).map(({ key: key$1 }) => this.pool.get(key$1)).filter((s) => s !== void 0 && s.sessionState !== "dead");
|
|
3700
|
+
if (live.length >= REMOTE_PTY_SESSION_LIMIT) {
|
|
3701
|
+
const listing = live.map(sessionLine).join(" · ");
|
|
3702
|
+
throw new Error(`[E_SESSION_LIMIT] remote: this Agent already holds ${live.length} live PTY sessions (limit ${REMOTE_PTY_SESSION_LIMIT}) — close one ({action:"close", target:"pty:<id>"}); idle sessions are reaped after ${this.ttlMinutes()} min.\n live: ${listing}`);
|
|
2596
3703
|
}
|
|
2597
|
-
const
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
const
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
3704
|
+
const { label } = opts;
|
|
3705
|
+
if (label !== void 0) validateLabel(label);
|
|
3706
|
+
const id = this.labels.freshId("pty-", sessionKey);
|
|
3707
|
+
const entry = {
|
|
3708
|
+
kind: "pty",
|
|
3709
|
+
name: id,
|
|
3710
|
+
id,
|
|
3711
|
+
...label !== void 0 ? { label } : {},
|
|
3712
|
+
connection: opts.connection,
|
|
3713
|
+
byo: opts.byo
|
|
3714
|
+
};
|
|
3715
|
+
if (label !== void 0) this.labels.claim(label, sessionKey, {
|
|
3716
|
+
...entry,
|
|
3717
|
+
name: label
|
|
3718
|
+
});
|
|
3719
|
+
const key = `${sessionKey}|p:${id}`;
|
|
3720
|
+
let session;
|
|
3721
|
+
try {
|
|
3722
|
+
session = this.pool.create({
|
|
3723
|
+
key,
|
|
3724
|
+
argv: opts.argv,
|
|
3725
|
+
id,
|
|
3726
|
+
...label !== void 0 ? { label } : {},
|
|
3727
|
+
connection: opts.connection,
|
|
3728
|
+
byo: opts.byo,
|
|
3729
|
+
builtOn: this.isBuiltOn(opts.connection, sessionKey),
|
|
3730
|
+
...opts.origin !== void 0 ? { origin: opts.origin } : {},
|
|
3731
|
+
onDead: () => {
|
|
3732
|
+
this.labels.release(id, sessionKey);
|
|
3733
|
+
if (label !== void 0) this.labels.release(label, sessionKey);
|
|
3734
|
+
}
|
|
3735
|
+
});
|
|
3736
|
+
} catch (error) {
|
|
3737
|
+
this.labels.release(id, sessionKey);
|
|
3738
|
+
if (label !== void 0) this.labels.release(label, sessionKey);
|
|
3739
|
+
throw error;
|
|
3740
|
+
}
|
|
3741
|
+
this.labels.claim(id, sessionKey, entry);
|
|
3742
|
+
return session;
|
|
2614
3743
|
}
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
return [`${display} — BYO pty session`, renderPtySession(this.pool.inspect(`${sessionKey}|p:${label}`))].join("\n");
|
|
3744
|
+
ttlMinutes() {
|
|
3745
|
+
return Math.max(1, Math.round(this.ptyIdleTtlSec / 60));
|
|
2618
3746
|
}
|
|
2619
|
-
/**
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
this.opts.onAudit?.(r);
|
|
2623
|
-
} catch {}
|
|
3747
|
+
/** connection 由 BYO ssh 身份建立 → card 面标 `(built on)`(与 roster 同词,R2 复核 P2-10)。 */
|
|
3748
|
+
isBuiltOn(connection, sessionKey) {
|
|
3749
|
+
return connection.startsWith("ssh:") && this.labels.resolve(connection.slice(4), sessionKey)?.kind === "ssh-byo";
|
|
2624
3750
|
}
|
|
2625
|
-
/**
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
3751
|
+
/** PTY 创建形唯一实现(execute 与 background 预建共用):spawn BYO / ssh BYO / native `<transport>:pty`。 */
|
|
3752
|
+
createPtyLane(params, form, sessionKey) {
|
|
3753
|
+
if (params.spawn !== void 0 && params.spawn.length > 0) {
|
|
3754
|
+
const label = form.form === "pty-selector" && form.idOrLabel !== void 0 ? form.idOrLabel : form.form === "bare" ? form.name : void 0;
|
|
3755
|
+
if (label !== void 0 && PTY_ID_RE.test(label)) throw new Error(`[E_BAD_LABEL] remote: ${JSON.stringify(label)} looks like an auto id — ids are generated, labels are yours to choose`);
|
|
3756
|
+
return { session: this.createSession({
|
|
3757
|
+
argv: (this.opts.spawnArgvFor ?? buildSpawnArgv)(params.spawn),
|
|
3758
|
+
connection: "BYOP",
|
|
3759
|
+
byo: true,
|
|
3760
|
+
...label !== void 0 ? { label } : {},
|
|
3761
|
+
origin: params.spawn
|
|
3762
|
+
}, sessionKey) };
|
|
3763
|
+
}
|
|
3764
|
+
if (params.ssh !== void 0 && form.form === "create-pty") {
|
|
3765
|
+
const name$1 = this.registerByoSsh(form.name, params.ssh, sessionKey);
|
|
3766
|
+
const connection = normalizeSshConnection(params.ssh);
|
|
3767
|
+
const plan = {
|
|
3768
|
+
kind: "ssh",
|
|
3769
|
+
host: connection.host,
|
|
3770
|
+
connection
|
|
3771
|
+
};
|
|
3772
|
+
return { session: this.createSession({
|
|
3773
|
+
argv: (this.opts.ptyArgvFor ?? buildPtyArgv)(plan),
|
|
3774
|
+
connection: `ssh:${name$1}`,
|
|
3775
|
+
byo: false,
|
|
3776
|
+
...form.label !== void 0 ? { label: form.label } : {}
|
|
3777
|
+
}, sessionKey) };
|
|
3778
|
+
}
|
|
3779
|
+
if (form.form === "create-pty") {
|
|
3780
|
+
const plan = form.transport === "ssh" ? this.sshPlanFor(form.name, sessionKey) : resolveTarget(`${form.transport}:${form.name}`);
|
|
3781
|
+
return { session: this.createSession({
|
|
3782
|
+
argv: (this.opts.ptyArgvFor ?? buildPtyArgv)(plan),
|
|
3783
|
+
connection: `${form.transport}:${form.name}`,
|
|
3784
|
+
byo: false,
|
|
3785
|
+
...form.label !== void 0 ? { label: form.label } : {}
|
|
3786
|
+
}, sessionKey) };
|
|
3787
|
+
}
|
|
3788
|
+
if (form.form === "hub-pty") {
|
|
3789
|
+
const hub = this.requireHub();
|
|
3790
|
+
this.hubProviders.add(hub);
|
|
3791
|
+
const endpoint = hub.ptyEndpoint(form.machine);
|
|
3792
|
+
const argv = this.opts.hubPtyArgvFor !== void 0 ? this.opts.hubPtyArgvFor(endpoint) : buildHubPtyArgv(endpoint, hubPtyAssets());
|
|
3793
|
+
return { session: this.createSession({
|
|
3794
|
+
argv,
|
|
3795
|
+
connection: `hub:${form.machine}`,
|
|
3796
|
+
byo: false,
|
|
3797
|
+
...form.label !== void 0 ? { label: form.label } : {}
|
|
3798
|
+
}, sessionKey) };
|
|
3799
|
+
}
|
|
2641
3800
|
}
|
|
2642
|
-
/**
|
|
2643
|
-
*
|
|
2644
|
-
async
|
|
3801
|
+
/** background PTY lane:会话先占位(不拨号)再进官方 jobs registry——首回执必须能寻址;
|
|
3802
|
+
* registry 拒绝时把新建的会话拆掉(复用形的会话绝不拆)。返回 undefined = 走普通 oneshot job。 */
|
|
3803
|
+
async preparePtyLane(params, callCtx = {}) {
|
|
2645
3804
|
this.assertOpen();
|
|
2646
|
-
|
|
2647
|
-
if (/^(docker|incus|ssh):/.test(target)) return resolveTarget(target);
|
|
2648
|
-
if (/^(byop|hub):/.test(target)) throw new Error("remote: select an SSH/Docker/Incus target for this connection resolver");
|
|
2649
|
-
const plan = await this.resolveBareName(target, callCtx.sessionKey ?? "no-session", false);
|
|
3805
|
+
const prepared = await prepareRemoteInput(params);
|
|
2650
3806
|
this.assertOpen();
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
if (
|
|
2662
|
-
if (
|
|
3807
|
+
const sessionKey = callCtx.sessionKey ?? "no-session";
|
|
3808
|
+
const form = parseTargetForm(prepared.target);
|
|
3809
|
+
const target = (id$1) => ({
|
|
3810
|
+
target: `pty:${id$1}`,
|
|
3811
|
+
cmd: params.cmd,
|
|
3812
|
+
stdin: params.stdin,
|
|
3813
|
+
timeout: params.timeout,
|
|
3814
|
+
mode: "pty"
|
|
3815
|
+
});
|
|
3816
|
+
const lane = this.createPtyLane(prepared, form, sessionKey);
|
|
3817
|
+
if (lane === void 0 && form.form === "pty-selector") {
|
|
3818
|
+
if (form.idOrLabel === void 0) throw new Error("[E_PARAMS] remote: \"pty\" alone selects nothing — append an id/label (pty:pty-1a2b, pty:build) or pass spawn to create one");
|
|
3819
|
+
const id$1 = this.resolvePty(form.idOrLabel, sessionKey).identity;
|
|
2663
3820
|
return {
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
3821
|
+
input: target(id$1.id),
|
|
3822
|
+
session: `pty:${id$1.id}`,
|
|
3823
|
+
connection: id$1.connection,
|
|
3824
|
+
...id$1.label !== void 0 ? { label: id$1.label } : {},
|
|
3825
|
+
cleanup: () => void 0
|
|
2667
3826
|
};
|
|
2668
3827
|
}
|
|
2669
|
-
if (
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
3828
|
+
if (lane === void 0) return void 0;
|
|
3829
|
+
const id = lane.session.identity;
|
|
3830
|
+
return {
|
|
3831
|
+
input: target(id.id),
|
|
3832
|
+
session: `pty:${id.id}`,
|
|
3833
|
+
connection: id.connection,
|
|
3834
|
+
...id.label !== void 0 ? { label: id.label } : {},
|
|
3835
|
+
cleanup: () => {
|
|
3836
|
+
lane.session.dispose();
|
|
3837
|
+
}
|
|
3838
|
+
};
|
|
3839
|
+
}
|
|
3840
|
+
/** `pty:<id|label>` 寻址:先 id 后 label;miss 给重建形式。 */
|
|
3841
|
+
resolvePty(selector, sessionKey) {
|
|
3842
|
+
const entry = this.labels.resolve(selector, sessionKey);
|
|
3843
|
+
if (entry?.kind === "pty") {
|
|
3844
|
+
const s = this.pool.get(`${sessionKey}|p:${entry.id}`);
|
|
3845
|
+
if (s !== void 0) return s;
|
|
2681
3846
|
}
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
3847
|
+
throw new Error(`[E_NO_SESSION] remote: no live PTY under ${PTY_ID_RE.test(selector) ? `id ${selector}` : `label ${JSON.stringify(selector)}`} — sessions are created by appending :pty to a transport target ({target:"ssh:dev4:pty", cmd:"…"}) or by spawn; idle sessions are reaped after ${this.ttlMinutes()} min`);
|
|
3848
|
+
}
|
|
3849
|
+
/** §6 close:默认撞 detached job 报错(列杀法);force = 杀组+关闭(披露 killed)。幂等 not-found。 */
|
|
3850
|
+
closePty(selector, sessionKey, force = false) {
|
|
3851
|
+
this.assertOpen();
|
|
3852
|
+
const entry = this.labels.resolve(selector, sessionKey);
|
|
3853
|
+
if (entry?.kind !== "pty") return {
|
|
3854
|
+
session: selector,
|
|
3855
|
+
connection: "",
|
|
3856
|
+
closed: false,
|
|
3857
|
+
reason: "not-found",
|
|
3858
|
+
killed: [],
|
|
3859
|
+
message: `no pty session is registered under ${JSON.stringify(selector)}`
|
|
3860
|
+
};
|
|
3861
|
+
const session = this.pool.get(`${sessionKey}|p:${entry.id}`);
|
|
3862
|
+
if (session === void 0) return {
|
|
3863
|
+
session: `pty:${entry.id}`,
|
|
3864
|
+
connection: entry.connection,
|
|
3865
|
+
closed: false,
|
|
3866
|
+
reason: "already-closed-or-reaped",
|
|
3867
|
+
killed: [],
|
|
3868
|
+
message: `pty:${entry.id} was already closed or reaped after ${this.ttlMinutes()} min idle`
|
|
2687
3869
|
};
|
|
2688
|
-
const
|
|
3870
|
+
const pending = session.detachedCommandId;
|
|
3871
|
+
if (pending !== null && !force) throw new Error(`[E_SESSION_BUSY] remote: pty session ${entry.id} still runs a detached command (${pending}) — job_kill ${pending} first (or wait for it), then close again; force:true closes the tab and kills the group in one step`);
|
|
3872
|
+
session.dispose();
|
|
2689
3873
|
return {
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
3874
|
+
session: `pty:${entry.id}`,
|
|
3875
|
+
connection: entry.connection,
|
|
3876
|
+
closed: true,
|
|
3877
|
+
...pending !== null ? { killed: [pending] } : { killed: [] }
|
|
2693
3878
|
};
|
|
2694
3879
|
}
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
const
|
|
2698
|
-
|
|
3880
|
+
/** job 通道收养回填(timeout handoff 时 registry id ≠ commandId,账本记录两者)。 */
|
|
3881
|
+
attachPtyJob(commandId, jobId, sessionKey) {
|
|
3882
|
+
for (const { key } of this.pool.list()) {
|
|
3883
|
+
if (!key.startsWith(`${sessionKey ?? "no-session"}|`)) continue;
|
|
3884
|
+
this.pool.get(key)?.attachJob(commandId, jobId);
|
|
3885
|
+
}
|
|
3886
|
+
}
|
|
3887
|
+
/** §3.1(2026-10-25)interactive-stdin:input 动作——向已有 live PTY 的当前运行命令
|
|
3888
|
+
* 追加 stdin。只解析池内已存在的会话(pty:<id|label> / 裸 label 命中 pty 项),
|
|
3889
|
+
* 不触发发现、拨号、创建或重连;machine target 与创建形(:pty 后缀,含 hub:<m4>:pty)
|
|
3890
|
+
* 一律明确拒绝并给出可恢复指引。回执附 connection/label 供工具层渲染。 */
|
|
3891
|
+
async input(target, options, callCtx = {}) {
|
|
3892
|
+
this.assertOpen();
|
|
3893
|
+
const sessionKey = callCtx.sessionKey ?? "no-session";
|
|
3894
|
+
const form = parseTargetForm(target);
|
|
3895
|
+
let selector;
|
|
3896
|
+
if (form.form === "pty-selector") {
|
|
3897
|
+
if (form.idOrLabel === void 0) throw new Error("[E_PARAMS] remote: \"pty\" alone selects nothing — append an id/label (pty:pty-1a2b, pty:build)");
|
|
3898
|
+
selector = form.idOrLabel;
|
|
3899
|
+
} else if (form.form === "bare") {
|
|
3900
|
+
if (this.labels.resolve(form.name, sessionKey)?.kind !== "pty") throw new Error(`[E_NO_SESSION] remote: no live PTY session under ${JSON.stringify(form.name)} in this Agent's pool — input never dials, discovers or creates; run {action:"status"} to list sessions, then address one as pty:<id|label>`);
|
|
3901
|
+
selector = form.name;
|
|
3902
|
+
} else if (form.form === "create-pty" || form.form === "hub-pty") throw new Error(`[E_TARGET_FORMAT] remote: input writes into a live PTY session — "${target}" is a creation form; input never creates a session. Start the interactive program with {action:"exec", target:"${target}", cmd:…} first, then input into it`);
|
|
3903
|
+
else throw new Error(`[E_TARGET_FORMAT] remote: input writes into a live PTY session — "${target}" is a machine target and machines are dialed per call. Run the interactive program with exec on a :pty session (e.g. {action:"exec", target:"ssh:dev4:pty" or "hub:<m4>:pty", cmd:…}), then input into that session`);
|
|
3904
|
+
const session = this.resolvePty(selector, sessionKey);
|
|
3905
|
+
const receipt = await session.input(options);
|
|
3906
|
+
const id = session.identity;
|
|
3907
|
+
return {
|
|
3908
|
+
...receipt,
|
|
3909
|
+
connection: id.connection,
|
|
3910
|
+
...id.label !== void 0 ? { label: id.label } : {}
|
|
3911
|
+
};
|
|
3912
|
+
}
|
|
3913
|
+
async dispatchPty(session, params, callCtx, timeoutSec, cap) {
|
|
3914
|
+
const hubConn = session.identity.connection;
|
|
3915
|
+
if (hubConn.startsWith("hub:")) {
|
|
2699
3916
|
const hub = this.requireHub();
|
|
2700
3917
|
this.hubProviders.add(hub);
|
|
2701
|
-
|
|
2702
|
-
if (routing.mode === "pty") {
|
|
2703
|
-
const result$1 = await hub.pty(machine, params.cmd, this.hubOwner, {
|
|
2704
|
-
stdin: params.stdin,
|
|
2705
|
-
timeout: timeoutSec
|
|
2706
|
-
});
|
|
2707
|
-
const out$2 = tailWindow(result$1.stdout, cap, result$1.outputStats?.stdout);
|
|
2708
|
-
return {
|
|
2709
|
-
...result$1,
|
|
2710
|
-
stdout: out$2.text,
|
|
2711
|
-
...out$2.stats ? { outputStats: {
|
|
2712
|
-
...result$1.outputStats,
|
|
2713
|
-
stdout: out$2.stats
|
|
2714
|
-
} } : {},
|
|
2715
|
-
...out$2.truncated === void 0 ? {} : { truncated: out$2.truncated }
|
|
2716
|
-
};
|
|
2717
|
-
}
|
|
2718
|
-
const process$1 = this.own(await hub.start(machine, {
|
|
2719
|
-
...params,
|
|
2720
|
-
target: routing.display,
|
|
2721
|
-
mode: "oneshot",
|
|
2722
|
-
timeout: timeoutSec
|
|
2723
|
-
}, this.hubOwner));
|
|
2724
|
-
if (this.disposed) process$1.cancel("owner disposed");
|
|
2725
|
-
const result = await process$1.done;
|
|
2726
|
-
const stdout = process$1.read("stdout", 0), stderr = process$1.read("stderr", 0);
|
|
2727
|
-
const out$1 = tailWindow(stdout.text, cap, stdout.stats);
|
|
2728
|
-
const err = tailWindow(stderr.text, cap, stderr.stats);
|
|
2729
|
-
return {
|
|
2730
|
-
...result,
|
|
2731
|
-
mode: "oneshot",
|
|
2732
|
-
target: routing.display,
|
|
2733
|
-
cwd: null,
|
|
2734
|
-
reconnected: false,
|
|
2735
|
-
stdout: (!stdout.stats && stdout.lossy ? "[truncated: peer returned only a tail; exact total/retained/dropped unavailable]\n" : "") + out$1.text,
|
|
2736
|
-
stderr: [err.text, stderr.diagnostic].filter(Boolean).join("\n"),
|
|
2737
|
-
...out$1.stats ? { outputStats: {
|
|
2738
|
-
stdout: out$1.stats,
|
|
2739
|
-
stderr: err.stats
|
|
2740
|
-
} } : { outputStatsUnavailable: true },
|
|
2741
|
-
...out$1.truncated === void 0 ? {} : { truncated: out$1.truncated }
|
|
2742
|
-
};
|
|
2743
|
-
}
|
|
2744
|
-
const sessionKey = callCtx.sessionKey ?? "no-session";
|
|
2745
|
-
if (routing.bare !== void 0) {
|
|
2746
|
-
const resolved = await this.resolveBareName(routing.bare, sessionKey, params.mode !== "oneshot");
|
|
2747
|
-
this.assertOpen();
|
|
2748
|
-
if (resolved.kind === "pty") {
|
|
2749
|
-
routing.pty = { label: resolved.label };
|
|
2750
|
-
routing.mode = "pty";
|
|
2751
|
-
routing.display = `byop:${resolved.label}`;
|
|
2752
|
-
} else routing.plan = resolved;
|
|
2753
|
-
}
|
|
2754
|
-
if (routing.pty !== void 0) return await this.ptyCall(routing.pty, params, sessionKey, timeoutSec, cap);
|
|
2755
|
-
if (routing.mode === "oneshot") {
|
|
2756
|
-
this.assertOpen();
|
|
2757
|
-
const process$1 = this.own(await this.nativeProcess(routing.plan, params, timeoutSec));
|
|
2758
|
-
if (this.disposed) process$1.cancel("owner disposed");
|
|
2759
|
-
const result = await process$1.done;
|
|
2760
|
-
const stdout = process$1.read("stdout", 0), stderr = process$1.read("stderr", 0);
|
|
2761
|
-
const r$1 = {
|
|
2762
|
-
...result,
|
|
2763
|
-
stdout: stdout.text,
|
|
2764
|
-
stderr: [stderr.text, stderr.diagnostic].filter(Boolean).join("\n"),
|
|
2765
|
-
outputStats: {
|
|
2766
|
-
stdout: stdout.stats,
|
|
2767
|
-
stderr: stderr.stats
|
|
2768
|
-
}
|
|
2769
|
-
};
|
|
2770
|
-
const out$1 = tailWindow(r$1.stdout, cap, r$1.outputStats?.stdout);
|
|
2771
|
-
const err = r$1.stderr.length > 0 ? tailWindow(r$1.stderr, cap, r$1.outputStats?.stderr) : void 0;
|
|
2772
|
-
return {
|
|
2773
|
-
mode: "oneshot",
|
|
2774
|
-
target: routing.display,
|
|
2775
|
-
exit: r$1.exit,
|
|
2776
|
-
cwd: null,
|
|
2777
|
-
timedOut: r$1.timedOut,
|
|
2778
|
-
reconnected: false,
|
|
2779
|
-
stdout: out$1.text,
|
|
2780
|
-
...err !== void 0 ? { stderr: err.text } : {},
|
|
2781
|
-
...out$1.stats ? { outputStats: {
|
|
2782
|
-
stdout: out$1.stats,
|
|
2783
|
-
stderr: err?.stats ?? r$1.outputStats?.stderr
|
|
2784
|
-
} } : {},
|
|
2785
|
-
durationMs: r$1.durationMs,
|
|
2786
|
-
...out$1.truncated !== void 0 ? { truncated: out$1.truncated } : {}
|
|
2787
|
-
};
|
|
3918
|
+
hub.ptyEndpoint(hubConn.slice(4));
|
|
2788
3919
|
}
|
|
2789
|
-
const
|
|
2790
|
-
const
|
|
2791
|
-
const r = await this.pool.getOrCreate(key, argv).dispatch(params.cmd, {
|
|
3920
|
+
const commandId = callCtx.commandId ?? genCommandId();
|
|
3921
|
+
const r = await session.dispatch(params.cmd, {
|
|
2792
3922
|
stdin: params.stdin,
|
|
2793
|
-
timeoutSec
|
|
3923
|
+
timeoutSec,
|
|
3924
|
+
commandId,
|
|
3925
|
+
...callCtx.ptyBackground === true ? {
|
|
3926
|
+
background: true,
|
|
3927
|
+
jobId: commandId
|
|
3928
|
+
} : {}
|
|
2794
3929
|
});
|
|
2795
3930
|
const out = tailWindow(r.output, cap, r.outputStats?.stdout);
|
|
3931
|
+
const id = session.identity;
|
|
2796
3932
|
return {
|
|
2797
3933
|
mode: "pty",
|
|
2798
|
-
target:
|
|
3934
|
+
target: `pty:${id.id}`,
|
|
3935
|
+
session: `pty:${id.id}`,
|
|
3936
|
+
...id.label !== void 0 ? { label: id.label } : {},
|
|
3937
|
+
connection: id.connection,
|
|
3938
|
+
...id.byo ? { byoTag: "byo-pty" } : {},
|
|
3939
|
+
commandId: r.commandId,
|
|
2799
3940
|
exit: r.exit,
|
|
2800
3941
|
cwd: r.cwd,
|
|
2801
3942
|
timedOut: r.timedOut,
|
|
@@ -2803,42 +3944,211 @@ var RemoteDriver = class {
|
|
|
2803
3944
|
stdout: out.text,
|
|
2804
3945
|
outputStats: out.stats ? { stdout: out.stats } : void 0,
|
|
2805
3946
|
durationMs: r.durationMs,
|
|
2806
|
-
...out.truncated !== void 0 ? { truncated: out.truncated } : {}
|
|
3947
|
+
...out.truncated !== void 0 ? { truncated: out.truncated } : {},
|
|
3948
|
+
...r.envDelta !== void 0 ? { envDelta: r.envDelta } : {},
|
|
3949
|
+
...r.running === true && r.job !== void 0 ? {
|
|
3950
|
+
running: true,
|
|
3951
|
+
ptyJob: r.job
|
|
3952
|
+
} : {},
|
|
3953
|
+
...this.ptyTtl(session.key)
|
|
2807
3954
|
};
|
|
2808
3955
|
}
|
|
2809
|
-
/**
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
3956
|
+
/** 预热(创建形无 cmd)回执:§3——无 commandId/envDelta;timeout 忽略。 */
|
|
3957
|
+
warmReceipt(session) {
|
|
3958
|
+
const id = session.identity;
|
|
3959
|
+
return {
|
|
3960
|
+
mode: "pty",
|
|
3961
|
+
target: `pty:${id.id}`,
|
|
3962
|
+
session: `pty:${id.id}`,
|
|
3963
|
+
...id.label !== void 0 ? { label: id.label } : {},
|
|
3964
|
+
connection: id.connection,
|
|
3965
|
+
...id.byo ? { byoTag: "byo-pty" } : {},
|
|
3966
|
+
created: true,
|
|
3967
|
+
exit: null,
|
|
3968
|
+
cwd: null,
|
|
3969
|
+
timedOut: false,
|
|
3970
|
+
reconnected: false,
|
|
3971
|
+
stdout: "",
|
|
3972
|
+
durationMs: 0,
|
|
3973
|
+
...this.ptyTtl(session.key)
|
|
3974
|
+
};
|
|
3975
|
+
}
|
|
3976
|
+
/** session card 回执(`pty:<id|label>` 无 cmd):connection/state/cwd + 最近 20 条账本(不带输出尾,§9 Q7)。 */
|
|
3977
|
+
cardReceipt(session) {
|
|
3978
|
+
const id = session.identity;
|
|
3979
|
+
const snap = session.snapshot;
|
|
3980
|
+
const state = snap.busy ? "busy (a command is running)" : snap.state === "dead" ? "died — next dispatch reconnects a fresh shell" : `idle ${Math.round((snap.idleMs ?? 0) / 1e3)}s (connected)`;
|
|
3981
|
+
const head = `pty:${id.id}${id.label !== void 0 ? ` (label ${id.label})` : ""} — ${id.connection}${id.byo ? " (byo-pty)" : id.builtOn ? " (built on)" : ""} · ${state} · cwd ${session.lastCwd ?? "(none yet)"}`;
|
|
2827
3982
|
return {
|
|
2828
3983
|
mode: "pty",
|
|
3984
|
+
target: `pty:${id.id}`,
|
|
3985
|
+
session: `pty:${id.id}`,
|
|
3986
|
+
...id.label !== void 0 ? { label: id.label } : {},
|
|
3987
|
+
connection: id.connection,
|
|
3988
|
+
...id.byo ? { byoTag: "byo-pty" } : {},
|
|
3989
|
+
exit: null,
|
|
3990
|
+
cwd: session.lastCwd,
|
|
3991
|
+
timedOut: false,
|
|
3992
|
+
reconnected: false,
|
|
3993
|
+
stdout: [head, renderLedger(session.ledgerSnapshot())].join("\n"),
|
|
3994
|
+
durationMs: 0,
|
|
3995
|
+
...this.ptyTtl(session.key)
|
|
3996
|
+
};
|
|
3997
|
+
}
|
|
3998
|
+
async oneshot(plan, display, params, timeoutSec, cap) {
|
|
3999
|
+
this.assertOpen();
|
|
4000
|
+
const process$1 = this.own(await this.nativeProcess(plan, params, timeoutSec));
|
|
4001
|
+
if (this.disposed) process$1.cancel("owner disposed");
|
|
4002
|
+
const result = await process$1.done;
|
|
4003
|
+
const stdout = process$1.read("stdout", 0), stderr = process$1.read("stderr", 0);
|
|
4004
|
+
const r = {
|
|
4005
|
+
...result,
|
|
4006
|
+
stdout: stdout.text,
|
|
4007
|
+
stderr: [stderr.text, stderr.diagnostic].filter(Boolean).join("\n"),
|
|
4008
|
+
outputStats: {
|
|
4009
|
+
stdout: stdout.stats,
|
|
4010
|
+
stderr: stderr.stats
|
|
4011
|
+
}
|
|
4012
|
+
};
|
|
4013
|
+
const out = tailWindow(r.stdout, cap, r.outputStats?.stdout);
|
|
4014
|
+
const err = r.stderr.length > 0 ? tailWindow(r.stderr, cap, r.outputStats?.stderr) : void 0;
|
|
4015
|
+
return {
|
|
4016
|
+
mode: "oneshot",
|
|
2829
4017
|
target: display,
|
|
2830
|
-
session: display,
|
|
2831
4018
|
exit: r.exit,
|
|
2832
|
-
cwd:
|
|
4019
|
+
cwd: null,
|
|
2833
4020
|
timedOut: r.timedOut,
|
|
2834
|
-
reconnected:
|
|
4021
|
+
reconnected: false,
|
|
2835
4022
|
stdout: out.text,
|
|
2836
|
-
...
|
|
2837
|
-
|
|
4023
|
+
...err !== void 0 ? { stderr: err.text } : {},
|
|
4024
|
+
...out.stats ? { outputStats: {
|
|
4025
|
+
stdout: out.stats,
|
|
4026
|
+
stderr: err?.stats ?? r.outputStats?.stderr
|
|
4027
|
+
} } : {},
|
|
2838
4028
|
durationMs: r.durationMs,
|
|
2839
|
-
...out.truncated !== void 0 ? { truncated: out.truncated } : {}
|
|
4029
|
+
...out.truncated !== void 0 ? { truncated: out.truncated } : {},
|
|
4030
|
+
...this.runnerOf.get(process$1) === void 0 ? {} : { runner: this.runnerOf.get(process$1) }
|
|
4031
|
+
};
|
|
4032
|
+
}
|
|
4033
|
+
async hubOneshot(machine, display, params, timeoutSec, cap) {
|
|
4034
|
+
const process$1 = this.own(await this.hubOneshotProcess(machine, params));
|
|
4035
|
+
if (this.disposed) process$1.cancel("owner disposed");
|
|
4036
|
+
const result = await process$1.done;
|
|
4037
|
+
const stdout = process$1.read("stdout", 0), stderr = process$1.read("stderr", 0);
|
|
4038
|
+
const out = tailWindow(stdout.text, cap, stdout.stats);
|
|
4039
|
+
const err = tailWindow(stderr.text, cap, stderr.stats);
|
|
4040
|
+
return {
|
|
4041
|
+
...result,
|
|
4042
|
+
mode: "oneshot",
|
|
4043
|
+
target: display,
|
|
4044
|
+
connection: display,
|
|
4045
|
+
cwd: null,
|
|
4046
|
+
reconnected: false,
|
|
4047
|
+
runner: HUB_RUNNER,
|
|
4048
|
+
stdout: (!stdout.stats && stdout.lossy ? "[truncated: peer returned only a tail; exact total/retained/dropped unavailable]\n" : "") + out.text,
|
|
4049
|
+
stderr: [err.text, stderr.diagnostic].filter(Boolean).join("\n"),
|
|
4050
|
+
...out.stats ? { outputStats: {
|
|
4051
|
+
stdout: out.stats,
|
|
4052
|
+
stderr: err.stats
|
|
4053
|
+
} } : { outputStatsUnavailable: true },
|
|
4054
|
+
...out.truncated === void 0 ? {} : { truncated: out.truncated }
|
|
2840
4055
|
};
|
|
2841
4056
|
}
|
|
4057
|
+
async hubOneshotProcess(machine, params) {
|
|
4058
|
+
const hub = this.requireHub();
|
|
4059
|
+
this.hubProviders.add(hub);
|
|
4060
|
+
return await hub.start(machine, {
|
|
4061
|
+
...params,
|
|
4062
|
+
target: `hub:${machine}`,
|
|
4063
|
+
mode: "oneshot"
|
|
4064
|
+
}, this.hubOwner);
|
|
4065
|
+
}
|
|
4066
|
+
/** Ruling P19 + §2.5:roster = 注意力入口——本地扫描刷新统一池,零拨号;机器面公共,会话面 caller-scoped。 */
|
|
4067
|
+
async roster(callCtx = {}) {
|
|
4068
|
+
this.assertOpen();
|
|
4069
|
+
const scan = await scanLocal({
|
|
4070
|
+
runner: this.opts.rosterRunner,
|
|
4071
|
+
readSshConfig: this.opts.sshConfigReader
|
|
4072
|
+
});
|
|
4073
|
+
this.assertOpen();
|
|
4074
|
+
this.labels.mergeScan(callCtx.sessionKey ?? "no-session", {
|
|
4075
|
+
sshHosts: scan.ssh.hosts,
|
|
4076
|
+
docker: scan.docker.rows.map((r) => r.name),
|
|
4077
|
+
incus: scan.incus.rows.map((r) => r.name),
|
|
4078
|
+
hub: this.opts.getHub?.()?.listTargets().map((t) => t.id) ?? []
|
|
4079
|
+
});
|
|
4080
|
+
const prefix = `${callCtx.sessionKey ?? "no-session"}|`;
|
|
4081
|
+
const sessions = this.pool.list().filter(({ key }) => key.startsWith(prefix)).map(({ key }) => {
|
|
4082
|
+
const s = this.pool.get(key);
|
|
4083
|
+
return s === void 0 ? null : s;
|
|
4084
|
+
}).filter((s) => s !== null);
|
|
4085
|
+
const hub = this.opts.getHub?.();
|
|
4086
|
+
return renderRoster(scan, this.labels.list(callCtx.sessionKey ?? "no-session"), sessions, hub === void 0 ? null : hub.listTargets());
|
|
4087
|
+
}
|
|
4088
|
+
/** status probe(target 无 cmd):机器面 = probe + 该 connection 上的会话;pty selector = session card。 */
|
|
4089
|
+
async status(target, callCtx = {}) {
|
|
4090
|
+
this.assertOpen();
|
|
4091
|
+
const sessionKey = callCtx.sessionKey ?? "no-session";
|
|
4092
|
+
const form = parseTargetForm(target);
|
|
4093
|
+
if (form.form === "hub" || form.form === "hub-pty") {
|
|
4094
|
+
const row = this.requireHub().listTargets().find((t) => t.id === form.machine);
|
|
4095
|
+
if (!row) throw new Error(`unknown remote machine ${form.machine} — select a remote machine from the Hub roster; local execution is not available`);
|
|
4096
|
+
return `hub:${form.machine} — Hub remote machine (${row.label}); exec ${row.execEnabled ? "enabled" : "disabled"}; not probed`;
|
|
4097
|
+
}
|
|
4098
|
+
if (form.form === "pty-selector") {
|
|
4099
|
+
if (form.idOrLabel === void 0) throw new Error("[E_PARAMS] remote: \"pty\" alone selects nothing — append an id/label (pty:pty-1a2b, pty:build)");
|
|
4100
|
+
return this.cardReceipt(this.resolvePty(form.idOrLabel, sessionKey)).stdout;
|
|
4101
|
+
}
|
|
4102
|
+
if (form.form !== "direct" && form.form !== "bare") throw new Error("[E_PARAMS] remote: status takes a machine target (bare name or ssh:/docker:/incus:/hub:) or a pty:<id|label> selector");
|
|
4103
|
+
const name$1 = directName(form) || (form.form === "bare" ? form.name : "");
|
|
4104
|
+
const entry = await this.resolvePoolEntry(name$1, sessionKey);
|
|
4105
|
+
this.assertOpen();
|
|
4106
|
+
if (entry.kind === "pty") {
|
|
4107
|
+
if (form.form !== "bare") throw new Error("[E_TARGET_FORMAT] remote: ssh:/docker:/incus: force a machine channel — the pty selector is pty:<id|label>");
|
|
4108
|
+
return this.cardReceipt(this.resolvePty(form.name, sessionKey)).stdout;
|
|
4109
|
+
}
|
|
4110
|
+
if (entry.kind === "hub") return this.status(`hub:${entry.machine}`, callCtx);
|
|
4111
|
+
const plan = this.planOf(entry);
|
|
4112
|
+
const head = `${target} — ${plan.kind === "ssh" ? "ssh host" : `${plan.kind} container`}${entry.kind === "ssh-byo" ? " (built on)" : ""}`;
|
|
4113
|
+
const runner = this.opts.probeRunner ?? runOneShot;
|
|
4114
|
+
const probe = await probeTarget(plan, { runner: (argv, options) => {
|
|
4115
|
+
this.assertOpen();
|
|
4116
|
+
return runner(argv, options);
|
|
4117
|
+
} });
|
|
4118
|
+
const prefix = `${sessionKey}|`;
|
|
4119
|
+
const onConnection = this.pool.list().filter(({ key }) => key.startsWith(prefix)).map(({ key }) => this.pool.get(key)).filter((s) => s !== void 0 && s.identity.connection === `${plan.kind === "ssh" ? "ssh" : plan.kind}:${name$1}`);
|
|
4120
|
+
return [
|
|
4121
|
+
head,
|
|
4122
|
+
renderProbe(probe),
|
|
4123
|
+
onConnection.length > 0 ? `pty sessions on this connection: ${onConnection.map(sessionLine).join(" · ")}` : "pty sessions on this connection: none"
|
|
4124
|
+
].join("\n");
|
|
4125
|
+
}
|
|
4126
|
+
/** Ruling 13:审计 best-effort——钩子抛错不得影响命令路径。 */
|
|
4127
|
+
audit(r) {
|
|
4128
|
+
try {
|
|
4129
|
+
this.opts.onAudit?.(r);
|
|
4130
|
+
} catch {}
|
|
4131
|
+
}
|
|
4132
|
+
/** Single target resolver for later copy/rsync; PTY sessions are not filesystem connections. */
|
|
4133
|
+
async resolveConnectionTarget(target, callCtx = {}) {
|
|
4134
|
+
this.assertOpen();
|
|
4135
|
+
const form = parseTargetForm(target);
|
|
4136
|
+
if (form.form === "pty-selector") throw new Error("remote: a PTY session is not a filesystem connection");
|
|
4137
|
+
if (form.form === "hub" || form.form === "hub-pty") throw new Error("remote: hub endpoints resolve through the Hub file lane, not a CLI connection");
|
|
4138
|
+
if (form.form === "create-pty") throw new Error("remote: a PTY session is not a filesystem connection");
|
|
4139
|
+
if (form.form === "direct") return form.transport === "ssh" ? this.sshPlanFor(form.name, callCtx.sessionKey ?? "no-session") : resolveTarget(`${form.transport}:${form.name}`);
|
|
4140
|
+
if (form.form === "ssh-prefix" || form.form === "empty") throw new Error("[E_TARGET_FORMAT] remote: connection targets need a name");
|
|
4141
|
+
const entry = await this.resolvePoolEntry(form.name, callCtx.sessionKey ?? "no-session");
|
|
4142
|
+
this.assertOpen();
|
|
4143
|
+
return this.planOf(entry);
|
|
4144
|
+
}
|
|
4145
|
+
/** P2/P3:回执即状态快照——idle TTL 剩余随每次 pty 回执带回。 */
|
|
4146
|
+
ptyTtl(key) {
|
|
4147
|
+
const snap = this.pool.inspect(key);
|
|
4148
|
+
if (snap === void 0 || snap.state === "dead" || snap.state === "disposed") return {};
|
|
4149
|
+
if (snap.idleMs === null) return { ttlSec: this.ptyIdleTtlSec };
|
|
4150
|
+
return { ttlSec: Math.max(0, Math.round(this.ptyIdleTtlSec - snap.idleMs / 1e3)) };
|
|
4151
|
+
}
|
|
2842
4152
|
hasHub() {
|
|
2843
4153
|
return this.opts.getHub?.() !== void 0;
|
|
2844
4154
|
}
|
|
@@ -2853,8 +4163,8 @@ var RemoteDriver = class {
|
|
|
2853
4163
|
}
|
|
2854
4164
|
dispose() {
|
|
2855
4165
|
if (this.disposal) return this.disposal;
|
|
2856
|
-
this.sshTargets.clear();
|
|
2857
4166
|
this.disposed = true;
|
|
4167
|
+
this.labels.clear();
|
|
2858
4168
|
this.fileAbort.abort(/* @__PURE__ */ new Error("remote owner disposed"));
|
|
2859
4169
|
for (const process$1 of this.processes) process$1.cancel("remote owner disposed");
|
|
2860
4170
|
return this.disposal = (async () => {
|
|
@@ -2868,13 +4178,87 @@ var RemoteDriver = class {
|
|
|
2868
4178
|
})();
|
|
2869
4179
|
}
|
|
2870
4180
|
};
|
|
4181
|
+
/** direct 形态回退到 resolveTarget 可解析的名字(ssh:dev4 → dev4)。 */
|
|
4182
|
+
function directName(form) {
|
|
4183
|
+
return form.form === "direct" ? form.name : form.form === "create-pty" ? form.name : "";
|
|
4184
|
+
}
|
|
4185
|
+
/** roster/status 一行的会话描述:`p-ab12 (label build) ssh:dev4 idle 12s`。 */
|
|
4186
|
+
function sessionLine(s) {
|
|
4187
|
+
const id = s.identity;
|
|
4188
|
+
const snap = s.snapshot;
|
|
4189
|
+
const state = snap.busy ? "busy" : snap.state === "dead" ? "died" : `idle ${Math.round((snap.idleMs ?? 0) / 1e3)}s`;
|
|
4190
|
+
return `${id.id}${id.label !== void 0 ? ` (label ${id.label})` : ""} ${id.connection}${id.byo ? " (byo-pty)" : ""} ${state}`;
|
|
4191
|
+
}
|
|
2871
4192
|
|
|
2872
4193
|
//#endregion
|
|
2873
4194
|
//#region src/remote/jobs.ts
|
|
4195
|
+
/** PTY job 的单通道输出:流在 PTY 里天然合并,无独立 stderr 通道(P5 如实披露)。
|
|
4196
|
+
* read 是 byte-cursor 增量(Utf16TailRing.read 语义:逐字节游标 + lossy 报尾环逐出)。 */
|
|
4197
|
+
const ptyOutputSources = (holder) => [{
|
|
4198
|
+
channel: "stdout",
|
|
4199
|
+
read: (fromByte) => holder.job?.read(fromByte) ?? {
|
|
4200
|
+
text: "",
|
|
4201
|
+
nextOffset: fromByte,
|
|
4202
|
+
lossy: false
|
|
4203
|
+
}
|
|
4204
|
+
}];
|
|
4205
|
+
/** 0.3.2-d CF:timedOut=true 且 aborted=false = 会话侧主动收束(close force / 行回收走的
|
|
4206
|
+
* dispose→interrupt 两段路)——同为 killed;exit 到手用 exit,只剩会话死亡时写 session closed。 */
|
|
4207
|
+
const ptyOutcome = (aborted, result) => {
|
|
4208
|
+
const interrupted = aborted || result.timedOut === true;
|
|
4209
|
+
return {
|
|
4210
|
+
status: interrupted ? "killed" : result.exit === null ? "failed" : "completed",
|
|
4211
|
+
detail: interrupted ? `interrupted: ${result.exit === null ? aborted ? "session died" : "session closed" : `exit ${result.exit}`}` : result.exit === null ? "session died" : `exit code: ${result.exit}`
|
|
4212
|
+
};
|
|
4213
|
+
};
|
|
2874
4214
|
/** No preparation or discovery before the official registry's admission. */
|
|
2875
4215
|
function startRemoteJob(registry, input, exec, driver) {
|
|
2876
|
-
if (input.mode === "pty" || input.spawn !== void 0 || input.target?.startsWith("byop:")) throw new Error("remote: background execution requires oneshot; PTY and BYO-PTY are unsupported");
|
|
2877
4216
|
if (!exec.agent) throw new Error("remote: background jobs require a live Agent owner");
|
|
4217
|
+
const form = parseTargetForm(input.target);
|
|
4218
|
+
if (form.form === "pty-selector" || form.form === "create-pty" || form.form === "hub-pty" || input.spawn !== void 0 || input.mode === "pty") {
|
|
4219
|
+
const holder = {};
|
|
4220
|
+
return registry.start({
|
|
4221
|
+
kind: "remote",
|
|
4222
|
+
owner: exec.agent.id,
|
|
4223
|
+
label: `${input.target}: ${input.cmd}`,
|
|
4224
|
+
output: ptyOutputSources(holder),
|
|
4225
|
+
run(job) {
|
|
4226
|
+
const controller = new AbortController();
|
|
4227
|
+
return {
|
|
4228
|
+
done: (async () => {
|
|
4229
|
+
try {
|
|
4230
|
+
const r = await driver.call({
|
|
4231
|
+
...input,
|
|
4232
|
+
mode: "pty"
|
|
4233
|
+
}, {
|
|
4234
|
+
ptyBackground: true,
|
|
4235
|
+
commandId: job.id,
|
|
4236
|
+
sessionKey: exec.agent?.id ?? "no-session"
|
|
4237
|
+
});
|
|
4238
|
+
if (r.running !== true || r.ptyJob === void 0) return {
|
|
4239
|
+
status: "failed",
|
|
4240
|
+
detail: "pty dispatch did not hand off a running job"
|
|
4241
|
+
};
|
|
4242
|
+
holder.job = r.ptyJob;
|
|
4243
|
+
if (controller.signal.aborted) r.ptyJob.interrupt();
|
|
4244
|
+
const outcome = await r.ptyJob.done;
|
|
4245
|
+
return ptyOutcome(controller.signal.aborted, outcome);
|
|
4246
|
+
} catch (error) {
|
|
4247
|
+
return {
|
|
4248
|
+
status: controller.signal.aborted ? "killed" : "failed",
|
|
4249
|
+
detail: error instanceof Error ? error.message : String(error)
|
|
4250
|
+
};
|
|
4251
|
+
}
|
|
4252
|
+
})(),
|
|
4253
|
+
cancel(reason) {
|
|
4254
|
+
if (controller.signal.aborted) return;
|
|
4255
|
+
controller.abort(reason);
|
|
4256
|
+
holder.job?.interrupt();
|
|
4257
|
+
}
|
|
4258
|
+
};
|
|
4259
|
+
}
|
|
4260
|
+
});
|
|
4261
|
+
}
|
|
2878
4262
|
let process$1;
|
|
2879
4263
|
const output = ["stdout", "stderr"].map((channel) => ({
|
|
2880
4264
|
channel,
|
|
@@ -2894,7 +4278,7 @@ function startRemoteJob(registry, input, exec, driver) {
|
|
|
2894
4278
|
return registry.start({
|
|
2895
4279
|
kind: "remote",
|
|
2896
4280
|
owner: exec.agent.id,
|
|
2897
|
-
label: `${input.target}: ${input.cmd
|
|
4281
|
+
label: `${input.target}: ${input.cmd}`,
|
|
2898
4282
|
output,
|
|
2899
4283
|
run() {
|
|
2900
4284
|
const controller = new AbortController();
|
|
@@ -2904,7 +4288,7 @@ function startRemoteJob(registry, input, exec, driver) {
|
|
|
2904
4288
|
process$1 = await driver.start({
|
|
2905
4289
|
...input,
|
|
2906
4290
|
mode: "oneshot"
|
|
2907
|
-
}, controller.signal);
|
|
4291
|
+
}, controller.signal, { sessionKey: exec.agent?.id ?? "no-session" });
|
|
2908
4292
|
if (controller.signal.aborted) process$1.cancel(controller.signal.reason);
|
|
2909
4293
|
const result = await process$1.done;
|
|
2910
4294
|
const diagnostic = process$1.read("stderr", 0).diagnostic;
|
|
@@ -2928,82 +4312,351 @@ function startRemoteJob(registry, input, exec, driver) {
|
|
|
2928
4312
|
}
|
|
2929
4313
|
});
|
|
2930
4314
|
}
|
|
4315
|
+
/** P4(2026-10-19)handoff 收养:同步 pty dispatch 超时后命令仍在跑——注册成 job,
|
|
4316
|
+
* job_output 即增量轮询、job_kill 即显式中断(P8 ^C+130-marker,会话存活)。 */
|
|
4317
|
+
function adoptRunningPtyJob(registry, exec, label, job) {
|
|
4318
|
+
if (!exec.agent) throw new Error("remote: background jobs require a live Agent owner");
|
|
4319
|
+
return registry.start({
|
|
4320
|
+
kind: "remote",
|
|
4321
|
+
owner: exec.agent.id,
|
|
4322
|
+
label,
|
|
4323
|
+
output: ptyOutputSources({ job }),
|
|
4324
|
+
run() {
|
|
4325
|
+
const controller = new AbortController();
|
|
4326
|
+
return {
|
|
4327
|
+
done: (async () => {
|
|
4328
|
+
if (controller.signal.aborted) job.interrupt();
|
|
4329
|
+
const outcome = await job.done;
|
|
4330
|
+
return ptyOutcome(controller.signal.aborted, outcome);
|
|
4331
|
+
})(),
|
|
4332
|
+
cancel(reason) {
|
|
4333
|
+
if (controller.signal.aborted) return;
|
|
4334
|
+
controller.abort(reason);
|
|
4335
|
+
job.interrupt();
|
|
4336
|
+
}
|
|
4337
|
+
};
|
|
4338
|
+
}
|
|
4339
|
+
});
|
|
4340
|
+
}
|
|
2931
4341
|
|
|
2932
4342
|
//#endregion
|
|
2933
4343
|
//#region src/remote/tool.ts
|
|
2934
|
-
const NO_SESSION_KEY = "remote:no-session";
|
|
4344
|
+
const NO_SESSION_KEY$1 = "remote:no-session";
|
|
2935
4345
|
/**
|
|
2936
|
-
* The model-visible surface of the `remote` tool.
|
|
2937
|
-
*
|
|
2938
|
-
*
|
|
4346
|
+
* The model-visible surface of the `remote` tool (0.3.2-d user-ruled restructure:
|
|
4347
|
+
* Actions / Targets / PTY / Oneshot / Examples — the PTY block is the user's verbatim
|
|
4348
|
+
* final draft; Examples receipts match renderValue byte-for-byte).
|
|
4349
|
+
* ONE template literal — no backticks, no "${".
|
|
4350
|
+
*
|
|
4351
|
+
* 语义目标(surface 就是产品):动作是唯一的派发维度;PTY 四词定位——stateful oneshot /
|
|
4352
|
+
* interact-able stdin / managed output / persistent env——回执形状与 oneshot 相同、只增状态,
|
|
4353
|
+
* 运行中的命令可分步观察后再补输(input 动作);多步与交互任务默认进 PTY。
|
|
2939
4354
|
*/
|
|
2940
|
-
const REMOTE_TOOL_DESCRIPTION = `Remote
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
4355
|
+
const REMOTE_TOOL_DESCRIPTION = `Remote shell over ssh / docker / incus (Hub when configured): stateless oneshots + persistent interactive PTY sessions. Default to PTY for multi-step or interactive work; oneshot for isolated commands.
|
|
4356
|
+
|
|
4357
|
+
Actions (action is the only dispatch dimension; unknown fields are rejected):
|
|
4358
|
+
- exec {target, cmd | scriptPath, stdin?, timeout?, run_in_background?}: run a command. Machine target → oneshot; pty:<id|label> → run inside that live session; <machine>:pty[:label] → create a NEW session and run there.
|
|
4359
|
+
- add {ssh:{...} | spawn:"<cmd>", target?}: register a BYO endpoint (identity or interactive-shell command); no command runs. Returns the addressable label; a taken label answers [E_LABEL_IN_USE] — address existing names directly, never add again.
|
|
4360
|
+
- status {}: roster — the one unified pool (machines, identities, live PTY sessions).
|
|
4361
|
+
- status {target}: machine probe, or a session card (connection, cwd, ledger of the last 20 commands).
|
|
4362
|
+
- input {target:"pty:<id|label>", stdin, commandId?}: write stdin into the command currently running in that session — passwords, OTP, tokens, menu choices, REPL lines. Never creates a session, never dials.
|
|
4363
|
+
- close {target, force?}: close a PTY session; a running command refuses it (job_kill first) unless force:true kills it in the same step.
|
|
4364
|
+
|
|
4365
|
+
Targets:
|
|
4366
|
+
- ssh:<name> / docker:<name> / incus:<name> / bare pool name → stateless oneshot.
|
|
4367
|
+
- <machine>:pty[:label] → NEW PTY every call — creation is a target suffix, not a different tool.
|
|
4368
|
+
- pty:<id|label> (or its bare label) → REUSE the live session.
|
|
4369
|
+
After creation, reuse the returned session; repeating :pty opens another. Prefixes force the channel; bare names resolve through the roster.
|
|
4370
|
+
|
|
4371
|
+
PTY:
|
|
4372
|
+
- stateful oneshot, interact-able stdin, managed output, persistent env
|
|
4373
|
+
- timeout (default 120s) → command keeps running; returns job handle.
|
|
4374
|
+
- run_in_background → same job lane. jobId = commandId.
|
|
4375
|
+
- Read: job_output(jobId). Cancel: job_kill; try Ctrl-C first.
|
|
4376
|
+
- Busy session: input / poll / cancel / use another session.
|
|
4377
|
+
- exec.stdin = startup input; input = subsequent input.
|
|
4378
|
+
- input is verbatim: "\\n" submits; "\\u0003" Ctrl-C; "\\u0004" Ctrl-D; "" writes nothing. Ctrl-D follows terminal EOF rules.
|
|
4379
|
+
- commandId, if supplied, must match running command.
|
|
4380
|
+
- Input receipt confirms write only; read result via SAME job.
|
|
4381
|
+
- Output may truncate (~30k chars per read); redirect bulk output to files.
|
|
4382
|
+
- Idle expiry: 15 min; running commands exempt.
|
|
4383
|
+
|
|
4384
|
+
Oneshot:
|
|
4385
|
+
- stdout/stderr separate, exit code verbatim; no retained shell state. stdin is startup-only: there is no input after start — a prompt on a oneshot means cancel (job_kill) and switch to PTY. Heredocs and input redirection remain valid bulk-input alternatives.
|
|
4386
|
+
- Supervision prefers a pinned superd-run helper cached on the endpoint (~/.cache/superd/run), falls back to a POSIX shim — the receipt field "runner" says which ran. Either way children are reaped on completion and the whole group is killed on timeout/cancel. The endpoint needs bash only — no Python.
|
|
4387
|
+
- scriptPath (oneshot only): a LOCAL absolute script read before any dialing, sent literally over stdin to a fixed bash -s — the file carrier for multi-line scripts; pairs with neither cmd nor stdin.
|
|
4388
|
+
|
|
4389
|
+
Examples
|
|
4390
|
+
|
|
4391
|
+
Manage the persistent PTY session. One-shot style output, but stable: every command returns synchronously with exit, cwd, and an env delta.
|
|
2948
4392
|
|
|
2949
|
-
|
|
4393
|
+
No direct route to the endpoint? Compose the transport and land the session on the innermost machine — bring your own PTY. Here: borrow pc as a jump host to reach dev4.
|
|
2950
4394
|
|
|
2951
|
-
|
|
4395
|
+
remote { "action": "add", "spawn": "ssh -t pc ssh -t dev4", "target": "pty:dev4via" }
|
|
2952
4396
|
|
|
2953
|
-
|
|
4397
|
+
[session created — address it as pty:pty-irsq]
|
|
4398
|
+
[pty:pty-irsq (dev4via) (byo-pty) · conn BYOP · idle-left ~15m · exit null · 0.0s]
|
|
4399
|
+
|
|
4400
|
+
remote { "action": "exec", "target": "pty:dev4via", "cmd": "hostname && sudo -n ss -tlnp | awk 'NR==1 || /LISTEN/' | head -5" }
|
|
4401
|
+
|
|
4402
|
+
dev4
|
|
4403
|
+
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
|
|
4404
|
+
LISTEN 0 4096 127.0.0.1:45207 0.0.0.0:* users:(("containerd",pid=1070,fd=14))
|
|
4405
|
+
LISTEN 0 4096 127.0.0.1:2019 0.0.0.0:* users:(("caddy",pid=5600,fd=4))
|
|
4406
|
+
LISTEN 0 4096 127.0.0.1:19514 0.0.0.0:* users:(("multica",pid=27030,fd=6))
|
|
4407
|
+
LISTEN 0 4096 127.0.0.54:53 0.0.0.0:* users:(("systemd-resolve",pid=26758,fd=17))
|
|
4408
|
+
[pty:pty-irsq (dev4via) (byo-pty) · conn BYOP · cmd remote-0d89215d1cc64cdc · cwd /home/u1 · idle-left ~15m · exit 0 · 0.3s]
|
|
4409
|
+
|
|
4410
|
+
Reuse the same session for a long task — returns a jobId immediately; collect with job_output, cancel with job_kill:
|
|
4411
|
+
|
|
4412
|
+
remote { "action": "exec", "target": "pty:dev4via", "cmd": "for i in 1 2 3; do sleep 1; echo \\"tick $i\\"; done; echo done", "run_in_background": true }
|
|
4413
|
+
|
|
4414
|
+
Started remote-47676dff2c6443e8 on pty:pty-irsq (dev4via) (BYOP). Use job_output to read and job_kill to cancel; completion is reported by the host.
|
|
4415
|
+
|
|
4416
|
+
job_output { "job_id": "remote-47676dff2c6443e8", "wait": true }
|
|
4417
|
+
|
|
4418
|
+
tick 1
|
|
4419
|
+
tick 2
|
|
4420
|
+
tick 3
|
|
4421
|
+
done
|
|
4422
|
+
[status: completed, exit code: 0]
|
|
4423
|
+
|
|
4424
|
+
- Bring Your Own PTY fits when the endpoint has no direct route, or the connection/transport layer must be composed yourself (jump chains, docker exec, console servers).
|
|
4425
|
+
- It also strips one or two shell-escaping layers — commands go straight to the innermost bash, quotes behave naturally.
|
|
4426
|
+
|
|
4427
|
+
Register once — the label enters the pool and works everywhere: exec, pty, copy, rsync. Worth it whenever more than one operation type is involved. Keys stay local-file references; nothing persisted.
|
|
4428
|
+
|
|
4429
|
+
remote { "action": "add", "ssh": { "host": "10.0.0.8", "user": "u1", "port": 22, "key": "/home/u1/.ssh/id_key4" }, "target": "ssh:lab" }
|
|
4430
|
+
remote { "action": "exec", "target": "ssh:lab", "cmd": "uname -a" }
|
|
4431
|
+
remote_transfer { "mode": "rsync", "src": "ssh:lab:/var/log/app/", "dst": "/home/u1/app-logs/", "argv": ["-a"] }`;
|
|
4432
|
+
/** action 是唯一派发维度:每个动词声明自己的字段集,超出即报错(不做在场推断、不留别名)。 */
|
|
4433
|
+
const ACTION_PARAMS = {
|
|
4434
|
+
exec: new Set([
|
|
4435
|
+
"action",
|
|
4436
|
+
"target",
|
|
4437
|
+
"cmd",
|
|
4438
|
+
"stdin",
|
|
4439
|
+
"scriptPath",
|
|
4440
|
+
"timeout",
|
|
4441
|
+
"run_in_background"
|
|
4442
|
+
]),
|
|
4443
|
+
add: new Set([
|
|
4444
|
+
"action",
|
|
4445
|
+
"target",
|
|
4446
|
+
"ssh",
|
|
4447
|
+
"spawn"
|
|
4448
|
+
]),
|
|
4449
|
+
status: new Set(["action", "target"]),
|
|
4450
|
+
close: new Set([
|
|
4451
|
+
"action",
|
|
4452
|
+
"target",
|
|
4453
|
+
"force"
|
|
4454
|
+
]),
|
|
4455
|
+
input: new Set([
|
|
4456
|
+
"action",
|
|
4457
|
+
"target",
|
|
4458
|
+
"stdin",
|
|
4459
|
+
"commandId"
|
|
4460
|
+
])
|
|
4461
|
+
};
|
|
4462
|
+
const ACTION_HINT = {
|
|
4463
|
+
exec: "exec takes target plus cmd (or scriptPath) and the execution options; ssh/spawn belong to add",
|
|
4464
|
+
add: "add takes exactly one of ssh or spawn, plus an optional target label",
|
|
4465
|
+
status: "status takes only an optional target — omit it for the roster",
|
|
4466
|
+
close: "close takes target pty:<id|label> and optional force",
|
|
4467
|
+
input: "input takes target (a live PTY session), stdin, and an optional commandId guard — no cmd, no timeout, no creation"
|
|
4468
|
+
};
|
|
4469
|
+
async function remoteExecute(ENV, args, exec) {
|
|
4470
|
+
const action = args.action;
|
|
4471
|
+
if (action === void 0) throw new Error("[E_PARAMS] remote: action is required — \"exec\" (run a command), \"add\" (register a BYO endpoint), \"status\" (roster / probe / session card), \"close\" (close a PTY session), \"input\" (append stdin to a running PTY command)");
|
|
4472
|
+
const allowed = ACTION_PARAMS[action];
|
|
4473
|
+
if (allowed === void 0) throw new Error(`[E_PARAMS] remote: unknown action ${JSON.stringify(String(action))} — one of exec / add / close / status / input`);
|
|
4474
|
+
for (const key of Object.keys(args)) if (!allowed.has(key)) throw new Error(`[E_PARAMS] remote: "${key}" does not belong to action "${action}" — ${ACTION_HINT[action]}`);
|
|
4475
|
+
const sessionKey = ENV.getSessionKey(exec);
|
|
4476
|
+
const hasTarget = typeof args.target === "string" && args.target.length > 0;
|
|
4477
|
+
const hasCmd = typeof args.cmd === "string" && args.cmd.length > 0;
|
|
4478
|
+
if (action === "status") {
|
|
4479
|
+
if (!hasTarget) return {
|
|
4480
|
+
kind: "roster",
|
|
4481
|
+
text: await ENV.driver.roster({ sessionKey }),
|
|
4482
|
+
exit: null,
|
|
4483
|
+
durationMs: 0
|
|
4484
|
+
};
|
|
4485
|
+
return {
|
|
4486
|
+
kind: "status",
|
|
4487
|
+
text: await ENV.driver.status(args.target, { sessionKey }),
|
|
4488
|
+
exit: null,
|
|
4489
|
+
durationMs: 0
|
|
4490
|
+
};
|
|
4491
|
+
}
|
|
4492
|
+
if (action === "close") {
|
|
4493
|
+
if (!hasTarget) throw new Error("[E_PARAMS] close requires target pty:<id|label>");
|
|
4494
|
+
const r$1 = ENV.driver.closePty(args.target.startsWith("pty:") ? args.target.slice(4) : args.target, sessionKey, args.force === true);
|
|
4495
|
+
return {
|
|
4496
|
+
kind: "close",
|
|
4497
|
+
text: r$1.closed ? `closed ${r$1.session} (${r$1.connection})${r$1.killed.length > 0 ? ` — killed running job ${r$1.killed.join(", ")}` : ""}` : `${r$1.session}: not closed (${r$1.reason}) — ${r$1.message ?? "no live session"}`,
|
|
4498
|
+
exit: null,
|
|
4499
|
+
durationMs: 0,
|
|
4500
|
+
session: r$1.session,
|
|
4501
|
+
closed: r$1.closed,
|
|
4502
|
+
...r$1.reason !== void 0 ? { reason: r$1.reason } : {},
|
|
4503
|
+
killed: r$1.killed
|
|
4504
|
+
};
|
|
4505
|
+
}
|
|
4506
|
+
if (action === "input") {
|
|
4507
|
+
if (!hasTarget) throw new Error("[E_PARAMS] remote: action \"input\" requires target — the live PTY session whose command is waiting (pty:<id|label> or its bare label)");
|
|
4508
|
+
if (args.stdin === void 0) throw new Error("[E_PARAMS] remote: action \"input\" requires stdin — the exact text to append; include a trailing \\n to submit a line, \"\\u0003\" for Ctrl-C, \"\\u0004\" for Ctrl-D (\"\" = zero bytes, not EOF)");
|
|
4509
|
+
if (typeof args.commandId === "string" && args.commandId.length === 0) throw new Error("[E_PARAMS] remote: input: commandId, when given, must be the non-empty id from the exec receipt / job_output");
|
|
4510
|
+
const r$1 = await ENV.driver.input(args.target, {
|
|
4511
|
+
stdin: args.stdin,
|
|
4512
|
+
...args.commandId !== void 0 ? { commandId: args.commandId } : {}
|
|
4513
|
+
}, { sessionKey });
|
|
4514
|
+
const handle = r$1.jobId ?? r$1.commandId;
|
|
4515
|
+
return {
|
|
4516
|
+
kind: "input",
|
|
4517
|
+
text: `wrote ${r$1.writtenBytes} byte${r$1.writtenBytes === 1 ? "" : "s"} into ${r$1.session} for command ${r$1.commandId} — this confirms the write, not the program's response; read the response with job_output ${handle}`,
|
|
4518
|
+
exit: null,
|
|
4519
|
+
durationMs: 0,
|
|
4520
|
+
session: r$1.session,
|
|
4521
|
+
connection: r$1.connection,
|
|
4522
|
+
...r$1.label !== void 0 ? { label: r$1.label } : {},
|
|
4523
|
+
commandId: r$1.commandId,
|
|
4524
|
+
...r$1.jobId !== void 0 ? { jobId: r$1.jobId } : {},
|
|
4525
|
+
writtenBytes: r$1.writtenBytes
|
|
4526
|
+
};
|
|
4527
|
+
}
|
|
4528
|
+
if (action === "add") {
|
|
4529
|
+
const hasSpawn = typeof args.spawn === "string" && args.spawn.length > 0;
|
|
4530
|
+
if (args.spawn !== void 0 && !hasSpawn) throw new Error("[E_PARAMS] remote: add: spawn must be a non-empty command string");
|
|
4531
|
+
if (args.ssh === void 0 && !hasSpawn) throw new Error("[E_PARAMS] remote: action \"add\" registers a BYO endpoint — pass ssh:{host,...} (identity) or spawn:\"<command>\" (PTY), exactly one");
|
|
4532
|
+
if (args.ssh !== void 0 && hasSpawn) throw new Error("[E_PARAMS] remote: add: ssh and spawn are two different BYO entry points — pass one, not both");
|
|
4533
|
+
const r$1 = await ENV.driver.call({
|
|
4534
|
+
...hasTarget ? { target: args.target } : {},
|
|
4535
|
+
...args.ssh === void 0 ? {} : { ssh: args.ssh },
|
|
4536
|
+
...hasSpawn ? { spawn: args.spawn } : {},
|
|
4537
|
+
cmd: ""
|
|
4538
|
+
}, { sessionKey });
|
|
4539
|
+
const v$1 = workbenchValue(r$1);
|
|
4540
|
+
v$1.created = true;
|
|
4541
|
+
if (!hasSpawn) v$1.notice = `registered — address it as ${r$1.session ?? r$1.target} from now on (the label, id and ssh alias all work)`;
|
|
4542
|
+
return v$1;
|
|
4543
|
+
}
|
|
4544
|
+
if (!hasTarget) throw new Error("[E_PARAMS] remote: action \"exec\" requires target — a machine (ssh:dev4, docker:corti, hub:<m4>, a pool name) or a PTY session (pty:<id|label>, a bare label, or <machine>:pty[:label] to create one). Status probes and the roster live under action \"status\".");
|
|
4545
|
+
const target = args.target;
|
|
4546
|
+
const ptyTarget = /^pty:/.test(target) || /:pty(:|$)/.test(target);
|
|
4547
|
+
if (args.scriptPath !== void 0) {
|
|
4548
|
+
if (args.scriptPath.length === 0) throw new Error("[E_PARAMS] remote: scriptPath must be a non-empty absolute path");
|
|
4549
|
+
if (ptyTarget) throw new Error("[E_SCRIPT_PARAMS] remote: scriptPath is oneshot-only — PTY lanes take cmd");
|
|
4550
|
+
if (hasCmd) throw new Error("[E_SCRIPT_PARAMS] remote: scriptPath and cmd are alternative carriers — pass one");
|
|
4551
|
+
if (args.stdin !== void 0) throw new Error("[E_SCRIPT_PARAMS] remote: scriptPath already occupies stdin — do not pass stdin with it");
|
|
4552
|
+
}
|
|
4553
|
+
if (args.stdin !== void 0 && !hasCmd) throw new Error("[E_STDIN_WITHOUT_CMD] remote: exec stdin is startup input and requires cmd — to feed a command that is already running in a PTY, use {action:\"input\", target:\"pty:<id|label>\", stdin}");
|
|
4554
|
+
if (!hasCmd && args.scriptPath === void 0) throw new Error("[E_PARAMS] remote: action \"exec\" must execute something — pass cmd, or scriptPath for a local script file");
|
|
4555
|
+
if (args.run_in_background) {
|
|
4556
|
+
const jobs = exec.agent?.ctx.get("jobs");
|
|
4557
|
+
if (!jobs) throw new Error("remote: background requires the official DSH jobs service and job_output/job_kill controller; foreground execution remains available");
|
|
4558
|
+
const lane = await ENV.driver.preparePtyLane({
|
|
4559
|
+
target: args.target,
|
|
4560
|
+
cmd: args.cmd,
|
|
4561
|
+
scriptPath: args.scriptPath,
|
|
4562
|
+
stdin: args.stdin,
|
|
4563
|
+
timeout: args.timeout
|
|
4564
|
+
}, { sessionKey });
|
|
4565
|
+
let jobId;
|
|
4566
|
+
try {
|
|
4567
|
+
jobId = startRemoteJob(jobs, lane !== void 0 ? lane.input : {
|
|
4568
|
+
target: args.target,
|
|
4569
|
+
cmd: args.cmd,
|
|
4570
|
+
scriptPath: args.scriptPath,
|
|
4571
|
+
stdin: args.stdin,
|
|
4572
|
+
timeout: args.timeout
|
|
4573
|
+
}, exec, ENV.driver);
|
|
4574
|
+
} catch (error) {
|
|
4575
|
+
lane?.cleanup();
|
|
4576
|
+
throw error;
|
|
4577
|
+
}
|
|
4578
|
+
const where = lane === void 0 ? "" : ` on ${lane.session}${lane.label !== void 0 ? ` (${lane.label})` : ""} (${lane.connection})`;
|
|
4579
|
+
return {
|
|
4580
|
+
kind: "job",
|
|
4581
|
+
jobId,
|
|
4582
|
+
exit: null,
|
|
4583
|
+
durationMs: 0,
|
|
4584
|
+
text: `Started ${jobId}${where}. Use job_output to read and job_kill to cancel; completion is reported by the host.`,
|
|
4585
|
+
...lane !== void 0 ? {
|
|
4586
|
+
commandId: jobId,
|
|
4587
|
+
session: lane.session,
|
|
4588
|
+
connection: lane.connection,
|
|
4589
|
+
...lane.label !== void 0 ? { label: lane.label } : {}
|
|
4590
|
+
} : {}
|
|
4591
|
+
};
|
|
4592
|
+
}
|
|
4593
|
+
const r = await ENV.driver.call({
|
|
4594
|
+
target: args.target,
|
|
4595
|
+
cmd: args.cmd,
|
|
4596
|
+
scriptPath: args.scriptPath,
|
|
4597
|
+
stdin: args.stdin,
|
|
4598
|
+
timeout: args.timeout
|
|
4599
|
+
}, { sessionKey });
|
|
4600
|
+
const v = workbenchValue(r);
|
|
4601
|
+
if (r.running === true && r.ptyJob !== void 0) {
|
|
4602
|
+
const jobs = exec.agent?.ctx.get("jobs");
|
|
4603
|
+
if (jobs) {
|
|
4604
|
+
const jobId = adoptRunningPtyJob(jobs, exec, `${r.target}: ${args.cmd}`, r.ptyJob);
|
|
4605
|
+
v.jobId = jobId;
|
|
4606
|
+
v.running = true;
|
|
4607
|
+
if (r.commandId !== void 0 && jobId !== r.commandId) ENV.driver.attachPtyJob(r.commandId, jobId, sessionKey);
|
|
4608
|
+
} else {
|
|
4609
|
+
r.ptyJob.interrupt();
|
|
4610
|
+
v.notice = "The command outlived its synchronous wait and no jobs service is available to poll it, so it was interrupted. Use run_in_background:true for long commands.";
|
|
4611
|
+
}
|
|
4612
|
+
}
|
|
4613
|
+
return v;
|
|
4614
|
+
}
|
|
2954
4615
|
function createRemoteTool(driver, opts = {}) {
|
|
2955
|
-
const getSessionKey = opts.getSessionKey ?? ((exec) => exec.agent?.id ?? NO_SESSION_KEY);
|
|
4616
|
+
const getSessionKey = opts.getSessionKey ?? ((exec) => exec.agent?.id ?? NO_SESSION_KEY$1);
|
|
2956
4617
|
const tool = defineTool({
|
|
2957
4618
|
name: "remote",
|
|
2958
4619
|
description: REMOTE_TOOL_DESCRIPTION,
|
|
2959
4620
|
parameters: {
|
|
2960
4621
|
action: {
|
|
2961
4622
|
type: "string",
|
|
2962
|
-
enum: [
|
|
2963
|
-
|
|
4623
|
+
enum: [
|
|
4624
|
+
"exec",
|
|
4625
|
+
"add",
|
|
4626
|
+
"status",
|
|
4627
|
+
"close",
|
|
4628
|
+
"input"
|
|
4629
|
+
],
|
|
4630
|
+
required: true,
|
|
4631
|
+
description: "Required. exec = run a command (oneshot on a machine, or inside a PTY session); add = register a BYO ssh identity or BYO PTY into the pool; status = roster (no target) or probe/session card (target); close = close a PTY session; input = append stdin to the command currently running in a live PTY session."
|
|
2964
4632
|
},
|
|
2965
|
-
|
|
4633
|
+
target: {
|
|
2966
4634
|
type: "string",
|
|
2967
|
-
description: "
|
|
4635
|
+
description: "exec: required. A machine (bare pool name, ssh:<name>, docker:<name>, incus:<name>, hub:<m4>), a live PTY session (pty:<id|label> or its bare label), or a machine with :pty[:label] to create a new session (ssh:dev4:pty, hub:<m4>:pty, ssh:dev4:pty:build). add: optional label for the BYO entry. status: optional — omit for the roster. close / input: pty:<id|label> (input never creates or dials — the session must already run the command)."
|
|
2968
4636
|
},
|
|
2969
|
-
|
|
4637
|
+
cmd: {
|
|
2970
4638
|
type: "string",
|
|
2971
|
-
description: "
|
|
2972
|
-
},
|
|
2973
|
-
argv: {
|
|
2974
|
-
type: "array",
|
|
2975
|
-
items: { type: "string" },
|
|
2976
|
-
description: "Ordered native CLI options and values for one-command routes (e.g. rsync [\"-a\",\"--partial\",\"--dry-run\"], scp [\"-p\"], docker cp [\"-a\"], incus file push/pull). One element = one argv token, appended verbatim before src/dst; no shell parsing, no whitelist, no forced defaults — unknown options fail in the native CLI itself. rsync only (SSH endpoints): explicit -e/--rsh overrides the tool's SSH wiring. Two-segment cross-endpoint copy uses pullArgv/pushArgv instead."
|
|
4639
|
+
description: "exec: one raw shell string parsed by the remote bash (multi-line = one compound; exit = last command's). Required unless scriptPath is given."
|
|
2977
4640
|
},
|
|
2978
|
-
|
|
2979
|
-
type: "
|
|
2980
|
-
|
|
2981
|
-
description: "Options for the PULL half (source endpoint → origin staging) of a two-command cross-endpoint copy (e.g. SSH↔Docker, SSH↔Incus, Docker↔Incus). Mutually exclusive with argv; must be paired with pushArgv. Only options valid for the pull half's CLI."
|
|
2982
|
-
},
|
|
2983
|
-
pushArgv: {
|
|
2984
|
-
type: "array",
|
|
2985
|
-
items: { type: "string" },
|
|
2986
|
-
description: "Options for the PUSH half (origin staging → destination endpoint) of a two-command cross-endpoint copy. Mutually exclusive with argv; must be paired with pullArgv. Only options valid for the push half's CLI."
|
|
4641
|
+
stdin: {
|
|
4642
|
+
type: "string",
|
|
4643
|
+
description: "exec: startup input fed to cmd — oneshot: piped to stdin; pty: written right after the command line (REPL-style); requires cmd. input: the exact text to append to the RUNNING command — \"\" writes zero bytes (not EOF); include \"\\n\" to submit a line; \"\\u0003\" = Ctrl-C, \"\\u0004\" = Ctrl-D as raw characters."
|
|
2987
4644
|
},
|
|
2988
|
-
|
|
2989
|
-
type: "
|
|
2990
|
-
description: "
|
|
4645
|
+
commandId: {
|
|
4646
|
+
type: "string",
|
|
4647
|
+
description: "input only: optional guard — when given it must equal the running command's id (from the exec receipt or job_output); a stale id refuses the write instead of feeding the next command. Ignored by other actions."
|
|
2991
4648
|
},
|
|
2992
|
-
|
|
2993
|
-
type: "
|
|
2994
|
-
description: "
|
|
4649
|
+
timeout: {
|
|
4650
|
+
type: "number",
|
|
4651
|
+
description: "exec: per-command timeout in seconds (default 120). oneshot: interrupts then kills the whole group. pty: the command is NOT killed on timeout — it hands off to a running job you can poll (job_output) and cancel (job_kill = Ctrl-C first; the session survives an interrupt)."
|
|
2995
4652
|
},
|
|
2996
4653
|
run_in_background: {
|
|
2997
4654
|
type: "boolean",
|
|
2998
|
-
description: "
|
|
2999
|
-
},
|
|
3000
|
-
target: {
|
|
3001
|
-
type: "string",
|
|
3002
|
-
description: "Single entry point. byossh:<label> reuses this Agent-scoped registered SSH identity (pass ssh on first call; no cmd registers only). Bare name / IP / domain matches in order: ssh config, then docker, then incus, then a live pty label (a collision goes to the earlier source). \"byop:<label>\" / \"docker:<name>\" / \"incus:<name>\" / \"ssh:<name>\" force a channel. For \"byop:<label>\", pass spawn the first time to create it and omit spawn afterwards to reuse it. Omit cmd → status probe."
|
|
4655
|
+
description: "exec: oneshot AND pty — return a native jobId immediately, read with job_output, cancel with job_kill; output is available while running. On pty lanes the jobId IS the commandId — it tracks the running command inside a persistent session; job_kill sends Ctrl-C and the session survives. Requires the official jobs service/controller."
|
|
3003
4656
|
},
|
|
3004
4657
|
ssh: {
|
|
3005
4658
|
type: "object",
|
|
3006
|
-
description: "
|
|
4659
|
+
description: "add: BYO ssh identity to register into the pool (no dialing). Later exec calls address the returned label. No inline keys or arbitrary SSH options; nothing is persisted — a new Agent registers again.",
|
|
3007
4660
|
additionalProperties: false,
|
|
3008
4661
|
properties: {
|
|
3009
4662
|
host: {
|
|
@@ -3031,28 +4684,11 @@ function createRemoteTool(driver, opts = {}) {
|
|
|
3031
4684
|
},
|
|
3032
4685
|
spawn: {
|
|
3033
4686
|
type: "string",
|
|
3034
|
-
description: "
|
|
3035
|
-
},
|
|
3036
|
-
cmd: {
|
|
3037
|
-
type: "string",
|
|
3038
|
-
description: "One raw shell string parsed by the remote bash (multi-line = one compound; exit = last command's). Omit with target → status probe; omit everything → roster."
|
|
3039
|
-
},
|
|
3040
|
-
script: {
|
|
3041
|
-
type: "string",
|
|
3042
|
-
description: "LOCAL absolute script path. Read before any dialing, sent literally over stdin to fixed bash -s. Oneshot only; cannot combine with cmd, stdin, spawn, pty mode or byop target. Hub inline cmd remains limited to 4096; script body is not argv."
|
|
3043
|
-
},
|
|
3044
|
-
mode: {
|
|
3045
|
-
type: "string",
|
|
3046
|
-
enum: ["oneshot", "pty"],
|
|
3047
|
-
description: "'oneshot' (default): stateless `bash -lc`, stdout/stderr separate, exit code is the process's own. 'pty': one persistent shell per (agent, target), cwd/env survive, streams merge, idle TTL 600s. A \"byop:<label>\" target locks mode to 'pty'."
|
|
3048
|
-
},
|
|
3049
|
-
stdin: {
|
|
3050
|
-
type: "string",
|
|
3051
|
-
description: "Input fed to the command. oneshot: piped to stdin. pty: written right after the command line (REPL-style) — only helps commands that read stdin there. Requires cmd."
|
|
4687
|
+
description: "add: BYO PTY entry point — the full command that starts an interactive shell (e.g. \"docker exec -it img bash\"). Pairs with target pty[:<label>] / a bare <label> / nothing (auto id). Nested hops are dumb pipes (only the innermost bash frames)."
|
|
3052
4688
|
},
|
|
3053
|
-
|
|
3054
|
-
type: "
|
|
3055
|
-
description: "
|
|
4689
|
+
force: {
|
|
4690
|
+
type: "boolean",
|
|
4691
|
+
description: "close only: default false — a session with a running job is refused (job_kill it first). true = kill the group and close in one step; the receipt lists what was killed."
|
|
3056
4692
|
}
|
|
3057
4693
|
},
|
|
3058
4694
|
output: {
|
|
@@ -3068,8 +4704,8 @@ function createRemoteTool(driver, opts = {}) {
|
|
|
3068
4704
|
"status",
|
|
3069
4705
|
"roster",
|
|
3070
4706
|
"job",
|
|
3071
|
-
"
|
|
3072
|
-
"
|
|
4707
|
+
"close",
|
|
4708
|
+
"input"
|
|
3073
4709
|
]
|
|
3074
4710
|
},
|
|
3075
4711
|
text: {
|
|
@@ -3087,8 +4723,49 @@ function createRemoteTool(driver, opts = {}) {
|
|
|
3087
4723
|
truncated: { type: "integer" },
|
|
3088
4724
|
outputStats: { type: "json" },
|
|
3089
4725
|
outputStatsUnavailable: { type: "boolean" },
|
|
3090
|
-
session: {
|
|
3091
|
-
|
|
4726
|
+
session: {
|
|
4727
|
+
type: "string",
|
|
4728
|
+
description: "pty session id, e.g. pty:pty-7k2m"
|
|
4729
|
+
},
|
|
4730
|
+
label: { type: "string" },
|
|
4731
|
+
connection: {
|
|
4732
|
+
type: "string",
|
|
4733
|
+
description: "underlying connection: ssh:dev4 / docker:c / incus:x / hub:m4 / BYOP"
|
|
4734
|
+
},
|
|
4735
|
+
byoTag: { type: "string" },
|
|
4736
|
+
commandId: {
|
|
4737
|
+
type: "string",
|
|
4738
|
+
description: "ledger key; equals the jobId whenever a job exists"
|
|
4739
|
+
},
|
|
4740
|
+
writtenBytes: {
|
|
4741
|
+
type: "integer",
|
|
4742
|
+
description: "input: UTF-8 bytes actually written; confirms the write, not the program response"
|
|
4743
|
+
},
|
|
4744
|
+
envDelta: {
|
|
4745
|
+
type: "json",
|
|
4746
|
+
description: "names only: {added,changed,removed}"
|
|
4747
|
+
},
|
|
4748
|
+
created: { type: "boolean" },
|
|
4749
|
+
notice: { type: "string" },
|
|
4750
|
+
runner: {
|
|
4751
|
+
type: "string",
|
|
4752
|
+
description: "oneshot supervision path: superd-run <ver> (<triple>), posix-shim, or hub-lease (peer hub server supervises natively)"
|
|
4753
|
+
},
|
|
4754
|
+
running: { type: "boolean" },
|
|
4755
|
+
ttlSec: { type: "integer" },
|
|
4756
|
+
closed: {
|
|
4757
|
+
type: "boolean",
|
|
4758
|
+
description: "close: true = the session is gone now"
|
|
4759
|
+
},
|
|
4760
|
+
reason: {
|
|
4761
|
+
type: "string",
|
|
4762
|
+
description: "close: not-found / already-closed-or-reaped"
|
|
4763
|
+
},
|
|
4764
|
+
killed: {
|
|
4765
|
+
type: "array",
|
|
4766
|
+
items: { type: "string" },
|
|
4767
|
+
description: "close force: the running commandIds that were killed"
|
|
4768
|
+
}
|
|
3092
4769
|
}
|
|
3093
4770
|
},
|
|
3094
4771
|
render: (_args, value) => [{
|
|
@@ -3097,174 +4774,257 @@ function createRemoteTool(driver, opts = {}) {
|
|
|
3097
4774
|
}]
|
|
3098
4775
|
},
|
|
3099
4776
|
async execute(args, exec) {
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
args.script,
|
|
3105
|
-
args.stdin,
|
|
3106
|
-
args.spawn,
|
|
3107
|
-
args.ssh,
|
|
3108
|
-
args.target,
|
|
3109
|
-
args.mode,
|
|
3110
|
-
args.timeout,
|
|
3111
|
-
args.run_in_background
|
|
3112
|
-
].some((value) => value !== void 0)) throw new Error(`${args.action} cannot be combined with execution/PTY/job arguments; register byossh separately first`);
|
|
3113
|
-
for (const legacy of [
|
|
3114
|
-
"dryRun",
|
|
3115
|
-
"delete",
|
|
3116
|
-
"excludes",
|
|
3117
|
-
"preserve"
|
|
3118
|
-
]) if (args[legacy] !== void 0) throw new Error(`${legacy} was removed: pass native options through argv instead (e.g. ${legacy === "dryRun" ? "\"--dry-run\"" : legacy === "delete" ? "\"--delete\"" : legacy === "excludes" ? "\"--exclude=<pattern>\"" : "\"-a\" / \"-r\""})`);
|
|
3119
|
-
if (args.action === "rsync") {
|
|
3120
|
-
if (args.pullArgv !== void 0 || args.pushArgv !== void 0) throw new Error("rsync takes argv only; pullArgv/pushArgv are copy-only fields");
|
|
3121
|
-
if ([args.verify, args.mkdir].some((value) => value !== void 0)) throw new Error("rsync cannot be combined with copy verify/mkdir options; the Hub/local staged lane is copy-only");
|
|
3122
|
-
const start = Date.now();
|
|
3123
|
-
const receipt$1 = await driver.rsync({
|
|
3124
|
-
src: args.src,
|
|
3125
|
-
dst: args.dst,
|
|
3126
|
-
...args.argv === void 0 ? {} : { argv: args.argv }
|
|
3127
|
-
}, exec.signal, { sessionKey: getSessionKey(exec) });
|
|
3128
|
-
if (receipt$1.exit !== 0) throw new Error(JSON.stringify(receipt$1));
|
|
3129
|
-
return {
|
|
3130
|
-
kind: "rsync",
|
|
3131
|
-
text: JSON.stringify(receipt$1),
|
|
3132
|
-
receipt: receipt$1,
|
|
3133
|
-
exit: receipt$1.exit,
|
|
3134
|
-
durationMs: Date.now() - start
|
|
3135
|
-
};
|
|
3136
|
-
}
|
|
3137
|
-
const receipt = await driver.copy({
|
|
3138
|
-
src: args.src,
|
|
3139
|
-
dst: args.dst,
|
|
3140
|
-
...args.verify === void 0 ? {} : { verify: args.verify },
|
|
3141
|
-
...args.mkdir === void 0 ? {} : { mkdir: args.mkdir },
|
|
3142
|
-
...args.argv === void 0 ? {} : { argv: args.argv },
|
|
3143
|
-
...args.pullArgv === void 0 ? {} : { pullArgv: args.pullArgv },
|
|
3144
|
-
...args.pushArgv === void 0 ? {} : { pushArgv: args.pushArgv }
|
|
3145
|
-
}, exec.signal, { sessionKey: getSessionKey(exec) });
|
|
3146
|
-
return {
|
|
3147
|
-
kind: "copy",
|
|
3148
|
-
text: JSON.stringify(receipt),
|
|
3149
|
-
receipt,
|
|
3150
|
-
exit: null,
|
|
3151
|
-
durationMs: 0
|
|
3152
|
-
};
|
|
3153
|
-
}
|
|
3154
|
-
if ([
|
|
3155
|
-
args.src,
|
|
3156
|
-
args.dst,
|
|
3157
|
-
args.argv,
|
|
3158
|
-
args.pullArgv,
|
|
3159
|
-
args.pushArgv,
|
|
3160
|
-
args.verify,
|
|
3161
|
-
args.mkdir
|
|
3162
|
-
].some((value) => value !== void 0)) throw new Error("file fields require action copy or rsync");
|
|
3163
|
-
const hasCmd = typeof args.cmd === "string" && args.cmd.length > 0;
|
|
3164
|
-
const hasTarget = typeof args.target === "string" && args.target.length > 0;
|
|
3165
|
-
const hasSpawn = typeof args.spawn === "string" && args.spawn.length > 0;
|
|
3166
|
-
if (args.mode !== void 0 && args.mode !== "oneshot" && args.mode !== "pty") throw new Error(`[E_BAD_MODE] remote: mode must be 'oneshot' or 'pty' (got ${JSON.stringify(args.mode)})`);
|
|
3167
|
-
if (args.ssh !== void 0 && (!args.target?.startsWith("byossh:") || hasSpawn)) throw new Error("[E_SSH_PARAMS] remote: ssh requires a byossh:<label> target; spawn is only for byop:<label>");
|
|
3168
|
-
if (args.run_in_background) {
|
|
3169
|
-
if (!hasCmd && args.script === void 0) throw new Error("remote: background requires cmd or script");
|
|
3170
|
-
if (args.mode === "pty" || hasSpawn || args.target?.startsWith("byop:")) throw new Error("remote: background requires oneshot; PTY and BYO-PTY are unsupported");
|
|
3171
|
-
const jobs = exec.agent?.ctx.get("jobs");
|
|
3172
|
-
if (!jobs) throw new Error("remote: background requires the official DSH jobs service and job_output/job_kill controller; foreground execution remains available");
|
|
3173
|
-
const jobId = startRemoteJob(jobs, {
|
|
3174
|
-
target: args.target,
|
|
3175
|
-
cmd: args.cmd,
|
|
3176
|
-
script: args.script,
|
|
3177
|
-
ssh: args.ssh,
|
|
3178
|
-
stdin: args.stdin,
|
|
3179
|
-
mode: "oneshot",
|
|
3180
|
-
timeout: args.timeout
|
|
3181
|
-
}, exec, driver);
|
|
3182
|
-
return {
|
|
3183
|
-
kind: "job",
|
|
3184
|
-
jobId,
|
|
3185
|
-
text: `Started ${jobId}. Use job_output to read and job_kill to cancel; completion is reported by the host.`,
|
|
3186
|
-
exit: null,
|
|
3187
|
-
durationMs: 0
|
|
3188
|
-
};
|
|
3189
|
-
}
|
|
3190
|
-
if (!hasCmd && args.script === void 0) {
|
|
3191
|
-
if (args.stdin !== void 0) throw new Error("[E_STDIN_WITHOUT_CMD] remote: stdin requires cmd — status probes take no input");
|
|
3192
|
-
if (hasSpawn) throw new Error("[E_PARAMS] remote: spawn is an exec channel — pass cmd (there is nothing to probe for BYO-PTY)");
|
|
3193
|
-
if (args.ssh !== void 0) return {
|
|
3194
|
-
kind: "status",
|
|
3195
|
-
text: driver.registerSsh(args.target, args.ssh),
|
|
3196
|
-
exit: null,
|
|
3197
|
-
durationMs: 0
|
|
3198
|
-
};
|
|
3199
|
-
if (!hasTarget) return {
|
|
3200
|
-
kind: "roster",
|
|
3201
|
-
text: await driver.roster({ sessionKey: getSessionKey(exec) }),
|
|
3202
|
-
exit: null,
|
|
3203
|
-
durationMs: 0
|
|
3204
|
-
};
|
|
3205
|
-
return {
|
|
3206
|
-
kind: "status",
|
|
3207
|
-
text: await driver.status(args.target, { sessionKey: getSessionKey(exec) }),
|
|
3208
|
-
exit: null,
|
|
3209
|
-
durationMs: 0
|
|
3210
|
-
};
|
|
3211
|
-
}
|
|
3212
|
-
const r = await driver.call({
|
|
3213
|
-
target: args.target,
|
|
3214
|
-
spawn: args.spawn,
|
|
3215
|
-
ssh: args.ssh,
|
|
3216
|
-
cmd: args.cmd,
|
|
3217
|
-
script: args.script,
|
|
3218
|
-
mode: args.mode === "oneshot" || args.mode === "pty" ? args.mode : void 0,
|
|
3219
|
-
stdin: args.stdin,
|
|
3220
|
-
timeout: args.timeout
|
|
3221
|
-
}, { sessionKey: getSessionKey(exec) });
|
|
3222
|
-
const v = {
|
|
3223
|
-
kind: "exec",
|
|
3224
|
-
text: r.stdout,
|
|
3225
|
-
exit: r.exit,
|
|
3226
|
-
durationMs: r.durationMs
|
|
3227
|
-
};
|
|
3228
|
-
if (r.cwd !== null) v.cwd = r.cwd;
|
|
3229
|
-
if (r.stderr !== void 0) v.stderr = r.stderr;
|
|
3230
|
-
if (r.timedOut) v.timedOut = true;
|
|
3231
|
-
if (r.reconnected) v.reconnected = true;
|
|
3232
|
-
if (r.truncated !== void 0) v.truncated = r.truncated;
|
|
3233
|
-
if (r.outputStats !== void 0) v.outputStats = r.outputStats;
|
|
3234
|
-
if (r.outputStatsUnavailable) v.outputStatsUnavailable = true;
|
|
3235
|
-
if (r.session !== void 0) v.session = r.session;
|
|
3236
|
-
if (r.notice !== void 0) v.notice = r.notice;
|
|
3237
|
-
return v;
|
|
4777
|
+
return remoteExecute({
|
|
4778
|
+
driver,
|
|
4779
|
+
getSessionKey
|
|
4780
|
+
}, args, exec);
|
|
3238
4781
|
}
|
|
3239
4782
|
});
|
|
3240
4783
|
const description = tool.description;
|
|
3241
4784
|
Object.defineProperty(tool, "description", {
|
|
3242
4785
|
enumerable: true,
|
|
3243
|
-
get: () => description + (driver.hasHub() ? "\nHub transport available: hub:<m4> selects a paired remote machine (never self).
|
|
4786
|
+
get: () => description + (driver.hasHub() ? "\nHub transport available: hub:<m4> selects a paired remote machine (never self; the roster lists them). Hub failures never fall back to SSH.\n- hub:<m4> oneshot: the peer hub server is the runner itself — bash -lc in a detached group, TERM→2s→KILL cleanup; the receipt runner field says \"hub-lease\" (the superd-run helper is a dumb-pipe artifact, never uploaded over the Hub). Inline cmd is limited to 4096 chars; scriptPath is the file carrier and is not argv.\n- hub:<m4>:pty[:label] opens the SAME persistent interactive session as every other transport — id, label, input, busy, timeout handoff, background, close, session card, ledger, idle TTL, quota — carried by a local pump child over one authenticated WebSocket to the peer terminal." : "")
|
|
3244
4787
|
});
|
|
3245
4788
|
return tool;
|
|
3246
4789
|
}
|
|
4790
|
+
/** RemoteCallResult → RemoteToolValue(pty 工作台字段 + 既有字段)。 */
|
|
4791
|
+
function workbenchValue(r) {
|
|
4792
|
+
const v = {
|
|
4793
|
+
kind: "exec",
|
|
4794
|
+
text: r.stdout,
|
|
4795
|
+
exit: r.exit,
|
|
4796
|
+
durationMs: r.durationMs
|
|
4797
|
+
};
|
|
4798
|
+
if (r.cwd !== null && r.cwd !== void 0) v.cwd = r.cwd;
|
|
4799
|
+
if (r.stderr !== void 0) v.stderr = r.stderr;
|
|
4800
|
+
if (r.timedOut) v.timedOut = true;
|
|
4801
|
+
if (r.reconnected) v.reconnected = true;
|
|
4802
|
+
if (r.truncated !== void 0) v.truncated = r.truncated;
|
|
4803
|
+
if (r.outputStats !== void 0) v.outputStats = r.outputStats;
|
|
4804
|
+
if (r.outputStatsUnavailable) v.outputStatsUnavailable = true;
|
|
4805
|
+
if (r.session !== void 0) v.session = r.session;
|
|
4806
|
+
if (r.label !== void 0) v.label = r.label;
|
|
4807
|
+
if (r.connection !== void 0) v.connection = r.connection;
|
|
4808
|
+
if (r.byoTag !== void 0) v.byoTag = r.byoTag;
|
|
4809
|
+
if (r.commandId !== void 0) v.commandId = r.commandId;
|
|
4810
|
+
if (r.envDelta !== void 0) v.envDelta = r.envDelta;
|
|
4811
|
+
if (r.created === true) v.created = true;
|
|
4812
|
+
if (r.notice !== void 0) v.notice = r.notice;
|
|
4813
|
+
if (r.runner !== void 0) v.runner = r.runner;
|
|
4814
|
+
if (r.ttlSec !== void 0) v.ttlSec = r.ttlSec;
|
|
4815
|
+
return v;
|
|
4816
|
+
}
|
|
4817
|
+
function renderEnvDelta(d) {
|
|
4818
|
+
const bits = [];
|
|
4819
|
+
if (d.added.length > 0) bits.push(`+${d.added.join(",+")}`);
|
|
4820
|
+
if (d.changed.length > 0) bits.push(`~${d.changed.join(",~")}`);
|
|
4821
|
+
if (d.removed.length > 0) bits.push(`-${d.removed.join(",-")}`);
|
|
4822
|
+
return bits.length > 0 ? bits.join(" ") : void 0;
|
|
4823
|
+
}
|
|
3247
4824
|
function renderValue(v) {
|
|
3248
|
-
if (v.kind === "status" || v.kind === "roster" || v.kind === "job" || v.kind === "
|
|
4825
|
+
if (v.kind === "status" || v.kind === "roster" || v.kind === "job" || v.kind === "close" || v.kind === "input") return v.text;
|
|
3249
4826
|
const parts = [];
|
|
3250
4827
|
if (v.reconnected === true) parts.push(RECONNECT_NOTICE);
|
|
3251
4828
|
if (typeof v.notice === "string" && v.notice.length > 0) parts.push(v.notice);
|
|
4829
|
+
if (v.created === true && v.session !== void 0) parts.push(`[session created — address it as ${v.session}]`);
|
|
3252
4830
|
parts.push(v.text);
|
|
3253
4831
|
const secs = ((v.durationMs ?? 0) / 1e3).toFixed(1);
|
|
3254
4832
|
const markers = [];
|
|
4833
|
+
if (typeof v.session === "string" && v.session.length > 0) markers.push(`${v.session}${typeof v.label === "string" && v.label.length > 0 ? ` (${v.label})` : ""}${v.byoTag !== void 0 ? ` (${v.byoTag})` : ""}`);
|
|
4834
|
+
if (typeof v.connection === "string" && v.connection.length > 0 && v.session !== void 0) markers.push(`conn ${v.connection}`);
|
|
4835
|
+
if (typeof v.commandId === "string" && v.commandId.length > 0) markers.push(`cmd ${v.commandId}`);
|
|
4836
|
+
if (typeof v.cwd === "string" && v.cwd.length > 0) markers.push(`cwd ${v.cwd}`);
|
|
4837
|
+
const envTag = v.envDelta !== void 0 ? renderEnvDelta(v.envDelta) : void 0;
|
|
4838
|
+
if (envTag !== void 0) markers.push(`env ${envTag}`);
|
|
4839
|
+
if (typeof v.ttlSec === "number") markers.push(`idle-left ~${Math.max(1, Math.round(v.ttlSec / 60))}m`);
|
|
4840
|
+
if (typeof v.runner === "string" && v.runner.length > 0) markers.push(`runner ${v.runner}`);
|
|
3255
4841
|
if (v.timedOut === true) markers.push("interrupted");
|
|
4842
|
+
markers.push(`exit ${v.exit}`);
|
|
4843
|
+
markers.push(`${secs}s`);
|
|
4844
|
+
if (v.running === true) markers.push(`still running — poll job_output${v.jobId !== void 0 ? ` ${v.jobId}` : ""}`);
|
|
3256
4845
|
if (v.truncated !== void 0) markers.push(`truncated, ${v.outputStatsUnavailable ? "returned peer tail" : "original"} ${v.truncated} ${v.outputStats?.stdout.unit === "bytes" ? "bytes" : "chars"}`);
|
|
3257
4846
|
if (v.outputStatsUnavailable) markers.push("peer output totals/retention unavailable; returned tail only");
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
const sessionTag = typeof v.session === "string" && v.session.length > 0 ? ` · ${v.session}` : "";
|
|
3261
|
-
parts.push(`[exit ${v.exit} · ${secs}s${suffix}${cwdTag}${sessionTag}]`);
|
|
4847
|
+
parts.push(`[${markers.join(" · ")}]`);
|
|
4848
|
+
if (v.runner === "posix-shim" && (v.exit !== null && v.exit !== 0 || v.timedOut === true)) parts.push("note: this oneshot ran through the POSIX fallback on this target; PTY lanes use an independent lane and may still work here");
|
|
3262
4849
|
if (v.stderr !== void 0 && v.stderr.length > 0) parts.push("[stderr]", v.stderr);
|
|
3263
4850
|
return parts.join("\n");
|
|
3264
4851
|
}
|
|
3265
4852
|
|
|
4853
|
+
//#endregion
|
|
4854
|
+
//#region src/remote/transfer-tool.ts
|
|
4855
|
+
const NO_SESSION_KEY = "remote:no-session";
|
|
4856
|
+
/**
|
|
4857
|
+
* The model-visible surface of the `remote_transfer` tool (split out of
|
|
4858
|
+
* `remote`, 2026-10-25). ONE template literal — no backticks, no "${".
|
|
4859
|
+
*/
|
|
4860
|
+
const TRANSFER_TOOL_DESCRIPTION = `File transfer between any two supported endpoints. Every call declares its mode:
|
|
4861
|
+
mode:"copy" → tree copy. Native CLI per endpoint (scp for ssh, docker cp, incus file push/pull), a plain tree copy when both ends are local, and the Hub binary lane when a Hub machine is involved. Directories copy recursively; exit codes are authoritative.
|
|
4862
|
+
mode:"rsync" → rsync over SSH only: at least one endpoint remote SSH, the other local or SSH (both remote legs tunnel through this machine; identities never leave it). Hub and container endpoints are rejected — no silent copy fallback. Trailing slashes keep rsync semantics.
|
|
4863
|
+
|
|
4864
|
+
Endpoints are "[target:]absolute path". No target = the machine running this Agent. Targets are the same unified pool remote uses: a bare pool name, ssh:<name>, docker:<name>, incus:<name>, hub:<m4>. Examples: "/srv/app", "ssh:dev4:/srv/app", "docker:corti:/var/lib/x", "hub:m4:/srv". A path is never guessed: both operands must be absolute.
|
|
4865
|
+
|
|
4866
|
+
Native CLI options travel through argv verbatim — one element = one token, appended before src/dst, no shell parsing and no whitelist: rsync ["-a","--partial"], scp ["-p","-r"], docker cp ["-a","-L"], incus file push ["--recursive"]. Cross-endpoint copies that need two commands (SSH↔Docker, SSH↔Incus, Docker↔Incus) take pullArgv plus pushArgv instead of argv. rsync is a single SSH command, so it takes argv only; an explicit -e/--rsh overrides the wiring.
|
|
4867
|
+
|
|
4868
|
+
Options: verify (copy only) — the Hub↔local staged lane computes independent SHA-256 digests by default and verify:false skips them; native CLI routes have no independent hash tier, so verify is rejected there (self-verify through a oneshot digest command). mkdir (copy only, default true) — one best-effort pre-hop creates the destination PARENT directory; the operand itself is never pre-created, so each CLI's own layout semantics stay byte-identical.
|
|
4869
|
+
|
|
4870
|
+
Failures are loud: a non-zero native exit throws with the receipt instead of returning a normal-looking result. The receipt stays in the receipt field (route, exits, verification, bytes/entries, cleanup); text is one formatted line. For checksum-grade verification of a native route, run a digest command through remote oneshot or PTY instead of trusting the copy receipt.`;
|
|
4871
|
+
const KNOWN_PARAMS = new Set([
|
|
4872
|
+
"mode",
|
|
4873
|
+
"src",
|
|
4874
|
+
"dst",
|
|
4875
|
+
"argv",
|
|
4876
|
+
"pullArgv",
|
|
4877
|
+
"pushArgv",
|
|
4878
|
+
"verify",
|
|
4879
|
+
"mkdir"
|
|
4880
|
+
]);
|
|
4881
|
+
async function transferExecute(ENV, args, exec) {
|
|
4882
|
+
for (const key of Object.keys(args)) if (!KNOWN_PARAMS.has(key)) throw new Error(`remote_transfer: unknown parameter "${key}" — this surface has no legacy aliases; pass native CLI options through argv instead`);
|
|
4883
|
+
if (args.mode !== "copy" && args.mode !== "rsync") throw new Error(`[E_PARAMS] remote_transfer: mode is required — "copy" (tree copy through each endpoint's native CLI or the Hub lane) or "rsync" (SSH only)`);
|
|
4884
|
+
if (typeof args.src !== "string" || args.src.length === 0 || typeof args.dst !== "string" || args.dst.length === 0) throw new Error(`[E_PARAMS] remote_transfer: ${args.mode} requires src and dst absolute endpoints`);
|
|
4885
|
+
const sessionKey = ENV.getSessionKey(exec);
|
|
4886
|
+
if (args.mode === "rsync") {
|
|
4887
|
+
if (args.pullArgv !== void 0 || args.pushArgv !== void 0) throw new Error("remote_transfer: rsync takes argv only; pullArgv/pushArgv are copy-only fields");
|
|
4888
|
+
if (args.verify !== void 0 || args.mkdir !== void 0) throw new Error("remote_transfer: rsync cannot be combined with copy verify/mkdir options; the Hub/local staged lane is copy-only");
|
|
4889
|
+
const start$1 = Date.now();
|
|
4890
|
+
const receipt$1 = await ENV.driver.rsync({
|
|
4891
|
+
src: args.src,
|
|
4892
|
+
dst: args.dst,
|
|
4893
|
+
...args.argv === void 0 ? {} : { argv: args.argv }
|
|
4894
|
+
}, exec.signal, { sessionKey });
|
|
4895
|
+
if (receipt$1.ok === false || receipt$1.exit !== 0) throw new Error(JSON.stringify(receipt$1));
|
|
4896
|
+
const durationMs$1 = Date.now() - start$1;
|
|
4897
|
+
return {
|
|
4898
|
+
kind: "rsync",
|
|
4899
|
+
text: formatTransferLine("rsync", receipt$1, durationMs$1),
|
|
4900
|
+
receipt: receipt$1,
|
|
4901
|
+
exit: receipt$1.exit,
|
|
4902
|
+
durationMs: durationMs$1
|
|
4903
|
+
};
|
|
4904
|
+
}
|
|
4905
|
+
const start = Date.now();
|
|
4906
|
+
const receipt = await ENV.driver.copy({
|
|
4907
|
+
src: args.src,
|
|
4908
|
+
dst: args.dst,
|
|
4909
|
+
...args.verify === void 0 ? {} : { verify: args.verify },
|
|
4910
|
+
...args.mkdir === void 0 ? {} : { mkdir: args.mkdir },
|
|
4911
|
+
...args.argv === void 0 ? {} : { argv: args.argv },
|
|
4912
|
+
...args.pullArgv === void 0 ? {} : { pullArgv: args.pullArgv },
|
|
4913
|
+
...args.pushArgv === void 0 ? {} : { pushArgv: args.pushArgv }
|
|
4914
|
+
}, exec.signal, { sessionKey });
|
|
4915
|
+
const asReceipt = receipt;
|
|
4916
|
+
const exits = asReceipt.exits ?? [];
|
|
4917
|
+
if (asReceipt.ok === false || exits.some((code) => code !== 0)) throw new Error(JSON.stringify(receipt));
|
|
4918
|
+
const durationMs = Date.now() - start;
|
|
4919
|
+
return {
|
|
4920
|
+
kind: "copy",
|
|
4921
|
+
text: formatTransferLine("copy", receipt, durationMs),
|
|
4922
|
+
receipt,
|
|
4923
|
+
exit: exits.length > 0 ? 0 : null,
|
|
4924
|
+
durationMs
|
|
4925
|
+
};
|
|
4926
|
+
}
|
|
4927
|
+
function createRemoteTransferTool(driver, opts = {}) {
|
|
4928
|
+
const getSessionKey = opts.getSessionKey ?? ((exec) => exec.agent?.id ?? NO_SESSION_KEY);
|
|
4929
|
+
return defineTool({
|
|
4930
|
+
name: "remote_transfer",
|
|
4931
|
+
description: TRANSFER_TOOL_DESCRIPTION,
|
|
4932
|
+
parameters: {
|
|
4933
|
+
mode: {
|
|
4934
|
+
type: "string",
|
|
4935
|
+
enum: ["copy", "rsync"],
|
|
4936
|
+
required: true,
|
|
4937
|
+
description: "Required. copy = tree copy through each endpoint's native CLI, or the Hub binary lane; rsync = SSH only (argv only, no verify/mkdir)."
|
|
4938
|
+
},
|
|
4939
|
+
src: {
|
|
4940
|
+
type: "string",
|
|
4941
|
+
description: "Source [target:]absolute path. No target = the machine running this Agent."
|
|
4942
|
+
},
|
|
4943
|
+
dst: {
|
|
4944
|
+
type: "string",
|
|
4945
|
+
description: "Destination [target:]absolute path. No target = the machine running this Agent."
|
|
4946
|
+
},
|
|
4947
|
+
argv: {
|
|
4948
|
+
type: "array",
|
|
4949
|
+
items: { type: "string" },
|
|
4950
|
+
description: "Ordered native CLI options and values for one-command routes (e.g. rsync [\"-a\",\"--partial\",\"--dry-run\"], scp [\"-p\",\"-r\"], docker cp [\"-a\",\"-L\"], incus file push/pull). One element = one argv token, appended verbatim before src/dst; no shell parsing, no whitelist, no forced defaults — unknown options fail in the native CLI itself. rsync only (SSH endpoints): explicit -e/--rsh overrides the tool's SSH wiring. docker cp: pass -L to follow symlinks (a symlink source like /etc/os-release fails without it). Two-segment cross-endpoint copy uses pullArgv/pushArgv instead."
|
|
4951
|
+
},
|
|
4952
|
+
pullArgv: {
|
|
4953
|
+
type: "array",
|
|
4954
|
+
items: { type: "string" },
|
|
4955
|
+
description: "Options for the PULL half (source endpoint → origin staging) of a two-command cross-endpoint copy (e.g. SSH↔Docker, SSH↔Incus, Docker↔Incus). Mutually exclusive with argv; must be paired with pushArgv. Only options valid for the pull half's CLI."
|
|
4956
|
+
},
|
|
4957
|
+
pushArgv: {
|
|
4958
|
+
type: "array",
|
|
4959
|
+
items: { type: "string" },
|
|
4960
|
+
description: "Options for the PUSH half (origin staging → destination endpoint) of a two-command cross-endpoint copy. Mutually exclusive with argv; must be paired with pullArgv."
|
|
4961
|
+
},
|
|
4962
|
+
verify: {
|
|
4963
|
+
type: "boolean",
|
|
4964
|
+
description: "copy only. Receipts name the verification tier actually performed (D1=A): native CLI routes are \"native-exit-only\" (no independent check — self-verify via oneshot digest commands when needed); the Hub↔local staged lane computes independent SHA-256 digests by default and verify:false skips them (\"not-applicable\"). No hash tier exists on native routes."
|
|
4965
|
+
},
|
|
4966
|
+
mkdir: {
|
|
4967
|
+
type: "boolean",
|
|
4968
|
+
description: "copy only, all routes. Default true: before transfer, one best-effort exec pre-hop ensures the destination's PARENT directory exists (the operand itself is never pre-created — each CLI's own layout semantics stay byte-identical). Receipt created field: true (parent created this call) / false (already existed) / \"n-a\" (skipped or pre-hop unavailable, e.g. docker exec on a stopped container — the native CLI then reports the real error itself). false skips the pre-hop."
|
|
4969
|
+
}
|
|
4970
|
+
},
|
|
4971
|
+
output: {
|
|
4972
|
+
schema: {
|
|
4973
|
+
type: "object",
|
|
4974
|
+
additionalProperties: false,
|
|
4975
|
+
properties: {
|
|
4976
|
+
kind: {
|
|
4977
|
+
type: "string",
|
|
4978
|
+
required: true,
|
|
4979
|
+
enum: ["copy", "rsync"]
|
|
4980
|
+
},
|
|
4981
|
+
text: {
|
|
4982
|
+
type: "string",
|
|
4983
|
+
required: true
|
|
4984
|
+
},
|
|
4985
|
+
receipt: { type: "json" },
|
|
4986
|
+
exit: { oneOf: [{ type: "integer" }, { type: "null" }] },
|
|
4987
|
+
durationMs: { type: "integer" }
|
|
4988
|
+
}
|
|
4989
|
+
},
|
|
4990
|
+
render: (_args, value) => [{
|
|
4991
|
+
type: "text",
|
|
4992
|
+
text: value.text
|
|
4993
|
+
}]
|
|
4994
|
+
},
|
|
4995
|
+
async execute(args, exec) {
|
|
4996
|
+
return transferExecute({
|
|
4997
|
+
driver,
|
|
4998
|
+
getSessionKey
|
|
4999
|
+
}, args, exec);
|
|
5000
|
+
}
|
|
5001
|
+
});
|
|
5002
|
+
}
|
|
5003
|
+
/** S8 (2026-10-17): copy/rsync render as one formatted line; the full receipt
|
|
5004
|
+
* stays in the receipt field — raw-JSON dumps are gone from text. */
|
|
5005
|
+
function formatTransferLine(mode, receipt, durationMs) {
|
|
5006
|
+
const r = receipt;
|
|
5007
|
+
const parts = [];
|
|
5008
|
+
if (r.ok === false) parts.push(`✗ ${r.reason ?? "failed"}`);
|
|
5009
|
+
parts.push(`${mode} ${r.src} → ${r.dst}`);
|
|
5010
|
+
if (r.route !== void 0 && r.route !== "") parts.push(`route ${r.route}`);
|
|
5011
|
+
if (r.exits !== void 0) parts.push(`exits [${r.exits.join(",")}]`);
|
|
5012
|
+
else if (r.exit !== void 0) parts.push(`exit ${r.exit}`);
|
|
5013
|
+
if (r.verification !== void 0) parts.push(`verification ${r.verification}`);
|
|
5014
|
+
if (r.created === true) parts.push("created yes");
|
|
5015
|
+
else if (r.created === false) parts.push("created pre-existing");
|
|
5016
|
+
else if (r.created === "n-a") parts.push("created n-a");
|
|
5017
|
+
if (r.cleanup !== void 0 && r.cleanup !== "none-required") parts.push(`cleanup ${r.cleanup}`);
|
|
5018
|
+
if (typeof r.bytes === "number") parts.push(`${r.bytes} bytes / ${r.entries} entries`);
|
|
5019
|
+
parts.push(`${(durationMs / 1e3).toFixed(1)}s`);
|
|
5020
|
+
if (r.note !== void 0 && r.note.length > 0) parts.push(`(${r.note})`);
|
|
5021
|
+
return parts.join(" · ");
|
|
5022
|
+
}
|
|
5023
|
+
|
|
3266
5024
|
//#endregion
|
|
3267
5025
|
//#region src/remote/agent-registration.ts
|
|
5026
|
+
/** The pair a row contributes: execution/PTY and file transfer are separate tools. */
|
|
5027
|
+
const TOOL_NAMES = ["remote", "remote_transfer"];
|
|
3268
5028
|
/** Host listeners attempt once per official creation edge, never on vacancy. */
|
|
3269
5029
|
function installAgentRemote(ctx, config) {
|
|
3270
5030
|
return ctx.on("agent/created", ({ agent }) => {
|
|
@@ -3274,12 +5034,14 @@ function installAgentRemote(ctx, config) {
|
|
|
3274
5034
|
...config,
|
|
3275
5035
|
getHub: () => agent.ctx.get("superdRemoteTransport")
|
|
3276
5036
|
});
|
|
3277
|
-
|
|
5037
|
+
const registered = [];
|
|
3278
5038
|
try {
|
|
3279
|
-
|
|
5039
|
+
registered.push(tools.register(createRemoteTool(driver, { getSessionKey: () => agent.id })));
|
|
5040
|
+
registered.push(tools.register(createRemoteTransferTool(driver, { getSessionKey: () => agent.id })));
|
|
3280
5041
|
} catch (error) {
|
|
5042
|
+
for (const undo of registered.splice(0)) undo();
|
|
3281
5043
|
driver.dispose();
|
|
3282
|
-
if (error instanceof Error && error.message ===
|
|
5044
|
+
if (TOOL_NAMES.find((name$1) => error instanceof Error && error.message === `tool "${name$1}" is already registered in this scope` && tools.get(name$1, agent) !== void 0) !== void 0) return;
|
|
3283
5045
|
throw error;
|
|
3284
5046
|
}
|
|
3285
5047
|
const stopService = agent.ctx.on("internal/service", (name$1) => {
|
|
@@ -3291,7 +5053,7 @@ function installAgentRemote(ctx, config) {
|
|
|
3291
5053
|
const cleanup = () => {
|
|
3292
5054
|
if (disposal) return disposal;
|
|
3293
5055
|
disposal = driver.dispose();
|
|
3294
|
-
|
|
5056
|
+
for (const undo of registered.splice(0)) undo();
|
|
3295
5057
|
stopService();
|
|
3296
5058
|
ownerUndo?.();
|
|
3297
5059
|
agentUndo?.();
|
|
@@ -3347,11 +5109,11 @@ const name = "dashr-remote";
|
|
|
3347
5109
|
const inject = [];
|
|
3348
5110
|
const Config = Schema.object({
|
|
3349
5111
|
execTimeoutSec: Schema.natural().min(1).default(120),
|
|
3350
|
-
idleTtlSec: Schema.natural().min(1).default(
|
|
5112
|
+
idleTtlSec: Schema.natural().min(1).default(REMOTE_PTY_IDLE_TTL_SEC),
|
|
3351
5113
|
maxOutputChars: Schema.natural().min(1).default(3e4)
|
|
3352
5114
|
}).default({
|
|
3353
5115
|
execTimeoutSec: 120,
|
|
3354
|
-
idleTtlSec:
|
|
5116
|
+
idleTtlSec: REMOTE_PTY_IDLE_TTL_SEC,
|
|
3355
5117
|
maxOutputChars: 3e4
|
|
3356
5118
|
});
|
|
3357
5119
|
/** MUST stay an arrow(RM0 plugin.ts 同注:function 声明会被 cordis 当构造器 new 掉,返回的 disposer 丢失)。 */
|
|
@@ -3366,4 +5128,4 @@ var plugin_default = {
|
|
|
3366
5128
|
};
|
|
3367
5129
|
|
|
3368
5130
|
//#endregion
|
|
3369
|
-
export { ByteTailRing, Config, FILE_FRAME_BYTES, FILE_MAX_ENTRIES, FILE_MAX_METADATA, PROCESS_CLEANUP_BOUND_MS,
|
|
5131
|
+
export { ByteTailRing, Config, FILE_FRAME_BYTES, FILE_MAX_ENTRIES, FILE_MAX_METADATA, PROCESS_CLEANUP_BOUND_MS, PtySession, Utf16TailRing, apply, buildHubPtyArgv, checkAbsolute, checkSelection, plugin_default as default, hubPtyAssets, inject, localFileEndpoint, name, readUtf8Tail, runFileWorker, runRsync, sshArgv, startBinaryProcess, startOneShot, startRemoteJob, tailWindow };
|