pi-web-ui 0.111.0 → 0.113.0
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/CHANGELOG.md +92 -2
- package/bin/frp-manager.mjs +9 -2
- package/bin/pi-web-ui.mjs +325 -45
- package/dist/server/agent-service-daemon.js +29 -4
- package/dist/server/agent-service.js +1527 -510
- package/dist/server/approval-audit.js +119 -0
- package/dist/server/approval-default-rules.js +4 -4
- package/dist/server/approval-rules.js +42 -17
- package/dist/server/attachment-store.js +8 -8
- package/dist/server/canvas/canvas-agent-tool.js +8 -0
- package/dist/server/canvas/canvas-orchestrator.js +128 -22
- package/dist/server/canvas/pstack-skills-data.js +498 -0
- package/dist/server/client-state.js +28 -0
- package/dist/server/delegate-mode.js +6 -3
- package/dist/server/delegate-task.js +18 -3
- package/dist/server/dispatch-domain-handlers.js +39 -11
- package/dist/server/dsh/dsh-agent-service.js +294 -15
- package/dist/server/dsh/dsh-serialize.js +1 -1
- package/dist/server/durable/durable-driver.js +112 -107
- package/dist/server/durable/durable-event-projector.js +253 -0
- package/dist/server/durable/durable-loader.js +1 -14
- package/dist/server/durable/durable-models.js +107 -0
- package/dist/server/durable/index.js +0 -4
- package/dist/server/engine-probe.js +111 -48
- package/dist/server/eval-tool.js +28 -3
- package/dist/server/goal-service.js +7 -0
- package/dist/server/index.js +371 -57
- package/dist/server/json-utils.js +57 -0
- package/dist/server/marker-service.js +8 -0
- package/dist/server/message-window.js +43 -10
- package/dist/server/model-admin.js +247 -163
- package/dist/server/model-resolver.js +66 -44
- package/dist/server/plan-manager.js +3 -6
- package/dist/server/plugin-api-catalog.js +1 -0
- package/dist/server/plugin-assets.js +238 -0
- package/dist/server/plugin-facilities.js +22 -0
- package/dist/server/plugin-ui-slots.js +1 -0
- package/dist/server/plugins.js +209 -11
- package/dist/server/preset-fields.js +25 -1
- package/dist/server/preset-share.js +5 -2
- package/dist/server/prompt-assembler.js +2 -1
- package/dist/server/prompt-composer.js +18 -8
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-utils.js +156 -0
- package/dist/server/remote-ssh-service.js +110 -12
- package/dist/server/sdk-builtin-extensions.js +85 -0
- package/dist/server/serialize.js +1 -1
- package/dist/server/server-config.js +66 -0
- package/dist/server/session-parser.js +49 -13
- package/dist/server/session-search.js +4 -3
- package/dist/server/settings-service.js +74 -53
- package/dist/server/setup-page.js +632 -0
- package/dist/server/skill-discovery.js +361 -59
- package/dist/server/skill-maintenance.js +231 -0
- package/dist/server/skill-tool.js +32 -3
- package/dist/server/soft-cap.js +30 -6
- package/dist/server/subagent-helpers.js +22 -1
- package/dist/server/subagent-notify.js +93 -0
- package/dist/server/subagent-security-gate.js +282 -0
- package/dist/server/subagent-templates.js +8 -0
- package/dist/server/subagents.js +390 -48
- package/dist/server/terminals.js +196 -8
- package/dist/server/text-quote.js +61 -0
- package/dist/server/tool-approval.js +63 -4
- package/dist/server/tool-guards.js +208 -0
- package/dist/server/tool-host-factories.js +48 -10
- package/dist/server/tool-manager.js +106 -28
- package/dist/server/tool-overrides.js +21 -11
- package/dist/server/universal/driver-base.js +8 -0
- package/dist/server/universal/drivers/claude-code.js +116 -7
- package/dist/server/universal/drivers/dsh-driver.js +3 -0
- package/dist/server/universal/index.js +0 -1
- package/dist/server/universal/universal-session.js +106 -10
- package/dist/server/worktree-service.js +189 -1
- package/docs/dsh-engine.md +1 -5
- package/package.json +1 -1
- package/plugin-sdk/client-utils.mjs +192 -5
- package/plugin-sdk/index.d.ts +63 -1
- package/plugin-sdk/index.mjs +94 -0
- package/plugin-sdk/package.json +5 -1
- package/plugins/catalog.json +21 -0
- package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-3wojLfLk.js} +2 -2
- package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
- package/web/dist/assets/index-BwL7qBh6.css +1 -0
- package/web/dist/index.html +11 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-B0ajS__T.js +0 -697
- package/web/dist/assets/index-BHik5WGG.css +0 -1
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
*
|
|
11
11
|
* 供 Claude Code CLI 驱动、DSH 引擎与 Pi 引擎统一调用,消除各引擎间的配置孤岛。
|
|
12
12
|
*/
|
|
13
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
13
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
14
14
|
import { homedir } from "node:os";
|
|
15
15
|
import { join } from "node:path";
|
|
16
16
|
function defaultAgentDir(agentDir) {
|
|
@@ -18,49 +18,8 @@ function defaultAgentDir(agentDir) {
|
|
|
18
18
|
? agentDir.trim()
|
|
19
19
|
: (process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"));
|
|
20
20
|
}
|
|
21
|
-
|
|
22
|
-
export
|
|
23
|
-
let out = "";
|
|
24
|
-
let inString = false;
|
|
25
|
-
let i = 0;
|
|
26
|
-
while (i < src.length) {
|
|
27
|
-
const c = src[i];
|
|
28
|
-
const next = src[i + 1];
|
|
29
|
-
if (inString) {
|
|
30
|
-
out += c;
|
|
31
|
-
if (c === "\\") {
|
|
32
|
-
out += next ?? "";
|
|
33
|
-
i += 2;
|
|
34
|
-
continue;
|
|
35
|
-
}
|
|
36
|
-
if (c === '"')
|
|
37
|
-
inString = false;
|
|
38
|
-
i++;
|
|
39
|
-
continue;
|
|
40
|
-
}
|
|
41
|
-
if (c === '"') {
|
|
42
|
-
inString = true;
|
|
43
|
-
out += c;
|
|
44
|
-
i++;
|
|
45
|
-
continue;
|
|
46
|
-
}
|
|
47
|
-
if (c === "/" && next === "/") {
|
|
48
|
-
while (i < src.length && src[i] !== "\n")
|
|
49
|
-
i++;
|
|
50
|
-
continue;
|
|
51
|
-
}
|
|
52
|
-
if (c === "/" && next === "*") {
|
|
53
|
-
i += 2;
|
|
54
|
-
while (i < src.length && !(src[i] === "*" && src[i + 1] === "/"))
|
|
55
|
-
i++;
|
|
56
|
-
i += 2;
|
|
57
|
-
continue;
|
|
58
|
-
}
|
|
59
|
-
out += c;
|
|
60
|
-
i++;
|
|
61
|
-
}
|
|
62
|
-
return out;
|
|
63
|
-
}
|
|
21
|
+
import { stripJsonComments, parseJsonWithComments } from "./json-utils.js";
|
|
22
|
+
export { stripJsonComments, parseJsonWithComments };
|
|
64
23
|
/** 读取并解析 models.json(容忍注释) */
|
|
65
24
|
export function readModelsJson(agentDir) {
|
|
66
25
|
const dir = defaultAgentDir(agentDir);
|
|
@@ -301,6 +260,69 @@ export function isProtocolSupportedByEngine(engine, api, providerId, modelId) {
|
|
|
301
260
|
}
|
|
302
261
|
return true;
|
|
303
262
|
}
|
|
263
|
+
/** 读取全局 settings.json */
|
|
264
|
+
export function readGlobalSettings(agentDir) {
|
|
265
|
+
const dir = defaultAgentDir(agentDir);
|
|
266
|
+
const filePath = join(dir, "settings.json");
|
|
267
|
+
if (!existsSync(filePath))
|
|
268
|
+
return {};
|
|
269
|
+
try {
|
|
270
|
+
const raw = readFileSync(filePath, "utf8");
|
|
271
|
+
return JSON.parse(stripJsonComments(raw));
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
return {};
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/** 获取特定模型在 settings.json 中的思考强度记忆或全局默认思考强度 */
|
|
278
|
+
export function getModelThinkingLevelFromSettings(modelId, agentDir) {
|
|
279
|
+
if (!modelId)
|
|
280
|
+
return undefined;
|
|
281
|
+
const settings = readGlobalSettings(agentDir);
|
|
282
|
+
const levels = settings.modelThinkingLevels;
|
|
283
|
+
if (levels && typeof levels === "object") {
|
|
284
|
+
// 1. 尝试全量匹配 "provider/model"
|
|
285
|
+
if (levels[modelId])
|
|
286
|
+
return levels[modelId];
|
|
287
|
+
// 2. 尝试裸 modelId 匹配
|
|
288
|
+
const slashIdx = modelId.indexOf("/");
|
|
289
|
+
const bareId = slashIdx >= 0 ? modelId.slice(slashIdx + 1) : modelId;
|
|
290
|
+
for (const [k, v] of Object.entries(levels)) {
|
|
291
|
+
if (k === bareId || k.endsWith(`/${bareId}`)) {
|
|
292
|
+
return v;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return settings.defaultThinkingLevel;
|
|
297
|
+
}
|
|
298
|
+
/** 保存特定模型的思考强度到 settings.json */
|
|
299
|
+
export function saveModelThinkingLevelToSettings(modelId, level, agentDir) {
|
|
300
|
+
if (!modelId || !level)
|
|
301
|
+
return;
|
|
302
|
+
const dir = defaultAgentDir(agentDir);
|
|
303
|
+
const filePath = join(dir, "settings.json");
|
|
304
|
+
try {
|
|
305
|
+
let current = {};
|
|
306
|
+
if (existsSync(filePath)) {
|
|
307
|
+
try {
|
|
308
|
+
current = JSON.parse(stripJsonComments(readFileSync(filePath, "utf8")));
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
/* start fresh */
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const existingLevels = (current.modelThinkingLevels && typeof current.modelThinkingLevels === "object"
|
|
315
|
+
? { ...current.modelThinkingLevels }
|
|
316
|
+
: {});
|
|
317
|
+
existingLevels[modelId] = level;
|
|
318
|
+
current.modelThinkingLevels = existingLevels;
|
|
319
|
+
const formatted = JSON.stringify(current, null, 2);
|
|
320
|
+
writeFileSync(filePath, formatted, "utf8");
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
/* best effort */
|
|
324
|
+
}
|
|
325
|
+
}
|
|
304
326
|
/**
|
|
305
327
|
* 结构化入参的协议校验重载包装(兼容既有调用点)。
|
|
306
328
|
*/
|
|
@@ -17,8 +17,8 @@
|
|
|
17
17
|
* - 运行时缓存(plansByConv):以会话槽位 conversationId 为主键,仅存活于进程内存,绝不落盘。
|
|
18
18
|
* - 历史文件清洗:严格过滤形如 /^c\d+$/ 的易变短 ID,防止服务重启后新会话被上一个会话的任务附体。
|
|
19
19
|
*/
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
20
|
+
import { readFileSync } from "node:fs";
|
|
21
|
+
import { writeJsonAtomicSync } from "./atomic-file.js";
|
|
22
22
|
const VALID_STATUSES = new Set(["pending", "in_progress", "done", "failed"]);
|
|
23
23
|
/** 判断是否为易变的临时 conversationId(如 c1, c2, c99 等)。此类短 ID 绝不入持久化文件。 */
|
|
24
24
|
function isEphemeralConvId(id) {
|
|
@@ -61,7 +61,6 @@ export class PlanManager {
|
|
|
61
61
|
if (!this.filePath)
|
|
62
62
|
return;
|
|
63
63
|
try {
|
|
64
|
-
mkdirSync(dirname(this.filePath), { recursive: true });
|
|
65
64
|
const obj = {};
|
|
66
65
|
for (const [k, v] of this.plansBySession.entries()) {
|
|
67
66
|
// 双重防护:临时 conversationId 绝不落盘
|
|
@@ -69,9 +68,7 @@ export class PlanManager {
|
|
|
69
68
|
continue;
|
|
70
69
|
obj[k] = v;
|
|
71
70
|
}
|
|
72
|
-
|
|
73
|
-
writeFileSync(tmp, JSON.stringify(obj, null, 2), "utf8");
|
|
74
|
-
renameSync(tmp, this.filePath);
|
|
71
|
+
writeJsonAtomicSync(this.filePath, obj);
|
|
75
72
|
}
|
|
76
73
|
catch {
|
|
77
74
|
// 持久化失败绝不阻断主流程
|
|
@@ -14,6 +14,7 @@ export const SLOT_EXAMPLES = {
|
|
|
14
14
|
"contextmenu.project": `{ "ui": { "contextmenu.project": [{ "id": "m", "label": "项目菜单", "kind": "action", "action": "my:m" }] } }`,
|
|
15
15
|
"contextmenu.file": `{ "contextmenu.file": [{ "id": "mail", "label": "发到邮箱", "kind": "action", "action": "my:send" }] }`,
|
|
16
16
|
"contextmenu.toolcall": `{ "ui": { "contextmenu.toolcall": [{ "id": "m", "label": "工具菜单", "kind": "action", "action": "my:m" }] } }`,
|
|
17
|
+
"tool.card.footer": `{ "ui": { "tool.card.footer": [{ "id": "m", "label": "工具卡底部", "kind": "action", "action": "my:m" }] } }`,
|
|
17
18
|
"settings.pages": `{ "settings": [{ "id": "conf", "label": "邮箱设置", "kind": "page" }] }`,
|
|
18
19
|
"tasks.panel": `{ "ui": { "tasks.panel": [{ "id": "pm2", "label": "pm2 托管的应用", "kind": "view" }] } }`,
|
|
19
20
|
"leftpanel.projects.actions": `{ "ui": { "leftpanel.projects.actions": [{ "id": "m", "label": "项目标题按钮", "kind": "action", "action": "my:m" }] } }`,
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 宿主插件重资产流水线(Heavy Asset Pipeline):
|
|
3
|
+
*
|
|
4
|
+
* 为插件提供体系化的重型依赖/二进制资产生命周期管理:
|
|
5
|
+
* 1. 规范化资产声明与探测(存在即秒过);
|
|
6
|
+
* 2. 多源候选与国内透明镜像自动回落(GitHub Release -> 镜像加速);
|
|
7
|
+
* 3. 并发防重入单例锁(同资产并发请求安全合并);
|
|
8
|
+
* 4. SHA-256 流式强完整性验签(防篡改与坏包解压);
|
|
9
|
+
* 5. Staging 隔离解压与原子安全替换;
|
|
10
|
+
* 6. 细粒度下载进度透传与日志归因。
|
|
11
|
+
*/
|
|
12
|
+
import { execSync } from "node:child_process";
|
|
13
|
+
import { createHash } from "node:crypto";
|
|
14
|
+
import { createWriteStream, existsSync, mkdirSync, renameSync, rmSync, unlinkSync } from "node:fs";
|
|
15
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
16
|
+
// 模块级并发单例锁:Key 为 `pluginDir:assetId`
|
|
17
|
+
const activeAssetPromises = new Map();
|
|
18
|
+
const assetProgressState = new Map();
|
|
19
|
+
/**
|
|
20
|
+
* 构建多源候选 URL 列表:
|
|
21
|
+
* 1. 用户自定义环境变量(PI_WEB_ASSET_MIRROR)优先拼装;
|
|
22
|
+
* 2. 保留原 Spec 列表;
|
|
23
|
+
* 3. 若含 GitHub 官方 Release,自动追加国内知名稳定加速镜像(如 ghfast.top)。
|
|
24
|
+
*/
|
|
25
|
+
export function buildAssetCandidateUrls(specUrls) {
|
|
26
|
+
const out = [];
|
|
27
|
+
const seen = new Set();
|
|
28
|
+
function push(u) {
|
|
29
|
+
if (!u)
|
|
30
|
+
return;
|
|
31
|
+
const trimmed = u.trim();
|
|
32
|
+
if (!trimmed || seen.has(trimmed))
|
|
33
|
+
return;
|
|
34
|
+
seen.add(trimmed);
|
|
35
|
+
out.push(trimmed);
|
|
36
|
+
}
|
|
37
|
+
const mirrorPrefix = process.env.PI_WEB_ASSET_MIRROR?.trim();
|
|
38
|
+
for (const url of specUrls) {
|
|
39
|
+
if (!url)
|
|
40
|
+
continue;
|
|
41
|
+
// 用户自定义镜像前缀置顶
|
|
42
|
+
if (mirrorPrefix) {
|
|
43
|
+
const prefix = mirrorPrefix.endsWith("/") ? mirrorPrefix : `${mirrorPrefix}/`;
|
|
44
|
+
if (url.startsWith("http://") || url.startsWith("https://")) {
|
|
45
|
+
push(`${prefix}${url}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
// 官方直链
|
|
49
|
+
push(url);
|
|
50
|
+
// 若为 GitHub 链接且未关闭镜像,自动追加通用透明反代镜像回落
|
|
51
|
+
if (process.env.PI_WEB_ASSET_AUTO_MIRROR !== "0" &&
|
|
52
|
+
process.env.PI_WEB_ASSET_AUTO_MIRROR !== "false" &&
|
|
53
|
+
(url.includes("github.com/") || url.includes("githubusercontent.com/"))) {
|
|
54
|
+
push(`https://ghfast.top/${url}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
/** 规范化目标绝对路径 */
|
|
60
|
+
export function resolveTargetDir(pluginDir, targetDir) {
|
|
61
|
+
return isAbsolute(targetDir) ? resolve(targetDir) : resolve(pluginDir, targetDir);
|
|
62
|
+
}
|
|
63
|
+
/** 查询指定资产在本地的就绪状态与实时进度 */
|
|
64
|
+
export function getPluginAssetStatus(pluginDir, spec) {
|
|
65
|
+
const absTarget = resolveTargetDir(pluginDir, spec.targetDir);
|
|
66
|
+
const lockKey = `${pluginDir}:${spec.id}`;
|
|
67
|
+
const current = assetProgressState.get(lockKey);
|
|
68
|
+
const isReady = spec.testFile ? existsSync(join(absTarget, spec.testFile)) : existsSync(absTarget);
|
|
69
|
+
return {
|
|
70
|
+
ready: isReady,
|
|
71
|
+
downloading: Boolean(current?.downloading),
|
|
72
|
+
progress: current?.progress ?? (isReady ? 100 : 0),
|
|
73
|
+
downloaded: current?.downloaded ?? 0,
|
|
74
|
+
total: current?.total ?? spec.size ?? 0,
|
|
75
|
+
error: current?.error ?? null,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* 确保资产就绪:
|
|
80
|
+
* 若本地已就绪则秒级通过;否则进入流式多源下载、SHA-256 验签、Staging 解压替换流水线。
|
|
81
|
+
*/
|
|
82
|
+
export async function ensurePluginAsset(pluginDir, spec, opts = {}) {
|
|
83
|
+
const absTarget = resolveTargetDir(pluginDir, spec.targetDir);
|
|
84
|
+
const lockKey = `${pluginDir}:${spec.id}`;
|
|
85
|
+
// 1. 检查本地已有状态
|
|
86
|
+
const readyNow = spec.testFile ? existsSync(join(absTarget, spec.testFile)) : existsSync(absTarget);
|
|
87
|
+
if (readyNow) {
|
|
88
|
+
return { ok: true, targetDir: absTarget, cached: true };
|
|
89
|
+
}
|
|
90
|
+
// 2. 并发合并锁:避免前台并发请求多次写盘
|
|
91
|
+
const inFlight = activeAssetPromises.get(lockKey);
|
|
92
|
+
if (inFlight) {
|
|
93
|
+
return await inFlight;
|
|
94
|
+
}
|
|
95
|
+
const promise = (async () => {
|
|
96
|
+
const log = opts.log ?? ((m) => console.log(`[asset:${spec.id}] ${m}`));
|
|
97
|
+
const candidateUrls = buildAssetCandidateUrls(spec.urls);
|
|
98
|
+
if (candidateUrls.length === 0) {
|
|
99
|
+
throw new Error(`未为资产 ${spec.id} 配置有效的下载源`);
|
|
100
|
+
}
|
|
101
|
+
const status = {
|
|
102
|
+
ready: false,
|
|
103
|
+
downloading: true,
|
|
104
|
+
progress: 0,
|
|
105
|
+
downloaded: 0,
|
|
106
|
+
total: spec.size ?? 0,
|
|
107
|
+
error: null,
|
|
108
|
+
};
|
|
109
|
+
assetProgressState.set(lockKey, status);
|
|
110
|
+
const timeoutMs = opts.timeoutMs ?? 600_000;
|
|
111
|
+
const tempTar = join(pluginDir, `.${spec.id}-download-${Date.now()}.tar.gz`);
|
|
112
|
+
let lastError = null;
|
|
113
|
+
let successUrl = "";
|
|
114
|
+
let computedSha = "";
|
|
115
|
+
try {
|
|
116
|
+
for (let i = 0; i < candidateUrls.length; i++) {
|
|
117
|
+
const currentUrl = candidateUrls[i];
|
|
118
|
+
try {
|
|
119
|
+
log(`[${i + 1}/${candidateUrls.length}] 正在从 ${currentUrl} 下载重资产...`);
|
|
120
|
+
const signals = [AbortSignal.timeout(timeoutMs)];
|
|
121
|
+
if (opts.signal)
|
|
122
|
+
signals.push(opts.signal);
|
|
123
|
+
const signal = AbortSignal.any ? AbortSignal.any(signals) : AbortSignal.timeout(timeoutMs);
|
|
124
|
+
const res = await fetch(currentUrl, { signal });
|
|
125
|
+
if (!res.ok) {
|
|
126
|
+
throw new Error(`HTTP 响应非预期: ${res.status} ${res.statusText}`);
|
|
127
|
+
}
|
|
128
|
+
const contentLength = Number(res.headers.get("content-length") || 0);
|
|
129
|
+
const totalBytes = contentLength > 0 ? contentLength : (spec.size ?? 0);
|
|
130
|
+
status.total = totalBytes;
|
|
131
|
+
const fileStream = createWriteStream(tempTar);
|
|
132
|
+
let streamError = null;
|
|
133
|
+
fileStream.on("error", (e) => {
|
|
134
|
+
streamError = e;
|
|
135
|
+
});
|
|
136
|
+
const hash = createHash("sha256");
|
|
137
|
+
const reader = res.body?.getReader();
|
|
138
|
+
if (!reader)
|
|
139
|
+
throw new Error("无法读取响应体数据流");
|
|
140
|
+
let downloaded = 0;
|
|
141
|
+
while (true) {
|
|
142
|
+
if (streamError)
|
|
143
|
+
throw streamError;
|
|
144
|
+
const { done, value } = await reader.read();
|
|
145
|
+
if (done)
|
|
146
|
+
break;
|
|
147
|
+
if (value) {
|
|
148
|
+
hash.update(value);
|
|
149
|
+
if (!fileStream.write(Buffer.from(value))) {
|
|
150
|
+
await new Promise((r) => fileStream.once("drain", r));
|
|
151
|
+
}
|
|
152
|
+
downloaded += value.length;
|
|
153
|
+
status.downloaded = downloaded;
|
|
154
|
+
if (totalBytes > 0) {
|
|
155
|
+
status.progress = Math.min(100, Math.round((downloaded / totalBytes) * 100));
|
|
156
|
+
}
|
|
157
|
+
opts.onProgress?.({
|
|
158
|
+
downloaded,
|
|
159
|
+
total: totalBytes,
|
|
160
|
+
percent: status.progress,
|
|
161
|
+
url: currentUrl,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
await new Promise((r) => fileStream.end(r));
|
|
166
|
+
if (streamError)
|
|
167
|
+
throw streamError;
|
|
168
|
+
computedSha = hash.digest("hex").toLowerCase();
|
|
169
|
+
// 强完整性验签(Fail-Closed):若哈希不符立即销毁,不进入解压步骤
|
|
170
|
+
if (spec.sha256) {
|
|
171
|
+
const expected = spec.sha256.trim().toLowerCase();
|
|
172
|
+
if (computedSha !== expected) {
|
|
173
|
+
throw new Error(`SHA-256 完整性验签失败!期望: ${expected},实际: ${computedSha}`);
|
|
174
|
+
}
|
|
175
|
+
log(`SHA-256 强校验通过: ${computedSha}`);
|
|
176
|
+
}
|
|
177
|
+
successUrl = currentUrl;
|
|
178
|
+
break; // 下载且验签成功,退出候选重试循环
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
lastError = err;
|
|
182
|
+
log(`下载源 ${currentUrl} 失败: ${err.message || String(err)}`);
|
|
183
|
+
try {
|
|
184
|
+
unlinkSync(tempTar);
|
|
185
|
+
}
|
|
186
|
+
catch { }
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (!successUrl) {
|
|
190
|
+
throw lastError || new Error(`所有 ${candidateUrls.length} 个候选下载源均尝试失败`);
|
|
191
|
+
}
|
|
192
|
+
log(`下载完成,正在进行 Staging 隔离解压与原子就绪...`);
|
|
193
|
+
const stagingDir = join(pluginDir, `.staging-${spec.id}-${Date.now()}`);
|
|
194
|
+
mkdirSync(stagingDir, { recursive: true });
|
|
195
|
+
try {
|
|
196
|
+
// 调用跨平台 tar 工具解压(--force-local 防 Windows 盘符冒号被识别为远程主机)
|
|
197
|
+
execSync(`tar --force-local -xzf "${tempTar}" -C "${stagingDir}"`, { windowsHide: true });
|
|
198
|
+
// 检查 staging 内部形态(若内部包装了同名子目录,取子目录内容)
|
|
199
|
+
const subDir = join(stagingDir, spec.targetDir);
|
|
200
|
+
const sourceRoot = existsSync(subDir) ? subDir : stagingDir;
|
|
201
|
+
// 替换目标目录
|
|
202
|
+
rmSync(absTarget, { recursive: true, force: true });
|
|
203
|
+
mkdirSync(resolve(absTarget, ".."), { recursive: true });
|
|
204
|
+
renameSync(sourceRoot, absTarget);
|
|
205
|
+
}
|
|
206
|
+
catch (e) {
|
|
207
|
+
rmSync(absTarget, { recursive: true, force: true });
|
|
208
|
+
throw new Error(`解压资产失败: ${e.message}`);
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
rmSync(stagingDir, { recursive: true, force: true });
|
|
212
|
+
try {
|
|
213
|
+
unlinkSync(tempTar);
|
|
214
|
+
}
|
|
215
|
+
catch { }
|
|
216
|
+
}
|
|
217
|
+
status.downloading = false;
|
|
218
|
+
status.ready = true;
|
|
219
|
+
status.progress = 100;
|
|
220
|
+
log(`资产 [${spec.id}] 就绪完毕并已安全挂载至 ${absTarget}`);
|
|
221
|
+
return { ok: true, targetDir: absTarget, sha256: computedSha };
|
|
222
|
+
}
|
|
223
|
+
catch (err) {
|
|
224
|
+
status.downloading = false;
|
|
225
|
+
status.ready = false;
|
|
226
|
+
status.error = err.message || String(err);
|
|
227
|
+
try {
|
|
228
|
+
unlinkSync(tempTar);
|
|
229
|
+
}
|
|
230
|
+
catch { }
|
|
231
|
+
throw err;
|
|
232
|
+
}
|
|
233
|
+
})().finally(() => {
|
|
234
|
+
activeAssetPromises.delete(lockKey);
|
|
235
|
+
});
|
|
236
|
+
activeAssetPromises.set(lockKey, promise);
|
|
237
|
+
return await promise;
|
|
238
|
+
}
|
|
@@ -143,6 +143,28 @@ export class PluginStorage {
|
|
|
143
143
|
}
|
|
144
144
|
});
|
|
145
145
|
}
|
|
146
|
+
has(key) {
|
|
147
|
+
return key in this.load();
|
|
148
|
+
}
|
|
149
|
+
keys() {
|
|
150
|
+
return Object.keys(this.load());
|
|
151
|
+
}
|
|
152
|
+
clear(preserveSettings = true) {
|
|
153
|
+
void withFileRmwLock(this.file, () => {
|
|
154
|
+
const store = this.readFromDisk();
|
|
155
|
+
const newStore = {};
|
|
156
|
+
if (preserveSettings && "settings" in store) {
|
|
157
|
+
newStore.settings = store.settings;
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
atomicWrite(this.file, JSON.stringify(newStore));
|
|
161
|
+
this.cache = newStore;
|
|
162
|
+
}
|
|
163
|
+
catch (err) {
|
|
164
|
+
console.error(`[plugin-storage] 写入失败 (${this.file}):`, err);
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
}
|
|
146
168
|
delete(key) {
|
|
147
169
|
// 同 set:写前重读 + RMW 锁,不拿旧快照回写。
|
|
148
170
|
void withFileRmwLock(this.file, () => {
|