@dsmm/dsmm 0.2.2 → 0.3.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.
- package/README.md +8 -10
- package/cordis.patch.yml +14 -0
- package/docs/agent-presets.md +4 -4
- package/docs/compatibility.md +19 -24
- package/docs/deferred-native-approval-risk.md +2 -2
- package/docs/model-routing.md +3 -3
- package/docs/profiles.md +1 -1
- package/docs/releasing.md +46 -6
- package/docs/settings-status.md +2 -2
- package/lib/agent-registry.d.ts +36 -0
- package/lib/agent-registry.js +75 -0
- package/lib/child-admission.d.ts +0 -2
- package/lib/child-admission.js +13 -24
- package/lib/child-capture.d.ts +5 -1
- package/lib/child-capture.js +7 -5
- package/lib/client/children-locales.d.ts +13 -13
- package/lib/client/deployment-controller.js +1 -1
- package/lib/client.js +3 -3
- package/lib/delivery-authority.d.ts +18 -3
- package/lib/delivery-authority.js +149 -12
- package/lib/index.d.ts +2 -2
- package/lib/index.js +13 -26
- package/lib/native-child-evidence.d.ts +1 -3
- package/lib/native-child-evidence.js +0 -29
- package/lib/permission-rpc.js +3 -3
- package/lib/profile-rpc.js +6 -4
- package/lib/profile-store.js +2 -2
- package/lib/role-control-rpc.js +12 -8
- package/lib/role-invocation.d.ts +1 -1
- package/lib/role-policy.d.ts +1 -4
- package/lib/role-policy.js +24 -41
- package/lib/role-providers.d.ts +1 -1
- package/lib/role-providers.js +15 -55
- package/lib/role-runs.d.ts +17 -14
- package/lib/role-runs.js +45 -14
- package/lib/role-subagents.js +16 -6
- package/lib/runtime-integration.d.ts +4 -35
- package/lib/runtime-integration.js +38 -120
- package/lib/session-persistence.d.ts +2 -1
- package/lib/session-persistence.js +1 -1
- package/lib/session-scope.js +4 -1
- package/lib/subagent-runtime.d.ts +19 -7
- package/lib/subagent-runtime.js +141 -15
- package/package.json +110 -100
- package/lib/legacy-child-policy.d.ts +0 -51
- package/lib/legacy-child-policy.js +0 -123
- package/lib/legacy-read-composition.d.ts +0 -20
- package/lib/legacy-read-composition.js +0 -144
- package/lib/legacy-read-contracts.d.ts +0 -157
- package/lib/legacy-read-contracts.js +0 -39
- package/lib/legacy-read-host.d.ts +0 -19
- package/lib/legacy-read-host.js +0 -67
- package/lib/legacy-read-integration.d.ts +0 -121
- package/lib/legacy-read-integration.js +0 -522
- package/lib/legacy-read-proxy.d.ts +0 -26
- package/lib/legacy-read-proxy.js +0 -237
- package/scripts/cold-profile-composition.mjs +0 -329
- package/scripts/cold-profile-sources.mjs +0 -238
- package/scripts/migrate-cold-profile.mjs +0 -315
- package/scripts/repair-session-log.mjs +0 -476
- package/scripts/session-repair-native-verifier.mjs +0 -367
|
@@ -1,238 +0,0 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
import { spawnSync } from "node:child_process";
|
|
3
|
-
import { lstatSync, readFileSync, realpathSync } from "node:fs";
|
|
4
|
-
import { createRequire } from "node:module";
|
|
5
|
-
import { dirname, isAbsolute, join, parse, resolve } from "node:path";
|
|
6
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
|
-
import { findNodeAtLocation, parseTree } from "jsonc-parser";
|
|
8
|
-
|
|
9
|
-
export class ColdProfileMigrationError extends Error {
|
|
10
|
-
constructor(code) {
|
|
11
|
-
super(`Cold-profile migration refused: ${code}`);
|
|
12
|
-
this.name = "ColdProfileMigrationError";
|
|
13
|
-
this.code = code;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export const refuse = code => { throw new ColdProfileMigrationError(code); };
|
|
18
|
-
export const digest = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
19
|
-
|
|
20
|
-
/** Writes never follow a profile, Home, or output directory symlink/junction. */
|
|
21
|
-
export function plainPath(filename, { missing = false } = {}) {
|
|
22
|
-
if (!isAbsolute(filename)) refuse("ABSOLUTE_PATH_REQUIRED");
|
|
23
|
-
let cursor = resolve(filename);
|
|
24
|
-
while (cursor !== parse(cursor).root) {
|
|
25
|
-
try {
|
|
26
|
-
if (lstatSync(cursor).isSymbolicLink()) refuse("LINKED_SOURCE_OR_TARGET");
|
|
27
|
-
} catch (error) {
|
|
28
|
-
if (error.code !== "ENOENT" || !missing) throw error;
|
|
29
|
-
}
|
|
30
|
-
cursor = dirname(cursor);
|
|
31
|
-
}
|
|
32
|
-
return resolve(filename);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** One necessary source readset, held in memory; source contents are never receipts. */
|
|
36
|
-
export class SourceReadset {
|
|
37
|
-
files = new Map();
|
|
38
|
-
capabilities = new Map();
|
|
39
|
-
record(entry) {
|
|
40
|
-
const previous = this.files.get(entry.filename);
|
|
41
|
-
if (previous && JSON.stringify(previous) !== JSON.stringify(entry)) refuse("SOURCE_CONFLICT");
|
|
42
|
-
this.files.set(entry.filename, entry);
|
|
43
|
-
}
|
|
44
|
-
read(filename, { optional = false, packageSource = false } = {}) {
|
|
45
|
-
filename = resolve(filename);
|
|
46
|
-
if (!packageSource) plainPath(filename, { missing: optional });
|
|
47
|
-
let bytes = null;
|
|
48
|
-
let canonical = null;
|
|
49
|
-
try {
|
|
50
|
-
canonical = realpathSync(filename);
|
|
51
|
-
if (!lstatSync(canonical).isFile()) refuse("SOURCE_NOT_FILE");
|
|
52
|
-
bytes = readFileSync(filename);
|
|
53
|
-
} catch (error) {
|
|
54
|
-
if (error.code !== "ENOENT" || !optional) throw error;
|
|
55
|
-
}
|
|
56
|
-
this.record({ kind: "source", filename, canonical, hash: bytes === null ? null : digest(bytes) });
|
|
57
|
-
return bytes?.toString("utf8") ?? null;
|
|
58
|
-
}
|
|
59
|
-
package(filename, { packageSource = true } = {}) {
|
|
60
|
-
filename = resolve(filename);
|
|
61
|
-
if (!packageSource) plainPath(filename);
|
|
62
|
-
const canonical = realpathSync(filename);
|
|
63
|
-
const manifest = jsonDocument(readFileSync(filename, "utf8")).value;
|
|
64
|
-
this.record({ kind: "package", filename, canonical, hash: packageIdentity(manifest) });
|
|
65
|
-
return manifest;
|
|
66
|
-
}
|
|
67
|
-
module(filename, { packageSource = false } = {}) {
|
|
68
|
-
filename = resolve(filename);
|
|
69
|
-
if (!packageSource) plainPath(filename);
|
|
70
|
-
const canonical = realpathSync(filename);
|
|
71
|
-
if (!lstatSync(canonical).isFile()) refuse("UNRESOLVED_ENTRY_MODULE");
|
|
72
|
-
this.record({ kind: "module", filename, canonical });
|
|
73
|
-
}
|
|
74
|
-
dormantCapability(options, baseURL, specifier) {
|
|
75
|
-
const request = { installAnchor: options.installAnchor, profileDir: options.profileDir, home: options.home, baseURL, specifier };
|
|
76
|
-
const selected = freshCapability(request);
|
|
77
|
-
if (!selected.resolved) return false;
|
|
78
|
-
const key = JSON.stringify(request);
|
|
79
|
-
const previous = this.capabilities.get(key);
|
|
80
|
-
if (previous && JSON.stringify(previous.selected) !== JSON.stringify(selected)) refuse("SOURCE_CONFLICT");
|
|
81
|
-
this.capabilities.set(key, { request, selected });
|
|
82
|
-
return true;
|
|
83
|
-
}
|
|
84
|
-
assertCurrent() {
|
|
85
|
-
for (const entry of this.files.values()) {
|
|
86
|
-
let canonical = null;
|
|
87
|
-
let hash = null;
|
|
88
|
-
try {
|
|
89
|
-
canonical = realpathSync(entry.filename);
|
|
90
|
-
if (!lstatSync(canonical).isFile()) refuse("SOURCE_CONFLICT");
|
|
91
|
-
if (entry.kind === "source") hash = digest(readFileSync(entry.filename));
|
|
92
|
-
else if (entry.kind === "package") hash = packageIdentity(jsonDocument(readFileSync(entry.filename, "utf8")).value);
|
|
93
|
-
} catch (error) {
|
|
94
|
-
if (error.code !== "ENOENT") throw error;
|
|
95
|
-
}
|
|
96
|
-
if (canonical !== entry.canonical || (entry.kind !== "module" && hash !== entry.hash)) refuse("SOURCE_CONFLICT");
|
|
97
|
-
}
|
|
98
|
-
for (const { request, selected } of this.capabilities.values()) {
|
|
99
|
-
if (JSON.stringify(freshCapability(request)) !== JSON.stringify(selected)) refuse("SOURCE_CONFLICT");
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
revision(context) {
|
|
103
|
-
const files = [...this.files.values()].sort((a, b) => a.filename.localeCompare(b.filename));
|
|
104
|
-
const capabilities = [...this.capabilities.values()].sort((a, b) => JSON.stringify(a.request).localeCompare(JSON.stringify(b.request)));
|
|
105
|
-
return digest(JSON.stringify({ context, files, ...(capabilities.length ? { capabilities } : {}) }));
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
const capabilitySpecifiers = new Set([
|
|
110
|
-
"@deepseek-ai/dsh-ptc-runtime-node/package.json",
|
|
111
|
-
"@deepseek-ai/dsh-agent-preset-registry/package.json",
|
|
112
|
-
]);
|
|
113
|
-
|
|
114
|
-
/** A new process discards Node's manifest/path caches and the SDK's ResolutionRouter caches. */
|
|
115
|
-
function freshCapability(request) {
|
|
116
|
-
if (!capabilitySpecifiers.has(request.specifier)) refuse("DORMANT_RESOLUTION_UNAVAILABLE");
|
|
117
|
-
// Preloaded hooks can change native routing or execute user code in the probe.
|
|
118
|
-
if (process.env.NODE_OPTIONS?.trim() || process.execArgv.some(arg => /^(?:--(?:import|require|loader|experimental-loader)(?:=|$)|-r)/.test(arg))) refuse("DORMANT_RESOLUTION_UNAVAILABLE");
|
|
119
|
-
const flags = [];
|
|
120
|
-
for (let i = 0; i < process.execArgv.length; i++) {
|
|
121
|
-
const arg = process.execArgv[i];
|
|
122
|
-
if (/^(?:--conditions=|--preserve-symlinks$|--preserve-symlinks-main$|--no-addons$|--no-experimental-require-module$)/.test(arg)) flags.push(arg);
|
|
123
|
-
else if (arg === "--conditions" || arg === "-C") flags.push(arg, process.execArgv[++i]);
|
|
124
|
-
}
|
|
125
|
-
const child = spawnSync(process.execPath, [...flags, fileURLToPath(import.meta.url), "--dsmm-dormant-resolution"], {
|
|
126
|
-
input: JSON.stringify(request), encoding: "utf8", timeout: 30_000, maxBuffer: 1024 * 1024,
|
|
127
|
-
env: { ...process.env, NODE_OPTIONS: "" }, windowsHide: true,
|
|
128
|
-
});
|
|
129
|
-
if (child.error || child.status !== 0) refuse("DORMANT_RESOLUTION_UNAVAILABLE");
|
|
130
|
-
let selected;
|
|
131
|
-
try { selected = JSON.parse(child.stdout); } catch { refuse("DORMANT_RESOLUTION_UNAVAILABLE"); }
|
|
132
|
-
if (typeof selected?.resolved !== "boolean") refuse("DORMANT_RESOLUTION_UNAVAILABLE");
|
|
133
|
-
return selected;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/** Uses the SDK's actual CJS interception, without mounting entries or importing capability code. */
|
|
137
|
-
async function resolveCapability(request) {
|
|
138
|
-
if (!capabilitySpecifiers.has(request.specifier)) refuse("DORMANT_RESOLUTION_UNAVAILABLE");
|
|
139
|
-
const native = createRequire(request.installAnchor);
|
|
140
|
-
const bootPath = native.resolve("@deepseek-ai/dsh-app-boot");
|
|
141
|
-
const boot = await import(pathToFileURL(bootPath).href);
|
|
142
|
-
if (boot.getDshRuntimeVersion() !== "0.2.0-rc.2") refuse("UNSUPPORTED_SDK");
|
|
143
|
-
const { Context } = await import(pathToFileURL(createRequire(bootPath).resolve("@deepseek-ai/cordis")).href);
|
|
144
|
-
const profile = boot.loadProfileDirectory("dsmm-cold-profile", request.profileDir, request.installAnchor);
|
|
145
|
-
if (profile.skippedBundles.length) refuse("SKIPPED_BUNDLE");
|
|
146
|
-
const resolution = await boot.createRuntimeResolution({ installAnchor: request.installAnchor, profile, home: request.home });
|
|
147
|
-
const ctx = new Context();
|
|
148
|
-
try {
|
|
149
|
-
await ctx.plugin(boot.PluginPackages, { resolution });
|
|
150
|
-
if (!ctx.get("pluginPackages")?.interception) refuse("DORMANT_RESOLUTION_UNAVAILABLE");
|
|
151
|
-
const require = createRequire(request.baseURL);
|
|
152
|
-
let target;
|
|
153
|
-
try { target = require.resolve(request.specifier); } catch { return { resolved: false }; }
|
|
154
|
-
const name = request.specifier.slice(0, -"/package.json".length);
|
|
155
|
-
const manifests = new Set([
|
|
156
|
-
target,
|
|
157
|
-
...(require.resolve.paths(name) ?? []).map(searchPath => join(searchPath, name, "package.json")),
|
|
158
|
-
...resolution.entries.filter(entry => entry.name === name).map(entry => join(entry.packageDir, "package.json")),
|
|
159
|
-
]);
|
|
160
|
-
const packages = [...manifests].sort().map(filename => {
|
|
161
|
-
try {
|
|
162
|
-
const canonical = realpathSync(filename);
|
|
163
|
-
const hash = packageIdentity(jsonDocument(readFileSync(filename, "utf8")).value);
|
|
164
|
-
return { filename, canonical, hash };
|
|
165
|
-
} catch (error) {
|
|
166
|
-
if (error.code !== "ENOENT" && error.code !== "ENOTDIR") throw error;
|
|
167
|
-
return { filename, canonical: null, hash: null };
|
|
168
|
-
}
|
|
169
|
-
});
|
|
170
|
-
const canonical = realpathSync(target);
|
|
171
|
-
if (!lstatSync(canonical).isFile()) refuse("DORMANT_RESOLUTION_UNAVAILABLE");
|
|
172
|
-
return { resolved: true, target, canonical, packages };
|
|
173
|
-
} finally {
|
|
174
|
-
await ctx.fiber.dispose();
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
function packageIdentity(manifest) {
|
|
179
|
-
const fields = ["name", "version", "type", "main", "exports", "imports", "dependencies", "peerDependencies", "optionalDependencies"];
|
|
180
|
-
const identity = Object.fromEntries(fields.filter(field => Object.hasOwn(manifest, field)).map(field => [field, manifest[field]]));
|
|
181
|
-
if (manifest.dsh?.bundle !== undefined) identity.bundle = manifest.dsh.bundle;
|
|
182
|
-
return digest(JSON.stringify(identity));
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/** SDK manifests are strict JSON; duplicate properties are refused rather than erased. */
|
|
186
|
-
export function jsonDocument(text) {
|
|
187
|
-
const errors = [];
|
|
188
|
-
const tree = parseTree(text, errors, { disallowComments: true, allowTrailingComma: false });
|
|
189
|
-
if (!tree || errors.length) refuse("INVALID_MANIFEST");
|
|
190
|
-
const visit = node => {
|
|
191
|
-
if (node.type === "object") {
|
|
192
|
-
const names = new Set();
|
|
193
|
-
for (const property of node.children ?? []) {
|
|
194
|
-
const key = property.children[0].value;
|
|
195
|
-
if (names.has(key)) refuse("DUPLICATE_MANIFEST_KEY");
|
|
196
|
-
names.add(key);
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
for (const child of node.children ?? []) visit(child);
|
|
200
|
-
};
|
|
201
|
-
visit(tree);
|
|
202
|
-
return { tree, value: JSON.parse(text) };
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
export function bundleToken(text, slot) {
|
|
206
|
-
const { tree } = jsonDocument(text);
|
|
207
|
-
const node = findNodeAtLocation(tree, ["dsh", "profile", "bundles", slot]);
|
|
208
|
-
if (node?.type !== "string") refuse("INVALID_BUNDLE_SLOT");
|
|
209
|
-
return { offset: node.offset, length: node.length, literal: text.slice(node.offset, node.offset + node.length) };
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
export function replaceBundleToken(text, slot, name) {
|
|
213
|
-
const token = bundleToken(text, slot);
|
|
214
|
-
return text.slice(0, token.offset) + JSON.stringify(name) + text.slice(token.offset + token.length);
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
export async function loadColdProfileSdk(installAnchor) {
|
|
218
|
-
if (!isAbsolute(installAnchor)) refuse("ABSOLUTE_PATH_REQUIRED");
|
|
219
|
-
const require = createRequire(installAnchor);
|
|
220
|
-
const bootPath = require.resolve("@deepseek-ai/dsh-app-boot");
|
|
221
|
-
const includePath = require.resolve("@deepseek-ai/cordis-plugin-include");
|
|
222
|
-
const yamlPath = require.resolve("js-yaml");
|
|
223
|
-
const atomicPath = require.resolve("@deepseek-ai/dsh-atomic-write");
|
|
224
|
-
const exportsPath = createRequire(bootPath).resolve("resolve.exports");
|
|
225
|
-
const [boot, include, yaml, atomic, packageExports] = await Promise.all(
|
|
226
|
-
[bootPath, includePath, yamlPath, atomicPath, exportsPath].map(filename => import(pathToFileURL(filename).href)),
|
|
227
|
-
);
|
|
228
|
-
if (boot.getDshRuntimeVersion() !== "0.2.0-rc.2") refuse("UNSUPPORTED_SDK");
|
|
229
|
-
return { boot, include, yaml, atomic, packageExports, modulePaths: [bootPath, includePath, yamlPath, atomicPath, exportsPath] };
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url) && process.argv[2] === "--dsmm-dormant-resolution") {
|
|
233
|
-
try {
|
|
234
|
-
process.stdout.write(JSON.stringify(await resolveCapability(JSON.parse(readFileSync(0, "utf8")))));
|
|
235
|
-
} catch {
|
|
236
|
-
process.exitCode = 1;
|
|
237
|
-
}
|
|
238
|
-
}
|
|
@@ -1,315 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { lstatSync, readFileSync } from "node:fs";
|
|
3
|
-
import { mkdir, open } from "node:fs/promises";
|
|
4
|
-
import { basename, dirname, isAbsolute, join, parse, resolve } from "node:path";
|
|
5
|
-
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { BASE_BUNDLE, MODULE_REPLACEMENTS, inspectColdComposition } from "./cold-profile-composition.mjs";
|
|
7
|
-
import {
|
|
8
|
-
ColdProfileMigrationError, bundleToken, digest, jsonDocument, loadColdProfileSdk,
|
|
9
|
-
plainPath, refuse, replaceBundleToken,
|
|
10
|
-
} from "./cold-profile-sources.mjs";
|
|
11
|
-
|
|
12
|
-
export { ColdProfileMigrationError, loadColdProfileSdk };
|
|
13
|
-
const RECEIPT = ".dsmm-cold-profile.json";
|
|
14
|
-
const PROJECTION_PREFIX = "@dsmm/cold-base-";
|
|
15
|
-
const ownName = name => typeof name === "string" && /^@dsmm\/cold-base-[0-9a-f-]{36}$/.test(name);
|
|
16
|
-
|
|
17
|
-
function normalizeOptions(input) {
|
|
18
|
-
if (!input || !["dsh-tui", "desktop"].includes(input.target)) refuse("EXPLICIT_TARGET_REQUIRED");
|
|
19
|
-
for (const key of ["profileDir", "installAnchor", "home"]) {
|
|
20
|
-
if (typeof input[key] !== "string" || !isAbsolute(input[key])) refuse("EXPLICIT_ABSOLUTE_SCOPE_REQUIRED");
|
|
21
|
-
}
|
|
22
|
-
const profileDir = plainPath(resolve(input.profileDir));
|
|
23
|
-
const home = plainPath(resolve(input.home));
|
|
24
|
-
if (profileDir === parse(profileDir).root || home === parse(home).root || profileDir === home) refuse("INVALID_DIRECTORY_SCOPE");
|
|
25
|
-
if (!lstatSync(profileDir).isDirectory() || !lstatSync(home).isDirectory()) refuse("INVALID_DIRECTORY_SCOPE");
|
|
26
|
-
const overlays = input.overlays ?? [];
|
|
27
|
-
const sourceRoots = input.sourceRoots ?? [profileDir, home];
|
|
28
|
-
if (!Array.isArray(overlays) || !Array.isArray(sourceRoots) || ![...overlays, ...sourceRoots].every(value => typeof value === "string" && isAbsolute(value))) refuse("EXPLICIT_ABSOLUTE_SCOPE_REQUIRED");
|
|
29
|
-
if (input.rootConfig !== undefined && (typeof input.rootConfig !== "string" || !isAbsolute(input.rootConfig))) refuse("EXPLICIT_ABSOLUTE_SCOPE_REQUIRED");
|
|
30
|
-
if (input.migrateShell !== undefined && typeof input.migrateShell !== "boolean") refuse("INVALID_SHELL_OPTION");
|
|
31
|
-
if (input.migrateSubagent !== undefined && typeof input.migrateSubagent !== "boolean") refuse("INVALID_SUBAGENT_OPTION");
|
|
32
|
-
if (input.migrateSessionPersistence !== undefined && typeof input.migrateSessionPersistence !== "boolean") refuse("INVALID_SESSION_PERSISTENCE_OPTION");
|
|
33
|
-
return {
|
|
34
|
-
target: input.target, profileDir, home, installAnchor: resolve(input.installAnchor),
|
|
35
|
-
overlays: overlays.map(filename => plainPath(resolve(filename))),
|
|
36
|
-
sourceRoots: [...new Set(sourceRoots.map(filename => plainPath(resolve(filename))))],
|
|
37
|
-
migrateShell: input.migrateShell ?? true,
|
|
38
|
-
migrateSubagent: input.migrateSubagent ?? false,
|
|
39
|
-
migrateSessionPersistence: input.migrateSessionPersistence ?? false,
|
|
40
|
-
...(input.rootConfig ? { rootConfig: plainPath(resolve(input.rootConfig)) } : {}),
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function projectionDir(options, name) {
|
|
45
|
-
if (!ownName(name)) refuse("INVALID_PROJECTION_IDENTITY");
|
|
46
|
-
return plainPath(join(options.profileDir, "node_modules", "@dsmm", basename(name)), { missing: true });
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function activeReceipt(options) {
|
|
50
|
-
const text = readFileSync(join(options.profileDir, "package.json"), "utf8");
|
|
51
|
-
const bundles = jsonDocument(text).value.dsh?.profile?.bundles;
|
|
52
|
-
if (!Array.isArray(bundles)) refuse("INVALID_BUNDLES");
|
|
53
|
-
const owned = bundles.filter(name => typeof name === "string" && name.startsWith(PROJECTION_PREFIX));
|
|
54
|
-
if (owned.length === 0) return undefined;
|
|
55
|
-
if (owned.length !== 1 || bundles.includes(BASE_BUNDLE)) refuse("AMBIGUOUS_PROJECTION");
|
|
56
|
-
return readReceipt(options, owned[0]);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
function readReceipt(options, name) {
|
|
60
|
-
const dir = projectionDir(options, name);
|
|
61
|
-
const receiptPath = plainPath(join(dir, RECEIPT));
|
|
62
|
-
const receipt = jsonDocument(readFileSync(receiptPath, "utf8")).value;
|
|
63
|
-
if (receipt.version !== 1 || receipt.projectionName !== name || receipt.profileDir !== options.profileDir ||
|
|
64
|
-
receipt.target !== options.target || receipt.home !== options.home || receipt.installAnchor !== options.installAnchor ||
|
|
65
|
-
receipt.migrateShell !== options.migrateShell || receipt.migrateSubagent !== options.migrateSubagent || !Number.isSafeInteger(receipt.slot) || receipt.slot < 0 ||
|
|
66
|
-
receipt.migrateSessionPersistence !== options.migrateSessionPersistence ||
|
|
67
|
-
!Array.isArray(receipt.changes) || !Array.isArray(receipt.outputs) ||
|
|
68
|
-
receipt.outputs.length !== 2 || receipt.outputs[0].name !== "package.json" || receipt.outputs[1].name !== "cordis.patch.yml" ||
|
|
69
|
-
receipt.originalLiteral === undefined || JSON.parse(receipt.originalLiteral) !== BASE_BUNDLE ||
|
|
70
|
-
![receipt.sourceRevision, receipt.beforeHash, receipt.afterHash, ...receipt.outputs.map(output => output.hash)].every(hash => typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash))) refuse("INVALID_RECEIPT");
|
|
71
|
-
if (receipt.changes.length < 2 || receipt.changes.length > Object.keys(MODULE_REPLACEMENTS).length ||
|
|
72
|
-
new Set(receipt.changes.map(change => change.id)).size !== receipt.changes.length ||
|
|
73
|
-
!receipt.changes.some(change => change.id === "llm" && change.original === "@deepseek-ai/dsh-llm") ||
|
|
74
|
-
!receipt.changes.some(change => change.id === "settings" && change.original === "@deepseek-ai/dsh-settings") ||
|
|
75
|
-
receipt.changes.some(change => change.original === "@deepseek-ai/dsh-subagent") !== options.migrateSubagent ||
|
|
76
|
-
receipt.changes.some(change => change.original === "@deepseek-ai/dsh-subagent" && change.id !== "subagent") ||
|
|
77
|
-
receipt.changes.some(change => change.original === "@deepseek-ai/dsh-session-persistence-jsonl") !== options.migrateSessionPersistence ||
|
|
78
|
-
receipt.changes.some(change => change.original === "@deepseek-ai/dsh-session-persistence-jsonl" && change.id !== "session-persistence-jsonl") ||
|
|
79
|
-
!receipt.changes.every(change => typeof change.id === "string" && Object.hasOwn(MODULE_REPLACEMENTS, change.original) && change.replacement === MODULE_REPLACEMENTS[change.original])) refuse("INVALID_RECEIPT");
|
|
80
|
-
for (const output of receipt.outputs) {
|
|
81
|
-
const filename = plainPath(join(dir, output.name));
|
|
82
|
-
if (digest(readFileSync(filename)) !== output.hash) refuse("OWNED_OUTPUT_CONFLICT");
|
|
83
|
-
}
|
|
84
|
-
return receipt;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
function summary(inspection, receipt) {
|
|
88
|
-
return {
|
|
89
|
-
status: receipt ? "already-applied" : "planned", revision: inspection.revision,
|
|
90
|
-
target: receipt?.target, slot: inspection.slot,
|
|
91
|
-
changes: inspection.changes, nativeToolSelection: inspection.nativeToolSelection,
|
|
92
|
-
...(receipt ? { projectionName: receipt.projectionName } : {}),
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/** Read-only. Returned revision binds all effective composition sources and explicit launch inputs. */
|
|
97
|
-
async function planMigration(input) {
|
|
98
|
-
const options = normalizeOptions(input);
|
|
99
|
-
const sdk = await loadColdProfileSdk(options.installAnchor);
|
|
100
|
-
const receipt = activeReceipt(options);
|
|
101
|
-
const inspection = await inspectColdComposition(options, sdk, { receipt });
|
|
102
|
-
return { ...summary(inspection, receipt), target: options.target };
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
async function safeOperation(operation) {
|
|
106
|
-
try { return await operation(); } catch (error) {
|
|
107
|
-
if (error instanceof ColdProfileMigrationError) throw error;
|
|
108
|
-
throw new ColdProfileMigrationError("SOURCE_OR_IO_FAILURE");
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
export const planColdProfileMigration = input => safeOperation(() => planMigration(input));
|
|
113
|
-
|
|
114
|
-
async function exclusiveFile(filename, text) {
|
|
115
|
-
const file = await open(filename, "wx", 0o600);
|
|
116
|
-
try {
|
|
117
|
-
await file.writeFile(text);
|
|
118
|
-
await file.sync();
|
|
119
|
-
} finally {
|
|
120
|
-
await file.close();
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
function requireRevision(inspection, expectedRevision) {
|
|
125
|
-
if (typeof expectedRevision !== "string" || !/^[a-f0-9]{64}$/.test(expectedRevision)) refuse("EXPECTED_REVISION_REQUIRED");
|
|
126
|
-
if (inspection.revision !== expectedRevision) refuse("SOURCE_CONFLICT");
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
async function prepareProjection(options, sdk, inspection) {
|
|
130
|
-
const projectionName = `${PROJECTION_PREFIX}${randomUUID()}`;
|
|
131
|
-
const dir = projectionDir(options, projectionName);
|
|
132
|
-
const patch = sdk.yaml.dump(inspection.projected, { schema: sdk.include.entryListSchema, noRefs: true, lineWidth: -1 });
|
|
133
|
-
const packageText = JSON.stringify({
|
|
134
|
-
name: projectionName, version: "1.0.0", private: true,
|
|
135
|
-
dsh: { bundle: { patch: "./cordis.patch.yml" } },
|
|
136
|
-
}, null, 2) + "\n";
|
|
137
|
-
const newText = replaceBundleToken(inspection.manifestText, inspection.slot, projectionName);
|
|
138
|
-
const transaction = {
|
|
139
|
-
version: 1, projectionName, profileDir: options.profileDir, target: options.target,
|
|
140
|
-
home: options.home, installAnchor: options.installAnchor, migrateShell: options.migrateShell, migrateSubagent: options.migrateSubagent,
|
|
141
|
-
migrateSessionPersistence: options.migrateSessionPersistence,
|
|
142
|
-
slot: inspection.slot, originalLiteral: bundleToken(inspection.manifestText, inspection.slot).literal,
|
|
143
|
-
sourceRevision: inspection.revision,
|
|
144
|
-
beforeHash: digest(inspection.manifestText), afterHash: digest(newText), changes: inspection.changes,
|
|
145
|
-
outputs: [{ name: "package.json", hash: digest(packageText) }, { name: "cordis.patch.yml", hash: digest(patch) }],
|
|
146
|
-
};
|
|
147
|
-
await mkdir(dirname(dir), { recursive: true });
|
|
148
|
-
plainPath(dirname(dir));
|
|
149
|
-
await mkdir(dir);
|
|
150
|
-
try {
|
|
151
|
-
await exclusiveFile(join(dir, "package.json"), packageText);
|
|
152
|
-
await exclusiveFile(join(dir, "cordis.patch.yml"), patch);
|
|
153
|
-
await exclusiveFile(join(dir, RECEIPT), JSON.stringify(transaction, null, 2) + "\n");
|
|
154
|
-
readReceipt(options, projectionName);
|
|
155
|
-
const serialized = sdk.boot.loadOverlayPatches("dsmm-cold-profile", join(dir, "cordis.patch.yml"));
|
|
156
|
-
if (JSON.stringify(serialized) !== JSON.stringify(inspection.projected)) refuse("PROJECTION_ROUNDTRIP_FAILED");
|
|
157
|
-
inspection.readset.assertCurrent();
|
|
158
|
-
return transaction;
|
|
159
|
-
} catch (error) {
|
|
160
|
-
const safe = error instanceof ColdProfileMigrationError ? error : new ColdProfileMigrationError("PREPARATION_FAILED");
|
|
161
|
-
safe.projectionName = projectionName;
|
|
162
|
-
throw safe;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
async function prepareMigration(input) {
|
|
167
|
-
const options = normalizeOptions(input);
|
|
168
|
-
const sdk = await loadColdProfileSdk(options.installAnchor);
|
|
169
|
-
const manifestPath = join(options.profileDir, "package.json");
|
|
170
|
-
plainPath(`${manifestPath}.lock`, { missing: true });
|
|
171
|
-
return sdk.atomic.withFileLock(manifestPath, async () => {
|
|
172
|
-
const active = activeReceipt(options);
|
|
173
|
-
const inspection = await inspectColdComposition(options, sdk, { receipt: active });
|
|
174
|
-
requireRevision(inspection, input.expectedRevision);
|
|
175
|
-
if (active) return { ...summary(inspection, active), target: options.target };
|
|
176
|
-
const receipt = await prepareProjection(options, sdk, inspection);
|
|
177
|
-
return { status: "prepared", projectionName: receipt.projectionName, revision: inspection.revision, nativeToolSelection: inspection.nativeToolSelection };
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
/** Prepare immutable, unreferenced outputs; interruption cannot affect the current boot composition. */
|
|
182
|
-
export const prepareColdProfileMigration = input => safeOperation(() => prepareMigration(input));
|
|
183
|
-
|
|
184
|
-
async function applyMigration(input) {
|
|
185
|
-
const options = normalizeOptions(input);
|
|
186
|
-
if (input.sourceWriteExclusion !== true) refuse("COLD_SOURCE_WRITE_EXCLUSION_REQUIRED");
|
|
187
|
-
const sdk = await loadColdProfileSdk(options.installAnchor);
|
|
188
|
-
const manifestPath = join(options.profileDir, "package.json");
|
|
189
|
-
plainPath(`${manifestPath}.lock`, { missing: true });
|
|
190
|
-
return sdk.atomic.withFileLock(manifestPath, async () => {
|
|
191
|
-
const receipt = activeReceipt(options);
|
|
192
|
-
const inspection = await inspectColdComposition(options, sdk, { receipt });
|
|
193
|
-
requireRevision(inspection, input.expectedRevision);
|
|
194
|
-
if (receipt) return { ...summary(inspection, receipt), target: options.target };
|
|
195
|
-
const transaction = input.projectionName ? readReceipt(options, input.projectionName) : await prepareProjection(options, sdk, inspection);
|
|
196
|
-
if (transaction.sourceRevision !== inspection.revision || transaction.beforeHash !== digest(inspection.manifestText)) refuse("SOURCE_CONFLICT");
|
|
197
|
-
const projectionName = transaction.projectionName;
|
|
198
|
-
const newText = replaceBundleToken(inspection.manifestText, inspection.slot, projectionName);
|
|
199
|
-
if (digest(newText) !== transaction.afterHash) refuse("INVALID_RECEIPT");
|
|
200
|
-
const current = await inspectColdComposition(options, sdk);
|
|
201
|
-
requireRevision(current, input.expectedRevision);
|
|
202
|
-
inspection.readset.assertCurrent();
|
|
203
|
-
readReceipt(options, projectionName);
|
|
204
|
-
if (resolve(sdk.boot.resolveBundleDir("dsmm-cold-profile", projectionName, options.installAnchor, options.profileDir)) !== projectionDir(options, projectionName)) refuse("PROJECTION_RESOLUTION_CONFLICT");
|
|
205
|
-
plainPath(manifestPath);
|
|
206
|
-
await sdk.atomic.writeFileAtomic(manifestPath, newText, { mode: lstatSync(manifestPath).mode & 0o777 });
|
|
207
|
-
return { status: "applied", target: options.target, projectionName, previousRevision: inspection.revision, nativeToolSelection: inspection.nativeToolSelection };
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
/**
|
|
212
|
-
* Requires cold-source write exclusion. Manual editors and non-locking SDK HMR
|
|
213
|
-
* writers must be quiescent across final CAS/rename; the SDK manifest lock
|
|
214
|
-
* coordinates cooperating installers. Conditional rename against arbitrary
|
|
215
|
-
* editors is not a filesystem capability.
|
|
216
|
-
*/
|
|
217
|
-
export const applyColdProfileMigration = input => safeOperation(() => applyMigration(input));
|
|
218
|
-
|
|
219
|
-
/**
|
|
220
|
-
* Inspect an exact transaction's recoverability. No directory scan and no profile backup.
|
|
221
|
-
* A prepared, unreferenced package is safe to leave in place and can be retired explicitly.
|
|
222
|
-
*/
|
|
223
|
-
async function planRecovery(input) {
|
|
224
|
-
const options = normalizeOptions(input);
|
|
225
|
-
const sdk = await loadColdProfileSdk(options.installAnchor);
|
|
226
|
-
const receipt = readReceipt(options, input.projectionName);
|
|
227
|
-
const text = readFileSync(plainPath(join(options.profileDir, "package.json")), "utf8");
|
|
228
|
-
const hash = digest(text);
|
|
229
|
-
if (hash !== receipt.beforeHash && hash !== receipt.afterHash) refuse("RECOVERY_CONFLICT");
|
|
230
|
-
const applied = hash === receipt.afterHash;
|
|
231
|
-
if (applied && JSON.parse(bundleToken(text, receipt.slot).literal) !== receipt.projectionName) refuse("RECOVERY_CONFLICT");
|
|
232
|
-
const inspection = await inspectColdComposition(options, sdk, { receipt: applied ? receipt : undefined });
|
|
233
|
-
return { status: applied ? "rollback-planned" : "unreferenced", revision: inspection.revision, projectionName: receipt.projectionName };
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
export const planColdProfileRecovery = input => safeOperation(() => planRecovery(input));
|
|
237
|
-
|
|
238
|
-
/** Restore only the original reference token, and only against the current expected source revision. */
|
|
239
|
-
async function recoverMigration(input) {
|
|
240
|
-
const options = normalizeOptions(input);
|
|
241
|
-
if (input.sourceWriteExclusion !== true) refuse("COLD_SOURCE_WRITE_EXCLUSION_REQUIRED");
|
|
242
|
-
const sdk = await loadColdProfileSdk(options.installAnchor);
|
|
243
|
-
const manifestPath = join(options.profileDir, "package.json");
|
|
244
|
-
plainPath(`${manifestPath}.lock`, { missing: true });
|
|
245
|
-
return sdk.atomic.withFileLock(manifestPath, async () => {
|
|
246
|
-
const recovery = await planColdProfileRecovery(input);
|
|
247
|
-
if (recovery.revision !== input.expectedRevision) refuse("SOURCE_CONFLICT");
|
|
248
|
-
const receipt = readReceipt(options, input.projectionName);
|
|
249
|
-
const text = readFileSync(manifestPath, "utf8");
|
|
250
|
-
if (recovery.status === "rollback-planned") {
|
|
251
|
-
if (digest(text) !== receipt.afterHash) refuse("RECOVERY_CONFLICT");
|
|
252
|
-
const token = bundleToken(text, receipt.slot);
|
|
253
|
-
const original = text.slice(0, token.offset) + receipt.originalLiteral + text.slice(token.offset + token.length);
|
|
254
|
-
if (digest(original) !== receipt.beforeHash) refuse("RECOVERY_CONFLICT");
|
|
255
|
-
const inspection = await inspectColdComposition(options, sdk, { receipt });
|
|
256
|
-
requireRevision(inspection, input.expectedRevision);
|
|
257
|
-
inspection.readset.assertCurrent();
|
|
258
|
-
await sdk.atomic.writeFileAtomic(manifestPath, original, { mode: lstatSync(manifestPath).mode & 0o777 });
|
|
259
|
-
}
|
|
260
|
-
// Keep immutable outputs and receipt for idempotent recovery; they are no longer referenced.
|
|
261
|
-
return { status: "recovered", projectionName: receipt.projectionName };
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
export const recoverColdProfileMigration = input => safeOperation(() => recoverMigration(input));
|
|
266
|
-
|
|
267
|
-
export async function coldProfileMigrationCli(argv) {
|
|
268
|
-
const [command, ...args] = argv;
|
|
269
|
-
const values = {};
|
|
270
|
-
const overlays = [];
|
|
271
|
-
const sourceRoots = [];
|
|
272
|
-
const flags = new Set(["--no-shell", "--migrate-subagent", "--migrate-session-persistence", "--source-write-exclusion"]);
|
|
273
|
-
const names = {
|
|
274
|
-
"--profile-dir": "profileDir", "--install-anchor": "installAnchor", "--home": "home",
|
|
275
|
-
"--target": "target", "--expected-revision": "expectedRevision", "--projection-name": "projectionName",
|
|
276
|
-
"--root-config": "rootConfig",
|
|
277
|
-
};
|
|
278
|
-
for (let index = 0; index < args.length; index++) {
|
|
279
|
-
const flag = args[index];
|
|
280
|
-
if (flags.has(flag)) {
|
|
281
|
-
if (Object.hasOwn(values, flag)) refuse("INVALID_ARGUMENTS");
|
|
282
|
-
values[flag] = true;
|
|
283
|
-
} else if (flag === "--patch" || flag === "--source-root" || Object.hasOwn(names, flag)) {
|
|
284
|
-
const value = args[++index];
|
|
285
|
-
if (!value || value.startsWith("--")) refuse("INVALID_ARGUMENTS");
|
|
286
|
-
if (flag === "--patch") overlays.push(value);
|
|
287
|
-
else if (flag === "--source-root") sourceRoots.push(value);
|
|
288
|
-
else {
|
|
289
|
-
if (Object.hasOwn(values, names[flag])) refuse("INVALID_ARGUMENTS");
|
|
290
|
-
values[names[flag]] = value;
|
|
291
|
-
}
|
|
292
|
-
} else refuse("INVALID_ARGUMENTS");
|
|
293
|
-
}
|
|
294
|
-
const input = {
|
|
295
|
-
...values, overlays, migrateShell: !values["--no-shell"], migrateSubagent: !!values["--migrate-subagent"],
|
|
296
|
-
migrateSessionPersistence: !!values["--migrate-session-persistence"], sourceWriteExclusion: !!values["--source-write-exclusion"],
|
|
297
|
-
};
|
|
298
|
-
if (sourceRoots.length) input.sourceRoots = sourceRoots;
|
|
299
|
-
const commands = {
|
|
300
|
-
plan: planColdProfileMigration, prepare: prepareColdProfileMigration, apply: applyColdProfileMigration,
|
|
301
|
-
"plan-recover": planColdProfileRecovery, recover: recoverColdProfileMigration,
|
|
302
|
-
};
|
|
303
|
-
if (!Object.hasOwn(commands, command)) refuse("INVALID_COMMAND");
|
|
304
|
-
return commands[command](input);
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
308
|
-
try {
|
|
309
|
-
console.log(JSON.stringify(await coldProfileMigrationCli(process.argv.slice(2))));
|
|
310
|
-
} catch (error) {
|
|
311
|
-
// SDK/YAML/filesystem diagnostics can contain configuration values: never echo them.
|
|
312
|
-
console.error(JSON.stringify({ status: "refused", code: error instanceof ColdProfileMigrationError ? error.code : "SOURCE_OR_IO_FAILURE", ...(error.projectionName ? { projectionName: error.projectionName } : {}) }));
|
|
313
|
-
process.exitCode = 1;
|
|
314
|
-
}
|
|
315
|
-
}
|