@igorjpimenta/brayer-openclaw 0.0.0-stage → 2026.10.29-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/index.js ADDED
@@ -0,0 +1,119 @@
1
+ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
2
+ import { createStore } from "@igorjpimenta/brayer/src/store.js";
3
+ import {
4
+ attachSession,
5
+ checkpointSession,
6
+ resumeSession,
7
+ } from "@igorjpimenta/brayer/plugins/shared/contract.js";
8
+ import { buildBrayerMeta } from "./meta.js";
9
+ import { checkpointPayload, resumeContext, sessionFromContext } from "./session.js";
10
+ import { registerClaimWebhook } from "./webhook.js";
11
+
12
+ export default definePluginEntry({
13
+ id: "brayer",
14
+ name: "Brayer",
15
+ description:
16
+ "Stamps _meta.brayer on Brayer MCP calls, checkpoints a configured order on turn end, and resumes its latest checkpoint.",
17
+ configSchema: () => ({
18
+ type: "object",
19
+ additionalProperties: true,
20
+ properties: {
21
+ orderId: {
22
+ type: "string",
23
+ description: "Existing Brayer order for this gateway. Required for automatic checkpoint/resume.",
24
+ },
25
+ dbPath: {
26
+ type: "string",
27
+ description: "Brayer SQLite path. Defaults to BRAYER_DB or ~/.brayer/store.sqlite.",
28
+ },
29
+ workspaceDir: {
30
+ type: "string",
31
+ description: "Workspace path used as the checkpoint tree pin.",
32
+ },
33
+ autoCheckpoint: {
34
+ type: "boolean",
35
+ description: "Checkpoint on turn end and session end. Default true when orderId is set.",
36
+ },
37
+ webhookBearer: {
38
+ type: "string",
39
+ description: "Shared secret for POST /api/brayer/claimed. Route stays disarmed until set.",
40
+ },
41
+ },
42
+ }),
43
+ register: (api) => {
44
+ if (typeof api.on !== "function") {
45
+ api.logger.warn("brayer: api.on unavailable; hooks not registered");
46
+ return;
47
+ }
48
+
49
+ api.on("before_tool_call", (event, ctx) => buildBrayerMeta(event, ctx));
50
+ registerClaimWebhook({ api, logger: api.logger });
51
+
52
+ const cfg = api.pluginConfig ?? {};
53
+ const orderId = cfg.orderId ?? process.env.BRAYER_ORDER_ID ?? null;
54
+ if (!orderId || cfg.autoCheckpoint === false) return;
55
+
56
+ let store = null;
57
+ const getStore = () => {
58
+ if (!store) {
59
+ store = createStore({ dbPath: cfg.dbPath ?? process.env.BRAYER_DB ?? undefined });
60
+ }
61
+ return store;
62
+ };
63
+ const attach = (session) => attachSession({ store: getStore(), session, orderId });
64
+
65
+ api.on("agent_end", (event, ctx) => {
66
+ const session = sessionFromContext(event, ctx);
67
+ if (!session) return;
68
+ try {
69
+ const attached = attach(session);
70
+ const trigger = event?.success === false ? "error" : "idle";
71
+ const payload = checkpointPayload({ trigger, event, workspaceDir: ctx?.workspaceDir ?? cfg.workspaceDir });
72
+ checkpointSession({
73
+ store: getStore(),
74
+ session,
75
+ orderId,
76
+ attemptId: attached.attempt.id,
77
+ ...payload,
78
+ });
79
+ } catch (err) {
80
+ api.logger.warn(`brayer: checkpoint failed: ${err?.message ?? err}`);
81
+ }
82
+ });
83
+
84
+ api.on("session_end", (event, ctx) => {
85
+ const session = sessionFromContext(event, ctx);
86
+ if (!session) return;
87
+ try {
88
+ const attached = attach(session);
89
+ const payload = checkpointPayload({ trigger: "stop", event, workspaceDir: ctx?.workspaceDir ?? cfg.workspaceDir });
90
+ checkpointSession({
91
+ store: getStore(),
92
+ session,
93
+ orderId,
94
+ attemptId: attached.attempt.id,
95
+ ...payload,
96
+ });
97
+ } catch (err) {
98
+ api.logger.warn(`brayer: session checkpoint failed: ${err?.message ?? err}`);
99
+ }
100
+ });
101
+
102
+ api.on("before_prompt_build", (event, ctx) => {
103
+ const session = sessionFromContext(event, ctx);
104
+ if (!session) return;
105
+ try {
106
+ const resumed = resumeSession({ store: getStore(), session, orderId });
107
+ const context = resumeContext(resumed.checkpoint);
108
+ if (context) return { prependContext: context };
109
+ } catch (err) {
110
+ api.logger.warn(`brayer: resume failed: ${err?.message ?? err}`);
111
+ }
112
+ });
113
+
114
+ api.on("gateway_stop", () => {
115
+ store?.close();
116
+ store = null;
117
+ });
118
+ },
119
+ });
package/meta.js ADDED
@@ -0,0 +1,23 @@
1
+ export function isBrayerTool(name) {
2
+ return typeof name === "string" && name.includes("brayer");
3
+ }
4
+
5
+ export function buildBrayerMeta(event, ctx) {
6
+ const toolName = event?.toolName ?? ctx?.toolName;
7
+ if (!isBrayerTool(toolName)) return undefined;
8
+
9
+ const agent = ctx?.agentId ?? event?.agentId ?? null;
10
+ const session = ctx?.sessionKey ?? ctx?.sessionId ?? ctx?.runId ?? event?.sessionId ?? event?.runId ?? null;
11
+ if (agent === null && session === null) return undefined;
12
+
13
+ const params = event?.params ?? {};
14
+ return {
15
+ params: {
16
+ ...params,
17
+ _meta: {
18
+ ...(params._meta ?? {}),
19
+ brayer: { harness: "openclaw", agent, session },
20
+ },
21
+ },
22
+ };
23
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "id": "brayer",
3
+ "name": "Brayer",
4
+ "description": "Stamps _meta.brayer (harness/agent/session) onto Brayer MCP tool calls.",
5
+ "enabledByDefault": true,
6
+ "activation": {
7
+ "onStartup": true
8
+ },
9
+ "configSchema": {
10
+ "type": "object",
11
+ "additionalProperties": true,
12
+ "properties": {}
13
+ }
14
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@igorjpimenta/brayer-openclaw",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2026.10.29-beta.1",
4
+ "description": "OpenClaw companion for Brayer: stamps caller identity on Brayer MCP tool calls.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/igorjpimenta/brayer.git",
10
+ "directory": "plugins/openclaw/brayer"
11
+ },
12
+ "publishConfig": {
13
+ "registry": "https://registry.npmjs.org",
14
+ "access": "public"
15
+ },
16
+ "files": [
17
+ "index.js",
18
+ "meta.js",
19
+ "session.js",
20
+ "webhook.js",
21
+ "openclaw.plugin.json"
22
+ ],
23
+ "openclaw": {
24
+ "extensions": [
25
+ "./index.js"
26
+ ],
27
+ "install": {
28
+ "minHostVersion": ">=2026.5.18"
29
+ }
30
+ },
31
+ "peerDependencies": {
32
+ "openclaw": ">=2026.5.18"
33
+ },
34
+ "dependencies": {
35
+ "@igorjpimenta/brayer": "2026.10.29-beta.1"
36
+ }
37
+ }
package/session.js ADDED
@@ -0,0 +1,30 @@
1
+ export function sessionFromContext(event, ctx) {
2
+ const agent = ctx?.agentId ?? event?.agentId ?? null;
3
+ const session = ctx?.sessionKey ?? ctx?.sessionId ?? ctx?.runId ?? event?.sessionId ?? event?.runId ?? null;
4
+ if (!agent || !session) return null;
5
+ return { harness: "openclaw", agent, session };
6
+ }
7
+
8
+ export function checkpointPayload({ trigger, event, workspaceDir }) {
9
+ return {
10
+ trigger,
11
+ state: {
12
+ trigger,
13
+ success: event?.success ?? null,
14
+ messageCount: Array.isArray(event?.messages) ? event.messages.length : null,
15
+ durationMs: event?.durationMs ?? null,
16
+ },
17
+ treeHash: workspaceDir ?? "unknown",
18
+ };
19
+ }
20
+
21
+ export function resumeContext(checkpoint) {
22
+ if (!checkpoint) return null;
23
+ return [
24
+ `Brayer checkpoint ${checkpoint.id} for this order.`,
25
+ `Summary: ${checkpoint.summary ?? "(none)"}`,
26
+ `Tree: ${checkpoint.treeHash ?? "(none)"}`,
27
+ `Resume: ${checkpoint.resumeRecipe ?? "(none)"}`,
28
+ `State: ${JSON.stringify(checkpoint.state ?? {})}`,
29
+ ].join("\n");
30
+ }
package/webhook.js ADDED
@@ -0,0 +1,125 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+
3
+ const MAX_BODY_BYTES = 1024 * 1024;
4
+
5
+ function safeEqual(a, b) {
6
+ const ab = Buffer.from(String(a ?? ""));
7
+ const bb = Buffer.from(String(b ?? ""));
8
+ return ab.length === bb.length && timingSafeEqual(ab, bb);
9
+ }
10
+
11
+ async function readJson(req, res) {
12
+ let size = 0;
13
+ let raw = "";
14
+ for await (const chunk of req) {
15
+ size += chunk.length;
16
+ if (size > MAX_BODY_BYTES) {
17
+ res.statusCode = 413;
18
+ res.end(JSON.stringify({ error: "body too large" }));
19
+ return undefined;
20
+ }
21
+ raw += chunk;
22
+ }
23
+ if (!raw) return {};
24
+ try {
25
+ return JSON.parse(raw);
26
+ } catch {
27
+ res.statusCode = 400;
28
+ res.end(JSON.stringify({ error: "invalid json body" }));
29
+ return undefined;
30
+ }
31
+ }
32
+
33
+ function json(res, status, body) {
34
+ res.statusCode = status;
35
+ res.setHeader("content-type", "application/json");
36
+ res.end(JSON.stringify(body));
37
+ }
38
+
39
+ export function claimError(body) {
40
+ if (!body || typeof body !== "object") return "body must be an object";
41
+ if (body.event === "webhook.test") return null;
42
+ if (body.event !== "order.claimed") return `unsupported event ${JSON.stringify(body.event)}`;
43
+ if (!body.order || typeof body.order.id !== "string" || !body.order.id) return "order.id required";
44
+ if (!body.session || typeof body.session.agent !== "string" || !body.session.agent) return "session.agent required";
45
+ if (typeof body.session.sessionKey !== "string" || !body.session.sessionKey) return "session.sessionKey required";
46
+ return null;
47
+ }
48
+
49
+ export function claimSessionKey(orderId) {
50
+ return `brayer-claim-${orderId}`;
51
+ }
52
+
53
+ export function claimMessage(body) {
54
+ const order = body.order;
55
+ const lines = [`Claimed Brayer order ${order.id}: ${order.title ?? "(untitled)"}`];
56
+ if (order.acceptance) lines.push(`Acceptance: ${order.acceptance}`);
57
+ lines.push(`Attach with BRAYER_ORDER_ID=${order.id} and report through the Brayer tools.`);
58
+ return lines.join("\n");
59
+ }
60
+
61
+ export function registerClaimWebhook({ api, logger }) {
62
+ if (typeof api?.registerHttpRoute !== "function") return false;
63
+ const log = logger ?? api.logger;
64
+ api.registerHttpRoute({
65
+ path: "/api/brayer/claimed",
66
+ auth: "plugin",
67
+ match: "exact",
68
+ handler: async (req, res) => {
69
+ if (req.method !== "POST") {
70
+ res.statusCode = 405;
71
+ res.setHeader("allow", "POST");
72
+ res.end(JSON.stringify({ error: "method not allowed" }));
73
+ return;
74
+ }
75
+ const bearer = api.pluginConfig?.webhookBearer;
76
+ if (typeof bearer !== "string" || bearer === "") {
77
+ json(res, 503, { error: "brayer claim webhook not configured (webhookBearer)" });
78
+ return;
79
+ }
80
+ const auth = req.headers?.authorization ?? "";
81
+ if (!auth.startsWith("Bearer ") || !safeEqual(auth.slice(7), bearer)) {
82
+ json(res, 401, { error: "unauthorized" });
83
+ return;
84
+ }
85
+ const body = await readJson(req, res);
86
+ if (body === undefined) return;
87
+ const shapeErr = claimError(body);
88
+ if (shapeErr) {
89
+ json(res, 400, { error: shapeErr });
90
+ return;
91
+ }
92
+ if (body.event === "webhook.test") {
93
+ json(res, 200, { ok: true, test: true });
94
+ return;
95
+ }
96
+
97
+ const orderId = body.order.id;
98
+ const agent = body.session.agent;
99
+ const message = claimMessage(body);
100
+ const workflow = api.session?.workflow;
101
+ let scheduled = false;
102
+ if (workflow && typeof workflow.scheduleSessionTurn === "function") {
103
+ try {
104
+ await workflow.scheduleSessionTurn({
105
+ sessionKey: claimSessionKey(orderId),
106
+ message,
107
+ agentId: agent,
108
+ delayMs: 0,
109
+ deleteAfterRun: true,
110
+ tag: "brayer-claim",
111
+ name: `brayer ${orderId}`,
112
+ });
113
+ scheduled = true;
114
+ } catch (err) {
115
+ log?.warn?.(`brayer: claim wake failed: ${err?.message ?? err}`);
116
+ }
117
+ }
118
+ if (!scheduled) {
119
+ log?.warn?.(`brayer: claim webhook received for ${orderId}, but no session schedule available`);
120
+ }
121
+ json(res, scheduled ? 200 : 202, { ok: true, scheduled, orderId });
122
+ },
123
+ });
124
+ return true;
125
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.