dsh-crate 0.5.10 → 0.6.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,601 @@
1
+ /**
2
+ * `/find-plugin <what you want>` in the DSH chat.
3
+ *
4
+ * A person asks for a thing, not for a keyword: "通知类型的插件", "找找 seo
5
+ * 优化写作的插件". Keyword search alone cannot read that (no plugin lists every
6
+ * word, and the filler words match nothing), so this is two steps:
7
+ *
8
+ * 1. Recall, here and cheap: drop the filler, expand synonyms, and keep every
9
+ * catalog entry that matches ANY remaining word, ranked by how many
10
+ * matched and where (name > category > description). About twenty.
11
+ * 2. Judgement, by the user's own model (the one their chat uses, or the
12
+ * default one for the market's AI search): it picks the few that really
13
+ * fit and says why, as JSON. That is their model and their tokens, spent
14
+ * on getting the answer right.
15
+ *
16
+ * The pick runs as a one-shot model call, not as a chat turn: the result is a
17
+ * command result (rendered as cards by the market's command-row renderer), so
18
+ * it never enters the conversation the user is having with the model.
19
+ *
20
+ * Nothing here installs anything. The cards offer the market's own install
21
+ * dialog (recommended), a direct install that still confirms first, or the
22
+ * install command to copy.
23
+ */
24
+ import { randomUUID } from 'node:crypto';
25
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
26
+ import { dirname, join } from 'node:path';
27
+ import { resolveDshHome } from './home-paths.js';
28
+ import { logEvent } from './log.js';
29
+ import { SEARCH_SYNONYM_GROUPS } from './search-synonyms.js';
30
+ import { pluginCategories } from './registry.js';
31
+ /** How many candidates go to the model. Enough to cover a vague request, few enough to read. */
32
+ export const CANDIDATE_LIMIT = 30;
33
+ /** Words that frame a request without saying what it is about. */
34
+ const FILLER_ZH = [
35
+ '帮我找找', '帮我找', '帮我', '给我找', '给我', '找一找', '找找', '找一下', '找个', '找', '搜索', '搜一下', '搜',
36
+ '我想要', '我想', '想要', '需要', '有没有', '有什么', '有哪些', '推荐一下', '推荐', '一些', '一下', '请问',
37
+ '插件箱子里的', '插件箱子', '插件', '类型', '种类', '相关的', '相关', '方面的', '方面', '用于', '用来', '可以', '能够', '能',
38
+ '的', '了', '吗', '呢', '吧', '一个', '个',
39
+ ];
40
+ const FILLER_EN = new Set([
41
+ 'find', 'search', 'show', 'give', 'recommend', 'looking', 'look', 'need', 'want', 'please', 'help', 'me', 'my', 'i', 'a', 'an', 'the',
42
+ 'some', 'any', 'for', 'to', 'of', 'that', 'which', 'with', 'can', 'could', 'would', 'is', 'are', 'there', 'plugin', 'plugins', 'dsh',
43
+ 'about', 'related', 'type', 'kind', 'and', 'or',
44
+ ]);
45
+ /** Pronouns and particles: a two-character piece containing one is a seam, not a word. */
46
+ const SEAM_CHARS = new Set([...'我你他她它们的了过着说让把被给能会要想在是和与或就都也还很']);
47
+ /** What was asked, minus the filler: the words worth matching. */
48
+ export function extractTerms(input) {
49
+ let text = input.toLowerCase().replace(/\s+/gu, ' ').trim();
50
+ // Longest filler first, so "帮我找找" goes before "帮我" before "找".
51
+ for (const word of [...FILLER_ZH].sort((a, b) => b.length - a.length))
52
+ text = text.split(word).join(' ');
53
+ const terms = [];
54
+ const seen = new Set();
55
+ for (const raw of text.split(/[\s,,。.!!??、;;::()()"'“”‘’/\\|]+/u)) {
56
+ const token = raw.trim();
57
+ if (token === '' || FILLER_EN.has(token))
58
+ continue;
59
+ // A run of Han characters without spaces ("优化写作") is several ideas
60
+ // glued together: keep the run, and also every two-character piece, which
61
+ // is the smallest unit that still means something. A piece that leans on
62
+ // a pronoun or particle ("住我", "说过") is a seam between words, not a
63
+ // word, and only adds noise.
64
+ const han = token.match(/\p{Script=Han}+/gu) ?? [];
65
+ const latin = token.replace(/\p{Script=Han}+/gu, ' ').split(' ').filter(piece => piece.length >= 2);
66
+ const pieces = [...latin];
67
+ for (const run of han) {
68
+ if (run.length >= 2)
69
+ pieces.push(run);
70
+ if (run.length > 2)
71
+ for (let i = 0; i + 2 <= run.length; i += 1) {
72
+ const piece = run.slice(i, i + 2);
73
+ if (![...piece].some(char => SEAM_CHARS.has(char)))
74
+ pieces.push(piece);
75
+ }
76
+ }
77
+ for (const piece of pieces)
78
+ if (!seen.has(piece)) {
79
+ seen.add(piece);
80
+ terms.push(piece);
81
+ }
82
+ }
83
+ return terms;
84
+ }
85
+ /** Words that mean the same as `term` to a user (the same table the market search uses). */
86
+ function synonymsOf(term) {
87
+ const out = new Set();
88
+ for (const group of SEARCH_SYNONYM_GROUPS) {
89
+ const terms = group.terms.map(value => value.toLowerCase());
90
+ if (!terms.includes(term))
91
+ continue;
92
+ for (const value of [...terms, ...(group.broad ?? []).map(word => word.toLowerCase())])
93
+ if (value !== term)
94
+ out.add(value);
95
+ }
96
+ return [...out];
97
+ }
98
+ const containsWord = (text, word) => {
99
+ if (/\p{Script=Han}/u.test(word))
100
+ return text.includes(word);
101
+ return new RegExp(`(^|[^a-z0-9])${word.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')}s?($|[^a-z0-9])`, 'u').test(text);
102
+ };
103
+ const WEIGHT = { name: 8, category: 4, description: 3, owner: 1 };
104
+ function describe(plugin, preferZh) {
105
+ const description = plugin.description ?? {};
106
+ const first = preferZh ? description.zh ?? description.en : description.en ?? description.zh;
107
+ return (first ?? Object.values(description)[0] ?? '').replace(/\s+/gu, ' ').trim();
108
+ }
109
+ /**
110
+ * One entry's score for these terms: each term counts once, at its best field,
111
+ * scaled by how rare the term is (a word on every third plugin, like "ai",
112
+ * says little; "记住" says a lot); synonyms count for half.
113
+ */
114
+ function scoreFor(plugin, terms, categories, rarity) {
115
+ const name = `${plugin.name} ${plugin.npm ?? ''}`.toLowerCase();
116
+ const owner = plugin.owner.toLowerCase();
117
+ const texts = Object.values(plugin.description ?? {}).filter((value) => typeof value === 'string').map(value => value.toLowerCase());
118
+ const cats = pluginCategories(plugin).flatMap(id => [id, ...Object.values(categories[id] ?? {})]).map(value => value.toLowerCase());
119
+ const best = (word) => {
120
+ if (containsWord(name, word))
121
+ return WEIGHT.name;
122
+ if (cats.some(value => containsWord(value, word)))
123
+ return WEIGHT.category;
124
+ if (texts.some(value => containsWord(value, word)))
125
+ return WEIGHT.description;
126
+ if (containsWord(owner, word))
127
+ return WEIGHT.owner;
128
+ return 0;
129
+ };
130
+ let total = 0;
131
+ for (const term of terms) {
132
+ const literal = best(term);
133
+ const weight = rarity.get(term) ?? 1;
134
+ if (literal > 0) {
135
+ total += literal * weight;
136
+ continue;
137
+ }
138
+ // Only through a synonym: worth half, so a plugin that says what the user
139
+ // said still outranks one that says it another way.
140
+ const viaSynonym = Math.max(0, ...synonymsOf(term).map(best));
141
+ total += (viaSynonym / 2) * weight;
142
+ }
143
+ return total;
144
+ }
145
+ const downloadsOf = (plugin) => typeof plugin.downloads === 'number' ? plugin.downloads : -1;
146
+ const starsOf = (plugin) => typeof plugin.stars === 'number' ? plugin.stars : -1;
147
+ /** Inverse document frequency per term over the whole catalog text (literal matches only). */
148
+ function termRarity(plugins, terms) {
149
+ const texts = plugins.map(plugin => `${plugin.name} ${plugin.npm ?? ''} ${Object.values(plugin.description ?? {}).join(' ')}`.toLowerCase());
150
+ const total = texts.length;
151
+ return new Map(terms.map(term => {
152
+ const df = texts.reduce((n, text) => n + (containsWord(text, term) ? 1 : 0), 0);
153
+ return [term, Math.log(1 + total / (1 + df))];
154
+ }));
155
+ }
156
+ /**
157
+ * The entries worth showing the model. Every entry matching any term, best
158
+ * first; when fewer than the limit match (a vague or unmatched request), the
159
+ * most downloaded of the rest fill the list, because a model can still pick
160
+ * something sensible from popular plugins, and an empty list helps no one.
161
+ */
162
+ export function recall(registry, terms, limit = CANDIDATE_LIMIT, exclude = new Set()) {
163
+ const usable = registry.plugins.filter(plugin => plugin.deprecated !== true && plugin.npm !== 'dsh-crate' && plugin.name !== 'dsh-crate' && !exclude.has(plugin.name));
164
+ const rarity = termRarity(usable, terms);
165
+ const scored = usable
166
+ .map(plugin => ({ plugin, score: terms.length === 0 ? 0 : scoreFor(plugin, terms, registry.categories, rarity) }));
167
+ const byPopularity = (a, b) => downloadsOf(b.plugin) - downloadsOf(a.plugin) || starsOf(b.plugin) - starsOf(a.plugin) || a.plugin.name.localeCompare(b.plugin.name);
168
+ const hits = scored.filter(item => item.score > 0).sort((a, b) => b.score - a.score || byPopularity(a, b));
169
+ const candidates = hits.slice(0, limit);
170
+ if (candidates.length < limit) {
171
+ const taken = new Set(candidates.map(item => item.plugin.name));
172
+ const rest = scored.filter(item => !taken.has(item.plugin.name)).sort(byPopularity);
173
+ candidates.push(...rest.slice(0, limit - candidates.length));
174
+ }
175
+ return { candidates, matched: hits.length };
176
+ }
177
+ export class FindPluginError extends Error {
178
+ code;
179
+ constructor(code, message) {
180
+ super(message);
181
+ this.code = code;
182
+ this.name = 'FindPluginError';
183
+ }
184
+ }
185
+ function catalogLine(plugin, index, registry, preferZh) {
186
+ const cats = pluginCategories(plugin).map(id => registry.categories[id]?.[preferZh ? 'zh' : 'en'] ?? registry.categories[id]?.en ?? id).join('/');
187
+ const stats = [typeof plugin.downloads === 'number' ? `downloads ${plugin.downloads}` : '', typeof plugin.stars === 'number' ? `stars ${plugin.stars}` : ''].filter(Boolean).join(', ');
188
+ return `${index + 1}. ${plugin.name} [${cats}] ${stats}\n ${describe(plugin, preferZh).slice(0, 400)}`;
189
+ }
190
+ /** The instruction and the candidates, as the one message the model reads. */
191
+ export function buildPickPrompt(request, registry, found, have) {
192
+ const preferZh = /\p{Script=Han}/u.test(request);
193
+ const weak = found.matched === 0
194
+ ? 'None of the candidates matched the request\'s words; they are only the most-downloaded plugins. Return an empty list unless one genuinely fits.'
195
+ : found.matched < found.candidates.length
196
+ ? `Only the first ${found.matched} candidates matched the request\'s words; the rest are popular fillers.`
197
+ : '';
198
+ const system = [
199
+ 'You help a user pick plugins from the DSH plugin crate. Answer ONLY with one JSON object, no prose around it:',
200
+ '{"intro": string, "picks": [{"name": string, "why": string}]}',
201
+ '- picks: the 1 to 5 candidates that best fit what the user actually wants, best first. Use names exactly as listed. Never include a name that is not in the list. Return [] if none fit.',
202
+ '- why: one short sentence on why it fits THIS request (not a copy of its description).',
203
+ '- intro: one short sentence framing the result, e.g. what you understood they want, or that nothing fits.',
204
+ `- Write intro and why in ${preferZh ? 'Simplified Chinese' : 'the language of the request'}.`,
205
+ weak,
206
+ have === undefined ? '' : '- The user\'s installed and favorited plugins are listed too (installed ones are already left out of the candidates). Use them to judge what suits this user; skip near-duplicates of what they have.',
207
+ ].filter(Boolean).join('\n');
208
+ const mine = have === undefined ? [] : [
209
+ '', 'Already installed:', ...(have.installed.length === 0 ? ['(none)'] : have.installed.map(plugin => `- ${plugin.name}: ${describe(plugin, preferZh).slice(0, 160)}`)),
210
+ 'Favorited:', ...(have.favorited.length === 0 ? ['(none)'] : have.favorited.map(plugin => `- ${plugin.name}: ${describe(plugin, preferZh).slice(0, 160)}`)),
211
+ ];
212
+ const user = [`Request: ${request}`, ...mine, '', 'Candidates:', ...found.candidates.map(({ plugin }, i) => catalogLine(plugin, i, registry, preferZh))].join('\n');
213
+ return { system, user };
214
+ }
215
+ /** Pull the JSON object out of a model reply (it may wrap it in a code fence). */
216
+ export function parsePickReply(text, allowed, max = 5) {
217
+ const start = text.indexOf('{'), end = text.lastIndexOf('}');
218
+ let value = null;
219
+ if (start >= 0 && end > start) {
220
+ try {
221
+ value = JSON.parse(text.slice(start, end + 1));
222
+ }
223
+ catch {
224
+ value = null;
225
+ }
226
+ }
227
+ if (value === null) {
228
+ // A reply cut off at the token limit (or with a stray character) still
229
+ // names its picks: take every complete {"name": ..., "why": ...} in order.
230
+ const found = [...text.matchAll(/"name"\s*:\s*"((?:[^"\\]|\\.)*)"(?:\s*,\s*"why"\s*:\s*"((?:[^"\\]|\\.)*)")?/gu)];
231
+ if (found.length === 0)
232
+ throw new Error('the model did not return JSON');
233
+ const intro = /"intro"\s*:\s*"((?:[^"\\]|\\.)*)"/u.exec(text)?.[1] ?? '';
234
+ value = { intro, picks: found.map(match => ({ name: match[1], why: match[2] ?? '' })) };
235
+ }
236
+ const picks = [];
237
+ const seen = new Set();
238
+ if (Array.isArray(value.picks)) {
239
+ for (const item of value.picks) {
240
+ const name = typeof item?.name === 'string' ? item.name.trim() : '';
241
+ if (!allowed.has(name) || seen.has(name))
242
+ continue;
243
+ seen.add(name);
244
+ picks.push({ name, why: typeof item?.why === 'string' ? item.why.trim().slice(0, 300) : '' });
245
+ if (picks.length === max)
246
+ break;
247
+ }
248
+ }
249
+ return { intro: typeof value.intro === 'string' ? value.intro.trim().slice(0, 300) : '', picks };
250
+ }
251
+ const errorCode = (error) => {
252
+ for (let current = error, depth = 0; current !== undefined && current !== null && depth < 5; depth += 1) {
253
+ const code = current.code;
254
+ if (typeof code === 'string')
255
+ return code;
256
+ current = current.cause;
257
+ }
258
+ return '';
259
+ };
260
+ const NO_MODEL = '还没有可用的模型:AI 找插件用的是你在 DSH 里配置的模型和 API Key,请先在「设置 → 模型」里配置一个。 / No model is set up yet: AI plugin search uses the model and API key you configured in DSH. Set one up under Settings → Models first.';
261
+ /** A catalog entry as a card-ready pick. */
262
+ function toPick(plugin, registry, preferZh, why) {
263
+ return {
264
+ name: plugin.name, owner: plugin.owner, url: plugin.url, npm: plugin.npm ?? null, install: plugin.install,
265
+ categories: pluginCategories(plugin).map(id => registry.categories[id]?.[preferZh ? 'zh' : 'en'] ?? registry.categories[id]?.en ?? id),
266
+ description: describe(plugin, preferZh),
267
+ downloads: typeof plugin.downloads === 'number' ? plugin.downloads : null,
268
+ stars: typeof plugin.stars === 'number' ? plugin.stars : null,
269
+ why,
270
+ };
271
+ }
272
+ const hasModel = (llm, selection) => llm !== undefined && selection !== undefined && Boolean(selection.provider) && Boolean(selection.model);
273
+ /** One model call over the candidates; the reply parsed to names that were offered. */
274
+ async function askForPicks(options) {
275
+ const { selection, prompt } = options;
276
+ let text = '';
277
+ let reasoning = '';
278
+ const seen = [];
279
+ try {
280
+ const stream = options.llm.stream({
281
+ provider: selection.provider,
282
+ model: selection.model,
283
+ // Picking from a list needs little thought, and a model set to think
284
+ // hard can spend the whole budget thinking and answer nothing (seen with
285
+ // DeepSeek at "high"). A selection that names an effort supports
286
+ // efforts, so it can be turned down; one that does not is left alone.
287
+ ...(selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort === 'off' ? 'off' : 'low' }),
288
+ system: prompt.system,
289
+ messages: [Object.freeze({
290
+ id: randomUUID(), role: 'user',
291
+ content: [{ type: 'text', text: prompt.user }],
292
+ source: { kind: 'plugin:dsh-crate' },
293
+ })],
294
+ maxTokens: options.maxTokens,
295
+ temperature: options.temperature,
296
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
297
+ });
298
+ for await (const chunk of stream) {
299
+ if (seen.length < 12)
300
+ seen.push(JSON.stringify(chunk).slice(0, 300));
301
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string')
302
+ text += chunk.text;
303
+ else if (chunk.type === 'reasoning-delta' && typeof chunk.text === 'string')
304
+ reasoning += chunk.text;
305
+ else if (chunk.type === 'finish') {
306
+ // The host ends a failed call (no key, bad key, provider down) with a
307
+ // finish whose reason is an error, rather than throwing.
308
+ const reason = chunk.reason;
309
+ if (reason?.kind === 'error') {
310
+ const failure = reason.failure ?? {};
311
+ throw Object.assign(new Error(typeof failure.message === 'string' ? failure.message : 'the model call failed'), typeof failure.code === 'string' ? { code: failure.code } : {});
312
+ }
313
+ }
314
+ else if (chunk.type === 'error') {
315
+ const failure = chunk.error ?? chunk.message;
316
+ throw failure instanceof Error ? failure : Object.assign(new Error(typeof failure === 'string' ? failure : JSON.stringify(failure)), typeof failure === 'object' && failure !== null ? { cause: failure } : {});
317
+ }
318
+ }
319
+ }
320
+ catch (error) {
321
+ const code = errorCode(error);
322
+ if (code === 'MISSING_CREDENTIAL' || code === 'INVALID_CREDENTIAL')
323
+ throw new FindPluginError('no-model', NO_MODEL);
324
+ const reason = error instanceof Error ? error.message : String(error);
325
+ throw new FindPluginError('model-failed', `模型这次没有回答(${reason})。请稍后重试,或换一个模型。 / The model did not answer (${reason}). Try again, or switch models.`);
326
+ }
327
+ let parsed;
328
+ try {
329
+ const allowed = new Set(options.candidates.map(item => item.plugin.name));
330
+ // Out of budget before the answer: the thinking often already holds it.
331
+ parsed = text.trim() === '' && reasoning !== '' ? parsePickReply(reasoning, allowed, options.max) : parsePickReply(text, allowed, options.max);
332
+ }
333
+ catch {
334
+ logEvent('warn', 'find-plugin', `unreadable model reply (${String(text.length)} chars, ${String(reasoning.length)} thinking): ${text.slice(0, 300)} … ${text.slice(-200)} | chunks: ${seen.join(' ')}`);
335
+ throw new FindPluginError('model-failed', '模型的回答格式不对,没法整理成结果。请重试一次。 / The model\'s answer was not in the expected shape. Try again.');
336
+ }
337
+ const byName = new Map(options.candidates.map(item => [item.plugin.name, item.plugin]));
338
+ return { intro: parsed.intro, picks: parsed.picks.map(({ name, why }) => ({ plugin: byName.get(name), why })) };
339
+ }
340
+ /** Recall, then let the model pick. Throws FindPluginError with a user-facing message. */
341
+ export async function findPlugins(options) {
342
+ const request = options.request.trim();
343
+ if (request === '')
344
+ throw new FindPluginError('empty', USAGE);
345
+ const { llm, registry, selection } = options;
346
+ if (!hasModel(llm, selection))
347
+ throw new FindPluginError('no-model', NO_MODEL);
348
+ const { have } = options;
349
+ const found = recall(registry, extractTerms(request), CANDIDATE_LIMIT, new Set((have?.installed ?? []).map(plugin => plugin.name)));
350
+ const answer = await askForPicks({
351
+ llm: llm, selection, prompt: buildPickPrompt(request, registry, found, have), candidates: found.candidates,
352
+ max: 5, maxTokens: 6000, temperature: 0.2, ...(options.signal === undefined ? {} : { signal: options.signal }),
353
+ });
354
+ const preferZh = /\p{Script=Han}/u.test(request);
355
+ const picks = answer.picks.map(({ plugin, why }) => toPick(plugin, registry, preferZh, why));
356
+ return { request, intro: answer.intro, picks, model: selection.model, at: new Date().toISOString(), personalized: have !== undefined };
357
+ }
358
+ // ---------- recommendations from what the user already has ----------
359
+ /** How many candidates a recommendation offers the model. */
360
+ export const RECOMMEND_CANDIDATES = 40;
361
+ /** How many plugins a recommendation shows. */
362
+ export const RECOMMEND_MAX = 10;
363
+ const isMarket = (plugin) => plugin.npm === 'dsh-crate' || plugin.name === 'dsh-crate';
364
+ export function userSeeds(registry, have) {
365
+ const names = new Set(have.installed.map(name => name.toLowerCase()));
366
+ const urls = new Set(have.favorites.map(url => url.toLowerCase().replace(/\.git$|\/+$/u, '')));
367
+ const installed = [];
368
+ const favorited = [];
369
+ for (const plugin of registry.plugins) {
370
+ if (isMarket(plugin))
371
+ continue;
372
+ if ((plugin.npm !== undefined && plugin.npm !== null && names.has(plugin.npm.toLowerCase())) || names.has(plugin.name.toLowerCase()))
373
+ installed.push(plugin);
374
+ else if (urls.has(plugin.url.toLowerCase().replace(/\.git$|\/+$/u, '')))
375
+ favorited.push(plugin);
376
+ }
377
+ return { installed, favorited };
378
+ }
379
+ /**
380
+ * What to offer the model: entries that share categories and words with what
381
+ * the user has (their taste), plus some popular ones from categories they have
382
+ * not touched (so a recommendation can open a new need, not only repeat one).
383
+ * Never what they already have, what was shown last time, or a deprecated one.
384
+ */
385
+ export function recommendCandidates(registry, seeds, exclude = [], limit = RECOMMEND_CANDIDATES) {
386
+ const skip = new Set([...seeds.map(plugin => plugin.name), ...exclude]);
387
+ const usable = registry.plugins.filter(plugin => plugin.deprecated !== true && !isMarket(plugin) && !skip.has(plugin.name));
388
+ const catWeight = new Map();
389
+ for (const plugin of seeds)
390
+ for (const id of pluginCategories(plugin))
391
+ catWeight.set(id, (catWeight.get(id) ?? 0) + 1);
392
+ const termCount = new Map();
393
+ for (const plugin of seeds) {
394
+ for (const term of new Set(extractTerms(`${describe(plugin, true)} ${describe(plugin, false)}`)))
395
+ termCount.set(term, (termCount.get(term) ?? 0) + 1);
396
+ }
397
+ const terms = [...termCount.entries()].sort((a, b) => b[1] - a[1]).slice(0, 40).map(([term]) => term);
398
+ const rarity = termRarity(usable, terms);
399
+ const popularity = (plugin) => Math.log10(2 + Math.max(0, downloadsOf(plugin))) + Math.log10(2 + Math.max(0, starsOf(plugin)));
400
+ const scored = usable.map(plugin => {
401
+ const cats = pluginCategories(plugin).reduce((sum, id) => sum + (catWeight.get(id) ?? 0), 0);
402
+ const words = terms.length === 0 ? 0 : scoreFor(plugin, terms, registry.categories, rarity);
403
+ return { plugin, score: cats * 4 + words + popularity(plugin) };
404
+ });
405
+ const fresh = (candidate) => pluginCategories(candidate.plugin).every(id => !catWeight.has(id));
406
+ const byScore = (a, b) => b.score - a.score || a.plugin.name.localeCompare(b.plugin.name);
407
+ const wider = Math.floor(limit / 4);
408
+ const near = scored.filter(item => !fresh(item)).sort(byScore).slice(0, limit - wider);
409
+ const far = scored.filter(fresh).sort((a, b) => popularity(b.plugin) - popularity(a.plugin) || byScore(a, b)).slice(0, limit - near.length);
410
+ return [...near, ...far];
411
+ }
412
+ export function buildRecommendPrompt(registry, seeds, candidates, preferZh) {
413
+ const system = [
414
+ 'You recommend plugins from the DSH plugin crate to one user, based on the plugins they already installed and favorited. Answer ONLY with one JSON object, no prose around it:',
415
+ '{"intro": string, "picks": [{"name": string, "why": string}]}',
416
+ `- picks: ${String(RECOMMEND_MAX - 4)} to ${String(RECOMMEND_MAX)} candidates this user is most likely to want next, best first. Use names exactly as listed; never a name that is not in the list.`,
417
+ '- Read what they have as a picture of how they use DSH. Prefer plugins that add something they do not have yet, or go well with what they have; skip near-duplicates of plugins they already have.',
418
+ '- Spread the picks over different needs rather than many plugins for one need. A well-used, maintained plugin beats an obscure one when both fit.',
419
+ '- why: one short sentence. intro: one short sentence on what you read from their plugins.',
420
+ `- Write intro and why in ${preferZh ? 'Simplified Chinese' : 'English'}.`,
421
+ ].join('\n');
422
+ const list = (plugins) => plugins.length === 0 ? ['(none)'] : plugins.map((plugin, i) => catalogLine(plugin, i, registry, preferZh));
423
+ const user = [
424
+ 'Installed:', ...list(seeds.installed), '',
425
+ 'Favorited (not necessarily installed):', ...list(seeds.favorited), '',
426
+ 'Candidates:', ...candidates.map(({ plugin }, i) => catalogLine(plugin, i, registry, preferZh)),
427
+ ].join('\n');
428
+ return { system, user };
429
+ }
430
+ const NO_SEEDS = '还没有装或收藏插件,AI 不知道你喜欢什么。先装或收藏几个插件再试试。 / Nothing installed or favorited yet, so there is nothing to go on. Install or favorite a few plugins first.';
431
+ /** Recommend plugins from what the user installed and favorited. Throws FindPluginError. */
432
+ export async function recommendPlugins(options) {
433
+ const { llm, registry, selection, preferZh } = options;
434
+ const seeds = userSeeds(registry, options);
435
+ if (seeds.installed.length + seeds.favorited.length === 0)
436
+ throw new FindPluginError('no-seeds', NO_SEEDS);
437
+ if (!hasModel(llm, selection))
438
+ throw new FindPluginError('no-model', NO_MODEL);
439
+ let candidates = recommendCandidates(registry, [...seeds.installed, ...seeds.favorited], options.exclude ?? []);
440
+ // "Show others" ran out of fresh entries: start over rather than show nothing.
441
+ if (candidates.length < RECOMMEND_MAX && (options.exclude ?? []).length > 0)
442
+ candidates = recommendCandidates(registry, [...seeds.installed, ...seeds.favorited]);
443
+ const answer = await askForPicks({
444
+ llm: llm, selection, prompt: buildRecommendPrompt(registry, seeds, candidates, preferZh), candidates,
445
+ max: RECOMMEND_MAX, maxTokens: 8000, temperature: 0.5, ...(options.signal === undefined ? {} : { signal: options.signal }),
446
+ });
447
+ const picks = answer.picks.map(({ plugin, why }) => toPick(plugin, registry, preferZh, why));
448
+ return { request: '', intro: answer.intro, picks, model: selection.model, at: new Date().toISOString() };
449
+ }
450
+ /** Plain text of a result, for hosts that draw the command row as text. */
451
+ export function resultText(result) {
452
+ if (result.picks.length === 0)
453
+ return result.intro || '没有找到合适的插件。 / No plugin fits this request.';
454
+ const lines = result.picks.map((pick, i) => `${i + 1}. ${pick.name} — ${pick.why}\n ${pick.install}`);
455
+ return [result.intro, ...lines].filter(Boolean).join('\n');
456
+ }
457
+ // ---------- results, kept so a card can be drawn again after a reload ----------
458
+ const RESULT_LIMIT = 200;
459
+ let results = null;
460
+ export function resultsFile(home = resolveDshHome()) {
461
+ return join(home, 'dsh-crate', 'find-plugin-results.json');
462
+ }
463
+ function loadResults(file) {
464
+ if (results !== null)
465
+ return results;
466
+ try {
467
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
468
+ results = new Map(Object.entries(raw));
469
+ }
470
+ catch {
471
+ results = new Map();
472
+ }
473
+ return results;
474
+ }
475
+ export function rememberResult(id, result, file = resultsFile()) {
476
+ const map = loadResults(file);
477
+ map.delete(id);
478
+ map.set(id, result);
479
+ while (map.size > RESULT_LIMIT)
480
+ map.delete(map.keys().next().value);
481
+ try {
482
+ mkdirSync(dirname(file), { recursive: true });
483
+ const temp = `${file}.${process.pid}.tmp`;
484
+ writeFileSync(temp, JSON.stringify(Object.fromEntries(map)));
485
+ renameSync(temp, file);
486
+ }
487
+ catch (error) {
488
+ logEvent('warn', 'find-plugin', `result not saved: ${error instanceof Error ? error.message : String(error)}`);
489
+ }
490
+ }
491
+ export function resultFor(id, file = resultsFile()) {
492
+ return loadResults(file).get(id);
493
+ }
494
+ /** Tests only. */
495
+ export function forgetResults() { results = null; }
496
+ const USAGE = '用法:/find-plugin 你想要什么样的插件,例如「通知类型的插件」「找找 seo 优化写作的插件」 / Usage: /find-plugin what you are looking for, e.g. "plugins that send notifications"';
497
+ const NO_ACCESS = { llm: () => undefined, defaultSelection: () => undefined };
498
+ let access = NO_ACCESS;
499
+ /** Set once by the plugin entry; routes read it at request time. */
500
+ export function setModelAccess(next) { access = next; }
501
+ export function modelAccess() { return access; }
502
+ // ---------- "use my plugins": the user's say-so, and where the lists come from ----------
503
+ /**
504
+ * Whether AI search and `/find-plugin` may read the user's installed and
505
+ * favorited plugins. Off until the user allows it from a result; one switch
506
+ * for the whole DSH home, kept beside the saved results.
507
+ */
508
+ export function consentFile(home = resolveDshHome()) {
509
+ return join(home, 'dsh-crate', 'ai-consent.json');
510
+ }
511
+ export function usesMyPlugins(file = consentFile()) {
512
+ try {
513
+ return JSON.parse(readFileSync(file, 'utf8')).useMyPlugins === true;
514
+ }
515
+ catch {
516
+ return false;
517
+ }
518
+ }
519
+ export function setUsesMyPlugins(on, file = consentFile()) {
520
+ mkdirSync(dirname(file), { recursive: true });
521
+ const temp = `${file}.${process.pid}.tmp`;
522
+ writeFileSync(temp, JSON.stringify({ useMyPlugins: on }));
523
+ renameSync(temp, file);
524
+ }
525
+ let readUserPlugins = () => ({ installed: [], favorites: [] });
526
+ /** Set by the routes, which know the active profile. */
527
+ export function setUserPluginsReader(next) { readUserPlugins = next; }
528
+ /** The user's own plugins for a search, or undefined when they have not allowed it. */
529
+ function allowedSeeds(registry) {
530
+ if (!usesMyPlugins())
531
+ return undefined;
532
+ try {
533
+ return userSeeds(registry, readUserPlugins());
534
+ }
535
+ catch (error) {
536
+ logEvent('warn', 'find-plugin', `could not read the user's plugins: ${error instanceof Error ? error.message : String(error)}`);
537
+ return undefined;
538
+ }
539
+ }
540
+ /** The market page's AI search: the same recall and pick, with the default model. */
541
+ export async function aiSearch(request, loadRegistry, signal) {
542
+ let registry;
543
+ try {
544
+ registry = await loadRegistry();
545
+ }
546
+ catch (error) {
547
+ throw new FindPluginError('catalog', `暂时拿不到插件目录(${error instanceof Error ? error.message : String(error)})。 / Could not reach the plugin catalog.`);
548
+ }
549
+ const have = allowedSeeds(registry);
550
+ return findPlugins({ request, registry, llm: access.llm(), selection: access.defaultSelection(), ...(have === undefined ? {} : { have }), ...(signal === undefined ? {} : { signal }) });
551
+ }
552
+ /** The market page's "recommend for me": what the user has, judged by their default model. */
553
+ export async function aiRecommend(have, loadRegistry, signal) {
554
+ let registry;
555
+ try {
556
+ registry = await loadRegistry();
557
+ }
558
+ catch (error) {
559
+ throw new FindPluginError('catalog', `暂时拿不到插件目录(${error instanceof Error ? error.message : String(error)})。 / Could not reach the plugin catalog.`);
560
+ }
561
+ return recommendPlugins({ registry, ...have, llm: access.llm(), selection: access.defaultSelection(), ...(signal === undefined ? {} : { signal }) });
562
+ }
563
+ /** Run one `/find-plugin`. The structured result is kept under the command id for the card renderer. */
564
+ export async function runFindPlugin(invocation, loadRegistry, models) {
565
+ if (invocation.rawInput.trim() === '')
566
+ return { kind: 'error', text: USAGE };
567
+ let registry;
568
+ try {
569
+ registry = await loadRegistry();
570
+ }
571
+ catch (error) {
572
+ const reason = error instanceof Error ? error.message : String(error);
573
+ return { kind: 'error', text: `暂时拿不到插件目录(${reason}),所以没法搜索。请稍后再试,或直接打开「插件」页的「插件箱子」。 / Could not reach the plugin catalog (${reason}), so there is nothing to search. Try again in a moment, or open Plugins → Plugin Crate.` };
574
+ }
575
+ // The model this chat is using, so the answer costs what the user expects;
576
+ // the default model when the agent does not say.
577
+ const own = invocation.agent.options;
578
+ const selection = own?.provider && own?.model ? { provider: own.provider, model: own.model } : models.defaultSelection();
579
+ try {
580
+ const have = allowedSeeds(registry);
581
+ const result = await findPlugins({ request: invocation.rawInput, registry, llm: models.llm(), selection, ...(have === undefined ? {} : { have }), signal: invocation.signal });
582
+ rememberResult(invocation.commandId, result);
583
+ // Also as this session's latest: on a blank session the chat draws no
584
+ // command row, and the client shows the result from here instead.
585
+ if (typeof invocation.agent.id === 'string')
586
+ rememberResult(`session:${invocation.agent.id}`, result);
587
+ return { kind: 'success', text: resultText(result) };
588
+ }
589
+ catch (error) {
590
+ return { kind: 'error', text: error instanceof FindPluginError ? error.message : String(error) };
591
+ }
592
+ }
593
+ /** Register `/find-plugin` on a host that has the command registry. */
594
+ export function registerFindPlugin(commands, loadRegistry, models) {
595
+ return commands.register({
596
+ name: 'find-plugin',
597
+ description: '用一句话在插件箱子里找插件(用你的模型挑选) / Describe what you want; your model picks plugins from the market',
598
+ input: { hint: '例如:通知类型的插件 · e.g. SEO writing' },
599
+ handler: invocation => runFindPlugin(invocation, loadRegistry, models),
600
+ });
601
+ }
package/lib/index.js CHANGED
@@ -13,6 +13,8 @@ import { mountMarketRoutes } from './routes.js';
13
13
  import { installDesktopMarketSettings, installMarketSettings } from './settings.js';
14
14
  import { MAX_AUTO_REPAIR_ATTEMPTS } from './pending-updates.js';
15
15
  import { observeStartupRepair } from './startup-repair-report.js';
16
+ import { modelAccess, registerFindPlugin, setModelAccess } from './find-plugin.js';
17
+ import { loadRegistry } from './registry.js';
16
18
  export const name = 'dsh-crate';
17
19
  /**
18
20
  * How long after the market mounts an interrupted update is repaired.
@@ -435,4 +437,25 @@ export function apply(ctx, config) {
435
437
  }, 'dsh-crate: Desktop http routes and package operations');
436
438
  });
437
439
  });
440
+ // The user's own model, for `/find-plugin` and the market's AI search. Both
441
+ // services are read at call time: a host without them answers "no model".
442
+ setModelAccess({
443
+ llm: () => ctx.get('llm'),
444
+ defaultSelection: () => {
445
+ const config = ctx.get('agentDefaultModel');
446
+ try {
447
+ return config?.currentSelection();
448
+ }
449
+ catch {
450
+ return undefined;
451
+ }
452
+ },
453
+ });
454
+ // `/find-plugin` in the chat. Only hosts that ship the command registry
455
+ // (dsh-commands) offer it; on an older host this never runs and nothing
456
+ // else depends on it.
457
+ ctx.inject(['commands'], (commandsCtx) => {
458
+ const commands = commandsCtx.commands;
459
+ commandsCtx.effect(() => registerFindPlugin(commands, () => loadRegistry(), modelAccess()), 'dsh-crate: /find-plugin command');
460
+ });
438
461
  }