bare-agent 0.6.2 → 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 -14
- package/index.js +2 -2
- package/package.json +14 -6
- package/src/bareguard-adapter.js +93 -0
- package/src/checkpoint.js +38 -4
- package/src/errors.js +0 -7
- package/src/loop.js +77 -79
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,7 +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`, `
|
|
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')` |
|
|
75
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 |
|
|
76
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) |
|
|
77
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 |
|
|
@@ -83,7 +84,7 @@ Every piece works alone — take what you need, ignore the rest.
|
|
|
83
84
|
|
|
84
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).
|
|
85
86
|
|
|
86
|
-
**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).
|
|
87
88
|
|
|
88
89
|
---
|
|
89
90
|
|
|
@@ -140,15 +141,17 @@ For wiring recipes and API details, see the **[Integration Guide](bareagent.cont
|
|
|
140
141
|
|
|
141
142
|
## The bare ecosystem
|
|
142
143
|
|
|
143
|
-
|
|
144
|
+
Four vanilla JS modules. Zero deps where possible (bareguard has one). Same API patterns.
|
|
144
145
|
|
|
145
|
-
| | [**bareagent**](https://npmjs.com/package/bare-agent) | [**barebrowse**](https://npmjs.com/package/barebrowse) | [**baremobile**](https://npmjs.com/package/baremobile) |
|
|
146
|
-
|
|
147
|
-
| **Does** | Gives agents a think→act loop | Gives agents a real browser | Gives agents Android + iOS devices |
|
|
148
|
-
| **How** | Goal in → coordinated actions out | URL in → pruned snapshot out | Screen in → pruned snapshot out |
|
|
149
|
-
| **Replaces** | LangChain, CrewAI, AutoGen | Playwright, Selenium, Puppeteer | Appium, Espresso, XCUITest |
|
|
150
|
-
| **Interfaces** | Library · CLI · subprocess | Library · CLI · MCP | Library · CLI · MCP |
|
|
151
|
-
| **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).
|
|
152
155
|
|
|
153
156
|
**What you can build:**
|
|
154
157
|
|
|
@@ -162,4 +165,4 @@ Three vanilla JS modules. Zero dependencies. Same API patterns.
|
|
|
162
165
|
|
|
163
166
|
## License
|
|
164
167
|
|
|
165
|
-
|
|
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,7 +18,6 @@ const {
|
|
|
17
18
|
TimeoutError,
|
|
18
19
|
ValidationError,
|
|
19
20
|
CircuitOpenError,
|
|
20
|
-
MaxRoundsError,
|
|
21
21
|
} = require('./src/errors');
|
|
22
22
|
|
|
23
23
|
module.exports = {
|
|
@@ -31,11 +31,11 @@ module.exports = {
|
|
|
31
31
|
Retry,
|
|
32
32
|
runPlan,
|
|
33
33
|
CircuitBreaker,
|
|
34
|
+
wireGate,
|
|
34
35
|
BareAgentError,
|
|
35
36
|
ProviderError,
|
|
36
37
|
ToolError,
|
|
37
38
|
TimeoutError,
|
|
38
39
|
ValidationError,
|
|
39
40
|
CircuitOpenError,
|
|
40
|
-
MaxRoundsError,
|
|
41
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",
|
|
@@ -24,7 +26,8 @@
|
|
|
24
26
|
"./stores": "./src/stores.js",
|
|
25
27
|
"./transports": "./src/transports.js",
|
|
26
28
|
"./tools": "./src/tools.js",
|
|
27
|
-
"./mcp": "./src/mcp.js"
|
|
29
|
+
"./mcp": "./src/mcp.js",
|
|
30
|
+
"./bareguard": "./src/bareguard-adapter.js"
|
|
28
31
|
},
|
|
29
32
|
"engines": {
|
|
30
33
|
"node": ">=18"
|
|
@@ -36,8 +39,13 @@
|
|
|
36
39
|
"ai",
|
|
37
40
|
"tool-calling",
|
|
38
41
|
"planner",
|
|
39
|
-
"lightweight"
|
|
42
|
+
"lightweight",
|
|
43
|
+
"bareguard",
|
|
44
|
+
"governance"
|
|
40
45
|
],
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"bareguard": "^0.1.1"
|
|
48
|
+
},
|
|
41
49
|
"optionalDependencies": {
|
|
42
50
|
"barebrowse": "^0.5.0",
|
|
43
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/checkpoint.js
CHANGED
|
@@ -1,11 +1,24 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { TimeoutError } = require('./errors');
|
|
4
|
+
|
|
5
|
+
const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
|
|
6
|
+
|
|
3
7
|
class Checkpoint {
|
|
8
|
+
/**
|
|
9
|
+
* @param {object} options
|
|
10
|
+
* @param {Array<string>} [options.tools] - Tool names that require approval (exact match).
|
|
11
|
+
* @param {Function} [options.shouldAsk] - Custom predicate `(toolName, args) => bool` — overrides tools list if set.
|
|
12
|
+
* @param {Function} options.send - Async `(question, context) => void` to deliver the question.
|
|
13
|
+
* @param {Function} options.waitForReply - Async `(context) => string` that resolves with the user's reply.
|
|
14
|
+
* @param {number} [options.timeout=300000] - Ms to wait before auto-denying. 0 disables.
|
|
15
|
+
*/
|
|
4
16
|
constructor(options = {}) {
|
|
5
17
|
this.tools = new Set(options.tools || []);
|
|
6
18
|
this.send = options.send || null;
|
|
7
19
|
this.waitForReply = options.waitForReply || null;
|
|
8
|
-
this.shouldAskFn = options.shouldAsk || null;
|
|
20
|
+
this.shouldAskFn = options.shouldAsk || null;
|
|
21
|
+
this.timeout = options.timeout !== undefined ? options.timeout : DEFAULT_TIMEOUT_MS;
|
|
9
22
|
}
|
|
10
23
|
|
|
11
24
|
shouldAsk(toolName, args) {
|
|
@@ -14,19 +27,40 @@ class Checkpoint {
|
|
|
14
27
|
}
|
|
15
28
|
|
|
16
29
|
/**
|
|
17
|
-
* Send a question and wait for a reply.
|
|
30
|
+
* Send a question and wait for a reply. Rejects with TimeoutError if `timeout` ms elapse
|
|
31
|
+
* without a reply — the Loop catches this, auto-denies the tool call, and routes the
|
|
32
|
+
* error through loop:error + onError. No silent hangs.
|
|
18
33
|
* @param {string} question - The approval question to send.
|
|
19
34
|
* @param {object} [context={}] - Context passed to send and waitForReply.
|
|
20
35
|
* @returns {Promise<string|null>} The user's reply, or null.
|
|
21
36
|
* @throws {Error} `[Checkpoint] send and waitForReply callbacks required` — when callbacks are missing.
|
|
37
|
+
* @throws {TimeoutError} When no reply arrives within `timeout` ms.
|
|
22
38
|
*/
|
|
23
39
|
async ask(question, context = {}) {
|
|
24
40
|
if (!this.send || !this.waitForReply) {
|
|
25
41
|
throw new Error('[Checkpoint] send and waitForReply callbacks required');
|
|
26
42
|
}
|
|
27
43
|
await this.send(question, context);
|
|
28
|
-
const
|
|
29
|
-
|
|
44
|
+
const waitPromise = Promise.resolve(this.waitForReply(context));
|
|
45
|
+
if (!this.timeout || this.timeout <= 0) {
|
|
46
|
+
const reply = await waitPromise;
|
|
47
|
+
return reply ?? null;
|
|
48
|
+
}
|
|
49
|
+
let timer;
|
|
50
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
51
|
+
timer = setTimeout(
|
|
52
|
+
() => reject(new TimeoutError(`[Checkpoint] no reply within ${this.timeout}ms — auto-denied`, {
|
|
53
|
+
context: { tool: context?.tool, timeout: this.timeout },
|
|
54
|
+
})),
|
|
55
|
+
this.timeout,
|
|
56
|
+
);
|
|
57
|
+
});
|
|
58
|
+
try {
|
|
59
|
+
const reply = await Promise.race([waitPromise, timeoutPromise]);
|
|
60
|
+
return reply ?? null;
|
|
61
|
+
} finally {
|
|
62
|
+
clearTimeout(timer);
|
|
63
|
+
}
|
|
30
64
|
}
|
|
31
65
|
}
|
|
32
66
|
|
package/src/errors.js
CHANGED
|
@@ -43,12 +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
46
|
module.exports = {
|
|
53
47
|
BareAgentError,
|
|
54
48
|
ProviderError,
|
|
@@ -56,5 +50,4 @@ module.exports = {
|
|
|
56
50
|
TimeoutError,
|
|
57
51
|
ValidationError,
|
|
58
52
|
CircuitOpenError,
|
|
59
|
-
MaxRoundsError,
|
|
60
53
|
};
|
package/src/loop.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const
|
|
4
|
-
const { ToolError, MaxRoundsError } = 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,44 +59,56 @@ 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
65
|
this._stopped = false;
|
|
66
66
|
this._history = []; // for chat() stateful mode
|
|
67
|
-
this._auditInFlight = new Set();
|
|
68
67
|
}
|
|
69
68
|
|
|
70
|
-
//
|
|
71
|
-
//
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
69
|
+
// Unified error emitter — every silent-ish failure path routes through here so
|
|
70
|
+
// operators see callback throws, checkpoint timeouts, stream listener errors
|
|
71
|
+
// in one place: loop:error stream event + onError callback.
|
|
72
|
+
_reportError(source, err, extra = {}) {
|
|
73
|
+
const message = err?.message || String(err);
|
|
74
|
+
this._safeEmit({ type: 'loop:error', data: { source, error: message, ...extra } });
|
|
75
|
+
if (this.onError) {
|
|
76
|
+
try {
|
|
77
|
+
this.onError(err, { source, ...extra });
|
|
78
|
+
} catch (cbErr) {
|
|
79
|
+
console.warn(`[Loop] onError callback threw: ${cbErr.message}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Swallow-proof stream emit: a throwing listener must not corrupt Loop state.
|
|
85
|
+
_safeEmit(event) {
|
|
86
|
+
if (!this.stream) return;
|
|
75
87
|
try {
|
|
76
|
-
|
|
88
|
+
this.stream.emit(event);
|
|
77
89
|
} catch (err) {
|
|
78
|
-
console.warn(`[Loop]
|
|
79
|
-
|
|
90
|
+
console.warn(`[Loop] stream listener threw on ${event.type}: ${err.message}`);
|
|
91
|
+
if (this.onError && event.type !== 'loop:error') {
|
|
92
|
+
try { this.onError(err, { source: 'stream', eventType: event.type }); } catch { /* swallow */ }
|
|
93
|
+
}
|
|
80
94
|
}
|
|
81
|
-
const p = fs.promises.appendFile(this.audit, line)
|
|
82
|
-
.catch(err => console.warn(`[Loop] audit write failed: ${err.message}`))
|
|
83
|
-
.finally(() => this._auditInFlight.delete(p));
|
|
84
|
-
this._auditInFlight.add(p);
|
|
85
95
|
}
|
|
86
96
|
|
|
87
|
-
//
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
97
|
+
// Fire a user callback without letting its throw kill the loop.
|
|
98
|
+
_safeCall(name, fn, ...args) {
|
|
99
|
+
if (!fn) return;
|
|
100
|
+
try {
|
|
101
|
+
fn(...args);
|
|
102
|
+
} catch (err) {
|
|
103
|
+
this._reportError(`callback:${name}`, err);
|
|
104
|
+
}
|
|
92
105
|
}
|
|
93
106
|
|
|
94
107
|
/**
|
|
95
108
|
* Run the think/act/observe loop.
|
|
96
109
|
* @param {Array<object>} messages - Conversation messages in OpenAI format.
|
|
97
110
|
* @param {Array<object>} [tools=[]] - Tool definitions with name, execute, description, parameters.
|
|
98
|
-
* @param {object} [options={}] - Per-run overrides (system, temperature, etc.).
|
|
111
|
+
* @param {object} [options={}] - Per-run overrides (system, temperature, ctx, etc.).
|
|
99
112
|
* @returns {Promise<{text: string, toolCalls: Array, usage: object, error: string|null}>}
|
|
100
113
|
* @throws {Error} `[Loop] Tool is missing a name` — when a tool has no name or a non-string name.
|
|
101
114
|
* @throws {Error} `[Loop] Tool "X" is missing an execute() function` — when execute is not a function.
|
|
@@ -104,6 +117,7 @@ class Loop {
|
|
|
104
117
|
async run(messages, tools = [], options = {}) {
|
|
105
118
|
this._stopped = false;
|
|
106
119
|
const system = options.system || this.system;
|
|
120
|
+
const ctx = options.ctx || null; // per-run opaque blob forwarded to policy
|
|
107
121
|
const msgs = system
|
|
108
122
|
? [{ role: 'system', content: system }, ...messages]
|
|
109
123
|
: [...messages];
|
|
@@ -125,12 +139,12 @@ class Loop {
|
|
|
125
139
|
}
|
|
126
140
|
}
|
|
127
141
|
|
|
128
|
-
this.
|
|
142
|
+
this._safeEmit({ type: 'loop:start', data: { messageCount: msgs.length } });
|
|
129
143
|
|
|
130
144
|
let lastUsage = { inputTokens: 0, outputTokens: 0 };
|
|
131
145
|
let totalCost = 0;
|
|
132
146
|
|
|
133
|
-
for (let round = 0; round <
|
|
147
|
+
for (let round = 0; round < HARD_ROUND_LIMIT; round++) {
|
|
134
148
|
if (this._stopped) break;
|
|
135
149
|
|
|
136
150
|
let result;
|
|
@@ -138,9 +152,7 @@ class Loop {
|
|
|
138
152
|
const generate = () => this.provider.generate(msgs, tools, options);
|
|
139
153
|
result = this.retry ? await this.retry.call(generate) : await generate();
|
|
140
154
|
} catch (err) {
|
|
141
|
-
this.
|
|
142
|
-
this.onError?.(err);
|
|
143
|
-
await this.flush();
|
|
155
|
+
this._reportError('provider', err, { round });
|
|
144
156
|
if (this.throwOnError) throw err;
|
|
145
157
|
return { text: '', toolCalls: [], usage: lastUsage, cost: totalCost, error: err.message };
|
|
146
158
|
}
|
|
@@ -152,10 +164,9 @@ class Loop {
|
|
|
152
164
|
|
|
153
165
|
// No tool calls — LLM gave a final text response
|
|
154
166
|
if (!result.toolCalls || result.toolCalls.length === 0) {
|
|
155
|
-
this.
|
|
156
|
-
this.onText
|
|
157
|
-
|
|
158
|
-
this.stream?.emit({ type: 'loop:done', data: { text: result.text, usage: lastUsage, cost: totalCost } });
|
|
167
|
+
this._safeEmit({ type: 'loop:text', data: { text: result.text } });
|
|
168
|
+
this._safeCall('onText', this.onText, result.text);
|
|
169
|
+
this._safeEmit({ type: 'loop:done', data: { text: result.text, usage: lastUsage, cost: totalCost } });
|
|
159
170
|
return { text: result.text, toolCalls: [], usage: lastUsage, cost: totalCost, error: null };
|
|
160
171
|
}
|
|
161
172
|
|
|
@@ -177,34 +188,46 @@ class Loop {
|
|
|
177
188
|
if (!tool) {
|
|
178
189
|
const errMsg = `[Loop] Unknown tool: ${tc.name}`;
|
|
179
190
|
msgs.push({ role: 'tool', tool_call_id: tc.id, content: errMsg });
|
|
180
|
-
this.
|
|
191
|
+
this._safeEmit({ type: 'loop:tool_result', data: { tool: tc.name, error: errMsg } });
|
|
181
192
|
continue;
|
|
182
193
|
}
|
|
183
194
|
|
|
184
195
|
// Checkpoint — ask for approval before executing
|
|
185
196
|
if (this.checkpoint?.shouldAsk(tc.name, tc.arguments)) {
|
|
186
|
-
this.
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
197
|
+
this._safeEmit({ type: 'checkpoint:ask', data: { tool: tc.name, args: tc.arguments } });
|
|
198
|
+
let reply;
|
|
199
|
+
try {
|
|
200
|
+
reply = await this.checkpoint.ask(
|
|
201
|
+
`Approve ${tc.name}(${JSON.stringify(tc.arguments)})?`,
|
|
202
|
+
{ tool: tc.name, args: tc.arguments }
|
|
203
|
+
);
|
|
204
|
+
} catch (err) {
|
|
205
|
+
// Checkpoint errors (e.g. timeout, transport failure) auto-deny and
|
|
206
|
+
// get reported via loop:error + onError. The loop never hangs silently.
|
|
207
|
+
this._reportError('checkpoint', err, { tool: tc.name });
|
|
208
|
+
msgs.push({ role: 'tool', tool_call_id: tc.id, content: `[Loop] Checkpoint failed: ${err.message}. Action auto-denied.` });
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
this._safeEmit({ type: 'checkpoint:reply', data: { reply } });
|
|
192
212
|
if (!reply || reply.toLowerCase() === 'no' || reply.toLowerCase() === 'n') {
|
|
193
213
|
msgs.push({ role: 'tool', tool_call_id: tc.id, content: 'User denied this action.' });
|
|
194
214
|
continue;
|
|
195
215
|
}
|
|
196
216
|
}
|
|
197
217
|
|
|
198
|
-
this.
|
|
199
|
-
this.onToolCall
|
|
218
|
+
this._safeEmit({ type: 'loop:tool_call', data: { tool: tc.name, args: tc.arguments } });
|
|
219
|
+
this._safeCall('onToolCall', this.onToolCall, tc.name, tc.arguments);
|
|
200
220
|
|
|
201
221
|
// Policy check — runs before execute. Fail-safe: only verdict === true allows;
|
|
202
222
|
// anything else (false, string, undefined, object, throw) denies. A string verdict
|
|
203
|
-
// is used verbatim as the deny reason.
|
|
223
|
+
// is used verbatim as the deny reason. `ctx` (opaque blob passed via
|
|
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.
|
|
204
227
|
if (this.policy) {
|
|
205
228
|
let verdict;
|
|
206
229
|
try {
|
|
207
|
-
verdict = await this.policy(tc.name, tc.arguments);
|
|
230
|
+
verdict = await this.policy(tc.name, tc.arguments, ctx);
|
|
208
231
|
} catch (err) {
|
|
209
232
|
verdict = `[Loop] policy error: ${err.message}`;
|
|
210
233
|
}
|
|
@@ -213,55 +236,30 @@ class Loop {
|
|
|
213
236
|
? verdict
|
|
214
237
|
: `[Loop] Tool "${tc.name}" denied by policy`;
|
|
215
238
|
msgs.push({ role: 'tool', tool_call_id: tc.id, content: reason });
|
|
216
|
-
this.
|
|
217
|
-
this._writeAudit({
|
|
218
|
-
ts: new Date().toISOString(),
|
|
219
|
-
tool: tc.name,
|
|
220
|
-
args: tc.arguments,
|
|
221
|
-
decision: 'deny',
|
|
222
|
-
reason,
|
|
223
|
-
});
|
|
239
|
+
this._safeEmit({ type: 'loop:tool_result', data: { tool: tc.name, denied: true, reason } });
|
|
224
240
|
continue;
|
|
225
241
|
}
|
|
226
242
|
}
|
|
227
243
|
|
|
228
|
-
const startedAt = Date.now();
|
|
229
244
|
try {
|
|
230
245
|
const execute = () => tool.execute(tc.arguments);
|
|
231
246
|
const toolResult = this.retry ? await this.retry.call(execute) : await execute();
|
|
232
247
|
const content = typeof toolResult === 'string' ? toolResult : JSON.stringify(toolResult);
|
|
233
248
|
msgs.push({ role: 'tool', tool_call_id: tc.id, content });
|
|
234
|
-
this.
|
|
235
|
-
this._writeAudit({
|
|
236
|
-
ts: new Date().toISOString(),
|
|
237
|
-
tool: tc.name,
|
|
238
|
-
args: tc.arguments,
|
|
239
|
-
decision: 'allow',
|
|
240
|
-
result: content,
|
|
241
|
-
durationMs: Date.now() - startedAt,
|
|
242
|
-
});
|
|
249
|
+
this._safeEmit({ type: 'loop:tool_result', data: { tool: tc.name, result: content } });
|
|
243
250
|
} catch (err) {
|
|
244
251
|
const toolErr = err instanceof ToolError ? err : new ToolError(err.message, { context: { tool: tc.name } });
|
|
245
252
|
const errMsg = `[Loop] Tool error: ${toolErr.message}`;
|
|
246
253
|
msgs.push({ role: 'tool', tool_call_id: tc.id, content: errMsg });
|
|
247
|
-
this.
|
|
248
|
-
this._writeAudit({
|
|
249
|
-
ts: new Date().toISOString(),
|
|
250
|
-
tool: tc.name,
|
|
251
|
-
args: tc.arguments,
|
|
252
|
-
decision: 'allow',
|
|
253
|
-
error: toolErr.message,
|
|
254
|
-
durationMs: Date.now() - startedAt,
|
|
255
|
-
});
|
|
254
|
+
this._safeEmit({ type: 'loop:tool_result', data: { tool: tc.name, error: errMsg } });
|
|
256
255
|
}
|
|
257
256
|
}
|
|
258
257
|
}
|
|
259
258
|
|
|
260
|
-
//
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
this.
|
|
264
|
-
if (this.throwOnError) throw new MaxRoundsError(warning);
|
|
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.`;
|
|
262
|
+
this._safeEmit({ type: 'loop:done', data: { text: '', warning, cost: totalCost } });
|
|
265
263
|
return { text: '', toolCalls: [], usage: lastUsage, cost: totalCost, error: warning };
|
|
266
264
|
}
|
|
267
265
|
|