super-dsh 0.3.1 → 0.3.2-d
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/index.js +135 -14
- package/package.json +1 -1
- package/remote/helper-bin/MANIFEST.json +35 -0
- package/remote/helper-bin/aarch64-apple-darwin/BUILT-VER +1 -0
- package/remote/helper-bin/aarch64-apple-darwin/superd-run +0 -0
- package/remote/helper-bin/aarch64-unknown-linux-musl/BUILT-VER +1 -0
- package/remote/helper-bin/aarch64-unknown-linux-musl/superd-run +0 -0
- package/remote/helper-bin/x86_64-pc-windows-gnu/BUILT-VER +1 -0
- package/remote/helper-bin/x86_64-pc-windows-gnu/superd-run.exe +0 -0
- package/remote/helper-bin/x86_64-unknown-linux-musl/BUILT-VER +1 -0
- package/remote/helper-bin/x86_64-unknown-linux-musl/superd-run +0 -0
- package/remote/hub-pty-pump.mjs +97 -0
- package/remote/plugin.d.ts +519 -197
- package/remote/plugin.js +2516 -754
- package/remote/provenance.json +36 -21
- package/superd-hub/dist/a2a-host.d.ts +11 -3
- package/superd-hub/dist/a2a-host.js +7 -7
- package/superd-hub/dist/a2a-row.js +7 -1
- package/superd-hub/dist/carrier.d.ts +9 -7
- package/superd-hub/dist/carrier.js +3 -3
- package/superd-hub/dist/client/pill-geometry.d.ts +70 -0
- package/superd-hub/dist/client/pill-geometry.js +49 -0
- package/superd-hub/dist/client/switch.d.ts +15 -0
- package/superd-hub/dist/client/switch.js +54 -1
- package/superd-hub/dist/companions.js +8 -6
- package/superd-hub/dist/fusion-transport.d.ts +18 -1
- package/superd-hub/dist/fusion-transport.js +44 -5
- package/superd-hub/dist/gateway.js +8 -1
- package/superd-hub/dist/hub-route.d.ts +5 -2
- package/superd-hub/dist/hub-route.js +6 -6
- package/superd-hub/dist/hub-tool.d.ts +1 -1
- package/superd-hub/dist/hub-tool.js +1 -1
- package/superd-hub/dist/remote-provider.js +70 -36
- package/superd-hub/dist/rpc.d.ts +5 -0
- package/superd-hub/dist/rpc.js +20 -1
- package/superd-hub/dist/switch-core.d.ts +41 -0
- package/superd-hub/dist/switch-core.js +40 -0
- package/superd-hub/dist/targets.d.ts +7 -0
- package/superd-hub/dist/world-lifecycle.js +1 -1
- package/superd-hub/lib/client/index.js +135 -14
- package/superd-hub/dist/exec-pty-channel.d.ts +0 -58
- package/superd-hub/dist/exec-pty-channel.js +0 -162
- package/superd-hub/dist/exec-pty-framing.d.ts +0 -34
- package/superd-hub/dist/exec-pty-framing.js +0 -89
- package/superd-hub/dist/exec-pty-session.d.ts +0 -78
- package/superd-hub/dist/exec-pty-session.js +0 -228
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
/** The transport seam the ported PtySession drives (spec §8.2: {write, onData, kill}). */
|
|
2
|
-
export interface PtyChannel {
|
|
3
|
-
/** Open the transport; resolves when bytes can flow (session readiness itself = the init nonce frame). */
|
|
4
|
-
open(onData: (chunk: string) => void): Promise<void>;
|
|
5
|
-
write(s: string): void;
|
|
6
|
-
/** Polite close (dispose path: 'exit\n' already sent by the session). */
|
|
7
|
-
close(): void;
|
|
8
|
-
/** Hard kill: the transport AND any process group behind it (Ruling 8 fallback). */
|
|
9
|
-
kill(): void;
|
|
10
|
-
/** Register for unexpected transport death (socket cut / process exit). */
|
|
11
|
-
onDead(callback: () => void): void;
|
|
12
|
-
/** Diagnostics tail (transport stderr / socket errors) for init-failure messages. */
|
|
13
|
-
readonly diag: string;
|
|
14
|
-
}
|
|
15
|
-
/** Local target: `script -qfec bash /dev/null` — host-side PTY, no node-pty (spec §8.2 / D12). */
|
|
16
|
-
export declare class LocalScriptChannel implements PtyChannel {
|
|
17
|
-
private readonly argv;
|
|
18
|
-
diag: string;
|
|
19
|
-
private proc;
|
|
20
|
-
private deadCb;
|
|
21
|
-
constructor(argv?: string[]);
|
|
22
|
-
open(onData: (chunk: string) => void): Promise<void>;
|
|
23
|
-
write(s: string): void;
|
|
24
|
-
close(): void;
|
|
25
|
-
kill(): void;
|
|
26
|
-
onDead(callback: () => void): void;
|
|
27
|
-
}
|
|
28
|
-
/** Structural view of the `ws` client socket (runtime peer — mesh-gateway precedent). */
|
|
29
|
-
interface WsSocketLike {
|
|
30
|
-
send(data: unknown): void;
|
|
31
|
-
terminate(): void;
|
|
32
|
-
close(): void;
|
|
33
|
-
on(event: 'open', listener: () => void): unknown;
|
|
34
|
-
on(event: 'error', listener: (error: unknown) => void): unknown;
|
|
35
|
-
on(event: 'message', listener: (data: unknown) => void): unknown;
|
|
36
|
-
on(event: 'close', listener: () => void): unknown;
|
|
37
|
-
}
|
|
38
|
-
type WsConstructorLike = new (url: string, options: {
|
|
39
|
-
headers: Record<string, string>;
|
|
40
|
-
}) => WsSocketLike;
|
|
41
|
-
/** Remote target: a WebSocket to the peer hub's dumb PTY executor, pairing Cookie riding the upgrade. */
|
|
42
|
-
export declare class WsPtyChannel implements PtyChannel {
|
|
43
|
-
private readonly url;
|
|
44
|
-
private readonly headers;
|
|
45
|
-
private readonly wsCtor;
|
|
46
|
-
diag: string;
|
|
47
|
-
private socket;
|
|
48
|
-
private deadCb;
|
|
49
|
-
private readonly pending;
|
|
50
|
-
private opened;
|
|
51
|
-
constructor(url: string, headers?: Record<string, string>, wsCtor?: WsConstructorLike | undefined);
|
|
52
|
-
open(onData: (chunk: string) => void): Promise<void>;
|
|
53
|
-
write(s: string): void;
|
|
54
|
-
close(): void;
|
|
55
|
-
kill(): void;
|
|
56
|
-
onDead(callback: () => void): void;
|
|
57
|
-
}
|
|
58
|
-
export {};
|
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
// PTY channels — the ONE seam spec §8.2 carves out of better-dsh's
|
|
2
|
-
// PtySession: the session machinery (nonce injection, framing, two-stage
|
|
3
|
-
// interrupt, idle TTL) is transport-agnostic; only {open, write, kill} differ
|
|
4
|
-
// between "a local `script -qfec` subprocess" (this machine as target) and
|
|
5
|
-
// "a WebSocket to the peer's dumb PTY executor" (a paired machine as target).
|
|
6
|
-
//
|
|
7
|
-
// The WS client follows mesh-gateway's crash-proofing lesson: an 'error'
|
|
8
|
-
// listener is ALWAYS registered (ECONNREFUSED / a rejected 401 upgrade would
|
|
9
|
-
// otherwise be an uncaught exception), and sends before 'open' queue in
|
|
10
|
-
// order while post-close sends are swallowed (the session's death path owns
|
|
11
|
-
// the teardown).
|
|
12
|
-
import { spawn } from 'node:child_process';
|
|
13
|
-
import { createRequire } from 'node:module';
|
|
14
|
-
/** Local target: `script -qfec bash /dev/null` — host-side PTY, no node-pty (spec §8.2 / D12). */
|
|
15
|
-
export class LocalScriptChannel {
|
|
16
|
-
argv;
|
|
17
|
-
diag = '';
|
|
18
|
-
proc = null;
|
|
19
|
-
deadCb;
|
|
20
|
-
constructor(argv = ['script', '-qfec', 'bash', '/dev/null']) {
|
|
21
|
-
this.argv = argv;
|
|
22
|
-
}
|
|
23
|
-
async open(onData) {
|
|
24
|
-
const proc = spawn(this.argv[0], this.argv.slice(1), { stdio: ['pipe', 'pipe', 'pipe'], detached: true });
|
|
25
|
-
this.proc = proc;
|
|
26
|
-
proc.stdout.setEncoding('utf8');
|
|
27
|
-
proc.stdout.on('data', (d) => onData(d));
|
|
28
|
-
proc.stderr.setEncoding('utf8').on('data', (d) => { this.diag = (this.diag + d).slice(-2_000); });
|
|
29
|
-
proc.once('close', () => this.deadCb?.());
|
|
30
|
-
proc.once('error', (err) => { this.diag = (this.diag + `\n[pty: spawn failed: ${err.message}]`).slice(-2_000); this.deadCb?.(); });
|
|
31
|
-
}
|
|
32
|
-
write(s) {
|
|
33
|
-
if (this.proc?.stdin?.writable !== true)
|
|
34
|
-
return;
|
|
35
|
-
try {
|
|
36
|
-
this.proc.stdin.write(s);
|
|
37
|
-
}
|
|
38
|
-
catch { /* dead: the death callback settles the session */ }
|
|
39
|
-
}
|
|
40
|
-
close() {
|
|
41
|
-
this.write('exit\n');
|
|
42
|
-
const pid = this.proc?.pid;
|
|
43
|
-
this.proc = null;
|
|
44
|
-
if (pid === undefined)
|
|
45
|
-
return;
|
|
46
|
-
setTimeout(() => { try {
|
|
47
|
-
process.kill(-pid, 'SIGKILL');
|
|
48
|
-
}
|
|
49
|
-
catch { /* already gone */ } }, 1_000).unref();
|
|
50
|
-
}
|
|
51
|
-
kill() {
|
|
52
|
-
const pid = this.proc?.pid;
|
|
53
|
-
this.proc = null;
|
|
54
|
-
if (pid === undefined)
|
|
55
|
-
return;
|
|
56
|
-
try {
|
|
57
|
-
process.kill(-pid, 'SIGTERM');
|
|
58
|
-
}
|
|
59
|
-
catch { /* already gone */ }
|
|
60
|
-
setTimeout(() => { try {
|
|
61
|
-
process.kill(-pid, 'SIGKILL');
|
|
62
|
-
}
|
|
63
|
-
catch { /* already gone */ } }, 2_000).unref();
|
|
64
|
-
}
|
|
65
|
-
onDead(callback) { this.deadCb = callback; }
|
|
66
|
-
}
|
|
67
|
-
const WS_MODULE = 'ws';
|
|
68
|
-
let wsConstructor;
|
|
69
|
-
function loadWs() {
|
|
70
|
-
if (wsConstructor !== undefined)
|
|
71
|
-
return wsConstructor;
|
|
72
|
-
const require = createRequire(import.meta.url);
|
|
73
|
-
const mod = require(WS_MODULE);
|
|
74
|
-
const boxed = mod;
|
|
75
|
-
wsConstructor = (typeof mod === 'function' ? mod : boxed.default);
|
|
76
|
-
return wsConstructor;
|
|
77
|
-
}
|
|
78
|
-
/** Remote target: a WebSocket to the peer hub's dumb PTY executor, pairing Cookie riding the upgrade. */
|
|
79
|
-
export class WsPtyChannel {
|
|
80
|
-
url;
|
|
81
|
-
headers;
|
|
82
|
-
wsCtor;
|
|
83
|
-
diag = '';
|
|
84
|
-
socket = null;
|
|
85
|
-
deadCb;
|
|
86
|
-
pending = [];
|
|
87
|
-
opened = false;
|
|
88
|
-
constructor(url, headers = {}, wsCtor = undefined) {
|
|
89
|
-
this.url = url;
|
|
90
|
-
this.headers = headers;
|
|
91
|
-
this.wsCtor = wsCtor;
|
|
92
|
-
}
|
|
93
|
-
open(onData) {
|
|
94
|
-
return new Promise((resolve, reject) => {
|
|
95
|
-
let settled = false;
|
|
96
|
-
let socket;
|
|
97
|
-
try {
|
|
98
|
-
socket = new (this.wsCtor ?? loadWs())(this.url, { headers: this.headers });
|
|
99
|
-
}
|
|
100
|
-
catch (err) {
|
|
101
|
-
reject(err instanceof Error ? err : new Error(String(err)));
|
|
102
|
-
return;
|
|
103
|
-
}
|
|
104
|
-
this.socket = socket;
|
|
105
|
-
// crash-proof by construction (mesh-gateway fix-round-1 lesson): 'error'
|
|
106
|
-
// ALWAYS has a listener; 'close' is guaranteed to follow and the dead
|
|
107
|
-
// path owns the teardown.
|
|
108
|
-
socket.on('error', (err) => { this.diag = (this.diag + `\n[pty-ws: ${err instanceof Error ? err.message : String(err)}]`).slice(-2_000); });
|
|
109
|
-
socket.on('open', () => {
|
|
110
|
-
if (settled)
|
|
111
|
-
return;
|
|
112
|
-
settled = true;
|
|
113
|
-
this.opened = true;
|
|
114
|
-
for (const chunk of this.pending.splice(0))
|
|
115
|
-
socket.send(chunk);
|
|
116
|
-
resolve();
|
|
117
|
-
});
|
|
118
|
-
socket.on('message', (data) => {
|
|
119
|
-
const text = typeof data === 'string'
|
|
120
|
-
? data
|
|
121
|
-
: Array.isArray(data)
|
|
122
|
-
? Buffer.concat(data).toString('utf8')
|
|
123
|
-
: Buffer.from(data).toString('utf8');
|
|
124
|
-
onData(text);
|
|
125
|
-
});
|
|
126
|
-
socket.on('close', () => {
|
|
127
|
-
if (!settled) {
|
|
128
|
-
settled = true;
|
|
129
|
-
reject(new Error(`pty-ws: socket closed before opening${this.diag !== '' ? `; ${this.diag}` : ''}`));
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
this.opened = false;
|
|
133
|
-
this.deadCb?.();
|
|
134
|
-
});
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
write(s) {
|
|
138
|
-
if (this.socket === null)
|
|
139
|
-
return;
|
|
140
|
-
if (!this.opened) {
|
|
141
|
-
this.pending.push(s);
|
|
142
|
-
return;
|
|
143
|
-
}
|
|
144
|
-
try {
|
|
145
|
-
this.socket.send(s);
|
|
146
|
-
}
|
|
147
|
-
catch { /* dead: the close path settles the session */ }
|
|
148
|
-
}
|
|
149
|
-
close() {
|
|
150
|
-
try {
|
|
151
|
-
this.socket?.close();
|
|
152
|
-
}
|
|
153
|
-
catch { /* already closing */ }
|
|
154
|
-
}
|
|
155
|
-
kill() {
|
|
156
|
-
try {
|
|
157
|
-
this.socket?.terminate();
|
|
158
|
-
}
|
|
159
|
-
catch { /* already gone */ }
|
|
160
|
-
}
|
|
161
|
-
onDead(callback) { this.deadCb = callback; }
|
|
162
|
-
}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import type { OutputStats } from '../../remote/plugin.js';
|
|
2
|
-
/** 收帧帧体:退出码 + 只读回传的 cwd(Non-Goal ②:报告不重建)。 */
|
|
3
|
-
export interface PtyFrame {
|
|
4
|
-
exit: number;
|
|
5
|
-
cwd: string | null;
|
|
6
|
-
}
|
|
7
|
-
/** 8 字节随机串的 hex 形(spec §五.2:每次下发前生成)。 */
|
|
8
|
-
export declare function genNonce(bytes?: number): string;
|
|
9
|
-
/** 命令整行:花括号复合体 + Nonce 收帧尾(spec §五.2 的 printf 逐字落地 + cwd 第三字段)。 */
|
|
10
|
-
export declare function wrapPtyCommand(cmd: string, nonce: string): string;
|
|
11
|
-
/** init 整行:哑终端(echo/PS1/PS2/TERM)+ 固定 40×120(Non-Goal ③)+ INIT 帧。 */
|
|
12
|
-
export declare function buildInitCommand(nonce: string): string;
|
|
13
|
-
export declare function stripAnsi(s: string): string;
|
|
14
|
-
export declare function normalizePtyText(s: string): string;
|
|
15
|
-
export declare function tailWindow(text: string, cap: number, stats?: OutputStats): {
|
|
16
|
-
text: string;
|
|
17
|
-
truncated?: number;
|
|
18
|
-
stats?: OutputStats;
|
|
19
|
-
};
|
|
20
|
-
export interface FrameParserEvents {
|
|
21
|
-
/** 输出文本:feed 路径经 normalize(剥 ANSI/规整换行);flush 路径为**裸放出**(残余字节原样,勿假设已剥洗)。 */
|
|
22
|
-
onOutput?(text: string): void;
|
|
23
|
-
onFrame(frame: PtyFrame): void;
|
|
24
|
-
}
|
|
25
|
-
export interface NonceFrameParser {
|
|
26
|
-
feed(chunk: string): void;
|
|
27
|
-
flush(): void;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* 单 nonce、单帧解析器:一轮 dispatch 一个实例。只认 `\x1b]133;D;<nonce>;`,
|
|
31
|
-
* 错误 nonce 的静态/伪造 marker 永不匹配,按普通输出流过(再经 ANSI 剥洗)。
|
|
32
|
-
* 缓冲尾若可能是 marker 前缀则扣留,flush() 时作为输出放出。
|
|
33
|
-
*/
|
|
34
|
-
export declare function createNonceFrameParser(nonce: string, events: FrameParserEvents): NonceFrameParser;
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
// PTY nonce framing — PORTED VERBATIM from better-dsh src/remote/nonce-framing.ts
|
|
2
|
-
// (spec §8.2 / D12 "原样照抄"; only the import specifiers were adapted to this
|
|
3
|
-
// package's ESM convention). Command wrap = brace compound + OSC-133;D nonce
|
|
4
|
-
// tail carrying exit + cwd; parser holds back possible marker prefixes and
|
|
5
|
-
// flushes leftovers raw.
|
|
6
|
-
import { randomBytes } from 'node:crypto';
|
|
7
|
-
/** 8 字节随机串的 hex 形(spec §五.2:每次下发前生成)。 */
|
|
8
|
-
export function genNonce(bytes = 8) {
|
|
9
|
-
return randomBytes(bytes).toString('hex');
|
|
10
|
-
}
|
|
11
|
-
/** 命令整行:花括号复合体 + Nonce 收帧尾(spec §五.2 的 printf 逐字落地 + cwd 第三字段)。 */
|
|
12
|
-
export function wrapPtyCommand(cmd, nonce) {
|
|
13
|
-
return `{\n${cmd}\n} ; printf '\\033]133;D;${nonce};%s;%s\\007' "$?" "$PWD"\n`;
|
|
14
|
-
}
|
|
15
|
-
/** init 整行:哑终端(echo/PS1/PS2/TERM)+ 固定 40×120(Non-Goal ③)+ INIT 帧。 */
|
|
16
|
-
export function buildInitCommand(nonce) {
|
|
17
|
-
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`;
|
|
18
|
-
}
|
|
19
|
-
const ANSI_RE = /\x1b(?:\][^\x07\x1b]*(?:\x07|\x1b\\)?|\[[0-9;?]*[ -/]*[@-~]|[@-Z\\-_])/g;
|
|
20
|
-
export function stripAnsi(s) {
|
|
21
|
-
return s.replace(ANSI_RE, '');
|
|
22
|
-
}
|
|
23
|
-
export function normalizePtyText(s) {
|
|
24
|
-
return stripAnsi(s).replace(/\r\n/g, '\n').replace(/\r/g, '');
|
|
25
|
-
}
|
|
26
|
-
export function tailWindow(text, cap, stats) {
|
|
27
|
-
let tail = text.slice(-cap);
|
|
28
|
-
if (tail.charCodeAt(0) >= 0xdc00 && tail.charCodeAt(0) <= 0xdfff)
|
|
29
|
-
tail = tail.slice(1);
|
|
30
|
-
const returned = stats?.unit === 'bytes' ? Buffer.byteLength(tail) : tail.length;
|
|
31
|
-
const total = stats?.total ?? text.length;
|
|
32
|
-
const updated = stats === undefined ? {} : { stats: { ...stats, returned } };
|
|
33
|
-
if (total <= returned)
|
|
34
|
-
return { text: tail, ...updated };
|
|
35
|
-
const unit = stats?.unit === 'bytes' ? 'bytes' : 'chars';
|
|
36
|
-
const eviction = stats !== undefined && stats.dropped > 0 ? `; retained ${stats.retained}, dropped head ${stats.dropped}, retention limit ${stats.retentionLimit} ${stats.unit === 'bytes' ? 'bytes' : 'UTF-16 code units'}` : '';
|
|
37
|
-
return { text: `[truncated: showing last ${returned} of ${total} ${unit}${eviction}]\n${tail}`, truncated: total, ...updated };
|
|
38
|
-
}
|
|
39
|
-
const FRAME_BODY_RE = /^(\d+);([^\x07\x1b]*)(?:\x07|\x1b\\)/; // cwd 是尾字段:合法路径可含 `;`,只有 BEL/ESC 终止它
|
|
40
|
-
/**
|
|
41
|
-
* 单 nonce、单帧解析器:一轮 dispatch 一个实例。只认 `\x1b]133;D;<nonce>;`,
|
|
42
|
-
* 错误 nonce 的静态/伪造 marker 永不匹配,按普通输出流过(再经 ANSI 剥洗)。
|
|
43
|
-
* 缓冲尾若可能是 marker 前缀则扣留,flush() 时作为输出放出。
|
|
44
|
-
*/
|
|
45
|
-
export function createNonceFrameParser(nonce, events) {
|
|
46
|
-
const prefix = `\x1b]133;D;${nonce};`;
|
|
47
|
-
let buf = '';
|
|
48
|
-
let done = false;
|
|
49
|
-
const emit = (raw) => {
|
|
50
|
-
const text = normalizePtyText(raw);
|
|
51
|
-
if (text.length > 0)
|
|
52
|
-
events.onOutput?.(text);
|
|
53
|
-
};
|
|
54
|
-
const holdback = () => {
|
|
55
|
-
const max = Math.min(buf.length, prefix.length - 1);
|
|
56
|
-
for (let k = max; k > 0; k--)
|
|
57
|
-
if (buf.endsWith(prefix.slice(0, k)))
|
|
58
|
-
return k;
|
|
59
|
-
return 0;
|
|
60
|
-
};
|
|
61
|
-
const consume = () => {
|
|
62
|
-
if (done)
|
|
63
|
-
return;
|
|
64
|
-
const i = buf.indexOf(prefix);
|
|
65
|
-
if (i < 0) {
|
|
66
|
-
const keep = holdback();
|
|
67
|
-
emit(buf.slice(0, buf.length - keep));
|
|
68
|
-
buf = buf.slice(buf.length - keep);
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
|
-
emit(buf.slice(0, i));
|
|
72
|
-
const rest = buf.slice(i + prefix.length);
|
|
73
|
-
const m = FRAME_BODY_RE.exec(rest);
|
|
74
|
-
if (m === null) {
|
|
75
|
-
buf = buf.slice(i);
|
|
76
|
-
return;
|
|
77
|
-
} // 帧体未到齐,整段扣留
|
|
78
|
-
events.onFrame({ exit: Number(m[1]), cwd: m[2].length > 0 ? m[2] : null });
|
|
79
|
-
done = true; // 帧后字节一律丢弃(下一轮是新解析器)
|
|
80
|
-
buf = '';
|
|
81
|
-
};
|
|
82
|
-
return {
|
|
83
|
-
feed(chunk) { buf += chunk; consume(); },
|
|
84
|
-
// 流结束 = 裸放出扣留的残余(含未完成的 marker 前缀):不经过 ANSI 剥洗——
|
|
85
|
-
// stripAnsi 会把未闭合 OSC 整段吃掉,扣留字节就此蒸发,违背 flush 语义。
|
|
86
|
-
flush() { if (buf.length > 0)
|
|
87
|
-
events.onOutput?.(buf); buf = ''; },
|
|
88
|
-
};
|
|
89
|
-
}
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
import { type StreamOutputStats } from '../../remote/plugin.js';
|
|
2
|
-
import type { PtyChannel } from './exec-pty-channel.js';
|
|
3
|
-
/** spec §五.2 逐字。 */
|
|
4
|
-
export declare const RECONNECT_NOTICE = "[remote: session reconnected to fresh shell; cwd reset to default]";
|
|
5
|
-
export interface PtySessionOptions {
|
|
6
|
-
key: string;
|
|
7
|
-
channel: PtyChannel;
|
|
8
|
-
idleTtlSec: number;
|
|
9
|
-
initTimeoutSec?: number;
|
|
10
|
-
/** 池回调:会话彻底出池(dispose)时触发;进程意外死亡不出池(Ruling 7)。 */
|
|
11
|
-
onDead?: () => void;
|
|
12
|
-
}
|
|
13
|
-
export interface PtyDispatchOptions {
|
|
14
|
-
stdin?: string;
|
|
15
|
-
timeoutSec?: number;
|
|
16
|
-
}
|
|
17
|
-
export interface PtyDispatchResult {
|
|
18
|
-
output: string;
|
|
19
|
-
outputStats?: StreamOutputStats;
|
|
20
|
-
exit: number | null;
|
|
21
|
-
cwd: string | null;
|
|
22
|
-
timedOut: boolean;
|
|
23
|
-
reconnected: boolean;
|
|
24
|
-
durationMs: number;
|
|
25
|
-
}
|
|
26
|
-
export type PtyState = 'cold' | 'starting' | 'ready' | 'dead' | 'disposed';
|
|
27
|
-
/** 会话运行时快照(status 面消费,Ruling 16 词汇源)。 */
|
|
28
|
-
export interface SessionSnapshot {
|
|
29
|
-
state: PtyState;
|
|
30
|
-
busy: boolean;
|
|
31
|
-
idleMs: number | null;
|
|
32
|
-
}
|
|
33
|
-
export declare class PtySession {
|
|
34
|
-
private readonly opts;
|
|
35
|
-
private state;
|
|
36
|
-
private startPromise;
|
|
37
|
-
private queue;
|
|
38
|
-
private idleTimer;
|
|
39
|
-
private onChunk;
|
|
40
|
-
private deathWaiters;
|
|
41
|
-
private inFlight;
|
|
42
|
-
private lastSettleAt;
|
|
43
|
-
constructor(opts: PtySessionOptions);
|
|
44
|
-
get sessionState(): PtyState;
|
|
45
|
-
/** status 面快照:state + busy(有命令在跑)+ idleMs(上次 settle 至今)。 */
|
|
46
|
-
get snapshot(): SessionSnapshot;
|
|
47
|
-
/** 同一会话命令严格串行(FIFO);死亡/冷态先重启。 */
|
|
48
|
-
dispatch(cmd: string, dOpts?: PtyDispatchOptions): Promise<PtyDispatchResult>;
|
|
49
|
-
/** TTL / row teardown:尽力 exit,1s 后杀组,出池。 */
|
|
50
|
-
dispose(): Promise<void>;
|
|
51
|
-
private write;
|
|
52
|
-
private start;
|
|
53
|
-
private doStart;
|
|
54
|
-
private diag;
|
|
55
|
-
private markDead;
|
|
56
|
-
private resetIdleTimer;
|
|
57
|
-
private clearIdleTimer;
|
|
58
|
-
}
|
|
59
|
-
export interface PtyPoolDefaults {
|
|
60
|
-
idleTtlSec: number;
|
|
61
|
-
initTimeoutSec?: number;
|
|
62
|
-
}
|
|
63
|
-
/** 会话池:键 → 会话。意外死亡的会话留在池内(下次 dispatch 带 reconnect 提示)。 */
|
|
64
|
-
export declare class PtyPool {
|
|
65
|
-
private readonly defaults;
|
|
66
|
-
private readonly sessions;
|
|
67
|
-
constructor(defaults: PtyPoolDefaults);
|
|
68
|
-
get size(): number;
|
|
69
|
-
/** status 面:键上的会话快照(无会话 = undefined → "none — dials on first exec")。 */
|
|
70
|
-
inspect(key: string): SessionSnapshot | undefined;
|
|
71
|
-
/** roster 面:池内全部会话。 */
|
|
72
|
-
list(): Array<{
|
|
73
|
-
key: string;
|
|
74
|
-
snapshot: SessionSnapshot;
|
|
75
|
-
}>;
|
|
76
|
-
getOrCreate(key: string, channelOf: () => PtyChannel): PtySession;
|
|
77
|
-
disposeAll(): Promise<void>;
|
|
78
|
-
}
|
|
@@ -1,228 +0,0 @@
|
|
|
1
|
-
import { Utf16TailRing } from '../../remote/plugin.js';
|
|
2
|
-
// PTY session machinery — PORTED from better-dsh src/remote/pty-session.ts
|
|
3
|
-
// (spec §8.2 / D12 "原样照抄"), with the ONE sanctioned adaptation: the
|
|
4
|
-
// subprocess spawn is replaced by the PtyChannel seam (exec-pty-channel.ts) —
|
|
5
|
-
// every state transition (init nonce handshake, FIFO dispatch, P8 two-stage
|
|
6
|
-
// interrupt \x03 + injected 130-marker, 3s grace, group-kill fallback, idle
|
|
7
|
-
// TTL, OUTPUT_HARD_CAP with surrogate-pair-safe slicing, I1 waiter hygiene)
|
|
8
|
-
// is the ported logic, unchanged.
|
|
9
|
-
import { buildInitCommand, createNonceFrameParser, genNonce, wrapPtyCommand } from './exec-pty-framing.js';
|
|
10
|
-
/** spec §五.2 逐字。 */
|
|
11
|
-
export const RECONNECT_NOTICE = '[remote: session reconnected to fresh shell; cwd reset to default]';
|
|
12
|
-
const DEFAULT_INIT_TIMEOUT_SEC = 30;
|
|
13
|
-
const INTERRUPT_GRACE_MS = 3_000;
|
|
14
|
-
/** pty 收集内存安全帽(Ruling P15,与 oneshot HARD_CAP 对齐):模型面只见尾窗,保留尾部。 */
|
|
15
|
-
const OUTPUT_HARD_CAP = 4_000_000;
|
|
16
|
-
export class PtySession {
|
|
17
|
-
opts;
|
|
18
|
-
state = 'cold';
|
|
19
|
-
startPromise = null;
|
|
20
|
-
queue = Promise.resolve();
|
|
21
|
-
idleTimer = null;
|
|
22
|
-
onChunk = null;
|
|
23
|
-
deathWaiters = [];
|
|
24
|
-
inFlight = 0;
|
|
25
|
-
lastSettleAt = 0;
|
|
26
|
-
constructor(opts) {
|
|
27
|
-
this.opts = opts;
|
|
28
|
-
this.opts.channel.onDead(() => this.markDead());
|
|
29
|
-
}
|
|
30
|
-
get sessionState() { return this.state; }
|
|
31
|
-
/** status 面快照:state + busy(有命令在跑)+ idleMs(上次 settle 至今)。 */
|
|
32
|
-
get snapshot() {
|
|
33
|
-
return { state: this.state, busy: this.inFlight > 0, idleMs: this.lastSettleAt > 0 ? Date.now() - this.lastSettleAt : null };
|
|
34
|
-
}
|
|
35
|
-
/** 同一会话命令严格串行(FIFO);死亡/冷态先重启。 */
|
|
36
|
-
dispatch(cmd, dOpts = {}) {
|
|
37
|
-
const attempt = async () => {
|
|
38
|
-
const started = Date.now();
|
|
39
|
-
const reconnected = this.state === 'dead';
|
|
40
|
-
if (this.state !== 'ready')
|
|
41
|
-
await this.start();
|
|
42
|
-
this.inFlight++;
|
|
43
|
-
return await new Promise((resolve) => {
|
|
44
|
-
const nonce = genNonce();
|
|
45
|
-
const ring = new Utf16TailRing(OUTPUT_HARD_CAP);
|
|
46
|
-
let interrupted = false;
|
|
47
|
-
let settled = false;
|
|
48
|
-
let interruptTimer;
|
|
49
|
-
let killTimer;
|
|
50
|
-
const deathWaiter = () => finish({ output: ring.text, exit: null, cwd: null, timedOut: interrupted });
|
|
51
|
-
const cleanup = () => {
|
|
52
|
-
this.onChunk = null;
|
|
53
|
-
// I1(终审):已结算 dispatch 的死亡等待必须摘除——否则闭包钉住整段 output,
|
|
54
|
-
// 长命会话每调用累积一个 waiter(init 路径的 filter 同款形态)
|
|
55
|
-
this.deathWaiters = this.deathWaiters.filter((w) => w !== deathWaiter);
|
|
56
|
-
if (interruptTimer !== undefined)
|
|
57
|
-
clearTimeout(interruptTimer);
|
|
58
|
-
if (killTimer !== undefined)
|
|
59
|
-
clearTimeout(killTimer);
|
|
60
|
-
};
|
|
61
|
-
const finish = (r) => {
|
|
62
|
-
if (settled)
|
|
63
|
-
return;
|
|
64
|
-
settled = true;
|
|
65
|
-
cleanup();
|
|
66
|
-
this.inFlight--;
|
|
67
|
-
this.lastSettleAt = Date.now();
|
|
68
|
-
this.resetIdleTimer();
|
|
69
|
-
resolve({ ...r, outputStats: { stdout: ring.stats() }, reconnected, durationMs: Date.now() - started });
|
|
70
|
-
};
|
|
71
|
-
const parser = createNonceFrameParser(nonce, {
|
|
72
|
-
onOutput: (t) => {
|
|
73
|
-
ring.push(t);
|
|
74
|
-
},
|
|
75
|
-
onFrame: ({ exit, cwd }) => finish({ output: ring.text, exit, cwd, timedOut: interrupted }),
|
|
76
|
-
});
|
|
77
|
-
this.onChunk = (c) => parser.feed(c);
|
|
78
|
-
this.write(wrapPtyCommand(cmd, nonce));
|
|
79
|
-
if (dOpts.stdin !== undefined)
|
|
80
|
-
this.write(dOpts.stdin); // Ruling 11: REPL 式紧随
|
|
81
|
-
interruptTimer = setTimeout(() => {
|
|
82
|
-
interrupted = true;
|
|
83
|
-
// P8 两段打断:\x03 中断前台作业后,交互 bash 会放弃当前命令行的剩余部分
|
|
84
|
-
// (尾部 marker 不再执行);紧随注入的同 nonce 130-marker 行在 bash 回到
|
|
85
|
-
// 读取态后被执行。无论 bash 弃行还是续行,帧都在宽限内到达且 exit=130,
|
|
86
|
-
// 会话存活;若命令 trap 掉 SIGINT,原 marker 先帧、注入行帧后字节被丢弃。
|
|
87
|
-
this.write('\x03');
|
|
88
|
-
this.write(`printf '\\033]133;D;${nonce};130;%s\\007' "$PWD"\n`);
|
|
89
|
-
killTimer = setTimeout(() => {
|
|
90
|
-
// Ruling 8 的 kill 兜底:宽限无帧 = 会话不可恢复,杀整组后收尸
|
|
91
|
-
// (否则 trap-INT 的卡死进程永生,重连后旧组再不可达)
|
|
92
|
-
this.opts.channel.kill();
|
|
93
|
-
this.markDead();
|
|
94
|
-
finish({ output: ring.text, exit: null, cwd: null, timedOut: true });
|
|
95
|
-
}, INTERRUPT_GRACE_MS);
|
|
96
|
-
}, dOpts.timeoutSec === undefined ? 120_000 : dOpts.timeoutSec * 1_000);
|
|
97
|
-
this.deathWaiters.push(deathWaiter);
|
|
98
|
-
});
|
|
99
|
-
};
|
|
100
|
-
const run = this.queue.then(attempt, attempt);
|
|
101
|
-
this.queue = run.then(() => undefined, () => undefined);
|
|
102
|
-
return run;
|
|
103
|
-
}
|
|
104
|
-
/** TTL / row teardown:尽力 exit,1s 后杀组,出池。 */
|
|
105
|
-
async dispose() {
|
|
106
|
-
if (this.state === 'disposed')
|
|
107
|
-
return;
|
|
108
|
-
this.clearIdleTimer();
|
|
109
|
-
this.state = 'disposed';
|
|
110
|
-
this.startPromise = null;
|
|
111
|
-
this.opts.channel.close();
|
|
112
|
-
this.opts.onDead?.();
|
|
113
|
-
}
|
|
114
|
-
write(s) {
|
|
115
|
-
this.opts.channel.write(s);
|
|
116
|
-
}
|
|
117
|
-
async start() {
|
|
118
|
-
if (this.state === 'disposed')
|
|
119
|
-
throw new Error(`[E_SESSION_DISPOSED] remote pty session '${this.opts.key}' was disposed — the pool replaces disposed sessions; this reference is stale`);
|
|
120
|
-
if (this.startPromise === null) {
|
|
121
|
-
this.state = 'starting';
|
|
122
|
-
this.startPromise = this.doStart().catch((err) => {
|
|
123
|
-
this.startPromise = null;
|
|
124
|
-
this.markDead();
|
|
125
|
-
throw err;
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
|
-
return this.startPromise;
|
|
129
|
-
}
|
|
130
|
-
async doStart() {
|
|
131
|
-
const initTimeoutSec = this.opts.initTimeoutSec ?? DEFAULT_INIT_TIMEOUT_SEC;
|
|
132
|
-
const initNonce = genNonce();
|
|
133
|
-
await new Promise((resolve, reject) => {
|
|
134
|
-
const timer = setTimeout(() => {
|
|
135
|
-
this.opts.channel.kill();
|
|
136
|
-
reject(new Error(`[E_SESSION_START] remote pty session '${this.opts.key}' did not initialize in ${initTimeoutSec}s` +
|
|
137
|
-
(this.diag().length > 0 ? `; transport stderr tail: ${this.diag()}` : '')));
|
|
138
|
-
}, initTimeoutSec * 1_000);
|
|
139
|
-
const waiter = () => {
|
|
140
|
-
clearTimeout(timer);
|
|
141
|
-
reject(new Error(`[E_SESSION_DIED] remote pty session '${this.opts.key}' died before initializing` +
|
|
142
|
-
(this.diag().length > 0 ? `; transport stderr tail: ${this.diag()}` : '')));
|
|
143
|
-
};
|
|
144
|
-
this.deathWaiters.push(waiter);
|
|
145
|
-
const parser = createNonceFrameParser(initNonce, {
|
|
146
|
-
onFrame: () => {
|
|
147
|
-
clearTimeout(timer);
|
|
148
|
-
this.deathWaiters = this.deathWaiters.filter((w) => w !== waiter);
|
|
149
|
-
if (this.state === 'disposed') {
|
|
150
|
-
// dispose 竞态 init:不得复活已终态会话(否则重挂 idle timer + 幽灵 ready)
|
|
151
|
-
reject(new Error(`[E_SESSION_DISPOSED] remote pty session '${this.opts.key}' disposed during init`));
|
|
152
|
-
return;
|
|
153
|
-
}
|
|
154
|
-
this.state = 'ready';
|
|
155
|
-
this.resetIdleTimer();
|
|
156
|
-
resolve();
|
|
157
|
-
},
|
|
158
|
-
});
|
|
159
|
-
this.onChunk = (c) => parser.feed(c);
|
|
160
|
-
this.opts.channel.open((chunk) => this.onChunk?.(chunk))
|
|
161
|
-
.catch((err) => {
|
|
162
|
-
clearTimeout(timer);
|
|
163
|
-
this.deathWaiters = this.deathWaiters.filter((w) => w !== waiter);
|
|
164
|
-
reject(err instanceof Error ? err : new Error(String(err)));
|
|
165
|
-
});
|
|
166
|
-
this.write(buildInitCommand(initNonce));
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
diag() { return this.opts.channel.diag; }
|
|
170
|
-
markDead() {
|
|
171
|
-
if (this.state === 'disposed') {
|
|
172
|
-
// dispose 是终态:不再翻转 state,但在飞 dispatch 的死亡等待仍需立即结算
|
|
173
|
-
// (row teardown 不是超时——不得等 123s 看门狗,也不得错标 timedOut)
|
|
174
|
-
const waiters = this.deathWaiters;
|
|
175
|
-
this.deathWaiters = [];
|
|
176
|
-
for (const w of waiters)
|
|
177
|
-
w();
|
|
178
|
-
return;
|
|
179
|
-
}
|
|
180
|
-
this.state = 'dead';
|
|
181
|
-
this.startPromise = null;
|
|
182
|
-
this.clearIdleTimer();
|
|
183
|
-
const waiters = this.deathWaiters;
|
|
184
|
-
this.deathWaiters = [];
|
|
185
|
-
for (const w of waiters)
|
|
186
|
-
w();
|
|
187
|
-
}
|
|
188
|
-
resetIdleTimer() {
|
|
189
|
-
this.clearIdleTimer();
|
|
190
|
-
this.idleTimer = setTimeout(() => void this.dispose(), this.opts.idleTtlSec * 1_000);
|
|
191
|
-
this.idleTimer.unref();
|
|
192
|
-
}
|
|
193
|
-
clearIdleTimer() {
|
|
194
|
-
if (this.idleTimer !== null) {
|
|
195
|
-
clearTimeout(this.idleTimer);
|
|
196
|
-
this.idleTimer = null;
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
/** 会话池:键 → 会话。意外死亡的会话留在池内(下次 dispatch 带 reconnect 提示)。 */
|
|
201
|
-
export class PtyPool {
|
|
202
|
-
defaults;
|
|
203
|
-
sessions = new Map();
|
|
204
|
-
constructor(defaults) {
|
|
205
|
-
this.defaults = defaults;
|
|
206
|
-
}
|
|
207
|
-
get size() { return this.sessions.size; }
|
|
208
|
-
/** status 面:键上的会话快照(无会话 = undefined → "none — dials on first exec")。 */
|
|
209
|
-
inspect(key) {
|
|
210
|
-
return this.sessions.get(key)?.snapshot;
|
|
211
|
-
}
|
|
212
|
-
/** roster 面:池内全部会话。 */
|
|
213
|
-
list() {
|
|
214
|
-
return [...this.sessions.entries()].map(([key, s]) => ({ key, snapshot: s.snapshot }));
|
|
215
|
-
}
|
|
216
|
-
getOrCreate(key, channelOf) {
|
|
217
|
-
let s = this.sessions.get(key);
|
|
218
|
-
if (s === undefined || s.sessionState === 'disposed') {
|
|
219
|
-
s = new PtySession({ key, channel: channelOf(), ...this.defaults, onDead: () => this.sessions.delete(key) });
|
|
220
|
-
this.sessions.set(key, s);
|
|
221
|
-
}
|
|
222
|
-
return s;
|
|
223
|
-
}
|
|
224
|
-
async disposeAll() {
|
|
225
|
-
await Promise.all([...this.sessions.values()].map((s) => s.dispose()));
|
|
226
|
-
this.sessions.clear();
|
|
227
|
-
}
|
|
228
|
-
}
|