codex-copilot-dx 1.4.16 → 1.4.17

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 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** sends one notification after a supported local Codex turn finishes. 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. Title and description are optional. The Codex icon comes from [Lobe Icons](https://github.com/lobehub/lobe-icons) and is included in the settings page. The phone retrieves the public icon URL separately.
288
+
289
+ CCDX checks recent local Codex session files while the service runs. It uses the recorded turn duration. Intermediate API responses, cancelled turns and background subagents are skipped. The notification carries the selected title and description, with no prompt or response content. The saved push URL stays in the OS credential store. Cloud-only sessions, Claude and Antigravity are outside this version's notification coverage.
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.4.16",
3
+ "version": "1.4.17",
4
4
  "description": "Local gateway for Codex, Claude and Gemini Antigravity with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
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,184 @@
1
+ import fs from "node:fs";
2
+ import files from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { createHash, randomBytes } from "node:crypto";
5
+ import { createApiSecretStore } from "./api-secrets.mjs";
6
+ import { atomicWriteFileSync } from "./atomic-file.mjs";
7
+ import { codexPaths } from "./codex-paths.mjs";
8
+ import { withFileLockSync } from "./lock.mjs";
9
+ import { readBoundedFileSync } from "./bounded-file.mjs";
10
+ import { readBoundedResponseText } from "./http-transport.mjs";
11
+ import { userSettingsPath } from "./user-settings.mjs";
12
+
13
+ const DEFAULTS = { enabled: false, minutes: 30, title: "", body: "" };
14
+ const ID = /^[a-zA-Z0-9-]{1,120}$/;
15
+ const ROLLOUT = /^rollout-[^/\\]+\.jsonl$/;
16
+ const MB = 1024 * 1024;
17
+ const ICON = "https://cdn.jsdelivr.net/npm/@lobehub/icons-static-png/light/codex-color.png";
18
+
19
+ function invalid() { return new Error("ccdx_bark_invalid"); }
20
+
21
+ export function parseBarkUrl(value) {
22
+ if (typeof value !== "string" || value.length > 2048) throw invalid();
23
+ let url;
24
+ try { url = new URL(value.trim()); } catch { throw invalid(); }
25
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash) throw invalid();
26
+ // Accept the copied test URL as well as the short URL ending at the key.
27
+ const parts = url.pathname.split("/").slice(1);
28
+ const keyIndex = parts.findIndex(part => /^[A-Za-z0-9_-]{16,128}$/.test(part));
29
+ if (keyIndex < 0 || parts.length > keyIndex + 4) throw invalid();
30
+ url.pathname = "/" + [...parts.slice(0, keyIndex), "push"].join("/");
31
+ url.search = "";
32
+ return { endpoint: url.href, deviceKey: parts[keyIndex] };
33
+ }
34
+
35
+ function record(text) {
36
+ try { return JSON.parse(text); } catch { return null; }
37
+ }
38
+
39
+ async function completions(file, since) {
40
+ const stat = await files.lstat(file);
41
+ if (!stat.isFile() || !stat.size) return [];
42
+ const handle = await files.open(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
43
+ try {
44
+ const current = await handle.stat();
45
+ if (!current.isFile() || current.ino !== stat.ino) return [];
46
+ const head = Buffer.alloc(Math.min(current.size, 64 * 1024));
47
+ const { bytesRead } = await handle.read(head, 0, head.length, 0);
48
+ const first = head.subarray(0, bytesRead).toString("utf8").split("\n", 1)[0];
49
+ const meta = record(first), source = meta?.payload?.source;
50
+ if (meta?.type !== "session_meta" || !ID.test(meta.payload?.id || "")
51
+ || source && typeof source === "object" && Object.hasOwn(source, "subagent") || source === "subagent") return [];
52
+ const tail = Buffer.alloc(Math.min(current.size, MB));
53
+ const offset = current.size - tail.length;
54
+ const read = await handle.read(tail, 0, tail.length, offset);
55
+ const rows = tail.subarray(0, read.bytesRead).toString("utf8").split("\n");
56
+ if (offset) rows.shift();
57
+ rows.pop(); // Only complete lines are eligible.
58
+ return rows.flatMap(line => {
59
+ if (!line.includes('"task_complete"') && !line.includes('"turn_complete"')) return [];
60
+ const row = record(line), turn = row?.payload, time = Date.parse(row?.timestamp);
61
+ if (row?.type !== "event_msg" || !["task_complete", "turn_complete"].includes(turn?.type)
62
+ || !Number.isFinite(time) || time < since || !ID.test(turn.turn_id || "")
63
+ || !Number.isSafeInteger(turn.duration_ms) || turn.duration_ms < 0
64
+ || typeof turn.last_agent_message !== "string" || !turn.last_agent_message.trim()
65
+ || turn.root_turn_id && turn.root_turn_id !== turn.turn_id
66
+ || turn.status != null && turn.status !== "completed") return [];
67
+ const id = createHash("sha256").update(meta.payload.id + "/" + turn.turn_id).digest("hex");
68
+ return [{ id, time, duration: turn.duration_ms }];
69
+ });
70
+ } finally { await handle.close(); }
71
+ }
72
+
73
+ export function createBarkNotifications({ env = process.env, home, platform = process.platform, fetchImpl = fetch,
74
+ secretStore = createApiSecretStore({ env, home, platform }), now = Date.now, scanIntervalMs = 10000 } = {}) {
75
+ const folder = path.dirname(userSettingsPath({ env, home }));
76
+ const file = path.join(folder, "bark.json"), ledger = path.join(folder, "bark-delivered.json");
77
+ const sessions = path.join(codexPaths({ env, home }).directory, "sessions");
78
+ let timer, lastResult = null, closed = false, running = false, watching = false, since = now();
79
+ let settings = readSettings();
80
+ const scanned = new Map();
81
+
82
+ function readSettings() {
83
+ try {
84
+ const value = JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 8192 }));
85
+ if (!value || typeof value.enabled !== "boolean" || !Number.isSafeInteger(value.minutes)
86
+ || value.minutes < 0 || value.minutes > 10080 || typeof value.title !== "string" || typeof value.body !== "string") return { ...DEFAULTS };
87
+ const ref = /^[a-f0-9]{32}$/.test(value.ref || "") ? value.ref : undefined;
88
+ return { enabled: value.enabled && Boolean(ref), minutes: value.minutes, title: value.title, body: value.body, ref };
89
+ } catch { return { ...DEFAULTS }; }
90
+ }
91
+
92
+ function claim(event) {
93
+ return withFileLockSync(ledger + ".lock", () => {
94
+ let sent = [];
95
+ try { sent = JSON.parse(readBoundedFileSync(ledger, { encoding: "utf8", maxBytes: 64 * 1024 })); }
96
+ catch (error) { if (error.code !== "ENOENT") throw error; }
97
+ if (sent.some(entry => entry.id === event.id)) return false;
98
+ sent = sent.filter(entry => entry.time >= now() - 86400000).slice(-255);
99
+ sent.push({ id: event.id, time: event.time });
100
+ atomicWriteFileSync(ledger, JSON.stringify(sent), { mode: 0o600 });
101
+ return true;
102
+ });
103
+ }
104
+
105
+ async function scan() {
106
+ if (running) return;
107
+ running = true;
108
+ const snapshot = settings;
109
+ try {
110
+ const root = await files.realpath(sessions);
111
+ const entries = (await files.readdir(root, { recursive: true, withFileTypes: true }))
112
+ .filter(entry => entry.isFile() && ROLLOUT.test(entry.name)).sort((a, b) => b.name.localeCompare(a.name)).slice(0, 4096);
113
+ if (closed || snapshot !== settings) return;
114
+ watching = true;
115
+ for (const entry of entries) {
116
+ if (closed || snapshot !== settings) break;
117
+ try {
118
+ const file = path.join(entry.parentPath, entry.name);
119
+ const stat = await files.stat(file);
120
+ if (stat.mtimeMs < since - 1000) continue;
121
+ const stamp = [stat.ino, stat.size, stat.mtimeMs].join(":");
122
+ if (scanned.get(file) === stamp) continue;
123
+ if (!(await files.realpath(file)).startsWith(root + path.sep)) continue;
124
+ for (const event of await completions(file, since)) {
125
+ if (closed || snapshot !== settings || event.duration < snapshot.minutes * 60000) continue;
126
+ const destination = parseBarkUrl(await secretStore.get(snapshot.ref));
127
+ if (closed || snapshot !== settings || !claim(event)) continue;
128
+ const result = await fetchImpl(destination.endpoint, {
129
+ method: "POST", headers: { "Content-Type": "application/json" }, redirect: "error", signal: AbortSignal.timeout(5000),
130
+ body: JSON.stringify({ device_key: destination.deviceKey, title: snapshot.title || "Codex task completed",
131
+ body: snapshot.body || "A long Codex task has finished.", icon: ICON, group: "CCDX" }),
132
+ });
133
+ // Bark can report an application error with HTTP success.
134
+ const reply = await readBoundedResponseText(result, { maxBytes: 4096, label: "Bark response" });
135
+ if (snapshot === settings) lastResult = result.ok && record(reply)?.code === 200 ? "sent" : "failed";
136
+ }
137
+ if (snapshot === settings) {
138
+ scanned.set(file, stamp);
139
+ if (scanned.size > 4096) scanned.delete(scanned.keys().next().value);
140
+ }
141
+ } catch (error) { if (error.code !== "ENOENT" && snapshot === settings) lastResult = "failed"; }
142
+ }
143
+ } catch { watching = false; }
144
+ finally { running = false;schedule(); }
145
+ }
146
+
147
+ function schedule(interval = scanIntervalMs) {
148
+ clearTimeout(timer);
149
+ if (!closed && settings.enabled) timer = setTimeout(() => { void scan(); }, interval).unref();
150
+ }
151
+
152
+ function snapshot() {
153
+ const { enabled, minutes, title, body, ref } = settings;
154
+ return { enabled, minutes, title, body, configured: Boolean(ref), watching, delivery: lastResult };
155
+ }
156
+
157
+ schedule(0);
158
+ return {
159
+ snapshot,
160
+ async save({ enabled, minutes, title, body, url = "" }) {
161
+ if (typeof enabled !== "boolean" || !Number.isSafeInteger(minutes) || minutes < 0 || minutes > 10080
162
+ || typeof title !== "string" || title.length > 160 || typeof body !== "string" || body.length > 500
163
+ || typeof url !== "string") throw invalid();
164
+ const prior = settings.ref;
165
+ const replacement = url.trim() !== "";
166
+ if (replacement) parseBarkUrl(url);
167
+ if (enabled && !replacement && !prior) throw invalid();
168
+ const ref = replacement ? randomBytes(16).toString("hex") : prior;
169
+ if (replacement) await secretStore.set(ref, url.trim());
170
+ const next = { enabled, minutes, title: title.trim(), body: body.trim(), ref };
171
+ try {
172
+ fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
173
+ atomicWriteFileSync(file, JSON.stringify(next), { mode: 0o600 });
174
+ } catch (error) {
175
+ if (replacement) await secretStore.remove(ref).catch(() => {});
176
+ throw error;
177
+ }
178
+ if (replacement && prior) await secretStore.remove(prior).catch(() => {});
179
+ watching = false;lastResult = null;settings = next;since = now();scanned.clear();schedule(0);
180
+ return snapshot();
181
+ },
182
+ close() { closed = true;clearTimeout(timer);secretStore.close?.(); },
183
+ };
184
+ }
@@ -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
- if (result.reused) markRequestObservation({ health_probe_reused: 1 });
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) {
Binary file
@@ -0,0 +1,38 @@
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
+ if (data.configured) words(fields.url, "bark_url_saved", "placeholder");
14
+ else { fields.url.removeAttribute("data-i18n-placeholder");fields.url.placeholder = "https://bark.example/…"; }
15
+ const message = data.delivery === "sent" ? "bark_sent" : data.delivery === "failed" ? "bark_failed"
16
+ : data.enabled && !data.watching ? "bark_waiting" : notice;
17
+ if (message) words(status, message);
18
+ else { status.removeAttribute("data-i18n");status.textContent = ""; }
19
+ fieldset.disabled = false;
20
+ }
21
+ form.addEventListener("input", () => { dirty = true;notice = null; });
22
+ form.addEventListener("submit", async event => {
23
+ event.preventDefault();
24
+ if (saving) return;
25
+ saving = true;fieldset.disabled = true;
26
+ let data;
27
+ try {
28
+ data = await api({ action: "bark", enabled: fields.enabled.checked, minutes: fields.minutes.valueAsNumber,
29
+ title: fields.title.value.trim() || fields.title.placeholder, body: fields.body.value.trim() || fields.body.placeholder, url: fields.url.value });
30
+ dirty = false;notice = "api_saved";
31
+ } catch (error) { words(status, error.message === "ccdx_bark_invalid" ? "bark_invalid" : "bark_save_failed"); }
32
+ finally { saving = false;fieldset.disabled = false; }
33
+ if (data) sync(data.bark);
34
+ });
35
+ return { sync };
36
+ }
37
+ globalThis.ccdxBarkSettings = { create };
38
+ })();
@@ -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(); });
@@ -527,7 +527,22 @@
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 &amp; enable</button></div></dialog>
530
+ <section class="panel dashboard-section" aria-labelledby="bark-heading">
531
+ <h2 id="bark-heading"><img src="@@BARK_CODEX_PNG@@" width="24" height="24" alt=""><span data-i18n="bark_heading">Bark notifications</span></h2>
532
+ <form id="bark-settings">
533
+ <fieldset disabled>
534
+ <div class="setting-row"><label for="bark-enabled" data-i18n="bark_enable">Notify when a Codex task finishes</label><input id="bark-enabled" name="enabled" type="checkbox"></div>
535
+ <div class="appearance-row"><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"></div>
536
+ <div class="appearance-row"><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></div>
537
+ <div class="appearance-row"><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="Codex task completed"></div>
538
+ <div class="appearance-row"><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="A long Codex task has finished."></div>
539
+ <div class="section-actions"><button type="submit" data-i18n="api_save">Save</button><span id="bark-status" role="status" aria-live="polite"></span></div>
540
+ </fieldset>
541
+ </form>
542
+ </section>
543
+
530
544
  <details class="panel dashboard-section" id="request-limits"><summary data-i18n="advanced_limits">Advanced: request limits</summary><div class="section-actions"><label><span data-i18n="decoded_limit">Decoded request limit (MiB)</span><input id="decoded-limit" type="number" min="128" max="512" step="1"></label><button id="decoded-limit-save" type="button" data-i18n="api_save">Save</button><button id="decoded-limit-default" type="button" data-i18n="limit_default">Use default</button></div><p id="decoded-limit-note" class="hint" role="status"></p><div class="section-actions"><label><span data-i18n="inflight_body_limit">Shared request-body limit (MiB)</span> <input id="inflight-body-limit" type="number" min="32" max="128" step="1" required aria-describedby="inflight-body-limit-note" disabled></label><button id="inflight-body-limit-save" type="button" data-i18n="api_save" disabled>Save</button><button id="inflight-body-limit-default" type="button" data-i18n="limit_default" disabled>Use default</button></div><p id="inflight-body-limit-note" class="hint" role="status"></p></details>
545
+
531
546
  <section class="panel dashboard-section" id="settings-preferences" aria-labelledby="preferences-heading">
532
547
  <h2 id="preferences-heading" data-i18n="preferences_heading">SAVE &amp; RESTORE</h2>
533
548
  <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,19 @@
1
1
  (() => {
2
2
  const translations = {
3
+ bark_heading: ["Bark notifications", "Bark 通知"],
4
+ bark_enable: ["Notify when a Codex task finishes", "Codex 任务完成时通知"],
5
+ bark_url: ["Bark URL with key", "带 key 的 Bark URL"],
6
+ bark_url_saved: ["Saved. Enter a new URL to replace it.", "已保存。输入新地址可替换。"],
7
+ bark_minutes: ["Minimum duration (minutes)", "最短任务时长(分钟)"],
8
+ bark_title: ["Notification title", "消息标题"],
9
+ bark_body: ["Notification description", "消息描述"],
10
+ bark_title_default: ["Codex task completed", "Codex 任务完成"],
11
+ bark_body_default: ["A long Codex task has finished.", "一个 Codex 长任务已完成。"],
12
+ bark_waiting: ["Waiting for the local Codex session directory.", "正在等待本机 Codex 会话目录。"],
13
+ bark_sent: ["Last notification accepted by Bark.", "Bark 已接收最近一条通知。"],
14
+ bark_failed: ["Bark delivery failed.", "Bark 推送失败。"],
15
+ bark_invalid: ["Check the Bark URL and minimum duration.", "请检查 Bark URL 和最短任务时长。"],
16
+ bark_save_failed: ["Could not save Bark settings.", "无法保存 Bark 设置。"],
3
17
  "tool_heading": ["Tool and agent activity","工具与代理活动"],
4
18
  "tool_style": ["Style","样式"],
5
19
  "tool_name": ["Tool", "工具"],
@@ -680,6 +680,9 @@ 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-heading { display:flex; align-items:center; gap:8px; }
684
+ #bark-settings fieldset { margin:0; padding:0; min-width:0; border:0; }
685
+ #bark-settings .appearance-row input { width:min(100%,340px); }
683
686
  .preferences-row { display:flex; align-items:center; justify-content:space-between; gap:20px; padding:12px 0; font-size:13px; }
684
687
  .preferences-row:last-of-type { padding-bottom:0; }
685
688
  .preferences-row .hint { margin-top:5px; }
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"]],
@@ -37,7 +38,11 @@ let bundle;
37
38
  function assets() {
38
39
  bundle ||= Promise.all([...ASSETS].map(async ([name, [file, type]]) => {
39
40
  let body = await readFile(new URL(file, import.meta.url));
40
- if (name === "/") body = Buffer.from(body.toString().replace(/(src|href)="(\/[a-z-]+\.(?:js|css))"/g, `$1="$2?v=${ADAPTER_VERSION}"`));
41
+ if (name === "/") {
42
+ const icon = await readFile(new URL("./dashboard/bark-codex.png", import.meta.url));
43
+ body = Buffer.from(body.toString().replace("@@BARK_CODEX_PNG@@", "data:image/png;base64," + icon.toString("base64"))
44
+ .replace(/(src|href)="(\/[a-z-]+\.(?:js|css))"/g, `$1="$2?v=${ADAPTER_VERSION}"`));
45
+ }
41
46
  return [name, { body, type, etag: `"${createHash("sha256").update(body).digest("hex")}"` }];
42
47
  })).then(async entries => {
43
48
  const installed = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
@@ -1,4 +1,4 @@
1
- import { createHash } from "node:crypto";
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 reusableMessage(status, text) {
19
- if (status !== 200 || Buffer.byteLength(text) > MAX_RETAINED_BYTES) return false;
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
- const message = JSON.parse(text);
22
- return message?.type === "message" && message.role === "assistant" && !message.error
23
- && ["end_turn", "max_tokens"].includes(message.stop_reason)
24
- && Array.isArray(message.content) && message.content.some(part => part?.type === "text" && typeof part.text === "string");
25
- } catch { return false; }
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
- // The prepared header set includes the effective credential. The cache
50
- // retains only a digest, never any request bytes or header values.
51
- const key = createHash("sha256").update(JSON.stringify([url, headers, bodyText])).digest("hex");
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 result = recent.get(key) || await flights.run(key, async signal => {
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 result = { owner, status: response.status, headers: responseHeaders(response), text, at: now(), usageRecorded: false };
60
- if (reusableMessage(result.status, text)) {
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: owner !== result.owner,
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;
@@ -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"],
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 === "application") {
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 && (key !== "context_window_tokens" || value > 0)) context[key] = value;
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) {