@unihc/dsh-process-manager 0.0.0-stage → 1.0.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/operations.js ADDED
@@ -0,0 +1,540 @@
1
+ /**
2
+ * Host-side orchestration: one cached snapshot per moment, per-session
3
+ * snapshot files for the panel, and the user-confirmed mutation paths. Both
4
+ * the panel commands and the read-only agent tools go through this module so
5
+ * they cannot drift apart.
6
+ */
7
+ import { mkdir, rename, rm, writeFile } from 'node:fs/promises'
8
+ import path from 'node:path'
9
+ import { randomUUID } from 'node:crypto'
10
+ import { normalizeSnapshot } from './collector.js'
11
+ import { buildSnapshot, compactSnapshot, compactStartup, formatBytes } from './model.js'
12
+ import { describeProcess, PROTECTED_PROCESS_NAMES } from './catalog.js'
13
+ import { collectSnapshot, inspectTarget, isWindows, openWindowsTool, setStartupEntry, stopProcesses } from './native.js'
14
+
15
+ export const REPORT_DIR = 'process-reports'
16
+ const SNAPSHOT_TTL_MS = 1500
17
+
18
+ let cache = { at: 0, snapshot: null, pending: null }
19
+
20
+ function fail(code, message, extra = {}) {
21
+ const error = new Error(message)
22
+ error.code = code
23
+ Object.assign(error, extra)
24
+ return error
25
+ }
26
+
27
+ export function invalidateSnapshot() {
28
+ cache = { at: 0, snapshot: null, pending: null }
29
+ }
30
+
31
+ export async function getSnapshot({ force = false } = {}) {
32
+ if (!isWindows()) throw fail('UNSUPPORTED_PLATFORM', '该功能仅支持 Windows')
33
+ if (!force && cache.snapshot !== null && Date.now() - cache.at < SNAPSHOT_TTL_MS) {
34
+ return cache.snapshot
35
+ }
36
+ if (cache.pending !== null) return cache.pending
37
+ cache.pending = (async () => {
38
+ const raw = await collectSnapshot()
39
+ const snapshot = buildSnapshot(normalizeSnapshot(raw))
40
+ cache = { at: Date.now(), snapshot, pending: null }
41
+ return snapshot
42
+ })()
43
+ try {
44
+ return await cache.pending
45
+ } catch (error) {
46
+ cache.pending = null
47
+ throw error
48
+ }
49
+ }
50
+
51
+ export function snapshotRelativePath(sessionId) {
52
+ return `${REPORT_DIR}/snapshot-${sessionId}.json`
53
+ }
54
+
55
+ async function writeSnapshotFile(cwd, sessionId, snapshot) {
56
+ const dir = path.join(cwd, REPORT_DIR)
57
+ await mkdir(dir, { recursive: true })
58
+ const target = path.join(dir, `snapshot-${sessionId}.json`)
59
+ const temp = path.join(dir, `.snapshot-${sessionId}.${randomUUID()}.tmp`)
60
+ try {
61
+ await writeFile(temp, JSON.stringify({ v: 1, generated_at: new Date().toISOString(), snapshot }), 'utf8')
62
+ await rename(temp, target)
63
+ } catch (error) {
64
+ await rm(temp, { force: true }).catch(() => {})
65
+ throw error
66
+ }
67
+ return snapshotRelativePath(sessionId)
68
+ }
69
+
70
+ /** The panel's refresh: collect, persist for the authenticated file read, ack. */
71
+ export async function createSnapshotFile(agent) {
72
+ const cwd = agent?.session?.header?.cwd
73
+ const sessionId = agent?.session?.header?.id
74
+ if (typeof cwd !== 'string' || cwd === '' || typeof sessionId !== 'string' || sessionId === '') {
75
+ throw fail('NO_WORKSPACE', '当前会话没有工作目录,无法保存进程快照')
76
+ }
77
+ const snapshot = await getSnapshot()
78
+ const relative = await writeSnapshotFile(cwd, sessionId, snapshot)
79
+ return {
80
+ ok: true,
81
+ path: relative,
82
+ generated_at: snapshot.collected_at,
83
+ summary: snapshot.summary,
84
+ startup_summary: snapshot.startup.summary,
85
+ warnings: snapshot.warnings,
86
+ }
87
+ }
88
+
89
+ function normalizePath(value) {
90
+ return String(value ?? '').replace(/\//g, '\\').toLowerCase()
91
+ }
92
+
93
+ function protectedPidsOf(snapshot) {
94
+ const pids = new Set([0, 4])
95
+ const byPid = new Map(snapshot.processes.map(item => [item.pid, item]))
96
+ let current = byPid.get(process.pid)
97
+ let guard = 0
98
+ while (current !== undefined && guard < 16) {
99
+ pids.add(current.pid)
100
+ current = byPid.get(current.ppid)
101
+ guard += 1
102
+ }
103
+ return [...pids]
104
+ }
105
+
106
+ function childMap(processes) {
107
+ const map = new Map()
108
+ for (const item of processes) {
109
+ const list = map.get(item.ppid) ?? []
110
+ list.push(item)
111
+ map.set(item.ppid, list)
112
+ }
113
+ return map
114
+ }
115
+
116
+ function validateTarget(raw) {
117
+ const pid = Number(raw?.pid)
118
+ if (!Number.isInteger(pid) || pid <= 0) throw fail('BAD_ARGS', '进程 ID 非法')
119
+ const name = String(raw?.name ?? '').trim()
120
+ if (name === '' || name.length > 260) throw fail('BAD_ARGS', '进程名非法')
121
+ const target = { pid, name }
122
+ if (typeof raw?.path === 'string' && raw.path !== '') target.path = raw.path.slice(0, 1000)
123
+ if (typeof raw?.started === 'string' && raw.started !== '') target.started = raw.started.slice(0, 64)
124
+ return target
125
+ }
126
+
127
+ /**
128
+ * Stop one or more processes. `mode: 'close'` asks the main window to close;
129
+ * `mode: 'kill'` force-terminates the target app and its descendants.
130
+ */
131
+ export async function stopTargets(payload, { signal, elevate = false } = {}) {
132
+ const mode = String(payload?.mode ?? '')
133
+ if (mode !== 'close' && mode !== 'kill') throw fail('BAD_ARGS', '不支持的操作方式')
134
+ const rawTargets = Array.isArray(payload?.targets) ? payload.targets : []
135
+ if (rawTargets.length === 0 || rawTargets.length > 60) throw fail('BAD_ARGS', '目标进程数量不合法')
136
+ if (mode === 'kill' && String(payload?.confirm ?? '') !== '结束') {
137
+ throw fail('CONFIRM_REQUIRED', '强制结束需要确认串「结束」')
138
+ }
139
+ const targets = rawTargets.map(validateTarget)
140
+ const snapshot = await getSnapshot()
141
+ const byPid = new Map(snapshot.processes.map(item => [item.pid, item]))
142
+ for (const target of targets) {
143
+ const live = byPid.get(target.pid)
144
+ if (live === undefined) continue
145
+ if (live.risk === 'critical' || live.risk === 'protected') {
146
+ throw fail('PROTECTED', `${live.name} 是关键进程,面板不会结束它`)
147
+ }
148
+ }
149
+
150
+ let finalTargets = targets.map(target => ({ ...target }))
151
+ if (mode === 'kill') {
152
+ const children = childMap(snapshot.processes)
153
+ const seen = new Set(finalTargets.map(target => target.pid))
154
+ const queue = [...finalTargets.map(target => target.pid)]
155
+ while (queue.length > 0) {
156
+ const current = queue.shift()
157
+ for (const child of children.get(current) ?? []) {
158
+ if (seen.has(child.pid)) continue
159
+ seen.add(child.pid)
160
+ queue.push(child.pid)
161
+ finalTargets.push({
162
+ pid: child.pid,
163
+ name: child.name,
164
+ ...(child.path === '' ? {} : { path: child.path }),
165
+ ...(child.started_at === '' ? {} : { started: child.started_at }),
166
+ })
167
+ }
168
+ }
169
+ }
170
+
171
+ const protectedPids = new Set(protectedPidsOf(snapshot))
172
+ const protectedNames = new Set([...PROTECTED_PROCESS_NAMES])
173
+ for (const target of finalTargets) {
174
+ if (protectedPids.has(target.pid)) {
175
+ throw fail('PROTECTED', '包含受保护的进程(Windows 关键进程或 DeepSeek Harness 本身),操作已取消')
176
+ }
177
+ if (protectedNames.has(target.name.toLowerCase())) {
178
+ throw fail('PROTECTED', `${target.name} 是 Windows 关键进程,面板不会结束它`)
179
+ }
180
+ }
181
+
182
+ const result = await stopProcesses({
183
+ targets: finalTargets,
184
+ mode,
185
+ protect: { names: [...protectedNames], pids: [...protectedPids] },
186
+ }, { signal, elevate }).catch((error) => {
187
+ const results = Array.isArray(error?.results) ? error.results : []
188
+ if (results.length > 0 && results.every(item => item.code === 'NO_WINDOW')) {
189
+ throw fail('NO_WINDOW', '该应用没有可关闭的主窗口,请改用强制结束')
190
+ }
191
+ if (!elevate && results.some(item => item.code === 'ACCESS_DENIED')) {
192
+ throw fail('ELEVATION_REQUIRED', '结束部分进程需要管理员权限', { results })
193
+ }
194
+ throw error
195
+ })
196
+ invalidateSnapshot()
197
+ return {
198
+ ok: true,
199
+ mode,
200
+ elevated: elevate,
201
+ stopped: (result.results ?? []).filter(item => item.ok).map(item => item.pid),
202
+ results: result.results ?? [],
203
+ message: mode === 'close' ? '已请求正常关闭' : '已结束所选进程',
204
+ }
205
+ }
206
+
207
+ function findStartupEntry(snapshot, payload) {
208
+ const source = String(payload?.source ?? '')
209
+ const detail = payload?.detail ?? {}
210
+ const entries = snapshot.startup.entries
211
+ if (source === 'run') {
212
+ return entries.find(entry => entry.source === 'run'
213
+ && entry.detail.hive === detail.hive
214
+ && entry.detail.key === detail.key
215
+ && entry.detail.name === detail.name)
216
+ }
217
+ if (source === 'folder') {
218
+ return entries.find(entry => entry.source === 'folder'
219
+ && entry.detail.scope === detail.scope
220
+ && entry.detail.file === detail.file)
221
+ }
222
+ if (source === 'task') {
223
+ return entries.find(entry => entry.source === 'task'
224
+ && entry.detail.path === detail.path
225
+ && entry.detail.name === detail.name)
226
+ }
227
+ if (source === 'service') {
228
+ return entries.find(entry => entry.source === 'service' && entry.detail.name === detail.name)
229
+ }
230
+ return undefined
231
+ }
232
+
233
+ /** Enable or disable one discovered startup entry, re-validated against a fresh snapshot. */
234
+ export async function toggleStartup(payload, { signal, elevate = false } = {}) {
235
+ const source = String(payload?.source ?? '')
236
+ if (!['run', 'folder', 'task', 'service'].includes(source)) throw fail('BAD_ARGS', '不支持的启动项类型')
237
+ const enabled = payload?.enabled === true
238
+ if (!enabled && String(payload?.confirm ?? '') !== '禁用') {
239
+ throw fail('CONFIRM_REQUIRED', '禁用启动项需要确认串「禁用」')
240
+ }
241
+ const snapshot = await getSnapshot()
242
+ const entry = findStartupEntry(snapshot, payload)
243
+ if (entry === undefined) throw fail('STALE_ENTRY', '启动项已不存在或已被修改,请刷新后重试')
244
+ if (entry.system === true || entry.protected_reason !== null || entry.risk === 'protected') {
245
+ throw fail('PROTECTED', entry.protected_reason || 'Windows 系统项不在面板修改范围内')
246
+ }
247
+
248
+ let nativePayload
249
+ if (source === 'run') {
250
+ const { hive, key, name } = entry.detail
251
+ if (key === 'RunOnce' || key === 'RunOnce32') throw fail('UNSUPPORTED', '一次性启动项不支持开关')
252
+ nativePayload = { source, hive, key, name, enabled, expect: entry.command }
253
+ } else if (source === 'folder') {
254
+ const { scope, file } = entry.detail
255
+ nativePayload = { source, scope, file, enabled, expect: entry.exe_path || '' }
256
+ } else if (source === 'task') {
257
+ const { path: taskPath, name: taskName } = entry.detail
258
+ nativePayload = { source, taskPath, taskName, enabled }
259
+ } else {
260
+ const { name: serviceName, delayed } = entry.detail
261
+ nativePayload = {
262
+ source,
263
+ serviceName,
264
+ enabled,
265
+ delayed: delayed === true,
266
+ stopRunning: payload?.stopRunning === true,
267
+ }
268
+ }
269
+ const result = await setStartupEntry(nativePayload, { signal, elevate })
270
+ invalidateSnapshot()
271
+ return {
272
+ ok: true,
273
+ source,
274
+ enabled: result.enabled === true,
275
+ elevated: elevate,
276
+ message: result.message ?? (result.enabled ? '已启用' : '已禁用'),
277
+ }
278
+ }
279
+
280
+ function samePath(a, b) {
281
+ return normalizePath(a) !== '' && normalizePath(a) === normalizePath(b)
282
+ }
283
+
284
+ /** Detail for one process or executable, shared by the command and the tool. */
285
+ export async function inspectProcess(payload, { signal } = {}) {
286
+ const snapshot = await getSnapshot()
287
+ let pid = Number(payload?.pid ?? 0)
288
+ let targetPath = typeof payload?.path === 'string' ? payload.path.trim() : ''
289
+ const name = typeof payload?.name === 'string' ? payload.name.trim().toLowerCase() : ''
290
+ if (pid > 0) {
291
+ const known = snapshot.processes.find(item => item.pid === pid)
292
+ if (known !== undefined && targetPath === '') targetPath = known.path
293
+ } else if (targetPath === '' && name !== '') {
294
+ const matches = snapshot.processes.filter(item => item.name.toLowerCase() === name)
295
+ if (matches.length === 0) throw fail('ITEM_NOT_FOUND', '找不到该进程')
296
+ const first = matches[0]
297
+ pid = first.pid
298
+ targetPath = first.path
299
+ } else if (targetPath === '') {
300
+ throw fail('BAD_ARGS', '需要 pid、name 或 path')
301
+ }
302
+
303
+ const raw = await inspectTarget({ pid: pid > 0 ? pid : 0, path: targetPath }, { signal })
304
+ const services = (raw.services ?? []).map(item => ({
305
+ name: String(item.Name ?? ''),
306
+ display: String(item.DisplayName ?? ''),
307
+ description: String(item.Description ?? ''),
308
+ state: String(item.State ?? ''),
309
+ start: String(item.StartMode ?? ''),
310
+ pid: Number(item.ProcessId ?? 0),
311
+ }))
312
+ const info = describeProcess({
313
+ name: raw.name,
314
+ company: raw.company,
315
+ product: raw.product,
316
+ description: raw.description,
317
+ path: raw.path,
318
+ services,
319
+ }, 'zh')
320
+ const relatedStartup = snapshot.startup.entries
321
+ .filter(entry => samePath(entry.exe_path, raw.path))
322
+ .map(entry => ({
323
+ source: entry.source,
324
+ label: entry.label,
325
+ enabled: entry.enabled,
326
+ detail: entry.detail,
327
+ id: entry.id,
328
+ }))
329
+ const runningPids = snapshot.processes
330
+ .filter(item => samePath(item.path, raw.path))
331
+ .map(item => item.pid)
332
+ return {
333
+ ok: true,
334
+ pid: pid > 0 ? pid : null,
335
+ path: raw.path,
336
+ name: raw.name,
337
+ command_line: raw.command_line,
338
+ started_at: raw.started_at,
339
+ company: raw.company,
340
+ product: raw.product,
341
+ description: raw.description,
342
+ version: raw.version,
343
+ size_bytes: raw.size_bytes,
344
+ created_at: raw.created_at,
345
+ modified_at: raw.modified_at,
346
+ signature_status: raw.signature_status,
347
+ signature_signer: raw.signature_signer,
348
+ services,
349
+ parents: raw.parents ?? [],
350
+ related_startup: relatedStartup,
351
+ running_pids: runningPids,
352
+ label: info.label,
353
+ label_en: info.labelEn,
354
+ purpose: info.purpose,
355
+ purpose_en: info.purposeEn,
356
+ risk: info.risk,
357
+ protected_reason: info.protectedReason,
358
+ vendor: info.vendor,
359
+ hash_like: info.hashLike,
360
+ }
361
+ }
362
+
363
+ const zhSystem = '你是只读的 Windows 进程分析助手。请根据给定的真实采集事实,用简体中文解释这个进程或启动项是什么、属于哪个应用、为什么在运行、结束它或禁用自启会产生什么影响。要具体、简洁,对不确定的地方说明依据。绝不声称已经执行过任何操作,也不要建议用户关闭 Windows 关键进程。'
364
+
365
+ const enSystem = 'You are a read-only Windows process analyst. Explain, from the supplied facts, what the process or startup entry is, which application it belongs to, why it runs, and what stopping it or disabling autostart would affect. Be concrete and concise and honest about uncertainty. Never claim to have performed an action and never suggest stopping core Windows processes.'
366
+
367
+ function explainFacts(detail, lang) {
368
+ const lines = []
369
+ const en = lang === 'en'
370
+ const push = (label, value) => {
371
+ if (value !== undefined && value !== null && String(value) !== '') lines.push(`${label}${en ? ': ' : ':'}${value}`)
372
+ }
373
+ push(en ? 'Name' : '名称', detail.name)
374
+ push(en ? 'Path' : '路径', detail.path)
375
+ push(en ? 'Publisher' : '发布者', detail.company)
376
+ push(en ? 'Product' : '产品', detail.product)
377
+ push(en ? 'Description' : '文件描述', detail.description)
378
+ push(en ? 'Version' : '版本', detail.version)
379
+ push(en ? 'Command line' : '命令行', detail.command_line)
380
+ push(en ? 'Signature' : '签名', detail.signature_status === 'Valid' ? (en ? `Valid (${detail.signature_signer})` : `有效(${detail.signature_signer})`) : detail.signature_status)
381
+ push(en ? 'Running PIDs' : '运行中的 PID', detail.running_pids?.join(', '))
382
+ push(en ? 'Hosted services' : '托管服务', (detail.services ?? []).map(item => `${item.display || item.name}${item.description ? `(${item.description.slice(0, 120)})` : ''}`).join('; '))
383
+ push(en ? 'Startup entries' : '关联启动项', (detail.related_startup ?? []).map(item => `${item.label}${item.enabled ? (en ? ' [enabled]' : '[已启用]') : (en ? ' [disabled]' : '[已禁用]')}`).join('; '))
384
+ push(en ? 'Panel verdict' : '面板判断', en ? `${detail.label_en} · ${detail.purpose_en ?? ''}` : `${detail.label} · ${detail.purpose ?? ''}`)
385
+ return lines.join('\n')
386
+ }
387
+
388
+ export async function explainProcess(ctx, payload, { signal, sessionId } = {}) {
389
+ const lang = payload?.lang === 'en' ? 'en' : 'zh'
390
+ const detail = await inspectProcess(payload ?? {}, { signal })
391
+ const selection = ctx.agentDefaultModel.currentSelection()
392
+ const prompt = [
393
+ lang === 'en'
394
+ ? 'Facts collected read-only from Windows. Explain in at most 250 words, with three numbered points: 1) what application or component this is; 2) what it is doing and whether it is needed; 3) what happens if it is stopped or its autostart is disabled, and what you recommend.'
395
+ : '以下是从本机只读采集到的事实。请控制在 250 字左右,分 3 点回答:1)这最可能是什么应用/系统组件;2)它现在在做什么、是否必要;3)关掉它或取消开机自启会有什么影响、建议怎么处理。',
396
+ lang === 'en'
397
+ ? 'Do not call tools. Do not claim any action was taken.'
398
+ : '不要调用工具,不要声称已经执行过任何操作。',
399
+ '',
400
+ explainFacts(detail, lang),
401
+ ].join('\n')
402
+
403
+ const options = {
404
+ provider: selection.provider,
405
+ model: selection.model,
406
+ ...(selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort }),
407
+ system: lang === 'en' ? enSystem : zhSystem,
408
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
409
+ maxTokens: 800,
410
+ signal,
411
+ ...(typeof sessionId === 'string' && sessionId !== '' ? { sessionId } : {}),
412
+ }
413
+ let text = ''
414
+ for await (const chunk of ctx.llm.stream(options)) {
415
+ if (chunk.type === 'text-delta') text += chunk.text
416
+ else if (chunk.type === 'block-end' && chunk.block?.type === 'text' && text === '') text = chunk.block.text
417
+ else if (chunk.type === 'finish') {
418
+ if (chunk.reason.kind === 'error' || chunk.reason.kind === 'aborted') {
419
+ const failure = chunk.reason.failure
420
+ throw fail(failure?.code ?? 'AI_FAILED', failure?.message ?? 'AI 解读失败')
421
+ }
422
+ }
423
+ }
424
+ text = text.trim()
425
+ if (text === '') throw fail('AI_EMPTY', 'AI 没有返回内容,请稍后重试')
426
+ return { ok: true, text, label: detail.label, label_en: detail.label_en }
427
+ }
428
+
429
+ export function openTool(payload) {
430
+ const tool = String(payload?.tool ?? '')
431
+ const result = openWindowsTool(tool, typeof payload?.path === 'string' ? payload.path : undefined)
432
+ return { ok: true, tool, ...result }
433
+ }
434
+
435
+ export function describeSnapshotForTool(snapshot, { query = '', sort = 'memory', limit = 40, lang = 'zh' } = {}) {
436
+ const compact = compactSnapshot(snapshot, { limit: 80 })
437
+ const needle = String(query ?? '').trim().toLowerCase()
438
+ let groups = compact.groups
439
+ if (needle !== '') {
440
+ groups = snapshot.groups.filter(group => {
441
+ if (String(group.pids).includes(needle)) return true
442
+ const haystack = [group.label, group.label_en, group.publisher, group.purpose, group.purpose_en, group.key].join(' ').toLowerCase()
443
+ return haystack.includes(needle)
444
+ }).slice(0, 80).map(group => ({
445
+ label: group.label,
446
+ label_en: group.label_en,
447
+ publisher: group.publisher,
448
+ kind: group.kind,
449
+ risk: group.risk,
450
+ process_count: group.process_count,
451
+ mem_bytes: group.mem_bytes,
452
+ cpu_percent: group.cpu_percent,
453
+ autostart: group.autostart,
454
+ purpose: group.purpose,
455
+ pids: group.pids.slice(0, 20),
456
+ }))
457
+ }
458
+ const sorted = [...groups].sort((a, b) => {
459
+ if (sort === 'cpu') return b.cpu_percent - a.cpu_percent
460
+ if (sort === 'name') return String(a.label_en ?? a.label).localeCompare(String(b.label_en ?? b.label))
461
+ return b.mem_bytes - a.mem_bytes
462
+ }).slice(0, Math.max(1, Math.min(120, Number(limit) || 40)))
463
+ return {
464
+ collected_at: snapshot.collected_at,
465
+ summary: snapshot.summary,
466
+ startup_summary: snapshot.startup.summary,
467
+ groups: sorted,
468
+ lang,
469
+ }
470
+ }
471
+
472
+ export function renderSnapshotText(value, lang = 'zh') {
473
+ const en = lang === 'en'
474
+ const lines = []
475
+ lines.push(en ? 'Windows processes (read-only snapshot)' : 'Windows 进程(只读快照)')
476
+ lines.push(en
477
+ ? `${value.summary.process_count} processes in ${value.summary.group_count} apps/groups; memory ${formatBytes(value.summary.mem_bytes)}; CPU ${value.summary.cpu_percent.toFixed(1)}%; ${value.summary.autostart_running} running from an autostart entry`
478
+ : `共 ${value.summary.process_count} 个进程,分 ${value.summary.group_count} 组;内存 ${formatBytes(value.summary.mem_bytes)};CPU ${value.summary.cpu_percent.toFixed(1)}%;其中 ${value.summary.autostart_running} 个由开机自启拉起`)
479
+ for (const group of value.groups) {
480
+ lines.push(`- ${en ? group.label_en : group.label}${group.publisher ? ` · ${group.publisher}` : ''} · ${group.process_count} 个进程 · ${formatBytes(group.mem_bytes)} · CPU ${group.cpu_percent.toFixed(1)}%${group.autostart ? (en ? ' · autostart' : ' · 开机自启') : ''}`)
481
+ lines.push(` ${en ? group.purpose_en || group.purpose : group.purpose}`)
482
+ lines.push(` PID: ${group.pids.join(', ')}`)
483
+ }
484
+ lines.push(en
485
+ ? 'This tool is read-only. Ending processes and toggling startup entries happen only in the “Processes and startup” right-sidebar panel, confirmed by the user.'
486
+ : '本工具只读;结束进程与启停开机自启只在右侧栏「进程与启动项」面板里由用户确认执行。')
487
+ return lines.join('\n')
488
+ }
489
+
490
+ export function renderStartupText(value, lang = 'zh') {
491
+ const en = lang === 'en'
492
+ const lines = []
493
+ lines.push(en ? 'Startup entries (read-only snapshot)' : '开机启动项(只读快照)')
494
+ lines.push(en
495
+ ? `${value.summary.total} entries: ${value.summary.enabled} enabled, ${value.summary.disabled} disabled`
496
+ : `共 ${value.summary.total} 项:已启用 ${value.summary.enabled},已禁用 ${value.summary.disabled}`)
497
+ const labels = { run: en ? 'Registry Run' : '注册表 Run', folder: en ? 'Startup folder' : '启动文件夹', task: en ? 'Scheduled task' : '计划任务', service: en ? 'Auto service' : '自动服务' }
498
+ let current = ''
499
+ for (const entry of value.entries) {
500
+ if (entry.source !== current) {
501
+ current = entry.source
502
+ lines.push(`\n[${labels[current] ?? current}]`)
503
+ }
504
+ const state = entry.enabled ? (en ? 'enabled' : '已启用') : (en ? 'disabled' : '已禁用')
505
+ lines.push(`- ${entry.label} · ${state}${entry.running_pids?.length ? (en ? ` · running (PID ${entry.running_pids.join(', ')})` : ` · 运行中(PID ${entry.running_pids.join(', ')})`) : ''}`)
506
+ lines.push(` ${entry.name}${entry.exe_path ? ` → ${entry.exe_path}` : ''}`)
507
+ lines.push(` ${en ? entry.purpose_en || entry.purpose : entry.purpose}`)
508
+ }
509
+ lines.push(en
510
+ ? 'Read-only: disabling or enabling an entry is a user action in the panel.'
511
+ : '只读:启用/禁用请在右侧栏「进程与启动项」面板里由用户确认。')
512
+ return lines.join('\n')
513
+ }
514
+
515
+ export function renderInspectText(value, lang = 'zh') {
516
+ const en = lang === 'en'
517
+ const lines = []
518
+ lines.push(`${en ? value.label_en : value.label}${value.risk === 'protected' ? (en ? ' · protected' : ' · 受保护') : ''}`)
519
+ lines.push(`${en ? 'Path' : '路径'}:${value.path}`)
520
+ if (value.company) lines.push(`${en ? 'Publisher' : '发布者'}:${value.company}`)
521
+ if (value.product) lines.push(`${en ? 'Product' : '产品'}:${value.product}`)
522
+ if (value.version) lines.push(`${en ? 'Version' : '版本'}:${value.version}`)
523
+ if (value.command_line) lines.push(`${en ? 'Command line' : '命令行'}:${value.command_line}`)
524
+ if (value.signature_status) lines.push(`${en ? 'Signature' : '签名'}:${value.signature_status}${value.signature_signer ? ` · ${value.signature_signer}` : ''}`)
525
+ if (value.started_at) lines.push(`${en ? 'Started' : '启动时间'}:${value.started_at}`)
526
+ if (value.running_pids?.length) lines.push(`${en ? 'Running PIDs' : '运行中 PID'}:${value.running_pids.join(', ')}`)
527
+ lines.push(`${en ? 'What it is for' : '用途'}:${en ? value.purpose_en || value.purpose : value.purpose}`)
528
+ if (value.services?.length) {
529
+ lines.push(en ? 'Hosted services:' : '托管服务:')
530
+ for (const service of value.services) lines.push(`- ${service.display || service.name}(${service.state || ''})${service.description ? ` · ${service.description.slice(0, 160)}` : ''}`)
531
+ }
532
+ if (value.parents?.length) {
533
+ lines.push(`${en ? 'Parent chain' : '父进程链'}:${value.parents.map(item => `${item.name}(${item.pid})`).join(' → ')}`)
534
+ }
535
+ if (value.related_startup?.length) {
536
+ lines.push(en ? 'Startup entries:' : '关联启动项:')
537
+ for (const entry of value.related_startup) lines.push(`- ${entry.label} · ${entry.enabled ? (en ? 'enabled' : '已启用') : (en ? 'disabled' : '已禁用')}`)
538
+ }
539
+ return lines.join('\n')
540
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@unihc/dsh-process-manager",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "Processes and startup entries for DeepSeek Harness: identify every Windows process by app and purpose, list Run keys, startup folders, logon tasks and auto services, and stop or toggle them with explicit user confirmation.",
6
+ "license": "MIT",
7
+ "author": "unihc",
8
+ "homepage": "https://github.com/Uni-h/dsh-process-manager#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/Uni-h/dsh-process-manager.git"
12
+ },
13
+ "keywords": [
14
+ "dsh-plugin",
15
+ "deepseek-harness",
16
+ "process-manager",
17
+ "startup",
18
+ "windows"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "registry": "https://registry.npmjs.org/"
23
+ },
24
+ "exports": {
25
+ ".": "./index.js",
26
+ "./client": "./client.js",
27
+ "./locale/*.json": "./locale/*.json",
28
+ "./icon": "./icon.svg"
29
+ },
30
+ "files": [
31
+ "index.js",
32
+ "operations.js",
33
+ "native.js",
34
+ "collector.js",
35
+ "model.js",
36
+ "catalog.js",
37
+ "client.js",
38
+ "cordis.patch.yml",
39
+ "locale/*.json",
40
+ "docs",
41
+ "icon.svg",
42
+ "README.md"
43
+ ],
44
+ "scripts": {
45
+ "prepublishOnly": "node scripts/verify-pack.mjs"
46
+ },
47
+ "dsh": {
48
+ "bundle": {
49
+ "patch": "./cordis.patch.yml",
50
+ "platforms": [
51
+ "win32"
52
+ ]
53
+ },
54
+ "client": {
55
+ "platform": "web",
56
+ "immediately": true,
57
+ "inject": [
58
+ "@deepseek-ai/dsh-client-ui-sidebar-right",
59
+ "@deepseek-ai/dsh-client-ui-sidebar"
60
+ ]
61
+ }
62
+ }
63
+ }