dshmarket 1.76.0 → 1.77.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/lib/dsh-cli.js CHANGED
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import { spawn, spawnSync } from 'node:child_process';
10
10
  import { existsSync, readFileSync, rmSync } from 'node:fs';
11
- import { homedir } from 'node:os';
11
+ import { homedir, tmpdir } from 'node:os';
12
12
  import { dirname, isAbsolute, join, resolve } from 'node:path';
13
13
  import { logEvent } from './log.js';
14
14
  import { createProgressTracker } from './ndjson.js';
@@ -749,6 +749,34 @@ export function probePnpm() {
749
749
  return probePnpmOnPath();
750
750
  return probeHostPackageManager().then(ready => ready ? true : probePnpmOnPath());
751
751
  }
752
+ /**
753
+ * The cwd to hand a provisioning child.
754
+ *
755
+ * `corepack enable`, `npm i -g` and `npm prefix -g` read no project files, so
756
+ * they gain nothing from inheriting this process's directory — and a host
757
+ * whose boot directory was deleted loses everything to it: the child dies
758
+ * inside `getcwd()` before running a line of its own logic, which is how a
759
+ * one-click setup ended up reporting `npm -g: exit=7` with `syscall:
760
+ * 'uv_cwd'` (#1270).
761
+ *
762
+ * A readable directory is still inherited unchanged, so a healthy machine
763
+ * behaves exactly as before, including the per-project `.npmrc` npm would
764
+ * read from it. Only an unreadable one is replaced, and then with a directory
765
+ * that exists by definition.
766
+ *
767
+ * `process.cwd()` throws instead of returning a stale path, so the call
768
+ * itself is the test.
769
+ * @returns `undefined` to inherit, or a directory that is known to exist.
770
+ */
771
+ export function provisionCwd() {
772
+ try {
773
+ process.cwd();
774
+ return undefined;
775
+ }
776
+ catch {
777
+ return tmpdir();
778
+ }
779
+ }
752
780
  /** Probe `pnpm --version` on PATH. */
753
781
  function probePnpmOnPath() {
754
782
  if (pnpmReady)
@@ -779,6 +807,7 @@ function runQuiet(file, args, timeoutMs) {
779
807
  env: spawnEnv(),
780
808
  stdio: ['ignore', 'pipe', 'pipe'],
781
809
  viaShell: winCmdShim,
810
+ cwd: provisionCwd(),
782
811
  });
783
812
  const output = createOutputBuffer(8 * 1024);
784
813
  const timer = setTimeout(() => killChild(child), timeoutMs);
@@ -894,11 +923,29 @@ function hostPackageManagerHint() {
894
923
  * @returns a bilingual, actionable hint, or undefined when unrecognized.
895
924
  */
896
925
  export function provisionHint(corepackOutput, npmOutput, npmFound = true, probeFailure = null) {
926
+ // npm started and then could not read the directory it was started in: the
927
+ // host's own cwd had been deleted, so `getcwd()` failed before npm reached
928
+ // any of its logic (#1270). Nothing is missing and nothing is
929
+ // misconfigured, which makes every PATH-shaped hint below — install pnpm,
930
+ // start from a terminal, set PNPM_HOME — advice for a problem this user
931
+ // does not have. `provisionCwd` now keeps a dead directory from being
932
+ // inherited in the first place, so reaching this means the cwd went away
933
+ // after the spawn; naming it is still the only accurate thing to say.
934
+ if (/syscall:\s*['"]uv_cwd['"]/.test(`${corepackOutput}\n${npmOutput}`)) {
935
+ return '这台机器上 dsh 进程启动时的工作目录已经被删掉了,所以 npm 还没跑到自己的逻辑就退了(`syscall: \'uv_cwd\'` 是取当前目录失败,不是找不到文件)。这不是 pnpm 的问题,也不是 PATH 的问题,装什么都修不好。请从一个存在的目录重启 dsh:launchd / systemd 托管的部署把工作目录指到一个确定存在的目录(例如 /tmp),或者先在终端 cd 到任意存在的目录再启动 / The directory this dsh process was started in no longer exists, so npm exited inside `getcwd()` before reaching any of its own logic (`syscall: \'uv_cwd\'` — reading the current directory failed, nothing is missing on disk). This is not a pnpm problem and not a PATH problem, and no install can fix it. Restart dsh from a directory that exists: for launchd/systemd deployments point the working directory at one that does (e.g. /tmp), or `cd` somewhere real before starting it';
936
+ }
897
937
  // Node itself unreachable: pointing the user back at this same button
898
938
  // would be a dead end (#32). `npmFound` answers this from disk, so it
899
939
  // holds on a Windows console that reports the same thing in a codepage we
900
- // cannot read (#167); the ENOENT match stays for callers without it.
901
- if (!npmFound || (/ENOENT/.test(corepackOutput) && /ENOENT/.test(npmOutput))) {
940
+ // cannot read (#167).
941
+ //
942
+ // The ENOENT pair stays as a fallback for callers that do not pass
943
+ // `npmFound`, but it now has to be a spawn-level miss — `spawn npm ENOENT`,
944
+ // the shape a command that was never found produces. Matching the bare
945
+ // word is how a genuine `spawn corepack ENOENT` got ANDed with npm's
946
+ // `uv_cwd` ENOENT: two unrelated meanings on one token (#1270).
947
+ const spawnMissed = (output, tool) => output.includes(`spawn ${tool} ENOENT`);
948
+ if (!npmFound || (spawnMissed(corepackOutput, 'corepack') && spawnMissed(npmOutput, 'npm'))) {
902
949
  // The searched list is spelled out because the previous wording named
903
950
  // only the Node directory, which was both incomplete and unhelpful: a
904
951
  // user who HAD installed pnpm could not tell whether we looked in the
@@ -159,8 +159,8 @@ function termRarity(plugins, terms) {
159
159
  * most downloaded of the rest fill the list, because a model can still pick
160
160
  * something sensible from popular plugins, and an empty list helps no one.
161
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');
162
+ export function recall(registry, terms, limit = CANDIDATE_LIMIT, exclude = new Set()) {
163
+ const usable = registry.plugins.filter(plugin => plugin.deprecated !== true && plugin.npm !== 'dshmarket' && plugin.name !== 'dsh-market' && !exclude.has(plugin.name));
164
164
  const rarity = termRarity(usable, terms);
165
165
  const scored = usable
166
166
  .map(plugin => ({ plugin, score: terms.length === 0 ? 0 : scoreFor(plugin, terms, registry.categories, rarity) }));
@@ -188,7 +188,7 @@ function catalogLine(plugin, index, registry, preferZh) {
188
188
  return `${index + 1}. ${plugin.name} [${cats}] ${stats}\n ${describe(plugin, preferZh).slice(0, 400)}`;
189
189
  }
190
190
  /** The instruction and the candidates, as the one message the model reads. */
191
- export function buildPickPrompt(request, registry, found) {
191
+ export function buildPickPrompt(request, registry, found, have) {
192
192
  const preferZh = /\p{Script=Han}/u.test(request);
193
193
  const weak = found.matched === 0
194
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.'
@@ -203,16 +203,36 @@ export function buildPickPrompt(request, registry, found) {
203
203
  '- intro: one short sentence framing the result, e.g. what you understood they want, or that nothing fits.',
204
204
  `- Write intro and why in ${preferZh ? 'Simplified Chinese' : 'the language of the request'}.`,
205
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.',
206
207
  ].filter(Boolean).join('\n');
207
- const user = [`Request: ${request}`, '', 'Candidates:', ...found.candidates.map(({ plugin }, i) => catalogLine(plugin, i, registry, preferZh))].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');
208
213
  return { system, user };
209
214
  }
210
215
  /** Pull the JSON object out of a model reply (it may wrap it in a code fence). */
211
- export function parsePickReply(text, allowed) {
216
+ export function parsePickReply(text, allowed, max = 5) {
212
217
  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));
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
+ }
216
236
  const picks = [];
217
237
  const seen = new Set();
218
238
  if (Array.isArray(value.picks)) {
@@ -222,7 +242,7 @@ export function parsePickReply(text, allowed) {
222
242
  continue;
223
243
  seen.add(name);
224
244
  picks.push({ name, why: typeof item?.why === 'string' ? item.why.trim().slice(0, 300) : '' });
225
- if (picks.length === 5)
245
+ if (picks.length === max)
226
246
  break;
227
247
  }
228
248
  }
@@ -238,36 +258,64 @@ const errorCode = (error) => {
238
258
  return '';
239
259
  };
240
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.';
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);
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;
252
276
  let text = '';
277
+ let reasoning = '';
278
+ const seen = [];
253
279
  try {
254
280
  const stream = options.llm.stream({
255
281
  provider: selection.provider,
256
282
  model: selection.model,
257
- ...(selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort }),
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' }),
258
288
  system: prompt.system,
259
289
  messages: [Object.freeze({
260
290
  id: randomUUID(), role: 'user',
261
291
  content: [{ type: 'text', text: prompt.user }],
262
292
  source: { kind: 'plugin:dshmarket' },
263
293
  })],
264
- maxTokens: 1200,
265
- temperature: 0.2,
294
+ maxTokens: options.maxTokens,
295
+ temperature: options.temperature,
266
296
  ...(options.signal === undefined ? {} : { signal: options.signal }),
267
297
  });
268
- for await (const chunk of stream)
298
+ for await (const chunk of stream) {
299
+ if (seen.length < 12)
300
+ seen.push(JSON.stringify(chunk).slice(0, 300));
269
301
  if (chunk.type === 'text-delta' && typeof chunk.text === 'string')
270
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
+ }
271
319
  }
272
320
  catch (error) {
273
321
  const code = errorCode(error);
@@ -278,25 +326,126 @@ export async function findPlugins(options) {
278
326
  }
279
327
  let parsed;
280
328
  try {
281
- parsed = parsePickReply(text, new Set(found.candidates.map(item => item.plugin.name)));
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);
282
332
  }
283
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(' ')}`);
284
335
  throw new FindPluginError('model-failed', '模型的回答格式不对,没法整理成结果。请重试一次。 / The model\'s answer was not in the expected shape. Try again.');
285
336
  }
286
- const byName = new Map(found.candidates.map(item => [item.plugin.name, item.plugin]));
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
+ });
287
354
  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
- };
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 === 'dshmarket' || plugin.name === 'dsh-market';
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 market 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 }),
298
446
  });
299
- return { request, intro: parsed.intro, picks, model: selection.model, at: new Date().toISOString() };
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() };
300
449
  }
301
450
  /** Plain text of a result, for hosts that draw the command row as text. */
302
451
  export function resultText(result) {
@@ -350,6 +499,44 @@ let access = NO_ACCESS;
350
499
  /** Set once by the plugin entry; routes read it at request time. */
351
500
  export function setModelAccess(next) { access = next; }
352
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-market', '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
+ }
353
540
  /** The market page's AI search: the same recall and pick, with the default model. */
354
541
  export async function aiSearch(request, loadRegistry, signal) {
355
542
  let registry;
@@ -359,7 +546,19 @@ export async function aiSearch(request, loadRegistry, signal) {
359
546
  catch (error) {
360
547
  throw new FindPluginError('catalog', `暂时拿不到插件目录(${error instanceof Error ? error.message : String(error)})。 / Could not reach the plugin catalog.`);
361
548
  }
362
- return findPlugins({ request, registry, llm: access.llm(), selection: access.defaultSelection(), ...(signal === undefined ? {} : { signal }) });
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 }) });
363
562
  }
364
563
  /** Run one `/find-plugin`. The structured result is kept under the command id for the card renderer. */
365
564
  export async function runFindPlugin(invocation, loadRegistry, models) {
@@ -378,7 +577,8 @@ export async function runFindPlugin(invocation, loadRegistry, models) {
378
577
  const own = invocation.agent.options;
379
578
  const selection = own?.provider && own?.model ? { provider: own.provider, model: own.model } : models.defaultSelection();
380
579
  try {
381
- const result = await findPlugins({ request: invocation.rawInput, registry, llm: models.llm(), selection, signal: invocation.signal });
580
+ const have = allowedSeeds(registry);
581
+ const result = await findPlugins({ request: invocation.rawInput, registry, llm: models.llm(), selection, ...(have === undefined ? {} : { have }), signal: invocation.signal });
382
582
  rememberResult(invocation.commandId, result);
383
583
  // Also as this session's latest: on a blank session the chat draws no
384
584
  // command row, and the client shows the result from here instead.
package/lib/routes.js CHANGED
@@ -14,7 +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
+ import { aiRecommend, aiSearch, FindPluginError, resultFor, setUserPluginsReader, setUsesMyPlugins, usesMyPlugins } from './find-plugin.js';
18
18
  import { forgetCatalog, loadRegistry, pluginCategories } from './registry.js';
19
19
  import { settingsNamespaceState } from './settings.js';
20
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';
@@ -451,6 +451,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
451
451
  throw new Error(message);
452
452
  }
453
453
  const activeProfileDir = profileDir(config.profile, config.profileDirectory);
454
+ // AI search and /find-plugin read these only after the user allowed it.
455
+ setUserPluginsReader(() => ({
456
+ installed: Object.keys(readInstalled(config.profile, activeProfileDir)),
457
+ favorites: readMarketState(activeProfileDir).favorites ?? [],
458
+ }));
454
459
  // #987: a remove that died between deleting the package and clearing the
455
460
  // rows its bundle patch declares leaves an insert naming a missing module —
456
461
  // and DSH's boot is all-or-nothing, so that row can keep the host from
@@ -837,23 +842,61 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
837
842
  if (await themes.setEntryDisabled(name, true))
838
843
  logEvent('info', 'boot', `plugin kept off: ${name}`);
839
844
  }
845
+ /**
846
+ * The boot pass: shim-mount client-only packages, then put the persisted
847
+ * disable list back down.
848
+ *
849
+ * It is started from the `ctx.inject(['webServer','loader'], …)` callback,
850
+ * so it runs on that callback's context — and it keeps running after the
851
+ * callback returns. The host re-provisions services while it boots, and
852
+ * cordis refreshes EVERY fiber that injects a re-provided name: that
853
+ * disposes this context and re-runs `apply` on a fresh one, while the work
854
+ * started here is still going against the disposed copy. Reading
855
+ * `host.loader` there throws `cannot get required service "loader" in
856
+ * inactive context` — including from `includePrefix`, whose only job is to
857
+ * strip a row-id prefix (#1277).
858
+ *
859
+ * Nothing awaits this pass, so the throw left as a rejection nobody
860
+ * handled, and the host turned that into `fatal load failure`: on a profile
861
+ * whose disable list was non-empty the app came up empty — no sessions, no
862
+ * workspace, "settings could not be read, saving paused" — while the
863
+ * profile on disk was untouched. The list is what decides whether the pass
864
+ * runs at all, which is why an empty one never showed this.
865
+ *
866
+ * Catching here is not bookkeeping. The instance that replaced this one
867
+ * reads the same state and replays the same list, so the stale pass has
868
+ * nothing left to do — and if nothing replaced it, the next boot replays.
869
+ * Whatever else a replay can throw, one package's boot work must never be
870
+ * able to take the host down with it.
871
+ */
872
+ async function replayBootDisables() {
873
+ // Named in the log line, so a reader knows which step stopped rather than
874
+ // being told "boot failed" and nothing else.
875
+ let stage = 'mounting client-only shims';
876
+ try {
877
+ const mounted = await mountClientOnlyDeps(host, activeProfileDir);
878
+ if (mounted.length > 0)
879
+ logEvent('info', 'boot', `client-only shims mounted: ${mounted.join(', ')}`);
880
+ // Replay the persisted disable list: bundle-layer plugins the user
881
+ // switched away from get live-disabled again (bundle trees are
882
+ // in-memory, so the disable never persists on its own). Client-only
883
+ // shims for disabled plugins were already skipped by mountClientOnlyDeps.
884
+ for (const name of [...disabled]) {
885
+ stage = `replaying ${name}`;
886
+ if (followOutsideEnable(name))
887
+ continue;
888
+ noteHomeLayerConflict(name);
889
+ await replayDisabledPackage(name);
890
+ }
891
+ }
892
+ catch (error) {
893
+ logEvent('warn', 'boot', `boot replay stopped while ${stage}: ${error instanceof Error ? error.message : String(error)}. The disable list on disk is unchanged, so the next boot applies it again — and so does the market instance that replaces this one when the host rebuilt it mid-boot; a package this pass had not reached yet stays on until then (#1277)`);
894
+ }
895
+ }
840
896
  // Client-only packages (dsh.client without dsh.bundle) are invisible to the
841
897
  // bundle layer in every boot; the market shim-mounts them so their client
842
898
  // bundles are actually served.
843
- void mountClientOnlyDeps(host, activeProfileDir).then(async (mounted) => {
844
- if (mounted.length > 0)
845
- logEvent('info', 'boot', `client-only shims mounted: ${mounted.join(', ')}`);
846
- // Replay the persisted disable list: bundle-layer plugins the user
847
- // switched away from get live-disabled again (bundle trees are
848
- // in-memory, so the disable never persists on its own). Client-only
849
- // shims for disabled plugins were already skipped by mountClientOnlyDeps.
850
- for (const name of [...disabled]) {
851
- if (followOutsideEnable(name))
852
- continue;
853
- noteHomeLayerConflict(name);
854
- await replayDisabledPackage(name);
855
- }
856
- });
899
+ void replayBootDisables();
857
900
  // Self-healing guard: dsh's own patch overlay can re-update entries during
858
901
  // activation and wipe the runtime disabled flag — whenever a fiber comes
859
902
  // up for a plugin the user switched off, put it back down.
@@ -3956,6 +3999,75 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3956
3999
  }
3957
4000
  },
3958
4001
  }),
4002
+ registerRoute({
4003
+ kind: 'exact',
4004
+ // The user's say-so for AI search and /find-plugin to read their
4005
+ // installed and favorited plugins. GET reads it, POST {on} sets it.
4006
+ path: '/dsh-market/ai-use-my-plugins',
4007
+ handler: async (request, response) => {
4008
+ if (request.method === 'GET') {
4009
+ sendJson(response, 200, { on: usesMyPlugins() });
4010
+ return;
4011
+ }
4012
+ if (request.method !== 'POST') {
4013
+ response.writeHead(405, { allow: 'GET, POST' });
4014
+ response.end();
4015
+ return;
4016
+ }
4017
+ if (!sameOrigin(request)) {
4018
+ sendJson(response, 403, { error: 'untrusted origin' });
4019
+ return;
4020
+ }
4021
+ const body = await readJsonBody(request).catch(() => null);
4022
+ if (typeof body?.on !== 'boolean') {
4023
+ sendJson(response, 400, { error: 'on must be true or false' });
4024
+ return;
4025
+ }
4026
+ try {
4027
+ setUsesMyPlugins(body.on);
4028
+ sendJson(response, 200, { on: body.on });
4029
+ }
4030
+ catch (error) {
4031
+ sendJson(response, 500, { error: `没能保存这个设置(${error instanceof Error ? error.message : String(error)})。请重试。 / Could not save this setting. Try again.` });
4032
+ }
4033
+ },
4034
+ }),
4035
+ registerRoute({
4036
+ kind: 'exact',
4037
+ // "Recommend for me": the user's installed and favorited plugins, judged
4038
+ // by their default model. Only on a click (it reads both lists and spends
4039
+ // the user's tokens); nothing here runs by itself.
4040
+ path: '/dsh-market/ai-recommend',
4041
+ handler: async (request, response) => {
4042
+ if (request.method !== 'POST') {
4043
+ response.writeHead(405, { allow: 'POST' });
4044
+ response.end();
4045
+ return;
4046
+ }
4047
+ if (!sameOrigin(request)) {
4048
+ sendJson(response, 403, { error: 'untrusted origin' });
4049
+ return;
4050
+ }
4051
+ const body = await readJsonBody(request).catch(() => null);
4052
+ const exclude = Array.isArray(body?.exclude) ? body.exclude.filter((name) => typeof name === 'string').slice(0, 200) : [];
4053
+ try {
4054
+ const result = await aiRecommend({
4055
+ installed: Object.keys(readInstalled(config.profile, activeProfileDir)),
4056
+ favorites: readMarketState(activeProfileDir).favorites ?? [],
4057
+ exclude,
4058
+ preferZh: body?.lang !== 'en' && body?.lang !== 'ja',
4059
+ }, () => loadRegistry());
4060
+ sendJson(response, 200, { result });
4061
+ }
4062
+ catch (error) {
4063
+ if (error instanceof FindPluginError) {
4064
+ sendJson(response, error.code === 'no-model' || error.code === 'no-seeds' ? 409 : 502, { code: error.code, error: error.message });
4065
+ return;
4066
+ }
4067
+ sendJson(response, 500, { code: 'model-failed', error: error instanceof Error ? error.message : String(error) });
4068
+ }
4069
+ },
4070
+ }),
3959
4071
  registerRoute({
3960
4072
  kind: 'exact',
3961
4073
  path: '/dsh-market/registry',