@igorjpimenta/brayer 0.0.0-stage → 2026.10.28-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/.migrations/0000_initial.sql +133 -0
  2. package/.migrations/0001_awesome_ben_parker.sql +8 -0
  3. package/.migrations/meta/0000_snapshot.json +931 -0
  4. package/.migrations/meta/0001_snapshot.json +983 -0
  5. package/.migrations/meta/_journal.json +20 -0
  6. package/LICENSE +21 -0
  7. package/README.md +245 -2
  8. package/bin/brayer.js +7 -0
  9. package/package.json +42 -4
  10. package/plugins/openclaw/brayer/index.js +119 -0
  11. package/plugins/openclaw/brayer/meta.js +23 -0
  12. package/plugins/openclaw/brayer/openclaw.plugin.json +14 -0
  13. package/plugins/openclaw/brayer/package.json +37 -0
  14. package/plugins/openclaw/brayer/session.js +30 -0
  15. package/plugins/openclaw/brayer/webhook.js +125 -0
  16. package/plugins/opencode/brayer/identity.js +11 -0
  17. package/plugins/opencode/brayer/index.js +92 -0
  18. package/plugins/opencode/brayer/package.json +27 -0
  19. package/plugins/opencode/brayer/session.js +25 -0
  20. package/plugins/shared/contract.js +193 -0
  21. package/plugins/wake/brayer/bin/brayer-wake.js +7 -0
  22. package/plugins/wake/brayer/index.js +125 -0
  23. package/plugins/wake/brayer/package.json +29 -0
  24. package/src/claim-webhook.js +66 -0
  25. package/src/cli.js +164 -0
  26. package/src/config.js +63 -0
  27. package/src/db.js +24 -0
  28. package/src/events-ws.js +121 -0
  29. package/src/evidence.js +42 -0
  30. package/src/identity.js +32 -0
  31. package/src/ids.js +17 -0
  32. package/src/mcp.js +114 -0
  33. package/src/schema.js +168 -0
  34. package/src/store/attempts.js +103 -0
  35. package/src/store/checkpoints.js +76 -0
  36. package/src/store/claims.js +139 -0
  37. package/src/store/events.js +24 -0
  38. package/src/store/evidence.js +67 -0
  39. package/src/store/orders.js +70 -0
  40. package/src/store/resume.js +38 -0
  41. package/src/store/rows.js +118 -0
  42. package/src/store/util.js +3 -0
  43. package/src/store/verdicts.js +61 -0
  44. package/src/store/webhooks.js +56 -0
  45. package/src/store.js +53 -0
  46. package/src/tools/attempts.js +75 -0
  47. package/src/tools/handoff.js +120 -0
  48. package/src/tools/index.js +28 -0
  49. package/src/tools/orders.js +146 -0
  50. package/src/tools/shared.js +7 -0
  51. package/src/tools/verdicts.js +46 -0
  52. package/src/version.js +5 -0
@@ -0,0 +1,66 @@
1
+ const DEFAULT_TIMEOUT_MS = 3000;
2
+
3
+ export function webhookConfig(cfg, harness = null, dbEntry = null) {
4
+ if (dbEntry?.url) {
5
+ return {
6
+ url: dbEntry.url,
7
+ bearer: dbEntry.bearer || null,
8
+ timeoutMs: dbEntry.timeoutMs ?? cfg?.claimWebhookTimeoutMs ?? DEFAULT_TIMEOUT_MS,
9
+ };
10
+ }
11
+ const entry = harness ? cfg?.claimWebhooks?.[harness] : null;
12
+ if (entry?.url) {
13
+ return {
14
+ url: entry.url,
15
+ bearer: entry.bearer || null,
16
+ timeoutMs: entry.timeoutMs ?? cfg?.claimWebhookTimeoutMs ?? DEFAULT_TIMEOUT_MS,
17
+ };
18
+ }
19
+ if (!cfg?.claimWebhookUrl) return null;
20
+ return {
21
+ url: cfg.claimWebhookUrl,
22
+ bearer: cfg.claimWebhookBearer || null,
23
+ timeoutMs: cfg.claimWebhookTimeoutMs ?? DEFAULT_TIMEOUT_MS,
24
+ };
25
+ }
26
+
27
+ export function sessionFromAgentId(agentId, sessionRef = null) {
28
+ const [harness, agent, ...rest] = String(agentId).split(":");
29
+ return {
30
+ harness: harness || null,
31
+ agent: agent || null,
32
+ sessionKey: sessionRef ?? (rest.length ? rest.join(":") : null),
33
+ };
34
+ }
35
+
36
+ export function claimPayload({ order, agentId, sessionRef, at = Date.now() }) {
37
+ return {
38
+ event: "order.claimed",
39
+ at,
40
+ order,
41
+ session: sessionFromAgentId(agentId, sessionRef),
42
+ };
43
+ }
44
+
45
+ export async function notifyClaim(cfg, payload, { logger = null, dbEntry = null } = {}) {
46
+ const hook = webhookConfig(cfg, payload?.session?.harness ?? null, dbEntry);
47
+ if (!hook) return { ok: false, reason: "disabled" };
48
+ try {
49
+ const headers = { "content-type": "application/json" };
50
+ if (hook.bearer) headers.authorization = `Bearer ${hook.bearer}`;
51
+ const res = await fetch(hook.url, {
52
+ method: "POST",
53
+ headers,
54
+ body: JSON.stringify(payload),
55
+ signal: AbortSignal.timeout(hook.timeoutMs),
56
+ });
57
+ if (!res.ok) {
58
+ logger?.warn?.(`brayer: claim webhook ${hook.url} -> ${res.status}`);
59
+ return { ok: false, reason: `http_${res.status}` };
60
+ }
61
+ return { ok: true, status: res.status };
62
+ } catch (err) {
63
+ logger?.warn?.(`brayer: claim webhook ${hook.url} failed: ${err?.message ?? err}`);
64
+ return { ok: false, reason: "error" };
65
+ }
66
+ }
package/src/cli.js ADDED
@@ -0,0 +1,164 @@
1
+ import { createStore } from "./store.js";
2
+ import { startMcpHttpServer, startMcpServer } from "./mcp.js";
3
+ import { startEventServer } from "./events-ws.js";
4
+ import { VERSION } from "./version.js";
5
+ import { webhookConfig } from "./claim-webhook.js";
6
+
7
+ const usage = `brayer ${VERSION}
8
+
9
+ Usage:
10
+ brayer --version
11
+ brayer serve --mcp stdio
12
+ brayer serve --mcp http --port 38293 [--host 127.0.0.1]
13
+ brayer serve --ws --port 38294
14
+ brayer status [--json]
15
+ brayer webhook set --harness H --url U [--bearer B] [--timeout-ms N]
16
+ brayer webhook list
17
+ brayer webhook remove --harness H
18
+ brayer webhook test --harness H
19
+
20
+ HTTP and the full inbox land in later stories.`;
21
+
22
+ function flagValue(args, name) {
23
+ const i = args.indexOf(name);
24
+ return i >= 0 ? args[i + 1] : null;
25
+ }
26
+
27
+ function flagMap(args) {
28
+ const out = {};
29
+ for (let i = 0; i < args.length; i += 1) {
30
+ if (args[i].startsWith("--") && args[i + 1] !== undefined) {
31
+ out[args[i].slice(2)] = args[i + 1];
32
+ i += 1;
33
+ }
34
+ }
35
+ return out;
36
+ }
37
+
38
+ export function formatStatus(orders) {
39
+ if (!orders.length) return "No work orders.";
40
+ const rows = orders.map((o) => [
41
+ o.id,
42
+ o.status.padEnd(9),
43
+ o.assignee ?? "-",
44
+ String(o.attemptCount),
45
+ o.title,
46
+ ]);
47
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => r[i].length)));
48
+ return rows.map((r) => r.map((v, i) => (i === 4 ? v : v.padEnd(widths[i]))).join(" ")).join("\n");
49
+ }
50
+
51
+ export async function main(argv = process.argv.slice(2), { env = process.env, logger = console } = {}) {
52
+ const [command, ...rest] = argv;
53
+
54
+ if (command === "--version" || command === "-v") {
55
+ console.log(VERSION);
56
+ return;
57
+ }
58
+ if (!command || command === "--help" || command === "-h") {
59
+ console.log(usage);
60
+ return;
61
+ }
62
+
63
+ if (command === "status") {
64
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
65
+ try {
66
+ const orders = store.order.list({ limit: 100 });
67
+ if (rest.includes("--json")) console.log(JSON.stringify({ orders }, null, 2));
68
+ else console.log(formatStatus(orders));
69
+ } finally {
70
+ store.close();
71
+ }
72
+ return;
73
+ }
74
+
75
+ if (command === "webhook") {
76
+ const [sub, ...webhookArgs] = rest;
77
+ const values = flagMap(webhookArgs);
78
+ const harness = values.harness;
79
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
80
+ try {
81
+ if (sub === "list") {
82
+ const rows = store.webhook.list().map((row) => ({ ...row, bearer: row.bearer ? "<set>" : null }));
83
+ console.log(JSON.stringify(rows, null, 2));
84
+ return;
85
+ }
86
+ if (!["set", "remove", "test"].includes(sub)) {
87
+ throw new Error("brayer: webhook requires set, list, remove or test");
88
+ }
89
+ if (!harness) throw new Error(`brayer: webhook ${sub} requires --harness`);
90
+ if (sub === "remove") {
91
+ if (!store.webhook.remove({ harness })) throw new Error(`brayer: no webhook for ${harness}`);
92
+ console.log(JSON.stringify({ removed: harness }));
93
+ return;
94
+ }
95
+ if (sub === "set") {
96
+ if (!values.url) throw new Error("brayer: webhook set requires --url");
97
+ const timeoutMs = values["timeout-ms"] !== undefined ? Number(values["timeout-ms"]) : null;
98
+ const row = store.webhook.upsert({
99
+ harness,
100
+ url: values.url,
101
+ bearer: values.bearer ?? null,
102
+ timeoutMs,
103
+ });
104
+ console.log(JSON.stringify({ ...row, bearer: row.bearer ? "<set>" : null }, null, 2));
105
+ return;
106
+ }
107
+ const hook = webhookConfig(store.config, harness, store.webhook.get(harness));
108
+ if (!hook) throw new Error(`brayer: no webhook for ${harness}`);
109
+ const headers = { "content-type": "application/json" };
110
+ if (hook.bearer) headers.authorization = `Bearer ${hook.bearer}`;
111
+ const res = await fetch(hook.url, {
112
+ method: "POST",
113
+ headers,
114
+ body: JSON.stringify({ event: "webhook.test", at: Date.now(), harness }),
115
+ signal: AbortSignal.timeout(hook.timeoutMs),
116
+ });
117
+ const text = await res.text();
118
+ console.log(JSON.stringify({ ok: res.ok, status: res.status, body: text.slice(0, 500) }, null, 2));
119
+ if (!res.ok) process.exitCode = 1;
120
+ return;
121
+ } finally {
122
+ store.close();
123
+ }
124
+ }
125
+
126
+ if (command === "serve") {
127
+ const mcpIndex = rest.indexOf("--mcp");
128
+ const transport = mcpIndex >= 0 ? rest[mcpIndex + 1] : null;
129
+ if (transport) {
130
+ if (!env.BRAYER_HARNESS) throw new Error("brayer: BRAYER_HARNESS is required for MCP");
131
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
132
+ if (transport === "stdio") {
133
+ await startMcpServer({ store, base: { harness: env.BRAYER_HARNESS }, logger });
134
+ return;
135
+ }
136
+ if (transport === "http") {
137
+ if (!env.BRAYER_MCP_BEARER) throw new Error("brayer: BRAYER_MCP_BEARER is required for HTTP");
138
+ const port = Number(flagValue(rest, "--port") ?? env.BRAYER_HTTP_PORT ?? 38293);
139
+ const host = flagValue(rest, "--host") ?? "127.0.0.1";
140
+ await startMcpHttpServer({
141
+ store,
142
+ base: { harness: env.BRAYER_HARNESS },
143
+ port,
144
+ host,
145
+ bearer: env.BRAYER_MCP_BEARER,
146
+ logger,
147
+ });
148
+ return;
149
+ }
150
+ throw new Error("brayer: serve --mcp supports stdio or http");
151
+ }
152
+
153
+ if (rest.includes("--ws")) {
154
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
155
+ const port = flagValue(rest, "--port");
156
+ startEventServer({ store, port: port ? Number(port) : undefined, logger });
157
+ return;
158
+ }
159
+
160
+ throw new Error("brayer: serve requires --mcp stdio or --ws");
161
+ }
162
+
163
+ throw new Error(`brayer: ${command} is not implemented yet`);
164
+ }
package/src/config.js ADDED
@@ -0,0 +1,63 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+
4
+ const DEFAULTS = {
5
+ dbPath: path.join(os.homedir(), ".brayer", "store.sqlite"),
6
+ blobsPath: path.join(os.homedir(), ".brayer", "blobs"),
7
+ leaseSeconds: 1800,
8
+ maxAttempts: 3,
9
+ httpPort: 38293,
10
+ wsPort: 38294,
11
+ claimWebhookUrl: "",
12
+ claimWebhookBearer: "",
13
+ claimWebhookTimeoutMs: 3000,
14
+ claimWebhooks: {},
15
+ };
16
+
17
+ const ENV_KEYS = {
18
+ dbPath: "BRAYER_DB",
19
+ blobsPath: "BRAYER_BLOBS",
20
+ leaseSeconds: "BRAYER_LEASE_SECONDS",
21
+ maxAttempts: "BRAYER_MAX_ATTEMPTS",
22
+ httpPort: "BRAYER_HTTP_PORT",
23
+ wsPort: "BRAYER_WS_PORT",
24
+ claimWebhookUrl: "BRAYER_CLAIM_WEBHOOK_URL",
25
+ claimWebhookBearer: "BRAYER_CLAIM_WEBHOOK_BEARER",
26
+ claimWebhookTimeoutMs: "BRAYER_CLAIM_WEBHOOK_TIMEOUT_MS",
27
+ };
28
+
29
+ const INT_KEYS = new Set(["leaseSeconds", "maxAttempts", "httpPort", "wsPort", "claimWebhookTimeoutMs"]);
30
+
31
+ function parseInteger(key, value) {
32
+ const n = Number(value);
33
+ if (!Number.isInteger(n) || n < 0) throw new Error(`brayer: ${key} must be a non-negative integer`);
34
+ return n;
35
+ }
36
+
37
+ export function resolveConfig({ explicit = {}, env = process.env } = {}) {
38
+ for (const key of Object.keys(explicit)) {
39
+ if (!(key in DEFAULTS)) throw new Error(`brayer: unknown config key: ${key}`);
40
+ }
41
+
42
+ const out = { ...DEFAULTS };
43
+ for (const [key, envKey] of Object.entries(ENV_KEYS)) {
44
+ if (env[envKey] !== undefined && env[envKey] !== "") out[key] = env[envKey];
45
+ }
46
+ Object.assign(out, explicit);
47
+
48
+ if (env.BRAYER_CLAIM_WEBHOOKS !== undefined && env.BRAYER_CLAIM_WEBHOOKS !== "") {
49
+ try {
50
+ out.claimWebhooks = JSON.parse(env.BRAYER_CLAIM_WEBHOOKS);
51
+ } catch {
52
+ throw new Error("brayer: BRAYER_CLAIM_WEBHOOKS must be valid JSON");
53
+ }
54
+ }
55
+ if (!out.claimWebhooks || typeof out.claimWebhooks !== "object" || Array.isArray(out.claimWebhooks)) {
56
+ throw new Error("brayer: claimWebhooks must be an object");
57
+ }
58
+
59
+ for (const key of INT_KEYS) out[key] = parseInteger(key, out[key]);
60
+ return out;
61
+ }
62
+
63
+ export { DEFAULTS };
package/src/db.js ADDED
@@ -0,0 +1,24 @@
1
+ import { existsSync, mkdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ import Database from "better-sqlite3";
4
+ import { drizzle } from "drizzle-orm/better-sqlite3";
5
+ import { migrate } from "drizzle-orm/better-sqlite3/migrator";
6
+ import * as schema from "./schema.js";
7
+
8
+ const MIGRATIONS_FOLDER = path.join(import.meta.dirname, "..", ".migrations");
9
+
10
+ export function openDatabase({ dbPath, logger } = {}) {
11
+ const dir = path.dirname(dbPath);
12
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
13
+
14
+ const sqlite = new Database(dbPath);
15
+ sqlite.exec("PRAGMA journal_mode = WAL;");
16
+ sqlite.exec("PRAGMA foreign_keys = ON;");
17
+ sqlite.exec("PRAGMA busy_timeout = 5000;");
18
+
19
+ const orm = drizzle(sqlite, { schema });
20
+ migrate(orm, { migrationsFolder: MIGRATIONS_FOLDER });
21
+
22
+ logger?.info?.(`brayer: store ready at ${dbPath}`);
23
+ return { sqlite, orm };
24
+ }
@@ -0,0 +1,121 @@
1
+ import http from "node:http";
2
+ import crypto from "node:crypto";
3
+ import { rowEvent } from "./store/rows.js";
4
+
5
+ const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
6
+ export const DEFAULT_WS_PORT = 38294;
7
+ export const HISTORY_LIMIT = 200;
8
+
9
+ function acceptKey(key) {
10
+ return crypto.createHash("sha1").update(key + WS_GUID).digest("base64");
11
+ }
12
+
13
+ function encodeFrame(text) {
14
+ const payload = Buffer.from(text, "utf8");
15
+ const len = payload.length;
16
+ let header;
17
+ if (len < 126) {
18
+ header = Buffer.from([0x81, len]);
19
+ } else if (len < 65536) {
20
+ header = Buffer.alloc(4);
21
+ header[0] = 0x81;
22
+ header[1] = 126;
23
+ header.writeUInt16BE(len, 2);
24
+ } else {
25
+ header = Buffer.alloc(10);
26
+ header[0] = 0x81;
27
+ header[1] = 127;
28
+ header.writeBigUInt64BE(BigInt(len), 2);
29
+ }
30
+ return Buffer.concat([header, payload]);
31
+ }
32
+
33
+ export function lastEventId(store) {
34
+ return store.db.prepare("SELECT COALESCE(MAX(id),0) AS m FROM events").get().m;
35
+ }
36
+
37
+ export function eventsSince(store, id, limit = HISTORY_LIMIT) {
38
+ return store.db.prepare("SELECT * FROM events WHERE id > ? ORDER BY id LIMIT ?").all(id, limit).map(rowEvent);
39
+ }
40
+
41
+ export function eventsLatest(store, limit = HISTORY_LIMIT) {
42
+ return store.db.prepare("SELECT * FROM events ORDER BY id DESC LIMIT ?").all(limit).reverse().map(rowEvent);
43
+ }
44
+
45
+ export function toEventMessage(store, event) {
46
+ const order = store.order.get(event.workOrderId);
47
+ return {
48
+ type: "event",
49
+ event: {
50
+ ...event,
51
+ order: order ? { id: order.id, title: order.title, status: order.status, assignee: order.assignee } : null,
52
+ },
53
+ };
54
+ }
55
+
56
+ export function startEventServer({ store, port = null, host = "127.0.0.1", intervalMs = 1000, historyLimit = HISTORY_LIMIT, logger } = {}) {
57
+ const listenPort = port ?? store.config.wsPort ?? DEFAULT_WS_PORT;
58
+ const pollMs = intervalMs;
59
+ const history = historyLimit;
60
+ const clients = new Set();
61
+ let cursor = lastEventId(store);
62
+
63
+ function broadcast(obj) {
64
+ const frame = encodeFrame(JSON.stringify(obj));
65
+ for (const sock of [...clients]) {
66
+ if (sock.destroyed || !sock.writable) {
67
+ clients.delete(sock);
68
+ continue;
69
+ }
70
+ sock.write(frame);
71
+ }
72
+ }
73
+
74
+ const server = http.createServer((req, res) => {
75
+ res.writeHead(404, { "content-type": "text/plain" });
76
+ res.end("brayer events: websocket only\n");
77
+ });
78
+
79
+ server.on("upgrade", (req, socket) => {
80
+ const key = req.headers["sec-websocket-key"];
81
+ if ((req.headers.upgrade || "").toLowerCase() !== "websocket" || !key) {
82
+ socket.destroy();
83
+ return;
84
+ }
85
+ socket.write(
86
+ "HTTP/1.1 101 Switching Protocols\r\n" +
87
+ "Upgrade: websocket\r\n" +
88
+ "Connection: Upgrade\r\n" +
89
+ `Sec-WebSocket-Accept: ${acceptKey(key)}\r\n\r\n`
90
+ );
91
+ clients.add(socket);
92
+ socket.on("close", () => clients.delete(socket));
93
+ socket.on("error", () => clients.delete(socket));
94
+ socket.on("data", (frame) => {
95
+ if ((frame[0] & 0x0f) === 0x8) {
96
+ clients.delete(socket);
97
+ socket.end();
98
+ }
99
+ });
100
+ socket.write(encodeFrame(JSON.stringify({ type: "welcome", lastEventId: cursor })));
101
+ socket.write(encodeFrame(JSON.stringify({ type: "history", events: eventsLatest(store, history) })));
102
+ logger?.info?.(`brayer: ws subscriber connected (${clients.size} total)`);
103
+ });
104
+
105
+ const timer = setInterval(() => {
106
+ if (!store.db.open) return;
107
+ const rows = eventsSince(store, cursor, history);
108
+ if (!rows.length) return;
109
+ for (const event of rows) {
110
+ cursor = Math.max(cursor, event.id);
111
+ broadcast(toEventMessage(store, event));
112
+ }
113
+ }, pollMs);
114
+ timer.unref?.();
115
+
116
+ server.on("close", () => clearInterval(timer));
117
+ server.listen(listenPort, host, () => {
118
+ logger?.info?.(`brayer: ws listening on ${host}:${server.address().port}`);
119
+ });
120
+ return server;
121
+ }
@@ -0,0 +1,42 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ function digest(buffer) {
6
+ return createHash("sha256").update(buffer).digest("hex");
7
+ }
8
+
9
+ function blobPath(root, sha256) {
10
+ return path.join(root, sha256.slice(0, 2), sha256);
11
+ }
12
+
13
+ export function storeFile({ root, filePath }) {
14
+ if (!root) throw new Error("blob root is required");
15
+ if (!filePath) throw new Error("filePath is required");
16
+ const buffer = readFileSync(filePath);
17
+ const sha256 = digest(buffer);
18
+ const dest = blobPath(root, sha256);
19
+ mkdirSync(path.dirname(dest), { recursive: true });
20
+ if (!existsSync(dest)) writeFileSync(dest, buffer);
21
+ return { sha256, uri: `file://${dest}` };
22
+ }
23
+
24
+ export function storeBytes({ root, buffer }) {
25
+ if (!root) throw new Error("blob root is required");
26
+ const sha256 = digest(buffer);
27
+ const dest = blobPath(root, sha256);
28
+ mkdirSync(path.dirname(dest), { recursive: true });
29
+ if (!existsSync(dest)) writeFileSync(dest, buffer);
30
+ return { sha256, uri: `file://${dest}` };
31
+ }
32
+
33
+ export function verifyFile({ root, sha256 }) {
34
+ if (!sha256) return false;
35
+ const file = blobPath(root, sha256);
36
+ if (!existsSync(file)) return false;
37
+ return digest(readFileSync(file)) === sha256;
38
+ }
39
+
40
+ export function readBlob({ root, sha256 }) {
41
+ return readFileSync(blobPath(root, sha256));
42
+ }
@@ -0,0 +1,32 @@
1
+ export function assertDeclaration(base = {}) {
2
+ const harness = base.harness ?? process.env.BRAYER_HARNESS;
3
+ if (typeof harness !== "string" || !harness.trim()) {
4
+ throw new Error("brayer: BRAYER_HARNESS is required");
5
+ }
6
+ return { ...base, harness: harness.trim() };
7
+ }
8
+
9
+ export function resolveIdentity({ meta, args, base } = {}) {
10
+ const declared = assertDeclaration(base);
11
+ const stamped = meta?.brayer ?? {};
12
+
13
+ const harness = stamped.harness ?? args?.brayer_harness ?? declared.harness;
14
+ if (harness !== declared.harness) {
15
+ throw new Error("brayer: harness mismatch");
16
+ }
17
+
18
+ const agent = stamped.agent ?? args?.brayer_agent;
19
+ const session = stamped.session ?? args?.brayer_session;
20
+ if (typeof agent !== "string" || !agent.trim()) {
21
+ throw new Error("brayer: agent must be stamped on the call");
22
+ }
23
+ if (typeof session !== "string" || !session.trim()) {
24
+ throw new Error("brayer: session must be stamped on the call");
25
+ }
26
+
27
+ return { harness: declared.harness, agent: agent.trim(), session: session.trim() };
28
+ }
29
+
30
+ export function identityKey(identity) {
31
+ return `${identity.harness}:${identity.agent}:${identity.session}`;
32
+ }
package/src/ids.js ADDED
@@ -0,0 +1,17 @@
1
+ import { randomBytes } from "node:crypto";
2
+
3
+ const ALPHABET = "abcdefghijkmnopqrstuvwxyz23456789";
4
+
5
+ function suffix(len = 8) {
6
+ const bytes = randomBytes(len);
7
+ let out = "";
8
+ for (let i = 0; i < len; i++) out += ALPHABET[bytes[i] % ALPHABET.length];
9
+ return out;
10
+ }
11
+
12
+ export function newOrderId() { return `WO-${suffix()}`; }
13
+ export function newAttemptId() { return `ATT-${suffix()}`; }
14
+ export function newCheckpointId() { return `CP-${suffix()}`; }
15
+ export function newEvidenceId() { return `EV-${suffix()}`; }
16
+ export function newVerdictId() { return `VD-${suffix()}`; }
17
+ export function newPlaybookId() { return `PB-${suffix()}`; }
package/src/mcp.js ADDED
@@ -0,0 +1,114 @@
1
+ import http from "node:http";
2
+ import { timingSafeEqual } from "node:crypto";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
6
+ import * as z from "zod/v4-mini";
7
+ import { createToolHandlers } from "./tools/index.js";
8
+ import { assertDeclaration, resolveIdentity } from "./identity.js";
9
+ import { VERSION } from "./version.js";
10
+
11
+ function errorResult(err) {
12
+ return {
13
+ content: [{ type: "text", text: JSON.stringify({ error: String(err?.message ?? err) }) }],
14
+ isError: true,
15
+ };
16
+ }
17
+
18
+ export function createMcpServer({ store, base, logger } = {}) {
19
+ const declared = assertDeclaration(base);
20
+ const { TOOL_DEFS, handle } = createToolHandlers(store);
21
+ const server = new McpServer({ name: "brayer", version: VERSION });
22
+
23
+ for (const def of TOOL_DEFS) {
24
+ server.registerTool(
25
+ def.name,
26
+ { description: def.description, inputSchema: z.object(def.shape) },
27
+ async (args, extra) => {
28
+ try {
29
+ const identity = resolveIdentity({ meta: extra?._meta, args, base: declared });
30
+ logger?.info?.(`brayer: ${def.name} from ${identity.harness}:${identity.agent}:${identity.session}`);
31
+ const result = await handle(def.name, args, identity);
32
+ return { content: [{ type: "text", text: JSON.stringify(result) }] };
33
+ } catch (err) {
34
+ return errorResult(err);
35
+ }
36
+ }
37
+ );
38
+ }
39
+
40
+ return server;
41
+ }
42
+
43
+ export async function startMcpServer({ store, base, logger } = {}) {
44
+ const server = createMcpServer({ store, base, logger });
45
+ const transport = new StdioServerTransport();
46
+ await server.connect(transport);
47
+ logger?.info?.("brayer: MCP server connected on stdio");
48
+ return server;
49
+ }
50
+
51
+ function safeEqual(a, b) {
52
+ const ab = Buffer.from(String(a ?? ""));
53
+ const bb = Buffer.from(String(b ?? ""));
54
+ return ab.length === bb.length && timingSafeEqual(ab, bb);
55
+ }
56
+
57
+ export async function startMcpHttpServer({
58
+ store,
59
+ base,
60
+ port = store.config.httpPort,
61
+ host = "127.0.0.1",
62
+ bearer,
63
+ logger,
64
+ } = {}) {
65
+ if (!bearer) throw new Error("brayer: BRAYER_MCP_BEARER is required for HTTP");
66
+ const server = http.createServer(async (req, res) => {
67
+ if (req.url === "/health") {
68
+ res.writeHead(200, { "content-type": "application/json" });
69
+ res.end(JSON.stringify({ ok: true }));
70
+ return;
71
+ }
72
+ const pathname = new URL(req.url, "http://localhost").pathname;
73
+ if (pathname !== "/mcp") {
74
+ res.writeHead(404, { "content-type": "application/json" });
75
+ res.end(JSON.stringify({ error: "not found" }));
76
+ return;
77
+ }
78
+ const auth = req.headers.authorization ?? "";
79
+ if (!auth.startsWith("Bearer ") || !safeEqual(auth.slice(7), bearer)) {
80
+ res.writeHead(401, { "content-type": "application/json", "www-authenticate": "Bearer" });
81
+ res.end(JSON.stringify({ error: "unauthorized" }));
82
+ return;
83
+ }
84
+ if (req.method !== "POST") {
85
+ res.writeHead(405, { allow: "POST", "content-type": "application/json" });
86
+ res.end(JSON.stringify({ error: "method not allowed" }));
87
+ return;
88
+ }
89
+
90
+ const mcp = createMcpServer({ store, base, logger });
91
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
92
+ try {
93
+ await mcp.connect(transport);
94
+ await transport.handleRequest(req, res);
95
+ } catch (err) {
96
+ logger?.warn?.(`brayer: HTTP MCP failed: ${err?.message ?? err}`);
97
+ if (!res.headersSent) {
98
+ res.writeHead(500, { "content-type": "application/json" });
99
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null }));
100
+ }
101
+ } finally {
102
+ res.on("close", () => {
103
+ transport.close();
104
+ mcp.close();
105
+ });
106
+ }
107
+ });
108
+ await new Promise((resolve, reject) => {
109
+ server.once("error", reject);
110
+ server.listen(port, host, resolve);
111
+ });
112
+ logger?.info?.(`brayer: MCP HTTP listening on http://${host}:${server.address().port}/mcp`);
113
+ return server;
114
+ }