atp-hermes-hook 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 The Agent Trust Protocol Contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,122 @@
1
- # Temporary Holding Version
1
+ # atp-hermes-hook
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A fail-closed [Hermes Agent](https://github.com/NousResearch/hermes-agent) `pre_tool_call` shell hook that enforces **Agent Trust Protocol (ATP)** security profiles at the tool boundary. Before Hermes runs a matched tool, the hook evaluates it against an [`atp-profiles`](https://www.npmjs.com/package/atp-profiles) profile and a path scope you configure, then lets the call through, blocks it, or sends it to Hermes' human-approval gate.
4
+
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
+
7
+ ## Install
8
+
9
+ Install it locally (not through `npx`) so Hermes runs a fixed, reviewed copy without a network fetch on every tool call:
10
+
11
+ ```bash
12
+ mkdir -p ~/.hermes/agent-hooks/atp && cd ~/.hermes/agent-hooks/atp
13
+ npm init -y >/dev/null
14
+ npm install atp-hermes-hook
15
+ ```
16
+
17
+ ## Configure
18
+
19
+ Create `~/.hermes/agent-hooks/atp/atp-hermes.json`:
20
+
21
+ ```json
22
+ {
23
+ "profile": "safe-default",
24
+ "state": "executing",
25
+ "onApproval": "block",
26
+ "paths": {
27
+ "read": ["/home/me/projects/docs"],
28
+ "write": []
29
+ }
30
+ }
31
+ ```
32
+
33
+ | Key | Default | Meaning |
34
+ | --- | --- | --- |
35
+ | `profile` | `safe-default` | A built-in `atp-profiles` profile: `safe-default`, `dev-mode`, `enterprise-locked`, `openclaw-sandbox`. Unknown names are a configuration error. |
36
+ | `state` | `executing` | ATP lifecycle state: `planning`, `executing`, `communicating`, `completed`. |
37
+ | `onApproval` | `block` | What to do when the profile says `require_approval`: `block`, or `escalate` to Hermes' approval gate. |
38
+ | `paths.read` | `[]` | Directories that read tools may access. Relative entries resolve against the config file's directory. |
39
+ | `paths.write` | `[]` | Directories that write tools may modify. These are also readable. |
40
+ | `tools` | see below | Map Hermes tool names to ATP actions; `null` removes a default. |
41
+
42
+ Check the file before using it:
43
+
44
+ ```bash
45
+ ./node_modules/.bin/atp-hermes-hook --check --config ./atp-hermes.json
46
+ ```
47
+
48
+ Then add the hook to your Hermes profile's `config.yaml`, using absolute paths:
49
+
50
+ ```yaml
51
+ hooks:
52
+ pre_tool_call:
53
+ - matcher: "^(read_file|terminal|write_file|patch)$"
54
+ command: "/home/me/.hermes/agent-hooks/atp/node_modules/.bin/atp-hermes-hook --config /home/me/.hermes/agent-hooks/atp/atp-hermes.json"
55
+ timeout: 10
56
+ fail_closed: true
57
+ ```
58
+
59
+ Hermes asks for consent the first time it sees this hook. Review the installed code before you approve it. Hermes keys consent on the exact command string, not the script's contents, so re-review after upgrading. Keep `fail_closed: true`.
60
+
61
+ Verify the hook in a test profile: [allow one test-file read and confirm that the terminal attempt is blocked](https://github.com/agent-trust-protocol/atp-core/blob/main/examples/hermes-hook/README.md#check-blocking-in-your-own-test-profile). If that helped you protect a tool action, [star ATP Core](https://github.com/agent-trust-protocol/atp-core) to follow the project. [Share your result or setup blocker](https://github.com/agent-trust-protocol/atp-core/blob/main/docs/launch/developer-pilot.md).
62
+
63
+ ## Feedback and support
64
+
65
+ [Rate your setup experience](https://github.com/agent-trust-protocol/atp-core/blob/main/docs/package-feedback.md#hermes), leave a comment, or report a reproducible issue. Include `atp-hermes-hook`, its installed version, your runtime, and what you expected to happen. Remove secrets and private data from examples and logs. For vulnerabilities, follow the [private reporting guidance](https://github.com/agent-trust-protocol/atp-core/blob/main/SECURITY.md#reporting-a-vulnerability).
66
+
67
+ ## How a call is decided
68
+
69
+ 1. Anything that is not a `pre_tool_call` event, or a tool missing from `tools`, is **blocked**.
70
+ 2. The tool's ATP category (for example `shell` or `filesystem`) is evaluated against the profile and state with `evaluateActionWithProfile`. A `deny` is **blocked**.
71
+ 3. Filesystem tools must use a mode the profile permits (`safe-default` and `enterprise-locked` are read-only). Their path must also resolve, after following symlinks, to a location inside `paths`. Writes may create a new file only in an existing directory, and never through a dangling symlink.
72
+ 4. A `require_approval` decision is **blocked**, or, with `"onApproval": "escalate"`, returned as `{"action": "approve"}`. Hermes then asks a human; denial, timeout or a gate error fails closed. The approval `rule_key` is `atp:<profile>:<tool>`, so an "always" answer covers every later call of that tool under that profile.
73
+ 5. Otherwise the call proceeds (`{}`).
74
+
75
+ Every block writes `{"action":"block","message":"ATP: ..."}` and **exits with code 2**, which Hermes treats as a block even if `fail_closed` is missing. A missing or invalid configuration, unreadable input or an internal error also blocks.
76
+
77
+ ### Default tool mapping
78
+
79
+ | Hermes tool | ATP category | Path argument |
80
+ | --- | --- | --- |
81
+ | `read_file` | `filesystem` (read) | `path` |
82
+ | `write_file` | `filesystem` (write) | `path` |
83
+ | `patch` | `filesystem` (write) | `path` |
84
+ | `terminal` | `shell` | — |
85
+
86
+ To cover more tools, map them and widen the Hermes `matcher` to match:
87
+
88
+ ```json
89
+ {
90
+ "tools": {
91
+ "web_search": { "category": "network" },
92
+ "terminal": null
93
+ }
94
+ }
95
+ ```
96
+
97
+ Removing `terminal` from `tools` while the matcher still matches it means every terminal call is blocked as unmapped.
98
+
99
+ ## What this does not do
100
+
101
+ - It is a policy gate, not a sandbox. The path check and the tool's own file access are separate steps, so a concurrent change to the filesystem between them is not prevented. Keep Hermes' native permissions and sandbox, and protect the scoped directories from untrusted writers.
102
+ - Profile `network` domain lists, `shell.allowed_commands`, and the example `allowed_paths` inside built-in profiles are not enforced by this hook. Path scope comes only from this hook's `paths`.
103
+ - It does not verify identity, trust scores or mandates, and it does not write a signed audit log.
104
+ - Hermes shell hooks are trusted local code. Another hook or plugin can still affect execution.
105
+
106
+ ## Library use
107
+
108
+ ```js
109
+ import { loadConfig, decide } from 'atp-hermes-hook';
110
+
111
+ const config = loadConfig('/path/to/atp-hermes.json');
112
+ decide(config, { hook_event_name: 'pre_tool_call', tool_name: 'terminal', tool_input: { command: 'ls' } });
113
+ // { action: 'block', message: 'ATP: terminal requires approval under profile safe-default; approval escalation is disabled' }
114
+ ```
115
+
116
+ ## Verification
117
+
118
+ `npm test` covers configuration validation, path scoping (including symlink and traversal escapes), profile decisions and the binary's exit codes. `test/verify-live-hermes.py` runs a real Hermes `AIAgent` session, at a pinned Hermes commit, against a deterministic local provider. In that session an in-scope read executes, while terminal, write and out-of-scope read calls are blocked without running. CI runs it against the packed npm tarball. That shows runtime integration with scripted tool selection; it is not an evaluation of autonomous model behaviour.
119
+
120
+ ## License
121
+
122
+ Apache-2.0. Part of [ATP Core](https://github.com/agent-trust-protocol/atp-core), the open developer foundation for Agent Trust Protocol.
@@ -0,0 +1,91 @@
1
+ #!/usr/bin/env node
2
+ // Hermes Agent shell pre_tool_call hook. Reads one JSON event on stdin and writes
3
+ // one JSON directive on stdout. Every failure path blocks and exits with code 2,
4
+ // which Hermes treats as a block even when fail_closed is not set.
5
+ import { readFileSync } from 'node:fs';
6
+ import { decide, loadConfig } from '../src/index.mjs';
7
+
8
+ const BLOCK_EXIT = 2;
9
+ const USAGE = `Usage: atp-hermes-hook --config <file> (reads a Hermes pre_tool_call event on stdin)
10
+ atp-hermes-hook --check --config <file>
11
+ atp-hermes-hook --version
12
+
13
+ The configuration file can also be set with ATP_HERMES_HOOK_CONFIG.`;
14
+
15
+ function emit(directive) {
16
+ process.stdout.write(`${JSON.stringify(directive)}\n`);
17
+ process.exitCode = directive.action === 'block' ? BLOCK_EXIT : 0;
18
+ }
19
+
20
+ function parseArgs(argv) {
21
+ const options = { config: process.env.ATP_HERMES_HOOK_CONFIG, check: false, help: false, version: false };
22
+ for (let i = 0; i < argv.length; i += 1) {
23
+ const arg = argv[i];
24
+ if (arg === '--config') options.config = argv[(i += 1)];
25
+ else if (arg.startsWith('--config=')) options.config = arg.slice('--config='.length);
26
+ else if (arg === '--check') options.check = true;
27
+ else if (arg === '--help' || arg === '-h') options.help = true;
28
+ else if (arg === '--version') options.version = true;
29
+ else throw new Error(`unknown argument: ${arg}`);
30
+ }
31
+ return options;
32
+ }
33
+
34
+ function main() {
35
+ let options;
36
+ try {
37
+ options = parseArgs(process.argv.slice(2));
38
+ } catch (error) {
39
+ emit({ action: 'block', message: `ATP: hook invocation error: ${error.message}` });
40
+ return;
41
+ }
42
+ if (options.help) {
43
+ process.stdout.write(`${USAGE}\n`);
44
+ return;
45
+ }
46
+ if (options.version) {
47
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
48
+ process.stdout.write(`${pkg.version}\n`);
49
+ return;
50
+ }
51
+
52
+ let config;
53
+ try {
54
+ config = loadConfig(options.config);
55
+ } catch (error) {
56
+ if (options.check) {
57
+ process.stderr.write(`atp-hermes-hook: ${error.message}\n`);
58
+ process.exitCode = 1;
59
+ } else {
60
+ emit({ action: 'block', message: `ATP: hook configuration error: ${error.message}` });
61
+ }
62
+ return;
63
+ }
64
+
65
+ if (options.check) {
66
+ const summary = {
67
+ profile: config.profileName,
68
+ state: config.state,
69
+ onApproval: config.onApproval,
70
+ tools: config.tools,
71
+ paths: config.roots,
72
+ };
73
+ process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);
74
+ return;
75
+ }
76
+
77
+ let payload;
78
+ try {
79
+ payload = JSON.parse(readFileSync(0, 'utf8'));
80
+ } catch {
81
+ emit({ action: 'block', message: 'ATP: invalid hook input' });
82
+ return;
83
+ }
84
+ try {
85
+ emit(decide(config, payload));
86
+ } catch {
87
+ emit({ action: 'block', message: 'ATP: internal hook error' });
88
+ }
89
+ }
90
+
91
+ main();
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "atp-hermes-hook",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Fail-closed Hermes Agent pre_tool_call hook that enforces Agent Trust Protocol (ATP) security profiles at the tool boundary",
5
+ "type": "module",
6
+ "main": "./src/index.mjs",
7
+ "exports": {
8
+ ".": "./src/index.mjs",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "bin": {
12
+ "atp-hermes-hook": "bin/atp-hermes-hook.mjs"
13
+ },
14
+ "files": [
15
+ "bin/",
16
+ "src/",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "test": "node --test test/*.test.mjs"
22
+ },
23
+ "keywords": [
24
+ "atp",
25
+ "agent-trust-protocol",
26
+ "hermes",
27
+ "hermes-agent",
28
+ "pre_tool_call",
29
+ "hook",
30
+ "ai-agents",
31
+ "policy"
32
+ ],
33
+ "author": "ATP Development Team",
34
+ "license": "Apache-2.0",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/agent-trust-protocol/atp-core.git",
38
+ "directory": "packages/hermes-hook"
39
+ },
40
+ "homepage": "https://github.com/agent-trust-protocol/atp-core/tree/main/packages/hermes-hook#readme",
41
+ "bugs": {
42
+ "url": "https://github.com/agent-trust-protocol/atp-core/issues"
43
+ },
44
+ "dependencies": {
45
+ "atp-profiles": "^3.0.0"
46
+ },
47
+ "engines": {
48
+ "node": ">=20.0.0"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
53
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,207 @@
1
+ import { lstatSync, readFileSync, realpathSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
3
+ import { BUILTIN_PROFILES, evaluateActionWithProfile } from 'atp-profiles';
4
+
5
+ /**
6
+ * Default mapping from Hermes tool names to ATP action categories. Filesystem
7
+ * tools name the argument that carries their target path so the hook can scope it.
8
+ */
9
+ export const DEFAULT_TOOLS = Object.freeze({
10
+ read_file: Object.freeze({ category: 'filesystem', mode: 'read', pathArg: 'path' }),
11
+ write_file: Object.freeze({ category: 'filesystem', mode: 'write', pathArg: 'path' }),
12
+ patch: Object.freeze({ category: 'filesystem', mode: 'write', pathArg: 'path' }),
13
+ terminal: Object.freeze({ category: 'shell' }),
14
+ });
15
+
16
+ const STATES = new Set(['planning', 'executing', 'communicating', 'completed']);
17
+ const CONFIG_KEYS = new Set(['$schema', 'profile', 'state', 'tools', 'paths', 'onApproval']);
18
+
19
+ export class ConfigError extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = 'ConfigError';
23
+ }
24
+ }
25
+
26
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
27
+ const block = (message) => ({ action: 'block', message: `ATP: ${message}` });
28
+
29
+ function normalizeTool(name, spec) {
30
+ if (!isObject(spec)) throw new ConfigError(`tools.${name} must be an object or null`);
31
+ for (const key of Object.keys(spec)) {
32
+ if (!['category', 'mode', 'pathArg'].includes(key)) throw new ConfigError(`tools.${name}: unknown key ${key}`);
33
+ }
34
+ if (typeof spec.category !== 'string' || spec.category === '') {
35
+ throw new ConfigError(`tools.${name}.category must be a non-empty string`);
36
+ }
37
+ if (spec.category === 'filesystem') {
38
+ if (spec.mode !== 'read' && spec.mode !== 'write') {
39
+ throw new ConfigError(`tools.${name}.mode must be "read" or "write" for filesystem tools`);
40
+ }
41
+ if (typeof spec.pathArg !== 'string' || spec.pathArg === '') {
42
+ throw new ConfigError(`tools.${name}.pathArg must name the argument that holds the path`);
43
+ }
44
+ return Object.freeze({ category: 'filesystem', mode: spec.mode, pathArg: spec.pathArg });
45
+ }
46
+ if (spec.mode !== undefined || spec.pathArg !== undefined) {
47
+ throw new ConfigError(`tools.${name}: mode and pathArg apply only to filesystem tools`);
48
+ }
49
+ return Object.freeze({ category: spec.category });
50
+ }
51
+
52
+ function normalizeRoots(list, label, baseDir) {
53
+ if (list === undefined) return Object.freeze([]);
54
+ if (!Array.isArray(list)) throw new ConfigError(`paths.${label} must be an array of directories`);
55
+ return Object.freeze(list.map((entry) => {
56
+ if (typeof entry !== 'string' || entry === '') throw new ConfigError(`paths.${label} entries must be non-empty strings`);
57
+ try {
58
+ return realpathSync(resolve(baseDir, entry));
59
+ } catch {
60
+ throw new ConfigError(`paths.${label}: ${entry} does not exist`);
61
+ }
62
+ }));
63
+ }
64
+
65
+ /**
66
+ * Validate a raw configuration object. Relative paths resolve against baseDir
67
+ * (the configuration file's directory when loaded with loadConfig).
68
+ */
69
+ export function normalizeConfig(raw, baseDir = process.cwd()) {
70
+ if (!isObject(raw)) throw new ConfigError('configuration must be a JSON object');
71
+ for (const key of Object.keys(raw)) {
72
+ if (!CONFIG_KEYS.has(key)) throw new ConfigError(`unknown configuration key: ${key}`);
73
+ }
74
+ const profileName = raw.profile ?? 'safe-default';
75
+ if (typeof profileName !== 'string' || !Object.hasOwn(BUILTIN_PROFILES, profileName)) {
76
+ throw new ConfigError(`unknown profile: ${String(profileName)} (built-in: ${Object.keys(BUILTIN_PROFILES).join(', ')})`);
77
+ }
78
+ const state = raw.state ?? 'executing';
79
+ if (!STATES.has(state)) throw new ConfigError(`state must be one of ${[...STATES].join(', ')}`);
80
+ const onApproval = raw.onApproval ?? 'block';
81
+ if (onApproval !== 'block' && onApproval !== 'escalate') {
82
+ throw new ConfigError('onApproval must be "block" or "escalate"');
83
+ }
84
+
85
+ const tools = { ...DEFAULT_TOOLS };
86
+ if (raw.tools !== undefined) {
87
+ if (!isObject(raw.tools)) throw new ConfigError('tools must be an object');
88
+ for (const [name, spec] of Object.entries(raw.tools)) {
89
+ if (spec === null) delete tools[name];
90
+ else tools[name] = normalizeTool(name, spec);
91
+ }
92
+ }
93
+
94
+ if (raw.paths !== undefined && !isObject(raw.paths)) throw new ConfigError('paths must be an object');
95
+ const paths = raw.paths ?? {};
96
+ for (const key of Object.keys(paths)) {
97
+ if (key !== 'read' && key !== 'write') throw new ConfigError(`paths: unknown key ${key}`);
98
+ }
99
+
100
+ return Object.freeze({
101
+ profileName,
102
+ profile: BUILTIN_PROFILES[profileName],
103
+ state,
104
+ onApproval,
105
+ tools: Object.freeze(tools),
106
+ roots: Object.freeze({
107
+ read: normalizeRoots(paths.read, 'read', baseDir),
108
+ write: normalizeRoots(paths.write, 'write', baseDir),
109
+ }),
110
+ });
111
+ }
112
+
113
+ /** Read and validate a JSON configuration file. Throws ConfigError on any problem. */
114
+ export function loadConfig(file) {
115
+ if (typeof file !== 'string' || file === '') throw new ConfigError('no configuration file given');
116
+ const path = resolve(file);
117
+ let raw;
118
+ try {
119
+ raw = JSON.parse(readFileSync(path, 'utf8'));
120
+ } catch (error) {
121
+ throw new ConfigError(`cannot read ${path}: ${error.message}`);
122
+ }
123
+ return normalizeConfig(raw, dirname(path));
124
+ }
125
+
126
+ function within(root, target) {
127
+ const rel = relative(root, target);
128
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
129
+ }
130
+
131
+ /** Resolve the real target of a path, following symlinks; new files resolve via their parent. */
132
+ function resolveTarget(requested, mode) {
133
+ try {
134
+ return realpathSync(requested);
135
+ } catch (error) {
136
+ if (mode !== 'write' || error.code !== 'ENOENT') return null;
137
+ }
138
+ // A write may create a new file, but never through a dangling symlink.
139
+ try {
140
+ lstatSync(requested);
141
+ return null;
142
+ } catch (error) {
143
+ if (error.code !== 'ENOENT') return null;
144
+ }
145
+ try {
146
+ return join(realpathSync(dirname(requested)), basename(requested));
147
+ } catch {
148
+ return null;
149
+ }
150
+ }
151
+
152
+ function checkPath(config, name, spec, payload) {
153
+ const input = payload.tool_input;
154
+ const value = isObject(input) ? input[spec.pathArg] : undefined;
155
+ if (typeof value !== 'string' || value === '') return `${name} has no ${spec.pathArg} argument`;
156
+ if (!isAbsolute(value) && (typeof payload.cwd !== 'string' || !isAbsolute(payload.cwd))) {
157
+ return `${name} has a relative path but no absolute working directory`;
158
+ }
159
+ const target = resolveTarget(resolve(isAbsolute(value) ? '/' : payload.cwd, value), spec.mode);
160
+ if (target === null) return `${name} path cannot be resolved`;
161
+ const roots = spec.mode === 'read' ? [...config.roots.read, ...config.roots.write] : config.roots.write;
162
+ if (!roots.some((root) => within(root, target))) return `${name} path is outside the configured ${spec.mode} scope`;
163
+ return null;
164
+ }
165
+
166
+ /**
167
+ * Decide one Hermes pre_tool_call event. Returns the Hermes stdout directive:
168
+ * {} to proceed, {action:"block", message} to block, or, when onApproval is
169
+ * "escalate", {action:"approve", message, rule_key} for Hermes' approval gate.
170
+ */
171
+ export function decide(config, payload) {
172
+ if (!isObject(payload) || payload.hook_event_name !== 'pre_tool_call') return block('unrecognized hook event');
173
+ const name = payload.tool_name;
174
+ if (typeof name !== 'string' || !Object.hasOwn(config.tools, name)) {
175
+ return block(`tool ${typeof name === 'string' ? name : '(missing)'} is not mapped to an ATP action`);
176
+ }
177
+ const spec = config.tools[name];
178
+ const result = evaluateActionWithProfile(config.profile, { actionType: spec.category, state: config.state });
179
+ if (result.decision !== 'allow' && result.decision !== 'require_approval') {
180
+ return block(`${name} is denied by profile ${config.profileName} (${result.reason ?? 'denied'})`);
181
+ }
182
+ if (spec.category === 'filesystem') {
183
+ const modes = config.profile.controls?.filesystem?.modes ?? [];
184
+ if (!modes.includes(spec.mode)) {
185
+ return block(`${name} needs filesystem ${spec.mode} access, which profile ${config.profileName} does not permit`);
186
+ }
187
+ const problem = checkPath(config, name, spec, payload);
188
+ if (problem) return block(problem);
189
+ }
190
+ if (result.decision === 'require_approval') {
191
+ if (config.onApproval === 'escalate') {
192
+ return {
193
+ action: 'approve',
194
+ message: `ATP: ${name} requires approval under profile ${config.profileName} (${result.reason ?? 'approval required'})`,
195
+ rule_key: `atp:${config.profileName}:${name}`,
196
+ };
197
+ }
198
+ return block(`${name} requires approval under profile ${config.profileName}; approval escalation is disabled`);
199
+ }
200
+ if (result.allowed !== true) return block(`${name} was not allowed`);
201
+ return {};
202
+ }
203
+
204
+ /** Convenience: bind a validated configuration to a decision function. */
205
+ export function createHook(config) {
206
+ return (payload) => decide(config, payload);
207
+ }