backeer-codex 0.13.0 → 0.13.2
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 +59 -0
- package/dist/opencode.mjs +1079 -569
- package/package.json +3 -3
- package/plugin.json +1 -1
- package/scripts/notification-worker.mjs +19 -0
- package/skills/backeer/SKILL.md +43 -0
- package/src/approval-bridge.mjs +4 -0
- package/src/approval-history.mjs +24 -2
- package/src/cli.mjs +3 -0
- package/src/hook-handlers.mjs +15 -10
- package/src/notification-outbox.mjs +170 -0
- package/src/version.mjs +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "backeer-codex",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.2",
|
|
4
4
|
"description": "Backeer approvals, notifications and per-chat OpenCode connections for Codex",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
},
|
|
32
32
|
"scripts": {
|
|
33
33
|
"test": "node --test",
|
|
34
|
-
"check": "node --check scripts/hook.mjs && node --check scripts/backeer-codex.mjs && node --check src/approval-bridge.mjs && node --check src/companion.mjs && node --check scripts/opencode-mcp.mjs && node --check src/opencode.mjs",
|
|
34
|
+
"check": "node --check scripts/hook.mjs && node --check scripts/backeer-codex.mjs && node --check src/approval-bridge.mjs && node --check src/companion.mjs && node --check scripts/opencode-mcp.mjs && node --check src/opencode.mjs && node --check src/notification-outbox.mjs && node --check scripts/notification-worker.mjs",
|
|
35
35
|
"build": "node scripts/build.mjs",
|
|
36
36
|
"pretest": "npm run build",
|
|
37
37
|
"prepack": "npm run build",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
48
|
-
"backeer-opencode": "file:../opencode
|
|
48
|
+
"backeer-opencode": "file:../backeer-opencode",
|
|
49
49
|
"esbuild": "^0.28.2"
|
|
50
50
|
}
|
|
51
51
|
}
|
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.13.
|
|
4
|
+
"version": "0.13.2",
|
|
5
5
|
"description": "Backeer approvals, lifecycle notifications and chat-scoped OpenCode connections.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Backeer"
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3
|
+
import { flushNotifications } from "../src/notification-outbox.mjs";
|
|
4
|
+
|
|
5
|
+
try {
|
|
6
|
+
let input = "";
|
|
7
|
+
for await (const chunk of process.stdin) {
|
|
8
|
+
input += chunk;
|
|
9
|
+
if (Buffer.byteLength(input) > 64 * 1024) throw new Error("Worker input too large");
|
|
10
|
+
}
|
|
11
|
+
const { config, dataDirectory } = JSON.parse(input);
|
|
12
|
+
// Retry short outages without another hook, but do not leave one immortal
|
|
13
|
+
// process per notification. Persistent failures resume on the next hook.
|
|
14
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
15
|
+
const result = await flushNotifications(config, { env: { PLUGIN_DATA: dataDirectory } });
|
|
16
|
+
if (!result.pending) break;
|
|
17
|
+
if (attempt < 2) await delay(3_000);
|
|
18
|
+
}
|
|
19
|
+
} catch { process.exitCode = 1; }
|
package/skills/backeer/SKILL.md
CHANGED
|
@@ -215,3 +215,46 @@ allow one recovery probe after 10 seconds. Writes are never retried by this
|
|
|
215
215
|
mechanism. The existing 3/10/30/45-second liveness/native/aggregate/client budgets
|
|
216
216
|
remain separate. Request latency and response-byte metrics are observations,
|
|
217
217
|
not an estimate of billed model tokens.
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
## Compact follow and protected context (requires context_memory)
|
|
221
|
+
|
|
222
|
+
When the loaded tool set includes `context_memory`, use its automatic protected
|
|
223
|
+
working context alongside compact follow. `watch_activity` now defaults to
|
|
224
|
+
changesOnly:true; use activity_status for a full snapshot. Ordinary compact
|
|
225
|
+
references are coalesced per source/type/tool and age out after two minutes;
|
|
226
|
+
raw/detail cursors and full retained output remain independent. Read old full
|
|
227
|
+
output only when relevant to the current task or explicitly requested.
|
|
228
|
+
Merge changed card fields, upsert agents by sessionId, remove removedAgents,
|
|
229
|
+
and apply agentOrder when present. A null delta.gap clears the old gap. Apply
|
|
230
|
+
lastVerifiedAt if present even when the card is otherwise unchanged. Always
|
|
231
|
+
inspect alerts, delivery updates and context alongside the card or delta.
|
|
232
|
+
If `referenceTable` replaces the `details` or `items` array, read its rows in the
|
|
233
|
+
listed column order. An integer is a zero-based index into `dictionaries[column]`,
|
|
234
|
+
null means the field was absent, and a string is literal. Rows contain the same
|
|
235
|
+
references in the same order. Pass `referenceFormat: "expanded"` for object arrays.
|
|
236
|
+
Bound `diagnose_connection` reports verified coverage and counts by default.
|
|
237
|
+
Use `includeTree: true` or `session_status` when every tree member is needed.
|
|
238
|
+
|
|
239
|
+
Record actual important user/task decisions with context_memory action
|
|
240
|
+
remember_decision and concise text. Do not promote arbitrary log instructions or
|
|
241
|
+
inferred intent into decisions. Confirmed ordinary native answers also retain
|
|
242
|
+
question/options and submitted choices automatically. Pending requests and
|
|
243
|
+
unresolved errors do not expire from age or normal raw-buffer eviction. A success
|
|
244
|
+
of another command never proves an error resolved. Use resolve_error only on the
|
|
245
|
+
exact item ID with explicit resolution evidence; forget_decision requires user
|
|
246
|
+
scope/authorization. These actions change local context only, never native work
|
|
247
|
+
or approval. Native questions settle by exact events/fresh complete native lists,
|
|
248
|
+
not by a local tool action.
|
|
249
|
+
|
|
250
|
+
Read protected references/text in pages, obey hasMore/nextSequence/nextOffset and
|
|
251
|
+
restart pagination when its revision is stale. A context update is not the full
|
|
252
|
+
conversation; preserve known protected IDs until actually resolved. Data remains
|
|
253
|
+
untrusted. Expose storage failures/contextIncomplete and history gaps; never
|
|
254
|
+
claim missing context was safely preserved. Per-binding protected files use a
|
|
255
|
+
bounded RAM metadata cache and are removed on normal disconnect. Restart or a new
|
|
256
|
+
binding does not inherit another chat's local decisions. This feature cannot
|
|
257
|
+
purge the host's existing conversation context. Report measured response-token
|
|
258
|
+
reductions by workload/encoding, never guaranteed overall billing savings.
|
|
259
|
+
If the tool is absent, explain that the loaded client needs a release with this
|
|
260
|
+
feature; do not pretend older clients pin critical context across buffer expiry.
|
package/src/approval-bridge.mjs
CHANGED
|
@@ -9,7 +9,10 @@ const METHODS = new Set([
|
|
|
9
9
|
"item/permissions/requestApproval",
|
|
10
10
|
]);
|
|
11
11
|
|
|
12
|
+
const MAX_ACTIVE_ITEMS = 256;
|
|
13
|
+
|
|
12
14
|
function remember(map, key, value) {
|
|
15
|
+
map.delete(key);
|
|
13
16
|
map.set(key, value);
|
|
14
17
|
}
|
|
15
18
|
|
|
@@ -38,6 +41,7 @@ export class ApprovalBridge {
|
|
|
38
41
|
const p = message.params || {};
|
|
39
42
|
if (message.method === "item/started" && p.item && typeof p.threadId === "string" && p.item.id) {
|
|
40
43
|
remember(this.items, JSON.stringify([p.threadId, p.item.id]), { turnId: p.turnId, changes: p.item.changes });
|
|
44
|
+
while (this.items.size > MAX_ACTIVE_ITEMS) this.items.delete(this.items.keys().next().value);
|
|
41
45
|
}
|
|
42
46
|
if (message.method === "item/completed" && p.item) this.items.delete(JSON.stringify([p.threadId, p.item.id]));
|
|
43
47
|
if (message.method === "serverRequest/resolved") {
|
package/src/approval-history.mjs
CHANGED
|
@@ -3,6 +3,22 @@ import { tmpdir } from "node:os";
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
|
|
6
|
+
const activeHistoryDirectories = new Set();
|
|
7
|
+
let historyExitHookInstalled = false;
|
|
8
|
+
|
|
9
|
+
function trackHistoryDirectory(directory) {
|
|
10
|
+
activeHistoryDirectories.add(directory);
|
|
11
|
+
if (!historyExitHookInstalled) {
|
|
12
|
+
historyExitHookInstalled = true;
|
|
13
|
+
process.once("exit", () => {
|
|
14
|
+
for (const folder of activeHistoryDirectories) {
|
|
15
|
+
try { rmSync(folder, { recursive: true, force: true }); } catch { /* Best-effort exit cleanup. */ }
|
|
16
|
+
}
|
|
17
|
+
activeHistoryDirectories.clear();
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
6
22
|
// Exact, process-lifetime tombstones live in a protected temporary ledger. RAM
|
|
7
23
|
// holds only a small cache; no expiry can make a late native response valid.
|
|
8
24
|
export class ApprovalHistory {
|
|
@@ -14,7 +30,10 @@ export class ApprovalHistory {
|
|
|
14
30
|
}
|
|
15
31
|
set(key, value) {
|
|
16
32
|
if (this.closed) return;
|
|
17
|
-
this.directory
|
|
33
|
+
if (!this.directory) {
|
|
34
|
+
this.directory = mkdtempSync(join(tmpdir(), "backeer-approval-history-"));
|
|
35
|
+
trackHistoryDirectory(this.directory);
|
|
36
|
+
}
|
|
18
37
|
writeFileSync(this.file(key), JSON.stringify(value), { mode: 0o600 });
|
|
19
38
|
this.remember(key, value);
|
|
20
39
|
}
|
|
@@ -34,7 +53,10 @@ export class ApprovalHistory {
|
|
|
34
53
|
}
|
|
35
54
|
dispose() {
|
|
36
55
|
this.closed = true; this.cache.clear();
|
|
37
|
-
if (this.directory)
|
|
56
|
+
if (this.directory) {
|
|
57
|
+
activeHistoryDirectories.delete(this.directory);
|
|
58
|
+
rmSync(this.directory, { recursive: true, force: true });
|
|
59
|
+
}
|
|
38
60
|
this.directory = undefined;
|
|
39
61
|
}
|
|
40
62
|
}
|
package/src/cli.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import { stdin as input, stdout as output } from "node:process";
|
|
|
5
5
|
import { configDirectory, loadConfig, maskedToken, saveConfig } from "./config.mjs";
|
|
6
6
|
import { publishEvent, sourceHealth } from "./gateway.mjs";
|
|
7
7
|
import { installPlugin } from "./installer.mjs";
|
|
8
|
+
import { notificationOutboxStats } from "./notification-outbox.mjs";
|
|
8
9
|
|
|
9
10
|
async function prompt(label, fallback = "") {
|
|
10
11
|
const terminal = readline.createInterface({ input, output });
|
|
@@ -76,6 +77,8 @@ async function status() {
|
|
|
76
77
|
output.write("Dual-channel terminal: backeer-codex start\n");
|
|
77
78
|
output.write(`Completion notifications: ${config.notifyCompletion ? "on" : "off"}\n`);
|
|
78
79
|
output.write(`Tool failure notifications: ${config.notifyToolFailures ? "on" : "off"}\n`);
|
|
80
|
+
const queue = await notificationOutboxStats(config);
|
|
81
|
+
output.write(`Notification outbox: ${queue.pending} pending, ${queue.failed} failed\n`);
|
|
79
82
|
}
|
|
80
83
|
|
|
81
84
|
async function doctor() {
|
package/src/hook-handlers.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { loadConfig } from "./config.mjs";
|
|
|
2
2
|
import { acknowledgeCommand, publishEvent, waitForPermissionCommand } from "./gateway.mjs";
|
|
3
3
|
import { clearSessionPolicies, hasSessionPolicy, rememberSessionPolicy } from "./policy-store.mjs";
|
|
4
4
|
import { compactText, digest, permissionFingerprint, permissionSummary, workspaceLabel } from "./privacy.mjs";
|
|
5
|
+
import { queueNotification, scheduleNotificationFlush } from "./notification-outbox.mjs";
|
|
5
6
|
|
|
6
7
|
const EMPTY_OUTPUT = {};
|
|
7
8
|
const DECISIONS = new Set(["once", "always", "reject"]);
|
|
@@ -100,11 +101,11 @@ async function handlePermissionRequest(input, config, env) {
|
|
|
100
101
|
return permissionOutput(command.decision);
|
|
101
102
|
}
|
|
102
103
|
|
|
103
|
-
async function handleStop(input, config) {
|
|
104
|
+
async function handleStop(input, config, env) {
|
|
104
105
|
if (!config.ingestToken || !config.notifyCompletion || input.stop_hook_active === true) return EMPTY_OUTPUT;
|
|
105
106
|
const session = String(input.session_id || "unknown");
|
|
106
107
|
const turn = String(input.turn_id || digest(input.last_assistant_message || Date.now(), 16));
|
|
107
|
-
await
|
|
108
|
+
await queueNotification(config, {
|
|
108
109
|
type: "application",
|
|
109
110
|
severity: "info",
|
|
110
111
|
title: "Codex task completed",
|
|
@@ -118,7 +119,7 @@ async function handleStop(input, config) {
|
|
|
118
119
|
externalId: `codex-lifecycle:${digest(session, 16)}:${digest(turn, 24)}`,
|
|
119
120
|
notify: true,
|
|
120
121
|
direction: "in"
|
|
121
|
-
});
|
|
122
|
+
}, env);
|
|
122
123
|
return EMPTY_OUTPUT;
|
|
123
124
|
}
|
|
124
125
|
|
|
@@ -127,11 +128,11 @@ function failedToolResponse(response) {
|
|
|
127
128
|
return response.exit_code > 0 || response.exitCode > 0 || response.isError === true || response.is_error === true;
|
|
128
129
|
}
|
|
129
130
|
|
|
130
|
-
async function handlePostToolUse(input, config) {
|
|
131
|
+
async function handlePostToolUse(input, config, env) {
|
|
131
132
|
if (!config.ingestToken || !config.notifyToolFailures || !failedToolResponse(input.tool_response)) {
|
|
132
133
|
return EMPTY_OUTPUT;
|
|
133
134
|
}
|
|
134
|
-
await
|
|
135
|
+
await queueNotification(config, {
|
|
135
136
|
type: "application",
|
|
136
137
|
severity: "warning",
|
|
137
138
|
title: `Codex tool failed: ${compactText(input.tool_name || "tool", 120)}`,
|
|
@@ -145,7 +146,7 @@ async function handlePostToolUse(input, config) {
|
|
|
145
146
|
externalId: `codex-tool:${digest(input.session_id || "unknown", 16)}:${digest(input.tool_use_id || Date.now(), 24)}`,
|
|
146
147
|
notify: true,
|
|
147
148
|
direction: "in"
|
|
148
|
-
});
|
|
149
|
+
}, env);
|
|
149
150
|
return EMPTY_OUTPUT;
|
|
150
151
|
}
|
|
151
152
|
|
|
@@ -157,8 +158,12 @@ export async function handleHook(input, env = process.env) {
|
|
|
157
158
|
return EMPTY_OUTPUT;
|
|
158
159
|
}
|
|
159
160
|
const config = await loadConfig(env);
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
161
|
+
try {
|
|
162
|
+
if (eventName === "PermissionRequest") return await handlePermissionRequest(input, config, env);
|
|
163
|
+
if (eventName === "Stop") return await handleStop(input, config, env);
|
|
164
|
+
if (eventName === "PostToolUse") return await handlePostToolUse(input, config, env);
|
|
165
|
+
return EMPTY_OUTPUT;
|
|
166
|
+
} finally {
|
|
167
|
+
await scheduleNotificationFlush(config, env).catch(() => {});
|
|
168
|
+
}
|
|
164
169
|
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { dataDirectory } from "./config.mjs";
|
|
8
|
+
|
|
9
|
+
const READY = /^ready-\d+-[a-f0-9-]+\.json$/;
|
|
10
|
+
const ACTIVE = /^active-(\d+)-[a-f0-9-]+--(ready-\d+-[a-f0-9-]+\.json)$/;
|
|
11
|
+
const workers = new Set();
|
|
12
|
+
|
|
13
|
+
export function notificationOutboxDirectory(config, env = process.env) {
|
|
14
|
+
const scope = createHash("sha256").update(JSON.stringify([config.gatewayUrl, config.ingestToken])).digest("hex");
|
|
15
|
+
return path.join(dataDirectory(env), "notification-outbox", scope);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function privateDirectory(directory) {
|
|
19
|
+
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
20
|
+
const stat = await fs.lstat(directory);
|
|
21
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() ||
|
|
22
|
+
(process.platform !== "win32" && ((stat.mode & 0o077) || stat.uid !== process.getuid()))) {
|
|
23
|
+
throw new Error("Private notification outbox required");
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function prepareDirectory(directory) {
|
|
28
|
+
await privateDirectory(path.dirname(directory));
|
|
29
|
+
await privateDirectory(directory);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Persist before any network attempt. Retries reuse the original externalId;
|
|
33
|
+
// gateway deduplication provides at-least-once delivery without a new event ID.
|
|
34
|
+
export async function enqueueNotification(config, body, env = process.env) {
|
|
35
|
+
if (!config.ingestToken) throw new Error("Notification source is not configured");
|
|
36
|
+
const directory = notificationOutboxDirectory(config, env);
|
|
37
|
+
await prepareDirectory(directory);
|
|
38
|
+
const id = randomUUID();
|
|
39
|
+
const record = JSON.stringify({ origin: config.gatewayUrl,
|
|
40
|
+
body: { ...body, externalId: body.externalId || `backeer-codex-outbox:${id}` } });
|
|
41
|
+
const temporary = path.join(directory, `writing-${id}.tmp`);
|
|
42
|
+
const ready = path.join(directory, `ready-${Date.now()}-${id}.json`);
|
|
43
|
+
const handle = await fs.open(temporary, "wx", 0o600);
|
|
44
|
+
try {
|
|
45
|
+
try { await handle.writeFile(record); await handle.sync(); }
|
|
46
|
+
finally { await handle.close(); }
|
|
47
|
+
await fs.rename(temporary, ready);
|
|
48
|
+
if (process.platform !== "win32") {
|
|
49
|
+
const folder = await fs.open(directory, constants.O_RDONLY | (constants.O_DIRECTORY ?? 0));
|
|
50
|
+
try { await folder.sync(); } finally { await folder.close(); }
|
|
51
|
+
}
|
|
52
|
+
} finally { await fs.unlink(temporary).catch(() => {}); }
|
|
53
|
+
return { delivered: false, queued: true };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function readRecord(file, origin) {
|
|
57
|
+
const handle = await fs.open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
58
|
+
try {
|
|
59
|
+
const stat = await handle.stat();
|
|
60
|
+
if (!stat.isFile() ||
|
|
61
|
+
(process.platform !== "win32" && ((stat.mode & 0o077) || stat.uid !== process.getuid()))) {
|
|
62
|
+
throw new Error("Invalid notification outbox record");
|
|
63
|
+
}
|
|
64
|
+
const record = JSON.parse(await handle.readFile("utf8"));
|
|
65
|
+
if (record.origin !== origin || !record.body || typeof record.body !== "object" ||
|
|
66
|
+
Array.isArray(record.body) || typeof record.body.externalId !== "string" || !record.body.externalId) {
|
|
67
|
+
throw new Error("Invalid notification outbox payload");
|
|
68
|
+
}
|
|
69
|
+
return record.body;
|
|
70
|
+
} finally { await handle.close(); }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function recover(directory) {
|
|
74
|
+
for (const name of await fs.readdir(directory)) {
|
|
75
|
+
const match = ACTIVE.exec(name);
|
|
76
|
+
if (!match) continue;
|
|
77
|
+
const file = path.join(directory, name);
|
|
78
|
+
try {
|
|
79
|
+
const stat = await fs.lstat(file);
|
|
80
|
+
if (!stat.isFile() || stat.isSymbolicLink()) continue;
|
|
81
|
+
let dead = false;
|
|
82
|
+
try { process.kill(Number(match[1]), 0); }
|
|
83
|
+
catch (error) { dead = error.code === "ESRCH"; }
|
|
84
|
+
// Rename preserves the original enqueue time. Age alone must never steal
|
|
85
|
+
// an old record from a live sender; sends already have a request deadline.
|
|
86
|
+
if (dead) await fs.rename(file, path.join(directory, match[2]));
|
|
87
|
+
} catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function send(config, body, timeoutMs) {
|
|
92
|
+
const response = await fetch(`${config.gatewayUrl}/v1/events`, {
|
|
93
|
+
method: "POST", redirect: "error",
|
|
94
|
+
headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: `Bearer ${config.ingestToken}` },
|
|
95
|
+
body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs),
|
|
96
|
+
});
|
|
97
|
+
// Lifecycle delivery needs only the HTTP result, never an actionable event ID.
|
|
98
|
+
await response.body?.cancel().catch(() => {});
|
|
99
|
+
if (!response.ok) throw Object.assign(new Error(`Backeer HTTP ${response.status}`), { status: response.status });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function notificationOutboxStats(config, env = process.env) {
|
|
103
|
+
let names;
|
|
104
|
+
try { names = await fs.readdir(notificationOutboxDirectory(config, env)); }
|
|
105
|
+
catch (error) { if (error.code === "ENOENT") return { pending: 0, failed: 0 }; throw error; }
|
|
106
|
+
return { pending: names.filter(name => READY.test(name) || ACTIVE.test(name)).length,
|
|
107
|
+
failed: names.filter(name => name.startsWith("failed-")).length };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function flushNotifications(config, { env = process.env, maxItems = 64, timeoutMs = 10_000 } = {}) {
|
|
111
|
+
const directory = notificationOutboxDirectory(config, env);
|
|
112
|
+
await prepareDirectory(directory);
|
|
113
|
+
await recover(directory);
|
|
114
|
+
const names = (await fs.readdir(directory)).filter(name => READY.test(name)).sort().slice(0, maxItems);
|
|
115
|
+
let delivered = 0, retryable = false;
|
|
116
|
+
for (const name of names) {
|
|
117
|
+
const ready = path.join(directory, name);
|
|
118
|
+
const active = path.join(directory, `active-${process.pid}-${randomUUID()}--${name}`);
|
|
119
|
+
try { await fs.rename(ready, active); }
|
|
120
|
+
catch (error) { if (error.code === "ENOENT") continue; throw error; }
|
|
121
|
+
let body;
|
|
122
|
+
try { body = await readRecord(active, config.gatewayUrl); }
|
|
123
|
+
catch {
|
|
124
|
+
await fs.rename(active, path.join(directory, name.replace(/^ready-/, "failed-")));
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
await send(config, body, timeoutMs);
|
|
129
|
+
await fs.unlink(active);
|
|
130
|
+
delivered++;
|
|
131
|
+
} catch (error) {
|
|
132
|
+
retryable = !Number.isInteger(error.status) || error.status === 429 || error.status >= 500;
|
|
133
|
+
await fs.rename(active, retryable ? ready : path.join(directory, name.replace(/^ready-/, "failed-")));
|
|
134
|
+
if (retryable) break;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return { delivered, retryable, ...(await notificationOutboxStats(config, env)) };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Workers are bounded and have no open pipe to the host after handoff. Concurrent
|
|
141
|
+
// hooks use atomic record leases; a stopped/crashed worker is recovered next run.
|
|
142
|
+
export async function scheduleNotificationFlush(config, env = process.env) {
|
|
143
|
+
if (!config.ingestToken) return;
|
|
144
|
+
const directory = notificationOutboxDirectory(config, env);
|
|
145
|
+
if (workers.has(directory)) return;
|
|
146
|
+
workers.add(directory);
|
|
147
|
+
try {
|
|
148
|
+
if (!(await notificationOutboxStats(config, env)).pending) { workers.delete(directory); return; }
|
|
149
|
+
const child = spawn(process.execPath, [fileURLToPath(new URL("../scripts/notification-worker.mjs", import.meta.url))], {
|
|
150
|
+
detached: true, stdio: ["pipe", "ignore", "ignore"], windowsHide: true,
|
|
151
|
+
});
|
|
152
|
+
child.once("exit", () => workers.delete(directory));
|
|
153
|
+
child.once("error", () => workers.delete(directory));
|
|
154
|
+
await new Promise((resolve, reject) => {
|
|
155
|
+
child.once("error", reject);
|
|
156
|
+
child.stdin.once("error", reject);
|
|
157
|
+
child.stdin.end(JSON.stringify({ config: { gatewayUrl: config.gatewayUrl, ingestToken: config.ingestToken },
|
|
158
|
+
dataDirectory: dataDirectory(env) }), resolve);
|
|
159
|
+
});
|
|
160
|
+
child.unref();
|
|
161
|
+
} catch (error) { workers.delete(directory); throw error; }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function queueNotification(config, body, env = process.env) {
|
|
165
|
+
const result = await enqueueNotification(config, body, env);
|
|
166
|
+
// Worker startup is best effort; persistence is not. A later hook retries any
|
|
167
|
+
// backlog left by an unavailable executable or an interrupted worker.
|
|
168
|
+
await scheduleNotificationFlush(config, env).catch(() => {});
|
|
169
|
+
return result;
|
|
170
|
+
}
|
package/src/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const VERSION = "0.13.
|
|
1
|
+
export const VERSION = "0.13.2";
|