bare-agent 0.7.0 → 0.9.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 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 ~1800 lines. Zero required deps. MIT license.**
14
+ **Agent orchestration in ~2.7K lines of core. One required dep ([bareguard](https://npmjs.com/package/bareguard) ^0.2.0). 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. Throws on error by default. Returns estimated USD cost per run. Loop-level `policy(toolName, args, ctx)` + `audit` gate every tool call (native, MCP, browsing, mobile, user-defined) through one hook `ctx` is a per-call opaque blob for multi-tenant routing. `maxCost` cap catches runaway loops before they burn budget. Unified `loop:error` + `onError` surface every previously silent failure (audit write, callback throw, Checkpoint timeout) |
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,12 +71,14 @@ 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`, `MaxRoundsError`, `MaxCostError`, `CircuitOpenError`, `ValidationError` |
75
- | **Policy helpers** | `pathAllowlist`, `commandAllowlist`, `combinePolicies`composable predicates for `Loop({ policy })`. Home expansion, deny-wins, short-circuit combinator, argv-based safe allowlists. `require('bare-agent/policy')` |
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 |
79
- | **MCP Bridge** | Auto-discover MCP servers from IDE configs (Claude Code, Cursor, etc.), expose as bareagent tools. Static allow/deny via `.mcp-bridge.json`, `systemContext` for LLM awareness. Runtime policy lives in `Loop({ policy })` — one hook for MCP + native tools alike. Zero deps |
79
+ | **MCP Bridge** | Auto-discover MCP servers from IDE configs (Claude Code, Cursor, etc.), expose as bareagent tools. Static allow/deny via `.mcp-bridge.json`, `systemContext` for LLM awareness. Runtime policy lives in `Loop({ policy })` — one hook for MCP + native tools alike. Returns both bulk `tools` (one per MCP tool) and `metaTools` (`mcp_discover` + `mcp_invoke` for token-thrifty access to large catalogs). Zero deps |
80
+ | **Spawn** | Fork a child bareagent process as a specialist agent. LLM-callable form blocks until child exits; library form returns a handle (`wait`, `onLine`, `kill`). One JSONL channel per child — child stderr captured and re-emitted as `child:stderr` events on the parent stream. Threads `BAREGUARD_AUDIT_PATH` / `BAREGUARD_PARENT_RUN_ID` / `BAREGUARD_BUDGET_FILE` / `BAREGUARD_SPAWN_DEPTH` so the family stitches into one audit + budget. `bareguard ^0.2.0` adds `spawn.ratePerMinute` + `limits.maxDepth` per-family caps |
81
+ | **Defer** | Append a `{action, when}` record to a JSONL queue for a separate waker (cron / systemd timer / `examples/wake.sh`) to fire later. Two-phase governance: emit-time `gate.check` on the `defer` action; fire-time `gate.check` on the inner action when the waker re-invokes. `bareguard ^0.2.0` adds `defer.ratePerMinute` family-wide cap |
80
82
 
81
83
  **Providers:** OpenAI-compatible (OpenAI, OpenRouter, Groq, vLLM, LM Studio), Anthropic, Ollama, CLIPipe (any CLI tool via stdin/stdout with real-time streaming), Fallback, or bring your own (one method: `generate`). All return the same shape — swap freely.
82
84
 
@@ -84,7 +86,7 @@ Every piece works alone — take what you need, ignore the rest.
84
86
 
85
87
  **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
88
 
87
- **Deps:** 0 required. Optional: `cron-parser` (cron expressions), `better-sqlite3` (SQLite store), `barebrowse` (web browsing), `baremobile` (Android + iOS device control), `wearehere` (privacy assessment via barebrowse).
89
+ **Deps:** 1 required (`bareguard ^0.2.0` for governance — single-gate policy + audit + budget + per-family rate caps). Optional: `cron-parser` (cron expressions), `better-sqlite3` (SQLite store), `barebrowse` (web browsing), `baremobile` (Android + iOS device control), `wearehere` (privacy assessment via barebrowse).
88
90
 
89
91
  ---
90
92
 
@@ -141,15 +143,17 @@ For wiring recipes and API details, see the **[Integration Guide](bareagent.cont
141
143
 
142
144
  ## The bare ecosystem
143
145
 
144
- Three vanilla JS modules. Zero dependencies. Same API patterns.
146
+ Four vanilla JS modules. Zero deps where possible (bareguard has one). Same API patterns.
145
147
 
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 both as tools | Works standalone | Works standalone |
148
+ | | [**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) |
149
+ |---|---|---|---|---|
150
+ | **Does** | Gives agents a think→act loop | Gives agents a real browser | Gives agents Android + iOS devices | Gates everything an agent does |
151
+ | **How** | Goal in → coordinated actions out | URL in → pruned snapshot out | Screen in → pruned snapshot out | Action in → allow / deny / human-asked out |
152
+ | **Replaces** | LangChain, CrewAI, AutoGen | Playwright, Selenium, Puppeteer | Appium, Espresso, XCUITest | Hand-rolled allowlists, scattered policy code |
153
+ | **Interfaces** | Library · CLI · subprocess | Library · CLI · MCP | Library · CLI · MCP | Library |
154
+ | **Solo or together** | Orchestrates the others as tools | Works standalone | Works standalone | Embedded in bareagent's loop; usable by any runner |
155
+
156
+ > **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
157
 
154
158
  **What you can build:**
155
159
 
@@ -163,4 +167,4 @@ Three vanilla JS modules. Zero dependencies. Same API patterns.
163
167
 
164
168
  ## License
165
169
 
166
- MIT
170
+ Apache License, Version 2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE).
package/bin/cli.js CHANGED
@@ -1,7 +1,35 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ /**
5
+ * bin/cli.js — bareagent subprocess entry point.
6
+ *
7
+ * Two modes (auto-detected by flag presence):
8
+ *
9
+ * 1. Stdio JSONL mode (no --config):
10
+ * Reads JSONL requests `{ method, params: { goal | messages } }` from stdin,
11
+ * runs Loop with no special tools, emits JSONL events on stdout. Used by
12
+ * contrib/ subprocess wrappers and ad-hoc invocations.
13
+ *
14
+ * 2. Config-driven agent mode (--config <path>):
15
+ * Loads a JSON specialist/orchestrator config, wires the configured tools
16
+ * and bareguard Gate, reads ONE input record from stdin, runs Loop, emits
17
+ * JSONL events on stdout, exits when loop:done fires. This is what the
18
+ * `spawn` tool uses to fork child agents (PRD §10.6).
19
+ *
20
+ * Config schema (v0.9):
21
+ * {
22
+ * "systemPrompt": "string",
23
+ * "provider": "openai" | "anthropic" | "ollama",
24
+ * "model": "gpt-4o-mini" (etc),
25
+ * "tools": ["shell_read", "shell_grep", "spawn", "defer", ...],
26
+ * "gate": { ...bareguard config; humanChannel headless-defaults to deny }
27
+ * }
28
+ */
29
+
4
30
  const { createInterface } = require('node:readline');
31
+ const fs = require('node:fs');
32
+ const path = require('node:path');
5
33
  const { Loop } = require('../src/loop');
6
34
  const { Stream } = require('../src/stream');
7
35
  const { JsonlTransport } = require('../src/transport-jsonl');
@@ -12,60 +40,221 @@ const flag = (name) => {
12
40
  return i >= 0 ? args[i + 1] : undefined;
13
41
  };
14
42
 
15
- const providerName = flag('provider') || 'openai';
16
- const model = flag('model');
43
+ const configPath = flag('config');
44
+
45
+ if (configPath) {
46
+ runConfigMode(configPath).catch((err) => {
47
+ process.stdout.write(JSON.stringify({ type: 'loop:error', data: { source: 'cli', error: err.message } }) + '\n');
48
+ process.exit(1);
49
+ });
50
+ } else {
51
+ runStdioMode();
52
+ }
53
+
54
+ // ─── Mode 2: config-driven ────────────────────────────────────────────────
55
+
56
+ async function runConfigMode(cfgPath) {
57
+ const cfg = readConfig(cfgPath);
58
+ const stream = new Stream({ transport: new JsonlTransport() });
59
+
60
+ // Provider
61
+ const provider = createProvider(cfg.provider || 'openai', cfg.model);
62
+
63
+ // Tools — registry resolved by name from a curated set of built-ins.
64
+ const tools = await resolveTools(cfg.tools || [], { stream });
65
+
66
+ // Bareguard Gate (optional but strongly recommended for spawn children)
67
+ let policy = null;
68
+ let wrapToolsFn = (t) => t;
69
+ if (cfg.gate) {
70
+ try {
71
+ const { Gate } = require('bareguard');
72
+ const { wireGate } = require('../src/bareguard-adapter');
73
+
74
+ // Headless humanChannel default: warn once, deny safely. Overridden if
75
+ // the config explicitly sets humanChannel (rare in JSON, but supported
76
+ // via a require path).
77
+ let humanChannel = cfg.gate.humanChannel;
78
+ if (typeof humanChannel === 'string') {
79
+ // Allow `humanChannel: "./my-channel.js"` — load from a file relative to config.
80
+ const fnPath = path.resolve(path.dirname(cfgPath), humanChannel);
81
+ humanChannel = require(fnPath);
82
+ }
83
+ if (typeof humanChannel !== 'function') {
84
+ let warned = false;
85
+ humanChannel = async (event) => {
86
+ if (!warned) {
87
+ process.stderr.write(`[cli] no humanChannel configured — ${event.kind} on ${event.rule} auto-denying.\n`);
88
+ warned = true;
89
+ }
90
+ return { decision: 'deny' };
91
+ };
92
+ }
93
+
94
+ const gate = new Gate({ ...cfg.gate, humanChannel });
95
+ await gate.init();
96
+ const wired = wireGate(gate);
97
+ policy = wired.policy;
98
+ wrapToolsFn = wired.wrapTools;
99
+ } catch (err) {
100
+ process.stderr.write(`[cli] failed to wire bareguard: ${err.message}. Continuing without policy gate.\n`);
101
+ }
102
+ }
103
+
104
+ // Read ONE input record from stdin (JSON or raw string). Treat blank stdin
105
+ // as no input — let the systemPrompt drive the loop alone.
106
+ const stdin = await readStdin();
107
+ const initialMessage = buildInitialMessage(cfg, stdin);
108
+
109
+ const loop = new Loop({
110
+ provider,
111
+ system: cfg.systemPrompt || null,
112
+ stream,
113
+ policy,
114
+ onError: (err, meta) => {
115
+ process.stderr.write(`[loop:error ${meta.source}] ${err.message}\n`);
116
+ },
117
+ });
118
+
119
+ const wrapped = wrapToolsFn(tools);
120
+ await loop.run([initialMessage], wrapped);
121
+ // Stream's loop:done event has already been emitted; exit clean.
122
+ process.exit(0);
123
+ }
17
124
 
18
- function createProvider() {
19
- if (providerName === 'openai') {
125
+ function readConfig(cfgPath) {
126
+ const abs = path.resolve(cfgPath);
127
+ let raw;
128
+ try { raw = fs.readFileSync(abs, 'utf8'); }
129
+ catch (err) { throw new Error(`[cli] cannot read config at ${abs}: ${err.message}`); }
130
+ try { return JSON.parse(raw); }
131
+ catch (err) { throw new Error(`[cli] config at ${abs} is not valid JSON: ${err.message}`); }
132
+ }
133
+
134
+ function readStdin() {
135
+ return new Promise((resolve) => {
136
+ let buf = '';
137
+ if (process.stdin.isTTY) return resolve('');
138
+ process.stdin.setEncoding('utf8');
139
+ process.stdin.on('data', (chunk) => { buf += chunk; });
140
+ process.stdin.on('end', () => resolve(buf.trim()));
141
+ // Safety: don't hang forever if stdin never closes.
142
+ setTimeout(() => resolve(buf.trim()), 100).unref();
143
+ });
144
+ }
145
+
146
+ function buildInitialMessage(cfg, stdin) {
147
+ if (!stdin) {
148
+ return { role: 'user', content: cfg.defaultPrompt || 'Begin.' };
149
+ }
150
+ // Try to parse as JSON; fall back to raw string.
151
+ let parsed;
152
+ try { parsed = JSON.parse(stdin); } catch { /* fine */ }
153
+ if (parsed && typeof parsed === 'object') {
154
+ if (typeof parsed.content === 'string') {
155
+ return { role: 'user', content: parsed.content };
156
+ }
157
+ return { role: 'user', content: JSON.stringify(parsed) };
158
+ }
159
+ return { role: 'user', content: stdin };
160
+ }
161
+
162
+ async function resolveTools(names, ctx) {
163
+ const tools = [];
164
+ for (const name of names) {
165
+ const resolved = await resolveOneTool(name, ctx);
166
+ if (resolved) tools.push(...(Array.isArray(resolved) ? resolved : [resolved]));
167
+ }
168
+ return tools;
169
+ }
170
+
171
+ async function resolveOneTool(name, ctx) {
172
+ switch (name) {
173
+ case 'shell_read':
174
+ case 'shell_grep':
175
+ case 'shell_run':
176
+ case 'shell_exec': {
177
+ const { createShellTools } = require('../tools/shell');
178
+ const { tools } = createShellTools();
179
+ return tools.find(t => t.name === name) || null;
180
+ }
181
+ case 'shell_*': {
182
+ const { createShellTools } = require('../tools/shell');
183
+ return createShellTools().tools;
184
+ }
185
+ case 'spawn': {
186
+ const { createSpawnTool } = require('../tools/spawn');
187
+ return createSpawnTool({ stream: ctx.stream }).tool;
188
+ }
189
+ case 'defer': {
190
+ const { createDeferTool } = require('../tools/defer');
191
+ return createDeferTool().tool;
192
+ }
193
+ default:
194
+ process.stderr.write(`[cli] unknown tool name in config: ${name}\n`);
195
+ return null;
196
+ }
197
+ }
198
+
199
+ // ─── Mode 1: stdio JSONL (legacy) ─────────────────────────────────────────
200
+
201
+ function runStdioMode() {
202
+ const providerName = flag('provider') || 'openai';
203
+ const model = flag('model');
204
+ const stream = new Stream({ transport: new JsonlTransport() });
205
+ const loop = new Loop({ provider: createProvider(providerName, model), stream });
206
+
207
+ let pending = 0;
208
+ let closing = false;
209
+
210
+ const rl = createInterface({ input: process.stdin });
211
+ rl.on('line', async (line) => {
212
+ pending++;
213
+ try {
214
+ const req = JSON.parse(line);
215
+ const messages = req.params?.messages || [
216
+ { role: 'user', content: req.params?.goal || '' },
217
+ ];
218
+ const result = await loop.run(messages, []);
219
+ stream.emit({ type: 'result', data: result });
220
+ } catch (err) {
221
+ stream.emit({ type: 'error', data: { error: err.message } });
222
+ } finally {
223
+ pending--;
224
+ if (closing && pending === 0) process.exit(0);
225
+ }
226
+ });
227
+
228
+ rl.on('close', () => {
229
+ closing = true;
230
+ if (pending === 0) process.exit(0);
231
+ });
232
+ }
233
+
234
+ // ─── Shared: provider construction ────────────────────────────────────────
235
+
236
+ function createProvider(name, model) {
237
+ if (name === 'openai') {
20
238
  const { OpenAIProvider } = require('../src/provider-openai');
21
239
  return new OpenAIProvider({
22
240
  apiKey: process.env.OPENAI_API_KEY,
23
241
  ...(model && { model }),
24
242
  });
25
243
  }
26
- if (providerName === 'anthropic') {
244
+ if (name === 'anthropic') {
27
245
  const { AnthropicProvider } = require('../src/provider-anthropic');
28
246
  return new AnthropicProvider({
29
247
  apiKey: process.env.ANTHROPIC_API_KEY,
30
248
  ...(model && { model }),
31
249
  });
32
250
  }
33
- if (providerName === 'ollama') {
251
+ if (name === 'ollama') {
34
252
  const { OllamaProvider } = require('../src/provider-ollama');
35
253
  return new OllamaProvider({
36
254
  ...(model && { model }),
37
255
  ...(flag('url') && { url: flag('url') }),
38
256
  });
39
257
  }
40
- process.stderr.write(`Unknown provider: ${providerName}\n`);
258
+ process.stderr.write(`Unknown provider: ${name}\n`);
41
259
  process.exit(1);
42
260
  }
43
-
44
- const stream = new Stream({ transport: new JsonlTransport() });
45
- const loop = new Loop({ provider: createProvider(), stream });
46
-
47
- let pending = 0;
48
- let closing = false;
49
-
50
- const rl = createInterface({ input: process.stdin });
51
- rl.on('line', async (line) => {
52
- pending++;
53
- try {
54
- const req = JSON.parse(line);
55
- const messages = req.params?.messages || [
56
- { role: 'user', content: req.params?.goal || '' },
57
- ];
58
- const result = await loop.run(messages, []);
59
- stream.emit({ type: 'result', data: result });
60
- } catch (err) {
61
- stream.emit({ type: 'error', data: { error: err.message } });
62
- } finally {
63
- pending--;
64
- if (closing && pending === 0) process.exit(0);
65
- }
66
- });
67
-
68
- rl.on('close', () => {
69
- closing = true;
70
- if (pending === 0) process.exit(0);
71
- });
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
  };