dsh-crate 0.6.1 → 0.6.4

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/catalogs.js CHANGED
@@ -533,7 +533,7 @@ export function parseCatalogInput(text) {
533
533
  }
534
534
  }
535
535
  const expanded = expandHomePath(value);
536
- if (isAbsolute(expanded))
536
+ if (isAbsolute(expanded) || /^[\\/]/u.test(expanded))
537
537
  return { file: expanded };
538
538
  return { error: 'unrecognized' };
539
539
  }
@@ -233,9 +233,11 @@ function declarationResult(declaration, hostVersion) {
233
233
  /**
234
234
  * Derive the current host verdict from raw manifest facts.
235
235
  *
236
- * Every valid declaration is conjunctive: an explicit `engines.dsh` and all
237
- * host peers must agree. A malformed declaration keeps a passing result
238
- * unknown, but cannot erase a definite mismatch from another declaration.
236
+ * An explicit `engines.dsh` supersedes host peer declarations, matching the
237
+ * host loader. Without one, host peers are conjunctive. Host packages declared
238
+ * as ordinary dependencies remain checked because pnpm can hoist them over the
239
+ * runtime copy. A malformed declaration keeps a passing result unknown, but
240
+ * cannot erase a definite mismatch from another declaration.
239
241
  */
240
242
  export function deriveHostCompatibility(facts, hostVersion, hostPackages) {
241
243
  if (facts === null) {
@@ -245,14 +247,16 @@ export function deriveHostCompatibility(facts, hostVersion, hostPackages) {
245
247
  if (facts.enginesDsh !== null) {
246
248
  declarations.push({ kind: 'engine', range: facts.enginesDsh });
247
249
  }
248
- for (const [name, declared] of Object.entries(facts.peerDependencies)) {
249
- // Cordis (4.x) and schemastery (3.x) are host packages, but are not on
250
- // DSH's lockstep 0.x release line and therefore say nothing about the
251
- // DSH version. `hostPackages` is the local install inventory plus its
252
- // curated fallback, so future lockstep DSH packages are picked up too.
253
- if (!hostPackages.has(name) || !/^@deepseek-ai\/dsh(?:-|$)/.test(name))
254
- continue;
255
- declarations.push({ kind: 'peer', package: name, range: declared });
250
+ else {
251
+ for (const [name, declared] of Object.entries(facts.peerDependencies)) {
252
+ // Cordis (4.x) and schemastery (3.x) are host packages, but are not on
253
+ // DSH's lockstep 0.x release line and therefore say nothing about the
254
+ // DSH version. `hostPackages` is the local install inventory plus its
255
+ // curated fallback, so future lockstep DSH packages are picked up too.
256
+ if (!hostPackages.has(name) || !/^@deepseek-ai\/dsh(?:-|$)/.test(name))
257
+ continue;
258
+ declarations.push({ kind: 'peer', package: name, range: declared });
259
+ }
256
260
  }
257
261
  for (const [name, declared] of Object.entries(facts.dependencies ?? {})) {
258
262
  // The peer filter above restricts itself to DSH's lockstep line because a
@@ -182,10 +182,18 @@ export class FindPluginError extends Error {
182
182
  this.name = 'FindPluginError';
183
183
  }
184
184
  }
185
- function catalogLine(plugin, index, registry, preferZh) {
185
+ function catalogLine(plugin, registry, preferZh) {
186
186
  const cats = pluginCategories(plugin).map(id => registry.categories[id]?.[preferZh ? 'zh' : 'en'] ?? registry.categories[id]?.en ?? id).join('/');
187
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)}`;
188
+ return `${plugin.name} [${cats}] ${stats}\n ${describe(plugin, preferZh).slice(0, 400)}`;
189
+ }
190
+ const candidateId = (index) => `p${index + 1}`;
191
+ function candidateLines(candidates, registry, preferZh) {
192
+ return candidates.map(({ plugin }, index) => {
193
+ const source = [plugin.owner, plugin.npm].filter(Boolean).join(' / ');
194
+ const label = source === '' ? '' : ` (${source})`;
195
+ return `[${candidateId(index)}]${label} ${catalogLine(plugin, registry, preferZh)}`;
196
+ });
189
197
  }
190
198
  /** The instruction and the candidates, as the one message the model reads. */
191
199
  export function buildPickPrompt(request, registry, found, have) {
@@ -197,8 +205,8 @@ export function buildPickPrompt(request, registry, found, have) {
197
205
  : '';
198
206
  const system = [
199
207
  '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.',
208
+ '{"intro": string, "picks": [{"id": string, "why": string}]}',
209
+ '- picks: the 1 to 5 candidates that best fit what the user actually wants, best first. Use the candidate IDs (e.g. "p1") exactly as listed. Different entries may share a name. Return [] if none fit.',
202
210
  '- why: one short sentence on why it fits THIS request (not a copy of its description).',
203
211
  '- intro: one short sentence framing the result, e.g. what you understood they want, or that nothing fits.',
204
212
  `- Write intro and why in ${preferZh ? 'Simplified Chinese' : 'the language of the request'}.`,
@@ -209,7 +217,7 @@ export function buildPickPrompt(request, registry, found, have) {
209
217
  '', 'Already installed:', ...(have.installed.length === 0 ? ['(none)'] : have.installed.map(plugin => `- ${plugin.name}: ${describe(plugin, preferZh).slice(0, 160)}`)),
210
218
  'Favorited:', ...(have.favorited.length === 0 ? ['(none)'] : have.favorited.map(plugin => `- ${plugin.name}: ${describe(plugin, preferZh).slice(0, 160)}`)),
211
219
  ];
212
- const user = [`Request: ${request}`, ...mine, '', 'Candidates:', ...found.candidates.map(({ plugin }, i) => catalogLine(plugin, i, registry, preferZh))].join('\n');
220
+ const user = [`Request: ${request}`, ...mine, '', 'Candidates:', ...candidateLines(found.candidates, registry, preferZh)].join('\n');
213
221
  return { system, user };
214
222
  }
215
223
  /** Pull the JSON object out of a model reply (it may wrap it in a code fence). */
@@ -226,22 +234,22 @@ export function parsePickReply(text, allowed, max = 5) {
226
234
  }
227
235
  if (value === null) {
228
236
  // 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)];
237
+ // identifies its picks: keep every complete candidate ID in order.
238
+ const found = [...text.matchAll(/"id"\s*:\s*"(p\d+)"(?:\s*,\s*"why"\s*:\s*"((?:[^"\\]|\\.)*)")?/gu)];
231
239
  if (found.length === 0)
232
240
  throw new Error('the model did not return JSON');
233
241
  const intro = /"intro"\s*:\s*"((?:[^"\\]|\\.)*)"/u.exec(text)?.[1] ?? '';
234
- value = { intro, picks: found.map(match => ({ name: match[1], why: match[2] ?? '' })) };
242
+ value = { intro, picks: found.map(match => ({ id: match[1], why: match[2] ?? '' })) };
235
243
  }
236
244
  const picks = [];
237
245
  const seen = new Set();
238
246
  if (Array.isArray(value.picks)) {
239
247
  for (const item of value.picks) {
240
- const name = typeof item?.name === 'string' ? item.name.trim() : '';
241
- if (!allowed.has(name) || seen.has(name))
248
+ const id = typeof item?.id === 'string' ? item.id.trim() : '';
249
+ if (!allowed.has(id) || seen.has(id))
242
250
  continue;
243
- seen.add(name);
244
- picks.push({ name, why: typeof item?.why === 'string' ? item.why.trim().slice(0, 300) : '' });
251
+ seen.add(id);
252
+ picks.push({ id, why: typeof item?.why === 'string' ? item.why.trim().slice(0, 300) : '' });
245
253
  if (picks.length === max)
246
254
  break;
247
255
  }
@@ -270,7 +278,7 @@ function toPick(plugin, registry, preferZh, why) {
270
278
  };
271
279
  }
272
280
  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. */
281
+ /** One model call over the candidates; resolve picks only to the entries offered. */
274
282
  async function askForPicks(options) {
275
283
  const { selection, prompt } = options;
276
284
  let text = '';
@@ -280,11 +288,7 @@ async function askForPicks(options) {
280
288
  const stream = options.llm.stream({
281
289
  provider: selection.provider,
282
290
  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' }),
291
+ // Leave sampling and reasoning at the selected model's DSH defaults.
288
292
  system: prompt.system,
289
293
  messages: [Object.freeze({
290
294
  id: randomUUID(), role: 'user',
@@ -292,7 +296,6 @@ async function askForPicks(options) {
292
296
  source: { kind: 'plugin:dsh-crate' },
293
297
  })],
294
298
  maxTokens: options.maxTokens,
295
- temperature: options.temperature,
296
299
  ...(options.signal === undefined ? {} : { signal: options.signal }),
297
300
  });
298
301
  for await (const chunk of stream) {
@@ -324,9 +327,10 @@ async function askForPicks(options) {
324
327
  const reason = error instanceof Error ? error.message : String(error);
325
328
  throw new FindPluginError('model-failed', `模型这次没有回答(${reason})。请稍后重试,或换一个模型。 / The model did not answer (${reason}). Try again, or switch models.`);
326
329
  }
330
+ const byId = new Map(options.candidates.map(({ plugin }, index) => [candidateId(index), plugin]));
327
331
  let parsed;
328
332
  try {
329
- const allowed = new Set(options.candidates.map(item => item.plugin.name));
333
+ const allowed = new Set(byId.keys());
330
334
  // Out of budget before the answer: the thinking often already holds it.
331
335
  parsed = text.trim() === '' && reasoning !== '' ? parsePickReply(reasoning, allowed, options.max) : parsePickReply(text, allowed, options.max);
332
336
  }
@@ -334,8 +338,7 @@ async function askForPicks(options) {
334
338
  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
339
  throw new FindPluginError('model-failed', '模型的回答格式不对,没法整理成结果。请重试一次。 / The model\'s answer was not in the expected shape. Try again.');
336
340
  }
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 })) };
341
+ return { intro: parsed.intro, picks: parsed.picks.map(({ id, why }) => ({ plugin: byId.get(id), why })) };
339
342
  }
340
343
  /** Recall, then let the model pick. Throws FindPluginError with a user-facing message. */
341
344
  export async function findPlugins(options) {
@@ -349,11 +352,11 @@ export async function findPlugins(options) {
349
352
  const found = recall(registry, extractTerms(request), CANDIDATE_LIMIT, new Set((have?.installed ?? []).map(plugin => plugin.name)));
350
353
  const answer = await askForPicks({
351
354
  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 }),
355
+ max: 5, maxTokens: 6000, ...(options.signal === undefined ? {} : { signal: options.signal }),
353
356
  });
354
357
  const preferZh = /\p{Script=Han}/u.test(request);
355
358
  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 };
359
+ return { request, intro: answer.intro, picks, model: selection.model, at: new Date().toISOString(), selectionVersion: 2, personalized: have !== undefined };
357
360
  }
358
361
  // ---------- recommendations from what the user already has ----------
359
362
  /** How many candidates a recommendation offers the model. */
@@ -412,18 +415,18 @@ export function recommendCandidates(registry, seeds, exclude = [], limit = RECOM
412
415
  export function buildRecommendPrompt(registry, seeds, candidates, preferZh) {
413
416
  const system = [
414
417
  '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.`,
418
+ '{"intro": string, "picks": [{"id": string, "why": string}]}',
419
+ `- picks: ${String(RECOMMEND_MAX - 4)} to ${String(RECOMMEND_MAX)} candidates this user is most likely to want next, best first. Use the candidate IDs (e.g. "p1") exactly as listed. Different entries may share a name.`,
417
420
  '- 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
421
  '- 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
422
  '- why: one short sentence. intro: one short sentence on what you read from their plugins.',
420
423
  `- Write intro and why in ${preferZh ? 'Simplified Chinese' : 'English'}.`,
421
424
  ].join('\n');
422
- const list = (plugins) => plugins.length === 0 ? ['(none)'] : plugins.map((plugin, i) => catalogLine(plugin, i, registry, preferZh));
425
+ const list = (plugins) => plugins.length === 0 ? ['(none)'] : plugins.map((plugin, i) => `${i + 1}. ${catalogLine(plugin, registry, preferZh)}`);
423
426
  const user = [
424
427
  'Installed:', ...list(seeds.installed), '',
425
428
  'Favorited (not necessarily installed):', ...list(seeds.favorited), '',
426
- 'Candidates:', ...candidates.map(({ plugin }, i) => catalogLine(plugin, i, registry, preferZh)),
429
+ 'Candidates:', ...candidateLines(candidates, registry, preferZh),
427
430
  ].join('\n');
428
431
  return { system, user };
429
432
  }
@@ -442,10 +445,10 @@ export async function recommendPlugins(options) {
442
445
  candidates = recommendCandidates(registry, [...seeds.installed, ...seeds.favorited]);
443
446
  const answer = await askForPicks({
444
447
  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 }),
448
+ max: RECOMMEND_MAX, maxTokens: 8000, ...(options.signal === undefined ? {} : { signal: options.signal }),
446
449
  });
447
450
  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() };
451
+ return { request: '', intro: answer.intro, picks, model: selection.model, at: new Date().toISOString(), selectionVersion: 2 };
449
452
  }
450
453
  /** Plain text of a result, for hosts that draw the command row as text. */
451
454
  export function resultText(result) {
package/lib/hot.js CHANGED
@@ -507,9 +507,7 @@ export function readMarketState(profileDir) {
507
507
  // this switch is the market's only entry, so "the user turned it off"
508
508
  // must be distinguishable from "nobody has chosen yet" (#846).
509
509
  ...(typeof state.sidebarEntry === 'boolean' ? { sidebarEntry: state.sidebarEntry } : {}),
510
- // Only `false` is a stored answer here: shown is the default, and a
511
- // state file that says anything else reads as "never touched".
512
- ...(state.settingsSection === false ? { settingsSection: false } : {}),
510
+ ...(typeof state.settingsSection === 'boolean' ? { settingsSection: state.settingsSection } : {}),
513
511
  ...(state.pluginsTab === false ? { pluginsTab: false } : {}),
514
512
  buildEnv: buildEnvFromUnknown(state.buildEnv),
515
513
  };
@@ -671,7 +669,7 @@ function writeState(profileDir, state, ownStamps) {
671
669
  ...(typeof sidebarEntry === 'boolean' ? { sidebarEntry } : {}),
672
670
  // Only the OFF is written; `true` means "the default", so re-enabling
673
671
  // clears the field rather than pinning today's default forever (#1015).
674
- ...(settingsSection === false ? { settingsSection: false } : {}),
672
+ ...(typeof settingsSection === 'boolean' ? { settingsSection } : {}),
675
673
  ...(pluginsTab === false ? { pluginsTab: false } : {}),
676
674
  ...(state.region === undefined ? {} : { region: state.region }),
677
675
  ...(state.regionAuto === true ? { regionAuto: true } : {}),
@@ -743,6 +741,24 @@ export function forgetInstalled(profileDir, name) {
743
741
  state.installTimes = trimInstallTimes(map);
744
742
  writeState(profileDir, state, true);
745
743
  }
744
+ /**
745
+ * Forget every hot mount. Called when the market's routes unload.
746
+ *
747
+ * The trees these tables point at hang off the market's own instance, so
748
+ * they go down with it. The tables do not: they are module state, and a
749
+ * module the host did not replace — its file did not change — is still
750
+ * loaded when the next instance starts (src/self-reload.ts). Left as they
751
+ * are, the new instance would believe a plugin is still mounted that its
752
+ * predecessor took down: its shim would never be mounted again, and
753
+ * "switch off" would dispose a handle that is already gone while the plugin,
754
+ * brought back by the host's own composition, kept running.
755
+ */
756
+ export function resetHotState() {
757
+ hotHandles.clear();
758
+ hotTrees.clear();
759
+ hotTreeOf.clear();
760
+ shimNames.clear();
761
+ }
746
762
  /** Package names whose hot-mount trees are still attached and can be removed. */
747
763
  export function listHotMounts() {
748
764
  return [...hotHandles.keys()];
package/lib/http.js CHANGED
@@ -39,6 +39,23 @@ export function setRequestGateSource(source) {
39
39
  requestGateSource = source;
40
40
  return previous;
41
41
  }
42
+ /**
43
+ * The request as `connection.admit` reads it: headers, the socket, and an
44
+ * absolute `url` — what the host's own `webserver/authorize` hands the same
45
+ * check (the incoming request's `url` is only a path).
46
+ */
47
+ export function admissionFacts(request) {
48
+ const host = request.headers.host ?? 'localhost';
49
+ const scheme = request.socket?.encrypted === true ? 'https' : 'http';
50
+ let url;
51
+ try {
52
+ url = new URL(request.url ?? '/', `${scheme}://${host}`).href;
53
+ }
54
+ catch {
55
+ url = `${scheme}://localhost/`;
56
+ }
57
+ return { method: request.method ?? 'GET', headers: request.headers, socket: request.socket, url };
58
+ }
42
59
  /**
43
60
  * Answer the request with the host's rejection, if it has one.
44
61
  * @returns true when the request was refused and answered here.
@@ -61,7 +78,9 @@ export function refuseUnadmitted(request, response) {
61
78
  sendJson(response, status, {
62
79
  error: status === 401
63
80
  ? '需要先登录 DSH:请重新打开 dsh web 启动时打印的那个网址。 / DSH login required: reopen the URL dsh web printed at startup.'
64
- : '这个请求来自不受信任的地址,已拒绝。 / This request came from an untrusted origin and was refused.',
81
+ : status === 503
82
+ ? 'DSH 的登录检查暂时出错,请稍后重试。 / DSH\'s login check failed for now. Try again in a moment.'
83
+ : '这个请求来自不受信任的地址,已拒绝。 / This request came from an untrusted origin and was refused.',
65
84
  });
66
85
  return true;
67
86
  }
package/lib/index.js CHANGED
@@ -7,7 +7,7 @@ import { dirname, isAbsolute } from 'node:path';
7
7
  import { createDesktopPluginRuntime, setHostPackageManager } from './dsh-cli.js';
8
8
  import { createOfficialDesktopRuntime } from './official-desktop.js';
9
9
  import { isDshProfileName, profileDir } from './profile.js';
10
- import { setRequestGateSource, setTrustedHostsSource } from './http.js';
10
+ import { admissionFacts, setRequestGateSource, setTrustedHostsSource } from './http.js';
11
11
  import { setLauncherInstallAnchorSource } from './dsh-install.js';
12
12
  import { mountMarketRoutes } from './routes.js';
13
13
  import { installDesktopMarketSettings, installMarketSettings } from './settings.js';
@@ -196,14 +196,47 @@ export function useTrustedHosts(ctx) {
196
196
  }
197
197
  return hosts;
198
198
  });
199
+ // The gate below calls `connection.admit`, which verifies the browser login
200
+ // through `connection.authentication`. Cordis resolves a service property
201
+ // through the context the service was READ from, not the one that provided
202
+ // it: reading the connection from this plugin's own context — which
203
+ // declares `webServer` and `loader`, never the registry — made `admit`
204
+ // throw `cannot get property "connection.authentication" without inject`.
205
+ // The fence turns any throw into 403, so every route answered 403 for every
206
+ // browser, signed in or not, on every host that replaced `requestRejection`
207
+ // with `admit` (#1299).
208
+ //
209
+ // Declaring the registry is what makes that read legal, and the declared
210
+ // scope is what the call has to be made from. A host that has no registry —
211
+ // every release before `admit` existed — leaves the scope cold, and the
212
+ // source below then reads the connection from here exactly as it always
213
+ // did: `requestRejection` needs no such declaration. A host that has one
214
+ // makes both branches reachable, which is the whole point.
215
+ let gateCtx;
216
+ const gateScope = ctx.inject(['connection', 'connection.authentication'], (loginCtx) => {
217
+ gateCtx = loginCtx;
218
+ return () => { if (gateCtx === loginCtx)
219
+ gateCtx = undefined; };
220
+ });
199
221
  // The same service carries the host's request gate (#603): its fence plus
200
222
  // its browser login, the check its own API runs. Read per request for the
201
223
  // same reason as the authorities above.
202
224
  const previousGate = setRequestGateSource(() => {
203
- const connection = ctx.get('connection');
225
+ const connection = (gateCtx ?? ctx).get('connection');
204
226
  const gate = connection?.requestRejection;
205
- return typeof gate === 'function'
206
- ? (request => gate.call(connection, request))
227
+ if (typeof gate === 'function') {
228
+ return request => gate.call(connection, request);
229
+ }
230
+ // DSH 0.2.3 removed requestRejection for `admit(request)`: the Host/Origin
231
+ // fence, then the registered credential providers, answering `{ peer }` or
232
+ // `{ rejection: status }` (#1289). Without this the gate quietly became a
233
+ // no-op on those hosts.
234
+ const admit = connection?.admit;
235
+ return typeof admit === 'function'
236
+ ? (request => {
237
+ const answer = admit.call(connection, admissionFacts(request));
238
+ return typeof answer?.rejection === 'number' ? answer.rejection : answer === undefined ? 403 : undefined;
239
+ })
207
240
  : undefined;
208
241
  });
209
242
  // The setter returns the PREVIOUS source, not a restore closure — the same
@@ -211,6 +244,11 @@ export function useTrustedHosts(ctx) {
211
244
  return () => {
212
245
  setTrustedHostsSource(previous);
213
246
  setRequestGateSource(previousGate);
247
+ // The scoped fiber holds the only declaration that made the gate readable;
248
+ // keeping it alive after the source is pulled back would leave a dependency
249
+ // on a host that may never provide it.
250
+ void Promise.resolve(gateScope.dispose()).catch(() => { });
251
+ gateCtx = undefined;
214
252
  };
215
253
  }
216
254
  /**
package/lib/profile.js CHANGED
@@ -780,6 +780,28 @@ export function readLockCommits(profile, explicitDir) {
780
780
  catch { /* no lockfile — no git installs to report */ }
781
781
  return commits;
782
782
  }
783
+ /**
784
+ * The repository key and commit an archive tarball URL names, or null for a
785
+ * URL none of the supported hosts serves.
786
+ *
787
+ * The same shapes `readLockCommits` scans for, applied to one URL: a
788
+ * `resolution:` block records the archive it fetched, and that URL is the
789
+ * only place the commit appears in it.
790
+ */
791
+ function archiveIdentityOf(url) {
792
+ for (const shape of ARCHIVE_COMMIT_SHAPES) {
793
+ // These patterns are global for `matchAll` above; `exec` advances
794
+ // `lastIndex`, so both ends are reset rather than shared.
795
+ shape.lastIndex = 0;
796
+ const m = shape.exec(url);
797
+ shape.lastIndex = 0;
798
+ if (m === null)
799
+ continue;
800
+ const host = m[1].toLowerCase() === 'codeload.github.com' ? 'github.com' : m[1].toLowerCase();
801
+ return { key: `${host}/${archivePath(m[2]).toLowerCase()}`, commit: m[3].toLowerCase() };
802
+ }
803
+ return null;
804
+ }
783
805
  /**
784
806
  * Commit recorded for a non-codeload git resolution (`type: git` in pnpm's
785
807
  * lockfile). Matched against the install spec so a Gitea/GitLab URL can
@@ -790,6 +812,16 @@ export function readLockCommits(profile, explicitDir) {
790
812
  * when the spec names no subpath while several entries of that remote do,
791
813
  * there is no answer rather than the first sibling's commit (#632).
792
814
  *
815
+ * A `type: git` block is not the only shape: every host the market supports
816
+ * resolves its install to an archive of that host, whose resolution carries
817
+ * `gitHosted: true`, the commit inside `tarball:` and the subpackage in
818
+ * `path:` — no `commit:` and no `repo:` (#632, #637). Reading only the git
819
+ * block left a monorepo subpackage with no identity of its own, so callers
820
+ * fell back to `readLockCommits`, which keeps one slot per repository: with
821
+ * any sibling still on an older commit, that sibling answered for every
822
+ * subpackage, and an update that really happened was reported as STALE
823
+ * (#1296).
824
+ *
793
825
  * The key on both sides of the comparison is `hostedRepoKey`, the identity
794
826
  * the rest of the market already compares specs by (#851). This function
795
827
  * used to derive its own, and that second spelling lost every install pnpm
@@ -813,17 +845,34 @@ export function readGitResolutionCommit(profile, spec, explicitDir) {
813
845
  const body = m[1];
814
846
  const commit = /\bcommit:\s*([0-9a-f]{40})\b/i.exec(body);
815
847
  const repo = /\brepo:\s*([^\s,}]+)/.exec(body);
816
- if (commit === null || repo === null)
817
- continue;
818
- if (hostedRepoKey(repo[1]) !== want)
848
+ let recorded = null;
849
+ let fromArchive = false;
850
+ if (commit !== null && repo !== null) {
851
+ if (hostedRepoKey(repo[1]) === want)
852
+ recorded = commit[1].toLowerCase();
853
+ }
854
+ else {
855
+ const archive = archiveIdentityOf(/\btarball:\s*([^,}]+)/.exec(body)?.[1].trim() ?? '');
856
+ if (archive !== null && archive.key === want) {
857
+ recorded = archive.commit;
858
+ fromArchive = true;
859
+ }
860
+ }
861
+ if (recorded === null)
819
862
  continue;
820
- const entryPath = /\bpath:\s*([^\s,}]+)/.exec(body)?.[1]?.replace(/^\/+|\/+$/g, '').toLowerCase() ?? null;
863
+ const rawPath = /\bpath:\s*([^\s,}]+)/.exec(body)?.[1];
864
+ const entryPath = rawPath === undefined ? null : rawPath.replace(/^\/+|\/+$/g, '').toLowerCase() || null;
821
865
  if (wantPath !== null) {
822
866
  if (entryPath === wantPath)
823
- return commit[1].toLowerCase();
867
+ return recorded;
824
868
  continue;
825
869
  }
826
- matches.push(commit[1].toLowerCase());
870
+ // An archive entry is one subpackage, named by its `path:`. A spec that
871
+ // names no subpath is that repository's root, not the sibling pnpm
872
+ // happened to list last.
873
+ if (fromArchive && entryPath !== null)
874
+ continue;
875
+ matches.push(recorded);
827
876
  }
828
877
  }
829
878
  catch { /* no lockfile */ }