@craft_eco/craft-mcp 0.1.29 → 0.1.30
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 +10 -55
- package/bin/craft-mcp.mjs +4 -1
- package/dist-server/game-workflow/check.mjs +3 -2
- package/dist-server/game-workflow/context-state.mjs +67 -67
- package/dist-server/game-workflow/draft-archive.mjs +147 -2
- package/dist-server/game-workflow/draft-upload-identity.mjs +11 -0
- package/dist-server/game-workflow/draft-uploads.mjs +105 -60
- package/dist-server/game-workflow/local-context.mjs +62 -62
- package/dist-server/game-workflow/native-context.mjs +289 -289
- package/dist-server/game-workflow/project-bundles.mjs +246 -246
- package/dist-server/game-workflow/project-context.mjs +8 -8
- package/dist-server/game-workflow/projects.mjs +6 -4
- package/dist-server/game-workflow/tasks.mjs +1 -1
- package/dist-server/game-workflow/work-scope.mjs +7 -7
- package/dist-server/integrations/config.mjs +145 -145
- package/dist-server/integrations/connect.mjs +36 -0
- package/dist-server/integrations/connection-handoff.mjs +36 -42
- package/dist-server/integrations/dsh-config.mjs +182 -182
- package/dist-server/integrations/files.mjs +54 -54
- package/dist-server/integrations/fixed-launcher.mjs +31 -0
- package/dist-server/integrations/host-reload.mjs +19 -0
- package/dist-server/integrations/hosts.mjs +55 -55
- package/dist-server/integrations/install.mjs +223 -205
- package/dist-server/integrations/installation-state.mjs +84 -84
- package/dist-server/integrations/launcher-start.mjs +52 -0
- package/dist-server/integrations/npm-diagnostics.mjs +32 -0
- package/dist-server/integrations/runtime-gc.mjs +191 -188
- package/dist-server/integrations/runtime-identity.mjs +22 -0
- package/dist-server/integrations/runtime.mjs +111 -126
- package/dist-server/integrations/updates.mjs +258 -225
- package/dist-server/integrations/version-policy.mjs +32 -32
- package/dist-server/launcher.mjs +1845 -0
- package/dist-server/mcp/control-panel.mjs +8 -23
- package/dist-server/mcp/server.mjs +31 -80
- package/dist-server/mcp/update-session.mjs +107 -92
- package/dist-server/upstream/craft-aigc.mjs +43 -16
- package/dist-server/upstream/draft-source.mjs +29 -0
- package/package.json +3 -2
- package/resources/context-filter-report.json +1 -1
- package/resources/craft-create/SKILL.md +19 -19
- package/resources/craft-update/SKILL.md +9 -11
- package/resources/targets/claude/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/claude/js/context-filter-report.json +1 -1
- package/resources/targets/claude/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/claude/js/js/bundle.json +7 -7
- package/resources/targets/claude/js/recovery.md +5 -1
- package/resources/targets/claude/js/target.json +1 -1
- package/resources/targets/claude/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/claude/js3d/context-filter-report.json +1 -1
- package/resources/targets/claude/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/claude/js3d/js3d/bundle.json +7 -7
- package/resources/targets/claude/js3d/recovery.md +5 -1
- package/resources/targets/claude/js3d/target.json +1 -1
- package/resources/targets/codebuddy/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/codebuddy/js/context-filter-report.json +1 -1
- package/resources/targets/codebuddy/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/codebuddy/js/js/bundle.json +7 -7
- package/resources/targets/codebuddy/js/recovery.md +5 -1
- package/resources/targets/codebuddy/js/target.json +1 -1
- package/resources/targets/codebuddy/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/codebuddy/js3d/context-filter-report.json +1 -1
- package/resources/targets/codebuddy/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/codebuddy/js3d/js3d/bundle.json +7 -7
- package/resources/targets/codebuddy/js3d/recovery.md +5 -1
- package/resources/targets/codebuddy/js3d/target.json +1 -1
- package/resources/targets/codex/js/bootstrap/SKILL.md +2 -4
- package/resources/targets/codex/js/context-filter-report.json +1 -1
- package/resources/targets/codex/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/codex/js/js/bundle.json +7 -7
- package/resources/targets/codex/js/recovery.md +3 -3
- package/resources/targets/codex/js/target.json +1 -1
- package/resources/targets/codex/js3d/bootstrap/SKILL.md +2 -4
- package/resources/targets/codex/js3d/context-filter-report.json +1 -1
- package/resources/targets/codex/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/codex/js3d/js3d/bundle.json +7 -7
- package/resources/targets/codex/js3d/recovery.md +3 -3
- package/resources/targets/codex/js3d/target.json +1 -1
- package/resources/targets/cursor/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/cursor/js/context-filter-report.json +1 -1
- package/resources/targets/cursor/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/cursor/js/js/bundle.json +7 -7
- package/resources/targets/cursor/js/recovery.md +5 -1
- package/resources/targets/cursor/js/target.json +1 -1
- package/resources/targets/cursor/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/cursor/js3d/context-filter-report.json +1 -1
- package/resources/targets/cursor/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/cursor/js3d/js3d/bundle.json +7 -7
- package/resources/targets/cursor/js3d/recovery.md +5 -1
- package/resources/targets/cursor/js3d/target.json +1 -1
- package/resources/targets/dsh/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/dsh/js/context-filter-report.json +1 -1
- package/resources/targets/dsh/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/dsh/js/js/bundle.json +7 -7
- package/resources/targets/dsh/js/recovery.md +5 -1
- package/resources/targets/dsh/js/target.json +1 -1
- package/resources/targets/dsh/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/dsh/js3d/context-filter-report.json +1 -1
- package/resources/targets/dsh/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/dsh/js3d/js3d/bundle.json +7 -7
- package/resources/targets/dsh/js3d/recovery.md +5 -1
- package/resources/targets/dsh/js3d/target.json +1 -1
- package/resources/targets/index.json +32 -32
- package/resources/targets/kimi/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/kimi/js/context-filter-report.json +1 -1
- package/resources/targets/kimi/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/kimi/js/js/bundle.json +7 -7
- package/resources/targets/kimi/js/recovery.md +5 -1
- package/resources/targets/kimi/js/target.json +1 -1
- package/resources/targets/kimi/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/kimi/js3d/context-filter-report.json +1 -1
- package/resources/targets/kimi/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/kimi/js3d/js3d/bundle.json +7 -7
- package/resources/targets/kimi/js3d/recovery.md +5 -1
- package/resources/targets/kimi/js3d/target.json +1 -1
- package/resources/targets/workbuddy/js/bootstrap/SKILL.md +22 -24
- package/resources/targets/workbuddy/js/context-filter-report.json +1 -1
- package/resources/targets/workbuddy/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/workbuddy/js/js/bundle.json +8 -8
- package/resources/targets/workbuddy/js/js/context/AGENTS.md +29 -29
- package/resources/targets/workbuddy/js/recovery.md +19 -19
- package/resources/targets/workbuddy/js/target.json +1 -1
- package/resources/targets/workbuddy/js3d/bootstrap/SKILL.md +22 -24
- package/resources/targets/workbuddy/js3d/context-filter-report.json +1 -1
- package/resources/targets/workbuddy/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/workbuddy/js3d/js3d/bundle.json +8 -8
- package/resources/targets/workbuddy/js3d/js3d/context/AGENTS.md +30 -30
- package/resources/targets/workbuddy/js3d/recovery.md +19 -19
- package/resources/targets/workbuddy/js3d/target.json +1 -1
- package/resources/targets/zcode/js/bootstrap/SKILL.md +3 -1
- package/resources/targets/zcode/js/context-filter-report.json +1 -1
- package/resources/targets/zcode/js/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/zcode/js/js/bundle.json +7 -7
- package/resources/targets/zcode/js/recovery.md +5 -1
- package/resources/targets/zcode/js/target.json +1 -1
- package/resources/targets/zcode/js3d/bootstrap/SKILL.md +3 -1
- package/resources/targets/zcode/js3d/context-filter-report.json +1 -1
- package/resources/targets/zcode/js3d/craft-game-maker/SKILL.md +11 -15
- package/resources/targets/zcode/js3d/js3d/bundle.json +7 -7
- package/resources/targets/zcode/js3d/recovery.md +5 -1
- package/resources/targets/zcode/js3d/target.json +1 -1
- package/vendor/craft-runtime/SOURCE.json +4 -4
- package/vendor/craft-runtime/package.json +1 -1
- package/dist-server/game-workflow/publication-materials.mjs +0 -92
- package/dist-server/game-workflow/publications.mjs +0 -168
- package/dist-server/game-workflow/publish-capture-worker.mjs +0 -57
- package/dist-server/game-workflow/publish-capture.mjs +0 -75
- package/dist-server/mcp/publication-page.html +0 -86
- package/dist-server/mcp/publication-page.mjs +0 -375
- package/dist-server/mcp/publication-preview.mjs +0 -63
- package/dist-server/mcp/publication-tools.mjs +0 -22
- package/dist-server/mcp/publish-panel.mjs +0 -210
- package/dist-server/upstream/publication-transport.mjs +0 -101
|
@@ -1,188 +1,191 @@
|
|
|
1
|
-
import path from 'node:path';
|
|
2
|
-
import { readdir, readFile, mkdir, writeFile, unlink, lstat, realpath, rm } from 'node:fs/promises';
|
|
3
|
-
import { createHash } from 'node:crypto';
|
|
4
|
-
import { execFile } from 'node:child_process';
|
|
5
|
-
import { promisify } from 'node:util';
|
|
6
|
-
import lockfile from 'proper-lockfile';
|
|
7
|
-
import { readInstallation, activationStatus } from './installation-state.mjs';
|
|
8
|
-
import { readConfig } from './config.mjs';
|
|
9
|
-
import { assertPlainPath } from './files.mjs';
|
|
10
|
-
import { compareVersions } from './version-policy.mjs';
|
|
11
|
-
|
|
12
|
-
const execute = promisify(execFile);
|
|
13
|
-
const canonical = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
|
|
14
|
-
const samePath = (a, b) => canonical(a) === canonical(b);
|
|
15
|
-
const within = (root, file) => {
|
|
16
|
-
const relative = path.relative(canonical(root), canonical(file));
|
|
17
|
-
return relative !== '' && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
|
|
18
|
-
};
|
|
19
|
-
const pidAlive = pid => {
|
|
20
|
-
try { process.kill(pid, 0); return true; }
|
|
21
|
-
catch (error) { return error.code !== 'ESRCH'; }
|
|
22
|
-
};
|
|
23
|
-
function referencesDirectory(value, directory) {
|
|
24
|
-
if (typeof value === 'string') {
|
|
25
|
-
const normalized = value.replaceAll('\\', '/');
|
|
26
|
-
const target = directory.replaceAll('\\', '/');
|
|
27
|
-
const [text, root] = process.platform === 'win32' ? [normalized.toLowerCase(), target.toLowerCase()] : [normalized, target];
|
|
28
|
-
return text === root || text.includes(root + '/');
|
|
29
|
-
}
|
|
30
|
-
return value && typeof value === 'object' && Object.values(value).some(item => referencesDirectory(item, directory));
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
// Legacy runtimes have no connection lease. Inspect command lines too, without
|
|
34
|
-
// exposing them (or their environment/credentials) in reports or logs.
|
|
35
|
-
export async function runtimeProcessReferences(directories) {
|
|
36
|
-
if (!directories.length) return { complete: true, directories: [] };
|
|
37
|
-
try {
|
|
38
|
-
let commands, complete = true;
|
|
39
|
-
if (process.platform === 'win32') {
|
|
40
|
-
const script = "$ErrorActionPreference='Stop'; @(Get-CimInstance Win32_Process | Select-Object ProcessId,Name,CommandLine) | ConvertTo-Json -Compress";
|
|
41
|
-
const { stdout } = await execute('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, timeout: 15000, maxBuffer: 8 * 1024 * 1024 });
|
|
42
|
-
const parsed = JSON.parse(stdout || '[]'), rows = Array.isArray(parsed) ? parsed : [parsed];
|
|
43
|
-
const nodeNames = new Set(['node.exe', path.basename(process.execPath).toLowerCase()]);
|
|
44
|
-
if (!rows.some(row => row.ProcessId === process.pid)) return { complete: false, directories: [] };
|
|
45
|
-
// CIM can include a process that has already exited with no command line.
|
|
46
|
-
// A still-live, unreadable interpreter remains an unknown reference.
|
|
47
|
-
complete = !rows.some(row => nodeNames.has(row.Name?.toLowerCase()) && !row.CommandLine && pidAlive(row.ProcessId));
|
|
48
|
-
// Include every readable executable, including renamed Node binaries.
|
|
49
|
-
// System processes normally hide their command lines; recognizable Node
|
|
50
|
-
// processes with hidden command lines make collection inconclusive.
|
|
51
|
-
commands = rows.map(row => row.CommandLine).filter(command => typeof command === 'string' && command);
|
|
52
|
-
} else {
|
|
53
|
-
const { stdout } = await execute('ps', ['-axww', '-o', 'pid=', '-o', 'args='], { timeout: 15000, maxBuffer: 8 * 1024 * 1024 });
|
|
54
|
-
const rows = stdout.split('\n').map(line => /^\s*(\d+)\s+(.*)$/.exec(line)).filter(Boolean);
|
|
55
|
-
if (!rows.some(row => Number(row[1]) === process.pid)) return { complete: false, directories: [] };
|
|
56
|
-
commands = rows.map(row => row[2]);
|
|
57
|
-
}
|
|
58
|
-
return { complete, directories: directories.filter(directory => commands.some(command => referencesDirectory(command, directory))) };
|
|
59
|
-
} catch { return { complete: false, directories: [] }; }
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
async function safeDirectory(directory) {
|
|
63
|
-
const info = await lstat(directory);
|
|
64
|
-
if (!info.isDirectory() || info.isSymbolicLink() || !samePath(await realpath(directory), directory)) throw new Error('Runtime cleanup requires a plain canonical directory');
|
|
65
|
-
await assertPlainPath(path.join(directory, '.craft-path-check'));
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
async function ownedRuntimes(root, packageName) {
|
|
69
|
-
const owned = [];
|
|
70
|
-
for (const entry of await readdir(root, { withFileTypes: true })) {
|
|
71
|
-
if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
|
|
72
|
-
const directory = path.join(root, entry.name);
|
|
73
|
-
try {
|
|
74
|
-
await safeDirectory(directory);
|
|
75
|
-
const metadata = JSON.parse(await readFile(path.join(directory, 'craft-runtime.json'), 'utf8'));
|
|
76
|
-
if (metadata.package !== packageName || !/^[a-f0-9]{64}$/.test(metadata.sha256 ?? '') || !/^[a-f0-9]{64}$/.test(metadata.build_id ?? '') || entry.name !== metadata.version + '-' + metadata.sha256.slice(0, 16)) continue;
|
|
77
|
-
compareVersions(metadata.version, metadata.version);
|
|
78
|
-
const packageRoot = path.join(directory, 'node_modules', ...packageName.split('/'));
|
|
79
|
-
await assertPlainPath(path.join(packageRoot, 'package.json'));
|
|
80
|
-
const pkg = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
|
|
81
|
-
if (pkg.name !== packageName || pkg.version !== metadata.version) continue;
|
|
82
|
-
owned.push({ directory, packageRoot, metadata });
|
|
83
|
-
} catch { /* Unrecognized, linked or partial directories are not ours to remove. */ }
|
|
84
|
-
}
|
|
85
|
-
return owned;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
async function scopedState(installationFile, current) {
|
|
89
|
-
const state = await readInstallation(installationFile);
|
|
90
|
-
if (!path.isAbsolute(state.runtime_root ?? '') || current.package !== state.source.package) throw new Error('Invalid runtime cleanup scope');
|
|
91
|
-
await safeDirectory(state.runtime_root);
|
|
92
|
-
return state;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/** Only confirmed host connections collect installer-owned, unreferenced
|
|
96
|
-
* runtime directories. Unknown references always defer deletion. */
|
|
97
|
-
export async function collectRetiredRuntimes({ installationFile, current, processReferences = runtimeProcessReferences, isAlive = pidAlive, keepPrevious = 1 }) {
|
|
98
|
-
let unlock;
|
|
99
|
-
const skipped = reason => ({ status: 'deferred', reason, removed: [] });
|
|
100
|
-
try {
|
|
101
|
-
let state = await scopedState(installationFile, current);
|
|
102
|
-
const root = state.runtime_root;
|
|
103
|
-
unlock = await lockfile.lock(root, { stale: 120000, retries: 0 });
|
|
104
|
-
state = await readInstallation(installationFile);
|
|
105
|
-
if (!samePath(root, state.runtime_root)) return skipped('installation_changed');
|
|
106
|
-
const receipt = state.connection_verification;
|
|
107
|
-
if (state.schema !== 2 || activationStatus(current, state.target).status !== 'active_verified' || !receipt || receipt.instance_id !== current.instance_id || receipt.version !== current.version || receipt.build_id !== current.build_id) return skipped('connection_not_verified');
|
|
108
|
-
const candidates = await ownedRuntimes(root, state.source.package);
|
|
109
|
-
const protectedPaths = new Set(), preserve = value => {
|
|
110
|
-
for (const candidate of candidates) if (referencesDirectory(value, candidate.directory)) protectedPaths.add(canonical(candidate.directory));
|
|
111
|
-
};
|
|
112
|
-
preserve(current);
|
|
113
|
-
const stateRoot = path.dirname(installationFile);
|
|
114
|
-
// Check every managed installation sharing this state directory. Invalid
|
|
115
|
-
// state/config means ownership cannot be established, so collect nothing.
|
|
116
|
-
const snapshots = [];
|
|
117
|
-
for (const entry of await readdir(stateRoot, { withFileTypes: true })) {
|
|
118
|
-
if (!entry.name.endsWith('.json')) continue;
|
|
119
|
-
if (!entry.isFile() || entry.isSymbolicLink()) return skipped('unknown_installation_reference');
|
|
120
|
-
const file = path.join(stateRoot, entry.name), text = await readFile(file, 'utf8');
|
|
121
|
-
const installation = await readInstallation(file);
|
|
122
|
-
snapshots.push({ file, text });
|
|
123
|
-
preserve(installation.anchor); preserve(installation.target); preserve(installation.skills_runtime);
|
|
124
|
-
const configText = await readFile(installation.config, 'utf8');
|
|
125
|
-
preserve(readConfig(configText, installation.host));
|
|
126
|
-
snapshots.push({ file: installation.config, text: configText });
|
|
127
|
-
}
|
|
128
|
-
const leaseRoot = path.join(root, '.connections');
|
|
129
|
-
let leases = [];
|
|
130
|
-
try { await safeDirectory(leaseRoot); leases = await readdir(leaseRoot, { withFileTypes: true }); }
|
|
131
|
-
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
132
|
-
for (const entry of leases) {
|
|
133
|
-
if (!entry.isFile() || entry.isSymbolicLink() || !entry.name.endsWith('.json')) return skipped('unknown_connection_reference');
|
|
134
|
-
const file = path.join(leaseRoot, entry.name), lease = JSON.parse(await readFile(file, 'utf8'));
|
|
135
|
-
if (!Number.isSafeInteger(lease.pid) || lease.pid <= 0 || !path.isAbsolute(lease.package_root ?? '')) return skipped('invalid_connection_reference');
|
|
136
|
-
if (isAlive(lease.pid)) preserve(lease.package_root);
|
|
137
|
-
else await unlink(file);
|
|
138
|
-
}
|
|
139
|
-
const processes = await processReferences(candidates.map(candidate => candidate.directory));
|
|
140
|
-
if (!processes.complete) return skipped('process_inventory_unavailable');
|
|
141
|
-
preserve(processes.directories);
|
|
142
|
-
const retired = candidates.filter(candidate => !protectedPaths.has(canonical(candidate.directory)));
|
|
143
|
-
// A higher unreferenced candidate may belong to an interrupted update; do
|
|
144
|
-
// not remove it as an old release. Keep one previous build for recovery.
|
|
145
|
-
const older = retired.filter(candidate => compareVersions(candidate.metadata.version, current.version) <= 0)
|
|
146
|
-
.sort((a, b) => compareVersions(b.metadata.version, a.metadata.version) || b.directory.localeCompare(a.directory));
|
|
147
|
-
const keep = older.slice(0, Math.max(1, keepPrevious));
|
|
148
|
-
const removed = [], failures = [];
|
|
149
|
-
for (const candidate of older.slice(keep.length)) {
|
|
150
|
-
// Recheck just before each removal: a legacy host can start a cached
|
|
151
|
-
// command after the initial inventory without creating a connection lease.
|
|
152
|
-
const latestProcesses = await processReferences([candidate.directory]);
|
|
153
|
-
if (!latestProcesses.complete) return { ...skipped('process_inventory_unavailable'), removed };
|
|
154
|
-
if (referencesDirectory(latestProcesses.directories, candidate.directory)) continue;
|
|
155
|
-
for (const snapshot of snapshots) if (await readFile(snapshot.file, 'utf8') !== snapshot.text) return { ...skipped('references_changed'), removed };
|
|
156
|
-
const directory = path.resolve(candidate.directory);
|
|
157
|
-
if (!within(root, directory) || !samePath(path.dirname(directory), root)) throw new Error('Runtime cleanup escaped its managed root');
|
|
158
|
-
await safeDirectory(directory);
|
|
159
|
-
try { await rm(directory, { recursive: true, force: false }); removed.push(directory); }
|
|
160
|
-
catch { failures.push(directory); }
|
|
161
|
-
}
|
|
162
|
-
return { status: failures.length ? 'partial' : 'completed', removed, retained_backup: keep.map(item => item.directory), ...(failures.length ? { deferred: failures } : {}) };
|
|
163
|
-
} catch { return skipped('references_unavailable_or_busy'); }
|
|
164
|
-
finally { await unlock?.(); }
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
export async function registerRuntimeConnection({ installationFile, current }) {
|
|
168
|
-
if (!current?.instance_id) throw new Error('Runtime connection requires its actual instance identity');
|
|
169
|
-
const state = await scopedState(installationFile, current);
|
|
170
|
-
if (!within(state.runtime_root, current.package_root)) throw new Error('Runtime connection is outside the managed installation');
|
|
171
|
-
const unlock = await lockfile.lock(state.runtime_root, { stale: 120000, retries: { retries: 20, minTimeout: 50, maxTimeout: 250 } });
|
|
172
|
-
let leaseFile;
|
|
173
|
-
try {
|
|
174
|
-
const directory = path.join(state.runtime_root, '.connections');
|
|
175
|
-
await mkdir(directory, { recursive: true }); await safeDirectory(directory);
|
|
176
|
-
leaseFile = path.join(directory, createHash('sha256').update(current.instance_id).digest('hex') + '.json');
|
|
177
|
-
await assertPlainPath(leaseFile);
|
|
178
|
-
await writeFile(leaseFile, JSON.stringify({ pid: process.pid, instance_id: current.instance_id, package_root: current.package_root, version: current.version, build_id: current.build_id }), { flag: 'wx', mode: 0o600 });
|
|
179
|
-
} finally { await unlock(); }
|
|
180
|
-
let closed = false;
|
|
181
|
-
const collect = () => collectRetiredRuntimes({ installationFile, current });
|
|
182
|
-
return { collect, close: async () => {
|
|
183
|
-
if (closed) return;
|
|
184
|
-
closed = true;
|
|
185
|
-
await unlink(leaseFile).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { readdir, readFile, mkdir, writeFile, unlink, lstat, realpath, rm } from 'node:fs/promises';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import lockfile from 'proper-lockfile';
|
|
7
|
+
import { readInstallation, activationStatus } from './installation-state.mjs';
|
|
8
|
+
import { readConfig } from './config.mjs';
|
|
9
|
+
import { assertPlainPath } from './files.mjs';
|
|
10
|
+
import { compareVersions } from './version-policy.mjs';
|
|
11
|
+
|
|
12
|
+
const execute = promisify(execFile);
|
|
13
|
+
const canonical = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
|
|
14
|
+
const samePath = (a, b) => canonical(a) === canonical(b);
|
|
15
|
+
const within = (root, file) => {
|
|
16
|
+
const relative = path.relative(canonical(root), canonical(file));
|
|
17
|
+
return relative !== '' && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
|
|
18
|
+
};
|
|
19
|
+
const pidAlive = pid => {
|
|
20
|
+
try { process.kill(pid, 0); return true; }
|
|
21
|
+
catch (error) { return error.code !== 'ESRCH'; }
|
|
22
|
+
};
|
|
23
|
+
function referencesDirectory(value, directory) {
|
|
24
|
+
if (typeof value === 'string') {
|
|
25
|
+
const normalized = value.replaceAll('\\', '/');
|
|
26
|
+
const target = directory.replaceAll('\\', '/');
|
|
27
|
+
const [text, root] = process.platform === 'win32' ? [normalized.toLowerCase(), target.toLowerCase()] : [normalized, target];
|
|
28
|
+
return text === root || text.includes(root + '/');
|
|
29
|
+
}
|
|
30
|
+
return value && typeof value === 'object' && Object.values(value).some(item => referencesDirectory(item, directory));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Legacy runtimes have no connection lease. Inspect command lines too, without
|
|
34
|
+
// exposing them (or their environment/credentials) in reports or logs.
|
|
35
|
+
export async function runtimeProcessReferences(directories) {
|
|
36
|
+
if (!directories.length) return { complete: true, directories: [] };
|
|
37
|
+
try {
|
|
38
|
+
let commands, complete = true;
|
|
39
|
+
if (process.platform === 'win32') {
|
|
40
|
+
const script = "$ErrorActionPreference='Stop'; @(Get-CimInstance Win32_Process | Select-Object ProcessId,Name,CommandLine) | ConvertTo-Json -Compress";
|
|
41
|
+
const { stdout } = await execute('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, timeout: 15000, maxBuffer: 8 * 1024 * 1024 });
|
|
42
|
+
const parsed = JSON.parse(stdout || '[]'), rows = Array.isArray(parsed) ? parsed : [parsed];
|
|
43
|
+
const nodeNames = new Set(['node.exe', path.basename(process.execPath).toLowerCase()]);
|
|
44
|
+
if (!rows.some(row => row.ProcessId === process.pid)) return { complete: false, directories: [] };
|
|
45
|
+
// CIM can include a process that has already exited with no command line.
|
|
46
|
+
// A still-live, unreadable interpreter remains an unknown reference.
|
|
47
|
+
complete = !rows.some(row => nodeNames.has(row.Name?.toLowerCase()) && !row.CommandLine && pidAlive(row.ProcessId));
|
|
48
|
+
// Include every readable executable, including renamed Node binaries.
|
|
49
|
+
// System processes normally hide their command lines; recognizable Node
|
|
50
|
+
// processes with hidden command lines make collection inconclusive.
|
|
51
|
+
commands = rows.map(row => row.CommandLine).filter(command => typeof command === 'string' && command);
|
|
52
|
+
} else {
|
|
53
|
+
const { stdout } = await execute('ps', ['-axww', '-o', 'pid=', '-o', 'args='], { timeout: 15000, maxBuffer: 8 * 1024 * 1024 });
|
|
54
|
+
const rows = stdout.split('\n').map(line => /^\s*(\d+)\s+(.*)$/.exec(line)).filter(Boolean);
|
|
55
|
+
if (!rows.some(row => Number(row[1]) === process.pid)) return { complete: false, directories: [] };
|
|
56
|
+
commands = rows.map(row => row[2]);
|
|
57
|
+
}
|
|
58
|
+
return { complete, directories: directories.filter(directory => commands.some(command => referencesDirectory(command, directory))) };
|
|
59
|
+
} catch { return { complete: false, directories: [] }; }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function safeDirectory(directory) {
|
|
63
|
+
const info = await lstat(directory);
|
|
64
|
+
if (!info.isDirectory() || info.isSymbolicLink() || !samePath(await realpath(directory), directory)) throw new Error('Runtime cleanup requires a plain canonical directory');
|
|
65
|
+
await assertPlainPath(path.join(directory, '.craft-path-check'));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function ownedRuntimes(root, packageName) {
|
|
69
|
+
const owned = [];
|
|
70
|
+
for (const entry of await readdir(root, { withFileTypes: true })) {
|
|
71
|
+
if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
|
|
72
|
+
const directory = path.join(root, entry.name);
|
|
73
|
+
try {
|
|
74
|
+
await safeDirectory(directory);
|
|
75
|
+
const metadata = JSON.parse(await readFile(path.join(directory, 'craft-runtime.json'), 'utf8'));
|
|
76
|
+
if (metadata.package !== packageName || !/^[a-f0-9]{64}$/.test(metadata.sha256 ?? '') || !/^[a-f0-9]{64}$/.test(metadata.build_id ?? '') || entry.name !== metadata.version + '-' + metadata.sha256.slice(0, 16)) continue;
|
|
77
|
+
compareVersions(metadata.version, metadata.version);
|
|
78
|
+
const packageRoot = path.join(directory, 'node_modules', ...packageName.split('/'));
|
|
79
|
+
await assertPlainPath(path.join(packageRoot, 'package.json'));
|
|
80
|
+
const pkg = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
|
|
81
|
+
if (pkg.name !== packageName || pkg.version !== metadata.version) continue;
|
|
82
|
+
owned.push({ directory, packageRoot, metadata });
|
|
83
|
+
} catch { /* Unrecognized, linked or partial directories are not ours to remove. */ }
|
|
84
|
+
}
|
|
85
|
+
return owned;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function scopedState(installationFile, current) {
|
|
89
|
+
const state = await readInstallation(installationFile);
|
|
90
|
+
if (!path.isAbsolute(state.runtime_root ?? '') || current.package !== state.source.package) throw new Error('Invalid runtime cleanup scope');
|
|
91
|
+
await safeDirectory(state.runtime_root);
|
|
92
|
+
return state;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Only confirmed host connections collect installer-owned, unreferenced
|
|
96
|
+
* runtime directories. Unknown references always defer deletion. */
|
|
97
|
+
export async function collectRetiredRuntimes({ installationFile, current, processReferences = runtimeProcessReferences, isAlive = pidAlive, keepPrevious = 1 }) {
|
|
98
|
+
let unlock;
|
|
99
|
+
const skipped = reason => ({ status: 'deferred', reason, removed: [] });
|
|
100
|
+
try {
|
|
101
|
+
let state = await scopedState(installationFile, current);
|
|
102
|
+
const root = state.runtime_root;
|
|
103
|
+
unlock = await lockfile.lock(root, { stale: 120000, retries: 0 });
|
|
104
|
+
state = await readInstallation(installationFile);
|
|
105
|
+
if (!samePath(root, state.runtime_root)) return skipped('installation_changed');
|
|
106
|
+
const receipt = state.connection_verification;
|
|
107
|
+
if (state.schema !== 2 || activationStatus(current, state.target).status !== 'active_verified' || !receipt || receipt.instance_id !== current.instance_id || receipt.version !== current.version || receipt.build_id !== current.build_id) return skipped('connection_not_verified');
|
|
108
|
+
const candidates = await ownedRuntimes(root, state.source.package);
|
|
109
|
+
const protectedPaths = new Set(), preserve = value => {
|
|
110
|
+
for (const candidate of candidates) if (referencesDirectory(value, candidate.directory)) protectedPaths.add(canonical(candidate.directory));
|
|
111
|
+
};
|
|
112
|
+
preserve(current);
|
|
113
|
+
const stateRoot = path.dirname(installationFile);
|
|
114
|
+
// Check every managed installation sharing this state directory. Invalid
|
|
115
|
+
// state/config means ownership cannot be established, so collect nothing.
|
|
116
|
+
const snapshots = [];
|
|
117
|
+
for (const entry of await readdir(stateRoot, { withFileTypes: true })) {
|
|
118
|
+
if (!entry.name.endsWith('.json')) continue;
|
|
119
|
+
if (!entry.isFile() || entry.isSymbolicLink()) return skipped('unknown_installation_reference');
|
|
120
|
+
const file = path.join(stateRoot, entry.name), text = await readFile(file, 'utf8');
|
|
121
|
+
const installation = await readInstallation(file);
|
|
122
|
+
snapshots.push({ file, text });
|
|
123
|
+
preserve(installation.anchor); preserve(installation.target); preserve(installation.skills_runtime);
|
|
124
|
+
const configText = await readFile(installation.config, 'utf8');
|
|
125
|
+
preserve(readConfig(configText, installation.host));
|
|
126
|
+
snapshots.push({ file: installation.config, text: configText });
|
|
127
|
+
}
|
|
128
|
+
const leaseRoot = path.join(root, '.connections');
|
|
129
|
+
let leases = [];
|
|
130
|
+
try { await safeDirectory(leaseRoot); leases = await readdir(leaseRoot, { withFileTypes: true }); }
|
|
131
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
132
|
+
for (const entry of leases) {
|
|
133
|
+
if (!entry.isFile() || entry.isSymbolicLink() || !entry.name.endsWith('.json')) return skipped('unknown_connection_reference');
|
|
134
|
+
const file = path.join(leaseRoot, entry.name), lease = JSON.parse(await readFile(file, 'utf8'));
|
|
135
|
+
if (!Number.isSafeInteger(lease.pid) || lease.pid <= 0 || !path.isAbsolute(lease.package_root ?? '')) return skipped('invalid_connection_reference');
|
|
136
|
+
if (isAlive(lease.pid)) preserve(lease.package_root);
|
|
137
|
+
else await unlink(file);
|
|
138
|
+
}
|
|
139
|
+
const processes = await processReferences(candidates.map(candidate => candidate.directory));
|
|
140
|
+
if (!processes.complete) return skipped('process_inventory_unavailable');
|
|
141
|
+
preserve(processes.directories);
|
|
142
|
+
const retired = candidates.filter(candidate => !protectedPaths.has(canonical(candidate.directory)));
|
|
143
|
+
// A higher unreferenced candidate may belong to an interrupted update; do
|
|
144
|
+
// not remove it as an old release. Keep one previous build for recovery.
|
|
145
|
+
const older = retired.filter(candidate => compareVersions(candidate.metadata.version, current.version) <= 0)
|
|
146
|
+
.sort((a, b) => compareVersions(b.metadata.version, a.metadata.version) || b.directory.localeCompare(a.directory));
|
|
147
|
+
const keep = older.slice(0, Math.max(1, keepPrevious));
|
|
148
|
+
const removed = [], failures = [];
|
|
149
|
+
for (const candidate of older.slice(keep.length)) {
|
|
150
|
+
// Recheck just before each removal: a legacy host can start a cached
|
|
151
|
+
// command after the initial inventory without creating a connection lease.
|
|
152
|
+
const latestProcesses = await processReferences([candidate.directory]);
|
|
153
|
+
if (!latestProcesses.complete) return { ...skipped('process_inventory_unavailable'), removed };
|
|
154
|
+
if (referencesDirectory(latestProcesses.directories, candidate.directory)) continue;
|
|
155
|
+
for (const snapshot of snapshots) if (await readFile(snapshot.file, 'utf8') !== snapshot.text) return { ...skipped('references_changed'), removed };
|
|
156
|
+
const directory = path.resolve(candidate.directory);
|
|
157
|
+
if (!within(root, directory) || !samePath(path.dirname(directory), root)) throw new Error('Runtime cleanup escaped its managed root');
|
|
158
|
+
await safeDirectory(directory);
|
|
159
|
+
try { await rm(directory, { recursive: true, force: false }); removed.push(directory); }
|
|
160
|
+
catch { failures.push(directory); }
|
|
161
|
+
}
|
|
162
|
+
return { status: failures.length ? 'partial' : 'completed', removed, retained_backup: keep.map(item => item.directory), ...(failures.length ? { deferred: failures } : {}) };
|
|
163
|
+
} catch { return skipped('references_unavailable_or_busy'); }
|
|
164
|
+
finally { await unlock?.(); }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export async function registerRuntimeConnection({ installationFile, current }) {
|
|
168
|
+
if (!current?.instance_id) throw new Error('Runtime connection requires its actual instance identity');
|
|
169
|
+
const state = await scopedState(installationFile, current);
|
|
170
|
+
if (!within(state.runtime_root, current.package_root)) throw new Error('Runtime connection is outside the managed installation');
|
|
171
|
+
const unlock = await lockfile.lock(state.runtime_root, { stale: 120000, retries: { retries: 20, minTimeout: 50, maxTimeout: 250 } });
|
|
172
|
+
let leaseFile;
|
|
173
|
+
try {
|
|
174
|
+
const directory = path.join(state.runtime_root, '.connections');
|
|
175
|
+
await mkdir(directory, { recursive: true }); await safeDirectory(directory);
|
|
176
|
+
leaseFile = path.join(directory, createHash('sha256').update(current.instance_id).digest('hex') + '.json');
|
|
177
|
+
await assertPlainPath(leaseFile);
|
|
178
|
+
await writeFile(leaseFile, JSON.stringify({ pid: process.pid, instance_id: current.instance_id, package_root: current.package_root, version: current.version, build_id: current.build_id }), { flag: 'wx', mode: 0o600 });
|
|
179
|
+
} finally { await unlock(); }
|
|
180
|
+
let closed = false;
|
|
181
|
+
const collect = () => collectRetiredRuntimes({ installationFile, current });
|
|
182
|
+
return { collect, close: async () => {
|
|
183
|
+
if (closed) return;
|
|
184
|
+
closed = true;
|
|
185
|
+
await unlink(leaseFile).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
186
|
+
// Hosts may terminate a stdio child after a short shutdown grace period.
|
|
187
|
+
// Running process inventory/GC here can leave an abandoned runtime lock,
|
|
188
|
+
// blocking the next fixed-entry launch. Collect after a new connection is
|
|
189
|
+
// verified; shutdown only releases this connection's lease.
|
|
190
|
+
} };
|
|
191
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { readFile, readdir, lstat } from 'node:fs/promises';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
// The content identity is independent of tarball repacking and is read from the
|
|
6
|
+
// running package, never from a host-provided version environment variable.
|
|
7
|
+
export async function getRuntimeIdentity(packageRoot) {
|
|
8
|
+
packageRoot = path.resolve(packageRoot);
|
|
9
|
+
const pkg = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
|
|
10
|
+
const hash = createHash('sha256');
|
|
11
|
+
async function visit(relative) {
|
|
12
|
+
const file = path.join(packageRoot, relative);
|
|
13
|
+
let info; try { info = await lstat(file); } catch (error) { if (error.code === 'ENOENT') return; throw error; }
|
|
14
|
+
if (info.isSymbolicLink()) throw new Error('Craft runtime contains a linked product file: ' + relative);
|
|
15
|
+
if (info.isDirectory()) {
|
|
16
|
+
for (const entry of (await readdir(file)).sort()) if (entry !== 'node_modules') await visit(relative + '/' + entry);
|
|
17
|
+
} else if (info.isFile()) hash.update(relative + '\0').update(await readFile(file)).update('\0');
|
|
18
|
+
else throw new Error('Invalid Craft runtime file: ' + relative);
|
|
19
|
+
}
|
|
20
|
+
for (const relative of ['package.json', 'bin', 'dist-server', 'resources', 'vendor']) await visit(relative);
|
|
21
|
+
return { package: pkg.name, version: pkg.version, build_id: hash.digest('hex'), package_root: packageRoot, entry: path.join(packageRoot, 'bin/craft-mcp.mjs') };
|
|
22
|
+
}
|