fix: 发布 1.1.47,演练台环境适配与首次用户须知。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
叫我小杨同学andCursor committed 2026-10-02 13:55:13 +08:00
1 parent 81c48bf465
commit b7c14005c3
13 files changed
+522 -297

No files matched your search

+168 -4
View File
@@ -118,6 +118,11 @@ export function resetPathMemo() {
for (const slot of Object.keys(memo)) memo[slot] = { ready: false, value: null };
}
export function clearDesktopLocateCache() {
try { desktop.clearDesktopLocateCache(); } catch { /* ignore */ }
resetPathMemo();
}
function isFile(fp) {
try {
if (desktop.isAsarSealedPath(fp)) return false;
@@ -1630,12 +1635,30 @@ export function sealedAsarHandoff(input = {}) {
const surface = input.surface ?? detectSurface(input);
if (adapterFor(surface) !== "desktop") return null;
const hinted = input.execPath;
const exe = hinted && desktop.isDesktopExecutable(hinted)
let exe = hinted && desktop.isDesktopExecutable(hinted)
? path.normalize(hinted)
: desktop.findDesktopAppExecutable(input);
if (!exe || !desktop.isOfficialHarnessExecutable(exe)) return null;
const asar = desktop.appAsarPath(exe);
if (!asarArchiveIsFile(asar)) return null;
const resourcesPath = input.resourcesPath ?? process.resourcesPath;
let asar = exe ? desktop.appAsarPath(exe) : "";
if (!asarArchiveIsFile(asar) && resourcesPath) {
const candidate = path.join(path.normalize(resourcesPath), "app.asar");
if (asarArchiveIsFile(candidate)) {
asar = candidate;
if (!exe) {
exe = desktop.findDesktopAppExecutable({ ...input, resourcesPath })
|| (desktop.isDesktopExecutable(process.execPath) ? path.normalize(process.execPath) : "")
|| path.normalize(process.execPath);
}
}
}
if (!exe || !asarArchiveIsFile(asar)) return null;
// 官方密封包:已知 exe 名,或当前进程 resources 里就有 app.asar。
if (
!desktop.isOfficialHarnessExecutable(exe)
&& !(resourcesPath && asarArchiveIsFile(path.join(path.normalize(resourcesPath), "app.asar")))
) {
return null;
}
return { exe, asar, swapAsar: true };
}
@@ -3706,6 +3729,144 @@ const NEW_TOOL_PATCHES = [
],
markers: ["[dsh-purge] guard undefined content"],
},
{
id: 69,
name: "MODEL_STREAM_RELEASE",
layer: "代码",
layer_en: "Code",
desc: "deepseek-flash 恢复官方 in-history,并撤掉会打成 TRANSPORT 的独立连接补丁 / restore official in-history and remove the transport-breaking socket patch",
file: ["llm-deepseek"],
optional: true,
skipIfMarked: true,
forbid: [
"[dsh-purge] one connection per model request",
"[dsh-purge] release model socket",
"[dsh-purge] drop the model socket",
],
replacements: [
{
pattern:
"\t\t\t\tsignal.throwIfAborted();\n" +
"\t\t\t\tconst betas = [...fileIds !== void 0 && fileIds.size > 0 ? [MESSAGES_FILES_BETA] : [], ...body.messages.some((message) => message.content.some((block) => block.type === \"tool_addition\" || block.type === \"tool_removal\")) ? [MESSAGES_TOOL_CHANGES_BETA] : []];\n" +
"\t\t\t\tlet streamAgent; // [dsh-purge] one connection per model request\n" +
"\t\t\t\ttry {\n" +
"\t\t\t\t\tconst undici = await import(\"undici\");\n" +
"\t\t\t\t\tif (typeof undici.Agent === \"function\") streamAgent = new undici.Agent({\n" +
"\t\t\t\t\t\tconnections: 1,\n" +
"\t\t\t\t\t\tpipelining: 0,\n" +
"\t\t\t\t\t\tkeepAliveTimeout: 1,\n" +
"\t\t\t\t\t\tkeepAliveMaxTimeout: 1,\n" +
"\t\t\t\t\t\tallowH2: true\n" +
"\t\t\t\t\t});\n" +
"\t\t\t\t} catch (_noUndici) {}\n" +
"\t\t\t\ttry {\n" +
"\t\t\t\t\tconst response = await fetch(`${messagesApiRoot(connection.baseURL)}/messages`, {\n" +
"\t\t\t\t\t\tmethod: \"POST\",\n" +
"\t\t\t\t\t\tsignal,\n" +
"\t\t\t\t\t\tbody: extensions.payload,\n" +
"\t\t\t\t\t\tredirect: \"error\",\n" +
"\t\t\t\t\t\t...streamAgent ? { dispatcher: streamAgent } : {},\n" +
"\t\t\t\t\t\theaders: {\n" +
"\t\t\t\t\t\t\t...attributionHeaders(),\n" +
"\t\t\t\t\t\t\t\"content-type\": \"application/json\",\n" +
"\t\t\t\t\t\t\t\"accept\": \"text/event-stream\",\n" +
"\t\t\t\t\t\t\t...auth.headers,\n" +
"\t\t\t\t\t\t\t\"anthropic-version\": \"2023-06-01\",\n" +
"\t\t\t\t\t\t\t...betas.length === 0 ? {} : { \"anthropic-beta\": betas.join(\",\") },\n" +
"\t\t\t\t\t\t\t\"x-deepseek-harness-user-id\": this.dependencies.resolveUserId(),\n" +
"\t\t\t\t\t\t\t...options.sessionId === void 0 ? {} : { \"x-deepseek-harness-session-id\": String(options.sessionId) },\n" +
"\t\t\t\t\t\t\t...options.purpose === \"compaction\" ? { \"x-deepseek-harness-compact\": \"1\" } : {}\n" +
"\t\t\t\t\t\t}\n" +
"\t\t\t\t\t});\n" +
"\t\t\t\t\tif (!response.ok) {\n" +
"\t\t\t\t\t\tconst text = await response.text();\n" +
"\t\t\t\t\t\tlet raw;\n" +
"\t\t\t\t\t\ttry {\n" +
"\t\t\t\t\t\t\traw = JSON.parse(text);\n" +
"\t\t\t\t\t\t} catch (_nonJsonGatewayError) {}\n" +
"\t\t\t\t\t\tconst detail = providerErrorDetail(raw);\n" +
"\t\t\t\t\t\tif (await files.retry(detail)) continue;\n" +
"\t\t\t\t\t\tconst failure = providerError(raw, response.status, response.headers);\n" +
"\t\t\t\t\t\tthrow new LlmError(files.errorMessage(response.status, failure.message, detail), failure.code, {\n" +
"\t\t\t\t\t\t\t...failure.failure,\n" +
"\t\t\t\t\t\t\tcause: new Error(text)\n" +
"\t\t\t\t\t\t});\n" +
"\t\t\t\t\t}\n" +
"\t\t\t\t\tawait extensions.accept();\n" +
"\t\t\t\t\tif (response.body === null) throw new LlmError(\"DeepSeek Messages returned no response body\", \"EMPTY_RESPONSE\");\n" +
"\t\t\t\t\tyield* translate(parseSse(response.body, activity), options.model);\n" +
"\t\t\t\t\treturn;\n" +
"\t\t\t\t} finally {\n" +
"\t\t\t\t\ttry {\n" +
"\t\t\t\t\t\tconst closed = streamAgent?.destroy();\n" +
"\t\t\t\t\t\tif (closed && typeof closed.catch === \"function\") closed.catch(() => {});\n" +
"\t\t\t\t\t} catch { /* [dsh-purge] release model socket */ }\n" +
"\t\t\t\t}",
replace:
"\t\t\t\tsignal.throwIfAborted();\n" +
"\t\t\t\tconst betas = [...fileIds !== void 0 && fileIds.size > 0 ? [MESSAGES_FILES_BETA] : [], ...body.messages.some((message) => message.content.some((block) => block.type === \"tool_addition\" || block.type === \"tool_removal\")) ? [MESSAGES_TOOL_CHANGES_BETA] : []];\n" +
"\t\t\t\tconst response = await fetch(`${messagesApiRoot(connection.baseURL)}/messages`, {\n" +
"\t\t\t\t\tmethod: \"POST\",\n" +
"\t\t\t\t\tsignal,\n" +
"\t\t\t\t\tbody: extensions.payload,\n" +
"\t\t\t\t\tredirect: \"error\",\n" +
"\t\t\t\t\theaders: {\n" +
"\t\t\t\t\t\t...attributionHeaders(),\n" +
"\t\t\t\t\t\t\"content-type\": \"application/json\",\n" +
"\t\t\t\t\t\t\"accept\": \"text/event-stream\",\n" +
"\t\t\t\t\t\t...auth.headers,\n" +
"\t\t\t\t\t\t\"anthropic-version\": \"2023-06-01\",\n" +
"\t\t\t\t\t\t...betas.length === 0 ? {} : { \"anthropic-beta\": betas.join(\",\") },\n" +
"\t\t\t\t\t\t\"x-deepseek-harness-user-id\": this.dependencies.resolveUserId(),\n" +
"\t\t\t\t\t\t...options.sessionId === void 0 ? {} : { \"x-deepseek-harness-session-id\": String(options.sessionId) },\n" +
"\t\t\t\t\t\t...options.purpose === \"compaction\" ? { \"x-deepseek-harness-compact\": \"1\" } : {}\n" +
"\t\t\t\t\t}\n" +
"\t\t\t\t});\n" +
"\t\t\t\tif (!response.ok) {\n" +
"\t\t\t\t\tconst text = await response.text();\n" +
"\t\t\t\t\tlet raw;\n" +
"\t\t\t\t\ttry {\n" +
"\t\t\t\t\t\traw = JSON.parse(text);\n" +
"\t\t\t\t\t} catch (_nonJsonGatewayError) {}\n" +
"\t\t\t\t\tconst detail = providerErrorDetail(raw);\n" +
"\t\t\t\t\tif (await files.retry(detail)) continue;\n" +
"\t\t\t\t\tconst failure = providerError(raw, response.status, response.headers);\n" +
"\t\t\t\t\tthrow new LlmError(files.errorMessage(response.status, failure.message, detail), failure.code, {\n" +
"\t\t\t\t\t\t...failure.failure,\n" +
"\t\t\t\t\t\tcause: new Error(text)\n" +
"\t\t\t\t\t});\n" +
"\t\t\t\t}\n" +
"\t\t\t\tawait extensions.accept();\n" +
"\t\t\t\tif (response.body === null) throw new LlmError(\"DeepSeek Messages returned no response body\", \"EMPTY_RESPONSE\");\n" +
"\t\t\t\tyield* translate(parseSse(response.body, activity), options.model);\n" +
"\t\t\t\treturn;",
},
{
pattern:
"\tid: \"deepseek-flash\",\n" +
"\tname: \"DeepSeek-V41-Flash\",\n" +
"\tcontextWindow: DEFAULT_CONTEXT_WINDOW,\n" +
"\tinputModalities: [\"text\", \"image\"],\n" +
"\ttoolUpdate: \"addition-only\"",
replace:
"\tid: \"deepseek-flash\",\n" +
"\tname: \"DeepSeek-V41-Flash\",\n" +
"\tcontextWindow: DEFAULT_CONTEXT_WINDOW,\n" +
"\tinputModalities: [\"text\", \"image\"],\n" +
"\tsystemPromptUpdate: \"in-history\", // [dsh-purge] deepseek-flash keeps in-history\n" +
"\ttoolUpdate: \"addition-only\"",
},
{
pattern:
"\tsystemPromptUpdate: \"in-history\",\n" +
"\ttoolUpdate: \"addition-only\"",
replace:
"\tsystemPromptUpdate: \"in-history\", // [dsh-purge] deepseek-flash keeps in-history\n" +
"\ttoolUpdate: \"addition-only\"",
},
],
markers: ["[dsh-purge] deepseek-flash keeps in-history"],
},
{
id: 56,
name: "REWIND_HIDE_CUT_ONLY",
@@ -4523,6 +4684,9 @@ export function targetFiles(aiBase, dshHome = findDshHome()) {
"deliverables-prompt": allExisting([
...nestedPkg(aiBase, "dsh-client-ui-deliverables", "lib", "index.js"),
]),
"llm-deepseek": allExisting([
...nestedPkg(aiBase, "dsh-llm-deepseek", "lib", "index.js"),
]),
"session": allExisting([
...nestedPkg(aiBase, "dsh-session", "lib", "index.js"),
]),
+28 -16
View File
@@ -80,11 +80,14 @@ export function looksLikeDesktopName(p) {
n.endsWith("/dsh desktop") ||
n.endsWith("/dsh desktop.app") ||
n.includes("dsh-desktop") ||
n.includes("/deepseek harness/") ||
n.includes("/deepseek-harness/") ||
n.includes("/deepseekharness") ||
/\/deepseek[\s._-]*harness(\/|$)/.test(n) ||
n.includes("/deepseek harness.app/") ||
n.endsWith("/deepseek harness.app") ||
/\/dsh desktop\.exe$/i.test(n) ||
/\/deepseek harness\.exe$/i.test(n) ||
/\/deepseek-harness\.exe$/i.test(n)
/\/deepseek[\s._-]*harness\.exe$/i.test(n)
);
}
@@ -101,12 +104,16 @@ function sameBase(name, expected) {
export function isDesktopExecutable(fp) {
const base = path.basename(String(fp || "")).toLowerCase();
return base === "dsh desktop.exe" || base === "dsh desktop" || OFFICIAL_HARNESS_BASES.has(base);
if (base === "dsh desktop.exe" || base === "dsh desktop") return true;
if (OFFICIAL_HARNESS_BASES.has(base)) return true;
return /^deepseek[\s._-]*harness(\.exe)?$/.test(base);
}
/** 只有官方 DeepSeek Harness 会把宿主封进 app.asar 并在「应用」时解开。第三方 DSH Desktop 不走这条。 */
export function isOfficialHarnessExecutable(fp) {
return OFFICIAL_HARNESS_BASES.has(path.basename(String(fp || "")).toLowerCase());
const base = path.basename(String(fp || "")).toLowerCase();
if (OFFICIAL_HARNESS_BASES.has(base)) return true;
return /^deepseek[\s._-]*harness(\.exe)?$/.test(base);
}
/** 某个安装目录下可能的 resources 文件夹(mac 大小写敏感盘要 Resources 和 resources 都试)。 */
@@ -267,7 +274,7 @@ function exeDirFromRegistryValue(value) {
let cachedRegistryDirs;
/** 从卸载登记读安装目录。盘符跟着用户安装位置,不写死。 */
export function registryInstallDirs() {
if (cachedRegistryDirs) return cachedRegistryDirs;
if (cachedRegistryDirs !== undefined) return cachedRegistryDirs;
if (process.platform !== "win32") {
cachedRegistryDirs = [];
return cachedRegistryDirs;
@@ -280,15 +287,14 @@ export function registryInstallDirs() {
timeout: 15000,
});
} catch {
cachedRegistryDirs = [];
return cachedRegistryDirs;
return [];
}
let rows = [];
try {
const parsed = JSON.parse(String(text || "").replace(/^\uFEFF/, "").trim() || "[]");
rows = Array.isArray(parsed) ? parsed : parsed ? [parsed] : [];
} catch {
rows = [];
return [];
}
const found = [];
for (const row of rows) {
@@ -371,7 +377,7 @@ if ($paths) { @($paths) | ConvertTo-Json -Compress }
let cachedRunningExes;
function runningOfficialExecutables() {
if (cachedRunningExes) return cachedRunningExes;
if (cachedRunningExes !== undefined) return cachedRunningExes;
if (process.platform !== "win32") {
cachedRunningExes = [];
return cachedRunningExes;
@@ -384,15 +390,15 @@ function runningOfficialExecutables() {
timeout: 15000,
});
} catch {
cachedRunningExes = [];
return cachedRunningExes;
// 探测失败不缓存空结果,否则整次进程都找不到正在跑的客户端。
return [];
}
let rows = [];
try {
const parsed = JSON.parse(String(text || "").replace(/^\uFEFF/, "").trim() || "[]");
rows = Array.isArray(parsed) ? parsed : parsed ? [parsed] : [];
} catch {
rows = [];
return [];
}
cachedRunningExes = uniquePaths(rows.map((item) => String(item || "").trim()).filter((fp) => isDesktopExecutable(fp) && isFile(fp)));
return cachedRunningExes;
@@ -426,7 +432,7 @@ if ($out.Count) { @($out) | ConvertTo-Json -Compress }
let cachedShortcutExes;
function shortcutOfficialExecutables() {
if (cachedShortcutExes) return cachedShortcutExes;
if (cachedShortcutExes !== undefined) return cachedShortcutExes;
if (process.platform !== "win32") {
cachedShortcutExes = [];
return cachedShortcutExes;
@@ -439,20 +445,26 @@ function shortcutOfficialExecutables() {
timeout: 15000,
});
} catch {
cachedShortcutExes = [];
return cachedShortcutExes;
return [];
}
let rows = [];
try {
const parsed = JSON.parse(String(text || "").replace(/^\uFEFF/, "").trim() || "[]");
rows = Array.isArray(parsed) ? parsed : parsed ? [parsed] : [];
} catch {
rows = [];
return [];
}
cachedShortcutExes = uniquePaths(rows.map((item) => String(item || "").trim()).filter((fp) => isDesktopExecutable(fp) && isFile(fp)));
return cachedShortcutExes;
}
/** 点「应用」前清掉失败的空缓存,重新找本机 exe。 */
export function clearDesktopLocateCache() {
cachedRunningExes = undefined;
cachedShortcutExes = undefined;
cachedRegistryDirs = undefined;
}
function extraDiscoveredInstallDirs(env = process.env) {
return uniquePaths([
...homeSiblingInstalls(env),
+2
View File
@@ -468,6 +468,7 @@ async function handlePurgeCommand(rawInput, config) {
case "apply":
case "a": {
core.applyRuntimeEnv();
core.clearDesktopLocateCache();
const scrubbed = core.sanitizeDesktopCommandRuntimes();
const state = await core.gatherState();
let handoff = null;
@@ -1288,6 +1289,7 @@ function installWebServer(ctx, cfg) {
}
try {
core.applyRuntimeEnv();
core.clearDesktopLocateCache();
const scrubbed = core.sanitizeDesktopCommandRuntimes();
const state = await core.gatherState();
let handoff = null;
+6
View File
@@ -2462,6 +2462,11 @@ window.__ModuleLoader__.load({
/* 老 host 还没有知识库接口:讲清怎么恢复,别让人对着 "engagement required" 发懵 */
? '知识库接口由 host 侧提供,当前宿主还是旧进程 —— 请完全退出后重新打开(官方 exe / 社区版 / dsh web 任一),再刷新页面。'
: err) : null,
!err && data && data.dbPath
? h('div', { className: 'rt-foot', style: { marginBottom: 6, fontSize: 11 } },
'知识库:' + data.dbPath
+ (data.root ? '(根目录 ' + data.root + ')' : ''))
: null,
h('div', { className: 'rt-table' },
(() => {
if (!grouped) return items.map(card)
@@ -2526,6 +2531,7 @@ window.__ModuleLoader__.load({
: '知识库还是空的。本机也还没有 nuclei 模板库 —— 在演练机上跑 setup.sh 或 `nuclei -update-templates`,装好后这里会出现「本机模板 N」。'))),
h('div', { style: { marginTop: 6, fontSize: 12 } },
'打 Nday/1day 的标准顺序:① redteam_poc_search 先查这里(顺带搜本机 nuclei 模板库)→ ② 都没有就互联网搜索(web_search / GitHub / ExploitDB / 厂商公告)或自己手搓 → ③ 在真实目标上验证有效后 redteam_poc_add 回填,后面的靶标直接就能用。'),
data.dbPath ? h('div', { style: { marginTop: 6, fontSize: 11 }, className: 'rt-mono' }, '知识库文件:' + data.dbPath) : null,
tpl.dir ? h('div', { style: { marginTop: 6, fontSize: 11 }, className: 'rt-mono' }, '模板目录:' + tpl.dir) : null)
: null),
h('div', { className: 'rt-foot' },
+17 -2
View File
@@ -45,6 +45,9 @@ import {
/* 内部辅助:原本就是 core.js 里的模块级函数,拆分后由 score-rules.js 提供 */
normalizePort, targetAuthority, systemKeyOf, pickBestHit, legacyCapGroup, targetHasIpv6Host,
} from './score-rules.js'
import {
platformSummary, savePlatformConfig, assignToolkitFolder, loadPlatformConfig, nucleiTemplatesDirOf,
} from './platform-config.js'
/* 再导出:core.js 的对外导出面与拆分前完全一致(调用方零改动) */
export {
@@ -739,9 +742,9 @@ export function dispatch(store, req = {}) {
const templates = q
? store.searchTemplates(q, Math.min(Number(req.templateLimit) || 20, 100))
: { dir: store.nucleiTemplatesDir() || null, total: store.templateStats().total, items: [] }
return { ok: true, items, stats: store.pocStats(), templates }
return { ok: true, items, stats: store.pocStats(), templates, dbPath: store.knowledgePath(), root: store.root }
}
if (op === 'pocList') return { ok: true, items: store.searchPocs(req), stats: store.pocStats() }
if (op === 'pocList') return { ok: true, items: store.searchPocs(req), stats: store.pocStats(), dbPath: store.knowledgePath(), root: store.root }
if (op === 'templateSearch') return Object.assign({ ok: true }, store.searchTemplates(req.q, Math.min(Number(req.limit) || 40, 200)))
if (op === 'templateStats') return { ok: true, stats: store.templateStats() }
if (op === 'pocGet') return Object.assign({ ok: true }, store.getPoc(req.id !== undefined ? req.id : req.code))
@@ -750,6 +753,13 @@ export function dispatch(store, req = {}) {
if (op === 'pocDelete') return Object.assign({ ok: true }, store.deletePoc(req.id !== undefined ? req.id : req.code))
if (op === 'pocUse') return Object.assign({ ok: true }, store.markPocUsed(req.id !== undefined ? req.id : req.code, req.used_on))
if (op === 'pocStats') return { ok: true, stats: store.pocStats() }
/* 环境适配:全局,不依赖靶标;面板 / CLI / 工具共用 */
if (op === 'platformConfigGet') return platformSummary(store.root)
if (op === 'platformConfigSave') {
savePlatformConfig(req.config || {}, store.root)
return platformSummary(store.root)
}
if (op === 'platformAssignToolkit') return assignToolkitFolder(req.dir, store.root)
/* 没选靶标时:提示词回内置默认;只读查询回空结果。不要抛英文 engagement required。 */
let id = typeof req.engagement === 'string' ? req.engagement.trim() : ''
if (!id && typeof store.activeEngagementId === 'function') id = store.activeEngagementId() || ''
@@ -3649,6 +3659,11 @@ export class RedteamStore {
/** 找本机 nuclei 模板目录(装了模板才有;找不到返回 undefined)。 */
nucleiTemplatesDir() {
/* 环境适配里手填/自动分配的路径优先(Windows 尤其依赖这一条) */
try {
const configured = nucleiTemplatesDirOf(loadPlatformConfig(this.root), this.root)
if (configured) return configured
} catch { /* 忽略配置读失败,继续默认探测 */ }
const candidates = [
join(this.root, 'toolkit', 'nuclei-templates'),
join(homedir(), '.local', 'nuclei-templates'),
+41 -9
View File
@@ -15,12 +15,22 @@
import { fileURLToPath } from 'node:url'
import { resolve, join } from 'node:path'
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, realpathSync } from 'node:fs'
import { homedir } from 'node:os'
import { spawn } from 'node:child_process'
import { dispatch, dispatchAsync } from './store-core.js'
/* 技能可用性判定与 redteam_preflight 共用同一份实现(环境变量 / 本机路径 / 占位符) */
import { checkSkill, summarizeSkills } from './skill-availability.js'
import { maxAgentsOf, maxAgentsSourceOf, saveMaxAgents, DEFAULT_MAX_AGENTS, MAX_AGENTS_LIMIT } from './settings.js'
import { loadPlatformConfig, mergeConfigEnv, redteamRoot, envAdaptStatus } from './platform-config.js'
import {
loadPlatformConfig, mergeConfigEnv, redteamRoot, envAdaptStatus,
platformSummary, savePlatformConfig, assignToolkitFolder,
} from './platform-config.js'
/** DSH_HOME:显式环境变量优先;Windows 上 HOME 常空,回退 homedir()。 */
function dshHomeOf() {
if (process.env.DSH_HOME) return process.env.DSH_HOME
return join(homedir(), '.dsh')
}
/**
* 本包自带技能目录候选。
@@ -29,7 +39,7 @@ import { loadPlatformConfig, mergeConfigEnv, redteamRoot, envAdaptStatus } from
* 不从 index.js 引 packagePaths,避免与 cordis 插件入口互相拖拽。
*/
function resolvePluginSkillsDir() {
const home = process.env.DSH_HOME || ''
const home = dshHomeOf()
const candidates = []
try {
const root = fileURLToPath(new URL('../..', import.meta.url))
@@ -38,12 +48,12 @@ function resolvePluginSkillsDir() {
try {
candidates.push(resolve(fileURLToPath(new URL('../../skills/redteam/', import.meta.url))))
} catch { /* ignore */ }
if (home) {
for (const profile of ['desktop', 'web', 'headless']) {
candidates.push(join(home, 'profiles', profile, 'node_modules', 'dsh-purge', 'skills', 'redteam'))
}
/* 不扫官方 $DSH_HOME/skills:技能只认本包 skills/redteam(与上游插件包内分发一致)。 */
/* installBundledSkills 落盘位置:包内路径失效时仍能列出技能 */
candidates.push(join(home, 'redteam', 'skills'))
for (const profile of ['desktop', 'web', 'headless']) {
candidates.push(join(home, 'profiles', profile, 'node_modules', 'dsh-purge', 'skills', 'redteam'))
}
/* 不扫官方 $DSH_HOME/skills:技能只认本包 / 同步副本(与上游插件包内分发一致)。 */
for (const raw of candidates) {
if (!raw) continue
try {
@@ -136,8 +146,25 @@ function profileDirOf(ctx) {
try {
if (typeof ctx.baseUrl === 'string' && ctx.baseUrl.length > 0) return ctx.baseUrl
} catch { /* 忽略 */ }
const home = process.env.DSH_HOME || join(process.env.HOME || '', '.dsh')
return join(home, 'profiles', 'web')
return join(dshHomeOf(), 'profiles', 'web')
}
/**
* 环境适配 op:面板 EnvTab 读写 `$DSH_HOME/redteam/config.json`。
* @returns JSON 结果,或 undefined 表示不是这个 op。
*/
function handlePlatformOp(store, request) {
const op = request && request.op
if (op !== 'platformConfigGet' && op !== 'platformConfigSave' && op !== 'platformAssignToolkit') {
return undefined
}
const root = (store && store.root) || redteamRoot()
if (op === 'platformConfigGet') return platformSummary(root)
if (op === 'platformConfigSave') {
savePlatformConfig(request.config || {}, root)
return platformSummary(root)
}
return assignToolkitFolder(request.dir, root)
}
/** 读 profile 的 package.json(依赖声明 + dsh.profile.bundles)。 */
@@ -847,6 +874,11 @@ export function apply(ctx) {
try {
const raw = await readBody(req)
const request = raw.trim() ? JSON.parse(raw) : {}
const platformResult = handlePlatformOp(store, request)
if (platformResult !== undefined) {
sendJson(res, 200, platformResult)
return
}
const agentsResult = await handleAgentsOp(ctx, request)
if (agentsResult !== undefined) {
sendJson(res, 200, agentsResult)
+28 -48
View File
@@ -340,13 +340,8 @@ export function wrapSessionDeriveMessages(session) {
if (!session || typeof session.deriveMessages !== "function" || session.__dshPurgeRewindDerive) return session;
const orig = session.deriveMessages.bind(session);
session.deriveMessages = function deriveMessagesWithoutRewind() {
let messages;
try {
messages = orig();
} catch {
// 回退后偶发 event.data.message.content 为空,官方 derive 读 .length 会直接炸掉。
return [];
}
// 抛错不能改成空数组。空历史仍会发出请求,界面停在进行中,模型没有可答的内容。
const messages = orig();
if (!Array.isArray(messages)) return [];
return messages.filter((message) => !isRewindDerivedMessage(message));
};
@@ -357,51 +352,36 @@ export function wrapSessionDeriveMessages(session) {
async function disarmRewoundSession(ctx, sessionId) {
if (!sessionId) return;
const controller = service(ctx, "sessionController");
const disarmOnce = async () => {
const agent = getAgent(ctx, sessionId);
try { agent?.inbox?.clear?.(); } catch { /* ignore */ }
try { ignoreSettled(agent?.cancel?.({ kind: "user" }, { keepInbox: false })); } catch { /* ignore */ }
const agent = getAgent(ctx, sessionId);
// 只停回退开始时还在跑的那一轮。延迟再 cancel 会把用户刚发出的下一句一起掐掉,界面停在进行中,请求发不出去。
const runningAbort = agent?.phase?.kind && agent.phase.kind !== "idle" ? agent.phase.abort : null;
if (runningAbort) {
try { ignoreSettled(agent.cancel({ kind: "user" }, { keepInbox: true })); } catch { /* ignore */ }
}
const ids = [];
try {
const log = await readSessionLog(ctx, sessionId);
ids.push(...pendingInboxInserts(log.events));
} catch { /* ignore */ }
try {
for (const message of [...(agent?.inbox?.nextTurn || []), ...(agent?.inbox?.nextStep || [])]) {
if (message?.id) ids.push(message.id);
}
} catch { /* ignore */ }
const seen = new Set();
for (const id of ids) {
if (!id || seen.has(id)) continue;
seen.add(id);
try {
await controller?.updateQueue?.({
sessionId,
itemId: id,
action: { kind: "remove" },
});
} catch { /* ignore */ }
}
try { agent?.inbox?.clear?.(); } catch { /* ignore */ }
if (agent?.status === "running") {
try { ignoreSettled(agent.cancel({ kind: "user" }, { keepInbox: false })); } catch { /* ignore */ }
}
};
await disarmOnce();
await sleep(20);
await disarmOnce();
const ids = [];
try {
const idle = getAgent(ctx, sessionId)?.whenIdle?.();
if (idle && typeof idle.then === "function") {
await Promise.race([idle, sleep(800)]);
const log = await readSessionLog(ctx, sessionId);
ids.push(...pendingInboxInserts(log.events));
} catch { /* ignore */ }
try {
for (const message of [...(agent?.inbox?.nextTurn || []), ...(agent?.inbox?.nextStep || [])]) {
if (message?.id) ids.push(message.id);
}
} catch { /* ignore */ }
await disarmOnce();
const seen = new Set();
for (const id of ids) {
if (!id || seen.has(id)) continue;
seen.add(id);
try {
await controller?.updateQueue?.({
sessionId,
itemId: id,
action: { kind: "remove" },
});
} catch { /* ignore */ }
}
}
export function invocationSessionId(invocation) {
+30 -8
View File
@@ -1,4 +1,5 @@
import path from "node:path";
import fs from "node:fs";
/** 当前已接线的宿主面。gui / tui 先能识别,适配仍回退 web。 */
export const SURFACES = Object.freeze(["web", "desktop", "gui", "tui"]);
@@ -18,9 +19,13 @@ function exeName(execPath) {
export function pathLooksDesktop(p) {
const n = slash(p);
if (!n) return false;
// 安装目录可能叫 "DeepSeek Harness" / "deepseek-harness",但源码仓库(monorepo)也叫这个名字 ——
// 所以只凭目录名不算,还必须带桌面安装形态(resources/、exe、.app/)。与 desktop.looksLikeDesktopName 对齐。
const harnessDir = n.includes("/deepseek harness/") || n.includes("/deepseek-harness/");
// 安装目录可能叫 "DeepSeek Harness" / "deepseek-harness" / "DeepseekHarnessDesktop"。
// 源码仓库也常带 deepseek-harness 名字,所以还要带 resources/、exe、.app/ 才算桌面安装。
const harnessDir =
n.includes("/deepseek harness/") ||
n.includes("/deepseek-harness/") ||
n.includes("/deepseekharness") ||
/\/deepseek[\s._-]*harness/.test(n);
return (
n.includes("/dsh desktop/") ||
n.includes("/dsh desktop.app/") ||
@@ -29,12 +34,28 @@ export function pathLooksDesktop(p) {
n.includes("/deepseek harness.app/") ||
(harnessDir && (n.includes("/resources/") || n.includes("/contents/resources/") || n.endsWith("/resources"))) ||
/\/dsh desktop\.exe$/i.test(n) ||
/\/deepseek[- ]harness\.exe$/i.test(n) ||
/\/deepseek[\s._-]*harness\.exe$/i.test(n) ||
n.endsWith("/host-process-entry.js") ||
n.endsWith("/desktop-cli.js")
);
}
function resourcesLookLikeDesktopInstall(resourcesPath) {
if (!resourcesPath) return false;
if (pathLooksDesktop(resourcesPath)) return true;
const n = slash(resourcesPath);
if (!(n.endsWith("/resources") || n.includes("/contents/resources"))) return false;
try {
const asar = path.join(resourcesPath, "app.asar");
if (fs.existsSync(asar) && fs.statSync(asar).isFile()) return true;
if (fs.existsSync(path.join(resourcesPath, "app", "dsh"))) return true;
if (fs.existsSync(path.join(resourcesPath, "app.asar.unpacked", "dsh"))) return true;
} catch {
/* ignore */
}
return false;
}
export function isDesktopSurface(input = {}) {
const env = input.env ?? process.env;
const forced = norm(env.DSH_SURFACE);
@@ -49,20 +70,21 @@ export function isDesktopSurface(input = {}) {
name === "deepseek harness.exe" ||
name === "deepseek-harness.exe" ||
name === "deepseek harness" ||
name === "deepseek-harness"
name === "deepseek-harness" ||
/^deepseek[\s._-]*harness(\.exe)?$/.test(name)
) return true;
if (pathLooksDesktop(execPath)) return true;
const resourcesPath = input.resourcesPath ?? process.resourcesPath;
if (pathLooksDesktop(resourcesPath)) return true;
if (resourcesLookLikeDesktopInstall(resourcesPath)) return true;
const argv = input.argv ?? process.argv;
if ((Array.isArray(argv) ? argv : []).some((arg) => pathLooksDesktop(arg))) return true;
const parentPort = input.parentPort !== undefined ? input.parentPort : process.parentPort;
if (parentPort && (pathLooksDesktop(execPath) || pathLooksDesktop(resourcesPath))) return true;
if (parentPort && (pathLooksDesktop(execPath) || resourcesLookLikeDesktopInstall(resourcesPath))) return true;
if (env.ELECTRON_RUN_AS_NODE && pathLooksDesktop(execPath)) return true;
if (env.ELECTRON_RUN_AS_NODE && (pathLooksDesktop(execPath) || resourcesLookLikeDesktopInstall(resourcesPath))) return true;
return false;
}