@xiaoqiong0v0/opencode-ssh-tool 0.6.12 → 0.6.15
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 +4 -1
- package/dist/agent.d.ts +2 -2
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +80 -21
- package/dist/agent.js.map +1 -1
- package/dist/base-session.d.ts +138 -25
- package/dist/base-session.d.ts.map +1 -1
- package/dist/base-session.js +485 -181
- package/dist/base-session.js.map +1 -1
- package/dist/constants.d.ts +41 -1
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +42 -1
- package/dist/constants.js.map +1 -1
- package/dist/i18n.d.ts +16 -0
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +13 -0
- package/dist/i18n.js.map +1 -1
- package/dist/local-session.d.ts.map +1 -1
- package/dist/local-session.js +2 -0
- package/dist/local-session.js.map +1 -1
- package/dist/server-entry.js +25 -15
- package/dist/server-entry.js.map +1 -1
- package/dist/server.d.ts +6 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +235 -21
- package/dist/server.js.map +1 -1
- package/dist/session-store.d.ts +35 -0
- package/dist/session-store.d.ts.map +1 -1
- package/dist/session-store.js +98 -3
- package/dist/session-store.js.map +1 -1
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +2 -0
- package/dist/session.js.map +1 -1
- package/dist/shell-adapter.d.ts +13 -4
- package/dist/shell-adapter.d.ts.map +1 -1
- package/dist/shell-adapter.js +23 -17
- package/dist/shell-adapter.js.map +1 -1
- package/dist/utils.d.ts +55 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +248 -27
- package/dist/utils.js.map +1 -1
- package/dist/web/app.css +4 -0
- package/dist/web/app.js +10 -10
- package/dist/web/index.html +1 -0
- package/package.json +1 -1
package/dist/base-session.js
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
// 统一完成标记法:注入 PROMPT_COMMAND 脚本,命令完成时输出 <SSH_DONE:退出码>
|
|
3
3
|
// 子类仅需实现:连接建立(connect)、数据写入(_write)、传输层清理(_closeTransport)、状态字段(getStatus)
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
|
-
import { ANIMATION_WINDOW_MS, MAX_OUTPUT_LEN, RAW_LOG_MAX, DONE_TAG, SYNTAX_QUIET_MS, SYNTAX_MAX_WAIT_MS, INTERRUPT_PROBE_INTERVAL_DEFAULT_SEC, } from "./constants.js";
|
|
6
|
-
import log, { debug, describeSend, tailLines, tailSummary } from "./log.js";
|
|
5
|
+
import { ANIMATION_WINDOW_MS, MAX_OUTPUT_LEN, RAW_LOG_MAX, DONE_TAG, SYNTAX_QUIET_MS, SYNTAX_MAX_WAIT_MS, FALLBACK_WATCH_INTERVAL_MS, INTERRUPT_PROBE_INTERVAL_DEFAULT_SEC, } from "./constants.js";
|
|
6
|
+
import log, { debug, describeSend, infoDedup, isDebugEnabled, tailLines, tailSummary } from "./log.js";
|
|
7
7
|
import { decodeTerminalEscapes } from "./escapes.js";
|
|
8
8
|
import { SessionHistory } from "./history.js";
|
|
9
|
-
import { toModelText, extractOutputStart, stripTrailingPromptLine } from "./utils.js";
|
|
9
|
+
import { toModelText, extractOutputStart, stripTrailingPromptLine, removeProbeEchoLines, ECHO_REGEX_MAX_CMD_CHARS, echoRegexSourceLength } from "./utils.js";
|
|
10
10
|
import { detectLastDoneMarker, stripMarkers, detectInterrupt, detectSyntaxError, adapters } from "./shell-adapter.js";
|
|
11
11
|
import { tr } from "./i18n.js";
|
|
12
12
|
/** buffer 最大长度(未消费输出超限时截断头部,防内存膨胀) */
|
|
@@ -63,6 +63,50 @@ function stripCommandTail(command) {
|
|
|
63
63
|
s = s.replace(/(?:&&|\|\||[;&|])[\s]*$/, "");
|
|
64
64
|
return (head + s).trimEnd();
|
|
65
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* 诊断辅助:转义控制字符,使日志单行可读(\r\n\t 转义、ESC 写成 \x1b)。
|
|
68
|
+
* 仅供日志打印使用,不参与任何控制流。
|
|
69
|
+
* @param s 原始字符串
|
|
70
|
+
* @returns 控制字符已转义的字符串
|
|
71
|
+
*/
|
|
72
|
+
function escapeCtl(s) {
|
|
73
|
+
return s.replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\x1b/g, "\\x1b");
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* 扫描文本中所有完成标记(`<SSH_DONE:nonce:seq:code>` / `<SSH_DONE:seq:code>` / `<SSH_DONE:code>`)。
|
|
77
|
+
* 宽松解析(不要求退出码为纯数字):既覆盖求值式标记,也覆盖**命令行回显**里的标记片段
|
|
78
|
+
* (重放内容中常见 `<SSH_DONE:2:$LASTEXITCODE>` 这种未求值的回显)。
|
|
79
|
+
* 用途:① 诊断日志(窗口内混入的标记来自哪条命令);② 定位失败时按标记边界裁剪窗口。
|
|
80
|
+
* @param s 待扫描文本
|
|
81
|
+
* @returns 命中列表(按出现顺序)
|
|
82
|
+
*/
|
|
83
|
+
function scanDoneMarkers(s) {
|
|
84
|
+
const out = [];
|
|
85
|
+
let from = 0;
|
|
86
|
+
for (;;) {
|
|
87
|
+
const i = s.indexOf(DONE_TAG, from);
|
|
88
|
+
if (i < 0)
|
|
89
|
+
break;
|
|
90
|
+
const gt = s.indexOf(">", i + DONE_TAG.length);
|
|
91
|
+
if (gt < 0)
|
|
92
|
+
break; // 未闭合:后续不再可能有完整标记
|
|
93
|
+
const segs = s.slice(i + DONE_TAG.length, gt).split(":");
|
|
94
|
+
let nonce = "";
|
|
95
|
+
let seq = null;
|
|
96
|
+
if (segs.length >= 3) {
|
|
97
|
+
nonce = segs[0];
|
|
98
|
+
const n = Number.parseInt(segs[1], 10);
|
|
99
|
+
seq = Number.isNaN(n) ? null : n;
|
|
100
|
+
}
|
|
101
|
+
else if (segs.length === 2) {
|
|
102
|
+
const n = Number.parseInt(segs[0], 10);
|
|
103
|
+
seq = Number.isNaN(n) ? null : n;
|
|
104
|
+
}
|
|
105
|
+
out.push({ pos: i, end: gt + 1, nonce, seq });
|
|
106
|
+
from = gt + 1;
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
66
110
|
/** 会话命令执行与读取的公共实现 */
|
|
67
111
|
export class BaseSession {
|
|
68
112
|
sessionID;
|
|
@@ -71,21 +115,41 @@ export class BaseSession {
|
|
|
71
115
|
_interruptProbeIntervalMs;
|
|
72
116
|
_connected = false;
|
|
73
117
|
_remoteBusy = false;
|
|
74
|
-
/**
|
|
75
|
-
* 是否保持 busy:排队命令顺序执行时,中间某条完成也不清 busy,
|
|
76
|
-
* 直到序列最后一条完成(否则 web/status 会在中间命令间隙闪 busy=false)。
|
|
77
|
-
*/
|
|
78
|
-
_holdBusy = false;
|
|
79
118
|
_buffer = "";
|
|
80
119
|
_connectedAt = 0;
|
|
81
120
|
_lastActive = 0;
|
|
82
121
|
_runningStartPos = null;
|
|
83
122
|
_runningCommand = "";
|
|
84
123
|
_watchTimer = null;
|
|
85
|
-
/**
|
|
124
|
+
/** 后台兜底判定的捕获窗口起点(相对 buffer;submit 为 0,exec 转后台为 captureStart) */
|
|
125
|
+
_watchStartPos = 0;
|
|
126
|
+
/** 后台兜底判定写入 history 用的命令(独立保存,避免运行上下文清理后取不到) */
|
|
127
|
+
_watchCommand = "";
|
|
128
|
+
/** 语法错误安静窗口的一次性定时器(数据到达时重置;到点即收尾,非轮询) */
|
|
129
|
+
_syntaxTimer = null;
|
|
130
|
+
/** 语法错误首次识别时刻(0=尚未识别) */
|
|
131
|
+
_syntaxSeenAt = 0;
|
|
132
|
+
/** 语法错误静默判定起点(识别后输出最后一次变化的时刻) */
|
|
133
|
+
_syntaxQuietAt = 0;
|
|
134
|
+
/** 语法错误识别后观测到的输出长度(判断输出是否仍在变化) */
|
|
135
|
+
_syntaxLen = 0;
|
|
136
|
+
/** exec 同步等待完成的一次性 animation 定时器(到点未完成 → 兑现 "running" 转后台) */
|
|
137
|
+
_animationTimer = null;
|
|
138
|
+
/** exec 同步等待完成的 resolver(数据到达/语法静默命中时由 _settleCompletion 兑现) */
|
|
139
|
+
_completionWaiter = null;
|
|
140
|
+
/** exec 转后台后等待 busy 释放的 resolver 列表(busy 翻转为 false 时统一兑现,替代 200ms 轮询) */
|
|
141
|
+
_busyWaiters = [];
|
|
142
|
+
/** 命令序号(完成标记 <SSH_DONE:nonce:seq:code> 标识本次命令,防残留误判) */
|
|
86
143
|
_cmdSeq = 0;
|
|
87
144
|
/** 当前命令序号(_beginCapture 递增,供检测/拼接用) */
|
|
88
145
|
_runningSeq = 0;
|
|
146
|
+
/**
|
|
147
|
+
* 会话级随机短串(8 位十六进制,构造时生成):写进完成标记 `<SSH_DONE:<nonce>:<seq>:<code>>`。
|
|
148
|
+
* 远端 Windows 控制台在新连接时会重放上一会话屏幕缓冲,其中含**别的会话**的完成标记;
|
|
149
|
+
* 新会话 seq 必然从 1 起、与重放会话撞号 → 无 nonce 时会把重放标记当自己的完成/边界。
|
|
150
|
+
* 只认自己 nonce:重放标记不再冒充本会话标记。
|
|
151
|
+
*/
|
|
152
|
+
_nonce = randomUUID().replace(/-/g, "").slice(0, 8);
|
|
89
153
|
/**
|
|
90
154
|
* 命令发起前缓冲的末行(旧提示符行):语法错误收尾时 shell 会重印同形提示符,
|
|
91
155
|
* 据此把它从输出尾部剥掉(exec 的输出窗口自命令回显起,旧提示符在窗口之外,需单独记录)。
|
|
@@ -116,6 +180,8 @@ export class BaseSession {
|
|
|
116
180
|
generation = randomUUID();
|
|
117
181
|
/** 生命周期监听器(命令开始/完成事件,agent 转报 server) */
|
|
118
182
|
_lifecycle = null;
|
|
183
|
+
/** 数据到达监听器(终端有新输出写入缓冲时回调,供 agent 事件驱动推流;null 清除) */
|
|
184
|
+
_dataListener = null;
|
|
119
185
|
/**
|
|
120
186
|
* busy 状态翻转监听器(插件挂接):命令运行期间收到 true、结束写回 false,
|
|
121
187
|
* 供插件把实时 busy 同步到跨进程状态文件,避免命令执行前落盘的旧值一直"过期"。
|
|
@@ -164,8 +230,9 @@ export class BaseSession {
|
|
|
164
230
|
if (this._adapter?.hasOpenContinuation(command))
|
|
165
231
|
return { ok: false, output: "", error: tr("cmd_continuation", this._lang) };
|
|
166
232
|
this._beginCapture(command);
|
|
233
|
+
this._armTracking(0, command);
|
|
167
234
|
this._write(this._composeCommand(command));
|
|
168
|
-
this.
|
|
235
|
+
this._startFallbackWatch();
|
|
169
236
|
return { ok: true, output: "", submitted: true, command, duration: 0, ...this._extraResult };
|
|
170
237
|
}
|
|
171
238
|
/**
|
|
@@ -178,18 +245,25 @@ export class BaseSession {
|
|
|
178
245
|
if (!this._ready())
|
|
179
246
|
return { ok: false, output: "", error: tr("err_not_connected", this._lang) };
|
|
180
247
|
if (this._remoteBusy) {
|
|
181
|
-
log.info(`exec quick-fail busy ${this._logTag}
|
|
248
|
+
log.info(`exec quick-fail busy ${this._logTag} cmdLen=${command.length} (busy=${this._remoteBusy})`);
|
|
249
|
+
debug(`exec quick-fail busy ${this._logTag} cmd=${tailLines(command, 3)}`);
|
|
182
250
|
return { ok: false, output: "", error: tr("cmd_busy", this._lang) };
|
|
183
251
|
}
|
|
184
252
|
if (this._adapter?.hasOpenContinuation(command)) {
|
|
185
|
-
log.info(`exec quick-fail open continuation ${this._logTag}
|
|
253
|
+
log.info(`exec quick-fail open continuation ${this._logTag} cmdLen=${command.length}`);
|
|
254
|
+
debug(`exec quick-fail open continuation ${this._logTag} cmd=${tailLines(command, 3)}`);
|
|
186
255
|
return { ok: false, output: "", error: tr("cmd_continuation", this._lang) };
|
|
187
256
|
}
|
|
188
257
|
this._beginCapture(command);
|
|
189
258
|
const captureStart = this._buffer.length;
|
|
259
|
+
this._armTracking(captureStart, command);
|
|
260
|
+
// 先挂同步等待者再写入:写命令可能同步回灌数据(本地 PTY 快速回显),事件驱动的 _settleCompletion
|
|
261
|
+
// 需要等待者已就位;否则完成会被判成后台收尾、exec 空等
|
|
262
|
+
const completion = this._awaitCompletion();
|
|
190
263
|
this._write(this._composeCommand(command));
|
|
191
|
-
const outcome = await
|
|
192
|
-
|
|
264
|
+
const outcome = await completion;
|
|
265
|
+
debug(`exec ${this._logTag} seq=${this._runningSeq} cmdLen=${command.length} -> ${outcome.kind}${outcome.kind === "running" ? "" : " markerPos=" + outcome.markerPos + " exitCode=" + outcome.exitCode + " duration=" + (Date.now() - startTs) + "ms"} (busy=${this._remoteBusy})`);
|
|
266
|
+
debug(`exec ${this._logTag} seq=${this._runningSeq} cmd=${tailLines(command, 3)}`);
|
|
193
267
|
switch (outcome.kind) {
|
|
194
268
|
case "done": {
|
|
195
269
|
// 同步完成:复用 _completeRunning 统一收尾(history/done/busy/[run] 结束日志/清上下文/停 watch),
|
|
@@ -203,16 +277,10 @@ export class BaseSession {
|
|
|
203
277
|
this._runningStartPos = 0;
|
|
204
278
|
this._setBusy(true, "cmdRunning");
|
|
205
279
|
this._cursor = this._buffer.length;
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
if (!this._remoteBusy) {
|
|
211
|
-
clearInterval(poll);
|
|
212
|
-
resolve();
|
|
213
|
-
}
|
|
214
|
-
}, 200);
|
|
215
|
-
});
|
|
280
|
+
// 转后台稀疏兜底监听(≥1s,仅覆盖断连等非数据事件);完成判定仍由数据到达事件驱动
|
|
281
|
+
this._startFallbackWatch();
|
|
282
|
+
// 等待命令收尾:事件驱动(busy 翻转为 false 时兑现),不再 200ms 轮询
|
|
283
|
+
await new Promise((resolve) => { this._busyWaiters.push(resolve); });
|
|
216
284
|
// watch 已写入 history,取最后一条记录的输出
|
|
217
285
|
const pairs = this._history.getPairs();
|
|
218
286
|
const last = pairs[pairs.length - 1];
|
|
@@ -230,7 +298,7 @@ export class BaseSession {
|
|
|
230
298
|
return { ok: false, output: "", error: tr("err_not_connected", this._lang) };
|
|
231
299
|
let out;
|
|
232
300
|
if (this._runningStartPos !== null && this._runningCommand) {
|
|
233
|
-
const marker = detectLastDoneMarker(this._buffer, this._runningStartPos, this._runningSeq);
|
|
301
|
+
const marker = detectLastDoneMarker(this._buffer, this._runningStartPos, this._nonce, this._runningSeq);
|
|
234
302
|
if (marker.done) {
|
|
235
303
|
// 与后台 watch 完成路径复用同一收尾(history/done/busy/停 watch),避免 busy 卡死
|
|
236
304
|
const raw = this._completeRunning(this._runningStartPos, marker.pos, marker.exitCode, this._runningCommand, undefined, "readBuffer");
|
|
@@ -278,6 +346,11 @@ export class BaseSession {
|
|
|
278
346
|
return { ok: true };
|
|
279
347
|
}
|
|
280
348
|
getHistory() { return this._history; }
|
|
349
|
+
/**
|
|
350
|
+
* 本会话完成标记的随机串(只读):供诊断/测试按真实格式构造标记。
|
|
351
|
+
* @returns 8 位十六进制会话串
|
|
352
|
+
*/
|
|
353
|
+
get nonce() { return this._nonce; }
|
|
281
354
|
getRunningOutput() {
|
|
282
355
|
if (this._runningStartPos === null || !this._connected || !this._runningCommand)
|
|
283
356
|
return "";
|
|
@@ -293,6 +366,15 @@ export class BaseSession {
|
|
|
293
366
|
setLifecycle(listener) {
|
|
294
367
|
this._lifecycle = listener;
|
|
295
368
|
}
|
|
369
|
+
/**
|
|
370
|
+
* 设置数据到达监听器(每次终端有新输出写入缓冲时回调):
|
|
371
|
+
* SSH 的 `stream.on("data")` 与本地 PTY 的 data 回调最终都汇入 `_appendBuffer`,
|
|
372
|
+
* 在此统一触发,供 agent 做事件驱动的节流推流(不再依赖固定周期轮询)。
|
|
373
|
+
* @param listener 回调(null 表示清除)
|
|
374
|
+
*/
|
|
375
|
+
setDataListener(listener) {
|
|
376
|
+
this._dataListener = listener;
|
|
377
|
+
}
|
|
296
378
|
/**
|
|
297
379
|
* 设置 busy 状态翻转监听器(命令开始/结束/断连等每次 busy 翻转时回调):
|
|
298
380
|
* 供插件把最新 busy 同步到跨进程状态文件(server 拿不到 agent 状态回退读状态文件时,
|
|
@@ -302,32 +384,39 @@ export class BaseSession {
|
|
|
302
384
|
setBusyListener(listener) {
|
|
303
385
|
this._busyListener = listener;
|
|
304
386
|
}
|
|
305
|
-
/**
|
|
306
|
-
* 设置是否保持 busy(排队命令序列期间为 true):
|
|
307
|
-
* true 时中间命令完成不清 busy;置 false 时立即清 busy。
|
|
308
|
-
* @param hold 是否保持
|
|
309
|
-
*/
|
|
310
|
-
setHoldBusy(hold) {
|
|
311
|
-
this._holdBusy = hold;
|
|
312
|
-
if (!hold)
|
|
313
|
-
this._setBusy(false, "holdRelease");
|
|
314
|
-
}
|
|
315
387
|
/**
|
|
316
388
|
* 更新终端 busy 状态:仅在值翻转时记一行(会话/终端/当前 seq/翻转原因),
|
|
317
389
|
* 供事后对齐状态时间线(busy 每次翻转都能对应到具体原因,不再出现"忙了却查不出为何")。
|
|
318
390
|
* @param next 目标 busy 值
|
|
319
|
-
* @param reason 翻转原因(cmdStart / cmdRunning / cmdDone /
|
|
391
|
+
* @param reason 翻转原因(cmdStart / cmdRunning / cmdDone / 会话关闭 / 断连补 done 等)
|
|
392
|
+
* @param quiet true 时该行降为 debug:用于"释放"与紧随其后的收尾行(如 [run] 结束)重复的场景,
|
|
393
|
+
* 避免同一事件打两条 info(busy 时间线仍可由该收尾行还原)
|
|
320
394
|
*/
|
|
321
|
-
_setBusy(next, reason) {
|
|
395
|
+
_setBusy(next, reason, quiet = false) {
|
|
322
396
|
if (this._remoteBusy === next)
|
|
323
397
|
return;
|
|
324
398
|
this._remoteBusy = next;
|
|
325
|
-
|
|
399
|
+
const line = `[busy] ${this._logTag} seq=${this._runningSeq} busy=${next} reason=${reason}`;
|
|
400
|
+
if (quiet)
|
|
401
|
+
debug(line);
|
|
402
|
+
else
|
|
403
|
+
log.info(line);
|
|
326
404
|
// 通知插件同步状态文件(busy 已更新,getStatus 读到新值);监听器异常不打断执行
|
|
327
405
|
try {
|
|
328
406
|
this._busyListener?.(next, reason);
|
|
329
407
|
}
|
|
330
408
|
catch { /* 监听器异常不打断执行 */ }
|
|
409
|
+
// busy 释放:事件驱动地兑现 exec 转后台后的等待者(替代旧的 200ms busy=false 轮询)
|
|
410
|
+
if (!next && this._busyWaiters.length > 0) {
|
|
411
|
+
const waiters = this._busyWaiters;
|
|
412
|
+
this._busyWaiters = [];
|
|
413
|
+
for (const w of waiters) {
|
|
414
|
+
try {
|
|
415
|
+
w();
|
|
416
|
+
}
|
|
417
|
+
catch { /* 等待者异常不打断状态翻转 */ }
|
|
418
|
+
}
|
|
419
|
+
}
|
|
331
420
|
}
|
|
332
421
|
/** 触发命令开始事件 */
|
|
333
422
|
_emitStart(command, ts) {
|
|
@@ -357,9 +446,16 @@ export class BaseSession {
|
|
|
357
446
|
return { data: "", done: false };
|
|
358
447
|
}
|
|
359
448
|
// 完成标记先定位(marker 唯一 seq,从命令起点搜索,免疫 echoEnd 被后序回显带偏)
|
|
360
|
-
const marker = detectLastDoneMarker(this._buffer, this._runningStartPos, this._runningSeq);
|
|
449
|
+
const marker = detectLastDoneMarker(this._buffer, this._runningStartPos, this._nonce, this._runningSeq);
|
|
361
450
|
const markerEnd = marker.done ? marker.pos : this._buffer.length;
|
|
362
|
-
|
|
451
|
+
// 回显定位异常不得中断推流:按"未定位"处理(延续原有 end<=0 语义)
|
|
452
|
+
let end;
|
|
453
|
+
try {
|
|
454
|
+
end = extractOutputStart(this._buffer.slice(this._runningStartPos), this._composeEchoText(this._runningCommand), markerEnd - this._runningStartPos);
|
|
455
|
+
}
|
|
456
|
+
catch {
|
|
457
|
+
end = -1;
|
|
458
|
+
}
|
|
363
459
|
if (end <= 0)
|
|
364
460
|
return { data: "", done: false };
|
|
365
461
|
const echoEnd = this._runningStartPos + end;
|
|
@@ -369,10 +465,7 @@ export class BaseSession {
|
|
|
369
465
|
}
|
|
370
466
|
const raw = this._buffer.slice(this._streamPos, windowEnd);
|
|
371
467
|
this._streamPos = windowEnd;
|
|
372
|
-
|
|
373
|
-
if (this._adapter)
|
|
374
|
-
data = data.replace(this._markerCmd(this._runningSeq), "");
|
|
375
|
-
data = this._stripProbeEchoes(data);
|
|
468
|
+
const data = this._stripProbeEchoes(stripMarkers(raw));
|
|
376
469
|
return { data, done: marker.done };
|
|
377
470
|
}
|
|
378
471
|
/** 关闭终端,清理会话态(幂等) */
|
|
@@ -401,7 +494,7 @@ export class BaseSession {
|
|
|
401
494
|
* @returns 标记命令文本
|
|
402
495
|
*/
|
|
403
496
|
_markerCmd(seq) {
|
|
404
|
-
return this._adapter ? this._adapter.markerCmd(seq) : `printf '\\n${DONE_TAG}${seq}:%s>' $?`;
|
|
497
|
+
return this._adapter ? this._adapter.markerCmd(this._nonce, seq) : `printf '\\n${DONE_TAG}${this._nonce}:${seq}:%s>' $?`;
|
|
405
498
|
}
|
|
406
499
|
/**
|
|
407
500
|
* 组合实际写入 PTY 的命令:在规范形式(`_composeEchoText`)基础上把换行改写为行分隔符并补尾部回车。
|
|
@@ -510,22 +603,21 @@ export class BaseSession {
|
|
|
510
603
|
}
|
|
511
604
|
/**
|
|
512
605
|
* 从可见输出中剔除中断探针留下的痕迹(探针命令的回显)。
|
|
513
|
-
*
|
|
514
|
-
*
|
|
515
|
-
*
|
|
606
|
+
* 探针在用户中断时补发,其回显可能迟到落到后续命令的输出窗口里;这里对每个已记录探针 seq
|
|
607
|
+
* (以及当前命令自身的标记命令回显)做 **ANSI 容忍定位**:即便 pwsh 语法高亮在 token 间插入
|
|
608
|
+
* SGR、行首带提示符与 `\x1b[?25l`,也能命中并整段剔除(见 removeProbeEchoLines)。
|
|
609
|
+
* 三处调用点(本函数、_extractOutput 的 out.replace、getRunningStream 的 data.replace)
|
|
610
|
+
* 统一收敛至此,消除口径漂移。Raw 视图不经此函数,保留原始字节。
|
|
516
611
|
* @param text 可见输出文本
|
|
517
612
|
* @returns 剔除探针回显后的文本
|
|
518
613
|
*/
|
|
519
614
|
_stripProbeEchoes(text) {
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
out = out.split(echo).join("");
|
|
527
|
-
}
|
|
528
|
-
return out;
|
|
615
|
+
const needles = [];
|
|
616
|
+
for (const seq of this._probeSeqs)
|
|
617
|
+
needles.push(this._markerCmd(seq));
|
|
618
|
+
// 当前命令的标记命令回显:原 out.replace(_markerCmd(_runningSeq)) / data.replace(...) 两种口径并入此处
|
|
619
|
+
needles.push(this._markerCmd(this._runningSeq));
|
|
620
|
+
return removeProbeEchoLines(text, needles, this._promptRef);
|
|
529
621
|
}
|
|
530
622
|
/**
|
|
531
623
|
* 组合命令文本(规范/匹配用形式,始终以 `\n` 分隔行、无尾部回车):命令 + 完成标记。
|
|
@@ -572,19 +664,50 @@ export class BaseSession {
|
|
|
572
664
|
*/
|
|
573
665
|
_extractOutput(raw, command, syntaxMode = false) {
|
|
574
666
|
// 完成标记先定位:marker 自带唯一 seq,从窗口起点搜索即可(echoEnd 可能被连续输入的后序回显带偏)
|
|
575
|
-
const marker = detectLastDoneMarker(raw, 0, this._runningSeq);
|
|
667
|
+
const marker = detectLastDoneMarker(raw, 0, this._nonce, this._runningSeq);
|
|
576
668
|
const echoText = this._composeEchoText(command);
|
|
577
|
-
const
|
|
578
|
-
|
|
579
|
-
|
|
669
|
+
const echoLen = echoText.trim().length;
|
|
670
|
+
// 超长回显:extractOutputStart 会降级为"首/尾锚点"匹配(否则模式源约 265×长度,JSC 下会抛 too large)
|
|
671
|
+
if (echoLen > ECHO_REGEX_MAX_CMD_CHARS) {
|
|
672
|
+
debug(`[extract] ${this._logTag} seq=${this._runningSeq} 回显定位降级为首/尾锚点: echoLen=${echoLen} regexSrcLen=${echoRegexSourceLength(echoText)} (>阈值 ${ECHO_REGEX_MAX_CMD_CHARS})`);
|
|
673
|
+
}
|
|
674
|
+
let end;
|
|
675
|
+
try {
|
|
676
|
+
end = marker.done
|
|
677
|
+
? extractOutputStart(raw, echoText, marker.pos)
|
|
678
|
+
: extractOutputStart(raw, echoText, raw.length, syntaxMode);
|
|
679
|
+
}
|
|
680
|
+
catch (e) {
|
|
681
|
+
// 回显定位异常绝不上抛(否则会中断完成收尾):记一行后退回整窗输出
|
|
682
|
+
log.info(`[extract] ${this._logTag} seq=${this._runningSeq} 回显定位失败, 退回整窗: echoLen=${echoLen} err=${e instanceof Error ? e.message : String(e)}`);
|
|
683
|
+
end = -1;
|
|
684
|
+
}
|
|
685
|
+
// 诊断:输出窗口坐标 + 是否退回整窗(startPos=回显结束偏移,endPos=窗口末尾;窗口长=endPos-startPos)
|
|
686
|
+
const winStart = end <= 0 ? 0 : end;
|
|
687
|
+
const winEnd = marker.done ? marker.pos : raw.length;
|
|
688
|
+
debug(`[extract] ${this._logTag} seq=${this._runningSeq} 窗口: startPos=${winStart} endPos=${winEnd} 窗口长=${winEnd - winStart} markerSeq=${this._runningSeq} 是否退回整窗=${end <= 0 ? `是(定位失败, syntaxMode=${syntaxMode})` : "否"}`);
|
|
689
|
+
// 诊断:窗口前 120 字符(仅 SSH_TOOL_DEBUG=1 时落盘)
|
|
690
|
+
debug(`[extract] ${this._logTag} seq=${this._runningSeq} 窗口前120: ${escapeCtl(raw.slice(0, 120))}`);
|
|
580
691
|
if (end <= 0) {
|
|
581
|
-
//
|
|
582
|
-
//
|
|
583
|
-
|
|
692
|
+
// 未定位到命令回显(脏窗口含控制台屏幕重放/超宽命令折行重绘等):
|
|
693
|
+
// **不得退回整窗**——整窗会把重放的别会话命令行/标记当输出落盘(旧 bug:outLen=14019 全是杂物)。
|
|
694
|
+
// 改为按窗口内已有标记边界裁剪:取"本命令自己的标记之前、所有非本 seq 标记之后"的边界,
|
|
695
|
+
// 先把重放段整段切掉,再剥行首残余控制码噪音;定位仍失败也只剩边界之后的少量内容。
|
|
696
|
+
const ownEnd = marker.done ? marker.pos : raw.length;
|
|
697
|
+
const boundary = this._fallbackBoundary(raw, ownEnd);
|
|
698
|
+
let fallback = boundary > 0 ? raw.slice(boundary) : raw;
|
|
699
|
+
// 边界裁剪后"再试一次定位":此时窗口已剔除重放段,回显残片可能恢复成可匹配的连续文本
|
|
700
|
+
const retry = extractOutputStart(fallback, echoText, fallback.length, false);
|
|
701
|
+
if (retry > 0)
|
|
702
|
+
fallback = fallback.slice(retry);
|
|
703
|
+
else
|
|
704
|
+
fallback = this._stripLeadingControlNoise(fallback);
|
|
705
|
+
log.info(`[extract] ${this._logTag} seq=${this._runningSeq} 定位失败改用标记边界: boundary=${boundary} retry=${retry} 裁剪后长=${fallback.length} 原窗长=${raw.length}`);
|
|
706
|
+
// 中断命令再截到首个 ^C 回显,避免输出残留 ^C 与探针后 shell 重印的提示符(与旧版中断收尾语义一致)
|
|
584
707
|
if (this._interruptSent) {
|
|
585
|
-
const intr = detectInterrupt(
|
|
708
|
+
const intr = detectInterrupt(fallback, 0);
|
|
586
709
|
if (intr.interrupted)
|
|
587
|
-
fallback =
|
|
710
|
+
fallback = fallback.slice(0, intr.pos);
|
|
588
711
|
}
|
|
589
712
|
return this._stripProbeEchoes(stripMarkers(fallback));
|
|
590
713
|
}
|
|
@@ -608,24 +731,64 @@ export class BaseSession {
|
|
|
608
731
|
const intr = detectInterrupt(raw, end);
|
|
609
732
|
out = intr.interrupted ? raw.slice(end, intr.pos) : raw.slice(end);
|
|
610
733
|
}
|
|
611
|
-
if (this._adapter)
|
|
612
|
-
out = out.replace(this._markerCmd(this._runningSeq), "");
|
|
613
734
|
return this._stripProbeEchoes(stripMarkers(out.replace(/^[\r\n]+/, "")));
|
|
614
735
|
}
|
|
736
|
+
/**
|
|
737
|
+
* 回显定位失败时的标记边界裁剪:扫描窗口内所有完成标记,返回"本命令自己的标记之前、
|
|
738
|
+
* 所有非本 seq 标记之后"的边界偏移(无合适标记时为 0)。
|
|
739
|
+
* 用于把控制台屏幕重放(含上一会话的命令行与标记)整段切掉,避免其被当输出落盘。
|
|
740
|
+
* 判定:只按 seq 区分——seq 等于当前命令序号的标记(求值式或命令行回显式)属于本次命令,
|
|
741
|
+
* 不作边界(否则会把本次命令的回显一起切掉);其余标记(重放的别会话标记)取最后一个的结束位置。
|
|
742
|
+
* @param raw 待裁剪窗口原始字节流
|
|
743
|
+
* @param ownEnd 本命令完成标记的结束偏移(无标记时为窗口末尾)
|
|
744
|
+
* @returns 裁剪起点偏移(相对 raw)
|
|
745
|
+
*/
|
|
746
|
+
_fallbackBoundary(raw, ownEnd) {
|
|
747
|
+
let start = 0;
|
|
748
|
+
for (const h of scanDoneMarkers(raw)) {
|
|
749
|
+
if (h.pos >= ownEnd)
|
|
750
|
+
break;
|
|
751
|
+
if (h.seq === this._runningSeq)
|
|
752
|
+
continue;
|
|
753
|
+
start = Math.max(start, h.end);
|
|
754
|
+
}
|
|
755
|
+
return start;
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* 剥掉文本开头的控制码/重绘噪音(光标定位、颜色、OSC 标题等非打印序列)与空白,
|
|
759
|
+
* 直到首个可见字符;用于标记边界裁剪后仍残留的重绘噪音清理。
|
|
760
|
+
* @param s 待清理文本
|
|
761
|
+
* @returns 去掉行首控制噪音后的文本
|
|
762
|
+
*/
|
|
763
|
+
_stripLeadingControlNoise(s) {
|
|
764
|
+
return s.replace(/^(?:[\s\x00-\x1f\x7f]|\x1b\[[0-9;?]*[a-zA-Z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[^\x1b])+/, "");
|
|
765
|
+
}
|
|
615
766
|
/** 命令执行/提交前准备:裁剪已消费缓冲 + 丢弃上一条命令的迟到残留标记 */
|
|
616
767
|
_beginCapture(command) {
|
|
768
|
+
// 诊断用:记录进入时的缓冲/游标快照(仅用于日志,不参与裁剪决策)
|
|
769
|
+
const entryBufLen = this._buffer.length;
|
|
770
|
+
const entryCursor = this._cursor;
|
|
617
771
|
// 开始新命令:停掉上一条命令遗留的中断周期(新命令有自己的 seq 与收尾)
|
|
618
772
|
this._stopInterruptCycle("开始新命令");
|
|
619
|
-
// 用上一条命令完成标记(<SSH_DONE:seq:N>,此刻 _runningSeq 仍是上一条的)定位命令起点;
|
|
620
|
-
//
|
|
621
|
-
const marker = detectLastDoneMarker(this._buffer, 0, this._runningSeq);
|
|
773
|
+
// 用上一条命令完成标记(<SSH_DONE:nonce:seq:N>,此刻 _runningSeq 仍是上一条的)定位命令起点;
|
|
774
|
+
// 只认自己 nonce:别的会话经控制台重放混入的旧标记不会被误当本会话边界
|
|
775
|
+
const marker = detectLastDoneMarker(this._buffer, 0, this._nonce, this._runningSeq);
|
|
622
776
|
if (marker.done) {
|
|
623
777
|
this._buffer = this._buffer.slice(marker.pos);
|
|
624
|
-
this._cursor = 0;
|
|
625
778
|
}
|
|
626
|
-
|
|
779
|
+
else {
|
|
780
|
+
// 无本会话标记(首命令且基线标记尚未到达/不可用):至少按"非本 seq 标记"边界剥掉屏幕重放段
|
|
781
|
+
const replayBoundary = this._fallbackBoundary(this._buffer, this._buffer.length);
|
|
782
|
+
if (replayBoundary > 0)
|
|
783
|
+
this._buffer = this._buffer.slice(replayBoundary);
|
|
784
|
+
}
|
|
785
|
+
// fallback:再依赖 _cursor 裁剪
|
|
627
786
|
this._buffer = this._buffer.slice(this._cursor);
|
|
628
787
|
this._cursor = 0;
|
|
788
|
+
// 诊断:本次窗口起点取自"自身找到的 lastMarkerPos"(无标记时为 0,即缓冲起点);
|
|
789
|
+
// captureStart=裁剪后残留长度(exec 的实际捕获起点,与缓冲内容相关,仅供参考)
|
|
790
|
+
const winStartPos = marker.done ? marker.pos : 0;
|
|
791
|
+
debug(`[capture] ${this._logTag} seq=${this._cmdSeq + 1} 起点=${winStartPos} captureStart=${this._buffer.length}(参考) entryCursor=${entryCursor} bufLen=${entryBufLen} lastMarkerPos=${marker.done ? marker.pos : -1}`);
|
|
629
792
|
// 记录命令发起前缓冲末行(旧提示符行):语法错误收尾时 shell 会重印同形提示符,供输出尾部剥离
|
|
630
793
|
this._promptRef = this._buffer.split("\n").pop() ?? "";
|
|
631
794
|
this._runningStartPos = 0;
|
|
@@ -636,7 +799,8 @@ export class BaseSession {
|
|
|
636
799
|
this._runningSeq = this._cmdSeq;
|
|
637
800
|
this._setBusy(true, "cmdStart");
|
|
638
801
|
this._lastActive = Date.now();
|
|
639
|
-
|
|
802
|
+
debug(`[run] 开始 ${this._logTag} seq=${this._runningSeq} startPos=0 cmdLen=${command.length}`);
|
|
803
|
+
debug(`[run] 开始 ${this._logTag} seq=${this._runningSeq} cmd=${JSON.stringify(command.slice(0, 120))}`);
|
|
640
804
|
this._emitStart(command, this._runningStartTs);
|
|
641
805
|
}
|
|
642
806
|
/** 追加输出字节:维护业务缓冲 + 连续原始流 ring */
|
|
@@ -658,6 +822,35 @@ export class BaseSession {
|
|
|
658
822
|
this._rawLog = this._rawLog.slice(trimmed);
|
|
659
823
|
this._rawDiscarded += trimmed;
|
|
660
824
|
}
|
|
825
|
+
// 诊断:仅当本 chunk 含完成标记时记一行(回答"后续命令的标记为何在当前命令结束前就到")
|
|
826
|
+
if (text.includes(DONE_TAG)) {
|
|
827
|
+
const found = scanDoneMarkers(text).map((h) => h.seq ?? "?").join(",");
|
|
828
|
+
// 非内容信息保持 info(排障主力);命令/输出片段前缀(prefix)降级为 debug,避免泄漏内容
|
|
829
|
+
debug(`[chunk] ${this._logTag} seq=${this._runningSeq} runningStart=${this._runningStartPos} chunkLen=${text.length} found=[${found}]`);
|
|
830
|
+
debug(`[chunk] ${this._logTag} seq=${this._runningSeq} prefix=${escapeCtl(text.slice(0, 60))}`);
|
|
831
|
+
}
|
|
832
|
+
// 数据已落缓冲:通知数据到达监听器(agent 据此做节流合并推流;异常不打断数据写入)
|
|
833
|
+
try {
|
|
834
|
+
this._dataListener?.();
|
|
835
|
+
}
|
|
836
|
+
catch { /* 监听器异常不打断数据写入 */ }
|
|
837
|
+
// 完成判定改为事件驱动:每个数据块落入缓冲后立即判定完成标记/语法错误(异常不打断数据写入)
|
|
838
|
+
this._onDataArrived();
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* 会话初始化完成后发送**基线标记**(seq=0):作为第一条命令的"前驱"。
|
|
842
|
+
*
|
|
843
|
+
* 背景:新连接时远端 Windows 控制台会重放上一会话的屏幕缓冲,其内容落在缓冲区开头。
|
|
844
|
+
* 旧实现首条命令 `_beginCapture` 没有"上一条标记"可依,窗口被迫从缓冲起点(=重放内容)开始,
|
|
845
|
+
* 回显定位失败便退回整窗 → 重放杂物被当输出落盘。
|
|
846
|
+
* 发一条 seq=0 的求值标记后,首条命令能像后续命令一样"裁剪到上一条标记之后",起点即干净。
|
|
847
|
+
* 须在 shell 探测完成(adapter 已定)之后调用,使标记命令语法正确;写入方式与中断探针一致(尾随提交分隔符)。
|
|
848
|
+
* @returns 无
|
|
849
|
+
*/
|
|
850
|
+
_sendBaselineMarker() {
|
|
851
|
+
const baseline = this._markerCmd(0) + "\r";
|
|
852
|
+
debug(`[baseline] ${this._logTag} 初始化完成,发送基线标记 nonce=${this._nonce} seq=0`);
|
|
853
|
+
this._write(baseline);
|
|
661
854
|
}
|
|
662
855
|
/** 探测 shell 类型:按各适配器 probeCommand 逐个探测(POSIX 系优先,pwsh/cmd 用各自独有命令),
|
|
663
856
|
* login shell 的 $0 带 - 前缀(-bash/-zsh)由对应 parseProbe 容忍 */
|
|
@@ -690,118 +883,215 @@ export class BaseSession {
|
|
|
690
883
|
return this._buffer.length > 0 ? this._buffer : null;
|
|
691
884
|
}
|
|
692
885
|
/**
|
|
693
|
-
*
|
|
694
|
-
*
|
|
695
|
-
*
|
|
696
|
-
* @returns
|
|
697
|
-
* syntaxError=true 表示本次是语法/解析错误收尾(输出提取须改用首次回显匹配 + 剥尾部提示符)
|
|
886
|
+
* 挂起 exec 的同步完成等待(事件驱动,无轮询):
|
|
887
|
+
* - 数据到达(`_appendBuffer` → `_checkCompletion`)命中完成标记/语法静默时由 `_settleCompletion` 兑现;
|
|
888
|
+
* - 超过 ANIMATION_WINDOW_MS 仍未完成则由一次性 animation 定时器兑现 "running"(转后台继续追踪,不设硬超时)。
|
|
889
|
+
* @returns 完成结果(done 携带标记位置/退出码/语法错误标志;running 表示转后台)
|
|
698
890
|
*/
|
|
699
|
-
|
|
891
|
+
_awaitCompletion() {
|
|
700
892
|
return new Promise((resolve) => {
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
const curLen = this._buffer.length;
|
|
709
|
-
if (curLen !== lastLen)
|
|
710
|
-
lastLen = curLen;
|
|
711
|
-
// 语法/解析错误:**每轮最先判定**(优先于交互提示与"判为 running"),命中即进入静默等待再收尾。
|
|
712
|
-
// 整行命令作废(含同行拼装的完成标记也不会执行)→ 视为命令已结束。
|
|
713
|
-
// 不立即收尾:pwsh 的多行错误块由格式化器异步/批量渲染,须等输出安静一小段再收尾,
|
|
714
|
-
// 否则只截到 `ParserError:` 首行、丢掉 Line | 等后续行;安静窗口 300ms,自识别起上限 1s。
|
|
715
|
-
// 禁止"无标记超时即完成"式兜底:静默长命令(如 sleep)会被误判为已完成。
|
|
716
|
-
if (detectSyntaxError(this._adapter, this._buffer, startPos)) {
|
|
717
|
-
if (syntaxSeenAt === 0) {
|
|
718
|
-
syntaxSeenAt = now;
|
|
719
|
-
syntaxQuietAt = now;
|
|
720
|
-
syntaxLen = curLen;
|
|
721
|
-
}
|
|
722
|
-
else if (curLen !== syntaxLen) {
|
|
723
|
-
syntaxLen = curLen;
|
|
724
|
-
syntaxQuietAt = now;
|
|
725
|
-
}
|
|
726
|
-
if (now - syntaxQuietAt >= SYNTAX_QUIET_MS || now - syntaxSeenAt >= SYNTAX_MAX_WAIT_MS) {
|
|
727
|
-
clearInterval(timer);
|
|
728
|
-
// 无标记可读 → exitCode=null;markerPos 缺省 → 输出窗口取到缓冲区末尾(含整段错误)
|
|
729
|
-
resolve({ kind: "done", exitCode: null, syntaxError: true });
|
|
730
|
-
return;
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
// 完成判定(权威且唯一):命令后追加的 printf 输出 <SSH_DONE:seq:code>。
|
|
734
|
-
// marker 自带唯一 seq,从命令起点直接搜索即可(不依赖命令回显定位)。
|
|
735
|
-
// ^C 回显不作为完成依据:捕获/忽略 SIGINT 的程序(mysql/REPL)同样回显 ^C 但命令未结束,
|
|
736
|
-
// 据此判完成会把后续命令喂进运行中的程序;中断收尾改由 send() 补发的探针标记触发。
|
|
737
|
-
const marker = detectLastDoneMarker(this._buffer, startPos, this._runningSeq);
|
|
738
|
-
if (marker.done) {
|
|
739
|
-
clearInterval(timer);
|
|
740
|
-
resolve({ kind: "done", markerPos: marker.pos, exitCode: marker.exitCode });
|
|
741
|
-
return;
|
|
893
|
+
this._completionWaiter = { resolve };
|
|
894
|
+
this._animationTimer = setTimeout(() => {
|
|
895
|
+
this._animationTimer = null;
|
|
896
|
+
const w = this._completionWaiter;
|
|
897
|
+
if (w) {
|
|
898
|
+
this._completionWaiter = null;
|
|
899
|
+
w.resolve({ kind: "running" });
|
|
742
900
|
}
|
|
743
|
-
|
|
744
|
-
if (now - startTs >= ANIMATION_WINDOW_MS) {
|
|
745
|
-
clearInterval(timer);
|
|
746
|
-
resolve({ kind: "running" });
|
|
747
|
-
return;
|
|
748
|
-
}
|
|
749
|
-
}, 50);
|
|
901
|
+
}, ANIMATION_WINDOW_MS);
|
|
750
902
|
});
|
|
751
903
|
}
|
|
752
|
-
/**
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
904
|
+
/**
|
|
905
|
+
* 数据到达事件钩子(由 `_appendBuffer` 在每个数据块落入缓冲后调用):
|
|
906
|
+
* 仅在追踪运行命令时触发完成判定,异常不打断数据写入。
|
|
907
|
+
* @returns 无
|
|
908
|
+
*/
|
|
909
|
+
_onDataArrived() {
|
|
910
|
+
if (this._runningStartPos === null || this._runningCommand === "")
|
|
911
|
+
return;
|
|
912
|
+
try {
|
|
913
|
+
this._checkCompletion(true);
|
|
914
|
+
}
|
|
915
|
+
catch (e) {
|
|
916
|
+
log.info(`[watch] ${this._logTag} seq=${this._runningSeq} 数据到达判定异常, 保持监听: err=${e instanceof Error ? e.message : String(e)}`);
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* 完成判定(唯一入口,事件驱动):
|
|
921
|
+
* 断连优先处理;其次判当前 seq 完成标记(权威且唯一);再次判语法/解析错误(安静窗口后收尾)。
|
|
922
|
+
* ^C 回显不作为完成依据:捕获/忽略 SIGINT 的程序(mysql/REPL)同样回显 ^C 但命令未结束,
|
|
923
|
+
* 据此判完成会把后续命令喂进运行中的程序;中断收尾由 send() 补发的探针标记触发。
|
|
924
|
+
* @param fromData true=数据到达触发(推进语法静默计时);false=后台兜底 tick(不重置已挂的静默计时,避免无限顺延)
|
|
925
|
+
* @returns 无
|
|
926
|
+
*/
|
|
927
|
+
_checkCompletion(fromData) {
|
|
928
|
+
if (this._runningStartPos === null || !this._runningCommand)
|
|
929
|
+
return;
|
|
930
|
+
if (!this._connected) {
|
|
931
|
+
this._handleDisconnect();
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
try {
|
|
935
|
+
// 完成判定(权威且唯一):命令后追加的 printf 输出 <SSH_DONE:seq:code>;marker 自带唯一 seq,从命令起点搜索
|
|
936
|
+
const marker = detectLastDoneMarker(this._buffer, this._runningStartPos, this._nonce, this._runningSeq);
|
|
937
|
+
if (marker.done) {
|
|
938
|
+
this._settleCompletion({ kind: "done", markerPos: marker.pos, exitCode: marker.exitCode });
|
|
772
939
|
return;
|
|
773
940
|
}
|
|
774
|
-
//
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
941
|
+
// 语法/解析错误:整行命令作废(含同行拼装的完成标记也不会执行)→ 输出安静后按完成收尾
|
|
942
|
+
if (detectSyntaxError(this._adapter, this._buffer, this._watchStartPos)) {
|
|
943
|
+
// 兜底 tick 不重置已挂的静默计时(否则每周期顺延、永不收尾);数据到达时才推进
|
|
944
|
+
if (fromData || this._syntaxTimer === null)
|
|
945
|
+
this._armSyntaxQuiet();
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
catch (e) {
|
|
949
|
+
log.info(`[watch] ${this._logTag} seq=${this._runningSeq} 判定异常, 保持监听: err=${e instanceof Error ? e.message : String(e)}`);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* 兑现一次完成判定:有 exec 同步等待者时只回传结果(由 exec 走统一收尾);
|
|
954
|
+
* 无等待者(submit / exec 转后台)时直接调用 `_completeRunning` 收尾。
|
|
955
|
+
* @param o 完成结果
|
|
956
|
+
* @returns 无
|
|
957
|
+
*/
|
|
958
|
+
_settleCompletion(o) {
|
|
959
|
+
const w = this._completionWaiter;
|
|
960
|
+
if (w) {
|
|
961
|
+
this._completionWaiter = null;
|
|
962
|
+
this._clearAnimationTimer();
|
|
963
|
+
w.resolve(o);
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
if (o.kind !== "done")
|
|
967
|
+
return;
|
|
968
|
+
if (o.syntaxError) {
|
|
969
|
+
// 语法错误:输出窗口 = 回显结束 → 缓冲区末尾(含整段多行错误块),syntaxMode 提取
|
|
970
|
+
let out;
|
|
971
|
+
try {
|
|
972
|
+
out = this._extractOutput(this._buffer.slice(this._watchStartPos), this._watchCommand, true);
|
|
973
|
+
}
|
|
974
|
+
catch (e) {
|
|
975
|
+
// 输出提取异常绝不影响收尾:退化为整窗原始输出,保证 history/done/busy 一定落地
|
|
976
|
+
log.info(`[extract] ${this._logTag} seq=${this._runningSeq} 语法错误输出提取异常, 使用整窗输出: err=${e instanceof Error ? e.message : String(e)}`);
|
|
977
|
+
out = this._buffer.slice(this._watchStartPos);
|
|
978
|
+
}
|
|
979
|
+
this._completeRunning(this._watchStartPos, this._buffer.length, null, this._watchCommand, out, "watch(syntax)");
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
this._completeRunning(this._watchStartPos, o.markerPos ?? this._buffer.length, o.exitCode ?? null, this._watchCommand);
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* 推进语法错误安静窗口(一次性定时器,非轮询):识别到语法错误后等输出停止增长 SYNTAX_QUIET_MS 再收尾,
|
|
986
|
+
* 确保 pwsh 异步/批量渲染的多行错误块被完整收进输出窗口;自首次识别起上限 SYNTAX_MAX_WAIT_MS。
|
|
987
|
+
* 数据到达(输出变化)时重置安静窗口;兜底 tick 不重置(见 _checkCompletion)。
|
|
988
|
+
* @returns 无
|
|
989
|
+
*/
|
|
990
|
+
_armSyntaxQuiet() {
|
|
991
|
+
const now = Date.now();
|
|
992
|
+
const len = this._buffer.length;
|
|
993
|
+
if (this._syntaxSeenAt === 0) {
|
|
994
|
+
this._syntaxSeenAt = now;
|
|
995
|
+
this._syntaxQuietAt = now;
|
|
996
|
+
this._syntaxLen = len;
|
|
997
|
+
}
|
|
998
|
+
else if (len !== this._syntaxLen) {
|
|
999
|
+
this._syntaxLen = len;
|
|
1000
|
+
this._syntaxQuietAt = now;
|
|
1001
|
+
}
|
|
1002
|
+
if (now - this._syntaxSeenAt >= SYNTAX_MAX_WAIT_MS) {
|
|
1003
|
+
this._clearSyntaxTimer();
|
|
1004
|
+
this._settleCompletion({ kind: "done", exitCode: null, syntaxError: true });
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
const remain = Math.max(0, SYNTAX_QUIET_MS - (now - this._syntaxQuietAt));
|
|
1008
|
+
this._clearSyntaxTimer();
|
|
1009
|
+
this._syntaxTimer = setTimeout(() => {
|
|
1010
|
+
this._syntaxTimer = null;
|
|
1011
|
+
if (this._runningStartPos === null)
|
|
780
1012
|
return;
|
|
1013
|
+
try {
|
|
1014
|
+
this._settleCompletion({ kind: "done", exitCode: null, syntaxError: true });
|
|
781
1015
|
}
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
// exitCode=null(无标记可读),输出窗口 = 回显结束 → 缓冲区末尾(含整段多行错误块,
|
|
785
|
-
// 回显取首次匹配并剥掉尾部重印的提示符行,见 _extractOutput 的 syntaxMode)
|
|
786
|
-
if (detectSyntaxError(this._adapter, this._buffer, startPos)) {
|
|
787
|
-
const now = Date.now();
|
|
788
|
-
const len = this._buffer.length;
|
|
789
|
-
if (syntaxSeenAt === 0) {
|
|
790
|
-
syntaxSeenAt = now;
|
|
791
|
-
syntaxQuietAt = now;
|
|
792
|
-
syntaxLen = len;
|
|
793
|
-
}
|
|
794
|
-
else if (len !== syntaxLen) {
|
|
795
|
-
syntaxLen = len;
|
|
796
|
-
syntaxQuietAt = now;
|
|
797
|
-
}
|
|
798
|
-
if (now - syntaxQuietAt >= SYNTAX_QUIET_MS || now - syntaxSeenAt >= SYNTAX_MAX_WAIT_MS) {
|
|
799
|
-
const out = this._extractOutput(this._buffer.slice(startPos), command, true);
|
|
800
|
-
this._completeRunning(startPos, this._buffer.length, null, command, out, "watch(syntax)");
|
|
801
|
-
return;
|
|
802
|
-
}
|
|
1016
|
+
catch (e) {
|
|
1017
|
+
log.info(`[watch] ${this._logTag} seq=${this._runningSeq} 语法静默收尾异常: err=${e instanceof Error ? e.message : String(e)}`);
|
|
803
1018
|
}
|
|
804
|
-
},
|
|
1019
|
+
}, remain);
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* 断连收尾(由后台兜底 tick 判定 _connected=false 触发):命令视为结束(可能从未完成),
|
|
1023
|
+
* 补发 done 防 server busy 卡死;不写 history(输出窗口从未定案,无可信尾部可摘)。
|
|
1024
|
+
* @returns 无
|
|
1025
|
+
*/
|
|
1026
|
+
_handleDisconnect() {
|
|
1027
|
+
if (this._runningCommand) {
|
|
1028
|
+
this._emitDone(null, Date.now());
|
|
1029
|
+
// 断连收尾也是"结束":补记 [run] 结束;不附 tail(输出窗口从未定案,无可信尾部可摘)
|
|
1030
|
+
log.info(`[run] 结束 ${this._logTag} seq=${this._runningSeq} endPos=${this._buffer.length} exitCode=null duration=${Date.now() - this._runningStartTs}ms reason=disconnect`);
|
|
1031
|
+
}
|
|
1032
|
+
this._setBusy(false, "断连补 done");
|
|
1033
|
+
this._clearRunningContext();
|
|
1034
|
+
if (this._watchTimer) {
|
|
1035
|
+
clearInterval(this._watchTimer);
|
|
1036
|
+
this._watchTimer = null;
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* 开始一次命令的后台追踪:记录兜底判定所需的捕获窗口起点/命令,并复位语法静默状态。
|
|
1041
|
+
* 不做任何轮询——完成判定由数据到达事件驱动(见 `_onDataArrived`)。
|
|
1042
|
+
* @param startPos 捕获窗口起点(相对当前 buffer;submit 为 0,exec 转后台为 captureStart)
|
|
1043
|
+
* @param command 命令(history 记录用)
|
|
1044
|
+
* @returns 无
|
|
1045
|
+
*/
|
|
1046
|
+
_armTracking(startPos, command) {
|
|
1047
|
+
this._watchStartPos = startPos;
|
|
1048
|
+
this._watchCommand = command;
|
|
1049
|
+
this._syntaxSeenAt = 0;
|
|
1050
|
+
this._syntaxQuietAt = 0;
|
|
1051
|
+
this._syntaxLen = 0;
|
|
1052
|
+
this._clearSyntaxTimer();
|
|
1053
|
+
}
|
|
1054
|
+
/**
|
|
1055
|
+
* 启动稀疏兜底监听(≥1s,非高频轮询):完成判定已由数据到达事件驱动,此定时器仅覆盖
|
|
1056
|
+
* 断连(子类只置 `_connected=false`、不回调基类)与极端漏判保护;命令已不在追踪中则不启动。
|
|
1057
|
+
* @returns 无
|
|
1058
|
+
*/
|
|
1059
|
+
_startFallbackWatch() {
|
|
1060
|
+
if (this._runningStartPos === null || !this._runningCommand)
|
|
1061
|
+
return;
|
|
1062
|
+
if (this._watchTimer)
|
|
1063
|
+
return;
|
|
1064
|
+
this._watchTimer = setInterval(() => { this._fallbackTick(); }, FALLBACK_WATCH_INTERVAL_MS);
|
|
1065
|
+
}
|
|
1066
|
+
/** 后台兜底一次:断连优先处理,否则复用统一完成判定(异常不得让监听中断,否则 busy 卡死) */
|
|
1067
|
+
_fallbackTick() {
|
|
1068
|
+
try {
|
|
1069
|
+
if (this._runningStartPos === null || !this._runningCommand)
|
|
1070
|
+
return;
|
|
1071
|
+
if (!this._connected) {
|
|
1072
|
+
this._handleDisconnect();
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
this._checkCompletion(false);
|
|
1076
|
+
}
|
|
1077
|
+
catch (e) {
|
|
1078
|
+
// tick 内异常:记一行后继续下一轮监听(完成判定仍只认当前 seq 标记)
|
|
1079
|
+
infoDedup(`tick-exc:${this._logTag}:${this._runningSeq}`, `[watch] ${this._logTag} seq=${this._runningSeq} tick 异常, 保持监听: err=${e instanceof Error ? e.message : String(e)}`);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
/** 清除 exec 同步等待的 animation 一次性定时器(幂等) */
|
|
1083
|
+
_clearAnimationTimer() {
|
|
1084
|
+
if (this._animationTimer) {
|
|
1085
|
+
clearTimeout(this._animationTimer);
|
|
1086
|
+
this._animationTimer = null;
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
/** 清除语法静默一次性定时器(幂等) */
|
|
1090
|
+
_clearSyntaxTimer() {
|
|
1091
|
+
if (this._syntaxTimer) {
|
|
1092
|
+
clearTimeout(this._syntaxTimer);
|
|
1093
|
+
this._syntaxTimer = null;
|
|
1094
|
+
}
|
|
805
1095
|
}
|
|
806
1096
|
/**
|
|
807
1097
|
* 统一命令完成收尾(供 exec 同步完成、后台 watch 与 readBuffer 复用,避免多处收尾逻辑漂移):
|
|
@@ -816,14 +1106,26 @@ export class BaseSession {
|
|
|
816
1106
|
*/
|
|
817
1107
|
_completeRunning(startPos, endPos, exitCode, command, out, reason = "watch") {
|
|
818
1108
|
const raw = this._buffer.slice(startPos, endPos);
|
|
819
|
-
|
|
1109
|
+
let output;
|
|
1110
|
+
try {
|
|
1111
|
+
output = out ?? this._extractOutput(raw, command);
|
|
1112
|
+
}
|
|
1113
|
+
catch (e) {
|
|
1114
|
+
// 输出提取异常绝不影响收尾:退化为整窗原始输出,保证 history/done/busy 一定落地
|
|
1115
|
+
log.info(`[extract] ${this._logTag} seq=${this._runningSeq} 输出提取异常, 使用整窗输出: cmdLen=${command.length} err=${e instanceof Error ? e.message : String(e)}`);
|
|
1116
|
+
output = raw;
|
|
1117
|
+
}
|
|
820
1118
|
this._history.append(command, output, this._runningStartTs, undefined, exitCode ?? undefined);
|
|
821
1119
|
this._emitDone(exitCode, Date.now(), output);
|
|
822
1120
|
this._cursor = Math.max(startPos, endPos);
|
|
823
|
-
this._setBusy(
|
|
824
|
-
//
|
|
825
|
-
|
|
826
|
-
|
|
1121
|
+
this._setBusy(false, "cmdDone", true); // 命令完成即清 busy("保持 busy 到排队序列结束"的机制已移除);释放行紧随 [run] 结束,降 debug 免重复
|
|
1122
|
+
// 结束日志:非内容信息(长度/耗时/退出码/原因)保持 info;有界输出尾部摘要降级为 debug,避免泄漏输出内容
|
|
1123
|
+
log.info(`[run] 结束 ${this._logTag} seq=${this._runningSeq} endPos=${endPos} exitCode=${exitCode} outLen=${output.length} duration=${Date.now() - this._runningStartTs}ms reason=${reason}`);
|
|
1124
|
+
if (isDebugEnabled()) {
|
|
1125
|
+
const outTail = tailSummary(output);
|
|
1126
|
+
if (outTail)
|
|
1127
|
+
debug(`[run] 结束 ${this._logTag} seq=${this._runningSeq} tail=${outTail}`);
|
|
1128
|
+
}
|
|
827
1129
|
this._stopInterruptCycle("命令完成");
|
|
828
1130
|
this._clearRunningContext();
|
|
829
1131
|
if (this._watchTimer)
|
|
@@ -832,6 +1134,8 @@ export class BaseSession {
|
|
|
832
1134
|
}
|
|
833
1135
|
_clearRunningContext() {
|
|
834
1136
|
this._stopInterruptCycle("运行上下文清理");
|
|
1137
|
+
this._clearSyntaxTimer();
|
|
1138
|
+
this._clearAnimationTimer();
|
|
835
1139
|
this._runningStartPos = null;
|
|
836
1140
|
this._runningCommand = "";
|
|
837
1141
|
this._streamPos = null;
|