hermes-agent 0.19.0 → 0.20.1

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.
@@ -1,78 +1,326 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  const { spawnSync } = require("node:child_process");
4
+ const fs = require("node:fs");
4
5
  const path = require("node:path");
6
+
5
7
  const packageJson = require("../package.json");
6
8
  const { getRelatedPackageNames } = require("../lib/package-metadata");
7
- const { findPython, getPythonPackageSpec } = require("../lib/python-launcher");
9
+ const { getRuntimeSourceDirectory, getVenvDirectory } = require("../lib/python-launcher");
10
+ const { ensureUv, UV_VERSION } = require("../lib/uv-installer");
8
11
 
9
- const candidate = findPython();
10
- const packageSpec = getPythonPackageSpec();
11
12
  const packageName = packageJson.name;
13
+ const packageRoot = path.resolve(__dirname, "..");
14
+ const runtimeRoot = path.join(packageRoot, "runtime");
15
+ const sourceDirectory = getRuntimeSourceDirectory();
16
+ const venvDirectory = getVenvDirectory();
17
+ const managedPythonDirectory = path.join(runtimeRoot, "python");
18
+ const cacheDirectory = path.join(runtimeRoot, "cache");
19
+ const runtimeMarkerPath = path.join(packageRoot, ".hermes-agent-runtime.json");
20
+ const pythonVersion = packageJson.hermesAgent?.pythonVersion || "3.11";
21
+ const upstreamRepository = packageJson.hermesAgent?.upstreamRepository;
22
+ const upstreamTag = packageJson.hermesAgent?.upstreamGitTag;
23
+ const upstreamCommit = packageJson.hermesAgent?.upstreamCommit;
24
+ const forceRelease = process.argv.slice(2).includes("--force-release");
12
25
 
13
- function warnIfRelatedPackageInstalled() {
14
- const relatedPackages = getRelatedPackageNames(packageName);
26
+ function assertRuntimePath(target) {
27
+ const relative = path.relative(packageRoot, path.resolve(target));
28
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
29
+ throw new Error(`Refusing to modify path outside the npm package runtime: ${target}`);
30
+ }
31
+ }
15
32
 
16
- if (relatedPackages.length === 0) {
17
- return;
33
+ function removeRuntimePath(target) {
34
+ assertRuntimePath(target);
35
+ fs.rmSync(target, { recursive: true, force: true });
36
+ }
37
+
38
+ function validateMetadata() {
39
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(upstreamRepository || "")) {
40
+ throw new Error("package.json contains an invalid hermesAgent.upstreamRepository");
41
+ }
42
+ if (!/^v[A-Za-z0-9][A-Za-z0-9._-]*$/.test(upstreamTag || "")) {
43
+ throw new Error("package.json contains an invalid hermesAgent.upstreamGitTag");
44
+ }
45
+ if (!/^[0-9a-f]{40}$/.test(upstreamCommit || "")) {
46
+ throw new Error("package.json must pin hermesAgent.upstreamCommit to a full commit SHA");
18
47
  }
48
+ }
19
49
 
20
- const npmRootCommand = process.env.npm_execpath
21
- ? { command: process.execPath, args: [process.env.npm_execpath, "root", "-g"] }
22
- : { command: process.platform === "win32" ? "npm.cmd" : "npm", args: ["root", "-g"] };
50
+ function cleanGitEnvironment() {
51
+ const env = {
52
+ ...process.env,
53
+ GIT_TERMINAL_PROMPT: "0",
54
+ GCM_INTERACTIVE: "Never"
55
+ };
56
+ delete env.GIT_DIR;
57
+ delete env.GIT_WORK_TREE;
58
+ delete env.GIT_INDEX_FILE;
59
+ return env;
60
+ }
23
61
 
24
- const rootResult = spawnSync(npmRootCommand.command, npmRootCommand.args, {
25
- encoding: "utf8",
62
+ function run(command, args, options = {}) {
63
+ const result = spawnSync(command, args, {
64
+ cwd: options.cwd || packageRoot,
65
+ env: options.env || process.env,
66
+ encoding: options.capture ? "utf8" : undefined,
67
+ stdio: options.capture ? ["ignore", "pipe", "pipe"] : "inherit",
26
68
  windowsHide: true
27
69
  });
70
+ if (result.error) throw result.error;
71
+ if (result.status !== 0) {
72
+ const detail = options.capture ? (result.stderr || result.stdout || "").trim() : "";
73
+ throw new Error(`${command} ${args[0] || ""} failed with exit code ${result.status ?? "unknown"}${detail ? `: ${detail}` : ""}`);
74
+ }
75
+ return options.capture ? result.stdout.trim() : "";
76
+ }
28
77
 
29
- if (rootResult.status !== 0) {
30
- return;
78
+ function ensureGit() {
79
+ try {
80
+ return run("git", ["--version"], { capture: true, env: cleanGitEnvironment() });
81
+ } catch {
82
+ throw new Error(
83
+ "Git is required for the native 'hermes update' channel. Install Git and run 'npm rebuild hermes-agent'."
84
+ );
31
85
  }
86
+ }
32
87
 
33
- const globalRoot = rootResult.stdout.trim();
88
+ function git(args, options = {}) {
89
+ return run("git", args, { ...options, env: cleanGitEnvironment() });
90
+ }
34
91
 
35
- for (const relatedPackage of relatedPackages) {
36
- const relatedPackageJson = path.join(globalRoot, relatedPackage, "package.json");
37
-
38
- try {
39
- if (require("node:fs").existsSync(relatedPackageJson)) {
40
- console.warn(
41
- `${relatedPackage} is already installed globally. ` +
42
- `${packageName} is an alias package for the same Hermes Agent runtime; ` +
43
- "you do not need to install both."
44
- );
45
- }
46
- } catch {
47
- return;
92
+ function readMarker() {
93
+ try {
94
+ return JSON.parse(fs.readFileSync(runtimeMarkerPath, "utf8"));
95
+ } catch {
96
+ return null;
97
+ }
98
+ }
99
+
100
+ function markerMatchesPackage(marker) {
101
+ return Boolean(
102
+ marker &&
103
+ marker.npmPackage === packageName &&
104
+ marker.npmVersion === packageJson.version &&
105
+ marker.upstreamGitTag === upstreamTag &&
106
+ marker.upstreamCommit === upstreamCommit &&
107
+ marker.pythonVersion === pythonVersion &&
108
+ marker.uvVersion === UV_VERSION &&
109
+ marker.platform === process.platform &&
110
+ marker.arch === process.arch
111
+ );
112
+ }
113
+
114
+ function checkoutIsUsable() {
115
+ if (!fs.existsSync(path.join(sourceDirectory, ".git"))) return false;
116
+ try {
117
+ const origin = git(["-C", sourceDirectory, "remote", "get-url", "origin"], { capture: true });
118
+ const expectedHttps = `https://github.com/${upstreamRepository}.git`;
119
+ return origin.replace(/\/$/u, "") === expectedHttps;
120
+ } catch {
121
+ return false;
122
+ }
123
+ }
124
+
125
+ function checkoutIsClean() {
126
+ try {
127
+ return git(["-C", sourceDirectory, "status", "--porcelain", "--untracked-files=no"], { capture: true }) === "";
128
+ } catch {
129
+ return false;
130
+ }
131
+ }
132
+
133
+ function fetchAndVerifyPinnedTag(targetDirectory) {
134
+ const tagRef = `refs/tags/${upstreamTag}`;
135
+ git(["-C", targetDirectory, "fetch", "--depth=1", "--no-recurse-submodules", "origin", `+${tagRef}:${tagRef}`]);
136
+ const fetchedCommit = git(["-C", targetDirectory, "rev-parse", `${tagRef}^{commit}`], { capture: true });
137
+ if (fetchedCommit !== upstreamCommit) {
138
+ throw new Error(`Upstream tag ${upstreamTag} resolved to ${fetchedCommit}, expected ${upstreamCommit}`);
139
+ }
140
+ }
141
+
142
+ function createPinnedCheckout(targetDirectory) {
143
+ removeRuntimePath(targetDirectory);
144
+ fs.mkdirSync(targetDirectory, { recursive: true });
145
+ const origin = `https://github.com/${upstreamRepository}.git`;
146
+
147
+ git(["-c", "core.longpaths=true", "init", targetDirectory]);
148
+ git(["-C", targetDirectory, "config", "core.autocrlf", "false"]);
149
+ git(["-C", targetDirectory, "config", "core.longpaths", "true"]);
150
+ git(["-C", targetDirectory, "remote", "add", "origin", origin]);
151
+ fetchAndVerifyPinnedTag(targetDirectory);
152
+
153
+ git(["-C", targetDirectory, "checkout", "--detach", upstreamCommit]);
154
+ git(["-C", targetDirectory, "config", "remote.origin.fetch", "+refs/heads/main:refs/remotes/origin/main"]);
155
+ }
156
+
157
+ function resetPinnedCheckoutInPlace() {
158
+ const previousCommit = git(["-C", sourceDirectory, "rev-parse", "HEAD"], { capture: true });
159
+ fetchAndVerifyPinnedTag(sourceDirectory);
160
+ git(["-C", sourceDirectory, "reset", "--hard", upstreamCommit]);
161
+ return {
162
+ commit() {},
163
+ rollback() {
164
+ git(["-C", sourceDirectory, "reset", "--hard", previousCommit]);
165
+ }
166
+ };
167
+ }
168
+
169
+ function installPinnedCheckout() {
170
+ const stageDirectory = path.join(runtimeRoot, `.hermes-agent-stage-${process.pid}`);
171
+ const backupDirectory = path.join(runtimeRoot, `.hermes-agent-backup-${process.pid}`);
172
+ removeRuntimePath(stageDirectory);
173
+ removeRuntimePath(backupDirectory);
174
+ createPinnedCheckout(stageDirectory);
175
+
176
+ let backedUp = false;
177
+ try {
178
+ if (fs.existsSync(sourceDirectory)) {
179
+ fs.renameSync(sourceDirectory, backupDirectory);
180
+ backedUp = true;
48
181
  }
182
+ fs.renameSync(stageDirectory, sourceDirectory);
183
+ } catch (error) {
184
+ if (backedUp && !fs.existsSync(sourceDirectory)) fs.renameSync(backupDirectory, sourceDirectory);
185
+ throw new Error(`Unable to replace the Hermes runtime. Stop running Hermes processes and retry: ${error.message}`);
186
+ } finally {
187
+ removeRuntimePath(stageDirectory);
49
188
  }
189
+
190
+ return {
191
+ commit() {
192
+ removeRuntimePath(backupDirectory);
193
+ },
194
+ rollback() {
195
+ if (!backedUp || !fs.existsSync(backupDirectory)) return;
196
+ removeRuntimePath(sourceDirectory);
197
+ fs.renameSync(backupDirectory, sourceDirectory);
198
+ }
199
+ };
50
200
  }
51
201
 
52
- warnIfRelatedPackageInstalled();
202
+ function uvBootstrapEnvironment() {
203
+ const env = {
204
+ ...process.env,
205
+ UV_CACHE_DIR: cacheDirectory,
206
+ UV_NO_CONFIG: "true",
207
+ UV_PYTHON_INSTALL_BIN: "false",
208
+ UV_PYTHON_INSTALL_DIR: managedPythonDirectory
209
+ };
210
+ delete env.PYTHONHOME;
211
+ delete env.PYTHONPATH;
212
+ delete env.UV_PROJECT_ENVIRONMENT;
213
+ delete env.UV_PYTHON;
214
+ delete env.VIRTUAL_ENV;
215
+ return env;
216
+ }
53
217
 
54
- if (!candidate) {
55
- console.error("Hermes Agent requires Python 3.11 or newer.");
56
- console.error(`Install Python, then run: python -m pip install --upgrade ${packageSpec}`);
57
- process.exit(1);
218
+ function uvSyncEnvironment() {
219
+ const env = uvBootstrapEnvironment();
220
+ delete env.UV_NO_CONFIG;
221
+ env.UV_PROJECT_ENVIRONMENT = venvDirectory;
222
+ env.UV_PYTHON = process.platform === "win32"
223
+ ? path.join(venvDirectory, "Scripts", "python.exe")
224
+ : path.join(venvDirectory, "bin", "python");
225
+ env.VIRTUAL_ENV = venvDirectory;
226
+ return env;
58
227
  }
59
228
 
60
- function runPip(extraArgs) {
61
- return spawnSync(
62
- candidate.command,
63
- [...candidate.args, "-m", "pip", "install", "--upgrade", ...extraArgs, packageSpec],
64
- { stdio: "inherit", windowsHide: true }
65
- );
229
+ function syncRuntime(uvExecutable) {
230
+ const pythonExecutable = process.platform === "win32"
231
+ ? path.join(venvDirectory, "Scripts", "python.exe")
232
+ : path.join(venvDirectory, "bin", "python");
233
+
234
+ if (!fs.existsSync(pythonExecutable)) {
235
+ console.log(`Creating an isolated managed Python ${pythonVersion} environment...`);
236
+ run(uvExecutable, ["venv", "--managed-python", "--python", pythonVersion, venvDirectory], {
237
+ cwd: sourceDirectory,
238
+ env: uvBootstrapEnvironment()
239
+ });
240
+ }
241
+
242
+ console.log("Synchronizing the upstream lockfile into the isolated environment...");
243
+ run(uvExecutable, ["sync", "--locked", "--extra", "all", "--no-dev"], {
244
+ cwd: sourceDirectory,
245
+ env: uvSyncEnvironment()
246
+ });
66
247
  }
67
248
 
68
- let result = runPip([]);
249
+ function warnIfRelatedPackageInstalled() {
250
+ const relatedPackages = getRelatedPackageNames(packageName);
251
+ if (relatedPackages.length === 0) return;
252
+
253
+ const command = process.env.npm_execpath
254
+ ? { executable: process.execPath, args: [process.env.npm_execpath, "root", "--global"] }
255
+ : { executable: process.platform === "win32" ? "npm.cmd" : "npm", args: ["root", "--global"] };
256
+ const result = spawnSync(command.executable, command.args, {
257
+ encoding: "utf8",
258
+ windowsHide: true
259
+ });
260
+ if (result.status !== 0) return;
69
261
 
70
- if (result.status !== 0) {
71
- console.warn("Global pip install failed; retrying with --user.");
72
- result = runPip(["--user"]);
262
+ for (const relatedPackage of relatedPackages) {
263
+ if (fs.existsSync(path.join(result.stdout.trim(), relatedPackage, "package.json"))) {
264
+ console.warn(`${relatedPackage} is already installed globally; installing both packages creates duplicate runtimes.`);
265
+ }
266
+ }
73
267
  }
74
268
 
75
- if (result.status !== 0) {
76
- console.error(`Failed to install ${packageSpec}.`);
77
- process.exit(result.status || 1);
269
+ async function main() {
270
+ validateMetadata();
271
+ warnIfRelatedPackageInstalled();
272
+ console.log(ensureGit());
273
+ fs.mkdirSync(runtimeRoot, { recursive: true });
274
+
275
+ const uvExecutable = await ensureUv(packageRoot);
276
+ const marker = readMarker();
277
+ const currentCheckoutMatchesPackage = markerMatchesPackage(marker) && checkoutIsUsable();
278
+ const keepCurrentCheckout = !forceRelease && currentCheckoutMatchesPackage;
279
+ const resetCurrentCheckout = forceRelease && currentCheckoutMatchesPackage && checkoutIsClean();
280
+ let transaction = null;
281
+
282
+ try {
283
+ if (keepCurrentCheckout) {
284
+ console.log("Keeping the existing checkout; native rolling updates are preserved for this npm version.");
285
+ } else if (resetCurrentCheckout) {
286
+ console.log("Resetting the clean runtime to the release commit pinned by this npm package...");
287
+ transaction = resetPinnedCheckoutInPlace();
288
+ } else {
289
+ if (forceRelease) console.log("Resetting the runtime to the release commit pinned by this npm package...");
290
+ console.log(`Preparing Hermes Agent ${upstreamTag} at ${upstreamCommit.slice(0, 12)}...`);
291
+ transaction = installPinnedCheckout();
292
+ }
293
+
294
+ syncRuntime(uvExecutable);
295
+ const runtimeCommit = git(["-C", sourceDirectory, "rev-parse", "HEAD"], { capture: true });
296
+ const runtimeMarker = {
297
+ npmPackage: packageName,
298
+ npmVersion: packageJson.version,
299
+ upstreamVersion: packageJson.hermesAgent.upstreamVersion,
300
+ upstreamGitTag: upstreamTag,
301
+ upstreamCommit,
302
+ runtimeCommitAtInstall: runtimeCommit,
303
+ pythonVersion,
304
+ uvVersion: UV_VERSION,
305
+ platform: process.platform,
306
+ arch: process.arch,
307
+ installedAt: new Date().toISOString(),
308
+ nativeUpdateCommand: "hermes update",
309
+ npmUpdateCommand: "hermes-npm update"
310
+ };
311
+ fs.writeFileSync(runtimeMarkerPath, `${JSON.stringify(runtimeMarker, null, 2)}\n`, "utf8");
312
+ transaction?.commit();
313
+ console.log("Hermes Agent npm runtime is ready.");
314
+ console.log("Use 'hermes update' for upstream rolling updates or 'hermes-npm update' for npm releases.");
315
+ } catch (error) {
316
+ transaction?.rollback();
317
+ throw new Error(`Failed to prepare the isolated Hermes Agent runtime: ${error.message}`);
318
+ } finally {
319
+ removeRuntimePath(cacheDirectory);
320
+ }
78
321
  }
322
+
323
+ main().catch((error) => {
324
+ console.error(`Installation failed: ${error.message}`);
325
+ process.exit(1);
326
+ });