codex-copilot-dx 1.4.16 → 1.4.18
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/docs/REFERENCE.md +4 -0
- package/package.json +1 -1
- package/src/adapter.mjs +1 -1
- package/src/bark-notifications.mjs +319 -0
- package/src/claude-gateway.mjs +3 -1
- package/src/dashboard/bark.js +41 -0
- package/src/dashboard/console.js +2 -1
- package/src/dashboard/index.html +39 -1
- package/src/dashboard/language.js +19 -0
- package/src/dashboard/ui.css +21 -0
- package/src/dashboard.mjs +1 -0
- package/src/providers/claude-health-probes.mjs +31 -15
- package/src/service-control.mjs +9 -4
- package/src/stream-performance.mjs +7 -1
package/docs/REFERENCE.md
CHANGED
|
@@ -284,6 +284,10 @@ The initial internal ceiling is 128 concurrent requests per source/account. This
|
|
|
284
284
|
|
|
285
285
|
Settings separates saved preferences from effective state. Auto-save applies changes by default; required restarts remain explicit. Restore-defaults creates a backup first and keeps accounts, keys, model plans and chats. CLI preference reset/restore uses its own service-only backup; it does not change browser appearance or replace the Web UI's backup.
|
|
286
286
|
|
|
287
|
+
**Settings → Bark notifications** is collapsed by default. Enable it and paste the URL containing the device key from Bark. The minimum duration defaults to 30 minutes. Zero includes every eligible completed turn. Leave the title and description blank to use the name of the app that finished. The phone retrieves the matching public PNG from [Lobe Icons](https://github.com/lobehub/lobe-icons).
|
|
288
|
+
|
|
289
|
+
CCDX checks local Codex turns, Claude Desktop sessions in Code mode, and Antigravity sessions with a complete local transcript and a fully idle main conversation. Each source must provide matching start and completion evidence. Intermediate API responses, cancelled turns and background subagents are skipped. The notification carries the configured text and a client icon. Prompt and response content stay local, and the push URL stays in the OS credential store. Cloud-only sessions and ordinary Claude Chat and Cowork sessions lack these local completion records.
|
|
290
|
+
|
|
287
291
|
Web and terminal colors are independent. Web appearance is browser-local. **Settings → Web appearance → Grid paper** gives the light theme a warm paper color and faint gray grid, with a matching dark variant. The terminal keeps its selected color and animation; NO_COLOR, dumb/non-TTY and narrow output remain supported. Reduced motion disables decorative movement. Closed tabs and hidden views stop scheduled work. Model/usage data loads on demand; the Web UI adds no inference calls.
|
|
288
292
|
|
|
289
293
|
Activity, flow and current-run counters use one visible-page SSE connection at `/_ccdx/activity`. TUI activity subscribes to the same in-process notifications. Request starts, model/provider selection, first output, retries and completion coalesce within 50 ms; ordinary output chunks do not trigger pushes. A connection starts with current memory-only state, including the existing recent-request limits. Reconnection restores current state and totals; it does not replay animations or recover arbitrary old history. No replay buffer or durable event store is added.
|
package/package.json
CHANGED
package/src/adapter.mjs
CHANGED
|
@@ -618,7 +618,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
618
618
|
if (state?.version !== 1) throw new Error("Unsupported service-state version");
|
|
619
619
|
importResponseHistory(state.history);await optionalRoutes.importState(state.optional);
|
|
620
620
|
};
|
|
621
|
-
handler.cleanup = () => { activityEvents.close();optionalRoutes.dispose();copilotWeb?.close();antigravity?.close();if (!options.providerRuntime?.privacy) privacy.close(); };
|
|
621
|
+
handler.cleanup = () => { activityEvents.close();optionalRoutes.dispose();options.dashboardOptions?.serviceControl?.closeNotifications?.();copilotWeb?.close();antigravity?.close();if (!options.providerRuntime?.privacy) privacy.close(); };
|
|
622
622
|
return handler;
|
|
623
623
|
}
|
|
624
624
|
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import files from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
6
|
+
import { createApiSecretStore } from "./api-secrets.mjs";
|
|
7
|
+
import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
8
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
9
|
+
import { claudeClientPaths } from "./claude-client-config.mjs";
|
|
10
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
11
|
+
import { readBoundedFile, readBoundedFileSync } from "./bounded-file.mjs";
|
|
12
|
+
import { readBoundedResponseText } from "./http-transport.mjs";
|
|
13
|
+
import { userSettingsPath } from "./user-settings.mjs";
|
|
14
|
+
|
|
15
|
+
const DEFAULTS = { enabled: false, minutes: 30, title: "", body: "", language: "en" };
|
|
16
|
+
const ID = /^[a-zA-Z0-9-]{1,120}$/;
|
|
17
|
+
const ROLLOUT = /^rollout-[^/\\]+\.jsonl$/;
|
|
18
|
+
const CLAUDE_SESSION = /^local_[0-9a-f-]{36}\.json$/i;
|
|
19
|
+
const MB = 1024 * 1024;
|
|
20
|
+
const ICONS = "https://cdn.jsdelivr.net/npm/@lobehub/icons-static-png/light/";
|
|
21
|
+
const APPS = {
|
|
22
|
+
codex: { name: "Codex", icon: "codex-color.png" },
|
|
23
|
+
claude_app: { name: "Claude", icon: "claude-color.png" },
|
|
24
|
+
antigravity: { name: "Antigravity", icon: "antigravity-color.png" },
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
function invalid() { return new Error("ccdx_bark_invalid"); }
|
|
28
|
+
|
|
29
|
+
export function parseBarkUrl(value) {
|
|
30
|
+
if (typeof value !== "string" || value.length > 2048) throw invalid();
|
|
31
|
+
let url;
|
|
32
|
+
try { url = new URL(value.trim()); } catch { throw invalid(); }
|
|
33
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash) throw invalid();
|
|
34
|
+
// Accept the copied test URL as well as the short URL ending at the key.
|
|
35
|
+
const parts = url.pathname.split("/").slice(1);
|
|
36
|
+
const keyIndex = parts.findIndex(part => /^[A-Za-z0-9_-]{16,128}$/.test(part));
|
|
37
|
+
if (keyIndex < 0 || parts.length > keyIndex + 4) throw invalid();
|
|
38
|
+
url.pathname = "/" + [...parts.slice(0, keyIndex), "push"].join("/");
|
|
39
|
+
url.search = "";
|
|
40
|
+
return { endpoint: url.href, deviceKey: parts[keyIndex] };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function record(text) {
|
|
44
|
+
try { return JSON.parse(text); } catch { return null; }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function completions(file, since) {
|
|
48
|
+
const stat = await files.lstat(file);
|
|
49
|
+
if (!stat.isFile() || !stat.size) return [];
|
|
50
|
+
const handle = await files.open(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
51
|
+
try {
|
|
52
|
+
const current = await handle.stat();
|
|
53
|
+
if (!current.isFile() || current.ino !== stat.ino) return [];
|
|
54
|
+
const head = Buffer.alloc(Math.min(current.size, 64 * 1024));
|
|
55
|
+
const { bytesRead } = await handle.read(head, 0, head.length, 0);
|
|
56
|
+
const first = head.subarray(0, bytesRead).toString("utf8").split("\n", 1)[0];
|
|
57
|
+
const meta = record(first), source = meta?.payload?.source;
|
|
58
|
+
if (meta?.type !== "session_meta" || !ID.test(meta.payload?.id || "")
|
|
59
|
+
|| source && typeof source === "object" && Object.hasOwn(source, "subagent") || source === "subagent") return [];
|
|
60
|
+
const tail = Buffer.alloc(Math.min(current.size, MB));
|
|
61
|
+
const offset = current.size - tail.length;
|
|
62
|
+
const read = await handle.read(tail, 0, tail.length, offset);
|
|
63
|
+
const rows = tail.subarray(0, read.bytesRead).toString("utf8").split("\n");
|
|
64
|
+
if (offset) rows.shift();
|
|
65
|
+
rows.pop(); // Only complete lines are eligible.
|
|
66
|
+
return rows.flatMap(line => {
|
|
67
|
+
if (!line.includes('"task_complete"') && !line.includes('"turn_complete"')) return [];
|
|
68
|
+
const row = record(line), turn = row?.payload, time = Date.parse(row?.timestamp);
|
|
69
|
+
if (row?.type !== "event_msg" || !["task_complete", "turn_complete"].includes(turn?.type)
|
|
70
|
+
|| !Number.isFinite(time) || time < since || !ID.test(turn.turn_id || "")
|
|
71
|
+
|| !Number.isSafeInteger(turn.duration_ms) || turn.duration_ms < 0
|
|
72
|
+
|| typeof turn.last_agent_message !== "string" || !turn.last_agent_message.trim()
|
|
73
|
+
|| turn.root_turn_id && turn.root_turn_id !== turn.turn_id
|
|
74
|
+
|| turn.status != null && turn.status !== "completed") return [];
|
|
75
|
+
const id = createHash("sha256").update(meta.payload.id + "/" + turn.turn_id).digest("hex");
|
|
76
|
+
return [{ id, time, duration: turn.duration_ms, application: "codex" }];
|
|
77
|
+
});
|
|
78
|
+
} finally { await handle.close(); }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function claudeCompletion(file, since, previousCount) {
|
|
82
|
+
const session = record(await readBoundedFile(file, { encoding: "utf8", maxBytes: MB }));
|
|
83
|
+
if (!session || path.basename(file) !== session.sessionId + ".json") return null;
|
|
84
|
+
const count = session.completedTurns ?? 0;
|
|
85
|
+
if (!Number.isSafeInteger(count) || count < 0) return null;
|
|
86
|
+
const start = session.latestUserFrameAt, time = session.lastTurnEdgeAt;
|
|
87
|
+
// Claude Desktop's Code mode increments completedTurns only on a successful SDK result.
|
|
88
|
+
const advanced = previousCount === undefined ? count === 1 && session.createdAt >= since : count > previousCount;
|
|
89
|
+
if (!advanced || session.spawnedFrom || session.lastTurnCutShort || session.lastTurnStopped || session.interruptedAwaitingPerson
|
|
90
|
+
|| !Number.isSafeInteger(start) || !Number.isSafeInteger(time) || time < since || time <= start
|
|
91
|
+
|| Number.isSafeInteger(session.errorAt) && session.errorAt >= start) return { count };
|
|
92
|
+
const id = createHash("sha256").update("claude_app/" + session.sessionId + "/" + count).digest("hex");
|
|
93
|
+
return { count, event: { id, time, duration: time - start, application: "claude_app" } };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function notificationMessage(settings, event) {
|
|
97
|
+
const { name, icon } = APPS[event.application];
|
|
98
|
+
const zh = settings.language === "zh";
|
|
99
|
+
return { title: settings.title || (zh ? name + " 任务完成" : name + " task completed"),
|
|
100
|
+
body: settings.body || (zh ? "一个 " + name + " 任务已完成。" : "A " + name + " task has finished."),
|
|
101
|
+
icon: ICONS + icon, group: "CCDX" };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function antigravityCompletion(file, size, row, since) {
|
|
105
|
+
const handle = await files.open(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
106
|
+
try {
|
|
107
|
+
const tail = Buffer.alloc(Math.min(size, MB));
|
|
108
|
+
const offset = size - tail.length;
|
|
109
|
+
const read = await handle.read(tail, 0, tail.length, offset);
|
|
110
|
+
const lines = tail.subarray(0, read.bytesRead).toString("utf8").split("\n");
|
|
111
|
+
if (offset) lines.shift();
|
|
112
|
+
if (lines.pop() !== "") return null;
|
|
113
|
+
const end = record(lines.pop());
|
|
114
|
+
// An idle summary alone also occurs on errors, interruption or overdue background work.
|
|
115
|
+
if (end?.type !== "PLANNER_RESPONSE" || end.source !== "MODEL" || end.status !== "DONE"
|
|
116
|
+
|| !Number.isSafeInteger(end.step_index) || end.step_index + 1 !== row.step_count
|
|
117
|
+
|| typeof end.content !== "string" || !end.content.trim()
|
|
118
|
+
|| end.tool_calls != null && (!Array.isArray(end.tool_calls) || end.tool_calls.length)) return null;
|
|
119
|
+
const input = lines.map(record).findLast(step => step?.type === "USER_INPUT");
|
|
120
|
+
const startIndex = row.last_user_input_step_index === -1 ? 0 : row.last_user_input_step_index;
|
|
121
|
+
if (end.step_index <= startIndex || (input ? input.step_index !== startIndex : !offset || row.last_user_input_step_index < 0)) return null;
|
|
122
|
+
// Long turns may have pushed their input row out of the bounded transcript tail.
|
|
123
|
+
const time = Date.parse(end.created_at), start = Date.parse(input?.created_at ?? row.last_user_input_time);
|
|
124
|
+
if (!Number.isFinite(time) || !Number.isFinite(start) || time < since || time < start
|
|
125
|
+
|| Date.parse(row.last_modified_time) < time) return null;
|
|
126
|
+
const id = createHash("sha256").update("antigravity/" + row.conversation_id + "/" + startIndex).digest("hex");
|
|
127
|
+
return { id, time, duration: time - start, application: "antigravity" };
|
|
128
|
+
} finally { await handle.close(); }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function antigravityIdleConversations(root) {
|
|
132
|
+
const file = path.join(root, "conversation_summaries.db");
|
|
133
|
+
if (!(await files.lstat(file)).isFile()) return [];
|
|
134
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
135
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
136
|
+
try {
|
|
137
|
+
return db.prepare(`SELECT conversation_id, last_user_input_step_index, last_user_input_time, last_modified_time, step_count
|
|
138
|
+
FROM conversation_summaries
|
|
139
|
+
WHERE status = 'CASCADE_RUN_STATUS_IDLE' AND not_fully_idle = 0 AND killed = 0
|
|
140
|
+
AND nesting_depth = 0 AND COALESCE(parent_conversation_id, '') = ''
|
|
141
|
+
ORDER BY last_modified_time DESC LIMIT 256`).all();
|
|
142
|
+
} finally { db.close(); }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function createBarkNotifications({ env = process.env, home = os.homedir(), platform = process.platform, fetchImpl = fetch,
|
|
146
|
+
secretStore = createApiSecretStore({ env, home, platform }), now = Date.now, scanIntervalMs = 10000 } = {}) {
|
|
147
|
+
const folder = path.dirname(userSettingsPath({ env, home }));
|
|
148
|
+
const file = path.join(folder, "bark.json"), ledger = path.join(folder, "bark-delivered.json");
|
|
149
|
+
const claude = claudeClientPaths({ env, home, platform });
|
|
150
|
+
const sources = [
|
|
151
|
+
{ directory: path.join(codexPaths({ env, home }).directory, "sessions"), pattern: ROLLOUT, application: "codex" },
|
|
152
|
+
...[...new Set([claude.threep, claude.normal])].map(file => ({
|
|
153
|
+
directory: path.join(path.dirname(file), "claude-code-sessions"), pattern: CLAUDE_SESSION, application: "claude_app",
|
|
154
|
+
})),
|
|
155
|
+
];
|
|
156
|
+
const antigravity = path.join(home, ".gemini", "antigravity");
|
|
157
|
+
let timer, lastResult = null, closed = false, running = false, watching = false, since = now();
|
|
158
|
+
let settings = readSettings();
|
|
159
|
+
const scanned = new Map();
|
|
160
|
+
|
|
161
|
+
function readSettings() {
|
|
162
|
+
try {
|
|
163
|
+
const value = JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 8192 }));
|
|
164
|
+
if (!value || typeof value.enabled !== "boolean" || !Number.isSafeInteger(value.minutes)
|
|
165
|
+
|| value.minutes < 0 || value.minutes > 10080 || typeof value.title !== "string" || typeof value.body !== "string") return { ...DEFAULTS };
|
|
166
|
+
const ref = /^[a-f0-9]{32}$/.test(value.ref || "") ? value.ref : undefined;
|
|
167
|
+
// 1.4.17 persisted placeholders as text. Only migrate its exact default copy.
|
|
168
|
+
const legacy = value.language === undefined;
|
|
169
|
+
const zh = value.language === "zh" || legacy && ["Codex 任务完成", "一个 Codex 长任务已完成。"].some(word => word === value.title || word === value.body);
|
|
170
|
+
const title = legacy && ["Codex task completed", "Codex 任务完成"].includes(value.title) ? "" : value.title;
|
|
171
|
+
const body = legacy && ["A long Codex task has finished.", "一个 Codex 长任务已完成。"].includes(value.body) ? "" : value.body;
|
|
172
|
+
return { enabled: value.enabled && Boolean(ref), minutes: value.minutes, title, body, language: zh ? "zh" : "en", ref };
|
|
173
|
+
} catch { return { ...DEFAULTS }; }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function claim(event) {
|
|
177
|
+
return withFileLockSync(ledger + ".lock", () => {
|
|
178
|
+
let sent = [];
|
|
179
|
+
try { sent = JSON.parse(readBoundedFileSync(ledger, { encoding: "utf8", maxBytes: 64 * 1024 })); }
|
|
180
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
181
|
+
if (sent.some(entry => entry.id === event.id)) return false;
|
|
182
|
+
sent = sent.filter(entry => entry.time >= now() - 86400000).slice(-255);
|
|
183
|
+
sent.push({ id: event.id, time: event.time });
|
|
184
|
+
atomicWriteFileSync(ledger, JSON.stringify(sent), { mode: 0o600 });
|
|
185
|
+
return true;
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async function scan() {
|
|
190
|
+
if (running) return;
|
|
191
|
+
running = true;
|
|
192
|
+
const snapshot = settings;
|
|
193
|
+
let foundSource = false;
|
|
194
|
+
try {
|
|
195
|
+
for (const source of sources) {
|
|
196
|
+
if (closed || snapshot !== settings) return;
|
|
197
|
+
const root = await files.realpath(source.directory).catch(() => null);
|
|
198
|
+
if (!root) continue;
|
|
199
|
+
foundSource = await scanSource(source, root, snapshot) || foundSource;
|
|
200
|
+
}
|
|
201
|
+
if (!closed && snapshot === settings) foundSource = await scanAntigravity(snapshot) || foundSource;
|
|
202
|
+
} finally {
|
|
203
|
+
if (snapshot === settings) watching = foundSource;
|
|
204
|
+
running = false;schedule();
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function remember(file, value) {
|
|
209
|
+
scanned.set(file, value);
|
|
210
|
+
if (scanned.size > 4096) scanned.delete(scanned.keys().next().value);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function deliver(event, snapshot) {
|
|
214
|
+
if (closed || snapshot !== settings || event.duration < snapshot.minutes * 60000) return;
|
|
215
|
+
try {
|
|
216
|
+
const destination = parseBarkUrl(await secretStore.get(snapshot.ref));
|
|
217
|
+
if (closed || snapshot !== settings || !claim(event)) return;
|
|
218
|
+
const result = await fetchImpl(destination.endpoint, {
|
|
219
|
+
method: "POST", headers: { "Content-Type": "application/json" }, redirect: "error", signal: AbortSignal.timeout(5000),
|
|
220
|
+
body: JSON.stringify({ device_key: destination.deviceKey, ...notificationMessage(snapshot, event) }),
|
|
221
|
+
});
|
|
222
|
+
const reply = await readBoundedResponseText(result, { maxBytes: 4096, label: "Bark response" });
|
|
223
|
+
if (snapshot === settings) lastResult = result.ok && record(reply)?.code === 200 ? "sent" : "failed";
|
|
224
|
+
} catch {
|
|
225
|
+
if (snapshot === settings) lastResult = "failed";
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function scanAntigravity(snapshot) {
|
|
230
|
+
let root, rows;
|
|
231
|
+
try {
|
|
232
|
+
root = await files.realpath(antigravity);
|
|
233
|
+
rows = await antigravityIdleConversations(root);
|
|
234
|
+
} catch { return false; }
|
|
235
|
+
for (const row of rows) {
|
|
236
|
+
if (closed || snapshot !== settings) break;
|
|
237
|
+
if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(row.conversation_id || "")
|
|
238
|
+
|| !Number.isSafeInteger(row.last_user_input_step_index) || row.last_user_input_step_index < -1
|
|
239
|
+
|| !(Date.parse(row.last_modified_time) >= since)) continue;
|
|
240
|
+
const key = "antigravity:" + row.conversation_id;
|
|
241
|
+
try {
|
|
242
|
+
const file = path.join(root, "brain", row.conversation_id, ".system_generated", "logs", "transcript.jsonl");
|
|
243
|
+
if (await files.realpath(file) !== file) continue;
|
|
244
|
+
const stat = await files.lstat(file);
|
|
245
|
+
if (!stat.isFile() || !stat.size) continue;
|
|
246
|
+
// Both files matter: the summary may be written before the final transcript line.
|
|
247
|
+
const stamp = [row.last_modified_time, row.step_count, stat.ino, stat.size, stat.mtimeMs].join(":");
|
|
248
|
+
if (scanned.get(key)?.stamp === stamp) continue;
|
|
249
|
+
const event = await antigravityCompletion(file, stat.size, row, since);
|
|
250
|
+
if (event) await deliver(event, snapshot);
|
|
251
|
+
if (snapshot === settings) remember(key, { stamp });
|
|
252
|
+
} catch { /* The client may be writing or rotating its transcript. */ }
|
|
253
|
+
}
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async function scanSource(source, root, snapshot) {
|
|
258
|
+
try {
|
|
259
|
+
const entries = (await files.readdir(root, { recursive: true, withFileTypes: true }))
|
|
260
|
+
.filter(entry => entry.isFile() && source.pattern.test(entry.name)).sort((a, b) => b.name.localeCompare(a.name)).slice(0, 4096);
|
|
261
|
+
if (closed || snapshot !== settings) return;
|
|
262
|
+
for (const entry of entries) {
|
|
263
|
+
if (closed || snapshot !== settings) break;
|
|
264
|
+
try {
|
|
265
|
+
const file = path.join(entry.parentPath, entry.name);
|
|
266
|
+
const stat = await files.stat(file);
|
|
267
|
+
if (source.application === "codex" && stat.mtimeMs < since - 1000) continue;
|
|
268
|
+
const stamp = [stat.ino, stat.size, stat.mtimeMs].join(":");
|
|
269
|
+
const previous = scanned.get(file);
|
|
270
|
+
if (previous?.stamp === stamp) continue;
|
|
271
|
+
if (!(await files.realpath(file)).startsWith(root + path.sep)) continue;
|
|
272
|
+
const claude = source.application === "claude_app" ? await claudeCompletion(file, since, previous?.count) : null;
|
|
273
|
+
const events = source.application === "codex" ? await completions(file, since) : claude?.event ? [claude.event] : [];
|
|
274
|
+
for (const event of events) await deliver(event, snapshot);
|
|
275
|
+
if (snapshot === settings) remember(file, { stamp, count: claude?.count });
|
|
276
|
+
} catch { /* The client may be writing or rotating its session file. */ }
|
|
277
|
+
}
|
|
278
|
+
return true;
|
|
279
|
+
} catch { return false; }
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function schedule(interval = scanIntervalMs) {
|
|
283
|
+
clearTimeout(timer);
|
|
284
|
+
if (!closed && settings.enabled) timer = setTimeout(() => { void scan(); }, interval).unref();
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function snapshot() {
|
|
288
|
+
const { enabled, minutes, title, body, ref } = settings;
|
|
289
|
+
return { enabled, minutes, title, body, sources: Object.keys(APPS), configured: Boolean(ref), watching, delivery: lastResult };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
schedule(0);
|
|
293
|
+
return {
|
|
294
|
+
snapshot,
|
|
295
|
+
async save({ enabled, minutes, title, body, url = "", language = settings.language }) {
|
|
296
|
+
if (typeof enabled !== "boolean" || !Number.isSafeInteger(minutes) || minutes < 0 || minutes > 10080
|
|
297
|
+
|| typeof title !== "string" || title.length > 160 || typeof body !== "string" || body.length > 500
|
|
298
|
+
|| typeof url !== "string" || !["en", "zh"].includes(language)) throw invalid();
|
|
299
|
+
const prior = settings.ref;
|
|
300
|
+
const replacement = url.trim() !== "";
|
|
301
|
+
if (replacement) parseBarkUrl(url);
|
|
302
|
+
if (enabled && !replacement && !prior) throw invalid();
|
|
303
|
+
const ref = replacement ? randomBytes(16).toString("hex") : prior;
|
|
304
|
+
if (replacement) await secretStore.set(ref, url.trim());
|
|
305
|
+
const next = { enabled, minutes, title: title.trim(), body: body.trim(), language, ref };
|
|
306
|
+
try {
|
|
307
|
+
fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
308
|
+
atomicWriteFileSync(file, JSON.stringify(next), { mode: 0o600 });
|
|
309
|
+
} catch (error) {
|
|
310
|
+
if (replacement) await secretStore.remove(ref).catch(() => {});
|
|
311
|
+
throw error;
|
|
312
|
+
}
|
|
313
|
+
if (replacement && prior) await secretStore.remove(prior).catch(() => {});
|
|
314
|
+
watching = false;lastResult = null;settings = next;since = now();scanned.clear();schedule(0);
|
|
315
|
+
return snapshot();
|
|
316
|
+
},
|
|
317
|
+
close() { closed = true;clearTimeout(timer);secretStore.close?.(); },
|
|
318
|
+
};
|
|
319
|
+
}
|
package/src/claude-gateway.mjs
CHANGED
|
@@ -265,6 +265,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
265
265
|
if (healthProbe) {
|
|
266
266
|
context.purpose = "diagnostic";
|
|
267
267
|
tracker?.setPurpose("diagnostic");
|
|
268
|
+
markRequestObservation({ health_probe_state: "recognized" });
|
|
268
269
|
}
|
|
269
270
|
if (resolveRequest) {
|
|
270
271
|
const resolved = await resolveRequest(body, req);
|
|
@@ -309,7 +310,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
309
310
|
const callOptions = { headers: req.headers, countTokens, signal: abort.signal, sourceBodyManaged: true,
|
|
310
311
|
...(healthProbe ? { onClaudeHealthProbe(result) {
|
|
311
312
|
context.claudeHealthProbe = result;
|
|
312
|
-
|
|
313
|
+
markRequestObservation({ health_probe_state: result.state, health_probe_shape: result.shape,
|
|
314
|
+
health_probe_group: result.group, ...(result.reused ? { health_probe_reused: 1 } : {}) });
|
|
313
315
|
} } : {}),
|
|
314
316
|
onUpstreamErrorHeaders(status) { upstreamHeadersObserved = true;tracker?.upstreamHeaders(status);body = null;release();release = () => {}; },
|
|
315
317
|
onCountObservation(value) {
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
function create({ api, element: el }) {
|
|
3
|
+
const form = el("bark-settings");
|
|
4
|
+
if (!form) return null;
|
|
5
|
+
const fieldset = form.querySelector("fieldset"), status = el("bark-status"), fields = form.elements;
|
|
6
|
+
let dirty = false, saving = false, notice;
|
|
7
|
+
const words = (node, key, prop) => globalThis.ccdxLanguage.set(node, key, {}, prop);
|
|
8
|
+
function sync(data) {
|
|
9
|
+
if (!data || dirty || saving) return;
|
|
10
|
+
for (const key of ["minutes", "title", "body"]) fields[key].value = data[key];
|
|
11
|
+
fields.enabled.checked = data.enabled;
|
|
12
|
+
fields.url.value = "";
|
|
13
|
+
const apps = (data.sources || []).map(id => globalThis.ccdxLanguage.format("bark_source_" + id)).join(", ");
|
|
14
|
+
if (apps) globalThis.ccdxLanguage.set(el("bark-sources"), "bark_active_sources", { apps });
|
|
15
|
+
if (data.configured) words(fields.url, "bark_url_saved", "placeholder");
|
|
16
|
+
else { fields.url.removeAttribute("data-i18n-placeholder");fields.url.placeholder = "https://bark.example/…"; }
|
|
17
|
+
const message = data.delivery === "sent" ? "bark_sent" : data.delivery === "failed" ? "bark_failed"
|
|
18
|
+
: data.enabled && !data.watching ? "bark_waiting" : notice;
|
|
19
|
+
if (message) words(status, message);
|
|
20
|
+
else { status.removeAttribute("data-i18n");status.textContent = ""; }
|
|
21
|
+
fieldset.disabled = false;
|
|
22
|
+
}
|
|
23
|
+
form.addEventListener("input", () => { dirty = true;notice = null; });
|
|
24
|
+
form.addEventListener("submit", async event => {
|
|
25
|
+
event.preventDefault();
|
|
26
|
+
if (saving) return;
|
|
27
|
+
saving = true;fieldset.disabled = true;
|
|
28
|
+
let data;
|
|
29
|
+
try {
|
|
30
|
+
data = await api({ action: "bark", enabled: fields.enabled.checked, minutes: fields.minutes.valueAsNumber,
|
|
31
|
+
title: fields.title.value, body: fields.body.value, url: fields.url.value,
|
|
32
|
+
language: document.documentElement.lang.startsWith("zh") ? "zh" : "en" });
|
|
33
|
+
dirty = false;notice = "api_saved";
|
|
34
|
+
} catch (error) { words(status, error.message === "ccdx_bark_invalid" ? "bark_invalid" : "bark_save_failed"); }
|
|
35
|
+
finally { saving = false;fieldset.disabled = false; }
|
|
36
|
+
if (data) sync(data.bark);
|
|
37
|
+
});
|
|
38
|
+
return { sync };
|
|
39
|
+
}
|
|
40
|
+
globalThis.ccdxBarkSettings = { create };
|
|
41
|
+
})();
|
package/src/dashboard/console.js
CHANGED
|
@@ -87,6 +87,7 @@
|
|
|
87
87
|
selectAnimation: theme => animationView.select(theme),
|
|
88
88
|
refreshAnimation() { dashboardRefresh.invalidate("animation");if (current === "system") void dashboardRefresh.refresh("animation", { force: true }); } });
|
|
89
89
|
globalThis.ccdxSettingsPreferences = preferences;
|
|
90
|
+
const bark = globalThis.ccdxBarkSettings?.create({ element: el, api });
|
|
90
91
|
const features = globalThis.ccdxDashboardFeatures?.create({ element: el, api, apply: applySettings, change, localize: label });
|
|
91
92
|
const applications = globalThis.ccdxApplications?.create({ element: el, change, localize: label, isBusy: () => settingsPending });
|
|
92
93
|
globalThis.ccdxApplicationControls = applications;
|
|
@@ -193,7 +194,7 @@
|
|
|
193
194
|
}
|
|
194
195
|
}
|
|
195
196
|
el("process-notice").textContent = data.terminal?.last_notice || "";
|
|
196
|
-
preferences?.sync(data, meta);
|
|
197
|
+
preferences?.sync(data, meta);bark?.sync(data.bark);
|
|
197
198
|
applications?.sync(data);
|
|
198
199
|
}
|
|
199
200
|
window.addEventListener("ccdx:connections", event => { if (current === "codex" && event.detail?.imageChanged) void loadSettings(); });
|
package/src/dashboard/index.html
CHANGED
|
@@ -527,7 +527,45 @@
|
|
|
527
527
|
<div class="section-actions"><button id="privacy-cancel" type="button" hidden data-i18n="cancel">Cancel</button><button id="privacy-retry" type="button" hidden data-i18n="view_retry">Retry</button><button id="privacy-remove" type="button" hidden data-i18n="privacy_remove">Delete model</button><p id="privacy-error" class="hint" role="alert"></p></div>
|
|
528
528
|
</section>
|
|
529
529
|
<dialog id="privacy-dialog" class="preferences-dialog" aria-labelledby="privacy-dialog-title"><h2 id="privacy-dialog-title" data-i18n="privacy_enable">Local masking</h2><p data-i18n="privacy_download">Downloads about 39 MB plus the local component. Checks may add delay or mistake ordinary text.</p><p data-i18n="privacy_fail_closed">If a check cannot finish, the request is not sent.</p><div class="section-actions"><button id="privacy-dialog-cancel" type="button" data-i18n="cancel">Cancel</button><button id="privacy-dialog-confirm" type="button" data-i18n="privacy_confirm">Download & enable</button></div></dialog>
|
|
530
|
-
<details class="panel dashboard-section" id="
|
|
530
|
+
<details class="panel dashboard-section" id="bark-notifications">
|
|
531
|
+
<summary class="panel-heading"><h2 id="bark-heading" data-i18n="bark_heading">Bark notifications</h2></summary>
|
|
532
|
+
<form id="bark-settings">
|
|
533
|
+
<fieldset disabled>
|
|
534
|
+
<label class="bark-toggle"><input id="bark-enabled" name="enabled" type="checkbox" role="switch"><span data-i18n="bark_enable">Notify when a task finishes</span></label>
|
|
535
|
+
<p id="bark-sources" class="hint" data-i18n="bark_sources">Supported local clients appear here when settings load.</p>
|
|
536
|
+
<div class="bark-fields">
|
|
537
|
+
<label for="bark-url" data-i18n="bark_url">Bark URL with key</label><input id="bark-url" name="url" type="password" maxlength="2048" autocomplete="off" spellcheck="false">
|
|
538
|
+
<label for="bark-minutes" data-i18n="bark_minutes">Minimum duration (minutes)</label><input id="bark-minutes" name="minutes" type="number" min="0" max="10080" step="1" value="30" required>
|
|
539
|
+
<label for="bark-title" data-i18n="bark_title">Notification title</label><input id="bark-title" name="title" maxlength="160" data-i18n-placeholder="bark_title_default" placeholder="Automatic">
|
|
540
|
+
<label for="bark-body" data-i18n="bark_body">Notification description</label><input id="bark-body" name="body" maxlength="500" data-i18n-placeholder="bark_body_default" placeholder="Automatic">
|
|
541
|
+
</div>
|
|
542
|
+
<div class="section-actions"><button type="submit" data-i18n="api_save">Save</button><span id="bark-status" role="status" aria-live="polite"></span></div>
|
|
543
|
+
</fieldset>
|
|
544
|
+
</form>
|
|
545
|
+
</details>
|
|
546
|
+
|
|
547
|
+
<details class="panel dashboard-section" id="request-limits">
|
|
548
|
+
<summary data-i18n="advanced_limits">Advanced: request limits</summary>
|
|
549
|
+
<div class="request-limit">
|
|
550
|
+
<label for="decoded-limit" data-i18n="decoded_limit">Decoded request limit (MiB)</label>
|
|
551
|
+
<div class="section-actions">
|
|
552
|
+
<input id="decoded-limit" type="number" min="128" max="512" step="1">
|
|
553
|
+
<button id="decoded-limit-save" type="button" data-i18n="api_save">Save</button>
|
|
554
|
+
<button id="decoded-limit-default" type="button" data-i18n="limit_default">Use default</button>
|
|
555
|
+
</div>
|
|
556
|
+
<p id="decoded-limit-note" class="hint" role="status"></p>
|
|
557
|
+
</div>
|
|
558
|
+
<div class="request-limit">
|
|
559
|
+
<label for="inflight-body-limit" data-i18n="inflight_body_limit">Shared request-body limit (MiB)</label>
|
|
560
|
+
<div class="section-actions">
|
|
561
|
+
<input id="inflight-body-limit" type="number" min="32" max="128" step="1" required aria-describedby="inflight-body-limit-note" disabled>
|
|
562
|
+
<button id="inflight-body-limit-save" type="button" data-i18n="api_save" disabled>Save</button>
|
|
563
|
+
<button id="inflight-body-limit-default" type="button" data-i18n="limit_default" disabled>Use default</button>
|
|
564
|
+
</div>
|
|
565
|
+
<p id="inflight-body-limit-note" class="hint" role="status"></p>
|
|
566
|
+
</div>
|
|
567
|
+
</details>
|
|
568
|
+
|
|
531
569
|
<section class="panel dashboard-section" id="settings-preferences" aria-labelledby="preferences-heading">
|
|
532
570
|
<h2 id="preferences-heading" data-i18n="preferences_heading">SAVE & RESTORE</h2>
|
|
533
571
|
<div class="preferences-row"><div><label for="preferences-auto" data-i18n="preferences_auto">Save changes automatically</label></div><input id="preferences-auto" type="checkbox" role="switch" disabled checked></div>
|
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const translations = {
|
|
3
|
+
bark_heading: ["Bark notifications", "Bark 通知"],
|
|
4
|
+
bark_enable: ["Notify when a task finishes", "任务完成时通知"],
|
|
5
|
+
bark_sources: ["Supported local clients appear here when settings load.", "加载后显示支持的本机应用。"],
|
|
6
|
+
bark_active_sources: ["Local completion signals: {apps}", "支持的本机任务完成信号:{apps}"],
|
|
7
|
+
bark_source_codex: ["Codex", "Codex"],
|
|
8
|
+
bark_source_claude_app: ["Claude Desktop (Code)", "Claude 桌面端(Code)"],
|
|
9
|
+
bark_source_antigravity: ["Antigravity", "Antigravity"],
|
|
10
|
+
bark_url: ["Bark URL with key", "带 key 的 Bark URL"],
|
|
11
|
+
bark_url_saved: ["Saved. Enter a new URL to replace it.", "已保存。输入新地址可替换。"],
|
|
12
|
+
bark_minutes: ["Minimum duration (minutes)", "最短任务时长(分钟)"],
|
|
13
|
+
bark_title: ["Notification title", "消息标题"],
|
|
14
|
+
bark_body: ["Notification description", "消息描述"],
|
|
15
|
+
bark_title_default: ["Automatic", "自动生成"],
|
|
16
|
+
bark_body_default: ["Automatic", "自动生成"],
|
|
17
|
+
bark_waiting: ["Waiting for local completion records.", "正在等待本机任务完成记录。"],
|
|
18
|
+
bark_sent: ["Last notification accepted by Bark.", "Bark 已接收最近一条通知。"],
|
|
19
|
+
bark_failed: ["Bark delivery failed.", "Bark 推送失败。"],
|
|
20
|
+
bark_invalid: ["Check the Bark URL and minimum duration.", "请检查 Bark URL 和最短任务时长。"],
|
|
21
|
+
bark_save_failed: ["Could not save Bark settings.", "无法保存 Bark 设置。"],
|
|
3
22
|
"tool_heading": ["Tool and agent activity","工具与代理活动"],
|
|
4
23
|
"tool_style": ["Style","样式"],
|
|
5
24
|
"tool_name": ["Tool", "工具"],
|
package/src/dashboard/ui.css
CHANGED
|
@@ -680,6 +680,24 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
680
680
|
|
|
681
681
|
/* Settings-page preferences keep their own draft, save and recovery controls. */
|
|
682
682
|
.preferences-status { color:var(--muted); font-size:11px; }
|
|
683
|
+
#bark-settings { max-width: 38rem; margin-top: 14px; }
|
|
684
|
+
#bark-notifications:not([open]) #bark-settings { display: none; }
|
|
685
|
+
#bark-settings fieldset { margin: 0; padding: 0; min-width: 0; border: 0; }
|
|
686
|
+
.bark-toggle { display: inline-flex; align-items: center; gap: 10px; min-height: var(--control-height); cursor: pointer; }
|
|
687
|
+
#bark-sources { margin: 4px 0 16px; }
|
|
688
|
+
.bark-fields { display: grid; grid-template-columns: minmax(11rem, max-content) minmax(0, 1fr); align-items: center; gap: 10px 18px; }
|
|
689
|
+
.bark-fields input { box-sizing: border-box; width: 100%; min-width: 0; height: var(--control-height); padding: 7px 9px; font: inherit; color: var(--text); background: var(--page); border: 1px solid var(--border); }
|
|
690
|
+
.bark-fields input[type="number"] { max-width: 8rem; }
|
|
691
|
+
.bark-fields input:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
|
692
|
+
#bark-settings .section-actions { margin-top: 16px; }
|
|
693
|
+
@media (max-width: 640px) {
|
|
694
|
+
.bark-fields { display: block; }
|
|
695
|
+
.bark-fields label { display: block; margin-bottom: 6px; }
|
|
696
|
+
.bark-fields input { display: block; margin-bottom: 12px; }
|
|
697
|
+
}
|
|
698
|
+
@media (pointer: coarse) {
|
|
699
|
+
.bark-toggle, .bark-fields input { min-height: 44px; }
|
|
700
|
+
}
|
|
683
701
|
.preferences-row { display:flex; align-items:center; justify-content:space-between; gap:20px; padding:12px 0; font-size:13px; }
|
|
684
702
|
.preferences-row:last-of-type { padding-bottom:0; }
|
|
685
703
|
.preferences-row .hint { margin-top:5px; }
|
|
@@ -777,6 +795,9 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
777
795
|
.http-error-table :is(th,td) { text-align: right; white-space: normal; padding-block: 4px; font-variant-numeric: tabular-nums; }
|
|
778
796
|
.http-error-grid { display: none; }
|
|
779
797
|
.request-limits-line { display: flex; flex-wrap: wrap; gap: 4px 10px; }
|
|
798
|
+
.request-limit { margin-top: 14px; }
|
|
799
|
+
.request-limit > label { display: block; color: var(--muted); font-size: 12px; }
|
|
800
|
+
.request-limit .section-actions { margin-top: 7px; }
|
|
780
801
|
.recent-request-duration { text-align: right; font-variant-numeric: tabular-nums; }
|
|
781
802
|
@media (max-width: 620px) {
|
|
782
803
|
.http-error-table { display: none; }
|
package/src/dashboard.mjs
CHANGED
|
@@ -25,6 +25,7 @@ const ASSETS = new Map([
|
|
|
25
25
|
["/animation.js", ["./dashboard/animation.js", "text/javascript; charset=utf-8"]],
|
|
26
26
|
["/ui.js", ["./dashboard/ui.js", "text/javascript; charset=utf-8"]],
|
|
27
27
|
["/preferences.js", ["./dashboard/preferences.js", "text/javascript; charset=utf-8"]],
|
|
28
|
+
["/bark.js", ["./dashboard/bark.js", "text/javascript; charset=utf-8"]],
|
|
28
29
|
["/features.js", ["./dashboard/features.js", "text/javascript; charset=utf-8"]],
|
|
29
30
|
["/applications.js", ["./dashboard/applications.js", "text/javascript; charset=utf-8"]],
|
|
30
31
|
["/console.js", ["./dashboard/console.js", "text/javascript; charset=utf-8"]],
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
2
2
|
import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
|
|
3
3
|
import { MAX_UPSTREAM_ERROR_BODY_BYTES, readBoundedResponseText } from "../http-transport.mjs";
|
|
4
4
|
import { safeUpstreamResponseHeaders } from "../upstream-headers.mjs";
|
|
@@ -15,14 +15,21 @@ export function isClaudeHealthProbe(body, headers) {
|
|
|
15
15
|
&& SESSION_HEADERS.every(name => !headers[name]);
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
function
|
|
19
|
-
if (status !== 200
|
|
18
|
+
function responseShape(status, text) {
|
|
19
|
+
if (status !== 200) return "http_status";
|
|
20
|
+
if (Buffer.byteLength(text) > MAX_RETAINED_BYTES) return "too_large";
|
|
21
|
+
let message;
|
|
20
22
|
try {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
message = JSON.parse(text);
|
|
24
|
+
} catch { return "invalid_message"; }
|
|
25
|
+
if (message?.type !== "message" || message.role !== "assistant" || message.error
|
|
26
|
+
|| !["end_turn", "max_tokens"].includes(message.stop_reason) || !Array.isArray(message.content)) return "invalid_message";
|
|
27
|
+
if (message.content.some(part => part?.type === "text" && typeof part.text === "string")) return "text";
|
|
28
|
+
// The startup check uses HTTP success. A valid terminal message can have no visible text.
|
|
29
|
+
if (!message.content.length) return "empty";
|
|
30
|
+
if (message.content.every(part => (part?.type === "thinking" && typeof part.thinking === "string")
|
|
31
|
+
|| (part?.type === "redacted_thinking" && typeof part.data === "string"))) return "thinking_only";
|
|
32
|
+
return "other_content";
|
|
26
33
|
}
|
|
27
34
|
|
|
28
35
|
function responseHeaders(response) {
|
|
@@ -37,6 +44,7 @@ function responseHeaders(response) {
|
|
|
37
44
|
|
|
38
45
|
export function createClaudeHealthProbes({ now = () => performance.now() } = {}) {
|
|
39
46
|
const flights = createAbortAwareSingleflight(), recent = new Map();
|
|
47
|
+
let keySecret;
|
|
40
48
|
function remove(key) {
|
|
41
49
|
clearTimeout(recent.get(key)?.expiry);
|
|
42
50
|
recent.delete(key);
|
|
@@ -46,18 +54,22 @@ export function createClaudeHealthProbes({ now = () => performance.now() } = {})
|
|
|
46
54
|
clear() { for (const key of recent.keys()) remove(key); },
|
|
47
55
|
async run({ url, headers, bodyText, maxResponseBytes, signal, record }, send) {
|
|
48
56
|
signal?.throwIfAborted();
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
|
|
57
|
+
// Use the complete prepared request, including the effective credential.
|
|
58
|
+
// Only a short prefix of this provider-instance keyed digest reaches diagnostics.
|
|
59
|
+
keySecret ??= randomBytes(32);
|
|
60
|
+
const key = createHmac("sha256", keySecret).update(JSON.stringify([url, headers, bodyText])).digest("hex");
|
|
52
61
|
const at = now();
|
|
53
62
|
for (const [id, result] of recent) if (at - result.at >= REUSE_MS) remove(id);
|
|
54
63
|
const owner = Symbol();
|
|
55
|
-
const
|
|
64
|
+
const retained = recent.get(key);
|
|
65
|
+
const result = retained || await flights.run(key, async signal => {
|
|
56
66
|
const response = await send(signal);
|
|
57
67
|
const text = await readBoundedResponseText(response, { signal, label: "Claude health check response",
|
|
58
68
|
maxBytes: response.ok ? maxResponseBytes : MAX_UPSTREAM_ERROR_BODY_BYTES });
|
|
59
|
-
const
|
|
60
|
-
|
|
69
|
+
const shape = responseShape(response.status, text);
|
|
70
|
+
const stored = ["text", "empty", "thinking_only"].includes(shape);
|
|
71
|
+
const result = { owner, status: response.status, headers: responseHeaders(response), text, at: now(), shape, stored, usageRecorded: false };
|
|
72
|
+
if (stored) {
|
|
61
73
|
remove(key);
|
|
62
74
|
result.expiry = setTimeout(() => remove(key), REUSE_MS);
|
|
63
75
|
result.expiry.unref?.();
|
|
@@ -67,8 +79,12 @@ export function createClaudeHealthProbes({ now = () => performance.now() } = {})
|
|
|
67
79
|
return result;
|
|
68
80
|
}, { signal });
|
|
69
81
|
signal?.throwIfAborted();
|
|
82
|
+
const reused = owner !== result.owner;
|
|
70
83
|
record({
|
|
71
|
-
reused
|
|
84
|
+
reused,
|
|
85
|
+
state: retained ? "reused_recent" : reused ? "reused_inflight" : result.stored ? "stored" : "not_stored",
|
|
86
|
+
shape: result.shape,
|
|
87
|
+
group: key.slice(0, 16),
|
|
72
88
|
claimUsage() {
|
|
73
89
|
if (result.usageRecorded) return false;
|
|
74
90
|
result.usageRecorded = true;
|
package/src/service-control.mjs
CHANGED
|
@@ -12,14 +12,16 @@ import { predictionControlSnapshot, controlPrediction } from "./prediction-contr
|
|
|
12
12
|
import { imageSetupSummary, configureImageSetup } from "./image-setup.mjs";
|
|
13
13
|
import { createApplicationControl } from "./application-control.mjs";
|
|
14
14
|
import { openCodex, autoLaunchEnabled } from "./launcher.mjs";
|
|
15
|
+
import { createBarkNotifications } from "./bark-notifications.mjs";
|
|
15
16
|
|
|
16
17
|
export function createServiceControl({ env = process.env, home, platform = process.platform, providerRuntime, clientIntegration, terminal,
|
|
17
18
|
nightlyStatus = () => null, nightlyChanged = () => {},
|
|
18
19
|
manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup, imageHostControl = controlImage, codexLaunchControl = controlCodexLaunch,
|
|
19
20
|
clientVersions, applicationControlFactory = createApplicationControl,
|
|
20
|
-
adapterPort = 2026, adapterHost = "127.0.0.1",
|
|
21
|
+
adapterPort = 2026, adapterHost = "127.0.0.1", bark,
|
|
21
22
|
readImages = () => imageSetupSummary({ env, home }).configured, readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
|
|
22
23
|
const options = { env, home, platform };
|
|
24
|
+
const notifications = bark ?? createBarkNotifications(options);
|
|
23
25
|
const imageHostState = createImageHostState();
|
|
24
26
|
const applicationControl = applicationControlFactory({ ...options, providerRuntime, clientIntegration, imageHostState, port: adapterPort, host: adapterHost,
|
|
25
27
|
async openCodexApp() {
|
|
@@ -44,7 +46,7 @@ export function createServiceControl({ env = process.env, home, platform = proce
|
|
|
44
46
|
const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
|
|
45
47
|
const localPrivacy = providerRuntime?.privacy?.snapshot();
|
|
46
48
|
return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: localPrivacy,
|
|
47
|
-
applications: applicationControl.snapshot(),
|
|
49
|
+
applications: applicationControl.snapshot(), bark: notifications.snapshot(),
|
|
48
50
|
features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image: { ...image, runtime: imageHostState.snapshot() } },
|
|
49
51
|
decoded_body: decodedBodyLimitPreference(options), inflight_body: inflightBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
|
|
50
52
|
...(providerRuntime?.errorCaptureSnapshot ? { error_capture: providerRuntime.errorCaptureSnapshot() } : {}),
|
|
@@ -72,11 +74,14 @@ export function createServiceControl({ env = process.env, home, platform = proce
|
|
|
72
74
|
application: ["action", "id", "operation", "confirmed", "fresh", "expected_pid", "expected_started"],
|
|
73
75
|
update: ["action", "confirmed"], decoded_limit: ["action", "mib"], inflight_body_limit: ["action", "mib"],
|
|
74
76
|
error_capture: ["action", "operation", "source", "model"],
|
|
77
|
+
bark: ["action", "enabled", "minutes", "title", "body", "url", "language"],
|
|
75
78
|
preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
|
|
76
79
|
provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
|
|
77
80
|
if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
|
|
78
81
|
lastOperation = null;
|
|
79
|
-
if (input.action === "
|
|
82
|
+
if (input.action === "bark") {
|
|
83
|
+
await notifications.save(input);
|
|
84
|
+
} else if (input.action === "application") {
|
|
80
85
|
if (input.fresh !== undefined && typeof input.fresh !== "boolean") throw new Error("Invalid application check");
|
|
81
86
|
if (input.expected_pid !== undefined && (!Number.isSafeInteger(input.expected_pid) || input.expected_pid <= 0 || !Number.isFinite(Date.parse(input.expected_started)))) throw new Error("Invalid application identity");
|
|
82
87
|
lastOperation = { feature: "application", result: await applicationControl.action(input) };
|
|
@@ -147,7 +152,7 @@ export function createServiceControl({ env = process.env, home, platform = proce
|
|
|
147
152
|
}
|
|
148
153
|
return snapshot();
|
|
149
154
|
}
|
|
150
|
-
return { snapshot, applicationControl, busy: () => pending > 0 || applicationControl.busy?.() === true,
|
|
155
|
+
return { snapshot, applicationControl, closeNotifications: () => notifications.close(), busy: () => pending > 0 || applicationControl.busy?.() === true,
|
|
151
156
|
async inspectApplication(id, fresh = false) { await applicationControl.check(id, fresh);return snapshot(); },
|
|
152
157
|
action(input) {
|
|
153
158
|
if (input?.action === "client_versions") {
|
|
@@ -361,6 +361,11 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
361
361
|
if (Number.isSafeInteger(values.source_queue_ms) && values.source_queue_ms >= 0) context.source_queue_ms = values.source_queue_ms;
|
|
362
362
|
if (values.delivery_cancelled === 1) context.delivery_cancelled = 1;
|
|
363
363
|
if (values.health_probe_reused === 1) context.health_probe_reused = 1;
|
|
364
|
+
if (values.health_probe_state && ["recognized", "stored", "not_stored", "reused_recent", "reused_inflight"].includes(values.health_probe_state)) {
|
|
365
|
+
context.health_probe_state = values.health_probe_state;
|
|
366
|
+
if (["text", "empty", "thinking_only", "other_content", "invalid_message", "too_large", "http_status"].includes(values.health_probe_shape)) context.health_probe_shape = values.health_probe_shape;
|
|
367
|
+
if (typeof values.health_probe_group === "string" && /^[a-f0-9]{16}$/.test(values.health_probe_group)) context.health_probe_group = values.health_probe_group;
|
|
368
|
+
}
|
|
364
369
|
if (["codex", "claude_app", "claude_code"].includes(values.verified_application)) context.verified_application = values.verified_application;
|
|
365
370
|
if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
|
|
366
371
|
for (const key of [...Object.keys(context), "compaction", "requested_model", "routing_reason", "reasoning_effort_requested", "reasoning_effort_sent", "usage_state", "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "privacy_pending_bytes", "privacy_new_bytes", "privacy_pending_windows", "privacy_wait_budget_ms", "privacy_error", "privacy_event_type", "privacy_channel_type", "privacy_buffered_bytes", "privacy_terminal_seen", "client_tool_errors_received"]) {
|
|
@@ -375,7 +380,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
375
380
|
if (["capability_revision", "capability_constraints"].includes(key)) {
|
|
376
381
|
if (typeof value === "string" && /^[a-z0-9_,]{1,80}$/.test(value)) context[key] = value;continue;
|
|
377
382
|
}
|
|
378
|
-
if (Number.isSafeInteger(value) && value >= 0 && (
|
|
383
|
+
if (Number.isSafeInteger(value) && value >= 0 && (!context.health_probe_state || !key.startsWith("health_probe_"))
|
|
384
|
+
&& (key !== "context_window_tokens" || value > 0)) context[key] = value;
|
|
379
385
|
}
|
|
380
386
|
},
|
|
381
387
|
setErrorOrigin(value) {
|