super-dsh 0.3.2 → 0.3.3-c

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.
Files changed (61) hide show
  1. package/README.md +15 -14
  2. package/agent-agy/dist/agent.d.ts +4 -1
  3. package/agent-agy/dist/agent.js +15 -1
  4. package/agent-agy/dist/index.js +5 -8
  5. package/agent-agy/package.json +6 -6
  6. package/agent-agy-sdk/dist/agent.d.ts +4 -1
  7. package/agent-agy-sdk/dist/agent.js +15 -1
  8. package/agent-agy-sdk/dist/index.js +5 -8
  9. package/agent-agy-sdk/package.json +5 -5
  10. package/agent-claude/dist/agent.js +15 -1
  11. package/agent-claude/package.json +8 -8
  12. package/agent-codex/dist/agent.js +15 -1
  13. package/agent-codex/package.json +7 -7
  14. package/agent-codex-sdk/dist/agent.js +15 -1
  15. package/agent-codex-sdk/dist/index.js +5 -11
  16. package/agent-codex-sdk/package.json +7 -7
  17. package/agent-hermes/dist/agent.js +15 -1
  18. package/agent-hermes/dist/index.js +5 -8
  19. package/agent-hermes/package.json +7 -7
  20. package/agent-omp/dist/agent.js +26 -2
  21. package/agent-omp/package.json +8 -8
  22. package/agent-omp-sdk/dist/agent.d.ts +4 -1
  23. package/agent-omp-sdk/dist/agent.js +15 -1
  24. package/agent-omp-sdk/package.json +8 -8
  25. package/agent-pi/dist/agent.js +20 -2
  26. package/agent-pi/dist/index.js +5 -11
  27. package/agent-pi/package.json +7 -7
  28. package/client/index.js +106 -249
  29. package/cordis.patch.yml +0 -6
  30. package/package.json +22 -27
  31. package/remote/hub-pty-pump.mjs +97 -0
  32. package/remote/plugin.d.ts +476 -200
  33. package/remote/plugin.js +1448 -667
  34. package/remote/provenance.json +22 -17
  35. package/superd-hub/dist/agent-model-face.d.ts +93 -0
  36. package/superd-hub/dist/agent-model-face.js +113 -0
  37. package/superd-hub/dist/exec.d.ts +3 -2
  38. package/superd-hub/dist/exec.js +6 -5
  39. package/superd-hub/dist/fusion-transport.js +0 -1
  40. package/superd-hub/dist/hub-tool.d.ts +1 -1
  41. package/superd-hub/dist/hub-tool.js +6 -6
  42. package/superd-hub/dist/index.d.ts +1 -0
  43. package/superd-hub/dist/index.js +1 -0
  44. package/superd-hub/dist/remote-provider.js +70 -36
  45. package/superd-hub/dist/world-entry.js +30 -0
  46. package/superd-hub/lib/client/index.js +106 -249
  47. package/superd-hub/package.json +14 -10
  48. package/superd-hub/dist/bundle-setup.d.ts +0 -27
  49. package/superd-hub/dist/bundle-setup.js +0 -94
  50. package/superd-hub/dist/client/companion-api.d.ts +0 -5
  51. package/superd-hub/dist/client/companion-api.js +0 -30
  52. package/superd-hub/dist/companion-contract.d.ts +0 -9
  53. package/superd-hub/dist/companion-contract.js +0 -1
  54. package/superd-hub/dist/companions.d.ts +0 -30
  55. package/superd-hub/dist/companions.js +0 -211
  56. package/superd-hub/dist/exec-pty-channel.d.ts +0 -58
  57. package/superd-hub/dist/exec-pty-channel.js +0 -162
  58. package/superd-hub/dist/exec-pty-framing.d.ts +0 -34
  59. package/superd-hub/dist/exec-pty-framing.js +0 -89
  60. package/superd-hub/dist/exec-pty-session.d.ts +0 -78
  61. package/superd-hub/dist/exec-pty-session.js +0 -228
@@ -1,211 +0,0 @@
1
- /** Companion intent and the single native installation operation. */
2
- import { createHash } from 'node:crypto';
3
- import { readFile, mkdir, unlink, rmdir } from 'node:fs/promises';
4
- import { join, dirname } from 'node:path';
5
- import { writeFileAtomic } from '@deepseek-ai/dsh-atomic-write';
6
- // done marks a CONFIRMED first use (Better observed installed); removed marks a
7
- // migrated legacy removal record. A receipt with attempted but neither done,
8
- // error, nor removed is an interrupted first use — e.g. killed by the restart
9
- // that installing Super itself triggers — and must re-arm, not suppress, the retry.
10
- const message = (error) => error instanceof Error ? error.message : String(error);
11
- async function optionalJson(path) {
12
- try {
13
- return JSON.parse(await readFile(path, 'utf8'));
14
- }
15
- catch (error) {
16
- if (error.code === 'ENOENT')
17
- return undefined;
18
- throw error;
19
- }
20
- }
21
- function nativeFailure(result) {
22
- if ((result.application === 'applied' || result.application === 'restart-required') && result.error === undefined
23
- && (result.packageResult === undefined || result.packageResult.exitCode === 0))
24
- return undefined;
25
- return [result.application, result.error?.code, result.error?.diagnostic,
26
- result.packageResult?.kind, result.packageResult?.logPath].filter(Boolean).join(': ');
27
- }
28
- /** One controller per native profile; no package, registry, HMR or selection writer of its own. */
29
- export class BetterDashCompanion {
30
- version;
31
- manager;
32
- directory;
33
- receipt;
34
- legacy;
35
- initialized;
36
- intent = { attempted: false };
37
- active;
38
- stopped = false;
39
- restartNotice;
40
- constructor(profile, version, manager) {
41
- this.version = version;
42
- this.manager = manager;
43
- const key = createHash('sha256').update(profile.dir).digest('hex') + '.json';
44
- this.directory = join(profile.home, 'superd', 'companions');
45
- this.receipt = join(this.directory, key);
46
- this.legacy = join(profile.home, 'companion-registration', key);
47
- }
48
- initialize() {
49
- return this.initialized ??= (async () => {
50
- const saved = await optionalJson(this.receipt);
51
- if (saved !== undefined) {
52
- // Never-resurrect applies to a CONFIRMED first use, a recorded failure,
53
- // or a migrated removal record; an interrupted first use (no done, no
54
- // error, no removal marker) re-arms.
55
- this.intent = saved.attempted && saved.done !== true && saved.error === undefined && saved.removed !== true
56
- ? { attempted: false } : saved;
57
- await this.cleanLegacy();
58
- return;
59
- }
60
- const old = await optionalJson(this.legacy);
61
- // Any old registration was first use. An absent Better now means removal,
62
- // including when Super has since changed version; never resurrect it.
63
- if (old?.['super-dsh:better-dsh'] !== undefined) {
64
- this.intent = { attempted: true, removed: true };
65
- await this.save();
66
- await this.cleanLegacy();
67
- }
68
- })();
69
- }
70
- async cleanLegacy() {
71
- try {
72
- await unlink(this.legacy);
73
- }
74
- catch (error) {
75
- if (error.code !== 'ENOENT')
76
- throw error;
77
- }
78
- try {
79
- await rmdir(dirname(this.legacy));
80
- }
81
- catch (error) {
82
- if (!['ENOENT', 'ENOTEMPTY'].includes(error.code ?? ''))
83
- throw error;
84
- }
85
- }
86
- async save() {
87
- await mkdir(this.directory, { recursive: true, mode: 0o700 });
88
- await writeFileAtomic(this.receipt, JSON.stringify(this.intent) + '\n', { mode: 0o600 });
89
- }
90
- async getBetterDash() {
91
- const status = { installed: false, installing: this.active !== undefined, requestedVersion: this.version };
92
- try {
93
- await this.initialize();
94
- const manager = this.manager();
95
- if (manager === undefined)
96
- throw new Error('Native Plugin Manager is unavailable; enable it and retry Install in Settings.');
97
- const better = (await manager.listBundles()).find(bundle => bundle.name === 'better-dsh' && bundle.installed);
98
- if (better !== undefined) {
99
- status.installed = true;
100
- if (better.version !== undefined)
101
- status.version = better.version;
102
- status.enabled = better.enabled;
103
- // An installed dependency alone does not prove application succeeded:
104
- // native configure can fail after writing that dependency. Only a
105
- // missing -> installed recovery clears a previous failure here.
106
- if (this.active === undefined && this.intent.attempted
107
- && (this.intent.done !== true || (this.intent.error !== undefined && this.intent.missingAfterFailure === true))) {
108
- this.intent.done = true;
109
- delete this.intent.error;
110
- delete this.intent.missingAfterFailure;
111
- await this.save();
112
- }
113
- }
114
- else {
115
- this.restartNotice = undefined;
116
- if (this.active === undefined && this.intent.error !== undefined && this.intent.missingAfterFailure !== true) {
117
- this.intent.missingAfterFailure = true;
118
- await this.save();
119
- }
120
- }
121
- const error = this.intent.error ?? this.restartNotice;
122
- if (error !== undefined)
123
- status.error = error;
124
- }
125
- catch (error) {
126
- status.error = message(error);
127
- }
128
- return status;
129
- }
130
- ensureAutomatic() { return this.run(false); }
131
- installBetterDash() { return this.run(true); }
132
- run(manual) {
133
- if (this.active !== undefined)
134
- return this.active;
135
- const task = this.install(manual).catch(async (error) => {
136
- this.intent.error = `Better Dash installation failed: ${message(error)}. Check Better Dash in Plugin Manager; if missing, retry Install in Settings.`;
137
- const status = await this.getBetterDash();
138
- this.intent.missingAfterFailure = !status.installed;
139
- try {
140
- await this.save();
141
- }
142
- catch { /* Report the operation error even when persistence is unavailable. */ }
143
- return status;
144
- }).then(status => ({ ...status, installing: false })).finally(() => { this.active = undefined; });
145
- this.active = task;
146
- return task;
147
- }
148
- async install(manual) {
149
- await this.initialize();
150
- const before = await this.getBetterDash();
151
- if (this.stopped)
152
- return before;
153
- if (before.installed) {
154
- this.intent.attempted = true;
155
- this.intent.done = true;
156
- if (this.intent.missingAfterFailure === true) {
157
- delete this.intent.error;
158
- delete this.intent.missingAfterFailure;
159
- }
160
- await this.save();
161
- return this.getBetterDash(); // Native disablement and installed versions belong to the user.
162
- }
163
- // Native changed notifications enter through this operation, so its
164
- // read is active and deliberately cannot update the receipt itself.
165
- // Record removal here even when first-use installation is already done.
166
- if (this.intent.error !== undefined && this.intent.missingAfterFailure !== true) {
167
- this.intent.missingAfterFailure = true;
168
- await this.save();
169
- }
170
- if (!manual && this.intent.attempted)
171
- return before;
172
- this.intent = { attempted: true };
173
- await this.save(); // First use is durable before native HMR can unload this row.
174
- const manager = this.manager();
175
- if (manager === undefined)
176
- throw new Error('Native Plugin Manager is unavailable');
177
- if (this.version === 'unknown' || this.version.trim() === '')
178
- throw new Error('The installed Super Dash package version could not be read');
179
- const failures = [];
180
- for (const spec of [`better-dsh@${this.version}`, 'better-dsh@latest', 'better-dsh']) {
181
- if (this.stopped)
182
- break;
183
- try {
184
- const result = await manager.installBundle(spec);
185
- const failure = nativeFailure(result);
186
- if (failure === undefined) {
187
- const after = await this.getBetterDash();
188
- if (after.installed) {
189
- this.intent.done = true;
190
- delete this.intent.error;
191
- delete this.intent.missingAfterFailure;
192
- this.restartNotice = result.application === 'restart-required'
193
- ? 'Better Dash is installed; restart DSH to apply the native change.' : undefined;
194
- await this.save();
195
- return this.getBetterDash();
196
- }
197
- failures.push(`${spec}: native manager reported ${result.application}, but Better Dash is not installed`);
198
- }
199
- else
200
- failures.push(`${spec}: ${failure}`);
201
- }
202
- catch (error) {
203
- failures.push(`${spec}: ${message(error)}`);
204
- }
205
- }
206
- throw new Error(failures.join('; ') || 'Super Dash companion component was unloaded');
207
- }
208
- /** Read-only observation: an intermediate native event must never trigger reinstatement. */
209
- async observeNativeChange() { return this.getBetterDash(); }
210
- dispose() { this.stopped = true; }
211
- }
@@ -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
- }