@igorjpimenta/brayer 2026.10.28-beta.1 → 2026.11.3-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.
package/README.md CHANGED
@@ -76,7 +76,7 @@ The MCP tools are:
76
76
  | Area | Tools |
77
77
  | --- | --- |
78
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_get` |
79
+ | Attempts | `brayer_attempt_start`, `brayer_attempt_finish`, `brayer_attempt_report_usage`, `brayer_attempt_get` |
80
80
  | Handoff | `brayer_checkpoint_write`, `brayer_checkpoint_get` |
81
81
  | Evidence | `brayer_evidence_attach`, `brayer_evidence_list` |
82
82
  | Verdict | `brayer_verdict_issue`, `brayer_verdict_list` |
@@ -209,12 +209,28 @@ on turn end, resumes from the latest checkpoint, and receives claim webhooks at
209
209
  }
210
210
  ```
211
211
 
212
- **OpenCode** — `@igorjpimenta/brayer-opencode` stamps agent/session identity and
213
- checkpoints on idle, compaction and error. It loads through the OpenCode plugin
214
- config or a local `file://` entry.
212
+ **OpenCode** — `@igorjpimenta/brayer-opencode` stamps agent/session identity on
213
+ Brayer MCP tool calls. It needs the Brayer MCP server configured and
214
+ `BRAYER_AGENT` when the session agent cannot be captured.
215
215
 
216
- **Wake bridge** — OpenCode has no plugin HTTP route, so `@igorjpimenta/brayer-wake`
217
- receives the claim webhook and prompts the claiming session through the
216
+ ```json
217
+ {
218
+ "mcp": {
219
+ "brayer": {
220
+ "type": "remote",
221
+ "url": "http://127.0.0.1:38293/mcp",
222
+ "headers": { "Authorization": "Bearer secret" }
223
+ }
224
+ },
225
+ "plugin": ["@igorjpimenta/brayer-opencode"]
226
+ }
227
+ ```
228
+
229
+ Automatic checkpoint/resume is not part of this release; the agent uses the
230
+ Brayer MCP tools directly.
231
+
232
+ **Wake bridge** — the OpenCode package also ships the optional `brayer-wake` bin.
233
+ It receives the claim webhook and prompts the claiming session through the
218
234
  OpenCode SDK.
219
235
 
220
236
  ## Docker
@@ -229,9 +245,8 @@ HTTP MCP is exposed on 38293 and the event stream on 38294.
229
245
  ## Release
230
246
 
231
247
  Versions are CalVer (`YYYY.MM.DD-beta.N`). Tags are bare for core and prefixed
232
- for adapters: `brayer-openclaw-<calver>`, `brayer-opencode-<calver>`,
233
- `brayer-wake-<calver>`. Prereleases publish to `beta`; stable tags publish to
234
- `latest`.
248
+ for adapters: `brayer-openclaw-<calver>` and `brayer-opencode-<calver>`.
249
+ Prereleases publish to `beta`; stable tags publish to `latest`.
235
250
 
236
251
  ## Development
237
252
 
package/bin/brayer.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { main } from "../src/cli.js";
2
+ import { main } from "../src/cli/index.js";
3
3
 
4
4
  main().catch((err) => {
5
5
  console.error(err.message);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/brayer",
3
- "version": "2026.10.28-beta.1",
3
+ "version": "2026.11.3-beta.1",
4
4
  "description": "Vendor-neutral command layer for agent work",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -29,6 +29,7 @@
29
29
  "start": "node bin/brayer.js",
30
30
  "test": "node --test \"test/unit/**/*.js\"",
31
31
  "test:e2e": "node --test \"test/e2e/*.test.js\"",
32
+ "proof:opencode": "node scripts/proof-opencode.mjs",
32
33
  "db:generate": "drizzle-kit generate",
33
34
  "db:migrate": "drizzle-kit migrate"
34
35
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/brayer-openclaw",
3
- "version": "2026.10.28-beta.1",
3
+ "version": "2026.11.3-beta.1",
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.10.28-beta.1"
35
+ "@igorjpimenta/brayer": "2026.11.3-beta.1"
36
36
  }
37
37
  }
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { startWakeServer } from "../index.js";
2
+ import { startWakeServer } from "../wake.js";
3
3
 
4
4
  startWakeServer().catch((err) => {
5
5
  console.error(err?.message ?? err);
@@ -0,0 +1,17 @@
1
+ import { stampBrayerIdentity } from "./identity.js";
2
+
3
+ export function createBrayerHooks() {
4
+ const agents = new Map();
5
+
6
+ return {
7
+ "chat.message": async (input) => {
8
+ if (input?.sessionID && input?.agent) agents.set(input.sessionID, input.agent);
9
+ },
10
+ "chat.params": async (input) => {
11
+ if (input?.sessionID && input?.agent) agents.set(input.sessionID, input.agent);
12
+ },
13
+ "tool.execute.before": async (input, output) => {
14
+ stampBrayerIdentity(input, output, { agent: agents.get(input?.sessionID) ?? process.env.BRAYER_AGENT });
15
+ },
16
+ };
17
+ }
@@ -1,3 +1,9 @@
1
+ // identity.js — opencode can mutate tool args but not request _meta, so the
2
+ // brayer server accepts a whole agent+session pair as brayer_agent/
3
+ // brayer_session args (src/identity.js, args channel). The hook overwrites
4
+ // both unconditionally: a model-supplied pair must never survive. The harness
5
+ // is not an argument — the MCP connection declares it via X-Brayer-Harness.
6
+
1
7
  export function isBrayerTool(name) {
2
8
  return typeof name === "string" && name.includes("brayer");
3
9
  }
@@ -5,7 +11,7 @@ export function isBrayerTool(name) {
5
11
  export function stampBrayerIdentity(input, output, { agent = null } = {}) {
6
12
  if (!isBrayerTool(input?.tool)) return false;
7
13
  output.args = output.args ?? {};
8
- if (!output.args.brayer_agent && agent) output.args.brayer_agent = agent;
9
- if (!output.args.brayer_session) output.args.brayer_session = input.sessionID;
14
+ if (agent) output.args.brayer_agent = agent;
15
+ if (input?.sessionID) output.args.brayer_session = input.sessionID;
10
16
  return true;
11
17
  }
@@ -1,92 +1,5 @@
1
- import { createStore } from "@igorjpimenta/brayer/src/store.js";
2
- import {
3
- attachSession,
4
- checkpointSession,
5
- resumeSession,
6
- } from "@igorjpimenta/brayer/plugins/shared/contract.js";
7
- import { stampBrayerIdentity } from "./identity.js";
8
- import { checkpointPayload, eventSessionID, resumeContext } from "./session.js";
1
+ import { createBrayerHooks } from "./hooks.js";
9
2
 
10
- export { isBrayerTool, stampBrayerIdentity } from "./identity.js";
11
-
12
- const TRIGGERS = {
13
- "session.idle": "idle",
14
- "session.compacted": "compaction",
15
- "session.error": "error",
16
- };
17
-
18
- export function createBrayerHooks({ store, orderId, worktree } = {}) {
19
- const agents = new Map();
20
- const resumed = new Set();
21
-
22
- const sessionFor = (sessionID) => {
23
- const agent = agents.get(sessionID);
24
- if (!agent || !sessionID) return null;
25
- return { harness: "opencode", agent, session: sessionID };
26
- };
27
-
28
- const hooks = {
29
- "chat.message": async (input) => {
30
- if (input?.sessionID && input?.agent) agents.set(input.sessionID, input.agent);
31
- },
32
- "tool.execute.before": async (input, output) => {
33
- stampBrayerIdentity(input, output, { agent: agents.get(input?.sessionID) });
34
- },
35
- dispose: async () => {
36
- store?.close();
37
- },
38
- };
39
-
40
- if (!store || !orderId) return hooks;
41
-
42
- hooks.event = async ({ event } = {}) => {
43
- const trigger = TRIGGERS[event?.type];
44
- if (!trigger) return;
45
- const sessionID = eventSessionID(event);
46
- const session = sessionFor(sessionID);
47
- if (!session) return;
48
- try {
49
- const attached = attachSession({ store, session, orderId });
50
- const payload = checkpointPayload({ trigger, event });
51
- checkpointSession({
52
- store,
53
- session,
54
- orderId,
55
- attemptId: attached.attempt.id,
56
- ...payload,
57
- treeHash: worktree ?? "unknown",
58
- });
59
- } catch {}
60
- };
61
-
62
- hooks["experimental.chat.system.transform"] = async (input, output) => {
63
- if (!input?.sessionID || resumed.has(input.sessionID)) return;
64
- const session = sessionFor(input.sessionID);
65
- if (!session) return;
66
- try {
67
- const resumed = resumeSession({ store, session, orderId });
68
- const context = resumeContext(resumed.checkpoint);
69
- if (context) {
70
- output.system.push(context);
71
- resumed.add(input.sessionID);
72
- }
73
- } catch {}
74
- };
75
-
76
- return hooks;
3
+ export default async function BrayerPlugin() {
4
+ return createBrayerHooks();
77
5
  }
78
-
79
- export default {
80
- id: "brayer",
81
- server: async (input, options = {}) => {
82
- const orderId = options.orderId ?? process.env.BRAYER_ORDER_ID ?? null;
83
- const store = orderId
84
- ? createStore({ dbPath: options.dbPath ?? process.env.BRAYER_DB ?? undefined })
85
- : null;
86
- return createBrayerHooks({
87
- store,
88
- orderId,
89
- worktree: options.worktree ?? input?.worktree ?? input?.directory,
90
- });
91
- },
92
- };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@igorjpimenta/brayer-opencode",
3
- "version": "2026.10.28-beta.1",
4
- "description": "OpenCode companion for Brayer: stamps agent and session identity on Brayer tool calls.",
3
+ "version": "2026.11.3-beta.1",
4
+ "description": "OpenCode companion for Brayer: stamps identity and runs the optional claim wake bridge.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "repository": {
@@ -18,10 +18,16 @@
18
18
  },
19
19
  "files": [
20
20
  "index.js",
21
+ "hooks.js",
21
22
  "identity.js",
22
- "session.js"
23
+ "wake.js",
24
+ "bin/"
23
25
  ],
26
+ "main": "index.js",
27
+ "bin": {
28
+ "brayer-wake": "bin/brayer-wake.js"
29
+ },
24
30
  "dependencies": {
25
- "@igorjpimenta/brayer": "2026.10.28-beta.1"
31
+ "@opencode-ai/sdk": "1.19.3"
26
32
  }
27
33
  }
@@ -97,6 +97,7 @@ export function checkpointSession({
97
97
  goal = null,
98
98
  confidence = null,
99
99
  resumeRecipe = null,
100
+ usage = null,
100
101
  }) {
101
102
  const kind = CHECKPOINT_TRIGGERS[trigger];
102
103
  if (!kind) throw new Error(`brayer: unknown checkpoint trigger: ${trigger}`);
@@ -112,6 +113,7 @@ export function checkpointSession({
112
113
  treeHash,
113
114
  actor: sessionIdentity(session),
114
115
  });
116
+ if (usage) store.attempt.reportUsage({ attemptId, ...usage });
115
117
  return checkpoint;
116
118
  }
117
119
 
@@ -161,11 +163,11 @@ export function finishSession({
161
163
  attemptId,
162
164
  status = "finished",
163
165
  summary = null,
164
- tokensIn = 0,
165
- tokensOut = 0,
166
- cacheRead = 0,
167
- costUsd = 0,
168
- toolCalls = 0,
166
+ tokensIn,
167
+ tokensOut,
168
+ cacheRead,
169
+ costUsd,
170
+ toolCalls,
169
171
  error = null,
170
172
  checkpointId = null,
171
173
  }) {
@@ -0,0 +1,15 @@
1
+ export function flagValue(args, name) {
2
+ const i = args.indexOf(name);
3
+ return i >= 0 ? args[i + 1] : null;
4
+ }
5
+
6
+ export function flagMap(args) {
7
+ const out = {};
8
+ for (let i = 0; i < args.length; i += 1) {
9
+ if (args[i].startsWith("--") && args[i + 1] !== undefined) {
10
+ out[args[i].slice(2)] = args[i + 1];
11
+ i += 1;
12
+ }
13
+ }
14
+ return out;
15
+ }
@@ -0,0 +1,12 @@
1
+ export function formatStatus(orders) {
2
+ if (!orders.length) return "No work orders.";
3
+ const rows = orders.map((o) => [
4
+ o.id,
5
+ o.status.padEnd(9),
6
+ o.assignee ?? "-",
7
+ String(o.attemptCount),
8
+ o.title,
9
+ ]);
10
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => r[i].length)));
11
+ return rows.map((r) => r.map((v, i) => (i === 4 ? v : v.padEnd(widths[i]))).join(" ")).join("\n");
12
+ }
@@ -0,0 +1,60 @@
1
+ import { VERSION } from "../version.js";
2
+ import { flagMap } from "./args.js";
3
+ import { formatStatus } from "./format.js";
4
+ import { runServe } from "./serve.js";
5
+ import { runStatus } from "./status.js";
6
+ import { runSweep } from "./sweep.js";
7
+ import { runWebhook } from "./webhook.js";
8
+
9
+ const usage = `brayer ${VERSION}
10
+
11
+ Usage:
12
+ brayer --version
13
+ brayer serve --mcp stdio
14
+ brayer serve --mcp http --port 38293 [--host 127.0.0.1]
15
+ brayer serve --ws --port 38294
16
+ brayer status [--json]
17
+ brayer sweep [--max-attempts N]
18
+ brayer webhook set --harness H --url U [--bearer B] [--timeout-ms N]
19
+ brayer webhook list
20
+ brayer webhook remove --harness H
21
+ brayer webhook test --harness H
22
+
23
+ HTTP and the full inbox land in later stories.`;
24
+
25
+ export { formatStatus };
26
+
27
+ export async function main(argv = process.argv.slice(2), { env = process.env, logger = console } = {}) {
28
+ const [command, ...rest] = argv;
29
+
30
+ if (command === "--version" || command === "-v") {
31
+ console.log(VERSION);
32
+ return;
33
+ }
34
+ if (!command || command === "--help" || command === "-h") {
35
+ console.log(usage);
36
+ return;
37
+ }
38
+
39
+ if (command === "status") {
40
+ await runStatus({ rest, env, logger });
41
+ return;
42
+ }
43
+
44
+ if (command === "webhook") {
45
+ await runWebhook({ rest, env, logger });
46
+ return;
47
+ }
48
+
49
+ if (command === "sweep") {
50
+ await runSweep({ args: rest, env, logger });
51
+ return;
52
+ }
53
+
54
+ if (command === "serve") {
55
+ await runServe({ rest, env, logger });
56
+ return;
57
+ }
58
+
59
+ throw new Error(`brayer: ${command} is not implemented yet`);
60
+ }
@@ -0,0 +1,41 @@
1
+ import { createStore } from "../store.js";
2
+ import { startMcpHttpServer, startMcpServer } from "../mcp.js";
3
+ import { startEventServer } from "../events-ws.js";
4
+ import { flagValue } from "./args.js";
5
+
6
+ export async function runServe({ rest, env }) {
7
+ const mcpIndex = rest.indexOf("--mcp");
8
+ const transport = mcpIndex >= 0 ? rest[mcpIndex + 1] : null;
9
+ if (transport) {
10
+ const base = env.BRAYER_HARNESS ? { harness: env.BRAYER_HARNESS } : undefined;
11
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
12
+ if (transport === "stdio") {
13
+ if (!base) throw new Error("brayer: BRAYER_HARNESS is required for stdio MCP");
14
+ await startMcpServer({ store, base });
15
+ return;
16
+ }
17
+ if (transport === "http") {
18
+ if (!env.BRAYER_MCP_BEARER) throw new Error("brayer: BRAYER_MCP_BEARER is required for HTTP");
19
+ const port = Number(flagValue(rest, "--port") ?? env.BRAYER_HTTP_PORT ?? 38293);
20
+ const host = flagValue(rest, "--host") ?? "127.0.0.1";
21
+ await startMcpHttpServer({
22
+ store,
23
+ base,
24
+ port,
25
+ host,
26
+ bearer: env.BRAYER_MCP_BEARER,
27
+ });
28
+ return;
29
+ }
30
+ throw new Error("brayer: serve --mcp supports stdio or http");
31
+ }
32
+
33
+ if (rest.includes("--ws")) {
34
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
35
+ const port = flagValue(rest, "--port");
36
+ startEventServer({ store, port: port ? Number(port) : undefined });
37
+ return;
38
+ }
39
+
40
+ throw new Error("brayer: serve requires --mcp stdio or --ws");
41
+ }
@@ -0,0 +1,13 @@
1
+ import { createStore } from "../store.js";
2
+ import { formatStatus } from "./format.js";
3
+
4
+ export async function runStatus({ rest, env }) {
5
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
6
+ try {
7
+ const orders = store.order.list({ limit: 100 });
8
+ if (rest.includes("--json")) console.log(JSON.stringify({ orders }, null, 2));
9
+ else console.log(formatStatus(orders));
10
+ } finally {
11
+ store.close();
12
+ }
13
+ }
@@ -0,0 +1,28 @@
1
+ import { createStore } from "../store.js";
2
+
3
+ export function parseSweepArgs(args) {
4
+ const out = {};
5
+ for (let i = 0; i < args.length; i += 1) {
6
+ if (args[i].startsWith("--") && args[i + 1] !== undefined) {
7
+ out[args[i].slice(2)] = args[i + 1];
8
+ i += 1;
9
+ }
10
+ }
11
+ return out;
12
+ }
13
+
14
+ export async function runSweep({ args = [], env = process.env, logger = console } = {}) {
15
+ const values = parseSweepArgs(args);
16
+ const maxAttempts = values["max-attempts"] !== undefined ? Number(values["max-attempts"]) : undefined;
17
+ if (maxAttempts !== undefined && (!Number.isInteger(maxAttempts) || maxAttempts < 1)) {
18
+ throw new Error("brayer: --max-attempts must be a positive integer");
19
+ }
20
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
21
+ try {
22
+ const result = store.claim.sweepExpired(maxAttempts === undefined ? {} : { maxAttempts });
23
+ console.log(JSON.stringify(result, null, 2));
24
+ return result;
25
+ } finally {
26
+ store.close();
27
+ }
28
+ }
@@ -0,0 +1,53 @@
1
+ import { createStore } from "../store.js";
2
+ import { flagMap } from "./args.js";
3
+ import { webhookConfig } from "../claim-webhook.js";
4
+
5
+ export async function runWebhook({ rest, env }) {
6
+ const [sub, ...webhookArgs] = rest;
7
+ const values = flagMap(webhookArgs);
8
+ const harness = values.harness;
9
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
10
+ try {
11
+ if (sub === "list") {
12
+ const rows = store.webhook.list().map((row) => ({ ...row, bearer: row.bearer ? "<set>" : null }));
13
+ console.log(JSON.stringify(rows, null, 2));
14
+ return;
15
+ }
16
+ if (!["set", "remove", "test"].includes(sub)) {
17
+ throw new Error("brayer: webhook requires set, list, remove or test");
18
+ }
19
+ if (!harness) throw new Error(`brayer: webhook ${sub} requires --harness`);
20
+ if (sub === "remove") {
21
+ if (!store.webhook.remove({ harness })) throw new Error(`brayer: no webhook for ${harness}`);
22
+ console.log(JSON.stringify({ removed: harness }));
23
+ return;
24
+ }
25
+ if (sub === "set") {
26
+ if (!values.url) throw new Error("brayer: webhook set requires --url");
27
+ const timeoutMs = values["timeout-ms"] !== undefined ? Number(values["timeout-ms"]) : null;
28
+ const row = store.webhook.upsert({
29
+ harness,
30
+ url: values.url,
31
+ bearer: values.bearer ?? null,
32
+ timeoutMs,
33
+ });
34
+ console.log(JSON.stringify({ ...row, bearer: row.bearer ? "<set>" : null }, null, 2));
35
+ return;
36
+ }
37
+ const hook = webhookConfig(store.config, harness, store.webhook.get(harness));
38
+ if (!hook) throw new Error(`brayer: no webhook for ${harness}`);
39
+ const headers = { "content-type": "application/json" };
40
+ if (hook.bearer) headers.authorization = `Bearer ${hook.bearer}`;
41
+ const res = await fetch(hook.url, {
42
+ method: "POST",
43
+ headers,
44
+ body: JSON.stringify({ event: "webhook.test", at: Date.now(), harness }),
45
+ signal: AbortSignal.timeout(hook.timeoutMs),
46
+ });
47
+ const text = await res.text();
48
+ console.log(JSON.stringify({ ok: res.ok, status: res.status, body: text.slice(0, 500) }, null, 2));
49
+ if (!res.ok) process.exitCode = 1;
50
+ } finally {
51
+ store.close();
52
+ }
53
+ }
package/src/identity.js CHANGED
@@ -1,8 +1,26 @@
1
+ // A usable layer names something: non-empty, and neither of the two tokens
2
+ // no key may carry ("unknown", "instance:*").
3
+ function isUsableLayer(v) {
4
+ return (
5
+ typeof v === "string" &&
6
+ v.trim() !== "" &&
7
+ !/^(unknown|instance:.*)$/i.test(v.trim())
8
+ );
9
+ }
10
+
11
+ // The server is constructed with the harness it serves; the mint decides
12
+ // what that is per transport — BRAYER_HARNESS env for one-to-one stdio, the
13
+ // X-Brayer-Harness header at session creation for shared HTTP. Agent and
14
+ // session are never declared: they arrive per call, stamped by the calling
15
+ // harness's companion plugin.
1
16
  export function assertDeclaration(base = {}) {
2
17
  const harness = base.harness ?? process.env.BRAYER_HARNESS;
3
18
  if (typeof harness !== "string" || !harness.trim()) {
4
19
  throw new Error("brayer: BRAYER_HARNESS is required");
5
20
  }
21
+ if (/^(unknown|instance:.*)$/i.test(harness.trim())) {
22
+ throw new Error(`brayer: refused declaration (reserved: harness). "${harness}" cannot identify a consumer — declare the real harness name.`);
23
+ }
6
24
  return { ...base, harness: harness.trim() };
7
25
  }
8
26
 
@@ -10,21 +28,30 @@ export function resolveIdentity({ meta, args, base } = {}) {
10
28
  const declared = assertDeclaration(base);
11
29
  const stamped = meta?.brayer ?? {};
12
30
 
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");
31
+ // Whole pairs only: a _meta half never splices with an args half, so no
32
+ // call can assemble an identity across trust channels.
33
+ const usable = (v) => (typeof v === "string" && v.trim() ? v.trim() : null);
34
+ const mAgent = usable(stamped.agent);
35
+ const mSession = usable(stamped.session);
36
+ const aAgent = usable(args?.brayer_agent);
37
+ const aSession = usable(args?.brayer_session);
38
+ const pair =
39
+ mAgent && mSession
40
+ ? { agent: mAgent, session: mSession }
41
+ : aAgent && aSession
42
+ ? { agent: aAgent, session: aSession }
43
+ : null;
44
+ if (!pair) {
45
+ if ((mAgent || aAgent) && (mSession || aSession)) {
46
+ throw new Error("brayer: refused caller identity (halves in different channels — pairs never splice). Stamp a whole agent+session pair in one channel: _meta.brayer or brayer_agent/brayer_session args.");
47
+ }
48
+ const bad = [];
49
+ if (!mAgent && !aAgent) bad.push("agent");
50
+ if (!mSession && !aSession) bad.push("session");
51
+ throw new Error(`brayer: ${bad.join(" and ")} must be stamped on the call`);
25
52
  }
26
53
 
27
- return { harness: declared.harness, agent: agent.trim(), session: session.trim() };
54
+ return { harness: declared.harness, agent: pair.agent, session: pair.session };
28
55
  }
29
56
 
30
57
  export function identityKey(identity) {
package/src/mcp.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import http from "node:http";
2
- import { timingSafeEqual } from "node:crypto";
2
+ import { randomUUID, timingSafeEqual } from "node:crypto";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
5
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
@@ -63,6 +63,27 @@ export async function startMcpHttpServer({
63
63
  logger,
64
64
  } = {}) {
65
65
  if (!bearer) throw new Error("brayer: BRAYER_MCP_BEARER is required for HTTP");
66
+
67
+ // Shared HTTP mint: one process serves every harness. The first request on
68
+ // a session declares the harness via the X-Brayer-Harness header — set by
69
+ // the harness's own client config, never by the model — and that session
70
+ // keeps the declaration for its lifetime. Later session requests replay to
71
+ // the same server; the header is only consulted at minting.
72
+ const sessions = new Map();
73
+
74
+ async function readBody(req) {
75
+ const chunks = [];
76
+ for await (const chunk of req) chunks.push(chunk);
77
+ const body = Buffer.concat(chunks);
78
+ if (!body.length) return undefined;
79
+ return JSON.parse(body.toString("utf8"));
80
+ }
81
+
82
+ async function dispatch(req, res, entry) {
83
+ const body = await readBody(req);
84
+ await entry.transport.handleRequest(req, res, body);
85
+ }
86
+
66
87
  const server = http.createServer(async (req, res) => {
67
88
  if (req.url === "/health") {
68
89
  res.writeHead(200, { "content-type": "application/json" });
@@ -87,22 +108,52 @@ export async function startMcpHttpServer({
87
108
  return;
88
109
  }
89
110
 
90
- const mcp = createMcpServer({ store, base, logger });
91
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
111
+ const sid = req.headers["mcp-session-id"];
112
+ if (typeof sid === "string" && sessions.has(sid)) {
113
+ try {
114
+ await dispatch(req, res, sessions.get(sid));
115
+ } catch (err) {
116
+ logger?.warn?.(`brayer: HTTP MCP failed: ${err?.message ?? err}`);
117
+ if (!res.headersSent) {
118
+ res.writeHead(500, { "content-type": "application/json" });
119
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null }));
120
+ }
121
+ }
122
+ return;
123
+ }
124
+
125
+ // New session: read the declared harness, refuse unusable names, then
126
+ // mint the session-scoped server and register it by response header.
127
+ const header = req.headers["x-brayer-harness"];
128
+ const headerValue = Array.isArray(header) ? header[0] : header;
129
+ let minted;
130
+ try {
131
+ minted = assertDeclaration({ harness: headerValue });
132
+ } catch {
133
+ res.writeHead(400, { "content-type": "application/json" });
134
+ res.end(JSON.stringify({ error: "missing or reserved X-Brayer-Harness" }));
135
+ return;
136
+ }
137
+ const mcp = createMcpServer({ store, base: minted, logger });
138
+ const transport = new StreamableHTTPServerTransport({
139
+ sessionIdGenerator: () => randomUUID(),
140
+ onsessioninitialized: (id) => sessions.set(id, { server: mcp, transport }),
141
+ });
142
+ transport.onclose = () => {
143
+ for (const [id, entry] of sessions) {
144
+ if (entry.transport === transport) sessions.delete(id);
145
+ }
146
+ };
92
147
  try {
93
148
  await mcp.connect(transport);
94
- await transport.handleRequest(req, res);
149
+ await dispatch(req, res, { transport });
95
150
  } catch (err) {
151
+ mcp.close();
96
152
  logger?.warn?.(`brayer: HTTP MCP failed: ${err?.message ?? err}`);
97
153
  if (!res.headersSent) {
98
154
  res.writeHead(500, { "content-type": "application/json" });
99
155
  res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null }));
100
156
  }
101
- } finally {
102
- res.on("close", () => {
103
- transport.close();
104
- mcp.close();
105
- });
106
157
  }
107
158
  });
108
159
  await new Promise((resolve, reject) => {
@@ -2,7 +2,7 @@ import { newAttemptId } from "../ids.js";
2
2
  import { now } from "./util.js";
3
3
  import { rowAttempt } from "./rows.js";
4
4
 
5
- export function createAttemptApi({ db, insertEvent, orderApi }) {
5
+ export function createAttemptApi({ db, insertEvent, orderApi, clearExpiry }) {
6
6
  const attemptApi = {
7
7
  get(id) {
8
8
  return rowAttempt(db.prepare("SELECT * FROM attempts WHERE id=?").get(id));
@@ -49,15 +49,60 @@ export function createAttemptApi({ db, insertEvent, orderApi }) {
49
49
  }
50
50
  },
51
51
 
52
- finish({
52
+ reportUsage({
53
53
  attemptId,
54
- status,
55
- summary = null,
54
+ model = null,
56
55
  tokensIn = 0,
57
56
  tokensOut = 0,
58
57
  cacheRead = 0,
59
58
  costUsd = 0,
60
59
  toolCalls = 0,
60
+ } = {}) {
61
+ if (!attemptId) throw new Error("attemptId is required");
62
+ for (const [name, value] of Object.entries({ tokensIn, tokensOut, cacheRead, costUsd, toolCalls })) {
63
+ if (!Number.isFinite(value) || value < 0) throw new Error(`${name} must be a non-negative number`);
64
+ }
65
+ for (const [name, value] of Object.entries({ tokensIn, tokensOut, cacheRead, toolCalls })) {
66
+ if (!Number.isInteger(value)) throw new Error(`${name} must be an integer`);
67
+ }
68
+ const t = now();
69
+ db.exec("BEGIN IMMEDIATE");
70
+ try {
71
+ const attempt = attemptApi.get(attemptId);
72
+ if (!attempt) { db.exec("ROLLBACK"); return { attempt: null, order: null, reason: "not_found" }; }
73
+ if (attempt.status !== "running") { db.exec("ROLLBACK"); return { attempt, order: orderApi.get(attempt.workOrderId), reason: "not_running" }; }
74
+
75
+ db.prepare(`
76
+ UPDATE attempts
77
+ SET model=COALESCE(?, model),
78
+ tokens_in=tokens_in+?, tokens_out=tokens_out+?, cache_read=cache_read+?,
79
+ cost_usd=cost_usd+?, tool_calls=tool_calls+?
80
+ WHERE id=? AND status='running'
81
+ `).run(model, tokensIn, tokensOut, cacheRead, costUsd, toolCalls, attemptId);
82
+
83
+ insertEvent({
84
+ workOrderId: attempt.workOrderId, attemptId, fromStatus: "running", toStatus: "running",
85
+ kind: "attempt.usage", actor: attempt.agent,
86
+ note: `usage +${tokensIn}/+${tokensOut} in/out, +${toolCalls} tools, +$${costUsd}`,
87
+ sessionRef: attempt.sessionRef, at: t,
88
+ });
89
+ db.exec("COMMIT");
90
+ return { attempt: attemptApi.get(attemptId), order: orderApi.get(attempt.workOrderId), reason: null };
91
+ } catch (err) {
92
+ db.exec("ROLLBACK");
93
+ throw err;
94
+ }
95
+ },
96
+
97
+ finish({
98
+ attemptId,
99
+ status,
100
+ summary = null,
101
+ tokensIn,
102
+ tokensOut,
103
+ cacheRead,
104
+ costUsd,
105
+ toolCalls,
61
106
  error = null,
62
107
  checkpointId = null,
63
108
  } = {}) {
@@ -70,12 +115,31 @@ export function createAttemptApi({ db, insertEvent, orderApi }) {
70
115
  if (!attempt) { db.exec("ROLLBACK"); return { attempt: null, order: null, reason: "not_found" }; }
71
116
  if (attempt.status !== "running") { db.exec("ROLLBACK"); return { attempt, order: orderApi.get(attempt.workOrderId), reason: "not_running" }; }
72
117
 
118
+ const nextCheckpointId = checkpointId ?? attempt.checkpointId;
119
+ const nextUsage = {
120
+ tokensIn: tokensIn ?? attempt.tokensIn,
121
+ tokensOut: tokensOut ?? attempt.tokensOut,
122
+ cacheRead: cacheRead ?? attempt.cacheRead,
123
+ costUsd: costUsd ?? attempt.costUsd,
124
+ toolCalls: toolCalls ?? attempt.toolCalls,
125
+ };
126
+ for (const [name, value] of Object.entries(nextUsage)) {
127
+ if (!Number.isFinite(value) || value < 0) throw new Error(`${name} must be a non-negative number`);
128
+ }
129
+ for (const [name, value] of Object.entries({
130
+ tokensIn: nextUsage.tokensIn,
131
+ tokensOut: nextUsage.tokensOut,
132
+ cacheRead: nextUsage.cacheRead,
133
+ toolCalls: nextUsage.toolCalls,
134
+ })) {
135
+ if (!Number.isInteger(value)) throw new Error(`${name} must be an integer`);
136
+ }
73
137
  db.prepare(`
74
138
  UPDATE attempts
75
139
  SET status=?, ended_at=?, tokens_in=?, tokens_out=?, cache_read=?, cost_usd=?,
76
140
  tool_calls=?, error=?, checkpoint_id=?
77
141
  WHERE id=? AND status='running'
78
- `).run(status, t, tokensIn, tokensOut, cacheRead, costUsd, toolCalls, error, checkpointId, attemptId);
142
+ `).run(status, t, nextUsage.tokensIn, nextUsage.tokensOut, nextUsage.cacheRead, nextUsage.costUsd, nextUsage.toolCalls, error, nextCheckpointId, attemptId);
79
143
 
80
144
  const order = orderApi.get(attempt.workOrderId);
81
145
  const nextStatus = status === "finished" ? "review" : "ready";
@@ -91,6 +155,7 @@ export function createAttemptApi({ db, insertEvent, orderApi }) {
91
155
  actor: attempt.agent, note: summary ?? error ?? status, sessionRef: attempt.sessionRef, at: t,
92
156
  });
93
157
  db.exec("COMMIT");
158
+ clearExpiry?.(attempt.workOrderId);
94
159
  return { attempt: attemptApi.get(attemptId), order: orderApi.get(attempt.workOrderId), reason: null };
95
160
  } catch (err) {
96
161
  db.exec("ROLLBACK");
@@ -1,6 +1,35 @@
1
1
  import { now } from "./util.js";
2
2
 
3
- export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim }) {
3
+ export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim, logger }) {
4
+ const timers = new Map();
5
+ const MAX_TIMER_MS = 2147483647;
6
+
7
+ function clearExpiry(id) {
8
+ const timer = timers.get(id);
9
+ if (timer) {
10
+ clearTimeout(timer);
11
+ timers.delete(id);
12
+ }
13
+ }
14
+
15
+ function scheduleExpiry(id, expiresAt) {
16
+ clearExpiry(id);
17
+ const delay = Number(expiresAt) - Date.now();
18
+ if (!Number.isFinite(delay) || delay <= 0) return;
19
+ const timer = delay > MAX_TIMER_MS
20
+ ? setTimeout(() => scheduleExpiry(id, expiresAt), MAX_TIMER_MS)
21
+ : setTimeout(() => {
22
+ timers.delete(id);
23
+ try {
24
+ claimApi.sweepExpired({ at: Date.now() + 5 });
25
+ } catch (err) {
26
+ logger?.warn?.(`brayer: lease sweep failed: ${err?.message ?? err}`);
27
+ }
28
+ }, delay + 25);
29
+ timer.unref?.();
30
+ timers.set(id, timer);
31
+ }
32
+
4
33
  const claimApi = {
5
34
  claimById({ id, agentId, sessionRef = null, leaseSeconds = cfg.leaseSeconds } = {}) {
6
35
  if (!id) throw new Error("order id is required");
@@ -28,6 +57,7 @@ export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim })
28
57
  });
29
58
  db.exec("COMMIT");
30
59
  const claimed = orderApi.get(id);
60
+ scheduleExpiry(id, claimed.claimExpiresAt ?? expires);
31
61
  notifyClaim?.({ order: claimed, agentId, sessionRef, at: t });
32
62
  return { claimed, reason: null };
33
63
  } catch (err) {
@@ -61,7 +91,10 @@ export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim })
61
91
  SET claim_expires_at=?, lease_seconds=?, last_heartbeat=?, updated_at=?
62
92
  WHERE id=? AND status='claimed' AND assignee=?
63
93
  `).run(expires, leaseSeconds, t, t, id, agentId);
64
- return r.changes ? orderApi.get(id) : null;
94
+ if (!r.changes) return null;
95
+ const order = orderApi.get(id);
96
+ scheduleExpiry(id, order.claimExpiresAt);
97
+ return order;
65
98
  },
66
99
 
67
100
  release({ id, agentId, actor = "system", reason = "released" } = {}) {
@@ -81,6 +114,7 @@ export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim })
81
114
  actor, note: reason, at: t,
82
115
  });
83
116
  db.exec("COMMIT");
117
+ clearExpiry(id);
84
118
  return orderApi.get(id);
85
119
  } catch (err) {
86
120
  db.exec("ROLLBACK");
@@ -96,6 +130,7 @@ export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim })
96
130
  let released = 0;
97
131
  let blocked = 0;
98
132
  for (const row of expired) {
133
+ clearExpiry(row.id);
99
134
  db.exec("BEGIN IMMEDIATE");
100
135
  try {
101
136
  const cur = db.prepare("SELECT status, attempt_count FROM work_orders WHERE id=?").get(row.id);
@@ -135,5 +170,20 @@ export function createClaimApi({ db, cfg, insertEvent, orderApi, notifyClaim })
135
170
  },
136
171
  };
137
172
 
173
+ claimApi.startup = () => {
174
+ claimApi.sweepExpired({ at: now() });
175
+ const rows = db.prepare(`
176
+ SELECT id, claim_expires_at FROM work_orders
177
+ WHERE status='claimed' AND claim_expires_at IS NOT NULL
178
+ `).all();
179
+ for (const row of rows) scheduleExpiry(row.id, row.claim_expires_at);
180
+ };
181
+
182
+ claimApi.clearExpiry = clearExpiry;
183
+ claimApi.closeTimers = () => {
184
+ for (const timer of timers.values()) clearTimeout(timer);
185
+ timers.clear();
186
+ };
187
+
138
188
  return claimApi;
139
189
  }
@@ -33,6 +33,9 @@ export function createVerdictApi({ db, insertEvent, orderApi, evidenceApi }) {
33
33
  if (decision === "approve" && evidenceApi.list({ workOrderId }).length === 0) {
34
34
  throw new Error("approve requires at least one evidence row");
35
35
  }
36
+ const resolvedAttemptId = attemptId ?? db.prepare(
37
+ "SELECT id FROM attempts WHERE work_order_id=? ORDER BY started_at DESC LIMIT 1"
38
+ ).get(workOrderId)?.id ?? null;
36
39
 
37
40
  const nextStatus = decision === "approve" ? "approved"
38
41
  : decision === "reject" ? "rejected"
@@ -42,10 +45,10 @@ export function createVerdictApi({ db, insertEvent, orderApi, evidenceApi }) {
42
45
  db.prepare(`
43
46
  INSERT INTO verdicts(id, work_order_id, attempt_id, decision, reason, actor, policy, evidence_ids, created_at)
44
47
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
45
- `).run(id, workOrderId, attemptId, decision, reason, actor, policy, jsonOut(evidenceIds), t);
48
+ `).run(id, workOrderId, resolvedAttemptId, decision, reason, actor, policy, jsonOut(evidenceIds), t);
46
49
  db.prepare("UPDATE work_orders SET status=?, updated_at=? WHERE id=?").run(nextStatus, t, workOrderId);
47
50
  insertEvent({
48
- workOrderId, attemptId, fromStatus: order.status, toStatus: nextStatus, kind: "verdict.issued",
51
+ workOrderId, attemptId: resolvedAttemptId, fromStatus: order.status, toStatus: nextStatus, kind: "verdict.issued",
49
52
  actor, note: reason ?? decision, at: t,
50
53
  });
51
54
  db.exec("COMMIT");
package/src/store.js CHANGED
@@ -24,12 +24,14 @@ export function createStore({ dbPath, logger, config } = {}) {
24
24
  cfg,
25
25
  insertEvent,
26
26
  orderApi: order,
27
+ logger,
27
28
  notifyClaim: (payload) => {
28
29
  const body = claimPayload(payload);
29
30
  return notifyClaim(cfg, body, { logger, dbEntry: webhook.get(body.session.harness) });
30
31
  },
31
32
  });
32
- const attempt = createAttemptApi({ db, insertEvent, orderApi: order });
33
+ claim.startup?.();
34
+ const attempt = createAttemptApi({ db, insertEvent, orderApi: order, clearExpiry: claim.clearExpiry });
33
35
  const checkpoint = createCheckpointApi({ db, insertEvent, attemptApi: attempt });
34
36
  const evidence = createEvidenceApi({ db, insertEvent, attemptApi: attempt });
35
37
  const verdict = createVerdictApi({ db, insertEvent, orderApi: order, evidenceApi: evidence });
@@ -48,6 +50,6 @@ export function createStore({ dbPath, logger, config } = {}) {
48
50
  webhook,
49
51
  event: eventApi,
50
52
  insertEvent,
51
- close() { db.close(); },
53
+ close() { claim.closeTimers?.(); db.close(); },
52
54
  };
53
55
  }
@@ -31,6 +31,21 @@ export const attemptDefs = [
31
31
  checkpointId: z.optional(z.string()),
32
32
  },
33
33
  },
34
+ {
35
+ name: "brayer_attempt_report_usage",
36
+ description:
37
+ "Add usage deltas to a running attempt. Deltas accumulate; omitted finish totals preserve what was reported.",
38
+ shape: {
39
+ ...identityShape,
40
+ attemptId: z.string(),
41
+ model: z.optional(z.string()),
42
+ tokensIn: z.optional(z.int()),
43
+ tokensOut: z.optional(z.int()),
44
+ cacheRead: z.optional(z.int()),
45
+ costUsd: z.optional(z.number()),
46
+ toolCalls: z.optional(z.int()),
47
+ },
48
+ },
34
49
  {
35
50
  name: "brayer_attempt_get",
36
51
  description: "Read one attempt. Read-only.",
@@ -57,13 +72,25 @@ export const attemptHandlers = {
57
72
  attemptId: args.attemptId,
58
73
  status: args.status,
59
74
  summary: args.summary ?? null,
75
+ tokensIn: args.tokensIn,
76
+ tokensOut: args.tokensOut,
77
+ cacheRead: args.cacheRead,
78
+ costUsd: args.costUsd,
79
+ toolCalls: args.toolCalls,
80
+ error: args.error ?? null,
81
+ checkpointId: args.checkpointId ?? null,
82
+ });
83
+ },
84
+
85
+ brayer_attempt_report_usage({ store, args }) {
86
+ return store.attempt.reportUsage({
87
+ attemptId: args.attemptId,
88
+ model: args.model ?? null,
60
89
  tokensIn: args.tokensIn ?? 0,
61
90
  tokensOut: args.tokensOut ?? 0,
62
91
  cacheRead: args.cacheRead ?? 0,
63
92
  costUsd: args.costUsd ?? 0,
64
93
  toolCalls: args.toolCalls ?? 0,
65
- error: args.error ?? null,
66
- checkpointId: args.checkpointId ?? null,
67
94
  });
68
95
  },
69
96
 
@@ -1,25 +0,0 @@
1
- export function eventSessionID(event) {
2
- return event?.properties?.sessionID ?? event?.properties?.info?.id ?? null;
3
- }
4
-
5
- export function checkpointPayload({ trigger, event }) {
6
- return {
7
- trigger,
8
- state: {
9
- trigger,
10
- eventType: event?.type ?? null,
11
- error: event?.properties?.error?.message ?? null,
12
- },
13
- };
14
- }
15
-
16
- export function resumeContext(checkpoint) {
17
- if (!checkpoint) return null;
18
- return [
19
- `Brayer checkpoint ${checkpoint.id} for this order.`,
20
- `Summary: ${checkpoint.summary ?? "(none)"}`,
21
- `Tree: ${checkpoint.treeHash ?? "(none)"}`,
22
- `Resume: ${checkpoint.resumeRecipe ?? "(none)"}`,
23
- `State: ${JSON.stringify(checkpoint.state ?? {})}`,
24
- ].join("\n");
25
- }
package/src/cli.js DELETED
@@ -1,164 +0,0 @@
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
- }