@ran-sh/dsh-crew 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/.claude-plugin/marketplace.json +16 -16
  2. package/.claude-plugin/plugin.json +14 -14
  3. package/LICENSE +21 -21
  4. package/README.de.md +359 -359
  5. package/README.es.md +359 -359
  6. package/README.fr.md +359 -359
  7. package/README.hi.md +359 -359
  8. package/README.id.md +359 -359
  9. package/README.ja.md +359 -359
  10. package/README.ko.md +359 -359
  11. package/README.md +126 -126
  12. package/README.pt.md +359 -359
  13. package/README.ru.md +359 -359
  14. package/README.th.md +359 -359
  15. package/README.tr.md +359 -359
  16. package/README.vi.md +359 -359
  17. package/README.zh-TW.md +359 -359
  18. package/README.zh.md +116 -116
  19. package/agents/ds-flash.md +24 -24
  20. package/agents/ds-pro.md +24 -24
  21. package/agents/ds-reviewer.md +23 -23
  22. package/agents/ds-worker.md +23 -23
  23. package/bin/dsh-crew.mjs +16 -16
  24. package/codex/agents/ds-flash.toml +34 -34
  25. package/codex/agents/ds-pro.toml +34 -34
  26. package/codex/agents/ds-reviewer.toml +32 -32
  27. package/codex/agents/ds-worker.toml +32 -32
  28. package/codex/prompts/dsh-config.md +19 -19
  29. package/codex/prompts/dsh-status.md +5 -5
  30. package/commands/config.md +23 -23
  31. package/commands/off.md +5 -5
  32. package/commands/on.md +5 -5
  33. package/commands/status.md +9 -9
  34. package/cordis.patch.yml +4 -4
  35. package/docs/gpt-relay-extension.md +103 -103
  36. package/docs/installation.md +138 -138
  37. package/docs/job-contracts.md +103 -103
  38. package/docs/readiness-matrix.md +85 -85
  39. package/docs/ui-surfaces.md +107 -107
  40. package/official-web-bridge/cordis.patch.yml +4 -4
  41. package/official-web-bridge/entry.mjs +1 -1
  42. package/official-web-bridge/overlay-entry.mjs +59 -59
  43. package/official-web-bridge/package.json +25 -25
  44. package/package.json +3 -2
  45. package/scripts/build-client.mjs +49 -49
  46. package/scripts/live-crew-smoke.mjs +39 -39
  47. package/scripts/live-policy-matrix.mjs +177 -177
  48. package/scripts/policy-probe.mjs +101 -101
  49. package/scripts/remove-legacy-official-bridge.ps1 +89 -89
  50. package/scripts/setup.mjs +393 -393
  51. package/scripts/smoke-real.mjs +110 -110
  52. package/scripts/smoke.mjs +78 -78
  53. package/scripts/verify-crew-ui-polish.mjs +145 -145
  54. package/scripts/verify-history-ui.mjs +97 -97
  55. package/scripts/verify-installer-fix.mjs +26 -26
  56. package/scripts/verify-npm-install.mjs +311 -311
  57. package/scripts/verify-official-bridge-e2e.mjs +192 -192
  58. package/src/adaptive-routing.mjs +260 -260
  59. package/src/client/activation-summary.tsx +64 -64
  60. package/src/client/collapsible-sections.mjs +55 -55
  61. package/src/client/history-panel.tsx +108 -108
  62. package/src/client/host-readiness.mjs +71 -71
  63. package/src/client/index.tsx +1711 -1711
  64. package/src/client/model-callability-view.mjs +17 -17
  65. package/src/client/panel-chrome.tsx +40 -40
  66. package/src/client/quick-entry.tsx +10 -10
  67. package/src/client/quick-panel.tsx +275 -275
  68. package/src/client/readiness-envelope.mjs +34 -34
  69. package/src/client/surface-detection.mjs +43 -43
  70. package/src/config-readiness.mjs +226 -226
  71. package/src/credential-reference.mjs +38 -38
  72. package/src/delivery.mjs +205 -205
  73. package/src/dsh-cli-runtime.mjs +1021 -1021
  74. package/src/dsh-cohort.mjs +20 -20
  75. package/src/extension-contract.mjs +104 -104
  76. package/src/failure-classification.mjs +201 -201
  77. package/src/history/admission-gate.mjs +67 -67
  78. package/src/history/archive-store.mjs +272 -272
  79. package/src/history/cleanup-plan.mjs +89 -89
  80. package/src/history/http.mjs +32 -32
  81. package/src/history/operation.mjs +86 -86
  82. package/src/history/runner-detach.mjs +34 -34
  83. package/src/history/runner.mjs +52 -52
  84. package/src/history/runtime.mjs +36 -36
  85. package/src/history/service.mjs +177 -177
  86. package/src/history/state.mjs +27 -27
  87. package/src/hub/entry.mjs +104 -104
  88. package/src/hub/index.mjs +2694 -2694
  89. package/src/hub-client.mjs +154 -154
  90. package/src/hub-compatibility.mjs +42 -42
  91. package/src/i18n.mjs +19 -19
  92. package/src/information-flow.mjs +67 -67
  93. package/src/install/cli.mjs +28 -28
  94. package/src/install/install-legacy.mjs +711 -711
  95. package/src/install/install.mjs +483 -483
  96. package/src/install/npx-lifecycle.mjs +3456 -3456
  97. package/src/install/official-frontend-assets.mjs +78 -78
  98. package/src/install/official-web.mjs +95 -95
  99. package/src/install/payload-content.mjs +88 -88
  100. package/src/install/windows-startup.mjs +236 -236
  101. package/src/install/windows-supervisor-adapter.mjs +443 -443
  102. package/src/install/windows-supervisor-lifecycle.mjs +782 -782
  103. package/src/install/zcode.mjs +397 -397
  104. package/src/job-contracts.mjs +255 -255
  105. package/src/local-request-guard.mjs +60 -60
  106. package/src/mcp-runtime.mjs +340 -340
  107. package/src/model-callability-contract.mjs +79 -79
  108. package/src/model-catalog.mjs +180 -180
  109. package/src/model-routing.mjs +586 -586
  110. package/src/model-schedule.mjs +207 -207
  111. package/src/official-web-bridge.mjs +447 -447
  112. package/src/policy.mjs +235 -235
  113. package/src/provider-delete-adapters.mjs +1934 -1934
  114. package/src/provider-health.mjs +130 -130
  115. package/src/provider-inventory.mjs +182 -182
  116. package/src/provider-layer-migration-adapters.mjs +759 -759
  117. package/src/provider-layer-migration.mjs +198 -198
  118. package/src/provider-lifecycle-state.mjs +103 -103
  119. package/src/provider-lifecycle.mjs +252 -252
  120. package/src/provider-profile-store.mjs +390 -390
  121. package/src/provider-settings-store.mjs +633 -633
  122. package/src/provider-store-lock.mjs +67 -67
  123. package/src/readiness-matrix.mjs +181 -181
  124. package/src/removable-waiter.mjs +29 -29
  125. package/src/role-profiles.mjs +107 -107
  126. package/src/runtime-controls.mjs +84 -84
  127. package/src/runtime-identity-contract.mjs +34 -34
  128. package/src/runtime-identity.mjs +235 -235
  129. package/src/runtime-readiness-snapshot.mjs +285 -285
  130. package/src/server.mjs +581 -581
  131. package/src/session-origins.mjs +60 -60
  132. package/src/standalone-sdk.mjs +23 -23
  133. package/src/status-shard.mjs +63 -63
  134. package/src/structured-error-code.mjs +38 -38
  135. package/src/supervisor/restart-request.mjs +256 -256
  136. package/src/workflow-runtime.mjs +739 -739
  137. package/src/workflow.mjs +155 -155
  138. package/src/workspace-audit.mjs +231 -231
  139. package/src/workspace-context.mjs +146 -146
  140. package/src/workspace-isolation.mjs +463 -455
  141. package/src/workspace-readiness.mjs +32 -32
  142. package/statusline/statusline.sh +14 -14
  143. package/statusline/worker-segment.sh +35 -35
  144. package/windows/start-dsh-crew.cmd +57 -57
  145. package/windows/start-dsh-crew.ps1 +1302 -1302
  146. package/windows/supervisor-control.ps1 +467 -467
  147. package/worker.cordis.yml +67 -67
  148. package/zcode/agents/ds-reviewer.md +31 -31
  149. package/zcode/agents/ds-worker.md +31 -31
  150. package/zcode/commands/dsh-config.md +17 -17
  151. package/zcode/commands/dsh-status.md +5 -5
@@ -1,311 +1,311 @@
1
- #!/usr/bin/env node
2
-
3
- // Regression gate for the published-package peer contract.
4
- // This intentionally uses npm's default resolver for the candidate install:
5
- // no peer-resolution bypass or equivalent override is permitted here.
6
- //
7
- // The official DSH check is deliberately bounded. It audits authoritative
8
- // public registry manifests and cross-cohort ranges instead of materializing
9
- // or fully resolving the very large official DSH dependency graph.
10
-
11
- import { mkdtemp, readFile, rm } from 'node:fs/promises';
12
- import { existsSync } from 'node:fs';
13
- import os from 'node:os';
14
- import path from 'node:path';
15
- import { spawnSync } from 'node:child_process';
16
- import { fileURLToPath } from 'node:url';
17
- import { TARGET_DSH_VERSION } from '../src/dsh-cohort.mjs';
18
-
19
- const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
20
- const registry = process.env.NPM_REGISTRY ?? 'https://registry.npmjs.org/';
21
- export const supportedDshVersion = TARGET_DSH_VERSION;
22
- const verifyOfficialDsh = process.argv.includes('--with-official-dsh');
23
- const DSH_PACKAGE = '@deepseek-ai/dsh';
24
- const DSH_PREFIX = '@deepseek-ai/dsh-';
25
- const MAX_DIRECT_PEERS = 64;
26
-
27
- export function resolveNpmInvocation({
28
- platform = process.platform,
29
- nodePath = process.execPath,
30
- fileExists = existsSync,
31
- } = {}) {
32
- if (platform !== 'win32') return { command: 'npm', argsPrefix: [] };
33
- const npmCli = path.join(path.dirname(nodePath), 'node_modules', 'npm', 'bin', 'npm-cli.js');
34
- if (!fileExists(npmCli)) throw new Error(`npm CLI was not found beside Node.js: ${npmCli}`);
35
- return { command: nodePath, argsPrefix: [npmCli] };
36
- }
37
-
38
-
39
- /**
40
- * The candidate version is derived from the candidate package manifest at the
41
- * checkout root instead of a hard-coded release literal, so the verifier never
42
- * needs a source edit for the next candidate version. The audit guard still
43
- * requires the passed-in manifest to match this authoritative value.
44
- */
45
- export async function readCandidateVersion({ rootDir = root, readFileImpl = readFile } = {}) {
46
- const packageJson = await readFileImpl(path.join(rootDir, 'package.json'), 'utf8');
47
- return JSON.parse(packageJson).version;
48
- }
49
-
50
- function isDshPackage(name) {
51
- return name === DSH_PACKAGE || name.startsWith(DSH_PREFIX);
52
- }
53
-
54
- function parseVersion(value) {
55
- const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);
56
- if (!match) return null;
57
- return {
58
- major: Number(match[1]),
59
- minor: Number(match[2]),
60
- patch: Number(match[3]),
61
- prerelease: match[4] ? match[4].split('.') : [],
62
- };
63
- }
64
-
65
- function compareVersions(left, right) {
66
- for (const key of ['major', 'minor', 'patch']) {
67
- if (left[key] !== right[key]) return left[key] > right[key] ? 1 : -1;
68
- }
69
- if (left.prerelease.length === 0 && right.prerelease.length === 0) return 0;
70
- if (left.prerelease.length === 0) return 1;
71
- if (right.prerelease.length === 0) return -1;
72
- const length = Math.max(left.prerelease.length, right.prerelease.length);
73
- for (let index = 0; index < length; index += 1) {
74
- const a = left.prerelease[index];
75
- const b = right.prerelease[index];
76
- if (a === undefined) return -1;
77
- if (b === undefined) return 1;
78
- if (a === b) continue;
79
- const aNumber = /^\d+$/.test(a);
80
- const bNumber = /^\d+$/.test(b);
81
- if (aNumber && bNumber) return Number(a) > Number(b) ? 1 : -1;
82
- if (aNumber !== bNumber) return aNumber ? -1 : 1;
83
- return a > b ? 1 : -1;
84
- }
85
- return 0;
86
- }
87
-
88
- function upperBoundForCaret(version) {
89
- if (version.major > 0) return { major: version.major + 1, minor: 0, patch: 0, prerelease: [] };
90
- if (version.minor > 0) return { major: 0, minor: version.minor + 1, patch: 0, prerelease: [] };
91
- return { major: 0, minor: 0, patch: version.patch + 1, prerelease: [] };
92
- }
93
-
94
- function upperBoundForTilde(version) {
95
- return { major: version.major, minor: version.minor + 1, patch: 0, prerelease: [] };
96
- }
97
-
98
- function satisfiesComparator(version, operator, expected) {
99
- const comparison = compareVersions(version, expected);
100
- if (operator === '>') return comparison > 0;
101
- if (operator === '>=') return comparison >= 0;
102
- if (operator === '<') return comparison < 0;
103
- if (operator === '<=') return comparison <= 0;
104
- return comparison === 0;
105
- }
106
-
107
- function satisfiesAlternative(version, alternative) {
108
- const normalized = alternative.trim();
109
- if (!normalized || /[*xX]|workspace:|^npm:|^file:|^git:/.test(normalized)) return false;
110
- const tokens = normalized.replace(/,/g, ' ').split(/\s+/).filter(Boolean);
111
- return tokens.every((token) => {
112
- const prefix = /^(\^|~|>=|<=|>|<|=)/.exec(token)?.[1] ?? '';
113
- const raw = prefix ? token.slice(prefix.length) : token;
114
- const expected = parseVersion(raw);
115
- if (!expected) return false;
116
- if (prefix === '^') {
117
- return compareVersions(version, expected) >= 0 && compareVersions(version, upperBoundForCaret(expected)) < 0;
118
- }
119
- if (prefix === '~') {
120
- return compareVersions(version, expected) >= 0 && compareVersions(version, upperBoundForTilde(expected)) < 0;
121
- }
122
- return satisfiesComparator(version, prefix, expected);
123
- });
124
- }
125
-
126
- export function satisfiesCohortRange(versionString, range) {
127
- const version = parseVersion(versionString);
128
- if (!version || typeof range !== 'string') return false;
129
- return range.split(/\s*\|\|\s*/).some((alternative) => satisfiesAlternative(version, alternative));
130
- }
131
-
132
- function assertManifest(manifest, expectedName, expectedVersion) {
133
- if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
134
- throw new Error(`invalid registry manifest for ${expectedName}@${expectedVersion}`);
135
- }
136
- if (manifest.name !== expectedName || manifest.version !== expectedVersion) {
137
- throw new Error(`registry manifest identity mismatch for ${expectedName}@${expectedVersion}`);
138
- }
139
- return manifest;
140
- }
141
-
142
- function manifestUrl(registryUrl, name, version) {
143
- const encodedName = name.startsWith('@') ? name.replace('/', '%2f') : encodeURIComponent(name);
144
- return `${registryUrl.replace(/\/+$/, '')}/${encodedName}/${encodeURIComponent(version)}`;
145
- }
146
-
147
- export async function fetchPublicManifest(name, version, {
148
- registryUrl = registry,
149
- fetchImpl = globalThis.fetch,
150
- } = {}) {
151
- if (typeof fetchImpl !== 'function') throw new Error('global fetch is unavailable');
152
- const response = await fetchImpl(manifestUrl(registryUrl, name, version), {
153
- headers: { accept: 'application/json', 'user-agent': 'dsh-crew-cohort-audit' },
154
- });
155
- if (!response?.ok) throw new Error(`public manifest unavailable for ${name}@${version} (HTTP ${response?.status ?? 'unknown'})`);
156
- let manifest;
157
- try {
158
- manifest = await response.json();
159
- } catch {
160
- throw new Error(`public manifest was not valid JSON for ${name}@${version}`);
161
- }
162
- return assertManifest(manifest, name, version);
163
- }
164
-
165
- function dshReferences(manifest) {
166
- return [
167
- ...Object.entries(manifest.dependencies ?? {}),
168
- ...Object.entries(manifest.optionalDependencies ?? {}),
169
- ...Object.entries(manifest.peerDependencies ?? {}),
170
- ].filter(([name]) => isDshPackage(name));
171
- }
172
-
173
- function assertCrossCohortRanges(manifest, label) {
174
- const references = dshReferences(manifest);
175
- for (const [name, range] of references) {
176
- if (!satisfiesCohortRange(supportedDshVersion, range)) {
177
- throw new Error(`${label} has incompatible ${name} range ${JSON.stringify(range)} for ${supportedDshVersion}`);
178
- }
179
- }
180
- return references.length;
181
- }
182
-
183
- export async function auditOfficialDshCohort({
184
- candidateManifest,
185
- expectedCandidateVersion,
186
- registryUrl = registry,
187
- fetchManifest = (name, version) => fetchPublicManifest(name, version, { registryUrl }),
188
- } = {}) {
189
- if (!candidateManifest || typeof candidateManifest !== 'object') throw new Error('candidate package manifest is missing');
190
- if (typeof expectedCandidateVersion !== 'string' || expectedCandidateVersion.length === 0) {
191
- throw new Error('expectedCandidateVersion is required (derive it with readCandidateVersion)');
192
- }
193
- if (candidateManifest.version !== expectedCandidateVersion) {
194
- throw new Error(`package.json must be ${expectedCandidateVersion}`);
195
- }
196
-
197
- const directPeers = Object.entries(candidateManifest.peerDependencies ?? {})
198
- .filter(([name]) => isDshPackage(name));
199
- if (directPeers.length === 0 || directPeers.length > MAX_DIRECT_PEERS) {
200
- throw new Error(`candidate DSH peer count is outside the bounded audit limit: ${directPeers.length}`);
201
- }
202
- for (const [name, range] of directPeers) {
203
- if (range !== supportedDshVersion) {
204
- throw new Error(`candidate peer ${name} must pin exact cohort ${supportedDshVersion}, got ${JSON.stringify(range)}`);
205
- }
206
- }
207
-
208
- const officialManifest = assertManifest(
209
- await fetchManifest(DSH_PACKAGE, supportedDshVersion),
210
- DSH_PACKAGE,
211
- supportedDshVersion,
212
- );
213
- const manifests = [officialManifest];
214
- let crossCohortChecks = assertCrossCohortRanges(officialManifest, `${DSH_PACKAGE}@${supportedDshVersion}`);
215
-
216
- for (const [name] of directPeers) {
217
- const manifest = assertManifest(await fetchManifest(name, supportedDshVersion), name, supportedDshVersion);
218
- manifests.push(manifest);
219
- crossCohortChecks += assertCrossCohortRanges(manifest, `${name}@${supportedDshVersion}`);
220
- }
221
-
222
- return {
223
- marker: 'PASS',
224
- candidate: expectedCandidateVersion,
225
- officialDsh: supportedDshVersion,
226
- directPeerCount: directPeers.length,
227
- manifestCount: manifests.length,
228
- crossCohortChecks,
229
- };
230
- }
231
-
232
- function run(args, cwd = root) {
233
- const npmInvocation = resolveNpmInvocation();
234
- const result = spawnSync(npmInvocation.command, [...npmInvocation.argsPrefix, ...args], {
235
- cwd,
236
- encoding: 'utf8',
237
- shell: false,
238
- windowsHide: true,
239
- });
240
- if (result.error) throw result.error;
241
- return {
242
- status: result.status ?? 1,
243
- stdout: result.stdout ?? '',
244
- stderr: result.stderr ?? '',
245
- };
246
- }
247
-
248
- function fail(label, result) {
249
- const detail = `${result.stdout}\n${result.stderr}`.trim().replace(/\s+/g, ' ').slice(0, 800);
250
- throw new Error(`${label} failed (exit ${result.status}): ${detail}`);
251
- }
252
-
253
- export async function assertInstalled(prefix, label, expectedVersion) {
254
- const packageRoot = path.join(prefix, 'node_modules', '@ran-sh', 'dsh-crew');
255
- const packageJson = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
256
- const runtimeSource = await readFile(path.join(packageRoot, 'src', 'runtime-identity.mjs'), 'utf8');
257
- const runtimeVersion = runtimeSource.match(/RUNTIME_VERSION\s*=\s*'([^']+)'/)?.[1];
258
- const entryExists = await readFile(path.join(packageRoot, 'src', 'hub', 'entry.mjs')).then(() => true, () => false);
259
- const clientExists = await readFile(path.join(packageRoot, 'lib', 'client.js')).then(() => true, () => false);
260
- if (packageJson.version !== expectedVersion || runtimeVersion !== expectedVersion || !entryExists || !clientExists) {
261
- throw new Error(`${label} did not install the expected ${expectedVersion} package/runtime entries`);
262
- }
263
- }
264
-
265
- async function main() {
266
- const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'dsh-crew-install-verify-'));
267
- const paths = {
268
- pack: await mkdtemp(path.join(tempRoot, 'pack-')),
269
- standalone: await mkdtemp(path.join(tempRoot, 'standalone-')),
270
- };
271
-
272
- try {
273
- const packageJson = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));
274
- const candidateVersion = await readCandidateVersion();
275
- if (packageJson.version !== candidateVersion) throw new Error(`package.json must be ${candidateVersion}`);
276
-
277
- const packed = run(['pack', '--json', '--pack-destination', paths.pack]);
278
- if (packed.status !== 0) fail('npm pack', packed);
279
- const packInfo = JSON.parse(packed.stdout)[0];
280
- const tarball = path.join(paths.pack, packInfo.filename);
281
-
282
- const standalone = run([
283
- 'install', '--prefix', paths.standalone, '--no-save', '--package-lock=false', '--ignore-scripts', '--no-audit', '--no-fund',
284
- '--registry', registry, tarball,
285
- ]);
286
- if (standalone.status !== 0) fail('plain npm candidate install', standalone);
287
- await assertInstalled(paths.standalone, 'standalone candidate', candidateVersion);
288
-
289
- let officialMarker = 'not-run';
290
- if (verifyOfficialDsh) {
291
- const audit = await auditOfficialDshCohort({
292
- candidateManifest: packageJson,
293
- expectedCandidateVersion: candidateVersion,
294
- registryUrl: registry,
295
- });
296
- officialMarker = `${supportedDshVersion}:manifest-audit`;
297
- console.log(`DSH_COHORT_AUDIT=PASS official_dsh=${audit.officialDsh} direct_peers=${audit.directPeerCount} manifests=${audit.manifestCount} cross_cohort_checks=${audit.crossCohortChecks}`);
298
- }
299
-
300
- console.log(`NPM_INSTALL_CONTRACT=PASS candidate=${candidateVersion} official_dsh=${officialMarker}`);
301
- } finally {
302
- await rm(tempRoot, { recursive: true, force: true });
303
- }
304
- }
305
-
306
- if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
307
- main().catch((error) => {
308
- console.error(error instanceof Error ? error.message : String(error));
309
- process.exitCode = 1;
310
- });
311
- }
1
+ #!/usr/bin/env node
2
+
3
+ // Regression gate for the published-package peer contract.
4
+ // This intentionally uses npm's default resolver for the candidate install:
5
+ // no peer-resolution bypass or equivalent override is permitted here.
6
+ //
7
+ // The official DSH check is deliberately bounded. It audits authoritative
8
+ // public registry manifests and cross-cohort ranges instead of materializing
9
+ // or fully resolving the very large official DSH dependency graph.
10
+
11
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
12
+ import { existsSync } from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { spawnSync } from 'node:child_process';
16
+ import { fileURLToPath } from 'node:url';
17
+ import { TARGET_DSH_VERSION } from '../src/dsh-cohort.mjs';
18
+
19
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
20
+ const registry = process.env.NPM_REGISTRY ?? 'https://registry.npmjs.org/';
21
+ export const supportedDshVersion = TARGET_DSH_VERSION;
22
+ const verifyOfficialDsh = process.argv.includes('--with-official-dsh');
23
+ const DSH_PACKAGE = '@deepseek-ai/dsh';
24
+ const DSH_PREFIX = '@deepseek-ai/dsh-';
25
+ const MAX_DIRECT_PEERS = 64;
26
+
27
+ export function resolveNpmInvocation({
28
+ platform = process.platform,
29
+ nodePath = process.execPath,
30
+ fileExists = existsSync,
31
+ } = {}) {
32
+ if (platform !== 'win32') return { command: 'npm', argsPrefix: [] };
33
+ const npmCli = path.join(path.dirname(nodePath), 'node_modules', 'npm', 'bin', 'npm-cli.js');
34
+ if (!fileExists(npmCli)) throw new Error(`npm CLI was not found beside Node.js: ${npmCli}`);
35
+ return { command: nodePath, argsPrefix: [npmCli] };
36
+ }
37
+
38
+
39
+ /**
40
+ * The candidate version is derived from the candidate package manifest at the
41
+ * checkout root instead of a hard-coded release literal, so the verifier never
42
+ * needs a source edit for the next candidate version. The audit guard still
43
+ * requires the passed-in manifest to match this authoritative value.
44
+ */
45
+ export async function readCandidateVersion({ rootDir = root, readFileImpl = readFile } = {}) {
46
+ const packageJson = await readFileImpl(path.join(rootDir, 'package.json'), 'utf8');
47
+ return JSON.parse(packageJson).version;
48
+ }
49
+
50
+ function isDshPackage(name) {
51
+ return name === DSH_PACKAGE || name.startsWith(DSH_PREFIX);
52
+ }
53
+
54
+ function parseVersion(value) {
55
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);
56
+ if (!match) return null;
57
+ return {
58
+ major: Number(match[1]),
59
+ minor: Number(match[2]),
60
+ patch: Number(match[3]),
61
+ prerelease: match[4] ? match[4].split('.') : [],
62
+ };
63
+ }
64
+
65
+ function compareVersions(left, right) {
66
+ for (const key of ['major', 'minor', 'patch']) {
67
+ if (left[key] !== right[key]) return left[key] > right[key] ? 1 : -1;
68
+ }
69
+ if (left.prerelease.length === 0 && right.prerelease.length === 0) return 0;
70
+ if (left.prerelease.length === 0) return 1;
71
+ if (right.prerelease.length === 0) return -1;
72
+ const length = Math.max(left.prerelease.length, right.prerelease.length);
73
+ for (let index = 0; index < length; index += 1) {
74
+ const a = left.prerelease[index];
75
+ const b = right.prerelease[index];
76
+ if (a === undefined) return -1;
77
+ if (b === undefined) return 1;
78
+ if (a === b) continue;
79
+ const aNumber = /^\d+$/.test(a);
80
+ const bNumber = /^\d+$/.test(b);
81
+ if (aNumber && bNumber) return Number(a) > Number(b) ? 1 : -1;
82
+ if (aNumber !== bNumber) return aNumber ? -1 : 1;
83
+ return a > b ? 1 : -1;
84
+ }
85
+ return 0;
86
+ }
87
+
88
+ function upperBoundForCaret(version) {
89
+ if (version.major > 0) return { major: version.major + 1, minor: 0, patch: 0, prerelease: [] };
90
+ if (version.minor > 0) return { major: 0, minor: version.minor + 1, patch: 0, prerelease: [] };
91
+ return { major: 0, minor: 0, patch: version.patch + 1, prerelease: [] };
92
+ }
93
+
94
+ function upperBoundForTilde(version) {
95
+ return { major: version.major, minor: version.minor + 1, patch: 0, prerelease: [] };
96
+ }
97
+
98
+ function satisfiesComparator(version, operator, expected) {
99
+ const comparison = compareVersions(version, expected);
100
+ if (operator === '>') return comparison > 0;
101
+ if (operator === '>=') return comparison >= 0;
102
+ if (operator === '<') return comparison < 0;
103
+ if (operator === '<=') return comparison <= 0;
104
+ return comparison === 0;
105
+ }
106
+
107
+ function satisfiesAlternative(version, alternative) {
108
+ const normalized = alternative.trim();
109
+ if (!normalized || /[*xX]|workspace:|^npm:|^file:|^git:/.test(normalized)) return false;
110
+ const tokens = normalized.replace(/,/g, ' ').split(/\s+/).filter(Boolean);
111
+ return tokens.every((token) => {
112
+ const prefix = /^(\^|~|>=|<=|>|<|=)/.exec(token)?.[1] ?? '';
113
+ const raw = prefix ? token.slice(prefix.length) : token;
114
+ const expected = parseVersion(raw);
115
+ if (!expected) return false;
116
+ if (prefix === '^') {
117
+ return compareVersions(version, expected) >= 0 && compareVersions(version, upperBoundForCaret(expected)) < 0;
118
+ }
119
+ if (prefix === '~') {
120
+ return compareVersions(version, expected) >= 0 && compareVersions(version, upperBoundForTilde(expected)) < 0;
121
+ }
122
+ return satisfiesComparator(version, prefix, expected);
123
+ });
124
+ }
125
+
126
+ export function satisfiesCohortRange(versionString, range) {
127
+ const version = parseVersion(versionString);
128
+ if (!version || typeof range !== 'string') return false;
129
+ return range.split(/\s*\|\|\s*/).some((alternative) => satisfiesAlternative(version, alternative));
130
+ }
131
+
132
+ function assertManifest(manifest, expectedName, expectedVersion) {
133
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
134
+ throw new Error(`invalid registry manifest for ${expectedName}@${expectedVersion}`);
135
+ }
136
+ if (manifest.name !== expectedName || manifest.version !== expectedVersion) {
137
+ throw new Error(`registry manifest identity mismatch for ${expectedName}@${expectedVersion}`);
138
+ }
139
+ return manifest;
140
+ }
141
+
142
+ function manifestUrl(registryUrl, name, version) {
143
+ const encodedName = name.startsWith('@') ? name.replace('/', '%2f') : encodeURIComponent(name);
144
+ return `${registryUrl.replace(/\/+$/, '')}/${encodedName}/${encodeURIComponent(version)}`;
145
+ }
146
+
147
+ export async function fetchPublicManifest(name, version, {
148
+ registryUrl = registry,
149
+ fetchImpl = globalThis.fetch,
150
+ } = {}) {
151
+ if (typeof fetchImpl !== 'function') throw new Error('global fetch is unavailable');
152
+ const response = await fetchImpl(manifestUrl(registryUrl, name, version), {
153
+ headers: { accept: 'application/json', 'user-agent': 'dsh-crew-cohort-audit' },
154
+ });
155
+ if (!response?.ok) throw new Error(`public manifest unavailable for ${name}@${version} (HTTP ${response?.status ?? 'unknown'})`);
156
+ let manifest;
157
+ try {
158
+ manifest = await response.json();
159
+ } catch {
160
+ throw new Error(`public manifest was not valid JSON for ${name}@${version}`);
161
+ }
162
+ return assertManifest(manifest, name, version);
163
+ }
164
+
165
+ function dshReferences(manifest) {
166
+ return [
167
+ ...Object.entries(manifest.dependencies ?? {}),
168
+ ...Object.entries(manifest.optionalDependencies ?? {}),
169
+ ...Object.entries(manifest.peerDependencies ?? {}),
170
+ ].filter(([name]) => isDshPackage(name));
171
+ }
172
+
173
+ function assertCrossCohortRanges(manifest, label) {
174
+ const references = dshReferences(manifest);
175
+ for (const [name, range] of references) {
176
+ if (!satisfiesCohortRange(supportedDshVersion, range)) {
177
+ throw new Error(`${label} has incompatible ${name} range ${JSON.stringify(range)} for ${supportedDshVersion}`);
178
+ }
179
+ }
180
+ return references.length;
181
+ }
182
+
183
+ export async function auditOfficialDshCohort({
184
+ candidateManifest,
185
+ expectedCandidateVersion,
186
+ registryUrl = registry,
187
+ fetchManifest = (name, version) => fetchPublicManifest(name, version, { registryUrl }),
188
+ } = {}) {
189
+ if (!candidateManifest || typeof candidateManifest !== 'object') throw new Error('candidate package manifest is missing');
190
+ if (typeof expectedCandidateVersion !== 'string' || expectedCandidateVersion.length === 0) {
191
+ throw new Error('expectedCandidateVersion is required (derive it with readCandidateVersion)');
192
+ }
193
+ if (candidateManifest.version !== expectedCandidateVersion) {
194
+ throw new Error(`package.json must be ${expectedCandidateVersion}`);
195
+ }
196
+
197
+ const directPeers = Object.entries(candidateManifest.peerDependencies ?? {})
198
+ .filter(([name]) => isDshPackage(name));
199
+ if (directPeers.length === 0 || directPeers.length > MAX_DIRECT_PEERS) {
200
+ throw new Error(`candidate DSH peer count is outside the bounded audit limit: ${directPeers.length}`);
201
+ }
202
+ for (const [name, range] of directPeers) {
203
+ if (range !== supportedDshVersion) {
204
+ throw new Error(`candidate peer ${name} must pin exact cohort ${supportedDshVersion}, got ${JSON.stringify(range)}`);
205
+ }
206
+ }
207
+
208
+ const officialManifest = assertManifest(
209
+ await fetchManifest(DSH_PACKAGE, supportedDshVersion),
210
+ DSH_PACKAGE,
211
+ supportedDshVersion,
212
+ );
213
+ const manifests = [officialManifest];
214
+ let crossCohortChecks = assertCrossCohortRanges(officialManifest, `${DSH_PACKAGE}@${supportedDshVersion}`);
215
+
216
+ for (const [name] of directPeers) {
217
+ const manifest = assertManifest(await fetchManifest(name, supportedDshVersion), name, supportedDshVersion);
218
+ manifests.push(manifest);
219
+ crossCohortChecks += assertCrossCohortRanges(manifest, `${name}@${supportedDshVersion}`);
220
+ }
221
+
222
+ return {
223
+ marker: 'PASS',
224
+ candidate: expectedCandidateVersion,
225
+ officialDsh: supportedDshVersion,
226
+ directPeerCount: directPeers.length,
227
+ manifestCount: manifests.length,
228
+ crossCohortChecks,
229
+ };
230
+ }
231
+
232
+ function run(args, cwd = root) {
233
+ const npmInvocation = resolveNpmInvocation();
234
+ const result = spawnSync(npmInvocation.command, [...npmInvocation.argsPrefix, ...args], {
235
+ cwd,
236
+ encoding: 'utf8',
237
+ shell: false,
238
+ windowsHide: true,
239
+ });
240
+ if (result.error) throw result.error;
241
+ return {
242
+ status: result.status ?? 1,
243
+ stdout: result.stdout ?? '',
244
+ stderr: result.stderr ?? '',
245
+ };
246
+ }
247
+
248
+ function fail(label, result) {
249
+ const detail = `${result.stdout}\n${result.stderr}`.trim().replace(/\s+/g, ' ').slice(0, 800);
250
+ throw new Error(`${label} failed (exit ${result.status}): ${detail}`);
251
+ }
252
+
253
+ export async function assertInstalled(prefix, label, expectedVersion) {
254
+ const packageRoot = path.join(prefix, 'node_modules', '@ran-sh', 'dsh-crew');
255
+ const packageJson = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
256
+ const runtimeSource = await readFile(path.join(packageRoot, 'src', 'runtime-identity.mjs'), 'utf8');
257
+ const runtimeVersion = runtimeSource.match(/RUNTIME_VERSION\s*=\s*'([^']+)'/)?.[1];
258
+ const entryExists = await readFile(path.join(packageRoot, 'src', 'hub', 'entry.mjs')).then(() => true, () => false);
259
+ const clientExists = await readFile(path.join(packageRoot, 'lib', 'client.js')).then(() => true, () => false);
260
+ if (packageJson.version !== expectedVersion || runtimeVersion !== expectedVersion || !entryExists || !clientExists) {
261
+ throw new Error(`${label} did not install the expected ${expectedVersion} package/runtime entries`);
262
+ }
263
+ }
264
+
265
+ async function main() {
266
+ const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'dsh-crew-install-verify-'));
267
+ const paths = {
268
+ pack: await mkdtemp(path.join(tempRoot, 'pack-')),
269
+ standalone: await mkdtemp(path.join(tempRoot, 'standalone-')),
270
+ };
271
+
272
+ try {
273
+ const packageJson = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));
274
+ const candidateVersion = await readCandidateVersion();
275
+ if (packageJson.version !== candidateVersion) throw new Error(`package.json must be ${candidateVersion}`);
276
+
277
+ const packed = run(['pack', '--json', '--pack-destination', paths.pack]);
278
+ if (packed.status !== 0) fail('npm pack', packed);
279
+ const packInfo = JSON.parse(packed.stdout)[0];
280
+ const tarball = path.join(paths.pack, packInfo.filename);
281
+
282
+ const standalone = run([
283
+ 'install', '--prefix', paths.standalone, '--no-save', '--package-lock=false', '--ignore-scripts', '--no-audit', '--no-fund',
284
+ '--registry', registry, tarball,
285
+ ]);
286
+ if (standalone.status !== 0) fail('plain npm candidate install', standalone);
287
+ await assertInstalled(paths.standalone, 'standalone candidate', candidateVersion);
288
+
289
+ let officialMarker = 'not-run';
290
+ if (verifyOfficialDsh) {
291
+ const audit = await auditOfficialDshCohort({
292
+ candidateManifest: packageJson,
293
+ expectedCandidateVersion: candidateVersion,
294
+ registryUrl: registry,
295
+ });
296
+ officialMarker = `${supportedDshVersion}:manifest-audit`;
297
+ console.log(`DSH_COHORT_AUDIT=PASS official_dsh=${audit.officialDsh} direct_peers=${audit.directPeerCount} manifests=${audit.manifestCount} cross_cohort_checks=${audit.crossCohortChecks}`);
298
+ }
299
+
300
+ console.log(`NPM_INSTALL_CONTRACT=PASS candidate=${candidateVersion} official_dsh=${officialMarker}`);
301
+ } finally {
302
+ await rm(tempRoot, { recursive: true, force: true });
303
+ }
304
+ }
305
+
306
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
307
+ main().catch((error) => {
308
+ console.error(error instanceof Error ? error.message : String(error));
309
+ process.exitCode = 1;
310
+ });
311
+ }