backeer-codex 0.12.0 → 0.13.0
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/.codex-plugin/plugin.json +1 -1
- package/README.md +18 -0
- package/dist/opencode.mjs +2 -2
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/scripts/check-package.mjs +4 -1
- package/src/approval-bridge.mjs +24 -9
- package/src/approval-history.mjs +40 -0
- package/src/command-frames.mjs +50 -0
- package/src/companion.mjs +33 -16
- package/src/gateway.mjs +13 -41
- package/src/install-lock.mjs +43 -0
- package/src/installer.mjs +8 -1
- package/src/version.mjs +1 -1
package/README.md
CHANGED
|
@@ -13,6 +13,24 @@ It provides:
|
|
|
13
13
|
- Safe fallback to the normal Codex permission prompt when Backeer is unavailable or not configured.
|
|
14
14
|
- Saved OpenCode connections and an independent exact-session binding for each chat, automatically tracking its subagent tree over live SSE.
|
|
15
15
|
|
|
16
|
+
## Stability update (0.13.0)
|
|
17
|
+
|
|
18
|
+
The terminal companion releases completed tool payloads on item/turn/thread
|
|
19
|
+
completion. Small exact late-response markers live in a protected temporary ledger
|
|
20
|
+
with a 256-entry RAM cache and are removed on normal shutdown. They do not contain
|
|
21
|
+
tool output, command text or permission parameters.
|
|
22
|
+
|
|
23
|
+
The proxy pauses input/output producers when a receiver is slow, resumes without
|
|
24
|
+
dropping messages, and enforces an explicit 64 MiB per-message budget. Mobile
|
|
25
|
+
control SSE uses a separate 1 MiB frame budget, a ten-second partial-frame deadline
|
|
26
|
+
and a 45-second idle deadline. These limits do not truncate live session output.
|
|
27
|
+
Concurrent Backeer installations serialize through a per-user process lock, so an
|
|
28
|
+
older failed installation cannot roll back a newer successful one.
|
|
29
|
+
|
|
30
|
+
The bundled OpenCode implementation is 0.16.0, including lazy command receipts and
|
|
31
|
+
shared-project hub cleanup. Existing connections, exact request IDs, tree tracking
|
|
32
|
+
and all 25 managed tools retain their protocol behavior.
|
|
33
|
+
|
|
16
34
|
## OpenCode connection per chat
|
|
17
35
|
|
|
18
36
|
### Guided first setup (0.4.0)
|
package/dist/opencode.mjs
CHANGED
|
@@ -12951,7 +12951,7 @@ var require_dist = __commonJS({
|
|
|
12951
12951
|
});
|
|
12952
12952
|
|
|
12953
12953
|
// src/version.mjs
|
|
12954
|
-
var VERSION = "0.
|
|
12954
|
+
var VERSION = "0.13.0";
|
|
12955
12955
|
|
|
12956
12956
|
// src/opencode.mjs
|
|
12957
12957
|
import path2 from "node:path";
|
|
@@ -12963,7 +12963,7 @@ import { dirname, isAbsolute as isAbsolute2 } from "node:path";
|
|
|
12963
12963
|
import { randomUUID } from "node:crypto";
|
|
12964
12964
|
|
|
12965
12965
|
// ../opencode-plugin/src/updates.js
|
|
12966
|
-
var PLUGIN_VERSION = "0.
|
|
12966
|
+
var PLUGIN_VERSION = "0.16.0";
|
|
12967
12967
|
var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
12968
12968
|
|
|
12969
12969
|
// ../opencode-plugin/src/live-compatibility.js
|
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
|
3
3
|
"name": "backeer-codex",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.13.0",
|
|
5
5
|
"description": "Backeer approvals, lifecycle notifications and chat-scoped OpenCode connections.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Backeer"
|
|
@@ -6,7 +6,10 @@ import path from "node:path";
|
|
|
6
6
|
const npm = process.env.npm_execpath;
|
|
7
7
|
if (!npm) throw new Error("Run this check with npm run check:package.");
|
|
8
8
|
const { stdout } = await promisify(execFile)(process.execPath, [npm, "pack", "--dry-run", "--json", "--ignore-scripts"], { maxBuffer: 2 * 1024 * 1024 });
|
|
9
|
-
const
|
|
9
|
+
const packed = JSON.parse(stdout);
|
|
10
|
+
const archives = Array.isArray(packed) ? packed : Object.values(packed);
|
|
11
|
+
if (archives.length !== 1 || !Array.isArray(archives[0]?.files) || !archives[0].files.length) throw new Error("Unexpected npm package manifest.");
|
|
12
|
+
const [archive] = archives;
|
|
10
13
|
const rules = [
|
|
11
14
|
["private key", /-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/],
|
|
12
15
|
["npm credential", /\bnpm_[A-Za-z0-9]{30,}/],
|
package/src/approval-bridge.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ApprovalHistory } from "./approval-history.mjs";
|
|
1
2
|
import crypto from "node:crypto";
|
|
2
3
|
import { acknowledgeCommand, publishEvent } from "./gateway.mjs";
|
|
3
4
|
import { compactText, digest, workspaceLabel } from "./privacy.mjs";
|
|
@@ -20,24 +21,34 @@ export class ApprovalBridge {
|
|
|
20
21
|
this.byExternalId = new Map();
|
|
21
22
|
this.receipts = new Map();
|
|
22
23
|
this.items = new Map();
|
|
24
|
+
this.history = new ApprovalHistory();
|
|
25
|
+
this.disposed = false;
|
|
23
26
|
}
|
|
24
27
|
|
|
25
28
|
async receipt(command, status, errorCode) {
|
|
29
|
+
this.history.set(`command:${command.id}`, { status, errorCode });
|
|
26
30
|
remember(this.receipts, command.id, { status, errorCode });
|
|
31
|
+
while (this.receipts.size > 256) this.receipts.delete(this.receipts.keys().next().value);
|
|
27
32
|
try { await this.acknowledge(this.config, command, status, errorCode); }
|
|
28
33
|
catch { this.warn("Backeer decision receipt could not be delivered."); }
|
|
29
34
|
}
|
|
30
35
|
|
|
31
36
|
observeServer(message) {
|
|
37
|
+
if (this.disposed) return;
|
|
32
38
|
const p = message.params || {};
|
|
33
|
-
if (message.method === "item/started" && p.item) {
|
|
34
|
-
remember(this.items, JSON.stringify([p.threadId, p.item.id]), p.item);
|
|
39
|
+
if (message.method === "item/started" && p.item && typeof p.threadId === "string" && p.item.id) {
|
|
40
|
+
remember(this.items, JSON.stringify([p.threadId, p.item.id]), { turnId: p.turnId, changes: p.item.changes });
|
|
35
41
|
}
|
|
42
|
+
if (message.method === "item/completed" && p.item) this.items.delete(JSON.stringify([p.threadId, p.item.id]));
|
|
36
43
|
if (message.method === "serverRequest/resolved") {
|
|
37
44
|
const entry = this.requests.get(p.requestId);
|
|
38
45
|
if (entry && entry.params.threadId === p.threadId) this.clear(entry, true);
|
|
39
46
|
}
|
|
40
47
|
if (["turn/completed", "thread/closed", "thread/archived"].includes(message.method)) {
|
|
48
|
+
for (const [key, item] of this.items) {
|
|
49
|
+
const [thread] = JSON.parse(key);
|
|
50
|
+
if (thread === p.threadId && (message.method !== "turn/completed" || !item.turnId || item.turnId === p.turn?.id)) this.items.delete(key);
|
|
51
|
+
}
|
|
41
52
|
for (const entry of this.requests.values()) {
|
|
42
53
|
if (entry.params.threadId === p.threadId &&
|
|
43
54
|
(message.method !== "turn/completed" || entry.params.turnId === p.turn?.id)) this.clear(entry, false);
|
|
@@ -88,18 +99,18 @@ export class ApprovalBridge {
|
|
|
88
99
|
forwardLocal(message) {
|
|
89
100
|
if (message.method || message.id == null) return true;
|
|
90
101
|
const entry = this.requests.get(message.id);
|
|
91
|
-
if (!entry) return
|
|
102
|
+
if (!entry) return !this.history.get(`request:${JSON.stringify(message.id)}`);
|
|
92
103
|
if (entry.state !== "pending") return false;
|
|
93
104
|
entry.state = "local";
|
|
94
105
|
return true;
|
|
95
106
|
}
|
|
96
107
|
|
|
97
108
|
async handleCommand(command) {
|
|
98
|
-
if (command?.type !== "codex_permission_reply" || typeof command.id !== "string" ||
|
|
109
|
+
if (this.disposed || command?.type !== "codex_permission_reply" || typeof command.id !== "string" ||
|
|
99
110
|
!command.id) return;
|
|
100
|
-
const entry = this.byExternalId.get(command.externalId);
|
|
111
|
+
const entry = this.byExternalId.get(command.externalId) || this.history.get(`external:${command.externalId}`);
|
|
101
112
|
if (!entry) return; // Another process/session owns this command.
|
|
102
|
-
const previous = this.receipts.get(command.id);
|
|
113
|
+
const previous = this.receipts.get(command.id) || this.history.get(`command:${command.id}`);
|
|
103
114
|
if (previous) return this.receipt(command, previous.status, previous.errorCode);
|
|
104
115
|
if (entry.command?.id === command.id) return; // Await server confirmation.
|
|
105
116
|
if (entry.state !== "pending") return this.receipt(command, "stale", "already_resolved");
|
|
@@ -122,15 +133,19 @@ export class ApprovalBridge {
|
|
|
122
133
|
if (entry.state === "cleared") return;
|
|
123
134
|
entry.state = "cleared";
|
|
124
135
|
if (entry.command) void this.receipt(entry.command, confirmed ? "applied" : "stale",
|
|
125
|
-
confirmed ? undefined : "request_cleared");
|
|
126
|
-
|
|
136
|
+
confirmed ? undefined : "request_cleared").catch(() => this.warn("Backeer decision receipt could not be recorded."));
|
|
137
|
+
this.history.set(`request:${JSON.stringify(entry.id)}`, { state: "cleared" });
|
|
138
|
+
this.history.set(`external:${entry.externalId}`, { state: "cleared" });
|
|
139
|
+
this.requests.delete(entry.id); this.byExternalId.delete(entry.externalId);
|
|
140
|
+
delete entry.params; delete entry.method; delete entry.command;
|
|
127
141
|
}
|
|
128
142
|
|
|
129
143
|
dispose() {
|
|
130
|
-
|
|
144
|
+
this.disposed = true;
|
|
131
145
|
this.items.clear();
|
|
132
146
|
this.requests.clear();
|
|
133
147
|
this.byExternalId.clear();
|
|
134
148
|
this.receipts.clear();
|
|
149
|
+
this.history.dispose();
|
|
135
150
|
}
|
|
136
151
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { mkdtempSync, writeFileSync, readFileSync, lstatSync, rmSync, constants, openSync, closeSync, fstatSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
|
|
6
|
+
// Exact, process-lifetime tombstones live in a protected temporary ledger. RAM
|
|
7
|
+
// holds only a small cache; no expiry can make a late native response valid.
|
|
8
|
+
export class ApprovalHistory {
|
|
9
|
+
constructor(limit = 256) { this.limit = limit; this.cache = new Map(); this.directory = undefined; this.closed = false; }
|
|
10
|
+
file(key) { return join(this.directory, createHash("sha256").update(key).digest("hex")); }
|
|
11
|
+
remember(key, value) {
|
|
12
|
+
this.cache.delete(key); this.cache.set(key, value);
|
|
13
|
+
while (this.cache.size > this.limit) this.cache.delete(this.cache.keys().next().value);
|
|
14
|
+
}
|
|
15
|
+
set(key, value) {
|
|
16
|
+
if (this.closed) return;
|
|
17
|
+
this.directory ||= mkdtempSync(join(tmpdir(), "backeer-approval-history-"));
|
|
18
|
+
writeFileSync(this.file(key), JSON.stringify(value), { mode: 0o600 });
|
|
19
|
+
this.remember(key, value);
|
|
20
|
+
}
|
|
21
|
+
get(key) {
|
|
22
|
+
if (this.closed || !this.directory) return undefined;
|
|
23
|
+
if (this.cache.has(key)) { const value = this.cache.get(key); this.remember(key, value); return value; }
|
|
24
|
+
let fd;
|
|
25
|
+
try {
|
|
26
|
+
const root = lstatSync(this.directory);
|
|
27
|
+
if (!root.isDirectory() || root.isSymbolicLink()) throw new Error("Invalid approval history directory");
|
|
28
|
+
fd = openSync(this.file(key), constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | (constants.O_NONBLOCK || 0));
|
|
29
|
+
const stat = fstatSync(fd);
|
|
30
|
+
if (!stat.isFile() || stat.size > 4096 || (process.platform !== "win32" && ((stat.mode & 0o077) || stat.uid !== process.getuid()))) throw new Error("Invalid approval history record");
|
|
31
|
+
const value = JSON.parse(readFileSync(fd, "utf8")); this.remember(key, value); return value;
|
|
32
|
+
} catch (error) { if (error.code === "ENOENT") return undefined; throw error; }
|
|
33
|
+
finally { if (fd !== undefined) closeSync(fd); }
|
|
34
|
+
}
|
|
35
|
+
dispose() {
|
|
36
|
+
this.closed = true; this.cache.clear();
|
|
37
|
+
if (this.directory) rmSync(this.directory, { recursive: true, force: true });
|
|
38
|
+
this.directory = undefined;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Mobile command frames are control messages, separate from live output history.
|
|
2
|
+
export async function* commandFrames(response, { signal, maxFrameBytes = 1024 * 1024, idleMs = 45000, frameMs = 10000 } = {}) {
|
|
3
|
+
if (!response.body) throw new Error("Command stream has no body")
|
|
4
|
+
for (const value of [maxFrameBytes, idleMs, frameMs]) if (!Number.isSafeInteger(value) || value < 1) throw new Error("Invalid command stream budget")
|
|
5
|
+
if (signal?.aborted) {
|
|
6
|
+
await response.body.cancel().catch(() => {})
|
|
7
|
+
throw Object.assign(new Error("Command stream cancelled"), { name: "AbortError", code: "command_stream_cancelled" })
|
|
8
|
+
}
|
|
9
|
+
const reader = response.body.getReader(), decoder = new TextDecoder()
|
|
10
|
+
let buffer = "", began = 0
|
|
11
|
+
const failure = (message, code, name = "Error") => Object.assign(new Error(message), { name, code })
|
|
12
|
+
const next = timeoutMs => new Promise((resolve, reject) => {
|
|
13
|
+
let timer, settled = false
|
|
14
|
+
const finish = (error, value) => {
|
|
15
|
+
if (settled) return
|
|
16
|
+
settled = true; clearTimeout(timer); signal?.removeEventListener("abort", abort)
|
|
17
|
+
if (error) reject(error); else resolve(value)
|
|
18
|
+
}
|
|
19
|
+
const abort = () => finish(failure("Command stream cancelled", "command_stream_cancelled", "AbortError"))
|
|
20
|
+
timer = setTimeout(() => finish(failure("Command stream frame or heartbeat timed out", "command_stream_timeout", "TimeoutError")), Math.max(1, timeoutMs))
|
|
21
|
+
signal?.addEventListener("abort", abort, { once: true })
|
|
22
|
+
if (signal?.aborted) abort()
|
|
23
|
+
else reader.read().then(value => finish(null, value), error => finish(error))
|
|
24
|
+
})
|
|
25
|
+
try {
|
|
26
|
+
while (!signal?.aborted) {
|
|
27
|
+
const remaining = began ? Math.min(idleMs, frameMs - (Date.now() - began)) : idleMs
|
|
28
|
+
const { done, value } = await next(remaining)
|
|
29
|
+
if (done) {
|
|
30
|
+
if (buffer.trim()) throw failure("Command stream ended inside a frame", "command_stream_incomplete")
|
|
31
|
+
return
|
|
32
|
+
}
|
|
33
|
+
if (!began) began = Date.now()
|
|
34
|
+
buffer += decoder.decode(value, { stream: true })
|
|
35
|
+
let match
|
|
36
|
+
while ((match = /\r\n\r\n|\n\n|\r\r/.exec(buffer))) {
|
|
37
|
+
const frame = buffer.slice(0, match.index)
|
|
38
|
+
if (Buffer.byteLength(frame) > maxFrameBytes) throw failure("Command frame exceeds its configured budget", "command_frame_limit")
|
|
39
|
+
buffer = buffer.slice(match.index + match[0].length)
|
|
40
|
+
began = buffer.length ? Date.now() : 0
|
|
41
|
+
yield frame
|
|
42
|
+
}
|
|
43
|
+
if (Buffer.byteLength(buffer) > maxFrameBytes) throw failure("Command frame exceeds its configured budget", "command_frame_limit")
|
|
44
|
+
if (began && Date.now() - began >= frameMs) throw failure("Command stream frame timed out", "command_stream_timeout", "TimeoutError")
|
|
45
|
+
}
|
|
46
|
+
} finally {
|
|
47
|
+
await reader.cancel().catch(() => {})
|
|
48
|
+
reader.releaseLock()
|
|
49
|
+
}
|
|
50
|
+
}
|
package/src/companion.mjs
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import crypto from "node:crypto";
|
|
2
2
|
import http from "node:http";
|
|
3
3
|
import { spawn } from "node:child_process";
|
|
4
|
-
import readline from "node:readline";
|
|
5
4
|
import { setTimeout as delay } from "node:timers/promises";
|
|
6
5
|
import { WebSocketServer, WebSocket } from "ws";
|
|
7
6
|
import { ApprovalBridge } from "./approval-bridge.mjs";
|
|
@@ -9,7 +8,7 @@ import { loadConfig } from "./config.mjs";
|
|
|
9
8
|
import { streamPermissionCommands } from "./gateway.mjs";
|
|
10
9
|
|
|
11
10
|
const REQUIRED_NOTIFICATIONS = new Set([
|
|
12
|
-
"serverRequest/resolved", "turn/completed", "thread/closed", "thread/archived", "item/started",
|
|
11
|
+
"serverRequest/resolved", "turn/completed", "thread/closed", "thread/archived", "item/started", "item/completed",
|
|
13
12
|
]);
|
|
14
13
|
|
|
15
14
|
// Authenticated loopback proxy: native Codex TUI <-> JSON-RPC <-> app-server.
|
|
@@ -23,13 +22,14 @@ export async function createCompanion({
|
|
|
23
22
|
subscribe = streamPermissionCommands,
|
|
24
23
|
publish, acknowledge,
|
|
25
24
|
warn = (message) => process.stderr.write(`Backeer: ${message}\n`),
|
|
26
|
-
onFatal = () => {},
|
|
25
|
+
onFatal = () => {}, maxMessageBytes = 64 * 1024 * 1024,
|
|
27
26
|
} = {}) {
|
|
27
|
+
if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 1) throw new Error("Invalid proxy message budget");
|
|
28
28
|
const token = crypto.randomBytes(32).toString("hex");
|
|
29
29
|
const server = http.createServer((_request, response) => { response.writeHead(404); response.end(); });
|
|
30
|
-
const sockets = new WebSocketServer({ noServer: true, maxPayload:
|
|
30
|
+
const sockets = new WebSocketServer({ noServer: true, maxPayload: maxMessageBytes, perMessageDeflate: false });
|
|
31
31
|
const abort = new AbortController();
|
|
32
|
-
let backend, socket, bridge,
|
|
32
|
+
let backend, socket, bridge, outputTask, remoteTask, closeTask, closing = false, used = false;
|
|
33
33
|
const connections = new Set();
|
|
34
34
|
server.on("connection", (connection) => {
|
|
35
35
|
if (closing) { connection.destroy(); return; }
|
|
@@ -39,7 +39,11 @@ export async function createCompanion({
|
|
|
39
39
|
|
|
40
40
|
const sendBackend = (message) => {
|
|
41
41
|
if (!backend || backend.stdin.destroyed || backend.stdin.writableEnded) throw new Error("App-server disconnected");
|
|
42
|
-
backend.stdin.write(`${JSON.stringify(message)}\n`)
|
|
42
|
+
if (!backend.stdin.write(`${JSON.stringify(message)}\n`) && socket && !socket.isPaused) {
|
|
43
|
+
socket.pause();
|
|
44
|
+
backend.stdin.once("drain", () => { if (!closing) socket?.resume(); });
|
|
45
|
+
}
|
|
46
|
+
if (backend.stdin.writableLength > maxMessageBytes * 2) throw new Error("App-server input exceeded its configured budget");
|
|
43
47
|
};
|
|
44
48
|
|
|
45
49
|
const fail = () => {
|
|
@@ -85,14 +89,27 @@ export async function createCompanion({
|
|
|
85
89
|
backend.stdin.on("error", fail);
|
|
86
90
|
ws.on("error", fail);
|
|
87
91
|
ws.on("close", (code) => { if (code === 1000 || code === 1001) void close(); else fail(); });
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
92
|
+
outputTask = (async () => {
|
|
93
|
+
let buffer = "";
|
|
94
|
+
const decoder = new TextDecoder();
|
|
95
|
+
for await (const chunk of backend.stdout) {
|
|
96
|
+
if (closing) return;
|
|
97
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
98
|
+
let at;
|
|
99
|
+
while ((at = buffer.indexOf("\n")) >= 0) {
|
|
100
|
+
const line = buffer.slice(0, at); buffer = buffer.slice(at + 1);
|
|
101
|
+
if (Buffer.byteLength(line) > maxMessageBytes) throw new Error("App-server output exceeded its configured budget");
|
|
102
|
+
if (!line.trim()) continue;
|
|
103
|
+
const message = JSON.parse(line);
|
|
104
|
+
bridge.observeServer(message);
|
|
105
|
+
if (ws.readyState !== WebSocket.OPEN) return;
|
|
106
|
+
// Await the socket write callback before reading more backend output.
|
|
107
|
+
await new Promise((resolve, reject) => ws.send(JSON.stringify(message), error => error ? reject(error) : resolve()));
|
|
108
|
+
}
|
|
109
|
+
if (Buffer.byteLength(buffer) > maxMessageBytes) throw new Error("App-server output exceeded its configured budget");
|
|
110
|
+
}
|
|
111
|
+
if (buffer.trim() && !closing) throw new Error("App-server ended inside a message");
|
|
112
|
+
})().catch(() => { if (!closing) fail(); });
|
|
96
113
|
ws.on("message", (data, binary) => {
|
|
97
114
|
try {
|
|
98
115
|
if (binary) throw new Error("Expected JSON text");
|
|
@@ -117,7 +134,7 @@ export async function createCompanion({
|
|
|
117
134
|
closeTask = Promise.resolve().then(async () => {
|
|
118
135
|
abort.abort();
|
|
119
136
|
bridge?.dispose();
|
|
120
|
-
|
|
137
|
+
backend?.stdout.destroy();
|
|
121
138
|
socket?.terminate();
|
|
122
139
|
// A peer can connect without finishing HTTP/upgrade headers. Those
|
|
123
140
|
// sockets never reach the WebSocket handler but must close with us too.
|
|
@@ -139,7 +156,7 @@ export async function createCompanion({
|
|
|
139
156
|
server.closeIdleConnections?.();
|
|
140
157
|
});
|
|
141
158
|
}
|
|
142
|
-
await Promise.all([remoteTask, backendClosed]);
|
|
159
|
+
await Promise.all([remoteTask, backendClosed, outputTask]);
|
|
143
160
|
});
|
|
144
161
|
return closeTask;
|
|
145
162
|
}
|
package/src/gateway.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { commandFrames } from "./command-frames.mjs";
|
|
1
2
|
const JSON_HEADERS = { "Content-Type": "application/json", Accept: "application/json" };
|
|
2
3
|
|
|
3
4
|
function authorization(token) {
|
|
@@ -48,7 +49,7 @@ export async function acknowledgeCommand(config, command, status, errorCode = nu
|
|
|
48
49
|
|
|
49
50
|
function parseSSEBlock(block) {
|
|
50
51
|
const fields = {};
|
|
51
|
-
for (const line of block.split(/\r
|
|
52
|
+
for (const line of block.split(/\r\n|\r|\n/)) {
|
|
52
53
|
if (!line || line.startsWith(":")) continue;
|
|
53
54
|
const separator = line.indexOf(":");
|
|
54
55
|
const key = separator < 0 ? line : line.slice(0, separator);
|
|
@@ -64,25 +65,10 @@ export async function streamPermissionCommands(config, { signal, onCommand }) {
|
|
|
64
65
|
const response = await fetch(`${config.gatewayUrl}/v1/commands/stream`, {
|
|
65
66
|
headers: { Accept: "text/event-stream", ...authorization(config.ingestToken) }, signal,
|
|
66
67
|
});
|
|
67
|
-
if (!response.ok || !response.body) throw new Error("Backeer command stream unavailable");
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
let buffer = "";
|
|
72
|
-
while (!signal.aborted) {
|
|
73
|
-
const { done, value } = await reader.read();
|
|
74
|
-
if (done) return;
|
|
75
|
-
buffer += decoder.decode(value, { stream: true });
|
|
76
|
-
let match;
|
|
77
|
-
while ((match = /\r?\n\r?\n/.exec(buffer))) {
|
|
78
|
-
const command = parseSSEBlock(buffer.slice(0, match.index));
|
|
79
|
-
buffer = buffer.slice(match.index + match[0].length);
|
|
80
|
-
if (command?.type === "codex_permission_reply") await onCommand(command);
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
} finally {
|
|
84
|
-
await reader.cancel().catch(() => {});
|
|
85
|
-
reader.releaseLock();
|
|
68
|
+
if (!response.ok || !response.body) { await response.body?.cancel().catch(() => {}); throw new Error("Backeer command stream unavailable"); }
|
|
69
|
+
for await (const frame of commandFrames(response, { signal, ...(config.commandStreamBudgets || {}) })) {
|
|
70
|
+
const command = parseSSEBlock(frame);
|
|
71
|
+
if (command?.type === "codex_permission_reply") await onCommand(command);
|
|
86
72
|
}
|
|
87
73
|
}
|
|
88
74
|
|
|
@@ -104,30 +90,16 @@ export async function waitForPermissionCommand(config, externalId) {
|
|
|
104
90
|
headers: { Accept: "text/event-stream", ...authorization(config.ingestToken) },
|
|
105
91
|
signal: controller.signal,
|
|
106
92
|
});
|
|
107
|
-
if (!response.ok || !response.body) throw new Error(`Backeer command stream returned HTTP ${response.status}`);
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
while (true) {
|
|
112
|
-
const { done, value } = await reader.read();
|
|
113
|
-
if (done) {
|
|
93
|
+
if (!response.ok || !response.body) { await response.body?.cancel().catch(() => {}); throw new Error(`Backeer command stream returned HTTP ${response.status}`); }
|
|
94
|
+
for await (const frame of commandFrames(response, { signal: controller.signal, ...(config.commandStreamBudgets || {}) })) {
|
|
95
|
+
const command = parseSSEBlock(frame);
|
|
96
|
+
if (command?.type === "codex_permission_reply" && command.externalId === externalId) {
|
|
114
97
|
streamFinished = true;
|
|
115
|
-
return
|
|
116
|
-
}
|
|
117
|
-
buffer += decoder.decode(value, { stream: true });
|
|
118
|
-
let boundary;
|
|
119
|
-
while ((boundary = buffer.search(/\r?\n\r?\n/)) >= 0) {
|
|
120
|
-
const delimiter = buffer.slice(boundary).match(/^\r?\n\r?\n/)?.[0] ?? "\n\n";
|
|
121
|
-
const block = buffer.slice(0, boundary);
|
|
122
|
-
buffer = buffer.slice(boundary + delimiter.length);
|
|
123
|
-
const command = parseSSEBlock(block);
|
|
124
|
-
if (command?.type === "codex_permission_reply" && command.externalId === externalId) {
|
|
125
|
-
await reader.cancel().catch(() => {});
|
|
126
|
-
streamFinished = true;
|
|
127
|
-
return command;
|
|
128
|
-
}
|
|
98
|
+
return command;
|
|
129
99
|
}
|
|
130
100
|
}
|
|
101
|
+
streamFinished = true;
|
|
102
|
+
return null;
|
|
131
103
|
} catch (error) {
|
|
132
104
|
if (error?.name === "AbortError" || error?.name === "TimeoutError") return null;
|
|
133
105
|
throw error;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import crypto from "node:crypto";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
|
|
6
|
+
// Atomic link publishes a complete owner record. No partially written lock can
|
|
7
|
+
// be mistaken for a dead installer. Reclamation is serialized separately.
|
|
8
|
+
export async function acquireInstallLock(directory, { timeoutMs = 120000 } = {}) {
|
|
9
|
+
await fs.mkdir(directory, { recursive: true });
|
|
10
|
+
const lock = path.join(directory, ".backeer-codex.install-lock");
|
|
11
|
+
const nonce = crypto.randomUUID(), candidate = `${lock}.${nonce}.candidate`;
|
|
12
|
+
const identity = JSON.stringify({ pid: process.pid, nonce });
|
|
13
|
+
await fs.writeFile(candidate, identity, { flag: "wx", mode: 0o600 });
|
|
14
|
+
const deadline = Date.now() + timeoutMs;
|
|
15
|
+
try {
|
|
16
|
+
while (true) {
|
|
17
|
+
try { await fs.link(candidate, lock); break; }
|
|
18
|
+
catch (error) { if (error.code !== "EEXIST") throw error; }
|
|
19
|
+
let owner;
|
|
20
|
+
try { owner = JSON.parse(await fs.readFile(lock, "utf8")); }
|
|
21
|
+
catch (error) { if (error.code === "ENOENT") continue; throw new Error("Backeer installation lock is unreadable. Inspect it before retrying."); }
|
|
22
|
+
let dead = false;
|
|
23
|
+
if (!Number.isSafeInteger(owner.pid) || owner.pid < 1 || typeof owner.nonce !== "string") throw new Error("Invalid Backeer installation lock.");
|
|
24
|
+
try { process.kill(owner.pid, 0); } catch (error) { if (error.code === "ESRCH") dead = true; }
|
|
25
|
+
if (dead) {
|
|
26
|
+
const reaper = `${lock}.reap`;
|
|
27
|
+
let acquired = false;
|
|
28
|
+
try {
|
|
29
|
+
await fs.mkdir(reaper, { mode: 0o700 }); acquired = true;
|
|
30
|
+
const current = JSON.parse(await fs.readFile(lock, "utf8"));
|
|
31
|
+
if (current.nonce === owner.nonce) await fs.unlink(lock);
|
|
32
|
+
} catch (error) { if (!["EEXIST", "ENOENT"].includes(error.code)) throw error; }
|
|
33
|
+
finally { if (acquired) await fs.rmdir(reaper); }
|
|
34
|
+
}
|
|
35
|
+
if (Date.now() >= deadline) throw new Error("Another Backeer installation is active; retry after it completes.");
|
|
36
|
+
await delay(50);
|
|
37
|
+
}
|
|
38
|
+
} finally { await fs.rm(candidate, { force: true }); }
|
|
39
|
+
return async () => {
|
|
40
|
+
try { const current = JSON.parse(await fs.readFile(lock, "utf8")); if (current.nonce === nonce) await fs.unlink(lock); }
|
|
41
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
42
|
+
};
|
|
43
|
+
}
|
package/src/installer.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { acquireInstallLock } from "./install-lock.mjs";
|
|
1
2
|
import { randomUUID } from "node:crypto";
|
|
2
3
|
import fs from "node:fs/promises";
|
|
3
4
|
import os from "node:os";
|
|
@@ -101,7 +102,7 @@ function runCodexInstall(marketplaceName) {
|
|
|
101
102
|
});
|
|
102
103
|
}
|
|
103
104
|
|
|
104
|
-
|
|
105
|
+
async function installLocked(options = {}) {
|
|
105
106
|
const paths = personalPaths(options.homeDirectory);
|
|
106
107
|
// Validate before touching an installed plugin: a corrupt registry must not
|
|
107
108
|
// leave new files behind while reporting that the installation failed.
|
|
@@ -144,3 +145,9 @@ export async function installPlugin(options = {}) {
|
|
|
144
145
|
return { ...paths, marketplaceName };
|
|
145
146
|
}
|
|
146
147
|
|
|
148
|
+
|
|
149
|
+
export async function installPlugin(options = {}) {
|
|
150
|
+
const paths = personalPaths(options.homeDirectory);
|
|
151
|
+
const release = await acquireInstallLock(path.dirname(paths.pluginDirectory));
|
|
152
|
+
try { return await installLocked(options); } finally { await release(); }
|
|
153
|
+
}
|
package/src/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const VERSION = "0.
|
|
1
|
+
export const VERSION = "0.13.0";
|