dshmarket 1.74.0 → 1.76.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,401 @@
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) {
163
+ const usable = registry.plugins.filter(plugin => plugin.deprecated !== true && plugin.npm !== 'dshmarket' && plugin.name !== 'dsh-market');
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) {
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 market. 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
+ ].filter(Boolean).join('\n');
207
+ const user = [`Request: ${request}`, '', 'Candidates:', ...found.candidates.map(({ plugin }, i) => catalogLine(plugin, i, registry, preferZh))].join('\n');
208
+ return { system, user };
209
+ }
210
+ /** Pull the JSON object out of a model reply (it may wrap it in a code fence). */
211
+ export function parsePickReply(text, allowed) {
212
+ const start = text.indexOf('{'), end = text.lastIndexOf('}');
213
+ if (start < 0 || end <= start)
214
+ throw new Error('the model did not return JSON');
215
+ const value = JSON.parse(text.slice(start, end + 1));
216
+ const picks = [];
217
+ const seen = new Set();
218
+ if (Array.isArray(value.picks)) {
219
+ for (const item of value.picks) {
220
+ const name = typeof item?.name === 'string' ? item.name.trim() : '';
221
+ if (!allowed.has(name) || seen.has(name))
222
+ continue;
223
+ seen.add(name);
224
+ picks.push({ name, why: typeof item?.why === 'string' ? item.why.trim().slice(0, 300) : '' });
225
+ if (picks.length === 5)
226
+ break;
227
+ }
228
+ }
229
+ return { intro: typeof value.intro === 'string' ? value.intro.trim().slice(0, 300) : '', picks };
230
+ }
231
+ const errorCode = (error) => {
232
+ for (let current = error, depth = 0; current !== undefined && current !== null && depth < 5; depth += 1) {
233
+ const code = current.code;
234
+ if (typeof code === 'string')
235
+ return code;
236
+ current = current.cause;
237
+ }
238
+ return '';
239
+ };
240
+ 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.';
241
+ /** Recall, then let the model pick. Throws FindPluginError with a user-facing message. */
242
+ export async function findPlugins(options) {
243
+ const request = options.request.trim();
244
+ if (request === '')
245
+ throw new FindPluginError('empty', USAGE);
246
+ if (options.llm === undefined || options.selection === undefined || !options.selection.provider || !options.selection.model) {
247
+ throw new FindPluginError('no-model', NO_MODEL);
248
+ }
249
+ const { registry, selection } = options;
250
+ const found = recall(registry, extractTerms(request));
251
+ const prompt = buildPickPrompt(request, registry, found);
252
+ let text = '';
253
+ try {
254
+ const stream = options.llm.stream({
255
+ provider: selection.provider,
256
+ model: selection.model,
257
+ ...(selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort }),
258
+ system: prompt.system,
259
+ messages: [Object.freeze({
260
+ id: randomUUID(), role: 'user',
261
+ content: [{ type: 'text', text: prompt.user }],
262
+ source: { kind: 'plugin:dshmarket' },
263
+ })],
264
+ maxTokens: 1200,
265
+ temperature: 0.2,
266
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
267
+ });
268
+ for await (const chunk of stream)
269
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string')
270
+ text += chunk.text;
271
+ }
272
+ catch (error) {
273
+ const code = errorCode(error);
274
+ if (code === 'MISSING_CREDENTIAL' || code === 'INVALID_CREDENTIAL')
275
+ throw new FindPluginError('no-model', NO_MODEL);
276
+ const reason = error instanceof Error ? error.message : String(error);
277
+ throw new FindPluginError('model-failed', `模型这次没有回答(${reason})。请稍后重试,或换一个模型。 / The model did not answer (${reason}). Try again, or switch models.`);
278
+ }
279
+ let parsed;
280
+ try {
281
+ parsed = parsePickReply(text, new Set(found.candidates.map(item => item.plugin.name)));
282
+ }
283
+ catch {
284
+ throw new FindPluginError('model-failed', '模型的回答格式不对,没法整理成结果。请重试一次。 / The model\'s answer was not in the expected shape. Try again.');
285
+ }
286
+ const byName = new Map(found.candidates.map(item => [item.plugin.name, item.plugin]));
287
+ const preferZh = /\p{Script=Han}/u.test(request);
288
+ const picks = parsed.picks.map(({ name, why }) => {
289
+ const plugin = byName.get(name);
290
+ return {
291
+ name: plugin.name, owner: plugin.owner, url: plugin.url, npm: plugin.npm ?? null, install: plugin.install,
292
+ categories: pluginCategories(plugin).map(id => registry.categories[id]?.[preferZh ? 'zh' : 'en'] ?? registry.categories[id]?.en ?? id),
293
+ description: describe(plugin, preferZh),
294
+ downloads: typeof plugin.downloads === 'number' ? plugin.downloads : null,
295
+ stars: typeof plugin.stars === 'number' ? plugin.stars : null,
296
+ why,
297
+ };
298
+ });
299
+ return { request, intro: parsed.intro, picks, model: selection.model, at: new Date().toISOString() };
300
+ }
301
+ /** Plain text of a result, for hosts that draw the command row as text. */
302
+ export function resultText(result) {
303
+ if (result.picks.length === 0)
304
+ return result.intro || '没有找到合适的插件。 / No plugin fits this request.';
305
+ const lines = result.picks.map((pick, i) => `${i + 1}. ${pick.name} — ${pick.why}\n ${pick.install}`);
306
+ return [result.intro, ...lines].filter(Boolean).join('\n');
307
+ }
308
+ // ---------- results, kept so a card can be drawn again after a reload ----------
309
+ const RESULT_LIMIT = 200;
310
+ let results = null;
311
+ export function resultsFile(home = resolveDshHome()) {
312
+ return join(home, 'dsh-market', 'find-plugin-results.json');
313
+ }
314
+ function loadResults(file) {
315
+ if (results !== null)
316
+ return results;
317
+ try {
318
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
319
+ results = new Map(Object.entries(raw));
320
+ }
321
+ catch {
322
+ results = new Map();
323
+ }
324
+ return results;
325
+ }
326
+ export function rememberResult(id, result, file = resultsFile()) {
327
+ const map = loadResults(file);
328
+ map.delete(id);
329
+ map.set(id, result);
330
+ while (map.size > RESULT_LIMIT)
331
+ map.delete(map.keys().next().value);
332
+ try {
333
+ mkdirSync(dirname(file), { recursive: true });
334
+ const temp = `${file}.${process.pid}.tmp`;
335
+ writeFileSync(temp, JSON.stringify(Object.fromEntries(map)));
336
+ renameSync(temp, file);
337
+ }
338
+ catch (error) {
339
+ logEvent('warn', 'find-plugin', `result not saved: ${error instanceof Error ? error.message : String(error)}`);
340
+ }
341
+ }
342
+ export function resultFor(id, file = resultsFile()) {
343
+ return loadResults(file).get(id);
344
+ }
345
+ /** Tests only. */
346
+ export function forgetResults() { results = null; }
347
+ const USAGE = '用法:/find-plugin 你想要什么样的插件,例如「通知类型的插件」「找找 seo 优化写作的插件」 / Usage: /find-plugin what you are looking for, e.g. "plugins that send notifications"';
348
+ const NO_ACCESS = { llm: () => undefined, defaultSelection: () => undefined };
349
+ let access = NO_ACCESS;
350
+ /** Set once by the plugin entry; routes read it at request time. */
351
+ export function setModelAccess(next) { access = next; }
352
+ export function modelAccess() { return access; }
353
+ /** The market page's AI search: the same recall and pick, with the default model. */
354
+ export async function aiSearch(request, loadRegistry, signal) {
355
+ let registry;
356
+ try {
357
+ registry = await loadRegistry();
358
+ }
359
+ catch (error) {
360
+ throw new FindPluginError('catalog', `暂时拿不到插件目录(${error instanceof Error ? error.message : String(error)})。 / Could not reach the plugin catalog.`);
361
+ }
362
+ return findPlugins({ request, registry, llm: access.llm(), selection: access.defaultSelection(), ...(signal === undefined ? {} : { signal }) });
363
+ }
364
+ /** Run one `/find-plugin`. The structured result is kept under the command id for the card renderer. */
365
+ export async function runFindPlugin(invocation, loadRegistry, models) {
366
+ if (invocation.rawInput.trim() === '')
367
+ return { kind: 'error', text: USAGE };
368
+ let registry;
369
+ try {
370
+ registry = await loadRegistry();
371
+ }
372
+ catch (error) {
373
+ const reason = error instanceof Error ? error.message : String(error);
374
+ 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 Market.` };
375
+ }
376
+ // The model this chat is using, so the answer costs what the user expects;
377
+ // the default model when the agent does not say.
378
+ const own = invocation.agent.options;
379
+ const selection = own?.provider && own?.model ? { provider: own.provider, model: own.model } : models.defaultSelection();
380
+ try {
381
+ const result = await findPlugins({ request: invocation.rawInput, registry, llm: models.llm(), selection, signal: invocation.signal });
382
+ rememberResult(invocation.commandId, result);
383
+ // Also as this session's latest: on a blank session the chat draws no
384
+ // command row, and the client shows the result from here instead.
385
+ if (typeof invocation.agent.id === 'string')
386
+ rememberResult(`session:${invocation.agent.id}`, result);
387
+ return { kind: 'success', text: resultText(result) };
388
+ }
389
+ catch (error) {
390
+ return { kind: 'error', text: error instanceof FindPluginError ? error.message : String(error) };
391
+ }
392
+ }
393
+ /** Register `/find-plugin` on a host that has the command registry. */
394
+ export function registerFindPlugin(commands, loadRegistry, models) {
395
+ return commands.register({
396
+ name: 'find-plugin',
397
+ description: '用一句话在插件市场里找插件(用你的模型挑选) / Describe what you want; your model picks plugins from the market',
398
+ input: { hint: '例如:通知类型的插件 · e.g. SEO writing' },
399
+ handler: invocation => runFindPlugin(invocation, loadRegistry, models),
400
+ });
401
+ }
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-market';
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-market: 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-market: /find-plugin command');
460
+ });
438
461
  }
package/lib/routes.js CHANGED
@@ -14,6 +14,7 @@ import { Readable } from 'node:stream';
14
14
  import { isDeepStrictEqual } from 'node:util';
15
15
  import { load as loadYaml } from 'js-yaml';
16
16
  import { packageFileFromRegistry } from './catalog-npm.js';
17
+ import { aiSearch, FindPluginError, resultFor } from './find-plugin.js';
17
18
  import { forgetCatalog, loadRegistry, pluginCategories } from './registry.js';
18
19
  import { settingsNamespaceState } from './settings.js';
19
20
  import { buildEnvFromUnknown, cleanHotDir, forgetInstalled, hotMount, hotMountFailure, hotUnmount, listHotMounts, listLiveHotMounts, MAX_BLOCKED, MAX_BLOCKED_NAME, MAX_FAVORITES, MAX_NOTE, MAX_UPDATE_EXEMPT, mountClientOnlyDeps, purgeMarketState, readMarketState, recordInstalled, recordUpdated, writeMarketState, } from './hot.js';
@@ -198,6 +199,33 @@ function githubUpdateTarget(spec) {
198
199
  const selectors = [...(ref === null ? [] : [ref]), ...(subpath === null ? [] : [`path:/${subpath}`])];
199
200
  return selectors.length === 0 ? repo : `${repo}#${selectors.join('&')}`;
200
201
  }
202
+ /**
203
+ * What an update of `spec` re-resolves, before any region acceleration:
204
+ * `gitSpec` for a GitHub source in either spelling (the `github:` shortcut or
205
+ * a legacy proxied codeload URL), `genericGitTarget` for any other git remote
206
+ * (#525). Both are null for a source that is not git.
207
+ */
208
+ function gitUpdateTargets(spec) {
209
+ const codeloadRepo = spec.startsWith('github:') ? null : repoOfTarget(spec);
210
+ const gitSpec = spec.startsWith('github:')
211
+ ? githubUpdateTarget(spec)
212
+ : codeloadRepo === null ? null : `github:${codeloadRepo}`;
213
+ return { gitSpec, genericGitTarget: gitSpec === null ? gitUpdateTarget(spec) : null };
214
+ }
215
+ /**
216
+ * Whether the update route may send this install's update as
217
+ * `pnpm update <name>` on a host that takes the market's options: a floating
218
+ * git source, whose update target is the specifier itself (#562). The
219
+ * one-shot release-age retry (#39) covers only `add` and `remove`, so that
220
+ * update fails on a young lockfile entry. "May": in an accelerated region (a
221
+ * bare `github:owner/repo`) and for a deferred run (any `github:` source) the
222
+ * route first pins the source to its head commit when it can resolve one, and
223
+ * the pinned target goes out as an `add`.
224
+ */
225
+ function mayUpdateGitInPlace(spec) {
226
+ const { gitSpec, genericGitTarget } = gitUpdateTargets(spec);
227
+ return (genericGitTarget ?? gitSpec) === spec;
228
+ }
201
229
  /**
202
230
  * Whether an installed package declares a client part (`dsh.client`). Its UI
203
231
  * is injected into the page, so toggling it needs a browser refresh to show
@@ -2982,7 +3010,24 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2982
3010
  profileKey: createHash('sha256').update(activeProfileDir).digest('hex'),
2983
3011
  enabled: marketState.backgroundUpdateChecks === true,
2984
3012
  intervalHours: marketState.backgroundUpdateIntervalHours,
2985
- overlay: updates => applyProfileBlockers(updates, activeProfileDir),
3013
+ // A learned blocker (#1252) holds the offered updates that would stop or
3014
+ // fail on it. On the official Desktop bridge (no market options) and on
3015
+ // Desktop hosts that is every one, as before; checkUpdates holds young
3016
+ // releases on those hosts too (#945). Elsewhere the update route never
3017
+ // stops on a blocker, and it sends most updates as an `add`, which it
3018
+ // retries once with the release-age bypass (#39) when pnpm refuses it for
3019
+ // a young lockfile entry, so those rows stay offered. A floating git
3020
+ // source may go out as `pnpm update <name>` instead; that verb gets no
3021
+ // retry and fails on the blocker, so its row stays held.
3022
+ overlay: updates => {
3023
+ if (!marketFlags || config.desktopHost === true)
3024
+ return applyProfileBlockers(updates, activeProfileDir);
3025
+ const installed = readInstalled(config.profile, activeProfileDir);
3026
+ return applyProfileBlockers(updates, activeProfileDir, Date.now(), name => {
3027
+ const spec = installed[name];
3028
+ return spec === undefined || mayUpdateGitInPlace(spec);
3029
+ });
3030
+ },
2986
3031
  inventory: () => {
2987
3032
  const installed = readInstalled(config.profile, activeProfileDir);
2988
3033
  const commits = readLockCommits(config.profile, activeProfileDir);
@@ -3858,6 +3903,59 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3858
3903
  }
3859
3904
  },
3860
3905
  }),
3906
+ registerRoute({
3907
+ kind: 'exact',
3908
+ // The card behind one `/find-plugin` row: the chat keeps only the
3909
+ // command's text, the structured picks live here under its command id.
3910
+ path: '/dsh-market/find-plugin/result',
3911
+ handler: async (request, response) => {
3912
+ if (request.method !== 'GET') {
3913
+ response.writeHead(405, { allow: 'GET' });
3914
+ response.end();
3915
+ return;
3916
+ }
3917
+ const params = new URL(request.url ?? '', 'http://x').searchParams;
3918
+ const id = params.get('id') ?? '';
3919
+ const session = params.get('session') ?? '';
3920
+ const result = id !== '' ? resultFor(id) : session !== '' ? resultFor(`session:${session}`) : undefined;
3921
+ if (result === undefined)
3922
+ sendJson(response, 404, { error: 'unknown result' });
3923
+ else
3924
+ sendJson(response, 200, { result });
3925
+ },
3926
+ }),
3927
+ registerRoute({
3928
+ kind: 'exact',
3929
+ // The market page's AI search: the user's default model picks from the catalog.
3930
+ path: '/dsh-market/ai-search',
3931
+ handler: async (request, response) => {
3932
+ if (request.method !== 'POST') {
3933
+ response.writeHead(405, { allow: 'POST' });
3934
+ response.end();
3935
+ return;
3936
+ }
3937
+ if (!sameOrigin(request)) {
3938
+ sendJson(response, 403, { error: 'untrusted origin' });
3939
+ return;
3940
+ }
3941
+ const body = await readJsonBody(request).catch(() => null);
3942
+ const query = typeof body?.query === 'string' ? body.query.slice(0, 500) : '';
3943
+ if (query.trim() === '') {
3944
+ sendJson(response, 400, { code: 'empty', error: '请先描述你想要什么样的插件。 / Describe the plugin you want first.' });
3945
+ return;
3946
+ }
3947
+ try {
3948
+ sendJson(response, 200, { result: await aiSearch(query, () => loadRegistry()) });
3949
+ }
3950
+ catch (error) {
3951
+ if (error instanceof FindPluginError) {
3952
+ sendJson(response, error.code === 'no-model' ? 409 : 502, { code: error.code, error: error.message });
3953
+ return;
3954
+ }
3955
+ sendJson(response, 500, { code: 'model-failed', error: error instanceof Error ? error.message : String(error) });
3956
+ }
3957
+ },
3958
+ }),
3861
3959
  registerRoute({
3862
3960
  kind: 'exact',
3863
3961
  path: '/dsh-market/registry',
@@ -5882,14 +5980,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5882
5980
  // from it. Without this branch these fell through to the npm path
5883
5981
  // below, where `name@latest` either fails or — far worse —
5884
5982
  // installs an unrelated package that shares the plugin's name.
5885
- const codeloadRepo = spec.startsWith('github:') ? null : repoOfTarget(spec);
5886
- const gitSpec = spec.startsWith('github:')
5887
- ? githubUpdateTarget(spec)
5888
- : codeloadRepo === null ? null : `github:${codeloadRepo}`;
5983
+ //
5889
5984
  // Non-GitHub git remotes (Gitea / git+https): keep the remote URL
5890
5985
  // as the add target. Falling through to name@latest is what #525
5891
5986
  // reported — a colliding npm package replaced the private install.
5892
- const genericGitTarget = gitSpec === null ? gitUpdateTarget(spec) : null;
5987
+ const { gitSpec, genericGitTarget } = gitUpdateTargets(spec);
5893
5988
  const isGit = gitSpec !== null || genericGitTarget !== null;
5894
5989
  const isReleaseTarball = !restore && isGitHubReleaseTarballSpec(spec);
5895
5990
  let releaseUpdate = null;
@@ -0,0 +1,55 @@
1
+ export const SEARCH_SYNONYM_GROUPS = [
2
+ // Notifications
3
+ // 推送 (also git push) and alert are left out on purpose: two meanings.
4
+ { terms: ['通知', 'notify', 'notification', 'notifier', '消息提醒'], broad: ['提醒', 'reminder'] },
5
+ // Image generation
6
+ { terms: ['生图', '画图', '绘图', '作图', '出图', '图片生成', '生成图片', '生成图', '文生图', 'image generation', 'image gen', 'imagegen', 'text2img', 'text to image'] },
7
+ { terms: ['视频', 'video'] },
8
+ // Chat apps
9
+ { terms: ['飞书', 'feishu', 'lark'] },
10
+ { terms: ['微信', 'wechat', 'weixin'] },
11
+ { terms: ['企业微信', '企微', 'wecom'] },
12
+ { terms: ['钉钉', 'dingtalk'] },
13
+ { terms: ['qq', 'qqbot', 'onebot', 'napcat'] },
14
+ // Memory
15
+ { terms: ['记忆', '长期记忆', '记忆库', 'memory', 'long term memory'] },
16
+ // Themes
17
+ { terms: ['主题', '皮肤', '配色', '换肤', 'theme', 'skin', 'color scheme'] },
18
+ // Voice
19
+ {
20
+ terms: ['语音', 'voice', 'speech'],
21
+ broad: ['tts', 'stt', '朗读', '语音识别', '语音合成', 'text to speech', 'speech to text'],
22
+ },
23
+ { terms: ['tts', 'text to speech', '朗读', '语音合成', '文字转语音'] },
24
+ { terms: ['stt', 'asr', 'speech to text', '语音识别', '语音转文字', '听写'] },
25
+ // Translation
26
+ { terms: ['翻译', 'translate', 'translation', 'translator', '双语', 'bilingual'] },
27
+ // Search, browser, MCP
28
+ { terms: ['搜索', '检索', 'search', '联网搜索', '网页搜索', 'web search'] },
29
+ { terms: ['浏览器', 'browser'], broad: ['chrome', 'cdp', 'playwright', 'puppeteer', '网页自动化'] },
30
+ { terms: ['mcp', 'model context protocol', '模型上下文协议'] },
31
+ // Models and keys
32
+ { terms: ['模型接入', '接入模型', '模型供应商', '模型提供商', '自定义模型', 'provider'] },
33
+ { terms: ['api key', 'apikey', '密钥', 'api 密钥'] },
34
+ // Cost and usage
35
+ { terms: ['费用', '花费', '计费', '账单', 'cost', 'billing'] },
36
+ { terms: ['用量', '额度', 'usage', 'quota'] },
37
+ // Context
38
+ { terms: ['上下文', '上下文窗口', 'context window', 'context'], broad: ['上下文压缩', 'context compression', 'compaction'] },
39
+ { terms: ['上下文压缩', 'context compression', 'compaction'] },
40
+ // Office
41
+ { terms: ['ppt', 'pptx', 'powerpoint', '幻灯片', 'slides', '演示文稿'] },
42
+ { terms: ['excel', 'xlsx', 'spreadsheet'] },
43
+ { terms: ['docx', 'word 文档', 'microsoft word'] },
44
+ { terms: ['剪贴板', 'clipboard'] },
45
+ { terms: ['邮件', '邮箱', 'email', 'mail'] },
46
+ { terms: ['定时', '定时任务', '计划任务', 'cron'] },
47
+ // Developer
48
+ { terms: ['git', '版本控制', 'version control'] },
49
+ { terms: ['终端', 'terminal', 'shell', '命令行', 'command line'], broad: ['pty', 'tmux', 'tui'] },
50
+ // Pets
51
+ { terms: ['桌宠', '宠物', '桌面宠物', '看板娘', 'pet', 'mascot'], broad: ['live2d'] },
52
+ // Mobile and remote
53
+ { terms: ['手机', '手机端', '移动端', 'mobile', 'phone'], broad: ['pwa', 'android', 'ios'] },
54
+ { terms: ['远程', '远程控制', '远程访问', 'remote', 'remote control'], broad: ['内网穿透', 'tunnel'] },
55
+ ];