diff --git a/application/i18n/locales/en/scripts.ts b/application/i18n/locales/en/scripts.ts index 321251766..6c49e6938 100644 --- a/application/i18n/locales/en/scripts.ts +++ b/application/i18n/locales/en/scripts.ts @@ -9,7 +9,7 @@ export const enScriptsMessages = { 'scripts.trigger.manual': 'Manual run', 'scripts.trigger.onConnect': 'Run on connect', 'scripts.trigger.onOutput': 'Run on output match', - 'scripts.trigger.onOutputHint': 'Fires when server output matches the pattern (user keystroke echo is ignored). With no target hosts configured, listens on the current connected session; with targets, only those hosts. Disabled in alternate-screen apps such as vim or htop. Suppressed while another script is running on this session; rechecked after it finishes. For in-flow waits, use nct.screen.waitFor in script code.', + 'scripts.trigger.onOutputHint': 'Fires when server output matches the pattern (user keystroke echo is ignored). With no target hosts configured, listens on the current connected session; with targets, only those hosts. Disabled in alternate-screen apps such as vim or htop. Suppressed while another script is running on this session; rechecked after it finishes. For in-flow waits, use nct.screen.waitForText or nct.screen.waitForRegex in script code.', 'scripts.actions.save': 'Save', 'scripts.actions.runNow': 'Run now', 'scripts.actions.openEditor': 'Open editor', diff --git a/application/i18n/locales/zh-CN/scripts.ts b/application/i18n/locales/zh-CN/scripts.ts index d272647c5..1e48874f6 100644 --- a/application/i18n/locales/zh-CN/scripts.ts +++ b/application/i18n/locales/zh-CN/scripts.ts @@ -9,7 +9,7 @@ export const zhCNScriptsMessages = { 'scripts.trigger.manual': '手动运行', 'scripts.trigger.onConnect': '连接时运行', 'scripts.trigger.onOutput': '输出匹配时运行', - 'scripts.trigger.onOutputHint': '仅在服务端输出匹配正则时触发(会忽略本地按键回显)。未配置目标主机时,对当前已连接会话生效;配置目标后仅监听对应主机。进入备用屏幕的应用(如 vim、htop)期间不会触发。本 session 有其他脚本运行期间会抑制;脚本结束后再检查 buffer。流程内等待请用 nct.screen.waitFor。', + 'scripts.trigger.onOutputHint': '仅在服务端输出匹配正则时触发(会忽略本地按键回显)。未配置目标主机时,对当前已连接会话生效;配置目标后仅监听对应主机。进入备用屏幕的应用(如 vim、htop)期间不会触发。本 session 有其他脚本运行期间会抑制;脚本结束后再检查 buffer。流程内等待普通文本用 nct.screen.waitForText,正则用 nct.screen.waitForRegex。', 'scripts.actions.save': '保存', 'scripts.actions.runNow': '立即运行', 'scripts.actions.openEditor': '弹窗编辑', diff --git a/application/i18n/locales/zh-TW/scripts.ts b/application/i18n/locales/zh-TW/scripts.ts index 8b6265ba5..f3ccc02e5 100644 --- a/application/i18n/locales/zh-TW/scripts.ts +++ b/application/i18n/locales/zh-TW/scripts.ts @@ -9,7 +9,7 @@ export const zhTWScriptsMessages = { 'scripts.trigger.manual': '手動執行', 'scripts.trigger.onConnect': '連線時執行', 'scripts.trigger.onOutput': '輸出比對時執行', - 'scripts.trigger.onOutputHint': '僅在伺服器端輸出比對到正規表示式時觸發(會忽略本機按鍵回顯)。未設定目標主機時,對目前已連線的工作階段生效;設定目標後僅監聽對應主機。進入備用畫面的應用程式(如 vim、htop)期間不會觸發。本 session 有其他指令碼執行期間會抑制;指令碼結束後再檢查 buffer。流程內等待請用 nct.screen.waitFor。', + 'scripts.trigger.onOutputHint': '僅在伺服器端輸出比對到正規表示式時觸發(會忽略本機按鍵回顯)。未設定目標主機時,對目前已連線的工作階段生效;設定目標後僅監聽對應主機。進入備用畫面的應用程式(如 vim、htop)期間不會觸發。本 session 有其他指令碼執行期間會抑制;指令碼結束後再檢查 buffer。流程內等待一般文字用 nct.screen.waitForText,正規表示式用 nct.screen.waitForRegex。', 'scripts.actions.save': '儲存', 'scripts.actions.runNow': '立即執行', 'scripts.actions.openEditor': '彈出視窗編輯', diff --git a/domain/scriptApiReference.ts b/domain/scriptApiReference.ts index 78a158316..4ec357912 100644 --- a/domain/scriptApiReference.ts +++ b/domain/scriptApiReference.ts @@ -27,7 +27,9 @@ Global \`nct.version\` exposes the runtime version. ### nct.screen - \`await nct.screen.waitForPrompt(ms?)\` — wait for shell prompt (# root / $ user) -- \`await nct.screen.waitFor(pattern, ms?)\` — wait for output (string or RegExp, default 30s) +- \`await nct.screen.waitForText(text, ms?)\` — wait for exact text; regex characters are treated literally +- \`await nct.screen.waitForRegex(pattern, ms?)\` — wait for regex output; string patterns match multiline output +- \`await nct.screen.waitFor(pattern, ms?)\` — compatibility helper; plain strings are literal, and legacy \`/regex/flags\` strings still work - \`await nct.screen.waitForAny(patterns, ms?)\` — wait until any pattern matches - \`await nct.screen.sendLine(cmd)\` — type command + Enter - \`await nct.screen.send(text)\` — raw keys without Enter @@ -35,6 +37,9 @@ Global \`nct.version\` exposes the runtime version. - \`await nct.screen.clear()\` — clear screen - Properties: \`rows\`, \`cols\`, \`currentRow\` +Use \`waitForText("请选择SSH资源")\` for literal prompts. +Use \`waitForRegex(".*请选择SSH资源.*登录方式.*")\` for regex or output split across terminal lines. + ### nct.session - \`nct.session.connected\`, \`hostname\`, \`username\` - \`await nct.session.sleep(ms)\` — alias \`await nct.sleep(ms)\` diff --git a/domain/snippetScript.ts b/domain/snippetScript.ts index db32f1081..29e38d503 100644 --- a/domain/snippetScript.ts +++ b/domain/snippetScript.ts @@ -55,9 +55,9 @@ async function main() { nct.log('[1/12] waitForPrompt'); await nct.screen.waitForPrompt(CONFIG.PROMPT_TIMEOUT_MS); - nct.log('[2/12] sendLine + waitFor literal'); + nct.log('[2/12] sendLine + waitForText'); await nct.screen.sendLine(\`echo "\${tag}_BOOTSTRAP_OK"\`); - await nct.screen.waitFor(\`\${tag}_BOOTSTRAP_OK\`, CONFIG.STEP_TIMEOUT_MS); + await nct.screen.waitForText(\`\${tag}_BOOTSTRAP_OK\`, CONFIG.STEP_TIMEOUT_MS); nct.log('[3/12] waitForAny'); await nct.screen.sendLine('echo ANY_CHECK && uname -s'); @@ -71,11 +71,11 @@ async function main() { nct.log('[5/12] send raw + Enter'); await nct.screen.send(\`echo -n "\${tag}_RAW"\`); await nct.screen.sendLine(''); - await nct.screen.waitFor(\`\${tag}_RAW\`, CONFIG.STEP_TIMEOUT_MS); + await nct.screen.waitForText(\`\${tag}_RAW\`, CONFIG.STEP_TIMEOUT_MS); - nct.log('[6/12] waitFor regex'); + nct.log('[6/12] waitForRegex'); await nct.screen.sendLine(\`echo BUILD_ID=\${tag}\`); - await nct.screen.waitFor(new RegExp(\`BUILD_ID=\${tag}\`), CONFIG.STEP_TIMEOUT_MS); + await nct.screen.waitForRegex(new RegExp(\`BUILD_ID=\${tag}\`), CONFIG.STEP_TIMEOUT_MS); nct.log('[7/12] session.sleep / nct.sleep'); await nct.session.sleep(800); @@ -93,7 +93,7 @@ async function main() { \`echo "\${tag}_SAMPLE_\${i}_DONE"\`, ].join(' && '); await nct.screen.sendLine(cmd); - await nct.screen.waitFor(new RegExp(\`\${tag}_SAMPLE_\${i}_DONE\`), CONFIG.STEP_TIMEOUT_MS); + await nct.screen.waitForRegex(new RegExp(\`\${tag}_SAMPLE_\${i}_DONE\`), CONFIG.STEP_TIMEOUT_MS); await nct.screen.waitForPrompt(CONFIG.PROMPT_TIMEOUT_MS); nct.progress.step(\`sample \${i}/\${CONFIG.SAMPLE_COUNT}\`); nct.log(\`sample \${i}/\${CONFIG.SAMPLE_COUNT} ok\`); @@ -114,7 +114,7 @@ async function main() { nct.log('[10/12] startLog / stopLog'); await nct.session.startLog(\`./netcatty-it-\${tag}.log\`); await nct.screen.sendLine(\`echo "\${tag}_LOGGED"\`); - await nct.screen.waitFor(\`\${tag}_LOGGED\`, CONFIG.STEP_TIMEOUT_MS); + await nct.screen.waitForText(\`\${tag}_LOGGED\`, CONFIG.STEP_TIMEOUT_MS); await nct.session.stopLog(); } else { nct.log('[10/12] startLog/stopLog skipped'); @@ -145,7 +145,7 @@ async function main() { } await nct.screen.sendLine(\`echo "=== \${tag} ALL_PASSED ==="\`); - await nct.screen.waitFor(\`\${tag} ALL_PASSED\`, CONFIG.STEP_TIMEOUT_MS); + await nct.screen.waitForText(\`\${tag} ALL_PASSED\`, CONFIG.STEP_TIMEOUT_MS); nct.log('=== Netcatty Integration Test PASSED ==='); } @@ -155,7 +155,8 @@ await main(); export const DEFAULT_SCRIPT_TEMPLATE = `// Netcatty automation script - async JS in the active terminal session // // nct.screen.waitForPrompt(ms?) wait for shell prompt (# root / $ user) -// nct.screen.waitFor(pattern, ms?) wait for output (string or /regex/, default 30s) +// nct.screen.waitForText(text, ms?) wait for exact output text +// nct.screen.waitForRegex(pattern, ms?) wait for regex output, including multiline // nct.screen.waitForAny([patterns], ms?) wait until any pattern matches // nct.screen.sendLine(cmd) type command + Enter; send(text) raw keys only // nct.screen.getText(start?, end?) | clear() diff --git a/electron/scripts/scriptCodegen.cjs b/electron/scripts/scriptCodegen.cjs index cf6ec6c38..4952d7d54 100644 --- a/electron/scripts/scriptCodegen.cjs +++ b/electron/scripts/scriptCodegen.cjs @@ -24,7 +24,7 @@ function stepsToJavaScript(steps, recordedAt) { } lines.push(` await nct.screen.sendLine(${escapeJsString(step.value)});`); } else if (step.type === "waitFor") { - lines.push(` await nct.screen.waitFor(${escapeJsString(step.value)}, ${step.timeoutMs || 5000});`); + lines.push(` await nct.screen.waitForText(${escapeJsString(step.value)}, ${step.timeoutMs || 5000});`); } else if (step.type === "waitForPrompt") { lines.push(` await nct.screen.waitForPrompt(${step.timeoutMs || 30000});`); } else if (step.type === "sleep") { diff --git a/electron/scripts/scriptRuntime.cjs b/electron/scripts/scriptRuntime.cjs index 4949e7d3a..e9e5c8145 100644 --- a/electron/scripts/scriptRuntime.cjs +++ b/electron/scripts/scriptRuntime.cjs @@ -179,7 +179,9 @@ function createScriptRuntime(deps) { } } - async function waitForWithRecovery(pattern, timeoutMs = 30000) { + async function waitForWithRecovery(pattern, timeoutMs = 30000, options = {}) { + const waitMethod = options.waitMethod || "waitFor"; + const operationLabel = options.operationLabel || waitMethod; const patternLabel = pattern instanceof RegExp ? pattern.source : String(pattern); let stepTracked = false; while (true) { @@ -187,12 +189,12 @@ function createScriptRuntime(deps) { throw new Error("Script stopped"); } if (!stepTracked) { - await trackStep(`waitFor ${truncateActivityLabel(patternLabel, 60)}`); + await trackStep(`${operationLabel} ${truncateActivityLabel(patternLabel, 60)}`); stepTracked = true; } onStatusChange?.(runId, { waitingFor: patternLabel, status: "running", elapsedMs: Math.max(0, Date.now() - startedAt) }); try { - return await getOutputBuffer(sessionId).waitFor( + return await getOutputBuffer(sessionId)[waitMethod]( pattern, timeoutMs, () => Boolean(deps.isAborted?.()), @@ -329,6 +331,18 @@ function createScriptRuntime(deps) { waitFor(pattern, timeoutMs = 30000) { return waitForWithRecovery(pattern, timeoutMs); }, + waitForText(text, timeoutMs = 30000) { + return waitForWithRecovery(text, timeoutMs, { + waitMethod: "waitForText", + operationLabel: "waitForText", + }); + }, + waitForRegex(pattern, timeoutMs = 30000) { + return waitForWithRecovery(pattern, timeoutMs, { + waitMethod: "waitForRegex", + operationLabel: "waitForRegex", + }); + }, waitForPrompt(timeoutMs = 60000) { return waitForPromptWithRecovery(timeoutMs); }, diff --git a/electron/scripts/scriptRuntime.test.cjs b/electron/scripts/scriptRuntime.test.cjs index 20be89482..5c7bda797 100644 --- a/electron/scripts/scriptRuntime.test.cjs +++ b/electron/scripts/scriptRuntime.test.cjs @@ -3,6 +3,7 @@ const test = require("node:test"); const assert = require("node:assert/strict"); const { createScriptRuntime, wrapScriptSource, interruptibleSleep } = require("./scriptRuntime.cjs"); +const { SessionOutputBuffer } = require("./sessionOutputBuffer.cjs"); test("wrapScriptSource wraps async main scripts in async IIFE", () => { const wrapped = wrapScriptSource(` @@ -83,6 +84,32 @@ test("createScriptRuntime executes simple log script", async () => { assert.deepEqual(logs, ["hello"]); }); +test("createScriptRuntime supports regex waits over multiline output", async () => { + const logs = []; + const buffer = new SessionOutputBuffer("s1"); + const runtime = createScriptRuntime({ + sessionId: "s1", + runId: "r1", + appendLog: (_id, message) => logs.push(message), + writeToSession: () => {}, + getOutputBuffer: () => buffer, + getSessionMeta: () => ({ connected: true, hostname: "host", username: "user" }), + showDialog: async () => true, + isPaused: () => false, + isAborted: () => false, + onStatusChange: () => {}, + }); + + const run = runtime.execute(` + await nct.screen.waitForRegex(".*SSH资源.*登录方式.*", 1000); + nct.log("matched"); + `); + buffer.append("1. SSH资源\n请选择SSH资源\n'zxadmin'登录方式:"); + + await run; + assert.deepEqual(logs, ["matched"]); +}); + test("createScriptRuntime reports activity labels for loops without X/Y totals", async () => { const statuses = []; const runtime = createScriptRuntime({ diff --git a/electron/scripts/scriptStepCounter.cjs b/electron/scripts/scriptStepCounter.cjs index 434507b85..13fb348de 100644 --- a/electron/scripts/scriptStepCounter.cjs +++ b/electron/scripts/scriptStepCounter.cjs @@ -3,6 +3,8 @@ const STEP_MATCHERS = [ { regex: /await\s+nct\.screen\.waitForPrompt\s*\(/g, label: "waitForPrompt" }, { regex: /await\s+nct\.screen\.waitForAny\s*\(/g, label: "waitForAny" }, + { regex: /await\s+nct\.screen\.waitForText\s*\(/g, label: "waitForText" }, + { regex: /await\s+nct\.screen\.waitForRegex\s*\(/g, label: "waitForRegex" }, { regex: /await\s+nct\.screen\.waitFor\s*\(/g, label: "waitFor" }, { regex: /await\s+nct\.screen\.sendLine\s*\(/g, label: "sendLine" }, { regex: /await\s+nct\.screen\.send\s*\(/g, label: "send" }, diff --git a/electron/scripts/scriptStepCounter.test.cjs b/electron/scripts/scriptStepCounter.test.cjs index cec61b189..6e46e99e6 100644 --- a/electron/scripts/scriptStepCounter.test.cjs +++ b/electron/scripts/scriptStepCounter.test.cjs @@ -7,8 +7,10 @@ const { countScriptSteps } = require("./scriptStepCounter.cjs"); test("countScriptSteps counts common nct calls", () => { const source = ` await nct.screen.waitFor('$ ', 5000); +await nct.screen.waitForText('ready', 5000); +await nct.screen.waitForRegex('READY.*', 5000); await nct.screen.sendLine('ls'); nct.log('done'); `; - assert.equal(countScriptSteps(source), 3); + assert.equal(countScriptSteps(source), 5); }); diff --git a/electron/scripts/sessionOutputBuffer.cjs b/electron/scripts/sessionOutputBuffer.cjs index e965d53f0..1d2608ee9 100644 --- a/electron/scripts/sessionOutputBuffer.cjs +++ b/electron/scripts/sessionOutputBuffer.cjs @@ -17,6 +17,71 @@ function isRegExpLike(pattern) { ); } +function escapeRegExp(value) { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function hasUnescapedCharAt(source, index, char) { + if (source[index] !== char) return false; + let backslashCount = 0; + for (let cursor = index - 1; cursor >= 0 && source[cursor] === "\\"; cursor -= 1) { + backslashCount += 1; + } + return backslashCount % 2 === 0; +} + +function isRegexCompatibleWaitPattern(pattern) { + return pattern instanceof RegExp || isRegExpLike(pattern); +} + +function edgeDotRepeatTokenLengthAt(source, index) { + if (source[index] !== ".") return 0; + const quantifier = source[index + 1]; + if (quantifier !== "*" && quantifier !== "+") return 0; + if (!hasUnescapedCharAt(source, index, ".")) return 0; + return source[index + 2] === "?" ? 3 : 2; +} + +function stripEdgeDotRepeats(source) { + let start = 0; + let end = source.length; + if (hasUnescapedCharAt(source, start, "^")) { + start += 1; + } + if (end > start && hasUnescapedCharAt(source, end - 1, "$")) { + end -= 1; + } + + while (start < end) { + const tokenLength = edgeDotRepeatTokenLengthAt(source, start); + if (tokenLength === 0) break; + start += tokenLength; + } + while (end - start >= 2) { + const lazyTokenLength = edgeDotRepeatTokenLengthAt(source, end - 3); + if (lazyTokenLength === 3) { + end -= 3; + continue; + } + const greedyTokenLength = edgeDotRepeatTokenLengthAt(source, end - 2); + if (greedyTokenLength !== 2) break; + end -= 2; + } + return source.slice(start, end); +} + +function getRegExpFlags(regex, fallbackFlags = "") { + if (typeof regex.flags === "string") return regex.flags; + let flags = fallbackFlags; + if (regex.global && !flags.includes("g")) flags += "g"; + if (regex.ignoreCase && !flags.includes("i")) flags += "i"; + if (regex.multiline && !flags.includes("m")) flags += "m"; + if (regex.dotAll && !flags.includes("s")) flags += "s"; + if (regex.unicode && !flags.includes("u")) flags += "u"; + if (regex.sticky && !flags.includes("y")) flags += "y"; + return flags; +} + function compilePattern(pattern) { if (pattern instanceof RegExp || isRegExpLike(pattern)) return pattern; if (typeof pattern !== "string") { @@ -26,8 +91,41 @@ function compilePattern(pattern) { if (slashMatch) { return new RegExp(slashMatch[1], slashMatch[2]); } - const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(escaped); + return new RegExp(escapeRegExp(pattern)); +} + +function compileTextPattern(text) { + if (typeof text !== "string") { + throw new TypeError("waitForText pattern must be a string"); + } + return new RegExp(escapeRegExp(text)); +} + +function compileRegexPattern(pattern) { + if (pattern instanceof RegExp || isRegExpLike(pattern)) return pattern; + if (typeof pattern !== "string") { + throw new TypeError("waitForRegex pattern must be a string or RegExp"); + } + const slashMatch = pattern.match(/^\/(.+)\/([gimsuy]*)$/); + if (slashMatch) { + const flags = slashMatch[2].includes("s") ? slashMatch[2] : `${slashMatch[2]}s`; + return new RegExp(slashMatch[1], flags); + } + return new RegExp(pattern, "s"); +} + +function compileRegexFreshnessPattern(pattern) { + const regex = compileRegexPattern(pattern); + const source = typeof regex.source === "string" ? regex.source : String(pattern); + const strippedSource = stripEdgeDotRepeats(source); + if (!strippedSource || strippedSource === source) return null; + const flags = getRegExpFlags(regex).replace(/y/g, ""); + const globalFlags = flags.includes("g") ? flags : `${flags}g`; + try { + return new RegExp(strippedSource, globalFlags); + } catch { + return null; + } } function tryMatch(text, pattern) { @@ -37,8 +135,8 @@ function tryMatch(text, pattern) { return match[0]; } -function tryMatchWithEnd(text, pattern) { - const regex = compilePattern(pattern); +function tryMatchWithEnd(text, pattern, compiler = compilePattern) { + const regex = compiler(pattern); if (typeof regex.lastIndex === "number") regex.lastIndex = 0; const match = regex.exec(text); if (!match || match.index === undefined) return null; @@ -48,6 +146,56 @@ function tryMatchWithEnd(text, pattern) { }; } +function tryRegexMatchWithEnd(text, pattern) { + const regex = compileRegexPattern(pattern); + if (typeof regex.lastIndex === "number") regex.lastIndex = 0; + const match = regex.exec(text); + if (!match || match.index === undefined) return null; + + const value = match[0]; + let freshStartOffset = match.index; + let freshEndOffset = match.index + value.length; + const freshnessRegex = compileRegexFreshnessPattern(pattern); + if (freshnessRegex) { + if (typeof freshnessRegex.lastIndex === "number") freshnessRegex.lastIndex = 0; + let freshMatch = freshnessRegex.exec(value); + let latestFreshStartOffset = null; + let latestFreshEndOffset = null; + while (freshMatch && freshMatch.index !== undefined) { + const startOffset = freshMatch.index; + const endOffset = freshMatch.index + freshMatch[0].length; + if (latestFreshEndOffset === null || endOffset >= latestFreshEndOffset) { + latestFreshStartOffset = startOffset; + } + latestFreshEndOffset = Math.max(latestFreshEndOffset ?? 0, endOffset); + if (freshMatch[0].length === 0) { + freshnessRegex.lastIndex += 1; + } + freshMatch = freshnessRegex.exec(value); + } + if (latestFreshEndOffset !== null) { + freshStartOffset = match.index + latestFreshStartOffset; + freshEndOffset = match.index + latestFreshEndOffset; + } + } + + return { + value, + startOffset: match.index, + endOffset: match.index + value.length, + freshStartOffset, + freshEndOffset, + }; +} + +function staleAdvanceEndOffset(matched) { + return Math.max(Number(matched?.endOffset) || 0, 1); +} + +function staleRegexAdvanceEndOffset(matched) { + return Math.max((Number(matched?.startOffset) || 0) + 1, 1); +} + function findFreshTailMatchAny(text, patterns) { for (let index = 0; index < patterns.length; index += 1) { const pattern = patterns[index]; @@ -131,6 +279,14 @@ class SessionOutputBuffer { return tryMatchWithEnd(this.getPendingText(), pattern); } + tryMatchPendingText(text) { + return tryMatchWithEnd(this.getPendingText(), text, compileTextPattern); + } + + tryMatchPendingRegex(pattern) { + return tryRegexMatchWithEnd(this.getPendingText(), pattern); + } + consumeFreshPendingMatch(pattern) { while (true) { const matched = this.tryMatchPending(pattern); @@ -139,10 +295,64 @@ class SessionOutputBuffer { if (isFreshTailMatch(this.getText().length, absoluteEnd)) { return matched; } - this.advanceScanOffset(matched.endOffset); + this.advanceScanOffset(staleAdvanceEndOffset(matched)); } } + consumeFreshPendingText(text) { + while (true) { + const matched = this.tryMatchPendingText(text); + if (matched === null) return null; + const absoluteEnd = this.scanOffset + matched.endOffset; + if (isFreshTailMatch(this.getText().length, absoluteEnd)) { + return matched; + } + this.advanceScanOffset(staleAdvanceEndOffset(matched)); + } + } + + consumeFreshPendingRegex(pattern, options = {}) { + const text = this.getText(); + const baseOffset = this.scanOffset; + const pendingText = text.slice(baseOffset); + let relativeOffset = 0; + while (relativeOffset <= pendingText.length) { + const matched = tryRegexMatchWithEnd(pendingText.slice(relativeOffset), pattern); + if (matched === null) { + if (relativeOffset > 0) { + this.scanOffset = Math.min(baseOffset + relativeOffset, text.length); + } + return null; + } + const minFreshStartAbsolute = Number.isFinite(options.minFreshStartAbsolute) + ? options.minFreshStartAbsolute + : null; + const absoluteStart = baseOffset + relativeOffset + matched.freshStartOffset; + const absoluteEnd = baseOffset + relativeOffset + matched.freshEndOffset; + const matchStartAbsolute = baseOffset + relativeOffset + matched.startOffset; + if ( + isFreshTailMatch(text.length, absoluteEnd) + && (minFreshStartAbsolute === null || absoluteStart >= minFreshStartAbsolute) + ) { + let value = matched.value; + if (minFreshStartAbsolute !== null && matchStartAbsolute < minFreshStartAbsolute) { + const valueFreshStart = matched.freshStartOffset - matched.startOffset; + const lineStart = matched.value.lastIndexOf("\n", Math.max(0, valueFreshStart - 1)); + const valueStart = lineStart >= 0 ? lineStart : Math.max(0, valueFreshStart); + value = matched.value.slice(valueStart); + } + return { + ...matched, + value, + endOffset: relativeOffset + matched.endOffset, + }; + } + relativeOffset += staleRegexAdvanceEndOffset(matched); + } + this.scanOffset = Math.min(baseOffset + relativeOffset, text.length); + return null; + } + consumeFreshPendingMatchAny(patterns) { for (let index = 0; index < patterns.length; index += 1) { const pattern = patterns[index]; @@ -153,7 +363,7 @@ class SessionOutputBuffer { if (isFreshTailMatch(this.getText().length, absoluteEnd)) { return { index, matched }; } - this.advanceScanOffset(matched.endOffset); + this.advanceScanOffset(staleAdvanceEndOffset(matched)); } } return null; @@ -235,7 +445,70 @@ class SessionOutputBuffer { this.waiters = remaining; } + waitForWithMatcher({ pattern, timeoutMs, shouldAbort, consumeFreshMatch, timeoutLabel }) { + return new Promise((resolve, reject) => { + const waiter = { + pattern, + resolve, + reject, + shouldAbort, + timer: null, + check: () => { + const matched = consumeFreshMatch(); + if (matched === null) return false; + this.advanceScanOffset(matched.endOffset); + clearTimeout(waiter.timer); + if (waiter.abortInterval) clearInterval(waiter.abortInterval); + this.waiters = this.waiters.filter((entry) => entry.custom !== waiter); + resolve(matched.value); + return true; + }, + }; + waiter.timer = setTimeout(() => { + this.waiters = this.waiters.filter((entry) => entry.custom !== waiter); + if (waiter.abortInterval) clearInterval(waiter.abortInterval); + reject(new Error(`${timeoutLabel} timed out after ${timeoutMs}ms`)); + }, timeoutMs); + if (typeof shouldAbort === "function") { + waiter.abortInterval = setInterval(() => { + if (!shouldAbort()) return; + clearTimeout(waiter.timer); + clearInterval(waiter.abortInterval); + this.waiters = this.waiters.filter((entry) => entry.custom !== waiter); + reject(new Error("Script stopped")); + }, 100); + } + this.waiters.push({ + pattern, + resolve: () => {}, + reject, + timer: waiter.timer, + custom: waiter, + }); + }); + } + waitFor(pattern, timeoutMs = 30000, shouldAbort) { + if (isRegexCompatibleWaitPattern(pattern)) { + const minFreshStartAbsolute = Math.max( + this.scanOffset, + this.getText().length - FRESH_MATCH_TAIL_SLACK, + ); + const immediate = this.consumeFreshPendingRegex(pattern, { minFreshStartAbsolute }); + if (immediate !== null) { + this.advanceScanOffset(immediate.endOffset); + return Promise.resolve(immediate.value); + } + + return this.waitForWithMatcher({ + pattern, + timeoutMs, + shouldAbort, + consumeFreshMatch: () => this.consumeFreshPendingRegex(pattern, { minFreshStartAbsolute }), + timeoutLabel: "waitFor", + }); + } + const immediate = this.consumeFreshPendingMatch(pattern); if (immediate !== null) { this.advanceScanOffset(immediate.endOffset); @@ -267,10 +540,48 @@ class SessionOutputBuffer { }); } + waitForText(text, timeoutMs = 30000, shouldAbort) { + const immediate = this.consumeFreshPendingText(text); + if (immediate !== null) { + this.advanceScanOffset(immediate.endOffset); + return Promise.resolve(immediate.value); + } + + return this.waitForWithMatcher({ + pattern: text, + timeoutMs, + shouldAbort, + consumeFreshMatch: () => this.consumeFreshPendingText(text), + timeoutLabel: "waitForText", + }); + } + + waitForRegex(pattern, timeoutMs = 30000, shouldAbort) { + const minFreshStartAbsolute = Math.max( + this.scanOffset, + this.getText().length - FRESH_MATCH_TAIL_SLACK, + ); + const immediate = this.consumeFreshPendingRegex(pattern, { minFreshStartAbsolute }); + if (immediate !== null) { + this.advanceScanOffset(immediate.endOffset); + return Promise.resolve(immediate.value); + } + + return this.waitForWithMatcher({ + pattern, + timeoutMs, + shouldAbort, + consumeFreshMatch: () => this.consumeFreshPendingRegex(pattern, { minFreshStartAbsolute }), + timeoutLabel: "waitForRegex", + }); + } + abortWaiters(reason = "Script stopped") { for (const waiter of this.waiters) { clearTimeout(waiter.timer); if (waiter.abortInterval) clearInterval(waiter.abortInterval); + if (waiter.custom?.abortInterval) clearInterval(waiter.custom.abortInterval); + if (waiter.custom?.interval) clearInterval(waiter.custom.interval); waiter.reject?.(new Error(reason)); } this.waiters = []; @@ -357,6 +668,9 @@ class SessionOutputBuffer { dispose() { for (const waiter of this.waiters) { clearTimeout(waiter.timer); + if (waiter.abortInterval) clearInterval(waiter.abortInterval); + if (waiter.custom?.abortInterval) clearInterval(waiter.custom.abortInterval); + if (waiter.custom?.interval) clearInterval(waiter.custom.interval); waiter.reject?.(new Error("Session output buffer disposed")); } this.waiters = []; diff --git a/electron/scripts/sessionOutputBuffer.test.cjs b/electron/scripts/sessionOutputBuffer.test.cjs index d11f181a8..c7a237d48 100644 --- a/electron/scripts/sessionOutputBuffer.test.cjs +++ b/electron/scripts/sessionOutputBuffer.test.cjs @@ -14,6 +14,13 @@ test("tryMatch supports slash-delimited regex patterns", () => { assert.equal(tryMatch("sudo password:", "/password/i"), "password"); }); +test("tryMatch keeps wildcard-looking strings literal", () => { + assert.equal( + tryMatch("literal .* [broken", ".* [broken"), + ".* [broken", + ); +}); + test("tryMatch accepts RegExp objects from an isolated vm context", () => { const vm = require("node:vm"); const sandbox = {}; @@ -36,6 +43,226 @@ test("SessionOutputBuffer waitFor resolves root shell prompt", async () => { assert.equal(await pending, "# "); }); +test("SessionOutputBuffer waitForRegex resolves regex source strings across line breaks", async () => { + const buffer = new SessionOutputBuffer("s1"); + const pending = buffer.waitForRegex(".*SSH资源.*登录方式.*", 1000); + buffer.append("1. SSH资源\n请选择SSH资源\n'zxadmin'登录方式:"); + assert.equal(await pending, "1. SSH资源\n请选择SSH资源\n'zxadmin'登录方式:"); +}); + +test("SessionOutputBuffer waitFor treats wildcard-looking strings as literal text", async () => { + const buffer = new SessionOutputBuffer("s1"); + const pending = buffer.waitFor(".*SSH资源.*登录方式.*", 200); + let resolvedEarly = false; + void pending.then(() => { + resolvedEarly = true; + }); + + buffer.append("1. SSH资源\n请选择SSH资源\n'zxadmin'登录方式:"); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(resolvedEarly, false); + + buffer.append("\n.*SSH资源.*登录方式.*"); + assert.equal(await pending, ".*SSH资源.*登录方式.*"); +}); + +test("SessionOutputBuffer waitFor preserves slash regex dot behavior", async () => { + const buffer = new SessionOutputBuffer("s1"); + const pending = buffer.waitFor("/BEGIN.*END/", 200); + let resolvedEarly = false; + void pending.then(() => { + resolvedEarly = true; + }); + + buffer.append("BEGIN\nEND"); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(resolvedEarly, false); + + buffer.append("\nBEGIN END"); + assert.equal(await pending, "BEGIN END"); +}); + +test("SessionOutputBuffer waitFor handles invalid-regex-looking strings literally", async () => { + const buffer = new SessionOutputBuffer("s1"); + const pending = buffer.waitFor("literal .* [broken", 1000); + buffer.append("literal .* [broken"); + assert.equal(await pending, "literal .* [broken"); +}); + +test("SessionOutputBuffer waitForRegex resolves simple source strings immediately", async () => { + const buffer = new SessionOutputBuffer("s1"); + buffer.append("READY"); + assert.equal(await buffer.waitForRegex("READY", 1000), "READY"); +}); + +test("SessionOutputBuffer waitForRegex resolves simple source strings after append", async () => { + const buffer = new SessionOutputBuffer("s1"); + const pending = buffer.waitForRegex("READY", 1000); + buffer.append("READY"); + assert.equal(await pending, "READY"); +}); + +test("SessionOutputBuffer waitForText keeps strings literal", async () => { + const buffer = new SessionOutputBuffer("s1"); + const pending = buffer.waitForText("资源'[Empty]'账户:", 1000); + buffer.append("资源'[Empty]'账户:"); + assert.equal(await pending, "资源'[Empty]'账户:"); +}); + +test("SessionOutputBuffer waitForText treats wildcard-looking strings as literal text", async () => { + const buffer = new SessionOutputBuffer("s1"); + const pending = buffer.waitForText("literal .* prompt", 200); + let resolvedEarly = false; + void pending.then(() => { + resolvedEarly = true; + }); + buffer.append("literal abc prompt"); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(resolvedEarly, false); + + buffer.append("\nliteral .* prompt"); + assert.equal(await pending, "literal .* prompt"); +}); + +test("SessionOutputBuffer waitForRegex does not treat stale edge-wildcard matches as fresh", async () => { + const buffer = new SessionOutputBuffer("s1"); + buffer.append(`SSH资源${"x".repeat(600)}`); + + const pending = buffer.waitForRegex(".*SSH资源.*", 200); + let resolvedEarly = false; + void pending.then(() => { + resolvedEarly = true; + }); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(resolvedEarly, false); + + buffer.append("\nSSH资源"); + assert.equal(await pending, "\nSSH资源"); +}); + +test("SessionOutputBuffer waitForRegex preserves the full regex match value", async () => { + const buffer = new SessionOutputBuffer("s1"); + const pending = buffer.waitForRegex("Version: .*", 1000); + buffer.append("Version: 1.2.3 ready"); + assert.equal(await pending, "Version: 1.2.3 ready"); +}); + +test("SessionOutputBuffer waitForRegex applies stale protection to RegExp objects", async () => { + const buffer = new SessionOutputBuffer("s1"); + buffer.append(`SSH资源${"x".repeat(600)}`); + + const pending = buffer.waitForRegex(/.*SSH资源.*/s, 200); + let resolvedEarly = false; + void pending.then(() => { + resolvedEarly = true; + }); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(resolvedEarly, false); + + buffer.append("\nSSH资源"); + assert.equal(await pending, "\nSSH资源"); +}); + +test("SessionOutputBuffer waitForRegex handles lazy edge wildcards", async () => { + const buffer = new SessionOutputBuffer("s1"); + const pending = buffer.waitForRegex(/.*?READY.*?/s, 1000); + buffer.append("READY"); + assert.equal(await pending, "READY"); +}); + +test("SessionOutputBuffer waitForRegex applies stale protection to anchored edge wildcards", async () => { + const buffer = new SessionOutputBuffer("s1"); + buffer.append(`READY${"x".repeat(600)}`); + + const pending = buffer.waitForRegex(/^.*READY.*$/s, 200); + let resolvedEarly = false; + void pending.then(() => { + resolvedEarly = true; + }); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(resolvedEarly, false); + + buffer.append("\nREADY"); + assert.equal(await pending, "\nREADY"); +}); + +test("SessionOutputBuffer waitForRegex applies stale protection to edge plus wildcards", async () => { + const buffer = new SessionOutputBuffer("s1"); + buffer.append(`xREADYy${"x".repeat(600)}`); + + const pending = buffer.waitForRegex(/.+READY.+/s, 200); + let resolvedEarly = false; + void pending.then(() => { + resolvedEarly = true; + }); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(resolvedEarly, false); + + buffer.append("\nxREADYy"); + assert.equal(await pending, "\nxREADYy"); +}); + +test("SessionOutputBuffer waitForRegex accepts fresh core matches later in a full regex result", async () => { + const buffer = new SessionOutputBuffer("s1"); + const pending = buffer.waitForRegex(".*READY.*", 1000); + buffer.append(`READY${"x".repeat(600)}READY`); + assert.equal(await pending, `READY${"x".repeat(600)}READY`); +}); + +test("SessionOutputBuffer waitForRegex does not combine stale prefix with fresh suffix", async () => { + const buffer = new SessionOutputBuffer("s1"); + buffer.append(`SSH资源${"x".repeat(600)}`); + + const pending = buffer.waitForRegex(".*SSH资源.*登录方式.*", 1000); + let resolvedEarly = false; + void pending.then(() => { + resolvedEarly = true; + }); + + buffer.append("\n登录方式:"); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(resolvedEarly, false); + + buffer.append("\nSSH资源\n登录方式:"); + assert.equal(await pending, "\nSSH资源\n登录方式:"); +}); + +test("SessionOutputBuffer waitForRegex finds fresh match after rejected stale overlap", async () => { + const buffer = new SessionOutputBuffer("s1"); + buffer.append(`SSH资源${"x".repeat(600)}`); + + const pending = buffer.waitForRegex(".*SSH资源.*登录方式.*", 1000); + buffer.append("\n登录方式:\nSSH资源\n登录方式:"); + assert.equal(await pending, "\nSSH资源\n登录方式:"); +}); + +test("SessionOutputBuffer waitForRegex rejects preexisting stale prefix with tail suffix", async () => { + const buffer = new SessionOutputBuffer("s1"); + buffer.append(`SSH资源${"x".repeat(600)}登录方式:`); + + const pending = buffer.waitForRegex(".*SSH资源.*登录方式.*", 1000); + let resolvedEarly = false; + void pending.then(() => { + resolvedEarly = true; + }); + + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(resolvedEarly, false); + + buffer.append("\nSSH资源\n登录方式:"); + assert.equal(await pending, "\nSSH资源\n登录方式:"); +}); + +test("SessionOutputBuffer waitForRegex does not loop forever on stale zero-length matches", async () => { + const buffer = new SessionOutputBuffer("s1"); + buffer.append(`READY${"x".repeat(600)}`); + + await assert.rejects( + buffer.waitForRegex(/(?=READY)/, 50), + /waitForRegex timed out/, + ); +}); + test("shell prompt regex matches root and user prompts", () => { assert.match("root@VM-4-16-ubuntu:~# ", SHELL_PROMPT_END_REGEX); assert.match("user@host:~$ ", SHELL_PROMPT_END_REGEX); @@ -179,9 +406,11 @@ test("stepsToJavaScript generates sendLine and waitForPrompt steps", () => { const code = stepsToJavaScript([ { type: "waitForPrompt", timeoutMs: 30000 }, { type: "send", value: "ls -la" }, + { type: "waitFor", value: "DONE", timeoutMs: 5000 }, { type: "waitForPrompt", timeoutMs: 30000 }, ], "2026-06-27"); assert.match(code, /sendLine\("ls -la"\)/); + assert.match(code, /waitForText\("DONE", 5000\)/); assert.match(code, /waitForPrompt\(30000\)/); - assert.doesNotMatch(code, /waitFor\("\$ "/); + assert.doesNotMatch(code, /waitFor\("DONE"/); }); diff --git a/electron/shared/vaultAgentGuidance.cjs b/electron/shared/vaultAgentGuidance.cjs index f682276e9..e0ea58222 100644 --- a/electron/shared/vaultAgentGuidance.cjs +++ b/electron/shared/vaultAgentGuidance.cjs @@ -18,7 +18,7 @@ const VAULT_HOSTS_VS_NOTES_GUIDANCE = const VAULT_SCRIPTS_GUIDANCE = "Snippets vs automation scripts: snippets_* for shell command text (optional {{variables}}). " - + "scripts_* for nct JavaScript automation (await nct.screen.sendLine, waitFor, dialogs). " + + "scripts_* for nct JavaScript automation (await nct.screen.sendLine, waitForText/waitForRegex, dialogs). " + "Call scripts_reference before authoring scripts. scripts_run with wait=true blocks until completion; " + "use scripts_runs_list / scripts_run_stop / scripts_run_pause / scripts_run_resume for lifecycle. " + "Triggers: manual, onConnect (runs after connect), onOutput (regex triggerPattern). " diff --git a/electron/shared/vaultAgentGuidance.test.cjs b/electron/shared/vaultAgentGuidance.test.cjs index 236c36180..2d0f48a5b 100644 --- a/electron/shared/vaultAgentGuidance.test.cjs +++ b/electron/shared/vaultAgentGuidance.test.cjs @@ -5,6 +5,7 @@ const assert = require("node:assert/strict"); const { VAULT_HOSTS_VS_NOTES_GUIDANCE, + VAULT_SCRIPTS_GUIDANCE, appendVaultAgentGuidance, } = require("./vaultAgentGuidance.cjs"); @@ -29,3 +30,8 @@ test("appendVaultAgentGuidance appends guidance once", () => { const twice = appendVaultAgentGuidance(once); assert.equal(twice, once); }); + +test("VAULT_SCRIPTS_GUIDANCE prefers explicit wait APIs", () => { + assert.match(VAULT_SCRIPTS_GUIDANCE, /waitForText\/waitForRegex/); + assert.doesNotMatch(VAULT_SCRIPTS_GUIDANCE, /sendLine,\s*waitFor,\s*dialogs/); +}); diff --git a/infrastructure/ai/cattyAgent/systemPrompt.test.ts b/infrastructure/ai/cattyAgent/systemPrompt.test.ts index 51257fed1..c231b5c54 100644 --- a/infrastructure/ai/cattyAgent/systemPrompt.test.ts +++ b/infrastructure/ai/cattyAgent/systemPrompt.test.ts @@ -16,3 +16,15 @@ test('system prompt tells Catty how to import unknown attached host lists safely assert.match(prompt, /tool_output_read/i); assert.match(prompt, /compressed|truncated/i); }); + +test('system prompt prefers explicit script wait APIs', () => { + const prompt = buildSystemPrompt({ + scopeType: 'terminal', + hosts: [], + permissionMode: 'confirm', + }); + + assert.match(prompt, /waitForText/); + assert.match(prompt, /waitForRegex/); + assert.doesNotMatch(prompt, /sendLine`,\s*`waitFor`,\s*dialogs/); +}); diff --git a/infrastructure/ai/cattyAgent/systemPrompt.ts b/infrastructure/ai/cattyAgent/systemPrompt.ts index 45dc95a49..61f638773 100644 --- a/infrastructure/ai/cattyAgent/systemPrompt.ts +++ b/infrastructure/ai/cattyAgent/systemPrompt.ts @@ -59,7 +59,7 @@ ${permissionRules} **Vault → Notes (sidebar markdown docs):** When the user explicitly wants documentation saved to **Vault → Notes** (the notes sidebar / 保险箱笔记), use \`vault_notes_create\` or \`vault_notes_update\` — **not** \`host_notes_set\` (Host Details only) and **not** as a substitute for creating a host. - **Snippets vs automation scripts:** Use \`snippets_*\` for shell command text (paste/execute with optional \`{{variables}}\`). Use \`scripts_*\` for multi-step terminal automation written in JavaScript with the \`nct.*\` API (\`await nct.screen.sendLine\`, \`waitFor\`, dialogs, progress). Call \`scripts_reference\` before authoring or editing scripts. Run scripts with \`scripts_run\` (set \`wait: true\` to block until done); use \`scripts_runs_list\`, \`scripts_run_stop\`, \`scripts_run_pause\`, and \`scripts_run_resume\` for lifecycle control. Create/update/delete vault entries with \`snippets_create/update/delete\` (any kind) or \`scripts_create/update/delete\` (scripts only). + **Snippets vs automation scripts:** Use \`snippets_*\` for shell command text (paste/execute with optional \`{{variables}}\`). Use \`scripts_*\` for multi-step terminal automation written in JavaScript with the \`nct.*\` API (\`await nct.screen.sendLine\`, \`waitForText\` / \`waitForRegex\`, dialogs, progress). Call \`scripts_reference\` before authoring or editing scripts. Run scripts with \`scripts_run\` (set \`wait: true\` to block until done); use \`scripts_runs_list\`, \`scripts_run_stop\`, \`scripts_run_pause\`, and \`scripts_run_resume\` for lifecycle control. Create/update/delete vault entries with \`snippets_create/update/delete\` (any kind) or \`scripts_create/update/delete\` (scripts only). **Script triggers and hosts:** \`trigger: manual\` runs on demand; \`onConnect\` runs after SSH connect (global \`targetsAllHosts\` scripts first, then per-host \`connectScriptIds\` queue); \`onOutput\` runs when terminal output matches \`triggerPattern\` (regex). Link scripts to hosts with \`scripts_targets_set\` or manage per-host connect order with \`host_connect_scripts_list\` / \`host_connect_scripts_set\`. diff --git a/infrastructure/scripts/nctMonacoCompletion.ts b/infrastructure/scripts/nctMonacoCompletion.ts index ccf1dbe78..7ad6bc58a 100644 --- a/infrastructure/scripts/nctMonacoCompletion.ts +++ b/infrastructure/scripts/nctMonacoCompletion.ts @@ -5,15 +5,31 @@ type CompletionDisposable = { dispose: () => void }; const NCT_API_COMPLETIONS = [ { label: 'nct.screen.waitForPrompt', + sortText: 'nct.screen.waitFor.00.prompt', insertText: 'await nct.screen.waitForPrompt(${1:30000});', detail: 'Wait for shell prompt', documentation: 'Wait until an interactive shell prompt appears (# for root, $ for regular user).', }, + { + label: 'nct.screen.waitForText', + sortText: 'nct.screen.waitFor.01.text', + insertText: "await nct.screen.waitForText('${1:text}', ${2:30000});", + detail: 'Wait for literal text', + documentation: 'Wait until the exact text appears in session output. Regex characters are treated as normal text.', + }, + { + label: 'nct.screen.waitForRegex', + sortText: 'nct.screen.waitFor.02.regex', + insertText: "await nct.screen.waitForRegex('${1:pattern}', ${2:30000});", + detail: 'Wait for regex match', + documentation: 'Wait until session output matches a regular expression. String patterns use dotAll matching for multiline output.', + }, { label: 'nct.screen.waitFor', - insertText: "await nct.screen.waitFor('${1:pattern}', ${2:30000});", - detail: 'Wait for terminal output', - documentation: 'Wait until the session output matches a literal string or /regex/flags pattern.', + sortText: 'nct.screen.waitFor.03.legacy', + insertText: "await nct.screen.waitFor('${1:text}', ${2:30000});", + detail: 'Wait for terminal output (legacy)', + documentation: 'Compatibility helper. Plain string patterns are literal; legacy /regex/flags strings still work, but prefer waitForText for text or waitForRegex for regular expressions.', }, { label: 'nct.screen.waitForAny', @@ -162,6 +178,7 @@ export function registerNctMonacoCompletionProvider(monaco: Monaco): CompletionD insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, detail: item.detail, documentation: item.documentation, + sortText: item.sortText ?? item.label, range, }));