backeer-codex 0.11.1 → 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 +50 -2
- package/dist/opencode.mjs +539 -66
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/scripts/check-package.mjs +4 -1
- package/skills/backeer/SKILL.md +60 -5
- 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 +43 -11
- package/src/opencode.mjs +15 -6
- package/src/version.mjs +1 -0
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/skills/backeer/SKILL.md
CHANGED
|
@@ -19,6 +19,7 @@ Commands:
|
|
|
19
19
|
- `opencode connections`: list saved OpenCode connections without exposing token files or values.
|
|
20
20
|
- `opencode setup`: guide setup in an interactive terminal. Reuse a saved connection or discover an existing bridge, then select a current session by number. Session choices are not saved in profiles. Never asks for a raw token or password.
|
|
21
21
|
- `opencode verify <name> "<exact session title>"`: read-only end-to-end project/session/SSE verification; sends no model instruction and closes its temporary stream.
|
|
22
|
+
- `opencode report <name>`: one read-only report of loaded versions, feature compatibility, native owners, stream and request latency.
|
|
22
23
|
- `opencode diagnose <name>`: read-only diagnosis for one saved connection; no SSH, credential or remote session changes.
|
|
23
24
|
- `opencode discover`: return safe discovered candidates and actionable setup diagnostics without printing credentials or private token file paths.
|
|
24
25
|
- `opencode add <name> <loopback-url> <token-file> <remote-project-directory>`: save a connection with an existing protected live-control token file. Requires the user's intended server/project, not a guessed target. Does not alter SSH configuration, start a tunnel or create a session.
|
|
@@ -43,13 +44,13 @@ Use `connection_setup` for a guided flow when the user needs help choosing a con
|
|
|
43
44
|
|
|
44
45
|
On a connection failure call `diagnose_connection` with exactly one connection name or this chat's bindingId. Explain its safe diagnostic and next step rather than repeatedly returning a generic error. A refused loopback connection means the local endpoint/tunnel is unavailable; it does not prove an OpenCode bug. The plugin retries SSE every three seconds but does not create an SSH tunnel. Never change SSH or credentials as an automatic repair.
|
|
45
46
|
|
|
46
|
-
Reads during temporary transport failures can return buffered events with `verified: false`. Identify them as previously received output; keep the binding/cursor, and verify the exact session with `session_status` after reconnection. Do not send a new instruction, automatically retry a POST, or acknowledge a replay gap while verification is pending. Different bindings keep independent
|
|
47
|
+
Reads during temporary transport failures can return buffered events with `verified: false`. Identify them as previously received output; keep the binding/cursor, and verify the exact session with `session_status` after reconnection. Do not send a new instruction, automatically retry a POST, or acknowledge a replay gap while verification is pending. Different bindings keep independent projections and unread cursors while compatible bindings in one MCP process share a project SSE transport, including two chats observing the same session.
|
|
47
48
|
|
|
48
49
|
Tree tracking requires a remote bridge advertising `capabilities.sessionTree` (Backeer OpenCode 0.12.0+) and the updated local adapter (Backeer Codex 0.9.0+). If unsupported, explain that the remote bridge must be updated; do not silently fall back to parent-only output or an unfiltered project stream. The binding's root and event scope are fixed until explicitly disconnected/reconnected. Existing and newly created descendants are followed through verified native `parentID` relationships, including nested subagents; unrelated sessions and fork provenance are not task ancestry.
|
|
49
50
|
|
|
50
51
|
Backeer OpenCode 0.12.0 automatically answers native filesystem permission actions (`read`, `edit`, `glob`, `grep`, V1 `list`, `external_directory`) with OpenCode's Always allow decision. This runs in the owning OpenCode process, including for subagents, independently of mobile notifications. Do not submit a second answer through a chat instruction or ordinary question tool. From Backeer OpenCode 0.12.1, successful automatic approvals also send an informational mobile push when permission notifications and the mobile token are enabled. The configured native TUI owner runs mobile notification handling independently of the live SSE switch or project pin. Other permission types use their existing approval flow. OpenCode owns the saved approval patterns; the Codex launcher's separate permission settings are not changed by this feature.
|
|
51
52
|
|
|
52
|
-
Label output with its source `sessionID` and available agent/title rather than presenting every child's output as the parent. Check `session_status` for the tree's member states, active/waiting counts and failed outcomes. A child's or parent's idle event alone does not establish that all work is complete; unknown states remain unverified. If `tree.complete` is false, disclose the incomplete snapshot and retry status after recovery; do not infer completion from its partial counts. A `session_tree_unavailable` gap means ancestry could not be verified for some output; disclose the gap and follow the normal status/explicit-cursor recovery procedure. Keep waiting when descendants are active or waiting. Instructions
|
|
53
|
+
Label output with its source `sessionID` and available agent/title rather than presenting every child's output as the parent. Check `session_status` for the tree's member states, active/waiting counts and failed outcomes. A child's or parent's idle event alone does not establish that all work is complete; unknown states remain unverified. If `tree.complete` is false, disclose the incomplete snapshot and retry status after recovery; do not infer completion from its partial counts. A `session_tree_unavailable` gap means ancestry could not be verified for some output; disclose the gap and follow the normal status/explicit-cursor recovery procedure. Keep waiting when descendants are active or waiting. Instructions target the selected root. For an ordinary child question authorized by the user, pass its exact source as targetSessionId to list_questions and answer_question on the same binding. The manager and bridge freshly verify its native parent ancestry and form revision. Never route a child answer through the root or use ordinary forms to approve permissions/authentication. Tree tracking covers OpenCode child sessions, not opaque agents inside a separate Codex process. V2 assistant text still arrives as completed, redacted text units, not raw token deltas.
|
|
53
54
|
|
|
54
55
|
Profiles are local to each computer. This local stdio plugin works in a host with a local executor (such as Codex Desktop); ordinary ChatGPT web/mobile chats do not automatically inherit this computer's plugin or SSH tunnel.
|
|
55
56
|
|
|
@@ -120,9 +121,9 @@ permissions and errors wake the tool immediately, even during native verificatio
|
|
|
120
121
|
children are active, waiting or unknown. `coverageComplete` is about known scope,
|
|
121
122
|
not task completion. An interruption must never be presented as completion.
|
|
122
123
|
|
|
123
|
-
On a question alert, read pending questions for that exact source.
|
|
124
|
-
|
|
125
|
-
|
|
124
|
+
On a question alert, read pending questions for that exact source. From Codex 0.12.0 / OpenCode 0.15.0, ordinary child questions can use the same
|
|
125
|
+
binding with an explicit targetSessionId from the alert. Read and answer that
|
|
126
|
+
exact child form after user authorization; never send its answer to the parent.
|
|
126
127
|
Filesystem permissions still auto-allow in their native owner; report them as
|
|
127
128
|
informational when already settled, without sending another decision.
|
|
128
129
|
|
|
@@ -160,3 +161,57 @@ are verified with bounded parallel reads, without dropping ownership checks.
|
|
|
160
161
|
Update and load both bridge 0.14.2+ and adapter 0.11.1+ when older timeouts are
|
|
161
162
|
still active; don't repeatedly diagnose unchanged outages or silently reduce
|
|
162
163
|
tree scope to get past a timeout.
|
|
164
|
+
|
|
165
|
+
## Reliability and direct tools (Codex 0.12.0 / OpenCode 0.15.0)
|
|
166
|
+
|
|
167
|
+
Use `connection_report` for one connection or this binding. It separates the
|
|
168
|
+
running local adapter, embedded bridge client and remote loaded version. Remote
|
|
169
|
+
installation on disk is unknown unless separately verified. Unsupported protocol
|
|
170
|
+
majors fail closed; missing optional features remain explicitly unavailable.
|
|
171
|
+
A reachable listener is not proof that its native session API is working.
|
|
172
|
+
OpenCode's `backeer-opencode status` CLI, `/backeer-status` TUI command and
|
|
173
|
+
“Backeer: Bağlantı raporu” palette entry display local state without a model call.
|
|
174
|
+
The TUI entry requires the package's TUI plugin to be loaded.
|
|
175
|
+
|
|
176
|
+
Activity is projected from SSE events. Full native reconciliation happens on
|
|
177
|
+
connection/reconnection, membership changes, uncertain coverage, terminal
|
|
178
|
+
verification and a periodic 30-second freshness check, rather than every update.
|
|
179
|
+
Use `changesOnly: true` with watch_activity after the first card. Merge `delta`
|
|
180
|
+
into the previous card; suppress an unchanged card while still showing urgent
|
|
181
|
+
alerts and delivery updates. Use activity_status for a full view as needed.
|
|
182
|
+
Unknown ancestry and expired buffers stay explicit gaps. Never acknowledge one
|
|
183
|
+
without a fresh complete status check. Compatible bindings share one SSE per
|
|
184
|
+
endpoint/project/credential within an MCP process; each retains independent
|
|
185
|
+
scope, activity, raw/detail cursors, history-gap acknowledgement and cancellation.
|
|
186
|
+
Different processes still have independent transports. This is not a global
|
|
187
|
+
subscription shared across all desktop chats.
|
|
188
|
+
|
|
189
|
+
For requested output use `tail_output` (default last 50 retained lines),
|
|
190
|
+
`read_errors` or `tool_result` by exact retained eventId. Optional sessionId
|
|
191
|
+
narrows to an exact descendant; it never widens the binding. Source references,
|
|
192
|
+
clipping, partial first lines and retention expiry are explicit. These tools do
|
|
193
|
+
not consume other read cursors. Use read_details with eventId/offset/nextOffset
|
|
194
|
+
for full retained source text. Buffered reads during native outages are marked
|
|
195
|
+
verified:false and must not be described as newly verified live output.
|
|
196
|
+
|
|
197
|
+
After send_instruction, keep its requestId and receipt. `accepted` means native
|
|
198
|
+
admission, not execution or completion. Use `instruction_status` for the exact
|
|
199
|
+
receipt: delivery is unknown/queued/delivered/cancelled. Native V2 inbox events
|
|
200
|
+
update delivery, including compact activity delivery updates. Execution/outcome
|
|
201
|
+
in this receipt belongs to the session, not necessarily this one instruction.
|
|
202
|
+
Never automatically resend, change delivery mode, or invent per-message task
|
|
203
|
+
completion. Legacy native APIs can report unknown delivery.
|
|
204
|
+
|
|
205
|
+
With durableCommands, protected append-only transition records preserve request
|
|
206
|
+
signatures and receipts across owner/plugin restarts. Prompt/answer text and
|
|
207
|
+
credentials are not stored. Reusing an accepted ID returns its receipt; an
|
|
208
|
+
interrupted reservation remains command_delivery_uncertain and is never replayed
|
|
209
|
+
automatically. Never delete reservations as a repair. A missing receipt after
|
|
210
|
+
migration or on another owner is not proof that delivery never happened.
|
|
211
|
+
The new guarantee starts with requests recorded by the updated bridge.
|
|
212
|
+
|
|
213
|
+
Read-only native failures enter a per-owner circuit after three failures and
|
|
214
|
+
allow one recovery probe after 10 seconds. Writes are never retried by this
|
|
215
|
+
mechanism. The existing 3/10/30/45-second liveness/native/aggregate/client budgets
|
|
216
|
+
remain separate. Request latency and response-byte metrics are observations,
|
|
217
|
+
not an estimate of billed model tokens.
|
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,5 @@
|
|
|
1
|
+
import { acquireInstallLock } from "./install-lock.mjs";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
1
3
|
import fs from "node:fs/promises";
|
|
2
4
|
import os from "node:os";
|
|
3
5
|
import path from "node:path";
|
|
@@ -100,22 +102,52 @@ function runCodexInstall(marketplaceName) {
|
|
|
100
102
|
});
|
|
101
103
|
}
|
|
102
104
|
|
|
103
|
-
|
|
105
|
+
async function installLocked(options = {}) {
|
|
104
106
|
const paths = personalPaths(options.homeDirectory);
|
|
105
107
|
// Validate before touching an installed plugin: a corrupt registry must not
|
|
106
108
|
// leave new files behind while reporting that the installation failed.
|
|
107
109
|
const marketplace = await readMarketplace(paths.marketplaceFile);
|
|
108
110
|
validateMarketplace(paths.marketplaceFile, marketplace);
|
|
109
|
-
|
|
110
|
-
//
|
|
111
|
-
//
|
|
112
|
-
const
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
111
|
+
const source = options.packageRoot || PACKAGE_ROOT;
|
|
112
|
+
// Construct a complete replacement before touching the installed directory.
|
|
113
|
+
// Rename removes obsolete files and avoids mixing two package versions.
|
|
114
|
+
const suffix = randomUUID();
|
|
115
|
+
const staging = `${paths.pluginDirectory}.stage-${suffix}`;
|
|
116
|
+
const previous = `${paths.pluginDirectory}.previous-${suffix}`;
|
|
117
|
+
const originalRegistry = await fs.readFile(paths.marketplaceFile).catch(error => {
|
|
118
|
+
if (error.code === "ENOENT") return undefined;
|
|
119
|
+
throw error;
|
|
120
|
+
});
|
|
121
|
+
let movedOld = false, committed = false, registryWritten = false;
|
|
122
|
+
let marketplaceName;
|
|
123
|
+
try {
|
|
124
|
+
await copyPlugin(source, staging);
|
|
125
|
+
const wsRoot = path.dirname(require.resolve("ws/package.json"));
|
|
126
|
+
await fs.cp(wsRoot, path.join(staging, "node_modules", "ws"), { recursive: true, force: true });
|
|
127
|
+
try { await fs.rename(paths.pluginDirectory, previous); movedOld = true; }
|
|
128
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
129
|
+
await fs.rename(staging, paths.pluginDirectory); committed = true;
|
|
130
|
+
marketplaceName = await writeMarketplace(paths.marketplaceFile, marketplace); registryWritten = true;
|
|
131
|
+
if (options.installWithCodex !== false) await (options.runInstall || runCodexInstall)(marketplaceName);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
if (committed) await fs.rm(paths.pluginDirectory, { recursive: true, force: true });
|
|
134
|
+
if (movedOld) await fs.rename(previous, paths.pluginDirectory);
|
|
135
|
+
if (registryWritten) {
|
|
136
|
+
if (originalRegistry) {
|
|
137
|
+
const rollback = `${paths.marketplaceFile}.${suffix}.rollback`;
|
|
138
|
+
await fs.writeFile(rollback, originalRegistry, { mode: 0o600 });
|
|
139
|
+
await fs.rename(rollback, paths.marketplaceFile);
|
|
140
|
+
} else await fs.rm(paths.marketplaceFile, { force: true });
|
|
141
|
+
}
|
|
142
|
+
throw error;
|
|
143
|
+
} finally { await fs.rm(staging, { recursive: true, force: true }); }
|
|
144
|
+
if (movedOld) await fs.rm(previous, { recursive: true, force: true });
|
|
119
145
|
return { ...paths, marketplaceName };
|
|
120
146
|
}
|
|
121
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
|
+
}
|