dsh-pick 0.2.6 → 0.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.
package/README.md CHANGED
@@ -42,6 +42,21 @@ dsh plugin --profile web add dsh-pick
42
42
  **设置 → dsh-pick** 是精简页:版本 / 更新 / 卸载、怎么打开面板、数据口径。
43
43
  面板顶部一行:插件名、当前版本号、更新按钮,最右侧是卸载按钮——更新和卸载都交给 DSH 自己的插件管理器,完成后重启 DSH 生效。
44
44
 
45
+ **和对话联动**(这是插件版比独立网页好用的地方):
46
+
47
+ - **+AI**:候选卡片、「候选」「结论」「我的监控」的标题上都有。点一下,把这块的需求和关键数字整理成一段话发到当前对话,AI 在对话里结合你的场景分析。只发结论和数字,不发原始数据;输入框里有你没发出的文字时不会覆盖。
48
+ - **在对话里直接问**:插件给 AI 注册了 4 个工具,不开面板也行,直接问「我想装个数据库插件,哪个靠谱?」,AI 会自己查目录、比较。
49
+
50
+ | 工具 | 作用 |
51
+ |---|---|
52
+ | `pick_search` | 按需求找候选 |
53
+ | `pick_stats` | 查几个插件的详细数据(目录里没有去噪指标的实时查 npm) |
54
+ | `pick_compare` | 2~6 个插件逐项对比,标出每项最好的 |
55
+ | `pick_rank` | 全部或某一类的排行 |
56
+
57
+ 每个工具的结果都带口径说明,并要求 AI 只引用工具给的数字,不自己推算。
58
+ - **安装**:候选卡片上点「安装 → 确认安装」,交给 DSH 的插件管理器装;已装的显示「✓ 已安装」。只能装目录里有的插件(带 `dsh-plugin` 关键字的 npm 包)。
59
+
45
60
  首次使用要先生成目录(在 dsh-pick 的安装目录下,或任意目录):
46
61
 
47
62
  ```sh
@@ -96,8 +111,9 @@ dsh-pick/
96
111
  │ └── normalize.js (在 engine.js 内)排名与链接字段
97
112
  ├── data/catalog.json 目录产物
98
113
  ├── plugin/
99
- │ ├── index.js DSH 宿主端:挂 /api-dsh-pick/* 路由
100
- │ ├── client.js 右侧栏页签(iframe 复用 web/panel.html)+ 设置页精简版
114
+ │ ├── index.js DSH 宿主端:挂 /api-dsh-pick/* 路由(面板、更新、卸载、安装)
115
+ │ ├── tools.js 给对话里的 AI 用的 4 个工具(pick_search / stats / compare / rank)
116
+ │ ├── client.js 右侧栏页签(iframe 复用 web/panel.html,转发「+AI」到对话)+ 设置页精简版
101
117
  │ └── cordis.patch.yml 插进 DSH
102
118
  └── web/
103
119
  ├── panel.html 选插件面板(独立调试用,也是插件内嵌的同一份)
@@ -129,11 +145,13 @@ dsh-pick/
129
145
  - 选插件四步流程 + 规则版结论
130
146
  - 结论导出为独立网页
131
147
  - 我的监控(localStorage)
148
+ - DSH 插件形态:右侧栏完整面板 + 设置页精简版,跟随 DSH 明暗主题;面板内更新 / 卸载本插件
149
+ - 「+AI」把面板内容发到对话;面板内一键安装插件
150
+ - 4 个 AI 工具:`pick_search` / `pick_stats` / `pick_compare` / `pick_rank`(口径随结果附上,禁止 AI 自己推算数字)
132
151
 
133
- **待做(见方案文档)**
134
- - DSH 插件形态:托管端 `plugin/index.js` + `plugin/client.js` + `cordis.patch.yml`
135
- - 5 + 2 个 AI 工具:`pick_ranking` / `pick_search` / `pick_stats` / `pick_compare` / `pick_trend` / `pick_recommend` / `pick_export`
136
- - skill `plugin-analyst`(意图路由 + 口径说明 + 禁止 AI 自己推算数字)
152
+ **待做**
153
+ - 更多 AI 工具:`pick_trend`(走势)/ `pick_export`(导出结论)
154
+ - skill `plugin-analyst`(意图路由 + 更完整的口径说明)
137
155
  - AI 语义分类,把「其他」从 29% 压到 10% 以内
138
156
  - 周报(可指定方向)
139
157
  - PDF 导出(DSH Desktop 可用 Electron `printToPDF`)
package/lib/words.js CHANGED
@@ -48,24 +48,38 @@ export const SYNONYMS = {
48
48
  '管理': ['manager', 'manage', 'admin'],
49
49
  }
50
50
 
51
+ // 整句话里的口头词:「我想装个数据库」要先去掉「我想」「装个」,剩下的才是要找的东西
52
+ const FILLER = /我想|我要|想要|帮我|给我|有没有|能不能|有什么|一个|一款|装个|装一个|安装|需要|什么|怎么|如何|可以|插件|工具|东西|功能|哪个|哪些|好用|推荐|的|吗|呢/g
53
+
51
54
  /**
52
55
  * @param {string} need 用户原话
53
56
  * @returns {{w:string, weight:number}[]}
54
57
  */
55
58
  export function expandWords(need) {
56
59
  const raw = String(need || '').toLowerCase()
57
- .split(/[\s,,、。??!!/;;::()()"'《》【】\[\]+]+/).map(w => w.trim())
60
+ .split(/[\s,,、。??!!/;;::()()"'《》【】\[\]+]+/)
61
+ // 中文整句:去掉口头词再切开
62
+ .flatMap(w => (/[\u4e00-\u9fa5]/.test(w) ? w.replace(FILLER, ' ').split(/\s+/) : [w]))
63
+ .map(w => w.trim())
58
64
  .filter(w => w.length >= 2 && !STOP.has(w))
59
65
 
60
- const out = []
66
+ const best = new Map() // 同一个词只留最高权重
67
+ const add = (w, weight) => { if ((best.get(w) || 0) < weight) best.set(w, weight) }
61
68
  for (const w of raw) {
62
- out.push({ w, weight: 3 })
69
+ add(w, 3)
63
70
  const syn = SYNONYMS[w]
64
- if (syn) for (const s of syn) out.push({ w: s, weight: 2 })
65
- // 长中文词切二元,兜底同义词词典没覆盖的说法
66
- if (/[\u4e00-\u9fa5]/.test(w) && w.length >= 4) {
67
- for (let i = 0; i + 2 <= w.length; i++) out.push({ w: w.slice(i, i + 2), weight: 1 })
71
+ if (syn) for (const s of syn) add(s, 2)
72
+ if (/[\u4e00-\u9fa5]/.test(w)) {
73
+ // 词典里的词藏在长一点的说法里(「数据库管理」里的「数据库」):照样认出来
74
+ for (const key of Object.keys(SYNONYMS)) {
75
+ if (key !== w && w.includes(key)) {
76
+ add(key, 3)
77
+ for (const s of SYNONYMS[key]) add(s, 2)
78
+ }
79
+ }
80
+ // 长中文词切二元,兜底同义词词典没覆盖的说法
81
+ if (w.length >= 4) for (let i = 0; i + 2 <= w.length; i++) add(w.slice(i, i + 2), 1)
68
82
  }
69
83
  }
70
- return out
84
+ return [...best].map(([w, weight]) => ({ w, weight }))
71
85
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-pick",
3
- "version": "0.2.6",
3
+ "version": "0.3.0",
4
4
  "description": "帮你在 DSH 生态里选对插件:说需求 → 找候选 → 多维比较 → 出结论。下载量是证据,AI 是推理。",
5
5
  "type": "module",
6
6
  "main": "./plugin/index.js",
package/plugin/client.js CHANGED
@@ -15,7 +15,7 @@ window.__ModuleLoader__.load({
15
15
  const module = { exports: {} }
16
16
  const React = require('react')
17
17
  const h = React.createElement
18
- const { useEffect, useState } = React
18
+ const { useEffect, useRef, useState } = React
19
19
 
20
20
  // 语言:跟着页面(dsh 只有中、英两种)
21
21
  const isZh = () => {
@@ -137,13 +137,70 @@ window.__ModuleLoader__.load({
137
137
  )
138
138
  }
139
139
 
140
+ // —— 「+AI」:面板(iframe)里点了,消息传到这里,写进这个对话的输入框发出去 ——
141
+ // 拿输入框的办法照 dsh-vps-manager:sessions 服务 → 这个对话的 conversation.input
142
+ let composerOf = null
143
+ function composerFor(sessionId) {
144
+ try { return (sessionId && composerOf && composerOf(sessionId)) || null } catch { return null }
145
+ }
146
+ /** 输入框里还没发出去的文字 */
147
+ function composerDraft(input) {
148
+ try {
149
+ const st = input.snapshot || (input.state && input.state.get && input.state.get()) || {}
150
+ return String(st.draft || '').trim()
151
+ } catch { return '' }
152
+ }
153
+ /** 这个对话里排着队、还没轮到的消息(只取文字) */
154
+ function queuedTexts(input) {
155
+ try {
156
+ const st = input.snapshot || (input.state && input.state.get && input.state.get()) || {}
157
+ return (st.queue || []).map(m => (m.content || []).filter(b => b.type === 'text').map(b => b.text).join('').trim())
158
+ } catch { return [] }
159
+ }
160
+ /** @returns {'sent'|'queued'|'draft'|'none'} */
161
+ async function sendToChat(sessionId, text) {
162
+ const input = composerFor(sessionId)
163
+ if (!input) return 'none'
164
+ // 用户正在输入的内容不覆盖
165
+ if (composerDraft(input)) return 'draft'
166
+ // AI 忙着时连点几下,别排一串一样的
167
+ if (queuedTexts(input).includes(text.trim())) return 'queued'
168
+ input.setDraft(text)
169
+ // 输入框更新是异步的:等它收到这句话再发,不然发出去的是空的
170
+ for (let i = 0; i < 20 && !composerDraft(input); i += 1) await new Promise(r => setTimeout(r, 25))
171
+ if (!composerDraft(input)) {
172
+ if (input.focus) input.focus()
173
+ return 'none'
174
+ }
175
+ await input.submit('queue')
176
+ return 'sent'
177
+ }
178
+
140
179
  /** 右侧栏里的完整面板:标题行 + 占满栏高的 iframe(iframe 自己滚动;目录信息面板里自带) */
141
- function PickPanel() {
180
+ function PickPanel({ sessionId }) {
181
+ const frame = useRef(null)
182
+ const sid = sessionId ? String(sessionId) : ''
183
+
184
+ useEffect(() => {
185
+ const onMessage = async (e) => {
186
+ const win = frame.current && frame.current.contentWindow
187
+ if (!win || e.source !== win || e.origin !== window.location.origin) return
188
+ const d = e.data
189
+ if (!d || d.type !== 'dsh-pick:ask' || typeof d.text !== 'string' || !d.text.trim()) return
190
+ let status = 'none'
191
+ try { status = await sendToChat(sid, d.text.slice(0, 8000)) } catch { status = 'none' }
192
+ win.postMessage({ type: 'dsh-pick:ask-result', id: d.id, status }, window.location.origin)
193
+ }
194
+ window.addEventListener('message', onMessage)
195
+ return () => window.removeEventListener('message', onMessage)
196
+ }, [sid])
197
+
142
198
  return h('div', {
143
199
  style: { color: C.text, height: '100%', display: 'flex', flexDirection: 'column', padding: '10px 12px', boxSizing: 'border-box' },
144
200
  },
145
201
  h(HeaderBar),
146
202
  h('iframe', {
203
+ ref: frame,
147
204
  src: '/api-dsh-pick/panel',
148
205
  title: 'dsh-pick',
149
206
  style: {
@@ -236,6 +293,22 @@ window.__ModuleLoader__.load({
236
293
 
237
294
  const injectSlots = ['slots']
238
295
  function apply(ctx) {
296
+ try {
297
+ // 对话输入框(可选服务:没有就是「+AI」发不出去,面板照常能用)
298
+ ctx.inject && ctx.inject(['sessions', 'conversation'], (scope) => {
299
+ const sessions = (scope.get && scope.get('sessions')) || scope.sessions
300
+ const reader = (sessionId) => {
301
+ const actx = sessions && sessions.scope && sessions.scope(sessionId)
302
+ const conv = actx && actx.get && actx.get('conversation')
303
+ const input = conv && conv.input && conv.input.for && conv.input.for(actx)
304
+ return input && typeof input.setDraft === 'function' && typeof input.submit === 'function' ? input : null
305
+ }
306
+ composerOf = reader
307
+ if (scope.effect) scope.effect(() => () => { if (composerOf === reader) composerOf = null }, 'dsh-pick: composer')
308
+ })
309
+ } catch (error) {
310
+ console.warn('[dsh-pick] 拿不到对话输入框', error)
311
+ }
239
312
  try {
240
313
  ctx.inject && ctx.inject(['sidebarRight', 'sidebarRightTabs'], (scope) => {
241
314
  const right = (scope.get && scope.get('sidebarRight')) || scope.sidebarRight
@@ -278,7 +351,8 @@ window.__ModuleLoader__.load({
278
351
  }
279
352
  }
280
353
 
281
- module.exports = { name: 'dsh-pick', inject: injectSlots, apply }
354
+ // 给测试用的内部句柄(浏览器里没人碰它)
355
+ module.exports = { name: 'dsh-pick', inject: injectSlots, apply, __test: { sendToChat } }
282
356
  return module.exports
283
357
  },
284
358
  })
package/plugin/index.js CHANGED
@@ -12,12 +12,17 @@
12
12
  // GET /api-dsh-pick/update 本插件版本 + npm 上的最新版本
13
13
  // POST /api-dsh-pick/update 更新到 npm 最新版(交给 DSH 的插件管理器)
14
14
  // POST /api-dsh-pick/uninstall 从 DSH 卸载本插件
15
+ // GET /api-dsh-pick/installed DSH 里已装的插件名(面板的「已安装」标记)
16
+ // POST /api-dsh-pick/install 安装目录里的某个插件 { name }
17
+ //
18
+ // 另外注册 4 个 AI 工具(plugin/tools.js):对话里的 AI 能自己查目录、比较插件。
15
19
  //
16
20
  // 写法照 dsh-model(同机参考)与 dsh-vps-manager(同作者)的 plugin/index.js。
17
21
 
18
22
  import { readFile } from 'node:fs/promises'
19
23
  import { fileURLToPath } from 'node:url'
20
24
  import { join } from 'node:path'
25
+ import { registerTools } from './tools.js'
21
26
 
22
27
  /** 本包根目录:插件就是完整的 dsh-pick 包 */
23
28
  const PKG_ROOT = fileURLToPath(new URL('..', import.meta.url))
@@ -98,6 +103,35 @@ function managerError(result) {
98
103
  return detail ? `${code}:${detail}` : code
99
104
  }
100
105
 
106
+ /** 读请求体里的 JSON(最多 16 KB,这里只收很小的参数) */
107
+ function readJsonBody(req) {
108
+ return new Promise((resolve) => {
109
+ let size = 0
110
+ const chunks = []
111
+ req.on('data', (c) => {
112
+ size += c.length
113
+ if (size > 16 * 1024) { req.destroy(); resolve({}) } else chunks.push(c)
114
+ })
115
+ req.on('end', () => {
116
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) } catch { resolve({}) }
117
+ })
118
+ req.on('error', () => resolve({}))
119
+ })
120
+ }
121
+
122
+ /** DSH 插件管理器清单里已装、已启用的插件名;拿不到就是 null(老版本 DSH) */
123
+ function installedNames(pluginManager) {
124
+ try {
125
+ const list = pluginManager && typeof pluginManager.listBundles === 'function' ? pluginManager.listBundles() : null
126
+ if (!Array.isArray(list)) return null
127
+ return new Set(list.filter(b => b && b.name && b.installed !== false).map(b => b.name))
128
+ } catch {
129
+ return null
130
+ }
131
+ }
132
+
133
+ const NAME_RE = /^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i
134
+
101
135
  function sendJson(res, status, body) {
102
136
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
103
137
  res.end(JSON.stringify(body))
@@ -154,6 +188,14 @@ export function apply(ctx) {
154
188
  profile = ctx.get && ctx.get('profileContext') && ctx.get('profileContext').name
155
189
  } catch { profile = undefined }
156
190
 
191
+ // AI 工具:DSH 有 tools 服务才注册(可选依赖,没有也不影响面板)
192
+ ctx.inject(['tools'], (toolsCtx) => {
193
+ const tools = toolsCtx.tools || (toolsCtx.get && toolsCtx.get('tools'))
194
+ if (!tools || typeof tools.register !== 'function') return
195
+ registerTools({ tools }, { installed: () => installedNames(pluginManager) || new Set() })
196
+ .catch(e => console.warn('[dsh-pick] AI 工具注册失败', e))
197
+ })
198
+
157
199
  ctx.inject(['webServer'], (webCtx) => {
158
200
  const ws = webCtx.webServer
159
201
  if (!ws || typeof ws.register !== 'function') return
@@ -253,6 +295,49 @@ export function apply(ctx) {
253
295
  },
254
296
  }))
255
297
 
298
+ // 已装的插件(面板卡片上的「已安装」)
299
+ track(ws.register({
300
+ kind: 'exact',
301
+ path: '/api-dsh-pick/installed',
302
+ handler: async (req, res) => {
303
+ const names = installedNames(pluginManager)
304
+ sendJson(res, 200, {
305
+ known: Boolean(names),
306
+ names: names ? [...names] : [],
307
+ canInstall: Boolean(pluginManager && typeof pluginManager.installBundle === 'function'),
308
+ })
309
+ },
310
+ }))
311
+
312
+ // 安装目录里的插件:只装目录里有的(都是带 dsh-plugin 关键字的 npm 包),不接受任意包名
313
+ track(ws.register({
314
+ kind: 'exact',
315
+ path: '/api-dsh-pick/install',
316
+ handler: async (req, res) => {
317
+ if (!isSafePost(req)) return sendJson(res, 403, { ok: false, message: '只接受本页面发出的请求' })
318
+ const { name } = await readJsonBody(req)
319
+ if (typeof name !== 'string' || !NAME_RE.test(name)) return sendJson(res, 400, { ok: false, message: '包名不对' })
320
+ let inCatalog = false
321
+ try {
322
+ const cat = JSON.parse(await readFile(join(PKG_ROOT, 'data', 'catalog.json'), 'utf8'))
323
+ inCatalog = Boolean(cat.packages && cat.packages[name])
324
+ } catch { /* 目录读不到就当不在 */ }
325
+ if (!inCatalog) return sendJson(res, 400, { ok: false, message: `${name} 不在 DSH 插件目录里,这里不装` })
326
+ const command = pluginCommand(`add ${name}`, profile)
327
+ if (!pluginManager || typeof pluginManager.installBundle !== 'function') {
328
+ return sendJson(res, 200, { ok: false, message: '这个版本的 DSH 不能在这里装插件,请在终端执行命令', command })
329
+ }
330
+ try {
331
+ const result = await pluginManager.installBundle(name, { enabled: true })
332
+ const err = managerError(result)
333
+ if (err) return sendJson(res, 200, { ok: false, message: `安装失败(${err})`, command })
334
+ return sendJson(res, 200, { ok: true, restart: result && result.application === 'restart-required' })
335
+ } catch (e) {
336
+ return sendJson(res, 200, { ok: false, message: `安装失败:${e.message}`, command })
337
+ }
338
+ },
339
+ }))
340
+
256
341
  // 面板是内嵌在 dsh 设置页里的 iframe,同源即可,不需要额外令牌:
257
342
  // 这些路由全都先过 dsh 的登录校验(挂在 dsh 自己的 webServer 上)。
258
343
  })
@@ -0,0 +1,247 @@
1
+ // plugin/tools.js — 给 DSH 对话里的 AI 用的 4 个工具
2
+ //
3
+ // 让用户不打开面板、直接在对话里问「我想装个数据库插件,哪个靠谱」,AI 自己查目录、拿去噪指标、做比较。
4
+ // 数据全部来自本包的 data/catalog.json(pick_stats 遇到目录外的包会实时查 npm)。
5
+ //
6
+ // 工具描述保持短;口径写在 NOTE 里,每个工具的结果都带上,免得 AI 把下载量当用户数、或者自己编数字。
7
+ // 写法照 dsh-vps-manager 的 lib/tools.js:defineTool 来自 DSH 的 @deepseek-ai/dsh-tools,拿不到就原样定义。
8
+
9
+ import { loadCatalog, searchByNeed, rank, stats } from '../lib/engine.js'
10
+ import { allCategories } from '../lib/classify.js'
11
+
12
+ async function loadDefineTool() {
13
+ try {
14
+ const mod = await import('@deepseek-ai/dsh-tools')
15
+ return mod.defineTool || (d => d)
16
+ } catch {
17
+ return d => d
18
+ }
19
+ }
20
+
21
+ // 返回值的字段随包变化很大,声明成任意 JSON(模型只看 render 出来的文字)
22
+ const ANY_JSON = { type: 'json' }
23
+ const plain = v => JSON.parse(JSON.stringify(v == null ? null : v))
24
+
25
+ const NOTE =
26
+ '口径:周下载/月下载含 CI、镜像、爬虫流量,不等于用户数;日常基线 = 扣掉发布日与次日后的每日中位数,最接近真实使用量;' +
27
+ '环比 = 近 7 日比前 7 日;健康度 0~100 = 基线 40% + 增速 25% + 新鲜度 20% + 版本节奏 15%。' +
28
+ '只有周下载 Top 约 330 的包有去噪指标,其余为「—」。回答里的数字只能引用这些结果,不要自己推算。'
29
+
30
+ const num = n => (n == null ? '—' : Number(n).toLocaleString('en-US'))
31
+ const pct = n => (n == null ? '—' : (n >= 0 ? '+' : '') + Math.round(n * 100) + '%')
32
+
33
+ /** 一个包的一行摘要(给模型看) */
34
+ function line(r, installed) {
35
+ const d = r.deep
36
+ const parts = [
37
+ `${r.name}${r.version ? ' v' + r.version : ''}`,
38
+ r.category ? `[${r.category}]` : '',
39
+ installed && installed.has(r.name) ? '(已安装)' : '',
40
+ ].filter(Boolean).join(' ')
41
+ const nums = [
42
+ `周下载 ${num(r.weekly)}`,
43
+ d ? `日常基线 ${num(d.baseline)}` : '无去噪指标',
44
+ d ? `环比 ${pct(d.growth)}` : '',
45
+ d && d.cadence != null ? `${d.cadence} 天/版` : '',
46
+ d && d.ageDays != null ? `${d.ageDays} 天前更新` : '',
47
+ d && d.score != null ? `健康度 ${d.score}` : '',
48
+ r.relevance != null ? `相关度 ${r.relevance}%` : '',
49
+ ].filter(Boolean).join(' · ')
50
+ const desc = r.description ? `\n ${String(r.description).slice(0, 160)}` : ''
51
+ return `- ${parts}\n ${nums}${desc}`
52
+ }
53
+
54
+ /** 排行榜返回的是目录原始记录(字段名短),转成和搜索一样的形状 */
55
+ function fromRec(rec) {
56
+ return {
57
+ name: rec.n,
58
+ version: rec.v,
59
+ category: rec.cat,
60
+ description: rec.d,
61
+ weekly: rec.w,
62
+ monthly: rec.m,
63
+ rank: rec.rank,
64
+ deep: rec.deep
65
+ ? { baseline: rec.deep.base, growth: rec.deep.growth, cadence: rec.deep.cadence, ageDays: rec.deep.age, lastRelease: rec.deep.lastRelease, versions: rec.deep.versions, score: rec.deep.s }
66
+ : null,
67
+ }
68
+ }
69
+
70
+ /**
71
+ * stats() 实时查到的结果(目录里没有去噪指标的包)没带版本、分类、链接:目录里有就补上;
72
+ * 顺手去掉 30 天日序列(太长,模型用不上)
73
+ */
74
+ const withCatalogFields = cat => ({ daily, ...r }) => {
75
+ if (r.source !== 'live') return r
76
+ const rec = cat.packages && cat.packages[r.name]
77
+ return {
78
+ ...r,
79
+ version: r.latest || (rec && rec.v) || null,
80
+ category: rec ? rec.cat : null,
81
+ rank: rec ? rec.rank : null,
82
+ npmUrl: (rec && rec.npmUrl) || `https://www.npmjs.com/package/${r.name.replace('/', '%2F')}`,
83
+ }
84
+ }
85
+
86
+ const clampInt = (v, lo, hi, dflt) => {
87
+ const n = Number.parseInt(v, 10)
88
+ return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : dflt
89
+ }
90
+
91
+ const cleanNames = (names, max) =>
92
+ [...new Set((Array.isArray(names) ? names : [names]).map(s => String(s || '').trim()).filter(s => /^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i.test(s)))].slice(0, max)
93
+
94
+ /**
95
+ * @param {object} deps
96
+ * @param {() => Set<string>} [deps.installed] 当前 DSH 已装的插件名(拿不到就空集合)
97
+ */
98
+ export async function buildToolDefinitions(deps = {}) {
99
+ const defineTool = await loadDefineTool()
100
+ const installed = () => {
101
+ try { return deps.installed ? deps.installed() : new Set() } catch { return new Set() }
102
+ }
103
+ const header = cat => `目录数据截止 ${cat.anchor || '未知'}(npm 统计约滞后 5 天),共 ${num(cat.total)} 个插件。`
104
+ const CATS = allCategories()
105
+
106
+ return [
107
+ defineTool({
108
+ name: 'pick_search',
109
+ description:
110
+ '按需求在 DSH 插件目录里找候选插件,返回相关度、下载量和去噪指标。用户想找「能做某件事的插件」时先用它。',
111
+ parameters: {
112
+ need: { type: 'string', required: true, description: '要找的东西,用短词效果最好,例如「数据库」「微信 通知」「记忆」;整句也行' },
113
+ category: { type: 'string', enum: CATS, description: '只在某一类里找(可省略)' },
114
+ limit: { type: 'integer', description: '最多返回几个,默认 8,最多 20' },
115
+ },
116
+ output: {
117
+ schema: ANY_JSON,
118
+ render: (_a, v) => [{
119
+ type: 'text',
120
+ text: v.candidates.length
121
+ ? `${v.header}\n需求「${v.need}」的候选(按相关度与下载量综合排序):\n${v.candidates.map(r => line(r, new Set(v.installed))).join('\n')}\n\n${NOTE}`
122
+ : `${v.header}\n没找到和「${v.need}」相关的插件。可以换个说法,或用 pick_rank 看某一类的排行。`,
123
+ }],
124
+ },
125
+ async execute(args) {
126
+ const cat = await loadCatalog()
127
+ const need = String(args.need || '').trim()
128
+ const candidates = searchByNeed(cat, need, {
129
+ limit: clampInt(args.limit, 1, 20, 8),
130
+ category: CATS.includes(args.category) ? args.category : null,
131
+ })
132
+ const have = installed()
133
+ return plain({ header: header(cat), need, candidates, installed: candidates.map(c => c.name).filter(n => have.has(n)) })
134
+ },
135
+ }),
136
+
137
+ defineTool({
138
+ name: 'pick_stats',
139
+ description:
140
+ '查一个或几个插件的详细数据:简介、版本、下载量、日常基线、环比、版本节奏、最近更新、健康度。目录里没有的包会实时查 npm。',
141
+ parameters: {
142
+ names: { type: 'array', required: true, items: { type: 'string' }, description: 'npm 包名,最多 8 个' },
143
+ },
144
+ output: {
145
+ schema: ANY_JSON,
146
+ render: (_a, v) => [{
147
+ type: 'text',
148
+ text: `${v.header}\n${v.rows.map(r => r.source === 'not-found'
149
+ ? `- ${r.name}:npm 上找不到,或没有下载数据`
150
+ : line(r, new Set(v.installed)) + (r.source === 'live' ? '\n (去噪指标是刚从 npm 实时算的)' : '') + (r.npmUrl ? `\n ${r.npmUrl}` : '')).join('\n')}\n\n${NOTE}`,
151
+ }],
152
+ },
153
+ async execute(args) {
154
+ const cat = await loadCatalog()
155
+ const names = cleanNames(args.names, 8)
156
+ if (!names.length) throw new Error('names 里没有合法的 npm 包名')
157
+ const rows = (await stats(cat, names)).map(withCatalogFields(cat))
158
+ const have = installed()
159
+ return plain({ header: header(cat), rows, installed: names.filter(n => have.has(n)) })
160
+ },
161
+ }),
162
+
163
+ defineTool({
164
+ name: 'pick_compare',
165
+ description:
166
+ '把 2~6 个插件放在一起比:逐项指标列出数值并标出每项最好的那个,再按健康度排序。用户在几个候选里拿不定主意时用它。',
167
+ parameters: {
168
+ names: { type: 'array', required: true, items: { type: 'string' }, description: '要比较的 npm 包名,2~6 个' },
169
+ },
170
+ output: {
171
+ schema: ANY_JSON,
172
+ render: (_a, v) => [{
173
+ type: 'text',
174
+ text: [
175
+ v.header,
176
+ '逐项最好:',
177
+ ...v.best.map(b => `- ${b.label}:${b.winner ? `${b.winner}(${b.value})` : '都没有数据'}`),
178
+ '',
179
+ '按健康度排序(没有去噪指标的排在最后):',
180
+ ...v.rows.map(r => line(r, new Set(v.installed))),
181
+ ...(v.missing.length ? ['', `查不到:${v.missing.join('、')}`] : []),
182
+ '',
183
+ NOTE,
184
+ ].join('\n'),
185
+ }],
186
+ },
187
+ async execute(args) {
188
+ const cat = await loadCatalog()
189
+ const names = cleanNames(args.names, 6)
190
+ if (names.length < 2) throw new Error('至少要两个合法的 npm 包名')
191
+ const all = (await stats(cat, names)).map(withCatalogFields(cat))
192
+ const rows = all.filter(r => r.source !== 'not-found')
193
+ const missing = all.filter(r => r.source === 'not-found').map(r => r.name)
194
+ const METRICS = [
195
+ { label: '日常基线(越高越好)', get: r => r.deep && r.deep.baseline, better: 'max', fmt: num },
196
+ { label: '近 7 日环比(越高越好)', get: r => r.deep && r.deep.growth, better: 'max', fmt: pct },
197
+ { label: '最近更新(越近越好)', get: r => r.deep && r.deep.ageDays, better: 'min', fmt: n => `${n} 天前` },
198
+ { label: '版本节奏(越短越活跃)', get: r => r.deep && r.deep.cadence, better: 'min', fmt: n => `${n} 天/版` },
199
+ { label: '健康度(越高越好)', get: r => r.deep && r.deep.score, better: 'max', fmt: n => String(n) },
200
+ { label: '周下载(含非人类流量)', get: r => r.weekly, better: 'max', fmt: num },
201
+ ]
202
+ const best = METRICS.map(m => {
203
+ const vals = rows.map(r => [r.name, m.get(r)]).filter(([, x]) => x != null && !Number.isNaN(x))
204
+ if (!vals.length) return { label: m.label, winner: null }
205
+ vals.sort((a, b) => (m.better === 'max' ? b[1] - a[1] : a[1] - b[1]))
206
+ return { label: m.label, winner: vals[0][0], value: m.fmt(vals[0][1]) }
207
+ })
208
+ rows.sort((a, b) => ((b.deep && b.deep.score) ?? -1) - ((a.deep && a.deep.score) ?? -1))
209
+ const have = installed()
210
+ return plain({ header: header(cat), best, rows, missing, installed: names.filter(n => have.has(n)) })
211
+ },
212
+ }),
213
+
214
+ defineTool({
215
+ name: 'pick_rank',
216
+ description:
217
+ '插件排行榜:全部或某一类,可按周下载、日常基线、环比增速、健康度排。用户问「哪些插件最火 / 某类里谁最好」时用它。',
218
+ parameters: {
219
+ metric: { type: 'string', enum: ['weekly', 'baseline', 'growth', 'score'], description: '排序指标,默认 baseline(日常基线,最接近真实使用量)' },
220
+ category: { type: 'string', enum: CATS, description: '只看某一类(可省略)' },
221
+ limit: { type: 'integer', description: '前几名,默认 10,最多 30' },
222
+ },
223
+ output: {
224
+ schema: ANY_JSON,
225
+ render: (_a, v) => [{
226
+ type: 'text',
227
+ text: `${v.header}\n排行:${v.category || '全部'} · 按${v.metricLabel}\n${v.rows.map((r, i) => `${i + 1}.${line(r, new Set(v.installed)).slice(1)}`).join('\n')}\n\n${NOTE}`,
228
+ }],
229
+ },
230
+ async execute(args) {
231
+ const cat = await loadCatalog()
232
+ const LABELS = { weekly: '周下载', baseline: '日常基线', growth: '环比增速', score: '健康度' }
233
+ const metric = LABELS[args.metric] ? args.metric : 'baseline'
234
+ const category = CATS.includes(args.category) ? args.category : null
235
+ const rows = rank(cat, { metric, category, limit: clampInt(args.limit, 1, 30, 10) }).map(fromRec)
236
+ const have = installed()
237
+ return plain({ header: header(cat), metric, metricLabel: LABELS[metric], category, rows, installed: rows.map(r => r.name).filter(n => have.has(n)) })
238
+ },
239
+ }),
240
+ ]
241
+ }
242
+
243
+ /** 注册工具;返回反注册函数数组 */
244
+ export async function registerTools(ctx, deps = {}) {
245
+ const defs = await buildToolDefinitions(deps)
246
+ return defs.map(def => ctx.tools.register(def))
247
+ }
package/web/panel.html CHANGED
@@ -17,6 +17,7 @@
17
17
  --bar-bg:rgba(245,246,248,.92); --shadow:rgba(16,24,40,.09); --focus:rgba(47,107,255,.12);
18
18
  --ok-text:#0b7a45; --warn-text:#a8620a; --bad-text:#a52f2f;
19
19
  --ok-line:#bfe6d1; --warn-line:#f2ddb6; --bad-line:#f2cccc;
20
+ --ai:#7c4dff;
20
21
  color-scheme:light;
21
22
  }
22
23
  /* 暗色:嵌在 DSH 里时由下面的脚本按 DSH 主题设 data-theme(并把 DSH 的颜色变量覆盖上来);
@@ -32,6 +33,7 @@
32
33
  --bar-bg:rgba(23,24,28,.9); --shadow:rgba(0,0,0,.4); --focus:rgba(91,140,255,.25);
33
34
  --ok-text:#5fd99a; --warn-text:#f3b65e; --bad-text:#f58a8a;
34
35
  --ok-line:rgba(60,207,127,.3); --warn-line:rgba(240,164,58,.3); --bad-line:rgba(240,107,107,.3);
36
+ --ai:#a98bff;
35
37
  color-scheme:dark;
36
38
  }
37
39
  @media (prefers-color-scheme: dark){
@@ -46,6 +48,7 @@
46
48
  --bar-bg:rgba(23,24,28,.9); --shadow:rgba(0,0,0,.4); --focus:rgba(91,140,255,.25);
47
49
  --ok-text:#5fd99a; --warn-text:#f3b65e; --bad-text:#f58a8a;
48
50
  --ok-line:rgba(60,207,127,.3); --warn-line:rgba(240,164,58,.3); --bad-line:rgba(240,107,107,.3);
51
+ --ai:#a98bff;
49
52
  color-scheme:dark;
50
53
  }
51
54
  }
@@ -94,7 +97,27 @@ h1{margin:0;font-size:19px;font-weight:650;letter-spacing:-.2px}
94
97
  .cand .rk b{color:var(--t2);font-weight:700}
95
98
  .cand .d{font-size:11.5px;color:var(--t2);margin:5px 0 8px;line-height:1.5;
96
99
  display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
97
- .links{display:flex;gap:6px;margin-top:9px;padding-top:9px;border-top:1px dashed var(--line)}
100
+ .links{display:flex;gap:6px;margin-top:9px;padding-top:9px;border-top:1px dashed var(--line);align-items:center;flex-wrap:wrap}
101
+ .links .sp{flex:1}
102
+ /* 「+AI」:把这块内容发到 DSH 对话里,AI 在对话里回答(样式照 dsh-vps-manager 卡片上的那颗) */
103
+ .ai{appearance:none;display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:10px;cursor:pointer;
104
+ font-family:inherit;font-size:10.5px;font-weight:650;letter-spacing:.2px;line-height:1;white-space:nowrap;color:var(--ai);
105
+ border:.5px solid color-mix(in srgb,var(--ai) 40%,transparent);
106
+ background:linear-gradient(135deg,color-mix(in srgb,var(--accent) 12%,transparent),color-mix(in srgb,var(--ai) 18%,transparent))}
107
+ .ai:hover{border-color:color-mix(in srgb,var(--ai) 62%,transparent);
108
+ background:linear-gradient(135deg,color-mix(in srgb,var(--accent) 22%,transparent),color-mix(in srgb,var(--ai) 28%,transparent))}
109
+ .section h2 .ai{margin-left:auto;font-weight:650}
110
+ .inst{appearance:none;font-family:inherit;font-size:10.5px;font-weight:600;border-radius:6px;padding:2px 9px;cursor:pointer;
111
+ border:1px solid var(--accent);background:var(--panel);color:var(--accent);white-space:nowrap}
112
+ .inst:hover{background:var(--accent-bg)}
113
+ .inst.confirm{background:var(--accent);color:#fff}
114
+ .inst:disabled{opacity:.6;cursor:default}
115
+ .badge-in{font-size:10.5px;color:var(--ok-text);background:var(--ok-bg);border-radius:6px;padding:2px 8px;white-space:nowrap}
116
+ .toast{position:fixed;left:50%;bottom:18px;transform:translateX(-50%);z-index:90;max-width:calc(100% - 24px);
117
+ background:var(--text);color:var(--bg);font-size:12px;line-height:1.6;padding:8px 14px;border-radius:9px;
118
+ box-shadow:0 4px 16px var(--shadow);opacity:0;pointer-events:none;transition:opacity .2s}
119
+ .toast.on{opacity:1;pointer-events:auto}
120
+ .toast code{display:block;margin-top:4px;user-select:all;font-size:11px;opacity:.85}
98
121
  .lk{display:inline-flex;align-items:center;gap:5px;font-size:10.5px;color:var(--t2);text-decoration:none;
99
122
  border:1px solid var(--line);border-radius:6px;padding:2px 8px;background:var(--panel);transition:.15s}
100
123
  .lk:hover{border-color:var(--accent);color:var(--accent);background:var(--accent-bg)}
@@ -280,7 +303,7 @@ td.down{color:var(--bad);font-weight:600}
280
303
  </div>
281
304
 
282
305
  <div class="section hidden" id="secCand">
283
- <h2><span class="n">2</span>候选 <span style="font-size:11.5px;color:var(--t3);font-weight:500" id="candCount"></span></h2>
306
+ <h2><span class="n">2</span>候选 <span style="font-size:11.5px;color:var(--t3);font-weight:500" id="candCount"></span><button class="ai hidden" id="aiCands" title="把这批候选发到对话里,让 AI 帮你挑">+AI 帮我挑</button></h2>
284
307
  <p class="cap">点选 2~6 个进行比较。排序按「相关性 × 下载量」,下载量只做微弱加权,避免发版本最勤的挤掉真正相关的。</p>
285
308
  <div class="cands" id="cands"></div>
286
309
  </div>
@@ -295,8 +318,8 @@ td.down{color:var(--bad);font-weight:600}
295
318
  </div>
296
319
 
297
320
  <div class="section hidden" id="secVerdict">
298
- <h2><span class="n">4</span>结论</h2>
299
- <p class="cap">以下判断由本地规则给出,依据就是上面这张表里的数字。装上 DSH 插件版后,这一步由 AI 生成,能结合你的具体场景解释取舍。</p>
321
+ <h2><span class="n">4</span>结论<button class="ai hidden" id="aiVerdict" title="把对比表和规则结论发到对话里,让 AI 结合你的场景判断">+AI 帮我判断</button></h2>
322
+ <p class="cap" id="verdictCap">以下判断由本地规则给出,依据就是上面这张表里的数字。装上 DSH 插件版后,可以一键交给 AI,结合你的具体场景解释取舍。</p>
300
323
  <div id="verdicts"></div>
301
324
  <div style="display:flex;gap:9px;margin-top:14px;flex-wrap:wrap">
302
325
  <button class="btn ghost" id="btnExport">导出结论(网页)</button>
@@ -330,7 +353,7 @@ td.down{color:var(--bad);font-weight:600}
330
353
  <!-- ============ Tab 2:监控 ============ -->
331
354
  <div id="tab-watch" class="hidden">
332
355
  <div class="section">
333
- <h2>我的监控</h2>
356
+ <h2>我的监控<button class="ai hidden" id="aiWatch" title="把监控列表发到对话里,让 AI 看看谁在涨、谁停更了">+AI 看看近况</button></h2>
334
357
  <p class="cap">存在浏览器本地(localStorage),不上传。数据取自目录,目录每天重建一次。</p>
335
358
  <div id="watchList"></div>
336
359
  </div>
@@ -343,6 +366,7 @@ td.down{color:var(--bad);font-weight:600}
343
366
 
344
367
  <div class="foot" id="foot"></div>
345
368
  </div>
369
+ <div class="toast" id="toast"></div>
346
370
 
347
371
  <script type="module">
348
372
  // 同一个面板两种宿主:独立预览加载 /web/panel.js,插件内嵌加载 /api-dsh-pick/panel.js
package/web/panel.js CHANGED
@@ -9,6 +9,11 @@ const P = {
9
9
  catalog: IS_PLUGIN ? '/api-dsh-pick/catalog.json' : '/data/catalog.json',
10
10
  }
11
11
 
12
+ // 嵌在 DSH 里(同源 iframe)才有「+AI」和「安装」:消息交给外层(plugin/client.js)写进当前对话;
13
+ // 独立打开(dsh-pick serve)时外面没有 DSH,这两样都不显示
14
+ let IN_DSH = false
15
+ try { IN_DSH = IS_PLUGIN && window.parent !== window && Boolean(window.parent.document) } catch { IN_DSH = false }
16
+
12
17
  const $ = s => document.querySelector(s)
13
18
  let CAT = null
14
19
  let cands = []
@@ -22,6 +27,154 @@ const num = n => (n === null || n === undefined) ? '—' : Number(n).toLocaleStr
22
27
  const pct = n => (n === null || n === undefined) ? '—' : (n >= 0 ? '+' : '') + Math.round(n * 100) + '%'
23
28
  const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
24
29
 
30
+ /* ---------------- 发到对话 / 安装 ---------------- */
31
+ let toastTimer = 0
32
+ function toast(text, command) {
33
+ const el = $('#toast')
34
+ el.innerHTML = esc(text) + (command ? `<code>${esc(command)}</code>` : '')
35
+ el.classList.add('on')
36
+ clearTimeout(toastTimer)
37
+ toastTimer = setTimeout(() => el.classList.remove('on'), command ? 9000 : 3500)
38
+ }
39
+
40
+ // 外层回话:发出去了没有
41
+ const ASK_RESULT = {
42
+ sent: '已发到对话,AI 正在看',
43
+ queued: '这句已经在对话里排着队了',
44
+ draft: '对话输入框里还有没发出的文字,先发掉或清空再试',
45
+ none: '没找到当前对话:先打开一个对话,再从右侧栏用',
46
+ }
47
+ let askSeq = 0
48
+ window.addEventListener('message', e => {
49
+ if (e.source !== window.parent || !e.data || e.data.type !== 'dsh-pick:ask-result') return
50
+ toast(ASK_RESULT[e.data.status] || '没发出去,再试一次')
51
+ })
52
+
53
+ /** 把一段话交给外层,写进当前对话发出去 */
54
+ function askAI(text) {
55
+ if (!IN_DSH) return
56
+ window.parent.postMessage({ type: 'dsh-pick:ask', id: ++askSeq, text }, location.origin)
57
+ }
58
+
59
+ /** 一个包的关键数字(发给 AI 用,一行) */
60
+ function factLine(r) {
61
+ const d = r.deep
62
+ return [
63
+ `周下载 ${num(r.w)}`,
64
+ d ? `日常基线 ${num(d.base)}` : '无去噪指标(周下载 Top 之外)',
65
+ d ? `近 7 日环比 ${pct(d.growth)}` : '',
66
+ d && d.cadence != null ? `${d.cadence} 天/版` : '',
67
+ d && d.age != null ? `${d.age} 天前更新` : '',
68
+ d ? `健康度 ${d.s}` : '',
69
+ r.rank ? `总榜 #${r.rank}` : '',
70
+ ].filter(Boolean).join(' · ')
71
+ }
72
+ const needLine = () => {
73
+ const need = $('#need').value.trim()
74
+ return need ? `我的需求:${need}` : null
75
+ }
76
+ const dataAsOf = () => `(dsh-pick 数据,截止 ${CAT.anchor};下载量含 CI / 镜像流量,不等于用户数)`
77
+ const TAIL = '需要更多数据可以用 pick_search / pick_stats / pick_compare 查。先只分析,不要安装。'
78
+
79
+ function askCard(r) {
80
+ return [
81
+ `帮我看看 DSH 插件 ${r.n}(v${r.v},${r.cat})值不值得装。`,
82
+ needLine(),
83
+ `简介:${String(r.d || '').slice(0, 200)}`,
84
+ `数据${dataAsOf()}:${factLine(r)}`,
85
+ '',
86
+ `请说说它适不适合我、有什么风险、有没有更好的替代。${TAIL}`,
87
+ ].filter(x => x != null).join('\n')
88
+ }
89
+
90
+ function askCands() {
91
+ return [
92
+ `我在找 DSH 插件,需求是「${$('#need').value.trim()}」。dsh-pick 找到这些候选${dataAsOf()}:`,
93
+ ...cands.map((r, i) => `${i + 1}. ${r.n}(${r.cat})— ${factLine(r)} — ${String(r.d || '').slice(0, 80)}`),
94
+ '',
95
+ `请帮我挑出最合适的 1~2 个并说明理由,不合适的也说一句为什么。${TAIL}`,
96
+ ].join('\n')
97
+ }
98
+
99
+ function askVerdict() {
100
+ const rows = picked.map(n => CAT.packages[n]).filter(Boolean)
101
+ const rule = $('#verdicts').innerText.trim().replace(/\n+/g, ' / ')
102
+ return [
103
+ `帮我在这几个 DSH 插件里做个选择${dataAsOf()}。`,
104
+ needLine(),
105
+ ...rows.map(r => `- ${r.n}(${r.cat}):${factLine(r)}`),
106
+ rule ? `dsh-pick 的规则结论(只按数字算的,仅供参考):${rule}` : null,
107
+ '',
108
+ `请结合我的需求重新判断:选哪个、为什么、什么情况下该选别的。${TAIL}`,
109
+ ].filter(x => x != null).join('\n')
110
+ }
111
+
112
+ function askWatch() {
113
+ const rows = watch().map(n => CAT.packages[n]).filter(Boolean)
114
+ return [
115
+ `帮我看看我关注的这些 DSH 插件最近怎么样${dataAsOf()}:`,
116
+ ...rows.map(r => `- ${r.n}(${r.cat}):${factLine(r)}`),
117
+ '',
118
+ `谁在涨、谁停更了、有没有该换掉的?${TAIL}`,
119
+ ].join('\n')
120
+ }
121
+
122
+ // 已装的插件、能不能在这里装(外层 DSH 的插件管理器)
123
+ let INSTALLED = new Set()
124
+ let CAN_INSTALL = false
125
+ async function loadInstalled() {
126
+ if (!IN_DSH) return
127
+ try {
128
+ const j = await (await fetch('/api-dsh-pick/installed', { cache: 'no-store' })).json()
129
+ INSTALLED = new Set(j.names || [])
130
+ CAN_INSTALL = Boolean(j.canInstall)
131
+ } catch { /* 拿不到就不显示安装 */ }
132
+ }
133
+
134
+ /** 卡片上的安装区:已安装 / 安装(点一下变「确认安装」,再点才装) */
135
+ function installArea(r) {
136
+ if (!IN_DSH) return ''
137
+ if (INSTALLED.has(r.n)) return '<span class="badge-in">✓ 已安装</span>'
138
+ if (!CAN_INSTALL) return ''
139
+ return `<button class="inst" data-install="${esc(r.n)}" title="用 DSH 的插件管理器安装">安装</button>`
140
+ }
141
+
142
+ async function onInstallClick(btn) {
143
+ const name = btn.dataset.install
144
+ if (!btn.classList.contains('confirm')) {
145
+ btn.classList.add('confirm')
146
+ btn.textContent = '确认安装?'
147
+ setTimeout(() => {
148
+ if (btn.isConnected && btn.classList.contains('confirm') && !btn.disabled) {
149
+ btn.classList.remove('confirm'); btn.textContent = '安装'
150
+ }
151
+ }, 4000)
152
+ return
153
+ }
154
+ btn.disabled = true
155
+ btn.textContent = '安装中…'
156
+ try {
157
+ const r = await fetch('/api-dsh-pick/install', {
158
+ method: 'POST',
159
+ headers: { 'content-type': 'application/json' },
160
+ body: JSON.stringify({ name }),
161
+ })
162
+ const j = await r.json()
163
+ if (j.ok) {
164
+ INSTALLED.add(name)
165
+ toast(j.restart ? `${name} 已安装,重启 DSH 后生效` : `${name} 已安装`)
166
+ renderCands($('#need').value.trim())
167
+ return
168
+ }
169
+ toast(j.message || '安装失败', j.command)
170
+ } catch (e) {
171
+ toast('安装请求失败:' + e.message)
172
+ }
173
+ btn.disabled = false
174
+ btn.classList.remove('confirm')
175
+ btn.textContent = '安装'
176
+ }
177
+
25
178
  /* ---------------- 排名文案与外链按钮 ---------------- */
26
179
  function rankText(rec) {
27
180
  if (!rec.rank) return ''
@@ -78,7 +231,15 @@ async function boot() {
78
231
  $('#foot').innerHTML =
79
232
  `<b>口径:</b>下载量含 CI、镜像、爬虫等非人类流量,不等于用户数;<b>日常基线</b>= 扣掉版本发布日与次日后的每日中位数,比原始下载量更接近真实使用量。<br>` +
80
233
  `<b>覆盖范围:</b>npm 上带 <code>dsh-plugin</code> 关键字的 ${num(CAT.total)} 个包;去噪指标只算了周下载 Top ${num(deepN)}。目录每天重建一次,重跑 <code>dsh-pick build</code> 即可。<br>` +
81
- `<b>当前结论由本地规则生成</b>(依据就是对比表里的数字)。装上 DSH 插件版后,这一步由 AI 生成,可结合你的具体场景解释取舍。`
234
+ (IN_DSH
235
+ ? `<b>当前结论由本地规则生成</b>(依据就是对比表里的数字)。点各处的「+AI」,把数据发到对话里让 AI 结合你的场景分析;在对话里也可以直接问「哪个插件能做某某」,AI 会自己查这份目录。`
236
+ : `<b>当前结论由本地规则生成</b>(依据就是对比表里的数字)。装上 DSH 插件版后,可以一键交给 AI,结合你的具体场景解释取舍。`)
237
+
238
+ await loadInstalled()
239
+ if (IN_DSH) {
240
+ ;['#aiCands', '#aiVerdict', '#aiWatch'].forEach(id => $(id).classList.remove('hidden'))
241
+ $('#verdictCap').textContent = '以下判断由本地规则给出,只看数字。点「+AI 帮我判断」,让对话里的 AI 结合你的具体场景解释取舍。'
242
+ }
82
243
 
83
244
  buildCategoryFilter()
84
245
  renderRank()
@@ -118,6 +279,10 @@ function bindEvents() {
118
279
  })
119
280
  $('#rankCat').addEventListener('change', renderRank)
120
281
 
282
+ $('#aiCands').addEventListener('click', () => cands.length && askAI(askCands()))
283
+ $('#aiVerdict').addEventListener('click', () => picked.length >= 2 && askAI(askVerdict()))
284
+ $('#aiWatch').addEventListener('click', () => watch().length && askAI(askWatch()))
285
+
121
286
  $('#btnExport').addEventListener('click', exportHtml)
122
287
  $('#btnWatch').addEventListener('click', addPickedToWatch)
123
288
  }
@@ -158,9 +323,19 @@ function renderCands(need) {
158
323
  `<span>月 <b>${num(rec.m)}</b></span>` +
159
324
  (d ? `<span>基线 <b>${num(d.base)}</b></span><span>环比 <b>${pct(d.growth)}</b></span>` : '') +
160
325
  `</div>` +
161
- `<div class="links">${linkBtns(rec)}</div>` +
326
+ `<div class="links">${linkBtns(rec)}<span class="sp"></span>${installArea(rec)}` +
327
+ (IN_DSH ? `<button class="ai" data-ask title="把这个插件的数据发到对话里问 AI">+AI</button>` : '') +
328
+ `</div>` +
162
329
  `</div>`
163
- el.addEventListener('click', () => togglePick(rec.n))
330
+ el.addEventListener('click', e => {
331
+ // 卡片上的按钮和链接各管各的,不算「选中」
332
+ const ask = e.target.closest('[data-ask]')
333
+ if (ask) { e.stopPropagation(); askAI(askCard(rec)); return }
334
+ const inst = e.target.closest('[data-install]')
335
+ if (inst) { e.stopPropagation(); onInstallClick(inst); return }
336
+ if (e.target.closest('a')) return
337
+ togglePick(rec.n)
338
+ })
164
339
  host.appendChild(el)
165
340
  })
166
341