dsh-sixlayer-memory 0.0.0-stage → 2.0.3
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 +123 -0
- package/README.md +292 -3
- package/catalog/.index.json +111704 -0
- package/catalog/parts.json +8808 -0
- package/cordis.patch.yml +8 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +51 -0
- package/docs//347/224/237/345/221/275/345/221/250/346/234/237-/350/207/252/345/212/250/345/217/254/345/233/236/344/270/216/345/200/231/351/200/211.md +103 -0
- package/icon.svg +8 -0
- package/lib/client.js +1209 -0
- package/lib/index.js +741 -0
- package/lib/memory/affect-alert.js +60 -0
- package/lib/memory/affect-events.js +201 -0
- package/lib/memory/affect-report.js +61 -0
- package/lib/memory/api.js +194 -0
- package/lib/memory/crypto.js +68 -0
- package/lib/memory/detail.js +43 -0
- package/lib/memory/embed.js +394 -0
- package/lib/memory/emotion.js +99 -0
- package/lib/memory/explain.js +207 -0
- package/lib/memory/importer.js +215 -0
- package/lib/memory/inject.js +193 -0
- package/lib/memory/ledger.js +101 -0
- package/lib/memory/lifecycle.js +491 -0
- package/lib/memory/notify.js +164 -0
- package/lib/memory/policy.js +182 -0
- package/lib/memory/qq-official.js +196 -0
- package/lib/memory/qq.js +326 -0
- package/lib/memory/recorder.js +241 -0
- package/lib/memory/redact.js +120 -0
- package/lib/memory/scanners.js +142 -0
- package/lib/memory/schema.js +205 -0
- package/lib/memory/service-plugin.js +69 -0
- package/lib/memory/service.js +123 -0
- package/lib/memory/shadow.js +133 -0
- package/lib/memory/store.js +1138 -0
- package/lib/memory/timeline.js +74 -0
- package/lib/memory/tokenize.js +66 -0
- package/lib/memory/tools.js +1371 -0
- package/lib/memory/util.js +129 -0
- package/lib/parts/index.js +154 -0
- package/lib/parts/installer.js +294 -0
- package/lib/parts/jobs.js +91 -0
- package/lib/parts/library.js +91 -0
- package/lib/probe-plugin.js +38 -0
- package/lib/voice/board-asr.js +31 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +114 -3
- package/tools/backfill-affect.mjs +82 -0
- package/tools/eval.mjs +88 -0
- package/tools/p1.mjs +108 -0
- package/tools/p10.mjs +36 -0
- package/tools/p11.mjs +51 -0
- package/tools/p12.mjs +53 -0
- package/tools/p13.mjs +65 -0
- package/tools/p14.mjs +66 -0
- package/tools/p15.mjs +43 -0
- package/tools/p16.mjs +42 -0
- package/tools/p17.mjs +29 -0
- package/tools/p18.mjs +48 -0
- package/tools/p19.mjs +50 -0
- package/tools/p2.mjs +59 -0
- package/tools/p20.mjs +54 -0
- package/tools/p21.mjs +42 -0
- package/tools/p22.mjs +32 -0
- package/tools/p23.mjs +43 -0
- package/tools/p24.mjs +40 -0
- package/tools/p25.mjs +151 -0
- package/tools/p26.mjs +113 -0
- package/tools/p27.mjs +89 -0
- package/tools/p28.mjs +60 -0
- package/tools/p3.mjs +54 -0
- package/tools/p4.mjs +73 -0
- package/tools/p5.mjs +117 -0
- package/tools/p6.mjs +122 -0
- package/tools/p8.mjs +50 -0
- package/tools/p9.mjs +35 -0
- package/tools/phase2.mjs +159 -0
- package/tools/preflight.mjs +320 -0
- package/tools/push-via-api.mjs +187 -0
- package/tools/quarterly.mjs +129 -0
- package/tools/refresh-catalog.mjs +60 -0
- package/tools/register-bundle.mjs +38 -0
- package/tools/review.mjs +156 -0
- package/tools/selfcheck.mjs +80 -0
- package/tools/smoke.mjs +112 -0
- package/tools/testset-v1.json +70 -0
- package/tools/validate-tools.mjs +150 -0
- package/tools/verify-all.mjs +39 -0
- package/tools/write-chain.mjs +139 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* util.js — 纯函数工具:ULID、哈希、时间、路径、JSON 读写。
|
|
3
|
+
* 刻意不引任何第三方包:这个插件要在别人的 host 进程里跑,依赖越少越好。
|
|
4
|
+
*/
|
|
5
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
6
|
+
import fs from 'node:fs'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
|
|
9
|
+
// ---------- 时间 ----------
|
|
10
|
+
|
|
11
|
+
/** 本地 ISO 时间(带时区偏移),用于人类阅读与审计。 */
|
|
12
|
+
export function nowIso() {
|
|
13
|
+
const d = new Date()
|
|
14
|
+
const pad = (n, w = 2) => String(n).padStart(w, '0')
|
|
15
|
+
const off = -d.getTimezoneOffset()
|
|
16
|
+
const sign = off >= 0 ? '+' : '-'
|
|
17
|
+
const abs = Math.abs(off)
|
|
18
|
+
return (
|
|
19
|
+
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +
|
|
20
|
+
`T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}` +
|
|
21
|
+
`${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`
|
|
22
|
+
)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 稳定时间戳(UTC ISO),用于排序与哈希。 */
|
|
26
|
+
export function nowUtc() {
|
|
27
|
+
return new Date().toISOString()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// ---------- ULID ----------
|
|
31
|
+
|
|
32
|
+
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
|
|
33
|
+
let lastTime = -1
|
|
34
|
+
let lastRandom = null
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 单调 ULID:同一毫秒内多次生成也严格递增。
|
|
38
|
+
* 排序即时间序,适合做 record_id / trace_id。
|
|
39
|
+
*/
|
|
40
|
+
export function ulid(seedTime = Date.now()) {
|
|
41
|
+
let time = seedTime
|
|
42
|
+
if (time <= lastTime) {
|
|
43
|
+
time = lastTime
|
|
44
|
+
}
|
|
45
|
+
let random
|
|
46
|
+
if (time === lastTime && lastRandom) {
|
|
47
|
+
// 同毫秒:在上一份随机数上做 +1(Crockford base32 进位)
|
|
48
|
+
random = lastRandom.slice()
|
|
49
|
+
let i = random.length - 1
|
|
50
|
+
while (i >= 0) {
|
|
51
|
+
if (random[i] === 31) {
|
|
52
|
+
random[i] = 0
|
|
53
|
+
i -= 1
|
|
54
|
+
} else {
|
|
55
|
+
random[i] += 1
|
|
56
|
+
break
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
} else {
|
|
60
|
+
random = Array.from(randomBytes(10))
|
|
61
|
+
}
|
|
62
|
+
lastTime = time
|
|
63
|
+
lastRandom = random
|
|
64
|
+
let out = ''
|
|
65
|
+
for (let i = 9; i >= 0; i -= 1) {
|
|
66
|
+
out = CROCKFORD[(time / Math.pow(32, i)) % 32 | 0] + out
|
|
67
|
+
}
|
|
68
|
+
for (let i = 0; i < random.length; i += 1) {
|
|
69
|
+
const byte = random[i]
|
|
70
|
+
out += CROCKFORD[byte & 31] + CROCKFORD[(byte >> 5) & 31]
|
|
71
|
+
}
|
|
72
|
+
return out.slice(0, 26)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ---------- 哈希 ----------
|
|
76
|
+
|
|
77
|
+
/** 规范化正文:去首尾空白、统一换行、折叠行尾空格。 */
|
|
78
|
+
export function normalizeContent(text) {
|
|
79
|
+
return String(text)
|
|
80
|
+
.replace(/\r\n?/g, '\n')
|
|
81
|
+
.split('\n')
|
|
82
|
+
.map((line) => line.replace(/[ \t]+$/g, ''))
|
|
83
|
+
.join('\n')
|
|
84
|
+
.trim()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function sha256(text) {
|
|
88
|
+
return createHash('sha256').update(String(text), 'utf8').digest('hex')
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ---------- 路径 ----------
|
|
92
|
+
|
|
93
|
+
export function ensureDir(dir) {
|
|
94
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
95
|
+
return dir
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function readJson(file, fallback) {
|
|
99
|
+
try {
|
|
100
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
101
|
+
} catch {
|
|
102
|
+
return fallback
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function writeJson(file, value) {
|
|
107
|
+
ensureDir(path.dirname(file))
|
|
108
|
+
const tmp = `${file}.tmp-${process.pid}`
|
|
109
|
+
fs.writeFileSync(tmp, JSON.stringify(value, null, 2), 'utf8')
|
|
110
|
+
fs.renameSync(tmp, file)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ---------- 数据分级 ----------
|
|
114
|
+
|
|
115
|
+
/** 凭证类特征:命中即判 S 级(方案 §10:密钥/凭证绝不进自动召回)。 */
|
|
116
|
+
const SENSITIVE_PATTERNS = [
|
|
117
|
+
/(?:密码|口令|password|passwd|pwd)\s*[:=:是]\s*\S{3,}/i,
|
|
118
|
+
/(?:api[_-]?key|token|secret|access[_-]?key)\s*[:=:]\s*\S{8,}/i,
|
|
119
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----/,
|
|
120
|
+
/(?:ssh|vnc)\s*(?:口令|密码|password)?\s*[:=:]?\s*(?:root\/)?\S{6,}/i,
|
|
121
|
+
/\bghp_[A-Za-z0-9]{20,}\b/,
|
|
122
|
+
/\bsk-[A-Za-z0-9]{20,}\b/,
|
|
123
|
+
/\bAKIA[0-9A-Z]{16}\b/,
|
|
124
|
+
]
|
|
125
|
+
|
|
126
|
+
export function looksSensitive(text) {
|
|
127
|
+
const s = String(text)
|
|
128
|
+
return SENSITIVE_PATTERNS.some((re) => re.test(s))
|
|
129
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* parts.js — 把记忆能力拆成「零件」,并提供装配协议。
|
|
3
|
+
*
|
|
4
|
+
* 理念来源:DSH「一切皆零件」——功能不写死成一个大黑盒,
|
|
5
|
+
* 而是拆成有名字、有契约、可替换的小零件,按需拼装。
|
|
6
|
+
*
|
|
7
|
+
* 零件契约:
|
|
8
|
+
* { name, version, describe(), run(store, ctx) -> string[] }
|
|
9
|
+
*
|
|
10
|
+
* 装配:compose(store, { scene, parts, maxChars })
|
|
11
|
+
* - 按给定顺序执行零件
|
|
12
|
+
* - 去重、限长、保留来源标注
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
function oneLine(text, max = 100) {
|
|
16
|
+
const s = String(text ?? '').replace(/\s+/g, ' ').trim()
|
|
17
|
+
return s.length > max ? `${s.slice(0, max)}…` : s
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function rowsToLines(rows) {
|
|
21
|
+
return rows.map((r) => `- [${r.layer}/${r.affect_label ?? 'A'}] ${oneLine(r.summary)}`)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const PARTS = {
|
|
25
|
+
profile: {
|
|
26
|
+
version: 1,
|
|
27
|
+
describe: '身份与长期事实:高重要性、L1/L2 的记忆',
|
|
28
|
+
run(store, ctx = {}) {
|
|
29
|
+
const rows = store.db
|
|
30
|
+
.prepare(
|
|
31
|
+
`SELECT layer, summary, affect_label FROM records
|
|
32
|
+
WHERE status = 'active' AND sad_level != 'S' AND layer IN ('L1','L2')
|
|
33
|
+
ORDER BY importance DESC, created_at DESC LIMIT ?`,
|
|
34
|
+
)
|
|
35
|
+
.all(Math.min(Number(ctx.limit ?? 3), 10))
|
|
36
|
+
return rowsToLines(rows)
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
|
|
40
|
+
recent: {
|
|
41
|
+
version: 1,
|
|
42
|
+
describe: '最近写入的活跃记忆',
|
|
43
|
+
run(store, ctx = {}) {
|
|
44
|
+
const rows = store.db
|
|
45
|
+
.prepare(
|
|
46
|
+
`SELECT layer, summary, affect_label FROM records
|
|
47
|
+
WHERE status = 'active' AND sad_level != 'S'
|
|
48
|
+
ORDER BY created_at DESC LIMIT ?`,
|
|
49
|
+
)
|
|
50
|
+
.all(Math.min(Number(ctx.limit ?? 3), 10))
|
|
51
|
+
return rowsToLines(rows)
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
|
|
55
|
+
lessons: {
|
|
56
|
+
version: 1,
|
|
57
|
+
describe: '教训:负面/紧急且高唤醒的记忆',
|
|
58
|
+
run(store, ctx = {}) {
|
|
59
|
+
const rows = store.db
|
|
60
|
+
.prepare(
|
|
61
|
+
`SELECT layer, summary, affect_label FROM records
|
|
62
|
+
WHERE status = 'active' AND sad_level != 'S'
|
|
63
|
+
AND affect_label IN ('negative','urgent')
|
|
64
|
+
ORDER BY COALESCE(affect_arousal,0) DESC, importance DESC LIMIT ?`,
|
|
65
|
+
)
|
|
66
|
+
.all(Math.min(Number(ctx.limit ?? 3), 10))
|
|
67
|
+
return rowsToLines(rows)
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
|
|
71
|
+
scene: {
|
|
72
|
+
version: 1,
|
|
73
|
+
describe: '指定场景的记忆(按 tag = scene 匹配)',
|
|
74
|
+
run(store, ctx = {}) {
|
|
75
|
+
const scene = String(ctx.scene ?? '').trim()
|
|
76
|
+
if (!scene) return []
|
|
77
|
+
const rows = store.db
|
|
78
|
+
.prepare(
|
|
79
|
+
`SELECT r.layer, r.summary, r.affect_label FROM records r
|
|
80
|
+
JOIN tags t ON t.record_id = r.record_id
|
|
81
|
+
WHERE (t.tag = ? OR t.tag = 'scene:' || ?) AND r.status = 'active' AND r.sad_level != 'S'
|
|
82
|
+
ORDER BY r.importance DESC LIMIT ?`,
|
|
83
|
+
)
|
|
84
|
+
.all(scene, scene, Math.min(Number(ctx.limit ?? 5), 20))
|
|
85
|
+
return rowsToLines(rows)
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
associations: {
|
|
90
|
+
version: 1,
|
|
91
|
+
describe: '联想:与 seed(record_id 或文本)相关的记忆',
|
|
92
|
+
run(store, ctx = {}) {
|
|
93
|
+
const seed = String(ctx.seed ?? '').trim()
|
|
94
|
+
if (!seed) return []
|
|
95
|
+
const result = store.associate({ recordId: seed, query: seed, topK: Math.min(Number(ctx.limit ?? 3), 10) })
|
|
96
|
+
return result.items.map((it) => `- [${it.layer}] ${oneLine(it.summary)} | ${it.reasons.join('、')}`)
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function listParts() {
|
|
102
|
+
return Object.entries(PARTS).map(([name, part]) => ({
|
|
103
|
+
name,
|
|
104
|
+
version: part.version,
|
|
105
|
+
describe: part.describe,
|
|
106
|
+
}))
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 装配:按顺序跑零件,拼成一段可直接注入的上下文。
|
|
111
|
+
* @returns {{scene: string, parts: Array<{name: string, version: number, lines: string[]}>, text: string}}
|
|
112
|
+
*/
|
|
113
|
+
export function compose(store, input = {}) {
|
|
114
|
+
const names = Array.isArray(input.parts) && input.parts.length > 0
|
|
115
|
+
? input.parts.map(String)
|
|
116
|
+
: ['profile', 'lessons', 'recent']
|
|
117
|
+
const maxChars = Math.min(Math.max(Number(input.maxChars ?? 1200), 100), 4000)
|
|
118
|
+
const scene = String(input.scene ?? '')
|
|
119
|
+
const ctx = { scene, seed: input.seed, limit: input.limit }
|
|
120
|
+
|
|
121
|
+
const used = new Set()
|
|
122
|
+
const blocks = []
|
|
123
|
+
let budget = maxChars
|
|
124
|
+
for (const name of names) {
|
|
125
|
+
const part = PARTS[name]
|
|
126
|
+
if (!part) {
|
|
127
|
+
blocks.push({ name, version: 0, lines: ['(未知零件,已跳过)'] })
|
|
128
|
+
continue
|
|
129
|
+
}
|
|
130
|
+
let lines = []
|
|
131
|
+
try {
|
|
132
|
+
lines = part.run(store, ctx) ?? []
|
|
133
|
+
} catch (error) {
|
|
134
|
+
lines = ['(零件执行失败:' + (error?.message ?? String(error)) + ')']
|
|
135
|
+
}
|
|
136
|
+
const kept = []
|
|
137
|
+
for (const line of lines) {
|
|
138
|
+
const key = line.replace(/^- /, '').slice(0, 40)
|
|
139
|
+
if (used.has(key)) continue
|
|
140
|
+
if (budget - line.length - 1 < 0) break
|
|
141
|
+
used.add(key)
|
|
142
|
+
kept.push(line)
|
|
143
|
+
budget -= line.length + 1
|
|
144
|
+
}
|
|
145
|
+
blocks.push({ name, version: part.version, lines: kept })
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const text = blocks
|
|
149
|
+
.filter((b) => b.lines.length > 0)
|
|
150
|
+
.map((b) => `### ${b.name}(v${b.version})\n${b.lines.join('\n')}`)
|
|
151
|
+
.join('\n\n')
|
|
152
|
+
|
|
153
|
+
return { scene, parts: blocks, text }
|
|
154
|
+
}
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* installer.js — 零件的一键安装/卸载(走官方 CLI → pnpm)。
|
|
3
|
+
*
|
|
4
|
+
* 安全边界:
|
|
5
|
+
* - 只允许 github: / https: / 包名 形式的规格
|
|
6
|
+
* - 禁止卸载 @deepseek-ai/* 与工作台自身
|
|
7
|
+
* - 安装后自动把包名登记进 dsh.profile.bundles(否则重启不加载)
|
|
8
|
+
* - 不执行任意命令,只调 `dsh plugin add/remove`
|
|
9
|
+
*
|
|
10
|
+
* 进度:CLI 输出逐行回调 onProgress,供 jobs.js 生成进度条。
|
|
11
|
+
*/
|
|
12
|
+
import { spawn } from 'node:child_process'
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
|
|
16
|
+
const CLI = process.env.DSH_CLI || 'C:/000001/resources/runtime/cli/bin/dsh.cmd'
|
|
17
|
+
const CORE_PREFIX = '@deepseek-ai/'
|
|
18
|
+
const SELF = 'dsh-sixlayer-memory'
|
|
19
|
+
let activeKind = null
|
|
20
|
+
|
|
21
|
+
export async function resolveNpmName(spec) {
|
|
22
|
+
const m = String(spec).match(/^github:([^/]+)\/(.+)$/)
|
|
23
|
+
if (!m) return null
|
|
24
|
+
const owner = m[1]
|
|
25
|
+
const repo = m[2].replace(/\.git$/, '')
|
|
26
|
+
try {
|
|
27
|
+
const res = await fetch(`https://api.github.com/repos/${owner}/${repo}/contents/package.json`, {
|
|
28
|
+
headers: { accept: 'application/vnd.github+json', 'user-agent': 'dsh-sixlayer-memory' },
|
|
29
|
+
signal: AbortSignal.timeout(8000),
|
|
30
|
+
})
|
|
31
|
+
if (res.ok) {
|
|
32
|
+
const j = await res.json()
|
|
33
|
+
const pkg = JSON.parse(Buffer.from(j.content, 'base64').toString('utf8'))
|
|
34
|
+
if (typeof pkg.name === 'string' && pkg.name) return pkg.name
|
|
35
|
+
}
|
|
36
|
+
} catch {
|
|
37
|
+
/* 落到搜索 */
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
const res = await fetch(`https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(repo)}&size=20`, {
|
|
41
|
+
signal: AbortSignal.timeout(8000),
|
|
42
|
+
})
|
|
43
|
+
if (!res.ok) return null
|
|
44
|
+
const j = await res.json()
|
|
45
|
+
const target = ('github.com/' + owner + '/' + repo).toLowerCase()
|
|
46
|
+
for (const item of j.objects ?? []) {
|
|
47
|
+
const links = item.package?.links ?? {}
|
|
48
|
+
const link = String(links.repository ?? links.homepage ?? '').toLowerCase()
|
|
49
|
+
if (link.includes(target)) return item.package.name
|
|
50
|
+
}
|
|
51
|
+
} catch {
|
|
52
|
+
/* 忽略 */
|
|
53
|
+
}
|
|
54
|
+
return null
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function npmLatest(name) {
|
|
58
|
+
try {
|
|
59
|
+
const url = 'https://registry.npmjs.org/' + encodeURIComponent(name).replace(/^%40/, '@')
|
|
60
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(8000) })
|
|
61
|
+
if (!res.ok) return null
|
|
62
|
+
const j = await res.json()
|
|
63
|
+
return (j['dist-tags'] && j['dist-tags'].latest) || null
|
|
64
|
+
} catch {
|
|
65
|
+
return null
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function probeCodeload() {
|
|
70
|
+
try {
|
|
71
|
+
const res = await fetch('https://codeload.github.com/', { method: 'HEAD', signal: AbortSignal.timeout(6000) })
|
|
72
|
+
return res.status > 0
|
|
73
|
+
} catch {
|
|
74
|
+
return false
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function readJson(file) {
|
|
79
|
+
return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function writeJson(file, value) {
|
|
83
|
+
fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', 'utf8')
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function runCliStreaming(args, { dshHome, timeoutMs = 180000, onProgress, onChild } = {}) {
|
|
87
|
+
return new Promise((resolve) => {
|
|
88
|
+
let child
|
|
89
|
+
try {
|
|
90
|
+
child = spawn('cmd.exe', ['/c', CLI, ...args], {
|
|
91
|
+
env: { ...process.env, DSH_HOME: dshHome },
|
|
92
|
+
windowsHide: true,
|
|
93
|
+
})
|
|
94
|
+
} catch (error) {
|
|
95
|
+
resolve({ ok: false, code: -1, stdout: '', stderr: String(error) })
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
onChild?.(child)
|
|
100
|
+
let stdout = ''
|
|
101
|
+
let stderr = ''
|
|
102
|
+
let finished = false
|
|
103
|
+
const timer = setTimeout(() => {
|
|
104
|
+
try {
|
|
105
|
+
child.kill()
|
|
106
|
+
} catch {
|
|
107
|
+
/* 忽略 */
|
|
108
|
+
}
|
|
109
|
+
if (!finished) {
|
|
110
|
+
finished = true
|
|
111
|
+
resolve({ ok: false, code: -1, stdout, stderr: stderr + '\n[timeout]' })
|
|
112
|
+
}
|
|
113
|
+
}, timeoutMs)
|
|
114
|
+
|
|
115
|
+
const feed = (chunk, isErr) => {
|
|
116
|
+
const text = chunk.toString('utf8')
|
|
117
|
+
if (isErr) stderr += text
|
|
118
|
+
else stdout += text
|
|
119
|
+
for (const line of text.split(/\r?\n/)) {
|
|
120
|
+
const trimmed = line.trim()
|
|
121
|
+
if (trimmed) onProgress?.({ line: trimmed })
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
child.stdout?.on('data', (c) => feed(c, false))
|
|
125
|
+
child.stderr?.on('data', (c) => feed(c, true))
|
|
126
|
+
child.on('error', (error) => {
|
|
127
|
+
clearTimeout(timer)
|
|
128
|
+
if (!finished) {
|
|
129
|
+
finished = true
|
|
130
|
+
resolve({ ok: false, code: -1, stdout, stderr: String(error) })
|
|
131
|
+
}
|
|
132
|
+
})
|
|
133
|
+
child.on('close', (code) => {
|
|
134
|
+
clearTimeout(timer)
|
|
135
|
+
if (!finished) {
|
|
136
|
+
finished = true
|
|
137
|
+
resolve({ ok: code === 0, code, stdout, stderr })
|
|
138
|
+
}
|
|
139
|
+
})
|
|
140
|
+
})
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function resetActive() {
|
|
144
|
+
activeKind = null
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function normalizeSpec(item) {
|
|
148
|
+
if (item?.spec) return String(item.spec)
|
|
149
|
+
const repo = String(item?.repo ?? '')
|
|
150
|
+
const m = repo.match(/github\.com\/([^/]+)\/([^/#?]+)/)
|
|
151
|
+
if (m) return `github:${m[1]}/${m[2].replace(/\.git$/, '')}`
|
|
152
|
+
if (repo.startsWith('https://') || repo.startsWith('http://')) return repo
|
|
153
|
+
return null
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function isSafeSpec(spec) {
|
|
157
|
+
return /^(github:|https?:\/\/|[a-z0-9@][\w.@/-]*$)/i.test(spec) && !spec.includes('..')
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function deps(profileDir) {
|
|
161
|
+
const pkg = readJson(path.join(profileDir, 'package.json'))
|
|
162
|
+
return Object.keys(pkg.dependencies ?? {})
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function bundles(profileDir) {
|
|
166
|
+
const pkg = readJson(path.join(profileDir, 'package.json'))
|
|
167
|
+
return pkg.dsh?.profile?.bundles ?? []
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function addBundle(profileDir, name) {
|
|
171
|
+
const file = path.join(profileDir, 'package.json')
|
|
172
|
+
const pkg = readJson(file)
|
|
173
|
+
const list = pkg.dsh?.profile?.bundles ?? []
|
|
174
|
+
if (!list.includes(name)) list.push(name)
|
|
175
|
+
pkg.dsh = pkg.dsh ?? {}
|
|
176
|
+
pkg.dsh.profile = { ...(pkg.dsh.profile ?? {}), bundles: list }
|
|
177
|
+
writeJson(file, pkg)
|
|
178
|
+
return list.includes(name)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function removeBundle(profileDir, name) {
|
|
182
|
+
const file = path.join(profileDir, 'package.json')
|
|
183
|
+
const pkg = readJson(file)
|
|
184
|
+
const list = (pkg.dsh?.profile?.bundles ?? []).filter((x) => x !== name)
|
|
185
|
+
pkg.dsh = pkg.dsh ?? {}
|
|
186
|
+
pkg.dsh.profile = { ...(pkg.dsh.profile ?? {}), bundles: list }
|
|
187
|
+
writeJson(file, pkg)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function listInstalled({ dshHome, profile }) {
|
|
191
|
+
const profileDir = path.join(dshHome, 'profiles', profile)
|
|
192
|
+
const names = deps(profileDir)
|
|
193
|
+
const bundleList = bundles(profileDir)
|
|
194
|
+
return names.map((name) => {
|
|
195
|
+
let version = ''
|
|
196
|
+
let description = ''
|
|
197
|
+
try {
|
|
198
|
+
const pkg = readJson(path.join(profileDir, 'node_modules', name, 'package.json'))
|
|
199
|
+
version = pkg.version ?? ''
|
|
200
|
+
description = pkg.description ?? ''
|
|
201
|
+
} catch {
|
|
202
|
+
/* 没装好或不是包 */
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
name,
|
|
206
|
+
version,
|
|
207
|
+
description,
|
|
208
|
+
bundle: bundleList.includes(name),
|
|
209
|
+
removable: name !== SELF && !name.startsWith(CORE_PREFIX),
|
|
210
|
+
}
|
|
211
|
+
})
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export async function installPart({ item, profile, dshHome, onProgress, registerAbort } = {}) {
|
|
215
|
+
if (activeKind) throw new Error('已有任务在进行(' + activeKind + '),请等它完成或先取消')
|
|
216
|
+
const profileDir = path.join(dshHome, 'profiles', profile)
|
|
217
|
+
const spec = normalizeSpec(item)
|
|
218
|
+
if (!spec) throw new Error('缺少可安装的仓库地址(repo/spec)')
|
|
219
|
+
if (!isSafeSpec(spec)) throw new Error('安装规格不合法:' + spec)
|
|
220
|
+
let effective = spec
|
|
221
|
+
if (spec.startsWith('github:')) {
|
|
222
|
+
onProgress?.({ percent: 4, message: '检查安装通道…' })
|
|
223
|
+
const npmName = await resolveNpmName(spec)
|
|
224
|
+
const latest = npmName ? await npmLatest(npmName) : null
|
|
225
|
+
if (npmName && latest) {
|
|
226
|
+
effective = npmName + '@' + latest
|
|
227
|
+
onProgress?.({ percent: 6, message: 'GitHub 下载通道不通,改用 npm 包:' + effective })
|
|
228
|
+
} else {
|
|
229
|
+
const ok = await probeCodeload()
|
|
230
|
+
if (!ok) throw new Error('本机无法访问 GitHub 下载通道(codeload),且该仓库没有可用的 npm 包。请配置代理,或提供可访问的包名。')
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
activeKind = 'install ' + effective
|
|
235
|
+
onProgress?.({ percent: 5, message: '开始安装 ' + spec })
|
|
236
|
+
const before = deps(profileDir)
|
|
237
|
+
const res = await runCliStreaming(['plugin', '--profile', profile, 'add', effective], {
|
|
238
|
+
dshHome,
|
|
239
|
+
onChild: (child) => registerAbort?.(() => { try { child.kill() } catch {} }),
|
|
240
|
+
onProgress: (p) => {
|
|
241
|
+
const line = p.line
|
|
242
|
+
const packages = line.match(/Packages:\s*\+(\d+)/)
|
|
243
|
+
const resolved = line.match(/Progress:\s*resolved\s*(\d+)/)
|
|
244
|
+
if (packages) onProgress?.({ percent: 15, message: '下载依赖 ' + packages[1] + ' 个…' })
|
|
245
|
+
else if (resolved) onProgress?.({ percent: Math.min(80, 15 + Number(resolved[1])), message: '解析依赖 ' + resolved[1] })
|
|
246
|
+
else if (/Done in/.test(line)) onProgress?.({ percent: 85, message: '依赖安装完成' })
|
|
247
|
+
onProgress?.({ line })
|
|
248
|
+
},
|
|
249
|
+
})
|
|
250
|
+
if (!res.ok) {
|
|
251
|
+
activeKind = null
|
|
252
|
+
throw new Error('安装失败:' + (res.stderr || res.stdout).slice(-800))
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const after = deps(profileDir)
|
|
256
|
+
const added = after.find((n) => !before.includes(n)) ?? null
|
|
257
|
+
onProgress?.({ percent: 90, message: '登记 bundle…' })
|
|
258
|
+
let bundleAdded = false
|
|
259
|
+
if (added) bundleAdded = addBundle(profileDir, added)
|
|
260
|
+
onProgress?.({ percent: 100, message: '完成,需要重启' })
|
|
261
|
+
activeKind = null
|
|
262
|
+
return {
|
|
263
|
+
spec: effective,
|
|
264
|
+
package: added,
|
|
265
|
+
bundle: bundleAdded,
|
|
266
|
+
restartRequired: true,
|
|
267
|
+
output: (res.stdout || '').slice(-600),
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export async function uninstallPart({ name, profile, dshHome, onProgress } = {}) {
|
|
272
|
+
const target = String(name ?? '').trim()
|
|
273
|
+
if (!target) throw new Error('需要包名')
|
|
274
|
+
if (target === SELF) throw new Error('不能卸载工作台自身')
|
|
275
|
+
if (target.startsWith(CORE_PREFIX)) throw new Error('内置包不能卸载:' + target)
|
|
276
|
+
const profileDir = path.join(dshHome, 'profiles', profile)
|
|
277
|
+
|
|
278
|
+
onProgress?.({ percent: 5, message: '移除 bundle 登记…' })
|
|
279
|
+
removeBundle(profileDir, target)
|
|
280
|
+
onProgress?.({ percent: 15, message: '开始卸载 ' + target })
|
|
281
|
+
const res = await runCliStreaming(['plugin', '--profile', profile, 'remove', target], {
|
|
282
|
+
dshHome,
|
|
283
|
+
onProgress: (p) => {
|
|
284
|
+
const line = p.line
|
|
285
|
+
const resolved = line.match(/Progress:\s*resolved\s*(\d+)/)
|
|
286
|
+
if (resolved) onProgress?.({ percent: Math.min(85, 20 + Number(resolved[1])), message: '卸载中 ' + resolved[1] })
|
|
287
|
+
else if (/Done in/.test(line)) onProgress?.({ percent: 90, message: '卸载完成' })
|
|
288
|
+
onProgress?.({ line })
|
|
289
|
+
},
|
|
290
|
+
})
|
|
291
|
+
if (!res.ok) throw new Error('卸载失败:' + (res.stderr || res.stdout).slice(-800))
|
|
292
|
+
onProgress?.({ percent: 100, message: '完成,需要重启' })
|
|
293
|
+
return { package: target, restartRequired: true, output: (res.stdout || '').slice(-600) }
|
|
294
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* jobs.js — 后台任务登记表(安装/卸载的进度来源)。
|
|
3
|
+
*
|
|
4
|
+
* 安装走官方 CLI,可能几十秒到几分钟;阻塞式 RPC 会让 UI 只能转圈。
|
|
5
|
+
* 这里把任务放到内存表里,UI 用 jobId 轮询 progress。
|
|
6
|
+
*/
|
|
7
|
+
const jobs = new Map()
|
|
8
|
+
let seq = 0
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {(progress: (p: {percent?: number, message?: string, phase?: string}) => void) => Promise<any>} runner
|
|
12
|
+
* @returns {{id: string}}
|
|
13
|
+
*/
|
|
14
|
+
export function startJob(runner) {
|
|
15
|
+
const id = `job-${Date.now()}-${(seq += 1)}`
|
|
16
|
+
const job = {
|
|
17
|
+
id,
|
|
18
|
+
state: 'running',
|
|
19
|
+
percent: 2,
|
|
20
|
+
message: '准备中…',
|
|
21
|
+
phase: 'start',
|
|
22
|
+
lines: [],
|
|
23
|
+
result: null,
|
|
24
|
+
error: null,
|
|
25
|
+
startedAt: Date.now(),
|
|
26
|
+
}
|
|
27
|
+
jobs.set(id, job)
|
|
28
|
+
|
|
29
|
+
const progress = (patch) => {
|
|
30
|
+
if (!patch) return
|
|
31
|
+
if (typeof patch.percent === 'number') job.percent = Math.max(job.percent, Math.min(100, Math.round(patch.percent)))
|
|
32
|
+
if (patch.message) job.message = String(patch.message)
|
|
33
|
+
if (patch.phase) job.phase = String(patch.phase)
|
|
34
|
+
if (patch.line) {
|
|
35
|
+
job.lines.push(String(patch.line).slice(0, 300))
|
|
36
|
+
if (job.lines.length > 40) job.lines.shift()
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
Promise.resolve()
|
|
41
|
+
.then(() => runner(progress, (abortFn) => { job.abort = abortFn }))
|
|
42
|
+
.then((result) => {
|
|
43
|
+
job.state = 'done'
|
|
44
|
+
job.percent = 100
|
|
45
|
+
job.phase = 'done'
|
|
46
|
+
job.message = '完成'
|
|
47
|
+
job.result = result ?? null
|
|
48
|
+
})
|
|
49
|
+
.catch((error) => {
|
|
50
|
+
job.state = 'error'
|
|
51
|
+
job.phase = 'error'
|
|
52
|
+
const msg = error?.message ?? String(error)
|
|
53
|
+
job.error = msg
|
|
54
|
+
job.message = '失败:' + String(msg).slice(0, 120)
|
|
55
|
+
})
|
|
56
|
+
.finally(() => {
|
|
57
|
+
setTimeout(() => jobs.delete(id), 10 * 60 * 1000).unref?.()
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
return { id }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function cancelJob(id) {
|
|
64
|
+
const job = jobs.get(String(id ?? ''))
|
|
65
|
+
if (!job || job.state !== 'running') return { ok: false, reason: 'not-running' }
|
|
66
|
+
try {
|
|
67
|
+
job.abort?.()
|
|
68
|
+
} catch {
|
|
69
|
+
/* 忽略 */
|
|
70
|
+
}
|
|
71
|
+
job.state = 'cancelled'
|
|
72
|
+
job.phase = 'cancelled'
|
|
73
|
+
job.message = '已取消'
|
|
74
|
+
return { ok: true }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function getJob(id) {
|
|
78
|
+
const job = jobs.get(String(id ?? ''))
|
|
79
|
+
if (!job) return null
|
|
80
|
+
return {
|
|
81
|
+
id: job.id,
|
|
82
|
+
state: job.state,
|
|
83
|
+
percent: job.percent,
|
|
84
|
+
phase: job.phase,
|
|
85
|
+
message: job.message,
|
|
86
|
+
lines: job.lines.slice(-12),
|
|
87
|
+
result: job.result,
|
|
88
|
+
error: job.error,
|
|
89
|
+
startedAt: job.startedAt,
|
|
90
|
+
}
|
|
91
|
+
}
|