codex-copilot-dx 1.4.15 → 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/ARCHITECTURE.md +2 -0
- package/docs/REFERENCE.md +10 -4
- package/package.json +1 -1
- package/src/adapter.mjs +9 -5
- package/src/antigravity-handler.mjs +19 -6
- package/src/bark-notifications.mjs +184 -0
- package/src/claude-gateway.mjs +17 -1
- package/src/cli-management-app.mjs +2 -2
- package/src/cli-status.mjs +4 -0
- package/src/connection-routing.mjs +2 -0
- package/src/connection-runtime.mjs +19 -3
- package/src/dashboard/bark-codex.png +0 -0
- package/src/dashboard/bark.js +38 -0
- package/src/dashboard/console.js +2 -1
- package/src/dashboard/index.html +45 -27
- package/src/dashboard/language.js +26 -4
- package/src/dashboard/preferences.js +1 -1
- package/src/dashboard/status.js +3 -2
- package/src/dashboard/theme.js +3 -2
- package/src/dashboard/tool-activity-machines.js +351 -344
- package/src/dashboard/tool-activity.js +37 -18
- package/src/dashboard/ui.css +48 -1
- package/src/dashboard/usage.js +20 -3
- package/src/dashboard-api.mjs +2 -2
- package/src/dashboard.mjs +6 -1
- package/src/file-rotation.mjs +2 -1
- package/src/providers/api.mjs +21 -3
- package/src/providers/claude-health-probes.mjs +97 -0
- package/src/response-failures.mjs +2 -1
- package/src/service-control.mjs +9 -4
- package/src/source-admission.mjs +7 -5
- package/src/stream-performance.mjs +10 -2
- package/src/terminal-console.mjs +7 -5
- package/src/terminal-state.mjs +5 -1
- package/src/usage-analysis.mjs +13 -2
- package/src/usage-archive.mjs +90 -0
- package/src/usage-store.mjs +66 -16
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
const motion = globalThis.matchMedia?.("(prefers-reduced-motion: reduce)") || { matches: false, addEventListener() {} };
|
|
12
12
|
let records = [], fresh = false, supported = false, visible = true, raf = 0, last = 0, start = performance.now(), expiry = null;
|
|
13
13
|
let drawnTime = null;
|
|
14
|
+
let visibleToolRows = new Map();
|
|
14
15
|
let signature = "", box = { width: 0, height: 0 }, color = "", surface = "", omitted = 0, requests = [], requestDeadline = 0;
|
|
15
16
|
const animating = () => ["calling", "parallel", "waiting", "processing", "responding"].includes(state.scene);
|
|
16
17
|
const shown = () => document.visibilityState === "visible" && !root.closest("[hidden]") && visible;
|
|
@@ -87,29 +88,47 @@
|
|
|
87
88
|
const groups = new Map(displayed.map(row => [`${row.application}:${row.provider}:${row.model}`, row]));
|
|
88
89
|
el("tool-context").hidden = !displayed.length;
|
|
89
90
|
el("tool-context").textContent = groups.size === 1 ? phrase("model_action_label", { name: appName(displayed[0].application), action: displayed[0].model === "other" ? phrase("flow_model_pending") : displayed[0].model }) : phrase("tool_groups", { count: groups.size });
|
|
90
|
-
const list = el("tool-list");
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
91
|
+
const list = el("tool-list");
|
|
92
|
+
const nextToolRows = new Map();
|
|
93
|
+
const children = displayed.slice(0, 6).map((row, index) => {
|
|
94
|
+
const agent = row.responding !== undefined, rowKey = agent ? `agent-${index}` : row.id;
|
|
95
|
+
let item = visibleToolRows.get(rowKey);
|
|
96
|
+
if (!item) {
|
|
97
|
+
item = document.createElement("div");item.className = "tool-entry";
|
|
98
|
+
const mark = document.createElement("span");mark.className = "tool-mark";mark.setAttribute("aria-hidden", "true");
|
|
99
|
+
const name = document.createElement("span");name.className = "tool-name";
|
|
100
|
+
const status = document.createElement("span");
|
|
101
|
+
item.append(mark, name, status);
|
|
102
|
+
}
|
|
103
|
+
item.dataset.state = agent ? "preparing" : row.state;
|
|
104
|
+
const name = phrase(agent ? row.responding ? "tool_response_action" : "tool_processing_action" : category(row.name));
|
|
105
|
+
const status = phrase(agent ? "tool_row_active" : `tool_row_${row.state}`);
|
|
106
|
+
if (item.children[1].textContent !== name) item.children[1].textContent = name;
|
|
107
|
+
if (item.children[2].textContent !== status) item.children[2].textContent = status;
|
|
108
|
+
nextToolRows.set(rowKey, item);
|
|
109
|
+
return item;
|
|
110
|
+
});
|
|
111
|
+
if (list.children.length !== children.length || children.some((child, index) => list.children[index] !== child)) list.replaceChildren(...children);
|
|
112
|
+
visibleToolRows = nextToolRows;
|
|
113
|
+
const details = el("tool-details");
|
|
114
|
+
details.hidden = !rows.length;
|
|
115
|
+
if (details.open) {
|
|
116
|
+
el("tool-technical").replaceChildren();
|
|
117
|
+
for (const row of rows) {
|
|
118
|
+
const line = document.createElement("tr");
|
|
119
|
+
for (const [label, value] of [["client", appName(row.application)], ["source", sourceName(row.provider)], ["model", row.model],
|
|
120
|
+
["tool_name", row.name || phrase("tool_action_generic")], ["outcome", phrase(`tool_row_${row.state}`)]]) {
|
|
121
|
+
const cell = document.createElement("td");cell.textContent = value;cell.dataset.label = phrase(label);line.append(cell);
|
|
122
|
+
}
|
|
123
|
+
el("tool-technical").append(line);
|
|
106
124
|
}
|
|
107
|
-
el("tool-technical").append(line);
|
|
108
125
|
}
|
|
109
126
|
el("tool-more").hidden = rows.length <= 6 && !omitted;
|
|
110
127
|
text("tool-more", "tool_more", { count: Math.max(0, rows.length - 6) + omitted });
|
|
111
|
-
measure();
|
|
128
|
+
if (force || !box.width) measure();
|
|
129
|
+
else if (wasAnimating !== animating()) refreshAnimation();
|
|
112
130
|
}
|
|
131
|
+
el("tool-details").addEventListener("toggle", () => { if (el("tool-details").open) render(true); });
|
|
113
132
|
el("tool-style").addEventListener("change", () => {
|
|
114
133
|
const next = el("tool-style").value;if (!styles.has(next)) return;state.style = next;
|
|
115
134
|
try { localStorage.setItem(storageKey, next); } catch {}render(true);
|
package/src/dashboard/ui.css
CHANGED
|
@@ -201,7 +201,7 @@ select option { color: var(--text); background: var(--surface); }
|
|
|
201
201
|
.calendar-day[data-level="2"] { background: color-mix(in srgb, var(--accent-soft) 45%, var(--surface)); }
|
|
202
202
|
.calendar-day[data-level="3"] { background: color-mix(in srgb, var(--accent-soft) 70%, var(--surface)); }
|
|
203
203
|
.calendar-day[data-level="4"] { background: var(--accent-soft); }
|
|
204
|
-
.calendar-day:disabled
|
|
204
|
+
.calendar-day:disabled { background: repeating-linear-gradient(135deg, transparent, transparent 3px, var(--border) 3px, var(--border) 4px); opacity: .5; cursor: default; }
|
|
205
205
|
footer { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; color: var(--footer); font-size: 10px; letter-spacing: .05em; padding: 22px 0 30px; }
|
|
206
206
|
#auto-refresh[aria-pressed="false"] { background: transparent; color: var(--muted); border-color: var(--border); }
|
|
207
207
|
.refresh-time { display: block; margin: 10px 0 0; color: var(--muted); font-size: 11px; line-height: 1.5; }
|
|
@@ -438,6 +438,36 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
438
438
|
--ansi-51:#555; --ansi-45:#666; --ansi-39:#777; --ansi-33:#888;
|
|
439
439
|
--bad:#000; --failed:#000; --incomplete:#000;
|
|
440
440
|
}
|
|
441
|
+
:root[data-palette="paper"] {
|
|
442
|
+
--page:#22221e; --surface:#292821; --text:#eee8da; --strong:#fff5e7;
|
|
443
|
+
--muted:#c1b8a7; --badge:#c1b8a7; --subtle:#beb4a3; --quiet:#b6ad9d; --footer:#b6ad9d;
|
|
444
|
+
--border:#625c4f; --top-border:#625c4f; --accent:#e4ceb0; --accent-soft:#e4ceb0; --heading:#e4ceb0;
|
|
445
|
+
--button-border:#8d806a; --button-bg:#353026; --button-fg:#f2dfc3; --button-hover:#493e2d;
|
|
446
|
+
--selected-bg:#40382b; --option-hover:#393126; --table-text:#ebe3d5; --preview:#beb19d;
|
|
447
|
+
--ansi-white:#f2dfc3; --ansi-159:#eddbbf; --ansi-123:#e7d1b4; --ansi-87:#e1c8a8;
|
|
448
|
+
--ansi-51:#d6bb9a; --ansi-45:#ccb091; --ansi-39:#c2a384; --ansi-33:#b79a7b;
|
|
449
|
+
--bad:#ff9e88; --failed:#ff9e88; --incomplete:#e5c582;
|
|
450
|
+
--paper-grid:rgba(214,217,221,.065); --paper-grid-faint:rgba(214,217,221,.04);
|
|
451
|
+
}
|
|
452
|
+
:root[data-palette="paper"][data-theme="light"] {
|
|
453
|
+
--page:#f3ead3; --surface:#fbf5e6; --text:#2e302d; --strong:#262824;
|
|
454
|
+
--muted:#57554b; --badge:#57554b; --subtle:#615e52; --quiet:#625e52; --footer:#625e52;
|
|
455
|
+
--border:#b8b0a0; --top-border:#b0a896; --accent:#4c493e; --accent-soft:#4c493e; --heading:#474236;
|
|
456
|
+
--button-border:#9a907d; --button-bg:#f8efdb; --button-fg:#39372f; --button-hover:#ede1c4;
|
|
457
|
+
--selected-bg:#ebe0c6; --option-hover:#f3e8ce; --table-text:#383832; --preview:#666154;
|
|
458
|
+
--ansi-white:#514a3a; --ansi-159:#574936; --ansi-123:#5b4a35; --ansi-87:#604e38;
|
|
459
|
+
--ansi-51:#66513a; --ansi-45:#6b533b; --ansi-39:#725940; --ansi-33:#785d43;
|
|
460
|
+
--bad:#9c3528; --failed:#9c3528; --incomplete:#785200;
|
|
461
|
+
--paper-grid:rgba(100,105,113,.14); --paper-grid-faint:rgba(100,105,113,.065);
|
|
462
|
+
}
|
|
463
|
+
:root[data-palette="paper"] :is(body,.sidebar,.topbar,.card,.panel,.lower) {
|
|
464
|
+
background-image:linear-gradient(90deg,var(--paper-grid) 1px,transparent 1px),
|
|
465
|
+
linear-gradient(var(--paper-grid) 1px,transparent 1px);
|
|
466
|
+
background-size:18px 18px;
|
|
467
|
+
}
|
|
468
|
+
:root[data-palette="paper"] :is(.card,.panel,.lower) {
|
|
469
|
+
--paper-grid:var(--paper-grid-faint);
|
|
470
|
+
}
|
|
441
471
|
.terminal-sample[data-terminal-palette="pink"] { --sample-logo:#f3a8c8; --sample-table:#f3a8c8; --sample-motion:#f3a8c8; }
|
|
442
472
|
.terminal-sample[data-terminal-palette="orange"] { --sample-logo:#ff9a3d; --sample-table:#ff9a3d; --sample-motion:#ff9a3d; }
|
|
443
473
|
.terminal-sample[data-terminal-palette="mono"] { --sample-bg:#000; --sample-text:#fff; --sample-muted:#aaa; --sample-line:#777; --sample-logo:#fff; --sample-table:#fff; --sample-motion:#fff; }
|
|
@@ -650,6 +680,9 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
650
680
|
|
|
651
681
|
/* Settings-page preferences keep their own draft, save and recovery controls. */
|
|
652
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); }
|
|
653
686
|
.preferences-row { display:flex; align-items:center; justify-content:space-between; gap:20px; padding:12px 0; font-size:13px; }
|
|
654
687
|
.preferences-row:last-of-type { padding-bottom:0; }
|
|
655
688
|
.preferences-row .hint { margin-top:5px; }
|
|
@@ -764,6 +797,20 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
764
797
|
[data-view="overview"] .card { min-height: 0; padding-block: 12px; }
|
|
765
798
|
[data-view="overview"] .card strong { margin-top: 6px; }
|
|
766
799
|
|
|
800
|
+
/* Keep short columns stable and let names and explanations use the remaining width. */
|
|
801
|
+
.column-table { table-layout: fixed; }
|
|
802
|
+
.column-table th[data-width="compact"] { width:min(14ch, 16%); }
|
|
803
|
+
.column-table th[data-width="balanced"] { width:min(22ch, 22%); }
|
|
804
|
+
.usage-table td:nth-child(n+2),
|
|
805
|
+
#source-requests-body td:nth-child(n+3), #provider-requests td:nth-child(n+3) {
|
|
806
|
+
font-variant-numeric:tabular-nums; text-align:right;
|
|
807
|
+
}
|
|
808
|
+
.usage-table th:nth-child(n+2) { text-align:right; }
|
|
809
|
+
@media (max-width:700px) {
|
|
810
|
+
.column-table th[data-width="compact"] { width:min(12ch, 19%); }
|
|
811
|
+
.column-table th[data-width="balanced"] { width:min(18ch, 23%); }
|
|
812
|
+
}
|
|
813
|
+
|
|
767
814
|
/* Fit long identifiers without widening the dashboard. */
|
|
768
815
|
.dense-table { table-layout: fixed; }
|
|
769
816
|
.dense-table :is(th,td) { white-space: normal; overflow-wrap: anywhere; vertical-align: top; }
|
package/src/dashboard/usage.js
CHANGED
|
@@ -133,6 +133,18 @@
|
|
|
133
133
|
}
|
|
134
134
|
|
|
135
135
|
function renderUsageState() {
|
|
136
|
+
const stored = usageData?.storage;
|
|
137
|
+
if (element("usage-storage")) element("usage-storage").hidden = !stored;
|
|
138
|
+
if (stored) {
|
|
139
|
+
if (element("usage-storage-note")) text("usage-storage-note", "usage_storage_limit", {
|
|
140
|
+
days: number(stored.archive_days), limit: number(stored.archive_max_bytes / 1048576),
|
|
141
|
+
});
|
|
142
|
+
const warning = element("usage-storage-warning");
|
|
143
|
+
if (warning) {
|
|
144
|
+
warning.hidden = !(stored.unconfirmed_records || stored.dropped_records || stored.archive_read_failures);
|
|
145
|
+
if (!warning.hidden) text("usage-storage-warning", "usage_storage_gap");
|
|
146
|
+
}
|
|
147
|
+
}
|
|
136
148
|
if (selectedUsageDate.startsWith("<")) text("usage-state", "usage_earlier_before", { date: selectedUsageDate.slice(1) });
|
|
137
149
|
else text("usage-state", selectedUsageDate || "local_log");
|
|
138
150
|
}
|
|
@@ -182,13 +194,18 @@
|
|
|
182
194
|
analyticsSignature = signature;
|
|
183
195
|
const days = analytics.days;
|
|
184
196
|
const range = element("analytics-range").value === "date" ? previousRange : element("analytics-range").value;
|
|
185
|
-
const
|
|
197
|
+
const displayedDays = usageData.filters ? [...(analytics.earlier ? [analytics.earlier] : []), ...days] : range === "all" ? days : days.slice(-Number(range));
|
|
198
|
+
const firstAvailable = displayedDays.findIndex(day => day.available);
|
|
199
|
+
const daily = firstAvailable < 0 ? [] : displayedDays.slice(firstAvailable);
|
|
186
200
|
const maximum = Math.max(1, ...daily.map((day) => {
|
|
187
201
|
const point = analyticsPoint(day, model);
|
|
188
202
|
return point.input_tokens + point.output_tokens;
|
|
189
203
|
}));
|
|
190
204
|
renderDaily(daily, model, maximum);
|
|
191
|
-
|
|
205
|
+
const empty = daily.length === 0;
|
|
206
|
+
for (const id of ["daily-bars", "daily-axis", "daily-legend"]) if (element(id)) element(id).hidden = empty;
|
|
207
|
+
if (element("daily-empty")) element("daily-empty").hidden = !empty;
|
|
208
|
+
text("daily-from", daily[0]?.date === "earlier" ? "usage_earlier" : daily[0]?.date || "—");
|
|
192
209
|
text("daily-to", analytics.to);
|
|
193
210
|
if (commonSignature === calendarSignature) return;
|
|
194
211
|
calendarSignature = commonSignature;
|
|
@@ -229,7 +246,7 @@
|
|
|
229
246
|
calendar.append(button);
|
|
230
247
|
}
|
|
231
248
|
text("analytics-note", "zone_from_to_retained_history_starts_first_oldest_day_may_be_par", {
|
|
232
|
-
zone: analytics.time_zone, from:
|
|
249
|
+
zone: analytics.time_zone, from: displayedDays[0]?.date === "earlier" ? analytics.first_date : displayedDays[0]?.date || analytics.from, to: analytics.to, first: analytics.first_date || phrase("unknown"),
|
|
233
250
|
excluded: analytics.undated_records ? phrase("count_records_with_invalid_future_timestamps_excluded", { count: number(analytics.undated_records) }) : "",
|
|
234
251
|
limit: analytics.models_truncated ? phrase("model_filters_limited_to_100_all_model_totals_include_the_remain") : "",
|
|
235
252
|
});
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
renderTerminalAnimationFrame,
|
|
15
15
|
TERMINAL_ANIMATION_THEMES,
|
|
16
16
|
} from "./terminal-animation.mjs";
|
|
17
|
-
import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageModelGroups, usageProvider } from "./usage-store.mjs";
|
|
17
|
+
import { cacheReadTokens, summarizeUsageLogs, usageCacheHitRate, usageModelGroups, usageProvider, usageLoggingStats } from "./usage-store.mjs";
|
|
18
18
|
import { createUsageAnalytics } from "./usage-analytics.mjs";
|
|
19
19
|
import { analyzeUsageLogs } from "./usage-analysis.mjs";
|
|
20
20
|
import { createUsageQuery } from "./usage-query.mjs";
|
|
@@ -418,7 +418,7 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
418
418
|
...(filtered ? { recordFilter } : {}), ...(analytics ? { onRecord: analytics.record } : {}) });
|
|
419
419
|
const availableModels = analysis?.analytics.models || (observedModels.size ? [...observedModels].sort() : Object.keys(provider ? summary.byModel : summary.bySourceModel || summary.byModel).sort().slice(0, 100));
|
|
420
420
|
if (!abort.signal.aborted) sendJson(res, 200, { source: "local_usage_log", provider: provider || "all", providers: summary.providers, filters: selection.filters, available_models: availableModels,
|
|
421
|
-
...usageTable(summary), ...(analytics ? { analytics: analysis?.analytics || analytics.snapshot() } : {}) });
|
|
421
|
+
...usageTable(summary), storage: { ...usageLoggingStats(), archive_read_failures: summary.archive_read_failures || 0 }, ...(analytics ? { analytics: analysis?.analytics || analytics.snapshot() } : {}) });
|
|
422
422
|
} catch {
|
|
423
423
|
if (!abort.signal.aborted) sendJson(res, 500, { error: "Could not read local usage summary" });
|
|
424
424
|
} finally { abort.cleanup(); }
|
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 === "/")
|
|
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"));
|
package/src/file-rotation.mjs
CHANGED
|
@@ -31,7 +31,7 @@ export function rotateFileIfNeededSync(filePath, incomingBytes, maxBytes) {
|
|
|
31
31
|
|
|
32
32
|
// Callers serialize writers (usage also holds its cross-process file lock).
|
|
33
33
|
// Group adjacent lines without changing the existing per-record rotation rule.
|
|
34
|
-
export async function appendRotatingLines(filePath, lines, maxBytes) {
|
|
34
|
+
export async function appendRotatingLines(filePath, lines, maxBytes, { sealBackup } = {}) {
|
|
35
35
|
let size = 0;
|
|
36
36
|
try {
|
|
37
37
|
const stat = await fs.promises.stat(filePath);
|
|
@@ -51,6 +51,7 @@ export async function appendRotatingLines(filePath, lines, maxBytes) {
|
|
|
51
51
|
const length = Buffer.byteLength(line);
|
|
52
52
|
if (maxBytes > 0 && size > 0 && size + length > maxBytes) {
|
|
53
53
|
await flush();
|
|
54
|
+
await sealBackup?.(filePath);
|
|
54
55
|
await fs.promises.rm(rotatedFilePath(filePath), { force: true });
|
|
55
56
|
await fs.promises.rename(filePath, rotatedFilePath(filePath));
|
|
56
57
|
size = 0;
|
package/src/providers/api.mjs
CHANGED
|
@@ -27,6 +27,8 @@ import { currentRequestContext } from "../request-context.mjs";
|
|
|
27
27
|
import { redactDiagnosticText } from "../diagnostic-text.mjs";
|
|
28
28
|
import { createProviderCooldown, confirmedNetworkFailure } from "../provider-cooldown.mjs";
|
|
29
29
|
import { SOURCE_LIMIT_EVIDENCE, sourceLimitFeedback } from "../source-admission.mjs";
|
|
30
|
+
import { upstreamRetryAfter } from "../upstream-headers.mjs";
|
|
31
|
+
import { createClaudeHealthProbes } from "./claude-health-probes.mjs";
|
|
30
32
|
|
|
31
33
|
const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions", gemini: "/v1beta/models:generateContent" };
|
|
32
34
|
const geminiModelId = id => typeof id === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,139}$/.test(id) && !id.includes("..");
|
|
@@ -54,6 +56,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
54
56
|
if (config.endpoints.responses) targets.push(config.endpoints.responses.replace(/\/+$/, "") + "/compact");
|
|
55
57
|
let network, closed = false;
|
|
56
58
|
const initialization = createAbortAwareSingleflight(), lifetime = new AbortController();
|
|
59
|
+
const healthProbes = createClaudeHealthProbes();
|
|
57
60
|
const retiring = new Set();
|
|
58
61
|
const registry = { models: { data: catalog.filter(model => model.supported_endpoints.includes(paths.responses)) }, source: "configured", generation };
|
|
59
62
|
const getNetwork = async signal => {
|
|
@@ -97,6 +100,18 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
97
100
|
}
|
|
98
101
|
const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
|
|
99
102
|
if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
|
|
103
|
+
const wire = { key, stream, requestModel, headers, serialized };
|
|
104
|
+
if (api === "messages" && options.onClaudeHealthProbe && !options.countTokens && !stream) {
|
|
105
|
+
return healthProbes.run({ url, headers, bodyText: serialized, signal: options.signal, record: options.onClaudeHealthProbe,
|
|
106
|
+
maxResponseBytes: loadRuntimeConfig(env).maxUpstreamResponsesResponseBytes }, signal => sendRequest(url, body, {
|
|
107
|
+
...options, signal: AbortSignal.any([signal, lifetime.signal]),
|
|
108
|
+
onUpstreamStart() { if (!options.signal?.aborted) options.onUpstreamStart?.(); },
|
|
109
|
+
onUpstreamErrorHeaders(status) { if (!options.signal?.aborted) options.onUpstreamErrorHeaders?.(status); },
|
|
110
|
+
}, api, wire));
|
|
111
|
+
}
|
|
112
|
+
return sendRequest(url, body, options, api, wire);
|
|
113
|
+
}
|
|
114
|
+
async function sendRequest(url, body, options, api, { key, stream, requestModel, headers, serialized }) {
|
|
100
115
|
const cooldown = body && !options.countTokens ? cooldowns[api] : null;
|
|
101
116
|
const recovery = cooldown?.enter();let observed = false;
|
|
102
117
|
try {
|
|
@@ -143,7 +158,9 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
143
158
|
}
|
|
144
159
|
if (adapted || schemaCandidate) try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Preserve the original upstream failure. */ }
|
|
145
160
|
const code = `ccdx_api_http_${result.status}`;
|
|
146
|
-
const
|
|
161
|
+
const messagesRateLimit = api === "messages" && result.status === 429;
|
|
162
|
+
const safeHeaders = { "Content-Type": "application/json" };
|
|
163
|
+
const retry = messagesRateLimit ? upstreamRetryAfter(result.headers) : result.headers.get("retry-after");
|
|
147
164
|
for (const name of ["x-request-id", "x-correlation-id", "request-id"]) {
|
|
148
165
|
const value = result.headers.get(name);
|
|
149
166
|
if (value && /^[a-z\d_.:-]{1,80}$/i.test(value) && redactDiagnosticText(value) === value) { safeHeaders["X-Request-Id"] = value;break; }
|
|
@@ -153,7 +170,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
153
170
|
const requestId=currentRequestContext()?.requestId;
|
|
154
171
|
const contextOverflow = api === "messages" && ["context_length_exceeded", "context_window_exceeded"].includes(reason?.code);
|
|
155
172
|
const message=(contextOverflow ? "prompt is too long. " : "")+(reason?.message||"The source rejected the request (HTTP "+result.status+"); no recognised technical reason was returned.")+" Source: "+redactDiagnosticText(config.name||config.id)+". Model: "+redactDiagnosticText(body?.model||"unknown")+". API: "+api+"."+(requestId?" Request: "+requestId+".":"");
|
|
156
|
-
const errorType =
|
|
173
|
+
const errorType = messagesRateLimit ? "rate_limit_error"
|
|
174
|
+
: api === "messages" && ["input_length_invalid", "context_length_exceeded", "context_window_exceeded"].includes(reason?.code) ? "invalid_request_error" : "api_error";
|
|
157
175
|
const failure = new Response(JSON.stringify({ type: "error", error: { type: errorType, code, message,
|
|
158
176
|
...(reason ? { upstream_code: reason.code, ...(reason.parameter ? { param: reason.parameter } : {}), ...(reason.maximum ? { maximum: reason.maximum } : {}) } : {}) } }), { status: result.status, headers: safeHeaders });
|
|
159
177
|
if (sourceLimit) Object.defineProperty(failure, SOURCE_LIMIT_EVIDENCE, { value: sourceLimit });
|
|
@@ -305,6 +323,6 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
305
323
|
}
|
|
306
324
|
return { resp, reqContext: context, errorText: undefined, usedRetryPolicies: new Set() };
|
|
307
325
|
} },
|
|
308
|
-
close() { closed = true;lifetime.abort();network?.close();for (const previous of retiring) previous.close();retiring.clear(); },
|
|
326
|
+
close() { closed = true;lifetime.abort();healthProbes.clear();network?.close();for (const previous of retiring) previous.close();retiring.clear(); },
|
|
309
327
|
};
|
|
310
328
|
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
2
|
+
import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
|
|
3
|
+
import { MAX_UPSTREAM_ERROR_BODY_BYTES, readBoundedResponseText } from "../http-transport.mjs";
|
|
4
|
+
import { safeUpstreamResponseHeaders } from "../upstream-headers.mjs";
|
|
5
|
+
|
|
6
|
+
const REUSE_MS = 250;
|
|
7
|
+
const MAX_RETAINED_BYTES = 8 * 1024;
|
|
8
|
+
const MAX_RETAINED_RESULTS = 16;
|
|
9
|
+
const SESSION_HEADERS = ["session_id", "session-id", "x-conversation-id", "x-claude-code-session-id"];
|
|
10
|
+
|
|
11
|
+
export function isClaudeHealthProbe(body, headers) {
|
|
12
|
+
const message = body.messages[0];
|
|
13
|
+
return body.max_tokens === 1 && Object.keys(body).length === 3 && body.messages.length === 1
|
|
14
|
+
&& message?.role === "user" && message.content === "." && Object.keys(message).length === 2
|
|
15
|
+
&& SESSION_HEADERS.every(name => !headers[name]);
|
|
16
|
+
}
|
|
17
|
+
|
|
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;
|
|
22
|
+
try {
|
|
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";
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function responseHeaders(response) {
|
|
36
|
+
const headers = safeUpstreamResponseHeaders(response.headers);
|
|
37
|
+
if (headers["X-Upstream-Request-Id"]) {
|
|
38
|
+
headers["X-Request-Id"] = headers["X-Upstream-Request-Id"];
|
|
39
|
+
delete headers["X-Upstream-Request-Id"];
|
|
40
|
+
}
|
|
41
|
+
for (const [name, value] of response.headers) if (/^anthropic-ratelimit-[a-z0-9-]+$/.test(name)) headers[name] = value;
|
|
42
|
+
return headers;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function createClaudeHealthProbes({ now = () => performance.now() } = {}) {
|
|
46
|
+
const flights = createAbortAwareSingleflight(), recent = new Map();
|
|
47
|
+
let keySecret;
|
|
48
|
+
function remove(key) {
|
|
49
|
+
clearTimeout(recent.get(key)?.expiry);
|
|
50
|
+
recent.delete(key);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
clear() { for (const key of recent.keys()) remove(key); },
|
|
55
|
+
async run({ url, headers, bodyText, maxResponseBytes, signal, record }, send) {
|
|
56
|
+
signal?.throwIfAborted();
|
|
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");
|
|
61
|
+
const at = now();
|
|
62
|
+
for (const [id, result] of recent) if (at - result.at >= REUSE_MS) remove(id);
|
|
63
|
+
const owner = Symbol();
|
|
64
|
+
const retained = recent.get(key);
|
|
65
|
+
const result = retained || await flights.run(key, async signal => {
|
|
66
|
+
const response = await send(signal);
|
|
67
|
+
const text = await readBoundedResponseText(response, { signal, label: "Claude health check response",
|
|
68
|
+
maxBytes: response.ok ? maxResponseBytes : MAX_UPSTREAM_ERROR_BODY_BYTES });
|
|
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) {
|
|
73
|
+
remove(key);
|
|
74
|
+
result.expiry = setTimeout(() => remove(key), REUSE_MS);
|
|
75
|
+
result.expiry.unref?.();
|
|
76
|
+
recent.set(key, result);
|
|
77
|
+
if (recent.size > MAX_RETAINED_RESULTS) remove(recent.keys().next().value);
|
|
78
|
+
}
|
|
79
|
+
return result;
|
|
80
|
+
}, { signal });
|
|
81
|
+
signal?.throwIfAborted();
|
|
82
|
+
const reused = owner !== result.owner;
|
|
83
|
+
record({
|
|
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),
|
|
88
|
+
claimUsage() {
|
|
89
|
+
if (result.usageRecorded) return false;
|
|
90
|
+
result.usageRecorded = true;
|
|
91
|
+
return true;
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
return new Response(result.text || null, { status: result.status, headers: result.headers });
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
@@ -189,7 +189,7 @@ export function isDiscoveryRequest(method, pathname) {
|
|
|
189
189
|
|
|
190
190
|
export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers, model_error,
|
|
191
191
|
error_body, error_type, upstream_code, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
|
|
192
|
-
application, reason, capability_cached, shared_upstream, transport }) {
|
|
192
|
+
application, verified_application, reason, capability_cached, shared_upstream, transport }) {
|
|
193
193
|
if (!reason && code === "ccdx_client_source_disabled" && upstream_attempts === 0 && origin !== "upstream_http") {
|
|
194
194
|
reason = code;origin = "client_validation";
|
|
195
195
|
}
|
|
@@ -229,6 +229,7 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
|
|
|
229
229
|
...(requested_model ? { requested_model, request_kind: requested_model === "codex-auto-review" ? "auto_review" : "unknown" } : {}),
|
|
230
230
|
...(["codex_app", "codex_cli", "codex", "claude_app", "claude_code", "claude", "gemini_app", "api"].includes(application) ? { application } : {}),
|
|
231
231
|
...(Object.hasOwn(reasons, reason) ? { reason } : {}),
|
|
232
|
+
...(["codex", "claude_app", "claude_code"].includes(verified_application) ? { verified_application } : {}),
|
|
232
233
|
...(capability_cached === true ? { capability_cached: true } : {}), ...(shared_upstream === true ? { shared_upstream: true } : {}),
|
|
233
234
|
...(transport ? { transport: transportErrorDetails({ transport }) } : {}),
|
|
234
235
|
...(Number.isSafeInteger(upstream_attempts) ? { upstream_attempts } : {}) };
|
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"],
|
|
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") {
|
package/src/source-admission.mjs
CHANGED
|
@@ -86,7 +86,7 @@ export function createSourceAdmission({ now = Date.now, initialLimit = MAX_LIMIT
|
|
|
86
86
|
const activeRevision = deployment?.account === account ? deployment.revision : revision;
|
|
87
87
|
const key = fingerprint(activeRevision ? identity + "\0" + activeRevision : identity);
|
|
88
88
|
const saved = learned[key], restored = validLimit(saved?.limit) && saved?.limit !== null && now() >= saved.at && now() - saved.at < 86400000;
|
|
89
|
-
group = { source, key, revision: activeRevision, limit: restored ? saved.limit : initialLimit, active: 0, queue: [], models: new Map(), lastClient: null,
|
|
89
|
+
group = { source, key, revision: activeRevision, deploymentEpoch: 0, limit: restored ? saved.limit : initialLimit, active: 0, queue: [], models: new Map(), lastClient: null,
|
|
90
90
|
epoch: 0, stableAt: now(), successes: 0, readyToGrow: false, lastStableNotice: now(), pausedUntil: 0, reason: null, timer: null, completed: 0, rejected: 0 };
|
|
91
91
|
groups.set(identity, group);
|
|
92
92
|
}
|
|
@@ -126,7 +126,7 @@ export function createSourceAdmission({ now = Date.now, initialLimit = MAX_LIMIT
|
|
|
126
126
|
arm(group);
|
|
127
127
|
}
|
|
128
128
|
function feedback(group, entry, value) {
|
|
129
|
-
if (!value || entry.
|
|
129
|
+
if (!value || !entry.currentDeployment()) return;
|
|
130
130
|
const until = now() + Math.min(7 * 86400000, value.delay);
|
|
131
131
|
const model = modelState(group, entry.model);
|
|
132
132
|
if (value.scope === "source") { group.pausedUntil = Math.max(group.pausedUntil, until);group.reason = value.kind; }
|
|
@@ -147,12 +147,13 @@ export function createSourceAdmission({ now = Date.now, initialLimit = MAX_LIMIT
|
|
|
147
147
|
arm(group);
|
|
148
148
|
}
|
|
149
149
|
class Lease {
|
|
150
|
-
constructor(group, model, client, revision) { this.group = group;this.model = model;this.client = client;this.revision = revision;this.epoch = group.epoch;this.bytes = 0;this.released = false;this.observed = false; }
|
|
150
|
+
constructor(group, model, client, revision) { this.group = group;this.model = model;this.client = client;this.revision = revision;this.deploymentEpoch = group.deploymentEpoch;this.epoch = group.epoch;this.bytes = 0;this.released = false;this.observed = false; }
|
|
151
|
+
currentDeployment() { return this.revision === this.group.revision && this.deploymentEpoch === this.group.deploymentEpoch; }
|
|
151
152
|
limit(value) { this.observed = true;feedback(this.group, this, value); }
|
|
152
153
|
streamFailure(error, headers) { const value = sourceLimitFeedback(429, headers, { error }, now());if (value?.kind !== "unknown") this.limit(value); }
|
|
153
154
|
observe(status, headers, body) {
|
|
154
155
|
const group = this.group, entry = this;
|
|
155
|
-
if (entry.
|
|
156
|
+
if (!entry.currentDeployment()) return;
|
|
156
157
|
if (!this.headersObserved) {
|
|
157
158
|
this.headersObserved = true;
|
|
158
159
|
const declared = headers?.get?.("x-ratelimit-concurrency-limit");
|
|
@@ -170,7 +171,7 @@ export function createSourceAdmission({ now = Date.now, initialLimit = MAX_LIMIT
|
|
|
170
171
|
release(success = false) {
|
|
171
172
|
if (this.released) return;this.released = true;
|
|
172
173
|
const group = this.group, entry = this, model = this.modelState;group.active--;if (model) model.active--;group.completed++;
|
|
173
|
-
if (success && !this.observed && entry.
|
|
174
|
+
if (success && !this.observed && entry.currentDeployment()) {
|
|
174
175
|
group.successes = Math.min(8, group.successes + 1);
|
|
175
176
|
const mature = group.successes >= 8 && now() - group.stableAt >= stableMs;
|
|
176
177
|
group.readyToGrow ||= mature;
|
|
@@ -301,6 +302,7 @@ export function createSourceAdmission({ now = Date.now, initialLimit = MAX_LIMIT
|
|
|
301
302
|
Object.assign(group, { key: fingerprint(identity + "\0" + revision), revision, limit: initialLimit,
|
|
302
303
|
epoch: 0, stableAt: time, successes: 0, readyToGrow: false, lastStableNotice: time,
|
|
303
304
|
pausedUntil: 0, reason: null, advertised: undefined, advertisedUntil: 0 });
|
|
305
|
+
group.deploymentEpoch++;
|
|
304
306
|
group.models.clear();
|
|
305
307
|
drain(group);
|
|
306
308
|
},
|
|
@@ -360,6 +360,13 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
360
360
|
if (values.body_queue) context.body_queue = values.body_queue;
|
|
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
|
+
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
|
+
}
|
|
369
|
+
if (["codex", "claude_app", "claude_code"].includes(values.verified_application)) context.verified_application = values.verified_application;
|
|
363
370
|
if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
|
|
364
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"]) {
|
|
365
372
|
const value = values[key];
|
|
@@ -373,7 +380,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
373
380
|
if (["capability_revision", "capability_constraints"].includes(key)) {
|
|
374
381
|
if (typeof value === "string" && /^[a-z0-9_,]{1,80}$/.test(value)) context[key] = value;continue;
|
|
375
382
|
}
|
|
376
|
-
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;
|
|
377
385
|
}
|
|
378
386
|
},
|
|
379
387
|
setErrorOrigin(value) {
|
|
@@ -387,7 +395,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
387
395
|
if (terminalModel !== undefined) model = modelLabel(terminalModel);
|
|
388
396
|
if (TERMINAL_ORIGINS.has(origin)) terminalOrigin = origin;
|
|
389
397
|
if (outcome === "incomplete") incompleteReason = INCOMPLETE_REASONS.has(reason) ? reason : "other";
|
|
390
|
-
if (["end_turn", "max_tokens", "tool_use", "stop_sequence", "pause_turn", "refusal", "model_context_window_exceeded"].includes(stopped)) stopReason = stopped;
|
|
398
|
+
if (["end_turn", "max_tokens", "tool_use", "stop_sequence", "pause_turn", "refusal", "model_context_window_exceeded", "content_filter"].includes(stopped)) stopReason = stopped;
|
|
391
399
|
if (outcome !== "completed") failed = true;
|
|
392
400
|
},
|
|
393
401
|
fail() {
|
package/src/terminal-console.mjs
CHANGED
|
@@ -82,22 +82,24 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
|
|
|
82
82
|
if (dirty) {
|
|
83
83
|
const usage = data.runtime_usage || {}, view = projection;
|
|
84
84
|
const heading = readFailed ? updatedAt === null ? "Status unavailable" : `Previous data / ${new Date(updatedAt).toLocaleTimeString("en-GB")}`
|
|
85
|
-
: `Running
|
|
85
|
+
: `Running for ${terminalUptime(data.uptime_ms)}`;
|
|
86
86
|
const webAddress = baseUrl ? `Web UI: ${baseUrl}` : "Web UI: address unavailable";
|
|
87
87
|
const sourceHeader = view.sources ? `Enabled sources: ${view.sources.length}` : "Enabled sources: unknown";
|
|
88
88
|
const appSize = width < 64 ? 13 : 15, setupSize = Math.max(10, Math.min(20, width - appSize - 7));
|
|
89
89
|
const appRows = view.clients.map(client => `${clip(client.name, appSize - 1).padEnd(appSize)}${clip(client.setup, setupSize - 1).padEnd(setupSize)}${String(readFailed || client.active === null ? "—" : client.active).padStart(6)}`);
|
|
90
90
|
const issue = view.issue?.label;
|
|
91
|
-
const notice =
|
|
91
|
+
const notice = issue ? `Last request issue: ${issue}`
|
|
92
|
+
: notices ? `${notices} ${notices === 1 ? "notice" : "notices"}. Run ccdx status --details.`
|
|
93
|
+
: imageRuntime?.error ? "Image tools need attention. Run ccdx app codex image status." : "";
|
|
92
94
|
content = [clip(heading, width), clip(webAddress, width), sourceHeader,
|
|
93
|
-
...(view.sources ? wrap(view.sources.map(source => source.name).join("
|
|
95
|
+
...(view.sources ? wrap(view.sources.map(source => source.name).join(", "), width) : []),
|
|
94
96
|
`${"App".padEnd(appSize)}${"Setup".padEnd(setupSize)}${"Active".padStart(6)}`, ...appRows,
|
|
95
97
|
...table(width, usage, view.requests, readFailed ? null : view.active, key => view.outcomes[key]),
|
|
96
|
-
clip("Help: ccdx help
|
|
98
|
+
clip("Help: ccdx help Stop: Ctrl+C", width), notice ? clip(notice, width) : ""];
|
|
97
99
|
if (content.length + 1 >= (Number(output.rows) || 24)) {
|
|
98
100
|
const grouped = Object.entries(view.clients.reduce((counts, client) => ({ ...counts, [client.setup]: (counts[client.setup] || 0) + 1 }), {})).map(([state, count]) => `${count} ${state.toLowerCase()}`).join(" · ");
|
|
99
101
|
content = [clip(readFailed ? heading : webAddress, width), sourceHeader, clip(`Apps: ${grouped}`, width),
|
|
100
|
-
...table(width, usage, view.requests, readFailed ? null : view.active, key => view.outcomes[key], true), clip(notice, width)];
|
|
102
|
+
...table(width, usage, view.requests, readFailed ? null : view.active, key => view.outcomes[key], true), notice ? clip(notice, width) : ""];
|
|
101
103
|
}
|
|
102
104
|
dirty = false;
|
|
103
105
|
}
|