better-dsh 0.3.1 → 0.3.2-e
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 +523 -199
- package/lib/remote/plugin.js +2527 -765
- package/lib/url-schemes/index.d.ts +11 -11
- package/lib/url-schemes/index.js +12 -12
- package/lib/{wasm_bg-CNXhHjVg.js → wasm_bg.js} +1 -1
- package/lib/web-password.d.ts +7 -7
- package/lib/web-password.js +1 -1
- package/lib/web-trust.d.ts +2 -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) {
|
|
@@ -1590,26 +1974,30 @@ function stripAnsi(s) {
|
|
|
1590
1974
|
function normalizePtyText(s) {
|
|
1591
1975
|
return stripAnsi(s).replace(/\r\n/g, "\n").replace(/\r/g, "");
|
|
1592
1976
|
}
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1977
|
+
/** 0.3.2-e:自有 30K 返回窗口已删(原生 agent runtime 的 spill/输出保护接管模型上下文
|
|
1978
|
+
* 尺寸)。本 helper 只做 retention 披露:ring 留存(4M UTF-16 / 4MiB bytes)未驱逐时
|
|
1979
|
+
* 全量透传(returned=retained,无 banner);驱逐(dropped>0,仅 >4M 输出发生)时打一行
|
|
1980
|
+
* banner 且 truncated=原始总量。text 已是 ring 尾部,不再二次裁剪。 */
|
|
1981
|
+
function disclose(text, stats) {
|
|
1982
|
+
if (stats === void 0) return { text };
|
|
1983
|
+
const returned = stats.retained;
|
|
1984
|
+
const updated = { stats: {
|
|
1599
1985
|
...stats,
|
|
1600
1986
|
returned
|
|
1601
1987
|
} };
|
|
1602
|
-
if (
|
|
1603
|
-
text
|
|
1988
|
+
if (stats.dropped <= 0) return {
|
|
1989
|
+
text,
|
|
1604
1990
|
...updated
|
|
1605
1991
|
};
|
|
1992
|
+
const unit = stats.unit === "bytes" ? "bytes" : "chars";
|
|
1606
1993
|
return {
|
|
1607
|
-
text: `[
|
|
1608
|
-
truncated: total,
|
|
1994
|
+
text: `[retention tail: showing last ${stats.retained} of ${stats.total} ${unit}; dropped head ${stats.dropped}, retention limit ${stats.retentionLimit} ${stats.unit === "bytes" ? "bytes" : "UTF-16 code units"}]\n${text}`,
|
|
1995
|
+
truncated: stats.total,
|
|
1609
1996
|
...updated
|
|
1610
1997
|
};
|
|
1611
1998
|
}
|
|
1612
1999
|
const FRAME_BODY_RE = /^(\d+);([^\x07\x1b]*)(?:\x07|\x1b\\)/;
|
|
2000
|
+
const ENV_BODY_RE = /^([A-Za-z0-9+/=]*)\x07/;
|
|
1613
2001
|
/**
|
|
1614
2002
|
* 单 nonce、单帧解析器:一轮 dispatch 一个实例。只认 `\x1b]133;D;<nonce>;`,
|
|
1615
2003
|
* 错误 nonce 的静态/伪造 marker 永不匹配,按普通输出流过(再经 ANSI 剥洗)。
|
|
@@ -1617,31 +2005,60 @@ const FRAME_BODY_RE = /^(\d+);([^\x07\x1b]*)(?:\x07|\x1b\\)/;
|
|
|
1617
2005
|
*/
|
|
1618
2006
|
function createNonceFrameParser(nonce, events) {
|
|
1619
2007
|
const prefix = `\x1b]133;D;${nonce};`;
|
|
2008
|
+
const prefixE = `\x1b]133;E;${nonce};`;
|
|
2009
|
+
const prefixes = [prefix, prefixE];
|
|
1620
2010
|
let buf = "";
|
|
1621
2011
|
let done = false;
|
|
1622
2012
|
const emit = (raw) => {
|
|
1623
2013
|
const text = normalizePtyText(raw);
|
|
1624
2014
|
if (text.length > 0) events.onOutput?.(text);
|
|
1625
2015
|
};
|
|
2016
|
+
/** 缓冲尾若是任一候选前缀的真前缀则扣留(D/E 共用);flush() 放出残余。 */
|
|
1626
2017
|
const holdback = () => {
|
|
1627
|
-
|
|
1628
|
-
for (
|
|
1629
|
-
|
|
2018
|
+
let best = 0;
|
|
2019
|
+
for (const p of prefixes) {
|
|
2020
|
+
const max = Math.min(buf.length, p.length - 1);
|
|
2021
|
+
for (let k = max; k > best; k--) if (buf.endsWith(p.slice(0, k))) {
|
|
2022
|
+
best = k;
|
|
2023
|
+
break;
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
return best;
|
|
1630
2027
|
};
|
|
2028
|
+
/** 扫描最早出现的帧:E(env 侧信道)先于 D 下发;D = settle,帧后字节丢弃。 */
|
|
1631
2029
|
const consume = () => {
|
|
1632
2030
|
if (done) return;
|
|
1633
|
-
|
|
1634
|
-
|
|
2031
|
+
let idx = -1;
|
|
2032
|
+
let isEnv = false;
|
|
2033
|
+
for (const p of prefixes) {
|
|
2034
|
+
const i = buf.indexOf(p);
|
|
2035
|
+
if (i >= 0 && (idx === -1 || i < idx)) {
|
|
2036
|
+
idx = i;
|
|
2037
|
+
isEnv = p === prefixE;
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
if (idx < 0) {
|
|
1635
2041
|
const keep = holdback();
|
|
1636
2042
|
emit(buf.slice(0, buf.length - keep));
|
|
1637
2043
|
buf = buf.slice(buf.length - keep);
|
|
1638
2044
|
return;
|
|
1639
2045
|
}
|
|
1640
|
-
emit(buf.slice(0,
|
|
1641
|
-
const rest = buf.slice(
|
|
2046
|
+
emit(buf.slice(0, idx));
|
|
2047
|
+
const rest = buf.slice(idx + (isEnv ? prefixE.length : prefix.length));
|
|
2048
|
+
if (isEnv) {
|
|
2049
|
+
const m$1 = ENV_BODY_RE.exec(rest);
|
|
2050
|
+
if (m$1 === null) {
|
|
2051
|
+
buf = buf.slice(idx);
|
|
2052
|
+
return;
|
|
2053
|
+
}
|
|
2054
|
+
if (m$1[1].length > 0) events.onEnv?.(m$1[1]);
|
|
2055
|
+
buf = rest.slice(m$1[0].length);
|
|
2056
|
+
consume();
|
|
2057
|
+
return;
|
|
2058
|
+
}
|
|
1642
2059
|
const m = FRAME_BODY_RE.exec(rest);
|
|
1643
2060
|
if (m === null) {
|
|
1644
|
-
buf = buf.slice(
|
|
2061
|
+
buf = buf.slice(idx);
|
|
1645
2062
|
return;
|
|
1646
2063
|
}
|
|
1647
2064
|
events.onFrame({
|
|
@@ -1662,33 +2079,90 @@ function createNonceFrameParser(nonce, events) {
|
|
|
1662
2079
|
}
|
|
1663
2080
|
};
|
|
1664
2081
|
}
|
|
2082
|
+
/** E 帧 payload → name→value-hash(值不离开端点;hash 只为 changed 判定)。空/坏 payload → undefined。 */
|
|
2083
|
+
function decodeEnvSnapshot(b64) {
|
|
2084
|
+
if (b64.length === 0) return void 0;
|
|
2085
|
+
let text;
|
|
2086
|
+
try {
|
|
2087
|
+
text = Buffer.from(b64, "base64").toString("utf8");
|
|
2088
|
+
} catch {
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
const map = /* @__PURE__ */ new Map();
|
|
2092
|
+
for (const entry of text.split("\0")) {
|
|
2093
|
+
if (entry.length === 0) continue;
|
|
2094
|
+
const eq = entry.indexOf("=");
|
|
2095
|
+
const name$1 = eq === -1 ? entry : entry.slice(0, eq);
|
|
2096
|
+
if (name$1.startsWith("__superd")) continue;
|
|
2097
|
+
let h = 5381;
|
|
2098
|
+
const value = eq === -1 ? "" : entry.slice(eq + 1);
|
|
2099
|
+
for (let i = 0; i < value.length; i++) h = (h * 33 ^ value.charCodeAt(i)) >>> 0;
|
|
2100
|
+
map.set(name$1, h);
|
|
2101
|
+
}
|
|
2102
|
+
return map.size > 0 ? map : void 0;
|
|
2103
|
+
}
|
|
2104
|
+
/** prev 未知(init 侧信道失败)时返回 undefined——不报告假 delta。 */
|
|
2105
|
+
function diffEnv(prev, next) {
|
|
2106
|
+
if (prev === void 0) return void 0;
|
|
2107
|
+
const added = [], changed = [], removed = [];
|
|
2108
|
+
for (const [name$1, h] of next) if (!prev.has(name$1)) added.push(name$1);
|
|
2109
|
+
else if (prev.get(name$1) !== h) changed.push(name$1);
|
|
2110
|
+
for (const name$1 of prev.keys()) if (!next.has(name$1)) removed.push(name$1);
|
|
2111
|
+
added.sort();
|
|
2112
|
+
changed.sort();
|
|
2113
|
+
removed.sort();
|
|
2114
|
+
return {
|
|
2115
|
+
added,
|
|
2116
|
+
changed,
|
|
2117
|
+
removed
|
|
2118
|
+
};
|
|
2119
|
+
}
|
|
1665
2120
|
|
|
1666
2121
|
//#endregion
|
|
1667
2122
|
//#region src/remote/pty-session.ts
|
|
1668
2123
|
/** spec §五.2 逐字。 */
|
|
1669
2124
|
const RECONNECT_NOTICE = "[remote: session reconnected to fresh shell; cwd reset to default]";
|
|
1670
|
-
/** 池键 → 模型面名字:剥掉 agent 前缀与内部标记(`
|
|
1671
|
-
*
|
|
1672
|
-
*
|
|
2125
|
+
/** 池键 → 模型面名字:剥掉 agent 前缀与内部标记(`p:` → `pty:<id>`)。
|
|
2126
|
+
* 这是**唯一**的 key→名字映射规则,roster 与错误面共用——错误面不得回吐内部键:
|
|
2127
|
+
* 2026-10-03 实测报告 F1,`E_SESSION_*` 曾把 `session-<uuid>|p:<label>` 整条吐给模型。 */
|
|
1673
2128
|
function displayKey(key) {
|
|
1674
2129
|
const raw = key.includes("|") ? key.slice(key.indexOf("|") + 1) : key;
|
|
1675
|
-
return raw.startsWith("
|
|
2130
|
+
return raw.startsWith("p:") ? `pty:${raw.slice(2)}` : raw;
|
|
1676
2131
|
}
|
|
2132
|
+
const LEDGER_MAX = 20;
|
|
2133
|
+
const summaryOf = (cmd) => {
|
|
2134
|
+
const first = cmd.trim().split(/\r?\n/, 1)[0] ?? "";
|
|
2135
|
+
return first.length > 72 ? `${first.slice(0, 71)}…` : first;
|
|
2136
|
+
};
|
|
1677
2137
|
const DEFAULT_INIT_TIMEOUT_SEC = 30;
|
|
1678
2138
|
const INTERRUPT_GRACE_MS = 3e3;
|
|
2139
|
+
/** F2(0.3.2-d):\x03 触发 ISIG 时内核 flush 输入队列——130-marker 必须等 flush 完成
|
|
2140
|
+
* 再入队,否则首字节被吞(实测 'rintf' not found → 会话死)。 */
|
|
2141
|
+
const MARKER_SETTLE_MS = 80;
|
|
1679
2142
|
/** pty 收集内存安全帽(Ruling P15,与 oneshot HARD_CAP 对齐):模型面只见尾窗,保留尾部。 */
|
|
1680
2143
|
const OUTPUT_HARD_CAP = 4e6;
|
|
1681
2144
|
var PtySession = class {
|
|
1682
2145
|
proc = null;
|
|
1683
2146
|
state = "cold";
|
|
1684
2147
|
startPromise = null;
|
|
1685
|
-
queue = Promise.resolve();
|
|
1686
2148
|
idleTimer = null;
|
|
1687
2149
|
onChunk = null;
|
|
1688
2150
|
deathWaiters = [];
|
|
1689
2151
|
diag = "";
|
|
1690
2152
|
inFlight = 0;
|
|
1691
|
-
|
|
2153
|
+
/** P4/P5:当前占用前台的 detached job(background/超时 handoff)。非 null 时新命令拒绝(Q6)。 */
|
|
2154
|
+
detachedJob = null;
|
|
2155
|
+
/** §3.2(2026-10-25):当前占用会话的命令——dispatch 同步占位,settle/cleanup 释放;input 的唯一写入对象。 */
|
|
2156
|
+
activeCommand = null;
|
|
2157
|
+
/** 账本(§5):本会话最近 20 条命令(FIFO,超出丢最旧)。 */
|
|
2158
|
+
ledger = [];
|
|
2159
|
+
/** env 侧信道基线(init E 帧);undefined = 侧信道不可用(不报假 delta)。 */
|
|
2160
|
+
envBaseline;
|
|
2161
|
+
/** idle 起点(ready / settle 时重置);null = 尚无 idle 时钟(cold 或已 dispose)。 */
|
|
2162
|
+
idleSince = null;
|
|
2163
|
+
/** 意外死亡后的回收定时器(R2):ready 过的会话先留池供 reconnect,超时仍无人寻址则出池。 */
|
|
2164
|
+
deathTimer = null;
|
|
2165
|
+
lastCwdSeen = null;
|
|
1692
2166
|
/** 是否曾成功初始化(ready 过)。决定死亡语义:ready 过 → reconnect(留池);从未 ready → 出池(见 start())。 */
|
|
1693
2167
|
everReady = false;
|
|
1694
2168
|
disposal;
|
|
@@ -1700,7 +2174,39 @@ var PtySession = class {
|
|
|
1700
2174
|
get sessionState() {
|
|
1701
2175
|
return this.state;
|
|
1702
2176
|
}
|
|
1703
|
-
/**
|
|
2177
|
+
/** 池键(driver 的 ttl/inspect 用)。 */
|
|
2178
|
+
get key() {
|
|
2179
|
+
return this.opts.key;
|
|
2180
|
+
}
|
|
2181
|
+
/** 最近帧 cwd(card 面);从未执行过 = null。 */
|
|
2182
|
+
get lastCwd() {
|
|
2183
|
+
return this.lastCwdSeen;
|
|
2184
|
+
}
|
|
2185
|
+
/** 占用前台的 detached job 的 commandId(无 = null;close 拒绝与 busy 文案共用)。 */
|
|
2186
|
+
get detachedCommandId() {
|
|
2187
|
+
return this.detachedJob?.commandId ?? null;
|
|
2188
|
+
}
|
|
2189
|
+
/** job 通道收养后回填 jobId(timeout handoff 时 registry id ≠ commandId,账本如实记录两者);运行中的命令同步携带(input 回执用)。 */
|
|
2190
|
+
attachJob(commandId, jobId) {
|
|
2191
|
+
const entry = [...this.ledger].reverse().find((e) => e.commandId === commandId);
|
|
2192
|
+
if (entry !== void 0) entry.jobId = jobId;
|
|
2193
|
+
if (this.activeCommand !== null && this.activeCommand.commandId === commandId) this.activeCommand.jobId = jobId;
|
|
2194
|
+
}
|
|
2195
|
+
/** Workbench 身份(§3):id + 可选 label + connection + byo 标记。 */
|
|
2196
|
+
get identity() {
|
|
2197
|
+
return {
|
|
2198
|
+
id: this.opts.id,
|
|
2199
|
+
...this.opts.label !== void 0 ? { label: this.opts.label } : {},
|
|
2200
|
+
connection: this.opts.connection,
|
|
2201
|
+
byo: this.opts.byo === true,
|
|
2202
|
+
builtOn: this.opts.builtOn === true
|
|
2203
|
+
};
|
|
2204
|
+
}
|
|
2205
|
+
/** 账本快照(session card 面,只读)。 */
|
|
2206
|
+
ledgerSnapshot() {
|
|
2207
|
+
return this.ledger;
|
|
2208
|
+
}
|
|
2209
|
+
/** spawn 创建原文(仅 BYO 会话;v2 起仅存档,不参与复用判定)。 */
|
|
1704
2210
|
get origin() {
|
|
1705
2211
|
return this.opts.origin;
|
|
1706
2212
|
}
|
|
@@ -1709,93 +2215,226 @@ var PtySession = class {
|
|
|
1709
2215
|
return {
|
|
1710
2216
|
state: this.state,
|
|
1711
2217
|
busy: this.inFlight > 0,
|
|
1712
|
-
idleMs: this.
|
|
2218
|
+
idleMs: this.idleSince === null ? null : Date.now() - this.idleSince,
|
|
1713
2219
|
pid: this.proc?.pid ?? null
|
|
1714
2220
|
};
|
|
1715
2221
|
}
|
|
1716
|
-
/**
|
|
1717
|
-
|
|
2222
|
+
/** 预热创建(创建形无 cmd):真正拨号到 init 帧——「会话已就绪」必须是真的,
|
|
2223
|
+
* 而且只有 ready 过才挂 idle 回收(cold 会话没有 timer,会永远占配额)。 */
|
|
2224
|
+
async warm() {
|
|
2225
|
+
await this.start();
|
|
2226
|
+
}
|
|
2227
|
+
/** 同一会话命令占位制(2026-10-25 interactive-stdin 轮):dispatch 入口**同步**建立
|
|
2228
|
+
* 命令占位(activeCommand + inFlight + 账本条目)——上一条命令仍在运行(同步等待 /
|
|
2229
|
+
* 等输入 / detached job)时新 cmd 立即 E_SESSION_BUSY;原「纯同步并发排 FIFO」语义
|
|
2230
|
+
* 废除(排队会让等输入的命令与补输入动作互相卡死,也给 busy 留下绕行窗口)。
|
|
2231
|
+
* P4/P5:超时不杀命令而是 handoff 成 running job;background 立即回执;P8 显式
|
|
2232
|
+
* interrupt 保留在 job.interrupt;死亡/冷态先重启(reconnect 语义不变)。 */
|
|
2233
|
+
dispatch(cmd, dOpts) {
|
|
2234
|
+
if (this.state === "disposed") return Promise.reject(/* @__PURE__ */ new Error(`[E_SESSION_DISPOSED] remote pty session '${this.opts.id}' was disposed before dispatch`));
|
|
2235
|
+
if (this.activeCommand !== null) {
|
|
2236
|
+
const handle = this.activeCommand.jobId ?? this.activeCommand.commandId;
|
|
2237
|
+
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`));
|
|
2238
|
+
}
|
|
2239
|
+
const commandId = dOpts.commandId;
|
|
2240
|
+
const entry = {
|
|
2241
|
+
commandId,
|
|
2242
|
+
summary: summaryOf(cmd),
|
|
2243
|
+
exit: null,
|
|
2244
|
+
durationMs: 0,
|
|
2245
|
+
running: true,
|
|
2246
|
+
...dOpts.jobId !== void 0 ? { jobId: dOpts.jobId } : {}
|
|
2247
|
+
};
|
|
2248
|
+
this.ledger.push(entry);
|
|
2249
|
+
if (this.ledger.length > LEDGER_MAX) this.ledger.shift();
|
|
2250
|
+
this.activeCommand = {
|
|
2251
|
+
commandId,
|
|
2252
|
+
...dOpts.jobId !== void 0 ? { jobId: dOpts.jobId } : {}
|
|
2253
|
+
};
|
|
2254
|
+
this.inFlight++;
|
|
1718
2255
|
const attempt = async () => {
|
|
1719
2256
|
const started = Date.now();
|
|
1720
2257
|
const reconnected = this.state === "dead";
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
2258
|
+
/** 占位撤销:命令从未真正启动(建连失败 / 建连中被 dispose)——释放 busy 与计数,
|
|
2259
|
+
* 撤掉账本条目(与旧时序等价:条目原本在 start 成功之后才建立)。 */
|
|
2260
|
+
const abandon = () => {
|
|
2261
|
+
this.activeCommand = null;
|
|
2262
|
+
this.inFlight--;
|
|
2263
|
+
const index = this.ledger.indexOf(entry);
|
|
2264
|
+
if (index >= 0) this.ledger.splice(index, 1);
|
|
2265
|
+
};
|
|
2266
|
+
if (this.state !== "ready") try {
|
|
2267
|
+
await this.start();
|
|
2268
|
+
} catch (error) {
|
|
2269
|
+
abandon();
|
|
2270
|
+
throw error;
|
|
2271
|
+
}
|
|
2272
|
+
if (this.state === "disposed") {
|
|
2273
|
+
abandon();
|
|
2274
|
+
throw new Error(`[E_SESSION_DISPOSED] remote pty session '${this.opts.id}' was disposed before dispatch`);
|
|
2275
|
+
}
|
|
1724
2276
|
return await new Promise((resolve$1) => {
|
|
1725
2277
|
const nonce = genNonce();
|
|
1726
2278
|
const ring = new Utf16TailRing(OUTPUT_HARD_CAP);
|
|
1727
2279
|
let interrupted = false;
|
|
1728
2280
|
let settled = false;
|
|
2281
|
+
let jobSettled = false;
|
|
1729
2282
|
let interruptTimer;
|
|
1730
2283
|
let killTimer;
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
2284
|
+
let markerTimer;
|
|
2285
|
+
let jobDone = null;
|
|
2286
|
+
let envNext;
|
|
2287
|
+
const detach = () => {
|
|
2288
|
+
const job = {
|
|
2289
|
+
commandId,
|
|
2290
|
+
read: (fromByte) => ring.read(fromByte),
|
|
2291
|
+
stats: () => ring.stats(),
|
|
2292
|
+
interrupt: () => {
|
|
2293
|
+
if (!jobSettled) twoStage();
|
|
2294
|
+
},
|
|
2295
|
+
done: new Promise((res) => {
|
|
2296
|
+
jobDone = res;
|
|
2297
|
+
})
|
|
2298
|
+
};
|
|
2299
|
+
this.detachedJob = job;
|
|
2300
|
+
settled = true;
|
|
2301
|
+
resolve$1({
|
|
2302
|
+
output: ring.text,
|
|
2303
|
+
outputStats: { stdout: ring.stats() },
|
|
2304
|
+
exit: null,
|
|
2305
|
+
cwd: null,
|
|
2306
|
+
timedOut: false,
|
|
2307
|
+
running: true,
|
|
2308
|
+
job,
|
|
2309
|
+
commandId,
|
|
2310
|
+
reconnected,
|
|
2311
|
+
durationMs: Date.now() - started
|
|
2312
|
+
});
|
|
2313
|
+
return job;
|
|
2314
|
+
};
|
|
1737
2315
|
const cleanup = () => {
|
|
1738
2316
|
this.onChunk = null;
|
|
2317
|
+
this.detachedJob = null;
|
|
2318
|
+
this.activeCommand = null;
|
|
1739
2319
|
this.deathWaiters = this.deathWaiters.filter((w) => w !== deathWaiter);
|
|
1740
2320
|
if (interruptTimer !== void 0) clearTimeout(interruptTimer);
|
|
1741
2321
|
if (killTimer !== void 0) clearTimeout(killTimer);
|
|
2322
|
+
if (markerTimer !== void 0) clearTimeout(markerTimer);
|
|
1742
2323
|
};
|
|
1743
|
-
const
|
|
1744
|
-
if (
|
|
1745
|
-
|
|
2324
|
+
const settle = (r) => {
|
|
2325
|
+
if (jobSettled) return;
|
|
2326
|
+
jobSettled = true;
|
|
1746
2327
|
cleanup();
|
|
1747
2328
|
this.inFlight--;
|
|
1748
|
-
this.
|
|
2329
|
+
this.idleSince = Date.now();
|
|
1749
2330
|
this.resetIdleTimer();
|
|
1750
|
-
|
|
2331
|
+
if (r.cwd !== null) this.lastCwdSeen = r.cwd;
|
|
2332
|
+
const envDelta = envNext !== void 0 ? diffEnv(this.envBaseline, envNext) : void 0;
|
|
2333
|
+
if (envNext !== void 0) this.envBaseline = envNext;
|
|
2334
|
+
entry.exit = r.exit;
|
|
2335
|
+
entry.durationMs = Date.now() - started;
|
|
2336
|
+
entry.running = false;
|
|
2337
|
+
const full = {
|
|
1751
2338
|
...r,
|
|
1752
2339
|
outputStats: { stdout: ring.stats() },
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
}
|
|
2340
|
+
commandId,
|
|
2341
|
+
...envDelta !== void 0 ? { envDelta } : {}
|
|
2342
|
+
};
|
|
2343
|
+
jobDone?.(full);
|
|
2344
|
+
if (!settled) {
|
|
2345
|
+
settled = true;
|
|
2346
|
+
resolve$1({
|
|
2347
|
+
...full,
|
|
2348
|
+
reconnected,
|
|
2349
|
+
durationMs: Date.now() - started
|
|
2350
|
+
});
|
|
2351
|
+
}
|
|
1756
2352
|
};
|
|
2353
|
+
const deathWaiter = () => settle({
|
|
2354
|
+
output: ring.text,
|
|
2355
|
+
exit: null,
|
|
2356
|
+
cwd: null,
|
|
2357
|
+
timedOut: interrupted
|
|
2358
|
+
});
|
|
1757
2359
|
const parser = createNonceFrameParser(nonce, {
|
|
1758
2360
|
onOutput: (t) => {
|
|
1759
2361
|
ring.push(t);
|
|
1760
2362
|
},
|
|
1761
|
-
|
|
2363
|
+
onEnv: (b64) => {
|
|
2364
|
+
const m = decodeEnvSnapshot(b64);
|
|
2365
|
+
if (m !== void 0) envNext = m;
|
|
2366
|
+
},
|
|
2367
|
+
onFrame: ({ exit, cwd }) => settle({
|
|
1762
2368
|
output: ring.text,
|
|
1763
2369
|
exit,
|
|
1764
2370
|
cwd,
|
|
1765
2371
|
timedOut: interrupted
|
|
1766
2372
|
})
|
|
1767
2373
|
});
|
|
1768
|
-
|
|
1769
|
-
this.write(wrapPtyCommand(cmd, nonce));
|
|
1770
|
-
if (dOpts.stdin !== void 0) this.write(dOpts.stdin);
|
|
1771
|
-
interruptTimer = setTimeout(() => {
|
|
2374
|
+
const twoStage = () => {
|
|
1772
2375
|
interrupted = true;
|
|
1773
2376
|
this.write("");
|
|
1774
|
-
|
|
2377
|
+
markerTimer = setTimeout(() => {
|
|
2378
|
+
this.write(`printf '\\033]133;D;${nonce};130;%s\\007' "$PWD"\n`);
|
|
2379
|
+
}, MARKER_SETTLE_MS);
|
|
1775
2380
|
killTimer = setTimeout(() => {
|
|
1776
2381
|
this.killTree();
|
|
1777
2382
|
this.markDead();
|
|
1778
|
-
|
|
2383
|
+
settle({
|
|
1779
2384
|
output: ring.text,
|
|
1780
2385
|
exit: null,
|
|
1781
2386
|
cwd: null,
|
|
1782
2387
|
timedOut: true
|
|
1783
2388
|
});
|
|
1784
2389
|
}, INTERRUPT_GRACE_MS);
|
|
1785
|
-
}
|
|
2390
|
+
};
|
|
2391
|
+
this.onChunk = (c) => parser.feed(c);
|
|
2392
|
+
this.write(wrapPtyCommand(cmd, nonce));
|
|
2393
|
+
if (dOpts.stdin !== void 0) this.write(dOpts.stdin);
|
|
1786
2394
|
this.deathWaiters.push(deathWaiter);
|
|
2395
|
+
if (dOpts.background === true) {
|
|
2396
|
+
detach();
|
|
2397
|
+
return;
|
|
2398
|
+
}
|
|
2399
|
+
interruptTimer = setTimeout(() => detach(), dOpts.timeoutSec === void 0 ? 12e4 : dOpts.timeoutSec * 1e3);
|
|
1787
2400
|
});
|
|
1788
2401
|
};
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
2402
|
+
return attempt();
|
|
2403
|
+
}
|
|
2404
|
+
/** §3.1(2026-10-25)interactive-stdin:向当前运行中的命令追加 stdin——只写既有通道
|
|
2405
|
+
* 与身份,不新建命令、账本条目或输出游标;不重连、不重放(dead/disposed 明确拒绝)。
|
|
2406
|
+
* 校验与写入全同步:多次 input 按调用顺序整段写入不交错;写入失败如实抛错(私有
|
|
2407
|
+
* write() 的静默忽略不适用于回执语义)。stdin:"" 是零字节写入,不是 EOF。 */
|
|
2408
|
+
input(options) {
|
|
2409
|
+
const fail = (code, hint) => Promise.reject(/* @__PURE__ */ new Error(`${code} remote: ${hint}`));
|
|
2410
|
+
if (this.state === "disposed") return fail("[E_SESSION_DISPOSED]", `pty session '${displayKey(this.opts.key)}' was disposed — input never reaches a disposed session`);
|
|
2411
|
+
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`);
|
|
2412
|
+
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`);
|
|
2413
|
+
const active = this.activeCommand;
|
|
2414
|
+
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`);
|
|
2415
|
+
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`);
|
|
2416
|
+
const stdin = this.proc?.stdin;
|
|
2417
|
+
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`);
|
|
2418
|
+
try {
|
|
2419
|
+
stdin.write(options.stdin);
|
|
2420
|
+
} catch (error) {
|
|
2421
|
+
return fail("[E_SESSION_WRITE_FAILED]", `writing stdin to pty session '${displayKey(this.opts.key)}' failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
2422
|
+
}
|
|
2423
|
+
return Promise.resolve({
|
|
2424
|
+
session: displayKey(this.opts.key),
|
|
2425
|
+
commandId: active.commandId,
|
|
2426
|
+
...active.jobId !== void 0 ? { jobId: active.jobId } : {},
|
|
2427
|
+
writtenBytes: Buffer$1.byteLength(options.stdin, "utf8")
|
|
2428
|
+
});
|
|
1792
2429
|
}
|
|
1793
2430
|
/** TTL / row teardown:尽力 exit,1s 后杀组,出池。 */
|
|
1794
2431
|
dispose() {
|
|
1795
2432
|
if (this.disposal) return this.disposal;
|
|
1796
2433
|
this.clearIdleTimer();
|
|
2434
|
+
this.clearDeathTimer();
|
|
1797
2435
|
this.state = "disposed";
|
|
1798
2436
|
this.startPromise = null;
|
|
2437
|
+
this.detachedJob?.interrupt();
|
|
1799
2438
|
const proc = this.proc;
|
|
1800
2439
|
const close = this.procClose;
|
|
1801
2440
|
const group = this.reapGroup(proc?.pid, 1e3, close);
|
|
@@ -1806,7 +2445,7 @@ var PtySession = class {
|
|
|
1806
2445
|
]).then(() => {
|
|
1807
2446
|
if (this.proc === proc) this.proc = null;
|
|
1808
2447
|
});
|
|
1809
|
-
this.write("exit\n");
|
|
2448
|
+
if (this.detachedJob === null) this.write("exit\n");
|
|
1810
2449
|
this.opts.onDead?.();
|
|
1811
2450
|
return this.disposal;
|
|
1812
2451
|
}
|
|
@@ -1818,6 +2457,7 @@ var PtySession = class {
|
|
|
1818
2457
|
}
|
|
1819
2458
|
async start() {
|
|
1820
2459
|
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`);
|
|
2460
|
+
this.clearDeathTimer();
|
|
1821
2461
|
if (this.startPromise === null) {
|
|
1822
2462
|
this.state = "starting";
|
|
1823
2463
|
this.startPromise = this.doStart().catch((err) => {
|
|
@@ -1846,6 +2486,9 @@ var PtySession = class {
|
|
|
1846
2486
|
proc.stderr.setEncoding("utf8").on("data", (d) => {
|
|
1847
2487
|
this.diag = (this.diag + d).slice(-2e3);
|
|
1848
2488
|
});
|
|
2489
|
+
proc.stdin.on("error", (err) => {
|
|
2490
|
+
this.diag = (this.diag + `\n[remote: stdin write failed: ${err.message}]`).slice(-2e3);
|
|
2491
|
+
});
|
|
1849
2492
|
this.procClose = new Promise((resolve$1) => {
|
|
1850
2493
|
proc.once("close", () => {
|
|
1851
2494
|
this.markDead();
|
|
@@ -1867,18 +2510,24 @@ var PtySession = class {
|
|
|
1867
2510
|
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
2511
|
};
|
|
1869
2512
|
this.deathWaiters.push(waiter);
|
|
1870
|
-
const parser = createNonceFrameParser(initNonce, {
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
2513
|
+
const parser = createNonceFrameParser(initNonce, {
|
|
2514
|
+
onEnv: (b64) => {
|
|
2515
|
+
const m = decodeEnvSnapshot(b64);
|
|
2516
|
+
if (m !== void 0) this.envBaseline = m;
|
|
2517
|
+
},
|
|
2518
|
+
onFrame: () => {
|
|
2519
|
+
clearTimeout(timer);
|
|
2520
|
+
this.deathWaiters = this.deathWaiters.filter((w) => w !== waiter);
|
|
2521
|
+
if (this.state === "disposed") {
|
|
2522
|
+
reject(/* @__PURE__ */ new Error(`[E_SESSION_DISPOSED] remote pty session '${displayKey(this.opts.key)}' disposed during init`));
|
|
2523
|
+
return;
|
|
2524
|
+
}
|
|
2525
|
+
this.everReady = true;
|
|
2526
|
+
this.state = "ready";
|
|
2527
|
+
this.resetIdleTimer();
|
|
2528
|
+
resolve$1();
|
|
1876
2529
|
}
|
|
1877
|
-
|
|
1878
|
-
this.state = "ready";
|
|
1879
|
-
this.resetIdleTimer();
|
|
1880
|
-
resolve$1();
|
|
1881
|
-
} });
|
|
2530
|
+
});
|
|
1882
2531
|
this.onChunk = (c) => parser.feed(c);
|
|
1883
2532
|
this.write(buildInitCommand(initNonce));
|
|
1884
2533
|
});
|
|
@@ -1893,6 +2542,7 @@ var PtySession = class {
|
|
|
1893
2542
|
this.state = "dead";
|
|
1894
2543
|
this.startPromise = null;
|
|
1895
2544
|
this.clearIdleTimer();
|
|
2545
|
+
this.armDeathReaper();
|
|
1896
2546
|
const waiters = this.deathWaiters;
|
|
1897
2547
|
this.deathWaiters = [];
|
|
1898
2548
|
for (const w of waiters) w();
|
|
@@ -1900,7 +2550,14 @@ var PtySession = class {
|
|
|
1900
2550
|
resetIdleTimer() {
|
|
1901
2551
|
this.clearIdleTimer();
|
|
1902
2552
|
if (this.state === "disposed") return;
|
|
1903
|
-
this.
|
|
2553
|
+
this.idleSince = Date.now();
|
|
2554
|
+
this.idleTimer = setTimeout(() => {
|
|
2555
|
+
if (this.inFlight > 0) {
|
|
2556
|
+
this.resetIdleTimer();
|
|
2557
|
+
return;
|
|
2558
|
+
}
|
|
2559
|
+
this.dispose();
|
|
2560
|
+
}, this.opts.idleTtlSec * 1e3);
|
|
1904
2561
|
this.idleTimer.unref();
|
|
1905
2562
|
}
|
|
1906
2563
|
clearIdleTimer() {
|
|
@@ -1909,6 +2566,22 @@ var PtySession = class {
|
|
|
1909
2566
|
this.idleTimer = null;
|
|
1910
2567
|
}
|
|
1911
2568
|
}
|
|
2569
|
+
/** 意外死亡后的回收:留池只换取一次 reconnect 机会,不得超过一段 idle TTL(R2 复核 P0)。
|
|
2570
|
+
* 否则死会话永久占 label + 永久计入 10 配额,Agent 再也开不出新会话。 */
|
|
2571
|
+
armDeathReaper() {
|
|
2572
|
+
this.clearDeathTimer();
|
|
2573
|
+
if (!this.everReady || this.state !== "dead") return;
|
|
2574
|
+
this.deathTimer = setTimeout(() => {
|
|
2575
|
+
this.dispose();
|
|
2576
|
+
}, this.opts.idleTtlSec * 1e3);
|
|
2577
|
+
this.deathTimer.unref();
|
|
2578
|
+
}
|
|
2579
|
+
clearDeathTimer() {
|
|
2580
|
+
if (this.deathTimer !== null) {
|
|
2581
|
+
clearTimeout(this.deathTimer);
|
|
2582
|
+
this.deathTimer = null;
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
1912
2585
|
killTree() {
|
|
1913
2586
|
const pid = this.proc?.pid;
|
|
1914
2587
|
this.proc = null;
|
|
@@ -1998,19 +2671,20 @@ var PtyPool = class {
|
|
|
1998
2671
|
const s = this.sessions.get(key);
|
|
1999
2672
|
return s === void 0 || s.sessionState === "disposed" ? void 0 : s;
|
|
2000
2673
|
}
|
|
2001
|
-
|
|
2674
|
+
/** v2:创建一律新建(「同 label 同来源复用」废除——复用只走 get/get by id);disposed 残留由这里替换。 */
|
|
2675
|
+
create(opts) {
|
|
2002
2676
|
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
|
-
|
|
2677
|
+
const existing = this.sessions.get(opts.key);
|
|
2678
|
+
if (existing !== void 0 && existing.sessionState !== "disposed") throw new Error(`[E_INTERNAL] remote: pty pool key collision for ${opts.id}`);
|
|
2679
|
+
const s = new PtySession({
|
|
2680
|
+
...opts,
|
|
2681
|
+
...this.defaults,
|
|
2682
|
+
onDead: () => {
|
|
2683
|
+
this.sessions.delete(opts.key);
|
|
2684
|
+
opts.onDead?.();
|
|
2685
|
+
}
|
|
2686
|
+
});
|
|
2687
|
+
this.sessions.set(opts.key, s);
|
|
2014
2688
|
return s;
|
|
2015
2689
|
}
|
|
2016
2690
|
disposeAll() {
|
|
@@ -2053,6 +2727,202 @@ function resolveTarget(target) {
|
|
|
2053
2727
|
host: raw
|
|
2054
2728
|
};
|
|
2055
2729
|
}
|
|
2730
|
+
const TRANSPORTS = [
|
|
2731
|
+
"ssh",
|
|
2732
|
+
"docker",
|
|
2733
|
+
"incus"
|
|
2734
|
+
];
|
|
2735
|
+
function parseTargetForm(target) {
|
|
2736
|
+
if (target === void 0 || target.length === 0) return { form: "empty" };
|
|
2737
|
+
if (target === "pty") return { form: "pty-selector" };
|
|
2738
|
+
if (target.startsWith("pty:")) {
|
|
2739
|
+
const rest = target.slice(4);
|
|
2740
|
+
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")`);
|
|
2741
|
+
return {
|
|
2742
|
+
form: "pty-selector",
|
|
2743
|
+
idOrLabel: rest
|
|
2744
|
+
};
|
|
2745
|
+
}
|
|
2746
|
+
if (target === "ssh") return { form: "ssh-prefix" };
|
|
2747
|
+
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>`}`);
|
|
2748
|
+
if (target.startsWith("hub:")) {
|
|
2749
|
+
const segs = target.slice(4).split(":");
|
|
2750
|
+
if (segs[0] === void 0 || segs[0].length === 0) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — hub takes a machine id`);
|
|
2751
|
+
if (segs.length === 1) return {
|
|
2752
|
+
form: "hub",
|
|
2753
|
+
machine: segs[0]
|
|
2754
|
+
};
|
|
2755
|
+
if (segs.length === 2 && segs[1] === "pty") return {
|
|
2756
|
+
form: "hub-pty",
|
|
2757
|
+
machine: segs[0]
|
|
2758
|
+
};
|
|
2759
|
+
if (segs.length === 3 && segs[1] === "pty") {
|
|
2760
|
+
if (segs[2] === void 0 || segs[2].length === 0) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — empty label after ":pty:"`);
|
|
2761
|
+
return {
|
|
2762
|
+
form: "hub-pty",
|
|
2763
|
+
machine: segs[0],
|
|
2764
|
+
label: segs[2]
|
|
2765
|
+
};
|
|
2766
|
+
}
|
|
2767
|
+
throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — hub PTY is hub:<m4>:pty[:label]`);
|
|
2768
|
+
}
|
|
2769
|
+
for (const transport of TRANSPORTS) {
|
|
2770
|
+
if (!target.startsWith(`${transport}:`)) continue;
|
|
2771
|
+
const rest = target.slice(transport.length + 1);
|
|
2772
|
+
if (rest.length === 0) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — ${transport} takes a name`);
|
|
2773
|
+
const ptyAt = rest.lastIndexOf(":pty");
|
|
2774
|
+
if (ptyAt === -1) return {
|
|
2775
|
+
form: "direct",
|
|
2776
|
+
transport,
|
|
2777
|
+
name: rest
|
|
2778
|
+
};
|
|
2779
|
+
const base = rest.slice(0, ptyAt);
|
|
2780
|
+
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)`);
|
|
2781
|
+
const tail = rest.slice(ptyAt + 4);
|
|
2782
|
+
if (tail.startsWith(":")) {
|
|
2783
|
+
if (tail.length === 1) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — empty label after ":pty:"`);
|
|
2784
|
+
return {
|
|
2785
|
+
form: "create-pty",
|
|
2786
|
+
transport,
|
|
2787
|
+
name: base,
|
|
2788
|
+
label: tail.slice(1)
|
|
2789
|
+
};
|
|
2790
|
+
}
|
|
2791
|
+
if (tail.length > 0) throw new TargetFormatError(`[E_TARGET_FORMAT] remote: ${JSON.stringify(target)} — unexpected ${JSON.stringify(tail)} after ":pty"`);
|
|
2792
|
+
return {
|
|
2793
|
+
form: "create-pty",
|
|
2794
|
+
transport,
|
|
2795
|
+
name: base
|
|
2796
|
+
};
|
|
2797
|
+
}
|
|
2798
|
+
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)`);
|
|
2799
|
+
return {
|
|
2800
|
+
form: "bare",
|
|
2801
|
+
name: target
|
|
2802
|
+
};
|
|
2803
|
+
}
|
|
2804
|
+
|
|
2805
|
+
//#endregion
|
|
2806
|
+
//#region src/remote/labels.ts
|
|
2807
|
+
/** label 字符集(与 BYO ssh label 同源);禁 `pty` 与会话 id 形态(防 selector 歧义)。 */
|
|
2808
|
+
const LABEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
2809
|
+
const PTY_ID_RE = /^pty-[a-z0-9]{4}$/;
|
|
2810
|
+
const RESERVED_LABELS = new Set(["pty"]);
|
|
2811
|
+
function validateLabel(label) {
|
|
2812
|
+
if (!LABEL_RE.test(label)) throw new Error(`[E_BAD_LABEL] remote: label must match ${LABEL_RE.source} (got ${JSON.stringify(label)})`);
|
|
2813
|
+
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)`);
|
|
2814
|
+
}
|
|
2815
|
+
function describeEntry(e) {
|
|
2816
|
+
switch (e.kind) {
|
|
2817
|
+
case "ssh": return `ssh host ${e.name}`;
|
|
2818
|
+
case "ssh-byo": return `a BYO ssh identity (${e.name})`;
|
|
2819
|
+
case "docker": return `docker container ${e.container}`;
|
|
2820
|
+
case "incus": return `incus container ${e.container}`;
|
|
2821
|
+
case "hub": return `hub machine ${e.machine}`;
|
|
2822
|
+
case "pty": return `pty session ${e.id}${e.label !== void 0 ? ` (label ${e.label})` : ""}`;
|
|
2823
|
+
}
|
|
2824
|
+
}
|
|
2825
|
+
/** 机器身份键:同一实体重扫后名字保持稳定(按身份匹配,不按名字)。 */
|
|
2826
|
+
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;
|
|
2827
|
+
const ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
2828
|
+
var LabelPool = class {
|
|
2829
|
+
/** 每 agent session 一个注册表:name → entry(机器 + 认领,到达序)。 */
|
|
2830
|
+
sessions = /* @__PURE__ */ new Map();
|
|
2831
|
+
registry(agent) {
|
|
2832
|
+
let reg = this.sessions.get(agent);
|
|
2833
|
+
if (reg === void 0) {
|
|
2834
|
+
reg = /* @__PURE__ */ new Map();
|
|
2835
|
+
this.sessions.set(agent, reg);
|
|
2836
|
+
}
|
|
2837
|
+
return reg;
|
|
2838
|
+
}
|
|
2839
|
+
resolve(name$1, agent) {
|
|
2840
|
+
return this.sessions.get(agent)?.get(name$1);
|
|
2841
|
+
}
|
|
2842
|
+
/** 显式认领(BYO ssh / PTY label):任何已立名字占用即拒——名字是模型选的,不自动改名。 */
|
|
2843
|
+
claim(name$1, agent, claim) {
|
|
2844
|
+
const reg = this.registry(agent);
|
|
2845
|
+
const existing = reg.get(name$1);
|
|
2846
|
+
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`);
|
|
2847
|
+
reg.set(name$1, claim);
|
|
2848
|
+
}
|
|
2849
|
+
/** 生成不撞本 session 的 id(`pty-` PTY 会话 / `ssh-` BYO ssh 身份)。 */
|
|
2850
|
+
freshId(prefix, agent) {
|
|
2851
|
+
const reg = this.registry(agent);
|
|
2852
|
+
for (;;) {
|
|
2853
|
+
let id = prefix;
|
|
2854
|
+
for (let i = 0; i < 4; i++) id += ID_ALPHABET[Math.floor(Math.random() * 36)];
|
|
2855
|
+
if (!reg.has(id)) return id;
|
|
2856
|
+
}
|
|
2857
|
+
}
|
|
2858
|
+
/**
|
|
2859
|
+
* 现场采集 merge(roster / 裸名 miss 触发):按 ssh → docker → incus → hub 顺序并入。
|
|
2860
|
+
* 已立名字永不挪动:同一实体(身份键相同)保持原槽;新实体撞已立名字 = latecomer,
|
|
2861
|
+
* 自动加 `<transport>-<name>`(再冲突 -2/-3)——无论对方是认领还是更早的机器。
|
|
2862
|
+
* 本轮扫描里消失的机器出表(名字释放);认领永远保留。
|
|
2863
|
+
*/
|
|
2864
|
+
mergeScan(agent, scan) {
|
|
2865
|
+
const reg = this.registry(agent);
|
|
2866
|
+
const renamed = [];
|
|
2867
|
+
const present = /* @__PURE__ */ new Map();
|
|
2868
|
+
for (const [name$1, e] of [...reg]) {
|
|
2869
|
+
const id = machineId(e);
|
|
2870
|
+
if (id === void 0) continue;
|
|
2871
|
+
reg.delete(name$1);
|
|
2872
|
+
present.set(id, e);
|
|
2873
|
+
}
|
|
2874
|
+
const place = (transport, raw, make) => {
|
|
2875
|
+
const id = `${transport}:${raw}`;
|
|
2876
|
+
const known = present.get(id);
|
|
2877
|
+
if (known !== void 0) {
|
|
2878
|
+
reg.set(known.name, known);
|
|
2879
|
+
return;
|
|
2880
|
+
}
|
|
2881
|
+
const fresh = make(raw);
|
|
2882
|
+
if (!reg.has(raw)) {
|
|
2883
|
+
reg.set(raw, fresh);
|
|
2884
|
+
return;
|
|
2885
|
+
}
|
|
2886
|
+
let candidate = `${transport}-${raw}`, n = 2;
|
|
2887
|
+
while (reg.has(candidate)) candidate = `${transport}-${raw}-${n++}`;
|
|
2888
|
+
reg.set(candidate, make(candidate));
|
|
2889
|
+
renamed.push([fresh, candidate]);
|
|
2890
|
+
};
|
|
2891
|
+
for (const host of scan.sshHosts) place("ssh", host, (name$1) => ({
|
|
2892
|
+
kind: "ssh",
|
|
2893
|
+
name: name$1,
|
|
2894
|
+
host
|
|
2895
|
+
}));
|
|
2896
|
+
for (const c of scan.docker) place("docker", c, (name$1) => ({
|
|
2897
|
+
kind: "docker",
|
|
2898
|
+
name: name$1,
|
|
2899
|
+
container: c
|
|
2900
|
+
}));
|
|
2901
|
+
for (const c of scan.incus) place("incus", c, (name$1) => ({
|
|
2902
|
+
kind: "incus",
|
|
2903
|
+
name: name$1,
|
|
2904
|
+
container: c
|
|
2905
|
+
}));
|
|
2906
|
+
for (const m of scan.hub) place("hub", m, (name$1) => ({
|
|
2907
|
+
kind: "hub",
|
|
2908
|
+
name: name$1,
|
|
2909
|
+
machine: m
|
|
2910
|
+
}));
|
|
2911
|
+
return { renamed };
|
|
2912
|
+
}
|
|
2913
|
+
/** 认领释放(会话 dispose/TTL;BYO 身份随 session 存亡);幂等。 */
|
|
2914
|
+
release(name$1, agent) {
|
|
2915
|
+
this.sessions.get(agent)?.delete(name$1);
|
|
2916
|
+
}
|
|
2917
|
+
/** roster 面:本 session 的全部条目(机器 + 认领,插入序)。 */
|
|
2918
|
+
list(agent) {
|
|
2919
|
+
return [...this.sessions.get(agent)?.values() ?? []];
|
|
2920
|
+
}
|
|
2921
|
+
/** driver dispose:全部 session 注册表清空。 */
|
|
2922
|
+
clear() {
|
|
2923
|
+
this.sessions.clear();
|
|
2924
|
+
}
|
|
2925
|
+
};
|
|
2056
2926
|
|
|
2057
2927
|
//#endregion
|
|
2058
2928
|
//#region src/remote/status.ts
|
|
@@ -2128,21 +2998,11 @@ function renderProbe(p) {
|
|
|
2128
2998
|
case "container": return `probe: container ${p.status} (just now, on demand)`;
|
|
2129
2999
|
}
|
|
2130
3000
|
}
|
|
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);
|
|
3001
|
+
/** session card(§5.5,`pty:<id|label>` 无 cmd):connection/state/cwd/ttl 由调用方拼头行,这里渲染账本。 */
|
|
3002
|
+
function renderLedger(ledger) {
|
|
3003
|
+
if (ledger.length === 0) return "ledger: empty — no command has run in this session yet";
|
|
3004
|
+
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}`);
|
|
3005
|
+
return `ledger (last ${ledger.length}):\n${rows.join("\n")}`;
|
|
2146
3006
|
}
|
|
2147
3007
|
|
|
2148
3008
|
//#endregion
|
|
@@ -2234,22 +3094,24 @@ function literalHosts(text) {
|
|
|
2234
3094
|
wildcardBlocks
|
|
2235
3095
|
};
|
|
2236
3096
|
}
|
|
2237
|
-
/**
|
|
2238
|
-
|
|
2239
|
-
* renders its native error (honest vocabulary: never invent, never hide).
|
|
2240
|
-
*/
|
|
2241
|
-
async function renderRoster(sessions, opts = {}) {
|
|
3097
|
+
/** 三段本地扫描(各自独立降级,错误如实带回给 roster 呈现)。 */
|
|
3098
|
+
async function scanLocal(opts = {}) {
|
|
2242
3099
|
const runner = opts.runner ?? runOneShot;
|
|
2243
3100
|
const readSshConfig = opts.readSshConfig ?? (async () => await readFile(join(homedir(), ".ssh", "config"), "utf8"));
|
|
2244
3101
|
const hard = opts.hardTimeoutSec ?? 10;
|
|
2245
|
-
|
|
3102
|
+
let ssh = {
|
|
3103
|
+
hosts: [],
|
|
3104
|
+
wildcardBlocks: 0
|
|
3105
|
+
};
|
|
2246
3106
|
try {
|
|
2247
|
-
|
|
2248
|
-
lines.push(`ssh hosts (~/.ssh/config): ${hosts.length > 0 ? hosts.join(", ") : "(none)"}${wildcardBlocks > 0 ? ` (+${wildcardBlocks} wildcard default blocks, not listed)` : ""}`);
|
|
3107
|
+
ssh = literalHosts(await readSshConfig());
|
|
2249
3108
|
} catch (error) {
|
|
2250
|
-
|
|
3109
|
+
ssh = {
|
|
3110
|
+
hosts: [],
|
|
3111
|
+
wildcardBlocks: 0,
|
|
3112
|
+
error: error instanceof Error ? error.message : String(error)
|
|
3113
|
+
};
|
|
2251
3114
|
}
|
|
2252
|
-
lines.push(`byossh labels (this Agent, in memory): ${opts.byosshLabels?.map((label) => `byossh:${label}`).join(", ") || "(none)"}`);
|
|
2253
3115
|
const docker = await runner([
|
|
2254
3116
|
"docker",
|
|
2255
3117
|
"ps",
|
|
@@ -2257,13 +3119,6 @@ async function renderRoster(sessions, opts = {}) {
|
|
|
2257
3119
|
"--format",
|
|
2258
3120
|
"{{.Names}} {{.State}}"
|
|
2259
3121
|
], { 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
3122
|
const incus = await runner([
|
|
2268
3123
|
"incus",
|
|
2269
3124
|
"list",
|
|
@@ -2272,35 +3127,97 @@ async function renderRoster(sessions, opts = {}) {
|
|
|
2272
3127
|
"--columns",
|
|
2273
3128
|
"ns"
|
|
2274
3129
|
], { timeoutSec: hard });
|
|
2275
|
-
|
|
2276
|
-
|
|
3130
|
+
return {
|
|
3131
|
+
ssh,
|
|
3132
|
+
docker: docker.exit === 0 ? { rows: docker.stdout.trim().split(/\r?\n/).filter(Boolean).map((l) => {
|
|
3133
|
+
const [name$1, state] = l.split(" ");
|
|
3134
|
+
return {
|
|
3135
|
+
name: (name$1 ?? "").trim(),
|
|
3136
|
+
state: (state ?? "").trim()
|
|
3137
|
+
};
|
|
3138
|
+
}).filter((r) => r.name.length > 0) } : {
|
|
3139
|
+
rows: [],
|
|
3140
|
+
error: oneLine(docker.stderr) || `docker exited ${docker.exit}`,
|
|
3141
|
+
...docker.timedOut ? { timedOut: true } : {}
|
|
3142
|
+
},
|
|
3143
|
+
incus: incus.exit === 0 ? { rows: incus.stdout.trim().split(/\r?\n/).filter(Boolean).map((l) => {
|
|
2277
3144
|
const [name$1, state] = l.split(",");
|
|
2278
|
-
return
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
3145
|
+
return {
|
|
3146
|
+
name: (name$1 ?? "").trim(),
|
|
3147
|
+
state: (state ?? "").trim()
|
|
3148
|
+
};
|
|
3149
|
+
}).filter((r) => r.name.length > 0) } : {
|
|
3150
|
+
rows: [],
|
|
3151
|
+
error: oneLine(incus.stderr) || `incus exited ${incus.exit}`,
|
|
3152
|
+
...incus.timedOut ? { timedOut: true } : {}
|
|
3153
|
+
}
|
|
3154
|
+
};
|
|
3155
|
+
}
|
|
3156
|
+
/** 统一池视图的 roster 呈现:机器三段 + BYO ssh 同位(built on)+ pty 会话段(caller-scoped)。 */
|
|
3157
|
+
function renderRoster(scan, entries, sessions, hubTargets) {
|
|
3158
|
+
const lines = [];
|
|
3159
|
+
if (hubTargets !== null) lines.push(`hub machines: ${hubTargets.map((t) => `hub:${t.id} (${t.label}${t.execEnabled ? "" : "; exec disabled"})`).join(", ") || "none"}`);
|
|
3160
|
+
if (scan.ssh.error !== void 0) lines.push(`ssh hosts: no readable ~/.ssh/config (${scan.ssh.error})`);
|
|
3161
|
+
else {
|
|
3162
|
+
const sshNames = entries.filter((e) => e.kind === "ssh").map((e) => e.name);
|
|
3163
|
+
const byoNames = entries.filter((e) => e.kind === "ssh-byo").map((e) => `${e.name} (built on)`);
|
|
3164
|
+
const all = [...sshNames, ...byoNames];
|
|
3165
|
+
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)` : ""}`);
|
|
3166
|
+
}
|
|
3167
|
+
const dockerStates = new Map(scan.docker.rows.map((r) => [r.name, r.state]));
|
|
3168
|
+
const dockerEntries = entries.filter((e) => e.kind === "docker");
|
|
3169
|
+
if (scan.docker.error !== void 0) lines.push(`docker containers: unavailable — ${scan.docker.timedOut ? `scan timed out` : scan.docker.error}`);
|
|
3170
|
+
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)"}`);
|
|
3171
|
+
const incusStates = new Map(scan.incus.rows.map((r) => [r.name, r.state]));
|
|
3172
|
+
const incusEntries = entries.filter((e) => e.kind === "incus");
|
|
3173
|
+
if (scan.incus.error !== void 0) lines.push(`incus containers: unavailable — ${scan.incus.timedOut ? `scan timed out` : scan.incus.error}`);
|
|
3174
|
+
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)"}`);
|
|
3175
|
+
lines.push(sessions.length > 0 ? `pty sessions: ${sessions.map((s) => {
|
|
3176
|
+
const id = s.identity;
|
|
3177
|
+
const snap = s.snapshot;
|
|
3178
|
+
const state = snap.busy ? "busy" : snap.state === "dead" ? "died" : `idle ${Math.round((snap.idleMs ?? 0) / 1e3)}s`;
|
|
3179
|
+
return `pty:${id.id}${id.label !== void 0 ? ` (label ${id.label})` : ""} ${id.connection}${id.byo ? " (byo-pty)" : ""} [${state}]`;
|
|
3180
|
+
}).join(" · ")}` : "pty sessions: none");
|
|
2283
3181
|
return lines.join("\n");
|
|
2284
3182
|
}
|
|
2285
3183
|
|
|
2286
3184
|
//#endregion
|
|
2287
3185
|
//#region src/remote/driver.ts
|
|
2288
|
-
/**
|
|
2289
|
-
const
|
|
2290
|
-
/**
|
|
3186
|
+
/** R1:idle TTL 15 min——idle 随活动重置,在用会话永不超时(PtySession 双条件)。 */
|
|
3187
|
+
const REMOTE_PTY_IDLE_TTL_SEC = 900;
|
|
3188
|
+
/** P3(user 2026-10-19):每 agent 10 个 PTY 会话,跨所有 connection 统一计;仅 error message 披露。 */
|
|
3189
|
+
const REMOTE_PTY_SESSION_LIMIT = 10;
|
|
3190
|
+
/** hub 线 one-shot 监督披露(0.3.2-c):对端 = 我们自己的 hub server(bash -lc 于独立进程组,
|
|
3191
|
+
* Node 原生 TERM→2s→KILL + 输出环 + 租约生命周期);superd-run helper 是 dumb-pipe 专用物,
|
|
3192
|
+
* 从不经 hub 上传(non-goal,docs/10_plans/2026-10-25-hub-remote-parity.md §3 O1/O8)。 */
|
|
3193
|
+
const HUB_RUNNER = "hub-lease (peer bash -lc, peer Node supervision)";
|
|
3194
|
+
/** hub PTY 泵资产:pump 与本模块同目录(npm 包与 Super 闭包同构,helper.ts 同款纪律)。
|
|
3195
|
+
* ws 模块路径由 transport 侧(superd-hub 上下文,分叉的 proven 解析链)解析后经
|
|
3196
|
+
* ptyEndpoint 传入——闭包自身子树无可解析的 ws,按名解析不在闭包里做(0.3.2-c 定稿)。 */
|
|
3197
|
+
function hubPtyAssets() {
|
|
3198
|
+
return { pumpPath: join(dirname(fileURLToPath(import.meta.url)), "hub-pty-pump.mjs") };
|
|
3199
|
+
}
|
|
3200
|
+
/** 账本键与 jobId 同构(同格式 `<kind>-<16hex>`);background 通道预传入 registry id 时两者字面相等。 */
|
|
3201
|
+
const genCommandId = () => `remote-${randomUUID().replace(/-/g, "").slice(0, 16)}`;
|
|
3202
|
+
/** 双轨调度器:参数校验 → 目标语法(parseTargetForm)→ 统一 label 池 → oneshot 子进程 / pty 会话池。 */
|
|
2291
3203
|
var RemoteDriver = class {
|
|
2292
|
-
sshTargets = new SshTargets();
|
|
2293
3204
|
pool;
|
|
3205
|
+
labels = new LabelPool();
|
|
2294
3206
|
hubOwner = randomUUID();
|
|
2295
3207
|
hubProviders = /* @__PURE__ */ new Set();
|
|
2296
3208
|
processes = /* @__PURE__ */ new Set();
|
|
2297
3209
|
starting = /* @__PURE__ */ new Set();
|
|
2298
3210
|
fileAbort = new AbortController();
|
|
2299
3211
|
disposed = false;
|
|
3212
|
+
/** undefined = 未尝试;null = 资产缺失(shim-only);registry = 每 target sticky 状态机。 */
|
|
3213
|
+
helpers;
|
|
3214
|
+
runnerOf = /* @__PURE__ */ new WeakMap();
|
|
2300
3215
|
disposal;
|
|
3216
|
+
ptyIdleTtlSec;
|
|
2301
3217
|
constructor(opts = {}) {
|
|
2302
3218
|
this.opts = opts;
|
|
2303
|
-
this.
|
|
3219
|
+
this.ptyIdleTtlSec = opts.idleTtlSec ?? REMOTE_PTY_IDLE_TTL_SEC;
|
|
3220
|
+
this.pool = new PtyPool({ idleTtlSec: this.ptyIdleTtlSec });
|
|
2304
3221
|
}
|
|
2305
3222
|
async call(params, callCtx = {}) {
|
|
2306
3223
|
const started = Date.now();
|
|
@@ -2308,10 +3225,11 @@ var RemoteDriver = class {
|
|
|
2308
3225
|
this.assertOpen();
|
|
2309
3226
|
const prepared = await prepareRemoteInput(params);
|
|
2310
3227
|
this.assertOpen();
|
|
2311
|
-
const
|
|
2312
|
-
|
|
3228
|
+
const form = parseTargetForm(prepared.target);
|
|
3229
|
+
this.validate(form, prepared);
|
|
3230
|
+
const result = await this.execute(prepared, form, callCtx);
|
|
2313
3231
|
this.audit({
|
|
2314
|
-
target:
|
|
3232
|
+
target: result.target,
|
|
2315
3233
|
cmd: prepared.cmd,
|
|
2316
3234
|
cwd: result.cwd ?? void 0,
|
|
2317
3235
|
exit: result.exit,
|
|
@@ -2328,10 +3246,106 @@ var RemoteDriver = class {
|
|
|
2328
3246
|
throw error;
|
|
2329
3247
|
}
|
|
2330
3248
|
}
|
|
2331
|
-
/**
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
3249
|
+
/** 参数互斥矩阵(§2):spawn/ssh 是 BYO 入口(参数在场即 BYO),只与对应形态的 target 配对。 */
|
|
3250
|
+
validate(form, params) {
|
|
3251
|
+
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)})`);
|
|
3252
|
+
if (params.stdin !== void 0 && (params.cmd === void 0 || params.cmd.length === 0)) throw new Error("[E_STDIN_WITHOUT_CMD] remote: stdin requires cmd");
|
|
3253
|
+
const hasSpawn = params.spawn !== void 0 && params.spawn.length > 0;
|
|
3254
|
+
const hasSsh = params.ssh !== void 0;
|
|
3255
|
+
if (hasSpawn && hasSsh) throw new Error("[E_PARAMS] remote: spawn and ssh are two different BYO entry points — pass one, not both");
|
|
3256
|
+
const ptyForm = form.form === "pty-selector" || form.form === "empty" || form.form === "bare";
|
|
3257
|
+
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";
|
|
3258
|
+
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");
|
|
3259
|
+
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)");
|
|
3260
|
+
}
|
|
3261
|
+
async execute(params, form, callCtx) {
|
|
3262
|
+
const timeoutSec = params.timeout ?? this.opts.execTimeoutSec ?? 120;
|
|
3263
|
+
const sessionKey = callCtx.sessionKey ?? "no-session";
|
|
3264
|
+
const hasCmd = params.cmd !== void 0 && params.cmd.length > 0;
|
|
3265
|
+
params.spawn !== void 0 && params.spawn.length;
|
|
3266
|
+
if (form.form === "hub") {
|
|
3267
|
+
const hub = this.requireHub();
|
|
3268
|
+
this.hubProviders.add(hub);
|
|
3269
|
+
const process$1 = this.own(await hub.start(form.machine, {
|
|
3270
|
+
...params,
|
|
3271
|
+
target: `hub:${form.machine}`,
|
|
3272
|
+
mode: "oneshot",
|
|
3273
|
+
timeout: timeoutSec
|
|
3274
|
+
}, this.hubOwner));
|
|
3275
|
+
if (this.disposed) process$1.cancel("owner disposed");
|
|
3276
|
+
const result = await process$1.done;
|
|
3277
|
+
const stdout = process$1.read("stdout", 0), stderr = process$1.read("stderr", 0);
|
|
3278
|
+
const out = disclose(stdout.text, stdout.stats);
|
|
3279
|
+
const err = disclose(stderr.text, stderr.stats);
|
|
3280
|
+
return {
|
|
3281
|
+
...result,
|
|
3282
|
+
mode: "oneshot",
|
|
3283
|
+
target: `hub:${form.machine}`,
|
|
3284
|
+
connection: `hub:${form.machine}`,
|
|
3285
|
+
cwd: null,
|
|
3286
|
+
reconnected: false,
|
|
3287
|
+
runner: HUB_RUNNER,
|
|
3288
|
+
stdout: (!stdout.stats && stdout.lossy ? "[truncated: peer returned only a tail; exact total/retained/dropped unavailable]\n" : "") + out.text,
|
|
3289
|
+
stderr: [err.text, stderr.diagnostic].filter(Boolean).join("\n"),
|
|
3290
|
+
...out.stats ? { outputStats: {
|
|
3291
|
+
stdout: out.stats,
|
|
3292
|
+
stderr: err.stats
|
|
3293
|
+
} } : { outputStatsUnavailable: true },
|
|
3294
|
+
...out.truncated === void 0 ? {} : { truncated: out.truncated }
|
|
3295
|
+
};
|
|
3296
|
+
}
|
|
3297
|
+
const lane = this.createPtyLane(params, form, sessionKey);
|
|
3298
|
+
if (lane !== void 0) {
|
|
3299
|
+
const session = lane.session;
|
|
3300
|
+
if (!hasCmd) {
|
|
3301
|
+
await session.warm();
|
|
3302
|
+
return this.warmReceipt(session);
|
|
3303
|
+
}
|
|
3304
|
+
return await this.dispatchPty(session, params, callCtx, timeoutSec);
|
|
3305
|
+
}
|
|
3306
|
+
if (params.ssh !== void 0) {
|
|
3307
|
+
const label = form.form === "direct" || form.form === "bare" ? form.name : void 0;
|
|
3308
|
+
const name$1 = this.registerByoSsh(label, params.ssh, sessionKey);
|
|
3309
|
+
if (!hasCmd) return {
|
|
3310
|
+
mode: "oneshot",
|
|
3311
|
+
target: `ssh:${name$1}`,
|
|
3312
|
+
connection: `ssh:${name$1}`,
|
|
3313
|
+
byoTag: "byo-ssh",
|
|
3314
|
+
exit: null,
|
|
3315
|
+
cwd: null,
|
|
3316
|
+
timedOut: false,
|
|
3317
|
+
reconnected: false,
|
|
3318
|
+
stdout: `ssh:${name$1} registered (byo-ssh, no dialing). Reuse the label anywhere ssh: aliases work; a new Agent registers again.`,
|
|
3319
|
+
durationMs: 0
|
|
3320
|
+
};
|
|
3321
|
+
return await this.oneshot({
|
|
3322
|
+
kind: "ssh",
|
|
3323
|
+
host: normalizeSshConnection(params.ssh).host,
|
|
3324
|
+
connection: normalizeSshConnection(params.ssh)
|
|
3325
|
+
}, `ssh:${name$1}`, params, timeoutSec);
|
|
3326
|
+
}
|
|
3327
|
+
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");
|
|
3328
|
+
if (form.form === "pty-selector") {
|
|
3329
|
+
const session = this.resolvePty(form.idOrLabel, sessionKey);
|
|
3330
|
+
if (!hasCmd) return this.cardReceipt(session);
|
|
3331
|
+
return await this.dispatchPty(session, params, callCtx, timeoutSec);
|
|
3332
|
+
}
|
|
3333
|
+
if (form.form === "direct") {
|
|
3334
|
+
const plan$1 = form.transport === "ssh" ? this.sshPlanFor(form.name, sessionKey) : resolveTarget(`${form.transport}:${form.name}`);
|
|
3335
|
+
return await this.oneshot(plan$1, `${form.transport}:${form.name}`, params, timeoutSec);
|
|
3336
|
+
}
|
|
3337
|
+
if (form.form !== "bare") throw new Error("[E_INTERNAL] remote: unreachable target form after routing");
|
|
3338
|
+
const entry = await this.resolvePoolEntry(form.name, sessionKey);
|
|
3339
|
+
if (entry.kind === "pty") {
|
|
3340
|
+
const session = this.resolvePty(form.name, sessionKey);
|
|
3341
|
+
if (!hasCmd) return this.cardReceipt(session);
|
|
3342
|
+
return await this.dispatchPty(session, params, callCtx, timeoutSec);
|
|
3343
|
+
}
|
|
3344
|
+
if (entry.kind === "hub") return await this.hubOneshot(entry.machine, `hub:${entry.machine}`, params, timeoutSec);
|
|
3345
|
+
const plan = this.planOf(entry);
|
|
3346
|
+
return await this.oneshot(plan, form.name, params, timeoutSec);
|
|
3347
|
+
}
|
|
3348
|
+
/** Native-first copy routing (spec: remote-native-shortcut) — unchanged by the workbench round. */
|
|
2335
3349
|
copy(request, signal, callCtx = {}) {
|
|
2336
3350
|
const combined = AbortSignal.any([signal, this.fileAbort.signal]);
|
|
2337
3351
|
const work = (async () => {
|
|
@@ -2403,13 +3417,18 @@ var RemoteDriver = class {
|
|
|
2403
3417
|
path: dst.path,
|
|
2404
3418
|
endpoint: localFileEndpoint()
|
|
2405
3419
|
}, combined);
|
|
2406
|
-
if (request.verify !== void 0
|
|
3420
|
+
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
3421
|
const planOf = (end) => end.kind === "cli" ? end.plan : end.kind === "local" ? { kind: "local" } : void 0;
|
|
2408
3422
|
const srcPlan = planOf(src), dstPlan = planOf(dst);
|
|
2409
3423
|
if (srcPlan === void 0 || dstPlan === void 0) throw new Error("copy: unreachable route resolution");
|
|
3424
|
+
const execArgvFor = (plan, script) => {
|
|
3425
|
+
const argv = helperShellArgv(plan, script);
|
|
3426
|
+
return this.opts.nativeArgvFor ? this.opts.nativeArgvFor(argv) : argv;
|
|
3427
|
+
};
|
|
2410
3428
|
return nativeCopy({
|
|
2411
3429
|
src: request.src,
|
|
2412
3430
|
dst: request.dst,
|
|
3431
|
+
...request.mkdir === void 0 ? {} : { mkdir: request.mkdir },
|
|
2413
3432
|
...request.argv === void 0 ? {} : { argv: request.argv },
|
|
2414
3433
|
...request.pullArgv === void 0 ? {} : { pullArgv: request.pullArgv },
|
|
2415
3434
|
...request.pushArgv === void 0 ? {} : { pushArgv: request.pushArgv }
|
|
@@ -2422,7 +3441,10 @@ var RemoteDriver = class {
|
|
|
2422
3441
|
plan: dstPlan,
|
|
2423
3442
|
path: dst.path
|
|
2424
3443
|
}
|
|
2425
|
-
}, combined, {
|
|
3444
|
+
}, combined, {
|
|
3445
|
+
wrapArgv: this.opts.nativeArgvFor,
|
|
3446
|
+
execArgvFor
|
|
3447
|
+
});
|
|
2426
3448
|
})();
|
|
2427
3449
|
this.starting.add(work);
|
|
2428
3450
|
work.then(() => this.starting.delete(work), () => this.starting.delete(work));
|
|
@@ -2436,7 +3458,8 @@ var RemoteDriver = class {
|
|
|
2436
3458
|
const endpoint = async (value) => {
|
|
2437
3459
|
const parsed = parseFileEndpoint(value);
|
|
2438
3460
|
if (!parsed.target) return { path: parsed.path };
|
|
2439
|
-
|
|
3461
|
+
const form = parseTargetForm(parsed.target);
|
|
3462
|
+
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
3463
|
const plan = await this.resolveConnectionTarget(parsed.target, callCtx);
|
|
2441
3464
|
this.assertOpen();
|
|
2442
3465
|
combined.throwIfAborted();
|
|
@@ -2456,45 +3479,66 @@ var RemoteDriver = class {
|
|
|
2456
3479
|
return work;
|
|
2457
3480
|
}
|
|
2458
3481
|
/** 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]));
|
|
3482
|
+
start(input, signal, callCtx = {}) {
|
|
3483
|
+
const work = this.startPrepared(input, AbortSignal.any([signal, this.fileAbort.signal]), callCtx);
|
|
2461
3484
|
this.starting.add(work);
|
|
2462
3485
|
work.then(() => this.starting.delete(work), () => this.starting.delete(work));
|
|
2463
3486
|
return work;
|
|
2464
3487
|
}
|
|
2465
|
-
async startPrepared(input, signal) {
|
|
3488
|
+
async startPrepared(input, signal, callCtx = {}) {
|
|
2466
3489
|
this.assertOpen();
|
|
2467
3490
|
signal.throwIfAborted();
|
|
2468
3491
|
const params = await prepareRemoteInput(input);
|
|
2469
3492
|
this.assertOpen();
|
|
2470
3493
|
signal.throwIfAborted();
|
|
2471
|
-
const
|
|
2472
|
-
|
|
3494
|
+
const form = parseTargetForm(params.target);
|
|
3495
|
+
this.validate(form, params);
|
|
3496
|
+
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");
|
|
3497
|
+
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
3498
|
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);
|
|
3499
|
+
if (form.form === "hub") process$1 = await this.hubOneshotProcess(form.machine, params);
|
|
3500
|
+
else if (form.form === "direct") {
|
|
3501
|
+
const plan = form.transport === "ssh" ? this.sshPlanFor(form.name, callCtx.sessionKey ?? "no-session") : resolveTarget(`${form.transport}:${form.name}`);
|
|
2483
3502
|
this.assertOpen();
|
|
2484
3503
|
signal.throwIfAborted();
|
|
2485
|
-
if (plan.kind === "pty") throw new Error("remote: background requires oneshot");
|
|
2486
3504
|
process$1 = await this.nativeProcess(plan, params, params.timeout, signal);
|
|
2487
|
-
}
|
|
3505
|
+
} else if (form.form === "bare") {
|
|
3506
|
+
const entry = await this.resolvePoolEntry(form.name, callCtx.sessionKey ?? "no-session");
|
|
3507
|
+
this.assertOpen();
|
|
3508
|
+
signal.throwIfAborted();
|
|
3509
|
+
if (entry.kind === "pty" || entry.kind === "hub") throw new Error("remote: background requires an ssh/docker/incus target");
|
|
3510
|
+
process$1 = await this.nativeProcess(this.planOf(entry), params, params.timeout, signal);
|
|
3511
|
+
} else throw new Error("remote: background oneshot takes a machine target");
|
|
2488
3512
|
this.own(process$1);
|
|
2489
3513
|
if (signal.aborted || this.disposed) process$1.cancel("owner closed during start");
|
|
2490
3514
|
return process$1;
|
|
2491
3515
|
}
|
|
2492
|
-
nativeProcess(plan, params, timeoutSec, signal = this.fileAbort.signal) {
|
|
3516
|
+
async nativeProcess(plan, params, timeoutSec, signal = this.fileAbort.signal) {
|
|
2493
3517
|
const cleanupTag = randomUUID().slice(0, 8);
|
|
3518
|
+
const helper = await this.ensureHelper(plan);
|
|
3519
|
+
if (helper !== null && !this.disposed) {
|
|
3520
|
+
const process$2 = startOneShot(buildHelperOneShotArgv(plan, helper.binPath, {
|
|
3521
|
+
tag: cleanupTag,
|
|
3522
|
+
cmd: params.cmd
|
|
3523
|
+
}), {
|
|
3524
|
+
stdin: params.stdin,
|
|
3525
|
+
timeoutSec
|
|
3526
|
+
});
|
|
3527
|
+
this.runnerOf.set(process$2, `superd-run ${helper.ver} (${helper.triple})`);
|
|
3528
|
+
process$2.done.then((result) => {
|
|
3529
|
+
if (!result.cancelled && !result.timedOut) return;
|
|
3530
|
+
startOneShot(buildHelperKillgroupArgv(plan, helper.binPath, cleanupTag), { timeoutSec: 15 }).done.catch(() => {});
|
|
3531
|
+
}).catch(() => {});
|
|
3532
|
+
const tracked = Promise.resolve(process$2);
|
|
3533
|
+
this.starting.add(tracked);
|
|
3534
|
+
tracked.then(() => this.starting.delete(tracked), () => this.starting.delete(tracked));
|
|
3535
|
+
return tracked;
|
|
3536
|
+
}
|
|
2494
3537
|
const process$1 = startOneShot((this.opts.oneshotArgvFor ?? buildOneShotArgv)(plan, params.cmd, { cleanupTag }), {
|
|
2495
3538
|
stdin: params.stdin,
|
|
2496
3539
|
timeoutSec
|
|
2497
3540
|
});
|
|
3541
|
+
this.runnerOf.set(process$1, "posix-shim");
|
|
2498
3542
|
process$1.done.then((result) => {
|
|
2499
3543
|
if (!result.cancelled && !result.timedOut) return;
|
|
2500
3544
|
const pidfile = `"\${TMPDIR:-/tmp}/superd-oneshot-${cleanupTag}.pgid"`;
|
|
@@ -2506,296 +3550,395 @@ var RemoteDriver = class {
|
|
|
2506
3550
|
work.then(() => this.starting.delete(work), () => this.starting.delete(work));
|
|
2507
3551
|
return work;
|
|
2508
3552
|
}
|
|
3553
|
+
/** Helper bootstrap is best-effort and sticky: any failure parks null for this driver
|
|
3554
|
+
* lifetime and the shim stays the path. First call to a target pays probe (+ upload). */
|
|
3555
|
+
async ensureHelper(plan) {
|
|
3556
|
+
if (this.helpers === void 0) {
|
|
3557
|
+
const assets = this.opts.helperAssetsFor?.() ?? helperAssets();
|
|
3558
|
+
this.helpers = assets === null ? null : new HelperRegistry(assets, (argv, options) => this.helperExec(argv, options), buildHelperProbeArgv, buildHelperUploadArgv);
|
|
3559
|
+
}
|
|
3560
|
+
if (this.helpers === null || this.disposed) return null;
|
|
3561
|
+
try {
|
|
3562
|
+
return await this.helpers.ensure(plan);
|
|
3563
|
+
} catch {
|
|
3564
|
+
return null;
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
async helperExec(argv, options) {
|
|
3568
|
+
this.assertOpen();
|
|
3569
|
+
const stdin = options?.stdin;
|
|
3570
|
+
if (stdin !== void 0) {
|
|
3571
|
+
const proc$1 = startBinaryProcess(argv, { timeoutSec: options?.timeoutSec });
|
|
3572
|
+
proc$1.stdin.on("error", () => {});
|
|
3573
|
+
proc$1.stdin.end(stdin);
|
|
3574
|
+
return {
|
|
3575
|
+
exit: (await proc$1.done).exit,
|
|
3576
|
+
stdout: ""
|
|
3577
|
+
};
|
|
3578
|
+
}
|
|
3579
|
+
const proc = startOneShot(argv, { timeoutSec: options?.timeoutSec });
|
|
3580
|
+
return {
|
|
3581
|
+
exit: (await proc.done).exit,
|
|
3582
|
+
stdout: proc.read("stdout", 0).text
|
|
3583
|
+
};
|
|
3584
|
+
}
|
|
2509
3585
|
own(process$1) {
|
|
2510
3586
|
this.processes.add(process$1);
|
|
2511
3587
|
process$1.done.then(() => this.processes.delete(process$1));
|
|
2512
3588
|
return process$1;
|
|
2513
3589
|
}
|
|
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) {
|
|
3590
|
+
/** 现场采集机器面并 merge 进本 session 注册表(ssh → docker → incus → hub,迟到者加前缀)。错误逐段吞掉(roster 另行如实呈现)。 */
|
|
3591
|
+
async refreshMachines(sessionKey) {
|
|
2521
3592
|
const runner = this.opts.rosterRunner ?? runOneShot;
|
|
2522
3593
|
const readCfg = this.opts.sshConfigReader ?? (async () => await readFile(join(homedir(), ".ssh", "config"), "utf8"));
|
|
2523
|
-
let
|
|
3594
|
+
let sshHosts = [];
|
|
2524
3595
|
try {
|
|
2525
|
-
|
|
3596
|
+
sshHosts = literalHosts(await readCfg()).hosts;
|
|
2526
3597
|
} catch {}
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
};
|
|
2532
|
-
const docker = await
|
|
3598
|
+
const names = (argv) => (async () => {
|
|
3599
|
+
const r = await runner(argv, { timeoutSec: 10 });
|
|
3600
|
+
this.assertOpen();
|
|
3601
|
+
return r.exit === 0 ? r.stdout.trim().split(/\r?\n/).map((l) => l.split(/[\t,]/)[0].trim()).filter((n) => n.length > 0) : [];
|
|
3602
|
+
})().catch(() => []);
|
|
3603
|
+
const [docker, incus] = await Promise.all([names([
|
|
2533
3604
|
"docker",
|
|
2534
3605
|
"ps",
|
|
2535
3606
|
"-a",
|
|
2536
3607
|
"--format",
|
|
2537
3608
|
"{{.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([
|
|
3609
|
+
]), names([
|
|
2545
3610
|
"incus",
|
|
2546
3611
|
"list",
|
|
2547
3612
|
"--format",
|
|
2548
3613
|
"csv",
|
|
2549
3614
|
"--columns",
|
|
2550
3615
|
"n"
|
|
2551
|
-
]
|
|
3616
|
+
])]);
|
|
3617
|
+
const hub = this.opts.getHub?.()?.listTargets().map((t) => t.id) ?? [];
|
|
3618
|
+
this.labels.mergeScan(sessionKey, {
|
|
3619
|
+
sshHosts,
|
|
3620
|
+
docker,
|
|
3621
|
+
incus,
|
|
3622
|
+
hub
|
|
3623
|
+
});
|
|
3624
|
+
}
|
|
3625
|
+
/** 池寻址:命中即回;miss 现场采集一次再寻址(docker 容器名不经 roster 也可达)。 */
|
|
3626
|
+
async resolvePoolEntry(name$1, sessionKey) {
|
|
3627
|
+
const hit = this.labels.resolve(name$1, sessionKey);
|
|
3628
|
+
if (hit !== void 0) return hit;
|
|
3629
|
+
await this.refreshMachines(sessionKey);
|
|
2552
3630
|
this.assertOpen();
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
3631
|
+
const after = this.labels.resolve(name$1, sessionKey);
|
|
3632
|
+
if (after !== void 0) return after;
|
|
3633
|
+
return {
|
|
3634
|
+
kind: "ssh",
|
|
3635
|
+
name: name$1,
|
|
3636
|
+
host: name$1
|
|
2556
3637
|
};
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
3638
|
+
}
|
|
3639
|
+
planOf(entry) {
|
|
3640
|
+
switch (entry.kind) {
|
|
3641
|
+
case "ssh": return {
|
|
3642
|
+
kind: "ssh",
|
|
3643
|
+
host: entry.host
|
|
3644
|
+
};
|
|
3645
|
+
case "ssh-byo": return {
|
|
3646
|
+
kind: "ssh",
|
|
3647
|
+
host: entry.connection.host,
|
|
3648
|
+
connection: entry.connection
|
|
3649
|
+
};
|
|
3650
|
+
case "docker": return {
|
|
3651
|
+
kind: "docker",
|
|
3652
|
+
container: entry.container
|
|
3653
|
+
};
|
|
3654
|
+
case "incus": return {
|
|
3655
|
+
kind: "incus",
|
|
3656
|
+
container: entry.container
|
|
3657
|
+
};
|
|
3658
|
+
case "pty": throw new Error("remote: a PTY session is not a connection target");
|
|
3659
|
+
case "hub": throw new Error("remote: hub machines are not connection targets");
|
|
3660
|
+
}
|
|
3661
|
+
}
|
|
3662
|
+
/** ssh:<name> 的池感知解析:BYO 身份 → 其 connection;否则按 config 别名/主机名。 */
|
|
3663
|
+
sshPlanFor(name$1, sessionKey) {
|
|
3664
|
+
const entry = this.labels.resolve(name$1, sessionKey);
|
|
3665
|
+
if (entry?.kind === "ssh-byo") return {
|
|
3666
|
+
kind: "ssh",
|
|
3667
|
+
host: entry.connection.host,
|
|
3668
|
+
connection: entry.connection
|
|
2560
3669
|
};
|
|
2561
3670
|
return {
|
|
2562
3671
|
kind: "ssh",
|
|
2563
3672
|
host: name$1
|
|
2564
3673
|
};
|
|
2565
3674
|
}
|
|
2566
|
-
/**
|
|
2567
|
-
|
|
2568
|
-
* 而活会话是**操作环境**——复用别的 agent 留下的 shell 等于继承未知状态,且两个 agent 各开一条线
|
|
2569
|
-
* 的代价可忽略。BYO-PTY 天然是活的,于是自然落进这个 scope,无需另立规则。 */
|
|
2570
|
-
async roster(callCtx = {}) {
|
|
3675
|
+
/** BYO ssh 注册(v2:无 spec 对比——label 占用即拒;注册成功才认领)。返回实际名(label 或 s-id)。 */
|
|
3676
|
+
registerByoSsh(label, connection, sessionKey) {
|
|
2571
3677
|
this.assertOpen();
|
|
2572
|
-
const
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
3678
|
+
const normalized = normalizeSshConnection(connection);
|
|
3679
|
+
if (label !== void 0) validateLabel(label);
|
|
3680
|
+
const name$1 = label ?? this.labels.freshId("ssh-", sessionKey);
|
|
3681
|
+
if (label !== void 0) {
|
|
3682
|
+
const existing = this.labels.resolve(label, sessionKey);
|
|
3683
|
+
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`);
|
|
3684
|
+
this.labels.claim(label, sessionKey, {
|
|
3685
|
+
kind: "ssh-byo",
|
|
3686
|
+
name: label,
|
|
3687
|
+
connection: normalized
|
|
3688
|
+
});
|
|
3689
|
+
return label;
|
|
3690
|
+
}
|
|
3691
|
+
this.labels.claim(name$1, sessionKey, {
|
|
3692
|
+
kind: "ssh-byo",
|
|
3693
|
+
name: name$1,
|
|
3694
|
+
connection: normalized
|
|
3695
|
+
});
|
|
3696
|
+
return name$1;
|
|
2588
3697
|
}
|
|
2589
|
-
|
|
3698
|
+
/** PTY 会话创建(native/spawn 同一形状):上限 → label 认领 → 惰性会话(失败由 onDead 释放 label)。 */
|
|
3699
|
+
createSession(opts, sessionKey) {
|
|
2590
3700
|
this.assertOpen();
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
const
|
|
2594
|
-
|
|
2595
|
-
return `${target} — Hub remote machine (${row.label}); exec ${row.execEnabled ? "enabled" : "disabled"}; not probed`;
|
|
3701
|
+
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");
|
|
3702
|
+
if (live.length >= REMOTE_PTY_SESSION_LIMIT) {
|
|
3703
|
+
const listing = live.map(sessionLine).join(" · ");
|
|
3704
|
+
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
3705
|
}
|
|
2597
|
-
const
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
const
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
3706
|
+
const { label } = opts;
|
|
3707
|
+
if (label !== void 0) validateLabel(label);
|
|
3708
|
+
const id = this.labels.freshId("pty-", sessionKey);
|
|
3709
|
+
const entry = {
|
|
3710
|
+
kind: "pty",
|
|
3711
|
+
name: id,
|
|
3712
|
+
id,
|
|
3713
|
+
...label !== void 0 ? { label } : {},
|
|
3714
|
+
connection: opts.connection,
|
|
3715
|
+
byo: opts.byo
|
|
3716
|
+
};
|
|
3717
|
+
if (label !== void 0) this.labels.claim(label, sessionKey, {
|
|
3718
|
+
...entry,
|
|
3719
|
+
name: label
|
|
3720
|
+
});
|
|
3721
|
+
const key = `${sessionKey}|p:${id}`;
|
|
3722
|
+
let session;
|
|
3723
|
+
try {
|
|
3724
|
+
session = this.pool.create({
|
|
3725
|
+
key,
|
|
3726
|
+
argv: opts.argv,
|
|
3727
|
+
id,
|
|
3728
|
+
...label !== void 0 ? { label } : {},
|
|
3729
|
+
connection: opts.connection,
|
|
3730
|
+
byo: opts.byo,
|
|
3731
|
+
builtOn: this.isBuiltOn(opts.connection, sessionKey),
|
|
3732
|
+
...opts.origin !== void 0 ? { origin: opts.origin } : {},
|
|
3733
|
+
onDead: () => {
|
|
3734
|
+
this.labels.release(id, sessionKey);
|
|
3735
|
+
if (label !== void 0) this.labels.release(label, sessionKey);
|
|
3736
|
+
}
|
|
3737
|
+
});
|
|
3738
|
+
} catch (error) {
|
|
3739
|
+
this.labels.release(id, sessionKey);
|
|
3740
|
+
if (label !== void 0) this.labels.release(label, sessionKey);
|
|
3741
|
+
throw error;
|
|
3742
|
+
}
|
|
3743
|
+
this.labels.claim(id, sessionKey, entry);
|
|
3744
|
+
return session;
|
|
2614
3745
|
}
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
return [`${display} — BYO pty session`, renderPtySession(this.pool.inspect(`${sessionKey}|p:${label}`))].join("\n");
|
|
3746
|
+
ttlMinutes() {
|
|
3747
|
+
return Math.max(1, Math.round(this.ptyIdleTtlSec / 60));
|
|
2618
3748
|
}
|
|
2619
|
-
/**
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
this.opts.onAudit?.(r);
|
|
2623
|
-
} catch {}
|
|
3749
|
+
/** connection 由 BYO ssh 身份建立 → card 面标 `(built on)`(与 roster 同词,R2 复核 P2-10)。 */
|
|
3750
|
+
isBuiltOn(connection, sessionKey) {
|
|
3751
|
+
return connection.startsWith("ssh:") && this.labels.resolve(connection.slice(4), sessionKey)?.kind === "ssh-byo";
|
|
2624
3752
|
}
|
|
2625
|
-
/**
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
3753
|
+
/** PTY 创建形唯一实现(execute 与 background 预建共用):spawn BYO / ssh BYO / native `<transport>:pty`。 */
|
|
3754
|
+
createPtyLane(params, form, sessionKey) {
|
|
3755
|
+
if (params.spawn !== void 0 && params.spawn.length > 0) {
|
|
3756
|
+
const label = form.form === "pty-selector" && form.idOrLabel !== void 0 ? form.idOrLabel : form.form === "bare" ? form.name : void 0;
|
|
3757
|
+
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`);
|
|
3758
|
+
return { session: this.createSession({
|
|
3759
|
+
argv: (this.opts.spawnArgvFor ?? buildSpawnArgv)(params.spawn),
|
|
3760
|
+
connection: "BYOP",
|
|
3761
|
+
byo: true,
|
|
3762
|
+
...label !== void 0 ? { label } : {},
|
|
3763
|
+
origin: params.spawn
|
|
3764
|
+
}, sessionKey) };
|
|
3765
|
+
}
|
|
3766
|
+
if (params.ssh !== void 0 && form.form === "create-pty") {
|
|
3767
|
+
const name$1 = this.registerByoSsh(form.name, params.ssh, sessionKey);
|
|
3768
|
+
const connection = normalizeSshConnection(params.ssh);
|
|
3769
|
+
const plan = {
|
|
3770
|
+
kind: "ssh",
|
|
3771
|
+
host: connection.host,
|
|
3772
|
+
connection
|
|
3773
|
+
};
|
|
3774
|
+
return { session: this.createSession({
|
|
3775
|
+
argv: (this.opts.ptyArgvFor ?? buildPtyArgv)(plan),
|
|
3776
|
+
connection: `ssh:${name$1}`,
|
|
3777
|
+
byo: false,
|
|
3778
|
+
...form.label !== void 0 ? { label: form.label } : {}
|
|
3779
|
+
}, sessionKey) };
|
|
3780
|
+
}
|
|
3781
|
+
if (form.form === "create-pty") {
|
|
3782
|
+
const plan = form.transport === "ssh" ? this.sshPlanFor(form.name, sessionKey) : resolveTarget(`${form.transport}:${form.name}`);
|
|
3783
|
+
return { session: this.createSession({
|
|
3784
|
+
argv: (this.opts.ptyArgvFor ?? buildPtyArgv)(plan),
|
|
3785
|
+
connection: `${form.transport}:${form.name}`,
|
|
3786
|
+
byo: false,
|
|
3787
|
+
...form.label !== void 0 ? { label: form.label } : {}
|
|
3788
|
+
}, sessionKey) };
|
|
3789
|
+
}
|
|
3790
|
+
if (form.form === "hub-pty") {
|
|
3791
|
+
const hub = this.requireHub();
|
|
3792
|
+
this.hubProviders.add(hub);
|
|
3793
|
+
const endpoint = hub.ptyEndpoint(form.machine);
|
|
3794
|
+
const argv = this.opts.hubPtyArgvFor !== void 0 ? this.opts.hubPtyArgvFor(endpoint) : buildHubPtyArgv(endpoint, hubPtyAssets());
|
|
3795
|
+
return { session: this.createSession({
|
|
3796
|
+
argv,
|
|
3797
|
+
connection: `hub:${form.machine}`,
|
|
3798
|
+
byo: false,
|
|
3799
|
+
...form.label !== void 0 ? { label: form.label } : {}
|
|
3800
|
+
}, sessionKey) };
|
|
3801
|
+
}
|
|
2641
3802
|
}
|
|
2642
|
-
/**
|
|
2643
|
-
*
|
|
2644
|
-
async
|
|
3803
|
+
/** background PTY lane:会话先占位(不拨号)再进官方 jobs registry——首回执必须能寻址;
|
|
3804
|
+
* registry 拒绝时把新建的会话拆掉(复用形的会话绝不拆)。返回 undefined = 走普通 oneshot job。 */
|
|
3805
|
+
async preparePtyLane(params, callCtx = {}) {
|
|
2645
3806
|
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);
|
|
3807
|
+
const prepared = await prepareRemoteInput(params);
|
|
2650
3808
|
this.assertOpen();
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
if (
|
|
2662
|
-
if (
|
|
3809
|
+
const sessionKey = callCtx.sessionKey ?? "no-session";
|
|
3810
|
+
const form = parseTargetForm(prepared.target);
|
|
3811
|
+
const target = (id$1) => ({
|
|
3812
|
+
target: `pty:${id$1}`,
|
|
3813
|
+
cmd: params.cmd,
|
|
3814
|
+
stdin: params.stdin,
|
|
3815
|
+
timeout: params.timeout,
|
|
3816
|
+
mode: "pty"
|
|
3817
|
+
});
|
|
3818
|
+
const lane = this.createPtyLane(prepared, form, sessionKey);
|
|
3819
|
+
if (lane === void 0 && form.form === "pty-selector") {
|
|
3820
|
+
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");
|
|
3821
|
+
const id$1 = this.resolvePty(form.idOrLabel, sessionKey).identity;
|
|
2663
3822
|
return {
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
3823
|
+
input: target(id$1.id),
|
|
3824
|
+
session: `pty:${id$1.id}`,
|
|
3825
|
+
connection: id$1.connection,
|
|
3826
|
+
...id$1.label !== void 0 ? { label: id$1.label } : {},
|
|
3827
|
+
cleanup: () => void 0
|
|
2667
3828
|
};
|
|
2668
3829
|
}
|
|
2669
|
-
if (
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
3830
|
+
if (lane === void 0) return void 0;
|
|
3831
|
+
const id = lane.session.identity;
|
|
3832
|
+
return {
|
|
3833
|
+
input: target(id.id),
|
|
3834
|
+
session: `pty:${id.id}`,
|
|
3835
|
+
connection: id.connection,
|
|
3836
|
+
...id.label !== void 0 ? { label: id.label } : {},
|
|
3837
|
+
cleanup: () => {
|
|
3838
|
+
lane.session.dispose();
|
|
3839
|
+
}
|
|
3840
|
+
};
|
|
3841
|
+
}
|
|
3842
|
+
/** `pty:<id|label>` 寻址:先 id 后 label;miss 给重建形式。 */
|
|
3843
|
+
resolvePty(selector, sessionKey) {
|
|
3844
|
+
const entry = this.labels.resolve(selector, sessionKey);
|
|
3845
|
+
if (entry?.kind === "pty") {
|
|
3846
|
+
const s = this.pool.get(`${sessionKey}|p:${entry.id}`);
|
|
3847
|
+
if (s !== void 0) return s;
|
|
2681
3848
|
}
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
3849
|
+
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`);
|
|
3850
|
+
}
|
|
3851
|
+
/** §6 close:默认撞 detached job 报错(列杀法);force = 杀组+关闭(披露 killed)。幂等 not-found。 */
|
|
3852
|
+
closePty(selector, sessionKey, force = false) {
|
|
3853
|
+
this.assertOpen();
|
|
3854
|
+
const entry = this.labels.resolve(selector, sessionKey);
|
|
3855
|
+
if (entry?.kind !== "pty") return {
|
|
3856
|
+
session: selector,
|
|
3857
|
+
connection: "",
|
|
3858
|
+
closed: false,
|
|
3859
|
+
reason: "not-found",
|
|
3860
|
+
killed: [],
|
|
3861
|
+
message: `no pty session is registered under ${JSON.stringify(selector)}`
|
|
3862
|
+
};
|
|
3863
|
+
const session = this.pool.get(`${sessionKey}|p:${entry.id}`);
|
|
3864
|
+
if (session === void 0) return {
|
|
3865
|
+
session: `pty:${entry.id}`,
|
|
3866
|
+
connection: entry.connection,
|
|
3867
|
+
closed: false,
|
|
3868
|
+
reason: "already-closed-or-reaped",
|
|
3869
|
+
killed: [],
|
|
3870
|
+
message: `pty:${entry.id} was already closed or reaped after ${this.ttlMinutes()} min idle`
|
|
2687
3871
|
};
|
|
2688
|
-
const
|
|
3872
|
+
const pending = session.detachedCommandId;
|
|
3873
|
+
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`);
|
|
3874
|
+
session.dispose();
|
|
2689
3875
|
return {
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
3876
|
+
session: `pty:${entry.id}`,
|
|
3877
|
+
connection: entry.connection,
|
|
3878
|
+
closed: true,
|
|
3879
|
+
...pending !== null ? { killed: [pending] } : { killed: [] }
|
|
2693
3880
|
};
|
|
2694
3881
|
}
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
const
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
this.hubProviders.add(hub);
|
|
2701
|
-
const machine = routing.display.slice(4);
|
|
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
|
-
};
|
|
3882
|
+
/** job 通道收养回填(timeout handoff 时 registry id ≠ commandId,账本记录两者)。 */
|
|
3883
|
+
attachPtyJob(commandId, jobId, sessionKey) {
|
|
3884
|
+
for (const { key } of this.pool.list()) {
|
|
3885
|
+
if (!key.startsWith(`${sessionKey ?? "no-session"}|`)) continue;
|
|
3886
|
+
this.pool.get(key)?.attachJob(commandId, jobId);
|
|
2743
3887
|
}
|
|
3888
|
+
}
|
|
3889
|
+
/** §3.1(2026-10-25)interactive-stdin:input 动作——向已有 live PTY 的当前运行命令
|
|
3890
|
+
* 追加 stdin。只解析池内已存在的会话(pty:<id|label> / 裸 label 命中 pty 项),
|
|
3891
|
+
* 不触发发现、拨号、创建或重连;machine target 与创建形(:pty 后缀,含 hub:<m4>:pty)
|
|
3892
|
+
* 一律明确拒绝并给出可恢复指引。回执附 connection/label 供工具层渲染。 */
|
|
3893
|
+
async input(target, options, callCtx = {}) {
|
|
3894
|
+
this.assertOpen();
|
|
2744
3895
|
const sessionKey = callCtx.sessionKey ?? "no-session";
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
if (
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
}
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
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
|
-
};
|
|
3896
|
+
const form = parseTargetForm(target);
|
|
3897
|
+
let selector;
|
|
3898
|
+
if (form.form === "pty-selector") {
|
|
3899
|
+
if (form.idOrLabel === void 0) throw new Error("[E_PARAMS] remote: \"pty\" alone selects nothing — append an id/label (pty:pty-1a2b, pty:build)");
|
|
3900
|
+
selector = form.idOrLabel;
|
|
3901
|
+
} else if (form.form === "bare") {
|
|
3902
|
+
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>`);
|
|
3903
|
+
selector = form.name;
|
|
3904
|
+
} 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`);
|
|
3905
|
+
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`);
|
|
3906
|
+
const session = this.resolvePty(selector, sessionKey);
|
|
3907
|
+
const receipt = await session.input(options);
|
|
3908
|
+
const id = session.identity;
|
|
3909
|
+
return {
|
|
3910
|
+
...receipt,
|
|
3911
|
+
connection: id.connection,
|
|
3912
|
+
...id.label !== void 0 ? { label: id.label } : {}
|
|
3913
|
+
};
|
|
3914
|
+
}
|
|
3915
|
+
async dispatchPty(session, params, callCtx, timeoutSec) {
|
|
3916
|
+
const hubConn = session.identity.connection;
|
|
3917
|
+
if (hubConn.startsWith("hub:")) {
|
|
3918
|
+
const hub = this.requireHub();
|
|
3919
|
+
this.hubProviders.add(hub);
|
|
3920
|
+
hub.ptyEndpoint(hubConn.slice(4));
|
|
2788
3921
|
}
|
|
2789
|
-
const
|
|
2790
|
-
const
|
|
2791
|
-
const r = await this.pool.getOrCreate(key, argv).dispatch(params.cmd, {
|
|
3922
|
+
const commandId = callCtx.commandId ?? genCommandId();
|
|
3923
|
+
const r = await session.dispatch(params.cmd, {
|
|
2792
3924
|
stdin: params.stdin,
|
|
2793
|
-
timeoutSec
|
|
3925
|
+
timeoutSec,
|
|
3926
|
+
commandId,
|
|
3927
|
+
...callCtx.ptyBackground === true ? {
|
|
3928
|
+
background: true,
|
|
3929
|
+
jobId: commandId
|
|
3930
|
+
} : {}
|
|
2794
3931
|
});
|
|
2795
|
-
const out =
|
|
3932
|
+
const out = disclose(r.output, r.outputStats?.stdout);
|
|
3933
|
+
const id = session.identity;
|
|
2796
3934
|
return {
|
|
2797
3935
|
mode: "pty",
|
|
2798
|
-
target:
|
|
3936
|
+
target: `pty:${id.id}`,
|
|
3937
|
+
session: `pty:${id.id}`,
|
|
3938
|
+
...id.label !== void 0 ? { label: id.label } : {},
|
|
3939
|
+
connection: id.connection,
|
|
3940
|
+
...id.byo ? { byoTag: "byo-pty" } : {},
|
|
3941
|
+
commandId: r.commandId,
|
|
2799
3942
|
exit: r.exit,
|
|
2800
3943
|
cwd: r.cwd,
|
|
2801
3944
|
timedOut: r.timedOut,
|
|
@@ -2803,42 +3946,211 @@ var RemoteDriver = class {
|
|
|
2803
3946
|
stdout: out.text,
|
|
2804
3947
|
outputStats: out.stats ? { stdout: out.stats } : void 0,
|
|
2805
3948
|
durationMs: r.durationMs,
|
|
2806
|
-
...out.truncated !== void 0 ? { truncated: out.truncated } : {}
|
|
3949
|
+
...out.truncated !== void 0 ? { truncated: out.truncated } : {},
|
|
3950
|
+
...r.envDelta !== void 0 ? { envDelta: r.envDelta } : {},
|
|
3951
|
+
...r.running === true && r.job !== void 0 ? {
|
|
3952
|
+
running: true,
|
|
3953
|
+
ptyJob: r.job
|
|
3954
|
+
} : {},
|
|
3955
|
+
...this.ptyTtl(session.key)
|
|
2807
3956
|
};
|
|
2808
3957
|
}
|
|
2809
|
-
/**
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
3958
|
+
/** 预热(创建形无 cmd)回执:§3——无 commandId/envDelta;timeout 忽略。 */
|
|
3959
|
+
warmReceipt(session) {
|
|
3960
|
+
const id = session.identity;
|
|
3961
|
+
return {
|
|
3962
|
+
mode: "pty",
|
|
3963
|
+
target: `pty:${id.id}`,
|
|
3964
|
+
session: `pty:${id.id}`,
|
|
3965
|
+
...id.label !== void 0 ? { label: id.label } : {},
|
|
3966
|
+
connection: id.connection,
|
|
3967
|
+
...id.byo ? { byoTag: "byo-pty" } : {},
|
|
3968
|
+
created: true,
|
|
3969
|
+
exit: null,
|
|
3970
|
+
cwd: null,
|
|
3971
|
+
timedOut: false,
|
|
3972
|
+
reconnected: false,
|
|
3973
|
+
stdout: "",
|
|
3974
|
+
durationMs: 0,
|
|
3975
|
+
...this.ptyTtl(session.key)
|
|
3976
|
+
};
|
|
3977
|
+
}
|
|
3978
|
+
/** session card 回执(`pty:<id|label>` 无 cmd):connection/state/cwd + 最近 20 条账本(不带输出尾,§9 Q7)。 */
|
|
3979
|
+
cardReceipt(session) {
|
|
3980
|
+
const id = session.identity;
|
|
3981
|
+
const snap = session.snapshot;
|
|
3982
|
+
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)`;
|
|
3983
|
+
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
3984
|
return {
|
|
2828
3985
|
mode: "pty",
|
|
3986
|
+
target: `pty:${id.id}`,
|
|
3987
|
+
session: `pty:${id.id}`,
|
|
3988
|
+
...id.label !== void 0 ? { label: id.label } : {},
|
|
3989
|
+
connection: id.connection,
|
|
3990
|
+
...id.byo ? { byoTag: "byo-pty" } : {},
|
|
3991
|
+
exit: null,
|
|
3992
|
+
cwd: session.lastCwd,
|
|
3993
|
+
timedOut: false,
|
|
3994
|
+
reconnected: false,
|
|
3995
|
+
stdout: [head, renderLedger(session.ledgerSnapshot())].join("\n"),
|
|
3996
|
+
durationMs: 0,
|
|
3997
|
+
...this.ptyTtl(session.key)
|
|
3998
|
+
};
|
|
3999
|
+
}
|
|
4000
|
+
async oneshot(plan, display, params, timeoutSec) {
|
|
4001
|
+
this.assertOpen();
|
|
4002
|
+
const process$1 = this.own(await this.nativeProcess(plan, params, timeoutSec));
|
|
4003
|
+
if (this.disposed) process$1.cancel("owner disposed");
|
|
4004
|
+
const result = await process$1.done;
|
|
4005
|
+
const stdout = process$1.read("stdout", 0), stderr = process$1.read("stderr", 0);
|
|
4006
|
+
const r = {
|
|
4007
|
+
...result,
|
|
4008
|
+
stdout: stdout.text,
|
|
4009
|
+
stderr: [stderr.text, stderr.diagnostic].filter(Boolean).join("\n"),
|
|
4010
|
+
outputStats: {
|
|
4011
|
+
stdout: stdout.stats,
|
|
4012
|
+
stderr: stderr.stats
|
|
4013
|
+
}
|
|
4014
|
+
};
|
|
4015
|
+
const out = disclose(r.stdout, r.outputStats?.stdout);
|
|
4016
|
+
const err = r.stderr.length > 0 ? disclose(r.stderr, r.outputStats?.stderr) : void 0;
|
|
4017
|
+
return {
|
|
4018
|
+
mode: "oneshot",
|
|
2829
4019
|
target: display,
|
|
2830
|
-
session: display,
|
|
2831
4020
|
exit: r.exit,
|
|
2832
|
-
cwd:
|
|
4021
|
+
cwd: null,
|
|
2833
4022
|
timedOut: r.timedOut,
|
|
2834
|
-
reconnected:
|
|
4023
|
+
reconnected: false,
|
|
2835
4024
|
stdout: out.text,
|
|
2836
|
-
...
|
|
2837
|
-
|
|
4025
|
+
...err !== void 0 ? { stderr: err.text } : {},
|
|
4026
|
+
...out.stats ? { outputStats: {
|
|
4027
|
+
stdout: out.stats,
|
|
4028
|
+
stderr: err?.stats ?? r.outputStats?.stderr
|
|
4029
|
+
} } : {},
|
|
2838
4030
|
durationMs: r.durationMs,
|
|
2839
|
-
...out.truncated !== void 0 ? { truncated: out.truncated } : {}
|
|
4031
|
+
...out.truncated !== void 0 ? { truncated: out.truncated } : {},
|
|
4032
|
+
...this.runnerOf.get(process$1) === void 0 ? {} : { runner: this.runnerOf.get(process$1) }
|
|
2840
4033
|
};
|
|
2841
4034
|
}
|
|
4035
|
+
async hubOneshot(machine, display, params, timeoutSec) {
|
|
4036
|
+
const process$1 = this.own(await this.hubOneshotProcess(machine, params));
|
|
4037
|
+
if (this.disposed) process$1.cancel("owner disposed");
|
|
4038
|
+
const result = await process$1.done;
|
|
4039
|
+
const stdout = process$1.read("stdout", 0), stderr = process$1.read("stderr", 0);
|
|
4040
|
+
const out = disclose(stdout.text, stdout.stats);
|
|
4041
|
+
const err = disclose(stderr.text, stderr.stats);
|
|
4042
|
+
return {
|
|
4043
|
+
...result,
|
|
4044
|
+
mode: "oneshot",
|
|
4045
|
+
target: display,
|
|
4046
|
+
connection: display,
|
|
4047
|
+
cwd: null,
|
|
4048
|
+
reconnected: false,
|
|
4049
|
+
runner: HUB_RUNNER,
|
|
4050
|
+
stdout: (!stdout.stats && stdout.lossy ? "[truncated: peer returned only a tail; exact total/retained/dropped unavailable]\n" : "") + out.text,
|
|
4051
|
+
stderr: [err.text, stderr.diagnostic].filter(Boolean).join("\n"),
|
|
4052
|
+
...out.stats ? { outputStats: {
|
|
4053
|
+
stdout: out.stats,
|
|
4054
|
+
stderr: err.stats
|
|
4055
|
+
} } : { outputStatsUnavailable: true },
|
|
4056
|
+
...out.truncated === void 0 ? {} : { truncated: out.truncated }
|
|
4057
|
+
};
|
|
4058
|
+
}
|
|
4059
|
+
async hubOneshotProcess(machine, params) {
|
|
4060
|
+
const hub = this.requireHub();
|
|
4061
|
+
this.hubProviders.add(hub);
|
|
4062
|
+
return await hub.start(machine, {
|
|
4063
|
+
...params,
|
|
4064
|
+
target: `hub:${machine}`,
|
|
4065
|
+
mode: "oneshot"
|
|
4066
|
+
}, this.hubOwner);
|
|
4067
|
+
}
|
|
4068
|
+
/** Ruling P19 + §2.5:roster = 注意力入口——本地扫描刷新统一池,零拨号;机器面公共,会话面 caller-scoped。 */
|
|
4069
|
+
async roster(callCtx = {}) {
|
|
4070
|
+
this.assertOpen();
|
|
4071
|
+
const scan = await scanLocal({
|
|
4072
|
+
runner: this.opts.rosterRunner,
|
|
4073
|
+
readSshConfig: this.opts.sshConfigReader
|
|
4074
|
+
});
|
|
4075
|
+
this.assertOpen();
|
|
4076
|
+
this.labels.mergeScan(callCtx.sessionKey ?? "no-session", {
|
|
4077
|
+
sshHosts: scan.ssh.hosts,
|
|
4078
|
+
docker: scan.docker.rows.map((r) => r.name),
|
|
4079
|
+
incus: scan.incus.rows.map((r) => r.name),
|
|
4080
|
+
hub: this.opts.getHub?.()?.listTargets().map((t) => t.id) ?? []
|
|
4081
|
+
});
|
|
4082
|
+
const prefix = `${callCtx.sessionKey ?? "no-session"}|`;
|
|
4083
|
+
const sessions = this.pool.list().filter(({ key }) => key.startsWith(prefix)).map(({ key }) => {
|
|
4084
|
+
const s = this.pool.get(key);
|
|
4085
|
+
return s === void 0 ? null : s;
|
|
4086
|
+
}).filter((s) => s !== null);
|
|
4087
|
+
const hub = this.opts.getHub?.();
|
|
4088
|
+
return renderRoster(scan, this.labels.list(callCtx.sessionKey ?? "no-session"), sessions, hub === void 0 ? null : hub.listTargets());
|
|
4089
|
+
}
|
|
4090
|
+
/** status probe(target 无 cmd):机器面 = probe + 该 connection 上的会话;pty selector = session card。 */
|
|
4091
|
+
async status(target, callCtx = {}) {
|
|
4092
|
+
this.assertOpen();
|
|
4093
|
+
const sessionKey = callCtx.sessionKey ?? "no-session";
|
|
4094
|
+
const form = parseTargetForm(target);
|
|
4095
|
+
if (form.form === "hub" || form.form === "hub-pty") {
|
|
4096
|
+
const row = this.requireHub().listTargets().find((t) => t.id === form.machine);
|
|
4097
|
+
if (!row) throw new Error(`unknown remote machine ${form.machine} — select a remote machine from the Hub roster; local execution is not available`);
|
|
4098
|
+
return `hub:${form.machine} — Hub remote machine (${row.label}); exec ${row.execEnabled ? "enabled" : "disabled"}; not probed`;
|
|
4099
|
+
}
|
|
4100
|
+
if (form.form === "pty-selector") {
|
|
4101
|
+
if (form.idOrLabel === void 0) throw new Error("[E_PARAMS] remote: \"pty\" alone selects nothing — append an id/label (pty:pty-1a2b, pty:build)");
|
|
4102
|
+
return this.cardReceipt(this.resolvePty(form.idOrLabel, sessionKey)).stdout;
|
|
4103
|
+
}
|
|
4104
|
+
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");
|
|
4105
|
+
const name$1 = directName(form) || (form.form === "bare" ? form.name : "");
|
|
4106
|
+
const entry = await this.resolvePoolEntry(name$1, sessionKey);
|
|
4107
|
+
this.assertOpen();
|
|
4108
|
+
if (entry.kind === "pty") {
|
|
4109
|
+
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>");
|
|
4110
|
+
return this.cardReceipt(this.resolvePty(form.name, sessionKey)).stdout;
|
|
4111
|
+
}
|
|
4112
|
+
if (entry.kind === "hub") return this.status(`hub:${entry.machine}`, callCtx);
|
|
4113
|
+
const plan = this.planOf(entry);
|
|
4114
|
+
const head = `${target} — ${plan.kind === "ssh" ? "ssh host" : `${plan.kind} container`}${entry.kind === "ssh-byo" ? " (built on)" : ""}`;
|
|
4115
|
+
const runner = this.opts.probeRunner ?? runOneShot;
|
|
4116
|
+
const probe = await probeTarget(plan, { runner: (argv, options) => {
|
|
4117
|
+
this.assertOpen();
|
|
4118
|
+
return runner(argv, options);
|
|
4119
|
+
} });
|
|
4120
|
+
const prefix = `${sessionKey}|`;
|
|
4121
|
+
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}`);
|
|
4122
|
+
return [
|
|
4123
|
+
head,
|
|
4124
|
+
renderProbe(probe),
|
|
4125
|
+
onConnection.length > 0 ? `pty sessions on this connection: ${onConnection.map(sessionLine).join(" · ")}` : "pty sessions on this connection: none"
|
|
4126
|
+
].join("\n");
|
|
4127
|
+
}
|
|
4128
|
+
/** Ruling 13:审计 best-effort——钩子抛错不得影响命令路径。 */
|
|
4129
|
+
audit(r) {
|
|
4130
|
+
try {
|
|
4131
|
+
this.opts.onAudit?.(r);
|
|
4132
|
+
} catch {}
|
|
4133
|
+
}
|
|
4134
|
+
/** Single target resolver for later copy/rsync; PTY sessions are not filesystem connections. */
|
|
4135
|
+
async resolveConnectionTarget(target, callCtx = {}) {
|
|
4136
|
+
this.assertOpen();
|
|
4137
|
+
const form = parseTargetForm(target);
|
|
4138
|
+
if (form.form === "pty-selector") throw new Error("remote: a PTY session is not a filesystem connection");
|
|
4139
|
+
if (form.form === "hub" || form.form === "hub-pty") throw new Error("remote: hub endpoints resolve through the Hub file lane, not a CLI connection");
|
|
4140
|
+
if (form.form === "create-pty") throw new Error("remote: a PTY session is not a filesystem connection");
|
|
4141
|
+
if (form.form === "direct") return form.transport === "ssh" ? this.sshPlanFor(form.name, callCtx.sessionKey ?? "no-session") : resolveTarget(`${form.transport}:${form.name}`);
|
|
4142
|
+
if (form.form === "ssh-prefix" || form.form === "empty") throw new Error("[E_TARGET_FORMAT] remote: connection targets need a name");
|
|
4143
|
+
const entry = await this.resolvePoolEntry(form.name, callCtx.sessionKey ?? "no-session");
|
|
4144
|
+
this.assertOpen();
|
|
4145
|
+
return this.planOf(entry);
|
|
4146
|
+
}
|
|
4147
|
+
/** P2/P3:回执即状态快照——idle TTL 剩余随每次 pty 回执带回。 */
|
|
4148
|
+
ptyTtl(key) {
|
|
4149
|
+
const snap = this.pool.inspect(key);
|
|
4150
|
+
if (snap === void 0 || snap.state === "dead" || snap.state === "disposed") return {};
|
|
4151
|
+
if (snap.idleMs === null) return { ttlSec: this.ptyIdleTtlSec };
|
|
4152
|
+
return { ttlSec: Math.max(0, Math.round(this.ptyIdleTtlSec - snap.idleMs / 1e3)) };
|
|
4153
|
+
}
|
|
2842
4154
|
hasHub() {
|
|
2843
4155
|
return this.opts.getHub?.() !== void 0;
|
|
2844
4156
|
}
|
|
@@ -2853,8 +4165,8 @@ var RemoteDriver = class {
|
|
|
2853
4165
|
}
|
|
2854
4166
|
dispose() {
|
|
2855
4167
|
if (this.disposal) return this.disposal;
|
|
2856
|
-
this.sshTargets.clear();
|
|
2857
4168
|
this.disposed = true;
|
|
4169
|
+
this.labels.clear();
|
|
2858
4170
|
this.fileAbort.abort(/* @__PURE__ */ new Error("remote owner disposed"));
|
|
2859
4171
|
for (const process$1 of this.processes) process$1.cancel("remote owner disposed");
|
|
2860
4172
|
return this.disposal = (async () => {
|
|
@@ -2868,13 +4180,87 @@ var RemoteDriver = class {
|
|
|
2868
4180
|
})();
|
|
2869
4181
|
}
|
|
2870
4182
|
};
|
|
4183
|
+
/** direct 形态回退到 resolveTarget 可解析的名字(ssh:dev4 → dev4)。 */
|
|
4184
|
+
function directName(form) {
|
|
4185
|
+
return form.form === "direct" ? form.name : form.form === "create-pty" ? form.name : "";
|
|
4186
|
+
}
|
|
4187
|
+
/** roster/status 一行的会话描述:`p-ab12 (label build) ssh:dev4 idle 12s`。 */
|
|
4188
|
+
function sessionLine(s) {
|
|
4189
|
+
const id = s.identity;
|
|
4190
|
+
const snap = s.snapshot;
|
|
4191
|
+
const state = snap.busy ? "busy" : snap.state === "dead" ? "died" : `idle ${Math.round((snap.idleMs ?? 0) / 1e3)}s`;
|
|
4192
|
+
return `${id.id}${id.label !== void 0 ? ` (label ${id.label})` : ""} ${id.connection}${id.byo ? " (byo-pty)" : ""} ${state}`;
|
|
4193
|
+
}
|
|
2871
4194
|
|
|
2872
4195
|
//#endregion
|
|
2873
4196
|
//#region src/remote/jobs.ts
|
|
4197
|
+
/** PTY job 的单通道输出:流在 PTY 里天然合并,无独立 stderr 通道(P5 如实披露)。
|
|
4198
|
+
* read 是 byte-cursor 增量(Utf16TailRing.read 语义:逐字节游标 + lossy 报尾环逐出)。 */
|
|
4199
|
+
const ptyOutputSources = (holder) => [{
|
|
4200
|
+
channel: "stdout",
|
|
4201
|
+
read: (fromByte) => holder.job?.read(fromByte) ?? {
|
|
4202
|
+
text: "",
|
|
4203
|
+
nextOffset: fromByte,
|
|
4204
|
+
lossy: false
|
|
4205
|
+
}
|
|
4206
|
+
}];
|
|
4207
|
+
/** 0.3.2-d CF:timedOut=true 且 aborted=false = 会话侧主动收束(close force / 行回收走的
|
|
4208
|
+
* dispose→interrupt 两段路)——同为 killed;exit 到手用 exit,只剩会话死亡时写 session closed。 */
|
|
4209
|
+
const ptyOutcome = (aborted, result) => {
|
|
4210
|
+
const interrupted = aborted || result.timedOut === true;
|
|
4211
|
+
return {
|
|
4212
|
+
status: interrupted ? "killed" : result.exit === null ? "failed" : "completed",
|
|
4213
|
+
detail: interrupted ? `interrupted: ${result.exit === null ? aborted ? "session died" : "session closed" : `exit ${result.exit}`}` : result.exit === null ? "session died" : `exit code: ${result.exit}`
|
|
4214
|
+
};
|
|
4215
|
+
};
|
|
2874
4216
|
/** No preparation or discovery before the official registry's admission. */
|
|
2875
4217
|
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
4218
|
if (!exec.agent) throw new Error("remote: background jobs require a live Agent owner");
|
|
4219
|
+
const form = parseTargetForm(input.target);
|
|
4220
|
+
if (form.form === "pty-selector" || form.form === "create-pty" || form.form === "hub-pty" || input.spawn !== void 0 || input.mode === "pty") {
|
|
4221
|
+
const holder = {};
|
|
4222
|
+
return registry.start({
|
|
4223
|
+
kind: "remote",
|
|
4224
|
+
owner: exec.agent.id,
|
|
4225
|
+
label: `${input.target}: ${input.cmd}`,
|
|
4226
|
+
output: ptyOutputSources(holder),
|
|
4227
|
+
run(job) {
|
|
4228
|
+
const controller = new AbortController();
|
|
4229
|
+
return {
|
|
4230
|
+
done: (async () => {
|
|
4231
|
+
try {
|
|
4232
|
+
const r = await driver.call({
|
|
4233
|
+
...input,
|
|
4234
|
+
mode: "pty"
|
|
4235
|
+
}, {
|
|
4236
|
+
ptyBackground: true,
|
|
4237
|
+
commandId: job.id,
|
|
4238
|
+
sessionKey: exec.agent?.id ?? "no-session"
|
|
4239
|
+
});
|
|
4240
|
+
if (r.running !== true || r.ptyJob === void 0) return {
|
|
4241
|
+
status: "failed",
|
|
4242
|
+
detail: "pty dispatch did not hand off a running job"
|
|
4243
|
+
};
|
|
4244
|
+
holder.job = r.ptyJob;
|
|
4245
|
+
if (controller.signal.aborted) r.ptyJob.interrupt();
|
|
4246
|
+
const outcome = await r.ptyJob.done;
|
|
4247
|
+
return ptyOutcome(controller.signal.aborted, outcome);
|
|
4248
|
+
} catch (error) {
|
|
4249
|
+
return {
|
|
4250
|
+
status: controller.signal.aborted ? "killed" : "failed",
|
|
4251
|
+
detail: error instanceof Error ? error.message : String(error)
|
|
4252
|
+
};
|
|
4253
|
+
}
|
|
4254
|
+
})(),
|
|
4255
|
+
cancel(reason) {
|
|
4256
|
+
if (controller.signal.aborted) return;
|
|
4257
|
+
controller.abort(reason);
|
|
4258
|
+
holder.job?.interrupt();
|
|
4259
|
+
}
|
|
4260
|
+
};
|
|
4261
|
+
}
|
|
4262
|
+
});
|
|
4263
|
+
}
|
|
2878
4264
|
let process$1;
|
|
2879
4265
|
const output = ["stdout", "stderr"].map((channel) => ({
|
|
2880
4266
|
channel,
|
|
@@ -2894,7 +4280,7 @@ function startRemoteJob(registry, input, exec, driver) {
|
|
|
2894
4280
|
return registry.start({
|
|
2895
4281
|
kind: "remote",
|
|
2896
4282
|
owner: exec.agent.id,
|
|
2897
|
-
label: `${input.target}: ${input.cmd
|
|
4283
|
+
label: `${input.target}: ${input.cmd}`,
|
|
2898
4284
|
output,
|
|
2899
4285
|
run() {
|
|
2900
4286
|
const controller = new AbortController();
|
|
@@ -2904,7 +4290,7 @@ function startRemoteJob(registry, input, exec, driver) {
|
|
|
2904
4290
|
process$1 = await driver.start({
|
|
2905
4291
|
...input,
|
|
2906
4292
|
mode: "oneshot"
|
|
2907
|
-
}, controller.signal);
|
|
4293
|
+
}, controller.signal, { sessionKey: exec.agent?.id ?? "no-session" });
|
|
2908
4294
|
if (controller.signal.aborted) process$1.cancel(controller.signal.reason);
|
|
2909
4295
|
const result = await process$1.done;
|
|
2910
4296
|
const diagnostic = process$1.read("stderr", 0).diagnostic;
|
|
@@ -2928,82 +4314,351 @@ function startRemoteJob(registry, input, exec, driver) {
|
|
|
2928
4314
|
}
|
|
2929
4315
|
});
|
|
2930
4316
|
}
|
|
4317
|
+
/** P4(2026-10-19)handoff 收养:同步 pty dispatch 超时后命令仍在跑——注册成 job,
|
|
4318
|
+
* job_output 即增量轮询、job_kill 即显式中断(P8 ^C+130-marker,会话存活)。 */
|
|
4319
|
+
function adoptRunningPtyJob(registry, exec, label, job) {
|
|
4320
|
+
if (!exec.agent) throw new Error("remote: background jobs require a live Agent owner");
|
|
4321
|
+
return registry.start({
|
|
4322
|
+
kind: "remote",
|
|
4323
|
+
owner: exec.agent.id,
|
|
4324
|
+
label,
|
|
4325
|
+
output: ptyOutputSources({ job }),
|
|
4326
|
+
run() {
|
|
4327
|
+
const controller = new AbortController();
|
|
4328
|
+
return {
|
|
4329
|
+
done: (async () => {
|
|
4330
|
+
if (controller.signal.aborted) job.interrupt();
|
|
4331
|
+
const outcome = await job.done;
|
|
4332
|
+
return ptyOutcome(controller.signal.aborted, outcome);
|
|
4333
|
+
})(),
|
|
4334
|
+
cancel(reason) {
|
|
4335
|
+
if (controller.signal.aborted) return;
|
|
4336
|
+
controller.abort(reason);
|
|
4337
|
+
job.interrupt();
|
|
4338
|
+
}
|
|
4339
|
+
};
|
|
4340
|
+
}
|
|
4341
|
+
});
|
|
4342
|
+
}
|
|
2931
4343
|
|
|
2932
4344
|
//#endregion
|
|
2933
4345
|
//#region src/remote/tool.ts
|
|
2934
|
-
const NO_SESSION_KEY = "remote:no-session";
|
|
4346
|
+
const NO_SESSION_KEY$1 = "remote:no-session";
|
|
2935
4347
|
/**
|
|
2936
|
-
* The model-visible surface of the `remote` tool.
|
|
2937
|
-
*
|
|
2938
|
-
*
|
|
4348
|
+
* The model-visible surface of the `remote` tool (0.3.2-d user-ruled restructure:
|
|
4349
|
+
* Actions / Targets / PTY / Oneshot / Examples — the PTY block is the user's verbatim
|
|
4350
|
+
* final draft; Examples receipts match renderValue byte-for-byte).
|
|
4351
|
+
* ONE template literal — no backticks, no "${".
|
|
4352
|
+
*
|
|
4353
|
+
* 语义目标(surface 就是产品):动作是唯一的派发维度;PTY 四词定位——stateful oneshot /
|
|
4354
|
+
* interact-able stdin / managed output / persistent env——回执形状与 oneshot 相同、只增状态,
|
|
4355
|
+
* 运行中的命令可分步观察后再补输(input 动作);多步与交互任务默认进 PTY。
|
|
2939
4356
|
*/
|
|
2940
|
-
const REMOTE_TOOL_DESCRIPTION = `Remote
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
4357
|
+
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.
|
|
4358
|
+
|
|
4359
|
+
Actions (action is the only dispatch dimension; unknown fields are rejected):
|
|
4360
|
+
- 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.
|
|
4361
|
+
- 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.
|
|
4362
|
+
- status {}: roster — the one unified pool (machines, identities, live PTY sessions).
|
|
4363
|
+
- status {target}: machine probe, or a session card (connection, cwd, ledger of the last 20 commands).
|
|
4364
|
+
- 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.
|
|
4365
|
+
- close {target, force?}: close a PTY session; a running command refuses it (job_kill first) unless force:true kills it in the same step.
|
|
4366
|
+
|
|
4367
|
+
Targets:
|
|
4368
|
+
- ssh:<name> / docker:<name> / incus:<name> / bare pool name → stateless oneshot.
|
|
4369
|
+
- <machine>:pty[:label] → NEW PTY every call — creation is a target suffix, not a different tool.
|
|
4370
|
+
- pty:<id|label> (or its bare label) → REUSE the live session.
|
|
4371
|
+
After creation, reuse the returned session; repeating :pty opens another. Prefixes force the channel; bare names resolve through the roster.
|
|
4372
|
+
|
|
4373
|
+
PTY:
|
|
4374
|
+
- stateful oneshot, interact-able stdin, managed output, persistent env
|
|
4375
|
+
- timeout (default 120s) → command keeps running; returns job handle.
|
|
4376
|
+
- run_in_background → same job lane. jobId = commandId.
|
|
4377
|
+
- Read: job_output(jobId). Cancel: job_kill; try Ctrl-C first.
|
|
4378
|
+
- Busy session: input / poll / cancel / use another session.
|
|
4379
|
+
- exec.stdin = startup input; input = subsequent input.
|
|
4380
|
+
- input is verbatim: "\\n" submits; "\\u0003" Ctrl-C; "\\u0004" Ctrl-D; "" writes nothing. Ctrl-D follows terminal EOF rules.
|
|
4381
|
+
- commandId, if supplied, must match running command.
|
|
4382
|
+
- Input receipt confirms write only; read result via SAME job.
|
|
4383
|
+
- Output returns in full up to retention (4M chars per stream; Hub oneshot 4MiB bytes) — beyond it the retained tail plus outputStats. Redirect bulk output to files.
|
|
4384
|
+
- Idle expiry: 15 min; running commands exempt.
|
|
4385
|
+
|
|
4386
|
+
Oneshot:
|
|
4387
|
+
- 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.
|
|
4388
|
+
- 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.
|
|
4389
|
+
- 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.
|
|
4390
|
+
|
|
4391
|
+
Examples
|
|
4392
|
+
|
|
4393
|
+
Manage the persistent PTY session. One-shot style output, but stable: every command returns synchronously with exit, cwd, and an env delta.
|
|
4394
|
+
|
|
4395
|
+
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.
|
|
4396
|
+
|
|
4397
|
+
remote { "action": "add", "spawn": "ssh -t pc ssh -t dev4", "target": "pty:dev4via" }
|
|
4398
|
+
|
|
4399
|
+
[session created — address it as pty:pty-irsq]
|
|
4400
|
+
[pty:pty-irsq (dev4via) (byo-pty) · conn BYOP · idle-left ~15m · exit null · 0.0s]
|
|
2948
4401
|
|
|
2949
|
-
|
|
4402
|
+
remote { "action": "exec", "target": "pty:dev4via", "cmd": "hostname && sudo -n ss -tlnp | awk 'NR==1 || /LISTEN/' | head -5" }
|
|
2950
4403
|
|
|
2951
|
-
|
|
4404
|
+
dev4
|
|
4405
|
+
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
|
|
4406
|
+
LISTEN 0 4096 127.0.0.1:45207 0.0.0.0:* users:(("containerd",pid=1070,fd=14))
|
|
4407
|
+
LISTEN 0 4096 127.0.0.1:2019 0.0.0.0:* users:(("caddy",pid=5600,fd=4))
|
|
4408
|
+
LISTEN 0 4096 127.0.0.1:19514 0.0.0.0:* users:(("multica",pid=27030,fd=6))
|
|
4409
|
+
LISTEN 0 4096 127.0.0.54:53 0.0.0.0:* users:(("systemd-resolve",pid=26758,fd=17))
|
|
4410
|
+
[pty:pty-irsq (dev4via) (byo-pty) · conn BYOP · cmd remote-0d89215d1cc64cdc · cwd /home/u1 · idle-left ~15m · exit 0 · 0.3s]
|
|
2952
4411
|
|
|
2953
|
-
|
|
4412
|
+
Reuse the same session for a long task — returns a jobId immediately; collect with job_output, cancel with job_kill:
|
|
4413
|
+
|
|
4414
|
+
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 }
|
|
4415
|
+
|
|
4416
|
+
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.
|
|
4417
|
+
|
|
4418
|
+
job_output { "job_id": "remote-47676dff2c6443e8", "wait": true }
|
|
4419
|
+
|
|
4420
|
+
tick 1
|
|
4421
|
+
tick 2
|
|
4422
|
+
tick 3
|
|
4423
|
+
done
|
|
4424
|
+
[status: completed, exit code: 0]
|
|
4425
|
+
|
|
4426
|
+
- 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).
|
|
4427
|
+
- It also strips one or two shell-escaping layers — commands go straight to the innermost bash, quotes behave naturally.
|
|
4428
|
+
|
|
4429
|
+
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.
|
|
4430
|
+
|
|
4431
|
+
remote { "action": "add", "ssh": { "host": "10.0.0.8", "user": "u1", "port": 22, "key": "/home/u1/.ssh/id_key4" }, "target": "ssh:lab" }
|
|
4432
|
+
remote { "action": "exec", "target": "ssh:lab", "cmd": "uname -a" }
|
|
4433
|
+
remote_transfer { "mode": "rsync", "src": "ssh:lab:/var/log/app/", "dst": "/home/u1/app-logs/", "argv": ["-a"] }`;
|
|
4434
|
+
/** action 是唯一派发维度:每个动词声明自己的字段集,超出即报错(不做在场推断、不留别名)。 */
|
|
4435
|
+
const ACTION_PARAMS = {
|
|
4436
|
+
exec: new Set([
|
|
4437
|
+
"action",
|
|
4438
|
+
"target",
|
|
4439
|
+
"cmd",
|
|
4440
|
+
"stdin",
|
|
4441
|
+
"scriptPath",
|
|
4442
|
+
"timeout",
|
|
4443
|
+
"run_in_background"
|
|
4444
|
+
]),
|
|
4445
|
+
add: new Set([
|
|
4446
|
+
"action",
|
|
4447
|
+
"target",
|
|
4448
|
+
"ssh",
|
|
4449
|
+
"spawn"
|
|
4450
|
+
]),
|
|
4451
|
+
status: new Set(["action", "target"]),
|
|
4452
|
+
close: new Set([
|
|
4453
|
+
"action",
|
|
4454
|
+
"target",
|
|
4455
|
+
"force"
|
|
4456
|
+
]),
|
|
4457
|
+
input: new Set([
|
|
4458
|
+
"action",
|
|
4459
|
+
"target",
|
|
4460
|
+
"stdin",
|
|
4461
|
+
"commandId"
|
|
4462
|
+
])
|
|
4463
|
+
};
|
|
4464
|
+
const ACTION_HINT = {
|
|
4465
|
+
exec: "exec takes target plus cmd (or scriptPath) and the execution options; ssh/spawn belong to add",
|
|
4466
|
+
add: "add takes exactly one of ssh or spawn, plus an optional target label",
|
|
4467
|
+
status: "status takes only an optional target — omit it for the roster",
|
|
4468
|
+
close: "close takes target pty:<id|label> and optional force",
|
|
4469
|
+
input: "input takes target (a live PTY session), stdin, and an optional commandId guard — no cmd, no timeout, no creation"
|
|
4470
|
+
};
|
|
4471
|
+
async function remoteExecute(ENV, args, exec) {
|
|
4472
|
+
const action = args.action;
|
|
4473
|
+
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)");
|
|
4474
|
+
const allowed = ACTION_PARAMS[action];
|
|
4475
|
+
if (allowed === void 0) throw new Error(`[E_PARAMS] remote: unknown action ${JSON.stringify(String(action))} — one of exec / add / close / status / input`);
|
|
4476
|
+
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]}`);
|
|
4477
|
+
const sessionKey = ENV.getSessionKey(exec);
|
|
4478
|
+
const hasTarget = typeof args.target === "string" && args.target.length > 0;
|
|
4479
|
+
const hasCmd = typeof args.cmd === "string" && args.cmd.length > 0;
|
|
4480
|
+
if (action === "status") {
|
|
4481
|
+
if (!hasTarget) return {
|
|
4482
|
+
kind: "roster",
|
|
4483
|
+
text: await ENV.driver.roster({ sessionKey }),
|
|
4484
|
+
exit: null,
|
|
4485
|
+
durationMs: 0
|
|
4486
|
+
};
|
|
4487
|
+
return {
|
|
4488
|
+
kind: "status",
|
|
4489
|
+
text: await ENV.driver.status(args.target, { sessionKey }),
|
|
4490
|
+
exit: null,
|
|
4491
|
+
durationMs: 0
|
|
4492
|
+
};
|
|
4493
|
+
}
|
|
4494
|
+
if (action === "close") {
|
|
4495
|
+
if (!hasTarget) throw new Error("[E_PARAMS] close requires target pty:<id|label>");
|
|
4496
|
+
const r$1 = ENV.driver.closePty(args.target.startsWith("pty:") ? args.target.slice(4) : args.target, sessionKey, args.force === true);
|
|
4497
|
+
return {
|
|
4498
|
+
kind: "close",
|
|
4499
|
+
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"}`,
|
|
4500
|
+
exit: null,
|
|
4501
|
+
durationMs: 0,
|
|
4502
|
+
session: r$1.session,
|
|
4503
|
+
closed: r$1.closed,
|
|
4504
|
+
...r$1.reason !== void 0 ? { reason: r$1.reason } : {},
|
|
4505
|
+
killed: r$1.killed
|
|
4506
|
+
};
|
|
4507
|
+
}
|
|
4508
|
+
if (action === "input") {
|
|
4509
|
+
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)");
|
|
4510
|
+
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)");
|
|
4511
|
+
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");
|
|
4512
|
+
const r$1 = await ENV.driver.input(args.target, {
|
|
4513
|
+
stdin: args.stdin,
|
|
4514
|
+
...args.commandId !== void 0 ? { commandId: args.commandId } : {}
|
|
4515
|
+
}, { sessionKey });
|
|
4516
|
+
const handle = r$1.jobId ?? r$1.commandId;
|
|
4517
|
+
return {
|
|
4518
|
+
kind: "input",
|
|
4519
|
+
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}`,
|
|
4520
|
+
exit: null,
|
|
4521
|
+
durationMs: 0,
|
|
4522
|
+
session: r$1.session,
|
|
4523
|
+
connection: r$1.connection,
|
|
4524
|
+
...r$1.label !== void 0 ? { label: r$1.label } : {},
|
|
4525
|
+
commandId: r$1.commandId,
|
|
4526
|
+
...r$1.jobId !== void 0 ? { jobId: r$1.jobId } : {},
|
|
4527
|
+
writtenBytes: r$1.writtenBytes
|
|
4528
|
+
};
|
|
4529
|
+
}
|
|
4530
|
+
if (action === "add") {
|
|
4531
|
+
const hasSpawn = typeof args.spawn === "string" && args.spawn.length > 0;
|
|
4532
|
+
if (args.spawn !== void 0 && !hasSpawn) throw new Error("[E_PARAMS] remote: add: spawn must be a non-empty command string");
|
|
4533
|
+
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");
|
|
4534
|
+
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");
|
|
4535
|
+
const r$1 = await ENV.driver.call({
|
|
4536
|
+
...hasTarget ? { target: args.target } : {},
|
|
4537
|
+
...args.ssh === void 0 ? {} : { ssh: args.ssh },
|
|
4538
|
+
...hasSpawn ? { spawn: args.spawn } : {},
|
|
4539
|
+
cmd: ""
|
|
4540
|
+
}, { sessionKey });
|
|
4541
|
+
const v$1 = workbenchValue(r$1);
|
|
4542
|
+
v$1.created = true;
|
|
4543
|
+
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)`;
|
|
4544
|
+
return v$1;
|
|
4545
|
+
}
|
|
4546
|
+
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\".");
|
|
4547
|
+
const target = args.target;
|
|
4548
|
+
const ptyTarget = /^pty:/.test(target) || /:pty(:|$)/.test(target);
|
|
4549
|
+
if (args.scriptPath !== void 0) {
|
|
4550
|
+
if (args.scriptPath.length === 0) throw new Error("[E_PARAMS] remote: scriptPath must be a non-empty absolute path");
|
|
4551
|
+
if (ptyTarget) throw new Error("[E_SCRIPT_PARAMS] remote: scriptPath is oneshot-only — PTY lanes take cmd");
|
|
4552
|
+
if (hasCmd) throw new Error("[E_SCRIPT_PARAMS] remote: scriptPath and cmd are alternative carriers — pass one");
|
|
4553
|
+
if (args.stdin !== void 0) throw new Error("[E_SCRIPT_PARAMS] remote: scriptPath already occupies stdin — do not pass stdin with it");
|
|
4554
|
+
}
|
|
4555
|
+
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}");
|
|
4556
|
+
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");
|
|
4557
|
+
if (args.run_in_background) {
|
|
4558
|
+
const jobs = exec.agent?.ctx.get("jobs");
|
|
4559
|
+
if (!jobs) throw new Error("remote: background requires the official DSH jobs service and job_output/job_kill controller; foreground execution remains available");
|
|
4560
|
+
const lane = await ENV.driver.preparePtyLane({
|
|
4561
|
+
target: args.target,
|
|
4562
|
+
cmd: args.cmd,
|
|
4563
|
+
scriptPath: args.scriptPath,
|
|
4564
|
+
stdin: args.stdin,
|
|
4565
|
+
timeout: args.timeout
|
|
4566
|
+
}, { sessionKey });
|
|
4567
|
+
let jobId;
|
|
4568
|
+
try {
|
|
4569
|
+
jobId = startRemoteJob(jobs, lane !== void 0 ? lane.input : {
|
|
4570
|
+
target: args.target,
|
|
4571
|
+
cmd: args.cmd,
|
|
4572
|
+
scriptPath: args.scriptPath,
|
|
4573
|
+
stdin: args.stdin,
|
|
4574
|
+
timeout: args.timeout
|
|
4575
|
+
}, exec, ENV.driver);
|
|
4576
|
+
} catch (error) {
|
|
4577
|
+
lane?.cleanup();
|
|
4578
|
+
throw error;
|
|
4579
|
+
}
|
|
4580
|
+
const where = lane === void 0 ? "" : ` on ${lane.session}${lane.label !== void 0 ? ` (${lane.label})` : ""} (${lane.connection})`;
|
|
4581
|
+
return {
|
|
4582
|
+
kind: "job",
|
|
4583
|
+
jobId,
|
|
4584
|
+
exit: null,
|
|
4585
|
+
durationMs: 0,
|
|
4586
|
+
text: `Started ${jobId}${where}. Use job_output to read and job_kill to cancel; completion is reported by the host.`,
|
|
4587
|
+
...lane !== void 0 ? {
|
|
4588
|
+
commandId: jobId,
|
|
4589
|
+
session: lane.session,
|
|
4590
|
+
connection: lane.connection,
|
|
4591
|
+
...lane.label !== void 0 ? { label: lane.label } : {}
|
|
4592
|
+
} : {}
|
|
4593
|
+
};
|
|
4594
|
+
}
|
|
4595
|
+
const r = await ENV.driver.call({
|
|
4596
|
+
target: args.target,
|
|
4597
|
+
cmd: args.cmd,
|
|
4598
|
+
scriptPath: args.scriptPath,
|
|
4599
|
+
stdin: args.stdin,
|
|
4600
|
+
timeout: args.timeout
|
|
4601
|
+
}, { sessionKey });
|
|
4602
|
+
const v = workbenchValue(r);
|
|
4603
|
+
if (r.running === true && r.ptyJob !== void 0) {
|
|
4604
|
+
const jobs = exec.agent?.ctx.get("jobs");
|
|
4605
|
+
if (jobs) {
|
|
4606
|
+
const jobId = adoptRunningPtyJob(jobs, exec, `${r.target}: ${args.cmd}`, r.ptyJob);
|
|
4607
|
+
v.jobId = jobId;
|
|
4608
|
+
v.running = true;
|
|
4609
|
+
if (r.commandId !== void 0 && jobId !== r.commandId) ENV.driver.attachPtyJob(r.commandId, jobId, sessionKey);
|
|
4610
|
+
} else {
|
|
4611
|
+
r.ptyJob.interrupt();
|
|
4612
|
+
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.";
|
|
4613
|
+
}
|
|
4614
|
+
}
|
|
4615
|
+
return v;
|
|
4616
|
+
}
|
|
2954
4617
|
function createRemoteTool(driver, opts = {}) {
|
|
2955
|
-
const getSessionKey = opts.getSessionKey ?? ((exec) => exec.agent?.id ?? NO_SESSION_KEY);
|
|
4618
|
+
const getSessionKey = opts.getSessionKey ?? ((exec) => exec.agent?.id ?? NO_SESSION_KEY$1);
|
|
2956
4619
|
const tool = defineTool({
|
|
2957
4620
|
name: "remote",
|
|
2958
4621
|
description: REMOTE_TOOL_DESCRIPTION,
|
|
2959
4622
|
parameters: {
|
|
2960
4623
|
action: {
|
|
2961
4624
|
type: "string",
|
|
2962
|
-
enum: [
|
|
2963
|
-
|
|
4625
|
+
enum: [
|
|
4626
|
+
"exec",
|
|
4627
|
+
"add",
|
|
4628
|
+
"status",
|
|
4629
|
+
"close",
|
|
4630
|
+
"input"
|
|
4631
|
+
],
|
|
4632
|
+
required: true,
|
|
4633
|
+
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
4634
|
},
|
|
2965
|
-
|
|
4635
|
+
target: {
|
|
2966
4636
|
type: "string",
|
|
2967
|
-
description: "
|
|
4637
|
+
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
4638
|
},
|
|
2969
|
-
|
|
4639
|
+
cmd: {
|
|
2970
4640
|
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."
|
|
2977
|
-
},
|
|
2978
|
-
pullArgv: {
|
|
2979
|
-
type: "array",
|
|
2980
|
-
items: { type: "string" },
|
|
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."
|
|
4641
|
+
description: "exec: one raw shell string parsed by the remote bash (multi-line = one compound; exit = last command's). Required unless scriptPath is given."
|
|
2982
4642
|
},
|
|
2983
|
-
|
|
2984
|
-
type: "
|
|
2985
|
-
|
|
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."
|
|
4643
|
+
stdin: {
|
|
4644
|
+
type: "string",
|
|
4645
|
+
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
4646
|
},
|
|
2988
|
-
|
|
2989
|
-
type: "
|
|
2990
|
-
description: "
|
|
4647
|
+
commandId: {
|
|
4648
|
+
type: "string",
|
|
4649
|
+
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
4650
|
},
|
|
2992
|
-
|
|
2993
|
-
type: "
|
|
2994
|
-
description: "
|
|
4651
|
+
timeout: {
|
|
4652
|
+
type: "number",
|
|
4653
|
+
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
4654
|
},
|
|
2996
4655
|
run_in_background: {
|
|
2997
4656
|
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."
|
|
4657
|
+
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
4658
|
},
|
|
3004
4659
|
ssh: {
|
|
3005
4660
|
type: "object",
|
|
3006
|
-
description: "
|
|
4661
|
+
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
4662
|
additionalProperties: false,
|
|
3008
4663
|
properties: {
|
|
3009
4664
|
host: {
|
|
@@ -3031,28 +4686,11 @@ function createRemoteTool(driver, opts = {}) {
|
|
|
3031
4686
|
},
|
|
3032
4687
|
spawn: {
|
|
3033
4688
|
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'."
|
|
4689
|
+
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)."
|
|
3048
4690
|
},
|
|
3049
|
-
|
|
3050
|
-
type: "
|
|
3051
|
-
description: "
|
|
3052
|
-
},
|
|
3053
|
-
timeout: {
|
|
3054
|
-
type: "number",
|
|
3055
|
-
description: "Per-command timeout in seconds (default 120, row-configurable). pty: Ctrl-C first, then kill; an interrupt does not kill the session."
|
|
4691
|
+
force: {
|
|
4692
|
+
type: "boolean",
|
|
4693
|
+
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
4694
|
}
|
|
3057
4695
|
},
|
|
3058
4696
|
output: {
|
|
@@ -3068,8 +4706,8 @@ function createRemoteTool(driver, opts = {}) {
|
|
|
3068
4706
|
"status",
|
|
3069
4707
|
"roster",
|
|
3070
4708
|
"job",
|
|
3071
|
-
"
|
|
3072
|
-
"
|
|
4709
|
+
"close",
|
|
4710
|
+
"input"
|
|
3073
4711
|
]
|
|
3074
4712
|
},
|
|
3075
4713
|
text: {
|
|
@@ -3087,8 +4725,49 @@ function createRemoteTool(driver, opts = {}) {
|
|
|
3087
4725
|
truncated: { type: "integer" },
|
|
3088
4726
|
outputStats: { type: "json" },
|
|
3089
4727
|
outputStatsUnavailable: { type: "boolean" },
|
|
3090
|
-
session: {
|
|
3091
|
-
|
|
4728
|
+
session: {
|
|
4729
|
+
type: "string",
|
|
4730
|
+
description: "pty session id, e.g. pty:pty-7k2m"
|
|
4731
|
+
},
|
|
4732
|
+
label: { type: "string" },
|
|
4733
|
+
connection: {
|
|
4734
|
+
type: "string",
|
|
4735
|
+
description: "underlying connection: ssh:dev4 / docker:c / incus:x / hub:m4 / BYOP"
|
|
4736
|
+
},
|
|
4737
|
+
byoTag: { type: "string" },
|
|
4738
|
+
commandId: {
|
|
4739
|
+
type: "string",
|
|
4740
|
+
description: "ledger key; equals the jobId whenever a job exists"
|
|
4741
|
+
},
|
|
4742
|
+
writtenBytes: {
|
|
4743
|
+
type: "integer",
|
|
4744
|
+
description: "input: UTF-8 bytes actually written; confirms the write, not the program response"
|
|
4745
|
+
},
|
|
4746
|
+
envDelta: {
|
|
4747
|
+
type: "json",
|
|
4748
|
+
description: "names only: {added,changed,removed}"
|
|
4749
|
+
},
|
|
4750
|
+
created: { type: "boolean" },
|
|
4751
|
+
notice: { type: "string" },
|
|
4752
|
+
runner: {
|
|
4753
|
+
type: "string",
|
|
4754
|
+
description: "oneshot supervision path: superd-run <ver> (<triple>), posix-shim, or hub-lease (peer hub server supervises natively)"
|
|
4755
|
+
},
|
|
4756
|
+
running: { type: "boolean" },
|
|
4757
|
+
ttlSec: { type: "integer" },
|
|
4758
|
+
closed: {
|
|
4759
|
+
type: "boolean",
|
|
4760
|
+
description: "close: true = the session is gone now"
|
|
4761
|
+
},
|
|
4762
|
+
reason: {
|
|
4763
|
+
type: "string",
|
|
4764
|
+
description: "close: not-found / already-closed-or-reaped"
|
|
4765
|
+
},
|
|
4766
|
+
killed: {
|
|
4767
|
+
type: "array",
|
|
4768
|
+
items: { type: "string" },
|
|
4769
|
+
description: "close force: the running commandIds that were killed"
|
|
4770
|
+
}
|
|
3092
4771
|
}
|
|
3093
4772
|
},
|
|
3094
4773
|
render: (_args, value) => [{
|
|
@@ -3097,174 +4776,257 @@ function createRemoteTool(driver, opts = {}) {
|
|
|
3097
4776
|
}]
|
|
3098
4777
|
},
|
|
3099
4778
|
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;
|
|
4779
|
+
return remoteExecute({
|
|
4780
|
+
driver,
|
|
4781
|
+
getSessionKey
|
|
4782
|
+
}, args, exec);
|
|
3238
4783
|
}
|
|
3239
4784
|
});
|
|
3240
4785
|
const description = tool.description;
|
|
3241
4786
|
Object.defineProperty(tool, "description", {
|
|
3242
4787
|
enumerable: true,
|
|
3243
|
-
get: () => description + (driver.hasHub() ? "\nHub transport available: hub:<m4> selects a paired remote machine (never self).
|
|
4788
|
+
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
4789
|
});
|
|
3245
4790
|
return tool;
|
|
3246
4791
|
}
|
|
4792
|
+
/** RemoteCallResult → RemoteToolValue(pty 工作台字段 + 既有字段)。 */
|
|
4793
|
+
function workbenchValue(r) {
|
|
4794
|
+
const v = {
|
|
4795
|
+
kind: "exec",
|
|
4796
|
+
text: r.stdout,
|
|
4797
|
+
exit: r.exit,
|
|
4798
|
+
durationMs: r.durationMs
|
|
4799
|
+
};
|
|
4800
|
+
if (r.cwd !== null && r.cwd !== void 0) v.cwd = r.cwd;
|
|
4801
|
+
if (r.stderr !== void 0) v.stderr = r.stderr;
|
|
4802
|
+
if (r.timedOut) v.timedOut = true;
|
|
4803
|
+
if (r.reconnected) v.reconnected = true;
|
|
4804
|
+
if (r.truncated !== void 0) v.truncated = r.truncated;
|
|
4805
|
+
if (r.outputStats !== void 0) v.outputStats = r.outputStats;
|
|
4806
|
+
if (r.outputStatsUnavailable) v.outputStatsUnavailable = true;
|
|
4807
|
+
if (r.session !== void 0) v.session = r.session;
|
|
4808
|
+
if (r.label !== void 0) v.label = r.label;
|
|
4809
|
+
if (r.connection !== void 0) v.connection = r.connection;
|
|
4810
|
+
if (r.byoTag !== void 0) v.byoTag = r.byoTag;
|
|
4811
|
+
if (r.commandId !== void 0) v.commandId = r.commandId;
|
|
4812
|
+
if (r.envDelta !== void 0) v.envDelta = r.envDelta;
|
|
4813
|
+
if (r.created === true) v.created = true;
|
|
4814
|
+
if (r.notice !== void 0) v.notice = r.notice;
|
|
4815
|
+
if (r.runner !== void 0) v.runner = r.runner;
|
|
4816
|
+
if (r.ttlSec !== void 0) v.ttlSec = r.ttlSec;
|
|
4817
|
+
return v;
|
|
4818
|
+
}
|
|
4819
|
+
function renderEnvDelta(d) {
|
|
4820
|
+
const bits = [];
|
|
4821
|
+
if (d.added.length > 0) bits.push(`+${d.added.join(",+")}`);
|
|
4822
|
+
if (d.changed.length > 0) bits.push(`~${d.changed.join(",~")}`);
|
|
4823
|
+
if (d.removed.length > 0) bits.push(`-${d.removed.join(",-")}`);
|
|
4824
|
+
return bits.length > 0 ? bits.join(" ") : void 0;
|
|
4825
|
+
}
|
|
3247
4826
|
function renderValue(v) {
|
|
3248
|
-
if (v.kind === "status" || v.kind === "roster" || v.kind === "job" || v.kind === "
|
|
4827
|
+
if (v.kind === "status" || v.kind === "roster" || v.kind === "job" || v.kind === "close" || v.kind === "input") return v.text;
|
|
3249
4828
|
const parts = [];
|
|
3250
4829
|
if (v.reconnected === true) parts.push(RECONNECT_NOTICE);
|
|
3251
4830
|
if (typeof v.notice === "string" && v.notice.length > 0) parts.push(v.notice);
|
|
4831
|
+
if (v.created === true && v.session !== void 0) parts.push(`[session created — address it as ${v.session}]`);
|
|
3252
4832
|
parts.push(v.text);
|
|
3253
4833
|
const secs = ((v.durationMs ?? 0) / 1e3).toFixed(1);
|
|
3254
4834
|
const markers = [];
|
|
4835
|
+
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})` : ""}`);
|
|
4836
|
+
if (typeof v.connection === "string" && v.connection.length > 0 && v.session !== void 0) markers.push(`conn ${v.connection}`);
|
|
4837
|
+
if (typeof v.commandId === "string" && v.commandId.length > 0) markers.push(`cmd ${v.commandId}`);
|
|
4838
|
+
if (typeof v.cwd === "string" && v.cwd.length > 0) markers.push(`cwd ${v.cwd}`);
|
|
4839
|
+
const envTag = v.envDelta !== void 0 ? renderEnvDelta(v.envDelta) : void 0;
|
|
4840
|
+
if (envTag !== void 0) markers.push(`env ${envTag}`);
|
|
4841
|
+
if (typeof v.ttlSec === "number") markers.push(`idle-left ~${Math.max(1, Math.round(v.ttlSec / 60))}m`);
|
|
4842
|
+
if (typeof v.runner === "string" && v.runner.length > 0) markers.push(`runner ${v.runner}`);
|
|
3255
4843
|
if (v.timedOut === true) markers.push("interrupted");
|
|
4844
|
+
markers.push(`exit ${v.exit}`);
|
|
4845
|
+
markers.push(`${secs}s`);
|
|
4846
|
+
if (v.running === true) markers.push(`still running — poll job_output${v.jobId !== void 0 ? ` ${v.jobId}` : ""}`);
|
|
3256
4847
|
if (v.truncated !== void 0) markers.push(`truncated, ${v.outputStatsUnavailable ? "returned peer tail" : "original"} ${v.truncated} ${v.outputStats?.stdout.unit === "bytes" ? "bytes" : "chars"}`);
|
|
3257
|
-
if (v.outputStatsUnavailable) markers.push("peer output totals/retention unavailable
|
|
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}]`);
|
|
4848
|
+
if (v.outputStatsUnavailable) markers.push("peer output totals/retention unavailable");
|
|
4849
|
+
parts.push(`[${markers.join(" · ")}]`);
|
|
4850
|
+
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
4851
|
if (v.stderr !== void 0 && v.stderr.length > 0) parts.push("[stderr]", v.stderr);
|
|
3263
4852
|
return parts.join("\n");
|
|
3264
4853
|
}
|
|
3265
4854
|
|
|
4855
|
+
//#endregion
|
|
4856
|
+
//#region src/remote/transfer-tool.ts
|
|
4857
|
+
const NO_SESSION_KEY = "remote:no-session";
|
|
4858
|
+
/**
|
|
4859
|
+
* The model-visible surface of the `remote_transfer` tool (split out of
|
|
4860
|
+
* `remote`, 2026-10-25). ONE template literal — no backticks, no "${".
|
|
4861
|
+
*/
|
|
4862
|
+
const TRANSFER_TOOL_DESCRIPTION = `File transfer between any two supported endpoints. Every call declares its mode:
|
|
4863
|
+
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.
|
|
4864
|
+
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.
|
|
4865
|
+
|
|
4866
|
+
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.
|
|
4867
|
+
|
|
4868
|
+
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.
|
|
4869
|
+
|
|
4870
|
+
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.
|
|
4871
|
+
|
|
4872
|
+
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.`;
|
|
4873
|
+
const KNOWN_PARAMS = new Set([
|
|
4874
|
+
"mode",
|
|
4875
|
+
"src",
|
|
4876
|
+
"dst",
|
|
4877
|
+
"argv",
|
|
4878
|
+
"pullArgv",
|
|
4879
|
+
"pushArgv",
|
|
4880
|
+
"verify",
|
|
4881
|
+
"mkdir"
|
|
4882
|
+
]);
|
|
4883
|
+
async function transferExecute(ENV, args, exec) {
|
|
4884
|
+
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`);
|
|
4885
|
+
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)`);
|
|
4886
|
+
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`);
|
|
4887
|
+
const sessionKey = ENV.getSessionKey(exec);
|
|
4888
|
+
if (args.mode === "rsync") {
|
|
4889
|
+
if (args.pullArgv !== void 0 || args.pushArgv !== void 0) throw new Error("remote_transfer: rsync takes argv only; pullArgv/pushArgv are copy-only fields");
|
|
4890
|
+
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");
|
|
4891
|
+
const start$1 = Date.now();
|
|
4892
|
+
const receipt$1 = await ENV.driver.rsync({
|
|
4893
|
+
src: args.src,
|
|
4894
|
+
dst: args.dst,
|
|
4895
|
+
...args.argv === void 0 ? {} : { argv: args.argv }
|
|
4896
|
+
}, exec.signal, { sessionKey });
|
|
4897
|
+
if (receipt$1.ok === false || receipt$1.exit !== 0) throw new Error(JSON.stringify(receipt$1));
|
|
4898
|
+
const durationMs$1 = Date.now() - start$1;
|
|
4899
|
+
return {
|
|
4900
|
+
kind: "rsync",
|
|
4901
|
+
text: formatTransferLine("rsync", receipt$1, durationMs$1),
|
|
4902
|
+
receipt: receipt$1,
|
|
4903
|
+
exit: receipt$1.exit,
|
|
4904
|
+
durationMs: durationMs$1
|
|
4905
|
+
};
|
|
4906
|
+
}
|
|
4907
|
+
const start = Date.now();
|
|
4908
|
+
const receipt = await ENV.driver.copy({
|
|
4909
|
+
src: args.src,
|
|
4910
|
+
dst: args.dst,
|
|
4911
|
+
...args.verify === void 0 ? {} : { verify: args.verify },
|
|
4912
|
+
...args.mkdir === void 0 ? {} : { mkdir: args.mkdir },
|
|
4913
|
+
...args.argv === void 0 ? {} : { argv: args.argv },
|
|
4914
|
+
...args.pullArgv === void 0 ? {} : { pullArgv: args.pullArgv },
|
|
4915
|
+
...args.pushArgv === void 0 ? {} : { pushArgv: args.pushArgv }
|
|
4916
|
+
}, exec.signal, { sessionKey });
|
|
4917
|
+
const asReceipt = receipt;
|
|
4918
|
+
const exits = asReceipt.exits ?? [];
|
|
4919
|
+
if (asReceipt.ok === false || exits.some((code) => code !== 0)) throw new Error(JSON.stringify(receipt));
|
|
4920
|
+
const durationMs = Date.now() - start;
|
|
4921
|
+
return {
|
|
4922
|
+
kind: "copy",
|
|
4923
|
+
text: formatTransferLine("copy", receipt, durationMs),
|
|
4924
|
+
receipt,
|
|
4925
|
+
exit: exits.length > 0 ? 0 : null,
|
|
4926
|
+
durationMs
|
|
4927
|
+
};
|
|
4928
|
+
}
|
|
4929
|
+
function createRemoteTransferTool(driver, opts = {}) {
|
|
4930
|
+
const getSessionKey = opts.getSessionKey ?? ((exec) => exec.agent?.id ?? NO_SESSION_KEY);
|
|
4931
|
+
return defineTool({
|
|
4932
|
+
name: "remote_transfer",
|
|
4933
|
+
description: TRANSFER_TOOL_DESCRIPTION,
|
|
4934
|
+
parameters: {
|
|
4935
|
+
mode: {
|
|
4936
|
+
type: "string",
|
|
4937
|
+
enum: ["copy", "rsync"],
|
|
4938
|
+
required: true,
|
|
4939
|
+
description: "Required. copy = tree copy through each endpoint's native CLI, or the Hub binary lane; rsync = SSH only (argv only, no verify/mkdir)."
|
|
4940
|
+
},
|
|
4941
|
+
src: {
|
|
4942
|
+
type: "string",
|
|
4943
|
+
description: "Source [target:]absolute path. No target = the machine running this Agent."
|
|
4944
|
+
},
|
|
4945
|
+
dst: {
|
|
4946
|
+
type: "string",
|
|
4947
|
+
description: "Destination [target:]absolute path. No target = the machine running this Agent."
|
|
4948
|
+
},
|
|
4949
|
+
argv: {
|
|
4950
|
+
type: "array",
|
|
4951
|
+
items: { type: "string" },
|
|
4952
|
+
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."
|
|
4953
|
+
},
|
|
4954
|
+
pullArgv: {
|
|
4955
|
+
type: "array",
|
|
4956
|
+
items: { type: "string" },
|
|
4957
|
+
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."
|
|
4958
|
+
},
|
|
4959
|
+
pushArgv: {
|
|
4960
|
+
type: "array",
|
|
4961
|
+
items: { type: "string" },
|
|
4962
|
+
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."
|
|
4963
|
+
},
|
|
4964
|
+
verify: {
|
|
4965
|
+
type: "boolean",
|
|
4966
|
+
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."
|
|
4967
|
+
},
|
|
4968
|
+
mkdir: {
|
|
4969
|
+
type: "boolean",
|
|
4970
|
+
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."
|
|
4971
|
+
}
|
|
4972
|
+
},
|
|
4973
|
+
output: {
|
|
4974
|
+
schema: {
|
|
4975
|
+
type: "object",
|
|
4976
|
+
additionalProperties: false,
|
|
4977
|
+
properties: {
|
|
4978
|
+
kind: {
|
|
4979
|
+
type: "string",
|
|
4980
|
+
required: true,
|
|
4981
|
+
enum: ["copy", "rsync"]
|
|
4982
|
+
},
|
|
4983
|
+
text: {
|
|
4984
|
+
type: "string",
|
|
4985
|
+
required: true
|
|
4986
|
+
},
|
|
4987
|
+
receipt: { type: "json" },
|
|
4988
|
+
exit: { oneOf: [{ type: "integer" }, { type: "null" }] },
|
|
4989
|
+
durationMs: { type: "integer" }
|
|
4990
|
+
}
|
|
4991
|
+
},
|
|
4992
|
+
render: (_args, value) => [{
|
|
4993
|
+
type: "text",
|
|
4994
|
+
text: value.text
|
|
4995
|
+
}]
|
|
4996
|
+
},
|
|
4997
|
+
async execute(args, exec) {
|
|
4998
|
+
return transferExecute({
|
|
4999
|
+
driver,
|
|
5000
|
+
getSessionKey
|
|
5001
|
+
}, args, exec);
|
|
5002
|
+
}
|
|
5003
|
+
});
|
|
5004
|
+
}
|
|
5005
|
+
/** S8 (2026-10-17): copy/rsync render as one formatted line; the full receipt
|
|
5006
|
+
* stays in the receipt field — raw-JSON dumps are gone from text. */
|
|
5007
|
+
function formatTransferLine(mode, receipt, durationMs) {
|
|
5008
|
+
const r = receipt;
|
|
5009
|
+
const parts = [];
|
|
5010
|
+
if (r.ok === false) parts.push(`✗ ${r.reason ?? "failed"}`);
|
|
5011
|
+
parts.push(`${mode} ${r.src} → ${r.dst}`);
|
|
5012
|
+
if (r.route !== void 0 && r.route !== "") parts.push(`route ${r.route}`);
|
|
5013
|
+
if (r.exits !== void 0) parts.push(`exits [${r.exits.join(",")}]`);
|
|
5014
|
+
else if (r.exit !== void 0) parts.push(`exit ${r.exit}`);
|
|
5015
|
+
if (r.verification !== void 0) parts.push(`verification ${r.verification}`);
|
|
5016
|
+
if (r.created === true) parts.push("created yes");
|
|
5017
|
+
else if (r.created === false) parts.push("created pre-existing");
|
|
5018
|
+
else if (r.created === "n-a") parts.push("created n-a");
|
|
5019
|
+
if (r.cleanup !== void 0 && r.cleanup !== "none-required") parts.push(`cleanup ${r.cleanup}`);
|
|
5020
|
+
if (typeof r.bytes === "number") parts.push(`${r.bytes} bytes / ${r.entries} entries`);
|
|
5021
|
+
parts.push(`${(durationMs / 1e3).toFixed(1)}s`);
|
|
5022
|
+
if (r.note !== void 0 && r.note.length > 0) parts.push(`(${r.note})`);
|
|
5023
|
+
return parts.join(" · ");
|
|
5024
|
+
}
|
|
5025
|
+
|
|
3266
5026
|
//#endregion
|
|
3267
5027
|
//#region src/remote/agent-registration.ts
|
|
5028
|
+
/** The pair a row contributes: execution/PTY and file transfer are separate tools. */
|
|
5029
|
+
const TOOL_NAMES = ["remote", "remote_transfer"];
|
|
3268
5030
|
/** Host listeners attempt once per official creation edge, never on vacancy. */
|
|
3269
5031
|
function installAgentRemote(ctx, config) {
|
|
3270
5032
|
return ctx.on("agent/created", ({ agent }) => {
|
|
@@ -3274,12 +5036,14 @@ function installAgentRemote(ctx, config) {
|
|
|
3274
5036
|
...config,
|
|
3275
5037
|
getHub: () => agent.ctx.get("superdRemoteTransport")
|
|
3276
5038
|
});
|
|
3277
|
-
|
|
5039
|
+
const registered = [];
|
|
3278
5040
|
try {
|
|
3279
|
-
|
|
5041
|
+
registered.push(tools.register(createRemoteTool(driver, { getSessionKey: () => agent.id })));
|
|
5042
|
+
registered.push(tools.register(createRemoteTransferTool(driver, { getSessionKey: () => agent.id })));
|
|
3280
5043
|
} catch (error) {
|
|
5044
|
+
for (const undo of registered.splice(0)) undo();
|
|
3281
5045
|
driver.dispose();
|
|
3282
|
-
if (error instanceof Error && error.message ===
|
|
5046
|
+
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
5047
|
throw error;
|
|
3284
5048
|
}
|
|
3285
5049
|
const stopService = agent.ctx.on("internal/service", (name$1) => {
|
|
@@ -3291,7 +5055,7 @@ function installAgentRemote(ctx, config) {
|
|
|
3291
5055
|
const cleanup = () => {
|
|
3292
5056
|
if (disposal) return disposal;
|
|
3293
5057
|
disposal = driver.dispose();
|
|
3294
|
-
|
|
5058
|
+
for (const undo of registered.splice(0)) undo();
|
|
3295
5059
|
stopService();
|
|
3296
5060
|
ownerUndo?.();
|
|
3297
5061
|
agentUndo?.();
|
|
@@ -3347,12 +5111,10 @@ const name = "dashr-remote";
|
|
|
3347
5111
|
const inject = [];
|
|
3348
5112
|
const Config = Schema.object({
|
|
3349
5113
|
execTimeoutSec: Schema.natural().min(1).default(120),
|
|
3350
|
-
idleTtlSec: Schema.natural().min(1).default(
|
|
3351
|
-
maxOutputChars: Schema.natural().min(1).default(3e4)
|
|
5114
|
+
idleTtlSec: Schema.natural().min(1).default(REMOTE_PTY_IDLE_TTL_SEC)
|
|
3352
5115
|
}).default({
|
|
3353
5116
|
execTimeoutSec: 120,
|
|
3354
|
-
idleTtlSec:
|
|
3355
|
-
maxOutputChars: 3e4
|
|
5117
|
+
idleTtlSec: REMOTE_PTY_IDLE_TTL_SEC
|
|
3356
5118
|
});
|
|
3357
5119
|
/** MUST stay an arrow(RM0 plugin.ts 同注:function 声明会被 cordis 当构造器 new 掉,返回的 disposer 丢失)。 */
|
|
3358
5120
|
const apply = (ctx, config) => {
|
|
@@ -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, disclose, hubPtyAssets, inject, localFileEndpoint, name, readUtf8Tail, runFileWorker, runRsync, sshArgv, startBinaryProcess, startOneShot, startRemoteJob };
|