dshmarket 1.73.12 → 1.73.13

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/client/client.js CHANGED
@@ -683,6 +683,7 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
683
683
  restoreDone: "恢复完成,请重启 DeepSeek Harness",
684
684
  restorePartial: "恢复已完成,但下列插件安装失败:",
685
685
  restoreUnportable: "安装来源是另一台电脑上的本地路径,本机找不到。请重新安装该插件,或改为本机路径",
686
+ restoreSelfPinned: "市场自身的版本不会随恢复改变(否则会在恢复途中替换掉正在运行的自己)。需要时请用「更新」单独升级",
686
687
  restoreBootError: "恢复后仍无法启动:",
687
688
  orphanBundle: "⚠️ 下次启动会失败:profile 声明了这些插件,但它们没有安装。请重新安装,或从 profile 的 package.json 的 dsh.profile.bundles 中删除:",
688
689
  restoreConfirm: "恢复将覆盖当前 profile 配置并重新安装插件,确定继续吗?",
@@ -1470,6 +1471,7 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
1470
1471
  restoreDone: "Restore complete — restart DeepSeek Harness",
1471
1472
  restorePartial: "Restore completed, but these plugins failed to install:",
1472
1473
  restoreUnportable: "installs from a path on another computer that does not exist here — reinstall or point it to a local path",
1474
+ restoreSelfPinned: "the market keeps its own version during a restore — swapping it mid-restore would replace the running market. Update it separately when you want the newer one",
1473
1475
  restoreBootError: "Still cannot boot after the restore:",
1474
1476
  orphanBundle: "⚠️ The next start will fail: the profile declares these plugins but they are not installed. Reinstall them, or remove them from dsh.profile.bundles in the profile package.json:",
1475
1477
  restoreConfirm: "Restore will overwrite this profile configuration and reinstall plugins. Continue?",
@@ -2256,6 +2258,7 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
2256
2258
  restoreDone: "復元が完了しました。DeepSeek Harness を再起動してください",
2257
2259
  restorePartial: "復元は完了しましたが、次のプラグインのインストールに失敗しました:",
2258
2260
  restoreUnportable: "インストール元が別のコンピュータ上のローカルパスで、ここには存在しません。そのプラグインを再インストールするか、このマシンのパスを指すようにしてください",
2261
+ restoreSelfPinned: "市場自身のバージョンは復元では変わりません(復元中に実行中の市場を置き換えてしまうため)。必要なときは「更新」で個別にアップグレードしてください",
2259
2262
  restoreBootError: "復元してもまだ起動できません:",
2260
2263
  orphanBundle: "⚠️ 次回の起動に失敗します。profile はこれらのプラグインを宣言していますが、インストールされていません。再インストールするか、profile の package.json の dsh.profile.bundles から削除してください:",
2261
2264
  restoreConfirm: "復元すると現在の profile の設定が上書きされ、プラグインが再インストールされます。続けますか?",
@@ -9929,7 +9932,59 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
9929
9932
  * Only preceding siblings on the path from this panel up to the scroller —
9930
9933
  * the host chrome sits above us. Walking the whole scroller would crawl the
9931
9934
  * catalog on every frame.
9935
+ *
9936
+ * dsh 0.2.2 keeps the plugin-page header's layout box at its resting height
9937
+ * and paints only the compact slice: an absolutely positioned ::before of
9938
+ * `--plugin-header-paint-height`, with the title clipped away. The border box
9939
+ * still reports the resting height, so sticking under `rect.bottom` parks
9940
+ * the market's own rows in that clipped gap and the catalog scrolls through
9941
+ * them. The cover is that ::before only when it is the opaque bar: shorter
9942
+ * than the box, flush to the top and both sides, and filled. A marker or a
9943
+ * strip hung from the bottom keeps the border box. Hosts without one keep
9944
+ * the border box.
9945
+ */
9946
+ /**
9947
+ * Bottom of a stuck bar's opaque ::before, in the same coordinate space as
9948
+ * `rect`, or null when that pseudo-element is not the cover.
9949
+ *
9950
+ * The 0.2.2 page bar's cover is `inset: 0 0 auto` with the page background,
9951
+ * so it starts at the padding edge (no border, no padding-top on that bar)
9952
+ * and is shorter than the resting box. A marker, a hairline, or a strip
9953
+ * anchored with `bottom` does not qualify — those keep the border box.
9954
+ */
9955
+ function paintedCoverBottom(node, rect) {
9956
+ const before = getComputedStyle(node, "::before");
9957
+ if (before.content === "none" || before.content === "normal") return null;
9958
+ if (before.position !== "absolute" && before.position !== "fixed") return null;
9959
+ const height = Number.parseFloat(before.height);
9960
+ if (!Number.isFinite(height) || height <= 0 || height >= rect.height - 1) return null;
9961
+ const top = Number.parseFloat(before.top);
9962
+ const left = Number.parseFloat(before.left);
9963
+ const right = Number.parseFloat(before.right);
9964
+ if (!Number.isFinite(top) || Math.abs(top) > 1) return null;
9965
+ if (!Number.isFinite(left) || !Number.isFinite(right) || Math.abs(left) > 1 || Math.abs(right) > 1) return null;
9966
+ if (before.backgroundColor === "transparent" || before.backgroundColor === "rgba(0, 0, 0, 0)") return null;
9967
+ const borderTop = Number.parseFloat(getComputedStyle(node).borderTopWidth);
9968
+ const border = Number.isFinite(borderTop) ? borderTop : 0;
9969
+ return rect.top + border + top + height;
9970
+ }
9971
+ /**
9972
+ * Painted height of a stuck bar that keeps its layout box and clips the rest.
9973
+ *
9974
+ * dsh 0.2.2's plugin page writes the drawn height onto the bar every frame as
9975
+ * an inline `--plugin-header-paint-height` and clips the box with it, so the
9976
+ * border box keeps reporting the resting height the bar no longer occupies.
9977
+ * Sticking under that number left a bare strip above the market's tab row
9978
+ * with cards scrolling through it (#1125). Read the drawn number when the
9979
+ * host publishes one; null means the border box is the honest one.
9932
9980
  */
9981
+ function paintedBarHeight(node, rect) {
9982
+ const inline = node.style?.getPropertyValue("--plugin-header-paint-height");
9983
+ if (inline === void 0 || inline.trim() === "") return null;
9984
+ const value = Number.parseFloat(inline);
9985
+ if (!Number.isFinite(value)) return null;
9986
+ return Math.max(0, Math.min(rect.height, value));
9987
+ }
9933
9988
  function hostStickyOffset(scroller, market) {
9934
9989
  const scrollerTop = scroller.getBoundingClientRect().top;
9935
9990
  let bottom = scrollerTop;
@@ -9937,7 +9992,13 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
9937
9992
  const position = getComputedStyle(node).position;
9938
9993
  if (position !== "sticky" && position !== "fixed") return;
9939
9994
  const rect = node.getBoundingClientRect();
9940
- if (rect.height > 0 && rect.top <= scrollerTop + 4 && rect.bottom > scrollerTop) bottom = Math.max(bottom, rect.bottom);
9995
+ if (rect.height <= 0 || rect.top > scrollerTop + 4 || rect.bottom <= scrollerTop) return;
9996
+ const painted = paintedBarHeight(node, rect);
9997
+ if (painted !== null) {
9998
+ bottom = Math.max(bottom, rect.top + painted);
9999
+ return;
10000
+ }
10001
+ bottom = Math.max(bottom, paintedCoverBottom(node, rect) ?? rect.bottom);
9941
10002
  };
9942
10003
  const walkPreceding = (node) => {
9943
10004
  consider(node);
@@ -13395,10 +13456,12 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
13395
13456
  const finishRestore = (0, react.useCallback)((body) => {
13396
13457
  const errors = Array.isArray(body.errors) ? body.errors : [];
13397
13458
  const unportable = Array.isArray(body.unportable) ? body.unportable : [];
13459
+ const pinned = Array.isArray(body.pinned) ? body.pinned : [];
13398
13460
  const bootErrors = Array.isArray(body.bootErrors) ? body.bootErrors.map(String) : [];
13399
13461
  setRestoreErrors([
13400
13462
  ...errors.map((item) => `${String(item.name)}: ${String(item.error)}`),
13401
13463
  ...unportable.map((item) => `${String(item.name)}: ${t("restoreUnportable")} (${String(item.spec)})`),
13464
+ ...pinned.map((item) => `${String(item.name)}: ${t("restoreSelfPinned")} (${String(item.from)} → ${String(item.to)})`),
13402
13465
  ...bootErrors.map((line) => `${t("restoreBootError")} ${line}`)
13403
13466
  ]);
13404
13467
  setBackupRestored(true);
@@ -18319,13 +18382,11 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
18319
18382
  /**
18320
18383
  * The market's block mark in the settings navigation.
18321
18384
  *
18322
- * The settings shell picks nav glyphs from a closed list of section ids
18323
- * (`models`, `agent-presets`, `plugins`) and falls back to its own gear for
18324
- * every other id; `settings.section` projects only `id` / `order` / `label`,
18325
- * so a registrant has no icon to pass — the slot contract in
18326
- * `@deepseek-ai/dsh-client-ui-settings` and the runtime slot inventory both
18327
- * list exactly those three options. Every third-party section therefore wears
18328
- * the gear, the market included.
18385
+ * Hosts before dsh 0.2.2 pick nav glyphs from a closed list of section ids
18386
+ * (`models`, `agent-presets`, `plugins`) and fall back to the gear for every
18387
+ * other id. `settings.section` on those hosts projects only `id` / `order` /
18388
+ * `label`, so a registrant has no icon to pass. Every third-party section
18389
+ * therefore wears the gear, the market included.
18329
18390
  *
18330
18391
  * So the market claims its own row once the dialog is mounted and swaps the
18331
18392
  * fallback gear for the block mark — the same mark `MarketLogo` draws inside
@@ -18342,8 +18403,10 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
18342
18403
  * - a locale switch re-claims the row through the MutationObserver, so the
18343
18404
  * label and the glyph never disagree.
18344
18405
  *
18345
- * Delete this module (and its call in index.ts) the day `settings.section`
18346
- * grows an `icon` field.
18406
+ * dsh 0.2.2 grew a real icon seat (`settings.section.icon`) and wrapped the
18407
+ * fallback gear, so this stand-in no longer lines up with that shell — the
18408
+ * caller keeps it only for hosts that never declare the seat. Delete this
18409
+ * module once those hosts are gone.
18347
18410
  */
18348
18411
  /** Marks the one nav row this plugin owns. */
18349
18412
  const NAV_ICON_MARKER = "data-dsh-market-nav-icon";
@@ -18411,9 +18474,14 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
18411
18474
  * @param resolveLabel - this plugin's current section label (the same thunk
18412
18475
  * the `settings.section` registration passes), re-read on every sync so a
18413
18476
  * locale switch is picked up without re-registering.
18477
+ * @returns a stopper. Calling it removes the marker and the stylesheet; the
18478
+ * fiber's own disposal does the same, and either one is safe to repeat.
18479
+ * The caller uses it when a host that looked old turns out to paint icons
18480
+ * itself.
18414
18481
  */
18415
18482
  function installSettingsNavIcon(ctx, resolveLabel) {
18416
- if (typeof document === "undefined") return;
18483
+ if (typeof document === "undefined") return () => {};
18484
+ let dispose = () => {};
18417
18485
  ctx.effect(() => {
18418
18486
  const tag = document.createElement("style");
18419
18487
  tag.dataset.plugin = "dshmarket";
@@ -18441,13 +18509,19 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
18441
18509
  subtree: true,
18442
18510
  characterData: true
18443
18511
  });
18444
- return () => {
18512
+ const cleanup = () => {
18513
+ if (disposed) return;
18445
18514
  disposed = true;
18446
18515
  observer.disconnect();
18447
18516
  for (const row of document.querySelectorAll(`[${NAV_ICON_MARKER}]`)) row.removeAttribute(NAV_ICON_MARKER);
18448
18517
  tag.remove();
18449
18518
  };
18519
+ dispose = cleanup;
18520
+ return cleanup;
18450
18521
  }, "dsh-market: settings nav icon");
18522
+ return () => {
18523
+ dispose();
18524
+ };
18451
18525
  }
18452
18526
  //#endregion
18453
18527
  //#region src/client/host-navigation.ts
@@ -18647,7 +18721,19 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
18647
18721
  ja
18648
18722
  }), "dsh-market: dictionaries");
18649
18723
  const t = ctx.locale.bind(NS);
18650
- installSettingsNavIcon(ctx, () => t("nav"));
18724
+ let stopNavStandIn;
18725
+ let hostPaintsNavIcon = false;
18726
+ ctx.slots.inject("settings.section.icon", () => {
18727
+ hostPaintsNavIcon = true;
18728
+ stopNavStandIn?.();
18729
+ stopNavStandIn = void 0;
18730
+ const off = ctx.slots.register({
18731
+ name: "settings.section.icon",
18732
+ id: "market"
18733
+ }, (owner = {}) => (0, react.createElement)(MarketLogo, { size: owner.size ?? 16 }));
18734
+ return typeof off === "function" ? off : () => {};
18735
+ });
18736
+ if (!hostPaintsNavIcon) stopNavStandIn = installSettingsNavIcon(ctx, () => t("nav"));
18651
18737
  let sidebar;
18652
18738
  /**
18653
18739
  * The host's `pluginNavigation` (dsh 0.2.1+), published as a store so the
package/lib/backup.js CHANGED
@@ -652,3 +652,37 @@ export function mergeRestoreManifest(backupManifest, current, selection) {
652
652
  merged.dsh = dshMerged;
653
653
  return merged;
654
654
  }
655
+ /**
656
+ * Dependencies a restore must leave at the spec the target already has — the
657
+ * market itself, while it is the package running the restore.
658
+ *
659
+ * A restore applies the backup's manifest through `pnpm install`, which
660
+ * rewrites whatever that manifest pins. When the backup was written by a
661
+ * different market version, that install replaces THIS package's files under
662
+ * the live module: the mixed state the update route refuses (#608), made
663
+ * worse here because the code answering the restore request is the code being
664
+ * swapped out. The running spec therefore wins, and the backup's spec is
665
+ * returned so the caller can report it — the update flow can apply it later,
666
+ * with its restart and rollback machinery.
667
+ *
668
+ * Only string specs take part: anything else is not a pin this can compare.
669
+ */
670
+ export function pinRunningDeps(merged, current, names) {
671
+ const mergedDeps = merged.dependencies === null || typeof merged.dependencies !== 'object' || Array.isArray(merged.dependencies)
672
+ ? {}
673
+ : merged.dependencies;
674
+ const currentDeps = current.dependencies === null || typeof current.dependencies !== 'object' || Array.isArray(current.dependencies)
675
+ ? {}
676
+ : current.dependencies;
677
+ const dependencies = { ...mergedDeps };
678
+ const pinned = [];
679
+ for (const name of names) {
680
+ const wanted = mergedDeps[name];
681
+ const running = currentDeps[name];
682
+ if (typeof wanted !== 'string' || typeof running !== 'string' || wanted === running)
683
+ continue;
684
+ dependencies[name] = running;
685
+ pinned.push({ name, from: wanted, to: running });
686
+ }
687
+ return { dependencies, pinned };
688
+ }
@@ -23,6 +23,35 @@ import { fetchBodyWhileProgressing } from './body-progress.js';
23
23
  import { marketFetch } from './net.js';
24
24
  /** Long enough for a multi-megabyte tarball on a slow link, short enough to fall back. */
25
25
  const TIMEOUT_MS = 20_000;
26
+ /**
27
+ * `dist.tarball` as an absolute URL.
28
+ *
29
+ * A registry behind a path prefix — Nexus, Verdaccio, a reverse proxy — may
30
+ * answer that field as a relative path (`/dsh-plugin-catalog/-/…`). pnpm
31
+ * resolves it against the registry; passing it straight to `fetch` threw
32
+ * "Failed to parse URL" instead, the npm source dropped out of the list, and
33
+ * the market read the catalog from somewhere else without saying so (#1117).
34
+ *
35
+ * Relative resolution follows the URL rules: a value starting with `/` is
36
+ * root-relative and a bare path is relative to the registry's own directory,
37
+ * which is where the registry serves it from. Nothing is rewritten when the
38
+ * field is already absolute.
39
+ */
40
+ export function absoluteTarballUrl(tarball, registry) {
41
+ try {
42
+ return new URL(tarball).href;
43
+ }
44
+ catch {
45
+ // Not absolute — resolve below, and keep the raw value if even that fails
46
+ // so the error still names what the registry answered.
47
+ }
48
+ try {
49
+ return new URL(tarball, `${registry.replace(/\/+$/u, '')}/`).href;
50
+ }
51
+ catch {
52
+ return tarball;
53
+ }
54
+ }
26
55
  /**
27
56
  * A tar entry header, as far as this needs to read one.
28
57
  *
@@ -109,7 +138,7 @@ file = 'package/plugins.json') {
109
138
  // the ceiling while bytes were still arriving, and the catalog fell through
110
139
  // to a source that took longer still. TIMEOUT_MS still bounds the wait for
111
140
  // the response to start, the one thing a fixed timer is good at.
112
- const bytes = fileFromTarball(Buffer.from(await fetchBodyWhileProgressing(marketFetch, tarball, `${pkg} tarball`)), file);
141
+ const bytes = fileFromTarball(Buffer.from(await fetchBodyWhileProgressing(marketFetch, absoluteTarballUrl(tarball, registry), `${pkg} tarball`)), file);
113
142
  if (bytes === null)
114
143
  throw new Error(`${pkg}@${version} carries no ${file}`);
115
144
  return { version, data: JSON.parse(bytes.toString('utf8')) };
@@ -140,7 +169,7 @@ export async function packageFileFromRegistry(registry, pkg, file) {
140
169
  const tarball = typeof meta.dist?.tarball === 'string' ? meta.dist.tarball : null;
141
170
  if (tarball === null)
142
171
  return null;
143
- const tarRes = await marketFetch(tarball, { signal: AbortSignal.timeout(TIMEOUT_MS) });
172
+ const tarRes = await marketFetch(absoluteTarballUrl(tarball, registry), { signal: AbortSignal.timeout(TIMEOUT_MS) });
144
173
  if (!tarRes.ok)
145
174
  return null;
146
175
  return fileFromTarball(Buffer.from(await tarRes.arrayBuffer()), file);
package/lib/dsh-cli.js CHANGED
@@ -13,6 +13,7 @@ import { dirname, isAbsolute, join, resolve } from 'node:path';
13
13
  import { logEvent } from './log.js';
14
14
  import { createProgressTracker } from './ndjson.js';
15
15
  import { pluginArgsFor } from './pnpm-compat.js';
16
+ import { createOutputBuffer } from './proc-text.js';
16
17
  import { isDshProfileName, profileDir } from './profile.js';
17
18
  import { activeRegion, DEFAULT_NPM_REGISTRY, routesFor } from './regions.js';
18
19
  import { NPM_NAME_RE } from './sources.js';
@@ -710,8 +711,8 @@ function probeHostPackageManager() {
710
711
  const child = spawnShim(invocation.command, [...invocation.args, '--version'], {
711
712
  stdio: ['ignore', 'pipe', 'pipe'], viaShell: winCmdShim, env: spawnEnv(),
712
713
  });
713
- let output = '';
714
- const collect = (chunk) => { output = (output + chunk.toString()).slice(-2000); };
714
+ const output = createOutputBuffer(2000);
715
+ const collect = (chunk) => { output.push(chunk); };
715
716
  child.stdout?.on('data', collect);
716
717
  child.stderr?.on('data', collect);
717
718
  child.on('error', (error) => {
@@ -720,7 +721,7 @@ function probeHostPackageManager() {
720
721
  });
721
722
  child.on('close', (code) => {
722
723
  hostPnpmReady = code === 0;
723
- hostProbeFailure = hostPnpmReady ? null : { command: invocation.command, output: output.trim() };
724
+ hostProbeFailure = hostPnpmReady ? null : { command: invocation.command, output: output.text().trim() };
724
725
  resolvePromise(hostPnpmReady);
725
726
  });
726
727
  });
@@ -753,8 +754,8 @@ function probePnpmOnPath() {
753
754
  // IS the explanation, and throwing it away is what left #228 with a
754
755
  // failure nobody could act on.
755
756
  const child = spawnShim('pnpm', ['--version'], { stdio: ['ignore', 'pipe', 'pipe'], viaShell: winCmdShim, env: spawnEnv() });
756
- let output = '';
757
- const collect = (chunk) => { output = (output + chunk.toString()).slice(-2000); };
757
+ const output = createOutputBuffer(2000);
758
+ const collect = (chunk) => { output.push(chunk); };
758
759
  child.stdout?.on('data', collect);
759
760
  child.stderr?.on('data', collect);
760
761
  child.on('error', (error) => {
@@ -763,7 +764,7 @@ function probePnpmOnPath() {
763
764
  });
764
765
  child.on('close', (code) => {
765
766
  pnpmReady = code === 0;
766
- pnpmProbeFailure = pnpmReady ? null : { kind: 'failed', output: output.trim() };
767
+ pnpmProbeFailure = pnpmReady ? null : { kind: 'failed', output: output.text().trim() };
767
768
  resolvePromise(pnpmReady);
768
769
  });
769
770
  });
@@ -775,13 +776,13 @@ function runQuiet(file, args, timeoutMs) {
775
776
  stdio: ['ignore', 'pipe', 'pipe'],
776
777
  viaShell: winCmdShim,
777
778
  });
778
- let output = '';
779
+ const output = createOutputBuffer(8 * 1024);
779
780
  const timer = setTimeout(() => killChild(child), timeoutMs);
780
- const collect = (chunk) => { output = (output + chunk.toString()).slice(-8 * 1024); };
781
+ const collect = (chunk) => { output.push(chunk); };
781
782
  child.stdout?.on('data', collect);
782
783
  child.stderr?.on('data', collect);
783
784
  child.on('error', (error) => { clearTimeout(timer); resolvePromise({ code: 127, output: error.message }); });
784
- child.on('close', (code) => { clearTimeout(timer); resolvePromise({ code, output }); });
785
+ child.on('close', (code) => { clearTimeout(timer); resolvePromise({ code, output: output.text() }); });
785
786
  });
786
787
  }
787
788
  /**
@@ -1055,23 +1056,21 @@ export function runHostPnpm(invocation, cwd, args) {
1055
1056
  });
1056
1057
  activeChild = child;
1057
1058
  cancelRequested = false;
1058
- let stdout = '';
1059
- let stderr = '';
1059
+ const stdoutBytes = createOutputBuffer(256 * 1024);
1060
+ const stderrBytes = createOutputBuffer(64 * 1024);
1060
1061
  let timedOut = false;
1061
1062
  const timer = setTimeout(() => {
1062
1063
  timedOut = true;
1063
1064
  killTree(child);
1064
1065
  }, INSTALL_TIMEOUT_MS);
1065
1066
  child.stdout?.on('data', (chunk) => {
1066
- const text = chunk.toString();
1067
- stdout = (stdout + text).slice(-256 * 1024);
1068
- feed(text);
1067
+ stdoutBytes.push(chunk);
1068
+ feed(chunk.toString());
1069
1069
  syncProgress(tracker);
1070
1070
  });
1071
1071
  child.stderr?.on('data', (chunk) => {
1072
- const text = chunk.toString();
1073
- stderr = (stderr + text).slice(-64 * 1024);
1074
- feed(text);
1072
+ stderrBytes.push(chunk);
1073
+ feed(chunk.toString());
1075
1074
  syncProgress(tracker);
1076
1075
  });
1077
1076
  child.on('error', (error) => {
@@ -1080,7 +1079,7 @@ export function runHostPnpm(invocation, cwd, args) {
1080
1079
  progress.cancelling = false;
1081
1080
  if (activeChild === child)
1082
1081
  activeChild = null;
1083
- resolvePromise({ exitCode: 127, timedOut: false, stdout, stderr: `${stderr}\n${error.message}`.trim(), cancelled: false });
1082
+ resolvePromise({ exitCode: 127, timedOut: false, stdout: stdoutBytes.text(), stderr: `${stderrBytes.text()}\n${error.message}`.trim(), cancelled: false });
1084
1083
  });
1085
1084
  child.on('close', (code) => {
1086
1085
  clearTimeout(timer);
@@ -1091,8 +1090,8 @@ export function runHostPnpm(invocation, cwd, args) {
1091
1090
  resolvePromise({
1092
1091
  exitCode: code,
1093
1092
  timedOut,
1094
- stdout,
1095
- stderr,
1093
+ stdout: stdoutBytes.text(),
1094
+ stderr: stderrBytes.text(),
1096
1095
  cancelled: cancelRequested,
1097
1096
  });
1098
1097
  });
@@ -1129,23 +1128,21 @@ export function runDshPlugin(profile, pluginArgs) {
1129
1128
  });
1130
1129
  activeChild = child;
1131
1130
  cancelRequested = false;
1132
- let stdout = '';
1133
- let stderr = '';
1131
+ const stdoutBytes = createOutputBuffer(256 * 1024);
1132
+ const stderrBytes = createOutputBuffer(64 * 1024);
1134
1133
  let timedOut = false;
1135
1134
  const timer = setTimeout(() => {
1136
1135
  timedOut = true;
1137
1136
  killTree(child);
1138
1137
  }, INSTALL_TIMEOUT_MS);
1139
1138
  child.stdout?.on('data', (chunk) => {
1140
- const text = chunk.toString();
1141
- stdout = (stdout + text).slice(-256 * 1024);
1142
- feed(text);
1139
+ stdoutBytes.push(chunk);
1140
+ feed(chunk.toString());
1143
1141
  syncProgress(tracker);
1144
1142
  });
1145
1143
  child.stderr?.on('data', (chunk) => {
1146
- const text = chunk.toString();
1147
- stderr = (stderr + text).slice(-64 * 1024);
1148
- feed(text);
1144
+ stderrBytes.push(chunk);
1145
+ feed(chunk.toString());
1149
1146
  syncProgress(tracker);
1150
1147
  });
1151
1148
  child.on('error', (error) => {
@@ -1154,7 +1151,7 @@ export function runDshPlugin(profile, pluginArgs) {
1154
1151
  progress.cancelling = false;
1155
1152
  if (activeChild === child)
1156
1153
  activeChild = null;
1157
- resolvePromise({ exitCode: 127, timedOut: false, stdout, stderr: `${stderr}\n${error.message}`, cancelled: false });
1154
+ resolvePromise({ exitCode: 127, timedOut: false, stdout: stdoutBytes.text(), stderr: `${stderrBytes.text()}\n${error.message}`, cancelled: false });
1158
1155
  });
1159
1156
  child.on('close', (code) => {
1160
1157
  clearTimeout(timer);
@@ -1174,8 +1171,8 @@ export function runDshPlugin(profile, pluginArgs) {
1174
1171
  resolvePromise({
1175
1172
  exitCode: code,
1176
1173
  timedOut,
1177
- stdout,
1178
- stderr,
1174
+ stdout: stdoutBytes.text(),
1175
+ stderr: stderrBytes.text(),
1179
1176
  cancelled: cancelRequested,
1180
1177
  ...(pnpmError !== null ? { pnpmError } : {}),
1181
1178
  ...(pnpmErrorCode !== null ? { pnpmErrorCode } : {}),
@@ -1254,19 +1251,17 @@ export function createDesktopPluginRuntime(service, activeProfileDir, invokingDi
1254
1251
  }
1255
1252
  const tracker = beginProgress(prepared.target);
1256
1253
  const feed = makeProgressFeeder(tracker);
1257
- let stdout = '';
1258
- let stderr = '';
1254
+ const stdoutBytes = createOutputBuffer(256 * 1024);
1255
+ const stderrBytes = createOutputBuffer(64 * 1024);
1259
1256
  let timedOut = false;
1260
1257
  const collectStdout = (chunk) => {
1261
- const text = chunk.toString();
1262
- stdout = (stdout + text).slice(-256 * 1024);
1263
- feed(text);
1258
+ stdoutBytes.push(typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk);
1259
+ feed(chunk.toString());
1264
1260
  syncProgress(tracker);
1265
1261
  };
1266
1262
  const collectStderr = (chunk) => {
1267
- const text = chunk.toString();
1268
- stderr = (stderr + text).slice(-64 * 1024);
1269
- feed(text);
1263
+ stderrBytes.push(typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk);
1264
+ feed(chunk.toString());
1270
1265
  syncProgress(tracker);
1271
1266
  };
1272
1267
  handle.stdout.on('data', collectStdout);
@@ -1284,8 +1279,8 @@ export function createDesktopPluginRuntime(service, activeProfileDir, invokingDi
1284
1279
  return {
1285
1280
  exitCode: outcome.exitCode,
1286
1281
  timedOut,
1287
- stdout,
1288
- stderr,
1282
+ stdout: stdoutBytes.text(),
1283
+ stderr: stderrBytes.text(),
1289
1284
  cancelled: active.userCancelled,
1290
1285
  ...(ignoredBuilds.length > 0 ? { ignoredBuilds } : {}),
1291
1286
  ...(pnpmError !== null ? { pnpmError } : {}),
@@ -1296,11 +1291,12 @@ export function createDesktopPluginRuntime(service, activeProfileDir, invokingDi
1296
1291
  catch (error) {
1297
1292
  const message = error instanceof Error ? error.message : String(error);
1298
1293
  progress.error = tracker.snapshot.error;
1299
- const detail = `${stderr}${stderr === '' ? '' : '\n'}${message}`;
1294
+ const stderrText = stderrBytes.text();
1295
+ const detail = `${stderrText}${stderrText === '' ? '' : '\n'}${message}`;
1300
1296
  return {
1301
1297
  exitCode: 127,
1302
1298
  timedOut,
1303
- stdout,
1299
+ stdout: stdoutBytes.text(),
1304
1300
  stderr: boundaryRefusesTarget ? `${detail}\n${NPM_ONLY_HOST_NOTE}` : detail,
1305
1301
  cancelled: active.userCancelled,
1306
1302
  ...(resolvedNpmVersion !== undefined ? { resolvedNpmVersion } : {}),
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Text a child process wrote, decoded by the encoding it actually used.
3
+ *
4
+ * A Windows console gives a child process the console code page, and a
5
+ * Chinese system is 936 (GBK): `cmd.exe` says "不是内部或外部命令" in GBK
6
+ * bytes. The pipe carries bytes and no encoding, so decoding them as UTF-8
7
+ * turned every one of those bytes into U+FFFD — the install error read
8
+ * `'dsh' �����ڲ����ⲿ���Ҳ���ǿ����еij���` (#1122), which tells the person
9
+ * looking at it nothing at all.
10
+ *
11
+ * UTF-8 is tried first and strictly, so text that IS UTF-8 decodes exactly as
12
+ * before; only bytes that cannot be UTF-8 fall through to the code page. No
13
+ * `chcp` probe: that costs a process per install, and the answer is already
14
+ * in the bytes.
15
+ */
16
+ /** Decode a complete child output buffer. */
17
+ export function decodeChildOutput(bytes, platform = process.platform) {
18
+ if (bytes.length === 0)
19
+ return '';
20
+ try {
21
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
22
+ }
23
+ catch {
24
+ // Not UTF-8. Only Windows consoles hand a child a non-UTF-8 code page;
25
+ // elsewhere keep the previous behaviour (replace the bad bytes) rather
26
+ // than invent Chinese out of binary noise.
27
+ if (platform !== 'win32')
28
+ return new TextDecoder('utf-8').decode(bytes);
29
+ try {
30
+ return new TextDecoder('gbk').decode(bytes);
31
+ }
32
+ catch {
33
+ // A Node without the GBK table (small-icu build). Showing the bytes as
34
+ // UTF-8 is still better than showing nothing.
35
+ return new TextDecoder('utf-8').decode(bytes);
36
+ }
37
+ }
38
+ }
39
+ /**
40
+ * The last `limit` bytes of one child stream, decoded when it is asked for.
41
+ *
42
+ * Kept as bytes rather than as a string because the encoding cannot be known
43
+ * from a prefix: the first chunks of a pnpm run are ASCII either way, and
44
+ * decoding each chunk as it arrives fixes the encoding before the text that
45
+ * decides it has been seen.
46
+ */
47
+ export function createOutputBuffer(limit, platform = process.platform) {
48
+ const chunks = [];
49
+ let size = 0;
50
+ return {
51
+ push(chunk) {
52
+ if (chunk.length === 0)
53
+ return;
54
+ chunks.push(chunk);
55
+ size += chunk.length;
56
+ while (size > limit && chunks.length > 1) {
57
+ size -= chunks.shift().length;
58
+ }
59
+ const first = chunks[0];
60
+ if (first !== undefined && size > limit) {
61
+ chunks[0] = first.subarray(size - limit);
62
+ size = limit;
63
+ }
64
+ },
65
+ text() {
66
+ return decodeChildOutput(Buffer.concat(chunks), platform);
67
+ },
68
+ };
69
+ }
package/lib/registry.js CHANGED
@@ -254,6 +254,15 @@ export async function loadRegistry(region = activeRegion()) {
254
254
  });
255
255
  }
256
256
  }
257
+ // Every source here is a fallback for the one before it, so this failure
258
+ // may never reach the screen: the market reads the catalog from the next
259
+ // source and looks fine, while a mirror this person configured and cannot
260
+ // see failing stays broken (#1117). One line per source per load — the
261
+ // full list is still in the thrown message when everything fails.
262
+ const ownFailure = failures.findLast(failure => failure.source === key);
263
+ if (ownFailure !== undefined && sourceIndex + 1 < catalogSources.length) {
264
+ logEvent('warn', 'registry', `catalog: ${key} failed, reading from a later source — ${ownFailure.reason.slice(0, 200)}`);
265
+ }
257
266
  }
258
267
  throw new Error(describeFetchFailure(last, Date.now() - started, attempts, failures));
259
268
  }
@@ -0,0 +1,70 @@
1
+ /** Published GitHub archives stay archive installs; never infer an npm identity. */
2
+ import { marketFetch } from './net.js';
3
+ import { activeRegion, githubRoutesFor, rememberGithubRoute, throughProxy } from './regions.js';
4
+ import { installTargetFor, parseSourceUrl } from './sources.js';
5
+ /** Only the catalog's own floating asset opts an existing archive into updates. */
6
+ export function catalogReleaseSourceOf(spec, entry) {
7
+ if (entry.npm !== null && entry.npm !== undefined)
8
+ return null;
9
+ const source = parseSourceUrl(entry.url);
10
+ if (source === null || typeof entry.tarball !== 'string' || installTargetFor(entry) !== entry.tarball)
11
+ return null;
12
+ try {
13
+ const approved = new URL(entry.tarball);
14
+ const installed = new URL(spec);
15
+ const asset = /^\/[^/]+\/[^/]+\/releases\/latest\/download\/([A-Za-z0-9._-]+\.(?:tgz|tar\.gz))$/.exec(approved.pathname)?.[1];
16
+ if (asset === undefined)
17
+ return null;
18
+ for (const url of [approved, installed]) {
19
+ if (url.protocol !== 'https:' || url.host !== 'github.com' || url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '')
20
+ return null;
21
+ }
22
+ const match = /^\/([^/]+\/[^/]+)\/releases\/(?:latest\/download|download\/[^/]+)\/([^/]+)$/.exec(installed.pathname);
23
+ if (match === null || match[1].toLowerCase() !== source.repo.toLowerCase() || match[2] !== asset)
24
+ return null;
25
+ return { repo: source.repo, asset, manifest: source.subpath === null ? 'package.json' : `${source.subpath}/package.json` };
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ export async function publishedReleaseUpdate(source, name) {
32
+ try {
33
+ const init = { headers: { 'user-agent': 'dsh-market' }, signal: AbortSignal.timeout(10_000) };
34
+ // The ordinary redirect has no REST API quota and cannot advertise an
35
+ // unpublished main-branch version. Keep the published tag in the add target.
36
+ const latest = await marketFetch(`https://github.com/${source.repo}/releases/latest`, { ...init, method: 'HEAD', redirect: 'manual' });
37
+ if (latest.status !== 302 && latest.status !== 301)
38
+ return null;
39
+ const location = new URL(latest.headers.get('location') ?? '', `https://github.com/${source.repo}/releases/latest`);
40
+ const prefix = `/${source.repo}/releases/tag/`;
41
+ if (location.origin !== 'https://github.com' || location.username !== '' || location.password !== '' || location.search !== '' || location.hash !== '' || !location.pathname.toLowerCase().startsWith(prefix.toLowerCase()))
42
+ return null;
43
+ const tag = location.pathname.slice(prefix.length);
44
+ if (!/^v?\d+\.\d+\.\d+$/.test(tag))
45
+ return null;
46
+ const version = tag.replace(/^v/, '');
47
+ const manifestUrl = `https://raw.githubusercontent.com/${source.repo}/${tag}/${source.manifest}`;
48
+ for (const route of githubRoutesFor('raw', activeRegion())) {
49
+ try {
50
+ const response = await marketFetch(throughProxy(route, manifestUrl), { headers: init.headers, signal: AbortSignal.timeout(10_000) });
51
+ if (!response.ok)
52
+ continue;
53
+ const manifest = await response.json();
54
+ if (manifest.name !== name || manifest.version !== version)
55
+ return null;
56
+ rememberGithubRoute('raw', route);
57
+ const target = `https://github.com/${source.repo}/releases/download/${tag}/${source.asset}`;
58
+ const archive = await marketFetch(target, { headers: init.headers, signal: AbortSignal.timeout(10_000), method: 'HEAD', redirect: 'manual' });
59
+ if (archive.status !== 200 && archive.status !== 302 && archive.status !== 301)
60
+ return null;
61
+ return { version, target };
62
+ }
63
+ catch { /* Another configured raw route may answer. */ }
64
+ }
65
+ return null;
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
package/lib/routes.js CHANGED
@@ -20,6 +20,7 @@ import { dshHostInfo, findDshInstallDir } from './dsh-install.js';
20
20
  import { catalogReleaseManifest, deriveHostCompatibility, DiscoveryManifestIndex, findCompatibleVersion } from './discovery-compatibility.js';
21
21
  import { configurePersistentLog, exportLogs, logEvent, readPersistentLog } from './log.js';
22
22
  import { marketFetch } from './net.js';
23
+ import { catalogReleaseSourceOf, publishedReleaseUpdate } from './release-updates.js';
23
24
  import { diagnosePackageManifests } from './diagnostics.js';
24
25
  import { BOOT_ID, cancelActive, probePnpm, progress, provisionPnpm, runDshPlugin, setBuildEnvSource, TARGET_RE, } from './dsh-cli.js';
25
26
  import { packageOfEntryName } from './entry-identity.js';
@@ -52,7 +53,7 @@ import { resolveDshHome } from './home-paths.js';
52
53
  import { detectedDebugger, detectedSupervisor, restartAllowed, scheduleRestart, servingPort, trustedRestartRequest, trustedDownloadRequest, trustedSelfUninstallRequest, selfUninstallReachableFrom, restartReachableFrom } from './restart.js';
53
54
  import { activationAfterReplace, brokenClientBundles, bundlePatchIsEmpty, checkClientBundle, defaultHostRuntimeFacts, findUnservedConfigNamespaces, hasHostHalf, hostPeerGate, isDeclaredLibraryDsh, newlyBrokenBundles, peerGateRemedy, verifyActivation } from './verify.js';
54
55
  import { carrierRowIds, disableRow, enableRow, findUserPatchPath, foreignRowIds, isProtectedModule, loaderEntryId, packagePatchFlags, readUserPatchState, removeRowBlocks, rowIdsForPackage, userPatchPackageReferences, } from './patch.js';
55
- import { createProfileBackup, downloadWebdav, MAX_BACKUP_BYTES, mergeRestoreManifest, restoreProfileBackup, unportableDeps, uploadWebdav, WebdavUrlError, } from './backup.js';
56
+ import { createProfileBackup, downloadWebdav, MAX_BACKUP_BYTES, mergeRestoreManifest, pinRunningDeps, restoreProfileBackup, unportableDeps, uploadWebdav, WebdavUrlError, } from './backup.js';
56
57
  import { createGist, fitsGistLimit, GistError, gistErrorCode, parseGistId, readGist, resolveGistTokenSource, updateGist, verifyGistToken, } from './gist.js';
57
58
  import { MAX_UPDATE_OPERATIONS_V1, UpdateOperationStoreV1, UPDATE_API_V1_SCHEMA } from './update-api-v1.js';
58
59
  import { declaredPredecessors, findCatalogRename, findGitToNpmMigration, findNpmTargetEntry, isRegistryRangeSpec, sameLoaderRows } from './source-migration.js';
@@ -71,7 +72,7 @@ function isGitHubReleaseTarballSpec(spec) {
71
72
  const segments = url.pathname.split('/').filter(segment => segment !== '');
72
73
  return segments.length >= 6
73
74
  && segments[2] === 'releases'
74
- && segments[3] === 'download'
75
+ && (segments[3] === 'download' || (segments[3] === 'latest' && segments[4] === 'download'))
75
76
  && (url.pathname.endsWith('.tgz') || url.pathname.endsWith('.tar.gz'));
76
77
  }
77
78
  catch {
@@ -1918,6 +1919,18 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1918
1919
  // Merge: current deps stay, backup specs win on name conflicts; bundle
1919
1920
  // lists are unioned. Full exports merge to the backup view unchanged.
1920
1921
  const mergedManifest = mergeRestoreManifest(JSON.parse(readFileSync(join(activeProfileDir, 'package.json'), 'utf8')), manifestBefore);
1922
+ // This profile belongs to the process running the restore, and the
1923
+ // market is part of it: a backup written by another market version
1924
+ // would have the install below swap this package's files under the
1925
+ // live module — the mixed state the update route refuses (#608), and
1926
+ // here it also removes the code that is going to answer this request.
1927
+ // The running spec wins; the backup's is reported so the update flow
1928
+ // can apply it as its own restart-aware operation.
1929
+ const selfPins = pinRunningDeps(mergedManifest, manifestBefore, SELF_NAMES);
1930
+ mergedManifest.dependencies = selfPins.dependencies;
1931
+ if (selfPins.pinned.length > 0) {
1932
+ logEvent('warn', 'restore', `kept the running market version — ${selfPins.pinned.map(dep => `${dep.name}: ${dep.from} -> ${dep.to}`).join('; ')}`);
1933
+ }
1921
1934
  writeFileSync(join(activeProfileDir, 'package.json'), `${JSON.stringify(mergedManifest, null, 2)}\n`);
1922
1935
  // Named BEFORE the install runs, because that is the install this
1923
1936
  // will make fail: a `link:/Users/…` spec from another machine points
@@ -1934,7 +1947,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1934
1947
  if (bootErrors.length > 0) {
1935
1948
  logEvent('warn', 'restore', `restored profile will not boot as-is — ${bootErrors.join('; ')}`);
1936
1949
  }
1937
- return { files: restored.files, errors: [], unportable, ...(bootErrors.length > 0 ? { bootErrors } : {}) };
1950
+ return { files: restored.files, errors: [], unportable, pinned: selfPins.pinned, ...(bootErrors.length > 0 ? { bootErrors } : {}) };
1938
1951
  }
1939
1952
  // A bad dependency makes pnpm abort the whole install. Retry from an
1940
1953
  // empty dependency list so one broken plugin cannot block the rest.
@@ -1945,15 +1958,23 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1945
1958
  const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
1946
1959
  const dependencies = Object.entries(manifest.dependencies ?? {});
1947
1960
  const desiredBundles = [...(manifest.dsh?.profile?.bundles ?? [])];
1948
- const dependencyNames = new Set(dependencies.map(([name]) => name));
1949
- manifest.dependencies = {};
1961
+ // Keep the running market out of the retry wipe. Clearing it from the
1962
+ // manifest this process is serving from drops it out of its own bundle
1963
+ // list mid-restore, and `pnpm add` of it writes this package's files
1964
+ // under the live module — the two ways a restore breaks the very plugin
1965
+ // that is running it. It is the one dependency a restore never has to
1966
+ // re-add: it is installed, and `selfPins` already kept its spec.
1967
+ const selfDependencies = dependencies.filter(([name]) => SELF_NAMES.has(name));
1968
+ const retryDependencies = dependencies.filter(([name]) => !SELF_NAMES.has(name));
1969
+ const retryNames = new Set(retryDependencies.map(([name]) => name));
1970
+ manifest.dependencies = Object.fromEntries(selfDependencies);
1950
1971
  if (Array.isArray(manifest.dsh?.profile?.bundles)) {
1951
- manifest.dsh.profile.bundles = desiredBundles.filter(bundle => !dependencyNames.has(bundle));
1972
+ manifest.dsh.profile.bundles = desiredBundles.filter(bundle => !retryNames.has(bundle));
1952
1973
  }
1953
1974
  writeFileSync(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`);
1954
1975
  const errors = [];
1955
1976
  let installed = 0;
1956
- for (const [name, spec] of dependencies) {
1977
+ for (const [name, spec] of retryDependencies) {
1957
1978
  const target = /^(?:file|link|github|git\+|https?):/.test(spec) ? spec : `${name}@${spec}`;
1958
1979
  try {
1959
1980
  const item = await runPlugin(config.profile, ['add', target]);
@@ -1981,7 +2002,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1981
2002
  delete current.dependencies[name];
1982
2003
  writeFileSync(manifestFile, `${JSON.stringify(current, null, 2)}\n`);
1983
2004
  }
1984
- if (installed === 0 && dependencies.length > 0) {
2005
+ if (installed === 0 && retryDependencies.length > 0) {
1985
2006
  restored.rollback();
1986
2007
  }
1987
2008
  invalidateUpdates();
@@ -1989,10 +2010,17 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1989
2010
  if (bootErrors.length > 0) {
1990
2011
  logEvent('warn', 'restore', `restored profile will not boot as-is — ${bootErrors.join('; ')}`);
1991
2012
  }
2013
+ // The retry deletes every dependency that failed, so re-reading the
2014
+ // manifest would report an empty unportable list — the in-memory
2015
+ // manifest names `{}` for the same reason (#205). Report the machine-
2016
+ // specific paths among the failures instead: those are the ones the
2017
+ // operator has to act on, and the generic pnpm error never says so.
2018
+ const failed = new Set(errors.map(error => error.name));
1992
2019
  return {
1993
2020
  files: restored.files,
1994
2021
  errors,
1995
- unportable: unportableDeps(manifest.dependencies),
2022
+ unportable: unportable.filter(dep => failed.has(dep.name)),
2023
+ pinned: selfPins.pinned,
1996
2024
  ...(bootErrors.length > 0 ? { bootErrors } : {}),
1997
2025
  };
1998
2026
  }
@@ -2244,12 +2272,18 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2244
2272
  // failure semantics as below: a failed registry load leaves the map
2245
2273
  // empty, and an empty map authorizes nothing.
2246
2274
  const catalogNpmByRepo = new Map();
2275
+ const releaseSources = new Map();
2247
2276
  try {
2248
2277
  const registry = await loadRegistry();
2249
2278
  for (const [name, spec] of Object.entries(installed)) {
2250
2279
  const source = onlineSourceOf(registry.plugins, name, spec);
2251
2280
  if (source !== null)
2252
2281
  onlineSourceFor.set(name, source);
2282
+ const releases = registry.plugins.map(plugin => catalogReleaseSourceOf(spec, plugin)).filter((value) => value !== null);
2283
+ // A shared asset must not select one of several monorepo manifests.
2284
+ const unique = new Map(releases.map(value => [JSON.stringify(value), value]));
2285
+ if (unique.size === 1)
2286
+ releaseSources.set(name, [...unique.values()][0]);
2253
2287
  }
2254
2288
  for (const plugin of registry.plugins) {
2255
2289
  if (plugin.npm === null || plugin.npm === undefined)
@@ -2262,7 +2296,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2262
2296
  catch (error) {
2263
2297
  logEvent('warn', 'updates', `package source lookup failed — ${error instanceof Error ? error.message : String(error)}`);
2264
2298
  }
2265
- return { channelFor, onlineSourceFor, catalogNpmByRepo };
2299
+ return { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources };
2266
2300
  }
2267
2301
  /**
2268
2302
  * Pre-install host compatibility refusal, shared by the update route and
@@ -2418,8 +2452,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2418
2452
  return;
2419
2453
  }
2420
2454
  try {
2421
- const { channelFor, onlineSourceFor, catalogNpmByRepo } = await updateCheckInputs();
2422
- const updates = await checkUpdates(config.profile, forceCheckFrom(request), activeProfileDir, channelFor, onlineSourceFor, catalogNpmByRepo, { holdYoungReleases: config.desktopHost === true });
2455
+ const { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources } = await updateCheckInputs();
2456
+ const updates = await checkUpdates(config.profile, forceCheckFrom(request), activeProfileDir, channelFor, onlineSourceFor, catalogNpmByRepo, { holdYoungReleases: config.desktopHost === true, releaseSources });
2423
2457
  // `packages` carries the same objects the single-package endpoint
2424
2458
  // returns, so one parser serves both. Only updatable ones: a badge
2425
2459
  // wants the count, a panel wants the rows, and neither wants to
@@ -2465,8 +2499,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2465
2499
  // The same inputs the market page builds, so a generation (#497)
2466
2500
  // or a catalog-matched local package answers here with the
2467
2501
  // release it can be compared against rather than with nothing.
2468
- const { channelFor, onlineSourceFor, catalogNpmByRepo } = await updateCheckInputs();
2469
- const update = (await checkUpdates(config.profile, force, activeProfileDir, channelFor, onlineSourceFor, catalogNpmByRepo, { holdYoungReleases: config.desktopHost === true }))[name];
2502
+ const { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources } = await updateCheckInputs();
2503
+ const update = (await checkUpdates(config.profile, force, activeProfileDir, channelFor, onlineSourceFor, catalogNpmByRepo, { holdYoungReleases: config.desktopHost === true, releaseSources }))[name];
2470
2504
  if (update === undefined) {
2471
2505
  sendJson(response, 404, { schema: UPDATE_API_V1_SCHEMA, error: 'plugin is not installed' });
2472
2506
  return;
@@ -4355,7 +4389,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4355
4389
  }
4356
4390
  try {
4357
4391
  const force = (request.url ?? '').includes('force=1');
4358
- const { channelFor, onlineSourceFor, catalogNpmByRepo } = await updateCheckInputs();
4392
+ const { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources } = await updateCheckInputs();
4359
4393
  // Migration hints are this listing's own business: the market page
4360
4394
  // is where "this could come from npm now" is offered, and no other
4361
4395
  // caller acts on it.
@@ -4386,7 +4420,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4386
4420
  catch (error) {
4387
4421
  logEvent('warn', 'updates', `package source lookup failed — ${error instanceof Error ? error.message : String(error)}`);
4388
4422
  }
4389
- const updates = await checkUpdates(config.profile, force, activeProfileDir, channelFor, onlineSourceFor, catalogNpmByRepo, { holdYoungReleases: config.desktopHost === true });
4423
+ const updates = await checkUpdates(config.profile, force, activeProfileDir, channelFor, onlineSourceFor, catalogNpmByRepo, { holdYoungReleases: config.desktopHost === true, releaseSources });
4390
4424
  for (const [name, migration] of sourceMigrationFor) {
4391
4425
  const status = updates[name];
4392
4426
  if (status !== undefined)
@@ -4916,17 +4950,35 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4916
4950
  const genericGitTarget = gitSpec === null ? gitUpdateTarget(spec) : null;
4917
4951
  const isGit = gitSpec !== null || genericGitTarget !== null;
4918
4952
  const isReleaseTarball = !restore && isGitHubReleaseTarballSpec(spec);
4953
+ let releaseUpdate = null;
4954
+ if (isReleaseTarball) {
4955
+ const source = (await updateCheckInputs()).releaseSources.get(name);
4956
+ if (source !== undefined) {
4957
+ const installedVersion = readInstalledVersion(config.profile, name, activeProfileDir);
4958
+ releaseUpdate = await publishedReleaseUpdate(source, name);
4959
+ if (releaseUpdate === null || (compatVersion !== null && releaseUpdate.version !== compatVersion)) {
4960
+ sendJson(response, 409, { error: '无法确认新版完整包,插件没有改动。请刷新市场后重试。 / The published complete package could not be verified. Nothing was changed; refresh the market and try again.' });
4961
+ return;
4962
+ }
4963
+ if (installedVersion !== null && !isUpgrade(installedVersion, releaseUpdate.version)) {
4964
+ invalidateUpdates();
4965
+ if (installedVersion === releaseUpdate.version)
4966
+ sendJson(response, 200, { ok: true, skipped: 'current', name, version: installedVersion });
4967
+ else
4968
+ sendJson(response, 400, { error: '新版完整包比已安装版本更旧,已停止更新。 / The published package is older than the installed version; nothing was changed.' });
4969
+ return;
4970
+ }
4971
+ }
4972
+ }
4919
4973
  const isNpmRollbackSource = !restore && !isGit && !isReleaseTarball
4920
4974
  // Market-managed npm installs persist only a range, version, or
4921
4975
  // dist-tag. Any protocol/path/manual shorthand needs its own
4922
4976
  // proven source-preserving rollback rather than being guessed
4923
4977
  // into name@<installed-version>.
4924
4978
  && !/[:/\\]/.test(spec);
4925
- // Every ordinary non-Git update still installs name@<tag>, even
4926
- // when its PREVIOUS source was a release URL. Source
4927
- // classification chooses rollback mechanics; it must not weaken
4928
- // the existing registry target/downgrade validation.
4929
- const usesNpmUpdateTarget = !restore && !isGit;
4979
+ // Curated floating archives remain archives. Other non-Git
4980
+ // sources retain the existing repo-bound npm migration checks.
4981
+ const usesNpmUpdateTarget = !restore && !isGit && releaseUpdate === null;
4930
4982
  // #768: an archive URL carries no registry identity, so
4931
4983
  // name@<tag> would not update this install — it would replace it
4932
4984
  // with whatever package shares its name. Only proceed when a
@@ -4950,7 +5002,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4950
5002
  // The market follows its channel; everything else is `latest`.
4951
5003
  const selfChannel = SELF_NAMES.has(name) ? activeChannel() : null;
4952
5004
  const tag = selfChannel === null ? 'latest' : DIST_TAG[selfChannel];
4953
- let expectedNpmVersion = null;
5005
+ let expectedNpmVersion = releaseUpdate?.version ?? null;
4954
5006
  /** The target could not be pinned because registry lookups failed (#1047). */
4955
5007
  let versionUnverified = false;
4956
5008
  let enforceMatureReleaseAge = false;
@@ -5190,11 +5242,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5190
5242
  // nothing where one does not.
5191
5243
  let target = restore
5192
5244
  ? (NPM_NAME_RE.test(spec) ? `${spec}@${tag}` : await acceleratedTarget(spec, region))
5193
- : usesNpmUpdateTarget
5194
- ? (expectedNpmVersion !== null ? `${name}@${expectedNpmVersion}` : `${name}@${tag}`)
5195
- : genericGitTarget !== null
5196
- ? genericGitTarget
5197
- : await acceleratedTarget(gitSpec, region);
5245
+ : releaseUpdate !== null ? releaseUpdate.target
5246
+ : usesNpmUpdateTarget
5247
+ ? (expectedNpmVersion !== null ? `${name}@${expectedNpmVersion}` : `${name}@${tag}`)
5248
+ : genericGitTarget !== null
5249
+ ? genericGitTarget
5250
+ : await acceleratedTarget(gitSpec, region);
5198
5251
  if (drainCall !== undefined && (drainCall.role === 'probe' || drainCall.expected !== null)) {
5199
5252
  target = await pinDrainGithubTarget(target, region);
5200
5253
  }
@@ -5757,7 +5810,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5757
5810
  // when a floating tag is what was sent). A version above the pin
5758
5811
  // is only possible on a floating target whose resolver moved
5759
5812
  // forward mid-download; that stays accepted.
5760
- if (ok && usesNpmUpdateTarget) {
5813
+ if (ok && (usesNpmUpdateTarget || releaseUpdate !== null)) {
5761
5814
  const floatingDistTag = expectedNpmVersion === null;
5762
5815
  if (floatingDistTag
5763
5816
  && typeof result.resolvedNpmVersion === 'string'
@@ -5778,7 +5831,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5778
5831
  const targetOrder = target !== null && afterVersion !== null
5779
5832
  ? compareVersions(afterVersion, target)
5780
5833
  : null;
5781
- const targetMismatch = target !== null && (afterVersion === null
5834
+ const targetMismatch = releaseUpdate !== null ? afterVersion !== target : target !== null && (afterVersion === null
5782
5835
  || (targetOrder !== null
5783
5836
  // Comparable: getting LESS than we asked for is the symptom.
5784
5837
  // A version above the target is `latest` moving forward while
@@ -145,4 +145,27 @@ export declare function unportableDeps(dependencies: unknown): Array<{
145
145
  spec: string;
146
146
  }>;
147
147
  export declare function mergeRestoreManifest(backupManifest: Record<string, unknown>, current: Record<string, unknown>, selection?: PluginSelection): Record<string, unknown>;
148
+ /**
149
+ * Dependencies a restore must leave at the spec the target already has — the
150
+ * market itself, while it is the package running the restore.
151
+ *
152
+ * A restore applies the backup's manifest through `pnpm install`, which
153
+ * rewrites whatever that manifest pins. When the backup was written by a
154
+ * different market version, that install replaces THIS package's files under
155
+ * the live module: the mixed state the update route refuses (#608), made
156
+ * worse here because the code answering the restore request is the code being
157
+ * swapped out. The running spec therefore wins, and the backup's spec is
158
+ * returned so the caller can report it — the update flow can apply it later,
159
+ * with its restart and rollback machinery.
160
+ *
161
+ * Only string specs take part: anything else is not a pin this can compare.
162
+ */
163
+ export declare function pinRunningDeps(merged: Record<string, unknown>, current: Record<string, unknown>, names: ReadonlySet<string>): {
164
+ dependencies: Record<string, unknown>;
165
+ pinned: Array<{
166
+ name: string;
167
+ from: string;
168
+ to: string;
169
+ }>;
170
+ };
148
171
  export {};
@@ -18,6 +18,21 @@
18
18
  * to the origin registry — verified against the Tencent mirror, which serves
19
19
  * its own host in that field.
20
20
  */
21
+ /**
22
+ * `dist.tarball` as an absolute URL.
23
+ *
24
+ * A registry behind a path prefix — Nexus, Verdaccio, a reverse proxy — may
25
+ * answer that field as a relative path (`/dsh-plugin-catalog/-/…`). pnpm
26
+ * resolves it against the registry; passing it straight to `fetch` threw
27
+ * "Failed to parse URL" instead, the npm source dropped out of the list, and
28
+ * the market read the catalog from somewhere else without saying so (#1117).
29
+ *
30
+ * Relative resolution follows the URL rules: a value starting with `/` is
31
+ * root-relative and a bare path is relative to the registry's own directory,
32
+ * which is where the registry serves it from. Nothing is rewritten when the
33
+ * field is already absolute.
34
+ */
35
+ export declare function absoluteTarballUrl(tarball: string, registry: string): string;
21
36
  /**
22
37
  * One file's bytes from a gzipped tar, or null when it is not in there.
23
38
  *
@@ -89,4 +89,6 @@ export declare function configuredProxy(): string | null;
89
89
  export declare function marketFetch(url: string, init?: {
90
90
  signal?: AbortSignal;
91
91
  headers?: Record<string, string>;
92
+ method?: 'GET' | 'HEAD';
93
+ redirect?: 'follow' | 'manual';
92
94
  }): Promise<Response>;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Text a child process wrote, decoded by the encoding it actually used.
3
+ *
4
+ * A Windows console gives a child process the console code page, and a
5
+ * Chinese system is 936 (GBK): `cmd.exe` says "不是内部或外部命令" in GBK
6
+ * bytes. The pipe carries bytes and no encoding, so decoding them as UTF-8
7
+ * turned every one of those bytes into U+FFFD — the install error read
8
+ * `'dsh' �����ڲ����ⲿ���Ҳ���ǿ����еij���` (#1122), which tells the person
9
+ * looking at it nothing at all.
10
+ *
11
+ * UTF-8 is tried first and strictly, so text that IS UTF-8 decodes exactly as
12
+ * before; only bytes that cannot be UTF-8 fall through to the code page. No
13
+ * `chcp` probe: that costs a process per install, and the answer is already
14
+ * in the bytes.
15
+ */
16
+ /** Decode a complete child output buffer. */
17
+ export declare function decodeChildOutput(bytes: Buffer, platform?: NodeJS.Platform): string;
18
+ /**
19
+ * The last `limit` bytes of one child stream, decoded when it is asked for.
20
+ *
21
+ * Kept as bytes rather than as a string because the encoding cannot be known
22
+ * from a prefix: the first chunks of a pnpm run are ASCII either way, and
23
+ * decoding each chunk as it arrives fixes the encoding before the text that
24
+ * decides it has been seen.
25
+ */
26
+ export declare function createOutputBuffer(limit: number, platform?: NodeJS.Platform): {
27
+ push(chunk: Buffer): void;
28
+ text(): string;
29
+ };
@@ -0,0 +1,15 @@
1
+ export interface CatalogReleaseSource {
2
+ repo: string;
3
+ asset: string;
4
+ manifest: string;
5
+ }
6
+ /** Only the catalog's own floating asset opts an existing archive into updates. */
7
+ export declare function catalogReleaseSourceOf(spec: string, entry: {
8
+ url: string;
9
+ npm?: unknown;
10
+ tarball?: unknown;
11
+ }): CatalogReleaseSource | null;
12
+ export declare function publishedReleaseUpdate(source: CatalogReleaseSource, name: string): Promise<{
13
+ version: string;
14
+ target: string;
15
+ } | null>;
@@ -4,6 +4,7 @@
4
4
  * dist-tag for registry installs — with a TTL cache.
5
5
  */
6
6
  import { type Channel } from './channels.ts';
7
+ import { type CatalogReleaseSource } from './release-updates.ts';
7
8
  import type { GitToNpmMigration, NpmRenameMigration } from './source-migration.ts';
8
9
  export interface UpdateStatus {
9
10
  /**
@@ -249,4 +250,5 @@ catalogNpmByRepo?: ReadonlyMap<string, string>,
249
250
  */
250
251
  options?: {
251
252
  holdYoungReleases?: boolean;
253
+ releaseSources?: ReadonlyMap<string, CatalogReleaseSource>;
252
254
  }): Promise<Record<string, UpdateStatus>>;
package/lib/updates.js CHANGED
@@ -11,6 +11,7 @@ import { DIST_TAG } from './channels.js';
11
11
  import { resolveHeadCommit } from './accelerate.js';
12
12
  import { inProbe } from './probe-context.js';
13
13
  import { marketFetch } from './net.js';
14
+ import { publishedReleaseUpdate } from './release-updates.js';
14
15
  import { activeRegion, githubRoutesFor, rememberGithubRoute, throughProxy } from './regions.js';
15
16
  import { isNumericReleaseAgeWindow, readMinimumReleaseAgeMs } from './install.js';
16
17
  import { isStableReleaseVersion, selectMatureUpdate } from './release-candidates.js';
@@ -735,7 +736,7 @@ options = {}) {
735
736
  // answer immediately, and a cache keyed on the profile alone would serve
736
737
  // the stable verdict for the rest of the TTL — reading as "the setting did
737
738
  // nothing".
738
- const cacheKey = `${activeProfileDir}\u0000${options.holdYoungReleases === true ? 'hold' : 'any'}\u0000${[...channelFor].map(([n, c]) => `${n}:${c}`).sort().join(',')}\u0000${[...onlineSourceFor].map(([n, s]) => `${n}:${s}`).sort().join(',')}\u0000${[...catalogNpmByRepo].map(([n, s]) => `${n}:${s}`).sort().join(',')}\u0000${options.holdYoungReleases === true ? profilePolicyFingerprint(activeProfileDir) : ''}`;
739
+ const cacheKey = `${activeProfileDir}\u0000${options.holdYoungReleases === true ? 'hold' : 'any'}\u0000${[...channelFor].map(([n, c]) => `${n}:${c}`).sort().join(',')}\u0000${[...onlineSourceFor].map(([n, s]) => `${n}:${s}`).sort().join(',')}\u0000${[...catalogNpmByRepo].map(([n, s]) => `${n}:${s}`).sort().join(',')}\u0000${options.holdYoungReleases === true ? profilePolicyFingerprint(activeProfileDir) : ''}` + JSON.stringify([...(options.releaseSources ?? [])]);
739
740
  if (!force && updatesCache?.key === cacheKey && Date.now() < updatesCache.recheckAt) {
740
741
  return updatesCache.data;
741
742
  }
@@ -862,6 +863,12 @@ options = {}) {
862
863
  // when a catalog entry owns both the repo the archive came from and
863
864
  // this name; otherwise report no update rather than a false one.
864
865
  if (/^https?:/i.test(spec)) {
866
+ const source = options.releaseSources?.get(name);
867
+ if (source !== undefined) {
868
+ const release = await publishedReleaseUpdate(source, name);
869
+ result[name] = { kind: 'npm', version, current: version, latest: release?.version ?? null, updateAvailable: isUpgrade(version, release?.version ?? null) };
870
+ return;
871
+ }
865
872
  const repo = lookupRepoFromUrl(spec);
866
873
  const repoKey = repo === null ? null : catalogRepoKey(repo);
867
874
  if (repoKey === null || catalogNpmByRepo.get(repoKey) !== name) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dshmarket",
3
3
  "description": "Visual plugin market inside DeepSeek Harness — browse, search, and one-click install community plugins. · DSH 可视化插件市场:逛一逛,点一下,装好。",
4
- "version": "1.73.12",
4
+ "version": "1.73.13",
5
5
  "icon": "assets/logo.svg",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",