dsh-sixlayer-memory 2.1.0 → 2.3.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.
@@ -0,0 +1,278 @@
1
+ /**
2
+ * hotkey.js —— 全局热键:按一个键,唤起系统语音听写(Win+H)。
3
+ *
4
+ * 为什么不用 Electron 的 globalShortcut:插件跑在宿主进程里,拿不到 Electron 主进程;
5
+ * 也不想为这个功能引原生模块。所以用一个 PowerShell 小进程注册系统热键
6
+ * (RegisterHotKey + 线程消息循环),零依赖,Windows 原生。
7
+ *
8
+ * 设计取舍:
9
+ * - 热键冲突(被别的软件占了)要能**明确告诉用户**,不能静默失效;
10
+ * - 子进程死了要能**自动重拉**,但不能疯狂重启;
11
+ * - 全部失败也只是"热键不可用",**绝不能影响记忆主流程**。
12
+ *
13
+ * @module memory/hotkey
14
+ */
15
+ import { spawn } from 'node:child_process'
16
+ import fs from 'node:fs'
17
+ import path from 'node:path'
18
+ import { fileURLToPath } from 'node:url'
19
+
20
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
21
+ export const HELPER = path.join(HERE, 'hotkey-helper.ps1')
22
+
23
+ /** 修饰键位(RegisterHotKey 的 fsModifiers)。 */
24
+ export const MOD = { alt: 1, ctrl: 2, control: 2, shift: 4, win: 8, meta: 8 }
25
+
26
+ export const DEFAULT_HOTKEY = 'Alt+V'
27
+
28
+ /**
29
+ * 解析热键字符串:`Alt+V`、`Ctrl+Shift+F9`、`F8`、`Alt+Space`。
30
+ * @param {string} spec
31
+ * @returns {{ok:boolean, mods:number, key:string, vk:number, label:string, reason?:string}}
32
+ */
33
+ export function parseHotkey(spec) {
34
+ const raw = String(spec ?? '').trim()
35
+ if (!raw) return { ok: false, mods: 0, key: '', vk: 0, label: '', reason: '空的热键' }
36
+ const parts = raw.split('+').map((s) => s.trim()).filter(Boolean)
37
+ if (parts.length === 0) return { ok: false, mods: 0, key: '', vk: 0, label: '', reason: '空的热键' }
38
+
39
+ let mods = 0
40
+ const names = []
41
+ const last = parts[parts.length - 1]
42
+ for (const p of parts.slice(0, -1)) {
43
+ const m = MOD[p.toLowerCase()]
44
+ if (!m) return { ok: false, mods: 0, key: '', vk: 0, label: '', reason: `不认识的修饰键:${p}` }
45
+ mods |= m
46
+ names.push(p.toLowerCase() === 'control' ? 'Ctrl' : p[0].toUpperCase() + p.slice(1).toLowerCase())
47
+ }
48
+
49
+ let key = last
50
+ let vk = 0
51
+ if (/^[A-Za-z]$/.test(key)) {
52
+ vk = key.toUpperCase().charCodeAt(0)
53
+ } else if (/^[0-9]$/.test(key)) {
54
+ vk = key.charCodeAt(0)
55
+ } else if (/^F([1-9]|1[0-9]|2[0-4])$/i.test(key)) {
56
+ vk = 0x70 + (Number(key.slice(1)) - 1)
57
+ key = key.toUpperCase()
58
+ } else if (/^space$/i.test(key)) {
59
+ vk = 0x20
60
+ key = 'Space'
61
+ } else if (/^enter$/i.test(key)) {
62
+ vk = 0x0d
63
+ key = 'Enter'
64
+ } else {
65
+ return { ok: false, mods: 0, key: '', vk: 0, label: '', reason: `不支持的按键:${key}` }
66
+ }
67
+
68
+ if (mods === 0) return { ok: false, mods: 0, key, vk, label: '', reason: '至少要带一个修饰键(Alt/Ctrl/Shift/Win),裸键会抢走正常打字' }
69
+ return { ok: true, mods, key: key.toUpperCase(), vk, label: [...names, key.toUpperCase()].join('+') }
70
+ }
71
+
72
+ /**
73
+ * 全局热键监听器。失败只记录、不抛给调用方。
74
+ */
75
+ export class HotkeyListener {
76
+ constructor({ key = DEFAULT_HOTKEY, action = 'dictation', onEvent = null, logger = null } = {}) {
77
+ this.spec = key
78
+ this.action = action
79
+ this.onEvent = onEvent
80
+ this.log = logger ?? (() => {})
81
+ this.child = null
82
+ this.state = 'idle' // idle | ready | error | stopped
83
+ this.lastError = ''
84
+ this.presses = 0
85
+ this.restarts = 0
86
+ this.stoppedByUs = false
87
+ this.parsed = parseHotkey(key)
88
+ }
89
+
90
+ get available() {
91
+ return this.parsed.ok
92
+ }
93
+
94
+ /** 启动。热键不合法或平台不对时返回 {ok:false, reason},不抛。 */
95
+ start() {
96
+ if (process.platform !== 'win32') return { ok: false, reason: '全局热键目前只支持 Windows' }
97
+ if (!this.parsed.ok) return { ok: false, reason: this.parsed.reason }
98
+ if (!fs.existsSync(HELPER)) return { ok: false, reason: '找不到 hotkey-helper.ps1' }
99
+ if (this.child) return { ok: true, already: true }
100
+ this.stoppedByUs = false
101
+ this._spawn()
102
+ return { ok: true, hotkey: this.parsed.label, action: this.action }
103
+ }
104
+
105
+ _spawn() {
106
+ let child
107
+ try {
108
+ child = spawn(
109
+ 'powershell.exe',
110
+ ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', HELPER, '-Key', this.parsed.key, '-Mods', String(this.parsed.mods), '-Action', this.action],
111
+ { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] },
112
+ )
113
+ } catch (error) {
114
+ this.state = 'error'
115
+ this.lastError = error.message
116
+ this.log(`热键启动失败:${error.message}`)
117
+ return
118
+ }
119
+ this.child = child
120
+
121
+ let buf = ''
122
+ child.stdout.setEncoding('utf8')
123
+ child.stdout.on('data', (chunk) => {
124
+ if (this.child !== child) return
125
+ buf += chunk
126
+ let i
127
+ while ((i = buf.indexOf('\n')) >= 0) {
128
+ const line = buf.slice(0, i).trim()
129
+ buf = buf.slice(i + 1)
130
+ this._onLine(line)
131
+ }
132
+ })
133
+ child.stderr.on('data', () => {})
134
+ child.on('error', (error) => {
135
+ if (this.child !== child) return
136
+ this.state = 'error'
137
+ this.lastError = error.message
138
+ })
139
+ child.on('exit', (code) => {
140
+ // 老的子进程(被 stop 掉的)退出时不能改当前状态
141
+ if (this.child !== child) return
142
+ this.child = null
143
+ if (this.stoppedByUs) {
144
+ this.state = 'stopped'
145
+ return
146
+ }
147
+ this.state = 'error'
148
+ // REGFAIL / BADKEY 已经写了具体原因,别再被"进程退出"盖掉
149
+ if (!this._fatalReason) this.lastError = `热键进程退出(code=${code})`
150
+ if (this.restarts < 5 && !this._fatalReason) {
151
+ this.restarts += 1
152
+ setTimeout(() => {
153
+ if (!this.stoppedByUs && !this.child) this._spawn()
154
+ }, 1000 * this.restarts)
155
+ }
156
+ })
157
+ }
158
+
159
+ _onLine(line) {
160
+ if (line === 'READY') {
161
+ this.state = 'ready'
162
+ this.lastError = ''
163
+ this._emit({ type: 'ready', hotkey: this.parsed.label })
164
+ } else if (line === 'PRESS') {
165
+ this.presses += 1
166
+ this._emit({ type: 'press', hotkey: this.parsed.label, count: this.presses })
167
+ } else if (line === 'REGFAIL') {
168
+ this.state = 'error'
169
+ this._fatalReason = `热键 ${this.parsed.label} 已被其它程序占用`
170
+ this.lastError = this._fatalReason
171
+ this._emit({ type: 'conflict', hotkey: this.parsed.label })
172
+ } else if (line === 'BADKEY') {
173
+ this.state = 'error'
174
+ this._fatalReason = '热键格式不支持'
175
+ this.lastError = this._fatalReason
176
+ }
177
+ }
178
+
179
+ _emit(event) {
180
+ try {
181
+ this.onEvent?.(event)
182
+ } catch (error) {
183
+ this.log(`热键回调出错:${error?.message ?? error}`)
184
+ }
185
+ }
186
+
187
+ stop() {
188
+ this.stoppedByUs = true
189
+ const child = this.child
190
+ this.child = null // 先置空:exit 回调看到 this.child !== child 就会跳过
191
+ if (child) {
192
+ try {
193
+ child.kill()
194
+ } catch {
195
+ /* 已经没了 */
196
+ }
197
+ }
198
+ this.state = 'stopped'
199
+ }
200
+
201
+ /**
202
+ * 运行时改键/改动作:正在跑就重启,没跑就只更新配置。
203
+ * @returns {{ok:boolean, restarted:boolean, reason?:string}}
204
+ */
205
+ reconfigure({ key, action } = {}) {
206
+ const wasRunning = Boolean(this.child) || this.state === 'ready'
207
+ this.stop()
208
+ if (key !== undefined) {
209
+ this.spec = String(key)
210
+ this.parsed = parseHotkey(this.spec)
211
+ }
212
+ if (action !== undefined) this.action = String(action)
213
+ this._fatalReason = ''
214
+ this.restarts = 0
215
+ if (!wasRunning) {
216
+ this.state = 'idle'
217
+ return { ok: this.parsed.ok, restarted: false, reason: this.parsed.ok ? undefined : this.parsed.reason }
218
+ }
219
+ const r = this.start()
220
+ return { ok: r.ok !== false, restarted: true, reason: r.reason }
221
+ }
222
+
223
+ status() {
224
+ return {
225
+ hotkey: this.parsed.label || this.spec,
226
+ action: this.action,
227
+ state: this.state,
228
+ presses: this.presses,
229
+ error: this.lastError,
230
+ available: this.parsed.ok,
231
+ }
232
+ }
233
+ }
234
+
235
+ // ---------- 配置:默认值 → 配置文件 → 工具写入的覆盖 ----------
236
+
237
+ /** 覆盖文件位置(跟其它 meta 文件放一起)。 */
238
+ export function overridesPath(dataDir) {
239
+ return path.join(String(dataDir ?? ''), 'meta', 'hotkey.json')
240
+ }
241
+
242
+ function readOverrides(dataDir) {
243
+ try {
244
+ const raw = fs.readFileSync(overridesPath(dataDir), 'utf8').replace(/^\uFEFF/, '')
245
+ const obj = JSON.parse(raw)
246
+ return obj && typeof obj === 'object' ? obj : {}
247
+ } catch {
248
+ return {}
249
+ }
250
+ }
251
+
252
+ /**
253
+ * 合并三层配置:cordis 配置 > 覆盖文件 > 默认值。
254
+ * 默认**关闭**:全局热键会抢系统按键,不主动开。
255
+ */
256
+ export function resolveHotkeyConfig(config = {}, dataDir = '') {
257
+ const stored = readOverrides(dataDir)
258
+ const pick = (k, fallback) => (config && config[k] !== undefined ? config[k] : stored[k] !== undefined ? stored[k] : fallback)
259
+ const action = String(pick('action', 'dictation'))
260
+ const ALLOWED = new Set(['dictation', 'asr', 'none'])
261
+ return {
262
+ enabled: Boolean(pick('enabled', false)),
263
+ key: String(pick('key', DEFAULT_HOTKEY)),
264
+ action: ALLOWED.has(action) ? action : 'dictation',
265
+ }
266
+ }
267
+
268
+ /** 写入覆盖文件(工具改键时用)。只写三个已知字段,避免脏数据。 */
269
+ export function saveHotkeyConfig(dataDir, patch = {}) {
270
+ const next = { ...readOverrides(dataDir) }
271
+ if (patch.key !== undefined) next.key = String(patch.key)
272
+ if (patch.action !== undefined) next.action = String(patch.action)
273
+ if (patch.enabled !== undefined) next.enabled = Boolean(patch.enabled)
274
+ const file = overridesPath(dataDir)
275
+ fs.mkdirSync(path.dirname(file), { recursive: true })
276
+ fs.writeFileSync(file, JSON.stringify(next, null, 2), 'utf8')
277
+ return next
278
+ }
@@ -12,6 +12,7 @@ import { listParts, compose } from '../parts/index.js'
12
12
  import { ingestQqSessions, affectReport } from './affect-events.js'
13
13
  import { ledgerInit, ledgerSync, ledgerVerify, healthLine } from './ledger.js'
14
14
  import { saveAffectReport } from './affect-report.js'
15
+ import { resolveHotkeyConfig, saveHotkeyConfig } from './hotkey.js'
15
16
 
16
17
  const textOut = (extra = {}) => ({
17
18
  type: 'object',
@@ -749,6 +750,166 @@ export function buildRegistry(store, host) {
749
750
  { label: '冲突记录', argsHint: 'mem_conflicts({ limit? })', needsOpen: true },
750
751
  )
751
752
 
753
+ add(
754
+ {
755
+ name: 'mem_hotkey',
756
+ description:
757
+ '全局热键:按一个键唤起系统语音听写(Win+H),像"按住说话"那样跟 AI 说话。' +
758
+ '不带参数就查状态;带 key/action/enabled 就改配置并立即生效(写进 memory-data/meta/hotkey.json)。' +
759
+ '默认关闭——热键会抢系统按键,开了才注册。',
760
+ parameters: {
761
+ type: 'object',
762
+ additionalProperties: false,
763
+ properties: {
764
+ key: { type: 'string', description: '热键,如 Alt+V / Ctrl+Shift+F9;必须带修饰键' },
765
+ action: {
766
+ type: 'string',
767
+ enum: ['dictation', 'asr', 'none'],
768
+ description: 'dictation=唤起系统听写;asr=录音并调 DeepSeek 识别后粘贴;none=只记录',
769
+ },
770
+ enabled: { type: 'boolean', description: '开或关' },
771
+ },
772
+ },
773
+ output: {
774
+ schema: textOut({
775
+ hotkey: { type: 'string' },
776
+ action: { type: 'string' },
777
+ state: { type: 'string' },
778
+ presses: { type: 'integer' },
779
+ available: { type: 'boolean' },
780
+ error: { type: 'string' },
781
+ }),
782
+ render: renderText,
783
+ },
784
+ isConcurrencySafe: () => true,
785
+ execute: async (args) => {
786
+ const ctl = host?.hotkey
787
+ if (!ctl) {
788
+ return { text: '热键服务不可用(插件降级模式)。', hotkey: '', action: '', state: 'unavailable', presses: 0, available: false, error: '降级模式' }
789
+ }
790
+ const wantsChange = args?.key !== undefined || args?.action !== undefined || args?.enabled !== undefined
791
+ if (wantsChange) {
792
+ const patch = {}
793
+ if (args?.key !== undefined) patch.key = args.key
794
+ if (args?.action !== undefined) patch.action = args.action
795
+ if (args?.enabled !== undefined) patch.enabled = args.enabled
796
+ saveHotkeyConfig(ctl.dataDir, patch)
797
+ const next = resolveHotkeyConfig({}, ctl.dataDir)
798
+ const r = ctl.listener.reconfigure({ key: next.key, action: next.action })
799
+ if (next.enabled && !ctl.listener.child) ctl.listener.start()
800
+ if (!next.enabled) ctl.listener.stop()
801
+ if (r.reason) ctl.listener.lastError = r.reason
802
+ }
803
+ const st = ctl.listener.status()
804
+ const lines = [
805
+ `热键:${st.hotkey || '(未设)'} · 动作:${st.action}`,
806
+ `状态:${st.state}${st.error ? `(${st.error})` : ''} · 已触发 ${st.presses} 次`,
807
+ st.state === 'ready'
808
+ ? '按下热键就会唤起 Windows 语音听写;说完文字会自动出现在光标处。'
809
+ : '热键当前没有在监听。用 enabled:true 打开,或换一个 key。',
810
+ ]
811
+ return { text: lines.join('\n'), ...st }
812
+ },
813
+ },
814
+ { label: '全局热键', argsHint: 'mem_hotkey({ key?, action?, enabled? })', needsOpen: false },
815
+ )
816
+
817
+ add(
818
+ {
819
+ name: 'mem_voice',
820
+ description:
821
+ '语音输入:不带参数查状态;start 开始录音、stop 停止并转写(DeepSeek ASR,失败自动走本地保底命令)、' +
822
+ 'file 直接转写一个已有音频文件。转写结果会粘到当前输入框(默认不自动回车)。',
823
+ parameters: {
824
+ type: 'object',
825
+ additionalProperties: false,
826
+ properties: {
827
+ action: { type: 'string', enum: ['status', 'start', 'stop', 'file'], description: '默认 status' },
828
+ file: { type: 'string', description: 'action=file 时的音频路径(16kHz 单声道 WAV 最佳)' },
829
+ },
830
+ },
831
+ output: {
832
+ schema: textOut({
833
+ state: { type: 'string' },
834
+ ok: { type: 'boolean' },
835
+ text: { type: 'string' },
836
+ via: { type: 'string' },
837
+ ms: { type: 'integer' },
838
+ reason: { type: 'string' },
839
+ file: { type: 'string' },
840
+ }),
841
+ render: renderText,
842
+ },
843
+ isConcurrencySafe: () => false,
844
+ execute: async (args) => {
845
+ const ctl = host?.voice
846
+ const action = String(args?.action ?? 'status')
847
+ if (!ctl) {
848
+ return { state: 'unavailable', ok: false, text: '', via: '', ms: 0, reason: '插件降级模式', file: '' }
849
+ }
850
+ if (action === 'start') {
851
+ const r = await ctl.recorder.start()
852
+ const st = r.ok ? 'recording' : 'idle'
853
+ return {
854
+ state: st,
855
+ ok: r.ok,
856
+ text: r.ok ? `开始录音(${r.device}),再调一次 stop 结束。` : `没开起来:${r.reason}`,
857
+ via: '',
858
+ ms: 0,
859
+ reason: r.reason ?? '',
860
+ file: r.file ?? '',
861
+ }
862
+ }
863
+ if (action === 'stop') {
864
+ const r = await ctl.toggle()
865
+ if (r?.stage === 'recording') {
866
+ return { state: 'recording', ok: true, text: '正在录音中…', via: '', ms: 0, reason: '', file: r.file ?? '' }
867
+ }
868
+ const ok = Boolean(r?.ok)
869
+ return {
870
+ state: ok ? 'done' : 'idle',
871
+ ok,
872
+ text: ok ? `识别完成(${r.via}/${r.ms}ms):${r.text}` : `失败:${r.reason ?? '未知'}`,
873
+ via: r?.via ?? '',
874
+ ms: Number(r?.ms ?? 0),
875
+ reason: r?.reason ?? '',
876
+ file: r?.file ?? '',
877
+ }
878
+ }
879
+ if (action === 'file') {
880
+ const file = String(args?.file ?? '').trim()
881
+ if (!file) return { state: 'idle', ok: false, text: '', via: '', ms: 0, reason: '需要 file', file: '' }
882
+ const r = await ctl.transcribeFile(file)
883
+ return {
884
+ state: r.ok ? 'done' : 'idle',
885
+ ok: r.ok,
886
+ text: r.ok ? `识别结果:${r.text}` : `失败:${r.reason}`,
887
+ via: r.via ?? '',
888
+ ms: Number(r.ms ?? 0),
889
+ reason: r.reason ?? '',
890
+ file,
891
+ }
892
+ }
893
+ const s = ctl.status()
894
+ return {
895
+ state: s.recording ? 'recording' : s.lastVoice?.ok ? 'done' : 'idle',
896
+ ok: true,
897
+ text: [
898
+ `录音:${s.recording ? '进行中' : '空闲'} · 设备:${s.device || '(自动)'}`,
899
+ `识别:${s.baseUrl}(云端)${s.localCommand ? ' / 本地保底已配' : ' / 本地保底未配'}`,
900
+ s.lastVoice ? `上次:${s.lastVoice.ok ? `「${s.lastVoice.text}」(${s.lastVoice.via})` : s.lastVoice.reason}` : '上次:还没有',
901
+ '热键动作设成 asr 后,按一下开始录、再按一下结束并转写。',
902
+ ].join('\n'),
903
+ via: s.lastVoice?.via ?? '',
904
+ ms: Number(s.lastVoice?.ms ?? 0),
905
+ reason: '',
906
+ file: s.lastVoice?.file ?? '',
907
+ }
908
+ },
909
+ },
910
+ { label: '语音输入', argsHint: 'mem_voice({ action?: start|stop|file|status, file? })', needsOpen: false },
911
+ )
912
+
752
913
  // ---------- 交接与体检(迁移自 luanyujia-workbench 记忆机制) ----------
753
914
 
754
915
  const SECTION_LABELS = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sixlayer-memory",
3
- "version": "2.1.0",
3
+ "version": "2.3.0",
4
4
  "private": false,
5
5
  "description": "DSH 工作台:六层记忆底座(每轮自动召回 + 候选沉淀 + 闸门审计)+ 零件化,支持 QQ 随身使用。",
6
6
  "type": "module",
@@ -63,6 +63,8 @@
63
63
  "mem_review",
64
64
  "mem_pending",
65
65
  "mem_conflicts",
66
+ "mem_hotkey",
67
+ "mem_voice",
66
68
  "mem_resume",
67
69
  "mem_handoff",
68
70
  "mem_check",
@@ -0,0 +1,100 @@
1
+ /**
2
+ * bump-market-version.mjs —— 把社区索引里本插件的 version 字段更新到指定版本,并提 PR。
3
+ *
4
+ * 用法:$env:GH='ghp_...'; node tools/bump-market-version.mjs 2.1.0
5
+ *
6
+ * 流程:同步 fork → 改 community.json 里我们那一条的 version → 提交到 fork → 向上游提 PR。
7
+ * 只动自己那一条,不动别人的条目。
8
+ */
9
+ import fs from 'node:fs'
10
+
11
+ const TOKEN = process.env.GH
12
+ const VERSION = process.argv[2]
13
+ const PKG = 'dsh-sixlayer-memory'
14
+ const UP = { owner: 'zhu1090093659', repo: 'dsh-community-plugins' }
15
+ const ME = 'z9134'
16
+ const FILE = 'community.json'
17
+
18
+ if (!TOKEN) throw new Error('缺少 GH 环境变量')
19
+ if (!/^\d+\.\d+\.\d+$/.test(VERSION ?? '')) throw new Error('用法:node bump-market-version.mjs <x.y.z>')
20
+
21
+ const H = {
22
+ authorization: `Bearer ${TOKEN}`,
23
+ accept: 'application/vnd.github+json',
24
+ 'x-github-api-version': '2022-11-28',
25
+ 'user-agent': 'dsh-sixlayer-market-bump',
26
+ }
27
+ const API = 'https://api.github.com'
28
+
29
+ async function call(method, url, body) {
30
+ const res = await fetch(API + url, {
31
+ method,
32
+ headers: { ...H, ...(body ? { 'content-type': 'application/json' } : {}) },
33
+ body: body ? JSON.stringify(body) : undefined,
34
+ })
35
+ const text = await res.text()
36
+ let json = null
37
+ try { json = text ? JSON.parse(text) : null } catch { /* 非 JSON */ }
38
+ if (!res.ok) throw new Error(`${method} ${url} -> ${res.status} ${json?.message ?? text.slice(0, 200)}`)
39
+ return json
40
+ }
41
+
42
+ // 1) 让 fork 和上游对齐(否则 PR diff 会把别人的提交也带上)
43
+ try {
44
+ const merged = await call('POST', `/repos/${ME}/${UP.repo}/merge-upstream`, { branch: 'main' })
45
+ console.log('fork 同步:', merged.message ?? merged.status ?? 'ok')
46
+ } catch (error) {
47
+ console.log('fork 同步失败(可能已是最新):', error.message)
48
+ }
49
+
50
+ // 2) 读 fork 上的文件(带 sha)
51
+ const file = await call('GET', `/repos/${ME}/${UP.repo}/contents/${FILE}?ref=main`)
52
+ const original = Buffer.from(file.content, 'base64').toString('utf8')
53
+ const entries = JSON.parse(original)
54
+ const hit = entries.find((e) => e.id === PKG)
55
+ if (!hit) throw new Error('上游没有这个条目,先跑 open-market-pr')
56
+ console.log(`当前 version: ${hit.version} → ${VERSION}`)
57
+ if (hit.version === VERSION) {
58
+ console.log('已经是最新,不需要改')
59
+ process.exit(0)
60
+ }
61
+
62
+ const keepNewline = original.endsWith('\n')
63
+
64
+ // 安全闸:fork 必须和上游条目数一致,否则这次提交会把别人的条目改掉/删掉
65
+ const upstream = JSON.parse(await (await fetch(`https://raw.githubusercontent.com/${UP.owner}/${UP.repo}/main/${FILE}`)).text())
66
+ if (entries.length !== upstream.length) {
67
+ throw new Error(`fork 与上游不一致(${entries.length} vs ${upstream.length} 条),先同步 fork 再改,否则会误删别人的条目`)
68
+ }
69
+ if (!hit.version) throw new Error('条目里没有 version 字段(fork 太旧),先同步 fork')
70
+
71
+ hit.version = VERSION
72
+ const next = JSON.stringify(entries, null, 2) + (keepNewline ? '\n' : '')
73
+
74
+ const put = await call('PUT', `/repos/${ME}/${UP.repo}/contents/${FILE}`, {
75
+ message: `chore(index): bump ${PKG} to ${VERSION}`,
76
+ content: Buffer.from(next, 'utf8').toString('base64'),
77
+ sha: file.sha,
78
+ branch: 'main',
79
+ })
80
+ console.log('已提交到 fork:', put.commit.sha.slice(0, 10))
81
+
82
+ const pr = await call('POST', `/repos/${UP.owner}/${UP.repo}/pulls`, {
83
+ title: `chore(index): bump ${PKG} to ${VERSION}`,
84
+ head: `${ME}:main`,
85
+ base: 'main',
86
+ body: [
87
+ '### 变更',
88
+ `- \`${PKG}\` 的 \`version\` 从 \`${hit.version}\` 更新为 \`${VERSION}\``,
89
+ '',
90
+ '### 为什么',
91
+ `${VERSION} 已发布到 npm(\`npm view ${PKG} dist-tags\` → \`latest: ${VERSION}\`)。`,
92
+ '市场按条目里的 version 安装(`pnpm add <npm>@<version>`),不更新的话用户装到的还是旧版本。',
93
+ '',
94
+ '### 检查',
95
+ `- [x] \`npm view ${PKG} version\` = ${VERSION}`,
96
+ '- [x] 只改了自己这一条,其他条目未动',
97
+ ].join('\n'),
98
+ })
99
+ console.log('PR:', pr.html_url)
100
+ fs.writeFileSync('D:/001/CH002/dist/market-pr/last-bump.json', JSON.stringify({ version: VERSION, pr: pr.html_url }, null, 2), 'utf8')
package/tools/monitor.mjs CHANGED
@@ -95,6 +95,23 @@ async function snapshot() {
95
95
  snap.pr121 = { error: error.message }
96
96
  }
97
97
 
98
+ // 版本号 PR:合并了没有 / 有没有人回话
99
+ try {
100
+ const pr = await got('https://api.github.com/repos/zhu1090093659/dsh-community-plugins/pulls/290')
101
+ const comments = await got('https://api.github.com/repos/zhu1090093659/dsh-community-plugins/issues/290/comments?per_page=50')
102
+ const last = comments[comments.length - 1]
103
+ snap.pr290 = {
104
+ state: pr.state,
105
+ merged: pr.merged,
106
+ mergeableState: pr.mergeable_state,
107
+ count: comments.length,
108
+ lastAt: last?.created_at ?? '',
109
+ lastBy: last?.user?.login ?? '',
110
+ }
111
+ } catch (error) {
112
+ snap.pr290 = { error: error.message }
113
+ }
114
+
98
115
  try {
99
116
  const index = await got(INDEX_URL, 30000)
100
117
  const hit = (index.plugins ?? []).find((p) => p.name === PKG)
@@ -163,6 +180,18 @@ function render(prev, cur) {
163
180
  }
164
181
  }
165
182
 
183
+ // 版本号 PR:只报状态变化和新评论
184
+ if (cur.pr290 && !cur.pr290.error) {
185
+ const p = prev?.pr290
186
+ const now = cur.pr290.merged ? '已合并' : cur.pr290.state === 'closed' ? '已关闭' : '待合并'
187
+ if (!p || p.state !== cur.pr290.state || p.merged !== cur.pr290.merged) {
188
+ out.push(`版本号 PR #290:${now}`)
189
+ }
190
+ if (p && cur.pr290.lastAt && cur.pr290.lastAt !== p.lastAt) {
191
+ out.push(` #290 有新评论:${cur.pr290.lastBy}`)
192
+ }
193
+ }
194
+
166
195
  if (cur.market && !cur.market.error) {
167
196
  const changed = prev?.market && !prev.market.error && prev.market.inIndex !== cur.market.inIndex
168
197
  const ver = cur.market.version ? ` · 索引版本 ${cur.market.version}` : ''