-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathruntime-common.mjs
More file actions
278 lines (231 loc) · 7.83 KB
/
runtime-common.mjs
File metadata and controls
278 lines (231 loc) · 7.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { constants as fsConstants } from "node:fs";
import { access, copyFile, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
export const INSTALL_TIMEOUT_MS = 120000;
const LOCK_STALE_MS = 10 * 60 * 1000;
const FALLBACK_PLUGIN_DATA_ROOT = join(homedir(), ".openviking", "claude-code-memory-plugin");
const RUNTIME_ENV_META_PATH = ".runtime-env.json";
export function getRuntimePaths() {
const pluginRoot = process.env.CLAUDE_PLUGIN_ROOT;
const pluginDataRoot = process.env.CLAUDE_PLUGIN_DATA || FALLBACK_PLUGIN_DATA_ROOT;
if (!pluginRoot) throw new Error("CLAUDE_PLUGIN_ROOT is not set");
const runtimeRoot = join(pluginDataRoot, "runtime");
return {
pluginRoot,
pluginDataRoot,
runtimeRoot,
sourcePackagePath: join(pluginRoot, "package.json"),
sourceLockPath: join(pluginRoot, "package-lock.json"),
sourceServerPath: join(pluginRoot, "servers", "memory-server.js"),
runtimePackagePath: join(runtimeRoot, "package.json"),
runtimeLockPath: join(runtimeRoot, "package-lock.json"),
runtimeServerPath: join(runtimeRoot, "servers", "memory-server.js"),
runtimeNodeModulesPath: join(runtimeRoot, "node_modules"),
statePath: join(runtimeRoot, "install-state.json"),
lockDir: join(runtimeRoot, ".install-lock"),
envMetaPath: join(runtimeRoot, RUNTIME_ENV_META_PATH),
usingFallbackPluginData: !process.env.CLAUDE_PLUGIN_DATA,
};
}
export async function computeSourceState(paths) {
const [pkgRaw, lockRaw, serverRaw] = await Promise.all([
readFile(paths.sourcePackagePath),
readFile(paths.sourceLockPath),
readFile(paths.sourceServerPath),
]);
const pkg = JSON.parse(pkgRaw.toString("utf8"));
return {
pluginVersion: typeof pkg.version === "string" ? pkg.version : "0.0.0",
manifestHash: sha256(pkgRaw, lockRaw),
serverHash: sha256(serverRaw),
};
}
export async function loadInstallState(paths) {
try {
return JSON.parse(await readFile(paths.statePath, "utf8"));
} catch {
return null;
}
}
export async function writeInstallState(paths, state) {
await mkdir(paths.runtimeRoot, { recursive: true });
await writeFile(
paths.statePath,
JSON.stringify(
{
...state,
updatedAt: new Date().toISOString(),
},
null,
2,
) + "\n",
);
}
export async function writeRuntimeEnvMeta(paths) {
await mkdir(paths.runtimeRoot, { recursive: true });
await writeFile(
paths.envMetaPath,
JSON.stringify(
{
pluginDataRoot: paths.pluginDataRoot,
runtimeRoot: paths.runtimeRoot,
usingFallbackPluginData: paths.usingFallbackPluginData,
updatedAt: new Date().toISOString(),
},
null,
2,
) + "\n",
);
}
export async function runtimeIsReady(paths, expectedState) {
const state = await loadInstallState(paths);
if (!state || state.status !== "ready") return false;
if (state.manifestHash !== expectedState.manifestHash) return false;
if (state.serverHash !== expectedState.serverHash) return false;
for (const target of [
paths.runtimePackagePath,
paths.runtimeLockPath,
paths.runtimeServerPath,
paths.runtimeNodeModulesPath,
]) {
if (!(await pathExists(target))) return false;
}
return true;
}
export async function syncRuntimeFiles(paths) {
await mkdir(join(paths.runtimeRoot, "servers"), { recursive: true });
await copyFile(paths.sourcePackagePath, paths.runtimePackagePath);
await copyFile(paths.sourceLockPath, paths.runtimeLockPath);
await copyFile(paths.sourceServerPath, paths.runtimeServerPath);
await writeRuntimeEnvMeta(paths);
}
export async function acquireInstallLock(paths, timeoutMs = INSTALL_TIMEOUT_MS) {
const startedAt = Date.now();
while (Date.now() - startedAt < timeoutMs) {
await mkdir(paths.runtimeRoot, { recursive: true });
try {
await mkdir(paths.lockDir);
await writeFile(
join(paths.lockDir, "owner.json"),
JSON.stringify({
pid: process.pid,
createdAt: new Date().toISOString(),
}) + "\n",
);
return async () => {
await rm(paths.lockDir, { recursive: true, force: true });
};
} catch (err) {
if (err?.code !== "EEXIST") throw err;
if (await isStaleLock(paths.lockDir)) {
await rm(paths.lockDir, { recursive: true, force: true });
continue;
}
await wait(500);
}
}
throw new Error(`Timed out waiting for install lock in ${paths.runtimeRoot}`);
}
export async function waitForRuntime(paths, expectedState, options = {}) {
const timeoutMs = options.timeoutMs ?? INSTALL_TIMEOUT_MS;
const pollMs = options.pollMs ?? 500;
const graceMs = options.graceMs ?? 5000;
const startedAt = Date.now();
let sawLock = await pathExists(paths.lockDir);
while (Date.now() - startedAt < timeoutMs) {
if (await runtimeIsReady(paths, expectedState)) return true;
const lockExists = await pathExists(paths.lockDir);
sawLock ||= lockExists;
if (!sawLock && Date.now() - startedAt >= graceMs) return false;
await wait(pollMs);
}
return runtimeIsReady(paths, expectedState);
}
export function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export async function ensureRuntimeInstalled(paths, expectedState) {
if (await runtimeIsReady(paths, expectedState)) return false;
const releaseLock = await acquireInstallLock(paths, INSTALL_TIMEOUT_MS);
try {
if (await runtimeIsReady(paths, expectedState)) return false;
await syncRuntimeFiles(paths);
const result = spawnSync(getNpmCommand(), installArgs(), {
cwd: paths.runtimeRoot,
encoding: "utf8",
stdio: "pipe",
shell: process.platform === "win32",
});
if (result.error) throw result.error;
if (result.status !== 0) throw new Error(formatInstallFailure(result));
await writeInstallState(paths, {
status: "ready",
pluginVersion: expectedState.pluginVersion,
manifestHash: expectedState.manifestHash,
serverHash: expectedState.serverHash,
pluginDataRoot: paths.pluginDataRoot,
usingFallbackPluginData: paths.usingFallbackPluginData,
});
return true;
} catch (err) {
await rm(paths.runtimeNodeModulesPath, { recursive: true, force: true });
await writeInstallState(paths, {
status: "error",
pluginVersion: expectedState.pluginVersion,
manifestHash: expectedState.manifestHash,
serverHash: expectedState.serverHash,
pluginDataRoot: paths.pluginDataRoot,
usingFallbackPluginData: paths.usingFallbackPluginData,
error: err instanceof Error ? err.message : String(err),
});
throw err;
} finally {
await releaseLock();
}
}
async function pathExists(target) {
try {
await access(target, fsConstants.F_OK);
return true;
} catch {
return false;
}
}
async function isStaleLock(lockDir) {
try {
const info = await stat(lockDir);
return Date.now() - info.mtimeMs > LOCK_STALE_MS;
} catch {
return false;
}
}
function sha256(...buffers) {
const hash = createHash("sha256");
for (const buf of buffers) hash.update(buf);
return hash.digest("hex");
}
function getNpmCommand() {
return process.platform === "win32" ? "npm.cmd" : "npm";
}
function installArgs() {
return ["ci", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund"];
}
function formatInstallFailure(result) {
const lines = [
`npm ci exited with status ${result.status ?? "unknown"}`,
trimOutput(result.stderr),
trimOutput(result.stdout),
].filter(Boolean);
return lines.join("\n");
}
function trimOutput(output) {
if (!output) return "";
const text = output.trim();
if (!text) return "";
const maxChars = 4000;
if (text.length <= maxChars) return text;
return text.slice(-maxChars);
}