hermes-agent 0.18.2 → 0.20.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.
@@ -0,0 +1,533 @@
1
+ const { spawn, spawnSync } = require("node:child_process");
2
+ const fs = require("node:fs");
3
+ const path = require("node:path");
4
+
5
+ const packageJson = require("../package.json");
6
+ const { getRuntimeSourceDirectory } = require("./python-launcher");
7
+ const {
8
+ createUpstreamMigrationPlan,
9
+ executeUpstreamMigration,
10
+ getDefaultHermesHome
11
+ } = require("./upstream-migration");
12
+
13
+ const packageRoot = path.resolve(__dirname, "..");
14
+ const npmRegistry = "https://registry.npmjs.org";
15
+ const canonicalPackageName = packageJson.hermesAgent?.canonicalNpmPackage || packageJson.name;
16
+
17
+ function npmCommand() {
18
+ return process.platform === "win32" ? "npm.cmd" : "npm";
19
+ }
20
+
21
+ function runGit(args) {
22
+ const env = {
23
+ ...process.env,
24
+ GIT_TERMINAL_PROMPT: "0",
25
+ GCM_INTERACTIVE: "Never"
26
+ };
27
+ delete env.GIT_DIR;
28
+ delete env.GIT_WORK_TREE;
29
+ delete env.GIT_INDEX_FILE;
30
+ const result = spawnSync("git", args, {
31
+ encoding: "utf8",
32
+ env,
33
+ windowsHide: true
34
+ });
35
+ return result.status === 0 ? result.stdout.trim() : null;
36
+ }
37
+
38
+ function findNodeModulesOwner(startPath) {
39
+ let current = path.resolve(startPath);
40
+ while (true) {
41
+ if (path.basename(current).toLowerCase() === "node_modules") {
42
+ return path.dirname(current);
43
+ }
44
+ const parent = path.dirname(current);
45
+ if (parent === current) return null;
46
+ current = parent;
47
+ }
48
+ }
49
+
50
+ function pathsReferToSameInstallLocation(left, right, platform = process.platform) {
51
+ if (!left || !right) return false;
52
+ return platform === "win32"
53
+ ? left.toLowerCase() === right.toLowerCase()
54
+ : left === right;
55
+ }
56
+
57
+ function detectInstallContext() {
58
+ const result = spawnSync(npmCommand(), ["root", "--global"], {
59
+ encoding: "utf8",
60
+ windowsHide: true
61
+ });
62
+ const globalRoot = result.status === 0 ? path.resolve(result.stdout.trim()) : null;
63
+ const packageParent = path.dirname(packageRoot);
64
+ const isGlobal = pathsReferToSameInstallLocation(packageParent, globalRoot);
65
+ return {
66
+ isGlobal,
67
+ projectRoot: isGlobal ? null : findNodeModulesOwner(packageRoot)
68
+ };
69
+ }
70
+
71
+ function getReleaseUpdateCommand() {
72
+ return "hermes-npm update";
73
+ }
74
+
75
+ function getReleaseUpdateArgs(version, context = detectInstallContext(), packageName = canonicalPackageName) {
76
+ parseSemver(version);
77
+ const args = ["install"];
78
+ if (context.isGlobal) args.push("--global");
79
+ args.push("--registry", npmRegistry, `${packageName}@${version}`);
80
+ return args;
81
+ }
82
+
83
+ function getAliasMigrationCommands(
84
+ version,
85
+ context,
86
+ installedPackageName = packageJson.name,
87
+ canonicalName = canonicalPackageName
88
+ ) {
89
+ if (installedPackageName === canonicalName) return null;
90
+ const uninstallArgs = ["uninstall"];
91
+ if (context.isGlobal) uninstallArgs.push("--global");
92
+ uninstallArgs.push(installedPackageName);
93
+ const installArgs = getReleaseUpdateArgs(version, context, canonicalName);
94
+ return [
95
+ `npm ${uninstallArgs.join(" ")}`,
96
+ `npm ${installArgs.join(" ")}`
97
+ ];
98
+ }
99
+
100
+ function assertReleaseUpdateAllowed(
101
+ version,
102
+ context,
103
+ installedPackageName = packageJson.name,
104
+ canonicalName = canonicalPackageName
105
+ ) {
106
+ const commands = getAliasMigrationCommands(version, context, installedPackageName, canonicalName);
107
+ if (!commands) return;
108
+ throw new Error(
109
+ `${installedPackageName} is an alias for ${canonicalName} and cannot update automatically. ` +
110
+ `Migrate manually:\n ${commands.join("\n ")}`
111
+ );
112
+ }
113
+
114
+ function parseSemver(version) {
115
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
116
+ if (!match) throw new Error(`Invalid npm semver: ${version}`);
117
+ return {
118
+ core: match.slice(1, 4).map(Number),
119
+ prerelease: match[4] ? match[4].split(".") : []
120
+ };
121
+ }
122
+
123
+ function compareSemver(left, right) {
124
+ const a = parseSemver(left);
125
+ const b = parseSemver(right);
126
+ for (let index = 0; index < 3; index += 1) {
127
+ if (a.core[index] !== b.core[index]) return a.core[index] > b.core[index] ? 1 : -1;
128
+ }
129
+ if (a.prerelease.length === 0 || b.prerelease.length === 0) {
130
+ if (a.prerelease.length === b.prerelease.length) return 0;
131
+ return a.prerelease.length === 0 ? 1 : -1;
132
+ }
133
+ const length = Math.max(a.prerelease.length, b.prerelease.length);
134
+ for (let index = 0; index < length; index += 1) {
135
+ const av = a.prerelease[index];
136
+ const bv = b.prerelease[index];
137
+ if (av === undefined || bv === undefined) return av === undefined ? -1 : 1;
138
+ if (av === bv) continue;
139
+ const an = /^\d+$/.test(av);
140
+ const bn = /^\d+$/.test(bv);
141
+ if (an && bn) return Number(av) > Number(bv) ? 1 : -1;
142
+ if (an !== bn) return an ? -1 : 1;
143
+ return av > bv ? 1 : -1;
144
+ }
145
+ return 0;
146
+ }
147
+
148
+ function readRuntimeStatus() {
149
+ const sourceDirectory = getRuntimeSourceDirectory();
150
+ const hermesHome = getDefaultHermesHome();
151
+ const markerPath = path.join(packageRoot, ".hermes-agent-runtime.json");
152
+ let marker = null;
153
+ try {
154
+ marker = JSON.parse(fs.readFileSync(markerPath, "utf8"));
155
+ } catch {
156
+ marker = null;
157
+ }
158
+
159
+ const runtimeCommit = runGit(["-C", sourceDirectory, "rev-parse", "HEAD"]);
160
+ const branch = runGit(["-C", sourceDirectory, "branch", "--show-current"]);
161
+ const dirty = runGit(["-C", sourceDirectory, "status", "--porcelain", "--untracked-files=no"]);
162
+ const packagedCommit = packageJson.hermesAgent?.upstreamCommit || null;
163
+ const runtimeReady = Boolean(runtimeCommit && marker);
164
+ const releasePinned = runtimeReady && runtimeCommit === packagedCommit && dirty === "";
165
+ const context = detectInstallContext();
166
+
167
+ return {
168
+ installation: "npm",
169
+ packageRoot,
170
+ npmPackage: packageJson.name,
171
+ npmVersion: packageJson.version,
172
+ packagedRelease: packageJson.hermesAgent?.upstreamGitTag || null,
173
+ packagedCommit,
174
+ runtimeCommit,
175
+ runtimeSourceDirectory: sourceDirectory,
176
+ runtimeVenvDirectory: path.join(sourceDirectory, "venv"),
177
+ runtimeBranch: branch || null,
178
+ runtimeDirty: dirty === null ? null : dirty !== "",
179
+ runtimeReady,
180
+ runtimeChannel: releasePinned ? "npm-release" : runtimeReady ? "upstream-native" : "missing",
181
+ runtimeModifiedByNativeUpdate: runtimeReady ? !releasePinned : null,
182
+ nativeUpdateCommand: "hermes update",
183
+ nativeCheckCommand: "hermes update --check",
184
+ releaseUpdateCommand: getReleaseUpdateCommand(),
185
+ releaseCheckCommand: "hermes-npm check",
186
+ installMethodsCommand: "hermes-npm methods --json",
187
+ hermesHome,
188
+ upstreamHandoffTarget: path.join(hermesHome, "hermes-agent"),
189
+ installScope: context.isGlobal ? "global" : "local"
190
+ };
191
+ }
192
+
193
+ async function fetchLatestNpmVersion() {
194
+ const encodedName = canonicalPackageName.startsWith("@")
195
+ ? `@${encodeURIComponent(canonicalPackageName.slice(1))}`
196
+ : encodeURIComponent(canonicalPackageName);
197
+ const response = await fetch(`${npmRegistry}/${encodedName}`, {
198
+ headers: {
199
+ Accept: "application/vnd.npm.install-v1+json",
200
+ "User-Agent": "hermes-agent-npm"
201
+ },
202
+ signal: AbortSignal.timeout(30_000)
203
+ });
204
+ if (!response.ok) {
205
+ throw new Error(`npm registry returned HTTP ${response.status} ${response.statusText}`);
206
+ }
207
+ const metadata = await response.json();
208
+ const latest = metadata["dist-tags"]?.latest;
209
+ if (!latest) throw new Error("npm registry response does not contain the latest dist-tag");
210
+ return latest;
211
+ }
212
+
213
+ function printStatus(status) {
214
+ console.log(`npm package: ${status.npmPackage}@${status.npmVersion} (${status.installScope})`);
215
+ console.log(`packaged release: ${status.packagedRelease} (${status.packagedCommit || "unknown"})`);
216
+ console.log(`runtime commit: ${status.runtimeCommit || "not installed"}`);
217
+ console.log(`runtime source: ${status.runtimeSourceDirectory}`);
218
+ console.log(`HERMES_HOME: ${status.hermesHome}`);
219
+ console.log(`runtime channel: ${status.runtimeChannel}`);
220
+ console.log(`native update: ${status.nativeUpdateCommand}`);
221
+ console.log(`release update: ${status.releaseUpdateCommand}`);
222
+ if (status.runtimeModifiedByNativeUpdate) {
223
+ console.log("note: npm reinstall/update will return the runtime to the latest release-pinned build.");
224
+ }
225
+ }
226
+
227
+ function getInstallMethods() {
228
+ return {
229
+ recommendedForNpmUsers: "npm-isolated",
230
+ methods: [
231
+ {
232
+ id: "npm-isolated",
233
+ install: "npm install --global hermes-agent",
234
+ projectInstall: "npm install hermes-agent",
235
+ commands: "hermes, hermes-agent, hermes-npm",
236
+ sourceLocation: "inside the installed npm package",
237
+ updateOwner: "hermes update (rolling) or hermes-npm update (npm Release)",
238
+ uninstall: "npm uninstall --global hermes-agent",
239
+ projectUninstall: "npm uninstall hermes-agent"
240
+ },
241
+ {
242
+ id: "upstream-managed",
243
+ install: "official upstream installer",
244
+ officialDocs: "https://github.com/NousResearch/hermes-agent#quick-install",
245
+ posixInstall: "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",
246
+ windowsInstall: "iex (irm https://hermes-agent.nousresearch.com/install.ps1)",
247
+ commands: "hermes, hermes-agent",
248
+ sourceLocation: "$HERMES_HOME/hermes-agent (user-scoped handoff target)",
249
+ updateOwner: "hermes update",
250
+ uninstall: "hermes uninstall",
251
+ migrateFromNpm: "hermes-npm migrate upstream --yes"
252
+ },
253
+ {
254
+ id: "manual-development",
255
+ install: "follow the upstream contributing guide",
256
+ officialDocs: "https://hermes-agent.nousresearch.com/docs/developer-guide/contributing",
257
+ commands: "checkout/venv entrypoints",
258
+ sourceLocation: "developer-selected checkout with an external venv",
259
+ updateOwner: "developer-managed Git and uv",
260
+ uninstall: "remove the selected checkout and external venv",
261
+ intendedFor: "contributors and CI, not ordinary npm users"
262
+ }
263
+ ]
264
+ };
265
+ }
266
+
267
+ function printMethods() {
268
+ console.log(`Hermes Agent installation methods
269
+
270
+ npm-isolated (recommended when npm should own the deployment)
271
+ global: npm install --global hermes-agent
272
+ project: npm install hermes-agent
273
+ update: hermes update (rolling) or hermes-npm update (npm Release)
274
+ uninstall: matching global/project npm uninstall
275
+
276
+ upstream-managed (official source layout and native ownership)
277
+ handoff: hermes-npm migrate upstream # show the plan
278
+ hermes-npm migrate upstream --yes # install, verify, remove npm package
279
+ direct: https://github.com/NousResearch/hermes-agent#quick-install
280
+ update: hermes update
281
+ uninstall: hermes uninstall
282
+
283
+ manual-development
284
+ follow upstream's contributing guide; Git and uv own the checkout/venv.
285
+
286
+ Do not run 'hermes uninstall' while npm owns the runtime. It can remove the
287
+ package-local checkout without uninstalling the npm package.`);
288
+ }
289
+
290
+ function printHelp(topic) {
291
+ if (topic === "install" || topic === "methods") {
292
+ printMethods();
293
+ return;
294
+ }
295
+ if (topic === "update") {
296
+ console.log(`Update commands
297
+
298
+ hermes update --check Check the upstream native rolling channel
299
+ hermes update Update the live checkout from upstream
300
+ hermes-npm check Check the npm Release channel
301
+ hermes-npm update Install/reset to the checked npm Release
302
+
303
+ Native rolling changes are replaced by the next npm Release update.`);
304
+ return;
305
+ }
306
+ if (topic === "migrate") {
307
+ console.log(`Upstream handoff
308
+
309
+ hermes-npm migrate upstream
310
+ Print the exact target, installer, and npm removal plan. No changes.
311
+
312
+ hermes-npm migrate upstream --yes
313
+ Run the pinned official installer non-interactively, verify its exact
314
+ Release commit and venv command, uninstall this npm package, then re-run
315
+ the official PATH stage so command ownership is unambiguous.
316
+
317
+ The handoff uses the existing HERMES_HOME (or its platform default), preserves
318
+ user data, and transfers command/update ownership to upstream. It is one-way;
319
+ the bridge does not keep two competing 'hermes' commands active.`);
320
+ return;
321
+ }
322
+ if (topic === "uninstall") {
323
+ console.log(`Uninstall ownership
324
+
325
+ npm deployment: npm uninstall --global hermes-agent
326
+ project dependency: npm uninstall hermes-agent
327
+ upstream deployment: hermes uninstall
328
+
329
+ Do not use upstream 'hermes uninstall' while npm owns the runtime.`);
330
+ return;
331
+ }
332
+ console.log(`Usage: hermes-npm <command> [options]
333
+
334
+ Commands:
335
+ status [--json] Show the npm release and live upstream runtime state
336
+ check [--json] Check the npm registry release channel
337
+ update Update through npm and return to the release channel
338
+ methods [--json] List supported installation and ownership models
339
+ migrate upstream Show a one-way handoff plan; add --yes to execute it
340
+ help [topic] Show help (install, update, migrate, uninstall)
341
+
342
+ The native rolling channel remains available through 'hermes update'.
343
+ Run 'hermes-npm help install' before choosing a deployment model.`);
344
+ }
345
+
346
+ function printMigrationPlan(plan) {
347
+ console.log(`Upstream handoff plan (no changes made)
348
+
349
+ npm package: ${plan.npmPackage}@${plan.npmVersion} (${plan.installScope})
350
+ upstream release: ${plan.upstreamRelease} (${plan.upstreamCommit})
351
+ HERMES_HOME: ${plan.hermesHome}
352
+ official checkout: ${plan.installDirectory}
353
+ npm-managed source: ${plan.npmManagedInstall ? "yes" : "no (execution will be refused)"}
354
+ final owner: upstream 'hermes update'
355
+
356
+ Execution will run the pinned upstream installer with setup/gateway prompts
357
+ disabled, verify the exact commit and venv command, and only then run:
358
+ npm ${plan.npmUninstall.args.join(" ")}
359
+
360
+ It finishes by re-running the official installer's PATH stage from the verified
361
+ external checkout, after npm has removed its own shims.
362
+
363
+ User configuration and state under HERMES_HOME are preserved. Stop gateways,
364
+ agents, and Desktop first. Re-run with '--yes' to execute this one-way handoff.`);
365
+ }
366
+
367
+ function applyReleaseUpdate(version) {
368
+ const context = detectInstallContext();
369
+ assertReleaseUpdateAllowed(version, context);
370
+ const args = getReleaseUpdateArgs(version, context);
371
+ const child = spawn(npmCommand(), args, {
372
+ cwd: context.projectRoot || process.cwd(),
373
+ stdio: "inherit",
374
+ windowsHide: false
375
+ });
376
+ child.on("exit", (code, signal) => {
377
+ if (signal) {
378
+ process.kill(process.pid, signal);
379
+ return;
380
+ }
381
+ process.exit(code ?? 1);
382
+ });
383
+ child.on("error", (error) => {
384
+ console.error(`Failed to start npm: ${error.message}`);
385
+ process.exit(1);
386
+ });
387
+ }
388
+
389
+ function resetCurrentRelease() {
390
+ const child = spawn(process.execPath, [path.join(packageRoot, "scripts", "postinstall.js"), "--force-release"], {
391
+ cwd: packageRoot,
392
+ stdio: "inherit",
393
+ windowsHide: false
394
+ });
395
+ child.on("exit", (code, signal) => {
396
+ if (signal) {
397
+ process.kill(process.pid, signal);
398
+ return;
399
+ }
400
+ process.exit(code ?? 1);
401
+ });
402
+ child.on("error", (error) => {
403
+ console.error(`Failed to reset the npm release runtime: ${error.message}`);
404
+ process.exit(1);
405
+ });
406
+ }
407
+
408
+ async function runNpmChannel(args) {
409
+ const command = args[0] || "status";
410
+ const json = args.includes("--json");
411
+
412
+ if (command === "help" || command === "--help" || command === "-h") {
413
+ printHelp(args[1]);
414
+ return;
415
+ }
416
+ if (command === "methods") {
417
+ const methods = getInstallMethods();
418
+ if (json) console.log(JSON.stringify(methods, null, 2));
419
+ else printMethods();
420
+ return;
421
+ }
422
+ if (command === "migrate") {
423
+ if (args[1] !== "upstream") {
424
+ console.error("Only 'hermes-npm migrate upstream' is supported.");
425
+ printHelp("migrate");
426
+ process.exitCode = 2;
427
+ return;
428
+ }
429
+ const unsupported = args.slice(2).filter((arg) => !["--yes", "--json"].includes(arg));
430
+ if (unsupported.length > 0) {
431
+ console.error(`Unknown migration option: ${unsupported[0]}`);
432
+ process.exitCode = 2;
433
+ return;
434
+ }
435
+ const plan = createUpstreamMigrationPlan(detectInstallContext());
436
+ if (!args.includes("--yes")) {
437
+ if (json) console.log(JSON.stringify(plan, null, 2));
438
+ else printMigrationPlan(plan);
439
+ return;
440
+ }
441
+ if (json) {
442
+ console.error("--json cannot be combined with --yes because execution streams installer output.");
443
+ process.exitCode = 2;
444
+ return;
445
+ }
446
+ try {
447
+ console.log(`Preparing the upstream handoff to ${plan.installDirectory}...`);
448
+ await executeUpstreamMigration(plan, {
449
+ runtimeStatus: readRuntimeStatus(),
450
+ runGit
451
+ });
452
+ console.log("Upstream handoff completed. Open a new terminal and run 'hermes --version'.");
453
+ } catch (error) {
454
+ console.error(`Unable to complete the upstream handoff: ${error.message}`);
455
+ console.error("The npm package is kept unless the final npm uninstall had already started.");
456
+ process.exitCode = 1;
457
+ }
458
+ return;
459
+ }
460
+ if (command === "status") {
461
+ const status = readRuntimeStatus();
462
+ if (json) console.log(JSON.stringify(status, null, 2));
463
+ else printStatus(status);
464
+ return;
465
+ }
466
+ if (command === "check") {
467
+ try {
468
+ const latestVersion = await fetchLatestNpmVersion();
469
+ const comparison = compareSemver(latestVersion, packageJson.version);
470
+ const result = {
471
+ ...readRuntimeStatus(),
472
+ latestNpmVersion: latestVersion,
473
+ releaseUpdateAvailable: comparison > 0,
474
+ localPackageAheadOfRegistry: comparison < 0
475
+ };
476
+ if (json) console.log(JSON.stringify(result, null, 2));
477
+ else {
478
+ printStatus(result);
479
+ console.log(`latest npm: ${latestVersion}`);
480
+ if (result.releaseUpdateAvailable) console.log("release update available");
481
+ else if (result.localPackageAheadOfRegistry) console.log("local package version is newer than the npm latest dist-tag");
482
+ else console.log("npm release channel is up to date");
483
+ }
484
+ } catch (error) {
485
+ console.error(`Unable to check the npm release channel: ${error.message}`);
486
+ process.exitCode = 1;
487
+ }
488
+ return;
489
+ }
490
+ if (command === "update") {
491
+ try {
492
+ const latestVersion = await fetchLatestNpmVersion();
493
+ if (compareSemver(latestVersion, packageJson.version) < 0) {
494
+ throw new Error(`npm latest is ${latestVersion}, older than the installed ${packageJson.version}; refusing to downgrade`);
495
+ }
496
+ const comparison = compareSemver(latestVersion, packageJson.version);
497
+ if (comparison > 0) {
498
+ applyReleaseUpdate(latestVersion);
499
+ } else {
500
+ const status = readRuntimeStatus();
501
+ if (status.runtimeChannel === "npm-release") {
502
+ console.log(`The npm release channel is already at ${packageJson.version}.`);
503
+ } else {
504
+ resetCurrentRelease();
505
+ }
506
+ }
507
+ } catch (error) {
508
+ console.error(`Unable to update through the npm release channel: ${error.message}`);
509
+ process.exitCode = 1;
510
+ }
511
+ return;
512
+ }
513
+
514
+ console.error(`Unknown hermes-npm command: ${command}`);
515
+ printHelp();
516
+ process.exitCode = 2;
517
+ }
518
+
519
+ module.exports = {
520
+ assertReleaseUpdateAllowed,
521
+ detectInstallContext,
522
+ compareSemver,
523
+ fetchLatestNpmVersion,
524
+ findNodeModulesOwner,
525
+ getAliasMigrationCommands,
526
+ getInstallMethods,
527
+ getReleaseUpdateArgs,
528
+ getReleaseUpdateCommand,
529
+ pathsReferToSameInstallLocation,
530
+ printHelp,
531
+ readRuntimeStatus,
532
+ runNpmChannel
533
+ };
@@ -18,7 +18,7 @@ function getAliasPackageName(packageName) {
18
18
  }
19
19
 
20
20
  function getPackageBinNames(packageName) {
21
- const names = ["hermes", "hermes-agent"];
21
+ const names = ["hermes", "hermes-agent", "hermes-npm"];
22
22
 
23
23
  if (packageName === ALIAS_PACKAGE_NAME) {
24
24
  names.push(ALIAS_PACKAGE_NAME);
@@ -1,37 +1,18 @@
1
- const { spawn, spawnSync } = require("node:child_process");
1
+ const { spawn } = require("node:child_process");
2
+ const fs = require("node:fs");
2
3
  const path = require("node:path");
3
4
 
4
5
  const packageJson = require("../package.json");
5
6
 
6
- function getPythonCandidates(platform = process.platform) {
7
- if (platform === "win32") {
8
- return [
9
- { command: "py", args: ["-3"] },
10
- { command: "python", args: [] },
11
- { command: "python3", args: [] }
12
- ];
13
- }
7
+ const packageRoot = path.resolve(__dirname, "..");
14
8
 
15
- return [
16
- { command: "python3", args: [] },
17
- { command: "python", args: [] }
18
- ];
9
+ function getRuntimeSourceDirectory() {
10
+ const configured = packageJson.hermesAgent?.runtimeDirectory || "runtime/hermes-agent";
11
+ return path.join(packageRoot, ...configured.split("/"));
19
12
  }
20
13
 
21
- function findPython(candidates = getPythonCandidates()) {
22
- for (const candidate of candidates) {
23
- const result = spawnSync(
24
- candidate.command,
25
- [...candidate.args, "-c", "import sys; raise SystemExit(0 if sys.version_info >= (3, 11) else 1)"],
26
- { encoding: "utf8", windowsHide: true }
27
- );
28
-
29
- if (result.status === 0) {
30
- return candidate;
31
- }
32
- }
33
-
34
- return null;
14
+ function getVenvDirectory() {
15
+ return path.join(getRuntimeSourceDirectory(), "venv");
35
16
  }
36
17
 
37
18
  function normalizeBinName(binName) {
@@ -39,45 +20,56 @@ function normalizeBinName(binName) {
39
20
  return baseName.replace(/(\.cmd|\.exe)$/i, "");
40
21
  }
41
22
 
42
- function getPythonEntryPoint(binName) {
43
- return normalizeBinName(binName) === "hermes" ? "hermes_cli.main" : "run_agent";
44
- }
45
-
46
- function getPythonCode(binName) {
47
- const moduleName = getPythonEntryPoint(binName);
48
- return `from ${moduleName} import main; raise SystemExit(main())`;
23
+ function getConsoleExecutable(binName, platform = process.platform) {
24
+ const normalized = normalizeBinName(binName) === "hermes" ? "hermes" : "hermes-agent";
25
+ if (platform === "win32") {
26
+ return path.join(getVenvDirectory(), "Scripts", `${normalized}.exe`);
27
+ }
28
+ return path.join(getVenvDirectory(), "bin", normalized);
49
29
  }
50
30
 
51
- function buildPythonInvocation(candidate, binName, userArgs) {
31
+ function buildConsoleInvocation(binName, userArgs, platform = process.platform) {
52
32
  return {
53
- command: candidate.command,
54
- args: [...candidate.args, "-c", getPythonCode(binName), ...userArgs]
33
+ command: getConsoleExecutable(binName, platform),
34
+ args: [...userArgs]
55
35
  };
56
36
  }
57
37
 
58
- function getPythonPackageSpec() {
59
- const version = packageJson.hermesAgent?.pythonPackageVersion || packageJson.version;
60
- return `hermes-agent==${version}`;
38
+ function getRuntimeEnvironment() {
39
+ const env = {
40
+ ...process.env,
41
+ VIRTUAL_ENV: getVenvDirectory(),
42
+ HERMES_NPM_BRIDGE: "1",
43
+ HERMES_NPM_PACKAGE_ROOT: packageRoot,
44
+ HERMES_NPM_PACKAGE_VERSION: packageJson.version,
45
+ HERMES_NPM_RELEASE_TAG: packageJson.hermesAgent?.upstreamGitTag || ""
46
+ };
47
+ delete env.PYTHONHOME;
48
+ delete env.PYTHONPATH;
49
+ return env;
61
50
  }
62
51
 
63
52
  function runHermes(binName, userArgs, stdio = "inherit") {
64
- const candidate = findPython();
53
+ const invocation = buildConsoleInvocation(binName, userArgs);
65
54
 
66
- if (!candidate) {
67
- console.error("Hermes Agent requires Python 3.11 or newer.");
68
- console.error("Install Python, then run: python -m pip install --upgrade " + getPythonPackageSpec());
55
+ if (!fs.existsSync(invocation.command)) {
56
+ console.error("Hermes Agent isolated runtime is not ready.");
57
+ console.error("Run 'npm rebuild hermes-agent' or reinstall the npm package.");
58
+ process.exitCode = 1;
69
59
  return 1;
70
60
  }
71
61
 
72
- const invocation = buildPythonInvocation(candidate, binName, userArgs);
73
- const child = spawn(invocation.command, invocation.args, { stdio, windowsHide: false });
62
+ const child = spawn(invocation.command, invocation.args, {
63
+ env: getRuntimeEnvironment(),
64
+ stdio,
65
+ windowsHide: false
66
+ });
74
67
 
75
68
  child.on("exit", (code, signal) => {
76
69
  if (signal) {
77
70
  process.kill(process.pid, signal);
78
71
  return;
79
72
  }
80
-
81
73
  process.exit(code ?? 1);
82
74
  });
83
75
 
@@ -90,10 +82,11 @@ function runHermes(binName, userArgs, stdio = "inherit") {
90
82
  }
91
83
 
92
84
  module.exports = {
93
- buildPythonInvocation,
94
- findPython,
95
- getPythonCandidates,
96
- getPythonEntryPoint,
97
- getPythonPackageSpec,
85
+ buildConsoleInvocation,
86
+ getConsoleExecutable,
87
+ getRuntimeEnvironment,
88
+ getRuntimeSourceDirectory,
89
+ getVenvDirectory,
90
+ normalizeBinName,
98
91
  runHermes
99
92
  };