backeer-codex 0.1.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.
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "backeer-codex",
3
+ "version": "0.1.0",
4
+ "description": "Approve Codex permission requests from Backeer and receive task lifecycle notifications.",
5
+ "author": {
6
+ "name": "Backeer"
7
+ },
8
+ "license": "LicenseRef-Backeer-Proprietary",
9
+ "keywords": [
10
+ "backeer",
11
+ "codex",
12
+ "notifications",
13
+ "permissions"
14
+ ],
15
+ "skills": "./skills/",
16
+ "interface": {
17
+ "displayName": "Backeer Codex",
18
+ "shortDescription": "Remote Codex approvals and lifecycle alerts.",
19
+ "longDescription": "Backeer Codex securely forwards approval requests and task completion events to Backeer without exposing source credentials to the iOS application.",
20
+ "developerName": "Backeer",
21
+ "category": "Productivity",
22
+ "capabilities": [
23
+ "Interactive",
24
+ "Notifications"
25
+ ],
26
+ "defaultPrompt": [
27
+ "Check the Backeer Codex connection.",
28
+ "Send a Backeer test notification.",
29
+ "Update my Backeer source token."
30
+ ],
31
+ "brandColor": "#2F80ED"
32
+ }
33
+ }
package/LICENSE ADDED
@@ -0,0 +1,10 @@
1
+ Copyright (c) 2026 Backeer. All rights reserved.
2
+
3
+ This software and its source code are proprietary. You may install and use an
4
+ unmodified copy solely to integrate Codex with the Backeer service. You may not
5
+ modify, adapt, redistribute, sublicense, sell, publish, reverse engineer, or
6
+ create derivative works without prior written permission from Backeer.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9
+ IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS
10
+ FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
package/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # Backeer Codex
2
+
3
+ `backeer-codex` is a separate Codex plugin. It does not modify or replace the `backeer-opencode` package.
4
+
5
+ It provides:
6
+
7
+ - Backeer approval actions for Codex `PermissionRequest` hooks: Allow once, Always allow, and Reject.
8
+ - Session-scoped exact-match policies for Always allow. Policies are deleted when the Codex session ends.
9
+ - Task-completion notifications through the Codex `Stop` hook.
10
+ - Optional failed-tool notifications (disabled by default).
11
+ - `status`, `doctor`, `test`, and interactive token configuration commands.
12
+ - Safe fallback to the normal Codex permission prompt when Backeer is unavailable or not configured.
13
+
14
+ ## Configure
15
+
16
+ Install the published package and register it in the default Codex personal marketplace:
17
+
18
+ ```sh
19
+ npm install --global backeer-codex
20
+ backeer-codex install
21
+ ```
22
+
23
+ Then configure the source credential and verify the connection:
24
+
25
+ ```sh
26
+ backeer-codex configure
27
+ backeer-codex doctor
28
+ backeer-codex test
29
+ ```
30
+
31
+ The source token is stored in `~/.config/backeer-codex/config.json` with mode `0600`. `BACKEER_INGEST_TOKEN` and `BACKEER_GATEWAY_URL` environment variables override the file without being written to disk.
32
+
33
+ After enabling or updating the plugin, use `/hooks` in Codex to review and trust the Backeer hook definition.
34
+
35
+ ## Privacy and security
36
+
37
+ 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
+
39
+ Codex plan-mode user questions are not exposed to lifecycle hooks. Remote answers for native Codex questions require a future App Server companion; this first plugin deliberately does not emulate or scrape that UI.
@@ -0,0 +1,54 @@
1
+ {
2
+ "description": "Backeer remote approvals and lifecycle notifications for Codex.",
3
+ "hooks": {
4
+ "PermissionRequest": [
5
+ {
6
+ "matcher": "*",
7
+ "hooks": [
8
+ {
9
+ "type": "command",
10
+ "command": "node \"$PLUGIN_ROOT/scripts/hook.mjs\"",
11
+ "timeout": 125,
12
+ "statusMessage": "Waiting for Backeer approval"
13
+ }
14
+ ]
15
+ }
16
+ ],
17
+ "Stop": [
18
+ {
19
+ "hooks": [
20
+ {
21
+ "type": "command",
22
+ "command": "node \"$PLUGIN_ROOT/scripts/hook.mjs\"",
23
+ "async": true,
24
+ "timeout": 20
25
+ }
26
+ ]
27
+ }
28
+ ],
29
+ "PostToolUse": [
30
+ {
31
+ "matcher": "Bash|apply_patch",
32
+ "hooks": [
33
+ {
34
+ "type": "command",
35
+ "command": "node \"$PLUGIN_ROOT/scripts/hook.mjs\"",
36
+ "async": true,
37
+ "timeout": 20
38
+ }
39
+ ]
40
+ }
41
+ ],
42
+ "SessionEnd": [
43
+ {
44
+ "hooks": [
45
+ {
46
+ "type": "command",
47
+ "command": "node \"$PLUGIN_ROOT/scripts/hook.mjs\"",
48
+ "timeout": 3
49
+ }
50
+ ]
51
+ }
52
+ ]
53
+ }
54
+ }
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "backeer-codex",
3
+ "version": "0.1.0",
4
+ "description": "Backeer lifecycle and permission hooks for Codex",
5
+ "type": "module",
6
+ "license": "SEE LICENSE IN LICENSE",
7
+ "keywords": [
8
+ "backeer",
9
+ "codex",
10
+ "notifications",
11
+ "permissions",
12
+ "hooks"
13
+ ],
14
+ "files": [
15
+ ".codex-plugin/",
16
+ "hooks/",
17
+ "scripts/",
18
+ "skills/",
19
+ "src/",
20
+ "LICENSE",
21
+ "README.md"
22
+ ],
23
+ "engines": {
24
+ "node": ">=18"
25
+ },
26
+ "bin": {
27
+ "backeer-codex": "./scripts/backeer-codex.mjs"
28
+ },
29
+ "scripts": {
30
+ "test": "node --test",
31
+ "check": "node --check scripts/hook.mjs && node --check scripts/backeer-codex.mjs"
32
+ }
33
+ }
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { runCLI } from "../src/cli.mjs";
3
+
4
+ try {
5
+ await runCLI(process.argv.slice(2));
6
+ } catch (error) {
7
+ process.stderr.write(`Backeer Codex: ${error.message}\n`);
8
+ process.exitCode = 1;
9
+ }
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import { handleHook } from "../src/hook-handlers.mjs";
3
+
4
+ async function readInput() {
5
+ let body = "";
6
+ for await (const chunk of process.stdin) body += chunk;
7
+ return body.trim() ? JSON.parse(body) : {};
8
+ }
9
+
10
+ try {
11
+ const output = await handleHook(await readInput());
12
+ process.stdout.write(`${JSON.stringify(output ?? {})}\n`);
13
+ } catch {
14
+ // Fail open: an unavailable Backeer service must never strand a Codex session.
15
+ // Empty output delegates the decision to Codex's normal local approval UI.
16
+ process.stdout.write("{}\n");
17
+ }
@@ -0,0 +1,19 @@
1
+ ---
2
+ name: backeer
3
+ description: Configure and diagnose the Backeer Codex plugin, rotate its source token, inspect status, or send a test notification. Use when the user asks about Backeer in Codex, Backeer status, doctor, token changes, or notification tests.
4
+ ---
5
+
6
+ # Backeer Codex management
7
+
8
+ Use the plugin's bundled management script. Resolve it with `$PLUGIN_ROOT` when that variable is available; otherwise locate the enabled `backeer-codex` plugin root and run `node <plugin-root>/scripts/backeer-codex.mjs`.
9
+
10
+ Commands:
11
+
12
+ - `status`: show the gateway, masked credential status, and notification settings.
13
+ - `doctor`: validate Node.js, protected config permissions, source authentication, and command-stream capability.
14
+ - `test`: send a normal Backeer test notification.
15
+ - `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.
16
+
17
+ After installing or updating the plugin, remind the user to open `/hooks` once and trust the current Backeer hook definition. Changed hook definitions require a new trust review.
18
+
19
+ Never read or print the unmasked token. Never copy it into a repository, `AGENTS.md`, an APNs payload, or a Codex response.
package/src/cli.mjs ADDED
@@ -0,0 +1,135 @@
1
+ import fs from "node:fs/promises";
2
+ import crypto from "node:crypto";
3
+ import readline from "node:readline/promises";
4
+ import { stdin as input, stdout as output } from "node:process";
5
+ import { configDirectory, loadConfig, maskedToken, saveConfig } from "./config.mjs";
6
+ import { publishEvent, sourceHealth } from "./gateway.mjs";
7
+ import { installPlugin } from "./installer.mjs";
8
+
9
+ async function prompt(label, fallback = "") {
10
+ const terminal = readline.createInterface({ input, output });
11
+ try {
12
+ const suffix = fallback ? ` [${fallback}]` : "";
13
+ return (await terminal.question(`${label}${suffix}: `)).trim() || fallback;
14
+ } finally {
15
+ terminal.close();
16
+ }
17
+ }
18
+
19
+ async function readToken() {
20
+ if (!input.isTTY || !input.setRawMode) return prompt("Backeer source token");
21
+ output.write("Backeer source token: ");
22
+ input.setRawMode(true);
23
+ input.resume();
24
+ input.setEncoding("utf8");
25
+ let token = "";
26
+ try {
27
+ for await (const chunk of input) {
28
+ for (const character of chunk) {
29
+ if (character === "\r" || character === "\n") {
30
+ output.write("\n");
31
+ return token.trim();
32
+ }
33
+ if (character === "\u0003") throw new Error("Cancelled");
34
+ if (character === "\u007f") {
35
+ if (token) { token = token.slice(0, -1); output.write("\b \b"); }
36
+ } else {
37
+ token += character;
38
+ output.write("•");
39
+ }
40
+ }
41
+ }
42
+ } finally {
43
+ input.setRawMode(false);
44
+ input.pause();
45
+ }
46
+ return token.trim();
47
+ }
48
+
49
+ async function configure() {
50
+ const current = await loadConfig();
51
+ const gatewayUrl = await prompt("Backeer gateway URL", current.gatewayUrl);
52
+ const ingestToken = await readToken();
53
+ if (!ingestToken && !current.ingestToken) throw new Error("A source token is required");
54
+ const saved = await saveConfig({ gatewayUrl, ingestToken: ingestToken || current.ingestToken });
55
+ const health = await sourceHealth(saved);
56
+ output.write(`Configured ${health.source.name} (${health.source.id}).\n`);
57
+ }
58
+
59
+ async function configureFromFile(file) {
60
+ if (!file) throw new Error("A token file path is required");
61
+ const contents = await fs.readFile(file, "utf8");
62
+ const token = contents.match(/\bbgi_[a-f0-9]{48}\b/i)?.[0];
63
+ if (!token) throw new Error("Token file does not contain a Backeer source token");
64
+ const saved = await saveConfig({ ingestToken: token });
65
+ const health = await sourceHealth(saved);
66
+ await fs.rm(file, { force: true });
67
+ output.write(`Configured ${health.source.name} (${health.source.id}).\n`);
68
+ }
69
+
70
+ async function status() {
71
+ const config = await loadConfig();
72
+ output.write(`Gateway: ${config.gatewayUrl}\n`);
73
+ output.write(`Token: ${maskedToken(config.ingestToken)}\n`);
74
+ output.write(`Config: ${configDirectory()}\n`);
75
+ output.write(`Completion notifications: ${config.notifyCompletion ? "on" : "off"}\n`);
76
+ output.write(`Tool failure notifications: ${config.notifyToolFailures ? "on" : "off"}\n`);
77
+ }
78
+
79
+ async function doctor() {
80
+ const config = await loadConfig();
81
+ const checks = [];
82
+ checks.push(["Node.js", Number(process.versions.node.split(".")[0]) >= 18, process.versions.node]);
83
+ checks.push(["Source token", Boolean(config.ingestToken), maskedToken(config.ingestToken)]);
84
+ try {
85
+ const stat = await fs.stat(`${configDirectory()}/config.json`);
86
+ checks.push(["Config permissions", (stat.mode & 0o077) === 0, `0${(stat.mode & 0o777).toString(8)}`]);
87
+ } catch {
88
+ checks.push(["Config permissions", false, "config missing"]);
89
+ }
90
+ try {
91
+ const health = await sourceHealth(config);
92
+ checks.push(["Gateway", true, `${health.source.name} (${health.source.id})`]);
93
+ checks.push(["Command stream", health.capabilities?.commands === true, "available"]);
94
+ } catch (error) {
95
+ checks.push(["Gateway", false, error.message]);
96
+ }
97
+ for (const [name, ok, detail] of checks) output.write(`${ok ? "✓" : "✗"} ${name}: ${detail}\n`);
98
+ if (checks.some(([, ok]) => !ok)) process.exitCode = 1;
99
+ }
100
+
101
+ async function testNotification() {
102
+ const config = await loadConfig();
103
+ if (!config.ingestToken) throw new Error("Run `backeer-codex configure` first");
104
+ const result = await publishEvent(config, {
105
+ type: "application",
106
+ severity: "info",
107
+ title: "Backeer Codex test",
108
+ body: "The Codex plugin can reach Backeer and send notifications.",
109
+ payload: [
110
+ { key: "Agent", value: "Codex" },
111
+ { key: "Test", value: "Notification" }
112
+ ],
113
+ externalId: `codex-test:${crypto.randomUUID()}`,
114
+ notify: true,
115
+ direction: "in"
116
+ });
117
+ output.write(`Test notification sent (${result.id}).\n`);
118
+ }
119
+
120
+ async function install() {
121
+ const result = await installPlugin();
122
+ output.write(`Installed Backeer Codex in ${result.pluginDirectory}.\n`);
123
+ output.write("Next: run `backeer-codex configure`, then open a new Codex session and trust it in `/hooks`.\n");
124
+ }
125
+
126
+ export async function runCLI(args) {
127
+ const command = args[0] || "status";
128
+ if (command === "install") return install();
129
+ if (["configure", "token"].includes(command)) return configure();
130
+ if (command === "configure-file") return configureFromFile(args[1]);
131
+ if (command === "status") return status();
132
+ if (command === "doctor") return doctor();
133
+ if (command === "test") return testNotification();
134
+ throw new Error("Usage: backeer-codex [install|configure|status|doctor|test]");
135
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,67 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ export const DEFAULT_GATEWAY_URL = "https://external-gateway.backeer.com";
6
+
7
+ export function configDirectory(env = process.env) {
8
+ if (env.BACKEER_CODEX_CONFIG_DIR) return path.resolve(env.BACKEER_CODEX_CONFIG_DIR);
9
+ const base = env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
10
+ return path.join(base, "backeer-codex");
11
+ }
12
+
13
+ export function dataDirectory(env = process.env) {
14
+ return env.PLUGIN_DATA ? path.resolve(env.PLUGIN_DATA) : path.join(configDirectory(env), "data");
15
+ }
16
+
17
+ export function normalizeGatewayURL(value) {
18
+ const url = new URL(String(value || DEFAULT_GATEWAY_URL));
19
+ if (url.protocol !== "https:" && !["localhost", "127.0.0.1", "::1"].includes(url.hostname)) {
20
+ throw new Error("Gateway URL must use HTTPS");
21
+ }
22
+ url.pathname = url.pathname.replace(/\/(v1(?:\/.*)?)?\/?$/, "");
23
+ url.search = "";
24
+ url.hash = "";
25
+ return url.toString().replace(/\/$/, "");
26
+ }
27
+
28
+ export async function loadConfig(env = process.env) {
29
+ let stored = {};
30
+ try {
31
+ stored = JSON.parse(await fs.readFile(path.join(configDirectory(env), "config.json"), "utf8"));
32
+ } catch (error) {
33
+ if (error?.code !== "ENOENT") throw new Error("Backeer config is not valid JSON");
34
+ }
35
+ return {
36
+ gatewayUrl: normalizeGatewayURL(env.BACKEER_GATEWAY_URL || stored.gatewayUrl),
37
+ ingestToken: String(env.BACKEER_INGEST_TOKEN || stored.ingestToken || "").trim(),
38
+ permissionTimeoutMs: Math.min(Math.max(Number(stored.permissionTimeoutMs) || 110000, 5000), 120000),
39
+ notifyCompletion: stored.notifyCompletion !== false,
40
+ notifyToolFailures: stored.notifyToolFailures === true,
41
+ };
42
+ }
43
+
44
+ export async function saveConfig(values, env = process.env) {
45
+ const directory = configDirectory(env);
46
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
47
+ const current = await loadConfig(env).catch(() => ({ gatewayUrl: DEFAULT_GATEWAY_URL }));
48
+ const next = {
49
+ gatewayUrl: normalizeGatewayURL(values.gatewayUrl ?? current.gatewayUrl),
50
+ ingestToken: String(values.ingestToken ?? current.ingestToken ?? "").trim(),
51
+ permissionTimeoutMs: values.permissionTimeoutMs ?? current.permissionTimeoutMs,
52
+ notifyCompletion: values.notifyCompletion ?? current.notifyCompletion,
53
+ notifyToolFailures: values.notifyToolFailures ?? current.notifyToolFailures,
54
+ };
55
+ const file = path.join(directory, "config.json");
56
+ const temporary = path.join(directory, `config.${process.pid}.tmp`);
57
+ await fs.writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
58
+ await fs.chmod(temporary, 0o600);
59
+ await fs.rename(temporary, file);
60
+ await fs.chmod(file, 0o600);
61
+ return next;
62
+ }
63
+
64
+ export function maskedToken(token) {
65
+ if (!token) return "not configured";
66
+ return token.length < 10 ? "configured" : `${token.slice(0, 5)}…${token.slice(-4)}`;
67
+ }
@@ -0,0 +1,102 @@
1
+ const JSON_HEADERS = { "Content-Type": "application/json", Accept: "application/json" };
2
+
3
+ function authorization(token) {
4
+ return { Authorization: `Bearer ${token}` };
5
+ }
6
+
7
+ async function responseJSON(response) {
8
+ const text = await response.text();
9
+ if (!response.ok) throw new Error(`Backeer returned HTTP ${response.status}`);
10
+ return text ? JSON.parse(text) : {};
11
+ }
12
+
13
+ export async function publishEvent(config, event) {
14
+ const response = await fetch(`${config.gatewayUrl}/v1/events`, {
15
+ method: "POST",
16
+ headers: { ...JSON_HEADERS, ...authorization(config.ingestToken) },
17
+ body: JSON.stringify(event),
18
+ signal: AbortSignal.timeout(10000),
19
+ });
20
+ return responseJSON(response);
21
+ }
22
+
23
+ export async function sourceHealth(config) {
24
+ const response = await fetch(`${config.gatewayUrl}/v1/source/health`, {
25
+ headers: { Accept: "application/json", ...authorization(config.ingestToken) },
26
+ signal: AbortSignal.timeout(10000),
27
+ });
28
+ return responseJSON(response);
29
+ }
30
+
31
+ export async function acknowledgeCommand(config, command, status, errorCode = null) {
32
+ const body = {
33
+ type: "codex_permission_reply_ack",
34
+ externalId: command.externalId,
35
+ status,
36
+ decision: command.decision,
37
+ processedAt: new Date().toISOString(),
38
+ ...(errorCode ? { errorCode } : {}),
39
+ };
40
+ const response = await fetch(`${config.gatewayUrl}/v1/commands/${encodeURIComponent(command.id)}/ack`, {
41
+ method: "POST",
42
+ headers: { ...JSON_HEADERS, ...authorization(config.ingestToken) },
43
+ body: JSON.stringify(body),
44
+ signal: AbortSignal.timeout(10000),
45
+ });
46
+ return responseJSON(response);
47
+ }
48
+
49
+ function parseSSEBlock(block) {
50
+ const fields = {};
51
+ for (const line of block.split(/\r?\n/)) {
52
+ if (!line || line.startsWith(":")) continue;
53
+ const separator = line.indexOf(":");
54
+ const key = separator < 0 ? line : line.slice(0, separator);
55
+ const value = separator < 0 ? "" : line.slice(separator + 1).replace(/^ /, "");
56
+ fields[key] = fields[key] ? `${fields[key]}\n${value}` : value;
57
+ }
58
+ if (fields.event !== "command" || !fields.data) return null;
59
+ try { return JSON.parse(fields.data); } catch { return null; }
60
+ }
61
+
62
+ export async function waitForPermissionCommand(config, externalId) {
63
+ const controller = new AbortController();
64
+ const timeout = setTimeout(() => controller.abort(), config.permissionTimeoutMs);
65
+ let streamFinished = false;
66
+ try {
67
+ const response = await fetch(`${config.gatewayUrl}/v1/commands/stream`, {
68
+ headers: { Accept: "text/event-stream", ...authorization(config.ingestToken) },
69
+ signal: controller.signal,
70
+ });
71
+ if (!response.ok || !response.body) throw new Error(`Backeer command stream returned HTTP ${response.status}`);
72
+ const reader = response.body.getReader();
73
+ const decoder = new TextDecoder();
74
+ let buffer = "";
75
+ while (true) {
76
+ const { done, value } = await reader.read();
77
+ if (done) {
78
+ streamFinished = true;
79
+ return null;
80
+ }
81
+ buffer += decoder.decode(value, { stream: true });
82
+ let boundary;
83
+ while ((boundary = buffer.search(/\r?\n\r?\n/)) >= 0) {
84
+ const delimiter = buffer.slice(boundary).match(/^\r?\n\r?\n/)?.[0] ?? "\n\n";
85
+ const block = buffer.slice(0, boundary);
86
+ buffer = buffer.slice(boundary + delimiter.length);
87
+ const command = parseSSEBlock(block);
88
+ if (command?.type === "codex_permission_reply" && command.externalId === externalId) {
89
+ await reader.cancel().catch(() => {});
90
+ streamFinished = true;
91
+ return command;
92
+ }
93
+ }
94
+ }
95
+ } catch (error) {
96
+ if (error?.name === "AbortError" || error?.name === "TimeoutError") return null;
97
+ throw error;
98
+ } finally {
99
+ clearTimeout(timeout);
100
+ if (!streamFinished) controller.abort();
101
+ }
102
+ }
@@ -0,0 +1,156 @@
1
+ import { loadConfig } from "./config.mjs";
2
+ import { acknowledgeCommand, publishEvent, waitForPermissionCommand } from "./gateway.mjs";
3
+ import { clearSessionPolicies, hasSessionPolicy, rememberSessionPolicy } from "./policy-store.mjs";
4
+ import { compactText, digest, permissionFingerprint, permissionSummary, workspaceLabel } from "./privacy.mjs";
5
+
6
+ const EMPTY_OUTPUT = {};
7
+ const DECISIONS = new Set(["once", "always", "reject"]);
8
+
9
+ function permissionOutput(decision) {
10
+ if (decision === "reject") {
11
+ return {
12
+ hookSpecificOutput: {
13
+ hookEventName: "PermissionRequest",
14
+ decision: { behavior: "deny", message: "Rejected from Backeer." },
15
+ },
16
+ };
17
+ }
18
+ return {
19
+ hookSpecificOutput: {
20
+ hookEventName: "PermissionRequest",
21
+ decision: { behavior: "allow" },
22
+ },
23
+ };
24
+ }
25
+
26
+ function correlation(input) {
27
+ const request = digest(JSON.stringify({
28
+ session: input.session_id,
29
+ turn: input.turn_id,
30
+ tool: input.tool_name,
31
+ toolInput: input.tool_input,
32
+ }), 32);
33
+ return {
34
+ request,
35
+ externalId: `codex:${digest(input.session_id, 16)}:${request}`,
36
+ };
37
+ }
38
+
39
+ async function handlePermissionRequest(input, config, env) {
40
+ const sessionId = String(input.session_id || "").trim();
41
+ const turnId = String(input.turn_id || "").trim();
42
+ const toolName = String(input.tool_name || "").trim();
43
+ if (!sessionId || !turnId || !toolName) return EMPTY_OUTPUT;
44
+
45
+ const fingerprint = permissionFingerprint(input);
46
+ if (await hasSessionPolicy(sessionId, fingerprint, env)) return permissionOutput("always");
47
+ if (!config.ingestToken) return EMPTY_OUTPUT;
48
+
49
+ const { request, externalId } = correlation(input);
50
+ const summary = permissionSummary(input.tool_input);
51
+ const created = await publishEvent(config, {
52
+ type: "application",
53
+ severity: "warning",
54
+ title: `Codex permission required: ${compactText(toolName, 120)}`,
55
+ body: summary || "Codex is waiting for approval.",
56
+ payload: [
57
+ { key: "Permission", value: toolName },
58
+ { key: "Session", value: sessionId },
59
+ { key: "Turn ID", value: turnId },
60
+ { key: "Request ID", value: request },
61
+ { key: "Patterns", value: summary || "Requested operation" },
62
+ { key: "Workspace", value: workspaceLabel(input.cwd) },
63
+ { key: "Action protocol", value: "codex-permission/v1" },
64
+ { key: "Available decisions", value: "once, always, reject" }
65
+ ],
66
+ externalId,
67
+ notify: true,
68
+ direction: "in"
69
+ });
70
+ if (!created?.id) return EMPTY_OUTPUT;
71
+
72
+ const command = await waitForPermissionCommand(config, externalId);
73
+ if (!command) return EMPTY_OUTPUT;
74
+ if (!DECISIONS.has(command.decision) || (command.decision === "always" && command.confirmed !== true)) {
75
+ await acknowledgeCommand(config, command, "rejected", command.decision === "always"
76
+ ? "confirmation_required"
77
+ : "invalid_decision").catch(() => {});
78
+ return EMPTY_OUTPUT;
79
+ }
80
+ if (new Date(command.expiresAt).getTime() <= Date.now()) {
81
+ await acknowledgeCommand(config, command, "expired").catch(() => {});
82
+ return EMPTY_OUTPUT;
83
+ }
84
+
85
+ if (command.decision === "always") await rememberSessionPolicy(sessionId, fingerprint, env);
86
+ try {
87
+ await acknowledgeCommand(config, command, "applied");
88
+ } catch {
89
+ // The approval can still be applied safely. Gateway delivery is at-least-once and
90
+ // the stable command will expire if its ACK was lost.
91
+ }
92
+ return permissionOutput(command.decision);
93
+ }
94
+
95
+ async function handleStop(input, config) {
96
+ if (!config.ingestToken || !config.notifyCompletion || input.stop_hook_active === true) return EMPTY_OUTPUT;
97
+ const session = String(input.session_id || "unknown");
98
+ const turn = String(input.turn_id || digest(input.last_assistant_message || Date.now(), 16));
99
+ await publishEvent(config, {
100
+ type: "application",
101
+ severity: "info",
102
+ title: "Codex task completed",
103
+ body: `Codex finished a task in ${workspaceLabel(input.cwd)}.`,
104
+ payload: [
105
+ { key: "Agent", value: "Codex" },
106
+ { key: "Workspace", value: workspaceLabel(input.cwd) },
107
+ { key: "Model", value: compactText(input.model || "Codex", 120) },
108
+ { key: "Lifecycle event", value: "Stop" }
109
+ ],
110
+ externalId: `codex-lifecycle:${digest(session, 16)}:${digest(turn, 24)}`,
111
+ notify: true,
112
+ direction: "in"
113
+ });
114
+ return EMPTY_OUTPUT;
115
+ }
116
+
117
+ function failedToolResponse(response) {
118
+ if (!response || typeof response !== "object") return false;
119
+ return response.exit_code > 0 || response.exitCode > 0 || response.isError === true || response.is_error === true;
120
+ }
121
+
122
+ async function handlePostToolUse(input, config) {
123
+ if (!config.ingestToken || !config.notifyToolFailures || !failedToolResponse(input.tool_response)) {
124
+ return EMPTY_OUTPUT;
125
+ }
126
+ await publishEvent(config, {
127
+ type: "application",
128
+ severity: "warning",
129
+ title: `Codex tool failed: ${compactText(input.tool_name || "tool", 120)}`,
130
+ body: permissionSummary(input.tool_input) || "A Codex tool returned an error.",
131
+ payload: [
132
+ { key: "Agent", value: "Codex" },
133
+ { key: "Tool", value: compactText(input.tool_name || "tool", 120) },
134
+ { key: "Workspace", value: workspaceLabel(input.cwd) },
135
+ { key: "Lifecycle event", value: "PostToolUse" }
136
+ ],
137
+ externalId: `codex-tool:${digest(input.session_id || "unknown", 16)}:${digest(input.tool_use_id || Date.now(), 24)}`,
138
+ notify: true,
139
+ direction: "in"
140
+ });
141
+ return EMPTY_OUTPUT;
142
+ }
143
+
144
+ export async function handleHook(input, env = process.env) {
145
+ const eventName = input?.hook_event_name;
146
+ if (!eventName) return EMPTY_OUTPUT;
147
+ if (eventName === "SessionEnd") {
148
+ if (input.session_id) await clearSessionPolicies(input.session_id, env);
149
+ return EMPTY_OUTPUT;
150
+ }
151
+ const config = await loadConfig(env);
152
+ if (eventName === "PermissionRequest") return handlePermissionRequest(input, config, env);
153
+ if (eventName === "Stop") return handleStop(input, config);
154
+ if (eventName === "PostToolUse") return handlePostToolUse(input, config);
155
+ return EMPTY_OUTPUT;
156
+ }
@@ -0,0 +1,105 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { spawn } from "node:child_process";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const PLUGIN_NAME = "backeer-codex";
8
+ const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
9
+
10
+ function personalPaths(homeDirectory = os.homedir()) {
11
+ return {
12
+ pluginDirectory: path.join(homeDirectory, "plugins", PLUGIN_NAME),
13
+ marketplaceFile: path.join(homeDirectory, ".agents", "plugins", "marketplace.json")
14
+ };
15
+ }
16
+
17
+ function defaultMarketplace() {
18
+ return {
19
+ name: "personal",
20
+ interface: { displayName: "Personal" },
21
+ plugins: []
22
+ };
23
+ }
24
+
25
+ async function readMarketplace(file) {
26
+ try {
27
+ return JSON.parse(await fs.readFile(file, "utf8"));
28
+ } catch (error) {
29
+ if (error.code === "ENOENT") return defaultMarketplace();
30
+ if (error instanceof SyntaxError) throw new Error(`Invalid marketplace JSON: ${file}`);
31
+ throw error;
32
+ }
33
+ }
34
+
35
+ function backeerEntry() {
36
+ return {
37
+ name: PLUGIN_NAME,
38
+ source: { source: "local", path: `./plugins/${PLUGIN_NAME}` },
39
+ policy: { installation: "AVAILABLE", authentication: "ON_INSTALL" },
40
+ category: "Productivity"
41
+ };
42
+ }
43
+
44
+ async function writeMarketplace(file, marketplace) {
45
+ if (!/^[A-Za-z0-9_-]+$/.test(marketplace.name || "")) {
46
+ throw new Error(`Invalid personal marketplace name in ${file}`);
47
+ }
48
+ if (!Array.isArray(marketplace.plugins)) {
49
+ throw new Error(`Invalid plugins list in ${file}`);
50
+ }
51
+
52
+ const entry = backeerEntry();
53
+ const index = marketplace.plugins.findIndex((plugin) => plugin?.name === PLUGIN_NAME);
54
+ if (index === -1) marketplace.plugins.push(entry);
55
+ else marketplace.plugins[index] = entry;
56
+
57
+ marketplace.interface ||= { displayName: "Personal" };
58
+ await fs.mkdir(path.dirname(file), { recursive: true });
59
+ const temporaryFile = `${file}.${process.pid}.tmp`;
60
+ await fs.writeFile(temporaryFile, `${JSON.stringify(marketplace, null, 2)}\n`, { mode: 0o600 });
61
+ await fs.rename(temporaryFile, file);
62
+ return marketplace.name;
63
+ }
64
+
65
+ async function copyPlugin(source, destination) {
66
+ if (path.resolve(source) === path.resolve(destination)) return;
67
+ await fs.mkdir(path.dirname(destination), { recursive: true });
68
+ await fs.cp(source, destination, {
69
+ recursive: true,
70
+ force: true,
71
+ filter(candidate) {
72
+ const relative = path.relative(source, candidate);
73
+ const firstPart = relative.split(path.sep)[0];
74
+ return !["node_modules", ".git", ".DS_Store"].includes(firstPart);
75
+ }
76
+ });
77
+ }
78
+
79
+ function runCodexInstall(marketplaceName) {
80
+ return new Promise((resolve, reject) => {
81
+ const child = spawn("codex", ["plugin", "add", `${PLUGIN_NAME}@${marketplaceName}`], {
82
+ stdio: "inherit"
83
+ });
84
+ child.once("error", (error) => {
85
+ if (error.code === "ENOENT") {
86
+ reject(new Error("Codex CLI was not found. Install Codex, then rerun `backeer-codex install`."));
87
+ return;
88
+ }
89
+ reject(error);
90
+ });
91
+ child.once("exit", (code, signal) => {
92
+ if (code === 0) resolve();
93
+ else reject(new Error(`Codex plugin installation failed (${signal || `exit ${code}`})`));
94
+ });
95
+ });
96
+ }
97
+
98
+ export async function installPlugin(options = {}) {
99
+ const paths = personalPaths(options.homeDirectory);
100
+ await copyPlugin(options.packageRoot || PACKAGE_ROOT, paths.pluginDirectory);
101
+ const marketplaceName = await writeMarketplace(paths.marketplaceFile, await readMarketplace(paths.marketplaceFile));
102
+ if (options.installWithCodex !== false) await runCodexInstall(marketplaceName);
103
+ return { ...paths, marketplaceName };
104
+ }
105
+
@@ -0,0 +1,27 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { dataDirectory } from "./config.mjs";
4
+ import { digest } from "./privacy.mjs";
5
+
6
+ function sessionDirectory(sessionId, env) {
7
+ return path.join(dataDirectory(env), "session-policies", digest(sessionId, 48));
8
+ }
9
+
10
+ export async function hasSessionPolicy(sessionId, fingerprint, env = process.env) {
11
+ try {
12
+ await fs.access(path.join(sessionDirectory(sessionId, env), fingerprint));
13
+ return true;
14
+ } catch {
15
+ return false;
16
+ }
17
+ }
18
+
19
+ export async function rememberSessionPolicy(sessionId, fingerprint, env = process.env) {
20
+ const directory = sessionDirectory(sessionId, env);
21
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
22
+ await fs.writeFile(path.join(directory, fingerprint), "always\n", { mode: 0o600 });
23
+ }
24
+
25
+ export async function clearSessionPolicies(sessionId, env = process.env) {
26
+ await fs.rm(sessionDirectory(sessionId, env), { recursive: true, force: true });
27
+ }
@@ -0,0 +1,47 @@
1
+ import crypto from "node:crypto";
2
+ import path from "node:path";
3
+
4
+ const SECRET_KEY = /(token|secret|password|passwd|authorization|api[_-]?key|cookie)/i;
5
+ const SECRET_TEXT = /(bearer\s+)[a-z0-9._~+\/-]+|((?:token|secret|password|api[_-]?key)\s*[=:]\s*)[^\s,;]+/gi;
6
+
7
+ export function digest(value, length = 32) {
8
+ return crypto.createHash("sha256").update(String(value)).digest("hex").slice(0, length);
9
+ }
10
+
11
+ export function redactValue(value, depth = 0) {
12
+ if (depth > 4) return "[truncated]";
13
+ if (typeof value === "string") return value.replace(SECRET_TEXT, "$1$2[redacted]");
14
+ if (Array.isArray(value)) return value.slice(0, 20).map((item) => redactValue(item, depth + 1));
15
+ if (value && typeof value === "object") {
16
+ return Object.fromEntries(Object.entries(value).slice(0, 30).map(([key, item]) => [
17
+ key,
18
+ SECRET_KEY.test(key) ? "[redacted]" : redactValue(item, depth + 1),
19
+ ]));
20
+ }
21
+ return value;
22
+ }
23
+
24
+ export function compactText(value, maxLength = 600) {
25
+ const text = typeof value === "string" ? value : JSON.stringify(redactValue(value));
26
+ const redacted = String(text || "").replace(SECRET_TEXT, "$1$2[redacted]").replace(/\s+/g, " ").trim();
27
+ return redacted.length > maxLength ? `${redacted.slice(0, maxLength - 1)}…` : redacted;
28
+ }
29
+
30
+ export function workspaceLabel(cwd) {
31
+ const normalized = path.resolve(String(cwd || "."));
32
+ return path.basename(normalized) || "workspace";
33
+ }
34
+
35
+ export function permissionSummary(input) {
36
+ const description = typeof input?.description === "string" ? input.description : "";
37
+ const command = typeof input?.command === "string" ? input.command : "";
38
+ return compactText(description || command || redactValue(input) || "Requested operation");
39
+ }
40
+
41
+ export function permissionFingerprint(hookInput) {
42
+ const canonical = JSON.stringify({
43
+ tool: hookInput.tool_name,
44
+ input: hookInput.tool_input,
45
+ });
46
+ return digest(canonical, 64);
47
+ }