dsh-crate 0.6.4 → 0.6.5

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
@@ -7,7 +7,7 @@
7
7
  * Security: the install route executes a shell command, so it accepts only
8
8
  * same-origin POSTs and only sources present in the curated registry.
9
9
  */
10
- import { createHash } from 'node:crypto';
10
+ import { createHash, randomUUID } from 'node:crypto';
11
11
  import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
12
12
  import { dirname, join } from 'node:path';
13
13
  import { Readable } from 'node:stream';
@@ -34,7 +34,7 @@ import { BOOT_ID, cancelActive, probePnpm, progress, provisionPnpm, runDshPlugin
34
34
  import { packageOfEntryName } from './entry-identity.js';
35
35
  import { PendingRowJournal, repairOrphanedRows } from './pending-rows.js';
36
36
  import { hasUnsettledPackageRun, loadHostProfileLock, PendingCheckoutLinks, withIdleProfile, } from './pending-checkout-links.js';
37
- import { addProfileBundle, bundleExpressionRowIds, bundleOptOutRowIds, bundlePatchInsertedIds, bundlesDroppedFromProfile, declareProfileDependency, dropFromManifest, dropReleaseAgeExcludes, generationManagedNames, hasLoadableEntry, holdsNativeAddon, INBOX_BUNDLES, isDshProfileName, profileDir, readDependencyOwners, readGitResolutionCommit, readInstalled, readInstalledManifest, readInstalledPackageName, readInstalledRepoEvidence, readInstalledVersion, readLockCommits, readProfileBundles, readProfileManifestSnapshot, removeProfileBundle, parsePatchRows, restoreProfileManifest, restoreRemovedProfileBundle, setAllowBuilds, shippedInsertedRowIds } from './profile.js';
37
+ import { addProfileBundle, bundleExpressionRowIds, bundleGroupGateRowIds, bundleOptOutRowIds, bundlePatchInsertedIds, bundlesDroppedFromProfile, declareProfileDependency, dropFromManifest, dropReleaseAgeExcludes, generationManagedNames, hasLoadableEntry, holdsNativeAddon, INBOX_BUNDLES, isDshProfileName, profileDir, readDependencyOwners, readGitResolutionCommit, readInstalled, readInstalledManifest, readInstalledPackageName, readInstalledRepoEvidence, readInstalledVersion, readLockCommits, readProfileBundles, readProfileManifestSnapshot, removeProfileBundle, parsePatchRows, restoreProfileManifest, restoreRemovedProfileBundle, setAllowBuilds, shippedInsertedRowIds } from './profile.js';
38
38
  import { assessProfile, classifyPeer, introducedDuplicateNames, introducedRisks } from './compatibility.js';
39
39
  import { runningAgentIds } from './agents.js';
40
40
  import { DrainCoordinator, DrainNoop, DrainRefusal } from './drain.js';
@@ -75,6 +75,8 @@ import { createGist, fitsGistLimit, GistError, gistErrorCode, parseGistId, readG
75
75
  import { MAX_UPDATE_OPERATIONS_V1, UpdateOperationStoreV1, UPDATE_API_V1_SCHEMA } from './update-api-v1.js';
76
76
  import { declaredPredecessors, findCatalogRename, findGitToNpmMigration, findNpmTargetEntry, isRegistryRangeSpec, sameLoaderRows } from './source-migration.js';
77
77
  const DISCOVERY_RETRY_MS = 30_000;
78
+ const CATALOG_PAGE_SIZE = 256;
79
+ const CATALOG_SNAPSHOT_TTL_MS = 10 * 60_000;
78
80
  /** These revisions describe the server's catalog, independently of what its source includes. */
79
81
  const discoveryCatalogs = new WeakMap();
80
82
  function discoveryCatalog(registry) {
@@ -464,6 +466,7 @@ function pnpmFailureMessage(result, profileDirectory) {
464
466
  */
465
467
  export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, hostActivation) {
466
468
  let disposed = false;
469
+ const catalogSnapshots = new Map();
467
470
  // An ordinary profile must resolve under DSH_HOME by the same rules as the
468
471
  // DSH CLI. A host-authoritative explicit directory (DSH Desktop) does not
469
472
  // derive a path from this display/profile name.
@@ -1361,7 +1364,15 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1361
1364
  const allOff = choices !== null && choices.ownOff.size === componentNames.size;
1362
1365
  // Old market builds stored only a state flag and unmarked, standalone
1363
1366
  // rows. Keep their ON path for that otherwise indistinguishable format.
1364
- const userAllOff = allOff && !(wasDisabled && choices.legacyAllOff);
1367
+ // A literal `disabled: true` on a `group: true` row the bundle gates with
1368
+ // an expression (as dsh-mnemon ships) is never the user's choice on the
1369
+ // plugins page, which toggles the components under the group and reports
1370
+ // the group's literal "saved but overridden". An older market wrote it when it switched the package off, so it
1371
+ // is residue to clean, and sending the user to the page that cannot help is
1372
+ // the dead end #1305 reported.
1373
+ const userPatchDisables = allOff ? readUserPatchState(userPatchPath).disables : [];
1374
+ const gateHeldShut = bundleGroupGateRowIds(packageDir).some(rowId => userPatchDisables.includes(rowId));
1375
+ const userAllOff = allOff && !(wasDisabled && choices.legacyAllOff) && !gateHeldShut;
1365
1376
  const initial = {
1366
1377
  ok: true, reason: undefined, patchRows: componentRows,
1367
1378
  patchWrite: null, carrierRows, isCarrier, bundleSwitch: { ok: true, reason: null },
@@ -4128,12 +4139,54 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4128
4139
  }
4129
4140
  try {
4130
4141
  try {
4131
- const registry = await loadRegistry();
4132
- sendJson(response, 200, {
4133
- registry: discoveryCatalog(registry).response,
4134
- ...(Object.keys(clientPolicy()).length > 0 ? { policy: clientPolicy() } : {}),
4135
- hostVersion: dshHostInfo()?.version ?? null,
4136
- });
4142
+ const query = new URL(request.url ?? '/', 'http://localhost').searchParams;
4143
+ const pageText = query.get('page');
4144
+ const sendCatalog = (registry, paging) => {
4145
+ const policy = clientPolicy();
4146
+ sendJson(response, 200, {
4147
+ registry, hostVersion: dshHostInfo()?.version ?? null,
4148
+ ...(Object.keys(policy).length > 0 ? { policy } : {}),
4149
+ ...paging,
4150
+ });
4151
+ };
4152
+ if (pageText === null && request.headers['x-dsh-catalog-paging'] !== '1') {
4153
+ sendCatalog(discoveryCatalog(await loadRegistry()).response);
4154
+ return;
4155
+ }
4156
+ if (pageText !== null && !/^\d{1,6}$/.test(pageText)) {
4157
+ sendJson(response, 400, { error: 'Invalid catalog page' });
4158
+ return;
4159
+ }
4160
+ const page = Number(pageText ?? 0);
4161
+ const now = Date.now();
4162
+ let snapshot = query.get('snapshot');
4163
+ let registry;
4164
+ if (page === 0 && snapshot === null) {
4165
+ registry = discoveryCatalog(await loadRegistry()).response;
4166
+ snapshot = [...catalogSnapshots].find(([, saved]) => saved.registry === registry)?.[0] ?? randomUUID();
4167
+ }
4168
+ else {
4169
+ const saved = catalogSnapshots.get(snapshot ?? '');
4170
+ if (snapshot === null || saved === undefined || saved.expiresAt <= now) {
4171
+ sendJson(response, 409, { error: 'The catalog changed while loading. Please retry.' });
4172
+ return;
4173
+ }
4174
+ registry = saved.registry;
4175
+ }
4176
+ const pages = Math.max(1, Math.ceil(registry.plugins.length / CATALOG_PAGE_SIZE));
4177
+ if (page >= pages) {
4178
+ sendJson(response, 400, { error: 'Invalid catalog page' });
4179
+ return;
4180
+ }
4181
+ if (pages > 1) {
4182
+ // Keep two generations for overlapping opens; active reads renew their idle limit.
4183
+ catalogSnapshots.delete(snapshot);
4184
+ catalogSnapshots.set(snapshot, { registry, expiresAt: Date.now() + CATALOG_SNAPSHOT_TTL_MS });
4185
+ if (catalogSnapshots.size > 2)
4186
+ catalogSnapshots.delete(catalogSnapshots.keys().next().value);
4187
+ }
4188
+ const start = page * CATALOG_PAGE_SIZE;
4189
+ sendCatalog({ ...registry, plugins: registry.plugins.slice(start, start + CATALOG_PAGE_SIZE) }, { snapshot, page, pages });
4137
4190
  }
4138
4191
  catch (error) {
4139
4192
  // Say what went wrong. The market used to substitute a bundled
@@ -7087,6 +7140,41 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7087
7140
  throw error;
7088
7141
  }
7089
7142
  drainPhaseOf(request)?.('verifying');
7143
+ if (result.selfSwapped === true) {
7144
+ // The host swapped the running market for the new build while it
7145
+ // ran this very request (see `updateInPlace`): this instance is
7146
+ // disposed, and everything below asks it for services it no
7147
+ // longer has — the loader inventory above all. The answer is
7148
+ // already in the result, and the new instance is serving.
7149
+ invalidateUpdates();
7150
+ if (result.exitCode === 0) {
7151
+ logEvent('info', 'update', `${name}: the host swapped in the new build while answering this request`);
7152
+ sendJson(response, 200, {
7153
+ ok: true,
7154
+ name,
7155
+ selfSwapped: true,
7156
+ // The page is still the old one: say so, so the market's own
7157
+ // "apply now" prompt (which only reloads the page here) shows.
7158
+ activation: {
7159
+ [name]: {
7160
+ state: 'restart',
7161
+ bundle: true,
7162
+ hot: false,
7163
+ reasons: ['新版本已经换上,刷新页面就能用上。 / The new version is already running; reload the page to use it.'],
7164
+ },
7165
+ },
7166
+ });
7167
+ }
7168
+ else {
7169
+ logEvent('error', 'update', `${name}: the host replaced the running market and the update did not hold — ${result.stderr.slice(0, 400)}`);
7170
+ sendJson(response, 502, {
7171
+ ok: false,
7172
+ error: result.stderr,
7173
+ ...(result.refusalCode === undefined ? {} : { failureCode: result.refusalCode }),
7174
+ });
7175
+ }
7176
+ return;
7177
+ }
7090
7178
  if (checkoutSource !== null && result.repairOnRestart === true) {
7091
7179
  // A direct add can time out without a remove/reinstall journal
7092
7180
  // (#928). Wait for the manager before reattaching a checkout
@@ -7515,10 +7603,17 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7515
7603
  // Remembered, not just reported: the listing recomputes
7516
7604
  // activation on every page load and would otherwise call this
7517
7605
  // live again the moment the user refreshed.
7518
- if (wasLive)
7606
+ // A host that swaps the new build in itself (HMR: `applied`) left
7607
+ // no old module running, so there is nothing stale to remember
7608
+ // or to ask a restart for — and the remembered flag would keep
7609
+ // saying "restart" on every later page load.
7610
+ const staleModule = wasLive && result.liveSwap !== true;
7611
+ if (staleModule)
7519
7612
  replacedWhileLive.add(name);
7613
+ else
7614
+ replacedWhileLive.delete(name);
7520
7615
  activation = {
7521
- [name]: activationAfterReplace(verifyActivation(config.profile, name, liveNames(), activeProfileDir, disabled.has(name)), wasLive),
7616
+ [name]: activationAfterReplace(verifyActivation(config.profile, name, liveNames(), activeProfileDir, disabled.has(name)), staleModule),
7522
7617
  };
7523
7618
  const after = assessProfile(config.profile, activeProfileDir);
7524
7619
  const risks = introducedRisks(compatibilityBefore, after);
@@ -200,6 +200,19 @@ export interface InstallResult {
200
200
  * not "that plugin is in use".
201
201
  */
202
202
  needsRestart?: boolean;
203
+ /**
204
+ * The host replaced the running market itself during this run, so the
205
+ * instance serving the request has been disposed and anything that needs
206
+ * its context (the loader inventory, hot mounts) would throw. The update
207
+ * route answers from this result alone.
208
+ */
209
+ selfSwapped?: boolean;
210
+ /**
211
+ * The host loaded the new build into the running process itself, so the
212
+ * module in memory IS the new one: the update route reports it live, not
213
+ * "restart to apply", and does not remember it as stale.
214
+ */
215
+ liveSwap?: boolean;
203
216
  /** Package names pnpm reported as having ignored build scripts (ndjson). */
204
217
  ignoredBuilds?: string[];
205
218
  /**
@@ -9,3 +9,14 @@ import { type Region } from './regions.ts';
9
9
  * surface and a different root name gives enough evidence to refuse the add.
10
10
  */
11
11
  export declare function mismatchedWorkspaceRoot(target: string, name: string, region: Region): Promise<string | null>;
12
+ /**
13
+ * The package version a commit of a GitHub plugin holds, read from its
14
+ * package.json — or null when it cannot be read.
15
+ *
16
+ * The desktop host's in-place update wants the exact version the target will
17
+ * install, and for a Git spec that number exists only inside the repository.
18
+ * Null is an ordinary answer, not a failure: the caller then updates the old
19
+ * way, which needs no version. Only the `github:owner/repo#<commit>` shape is
20
+ * read; any other address is not worth a guess.
21
+ */
22
+ export declare function githubPackageVersionAt(target: string, region: Region): Promise<string | null>;
@@ -1,6 +1,6 @@
1
1
  /** The official Electron profile is owned by DSH's in-process plugin manager. */
2
2
  import { type DesktopPluginRuntime, type HostPackageManager } from './dsh-cli.ts';
3
- import { type RepairReport } from './pending-updates.ts';
3
+ import { PendingUpdateJournal, type RepairReport } from './pending-updates.ts';
4
4
  interface ManagedResult {
5
5
  application: string;
6
6
  error?: unknown;
@@ -15,6 +15,49 @@ interface ManagedResult {
15
15
  repairOnRestart?: boolean;
16
16
  /** The refusal is the host's restart-first state, not a plugin in use (#1253). */
17
17
  needsRestart?: boolean;
18
+ /**
19
+ * The host stopped or undid its own work: the profile holds what it held
20
+ * before the call. Set by the in-place update path, where a refusal at the
21
+ * target check, a failed removal that never reached pnpm, and a failure the
22
+ * host already rolled back all leave the old version in place.
23
+ */
24
+ untouched?: boolean;
25
+ /** One more plain sentence for the user, appended to the failure's account. */
26
+ note?: string;
27
+ /**
28
+ * The host replaced the running market itself during this call: the
29
+ * instance that asked is already disposed (see `updateInPlace`).
30
+ */
31
+ selfSwapped?: boolean;
32
+ /**
33
+ * The host loaded the new build into the running process itself (HMR):
34
+ * `applied`, not `restart-required`. The old module is gone from memory, so
35
+ * the update route must not say "restart to apply".
36
+ */
37
+ liveSwap?: boolean;
38
+ }
39
+ /** What `updateBundle` answers (`PluginUpdateResult` in `@deepseek-ai/dsh-plugin-manager` 0.2.2+). */
40
+ export interface ManagedUpdateResult {
41
+ from: string;
42
+ to: string;
43
+ /** The last step that ran: the target check, the removal, or the target's install. */
44
+ step: 'check' | 'remove' | 'install';
45
+ result: ManagedResult & {
46
+ changed?: boolean;
47
+ stage?: string;
48
+ target?: string;
49
+ };
50
+ /** Present when the install failed after the old version was removed: the old version's reinstall. */
51
+ restore?: ManagedResult;
52
+ }
53
+ /** The part of one `listBundles` row the in-place update decision reads. */
54
+ export interface ManagedBundleRow {
55
+ name: string;
56
+ installed?: boolean;
57
+ version?: string;
58
+ source?: string;
59
+ /** How `updateBundle` can replace it; absent when it cannot. */
60
+ update?: 'registry' | 'git';
18
61
  }
19
62
  export interface OfficialPluginManagerLike {
20
63
  installBundle(spec: string, options?: {
@@ -23,6 +66,18 @@ export interface OfficialPluginManagerLike {
23
66
  }): Promise<ManagedResult>;
24
67
  removeBundle(name: string): Promise<ManagedResult>;
25
68
  cancelInstall(requestId: string): Promise<unknown>;
69
+ /**
70
+ * Replace an installed bundle with a newer version, in one call. Only dsh
71
+ * 0.2.2 and later: absent on 0.2.1, whose manager has no in-place update, and
72
+ * every caller must feature-detect it.
73
+ */
74
+ updateBundle?(name: string, version: string, options?: {
75
+ registry?: string | null;
76
+ spec?: string;
77
+ requestId?: string;
78
+ }): Promise<ManagedUpdateResult>;
79
+ /** Used with `updateBundle` to learn which bundles it can replace (`update`). */
80
+ listBundles?(): Promise<ManagedBundleRow[]>;
26
81
  }
27
82
  /**
28
83
  * What a user can actually do when the market cannot perform an operation on
@@ -32,6 +87,28 @@ export interface OfficialPluginManagerLike {
32
87
  export declare const OFFICIAL_PAGE_HINT = "\u5B98\u65B9\u684C\u9762\u5BA2\u6237\u7AEF\u7684\u8FD9\u4E2A\u63D2\u4EF6\u64CD\u4F5C\u9700\u8981\u5728\u300C\u8BBE\u7F6E \u2192 \u63D2\u4EF6\u300D\u91CC\u5B8C\u6210\uFF1B\u5E02\u573A\u65E0\u6CD5\u901A\u8FC7\u547D\u4EE4\u884C\u4FEE\u6539\u684C\u9762\u7AEF\u7684 profile\u3002 / On the official desktop app, do this from Settings \u2192 Plugins; the market cannot change the desktop profile through the command line.";
33
88
  /** `dsh-crate@1.66.32` → `dsh-crate`; anything that is not a registry name stays unparsed. */
34
89
  export declare function registryNameOf(spec: string): string | undefined;
90
+ /** What an update needs to journal itself and to be repaired later. */
91
+ interface UpdateContext {
92
+ profile: string;
93
+ profileDirectory: string;
94
+ journal: PendingUpdateJournal;
95
+ /** Bundled pnpm from the official desktop launcher; only used for the market itself. */
96
+ packageManager?: HostPackageManager | null;
97
+ /** Told when the market starts or ends a pnpm child of its own (the self-update overlay). */
98
+ onOwnChild?: (running: boolean) => void;
99
+ /**
100
+ * The Git commit's package version, for a Git bundle's in-place update: the
101
+ * host demands the exact version the spec will install, and a commit's
102
+ * version is only in its package.json. Null when it cannot be read — the
103
+ * update then takes the remove-and-install path instead.
104
+ */
105
+ gitVersionAt?: (spec: string) => Promise<string | null>;
106
+ /**
107
+ * Hear the host's own steps of one in-place update (`plugin-manager/update-
108
+ * state`) so the page can say which one is running. Returns the unsubscribe.
109
+ */
110
+ watchUpdateSteps?: (requestId: string, listener: (step: string) => void) => () => void;
111
+ }
35
112
  /** Test seam: a new host process starts with nothing pending. */
36
113
  export declare function forgetRestartPending(): void;
37
114
  /** The official runtime's own surface, plus the repair a later start owes the profile. */
@@ -58,6 +135,15 @@ export interface OfficialDesktopRuntime extends DesktopPluginRuntime {
58
135
  * quit it before running". The market only ever runs inside a live Desktop, so
59
136
  * for the market the answer is the same on every version: the app's own
60
137
  * plugin manager is the only door.
138
+ *
139
+ * `_profileDirectory` is unused by the manager bridge — it takes the profile
140
+ * by NAME — and optional because an explicitly configured `profile: desktop`
141
+ * may be the only thing that names this profile, with no launcher directory
142
+ * to go with it (#744). `packageManager` is where Official Desktop publishes
143
+ * its bundled pnpm; it is used only to overlay the market itself (#982), and
144
+ * other packages still go through the manager. `hooks` is what only the host
145
+ * process can supply to an in-place update (see `UpdateContext`); both are
146
+ * optional, and an update without them still works.
61
147
  */
62
- export declare function createOfficialDesktopRuntime(managerLookup: () => OfficialPluginManagerLike | undefined, profileName: string, _profileDirectory?: string, packageManager?: HostPackageManager | null): OfficialDesktopRuntime;
148
+ export declare function createOfficialDesktopRuntime(managerLookup: () => OfficialPluginManagerLike | undefined, profileName: string, _profileDirectory?: string, packageManager?: HostPackageManager | null, hooks?: Pick<UpdateContext, 'gitVersionAt' | 'watchUpdateSteps'>): OfficialDesktopRuntime;
63
149
  export {};
@@ -347,6 +347,8 @@ export declare function bundleOptOutRowIds(dir: string): string[];
347
347
  * Reads the same two patch sources as `bundleOptOutRowIds` above.
348
348
  */
349
349
  export declare function bundleExpressionRowIds(dir: string): string[];
350
+ /** The `group: true` rows a package gates with an expression (#1305). */
351
+ export declare function bundleGroupGateRowIds(dir: string): string[];
350
352
  /**
351
353
  * Row ids the installed copy of a package DECLARES it inserts (#1012).
352
354
  *
@@ -393,6 +395,7 @@ export declare function parsePatchRows(text: string): {
393
395
  insertedIds: string[];
394
396
  disabledIds: string[];
395
397
  expressionIds: string[];
398
+ groupGateIds: string[];
396
399
  };
397
400
  /**
398
401
  * Where a package's bundle patches live, according to the package itself.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-crate",
3
3
  "description": "逛一逛,点一下,装好。浏览和搜索 DeepSeek Harness 社区插件,看详情、一键安装,收藏和更新都在一处。",
4
- "version": "0.6.4",
4
+ "version": "0.6.5",
5
5
  "icon": "assets/logo.svg",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",