backeer-opencode 0.1.2 → 0.1.3

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.
@@ -0,0 +1,730 @@
1
+ // src/config.js
2
+ import { readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ // src/utilities.js
7
+ var MAX_TRACKED_ITEMS = 500;
8
+ var limit = (value, length = 1e3) => String(value ?? "").slice(0, length);
9
+ function enabled(value, fallback = true) {
10
+ if (typeof value === "boolean") return value;
11
+ if (typeof value !== "string") return fallback;
12
+ return !["0", "false", "no", "off"].includes(value.trim().toLowerCase());
13
+ }
14
+ function stableHash(value) {
15
+ let hash = 2166136261;
16
+ for (let index = 0; index < value.length; index++) {
17
+ hash ^= value.charCodeAt(index);
18
+ hash = Math.imul(hash, 16777619);
19
+ }
20
+ return (hash >>> 0).toString(16).padStart(8, "0");
21
+ }
22
+ function rememberBounded(map, key, value) {
23
+ map.delete(key);
24
+ map.set(key, value);
25
+ while (map.size > MAX_TRACKED_ITEMS) map.delete(map.keys().next().value);
26
+ }
27
+
28
+ // src/reporter.js
29
+ var LOG_LEVELS = /* @__PURE__ */ new Set(["silent", "error", "info", "debug"]);
30
+ var LOG_RANK = { silent: 0, error: 1, info: 2, debug: 3 };
31
+ var LOG_DEDUPLICATION_MS = 3e4;
32
+ function normalizeLogLevel(value) {
33
+ const level = String(value ?? "info").trim().toLowerCase();
34
+ return LOG_LEVELS.has(level) ? level : "info";
35
+ }
36
+ function createConsoleReporter(levelValue) {
37
+ const level = normalizeLogLevel(levelValue);
38
+ const useColor = Boolean(process.stdout?.isTTY) && !("NO_COLOR" in process.env) && process.env.TERM !== "dumb";
39
+ const recentlyEmitted = /* @__PURE__ */ new Map();
40
+ const decorate = (code, text) => useColor ? `\x1B[${code}m${text}\x1B[0m` : text;
41
+ const symbols = {
42
+ info: decorate("36", "\u25C6"),
43
+ success: decorate("32", "\u25C6"),
44
+ applied: decorate("32", "\u2713"),
45
+ warning: decorate("33", "!"),
46
+ error: decorate("31", "\xD7"),
47
+ debug: decorate("2", "\xB7")
48
+ };
49
+ const brand = decorate("1", "Backeer");
50
+ function emit(requiredLevel, kind, message, detail, deduplicate = false) {
51
+ if (LOG_RANK[level] < LOG_RANK[requiredLevel]) return;
52
+ const key = `${kind}:${message}`;
53
+ const now = Date.now();
54
+ if (deduplicate) {
55
+ const previous = recentlyEmitted.get(key);
56
+ if (previous && now - previous < LOG_DEDUPLICATION_MS) return;
57
+ recentlyEmitted.delete(key);
58
+ recentlyEmitted.set(key, now);
59
+ while (recentlyEmitted.size > 100) {
60
+ recentlyEmitted.delete(recentlyEmitted.keys().next().value);
61
+ }
62
+ }
63
+ const technical = level === "debug" && detail ? decorate("2", ` \xB7 ${limit(detail, 500)}`) : "";
64
+ const line = `${symbols[kind]} ${brand} ${message}${technical}`;
65
+ if (kind === "error" || kind === "warning") console.error(line);
66
+ else console.log(line);
67
+ }
68
+ return {
69
+ info: (message, detail) => emit("info", "info", message, detail),
70
+ success: (message, detail) => emit("info", "success", message, detail),
71
+ applied: (message, detail) => emit("info", "applied", message, detail),
72
+ warning: (message, detail) => emit("error", "warning", message, detail, true),
73
+ error: (message, detail) => emit("error", "error", message, detail, true),
74
+ debug: (message, detail) => emit("debug", "debug", message, detail)
75
+ };
76
+ }
77
+
78
+ // src/config.js
79
+ var DEFAULT_ORIGIN = "https://external-gateway.backeer.com";
80
+ function defaultConfigDirectory() {
81
+ const base = process.env.XDG_CONFIG_HOME?.trim();
82
+ return base ? join(base, "opencode") : join(homedir(), ".config", "opencode");
83
+ }
84
+ function loadToken(tokenFile) {
85
+ const environmentToken = process.env.BACKEER_INGEST_TOKEN?.trim();
86
+ if (environmentToken) return environmentToken;
87
+ try {
88
+ return readFileSync(tokenFile, "utf8").trim();
89
+ } catch {
90
+ return "";
91
+ }
92
+ }
93
+ function loadConfig(options = {}) {
94
+ const origin = new URL(
95
+ options.origin ?? process.env.BACKEER_ORIGIN ?? DEFAULT_ORIGIN
96
+ );
97
+ if (origin.protocol !== "https:") {
98
+ throw new Error("Backeer origin must use HTTPS");
99
+ }
100
+ const tokenFile = options.tokenFile ?? process.env.BACKEER_TOKEN_FILE ?? join(defaultConfigDirectory(), "secrets", "backeer-ingest-token");
101
+ return {
102
+ origin,
103
+ eventsEndpoint: new URL("/v1/events", origin),
104
+ commandStreamEndpoint: new URL("/v1/commands/stream", origin),
105
+ token: loadToken(tokenFile),
106
+ tokenFile,
107
+ permissions: enabled(
108
+ options.permissions ?? process.env.BACKEER_NOTIFY_PERMISSIONS
109
+ ),
110
+ questions: enabled(
111
+ options.questions ?? process.env.BACKEER_NOTIFY_QUESTIONS
112
+ ),
113
+ todos: enabled(options.todos ?? process.env.BACKEER_NOTIFY_TODOS),
114
+ logLevel: normalizeLogLevel(
115
+ options.logLevel ?? process.env.BACKEER_LOG_LEVEL
116
+ )
117
+ };
118
+ }
119
+
120
+ // src/http.js
121
+ var RETRY_DELAYS_MS = [0, 500, 1500];
122
+ var HttpError = class extends Error {
123
+ constructor(message, status, responseBody = "") {
124
+ super(message);
125
+ this.name = "HttpError";
126
+ this.status = status;
127
+ this.responseBody = responseBody;
128
+ }
129
+ };
130
+ function isRetryable(status) {
131
+ return status === 429 || status >= 500;
132
+ }
133
+ function isAbortError(error) {
134
+ return error instanceof Error && error.name === "AbortError";
135
+ }
136
+ function sleep(milliseconds, signal) {
137
+ return new Promise((resolve) => {
138
+ if (signal?.aborted) {
139
+ resolve();
140
+ return;
141
+ }
142
+ const timeout = setTimeout(done, milliseconds);
143
+ function done() {
144
+ clearTimeout(timeout);
145
+ signal?.removeEventListener("abort", done);
146
+ resolve();
147
+ }
148
+ signal?.addEventListener("abort", done, { once: true });
149
+ });
150
+ }
151
+ async function postJsonWithRetry(config, url, body, options = {}) {
152
+ const retryDelays = options.retryDelays ?? RETRY_DELAYS_MS;
153
+ for (let attempt = 0; attempt < retryDelays.length; attempt++) {
154
+ if (retryDelays[attempt] > 0) {
155
+ await sleep(retryDelays[attempt], options.signal);
156
+ }
157
+ if (options.signal?.aborted) throw new DOMException("Aborted", "AbortError");
158
+ const controller = new AbortController();
159
+ const abort = () => controller.abort();
160
+ const timeout = setTimeout(abort, options.timeoutMs ?? 5e3);
161
+ options.signal?.addEventListener("abort", abort, { once: true });
162
+ try {
163
+ const response = await fetch(url, {
164
+ method: "POST",
165
+ headers: {
166
+ Authorization: `Bearer ${config.token}`,
167
+ "Content-Type": "application/json",
168
+ ...options.headers
169
+ },
170
+ body: JSON.stringify(body),
171
+ signal: controller.signal
172
+ });
173
+ const responseBody = limit(await response.text(), 1e3);
174
+ if (response.ok) return { status: response.status, responseBody };
175
+ if (!isRetryable(response.status) || attempt === retryDelays.length - 1) {
176
+ throw new HttpError(
177
+ `HTTP request failed with status ${response.status}`,
178
+ response.status,
179
+ responseBody
180
+ );
181
+ }
182
+ } catch (error) {
183
+ if (options.signal?.aborted) throw new DOMException("Aborted", "AbortError");
184
+ if (error instanceof HttpError) throw error;
185
+ if (attempt === retryDelays.length - 1) throw error;
186
+ } finally {
187
+ clearTimeout(timeout);
188
+ options.signal?.removeEventListener("abort", abort);
189
+ }
190
+ }
191
+ throw new Error("HTTP retry loop ended unexpectedly");
192
+ }
193
+
194
+ // src/event-publishers.js
195
+ var ACTION_PROTOCOL = "opencode-permission/v1";
196
+ function permissionIdentity(request) {
197
+ const requestID = request.id ?? request.requestID;
198
+ const sessionID = request.sessionID;
199
+ if (typeof requestID !== "string" || typeof sessionID !== "string") return;
200
+ return {
201
+ requestID,
202
+ sessionID,
203
+ externalId: `opencode:${sessionID}:${requestID}`
204
+ };
205
+ }
206
+ async function publishPermission(config, reporter, request, directory, identity) {
207
+ const permissionType = request.permission ?? request.action ?? "unknown";
208
+ const resources = Array.isArray(request.patterns) ? request.patterns.join(", ") : Array.isArray(request.resources) ? request.resources.join(", ") : "";
209
+ const payload = [
210
+ { key: "Permission", value: limit(permissionType) },
211
+ { key: "Session", value: limit(identity.sessionID) },
212
+ { key: "Request ID", value: limit(identity.requestID) },
213
+ { key: "Patterns", value: limit(resources) },
214
+ { key: "Working directory", value: limit(directory) },
215
+ { key: "Action protocol", value: ACTION_PROTOCOL },
216
+ { key: "Available decisions", value: "once, always, reject" }
217
+ ].filter((item) => item.value.length > 0);
218
+ const result = await postJsonWithRetry(config, config.eventsEndpoint, {
219
+ type: "application",
220
+ severity: "warning",
221
+ title: `OpenCode permission required: ${limit(permissionType, 200)}`,
222
+ body: resources ? `OpenCode is waiting for approval to access: ${limit(resources, 500)}` : `OpenCode is waiting for approval for: ${limit(permissionType, 500)}`,
223
+ payload,
224
+ externalId: identity.externalId,
225
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
226
+ notify: true,
227
+ direction: "in"
228
+ });
229
+ reporter.success("Permission request sent", `HTTP ${result.status}`);
230
+ }
231
+ function questionIdentity(request) {
232
+ const requestID = request.id ?? request.requestID;
233
+ const sessionID = request.sessionID;
234
+ if (typeof requestID !== "string" || typeof sessionID !== "string") return;
235
+ return {
236
+ requestID,
237
+ sessionID,
238
+ externalId: `opencode-question:${sessionID}:${requestID}`
239
+ };
240
+ }
241
+ function formatQuestionOptions(options) {
242
+ if (!Array.isArray(options)) return "";
243
+ return options.map((option) => {
244
+ const label = limit(option?.label, 200);
245
+ const description = limit(option?.description, 500);
246
+ if (!label) return "";
247
+ return description ? `${label} \u2014 ${description}` : label;
248
+ }).filter(Boolean).join(" | ");
249
+ }
250
+ async function resolveSessionTitle(client, directory, sessionID, reporter) {
251
+ if (typeof client?.session?.get !== "function") return "";
252
+ try {
253
+ const result = await client.session.get({
254
+ path: { id: sessionID },
255
+ query: { directory },
256
+ throwOnError: true
257
+ });
258
+ return limit((result?.data ?? result)?.title);
259
+ } catch (error) {
260
+ reporter.debug("Session title unavailable", error);
261
+ return "";
262
+ }
263
+ }
264
+ async function publishQuestion(config, reporter, request, identity, client, directory) {
265
+ const questions = Array.isArray(request.questions) ? request.questions : [];
266
+ if (questions.length === 0) return;
267
+ const sessionTitle = await resolveSessionTitle(
268
+ client,
269
+ directory,
270
+ identity.sessionID,
271
+ reporter
272
+ );
273
+ const payload = [
274
+ { key: "OpenCode session", value: sessionTitle },
275
+ ...questions.flatMap((question, index) => {
276
+ const suffix = questions.length > 1 ? ` ${index + 1}` : "";
277
+ return [
278
+ { key: `Question title${suffix}`, value: limit(question?.header) },
279
+ { key: `Question${suffix}`, value: limit(question?.question) },
280
+ {
281
+ key: `Options${suffix}`,
282
+ value: limit(formatQuestionOptions(question?.options))
283
+ }
284
+ ];
285
+ })
286
+ ].filter((item) => item.value.length > 0);
287
+ const firstQuestion = questions[0];
288
+ const body = questions.map((question) => {
289
+ const header = limit(question?.header, 200);
290
+ const text = limit(question?.question, 500);
291
+ const options = limit(formatQuestionOptions(question?.options), 500);
292
+ return [header, text, options ? `Options: ${options}` : ""].filter(Boolean).join("\n");
293
+ }).join("\n\n");
294
+ const result = await postJsonWithRetry(config, config.eventsEndpoint, {
295
+ type: "application",
296
+ severity: "info",
297
+ title: `OpenCode question: ${limit(firstQuestion?.header, 200) || "Question"}`,
298
+ body: limit(body, 2e3),
299
+ payload,
300
+ externalId: identity.externalId,
301
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
302
+ notify: true,
303
+ direction: "in"
304
+ });
305
+ reporter.success("Question sent", `HTTP ${result.status}`);
306
+ }
307
+ async function publishTodoCompletion(config, reporter, request, eventID, client, directory) {
308
+ const todos = request.todos;
309
+ const sessionTitle = await resolveSessionTitle(
310
+ client,
311
+ directory,
312
+ request.sessionID,
313
+ reporter
314
+ );
315
+ const correlation = typeof eventID === "string" && eventID.length > 0 ? limit(eventID, 200) : stableHash(JSON.stringify(todos));
316
+ const externalId = `opencode-todo:${request.sessionID}:${correlation}`;
317
+ const visibleTodos = todos.slice(0, 20);
318
+ const payload = [
319
+ { key: "OpenCode session", value: sessionTitle },
320
+ { key: "Completed tasks", value: String(todos.length) },
321
+ ...visibleTodos.flatMap((todo, index) => [
322
+ { key: `Task ${index + 1}`, value: limit(todo?.content) },
323
+ { key: `Priority ${index + 1}`, value: limit(todo?.priority, 100) }
324
+ ]),
325
+ ...todos.length > visibleTodos.length ? [{ key: "Additional tasks", value: String(todos.length - visibleTodos.length) }] : []
326
+ ].filter((item) => item.value.length > 0);
327
+ const summary = todos.slice(0, 5).map((todo) => limit(todo?.content, 200)).filter(Boolean).join(" \u2022 ");
328
+ const location = sessionTitle ? ` in ${sessionTitle}` : "";
329
+ const body = [
330
+ `All ${todos.length} OpenCode tasks completed${location}.`,
331
+ summary
332
+ ].filter(Boolean).join("\n");
333
+ const result = await postJsonWithRetry(config, config.eventsEndpoint, {
334
+ type: "application",
335
+ severity: "info",
336
+ title: "OpenCode todo list completed",
337
+ body: limit(body, 2e3),
338
+ payload,
339
+ externalId,
340
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
341
+ notify: true,
342
+ direction: "in"
343
+ });
344
+ reporter.success("Todo completion sent", `HTTP ${result.status}`);
345
+ }
346
+
347
+ // src/sse.js
348
+ function parseSseFrame(frame) {
349
+ const data = [];
350
+ let event = "message";
351
+ let id;
352
+ for (const line of frame.split(/\r?\n/)) {
353
+ if (!line || line.startsWith(":")) continue;
354
+ const separator = line.indexOf(":");
355
+ const field = separator === -1 ? line : line.slice(0, separator);
356
+ let value = separator === -1 ? "" : line.slice(separator + 1);
357
+ if (value.startsWith(" ")) value = value.slice(1);
358
+ if (field === "event") event = value;
359
+ if (field === "id") id = value;
360
+ if (field === "data") data.push(value);
361
+ }
362
+ if (data.length === 0) return;
363
+ return { event, id, data: data.join("\n") };
364
+ }
365
+ function nextSseFrame(buffer) {
366
+ const lfIndex = buffer.indexOf("\n\n");
367
+ const crlfIndex = buffer.indexOf("\r\n\r\n");
368
+ if (lfIndex === -1 && crlfIndex === -1) return;
369
+ if (crlfIndex !== -1 && (lfIndex === -1 || crlfIndex < lfIndex)) {
370
+ return {
371
+ frame: buffer.slice(0, crlfIndex),
372
+ rest: buffer.slice(crlfIndex + 4)
373
+ };
374
+ }
375
+ return { frame: buffer.slice(0, lfIndex), rest: buffer.slice(lfIndex + 2) };
376
+ }
377
+ async function consumeSse(response, state, onCommand, signal, reporter) {
378
+ if (!response.body) throw new Error("Backeer command stream has no body");
379
+ const reader = response.body.getReader();
380
+ const decoder = new TextDecoder();
381
+ let buffer = "";
382
+ try {
383
+ while (!signal.aborted) {
384
+ const item = await reader.read();
385
+ if (item.done) break;
386
+ buffer += decoder.decode(item.value, { stream: true });
387
+ for (; ; ) {
388
+ const next = nextSseFrame(buffer);
389
+ if (!next) break;
390
+ buffer = next.rest;
391
+ const message = parseSseFrame(next.frame);
392
+ if (!message) continue;
393
+ if (message.id) state.lastEventID = message.id;
394
+ if (message.event !== "message" && message.event !== "command") continue;
395
+ try {
396
+ await onCommand(JSON.parse(message.data));
397
+ } catch (error) {
398
+ if (error instanceof SyntaxError) {
399
+ reporter.error("Invalid command received", "SSE data is not valid JSON");
400
+ continue;
401
+ }
402
+ throw error;
403
+ }
404
+ }
405
+ }
406
+ } finally {
407
+ await reader.cancel().catch(() => {
408
+ });
409
+ }
410
+ }
411
+ async function runCommandStream(config, reporter, { signal, hasPending, onCommand }) {
412
+ const state = { lastEventID: "" };
413
+ let reconnectDelay = 1e3;
414
+ let lastLoggedError = "";
415
+ while (!signal.aborted && hasPending()) {
416
+ try {
417
+ const headers = {
418
+ Accept: "text/event-stream",
419
+ Authorization: `Bearer ${config.token}`
420
+ };
421
+ if (state.lastEventID) headers["Last-Event-ID"] = state.lastEventID;
422
+ const response = await fetch(config.commandStreamEndpoint, {
423
+ headers,
424
+ signal
425
+ });
426
+ if (!response.ok) {
427
+ const responseBody = limit(await response.text(), 500);
428
+ throw new HttpError(
429
+ `Backeer command stream failed with status ${response.status}`,
430
+ response.status,
431
+ responseBody
432
+ );
433
+ }
434
+ if (!response.headers.get("content-type")?.includes("text/event-stream")) {
435
+ throw new Error("Backeer command stream returned an invalid content type");
436
+ }
437
+ reconnectDelay = 1e3;
438
+ lastLoggedError = "";
439
+ await consumeSse(response, state, onCommand, signal, reporter);
440
+ } catch (error) {
441
+ if (signal.aborted || isAbortError(error)) return;
442
+ const message = error instanceof HttpError ? `${error.message}: ${error.responseBody}` : limit(error, 500);
443
+ if (message !== lastLoggedError) {
444
+ const authenticationFailure = error instanceof HttpError && [401, 403].includes(error.status);
445
+ reporter.error(
446
+ authenticationFailure ? "Authentication failed \u2014 run: npx backeer-opencode@latest configure" : "Connection interrupted \u2014 retrying",
447
+ message
448
+ );
449
+ lastLoggedError = message;
450
+ }
451
+ if (error instanceof HttpError && [401, 403, 404].includes(error.status)) {
452
+ reconnectDelay = 6e4;
453
+ }
454
+ }
455
+ if (!signal.aborted && hasPending()) {
456
+ await sleep(reconnectDelay, signal);
457
+ reconnectDelay = Math.min(reconnectDelay * 2, 6e4);
458
+ }
459
+ }
460
+ }
461
+
462
+ // src/permission-controller.js
463
+ var ALLOWED_DECISIONS = /* @__PURE__ */ new Set(["once", "always", "reject"]);
464
+ var DECISION_LABELS = {
465
+ once: "Allow once",
466
+ always: "Always allow",
467
+ reject: "Reject"
468
+ };
469
+ async function replyToOpenCode(client, pending, decision) {
470
+ const result = await client.postSessionIdPermissionsPermissionId({
471
+ path: { id: pending.sessionID, permissionID: pending.requestID },
472
+ query: { directory: pending.directory },
473
+ body: { response: decision },
474
+ throwOnError: true
475
+ });
476
+ if (result?.data === false || result === false) {
477
+ throw new HttpError("OpenCode did not apply the permission reply", 409);
478
+ }
479
+ }
480
+ async function acknowledgeCommand(config, commandID, acknowledgement) {
481
+ const url = new URL(
482
+ `/v1/commands/${encodeURIComponent(commandID)}/ack`,
483
+ config.origin
484
+ );
485
+ await postJsonWithRetry(config, url, acknowledgement);
486
+ }
487
+ function createPermissionController({
488
+ config,
489
+ reporter,
490
+ client,
491
+ directory
492
+ }) {
493
+ const pendingByExternalID = /* @__PURE__ */ new Map();
494
+ const externalIDByRequestID = /* @__PURE__ */ new Map();
495
+ const processingCommands = /* @__PURE__ */ new Set();
496
+ const completedCommands = /* @__PURE__ */ new Map();
497
+ const publishedPermissions = /* @__PURE__ */ new Map();
498
+ let commandStream;
499
+ let disposed = false;
500
+ function removePendingByRequestID(requestID) {
501
+ const externalId = externalIDByRequestID.get(requestID);
502
+ if (!externalId) return;
503
+ externalIDByRequestID.delete(requestID);
504
+ pendingByExternalID.delete(externalId);
505
+ }
506
+ function stopCommandStreamIfIdle() {
507
+ if (pendingByExternalID.size === 0) commandStream?.controller.abort();
508
+ }
509
+ async function handleCommand(command) {
510
+ if (!command || typeof command !== "object") return;
511
+ if (command.type !== "opencode_permission_reply") return;
512
+ if (typeof command.id !== "string" || command.id.length > 200) return;
513
+ const previousAcknowledgement = completedCommands.get(command.id);
514
+ if (previousAcknowledgement) {
515
+ await acknowledgeCommand(config, command.id, previousAcknowledgement).catch((error) => reporter.warning("Decision receipt retry failed", error));
516
+ return;
517
+ }
518
+ if (processingCommands.has(command.id)) return;
519
+ if (typeof command.externalId !== "string") return;
520
+ const pending = pendingByExternalID.get(command.externalId);
521
+ if (!pending) return;
522
+ processingCommands.add(command.id);
523
+ let acknowledgement;
524
+ try {
525
+ if (!ALLOWED_DECISIONS.has(command.decision)) {
526
+ acknowledgement = { status: "rejected", errorCode: "invalid_decision" };
527
+ } else {
528
+ const expiresAt = Date.parse(command.expiresAt);
529
+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
530
+ acknowledgement = { status: "expired", decision: command.decision };
531
+ } else if (command.decision === "always" && command.confirmed !== true) {
532
+ acknowledgement = {
533
+ status: "rejected",
534
+ decision: command.decision,
535
+ errorCode: "confirmation_required"
536
+ };
537
+ } else {
538
+ await replyToOpenCode(client, pending, command.decision);
539
+ acknowledgement = { status: "applied", decision: command.decision };
540
+ removePendingByRequestID(pending.requestID);
541
+ }
542
+ }
543
+ } catch (error) {
544
+ const stale = error instanceof HttpError && error.status === 404;
545
+ acknowledgement = {
546
+ status: stale ? "stale" : "failed",
547
+ decision: ALLOWED_DECISIONS.has(command.decision) ? command.decision : void 0,
548
+ errorCode: stale ? "permission_not_found" : "opencode_reply_failed"
549
+ };
550
+ if (stale) removePendingByRequestID(pending.requestID);
551
+ reporter.error("Decision could not be applied", error);
552
+ } finally {
553
+ processingCommands.delete(command.id);
554
+ }
555
+ acknowledgement = {
556
+ ...acknowledgement,
557
+ type: "opencode_permission_reply_ack",
558
+ externalId: command.externalId,
559
+ processedAt: (/* @__PURE__ */ new Date()).toISOString()
560
+ };
561
+ rememberBounded(completedCommands, command.id, acknowledgement);
562
+ if (acknowledgement.status === "applied") {
563
+ reporter.applied(
564
+ `Decision applied: ${DECISION_LABELS[acknowledgement.decision]}`
565
+ );
566
+ } else if (acknowledgement.status === "expired") {
567
+ reporter.warning("Decision expired before it could be applied");
568
+ } else if (acknowledgement.status === "stale") {
569
+ reporter.warning("Permission was already answered locally");
570
+ } else if (acknowledgement.status === "rejected") {
571
+ reporter.warning("Decision was rejected by validation");
572
+ }
573
+ await acknowledgeCommand(config, command.id, acknowledgement).catch((error) => {
574
+ reporter.warning("Decision receipt could not be sent", error);
575
+ });
576
+ stopCommandStreamIfIdle();
577
+ }
578
+ function ensureCommandStream() {
579
+ if (disposed || commandStream || pendingByExternalID.size === 0) return;
580
+ const controller = new AbortController();
581
+ const current = {
582
+ controller,
583
+ task: runCommandStream(config, reporter, {
584
+ signal: controller.signal,
585
+ hasPending: () => pendingByExternalID.size > 0,
586
+ onCommand: handleCommand
587
+ })
588
+ };
589
+ commandStream = current;
590
+ void current.task.finally(() => {
591
+ if (commandStream === current) commandStream = void 0;
592
+ if (!disposed && pendingByExternalID.size > 0) ensureCommandStream();
593
+ });
594
+ }
595
+ return {
596
+ register(identity) {
597
+ pendingByExternalID.set(identity.externalId, { ...identity, directory });
598
+ externalIDByRequestID.set(identity.requestID, identity.externalId);
599
+ ensureCommandStream();
600
+ if (publishedPermissions.has(identity.externalId)) return false;
601
+ rememberBounded(publishedPermissions, identity.externalId, true);
602
+ return true;
603
+ },
604
+ resolveLocally(requestID) {
605
+ removePendingByRequestID(requestID);
606
+ stopCommandStreamIfIdle();
607
+ },
608
+ async dispose() {
609
+ disposed = true;
610
+ commandStream?.controller.abort();
611
+ await commandStream?.task.catch(() => {
612
+ });
613
+ pendingByExternalID.clear();
614
+ externalIDByRequestID.clear();
615
+ processingCommands.clear();
616
+ completedCommands.clear();
617
+ publishedPermissions.clear();
618
+ }
619
+ };
620
+ }
621
+
622
+ // src/plugin.js
623
+ async function BackeerPlugin({ client, directory }, options = {}) {
624
+ const bootstrapReporter = createConsoleReporter(
625
+ options.logLevel ?? process.env.BACKEER_LOG_LEVEL
626
+ );
627
+ let config;
628
+ try {
629
+ config = loadConfig(options);
630
+ } catch (error) {
631
+ bootstrapReporter.error("Plugin disabled \u2014 invalid configuration", error);
632
+ return {};
633
+ }
634
+ const reporter = createConsoleReporter(config.logLevel);
635
+ if (!config.token) {
636
+ reporter.error(
637
+ "Plugin disabled \u2014 run: npx backeer-opencode@latest configure",
638
+ `Token not found at ${config.tokenFile}`
639
+ );
640
+ return {};
641
+ }
642
+ const permissionController = createPermissionController({
643
+ config,
644
+ reporter,
645
+ client,
646
+ directory
647
+ });
648
+ const todoCompletionBySessionID = /* @__PURE__ */ new Map();
649
+ const publishedQuestions = /* @__PURE__ */ new Map();
650
+ async function handlePermissionAsked(event) {
651
+ const identity = permissionIdentity(event.properties);
652
+ if (!identity) {
653
+ reporter.error("Permission event is missing correlation IDs");
654
+ return;
655
+ }
656
+ if (!permissionController.register(identity)) return;
657
+ void publishPermission(
658
+ config,
659
+ reporter,
660
+ event.properties,
661
+ directory,
662
+ identity
663
+ ).catch((error) => reporter.error("Permission request could not be sent", error));
664
+ }
665
+ async function handleTodoUpdated(event) {
666
+ const { sessionID, todos } = event.properties;
667
+ if (typeof sessionID !== "string" || !Array.isArray(todos)) {
668
+ reporter.error("Todo event is missing a valid session or list");
669
+ return;
670
+ }
671
+ const isComplete = todos.length > 0 && todos.every((todo) => todo?.status === "completed");
672
+ const wasComplete = todoCompletionBySessionID.get(sessionID) === true;
673
+ rememberBounded(todoCompletionBySessionID, sessionID, isComplete);
674
+ if (!isComplete || wasComplete) return;
675
+ void publishTodoCompletion(
676
+ config,
677
+ reporter,
678
+ event.properties,
679
+ event.id,
680
+ client,
681
+ directory
682
+ ).catch((error) => reporter.error("Todo completion could not be sent", error));
683
+ }
684
+ async function handleQuestionAsked(event) {
685
+ const identity = questionIdentity(event.properties);
686
+ if (!identity) {
687
+ reporter.error("Question event is missing correlation IDs");
688
+ return;
689
+ }
690
+ if (publishedQuestions.has(identity.externalId)) return;
691
+ rememberBounded(publishedQuestions, identity.externalId, true);
692
+ void publishQuestion(
693
+ config,
694
+ reporter,
695
+ event.properties,
696
+ identity,
697
+ client,
698
+ directory
699
+ ).catch((error) => reporter.error("Question could not be sent", error));
700
+ }
701
+ return {
702
+ event: async ({ event }) => {
703
+ if (config.permissions && event.type === "permission.asked") {
704
+ await handlePermissionAsked(event);
705
+ return;
706
+ }
707
+ if (config.permissions && event.type === "permission.replied") {
708
+ permissionController.resolveLocally(
709
+ event.properties.requestID ?? event.properties.id
710
+ );
711
+ return;
712
+ }
713
+ if (config.todos && event.type === "todo.updated") {
714
+ await handleTodoUpdated(event);
715
+ return;
716
+ }
717
+ if (config.questions && (event.type === "question.asked" || event.type === "question.v2.asked")) {
718
+ await handleQuestionAsked(event);
719
+ }
720
+ },
721
+ dispose: async () => {
722
+ await permissionController.dispose();
723
+ todoCompletionBySessionID.clear();
724
+ publishedQuestions.clear();
725
+ }
726
+ };
727
+ }
728
+ export {
729
+ BackeerPlugin as default
730
+ };