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/routes.js CHANGED
@@ -22,7 +22,7 @@ import { setNpmrcProfileDir } from './npmrc.js';
22
22
  import { BundleError, extractBundle, isInsideOfflineRoot, MAX_BUNDLE_BYTES } from './offline.js';
23
23
  import { settingsNamespaceState } from './settings.js';
24
24
  import { statePath } from './state.js';
25
- 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';
25
+ import { buildEnvFromUnknown, cleanHotDir, forgetInstalled, hotMount, hotMountFailure, hotUnmount, listHotMounts, listLiveHotMounts, resetHotState, MAX_BLOCKED, MAX_BLOCKED_NAME, MAX_FAVORITES, MAX_NOTE, MAX_UPDATE_EXEMPT, mountClientOnlyDeps, purgeMarketState, readMarketState, recordInstalled, recordUpdated, writeMarketState, } from './hot.js';
26
26
  import { createGroup, deleteGroup, removeFromGroups, renameGroup, setGroupMembers } from './groups.js';
27
27
  import { dshHostInfo, findDshInstallDir } from './dsh-install.js';
28
28
  import { catalogReleaseManifest, deriveHostCompatibility, DiscoveryManifestIndex, findCompatibleVersion, githubCompatibilityRevision } from './discovery-compatibility.js';
@@ -64,6 +64,7 @@ import { DEFAULT_UPDATE_CHECK_INTERVAL_HOURS, isUpdateCheckIntervalHours } from
64
64
  import { createThemeManager } from './themes.js';
65
65
  import { readJsonBody, readRawBody, refuseUnadmitted, sameOrigin, sendJson } from './http.js';
66
66
  import { resolveDshHome } from './home-paths.js';
67
+ import { asHmr, claimInstance, reloadSelf, selfReloadReply } from './self-reload.js';
67
68
  import { readTelemetryState, sendOpened, setTelemetryEnabled, startHeartbeat } from './telemetry.js';
68
69
  import { clearWebdavSecret, readWebdavSecret, webdavSecretFor, writeWebdavSecret } from './webdav-secret.js';
69
70
  import { detectedDebugger, detectedSupervisor, restartAllowed, scheduleRestart, servingPort, trustedRestartRequest, trustedDownloadRequest, trustedSelfUninstallRequest, selfUninstallReachableFrom, restartReachableFrom } from './restart.js';
@@ -141,6 +142,27 @@ function isGitHubReleaseTarballSpec(spec) {
141
142
  * in frame the first reply always has to ask which one it was.
142
143
  */
143
144
  let cachedVersion = null;
145
+ /**
146
+ * Forget the version read from disk. Called when the routes unload: a module
147
+ * the host did not replace (its file did not change) stays loaded across an
148
+ * in-process reload (src/self-reload.ts), and the instance that comes next
149
+ * must report the package.json that is on disk now, not the one it started
150
+ * beside.
151
+ */
152
+ export function forgetMarketVersion() {
153
+ cachedVersion = null;
154
+ }
155
+ /**
156
+ * True only while this market is asking the host to swap in its own new build.
157
+ *
158
+ * The version a market reports must be the version of the CODE that is
159
+ * running. Any other reason this instance unloads (a settings change makes
160
+ * the host restart the entry) leaves the same code running, so the version
161
+ * read at first use stays true even though a newer package.json is on disk —
162
+ * forgetting it there would report the new version over the old code and
163
+ * hide exactly the mismatch the page needs to see.
164
+ */
165
+ let swappingSelf = false;
144
166
  export function marketVersion() {
145
167
  if (cachedVersion !== null)
146
168
  return cachedVersion;
@@ -619,15 +641,16 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
619
641
  *
620
642
  * The HOST decides which doors exist; this only combines the user's
621
643
  * preferences, because a request handler cannot see the browser's slots.
622
- * `sidebarEntry` defaults off while the two page tabs default on, so
623
- * "every door closed" is expressible — and has to be refused before it
624
- * reaches disk. A market with no entry can only be recovered by editing
644
+ * The Plugins page tab and the sidebar row default on; the settings page
645
+ * entry defaults off (it is the old door, kept for hosts without the other
646
+ * two — the browser shows it there anyway). "Every door closed" is still
647
+ * expressible, and has to be refused before it reaches disk. A market with no entry can only be recovered by editing
625
648
  * state.json or removing the package, which the card must never cause.
626
649
  */
627
650
  const entryDoors = (state = marketState) => ({
628
- settingsSection: state.settingsSection !== false,
651
+ settingsSection: state.settingsSection === true,
629
652
  pluginsTab: state.pluginsTab !== false,
630
- sidebarEntry: state.sidebarEntry === true,
653
+ sidebarEntry: state.sidebarEntry !== false,
631
654
  });
632
655
  const closesEveryDoor = (doors) => !doors.settingsSection && !doors.pluginsTab && !doors.sidebarEntry;
633
656
  /**
@@ -3234,6 +3257,18 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3234
3257
  kind: () => (config.desktopHost === true ? 'desktop' : 'web'),
3235
3258
  region: () => region,
3236
3259
  };
3260
+ /**
3261
+ * In-process reload of the market itself (see src/self-reload.ts).
3262
+ *
3263
+ * Available when the host can replace modules (its HMR service, DSH 0.2.1
3264
+ * and later) and the market is an installed package of this profile — a
3265
+ * development checkout has no newer files on disk to switch to.
3266
+ */
3267
+ const selfPackageName = () => readInstalled(config.profile, activeProfileDir)['dsh-crate'] !== undefined ? 'dsh-crate' : null;
3268
+ const hostHmr = () => asHmr(host.get?.('hmr'));
3269
+ const selfReloadAvailable = () => hostHmr() !== undefined && host.get?.('profileContext') !== undefined && selfPackageName() !== null;
3270
+ // Announced once the routes below are up; handlers read it lazily.
3271
+ let instanceClaim;
3237
3272
  const disposers = [
3238
3273
  // 页面打开:页面每次加载上报一次,服务端每天只保留第一次;立即返回,页面不等网络。
3239
3274
  registerRoute({
@@ -5198,18 +5233,34 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5198
5233
  }
5199
5234
  const state = readMarketState(activeProfileDir);
5200
5235
  const id = userCatalogId(entry);
5201
- const saved = (state.userCatalogs ?? []).filter(item => item.id !== id);
5236
+ // A newer pack of the same catalog replaces the older import. The id
5237
+ // follows the content, so without this the old copy keeps winning
5238
+ // ("first source wins") and the new version never shows (#1295).
5239
+ // "Same catalog" means an earlier OFFLINE import with the same label.
5240
+ const labelKey = JSON.stringify(probe.info.label ?? null);
5241
+ const replaced = [];
5242
+ for (const item of state.userCatalogs ?? []) {
5243
+ if (item.id === id || item.file === undefined || !isInsideOfflineRoot(item.file))
5244
+ continue;
5245
+ const older = await probeCatalog({ file: item.file });
5246
+ if (older.registry !== null && labelKey !== 'null' && JSON.stringify(older.info.label ?? null) === labelKey) {
5247
+ replaced.push({ id: item.id, file: item.file });
5248
+ }
5249
+ }
5250
+ const saved = (state.userCatalogs ?? []).filter(item => item.id !== id && !replaced.some(old => old.id === item.id));
5202
5251
  if (saved.length >= MAX_USER_CATALOGS) {
5203
5252
  rmSync(extracted.dir, { recursive: true, force: true });
5204
5253
  sendJson(response, 400, { ok: false, code: 'limit', limit: MAX_USER_CATALOGS, error: `at most ${String(MAX_USER_CATALOGS)} catalogs / 最多添加 ${String(MAX_USER_CATALOGS)} 个目录` });
5205
5254
  return;
5206
5255
  }
5207
5256
  writeMarketState(activeProfileDir, { ...state, userCatalogs: [...saved, { id, ...entry }] });
5257
+ for (const old of replaced)
5258
+ rmSync(dirname(old.file), { recursive: true, force: true });
5208
5259
  refreshMarketState();
5209
5260
  forgetCatalog();
5210
5261
  invalidateUpdates();
5211
- logEvent('info', 'offline', `imported bundle ${extracted.id}: ${String(probe.info.count)} plugins, ${String(extracted.files)} files`);
5212
- sendJson(response, 200, { ok: true, id, count: probe.info.count, label: probe.info.label });
5262
+ logEvent('info', 'offline', `imported bundle ${extracted.id}: ${String(probe.info.count)} plugins, ${String(extracted.files)} files${replaced.length > 0 ? `, replaced ${String(replaced.length)} older import(s)` : ''}`);
5263
+ sendJson(response, 200, { ok: true, id, count: probe.info.count, label: probe.info.label, replaced: replaced.length });
5213
5264
  });
5214
5265
  }
5215
5266
  catch (error) {
@@ -5692,7 +5743,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5692
5743
  // by the user — the card explains a choice it made on their behalf
5693
5744
  // exactly once, so nobody has to wonder why downloads moved.
5694
5745
  regionAuto,
5695
- sidebarEntry: marketState.sidebarEntry === true,
5746
+ sidebarEntry: marketState.sidebarEntry !== false,
5747
+ // Whether DSH Desktop owns this process (the market cannot restart it).
5748
+ desktopHost: config.desktopHost === true,
5696
5749
  restart: restartAllowed(config),
5697
5750
  // Named so the UI can say WHY the button is gone. A blank
5698
5751
  // "no restart button" is the state #229 reported as broken.
@@ -5711,6 +5764,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5711
5764
  // card hides a remove button that could only ever answer 403.
5712
5765
  selfUninstallReachable: selfUninstallReachableFrom(request),
5713
5766
  selfManaged: installed['dsh-crate'] !== undefined,
5767
+ // Whether POST /dsh-crate/reload-self can swap a newer build of the
5768
+ // market in without restarting DSH. The page that has just loaded a
5769
+ // newer client than this server reads it to choose between "reload
5770
+ // the market" and "restart DSH".
5771
+ selfReload: selfReloadAvailable(),
5714
5772
  // Whether the host took the market's settings namespace (#677).
5715
5773
  // `unsupported-by-host` is 0.1.7 and newer, where settings come from
5716
5774
  // a plugin's Config schema and no third-party namespace is served —
@@ -7849,7 +7907,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7849
7907
  handler: async (request, response) => {
7850
7908
  if (request.method === 'GET') {
7851
7909
  sendJson(response, 200, {
7852
- enabled: marketState.sidebarEntry === true,
7910
+ // Shown unless turned off (the default changed from off to on).
7911
+ enabled: marketState.sidebarEntry !== false,
7853
7912
  // Absent means nobody has ever chosen. On a host with no settings
7854
7913
  // page the row is then shown by default, because it is the only
7855
7914
  // way into the market (#846).
@@ -7912,7 +7971,13 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7912
7971
  handler: async (request, response) => {
7913
7972
  if (request.method === 'GET') {
7914
7973
  const doors = entryDoors();
7915
- sendJson(response, 200, { settingsSection: doors.settingsSection, pluginsTab: doors.pluginsTab });
7974
+ sendJson(response, 200, {
7975
+ settingsSection: doors.settingsSection,
7976
+ pluginsTab: doors.pluginsTab,
7977
+ // Unchosen, the browser still shows the settings entry when it is
7978
+ // the host's only door.
7979
+ settingsSectionChosen: typeof marketState.settingsSection === 'boolean',
7980
+ });
7916
7981
  return;
7917
7982
  }
7918
7983
  if (request.method !== 'POST') {
@@ -8173,6 +8238,56 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
8173
8238
  }
8174
8239
  },
8175
8240
  }),
8241
+ registerRoute({
8242
+ kind: 'exact',
8243
+ path: '/dsh-crate/reload-self',
8244
+ handler: async (request, response) => {
8245
+ if (request.method !== 'POST') {
8246
+ response.writeHead(405, { allow: 'POST' });
8247
+ response.end();
8248
+ return;
8249
+ }
8250
+ if (!sameOrigin(request)) {
8251
+ sendJson(response, 403, { error: 'untrusted origin' });
8252
+ return;
8253
+ }
8254
+ if (restarting) {
8255
+ sendJson(response, 409, { busy: true, error: 'restart already scheduled' });
8256
+ return;
8257
+ }
8258
+ try {
8259
+ // Under the same lock as every other change: a swap ends the instance
8260
+ // that would have finished a running install, so none may be running,
8261
+ // and none may start while it happens. A second request answers 409.
8262
+ const outcome = await withMutationLock(response, 'write', async () => {
8263
+ const name = selfPackageName();
8264
+ swappingSelf = true;
8265
+ try {
8266
+ return await reloadSelf({
8267
+ hmr: hostHmr,
8268
+ runningVersion: marketVersion(),
8269
+ installedVersion: () => name === null ? null : readInstalledVersion(config.profile, name, activeProfileDir),
8270
+ packageDir: () => join(activeProfileDir, 'node_modules', name ?? 'dsh-crate'),
8271
+ instanceId: instanceClaim?.id ?? '',
8272
+ log: (level, detail) => logEvent(level, 'reload', detail),
8273
+ });
8274
+ }
8275
+ finally {
8276
+ swappingSelf = false;
8277
+ }
8278
+ });
8279
+ if (outcome === null)
8280
+ return;
8281
+ const reply = selfReloadReply(outcome);
8282
+ sendJson(response, reply.status, reply.body);
8283
+ }
8284
+ catch (error) {
8285
+ const message = error instanceof Error ? error.message : String(error);
8286
+ logEvent('error', 'reload', `route error: ${message}`);
8287
+ sendJson(response, 500, { ok: false, error: message });
8288
+ }
8289
+ },
8290
+ }),
8176
8291
  registerRoute(captureLegacy('/dsh-crate/restart', {
8177
8292
  kind: 'exact',
8178
8293
  path: '/dsh-crate/restart',
@@ -9524,8 +9639,13 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
9524
9639
  ];
9525
9640
  startCheckoutRepair();
9526
9641
  const stopHeartbeat = startHeartbeat(telemetryOptions);
9642
+ instanceClaim = claimInstance(marketVersion());
9527
9643
  return async () => {
9528
9644
  disposed = true;
9645
+ instanceClaim?.release();
9646
+ if (swappingSelf)
9647
+ forgetMarketVersion();
9648
+ resetHotState();
9529
9649
  stopHeartbeat();
9530
9650
  checkoutRepairRound = undefined;
9531
9651
  if (checkoutRepairTimer !== undefined)
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Reload the market's OWN server half inside the running DSH process.
3
+ *
4
+ * Why this exists: the market updates itself by replacing its files, and the
5
+ * Node module it already imported keeps running. The browser, meanwhile, loads
6
+ * the NEW client bundle, which calls routes the old process does not have (the
7
+ * host answers 405 with an empty body). The only cure used to be a restart,
8
+ * and on DSH Desktop even that is not ours to do (`allowRestart: false`).
9
+ *
10
+ * How: not by re-importing ourselves — Node never re-evaluates a module at a
11
+ * URL it has already loaded, and a cache-busted URL only renews the entry
12
+ * file while every sibling it imports stays the old one. The host already
13
+ * solves exactly this for every plugin: `hmr.reconcileProfile()` (the service
14
+ * `@deepseek-ai/dsh-hmr` publishes as `ctx.hmr`, present from DSH 0.2.1)
15
+ * compares the files of every loaded module with the disk, evicts the ones
16
+ * that changed together with their importers, stops the loader entries that
17
+ * ran them and starts those entries again from the new files. The market is a
18
+ * loader entry like any other, so it is replaced the same way. This module is
19
+ * the orchestration around that one call.
20
+ *
21
+ * The part that is ours, and the reason this is more than one call:
22
+ *
23
+ * - The request that asks for the swap is served by the instance about to be
24
+ * replaced. Its closure outlives its own disposal (the HTTP response object
25
+ * belongs to the web server, not to the plugin), so the SAME request can
26
+ * still report how the swap went.
27
+ * - The host does not restore the old code when the new code cannot start: it
28
+ * evicts the old modules without a backup. So the new build is imported
29
+ * first, from a private copy at a path Node has never seen, and the swap is
30
+ * only asked for when that worked. A build that cannot even load never
31
+ * replaces a market that is running fine.
32
+ * - Which instance is serving is a fact held outside every module — on
33
+ * `globalThis` under a registered symbol — because the module that would
34
+ * hold it is exactly what gets replaced.
35
+ */
36
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
37
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
38
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
39
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
40
+ });
41
+ }
42
+ return path;
43
+ };
44
+ import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from 'node:fs';
45
+ import { basename, dirname, join } from 'node:path';
46
+ import { pathToFileURL } from 'node:url';
47
+ /**
48
+ * The host's HMR service when it can replace modules, otherwise undefined.
49
+ * Checked by shape: DSH 0.2.0 and earlier publish an `hmr` service without
50
+ * `reconcileProfile`, and a call into it would fail after we had decided to
51
+ * go ahead.
52
+ */
53
+ export function asHmr(value) {
54
+ if (value === null || typeof value !== 'object')
55
+ return undefined;
56
+ const candidate = value;
57
+ return typeof candidate.runExclusive === 'function' && typeof candidate.reconcileProfile === 'function'
58
+ ? value
59
+ : undefined;
60
+ }
61
+ // ── Which instance is serving ─────────────────────────────────────────────
62
+ const INSTANCE_KEY = Symbol.for('dsh-crate.serving-instance');
63
+ let instanceSequence = 0;
64
+ /**
65
+ * Announce this instance as the one serving. Returns the id to compare
66
+ * against, and a release that only clears the record when it is still this
67
+ * instance's own — a late release from a replaced instance must not erase the
68
+ * record its replacement has already written.
69
+ */
70
+ export function claimInstance(version) {
71
+ instanceSequence += 1;
72
+ const id = `${String(process.pid)}-${String(Date.now())}-${String(instanceSequence)}-${Math.random().toString(16).slice(2, 8)}`;
73
+ const holder = globalThis;
74
+ holder[INSTANCE_KEY] = { id, version };
75
+ return {
76
+ id,
77
+ release: () => {
78
+ if (holder[INSTANCE_KEY]?.id === id)
79
+ delete holder[INSTANCE_KEY];
80
+ },
81
+ };
82
+ }
83
+ /** The instance serving right now, or undefined while none is. */
84
+ export function currentInstance() {
85
+ return globalThis[INSTANCE_KEY];
86
+ }
87
+ let preflightSequence = 0;
88
+ /**
89
+ * Whether the package now on disk can be loaded at all.
90
+ *
91
+ * Imports a private copy of its `lib/` from a path nobody has imported, so
92
+ * the whole module graph is evaluated fresh and any failure — a syntax error,
93
+ * a dependency that is missing, a top-level throw — surfaces here, while the
94
+ * running market is still untouched. The copy sits NEXT TO the package so
95
+ * bare imports resolve through the same `node_modules` chain as the real one,
96
+ * and is deleted again afterwards; the host forgets files that disappeared.
97
+ *
98
+ * What it cannot see: a build that loads fine and then fails inside `apply`.
99
+ * That is only learnable by running it.
100
+ *
101
+ * `checked: false` means the check could not be run (the directory is not
102
+ * writable); the caller proceeds, because refusing every reload on a
103
+ * read-only profile would make the feature useless there.
104
+ */
105
+ export async function preflightBuild(packageDir) {
106
+ let real;
107
+ let main;
108
+ try {
109
+ real = realpathSync(packageDir);
110
+ const manifest = JSON.parse(readFileSync(join(real, 'package.json'), 'utf8'));
111
+ main = typeof manifest.main === 'string' ? manifest.main : 'index.js';
112
+ }
113
+ catch (error) {
114
+ return { ok: false, detail: `the installed package cannot be read — ${messageOf(error)}` };
115
+ }
116
+ if (!existsSync(join(real, main)))
117
+ return { ok: false, detail: `the entry file ${main} is missing` };
118
+ preflightSequence += 1;
119
+ const copy = join(dirname(real), `.dsh-crate-reload-${String(process.pid)}-${String(preflightSequence)}`);
120
+ try {
121
+ mkdirSync(copy, { recursive: true });
122
+ cpSync(join(real, 'package.json'), join(copy, 'package.json'));
123
+ cpSync(join(real, dirname(main)), join(copy, dirname(main)), {
124
+ recursive: true,
125
+ // Declarations are not loaded and a second copy of them is dead weight.
126
+ filter: source => {
127
+ const base = basename(source);
128
+ return base !== 'types' && base !== 'node_modules' && !base.endsWith('.d.ts');
129
+ },
130
+ });
131
+ }
132
+ catch {
133
+ rmSync(copy, { recursive: true, force: true });
134
+ return { ok: true, checked: false };
135
+ }
136
+ try {
137
+ const loaded = await import(__rewriteRelativeImportExtension(/* @vite-ignore */ pathToFileURL(join(copy, main)).href));
138
+ if (typeof loaded.apply !== 'function')
139
+ return { ok: false, detail: 'the new build does not export a plugin entry (apply)' };
140
+ return { ok: true, checked: true };
141
+ }
142
+ catch (error) {
143
+ return { ok: false, detail: messageOf(error) };
144
+ }
145
+ finally {
146
+ rmSync(copy, { recursive: true, force: true });
147
+ }
148
+ }
149
+ function messageOf(error) {
150
+ const text = error instanceof Error ? error.message : String(error);
151
+ // The copy's own path means nothing to the reader; the file name does.
152
+ return text.replace(/\.dsh-crate-reload-\d+-\d+/g, 'the new build').slice(0, 400);
153
+ }
154
+ const DEFAULT_QUEUE_WAIT_MS = 60_000;
155
+ const DEFAULT_SETTLE_MS = 5_000;
156
+ const sleep = (ms) => new Promise(resolve => { setTimeout(resolve, ms); });
157
+ /**
158
+ * Ask the host to replace this market with the version on disk.
159
+ *
160
+ * The caller has already refused when an operation is running: a swap ends
161
+ * the instance that would have finished it. Nothing here writes a file.
162
+ */
163
+ export async function reloadSelf(deps) {
164
+ const log = deps.log ?? (() => { });
165
+ const serving = deps.serving ?? currentInstance;
166
+ const hmr = deps.hmr();
167
+ if (hmr === undefined)
168
+ return { state: 'unsupported', reason: 'no-hmr' };
169
+ const target = deps.installedVersion();
170
+ if (target === null)
171
+ return { state: 'unsupported', reason: 'not-installed' };
172
+ if (target === deps.runningVersion)
173
+ return { state: 'current', version: target };
174
+ const verdict = await (deps.preflight ?? preflightBuild)(deps.packageDir());
175
+ if (!verdict.ok) {
176
+ log('warn', `reload to ${target} refused, the new build does not load: ${verdict.detail}`);
177
+ return { state: 'refused', detail: verdict.detail };
178
+ }
179
+ if (!verdict.checked)
180
+ log('warn', `reload to ${target}: the new build could not be test-loaded first`);
181
+ log('info', `reloading ${deps.runningVersion} -> ${target}`);
182
+ const queueWaitMs = deps.queueWaitMs ?? DEFAULT_QUEUE_WAIT_MS;
183
+ const swap = hmr.runExclusive(() => hmr.reconcileProfile());
184
+ // The swap itself is never abandoned: it was asked for, and running it a
185
+ // little late is what the user wants. Only the WAITING for it has a limit.
186
+ let timer;
187
+ const waited = await Promise.race([
188
+ swap.then(report => ({ report }), (error) => ({ error })),
189
+ new Promise(resolve => { timer = setTimeout(() => { resolve('queued'); }, queueWaitMs); }),
190
+ ]).finally(() => { clearTimeout(timer); });
191
+ if (waited === 'queued') {
192
+ void swap.catch((error) => { log('warn', `queued reload failed: ${messageOf(error)}`); });
193
+ return { state: 'queued' };
194
+ }
195
+ if ('error' in waited) {
196
+ const detail = messageOf(waited.error);
197
+ const stillOurs = serving()?.id === deps.instanceId;
198
+ log('warn', `reload to ${target} failed${stillOurs ? ' (the running market was not touched)' : ''}: ${detail}`);
199
+ return stillOurs
200
+ ? { state: 'restart-needed', detail }
201
+ : { state: 'failed', detail, serving: serving() !== undefined };
202
+ }
203
+ // The host says it is done. Believe the instance record, not the report: the
204
+ // new instance announces itself when its routes are up, which is the fact
205
+ // that matters.
206
+ const deadline = Date.now() + (deps.settleMs ?? DEFAULT_SETTLE_MS);
207
+ for (;;) {
208
+ const now = serving();
209
+ if (now !== undefined && now.id !== deps.instanceId) {
210
+ log('info', `reloaded to ${now.version}`);
211
+ return { state: 'reloaded', from: deps.runningVersion, to: now.version };
212
+ }
213
+ if (Date.now() >= deadline)
214
+ break;
215
+ await sleep(100);
216
+ }
217
+ const now = serving();
218
+ if (now?.id === deps.instanceId) {
219
+ // Nothing was replaced: the host could not compare or evict the modules
220
+ // (a loader without access to Node's module cache, a host-owned module).
221
+ const why = waited.report.restartReason !== undefined
222
+ ? `the host could not replace modules (${waited.report.restartReason})`
223
+ : waited.report.pending.length > 0
224
+ ? `the host keeps ${String(waited.report.pending.length)} changed module(s) until a restart (${waited.report.pending[0].reason})`
225
+ : 'the host reported done but the old code is still running';
226
+ log('warn', `reload to ${target}: ${why}`);
227
+ return { state: 'restart-needed', detail: why };
228
+ }
229
+ const detail = 'the new version did not start serving';
230
+ log('warn', `reload to ${target}: ${detail}`);
231
+ return { state: 'failed', detail, serving: false };
232
+ }
233
+ /**
234
+ * The HTTP answer for an outcome. Every failure says what happened, why and
235
+ * what to do now, in the project's two-language style; the state code is for
236
+ * the page, which decides what to offer next.
237
+ */
238
+ export function selfReloadReply(outcome) {
239
+ switch (outcome.state) {
240
+ case 'reloaded':
241
+ return { status: 200, body: { ok: true, outcome: 'reloaded', from: outcome.from, to: outcome.to } };
242
+ case 'current':
243
+ return { status: 200, body: { ok: true, outcome: 'current', version: outcome.version } };
244
+ case 'queued':
245
+ return {
246
+ status: 202,
247
+ body: {
248
+ ok: true,
249
+ outcome: 'queued',
250
+ message: 'DSH 正在处理另一项变更,市场会在它结束后自动换成新版。 / DSH is busy with another change. The market will switch to the new version when it finishes.',
251
+ },
252
+ };
253
+ case 'unsupported':
254
+ return {
255
+ status: 501,
256
+ body: {
257
+ ok: false,
258
+ outcome: 'unsupported',
259
+ error: outcome.reason === 'no-hmr'
260
+ ? '这个 DSH 版本不能原地换上新版市场。重启 DSH 就会用上新版。 / This DSH version cannot switch to the new market in place. Restart DSH to use it.'
261
+ : '市场不是作为插件装在这里的,没有新版文件可换。要用磁盘上的文件,请重启 DSH。 / The market is not installed as a plugin here, so there is no new version to switch to. Restart DSH to run what is on disk.',
262
+ },
263
+ };
264
+ case 'refused':
265
+ return {
266
+ status: 422,
267
+ body: {
268
+ ok: false,
269
+ outcome: 'refused',
270
+ detail: outcome.detail,
271
+ error: '新版本没能加载,已保留正在运行的版本,它照常可用。请再更新一次;重启 DSH 能看到具体原因。 / The new version could not load, so the running one was kept and still works. Update again, or restart DSH to see why.',
272
+ },
273
+ };
274
+ case 'restart-needed':
275
+ return {
276
+ status: 502,
277
+ body: {
278
+ ok: false,
279
+ outcome: 'restart-needed',
280
+ detail: outcome.detail,
281
+ error: 'DSH 这次没能换上新版,当前仍是旧版,功能照常。重启 DSH 就会用上新版。 / DSH could not switch to the new version this time. The old one keeps working. Restart DSH to use the new one.',
282
+ },
283
+ };
284
+ case 'failed':
285
+ return {
286
+ status: 502,
287
+ body: {
288
+ ok: false,
289
+ outcome: 'failed',
290
+ serving: outcome.serving,
291
+ detail: outcome.detail,
292
+ error: '切换到新版时出了问题,市场暂时不可用。重启 DSH 即可恢复。 / Switching to the new version went wrong and the market is unavailable. Restart DSH to recover.',
293
+ },
294
+ };
295
+ }
296
+ }
@@ -53,9 +53,11 @@ export declare function manifestFacts(value: unknown): NpmManifestFacts;
53
53
  /**
54
54
  * Derive the current host verdict from raw manifest facts.
55
55
  *
56
- * Every valid declaration is conjunctive: an explicit `engines.dsh` and all
57
- * host peers must agree. A malformed declaration keeps a passing result
58
- * unknown, but cannot erase a definite mismatch from another declaration.
56
+ * An explicit `engines.dsh` supersedes host peer declarations, matching the
57
+ * host loader. Without one, host peers are conjunctive. Host packages declared
58
+ * as ordinary dependencies remain checked because pnpm can hoist them over the
59
+ * runtime copy. A malformed declaration keeps a passing result unknown, but
60
+ * cannot erase a definite mismatch from another declaration.
59
61
  */
60
62
  export declare function deriveHostCompatibility(facts: NpmManifestFacts | null, hostVersion: string | null, hostPackages: ReadonlySet<string>): HostCompatibility;
61
63
  /**
@@ -39,6 +39,8 @@ export interface FindResult {
39
39
  /** Which model answered, for the card's footnote. */
40
40
  model: string;
41
41
  at: string;
42
+ /** Older saved results lack an exact candidate selection. */
43
+ selectionVersion?: 2;
42
44
  /** Whether the user's installed and favorited plugins informed the picks (they allowed it). */
43
45
  personalized?: boolean;
44
46
  }
@@ -52,11 +54,9 @@ export interface LlmLike {
52
54
  stream(options: {
53
55
  provider: string;
54
56
  model: string;
55
- reasoningEffort?: string;
56
57
  messages: unknown[];
57
58
  system?: string;
58
59
  maxTokens?: number;
59
- temperature?: number;
60
60
  signal?: AbortSignal;
61
61
  }): AsyncIterable<{
62
62
  type: string;
@@ -79,10 +79,10 @@ export declare function buildPickPrompt(request: string, registry: Registry, fou
79
79
  user: string;
80
80
  };
81
81
  /** Pull the JSON object out of a model reply (it may wrap it in a code fence). */
82
- export declare function parsePickReply(text: string, allowed: Set<string>, max?: number): {
82
+ export declare function parsePickReply(text: string, allowed: ReadonlySet<string>, max?: number): {
83
83
  intro: string;
84
84
  picks: Array<{
85
- name: string;
85
+ id: string;
86
86
  why: string;
87
87
  }>;
88
88
  };
@@ -250,11 +250,10 @@ export interface MarketState {
250
250
  /**
251
251
  * Whether the market still lists its own page in Settings (#1015).
252
252
  *
253
- * Absent means shown. Only an explicit `false` is stored, unlike
254
- * `sidebarEntry`: this entry has always been on, and every host before
255
- * 0.2.1 offers it as the only door, so an absent field is the ordinary
256
- * case rather than an unanswered question. Turning it back on clears the
257
- * field so a later default change still reaches users who never touched it.
253
+ * Absent means "not chosen": hidden wherever the Plugins page tab or the
254
+ * sidebar row is a way in, shown where it is the only one (a host before
255
+ * 0.2.1). Both answers are stored, like `sidebarEntry`, so turning it on
256
+ * keeps it on.
258
257
  */
259
258
  settingsSection?: boolean;
260
259
  /**
@@ -430,6 +429,19 @@ export declare function recordInstalled(profileDir: string, names: readonly stri
430
429
  export declare function recordUpdated(profileDir: string, names: readonly string[], at?: Date): void;
431
430
  /** The package is gone: its stamps must not outlive it. */
432
431
  export declare function forgetInstalled(profileDir: string, name: string): void;
432
+ /**
433
+ * Forget every hot mount. Called when the market's routes unload.
434
+ *
435
+ * The trees these tables point at hang off the market's own instance, so
436
+ * they go down with it. The tables do not: they are module state, and a
437
+ * module the host did not replace — its file did not change — is still
438
+ * loaded when the next instance starts (src/self-reload.ts). Left as they
439
+ * are, the new instance would believe a plugin is still mounted that its
440
+ * predecessor took down: its shim would never be mounted again, and
441
+ * "switch off" would dispose a handle that is already gone while the plugin,
442
+ * brought back by the host's own composition, kept running.
443
+ */
444
+ export declare function resetHotState(): void;
433
445
  /** Package names whose hot-mount trees are still attached and can be removed. */
434
446
  export declare function listHotMounts(): string[];
435
447
  /** Report a failed child only when it belongs to this package's hot-mount tree. */
@@ -25,6 +25,17 @@ export declare function sendJson(response: ServerResponse, status: number, paylo
25
25
  export type HostRequestGate = (request: IncomingMessage) => number | undefined;
26
26
  /** Point the market at the host's request gate. Returns the previous source. */
27
27
  export declare function setRequestGateSource(source: () => HostRequestGate | undefined): () => HostRequestGate | undefined;
28
+ /**
29
+ * The request as `connection.admit` reads it: headers, the socket, and an
30
+ * absolute `url` — what the host's own `webserver/authorize` hands the same
31
+ * check (the incoming request's `url` is only a path).
32
+ */
33
+ export declare function admissionFacts(request: IncomingMessage): {
34
+ method: string;
35
+ headers: IncomingMessage['headers'];
36
+ socket: IncomingMessage['socket'];
37
+ url: string;
38
+ };
28
39
  /**
29
40
  * Answer the request with the host's rejection, if it has one.
30
41
  * @returns true when the request was refused and answered here.