@igorjpimenta/brayer 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/.migrations/0000_initial.sql +133 -0
- package/.migrations/0001_awesome_ben_parker.sql +8 -0
- package/.migrations/meta/0000_snapshot.json +931 -0
- package/.migrations/meta/0001_snapshot.json +983 -0
- package/.migrations/meta/_journal.json +20 -0
- package/LICENSE +21 -0
- package/README.md +261 -2
- package/bin/brayer.js +7 -0
- package/package.json +43 -4
- package/plugins/openclaw/brayer/index.js +119 -0
- package/plugins/openclaw/brayer/meta.js +23 -0
- package/plugins/openclaw/brayer/openclaw.plugin.json +14 -0
- package/plugins/openclaw/brayer/package.json +37 -0
- package/plugins/openclaw/brayer/session.js +30 -0
- package/plugins/openclaw/brayer/webhook.js +125 -0
- package/plugins/opencode/brayer/hooks.js +17 -0
- package/plugins/opencode/brayer/identity.js +11 -0
- package/plugins/opencode/brayer/index.js +5 -0
- package/plugins/opencode/brayer/package.json +25 -0
- package/plugins/shared/contract.js +193 -0
- package/plugins/wake/brayer/bin/brayer-wake.js +7 -0
- package/plugins/wake/brayer/index.js +125 -0
- package/plugins/wake/brayer/package.json +29 -0
- package/src/claim-webhook.js +66 -0
- package/src/cli.js +164 -0
- package/src/config.js +63 -0
- package/src/db.js +24 -0
- package/src/events-ws.js +121 -0
- package/src/evidence.js +42 -0
- package/src/identity.js +32 -0
- package/src/ids.js +17 -0
- package/src/mcp.js +114 -0
- package/src/schema.js +168 -0
- package/src/store/attempts.js +104 -0
- package/src/store/checkpoints.js +76 -0
- package/src/store/claims.js +139 -0
- package/src/store/events.js +24 -0
- package/src/store/evidence.js +67 -0
- package/src/store/orders.js +70 -0
- package/src/store/resume.js +38 -0
- package/src/store/rows.js +118 -0
- package/src/store/util.js +3 -0
- package/src/store/verdicts.js +64 -0
- package/src/store/webhooks.js +56 -0
- package/src/store.js +53 -0
- package/src/tools/attempts.js +75 -0
- package/src/tools/handoff.js +120 -0
- package/src/tools/index.js +28 -0
- package/src/tools/orders.js +146 -0
- package/src/tools/shared.js +7 -0
- package/src/tools/verdicts.js +46 -0
- package/src/version.js +5 -0
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export function isBrayerTool(name) {
|
|
2
|
+
return typeof name === "string" && name.includes("brayer");
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function stampBrayerIdentity(input, output, { agent = null } = {}) {
|
|
6
|
+
if (!isBrayerTool(input?.tool)) return false;
|
|
7
|
+
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;
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
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.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/igorjpimenta/brayer.git",
|
|
10
|
+
"directory": "plugins/opencode/brayer"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"registry": "https://registry.npmjs.org",
|
|
14
|
+
"access": "public"
|
|
15
|
+
},
|
|
16
|
+
"exports": {
|
|
17
|
+
".": "./index.js"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"index.js",
|
|
21
|
+
"hooks.js",
|
|
22
|
+
"identity.js"
|
|
23
|
+
],
|
|
24
|
+
"main": "index.js"
|
|
25
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { storeFile } from "../../src/evidence.js";
|
|
2
|
+
import { identityKey } from "../../src/identity.js";
|
|
3
|
+
|
|
4
|
+
export const CHECKPOINT_TRIGGERS = Object.freeze({
|
|
5
|
+
idle: "auto",
|
|
6
|
+
compaction: "pre_compact",
|
|
7
|
+
error: "error",
|
|
8
|
+
stop: "stop",
|
|
9
|
+
manual: "manual",
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
function assertSession(session) {
|
|
13
|
+
if (!session?.harness || !session?.agent || !session?.session) {
|
|
14
|
+
throw new Error("brayer: adapter session requires harness, agent and session");
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
harness: session.harness,
|
|
18
|
+
agent: session.agent,
|
|
19
|
+
session: session.session,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function sessionIdentity(session) {
|
|
24
|
+
return identityKey(assertSession(session));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function claimOrResume({ store, session, orderId }) {
|
|
28
|
+
const identity = sessionIdentity(session);
|
|
29
|
+
let order = store.order.get(orderId);
|
|
30
|
+
if (!order) throw new Error(`brayer: order not found: ${orderId}`);
|
|
31
|
+
|
|
32
|
+
let resumed = false;
|
|
33
|
+
if (order.status === "rejected" || order.status === "blocked") {
|
|
34
|
+
order = store.resume.resume({
|
|
35
|
+
workOrderId: orderId,
|
|
36
|
+
actor: identity,
|
|
37
|
+
reason: "adapter resume",
|
|
38
|
+
}).order;
|
|
39
|
+
resumed = true;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (order.status === "ready") {
|
|
43
|
+
const claimed = store.claim.claimById({
|
|
44
|
+
id: orderId,
|
|
45
|
+
agentId: identity,
|
|
46
|
+
sessionRef: session.session,
|
|
47
|
+
});
|
|
48
|
+
if (!claimed.claimed) {
|
|
49
|
+
throw new Error(`brayer: could not claim ${orderId}: ${claimed.reason}`);
|
|
50
|
+
}
|
|
51
|
+
order = claimed.claimed;
|
|
52
|
+
resumed = true;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (order.status === "claimed") {
|
|
56
|
+
if (order.assignee !== identity) {
|
|
57
|
+
throw new Error(`brayer: ${orderId} is assigned to ${order.assignee}`);
|
|
58
|
+
}
|
|
59
|
+
const started = store.attempt.start({
|
|
60
|
+
workOrderId: orderId,
|
|
61
|
+
harness: session.harness,
|
|
62
|
+
agent: identity,
|
|
63
|
+
sessionRef: session.session,
|
|
64
|
+
});
|
|
65
|
+
if (!started.attempt) {
|
|
66
|
+
throw new Error(`brayer: could not start attempt: ${started.reason}`);
|
|
67
|
+
}
|
|
68
|
+
return { order: started.order, attempt: started.attempt, resumed };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (order.status === "running") {
|
|
72
|
+
const attempt = store.attempt
|
|
73
|
+
.list({ workOrderId: orderId, status: "running" })
|
|
74
|
+
.find((row) => row.agent === identity);
|
|
75
|
+
if (!attempt) throw new Error(`brayer: ${orderId} has no running attempt for ${identity}`);
|
|
76
|
+
return { order, attempt, resumed: true };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
throw new Error(`brayer: order ${orderId} is ${order.status}, not attachable`);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function attachSession({ store, session, orderId }) {
|
|
83
|
+
if (!store) throw new Error("brayer: store is required");
|
|
84
|
+
if (!orderId) throw new Error("brayer: orderId is required");
|
|
85
|
+
return claimOrResume({ store, session, orderId });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function checkpointSession({
|
|
89
|
+
store,
|
|
90
|
+
session,
|
|
91
|
+
orderId,
|
|
92
|
+
attemptId,
|
|
93
|
+
trigger = "idle",
|
|
94
|
+
state,
|
|
95
|
+
treeHash,
|
|
96
|
+
summary = null,
|
|
97
|
+
goal = null,
|
|
98
|
+
confidence = null,
|
|
99
|
+
resumeRecipe = null,
|
|
100
|
+
}) {
|
|
101
|
+
const kind = CHECKPOINT_TRIGGERS[trigger];
|
|
102
|
+
if (!kind) throw new Error(`brayer: unknown checkpoint trigger: ${trigger}`);
|
|
103
|
+
const checkpoint = store.checkpoint.write({
|
|
104
|
+
workOrderId: orderId,
|
|
105
|
+
attemptId,
|
|
106
|
+
kind,
|
|
107
|
+
goal,
|
|
108
|
+
state,
|
|
109
|
+
summary,
|
|
110
|
+
confidence,
|
|
111
|
+
resumeRecipe,
|
|
112
|
+
treeHash,
|
|
113
|
+
actor: sessionIdentity(session),
|
|
114
|
+
});
|
|
115
|
+
return checkpoint;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function attachEvidence({
|
|
119
|
+
store,
|
|
120
|
+
session,
|
|
121
|
+
orderId,
|
|
122
|
+
attemptId,
|
|
123
|
+
kind,
|
|
124
|
+
path = null,
|
|
125
|
+
uri = null,
|
|
126
|
+
sha256 = null,
|
|
127
|
+
summary = null,
|
|
128
|
+
command = null,
|
|
129
|
+
exitCode = null,
|
|
130
|
+
status = null,
|
|
131
|
+
verifier = null,
|
|
132
|
+
}) {
|
|
133
|
+
let resolvedUri = uri;
|
|
134
|
+
let resolvedSha = sha256;
|
|
135
|
+
if (path) {
|
|
136
|
+
const stored = storeFile({ root: store.config.blobsPath, filePath: path });
|
|
137
|
+
resolvedUri = stored.uri;
|
|
138
|
+
resolvedSha = stored.sha256;
|
|
139
|
+
}
|
|
140
|
+
if (!resolvedUri || !resolvedSha) {
|
|
141
|
+
throw new Error("brayer: evidence requires path or uri + sha256");
|
|
142
|
+
}
|
|
143
|
+
return store.evidence.attach({
|
|
144
|
+
workOrderId: orderId,
|
|
145
|
+
attemptId,
|
|
146
|
+
kind,
|
|
147
|
+
uri: resolvedUri,
|
|
148
|
+
sha256: resolvedSha,
|
|
149
|
+
summary,
|
|
150
|
+
command,
|
|
151
|
+
exitCode,
|
|
152
|
+
status,
|
|
153
|
+
verifier,
|
|
154
|
+
actor: sessionIdentity(session),
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function finishSession({
|
|
159
|
+
store,
|
|
160
|
+
session,
|
|
161
|
+
attemptId,
|
|
162
|
+
status = "finished",
|
|
163
|
+
summary = null,
|
|
164
|
+
tokensIn = 0,
|
|
165
|
+
tokensOut = 0,
|
|
166
|
+
cacheRead = 0,
|
|
167
|
+
costUsd = 0,
|
|
168
|
+
toolCalls = 0,
|
|
169
|
+
error = null,
|
|
170
|
+
checkpointId = null,
|
|
171
|
+
}) {
|
|
172
|
+
sessionIdentity(session);
|
|
173
|
+
return store.attempt.finish({
|
|
174
|
+
attemptId,
|
|
175
|
+
status,
|
|
176
|
+
summary,
|
|
177
|
+
tokensIn,
|
|
178
|
+
tokensOut,
|
|
179
|
+
cacheRead,
|
|
180
|
+
costUsd,
|
|
181
|
+
toolCalls,
|
|
182
|
+
error,
|
|
183
|
+
checkpointId,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function resumeSession({ store, session, orderId }) {
|
|
188
|
+
const attached = attachSession({ store, session, orderId });
|
|
189
|
+
return {
|
|
190
|
+
...attached,
|
|
191
|
+
checkpoint: store.checkpoint.latest({ workOrderId: orderId }),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import { timingSafeEqual } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
const MAX_BODY_BYTES = 1024 * 1024;
|
|
5
|
+
|
|
6
|
+
function safeEqual(a, b) {
|
|
7
|
+
const ab = Buffer.from(String(a ?? ""));
|
|
8
|
+
const bb = Buffer.from(String(b ?? ""));
|
|
9
|
+
return ab.length === bb.length && timingSafeEqual(ab, bb);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
async function readJson(req, res) {
|
|
13
|
+
let size = 0;
|
|
14
|
+
let raw = "";
|
|
15
|
+
for await (const chunk of req) {
|
|
16
|
+
size += chunk.length;
|
|
17
|
+
if (size > MAX_BODY_BYTES) {
|
|
18
|
+
res.statusCode = 413;
|
|
19
|
+
res.end(JSON.stringify({ error: "body too large" }));
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
raw += chunk;
|
|
23
|
+
}
|
|
24
|
+
if (!raw) return {};
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(raw);
|
|
27
|
+
} catch {
|
|
28
|
+
res.statusCode = 400;
|
|
29
|
+
res.end(JSON.stringify({ error: "invalid json body" }));
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function json(res, status, body) {
|
|
35
|
+
res.statusCode = status;
|
|
36
|
+
res.setHeader("content-type", "application/json");
|
|
37
|
+
res.end(JSON.stringify(body));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function claimError(body) {
|
|
41
|
+
if (!body || typeof body !== "object") return "body must be an object";
|
|
42
|
+
if (body.event === "webhook.test") return null;
|
|
43
|
+
if (body.event !== "order.claimed") return `unsupported event ${JSON.stringify(body.event)}`;
|
|
44
|
+
if (!body.order || typeof body.order.id !== "string" || !body.order.id) return "order.id required";
|
|
45
|
+
if (!body.session || typeof body.session.sessionKey !== "string" || !body.session.sessionKey) {
|
|
46
|
+
return "session.sessionKey required";
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function claimMessage(body) {
|
|
52
|
+
const order = body.order;
|
|
53
|
+
const lines = [`Claimed Brayer order ${order.id}: ${order.title ?? "(untitled)"}`];
|
|
54
|
+
if (order.acceptance) lines.push(`Acceptance: ${order.acceptance}`);
|
|
55
|
+
lines.push(`Attach with BRAYER_ORDER_ID=${order.id} and report through the Brayer tools.`);
|
|
56
|
+
return lines.join("\n");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function createWakeHandler({ prompt, bearer, logger } = {}) {
|
|
60
|
+
return async (req, res) => {
|
|
61
|
+
if (req.method !== "POST") {
|
|
62
|
+
res.statusCode = 405;
|
|
63
|
+
res.setHeader("allow", "POST");
|
|
64
|
+
res.end(JSON.stringify({ error: "method not allowed" }));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (!bearer) {
|
|
68
|
+
json(res, 503, { error: "brayer wake not configured (BRAYER_WAKE_BEARER)" });
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const auth = req.headers?.authorization ?? "";
|
|
72
|
+
if (!auth.startsWith("Bearer ") || !safeEqual(auth.slice(7), bearer)) {
|
|
73
|
+
json(res, 401, { error: "unauthorized" });
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const body = await readJson(req, res);
|
|
77
|
+
if (body === undefined) return;
|
|
78
|
+
const shapeErr = claimError(body);
|
|
79
|
+
if (shapeErr) {
|
|
80
|
+
json(res, 400, { error: shapeErr });
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (body.event === "webhook.test") {
|
|
84
|
+
json(res, 200, { ok: true, test: true });
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
await prompt(body.session.sessionKey, claimMessage(body));
|
|
89
|
+
json(res, 200, { ok: true, sessionKey: body.session.sessionKey });
|
|
90
|
+
} catch (err) {
|
|
91
|
+
logger?.warn?.(`brayer wake: ${err?.message ?? err}`);
|
|
92
|
+
json(res, 502, { error: "wake failed" });
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function createWakeServer(options = {}) {
|
|
98
|
+
return http.createServer(createWakeHandler(options));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function startWakeServer({
|
|
102
|
+
port = 38295,
|
|
103
|
+
bearer = process.env.BRAYER_WAKE_BEARER,
|
|
104
|
+
baseUrl = process.env.BRAYER_OPENCODE_URL ?? "http://127.0.0.1:4096",
|
|
105
|
+
logger = console,
|
|
106
|
+
} = {}) {
|
|
107
|
+
if (!bearer) throw new Error("brayer wake: BRAYER_WAKE_BEARER is required");
|
|
108
|
+
const { createOpencodeClient } = await import("@opencode-ai/sdk");
|
|
109
|
+
const client = createOpencodeClient({ baseUrl });
|
|
110
|
+
const server = createWakeServer({
|
|
111
|
+
bearer,
|
|
112
|
+
logger,
|
|
113
|
+
prompt: (sessionID, text) =>
|
|
114
|
+
client.session.prompt({
|
|
115
|
+
path: { id: sessionID },
|
|
116
|
+
body: { parts: [{ type: "text", text }] },
|
|
117
|
+
}),
|
|
118
|
+
});
|
|
119
|
+
await new Promise((resolve, reject) => {
|
|
120
|
+
server.once("error", reject);
|
|
121
|
+
server.listen(port, "127.0.0.1", resolve);
|
|
122
|
+
});
|
|
123
|
+
logger?.info?.(`brayer wake: listening on http://127.0.0.1:${port}/api/brayer/claimed`);
|
|
124
|
+
return server;
|
|
125
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@igorjpimenta/brayer-wake",
|
|
3
|
+
"version": "2026.10.28-beta.1",
|
|
4
|
+
"description": "OpenCode wake bridge for Brayer claim webhooks.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/igorjpimenta/brayer.git",
|
|
10
|
+
"directory": "plugins/wake/brayer"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"registry": "https://registry.npmjs.org",
|
|
14
|
+
"access": "public"
|
|
15
|
+
},
|
|
16
|
+
"bin": {
|
|
17
|
+
"brayer-wake": "bin/brayer-wake.js"
|
|
18
|
+
},
|
|
19
|
+
"exports": {
|
|
20
|
+
".": "./index.js"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"bin/",
|
|
24
|
+
"index.js"
|
|
25
|
+
],
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@opencode-ai/sdk": "1.19.3"
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
const DEFAULT_TIMEOUT_MS = 3000;
|
|
2
|
+
|
|
3
|
+
export function webhookConfig(cfg, harness = null, dbEntry = null) {
|
|
4
|
+
if (dbEntry?.url) {
|
|
5
|
+
return {
|
|
6
|
+
url: dbEntry.url,
|
|
7
|
+
bearer: dbEntry.bearer || null,
|
|
8
|
+
timeoutMs: dbEntry.timeoutMs ?? cfg?.claimWebhookTimeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
const entry = harness ? cfg?.claimWebhooks?.[harness] : null;
|
|
12
|
+
if (entry?.url) {
|
|
13
|
+
return {
|
|
14
|
+
url: entry.url,
|
|
15
|
+
bearer: entry.bearer || null,
|
|
16
|
+
timeoutMs: entry.timeoutMs ?? cfg?.claimWebhookTimeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
if (!cfg?.claimWebhookUrl) return null;
|
|
20
|
+
return {
|
|
21
|
+
url: cfg.claimWebhookUrl,
|
|
22
|
+
bearer: cfg.claimWebhookBearer || null,
|
|
23
|
+
timeoutMs: cfg.claimWebhookTimeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function sessionFromAgentId(agentId, sessionRef = null) {
|
|
28
|
+
const [harness, agent, ...rest] = String(agentId).split(":");
|
|
29
|
+
return {
|
|
30
|
+
harness: harness || null,
|
|
31
|
+
agent: agent || null,
|
|
32
|
+
sessionKey: sessionRef ?? (rest.length ? rest.join(":") : null),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function claimPayload({ order, agentId, sessionRef, at = Date.now() }) {
|
|
37
|
+
return {
|
|
38
|
+
event: "order.claimed",
|
|
39
|
+
at,
|
|
40
|
+
order,
|
|
41
|
+
session: sessionFromAgentId(agentId, sessionRef),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function notifyClaim(cfg, payload, { logger = null, dbEntry = null } = {}) {
|
|
46
|
+
const hook = webhookConfig(cfg, payload?.session?.harness ?? null, dbEntry);
|
|
47
|
+
if (!hook) return { ok: false, reason: "disabled" };
|
|
48
|
+
try {
|
|
49
|
+
const headers = { "content-type": "application/json" };
|
|
50
|
+
if (hook.bearer) headers.authorization = `Bearer ${hook.bearer}`;
|
|
51
|
+
const res = await fetch(hook.url, {
|
|
52
|
+
method: "POST",
|
|
53
|
+
headers,
|
|
54
|
+
body: JSON.stringify(payload),
|
|
55
|
+
signal: AbortSignal.timeout(hook.timeoutMs),
|
|
56
|
+
});
|
|
57
|
+
if (!res.ok) {
|
|
58
|
+
logger?.warn?.(`brayer: claim webhook ${hook.url} -> ${res.status}`);
|
|
59
|
+
return { ok: false, reason: `http_${res.status}` };
|
|
60
|
+
}
|
|
61
|
+
return { ok: true, status: res.status };
|
|
62
|
+
} catch (err) {
|
|
63
|
+
logger?.warn?.(`brayer: claim webhook ${hook.url} failed: ${err?.message ?? err}`);
|
|
64
|
+
return { ok: false, reason: "error" };
|
|
65
|
+
}
|
|
66
|
+
}
|