atp-hermes-hook 0.1.1 → 0.2.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.
package/README.md CHANGED
@@ -4,7 +4,76 @@ A fail-closed [Hermes Agent](https://github.com/NousResearch/hermes-agent) `pre_
4
4
 
5
5
  Requires Node.js 20 or newer. Want to see the decisions before changing Hermes settings? Start with the [local walkthrough](https://github.com/agent-trust-protocol/atp-core/tree/main/examples/hermes-hook), which runs the hook without starting Hermes or calling a model.
6
6
 
7
- ## Install
7
+ ## One-command setup (macOS/Linux)
8
+
9
+ Requires Hermes on your PATH and Node.js 20 or newer. From any directory, run:
10
+
11
+ ```bash
12
+ npx --yes atp-hermes-hook@0.2.1 setup
13
+ ```
14
+
15
+ This creates an `atp-pilot` Hermes profile if needed, installs a fixed copy under
16
+ `~/.hermes/agent-hooks/atp`, and creates a `safe-default` policy that allows reads
17
+ only within a disposable test folder. Terminal, write and patch calls are blocked.
18
+ Every tool call is intercepted; unmapped tools, including `execute_code`, are blocked.
19
+ It runs standalone read/terminal/write and unmapped-tool decision checks, backs up the profile's
20
+ `config.yaml`, and merges a fail-closed hook while preserving other hooks and
21
+ settings. It does not install packages into your current directory.
22
+
23
+ Hermes runs the persistent local copy, with no `npx` network fetch per tool call.
24
+ Setup does not restart gateways, import OpenClaw data, configure a model/provider,
25
+ or bypass Hermes' first-use consent. If the new profile needs a provider, run
26
+ `hermes -p atp-pilot setup` and skip unrelated migrations and messaging setup.
27
+
28
+ Verify Hermes' wiring next:
29
+
30
+ ```bash
31
+ hermes -p atp-pilot hooks test pre_tool_call --for-tool terminal
32
+ hermes -p atp-pilot chat
33
+ ```
34
+
35
+ Review and approve the exact local hook when Hermes asks. Expect an ATP terminal
36
+ block in the hook test. Complete the [live tool-call check](../../examples/hermes-hook/README.md#check-blocking-in-your-own-test-profile)
37
+ using this installation's `test-files/atp-setup-fixture.txt` as the allowed file.
38
+ Standalone checks do not prove live enforcement or signed mandate verification.
39
+
40
+ To choose another profile and read scope:
41
+
42
+ ```bash
43
+ npx --yes atp-hermes-hook@0.2.1 setup --hermes-profile my-test-profile --read /absolute/path/to/docs
44
+ ```
45
+
46
+ `--read` may be repeated; it replaces the default test-folder read scope on first
47
+ setup. No write scope is granted. Custom or existing policies receive terminal and
48
+ write checks; the fixture read check runs only when the test folder is an explicit
49
+ read root. Profiles configured by setup share this installation's policy file;
50
+ use manual installation for different policies per profile. `--hermes-home` selects
51
+ a custom Hermes root. Setup rejects malformed YAML, preserves existing ATP policies,
52
+ and refuses to replace their read scope implicitly. Rerunning setup does not add
53
+ duplicate copies of the same command. Existing manually configured ATP commands
54
+ are preserved with other hooks; review them separately if migrating. Unmapped
55
+ tools are blocked, so features such as code execution, browser automation and
56
+ delegation are unavailable until explicitly mapped and reviewed. Use WSL on Windows.
57
+
58
+ ### Upgrade from 0.2.0 or a manual four-tool matcher
59
+
60
+ The earlier `^(read_file|terminal|write_file|patch)$` matcher did not intercept
61
+ `execute_code`. A live pilot reported a blocked terminal call followed by a
62
+ successful Python subprocess through that alternate tool. The four-tool check
63
+ therefore did not establish execution containment. Re-run setup at 0.2.1 to
64
+ replace the installer's matcher with `.*`, or update your manual matcher below.
65
+ Upgrading the package alone does not update profile YAML. Restart the affected
66
+ CLI session (and deliberately restart any affected gateway) after configuration
67
+ changes. Verify both `terminal` and `execute_code` are blocked through Hermes.
68
+
69
+ To undo the YAML change, restore the exact backup path printed by setup. This
70
+ restores the whole pre-setup file, so preserve later configuration edits first.
71
+ Revoke consent with `hermes -p <profile> hooks revoke '<exact command>'` if needed.
72
+ Running gateways require a deliberate restart to pick up changes; setup never
73
+ restarts them. Package files and the ATP policy remain available for inspection
74
+ after a failed or undone setup.
75
+
76
+ ## Manual install
8
77
 
9
78
  Install it locally (not through `npx`) so Hermes runs a fixed, reviewed copy without a network fetch on every tool call:
10
79
 
@@ -50,7 +119,7 @@ Then add the hook to your Hermes profile's `config.yaml`, using absolute paths:
50
119
  ```yaml
51
120
  hooks:
52
121
  pre_tool_call:
53
- - matcher: "^(read_file|terminal|write_file|patch)$"
122
+ - matcher: ".*"
54
123
  command: "/home/me/.hermes/agent-hooks/atp/node_modules/.bin/atp-hermes-hook --config /home/me/.hermes/agent-hooks/atp/atp-hermes.json"
55
124
  timeout: 10
56
125
  fail_closed: true
@@ -83,7 +152,10 @@ Every block writes `{"action":"block","message":"ATP: ..."}` and **exits with co
83
152
  | `patch` | `filesystem` (write) | `path` |
84
153
  | `terminal` | `shell` | — |
85
154
 
86
- To cover more tools, map them and widen the Hermes `matcher` to match:
155
+ Every tool reaches this hook. To permit another tool, map it explicitly after
156
+ reviewing its capabilities. Do not map a general interpreter to a harmless
157
+ category: `execute_code` can run subprocesses and access files directly.
158
+ For example, to evaluate a network tool and remove the terminal mapping:
87
159
 
88
160
  ```json
89
161
  {
@@ -9,6 +9,8 @@ const BLOCK_EXIT = 2;
9
9
  const USAGE = `Usage: atp-hermes-hook --config <file> (reads a Hermes pre_tool_call event on stdin)
10
10
  atp-hermes-hook --check --config <file>
11
11
  atp-hermes-hook --version
12
+ atp-hermes-hook setup [--hermes-profile atp-pilot] [--read <directory>]
13
+ [--hermes-home <directory>]
12
14
 
13
15
  The configuration file can also be set with ATP_HERMES_HOOK_CONFIG.`;
14
16
 
@@ -88,4 +90,14 @@ function main() {
88
90
  }
89
91
  }
90
92
 
91
- main();
93
+ if (process.argv[2] === 'setup') {
94
+ try {
95
+ const { parseSetupArgs, setupHermes } = await import('../src/setup.mjs');
96
+ setupHermes(parseSetupArgs(process.argv.slice(3)));
97
+ } catch (error) {
98
+ process.stderr.write(`atp-hermes-hook setup: ${error.message}\n`);
99
+ process.exitCode = 1;
100
+ }
101
+ } else {
102
+ main();
103
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "atp-hermes-hook",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Fail-closed Hermes Agent pre_tool_call hook that enforces Agent Trust Protocol (ATP) security profiles at the tool boundary",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -42,7 +42,8 @@
42
42
  "url": "https://github.com/agent-trust-protocol/atp-core/issues"
43
43
  },
44
44
  "dependencies": {
45
- "atp-profiles": "^3.0.0"
45
+ "atp-profiles": "^3.0.0",
46
+ "yaml": "^2.9.1"
46
47
  },
47
48
  "engines": {
48
49
  "node": ">=20.0.0"
package/src/setup.mjs ADDED
@@ -0,0 +1,158 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { parseDocument } from 'yaml';
8
+ import { loadConfig } from './index.mjs';
9
+
10
+ // Dispatch every tool through ATP. Otherwise an unmapped execution tool (for
11
+ // example execute_code -> subprocess) can route around a blocked terminal call.
12
+ const MATCHER = '.*';
13
+ const packageRoot = fileURLToPath(new URL('../', import.meta.url));
14
+
15
+ function run(command, args, options = {}) {
16
+ const result = spawnSync(command, args, { encoding: 'utf8', timeout: 120_000, ...options });
17
+ if (result.error || result.status !== 0) {
18
+ throw new Error(`${command} ${args[0] ?? ''} failed: ${result.error?.message ?? result.stderr?.trim() ?? result.status}`);
19
+ }
20
+ return result;
21
+ }
22
+
23
+ function atomicWrite(file, content) {
24
+ const temp = `${file}.${randomUUID()}.tmp`;
25
+ try {
26
+ writeFileSync(temp, content, { mode: 0o600, flag: 'wx' });
27
+ renameSync(temp, file);
28
+ } finally {
29
+ rmSync(temp, { force: true });
30
+ }
31
+ }
32
+
33
+ function readProfile(file) {
34
+ const source = readFileSync(file, 'utf8');
35
+ const doc = parseDocument(source);
36
+ if (doc.errors.length) throw new Error(`Invalid Hermes YAML: ${doc.errors[0].message}`);
37
+ const config = doc.toJS({ maxAliasCount: 100 });
38
+ if (config !== null && (typeof config !== 'object' || Array.isArray(config))) {
39
+ throw new Error('Hermes config.yaml must contain a mapping');
40
+ }
41
+ const hooks = config?.hooks;
42
+ if (hooks != null && (typeof hooks !== 'object' || Array.isArray(hooks))) {
43
+ throw new Error('Existing hooks must be a mapping; no configuration was changed');
44
+ }
45
+ const entries = hooks?.pre_tool_call ?? [];
46
+ if (!Array.isArray(entries) || entries.some((entry) => !entry || typeof entry !== 'object' || Array.isArray(entry))) {
47
+ throw new Error('Existing hooks.pre_tool_call must be a list of mappings');
48
+ }
49
+ return { doc, source, entries };
50
+ }
51
+
52
+ /** Install a fixed local hook, merge it into one Hermes profile, and test its wire contract.
53
+ * The injected runner/package source are for packed-package tests, never CLI options.
54
+ */
55
+ export function setupHermes({ profile = 'atp-pilot', hermesHome = process.env.HERMES_HOME || join(homedir(), '.hermes'), read = [] } = {}, {
56
+ execute = run, packageSource, output = console.log,
57
+ } = {}) {
58
+ if (process.platform === 'win32') throw new Error('Run setup in WSL; native Windows setup is not supported yet');
59
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(profile)) throw new Error('Invalid Hermes profile name');
60
+ const home = resolve(hermesHome);
61
+ const profileDir = profile === 'default' ? home : join(home, 'profiles', profile);
62
+ const profileFile = join(profileDir, 'config.yaml');
63
+ const installDir = join(home, 'agent-hooks', 'atp');
64
+ const policyFile = join(installDir, 'atp-hermes.json');
65
+ // Hermes profile resolution and creation must use the same root as our file edits.
66
+ const hermesEnv = { ...process.env, HERMES_HOME: home };
67
+ const hermes = (args) => execute('hermes', args, { env: hermesEnv });
68
+ hermes(['--version']);
69
+ for (const path of read) {
70
+ if (!existsSync(resolve(path))) throw new Error(`Read scope does not exist: ${path}`);
71
+ }
72
+ if (existsSync(policyFile)) {
73
+ loadConfig(policyFile); // Keep a valid existing policy; never silently broaden it.
74
+ if (read.length) throw new Error(`An ATP policy already exists at ${policyFile}; edit its read scope explicitly`);
75
+ }
76
+ if (!existsSync(profileFile)) {
77
+ if (existsSync(profileDir)) throw new Error(`Profile directory exists without config.yaml: ${profileDir}`);
78
+ hermes(['profile', 'create', profile]);
79
+ }
80
+ const before = readProfile(profileFile); // Reject malformed/duplicate YAML before installing.
81
+ const version = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')).version;
82
+ mkdirSync(installDir, { recursive: true, mode: 0o700 });
83
+ output(`Installing a fixed local copy of atp-hermes-hook@${version}…`);
84
+ execute('npm', ['install', '--prefix', installDir, '--ignore-scripts', '--save-exact', '--no-fund', '--no-audit',
85
+ packageSource ?? `atp-hermes-hook@${version}`]);
86
+ const stableBin = join(installDir, 'node_modules', 'atp-hermes-hook', 'bin', 'atp-hermes-hook.mjs');
87
+ const fixtureDir = join(installDir, 'test-files');
88
+ mkdirSync(fixtureDir, { recursive: true, mode: 0o700 });
89
+ const fixture = join(fixtureDir, 'atp-setup-fixture.txt');
90
+ if (!existsSync(fixture)) writeFileSync(fixture, 'ATP Hermes read test.\n', { flag: 'wx', mode: 0o600 });
91
+ if (!existsSync(policyFile)) {
92
+ const policy = { profile: 'safe-default', state: 'executing', onApproval: 'block',
93
+ paths: { read: read.length ? read.map((path) => resolve(path)) : [fixtureDir], write: [] } };
94
+ writeFileSync(policyFile, `${JSON.stringify(policy, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
95
+ }
96
+ const config = loadConfig(policyFile);
97
+ execute(process.execPath, [stableBin, '--check', '--config', policyFile]);
98
+ const tests = [
99
+ ['terminal blocked', { tool_name: 'terminal', tool_input: { command: 'echo ATP-test' } }, 2],
100
+ ['write blocked', { tool_name: 'write_file', tool_input: { path: fixture, content: 'must not be written' } }, 2],
101
+ ['execute_code blocked', { tool_name: 'execute_code', tool_input: { code: 'import subprocess' } }, 2],
102
+ ['unmapped tool blocked', { tool_name: 'future_execution_tool', tool_input: {} }, 2],
103
+ ];
104
+ // The default fixture is the only read scope we can prove without reading a user's files.
105
+ if (config.roots.read.includes(fixtureDir)) {
106
+ tests.unshift(['fixture read allowed', { tool_name: 'read_file', tool_input: { path: fixture } }, 0]);
107
+ }
108
+ for (const [label, payload, expected] of tests) {
109
+ const result = spawnSync(process.execPath, [stableBin, '--config', policyFile], {
110
+ input: JSON.stringify({ hook_event_name: 'pre_tool_call', ...payload }), encoding: 'utf8', timeout: 10_000,
111
+ });
112
+ let directive;
113
+ try { directive = JSON.parse(result.stdout); } catch { /* report below */ }
114
+ if (result.status !== expected || !directive ||
115
+ (expected === 2 ? directive.action !== 'block' : Object.keys(directive).length !== 0)) {
116
+ throw new Error(`Self-test failed: ${label}; Hermes configuration was not changed`);
117
+ }
118
+ output(`PASS: ${label}`);
119
+ }
120
+ const command = [process.execPath, stableBin, '--config', policyFile].map((part) => JSON.stringify(part)).join(' ');
121
+ // Re-read after npm finishes: do not overwrite edits made during installation.
122
+ const current = readProfile(profileFile);
123
+ if (current.source !== before.source) throw new Error('Hermes configuration changed during setup; rerun setup');
124
+ const entry = { matcher: MATCHER, command, timeout: 10, fail_closed: true };
125
+ const entries = current.entries.filter((existing) => existing.command !== command);
126
+ entries.push(entry);
127
+ current.doc.setIn(['hooks', 'pre_tool_call'], entries);
128
+ const updated = current.doc.toString();
129
+ let backup = null;
130
+ if (updated !== current.source) {
131
+ backup = `${profileFile}.before-atp-${randomUUID()}`;
132
+ writeFileSync(backup, current.source, { flag: 'wx', mode: 0o600 });
133
+ atomicWrite(profileFile, updated);
134
+ }
135
+ output(`Configured Hermes profile: ${profile}`);
136
+ if (backup) output(`Backup: ${backup}`);
137
+ output(`Policy: ${policyFile}`);
138
+ output('Scope: every pre_tool_call is checked. Unmapped tools, including execute_code, are blocked.');
139
+ output('Standalone self-tests passed. Live Hermes enforcement is not verified yet.');
140
+ output(`Next: hermes -p ${profile} hooks test pre_tool_call --for-tool terminal`);
141
+ output('Review and approve the local hook when Hermes requests first-use consent.');
142
+ output(`Then: hermes -p ${profile} chat (run setup for this profile first if its provider is not configured).`);
143
+ output('No gateway was restarted and hook consent was not bypassed.');
144
+ return { profileFile, policyFile, stableBin, command, backup };
145
+ }
146
+
147
+ export function parseSetupArgs(args) {
148
+ const options = { read: [] };
149
+ for (let index = 0; index < args.length; index += 1) {
150
+ const flag = args[index];
151
+ if (!['--hermes-profile', '--hermes-home', '--read'].includes(flag)) throw new Error(`Unknown setup option: ${flag}`);
152
+ const value = args[++index];
153
+ if (!value || value.startsWith('--')) throw new Error(`${flag} requires a value`);
154
+ if (flag === '--read') options.read.push(value);
155
+ else options[flag === '--hermes-profile' ? 'profile' : 'hermesHome'] = value;
156
+ }
157
+ return options;
158
+ }