@igorjpimenta/brayer 2026.10.29-beta.1 → 2026.11.7-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` |
@@ -193,7 +193,10 @@ An adapter attaches an existing order; it never creates work.
193
193
 
194
194
  **OpenClaw** — `@igorjpimenta/brayer-openclaw` stamps `_meta.brayer`, checkpoints
195
195
  on turn end, resumes from the latest checkpoint, and receives claim webhooks at
196
- `POST /api/brayer/claimed`.
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.
197
200
 
198
201
  ```json
199
202
  {
@@ -229,8 +232,8 @@ Brayer MCP tool calls. It needs the Brayer MCP server configured and
229
232
  Automatic checkpoint/resume is not part of this release; the agent uses the
230
233
  Brayer MCP tools directly.
231
234
 
232
- **Wake bridge** — OpenCode has no plugin HTTP route, so `@igorjpimenta/brayer-wake`
233
- receives the claim webhook and prompts the claiming session through the
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
234
237
  OpenCode SDK.
235
238
 
236
239
  ## Docker
@@ -245,9 +248,8 @@ HTTP MCP is exposed on 38293 and the event stream on 38294.
245
248
  ## Release
246
249
 
247
250
  Versions are CalVer (`YYYY.MM.DD-beta.N`). Tags are bare for core and prefixed
248
- for adapters: `brayer-openclaw-<calver>`, `brayer-opencode-<calver>`,
249
- `brayer-wake-<calver>`. Prereleases publish to `beta`; stable tags publish to
250
- `latest`.
251
+ for adapters: `brayer-openclaw-<calver>` and `brayer-opencode-<calver>`.
252
+ Prereleases publish to `beta`; stable tags publish to `latest`.
251
253
 
252
254
  ## Development
253
255
 
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.29-beta.1",
3
+ "version": "2026.11.7-beta.1",
4
4
  "description": "Vendor-neutral command layer for agent work",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,3 +1,10 @@
1
+ // Identity goes out on every channel a consumer might read: `requestMeta` is
2
+ // the declared before_tool_call result field current OpenClaw hoists to
3
+ // JSON-RPC request `_meta` (openclaw/openclaw#193006); brayer_agent/
4
+ // brayer_session flat args and `params._meta.brayer` are mirrors for engines
5
+ // that predate the hoist (server picks protocol `_meta` first, args when it is
6
+ // lost). Unconditional overwrite on every channel: a model-supplied pair must
7
+ // never survive.
1
8
  export function isBrayerTool(name) {
2
9
  return typeof name === "string" && name.includes("brayer");
3
10
  }
@@ -11,13 +18,18 @@ export function buildBrayerMeta(event, ctx) {
11
18
  if (agent === null && session === null) return undefined;
12
19
 
13
20
  const params = event?.params ?? {};
21
+ const brayer = { harness: "openclaw", agent, session };
14
22
  return {
15
23
  params: {
16
24
  ...params,
25
+ ...(agent !== null && session !== null
26
+ ? { brayer_agent: agent, brayer_session: session }
27
+ : {}),
17
28
  _meta: {
18
29
  ...(params._meta ?? {}),
19
- brayer: { harness: "openclaw", agent, session },
30
+ brayer,
20
31
  },
21
32
  },
33
+ requestMeta: { brayer },
22
34
  };
23
35
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@igorjpimenta/brayer-openclaw",
3
- "version": "2026.10.29-beta.1",
3
+ "version": "2026.11.7-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.29-beta.1"
35
+ "@igorjpimenta/brayer": "2026.11.7-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);
@@ -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,7 +1,7 @@
1
1
  {
2
2
  "name": "@igorjpimenta/brayer-opencode",
3
- "version": "2026.10.28-beta.3",
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": {
@@ -19,7 +19,15 @@
19
19
  "files": [
20
20
  "index.js",
21
21
  "hooks.js",
22
- "identity.js"
22
+ "identity.js",
23
+ "wake.js",
24
+ "bin/"
23
25
  ],
24
- "main": "index.js"
26
+ "main": "index.js",
27
+ "bin": {
28
+ "brayer-wake": "bin/brayer-wake.js"
29
+ },
30
+ "dependencies": {
31
+ "@opencode-ai/sdk": "1.19.3"
32
+ }
25
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,42 @@
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, logger }) {
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, logger });
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
+ logger,
28
+ });
29
+ return;
30
+ }
31
+ throw new Error("brayer: serve --mcp supports stdio or http");
32
+ }
33
+
34
+ if (rest.includes("--ws")) {
35
+ const store = createStore({ dbPath: env.BRAYER_DB || undefined });
36
+ const port = flagValue(rest, "--port");
37
+ startEventServer({ store, port: port ? Number(port) : undefined });
38
+ return;
39
+ }
40
+
41
+ throw new Error("brayer: serve requires --mcp stdio or --ws");
42
+ }
@@ -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, via: "meta" }
41
+ : aAgent && aSession
42
+ ? { agent: aAgent, session: aSession, via: "args" }
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, via: pair.via };
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";
@@ -27,7 +27,8 @@ export function createMcpServer({ store, base, logger } = {}) {
27
27
  async (args, extra) => {
28
28
  try {
29
29
  const identity = resolveIdentity({ meta: extra?._meta, args, base: declared });
30
- logger?.info?.(`brayer: ${def.name} from ${identity.harness}:${identity.agent}:${identity.session}`);
30
+ const metaKeys = extra?._meta ? Object.keys(extra._meta).sort().join(",") : "-";
31
+ logger?.info?.(`brayer: ${def.name} from ${identity.harness}:${identity.agent}:${identity.session} via=${identity.via} metaKeys=${metaKeys}`);
31
32
  const result = await handle(def.name, args, identity);
32
33
  return { content: [{ type: "text", text: JSON.stringify(result) }] };
33
34
  } catch (err) {
@@ -63,6 +64,27 @@ export async function startMcpHttpServer({
63
64
  logger,
64
65
  } = {}) {
65
66
  if (!bearer) throw new Error("brayer: BRAYER_MCP_BEARER is required for HTTP");
67
+
68
+ // Shared HTTP mint: one process serves every harness. The first request on
69
+ // a session declares the harness via the X-Brayer-Harness header — set by
70
+ // the harness's own client config, never by the model — and that session
71
+ // keeps the declaration for its lifetime. Later session requests replay to
72
+ // the same server; the header is only consulted at minting.
73
+ const sessions = new Map();
74
+
75
+ async function readBody(req) {
76
+ const chunks = [];
77
+ for await (const chunk of req) chunks.push(chunk);
78
+ const body = Buffer.concat(chunks);
79
+ if (!body.length) return undefined;
80
+ return JSON.parse(body.toString("utf8"));
81
+ }
82
+
83
+ async function dispatch(req, res, entry) {
84
+ const body = await readBody(req);
85
+ await entry.transport.handleRequest(req, res, body);
86
+ }
87
+
66
88
  const server = http.createServer(async (req, res) => {
67
89
  if (req.url === "/health") {
68
90
  res.writeHead(200, { "content-type": "application/json" });
@@ -87,22 +109,52 @@ export async function startMcpHttpServer({
87
109
  return;
88
110
  }
89
111
 
90
- const mcp = createMcpServer({ store, base, logger });
91
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
112
+ const sid = req.headers["mcp-session-id"];
113
+ if (typeof sid === "string" && sessions.has(sid)) {
114
+ try {
115
+ await dispatch(req, res, sessions.get(sid));
116
+ } catch (err) {
117
+ logger?.warn?.(`brayer: HTTP MCP failed: ${err?.message ?? err}`);
118
+ if (!res.headersSent) {
119
+ res.writeHead(500, { "content-type": "application/json" });
120
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null }));
121
+ }
122
+ }
123
+ return;
124
+ }
125
+
126
+ // New session: read the declared harness, refuse unusable names, then
127
+ // mint the session-scoped server and register it by response header.
128
+ const header = req.headers["x-brayer-harness"];
129
+ const headerValue = Array.isArray(header) ? header[0] : header;
130
+ let minted;
131
+ try {
132
+ minted = assertDeclaration({ harness: headerValue });
133
+ } catch {
134
+ res.writeHead(400, { "content-type": "application/json" });
135
+ res.end(JSON.stringify({ error: "missing or reserved X-Brayer-Harness" }));
136
+ return;
137
+ }
138
+ const mcp = createMcpServer({ store, base: minted, logger });
139
+ const transport = new StreamableHTTPServerTransport({
140
+ sessionIdGenerator: () => randomUUID(),
141
+ onsessioninitialized: (id) => sessions.set(id, { server: mcp, transport }),
142
+ });
143
+ transport.onclose = () => {
144
+ for (const [id, entry] of sessions) {
145
+ if (entry.transport === transport) sessions.delete(id);
146
+ }
147
+ };
92
148
  try {
93
149
  await mcp.connect(transport);
94
- await transport.handleRequest(req, res);
150
+ await dispatch(req, res, { transport });
95
151
  } catch (err) {
152
+ mcp.close();
96
153
  logger?.warn?.(`brayer: HTTP MCP failed: ${err?.message ?? err}`);
97
154
  if (!res.headersSent) {
98
155
  res.writeHead(500, { "content-type": "application/json" });
99
156
  res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null }));
100
157
  }
101
- } finally {
102
- res.on("close", () => {
103
- transport.close();
104
- mcp.close();
105
- });
106
158
  }
107
159
  });
108
160
  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
  } = {}) {
@@ -71,12 +116,30 @@ export function createAttemptApi({ db, insertEvent, orderApi }) {
71
116
  if (attempt.status !== "running") { db.exec("ROLLBACK"); return { attempt, order: orderApi.get(attempt.workOrderId), reason: "not_running" }; }
72
117
 
73
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
+ }
74
137
  db.prepare(`
75
138
  UPDATE attempts
76
139
  SET status=?, ended_at=?, tokens_in=?, tokens_out=?, cache_read=?, cost_usd=?,
77
140
  tool_calls=?, error=?, checkpoint_id=?
78
141
  WHERE id=? AND status='running'
79
- `).run(status, t, tokensIn, tokensOut, cacheRead, costUsd, toolCalls, error, nextCheckpointId, attemptId);
142
+ `).run(status, t, nextUsage.tokensIn, nextUsage.tokensOut, nextUsage.cacheRead, nextUsage.costUsd, nextUsage.toolCalls, error, nextCheckpointId, attemptId);
80
143
 
81
144
  const order = orderApi.get(attempt.workOrderId);
82
145
  const nextStatus = status === "finished" ? "review" : "ready";
@@ -92,6 +155,7 @@ export function createAttemptApi({ db, insertEvent, orderApi }) {
92
155
  actor: attempt.agent, note: summary ?? error ?? status, sessionRef: attempt.sessionRef, at: t,
93
156
  });
94
157
  db.exec("COMMIT");
158
+ clearExpiry?.(attempt.workOrderId);
95
159
  return { attempt: attemptApi.get(attemptId), order: orderApi.get(attempt.workOrderId), reason: null };
96
160
  } catch (err) {
97
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
  }
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
 
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
- }