@igorjpimenta/brayer 2026.11.7-beta.2 → 2026.11.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,201 +2,129 @@
2
2
 
3
3
  **Ink the work, not the transcript.**
4
4
 
5
- Brayer is a vendor-neutral command layer for agent work. It records a work order,
6
- the attempts made against it, the handoff checkpoint, the evidence returned, and
7
- the verdict — so a fleet of coding agents can be supervised by exception instead
8
- of by transcript.
9
-
10
- ## Why Brayer
11
-
12
- A brayer is the printer's small hand roller that applies ink evenly to type. It
13
- does not rewrite the page, and it does not keep the manuscript. It puts the ink
14
- exactly where the work needs it.
15
-
16
- Brayer does the same for agents. It applies context to the work — the order, the
17
- checkpoint, the proof, the decision — instead of piling another transcript into
18
- the context window.
19
-
20
- The product is a command layer, not another agent:
21
-
22
- - **Work order in** — goal, acceptance, workspace, budget, approval mode.
23
- - **Handoff out** — a structured checkpoint with a tree hash, not a transcript.
24
- - **Evidence attached** — diff, tests, screenshots, artifacts, all content-addressed.
5
+ <p align="center">
6
+ <a href="https://github.com/igorjpimenta/brayer/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/igorjpimenta/brayer/ci.yml?branch=main&style=flat-square&label=ci" alt="CI status"></a>
7
+ <a href="https://www.npmjs.com/package/@igorjpimenta/brayer"><img src="https://img.shields.io/npm/v/@igorjpimenta/brayer?style=flat-square&label=npm" alt="npm version"></a>
8
+ <a href="https://nodejs.org"><img src="https://img.shields.io/node/v/%40igorjpimenta%2Fbrayer?style=flat-square" alt="Node.js version"></a>
9
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green?style=flat-square" alt="License: MIT"></a>
10
+ </p>
11
+
12
+ Brayer is a vendor-neutral work-order desk for coding agents. It records the work order, the attempts made against it, the handoff checkpoint, the content-addressed evidence, and the verdict — so a fleet of coding agents can be supervised by exception instead of by transcript. Every call carries the identity of the agent that made it, stamped at the connection layer so the model itself is never trusted to say who it is.
13
+
14
+ - **Work order in** — goal, acceptance criteria, workspace, budget, approval mode.
15
+ - **Handoff out** — a structured checkpoint pinned to the workspace tree hash, not a transcript.
16
+ - **Evidence attached** — diff, tests, screenshots, artifacts, all content-addressed by sha256.
25
17
  - **Verdict recorded** — approve, reject, escalate or rollback, with an audit event.
26
18
  - **Resume exact** — a leased attempt can die and continue in any harness without a re-brief.
27
19
 
28
- ## Who it is for
20
+ It is local-first and vendor-neutral: OpenCode, OpenClaw and future harnesses are adapters, not the product. A work order is self-contained — no external planner task id is required. Stable releases publish since `2026.11.7` ([release notes](docs/releases.md)).
29
21
 
30
- Technical operators who run several coding agents across repos and harnesses and
31
- need to supervise by exception, not by reading every trace. It is local-first and
32
- vendor-neutral: OpenCode, OpenClaw and future harnesses are adapters, not the
33
- product. It is also planning-system agnostic: a work order is
34
- self-contained, and no external planner task id is required.
35
-
36
- ## Status
37
-
38
- Brayer is in active development. The MCP server, SQLite store, claim lease,
39
- attempts, checkpoints, evidence, verdicts, resume, event stream, HTTP MCP,
40
- claim webhooks and the OpenCode/OpenClaw identity plugins are implemented.
22
+ [Why the name?](#why-the-name) · [npm: @igorjpimenta/brayer](https://www.npmjs.com/package/@igorjpimenta/brayer)
41
23
 
42
24
  ## Install
43
25
 
44
- Brayer is published to public npm:
26
+ Requires Node.js 22+.
45
27
 
46
28
  ```sh
47
- npm install -g @igorjpimenta/brayer@beta
29
+ npm install -g @igorjpimenta/brayer
48
30
  brayer --version
49
31
  ```
50
32
 
51
- ## What works
52
-
53
- ```sh
54
- # MCP over stdio for one harness
55
- BRAYER_HARNESS=opencode brayer serve --mcp stdio
56
-
57
- # MCP over HTTP with bearer auth
58
- BRAYER_HARNESS=openclaw BRAYER_MCP_BEARER=secret \
59
- brayer serve --mcp http --port 38293
33
+ The harness adapters publish separately and can use the same or different Brayer
34
+ versions than the daemon: [`@igorjpimenta/brayer-openclaw`](https://www.npmjs.com/package/@igorjpimenta/brayer-openclaw)
35
+ and [`@igorjpimenta/brayer-opencode`](https://www.npmjs.com/package/@igorjpimenta/brayer-opencode).
36
+ A `beta` dist-tag tracks prereleases (`YYYY.MM.DD-beta.N`) — see
37
+ [releases](docs/releases.md).
60
38
 
61
- # Event stream for dashboards and inboxes
62
- brayer serve --ws --port 38294
39
+ ## Quick start
63
40
 
64
- # Read the queue
65
- brayer status
66
- brayer status --json
41
+ One daemon serves every harness. Start it:
67
42
 
68
- # Register a claim wake target
69
- brayer webhook set --harness opencode \
70
- --url http://127.0.0.1:38295/api/brayer/claimed --bearer secret
71
- brayer webhook test --harness opencode
43
+ ```sh
44
+ BRAYER_MCP_BEARER=$(openssl rand -hex 32) \
45
+ brayer serve --mcp http --port 38293
72
46
  ```
73
47
 
74
- The MCP tools are:
75
-
76
- | Area | Tools |
77
- | --- | --- |
78
- | Orders | `brayer_order_create`, `brayer_order_get`, `brayer_order_next`, `brayer_order_claim`, `brayer_order_heartbeat`, `brayer_order_resume` |
79
- | Attempts | `brayer_attempt_start`, `brayer_attempt_finish`, `brayer_attempt_report_usage`, `brayer_attempt_get` |
80
- | Handoff | `brayer_checkpoint_write`, `brayer_checkpoint_get` |
81
- | Evidence | `brayer_evidence_attach`, `brayer_evidence_list` |
82
- | Verdict | `brayer_verdict_issue`, `brayer_verdict_list` |
83
-
84
- ## Flows
85
-
86
- ### Order lifecycle
48
+ Point a harness at it and let the agent work an order — OpenClaw and OpenCode
49
+ configs are in [Harnesses](#harnesses). Inside the agent's session:
87
50
 
88
- An order moves from ready through a claim and a running attempt to review. The
89
- verdict decides where it lands, and resume returns rejected or blocked work to
90
- ready.
91
-
92
- ```mermaid
93
- flowchart LR
94
- A[Order created] -->|status ready| B[Ready]
95
- B -->|claim| C[Claimed]
96
- C -->|attempt start| D[Running]
97
- D -->|checkpoint / evidence| D
98
- D -->|attempt finished| E[Review]
99
- D -->|attempt failed| B
100
- E -->|approve| F[Approved]
101
- E -->|reject| G[Rejected]
102
- E -->|escalate| H[Blocked]
103
- G -->|resume| B
104
- H -->|resume| B
105
51
  ```
106
-
107
- ### Claim and lease
108
-
109
- An agent claims a ready order, then keeps the lease alive with heartbeats. An
110
- expired lease returns to the queue or blocks at the attempt cap.
111
-
112
- ```mermaid
113
- flowchart LR
114
- Q[Ready order] -->|claimNext / claimById| L{Lease won?}
115
- L -->|no| Q
116
- L -->|yes| H[Claimed with lease]
117
- H -->|heartbeat| H
118
- H -->|lease expired| E{Attempt cap?}
119
- E -->|no| Q
120
- E -->|yes| X[Blocked]
52
+ brayer_order_create { title: "refactor invoice parser", goal: "…",
53
+ acceptance: "tests pass", status: "ready" }
54
+ brayer_order_claim { orderId: "WO-…" } # plugin stamps identity and opens the attempt
55
+ … work …
56
+ brayer_evidence_attach / brayer_checkpoint_write
57
+ brayer_attempt_finish → review → brayer_verdict_issue
121
58
  ```
122
59
 
123
- ### Checkpoint and evidence
60
+ Verify from the operator side — no transcript reading:
124
61
 
125
- The store validates the attempt and the handoff or proof before it records the
126
- row and emits the event.
62
+ ```sh
63
+ $ brayer status
64
+ WO-lqcvx0si refactor invoice parser review openclaw:main:agent:main:explicit:ses_x
127
65
 
128
- ```mermaid
129
- flowchart LR
130
- A[Running attempt] --> B{Belongs to order?}
131
- B -->|no| R[Refuse]
132
- B -->|yes| C{Valid state / tree hash / sha256?}
133
- C -->|no| R
134
- C -->|yes| D[Insert checkpoint or evidence]
135
- D --> E[Emit event]
66
+ brayer doctor --harness opencode # fails when the MCP entry or identity plugin is missing
67
+ brayer adoption --days 30 # real orders → attempts → verdicts, lease expiries, usage
136
68
  ```
137
69
 
138
- ### Verdict and resume
70
+ All MCP tools and their contracts are defined in [`src/tools/`](src/tools/index.js) — or just list them from the running server.
139
71
 
140
- A verdict closes review or blocked work. Reject and escalate remain resumable;
141
- rollback returns the order to ready directly.
72
+ ## How it fits together
142
73
 
143
- ```mermaid
144
- flowchart LR
145
- A[Review or blocked] --> B{Decision}
146
- B -->|approve| C[Approved]
147
- B -->|reject| D[Rejected]
148
- B -->|escalate| E[Blocked]
149
- B -->|rollback| F[Ready]
150
- D -->|resume| F
151
- E -->|resume| F
152
- ```
74
+ - The **Store** is one SQLite database (`~/.brayer/store.sqlite`) with content-addressed evidence blobs — the single source of truth, migrates applied on open.
75
+ - The **MCP server** exposes the whole desk as Brayer tools over stdio (one pipe per harness) or streamable HTTP (one shared daemon). Identity is stamped at the transport edge.
76
+ - The **Event stream** (`brayer serve --ws`) and claim webhooks notify dashboards and wake idle agents when work arrives.
77
+ - **Harness adapters** (`@igorjpimenta/brayer-openclaw`, `@igorjpimenta/brayer-opencode`) stamp identity, checkpoint on turn end (OpenClaw), and receive claim webhooks. The optional `brayer-wake` bridge prompts an OpenCode session when a webhook fires.
153
78
 
154
- ## Storage
155
-
156
- - SQLite at `BRAYER_DB` or `~/.brayer/store.sqlite`
157
- - Content-addressed evidence at `BRAYER_BLOBS` or `~/.brayer/blobs/<sha256>`
158
- - Drizzle migrations in `.migrations/`, applied on open
159
- - WAL, foreign keys and a 5s busy timeout
79
+ ```
80
+ harness agent ──MCP (stdio | HTTP + X-Brayer-Harness)── ▶ MCP server ──▶ SQLite store
81
+ │ claim webhook / event stream
82
+ ▼
83
+ wake bridge → idle harness agent
84
+ ```
160
85
 
161
- ## Configuration
86
+ ## Identity
162
87
 
163
- Explicit config beats `BRAYER_*` env beats defaults. Integer knobs refuse
164
- malformed values; unknown explicit keys refuse as typos.
88
+ Every call is keyed `harness:agent:session`, and the harness is declared per **connection**, never by the model:
165
89
 
166
- | Knob | Env | Default |
90
+ | Transport | Harness declared by | Example |
167
91
  | --- | --- | --- |
168
- | Store | `BRAYER_DB` | `~/.brayer/store.sqlite` |
169
- | Blobs | `BRAYER_BLOBS` | `~/.brayer/blobs` |
170
- | Lease | `BRAYER_LEASE_SECONDS` | `1800` |
171
- | Attempt cap | `BRAYER_MAX_ATTEMPTS` | `3` |
172
- | HTTP port | `BRAYER_HTTP_PORT` | `38293` |
173
- | WS port | `BRAYER_WS_PORT` | `38294` |
174
- | HTTP MCP bearer | `BRAYER_MCP_BEARER` | required for HTTP |
175
- | Claim webhook URL | `BRAYER_CLAIM_WEBHOOK_URL` | unset |
176
- | Claim webhook bearer | `BRAYER_CLAIM_WEBHOOK_BEARER` | unset |
177
- | Claim webhook timeout | `BRAYER_CLAIM_WEBHOOK_TIMEOUT_MS` | `3000` |
178
- | Per-harness webhooks | `BRAYER_CLAIM_WEBHOOKS` | `{}` |
179
- | Wake bridge port | `BRAYER_WAKE_PORT` | `38295` |
180
- | Wake bridge bearer | `BRAYER_WAKE_BEARER` | unset |
181
- | OpenCode server URL | `BRAYER_OPENCODE_URL` | `http://127.0.0.1:4096` |
92
+ | stdio | `BRAYER_HARNESS` env at launch | one pipe per harness |
93
+ | HTTP | `X-Brayer-Harness` header on the session's first request | one shared daemon, all harnesses |
182
94
 
183
- ## Identity
95
+ The agent and session halves are stamped per call as a whole pair, in **one** channel: either `_meta.brayer` (`{ agent, session, harness }`) or flat `brayer_agent` / `brayer_session` arguments — halves never splice across channels. Mutating calls without a full pair refuse; the adapters do this stamping automatically.
184
96
 
185
- Every call is keyed `harness:agent:session`. The harness is declared at
186
- construction (`BRAYER_HARNESS`); the agent and session are stamped per call via
187
- `_meta.brayer` with `brayer_agent` / `brayer_session` as the fallback. Missing or
188
- mismatched identity refuses the call.
97
+ Any non-empty harness name mints a session; deliverability is validated where it matters, at claim time: `brayer_order_claim` and `brayer_order_next` refuse unless the harness has a wake route registered (`brayer webhook set --harness <name>`, or `BRAYER_CLAIM_WEBHOOKS` / `BRAYER_CLAIM_WEBHOOK_URL`) — a claim nobody could be woken for is invisible work. See [lifecycle](docs/lifecycle.md).
189
98
 
190
99
  ## Harnesses
191
100
 
192
101
  An adapter attaches an existing order; it never creates work.
193
102
 
194
- **OpenClaw** — `@igorjpimenta/brayer-openclaw` stamps `_meta.brayer`, checkpoints
195
- on turn end, resumes from the latest checkpoint, and receives claim webhooks at
196
- `POST /api/brayer/claimed`. The hook declares the stamp on `requestMeta`, which
197
- current OpenClaw hoists to JSON-RPC request `_meta`
198
- (openclaw/openclaw#193006), and mirrors it on `brayer_agent`/`brayer_session`
199
- args for engines that predate the hoist.
103
+ **OpenClaw** — `@igorjpimenta/brayer-openclaw` stamps `_meta.brayer`, checkpoints on turn end, resumes from the latest checkpoint, and receives claim webhooks at `POST /api/brayer/claimed`.
104
+
105
+ ```sh
106
+ openclaw plugins install npm:@igorjpimenta/brayer-openclaw@latest
107
+ ```
108
+
109
+ One daemon for all harnesses (recommended):
110
+
111
+ ```json
112
+ {
113
+ "mcp": {
114
+ "servers": {
115
+ "brayer": {
116
+ "url": "http://127.0.0.1:38293/mcp",
117
+ "headers": {
118
+ "X-Brayer-Harness": "openclaw",
119
+ "Authorization": "Bearer <BRAYER_MCP_BEARER>"
120
+ }
121
+ }
122
+ }
123
+ }
124
+ }
125
+ ```
126
+
127
+ One pipe per harness instead:
200
128
 
201
129
  ```json
202
130
  {
@@ -212,44 +140,91 @@ args for engines that predate the hoist.
212
140
  }
213
141
  ```
214
142
 
215
- **OpenCode** — `@igorjpimenta/brayer-opencode` stamps agent/session identity on
216
- Brayer MCP tool calls. It needs the Brayer MCP server configured and
217
- `BRAYER_AGENT` when the session agent cannot be captured.
143
+ **OpenCode** — `@igorjpimenta/brayer-opencode` stamps identity on every Brayer MCP tool call. It needs the Brayer MCP server configured and `BRAYER_AGENT` when the session agent cannot be captured.
144
+
145
+ OpenCode reads config from `opencode.json(c)` (project root or `.opencode/`,
146
+ global at `~/.config/opencode/`, system at `/Library/Application Support/opencode`),
147
+ and also ships a CLI (`opencode mcp add`, `opencode plugin add`). V1 configs
148
+ (`"mcp": { "brayer": … }`, `"plugin": […]`) normalize into V2, but write V2
149
+ canonical form for new setup:
218
150
 
219
151
  ```json
220
152
  {
153
+ "$schema": "https://opencode.ai/config.json",
221
154
  "mcp": {
222
- "brayer": {
223
- "type": "remote",
224
- "url": "http://127.0.0.1:38293/mcp",
225
- "headers": { "Authorization": "Bearer secret" }
155
+ "servers": {
156
+ "brayer": {
157
+ "type": "remote",
158
+ "url": "http://127.0.0.1:38293/mcp",
159
+ "headers": {
160
+ "X-Brayer-Harness": "opencode",
161
+ "Authorization": "Bearer <BRAYER_MCP_BEARER>"
162
+ }
163
+ }
226
164
  }
227
165
  },
228
- "plugin": ["@igorjpimenta/brayer-opencode"]
166
+ "plugins": ["@igorjpimenta/brayer-opencode"]
229
167
  }
230
168
  ```
231
169
 
232
- Automatic checkpoint/resume is not part of this release; the agent uses the
233
- Brayer MCP tools directly.
170
+ Or via the CLI:
234
171
 
235
- **Wake bridge** — the OpenCode package also ships the optional `brayer-wake` bin.
236
- It receives the claim webhook and prompts the claiming session through the
237
- OpenCode SDK.
172
+ ```sh
173
+ opencode mcp add brayer --url http://127.0.0.1:38293/mcp \
174
+ --header "X-Brayer-Harness=opencode" \
175
+ --header "Authorization=Bearer <BRAYER_MCP_BEARER>"
176
+ opencode plugin add @igorjpimenta/brayer-opencode
177
+ ```
238
178
 
239
- ## Docker
179
+ Plugins also auto-discover from `.opencode/plugins/` directories (project or
180
+ global config dir).
240
181
 
241
- ```sh
242
- BRAYER_MCP_BEARER=secret docker compose up --build
182
+ Automatic checkpoint/resume is not part of the OpenCode adapter; the agent uses
183
+ the Brayer MCP tools directly. The optional `brayer-wake` bin binds an ephemeral
184
+ loopback port, registers that URL with the daemon, receives the claim webhook,
185
+ and prompts the claiming session through the OpenCode SDK — see
186
+ [webhooks and wake](docs/webhooks.md).
187
+
188
+ ## The order lifecycle
189
+
190
+ An order moves from ready through a claim and a running attempt to review. The
191
+ verdict decides where it lands, and resume returns rejected or blocked work to
192
+ ready.
193
+
194
+ ```mermaid
195
+ flowchart LR
196
+ A[Order created] -->|status ready| B[Ready]
197
+ B -->|claim| C[Claimed]
198
+ C -->|attempt start| D[Running]
199
+ D -->|checkpoint / evidence| D
200
+ D -->|attempt finished| E[Review]
201
+ D -->|attempt failed| B
202
+ E -->|approve| F[Approved]
203
+ E -->|reject| G[Rejected]
204
+ E -->|escalate| H[Blocked]
205
+ G -->|resume| B
206
+ H -->|resume| B
243
207
  ```
244
208
 
245
- The image stores SQLite and blobs on the `brayer-data` volume at `/data`;
246
- HTTP MCP is exposed on 38293 and the event stream on 38294.
209
+ Claim leases, attempt caps, and the checkpoint/evidence validation rules: [lifecycle](docs/lifecycle.md).
210
+
211
+ ## Documentation
212
+
213
+ | Goal | Start here |
214
+ | --- | --- |
215
+ | Configure ports, bearer, store, webhooks | [Configuration](docs/configuration.md) |
216
+ | Understand claim/lease/verdict rules | [Lifecycle](docs/lifecycle.md) |
217
+ | Wake idle agents on claims | [Webhooks and wake bridge](docs/webhooks.md) |
218
+ | Run it on a host persistently | [Docker](docs/docker.md) |
219
+ | Publish a release | [Releases](docs/releases.md) |
247
220
 
248
- ## Release
221
+ ## Why the name?
249
222
 
250
- Versions are CalVer (`YYYY.MM.DD-beta.N`). Tags are bare for core and prefixed
251
- for adapters: `brayer-openclaw-<calver>` and `brayer-opencode-<calver>`.
252
- Prereleases publish to `beta`; stable tags publish to `latest`.
223
+ A brayer is the printer's small hand roller that applies ink evenly to type. It
224
+ does not rewrite the page, and it does not keep the manuscript. It puts the ink
225
+ exactly where the work needs it. Brayer applies context to the work — the order,
226
+ the checkpoint, the proof, the decision — instead of piling another transcript
227
+ into the context window.
253
228
 
254
229
  ## Development
255
230
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/brayer",
3
- "version": "2026.11.7-beta.2",
3
+ "version": "2026.11.19",
4
4
  "description": "Vendor-neutral command layer for agent work",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/brayer-openclaw",
3
- "version": "2026.11.7-beta.2",
3
+ "version": "2026.11.19",
4
4
  "description": "OpenClaw companion for Brayer: stamps caller identity on Brayer MCP tool calls.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -32,6 +32,6 @@
32
32
  "openclaw": ">=2026.5.18"
33
33
  },
34
34
  "dependencies": {
35
- "@igorjpimenta/brayer": "2026.11.7-beta.2"
35
+ "@igorjpimenta/brayer": "2026.11.19"
36
36
  }
37
37
  }
@@ -1,7 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { startWakeServer } from "../wake.js";
3
3
 
4
- startWakeServer().catch((err) => {
4
+ const args = process.argv.slice(2);
5
+ const portIndex = args.indexOf("--port");
6
+ const port = portIndex >= 0 ? Number(args[portIndex + 1]) : undefined;
7
+
8
+ startWakeServer({ port }).catch((err) => {
5
9
  console.error(err?.message ?? err);
6
10
  process.exit(1);
7
11
  });
@@ -1,4 +1,4 @@
1
- import { stampBrayerIdentity } from "./identity.js";
1
+ import { stampBrayerIdentity, stampStartAttempt } from "./identity.js";
2
2
 
3
3
  export function createBrayerHooks() {
4
4
  const agents = new Map();
@@ -12,6 +12,7 @@ export function createBrayerHooks() {
12
12
  },
13
13
  "tool.execute.before": async (input, output) => {
14
14
  stampBrayerIdentity(input, output, { agent: agents.get(input?.sessionID) ?? process.env.BRAYER_AGENT });
15
+ stampStartAttempt(input, output);
15
16
  },
16
17
  };
17
18
  }
@@ -15,3 +15,14 @@ export function stampBrayerIdentity(input, output, { agent = null } = {}) {
15
15
  if (input?.sessionID) output.args.brayer_session = input.sessionID;
16
16
  return true;
17
17
  }
18
+
19
+ // The claim lease only guards the claimed→attempt window. Opening the attempt
20
+ // in the same call collapses that window, so a working session cannot drift
21
+ // into a 30-minute lease expiry while it is still doing the work.
22
+ export function stampStartAttempt(input, output) {
23
+ if (!isBrayerTool(input?.tool)) return false;
24
+ if (!/order_(claim|next)$/.test(String(input.tool))) return false;
25
+ output.args = output.args ?? {};
26
+ output.args.start_attempt = true;
27
+ return true;
28
+ }
@@ -1,5 +1,13 @@
1
1
  import { createBrayerHooks } from "./hooks.js";
2
+ import { setup } from "./setup.js";
2
3
 
3
- export default async function BrayerPlugin() {
4
+ // The legacy V1 path object-hook form, kept until the compatibility window
5
+ // closes. V1 hosts call server(); they cannot read id/setup().
6
+ export async function BrayerLegacy() {
4
7
  return createBrayerHooks();
5
8
  }
9
+
10
+ // setup() first: it is the entry. server() is the legacy V1 path. Each side
11
+ // stays on its own API — sharing the export does not translate one into the
12
+ // other.
13
+ export default { id: "brayer", setup, server: BrayerLegacy };
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/brayer-opencode",
3
- "version": "2026.11.3-beta.1",
3
+ "version": "2026.11.19",
4
4
  "description": "OpenCode companion for Brayer: stamps identity and runs the optional claim wake bridge.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -20,6 +20,7 @@
20
20
  "index.js",
21
21
  "hooks.js",
22
22
  "identity.js",
23
+ "setup.js",
23
24
  "wake.js",
24
25
  "bin/"
25
26
  ],
@@ -0,0 +1,36 @@
1
+ // setup.js — the entry. Hosts read it from the default export; the legacy
2
+ // server() in index.js gives a V1 host the object-hook form of the same
3
+ // behavior. V2 registers each hook on the domain that owns it, and the agent
4
+ // arrives on the session context hook rather than a chat event. The stamp is
5
+ // unchanged from the V1 side: the same overwrite-unconditionally rule applies,
6
+ // because a model-supplied pair must never survive on either host.
7
+
8
+ import { stampBrayerIdentity, stampStartAttempt } from "./identity.js";
9
+
10
+ export async function setup(ctx) {
11
+ // sessionID → agent, learned once per request. The context hook is the only
12
+ // surface that names the agent for a turn, and it runs immediately before
13
+ // the model request that may call a brayer tool.
14
+ const agents = new Map();
15
+
16
+ await ctx.session.hook("context", (event) => {
17
+ if (!event?.sessionID || !event?.agent) return;
18
+ agents.set(String(event.sessionID), String(event.agent));
19
+ });
20
+
21
+ await ctx.tool.hook("execute.before", (event) => {
22
+ if (!event || typeof event !== "object") return;
23
+ const agent = agents.get(String(event.sessionID)) ?? process.env.BRAYER_AGENT ?? null;
24
+ event.input = event.input && typeof event.input === "object" ? event.input : {};
25
+ const stamped = { args: event.input };
26
+ stampBrayerIdentity(
27
+ { tool: event.tool, sessionID: event.sessionID },
28
+ stamped,
29
+ { agent },
30
+ );
31
+ stampStartAttempt({ tool: event.tool }, stamped);
32
+ event.input = stamped.args;
33
+ });
34
+
35
+ return () => {};
36
+ }
@@ -98,13 +98,52 @@ export function createWakeServer(options = {}) {
98
98
  return http.createServer(createWakeHandler(options));
99
99
  }
100
100
 
101
+ export async function registerWakeTarget({
102
+ registerUrl,
103
+ harness = "opencode",
104
+ url,
105
+ bearer = null,
106
+ timeoutMs = 3000,
107
+ attempts = 5,
108
+ retryDelayMs = 500,
109
+ logger = null,
110
+ } = {}) {
111
+ if (!registerUrl) return { ok: false, reason: "disabled" };
112
+ const endpoint = `${String(registerUrl).replace(/\/+$/, "")}/api/brayer/webhooks`;
113
+ const headers = { "content-type": "application/json" };
114
+ let last = { ok: false, reason: "error" };
115
+ for (let i = 0; i < attempts; i += 1) {
116
+ try {
117
+ const res = await fetch(endpoint, {
118
+ method: "POST",
119
+ headers,
120
+ body: JSON.stringify({ harness, url, bearer }),
121
+ signal: AbortSignal.timeout(timeoutMs),
122
+ });
123
+ if (res.ok) return { ok: true, status: res.status };
124
+ last = { ok: false, reason: `http_${res.status}` };
125
+ if (res.status < 500) break;
126
+ } catch {
127
+ last = { ok: false, reason: "error" };
128
+ }
129
+ if (i + 1 < attempts) await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
130
+ }
131
+ logger?.warn?.(`brayer wake: register ${endpoint} failed (${last.reason})`);
132
+ return last;
133
+ }
134
+
101
135
  export async function startWakeServer({
102
- port = 38295,
136
+ port,
103
137
  bearer = process.env.BRAYER_WAKE_BEARER,
104
138
  baseUrl = process.env.BRAYER_OPENCODE_URL ?? "http://127.0.0.1:4096",
139
+ harness = process.env.BRAYER_WAKE_HARNESS ?? "opencode",
140
+ registerUrl = process.env.BRAYER_REGISTER_URL
141
+ ?? `http://127.0.0.1:${process.env.BRAYER_HTTP_PORT ?? 38293}`,
105
142
  logger = console,
106
143
  } = {}) {
107
144
  if (!bearer) throw new Error("brayer wake: BRAYER_WAKE_BEARER is required");
145
+ const resolvedPort = port ?? (process.env.BRAYER_WAKE_PORT ? Number(process.env.BRAYER_WAKE_PORT) : 0);
146
+ if (!Number.isInteger(resolvedPort) || resolvedPort < 0) throw new Error("brayer wake: port must be a non-negative integer");
108
147
  const { createOpencodeClient } = await import("@opencode-ai/sdk");
109
148
  const client = createOpencodeClient({ baseUrl });
110
149
  const server = createWakeServer({
@@ -118,8 +157,25 @@ export async function startWakeServer({
118
157
  });
119
158
  await new Promise((resolve, reject) => {
120
159
  server.once("error", reject);
121
- server.listen(port, "127.0.0.1", resolve);
160
+ server.listen(resolvedPort, "127.0.0.1", resolve);
122
161
  });
123
- logger?.info?.(`brayer wake: listening on http://127.0.0.1:${port}/api/brayer/claimed`);
162
+ const actualPort = server.address()?.port ?? resolvedPort;
163
+ const wakeUrl = `http://127.0.0.1:${actualPort}/api/brayer/claimed`;
164
+ logger?.info?.(`brayer wake: listening on ${wakeUrl}`);
165
+ const registered = await registerWakeTarget({
166
+ registerUrl,
167
+ harness,
168
+ url: wakeUrl,
169
+ bearer,
170
+ logger,
171
+ });
172
+ if (registered.ok) {
173
+ logger?.info?.(`brayer wake: registered ${harness} at ${wakeUrl}`);
174
+ } else {
175
+ logger?.warn?.(
176
+ `brayer wake: not registered (${registered.reason}); register manually: ` +
177
+ `brayer webhook set --harness ${harness} --url ${wakeUrl} --bearer <bearer>`
178
+ );
179
+ }
124
180
  return server;
125
181
  }
@@ -0,0 +1,19 @@
1
+ import { createStore } from "../store.js";
2
+ import { formatAdoption } from "./format.js";
3
+ import { flagValue } from "./args.js";
4
+
5
+ export async function runAdoption({ rest = [], env = process.env, logger = console } = {}) {
6
+ const daysRaw = flagValue(rest, "--days");
7
+ const days = daysRaw == null ? 30 : Number(daysRaw);
8
+ if (!Number.isInteger(days) || days < 1) throw new Error("brayer: --days must be a positive integer");
9
+ const harness = flagValue(rest, "--harness") ?? "opencode";
10
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
11
+ try {
12
+ const report = store.adoption.report({ days, harness });
13
+ if (rest.includes("--json")) console.log(JSON.stringify(report, null, 2));
14
+ else logger.log(formatAdoption(report));
15
+ return report;
16
+ } finally {
17
+ store.close();
18
+ }
19
+ }