bare-agent 0.7.0 → 0.8.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.
- package/LICENSE +202 -0
- package/NOTICE +13 -0
- package/README.md +17 -15
- package/index.js +2 -4
- package/package.json +13 -6
- package/src/bareguard-adapter.js +93 -0
- package/src/errors.js +0 -14
- package/src/loop.js +17 -78
- package/src/policy.js +0 -132
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
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 [yyyy] [name of copyright owner]
|
|
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.
|
|
202
|
+
|
package/NOTICE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
bare-agent
|
|
2
|
+
Copyright 2026 hamr0
|
|
3
|
+
|
|
4
|
+
This product includes software developed by hamr0
|
|
5
|
+
(https://github.com/hamr0/bareagent).
|
|
6
|
+
|
|
7
|
+
Licensed under the Apache License, Version 2.0 (the "License").
|
|
8
|
+
You may obtain a copy of the License at:
|
|
9
|
+
|
|
10
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
|
|
12
|
+
This NOTICE file is required by Section 4(d) of the License.
|
|
13
|
+
Forks and derivative works MUST preserve this attribution.
|
package/README.md
CHANGED
|
@@ -11,9 +11,9 @@
|
|
|
11
11
|
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
**Agent orchestration in ~
|
|
14
|
+
**Agent orchestration in ~2.4K lines of core. One required dep ([bareguard](https://npmjs.com/package/bareguard)). Apache 2.0.**
|
|
15
15
|
|
|
16
|
-
Lightweight enough to understand completely. Complete enough to not reinvent wheels. Not a framework, not 50,000 lines of opinions — just composable building blocks for agents.
|
|
16
|
+
Lightweight enough to understand completely. Complete enough to not reinvent wheels. Not a framework, not 50,000 lines of opinions — just composable building blocks for agents. Single-gate governance via bareguard: every tool call traverses one policy hook, one audit log, one budget cap.
|
|
17
17
|
|
|
18
18
|
## Quick start
|
|
19
19
|
|
|
@@ -60,7 +60,7 @@ Every piece works alone — take what you need, ignore the rest.
|
|
|
60
60
|
|
|
61
61
|
| Component | What it does |
|
|
62
62
|
|---|---|
|
|
63
|
-
| **Loop** | Think → act → observe → repeat. Calls any LLM, executes your tools, loops until done.
|
|
63
|
+
| **Loop** | Think → act → observe → repeat. Calls any LLM, executes your tools, loops until done. Returns estimated USD cost per run. Governance via `Loop({ policy })` — wire bareguard's `Gate` through `wireGate(gate)` and every tool call (native, MCP, browsing, mobile) traverses one chokepoint with per-caller `ctx` routing. Bareguard owns the audit log, budget caps, and halt decisions; Loop respects the verdict. `onError` + `loop:error` surface every silent-ish failure (callback throw, Checkpoint timeout) |
|
|
64
64
|
| **Planner** | Break a goal into a step DAG via LLM. Built-in caching (`cacheTTL`) |
|
|
65
65
|
| **runPlan** | Execute steps in parallel waves. Dependency-aware, failure propagation, per-step retry |
|
|
66
66
|
| **Retry** | Exponential/linear backoff with jitter. Respects `err.retryable` |
|
|
@@ -71,8 +71,8 @@ Every piece works alone — take what you need, ignore the rest.
|
|
|
71
71
|
| **Checkpoint** | Human approval gate. You provide the transport — terminal, Telegram, Slack, whatever |
|
|
72
72
|
| **Scheduler** | Cron (`0 9 * * 1-5`) or relative (`2h`, `30m`). Persisted jobs survive restarts |
|
|
73
73
|
| **Stream** | Structured event emitter. Pipe as JSONL, subscribe in-process, or custom transport |
|
|
74
|
-
| **Errors** | Typed hierarchy — `ProviderError`, `ToolError`, `TimeoutError`, `
|
|
75
|
-
| **
|
|
74
|
+
| **Errors** | Typed hierarchy — `ProviderError`, `ToolError`, `TimeoutError`, `CircuitOpenError`, `ValidationError`. Halt decisions (turn cap, budget cap, content rules) come from bareguard, not Loop |
|
|
75
|
+
| **bareguard adapter** | `wireGate(gate)` returns `{ policy, wrapTools }` — one-line wiring to bareguard's `Gate`. Maps gate decisions to Loop's `policy` contract; `wrapTools` decorates tools so `gate.record` fires after every execute. `require('bare-agent/bareguard')` |
|
|
76
76
|
| **Browsing** | Web navigation, clicking, typing, reading via `barebrowse` (17 tools). Two modes: library tools (inline snapshots, pass to Loop) or CLI session (disk-based snapshots, token-efficient for multi-step flows). Optional `assess` tool (privacy scan) when `wearehere` is installed |
|
|
77
77
|
| **Mobile** | Android + iOS device control via `baremobile`. Same two modes: library tools (`createMobileTools` — action tools auto-return snapshots) or CLI session (`baremobile` CLI — disk-based snapshots) |
|
|
78
78
|
| **Shell** | Cross-platform `shell_read`, `shell_grep`, `shell_run` (argv, no shell), `shell_exec` (raw shell). Pure Node — no `grep`/`rg`/`findstr` dependency. Injection-proof `shell_run` for policy-gated use |
|
|
@@ -84,7 +84,7 @@ Every piece works alone — take what you need, ignore the rest.
|
|
|
84
84
|
|
|
85
85
|
**Cross-language:** Runs as a subprocess. Communicate via JSONL on stdin/stdout from Python, Go, Rust, Ruby, Java, or anything that can spawn a process. Ready-made wrappers in [`contrib/`](contrib/README.md).
|
|
86
86
|
|
|
87
|
-
**Deps:**
|
|
87
|
+
**Deps:** 1 required (`bareguard` for governance — single-gate policy + audit + budget). Optional: `cron-parser` (cron expressions), `better-sqlite3` (SQLite store), `barebrowse` (web browsing), `baremobile` (Android + iOS device control), `wearehere` (privacy assessment via barebrowse).
|
|
88
88
|
|
|
89
89
|
---
|
|
90
90
|
|
|
@@ -141,15 +141,17 @@ For wiring recipes and API details, see the **[Integration Guide](bareagent.cont
|
|
|
141
141
|
|
|
142
142
|
## The bare ecosystem
|
|
143
143
|
|
|
144
|
-
|
|
144
|
+
Four vanilla JS modules. Zero deps where possible (bareguard has one). Same API patterns.
|
|
145
145
|
|
|
146
|
-
| | [**bareagent**](https://npmjs.com/package/bare-agent) | [**barebrowse**](https://npmjs.com/package/barebrowse) | [**baremobile**](https://npmjs.com/package/baremobile) |
|
|
147
|
-
|
|
148
|
-
| **Does** | Gives agents a think→act loop | Gives agents a real browser | Gives agents Android + iOS devices |
|
|
149
|
-
| **How** | Goal in → coordinated actions out | URL in → pruned snapshot out | Screen in → pruned snapshot out |
|
|
150
|
-
| **Replaces** | LangChain, CrewAI, AutoGen | Playwright, Selenium, Puppeteer | Appium, Espresso, XCUITest |
|
|
151
|
-
| **Interfaces** | Library · CLI · subprocess | Library · CLI · MCP | Library · CLI · MCP |
|
|
152
|
-
| **Solo or together** | Orchestrates
|
|
146
|
+
| | [**bareagent**](https://npmjs.com/package/bare-agent) | [**barebrowse**](https://npmjs.com/package/barebrowse) | [**baremobile**](https://npmjs.com/package/baremobile) | [**bareguard**](https://npmjs.com/package/bareguard) |
|
|
147
|
+
|---|---|---|---|---|
|
|
148
|
+
| **Does** | Gives agents a think→act loop | Gives agents a real browser | Gives agents Android + iOS devices | Gates everything an agent does |
|
|
149
|
+
| **How** | Goal in → coordinated actions out | URL in → pruned snapshot out | Screen in → pruned snapshot out | Action in → allow / deny / human-asked out |
|
|
150
|
+
| **Replaces** | LangChain, CrewAI, AutoGen | Playwright, Selenium, Puppeteer | Appium, Espresso, XCUITest | Hand-rolled allowlists, scattered policy code |
|
|
151
|
+
| **Interfaces** | Library · CLI · subprocess | Library · CLI · MCP | Library · CLI · MCP | Library |
|
|
152
|
+
| **Solo or together** | Orchestrates the others as tools | Works standalone | Works standalone | Embedded in bareagent's loop; usable by any runner |
|
|
153
|
+
|
|
154
|
+
> **Reach 50+ messengers with one Docker container via [beeperbox](https://github.com/hamr0/beeperbox)** — a headless Beeper Desktop that exposes WhatsApp, iMessage, Signal, Telegram, Slack, Discord, RCS, SMS and more as a single MCP server. Wire it through bareagent's MCP bridge; bareguard policies the invocations like any other tool (per-chat allowlists, ask patterns on destructive sends, all the usual layered defense).
|
|
153
155
|
|
|
154
156
|
**What you can build:**
|
|
155
157
|
|
|
@@ -163,4 +165,4 @@ Three vanilla JS modules. Zero dependencies. Same API patterns.
|
|
|
163
165
|
|
|
164
166
|
## License
|
|
165
167
|
|
|
166
|
-
|
|
168
|
+
Apache License, Version 2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
package/index.js
CHANGED
|
@@ -10,6 +10,7 @@ const { Stream } = require('./src/stream');
|
|
|
10
10
|
const { Retry } = require('./src/retry');
|
|
11
11
|
const { runPlan } = require('./src/run-plan');
|
|
12
12
|
const { CircuitBreaker } = require('./src/circuit-breaker');
|
|
13
|
+
const { wireGate } = require('./src/bareguard-adapter');
|
|
13
14
|
const {
|
|
14
15
|
BareAgentError,
|
|
15
16
|
ProviderError,
|
|
@@ -17,8 +18,6 @@ const {
|
|
|
17
18
|
TimeoutError,
|
|
18
19
|
ValidationError,
|
|
19
20
|
CircuitOpenError,
|
|
20
|
-
MaxRoundsError,
|
|
21
|
-
MaxCostError,
|
|
22
21
|
} = require('./src/errors');
|
|
23
22
|
|
|
24
23
|
module.exports = {
|
|
@@ -32,12 +31,11 @@ module.exports = {
|
|
|
32
31
|
Retry,
|
|
33
32
|
runPlan,
|
|
34
33
|
CircuitBreaker,
|
|
34
|
+
wireGate,
|
|
35
35
|
BareAgentError,
|
|
36
36
|
ProviderError,
|
|
37
37
|
ToolError,
|
|
38
38
|
TimeoutError,
|
|
39
39
|
ValidationError,
|
|
40
40
|
CircuitOpenError,
|
|
41
|
-
MaxRoundsError,
|
|
42
|
-
MaxCostError,
|
|
43
41
|
};
|
package/package.json
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bare-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"files": [
|
|
5
5
|
"index.js",
|
|
6
6
|
"src/",
|
|
7
7
|
"bin/",
|
|
8
|
-
"tools/"
|
|
8
|
+
"tools/",
|
|
9
|
+
"LICENSE",
|
|
10
|
+
"NOTICE"
|
|
9
11
|
],
|
|
10
|
-
"description": "Lightweight, composable agent orchestration. ~
|
|
11
|
-
"license": "
|
|
12
|
+
"description": "Lightweight, composable agent orchestration for autonomous agents. Single-gate governance via bareguard, cross-platform shell tools, MCP bridge. ~2.4K lines core, one required dep.",
|
|
13
|
+
"license": "Apache-2.0",
|
|
12
14
|
"author": "hamr0",
|
|
13
15
|
"repository": {
|
|
14
16
|
"type": "git",
|
|
@@ -25,7 +27,7 @@
|
|
|
25
27
|
"./transports": "./src/transports.js",
|
|
26
28
|
"./tools": "./src/tools.js",
|
|
27
29
|
"./mcp": "./src/mcp.js",
|
|
28
|
-
"./
|
|
30
|
+
"./bareguard": "./src/bareguard-adapter.js"
|
|
29
31
|
},
|
|
30
32
|
"engines": {
|
|
31
33
|
"node": ">=18"
|
|
@@ -37,8 +39,13 @@
|
|
|
37
39
|
"ai",
|
|
38
40
|
"tool-calling",
|
|
39
41
|
"planner",
|
|
40
|
-
"lightweight"
|
|
42
|
+
"lightweight",
|
|
43
|
+
"bareguard",
|
|
44
|
+
"governance"
|
|
41
45
|
],
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"bareguard": "^0.1.1"
|
|
48
|
+
},
|
|
42
49
|
"optionalDependencies": {
|
|
43
50
|
"barebrowse": "^0.5.0",
|
|
44
51
|
"baremobile": "^0.7.0",
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Wire a bareguard Gate into bareagent's Loop.
|
|
5
|
+
*
|
|
6
|
+
* Returns:
|
|
7
|
+
* - `policy` — async (toolName, args, ctx) closure for `new Loop({ policy })`.
|
|
8
|
+
* Maps gate.check decisions to true (allow) or a deny string
|
|
9
|
+
* (used verbatim by Loop as the LLM-visible reason).
|
|
10
|
+
* - `wrapTool` — wraps a single tool so its execute() also calls gate.record
|
|
11
|
+
* with the result + duration (or error). Bareguard owns the
|
|
12
|
+
* audit log and budget tracking; record() is what feeds them.
|
|
13
|
+
* - `wrapTools` — convenience: applies wrapTool to an array.
|
|
14
|
+
*
|
|
15
|
+
* Halt-severity decisions (budget exhausted, limits.maxTurns hit, etc.) come
|
|
16
|
+
* back as deny strings tagged `[HALT: <rule>]`. Subsequent rounds halt the
|
|
17
|
+
* same way; the LLM typically gives up and the loop exits naturally. For
|
|
18
|
+
* earlier exit, watch the loop:error stream (the closure also calls onError
|
|
19
|
+
* via Loop's policy-deny path) or wire `onError` to detect halt strings.
|
|
20
|
+
*
|
|
21
|
+
* @param {object} gate - A bareguard Gate instance (must have .check and .record).
|
|
22
|
+
* @returns {{policy: Function, wrapTool: Function, wrapTools: Function}}
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* const { Gate } = require('bareguard');
|
|
26
|
+
* const { Loop } = require('bare-agent');
|
|
27
|
+
* const { wireGate } = require('bare-agent/bareguard');
|
|
28
|
+
*
|
|
29
|
+
* const gate = new Gate({
|
|
30
|
+
* budget: { maxCostUsd: 0.50 },
|
|
31
|
+
* limits: { maxTurns: 20 },
|
|
32
|
+
* audit: { path: './audit.jsonl' },
|
|
33
|
+
* humanChannel: async (ev) => ({ decision: 'deny' }),
|
|
34
|
+
* });
|
|
35
|
+
* await gate.init();
|
|
36
|
+
*
|
|
37
|
+
* const { policy, wrapTools } = wireGate(gate);
|
|
38
|
+
* const loop = new Loop({ provider, policy });
|
|
39
|
+
* await loop.run(messages, wrapTools(myTools));
|
|
40
|
+
*/
|
|
41
|
+
function wireGate(gate) {
|
|
42
|
+
if (!gate || typeof gate.check !== 'function' || typeof gate.record !== 'function') {
|
|
43
|
+
throw new Error('[wireGate] expects a bareguard Gate instance (must have .check and .record).');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const policy = async (toolName, args, ctx) => {
|
|
47
|
+
const decision = await gate.check({ type: toolName, args, _ctx: ctx });
|
|
48
|
+
if (decision.outcome === 'allow') return true;
|
|
49
|
+
const tag = decision.severity === 'halt'
|
|
50
|
+
? `[HALT: ${decision.rule}]`
|
|
51
|
+
: `[deny: ${decision.rule}]`;
|
|
52
|
+
return decision.reason ? `${tag} ${decision.reason}` : `${tag} ${toolName} denied`;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
function wrapTool(tool) {
|
|
56
|
+
if (!tool || typeof tool.execute !== 'function') {
|
|
57
|
+
throw new Error('[wireGate.wrapTool] tool must have an execute() function');
|
|
58
|
+
}
|
|
59
|
+
const original = tool.execute;
|
|
60
|
+
return {
|
|
61
|
+
...tool,
|
|
62
|
+
execute: async (args) => {
|
|
63
|
+
const action = { type: tool.name, args };
|
|
64
|
+
const startedAt = Date.now();
|
|
65
|
+
try {
|
|
66
|
+
const result = await original(args);
|
|
67
|
+
await gate.record(action, {
|
|
68
|
+
result: typeof result === 'string' ? result : JSON.stringify(result),
|
|
69
|
+
durationMs: Date.now() - startedAt,
|
|
70
|
+
});
|
|
71
|
+
return result;
|
|
72
|
+
} catch (err) {
|
|
73
|
+
await gate.record(action, {
|
|
74
|
+
error: err?.message || String(err),
|
|
75
|
+
durationMs: Date.now() - startedAt,
|
|
76
|
+
});
|
|
77
|
+
throw err;
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function wrapTools(tools) {
|
|
84
|
+
if (!Array.isArray(tools)) {
|
|
85
|
+
throw new Error('[wireGate.wrapTools] expects an array of tools');
|
|
86
|
+
}
|
|
87
|
+
return tools.map(wrapTool);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return { policy, wrapTool, wrapTools };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
module.exports = { wireGate };
|
package/src/errors.js
CHANGED
|
@@ -43,18 +43,6 @@ class CircuitOpenError extends BareAgentError {
|
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
class MaxRoundsError extends BareAgentError {
|
|
47
|
-
constructor(message, opts = {}) {
|
|
48
|
-
super(message || 'Loop exceeded maximum rounds', { code: 'MAX_ROUNDS', retryable: false, ...opts });
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
class MaxCostError extends BareAgentError {
|
|
53
|
-
constructor(message, opts = {}) {
|
|
54
|
-
super(message || 'Loop exceeded maximum cost cap', { code: 'MAX_COST', retryable: false, ...opts });
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
46
|
module.exports = {
|
|
59
47
|
BareAgentError,
|
|
60
48
|
ProviderError,
|
|
@@ -62,6 +50,4 @@ module.exports = {
|
|
|
62
50
|
TimeoutError,
|
|
63
51
|
ValidationError,
|
|
64
52
|
CircuitOpenError,
|
|
65
|
-
MaxRoundsError,
|
|
66
|
-
MaxCostError,
|
|
67
53
|
};
|
package/src/loop.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const
|
|
4
|
-
const { ToolError, MaxRoundsError, MaxCostError } = require('./errors');
|
|
3
|
+
const { ToolError } = require('./errors');
|
|
5
4
|
|
|
6
5
|
// Average pricing per 1K tokens (USD). Adjust these to match your provider's rates.
|
|
7
6
|
// Last updated: 2026-03-18. Source: public provider pricing pages.
|
|
@@ -21,6 +20,11 @@ const COST_PER_1K = {
|
|
|
21
20
|
'_default': { in: 0.002, out: 0.008 },
|
|
22
21
|
};
|
|
23
22
|
|
|
23
|
+
// Internal safety net only — real iteration bounds come from a wired bareguard
|
|
24
|
+
// Gate via `limits.maxTurns`. If you hit this without bareguard wired, you have
|
|
25
|
+
// no governance and the LLM loop is unbounded by design — wire bareguard.
|
|
26
|
+
const HARD_ROUND_LIMIT = 100;
|
|
27
|
+
|
|
24
28
|
function estimateCost(model, usage) {
|
|
25
29
|
if (!usage || !model) return null;
|
|
26
30
|
const rates = COST_PER_1K[model] || COST_PER_1K['_default'];
|
|
@@ -34,20 +38,17 @@ class Loop {
|
|
|
34
38
|
/**
|
|
35
39
|
* @param {object} options
|
|
36
40
|
* @param {object} options.provider - LLM provider (must implement generate()).
|
|
37
|
-
* @param {number} [options.maxRounds=5] - Maximum think/act/observe cycles.
|
|
38
41
|
* @param {string} [options.system] - System prompt prepended to messages.
|
|
39
42
|
* @param {object} [options.checkpoint] - Checkpoint instance for human-in-the-loop.
|
|
40
43
|
* @param {object} [options.retry] - Retry instance for backoff on failures.
|
|
41
44
|
* @param {object} [options.stream] - Stream instance for event emission.
|
|
42
45
|
* @param {object} [options.store] - Store instance for validate() health check.
|
|
43
|
-
* @param {Function} [options.policy] - Async (toolName, args) => true|
|
|
44
|
-
* @param {string} [options.audit] - File path for JSONL audit log. Each tool call appends one line: {ts, tool, args, decision, result|reason|error, durationMs}.
|
|
46
|
+
* @param {Function} [options.policy] - Async (toolName, args, ctx) => true | string. Recommended wiring: closure that delegates to a bareguard Gate (`require('bare-agent/bareguard').wireGate(gate).policy`). Anything other than `true` denies; a string is fed to the LLM verbatim as the deny reason. All policy/budget/audit decisions live in bareguard — Loop just calls the closure and respects the verdict.
|
|
45
47
|
* @throws {Error} `[Loop] requires a provider` — when options.provider is missing.
|
|
46
48
|
*/
|
|
47
49
|
constructor(options = {}) {
|
|
48
50
|
if (!options.provider) throw new Error('[Loop] requires a provider');
|
|
49
51
|
this.provider = options.provider;
|
|
50
|
-
this.maxRounds = options.maxRounds || 5;
|
|
51
52
|
this.system = options.system || null;
|
|
52
53
|
this.checkpoint = options.checkpoint || null;
|
|
53
54
|
this.retry = options.retry || null;
|
|
@@ -58,19 +59,16 @@ class Loop {
|
|
|
58
59
|
this.throwOnError = options.throwOnError !== undefined ? options.throwOnError : true;
|
|
59
60
|
this.store = options.store || null;
|
|
60
61
|
if (options.policy != null && typeof options.policy !== 'function') {
|
|
61
|
-
throw new Error('[Loop] options.policy must be a function (toolName, args) => true |
|
|
62
|
+
throw new Error('[Loop] options.policy must be a function (toolName, args, ctx) => true | string');
|
|
62
63
|
}
|
|
63
64
|
this.policy = options.policy || null;
|
|
64
|
-
this.audit = options.audit || null;
|
|
65
|
-
this.maxCost = typeof options.maxCost === 'number' && options.maxCost > 0 ? options.maxCost : null;
|
|
66
65
|
this._stopped = false;
|
|
67
66
|
this._history = []; // for chat() stateful mode
|
|
68
|
-
this._auditInFlight = new Set();
|
|
69
67
|
}
|
|
70
68
|
|
|
71
69
|
// Unified error emitter — every silent-ish failure path routes through here so
|
|
72
|
-
// operators see
|
|
73
|
-
//
|
|
70
|
+
// operators see callback throws, checkpoint timeouts, stream listener errors
|
|
71
|
+
// in one place: loop:error stream event + onError callback.
|
|
74
72
|
_reportError(source, err, extra = {}) {
|
|
75
73
|
const message = err?.message || String(err);
|
|
76
74
|
this._safeEmit({ type: 'loop:error', data: { source, error: message, ...extra } });
|
|
@@ -106,35 +104,11 @@ class Loop {
|
|
|
106
104
|
}
|
|
107
105
|
}
|
|
108
106
|
|
|
109
|
-
// Append one JSONL record. Returns nothing (fire-and-forget for callers)
|
|
110
|
-
// but tracks the in-flight promise so `flush()` and the end of `run()` can await it.
|
|
111
|
-
_writeAudit(record) {
|
|
112
|
-
if (!this.audit) return;
|
|
113
|
-
let line;
|
|
114
|
-
try {
|
|
115
|
-
line = JSON.stringify(record) + '\n';
|
|
116
|
-
} catch (err) {
|
|
117
|
-
this._reportError('audit:serialize', err, { tool: record?.tool });
|
|
118
|
-
return;
|
|
119
|
-
}
|
|
120
|
-
const p = fs.promises.appendFile(this.audit, line)
|
|
121
|
-
.catch(err => this._reportError('audit:write', err, { tool: record?.tool }))
|
|
122
|
-
.finally(() => this._auditInFlight.delete(p));
|
|
123
|
-
this._auditInFlight.add(p);
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// Await any in-flight audit writes. Safe to call multiple times; resolves immediately
|
|
127
|
-
// when no writes are pending. Called automatically at the end of each `run()`.
|
|
128
|
-
async flush() {
|
|
129
|
-
if (this._auditInFlight.size === 0) return;
|
|
130
|
-
await Promise.all([...this._auditInFlight]);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
107
|
/**
|
|
134
108
|
* Run the think/act/observe loop.
|
|
135
109
|
* @param {Array<object>} messages - Conversation messages in OpenAI format.
|
|
136
110
|
* @param {Array<object>} [tools=[]] - Tool definitions with name, execute, description, parameters.
|
|
137
|
-
* @param {object} [options={}] - Per-run overrides (system, temperature, etc.).
|
|
111
|
+
* @param {object} [options={}] - Per-run overrides (system, temperature, ctx, etc.).
|
|
138
112
|
* @returns {Promise<{text: string, toolCalls: Array, usage: object, error: string|null}>}
|
|
139
113
|
* @throws {Error} `[Loop] Tool is missing a name` — when a tool has no name or a non-string name.
|
|
140
114
|
* @throws {Error} `[Loop] Tool "X" is missing an execute() function` — when execute is not a function.
|
|
@@ -170,7 +144,7 @@ class Loop {
|
|
|
170
144
|
let lastUsage = { inputTokens: 0, outputTokens: 0 };
|
|
171
145
|
let totalCost = 0;
|
|
172
146
|
|
|
173
|
-
for (let round = 0; round <
|
|
147
|
+
for (let round = 0; round < HARD_ROUND_LIMIT; round++) {
|
|
174
148
|
if (this._stopped) break;
|
|
175
149
|
|
|
176
150
|
let result;
|
|
@@ -179,7 +153,6 @@ class Loop {
|
|
|
179
153
|
result = this.retry ? await this.retry.call(generate) : await generate();
|
|
180
154
|
} catch (err) {
|
|
181
155
|
this._reportError('provider', err, { round });
|
|
182
|
-
await this.flush();
|
|
183
156
|
if (this.throwOnError) throw err;
|
|
184
157
|
return { text: '', toolCalls: [], usage: lastUsage, cost: totalCost, error: err.message };
|
|
185
158
|
}
|
|
@@ -189,21 +162,10 @@ class Loop {
|
|
|
189
162
|
const roundCost = estimateCost(model, lastUsage);
|
|
190
163
|
if (roundCost !== null) totalCost += roundCost;
|
|
191
164
|
|
|
192
|
-
// Cost cap — fail fast before the next round costs more money.
|
|
193
|
-
if (this.maxCost !== null && totalCost > this.maxCost) {
|
|
194
|
-
const msg = `[Loop] cost ${totalCost.toFixed(4)} exceeded cap ${this.maxCost.toFixed(4)} after round ${round + 1}`;
|
|
195
|
-
const err = new MaxCostError(msg, { context: { cost: totalCost, maxCost: this.maxCost, round } });
|
|
196
|
-
this._reportError('cost-cap', err, { cost: totalCost, maxCost: this.maxCost });
|
|
197
|
-
await this.flush();
|
|
198
|
-
if (this.throwOnError) throw err;
|
|
199
|
-
return { text: '', toolCalls: [], usage: lastUsage, cost: totalCost, error: msg };
|
|
200
|
-
}
|
|
201
|
-
|
|
202
165
|
// No tool calls — LLM gave a final text response
|
|
203
166
|
if (!result.toolCalls || result.toolCalls.length === 0) {
|
|
204
167
|
this._safeEmit({ type: 'loop:text', data: { text: result.text } });
|
|
205
168
|
this._safeCall('onText', this.onText, result.text);
|
|
206
|
-
await this.flush();
|
|
207
169
|
this._safeEmit({ type: 'loop:done', data: { text: result.text, usage: lastUsage, cost: totalCost } });
|
|
208
170
|
return { text: result.text, toolCalls: [], usage: lastUsage, cost: totalCost, error: null };
|
|
209
171
|
}
|
|
@@ -260,6 +222,8 @@ class Loop {
|
|
|
260
222
|
// anything else (false, string, undefined, object, throw) denies. A string verdict
|
|
261
223
|
// is used verbatim as the deny reason. `ctx` (opaque blob passed via
|
|
262
224
|
// loop.run(msgs, tools, { ctx })) is forwarded as the third arg for per-caller gating.
|
|
225
|
+
// Recommended wiring: bareguard's Gate via `wireGate(gate).policy` — bareguard
|
|
226
|
+
// owns budget, audit, and halt decisions; Loop just respects the verdict.
|
|
263
227
|
if (this.policy) {
|
|
264
228
|
let verdict;
|
|
265
229
|
try {
|
|
@@ -273,54 +237,29 @@ class Loop {
|
|
|
273
237
|
: `[Loop] Tool "${tc.name}" denied by policy`;
|
|
274
238
|
msgs.push({ role: 'tool', tool_call_id: tc.id, content: reason });
|
|
275
239
|
this._safeEmit({ type: 'loop:tool_result', data: { tool: tc.name, denied: true, reason } });
|
|
276
|
-
this._writeAudit({
|
|
277
|
-
ts: new Date().toISOString(),
|
|
278
|
-
tool: tc.name,
|
|
279
|
-
args: tc.arguments,
|
|
280
|
-
decision: 'deny',
|
|
281
|
-
reason,
|
|
282
|
-
});
|
|
283
240
|
continue;
|
|
284
241
|
}
|
|
285
242
|
}
|
|
286
243
|
|
|
287
|
-
const startedAt = Date.now();
|
|
288
244
|
try {
|
|
289
245
|
const execute = () => tool.execute(tc.arguments);
|
|
290
246
|
const toolResult = this.retry ? await this.retry.call(execute) : await execute();
|
|
291
247
|
const content = typeof toolResult === 'string' ? toolResult : JSON.stringify(toolResult);
|
|
292
248
|
msgs.push({ role: 'tool', tool_call_id: tc.id, content });
|
|
293
249
|
this._safeEmit({ type: 'loop:tool_result', data: { tool: tc.name, result: content } });
|
|
294
|
-
this._writeAudit({
|
|
295
|
-
ts: new Date().toISOString(),
|
|
296
|
-
tool: tc.name,
|
|
297
|
-
args: tc.arguments,
|
|
298
|
-
decision: 'allow',
|
|
299
|
-
result: content,
|
|
300
|
-
durationMs: Date.now() - startedAt,
|
|
301
|
-
});
|
|
302
250
|
} catch (err) {
|
|
303
251
|
const toolErr = err instanceof ToolError ? err : new ToolError(err.message, { context: { tool: tc.name } });
|
|
304
252
|
const errMsg = `[Loop] Tool error: ${toolErr.message}`;
|
|
305
253
|
msgs.push({ role: 'tool', tool_call_id: tc.id, content: errMsg });
|
|
306
254
|
this._safeEmit({ type: 'loop:tool_result', data: { tool: tc.name, error: errMsg } });
|
|
307
|
-
this._writeAudit({
|
|
308
|
-
ts: new Date().toISOString(),
|
|
309
|
-
tool: tc.name,
|
|
310
|
-
args: tc.arguments,
|
|
311
|
-
decision: 'allow',
|
|
312
|
-
error: toolErr.message,
|
|
313
|
-
durationMs: Date.now() - startedAt,
|
|
314
|
-
});
|
|
315
255
|
}
|
|
316
256
|
}
|
|
317
257
|
}
|
|
318
258
|
|
|
319
|
-
//
|
|
320
|
-
|
|
321
|
-
|
|
259
|
+
// Hard safety limit — should never fire under normal usage; bareguard's
|
|
260
|
+
// limits.maxTurns (or the LLM's natural completion) ends the loop first.
|
|
261
|
+
const warning = `[Loop] hit internal safety limit of ${HARD_ROUND_LIMIT} rounds. Wire bareguard for proper governance — see bare-agent/bareguard.`;
|
|
322
262
|
this._safeEmit({ type: 'loop:done', data: { text: '', warning, cost: totalCost } });
|
|
323
|
-
if (this.throwOnError) throw new MaxRoundsError(warning);
|
|
324
263
|
return { text: '', toolCalls: [], usage: lastUsage, cost: totalCost, error: warning };
|
|
325
264
|
}
|
|
326
265
|
|
package/src/policy.js
DELETED
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Policy helpers — composable predicates for `new Loop({ policy })`.
|
|
5
|
-
*
|
|
6
|
-
* Each helper returns an async function `(toolName, args, ctx) => true | string`
|
|
7
|
-
* matching bareagent's policy contract. `true` allows; anything else denies.
|
|
8
|
-
* A string is fed verbatim to the LLM as the deny reason.
|
|
9
|
-
*
|
|
10
|
-
* Compose multiple helpers with `combinePolicies(a, b, c)` — first non-`true`
|
|
11
|
-
* verdict wins, short-circuit semantics.
|
|
12
|
-
*
|
|
13
|
-
* Zero deps. Pure Node. Cross-platform.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
const path = require('node:path');
|
|
17
|
-
|
|
18
|
-
function expandHome(p) {
|
|
19
|
-
if (!p || typeof p !== 'string') return p;
|
|
20
|
-
if (p === '~') return process.env.HOME || process.env.USERPROFILE || '';
|
|
21
|
-
if (p.startsWith('~/') || p.startsWith('~\\')) {
|
|
22
|
-
const home = process.env.HOME || process.env.USERPROFILE || '';
|
|
23
|
-
return path.join(home, p.slice(2));
|
|
24
|
-
}
|
|
25
|
-
return p;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function normalize(p) {
|
|
29
|
-
try {
|
|
30
|
-
return path.resolve(expandHome(p));
|
|
31
|
-
} catch {
|
|
32
|
-
return p;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/**
|
|
37
|
-
* Allow/deny file-system paths used by tools like shell_read, shell_grep.
|
|
38
|
-
*
|
|
39
|
-
* Deny wins over allow. Paths containing `..` after normalization are denied
|
|
40
|
-
* unconditionally (prevents traversal bypassing the allow list).
|
|
41
|
-
*
|
|
42
|
-
* @param {object} options
|
|
43
|
-
* @param {string[]} [options.allow] - Path prefixes users may access. `~` expands.
|
|
44
|
-
* @param {string[]} [options.deny] - Path prefixes hard-denied. `~` expands.
|
|
45
|
-
* @param {string[]} [options.toolNames] - Only check these tool names. If omitted, checks any tool with an `args.path` string.
|
|
46
|
-
* @param {string} [options.argKey='path'] - Name of the args field to inspect.
|
|
47
|
-
* @returns {Function} policy predicate `(toolName, args) => true | string`
|
|
48
|
-
*/
|
|
49
|
-
function pathAllowlist({ allow = [], deny = [], toolNames, argKey = 'path' } = {}) {
|
|
50
|
-
const allowNorm = allow.map(normalize);
|
|
51
|
-
const denyNorm = deny.map(normalize);
|
|
52
|
-
const gatedTools = toolNames ? new Set(toolNames) : null;
|
|
53
|
-
|
|
54
|
-
return async function pathPolicy(toolName, args) {
|
|
55
|
-
if (gatedTools && !gatedTools.has(toolName)) return true;
|
|
56
|
-
const raw = args?.[argKey];
|
|
57
|
-
if (typeof raw !== 'string') return true; // nothing to check
|
|
58
|
-
const target = normalize(raw);
|
|
59
|
-
|
|
60
|
-
for (const d of denyNorm) {
|
|
61
|
-
if (target === d || target.startsWith(d + path.sep) || target.startsWith(d + '/')) {
|
|
62
|
-
return `Path denied: ${raw} is under a denied root (${d}).`;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
if (allowNorm.length === 0) return true;
|
|
66
|
-
for (const a of allowNorm) {
|
|
67
|
-
if (target === a || target.startsWith(a + path.sep) || target.startsWith(a + '/')) {
|
|
68
|
-
return true;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
return `Path denied: ${raw} is not under any allowed root.`;
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Allow/deny commands by their base name.
|
|
77
|
-
*
|
|
78
|
-
* For `shell_run` (argv-array): inspects `args.argv[0]`. Safe — no shell in path.
|
|
79
|
-
* For `shell_exec` (raw shell): inspects `args.command.split(/\s+/)[0]` BUT this
|
|
80
|
-
* is defeatable by shell metacharacters. Prefer gating `shell_run` with this helper
|
|
81
|
-
* and denying `shell_exec` entirely, or handling shell_exec with a custom policy
|
|
82
|
-
* that parses the command string carefully.
|
|
83
|
-
*
|
|
84
|
-
* Deny wins over allow.
|
|
85
|
-
*
|
|
86
|
-
* @param {object} options
|
|
87
|
-
* @param {string[]} [options.allow] - Base command names allowed.
|
|
88
|
-
* @param {string[]} [options.deny] - Base command names denied.
|
|
89
|
-
* @param {string} [options.toolName='shell_run'] - Which tool this helper gates.
|
|
90
|
-
* @returns {Function} policy predicate `(toolName, args) => true | string`
|
|
91
|
-
*/
|
|
92
|
-
function commandAllowlist({ allow = [], deny = [], toolName = 'shell_run' } = {}) {
|
|
93
|
-
const allowSet = new Set(allow);
|
|
94
|
-
const denySet = new Set(deny);
|
|
95
|
-
|
|
96
|
-
return async function commandPolicy(name, args) {
|
|
97
|
-
if (name !== toolName) return true;
|
|
98
|
-
let base;
|
|
99
|
-
if (name === 'shell_run') {
|
|
100
|
-
if (!Array.isArray(args?.argv) || typeof args.argv[0] !== 'string') return true;
|
|
101
|
-
base = args.argv[0];
|
|
102
|
-
} else {
|
|
103
|
-
if (typeof args?.command !== 'string') return true;
|
|
104
|
-
base = args.command.trim().split(/\s+/)[0];
|
|
105
|
-
}
|
|
106
|
-
if (denySet.has(base)) return `Command denied: ${base} is on the denylist.`;
|
|
107
|
-
if (allowSet.size > 0 && !allowSet.has(base)) {
|
|
108
|
-
return `Command denied: ${base} is not on the allowlist.`;
|
|
109
|
-
}
|
|
110
|
-
return true;
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Compose multiple policy predicates into one. First non-true verdict wins.
|
|
116
|
-
* Short-circuits on first deny — later predicates are not called.
|
|
117
|
-
*
|
|
118
|
-
* @param {...Function} policies - Any number of policy predicates.
|
|
119
|
-
* @returns {Function} combined policy predicate `(toolName, args, ctx) => true | string`
|
|
120
|
-
*/
|
|
121
|
-
function combinePolicies(...policies) {
|
|
122
|
-
const list = policies.filter(p => typeof p === 'function');
|
|
123
|
-
return async function combined(toolName, args, ctx) {
|
|
124
|
-
for (const p of list) {
|
|
125
|
-
const verdict = await p(toolName, args, ctx);
|
|
126
|
-
if (verdict !== true) return verdict;
|
|
127
|
-
}
|
|
128
|
-
return true;
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
module.exports = { pathAllowlist, commandAllowlist, combinePolicies };
|