backeer-codex 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +63 -2
- package/package.json +6 -3
- package/skills/backeer/SKILL.md +3 -0
- package/src/approval-bridge.mjs +140 -0
- package/src/cli.mjs +18 -1
- package/src/companion.mjs +175 -0
- package/src/config.mjs +2 -0
- package/src/gateway.mjs +28 -0
- package/src/hook-handlers.mjs +9 -1
- package/src/installer.mjs +10 -1
package/README.md
CHANGED
|
@@ -4,13 +4,72 @@
|
|
|
4
4
|
|
|
5
5
|
It provides:
|
|
6
6
|
|
|
7
|
-
-
|
|
7
|
+
- Simultaneous native terminal and Backeer approvals with `backeer-codex start`.
|
|
8
|
+
- Native Codex permission prompts by default; optional Backeer remote approval mode: Allow once, Always allow, and Reject.
|
|
8
9
|
- Session-scoped exact-match policies for Always allow. Policies are deleted when the Codex session ends.
|
|
9
10
|
- Task-completion notifications through the Codex `Stop` hook.
|
|
10
11
|
- Optional failed-tool notifications (disabled by default).
|
|
11
12
|
- `status`, `doctor`, `test`, and interactive token configuration commands.
|
|
12
13
|
- Safe fallback to the normal Codex permission prompt when Backeer is unavailable or not configured.
|
|
13
14
|
|
|
15
|
+
## Approval behavior and limitations
|
|
16
|
+
|
|
17
|
+
### Dual-channel terminal
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
backeer-codex start
|
|
21
|
+
# Optional Codex arguments, including a different project directory:
|
|
22
|
+
backeer-codex start -- -C /path/to/project --no-alt-screen
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
This starts Codex's own terminal interface connected through an authenticated
|
|
26
|
+
loopback bridge to a private `codex app-server` process. Requires a Codex version
|
|
27
|
+
with `--remote` support; tested with Codex CLI 0.159.2. No separate OpenAI API key
|
|
28
|
+
is needed: the app-server uses your existing Codex configuration and login.
|
|
29
|
+
|
|
30
|
+
Command, file-change and `request_permissions` approvals appear in the native
|
|
31
|
+
terminal and are also forwarded to Backeer. The first valid answer is sent to
|
|
32
|
+
Codex exactly once. Remote answers offer Allow once and Reject. Broader grants
|
|
33
|
+
remain available only in the native terminal. Backeer receipts report application
|
|
34
|
+
only after Codex confirms the request was resolved. Interrupted requests and late
|
|
35
|
+
responses cannot grant permission. Existing Backeer notifications may remain in
|
|
36
|
+
the phone's history after a local answer; their actions are no longer effective.
|
|
37
|
+
|
|
38
|
+
The gateway uses one reconnecting command subscription per launcher. If the
|
|
39
|
+
gateway is offline or the source token is missing, native terminal approval still
|
|
40
|
+
works. The local bridge binds only to `127.0.0.1`, accepts one authenticated client,
|
|
41
|
+
and closes with the terminal. Other server requests (including user questions)
|
|
42
|
+
continue to the terminal without remote handling.
|
|
43
|
+
|
|
44
|
+
### Standalone `codex` command
|
|
45
|
+
|
|
46
|
+
The default approval mode is `local`. The permission hook immediately returns no
|
|
47
|
+
decision, so Codex shows its native approval prompt without contacting Backeer or
|
|
48
|
+
using previously saved remote session policies. Completion and optional tool
|
|
49
|
+
failure notifications remain enabled according to their settings. Permission
|
|
50
|
+
requests are not sent to Backeer in local mode.
|
|
51
|
+
|
|
52
|
+
To switch modes explicitly:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
backeer-codex approval-mode local
|
|
56
|
+
backeer-codex approval-mode remote
|
|
57
|
+
backeer-codex status
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
In `remote` mode, the plugin uses a synchronous `PermissionRequest` hook. Codex waits for
|
|
61
|
+
this hook before showing its native approval prompt. While Backeer is waiting for
|
|
62
|
+
a remote decision (110 seconds by default), the native prompt is not available.
|
|
63
|
+
A valid remote decision resolves the request without displaying the native prompt.
|
|
64
|
+
If no remote decision arrives, or Backeer fails, the hook returns no decision and
|
|
65
|
+
Codex continues with its normal local approval flow.
|
|
66
|
+
|
|
67
|
+
Dual-channel approval uses the `start` launcher, not the standalone hook. Marking
|
|
68
|
+
the hook `async` cannot provide this behavior: background hooks cannot approve
|
|
69
|
+
or deny the pending operation. The launcher forces local hook mode only for its
|
|
70
|
+
child processes, leaving your saved standalone mode unchanged. See the
|
|
71
|
+
[official hook contract](https://learn.chatgpt.com/docs/hooks#permissionrequest).
|
|
72
|
+
|
|
14
73
|
## Configure
|
|
15
74
|
|
|
16
75
|
Install the published package and register it in the default Codex personal marketplace:
|
|
@@ -36,4 +95,6 @@ After enabling or updating the plugin, use `/hooks` in Codex to review and trust
|
|
|
36
95
|
|
|
37
96
|
The source credential stays on the computer running Codex. It is used only for Backeer source endpoints and is never added to event payloads, hook output, or the iOS application. Obvious secret fields are redacted and permission details are truncated before publication. Session policies contain only SHA-256 fingerprints.
|
|
38
97
|
|
|
39
|
-
Codex plan-mode user questions are not exposed to lifecycle hooks.
|
|
98
|
+
Codex plan-mode user questions are not exposed to lifecycle hooks. The App Server
|
|
99
|
+
companion currently forwards user questions to the native terminal only; remote
|
|
100
|
+
question answers are not implemented. Neither mode emulates or scrapes that UI.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "backeer-codex",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Backeer lifecycle and permission hooks for Codex",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE",
|
|
@@ -24,10 +24,13 @@
|
|
|
24
24
|
"node": ">=18"
|
|
25
25
|
},
|
|
26
26
|
"bin": {
|
|
27
|
-
"backeer-codex": "
|
|
27
|
+
"backeer-codex": "scripts/backeer-codex.mjs"
|
|
28
28
|
},
|
|
29
29
|
"scripts": {
|
|
30
30
|
"test": "node --test",
|
|
31
|
-
"check": "node --check scripts/hook.mjs && node --check scripts/backeer-codex.mjs"
|
|
31
|
+
"check": "node --check scripts/hook.mjs && node --check scripts/backeer-codex.mjs && node --check src/approval-bridge.mjs && node --check src/companion.mjs"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"ws": "^8.22.0"
|
|
32
35
|
}
|
|
33
36
|
}
|
package/skills/backeer/SKILL.md
CHANGED
|
@@ -9,7 +9,10 @@ Use the plugin's bundled management script. Resolve it with `$PLUGIN_ROOT` when
|
|
|
9
9
|
|
|
10
10
|
Commands:
|
|
11
11
|
|
|
12
|
+
- `start [-- Codex args]`: launch the native Codex terminal with simultaneous terminal and Backeer approvals. First valid response wins; remote choices are Allow once and Reject. Requires Codex `--remote` support. Standalone `codex` hook mode is not changed.
|
|
12
13
|
- `status`: show the gateway, masked credential status, and notification settings.
|
|
14
|
+
- `approval-mode local`: restore native Codex permission prompts without waiting for Backeer (the default); permission forwarding and remote session policies are bypassed.
|
|
15
|
+
- `approval-mode remote`: explicitly opt in to Backeer remote approvals; Codex's native prompt waits until the hook returns without a decision.
|
|
13
16
|
- `doctor`: validate Node.js, protected config permissions, source authentication, and command-stream capability.
|
|
14
17
|
- `test`: send a normal Backeer test notification.
|
|
15
18
|
- `configure`: interactively set or rotate the source token and optionally change the gateway URL. Run this in an interactive terminal; never place the token in command arguments, chat, logs, or tool output.
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import { acknowledgeCommand, publishEvent } from "./gateway.mjs";
|
|
3
|
+
import { compactText, digest, workspaceLabel } from "./privacy.mjs";
|
|
4
|
+
|
|
5
|
+
const METHODS = new Set([
|
|
6
|
+
"item/commandExecution/requestApproval",
|
|
7
|
+
"item/fileChange/requestApproval",
|
|
8
|
+
"item/permissions/requestApproval",
|
|
9
|
+
]);
|
|
10
|
+
|
|
11
|
+
function remember(map, key, value) {
|
|
12
|
+
map.set(key, value);
|
|
13
|
+
if (map.size > 2048) map.delete(map.keys().next().value);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export class ApprovalBridge {
|
|
17
|
+
constructor({ config, sendBackend, publish = publishEvent, acknowledge = acknowledgeCommand, warn = () => {} }) {
|
|
18
|
+
Object.assign(this, { config, sendBackend, publish, acknowledge, warn });
|
|
19
|
+
this.nonce = crypto.randomUUID();
|
|
20
|
+
this.requests = new Map();
|
|
21
|
+
this.byExternalId = new Map();
|
|
22
|
+
this.receipts = new Map();
|
|
23
|
+
this.items = new Map();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async receipt(command, status, errorCode) {
|
|
27
|
+
remember(this.receipts, command.id, { status, errorCode });
|
|
28
|
+
try { await this.acknowledge(this.config, command, status, errorCode); }
|
|
29
|
+
catch { this.warn("Backeer decision receipt could not be delivered."); }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
observeServer(message) {
|
|
33
|
+
const p = message.params || {};
|
|
34
|
+
if (message.method === "item/started" && p.item) {
|
|
35
|
+
remember(this.items, JSON.stringify([p.threadId, p.item.id]), p.item);
|
|
36
|
+
}
|
|
37
|
+
if (message.method === "serverRequest/resolved") {
|
|
38
|
+
const entry = this.requests.get(p.requestId);
|
|
39
|
+
if (entry && entry.params.threadId === p.threadId) this.clear(entry, true);
|
|
40
|
+
}
|
|
41
|
+
if (["turn/completed", "thread/closed", "thread/archived"].includes(message.method)) {
|
|
42
|
+
for (const entry of this.requests.values()) {
|
|
43
|
+
if (entry.params.threadId === p.threadId &&
|
|
44
|
+
(message.method !== "turn/completed" || entry.params.turnId === p.turn?.id)) this.clear(entry, false);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (!METHODS.has(message.method) || message.id == null || !p.threadId || !p.turnId || !p.itemId) return;
|
|
48
|
+
const item = this.items.get(JSON.stringify([p.threadId, p.itemId]));
|
|
49
|
+
const entry = { id: message.id, method: message.method, params: p, state: "pending",
|
|
50
|
+
externalId: `codex:${digest(this.nonce, 16)}:${digest(JSON.stringify([p.threadId, p.turnId, message.id]), 32)}` };
|
|
51
|
+
// Keep active requests, prune only completed tombstones.
|
|
52
|
+
this.requests.set(entry.id, entry);
|
|
53
|
+
this.byExternalId.set(entry.externalId, entry);
|
|
54
|
+
if (!this.config.ingestToken) return;
|
|
55
|
+
const details = compactText({ command: p.command, reason: p.reason, cwd: p.cwd,
|
|
56
|
+
network: p.networkApprovalContext, permissions: p.permissions,
|
|
57
|
+
additionalPermissions: p.additionalPermissions, grantRoot: p.grantRoot,
|
|
58
|
+
changes: item?.changes }, 2500);
|
|
59
|
+
const available = ["once", "reject"].filter((decision) => this.resultFor(entry, decision) !== null);
|
|
60
|
+
void this.publish(this.config, {
|
|
61
|
+
type: "application", severity: "warning", title: "Codex permission required",
|
|
62
|
+
body: details,
|
|
63
|
+
payload: [
|
|
64
|
+
{ key: "Permission", value: message.method },
|
|
65
|
+
{ key: "Session", value: p.threadId },
|
|
66
|
+
{ key: "Turn ID", value: p.turnId },
|
|
67
|
+
{ key: "Request ID", value: String(message.id) },
|
|
68
|
+
{ key: "Patterns", value: details },
|
|
69
|
+
{ key: "Workspace", value: workspaceLabel(p.cwd) },
|
|
70
|
+
{ key: "Action protocol", value: "codex-permission/v1" },
|
|
71
|
+
{ key: "Available decisions", value: available.join(", ") },
|
|
72
|
+
], externalId: entry.externalId, notify: true, direction: "in",
|
|
73
|
+
}).catch(() => this.warn("Backeer notification failed; terminal approval remains available."));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
resultFor(entry, decision) {
|
|
77
|
+
if (!["once", "reject"].includes(decision)) return null;
|
|
78
|
+
if (entry.method === "item/permissions/requestApproval") {
|
|
79
|
+
if (!entry.params.permissions || typeof entry.params.permissions !== "object") return null;
|
|
80
|
+
return { permissions: decision === "once" ? entry.params.permissions : {}, scope: "turn" };
|
|
81
|
+
}
|
|
82
|
+
const value = decision === "once" ? "accept" : "decline";
|
|
83
|
+
if (Array.isArray(entry.params.availableDecisions) && !entry.params.availableDecisions.includes(value)) return null;
|
|
84
|
+
return { decision: value };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Called before forwarding a terminal response. The synchronous state change
|
|
88
|
+
// arbitrates races even while gateway requests/ACKs are still in flight.
|
|
89
|
+
forwardLocal(message) {
|
|
90
|
+
if (message.method || message.id == null) return true;
|
|
91
|
+
const entry = this.requests.get(message.id);
|
|
92
|
+
if (!entry) return true;
|
|
93
|
+
if (entry.state !== "pending") return false;
|
|
94
|
+
entry.state = "local";
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async handleCommand(command) {
|
|
99
|
+
if (command?.type !== "codex_permission_reply" || typeof command.id !== "string" ||
|
|
100
|
+
!command.id || command.id.length > 200) return;
|
|
101
|
+
const entry = this.byExternalId.get(command.externalId);
|
|
102
|
+
if (!entry) return; // Another process/session owns this command.
|
|
103
|
+
const previous = this.receipts.get(command.id);
|
|
104
|
+
if (previous) return this.receipt(command, previous.status, previous.errorCode);
|
|
105
|
+
if (entry.command?.id === command.id) return; // Await server confirmation.
|
|
106
|
+
if (entry.state !== "pending") return this.receipt(command, "stale", "already_resolved");
|
|
107
|
+
const expiresAt = typeof command.expiresAt === "string" ? Date.parse(command.expiresAt) : NaN;
|
|
108
|
+
if (!Number.isFinite(expiresAt)) return this.receipt(command, "rejected", "invalid_expiration");
|
|
109
|
+
if (expiresAt <= Date.now()) return this.receipt(command, "expired");
|
|
110
|
+
const result = this.resultFor(entry, command.decision);
|
|
111
|
+
if (!result) return this.receipt(command, "rejected", "unsupported_decision");
|
|
112
|
+
entry.state = "remote";
|
|
113
|
+
entry.command = command;
|
|
114
|
+
try { this.sendBackend({ id: entry.id, result }); }
|
|
115
|
+
catch {
|
|
116
|
+
entry.state = "pending";
|
|
117
|
+
entry.command = undefined;
|
|
118
|
+
await this.receipt(command, "failed", "transport_unavailable");
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
clear(entry, confirmed) {
|
|
123
|
+
if (entry.state === "cleared") return;
|
|
124
|
+
entry.state = "cleared";
|
|
125
|
+
if (entry.command) void this.receipt(entry.command, confirmed ? "applied" : "stale",
|
|
126
|
+
confirmed ? undefined : "request_cleared");
|
|
127
|
+
// Retain bounded tombstones to discard late local/remote answers.
|
|
128
|
+
const cleared = [...this.requests.values()].filter((value) => value.state === "cleared");
|
|
129
|
+
if (cleared.length > 1024) {
|
|
130
|
+
const oldest = cleared[0];
|
|
131
|
+
this.requests.delete(oldest.id);
|
|
132
|
+
this.byExternalId.delete(oldest.externalId);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
dispose() {
|
|
137
|
+
for (const entry of this.requests.values()) this.clear(entry, false);
|
|
138
|
+
this.items.clear();
|
|
139
|
+
}
|
|
140
|
+
}
|
package/src/cli.mjs
CHANGED
|
@@ -72,6 +72,8 @@ async function status() {
|
|
|
72
72
|
output.write(`Gateway: ${config.gatewayUrl}\n`);
|
|
73
73
|
output.write(`Token: ${maskedToken(config.ingestToken)}\n`);
|
|
74
74
|
output.write(`Config: ${configDirectory()}\n`);
|
|
75
|
+
output.write(`Approval mode: ${config.approvalMode}\n`);
|
|
76
|
+
output.write("Dual-channel terminal: backeer-codex start\n");
|
|
75
77
|
output.write(`Completion notifications: ${config.notifyCompletion ? "on" : "off"}\n`);
|
|
76
78
|
output.write(`Tool failure notifications: ${config.notifyToolFailures ? "on" : "off"}\n`);
|
|
77
79
|
}
|
|
@@ -125,11 +127,26 @@ async function install() {
|
|
|
125
127
|
|
|
126
128
|
export async function runCLI(args) {
|
|
127
129
|
const command = args[0] || "status";
|
|
130
|
+
if (command === "start") {
|
|
131
|
+
const { startCompanion } = await import("./companion.mjs");
|
|
132
|
+
return startCompanion(args.slice(1));
|
|
133
|
+
}
|
|
134
|
+
if (command === "approval-mode") {
|
|
135
|
+
const approvalMode = args[1];
|
|
136
|
+
if (!["local", "remote"].includes(approvalMode)) {
|
|
137
|
+
throw new Error("Usage: backeer-codex approval-mode <local|remote>");
|
|
138
|
+
}
|
|
139
|
+
await saveConfig({ approvalMode });
|
|
140
|
+
output.write(`Approval mode: ${approvalMode}. ${approvalMode === "local"
|
|
141
|
+
? "Codex shows its native permission prompt; Backeer remote approvals are disabled."
|
|
142
|
+
: "Backeer handles approvals before the native Codex permission prompt."}\n`);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
128
145
|
if (command === "install") return install();
|
|
129
146
|
if (["configure", "token"].includes(command)) return configure();
|
|
130
147
|
if (command === "configure-file") return configureFromFile(args[1]);
|
|
131
148
|
if (command === "status") return status();
|
|
132
149
|
if (command === "doctor") return doctor();
|
|
133
150
|
if (command === "test") return testNotification();
|
|
134
|
-
throw new Error("Usage: backeer-codex [install|configure|status|doctor|test]");
|
|
151
|
+
throw new Error("Usage: backeer-codex [start [-- Codex args]|install|configure|status|doctor|test|approval-mode <local|remote>]");
|
|
135
152
|
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import readline from "node:readline";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { WebSocketServer, WebSocket } from "ws";
|
|
7
|
+
import { ApprovalBridge } from "./approval-bridge.mjs";
|
|
8
|
+
import { loadConfig } from "./config.mjs";
|
|
9
|
+
import { streamPermissionCommands } from "./gateway.mjs";
|
|
10
|
+
|
|
11
|
+
const REQUIRED_NOTIFICATIONS = new Set([
|
|
12
|
+
"serverRequest/resolved", "turn/completed", "thread/closed", "thread/archived", "item/started",
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
// Authenticated loopback proxy: native Codex TUI <-> JSON-RPC <-> app-server.
|
|
16
|
+
// No custom terminal rendering and no terminal input/key injection.
|
|
17
|
+
export async function createCompanion({
|
|
18
|
+
config, codex = "codex", env = process.env,
|
|
19
|
+
spawnBackend = () => spawn(codex, ["app-server", "--listen", "stdio://"], {
|
|
20
|
+
stdio: ["pipe", "pipe", "inherit"],
|
|
21
|
+
env: { ...env, BACKEER_APPROVAL_MODE: "local" },
|
|
22
|
+
}),
|
|
23
|
+
subscribe = streamPermissionCommands,
|
|
24
|
+
publish, acknowledge,
|
|
25
|
+
warn = (message) => process.stderr.write(`Backeer: ${message}\n`),
|
|
26
|
+
onFatal = () => {},
|
|
27
|
+
} = {}) {
|
|
28
|
+
const token = crypto.randomBytes(32).toString("hex");
|
|
29
|
+
const server = http.createServer((_request, response) => { response.writeHead(404); response.end(); });
|
|
30
|
+
const sockets = new WebSocketServer({ noServer: true, maxPayload: 16 * 1024 * 1024, perMessageDeflate: false });
|
|
31
|
+
const abort = new AbortController();
|
|
32
|
+
let backend, socket, bridge, lines, remoteTask, closeTask, closing = false, used = false;
|
|
33
|
+
|
|
34
|
+
const sendBackend = (message) => {
|
|
35
|
+
if (!backend || backend.stdin.destroyed || backend.stdin.writableEnded) throw new Error("App-server disconnected");
|
|
36
|
+
if (backend.stdin.writableLength > 16 * 1024 * 1024) throw new Error("App-server queue full");
|
|
37
|
+
backend.stdin.write(`${JSON.stringify(message)}\n`);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const fail = () => {
|
|
41
|
+
if (closing) return;
|
|
42
|
+
warn("Codex connection closed. Restart `backeer-codex start` to reconnect.");
|
|
43
|
+
onFatal();
|
|
44
|
+
void close();
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
async function runRemote() {
|
|
48
|
+
let retryMs = 500;
|
|
49
|
+
let warned = false;
|
|
50
|
+
while (!abort.signal.aborted) {
|
|
51
|
+
try {
|
|
52
|
+
await subscribe(config, { signal: abort.signal, onCommand: (command) => bridge.handleCommand(command) });
|
|
53
|
+
} catch {
|
|
54
|
+
if (!abort.signal.aborted && !warned) {
|
|
55
|
+
warned = true;
|
|
56
|
+
warn("Backeer stream unavailable; terminal approval is still active. Retrying.");
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
await delay(retryMs, undefined, { signal: abort.signal }).catch(() => {});
|
|
60
|
+
retryMs = Math.min(retryMs * 2, 5000);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
server.on("upgrade", (request, connection, head) => {
|
|
65
|
+
const supplied = Buffer.from(request.headers.authorization || "");
|
|
66
|
+
const expected = Buffer.from(`Bearer ${token}`);
|
|
67
|
+
if (closing || used || request.headers.origin || supplied.length !== expected.length ||
|
|
68
|
+
!crypto.timingSafeEqual(supplied, expected)) {
|
|
69
|
+
connection.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
used = true;
|
|
73
|
+
sockets.handleUpgrade(request, connection, head, (ws) => sockets.emit("connection", ws));
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
sockets.on("connection", (ws) => {
|
|
77
|
+
socket = ws;
|
|
78
|
+
try { backend = spawnBackend(); } catch { fail(); return; }
|
|
79
|
+
bridge = new ApprovalBridge({ config, sendBackend, publish, acknowledge, warn });
|
|
80
|
+
backend.on("error", fail);
|
|
81
|
+
backend.on("exit", fail);
|
|
82
|
+
backend.stdin.on("error", fail);
|
|
83
|
+
ws.on("error", fail);
|
|
84
|
+
ws.on("close", (code) => { if (code === 1000 || code === 1001) void close(); else fail(); });
|
|
85
|
+
lines = readline.createInterface({ input: backend.stdout });
|
|
86
|
+
lines.on("line", (line) => {
|
|
87
|
+
try {
|
|
88
|
+
const message = JSON.parse(line);
|
|
89
|
+
bridge.observeServer(message);
|
|
90
|
+
if (ws.bufferedAmount > 16 * 1024 * 1024) throw new Error("Terminal queue full");
|
|
91
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
|
|
92
|
+
} catch { fail(); }
|
|
93
|
+
});
|
|
94
|
+
ws.on("message", (data, binary) => {
|
|
95
|
+
try {
|
|
96
|
+
if (binary) throw new Error("Expected JSON text");
|
|
97
|
+
const message = JSON.parse(data.toString());
|
|
98
|
+
// The proxy itself consumes these lifecycle notifications, even if a
|
|
99
|
+
// particular terminal version does not need them for rendering.
|
|
100
|
+
const capabilities = message.method === "initialize" ? message.params?.capabilities : null;
|
|
101
|
+
if (Array.isArray(capabilities?.optOutNotificationMethods)) {
|
|
102
|
+
capabilities.optOutNotificationMethods = capabilities.optOutNotificationMethods
|
|
103
|
+
.filter((method) => !REQUIRED_NOTIFICATIONS.has(method));
|
|
104
|
+
}
|
|
105
|
+
if (bridge.forwardLocal(message)) sendBackend(message);
|
|
106
|
+
} catch { fail(); }
|
|
107
|
+
});
|
|
108
|
+
if (config.ingestToken) remoteTask = runRemote();
|
|
109
|
+
else warn("No Backeer source token configured; only terminal approval is active.");
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
function close() {
|
|
113
|
+
if (closeTask) return closeTask;
|
|
114
|
+
closing = true;
|
|
115
|
+
closeTask = Promise.resolve().then(async () => {
|
|
116
|
+
abort.abort();
|
|
117
|
+
bridge?.dispose();
|
|
118
|
+
lines?.close();
|
|
119
|
+
socket?.terminate();
|
|
120
|
+
backend?.stdin.end();
|
|
121
|
+
let backendClosed;
|
|
122
|
+
if (backend?.pid && backend.exitCode === null && backend.signalCode === null) {
|
|
123
|
+
backendClosed = new Promise((resolve) => backend.once("exit", resolve));
|
|
124
|
+
backend.kill("SIGTERM");
|
|
125
|
+
const kill = setTimeout(() => backend.kill("SIGKILL"), 1500);
|
|
126
|
+
kill.unref();
|
|
127
|
+
backend.once("exit", () => clearTimeout(kill));
|
|
128
|
+
}
|
|
129
|
+
sockets.close();
|
|
130
|
+
if (server.listening) {
|
|
131
|
+
await new Promise((resolve) => {
|
|
132
|
+
server.close(resolve);
|
|
133
|
+
server.closeIdleConnections?.();
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
await Promise.all([remoteTask, backendClosed]);
|
|
137
|
+
});
|
|
138
|
+
return closeTask;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
try {
|
|
142
|
+
await new Promise((resolve, reject) => {
|
|
143
|
+
server.once("error", reject);
|
|
144
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
145
|
+
});
|
|
146
|
+
} catch (error) { await close(); throw error; }
|
|
147
|
+
return { url: `ws://127.0.0.1:${server.address().port}`, token, close };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export async function startCompanion(args = []) {
|
|
151
|
+
if (args[0] === "--") args = args.slice(1);
|
|
152
|
+
if (args.some((arg) => arg === "--remote" || arg.startsWith("--remote=") ||
|
|
153
|
+
arg === "--remote-auth-token-env" || arg.startsWith("--remote-auth-token-env="))) {
|
|
154
|
+
throw new Error("The companion manages --remote itself; omit remote connection flags.");
|
|
155
|
+
}
|
|
156
|
+
if (!process.stdin.isTTY) throw new Error("Run `backeer-codex start` in an interactive terminal.");
|
|
157
|
+
const config = await loadConfig();
|
|
158
|
+
let tui;
|
|
159
|
+
const companion = await createCompanion({ config, onFatal: () => tui?.kill("SIGTERM") });
|
|
160
|
+
const stop = () => { tui?.kill("SIGTERM"); void companion.close(); };
|
|
161
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(signal, stop);
|
|
162
|
+
try {
|
|
163
|
+
tui = spawn("codex", ["--remote", companion.url, "--remote-auth-token-env", "BACKEER_CODEX_BRIDGE_AUTH", ...args], {
|
|
164
|
+
stdio: "inherit", env: { ...process.env, BACKEER_CODEX_BRIDGE_AUTH: companion.token, BACKEER_APPROVAL_MODE: "local" },
|
|
165
|
+
});
|
|
166
|
+
const code = await new Promise((resolve, reject) => {
|
|
167
|
+
tui.once("error", reject);
|
|
168
|
+
tui.once("exit", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
|
|
169
|
+
});
|
|
170
|
+
process.exitCode = code;
|
|
171
|
+
} finally {
|
|
172
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.off(signal, stop);
|
|
173
|
+
await companion.close();
|
|
174
|
+
}
|
|
175
|
+
}
|
package/src/config.mjs
CHANGED
|
@@ -35,6 +35,7 @@ export async function loadConfig(env = process.env) {
|
|
|
35
35
|
return {
|
|
36
36
|
gatewayUrl: normalizeGatewayURL(env.BACKEER_GATEWAY_URL || stored.gatewayUrl),
|
|
37
37
|
ingestToken: String(env.BACKEER_INGEST_TOKEN || stored.ingestToken || "").trim(),
|
|
38
|
+
approvalMode: (env.BACKEER_APPROVAL_MODE || stored.approvalMode) === "remote" ? "remote" : "local",
|
|
38
39
|
permissionTimeoutMs: Math.min(Math.max(Number(stored.permissionTimeoutMs) || 110000, 5000), 120000),
|
|
39
40
|
notifyCompletion: stored.notifyCompletion !== false,
|
|
40
41
|
notifyToolFailures: stored.notifyToolFailures === true,
|
|
@@ -48,6 +49,7 @@ export async function saveConfig(values, env = process.env) {
|
|
|
48
49
|
const next = {
|
|
49
50
|
gatewayUrl: normalizeGatewayURL(values.gatewayUrl ?? current.gatewayUrl),
|
|
50
51
|
ingestToken: String(values.ingestToken ?? current.ingestToken ?? "").trim(),
|
|
52
|
+
approvalMode: values.approvalMode ?? current.approvalMode ?? "local",
|
|
51
53
|
permissionTimeoutMs: values.permissionTimeoutMs ?? current.permissionTimeoutMs,
|
|
52
54
|
notifyCompletion: values.notifyCompletion ?? current.notifyCompletion,
|
|
53
55
|
notifyToolFailures: values.notifyToolFailures ?? current.notifyToolFailures,
|
package/src/gateway.mjs
CHANGED
|
@@ -59,6 +59,34 @@ function parseSSEBlock(block) {
|
|
|
59
59
|
try { return JSON.parse(fields.data); } catch { return null; }
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
// One cancellable subscription for all approvals in a companion session.
|
|
63
|
+
export async function streamPermissionCommands(config, { signal, onCommand }) {
|
|
64
|
+
const response = await fetch(`${config.gatewayUrl}/v1/commands/stream`, {
|
|
65
|
+
headers: { Accept: "text/event-stream", ...authorization(config.ingestToken) }, signal,
|
|
66
|
+
});
|
|
67
|
+
if (!response.ok || !response.body) throw new Error("Backeer command stream unavailable");
|
|
68
|
+
const reader = response.body.getReader();
|
|
69
|
+
const decoder = new TextDecoder();
|
|
70
|
+
try {
|
|
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
|
+
if (buffer.length > 1024 * 1024) throw new Error("Backeer command frame too large");
|
|
77
|
+
let match;
|
|
78
|
+
while ((match = /\r?\n\r?\n/.exec(buffer))) {
|
|
79
|
+
const command = parseSSEBlock(buffer.slice(0, match.index));
|
|
80
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
81
|
+
if (command?.type === "codex_permission_reply") await onCommand(command);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
} finally {
|
|
85
|
+
await reader.cancel().catch(() => {});
|
|
86
|
+
reader.releaseLock();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
62
90
|
export async function waitForPermissionCommand(config, externalId) {
|
|
63
91
|
const controller = new AbortController();
|
|
64
92
|
const timeout = setTimeout(() => controller.abort(), config.permissionTimeoutMs);
|
package/src/hook-handlers.mjs
CHANGED
|
@@ -37,6 +37,9 @@ function correlation(input) {
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
async function handlePermissionRequest(input, config, env) {
|
|
40
|
+
// Native approval must not depend on the gateway or old remote session policies.
|
|
41
|
+
// Only an explicit opt-in may intercept Codex's local approval flow.
|
|
42
|
+
if (config.approvalMode !== "remote") return EMPTY_OUTPUT;
|
|
40
43
|
const sessionId = String(input.session_id || "").trim();
|
|
41
44
|
const turnId = String(input.turn_id || "").trim();
|
|
42
45
|
const toolName = String(input.tool_name || "").trim();
|
|
@@ -77,7 +80,12 @@ async function handlePermissionRequest(input, config, env) {
|
|
|
77
80
|
: "invalid_decision").catch(() => {});
|
|
78
81
|
return EMPTY_OUTPUT;
|
|
79
82
|
}
|
|
80
|
-
|
|
83
|
+
const expiresAt = typeof command.expiresAt === "string" ? Date.parse(command.expiresAt) : NaN;
|
|
84
|
+
if (!Number.isFinite(expiresAt)) {
|
|
85
|
+
await acknowledgeCommand(config, command, "rejected", "invalid_expiration").catch(() => {});
|
|
86
|
+
return EMPTY_OUTPUT;
|
|
87
|
+
}
|
|
88
|
+
if (expiresAt <= Date.now()) {
|
|
81
89
|
await acknowledgeCommand(config, command, "expired").catch(() => {});
|
|
82
90
|
return EMPTY_OUTPUT;
|
|
83
91
|
}
|
package/src/installer.mjs
CHANGED
|
@@ -3,9 +3,11 @@ import os from "node:os";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { spawn } from "node:child_process";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { createRequire } from "node:module";
|
|
6
7
|
|
|
7
8
|
const PLUGIN_NAME = "backeer-codex";
|
|
8
9
|
const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
10
|
+
const require = createRequire(import.meta.url);
|
|
9
11
|
|
|
10
12
|
function personalPaths(homeDirectory = os.homedir()) {
|
|
11
13
|
return {
|
|
@@ -71,7 +73,7 @@ async function copyPlugin(source, destination) {
|
|
|
71
73
|
filter(candidate) {
|
|
72
74
|
const relative = path.relative(source, candidate);
|
|
73
75
|
const firstPart = relative.split(path.sep)[0];
|
|
74
|
-
return !["node_modules", ".git", ".DS_Store"].includes(firstPart);
|
|
76
|
+
return !["node_modules", ".git", ".codebase-memory", ".DS_Store"].includes(firstPart);
|
|
75
77
|
}
|
|
76
78
|
});
|
|
77
79
|
}
|
|
@@ -98,6 +100,13 @@ function runCodexInstall(marketplaceName) {
|
|
|
98
100
|
export async function installPlugin(options = {}) {
|
|
99
101
|
const paths = personalPaths(options.homeDirectory);
|
|
100
102
|
await copyPlugin(options.packageRoot || PACKAGE_ROOT, paths.pluginDirectory);
|
|
103
|
+
// Codex loads a copied plugin outside npm's global package directory. Its
|
|
104
|
+
// companion therefore needs its own runtime dependency, not just source files.
|
|
105
|
+
const wsRoot = path.dirname(require.resolve("ws/package.json"));
|
|
106
|
+
const wsDestination = path.join(paths.pluginDirectory, "node_modules", "ws");
|
|
107
|
+
if (path.resolve(wsRoot) !== path.resolve(wsDestination)) {
|
|
108
|
+
await fs.cp(wsRoot, wsDestination, { recursive: true, force: true });
|
|
109
|
+
}
|
|
101
110
|
const marketplaceName = await writeMarketplace(paths.marketplaceFile, await readMarketplace(paths.marketplaceFile));
|
|
102
111
|
if (options.installWithCodex !== false) await runCodexInstall(marketplaceName);
|
|
103
112
|
return { ...paths, marketplaceName };
|