@barivia/barmesh-mcp 0.8.9 → 0.8.11
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/README.md +8 -5
- package/dist/audit.js +9 -3
- package/dist/index.js +1 -1
- package/dist/job_monitor.js +19 -1
- package/dist/shared.js +46 -9
- package/dist/tools/barmesh_results_explorer.js +1 -0
- package/dist/tools/feedback.js +6 -1
- package/dist/tools/jobs.js +3 -2
- package/dist/tools/training_monitor.js +24 -10
- package/dist/ui-delivery.js +41 -8
- package/dist/views/src/views/barmesh-results-explorer/index.html +1 -1
- package/dist/views/src/views/barmesh-training-monitor/index.html +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -44,14 +44,16 @@ These complement, and do not replace, conventional numerical uncertainty analysi
|
|
|
44
44
|
```
|
|
45
45
|
|
|
46
46
|
Access to the analysis tools requires the **`cfd`** (or **`all_plus_cfd`**) entitlement on your
|
|
47
|
-
API key; otherwise the analysis calls return HTTP 403.
|
|
47
|
+
API key; otherwise the analysis calls return HTTP 403. **`barmesh_guide_workflow`** /
|
|
48
|
+
**`barmesh_prepare_mesh_data`** also redact their API bodies to an upgrade stub when the key
|
|
49
|
+
is not CFD-entitled (method/prep details are not returned). Contact Barivia to enable it.
|
|
48
50
|
|
|
49
51
|
## Tools
|
|
50
52
|
|
|
51
53
|
| Tool | Purpose |
|
|
52
54
|
|------|---------|
|
|
53
|
-
| `barmesh_guide_workflow` | Workflow + tool map (
|
|
54
|
-
| `barmesh_prepare_mesh_data` |
|
|
55
|
+
| `barmesh_guide_workflow` | Workflow + tool map from the API (full text when CFD-entitled). Call first. |
|
|
56
|
+
| `barmesh_prepare_mesh_data` | Mesh CSV recipe from the API (full text when CFD-entitled). |
|
|
55
57
|
| `barmesh_datasets` | Upload / preview / list / get / subset / delete the mesh CSV. |
|
|
56
58
|
| `barmesh_mesh_convergence` | SOM fingerprint distances (async job). |
|
|
57
59
|
| `barmesh_richardson` | Richardson/GCI on scalar QoIs (async job). |
|
|
@@ -91,7 +93,7 @@ API key; otherwise the analysis calls return HTTP 403. Contact Barivia to enable
|
|
|
91
93
|
### Migration notes
|
|
92
94
|
|
|
93
95
|
- **Feature-plane divergences (0.8.1):** Mesh jobs write `divergence_kl` / `feature_divergences.json` / `weights.json` (barsom-parallel). These measure association between SOM **component planes** — not mesh-vs-mesh fingerprint SKL/EMD (`KL_ref`, `EMD_*`). Refresh or add Wasserstein via `barmesh_results(action=feature_divergences)`.
|
|
94
|
-
- **UI delivery + mesh_order (0.7.3+ / 0.8.0):** App tools emit structured `ui_delivery` and **always put the standalone viz URL first** (hosts may advertise MCP Apps without mounting widgets). Env: `BARIVIA_UI_DELIVERY` (`auto` \| `apps` \| `localhost` \| `inline`), `BARIVIA_VIZ_PORT`. Default mesh_order interleaves U/G at tied cell counts; Richardson warns on mixed topology families.
|
|
96
|
+
- **UI delivery + mesh_order (0.7.3+ / 0.8.0 / 0.8.10+):** App tools emit structured `ui_delivery` and **always put the standalone viz URL first** (hosts may advertise MCP Apps without mounting widgets). Env: `BARIVIA_UI_DELIVERY` (`auto` \| `apps` \| `localhost` \| `inline` \| `text_only`), `BARIVIA_UI_PREFER_LOCALHOST=1` (opt-in localhost under `auto`), `BARIVIA_VIZ_PORT`. Default mesh_order interleaves U/G at tied cell counts; Richardson warns on mixed topology families.
|
|
95
97
|
- **Fixed-panel live TE (0.6.3 / barsom 0.20.4):** mid-training TE uses a fixed evaluation panel (`te_panel_size`; `te_inner_samples` alias). Curves stay on panel TE; monitors show **Panel TE** and **Map TE** separately — no snap-to-map on the curve tail.
|
|
96
98
|
- **`barmesh_training_monitor` (0.5.3):** server-side blocking monitor with throttled snapshots — preferred after job submit instead of manual `barmesh_jobs(status)` loops. Equivalent to `barmesh_jobs(action=monitor)`.
|
|
97
99
|
- **`send_feedback` → `barmesh_send_feedback` (0.3.0):** the feedback tool was renamed so it no longer collides with the `@barivia/barsom-mcp` tool of the same name when both servers are enabled in one client. Update any direct call sites; the behavior is unchanged.
|
|
@@ -118,4 +120,5 @@ Parquet staging is supported by the API but not yet exposed as an MCP upload for
|
|
|
118
120
|
| `BARIVIA_WORKSPACE_ROOT` | workspace/cwd | Root for resolving relative `file_path` uploads. |
|
|
119
121
|
| `BARIVIA_ENFORCE_WORKSPACE_SANDBOX` | `1` | Restrict uploads to the workspace; set `0` to allow absolute paths. |
|
|
120
122
|
| `BARIVIA_VIZ_PORT` | ephemeral | Fixed localhost port for standalone App pages (otherwise OS-assigned per session). |
|
|
121
|
-
| `BARIVIA_UI_DELIVERY` | `auto` | Client-capability override for App tools: `auto` \| `apps` \| `localhost` \| `inline`. Responses always lead with a standalone localhost URL. |
|
|
123
|
+
| `BARIVIA_UI_DELIVERY` | `auto` | Client-capability override for App tools: `auto` \| `apps` \| `localhost` \| `inline` \| `text_only`. Responses always lead with a standalone localhost URL. |
|
|
124
|
+
| `BARIVIA_UI_PREFER_LOCALHOST` | (off) | Set `1` to force `localhost` under `auto` even when the host advertises MCP Apps. |
|
package/dist/audit.js
CHANGED
|
@@ -88,11 +88,17 @@ export async function runMcpToolAudit(tool, action, args, handler) {
|
|
|
88
88
|
throw err;
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
|
-
export function registerAuditedTool(server, name, description, schema, handler) {
|
|
92
|
-
|
|
91
|
+
export function registerAuditedTool(server, name, description, schema, handler, annotations) {
|
|
92
|
+
const cb = (async (args) => {
|
|
93
93
|
const rec = args;
|
|
94
94
|
const action = typeof rec.action === "string" && rec.action.length > 0 ? rec.action : "default";
|
|
95
95
|
// One trace per tool invocation (every apiCall inside shares one trace_id).
|
|
96
96
|
return runWithTrace(() => runMcpToolAudit(name, action, rec, () => handler(args)));
|
|
97
|
-
})
|
|
97
|
+
});
|
|
98
|
+
if (annotations) {
|
|
99
|
+
server.tool(name, description, schema, annotations, cb);
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
server.tool(name, description, schema, cb);
|
|
103
|
+
}
|
|
98
104
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{McpServer as e}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as
|
|
2
|
+
import{McpServer as e}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as o}from"@modelcontextprotocol/sdk/server/stdio.js";import{getUiCapability as r,registerAppResource as s,RESOURCE_MIME_TYPE as t}from"@modelcontextprotocol/ext-apps/server";import{startVizServer as n}from"./viz-server.js";import{API_KEY as i,CLIENT_VERSION as a,apiCall as m,apiRawCall as l,loadViewHtml as c,setVizPort as p,setClientSupportsMcpApps as h}from"./shared.js";import{registerGuideTool as d}from"./tools/guide.js";import{registerDatasetsTool as _}from"./tools/datasets.js";import{registerCfdTools as b}from"./tools/cfd.js";import{registerJobsTool as u}from"./tools/jobs.js";import{registerResultsTool as f}from"./tools/results.js";import{registerResultsExplorerTool as v,RESULTS_EXPLORER_URI as y}from"./tools/barmesh_results_explorer.js";import{registerTrainingMonitorTool as I,TRAINING_MONITOR_URI as w}from"./tools/training_monitor.js";import{registerFeedbackTool as g}from"./tools/feedback.js";i||(console.error("Error: BARIVIA_API_KEY not set. Set it in your MCP client config."),process.exit(1));(async function(){const i=new e({name:"barmesh",version:a},{instructions:"# Barivia barmesh — CFD mesh-convergence analytics\n\n## Bootstrap (do this first)\n\nCall `barmesh_guide_workflow` (plan-scoped) and `barmesh_prepare_mesh_data` before upload/submit. Method details and mesh-prep recipe come from the API when your key has the CFD entitlement.\n\n## Tracks (names only)\n\n- `barmesh_mesh_convergence` — field-level mesh comparison (SOM fingerprints)\n- `barmesh_richardson` — classical Richardson/GCI on scalar QoIs\n\n## Workflow (short)\n\n1. `barmesh_guide_workflow`\n2. `barmesh_prepare_mesh_data`\n3. `barmesh_datasets(upload)` → preview\n4. Submit mesh_convergence and/or richardson → job_id\n5. `barmesh_training_monitor` or `barmesh_jobs(monitor/status)`\n6. `barmesh_results(get)` → `barmesh_results_explorer`\n\nInventory: `barmesh_jobs(inventory)` or list datasets+jobs. Set description/tags on upload/submit.\n\n## UI / outages\n\nTool results lead with a localhost viz URL and `ui_delivery` — follow `hint_for_agent`. Env: `BARIVIA_UI_DELIVERY` (auto|apps|localhost|inline|text_only), `BARIVIA_UI_PREFER_LOCALHOST=1` (opt-in localhost even when Apps advertised), `BARIVIA_VIZ_PORT`.\nOn `api_unreachable`: one calm line; honor `retry_after_sec`; use `barmesh_api_health`; keep reviewing last good figures. `barmesh_send_feedback` queues deferred drafts when the API is down."});s(i,y,y,{mimeType:t},async()=>{const e=await c("barmesh-results-explorer");return{contents:[{uri:y,mimeType:t,text:e??"<html><body>Results Explorer view not built yet. Run: npm run build:views</body></html>"}]}}),s(i,w,w,{mimeType:t},async()=>{const e=await c("barmesh-training-monitor");return{contents:[{uri:w,mimeType:t,text:e??"<html><body>Training Monitor view not built yet. Run: npm run build:views</body></html>"}]}}),d(i),v(i),_(i),b(i),u(i),I(i),f(i),g(i);try{const e=await n(m,l,c);p(e)}catch(e){process.env.BARIVIA_VIZ_PORT&&console.error("barmesh viz server failed to start:",e)}const A=i.server;A.oninitialized=()=>{const e=A.getClientCapabilities(),o=r(e);h(!!o?.mimeTypes?.includes(t))};const j=new o;await i.connect(j),console.error(`barmesh-mcp ${a} ready (API: ${process.env.BARIVIA_API_URL??"https://api.barivia.se"})`)})().catch(e=>{console.error("Fatal error starting barmesh-mcp:",e),process.exit(1)});
|
package/dist/job_monitor.js
CHANGED
|
@@ -11,6 +11,9 @@ export const DEFAULT_BLOCK_UNTIL_SEC = 900;
|
|
|
11
11
|
export const DEFAULT_POLL_INTERVAL_SEC = 5;
|
|
12
12
|
export const MIN_POLL_INTERVAL_SEC = 5;
|
|
13
13
|
export const HEARTBEAT_POLLS = 1;
|
|
14
|
+
/** After this many unchanged polls, gently raise interval (never below MIN_POLL). */
|
|
15
|
+
export const IDLE_BACKOFF_AFTER_POLLS = 8;
|
|
16
|
+
export const MAX_POLL_INTERVAL_SEC = 15;
|
|
14
17
|
function sleep(ms) {
|
|
15
18
|
return new Promise((r) => setTimeout(r, ms));
|
|
16
19
|
}
|
|
@@ -219,6 +222,7 @@ export async function monitorJob(job_id, options = {}) {
|
|
|
219
222
|
return buildPostHocReview(job_id, data, suggested);
|
|
220
223
|
}
|
|
221
224
|
let heartbeat = 0;
|
|
225
|
+
let idleStreak = 0;
|
|
222
226
|
while (Date.now() - start < blockMs) {
|
|
223
227
|
if (snapshots.length === 0) {
|
|
224
228
|
/* first fetch already done above */
|
|
@@ -230,6 +234,15 @@ export async function monitorJob(job_id, options = {}) {
|
|
|
230
234
|
const snap = snapshotFromJob(data, elapsedSec);
|
|
231
235
|
heartbeat += 1;
|
|
232
236
|
const heartbeatDue = heartbeat >= HEARTBEAT_POLLS;
|
|
237
|
+
const unchanged = lastSnap != null &&
|
|
238
|
+
lastSnap.status === snap.status &&
|
|
239
|
+
lastSnap.progress_pct === snap.progress_pct &&
|
|
240
|
+
lastSnap.phase === snap.phase &&
|
|
241
|
+
lastSnap.epoch === snap.epoch;
|
|
242
|
+
if (unchanged)
|
|
243
|
+
idleStreak += 1;
|
|
244
|
+
else
|
|
245
|
+
idleStreak = 0;
|
|
233
246
|
if (shouldRecordSnapshot(lastSnap, snap) || heartbeatDue) {
|
|
234
247
|
snapshots.push(snap);
|
|
235
248
|
lastSnap = snap;
|
|
@@ -239,7 +252,12 @@ export async function monitorJob(job_id, options = {}) {
|
|
|
239
252
|
if (status === "completed" || status === "failed" || status === "cancelled") {
|
|
240
253
|
break;
|
|
241
254
|
}
|
|
242
|
-
|
|
255
|
+
let waitMs = pollMs;
|
|
256
|
+
if (idleStreak >= IDLE_BACKOFF_AFTER_POLLS) {
|
|
257
|
+
const steps = Math.floor((idleStreak - IDLE_BACKOFF_AFTER_POLLS) / 2);
|
|
258
|
+
waitMs = Math.min(pollMs + steps * 5000, MAX_POLL_INTERVAL_SEC * 1000);
|
|
259
|
+
}
|
|
260
|
+
await sleep(Math.max(MIN_POLL_INTERVAL_SEC * 1000, waitMs));
|
|
243
261
|
}
|
|
244
262
|
const status = String(data.status ?? "");
|
|
245
263
|
const terminal = status === "completed" || status === "failed" || status === "cancelled";
|
package/dist/shared.js
CHANGED
|
@@ -27,15 +27,42 @@ export const RETRY_BASE_MS = parseInt(process.env.BARIVIA_RETRY_BASE_MS ?? "2000
|
|
|
27
27
|
export const RETRYABLE_STATUS = new Set([502, 503, 504]);
|
|
28
28
|
/** Cool-down hint after the burst is exhausted — agents should wait before another round. */
|
|
29
29
|
export const UNAVAILABLE_RETRY_AFTER_SEC = 30;
|
|
30
|
-
/**
|
|
31
|
-
|
|
30
|
+
/**
|
|
31
|
+
* Delay between burst retries. Keeps the flat RETRY_BASE_MS default (short gateway
|
|
32
|
+
* blips); when the server sends Retry-After / retry_after_sec, sleep at least that long.
|
|
33
|
+
*/
|
|
34
|
+
export function retryDelayMs(_attempt, retryAfterMs) {
|
|
35
|
+
if (retryAfterMs != null && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
|
|
36
|
+
return Math.max(RETRY_BASE_MS, Math.floor(retryAfterMs));
|
|
37
|
+
}
|
|
32
38
|
return RETRY_BASE_MS;
|
|
33
39
|
}
|
|
40
|
+
/** Parse Retry-After header (delta-seconds) and/or JSON body retry_after_sec → ms. */
|
|
41
|
+
export function parseRetryAfterMs(resp, bodyText) {
|
|
42
|
+
const header = resp.headers.get("Retry-After");
|
|
43
|
+
if (header) {
|
|
44
|
+
const sec = parseInt(header.trim(), 10);
|
|
45
|
+
if (!Number.isNaN(sec) && sec >= 0)
|
|
46
|
+
return sec * 1000;
|
|
47
|
+
}
|
|
48
|
+
if (bodyText) {
|
|
49
|
+
try {
|
|
50
|
+
const j = JSON.parse(bodyText);
|
|
51
|
+
const sec = Number(j.retry_after_sec);
|
|
52
|
+
if (Number.isFinite(sec) && sec >= 0)
|
|
53
|
+
return sec * 1000;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
/* not JSON */
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
34
61
|
function newRequestId() {
|
|
35
62
|
return randomUUID();
|
|
36
63
|
}
|
|
37
64
|
/** Single source of truth for the proxy version. Keep in sync with package.json on bump. */
|
|
38
|
-
export const CLIENT_VERSION = "0.8.
|
|
65
|
+
export const CLIENT_VERSION = "0.8.11";
|
|
39
66
|
export const PUBLIC_SITE_ORIGIN = "https://barivia.se";
|
|
40
67
|
/** Large per-cell CSV uploads may exceed the default fetch timeout. */
|
|
41
68
|
export const UPLOAD_DATASET_TIMEOUT_MS = 180_000;
|
|
@@ -148,7 +175,11 @@ export function suggestAfterCfdSubmit(jobId, prepSuffix = "") {
|
|
|
148
175
|
export function suggestAfterRender(parentJobId, fmt) {
|
|
149
176
|
return `Figures rendered as ${fmt}. Download with barmesh_results(action=download, job_id="${parentJobId}") or barmesh_results(action=image, job_id="${parentJobId}", filename=<figure>.${fmt}).`;
|
|
150
177
|
}
|
|
151
|
-
/**
|
|
178
|
+
/**
|
|
179
|
+
* Streaming SHA-256 of a file without reading it into memory.
|
|
180
|
+
* Used by tools/datasets.ts upload as Idempotency-Key = sha256(name+body) — do not
|
|
181
|
+
* invent a second key path here.
|
|
182
|
+
*/
|
|
152
183
|
export async function streamFileSha256(srcPath) {
|
|
153
184
|
return new Promise((resolve, reject) => {
|
|
154
185
|
const h = createHash("sha256");
|
|
@@ -707,7 +738,7 @@ export async function apiCall(method, pathPart, body, extraHeaders, requestTimeo
|
|
|
707
738
|
const text = await resp.text();
|
|
708
739
|
if (!resp.ok) {
|
|
709
740
|
if (attempt < MAX_RETRIES && isTransientError(null, resp.status)) {
|
|
710
|
-
const delayMs = retryDelayMs(attempt);
|
|
741
|
+
const delayMs = retryDelayMs(attempt, parseRetryAfterMs(resp, text));
|
|
711
742
|
logWarn("API retry", {
|
|
712
743
|
rid: requestId,
|
|
713
744
|
action: method,
|
|
@@ -729,7 +760,10 @@ export async function apiCall(method, pathPart, body, extraHeaders, requestTimeo
|
|
|
729
760
|
catch (err) {
|
|
730
761
|
lastError = err;
|
|
731
762
|
if (attempt < MAX_RETRIES && isTransientError(err)) {
|
|
732
|
-
const
|
|
763
|
+
const errRetryMs = typeof err.retryAfterSec === "number"
|
|
764
|
+
? err.retryAfterSec * 1000
|
|
765
|
+
: undefined;
|
|
766
|
+
const delayMs = retryDelayMs(attempt, errRetryMs);
|
|
733
767
|
logWarn("API retry", {
|
|
734
768
|
rid: requestId,
|
|
735
769
|
action: method,
|
|
@@ -764,8 +798,9 @@ export async function apiRawCall(pathPart, requestTimeoutMs) {
|
|
|
764
798
|
try {
|
|
765
799
|
const resp = await fetchWithTimeout(url, { method: "GET", headers: { Authorization: `Bearer ${API_KEY}`, "X-Request-ID": requestId, traceparent: _traceparentHeader() } }, effectiveTimeout);
|
|
766
800
|
if (!resp.ok) {
|
|
801
|
+
const text = await resp.text();
|
|
767
802
|
if (attempt < MAX_RETRIES && isTransientError(null, resp.status)) {
|
|
768
|
-
const delayMs = retryDelayMs(attempt);
|
|
803
|
+
const delayMs = retryDelayMs(attempt, parseRetryAfterMs(resp, text));
|
|
769
804
|
logWarn("API retry", {
|
|
770
805
|
rid: requestId,
|
|
771
806
|
path: pathPart,
|
|
@@ -777,7 +812,6 @@ export async function apiRawCall(pathPart, requestTimeoutMs) {
|
|
|
777
812
|
await new Promise((r) => setTimeout(r, delayMs));
|
|
778
813
|
continue;
|
|
779
814
|
}
|
|
780
|
-
const text = await resp.text();
|
|
781
815
|
throwApiError(resp.status, text, requestId);
|
|
782
816
|
}
|
|
783
817
|
const arrayBuf = await resp.arrayBuffer();
|
|
@@ -789,7 +823,10 @@ export async function apiRawCall(pathPart, requestTimeoutMs) {
|
|
|
789
823
|
catch (err) {
|
|
790
824
|
lastError = err;
|
|
791
825
|
if (attempt < MAX_RETRIES && isTransientError(err)) {
|
|
792
|
-
const
|
|
826
|
+
const errRetryMs = typeof err.retryAfterSec === "number"
|
|
827
|
+
? err.retryAfterSec * 1000
|
|
828
|
+
: undefined;
|
|
829
|
+
const delayMs = retryDelayMs(attempt, errRetryMs);
|
|
793
830
|
logWarn("API retry", {
|
|
794
831
|
rid: requestId,
|
|
795
832
|
path: pathPart,
|
|
@@ -163,6 +163,7 @@ async function handleResultsExplorer(job_id) {
|
|
|
163
163
|
jobId: job_id,
|
|
164
164
|
jobStatus: "completed",
|
|
165
165
|
inlineImageAttached,
|
|
166
|
+
uiResourceUri: RESULTS_EXPLORER_URI,
|
|
166
167
|
});
|
|
167
168
|
appendUiDeliveryContent(content, uiDelivery, {
|
|
168
169
|
linkLabel: "Open results explorer",
|
package/dist/tools/feedback.js
CHANGED
|
@@ -23,7 +23,7 @@ export function registerFeedbackTool(server) {
|
|
|
23
23
|
|
|
24
24
|
For a substantial issue, prefer feedback_items: submit several focused instances (each max 1400 chars) covering, e.g., symptoms, exact reproduction steps, environment, and concrete asks — they are stored together as one batch so developers see the full picture. Use the single feedback field for a short one-off note.
|
|
25
25
|
|
|
26
|
-
If the API or object storage is unavailable (e.g. gateway HTML 502 mid-demo), this tool queues feedback locally (~/.barivia/deferred-feedback, shared with barsom send_feedback) and returns deferred=true with request_id + api_health from GET /health (no R2). Call again later to flush.`, {
|
|
26
|
+
If the API or object storage is unavailable (e.g. gateway HTML 502 mid-demo), this tool queues feedback locally (~/.barivia/deferred-feedback, shared with barsom send_feedback) and returns deferred=true with request_id + api_health from GET /health (no R2). Call again later to flush (idempotent enqueue of the same draft).`, {
|
|
27
27
|
feedback: z.string().max(1400).optional().describe("Single feedback note (max 1400 characters). Use feedback_items instead for a multi-part report."),
|
|
28
28
|
feedback_items: z.array(z.string().max(1400)).max(10).optional().describe("Several feedback instances (each max 1400 characters, up to 10), stored together as one batch. Prefer this for a detailed issue: split it into focused parts (symptoms, reproduction, environment, asks)."),
|
|
29
29
|
}, async ({ feedback, feedback_items }) => {
|
|
@@ -103,5 +103,10 @@ If the API or object storage is unavailable (e.g. gateway HTML 502 mid-demo), th
|
|
|
103
103
|
}
|
|
104
104
|
throw err;
|
|
105
105
|
}
|
|
106
|
+
}, {
|
|
107
|
+
readOnlyHint: false,
|
|
108
|
+
destructiveHint: false,
|
|
109
|
+
idempotentHint: true,
|
|
110
|
+
openWorldHint: true,
|
|
106
111
|
});
|
|
107
112
|
}
|
package/dist/tools/jobs.js
CHANGED
|
@@ -20,8 +20,9 @@ export function registerJobsTool(server) {
|
|
|
20
20
|
|
|
21
21
|
BEST FOR: action=monitor after submit (one call, throttled snapshots — preferred for agents). action=status for a single one-shot check. action=inventory for a durable org catalog. action=delete for cleanup by known job_id (do not deep-page list to find IDs).
|
|
22
22
|
MONITOR MODES: barmesh_training_monitor — default visual MCP App (live curves, post-hoc review on completed jobs). barmesh_jobs(action=monitor) — headless blocking snapshots for agents (live or post-hoc review; attaches learning_curve.png when already completed).
|
|
23
|
-
ASYNC PROTOCOL: monitor blocks server-side until completed/failed or block_until timeout (default ${DEFAULT_BLOCK_UNTIL_SEC}s, poll every ${DEFAULT_POLL_INTERVAL_SEC}s). status is one-shot; poll every 10-20s manually if not using monitor. When status=completed, call barmesh_results(action=get, job_id=...) then barmesh_results_explorer(job_id=...).
|
|
24
|
-
LIST: slim by default (label,id,status,job_type,dataset_id,created_at,result_ref,description,tags — no fat params). has_results=true is the results catalog.
|
|
23
|
+
ASYNC PROTOCOL: monitor blocks server-side until completed/failed or block_until timeout (default ${DEFAULT_BLOCK_UNTIL_SEC}s, poll every ${DEFAULT_POLL_INTERVAL_SEC}s). status is one-shot; poll every 10-20s manually if not using monitor — do not abandon after one poll. When status=completed, call barmesh_results(action=get, job_id=...) then barmesh_results_explorer(job_id=...).
|
|
24
|
+
LIST: slim by default (label,id,status,job_type,dataset_id,created_at,result_ref,description,tags — no fat params). Page with limit+cursor; when next_cursor is returned, call again with cursor=. has_results=true is the results catalog.
|
|
25
|
+
INVENTORY: one-shot datasets + latest N jobs (limit); not a full unbounded job history — use list+cursor for more.
|
|
25
26
|
ESCALATION: status=failed returns an error message and (when available) a failure_stage; read it before retrying.
|
|
26
27
|
UNAVAILABLE: If the mesh analysis API is temporarily unavailable, say so plainly, pause (proxy already burst-retried; wait ~retry_after_sec), and keep reviewing the last good distances/figures — do not treat the demo as failed. Suggest retry later.`, {
|
|
27
28
|
action: z
|
|
@@ -1,12 +1,21 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { registerAppTool } from "@modelcontextprotocol/ext-apps/server";
|
|
3
3
|
import { runMcpToolAudit } from "../audit.js";
|
|
4
|
+
import { logWarn } from "../logger.js";
|
|
4
5
|
import { apiCall, BARMESH_VIZ_VIEWS, buildStandaloneVizPageUrl, buildVizRelatedUrls, getVizPort, structuredTextResult, } from "../shared.js";
|
|
5
6
|
import { appendUiDeliveryContent, resolveUiDelivery, } from "../ui-delivery.js";
|
|
6
7
|
import { enrichWithTrainingLog, needsTrainingLogEnrichment } from "../training_review.js";
|
|
7
8
|
import { formatRunConfigTable } from "../run_config.js";
|
|
8
9
|
export const TRAINING_MONITOR_URI = "ui://barmesh/training-monitor";
|
|
9
10
|
export const TRAINING_MONITOR_REFRESH_MS = 5000;
|
|
11
|
+
/** Loose shape check — warn + pass through on failure (never drop a successful monitor payload). */
|
|
12
|
+
const BarmeshTrainingMonitorStructuredSchema = z
|
|
13
|
+
.object({
|
|
14
|
+
type: z.literal("barmesh-training-monitor"),
|
|
15
|
+
jobId: z.string(),
|
|
16
|
+
refresh_interval_ms: z.number(),
|
|
17
|
+
})
|
|
18
|
+
.passthrough();
|
|
10
19
|
function buildStructuredContent(job_id, data, port) {
|
|
11
20
|
const id = String(data.id ?? job_id);
|
|
12
21
|
const standaloneUrl = buildStandaloneVizPageUrl(port, BARMESH_VIZ_VIEWS.trainingMonitor, id);
|
|
@@ -24,21 +33,17 @@ function buildStructuredContent(job_id, data, port) {
|
|
|
24
33
|
export function registerTrainingMonitorTool(server) {
|
|
25
34
|
registerAppTool(server, "barmesh_training_monitor", {
|
|
26
35
|
title: "Mesh Convergence Training Monitor",
|
|
27
|
-
description: "Default
|
|
36
|
+
description: "Default monitor for mesh_convergence jobs after submit. Prefer the standalone localhost URL in the tool result (always surfaced when the viz server is up) — some hosts list MCP Apps without mounting panels. When mounted, the App auto-refreshes every 5s: epoch progress, phase, ETA, QE/TE curves (≤1000 batch samples per phase), panel fingerprint ΔKL, hit-grid heatmap. Completed jobs replay training-log curves. Set BARIVIA_VIZ_PORT for a stable port. Headless: barmesh_jobs(action=monitor) or barmesh_jobs(action=status). After completion, barmesh_results_explorer for figures.",
|
|
28
37
|
inputSchema: {
|
|
29
38
|
job_id: z.string().describe("Job ID from barmesh_mesh_convergence or barmesh_richardson"),
|
|
30
|
-
fetch_training_log: z
|
|
31
|
-
.boolean()
|
|
32
|
-
.optional()
|
|
33
|
-
.describe("Internal: merge completed-job training-log arrays when live progress is empty"),
|
|
34
39
|
},
|
|
35
|
-
_meta: { ui: { resourceUri: TRAINING_MONITOR_URI } },
|
|
40
|
+
_meta: { ui: { resourceUri: TRAINING_MONITOR_URI, visibility: ["model", "app"] } },
|
|
36
41
|
}, async (args) => runMcpToolAudit("barmesh_training_monitor", "default", args, async () => {
|
|
37
|
-
const { job_id
|
|
42
|
+
const { job_id } = args;
|
|
38
43
|
let data = (await apiCall("GET", `/v1/jobs/${job_id}`));
|
|
39
44
|
const jobStatus = String(data.status ?? "");
|
|
40
45
|
const terminal = jobStatus === "completed" || jobStatus === "failed";
|
|
41
|
-
if (
|
|
46
|
+
if (needsTrainingLogEnrichment(data) || terminal || jobStatus === "cancelled") {
|
|
42
47
|
data = await enrichWithTrainingLog(job_id, data);
|
|
43
48
|
}
|
|
44
49
|
const structuredContent = buildStructuredContent(job_id, data, getVizPort());
|
|
@@ -58,12 +63,14 @@ export function registerTrainingMonitorTool(server) {
|
|
|
58
63
|
const modeNote = terminal ? " (post-hoc review — training-log curves)" : "";
|
|
59
64
|
const runConfigNote = formatRunConfigTable(data);
|
|
60
65
|
const text = (runConfigNote ? `${runConfigNote}\n` : "") +
|
|
61
|
-
`Training monitor (
|
|
66
|
+
`Training monitor (standalone URL + optional App panel; refreshes every ${TRAINING_MONITOR_REFRESH_MS / 1000}s when mounted): job ${job_id} — ${jobStatus} (${progress.toFixed(1)}%).${modeNote}${timingNote} ` +
|
|
67
|
+
`For headless progress use barmesh_jobs(action=status); this tool is optional.`;
|
|
62
68
|
const content = [{ type: "text", text }];
|
|
63
69
|
const uiDelivery = resolveUiDelivery({
|
|
64
70
|
tool: "training_monitor",
|
|
65
71
|
jobId: job_id,
|
|
66
72
|
jobStatus,
|
|
73
|
+
uiResourceUri: TRAINING_MONITOR_URI,
|
|
67
74
|
});
|
|
68
75
|
appendUiDeliveryContent(content, uiDelivery, {
|
|
69
76
|
linkLabel: "Open training monitor",
|
|
@@ -79,9 +86,16 @@ export function registerTrainingMonitorTool(server) {
|
|
|
79
86
|
}
|
|
80
87
|
}
|
|
81
88
|
structuredContent.ui_delivery = uiDelivery;
|
|
89
|
+
const parsed = BarmeshTrainingMonitorStructuredSchema.safeParse(structuredContent);
|
|
90
|
+
if (!parsed.success) {
|
|
91
|
+
logWarn("barmesh_training_monitor structuredContent validation failed — passing through", {
|
|
92
|
+
job_id,
|
|
93
|
+
issues: parsed.error.issues.slice(0, 5).map((i) => i.message),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
82
96
|
return {
|
|
83
97
|
...structuredTextResult(structuredContent, text, content),
|
|
84
|
-
_meta: { ui: { resourceUri: TRAINING_MONITOR_URI } },
|
|
98
|
+
_meta: { ui: { resourceUri: TRAINING_MONITOR_URI, visibility: ["model", "app"] } },
|
|
85
99
|
};
|
|
86
100
|
}));
|
|
87
101
|
}
|
package/dist/ui-delivery.js
CHANGED
|
@@ -6,11 +6,20 @@ import { getClientSupportsMcpApps, getVizPort, } from "./shared.js";
|
|
|
6
6
|
import { buildBarmeshVizStandaloneUrl } from "./viz_links.js";
|
|
7
7
|
export function parseUiDeliveryOverride() {
|
|
8
8
|
const raw = (process.env.BARIVIA_UI_DELIVERY ?? "auto").trim().toLowerCase();
|
|
9
|
-
if (raw === "apps" ||
|
|
9
|
+
if (raw === "apps" ||
|
|
10
|
+
raw === "localhost" ||
|
|
11
|
+
raw === "inline" ||
|
|
12
|
+
raw === "text_only" ||
|
|
13
|
+
raw === "auto") {
|
|
10
14
|
return raw;
|
|
11
15
|
}
|
|
12
16
|
return "auto";
|
|
13
17
|
}
|
|
18
|
+
/** Opt-in: force localhost under auto even when the host advertises MCP Apps. */
|
|
19
|
+
export function preferLocalhostUi() {
|
|
20
|
+
const v = (process.env.BARIVIA_UI_PREFER_LOCALHOST ?? "").trim().toLowerCase();
|
|
21
|
+
return v === "1" || v === "true" || v === "yes";
|
|
22
|
+
}
|
|
14
23
|
function vizPortPinned() {
|
|
15
24
|
return Boolean(process.env.BARIVIA_VIZ_PORT?.trim());
|
|
16
25
|
}
|
|
@@ -29,17 +38,26 @@ export function buildHealthUrl(jobId) {
|
|
|
29
38
|
}
|
|
30
39
|
function hintForTier(tier, tool, opts) {
|
|
31
40
|
const label = tool === "training_monitor" ? "training monitor" : "results explorer";
|
|
41
|
+
const linkFirst = opts.standaloneUrl
|
|
42
|
+
? `AGENT: Post a clickable markdown link first (e.g. "[Open ${label}](${opts.standaloneUrl})") — do not bury it after metrics.`
|
|
43
|
+
: undefined;
|
|
32
44
|
switch (tier) {
|
|
33
45
|
case "embedded":
|
|
34
|
-
return
|
|
46
|
+
return linkFirst
|
|
47
|
+
? `${linkFirst} Embedded panel if the host mounts Apps; some hosts list ui:// without mounting.`
|
|
48
|
+
: `The ${label} MCP App panel may embed. Always mention the standalone URL when present.`;
|
|
35
49
|
case "localhost":
|
|
36
|
-
return
|
|
37
|
-
?
|
|
50
|
+
return linkFirst
|
|
51
|
+
? `${linkFirst} Set BARIVIA_VIZ_PORT for a stable port.`
|
|
38
52
|
: `AGENT: Viz server unavailable — use barmesh_jobs(status) and barmesh_results(get).`;
|
|
39
53
|
case "inline_image":
|
|
40
|
-
return
|
|
54
|
+
return linkFirst
|
|
55
|
+
? `${linkFirst} Inline raster figure(s) may also be attached; offer barmesh_results_explorer for more.`
|
|
56
|
+
: `AGENT: Inline raster figure(s) are attached. Summarize metrics; offer barmesh_results_explorer for more figures.`;
|
|
41
57
|
case "text_only":
|
|
42
|
-
return
|
|
58
|
+
return linkFirst
|
|
59
|
+
? `${linkFirst} Otherwise use barmesh_jobs(status) and barmesh_results(get).`
|
|
60
|
+
: `AGENT: No embedded panel or localhost viz — use barmesh_jobs(status) and barmesh_results(get).`;
|
|
43
61
|
}
|
|
44
62
|
}
|
|
45
63
|
export function resolveUiDelivery(options) {
|
|
@@ -57,6 +75,12 @@ export function resolveUiDelivery(options) {
|
|
|
57
75
|
else if (override === "inline") {
|
|
58
76
|
delivery = options.inlineImageAttached ? "inline_image" : "text_only";
|
|
59
77
|
}
|
|
78
|
+
else if (override === "text_only") {
|
|
79
|
+
delivery = "text_only";
|
|
80
|
+
}
|
|
81
|
+
else if (preferLocalhostUi() && port) {
|
|
82
|
+
delivery = "localhost";
|
|
83
|
+
}
|
|
60
84
|
else if (mcpApps) {
|
|
61
85
|
delivery = "embedded";
|
|
62
86
|
}
|
|
@@ -70,11 +94,11 @@ export function resolveUiDelivery(options) {
|
|
|
70
94
|
delivery = "text_only";
|
|
71
95
|
}
|
|
72
96
|
const urls = [];
|
|
73
|
-
if (standaloneUrl
|
|
97
|
+
if (standaloneUrl) {
|
|
74
98
|
urls.push(standaloneUrl);
|
|
75
99
|
}
|
|
76
100
|
const healthUrl = buildHealthUrl(options.jobId);
|
|
77
|
-
if (healthUrl && delivery === "localhost") {
|
|
101
|
+
if (healthUrl && (delivery === "localhost" || preferLocalhostUi())) {
|
|
78
102
|
urls.push(healthUrl);
|
|
79
103
|
}
|
|
80
104
|
const crossLink = options.tool === "training_monitor" && options.jobStatus === "completed"
|
|
@@ -93,6 +117,7 @@ export function resolveUiDelivery(options) {
|
|
|
93
117
|
viz_port: port,
|
|
94
118
|
port_pinned: vizPortPinned(),
|
|
95
119
|
override,
|
|
120
|
+
...(options.uiResourceUri ? { ui_resource_uri: options.uiResourceUri } : {}),
|
|
96
121
|
};
|
|
97
122
|
}
|
|
98
123
|
/** Prepend prominent standalone URL + structured ui_delivery (Apps handshake may lie). */
|
|
@@ -128,6 +153,7 @@ export function getMcpClientDiagnostics() {
|
|
|
128
153
|
const override = parseUiDeliveryOverride();
|
|
129
154
|
const mcpApps = getClientSupportsMcpApps();
|
|
130
155
|
const port = getVizPort() || null;
|
|
156
|
+
const preferLocal = preferLocalhostUi();
|
|
131
157
|
let activeTier = "text_only";
|
|
132
158
|
if (override === "apps") {
|
|
133
159
|
activeTier = mcpApps ? "embedded" : port ? "localhost" : "text_only";
|
|
@@ -138,6 +164,12 @@ export function getMcpClientDiagnostics() {
|
|
|
138
164
|
else if (override === "inline") {
|
|
139
165
|
activeTier = "inline_image";
|
|
140
166
|
}
|
|
167
|
+
else if (override === "text_only") {
|
|
168
|
+
activeTier = "text_only";
|
|
169
|
+
}
|
|
170
|
+
else if (preferLocal && port) {
|
|
171
|
+
activeTier = "localhost";
|
|
172
|
+
}
|
|
141
173
|
else if (mcpApps) {
|
|
142
174
|
activeTier = "embedded";
|
|
143
175
|
}
|
|
@@ -149,6 +181,7 @@ export function getMcpClientDiagnostics() {
|
|
|
149
181
|
viz_port: port,
|
|
150
182
|
viz_port_pinned: vizPortPinned(),
|
|
151
183
|
ui_delivery_override: override,
|
|
184
|
+
ui_prefer_localhost: preferLocal,
|
|
152
185
|
active_delivery_tier: activeTier,
|
|
153
186
|
health_url: buildHealthUrl(),
|
|
154
187
|
};
|
|
@@ -136,7 +136,7 @@ Boolean requesting whether a visible border and background is provided by the ho
|
|
|
136
136
|
- omitted: host decides border`)});p({method:c("ui/request-display-mode"),params:p({mode:Le.describe("The display mode being requested.")})});var Hf=p({mode:Le.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),Jf=T([c("model"),c("app")]).describe("Tool visibility scope - who can access the tool.");p({resourceUri:l().optional(),visibility:I(Jf).optional().describe(`Who can access this tool. Default: ["model", "app"]
|
|
137
137
|
- "model": Tool visible to and callable by the agent
|
|
138
138
|
- "app": Tool callable by the app from this server only`),csp:_e().optional(),permissions:_e().optional()});p({mimeTypes:I(l()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});p({method:c("ui/download-file"),params:p({contents:I(T([Wu,Ku])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})});p({method:c("ui/message"),params:p({role:c("user").describe('Message role, currently only "user" is supported.'),content:I(ut).describe("Message content blocks (text, image, etc.).")})});p({method:c("ui/notifications/sandbox-resource-ready"),params:p({html:l().describe("HTML content to load into the inner iframe."),sandbox:l().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Gi.optional().describe("CSP configuration from resource metadata."),permissions:Qi.optional().describe("Sandbox permissions from resource metadata.")})});var Bf=p({method:c("ui/notifications/tool-result"),params:Un.describe("Standard MCP tool execution result.")}),tl=p({toolInfo:p({id:rt.optional().describe("JSON-RPC id of the tools/call request."),tool:Ki.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:Tf.optional().describe("Current color theme preference."),styles:Mf.optional().describe("Style configuration for theming the app."),displayMode:Le.optional().describe("How the UI is currently displayed."),availableDisplayModes:I(Le).optional().describe("Display modes the host supports."),containerDimensions:T([p({height:x().describe("Fixed container height in pixels.")}),p({maxHeight:T([x(),Ce()]).optional().describe("Maximum container height in pixels.")})]).and(T([p({width:x().describe("Fixed container width in pixels.")}),p({maxWidth:T([x(),Ce()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
|
|
139
|
-
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:l().optional().describe("User's language and region preference in BCP 47 format."),timeZone:l().optional().describe("User's timezone in IANA format."),userAgent:l().optional().describe("Host application identifier."),platform:T([c("web"),c("desktop"),c("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p({touch:Z().optional().describe("Whether the device supports touch input."),hover:Z().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p({top:x().describe("Top safe area inset in pixels."),right:x().describe("Right safe area inset in pixels."),bottom:x().describe("Bottom safe area inset in pixels."),left:x().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),Vf=p({method:c("ui/notifications/host-context-changed"),params:tl.describe("Partial context update containing only changed fields.")});p({method:c("ui/update-model-context"),params:p({content:I(ut).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(l(),C().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})});p({method:c("ui/initialize"),params:p({appInfo:Nn.describe("App identification (name and version)."),appCapabilities:Ff.describe("Features and capabilities this app provides."),protocolVersion:l().describe("Protocol version this app supports.")})});var Wf=p({protocolVersion:l().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Nn.describe("Host application identification and version."),hostCapabilities:qf.describe("Features and capabilities provided by the host."),hostContext:tl.describe("Rich context about the host environment.")}).passthrough(),Kf={target:"draft-2020-12"};async function wo(t,n){let r=t["~standard"];if(r.jsonSchema)return r.jsonSchema[n](Kf);if(r.vendor==="zod"){let{z:o}=await dl(()=>Promise.resolve().then(()=>Rm),void 0,import.meta.url);return o.toJSONSchema(t,{io:n})}throw Error(`Schema (vendor: ${r.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function So(t,n,r=""){let o=await t["~standard"].validate(n);if(o.issues){let e=o.issues.map(i=>{let a=i.path?.map(s=>typeof s=="object"?s.key:s).join(".");return a?`${a}: ${i.message}`:i.message}).join("; ");throw Error(r+e)}return o.value}class Yi extends zf{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(n){if(this._initializedSent)return;let r=`[ext-apps] App.${n}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(r);console.warn(`${r}. This will throw in a future release.`)}eventSchemas={toolinput:Rf,toolinputpartial:Zf,toolresult:Bf,toolcancelled:Cf,hostcontextchanged:Vf};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(n){if(!Yi.ONE_SHOT_EVENTS.has(n)||this._everHadListener.has(n)||(this._everHadListener.add(n),!this._initializedSent))return;let r=`[ext-apps] "${String(n)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(r);console.warn(r)}setEventHandler(n,r){r&&this._assertHandlerTiming(n),super.setEventHandler(n,r)}addEventListener(n,r){this._assertHandlerTiming(n),super.addEventListener(n,r)}onEventDispatch(n,r){n==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...r})}constructor(n,r={},o={autoResize:!0}){super(o),this._appInfo=n,this._capabilities=r,this.options=o,o.allowUnsafeEval||J({jitless:!0}),this.setRequestHandler(Tn,e=>(console.log("Received ping:",e.params),{})),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(n){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=If(this._capabilities,n)}registerTool(n,r,o){if(this._registeredTools[n])throw Error(`Tool ${n} is already registered`);let e=this,i=()=>{e._initializedSent&&e._capabilities.tools?.listChanged&&e.sendToolListChanged()},a=r.inputSchema!==void 0,s={title:r.title,description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema,annotations:r.annotations,_meta:r._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(m){Object.assign(this,m),i()},remove(){e._registeredTools[n]===s&&(delete e._registeredTools[n],i())},handler:async(m,g)=>{if(!s.enabled)throw Error(`Tool ${n} is disabled`);let h;if(a){let d=s.inputSchema,b=d?await So(d,m??{},`Invalid input for tool ${n}: `):m??{};h=await o(b,g)}else h=await o(g);return s.outputSchema&&!h.isError&&(h.structuredContent=await So(s.outputSchema,h.structuredContent,`Invalid output for tool ${n}: `)),h}};return this._registeredTools[n]=s,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),s}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(n,r)=>{let o=this._registeredTools[n.name];if(!o)throw Error(`Tool ${n.name} not found`);return o.handler(n.arguments,r)},this.onlisttools=async(n,r)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,e])=>e.enabled).map(async([o,e])=>{let i={name:o,title:e.title,description:e.description,inputSchema:e.inputSchema?await wo(e.inputSchema,"input"):{type:"object",properties:{}}};return e.outputSchema&&(i.outputSchema=await wo(e.outputSchema,"output")),e.annotations&&(i.annotations=e.annotations),e._meta&&(i._meta=e._meta),i}))}))}async sendToolListChanged(n={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:n})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(n){this.setEventHandler("toolinput",n)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(n){this.setEventHandler("toolinputpartial",n)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(n){this.setEventHandler("toolresult",n)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(n){this.setEventHandler("toolcancelled",n)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(n){this.setEventHandler("hostcontextchanged",n)}_onteardown;get onteardown(){return this._onteardown}set onteardown(n){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,n),this._onteardown=n,this.replaceRequestHandler(Lf,(r,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(r.params,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(n){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,n),this._oncalltool=n,this.replaceRequestHandler(Qu,(r,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(r.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(n){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,n),this._onlisttools=n,this.replaceRequestHandler(Gu,(r,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(r.params,o)})}assertCapabilityForMethod(n){switch(n){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${n})`);break}}assertRequestHandlerCapability(n){switch(n){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${n})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${n} registered`)}}assertNotificationCapability(n){}assertTaskCapability(n){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(n){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(n,r){if(this._assertInitialized("callServerTool"),typeof n=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${n}"). Did you mean: callServerTool({ name: "${n}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:n},Un,{onprogress:()=>{},resetTimeoutOnProgress:!0,...r})}async readServerResource(n,r){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:n},Vu,r)}async listServerResources(n,r){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:n},Bu,r)}async createSamplingMessage(n,r){this._assertInitialized("createSamplingMessage");let o=n.tools?el:Xu;return await this.request({method:"sampling/createMessage",params:n},o,r)}sendMessage(n,r){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:n},Df,r)}sendLog(n){return this.notification({method:"notifications/message",params:n})}updateModelContext(n,r){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:n},Ei,r)}openLink(n,r){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:n},Pf,r)}sendOpenLink=this.openLink;downloadFile(n,r){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:n},Ef,r)}requestTeardown(n={}){return this.notification({method:"ui/notifications/request-teardown",params:n})}requestDisplayMode(n,r){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:n},Hf,r)}sendSizeChanged(n){return this.notification({method:"ui/notifications/size-changed",params:n})}setupSizeChangedNotifications(){let n=!1,r=0,o=0,e=()=>{n||(n=!0,requestAnimationFrame(()=>{n=!1;let a=document.documentElement,s=a.style.height;a.style.height="max-content";let m=Math.ceil(a.getBoundingClientRect().height);a.style.height=s;let g=Math.ceil(window.innerWidth);(g!==r||m!==o)&&(r=g,o=m,this.sendSizeChanged({width:g,height:m}))}))};e();let i=new ResizeObserver(e);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(n=new Nf(window.parent,window.parent),r){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(n);try{let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:xf}},Wf,r);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}}const Zn=["overview","distances","diagnostics","component"],Gf={overview:"Overview",distances:"Distances",diagnostics:"Diagnostics",component:"Component planes"};function zt(t){return t==="combined"?"overview":t==="overview_distances"||t.startsWith("KL_")||t.startsWith("EMD_")?"distances":t==="learning_curve"||t.startsWith("plot_vol")?"diagnostics":t.startsWith("divergence_")||t.startsWith("plot_")?"component":"diagnostics"}const Io={combined:0,overview_distances:1,KL_ref:10,KL_stepwise:11,KL_asymmetric:12,EMD_ref:13,EMD_stepwise:14,learning_curve:15,plot_vol_all_meshes:19,plot_vol_coarse_fine:20,divergence_kl:28,divergence_w1:29};function zo(t){return t in Io?Io[t]:t.startsWith("plot_vol")?25:t.startsWith("divergence_")?28:t.startsWith("plot_")?30:50}let ae=null,ue=null,re=null,Cn=null;const xo=new Map,vt=document.getElementById("loading"),Qf=document.getElementById("app"),nl=document.getElementById("title"),rl=document.getElementById("subtitle"),ft=document.getElementById("metadata-strip"),Yf=document.getElementById("metrics"),qe=document.getElementById("figure-select"),Xf=document.getElementById("figure-title"),eh=document.getElementById("figure-file"),th=document.getElementById("figure-caption"),ne=document.getElementById("main-image"),nh=document.getElementById("figure-empty"),ht=document.getElementById("open-standalone"),On=document.getElementById("open-monitor-btn"),ce=document.getElementById("copy-url"),jo=document.getElementById("related-monitor"),il=document.getElementById("download-current");function rh(t){return[...t].sort((n,r)=>Zn.indexOf(n.section??zt(n.key))-Zn.indexOf(r.section??zt(r.key))||zo(n.key)-zo(r.key)||n.label.localeCompare(r.label))}function ih(t){if(t.find(r=>r.key==="combined"))return"combined";const n=t.find(r=>r.url||/\.(png|svg)$/i.test(r.filename));return n?n.key:t.find(r=>r.key==="KL_ref")?"KL_ref":t[0]?.key}function oh(t){const n=t.replace(/\.(png|pdf|svg)$/i,"");return n==="combined"?"Component planes (overview)":n==="overview_distances"?"Distances overview (KL + EMD)":n==="learning_curve"?"Learning curve (QE by epoch)":n==="KL_ref"?"KL divergence vs reference":n==="KL_stepwise"?"KL divergence stepwise":n==="EMD_ref"?"Wasserstein (EMD) vs reference":n==="EMD_stepwise"?"Wasserstein (EMD) stepwise":n==="KL_asymmetric"?"Asymmetric mesh KL matrix (coarse↔fine)":n==="divergence_kl"?"Feature-plane symmetric KL (not mesh KL)":n==="divergence_w1"?"Feature-plane Wasserstein-1":n==="plot_vol_all_meshes"?"Volume: all meshes":n==="plot_vol_coarse_fine"?"Volume: coarse vs reference":n.startsWith("plot_vol_")?"Volume: stepwise":n.startsWith("plot_")?`Component: ${n.replace(/^plot_/,"").replace(/_/g," ")}`:n.replace(/_/g," ")}function ah(t,n){const r=new Map;for(const o of t){const e=o.match(/^(.*)\.(png|pdf|svg)$/i);if(!e)continue;const i=e[1],a=r.get(i)??new Set;a.add(e[2].toLowerCase()),r.set(i,a)}return rh([...r.entries()].map(([o,e])=>{const i=[...e],a=e.has("png")?`${o}.png`:e.has("svg")?`${o}.svg`:`${o}.${i[0]}`,s=e.has("svg")?`${o}.svg`:e.has("pdf")?`${o}.pdf`:`${o}.png`,m=/\.(png|svg)$/i.test(a),g=i.filter(h=>h==="pdf"||h==="svg");return{key:o,label:oh(a),filename:a,downloadFilename:s,formats:i,section:zt(o),caption:g.length>0?`High-quality ${g.join("/").toUpperCase()} available to download.`:void 0,url:m?`/api/results/${n}/image/${a}`:void 0,downloadUrl:`/api/results/${n}/image/${s}`}}))}function sh(t,n){const r=t.summary??{},o=t.label!=null?String(t.label):null,e=n.length>8?`${n.slice(0,8)}…`:n,i=r.grid??[],a=r.epochs??[],s=[o?`label ${o}`:null,`job ${e}`,String(r.job_type??"cfd_mesh_convergence")].filter(Boolean).join(" · "),m=[r.n_train_total!=null?`n_train ${r.n_train_total}`:null,r.reference_mesh!=null?`ref ${r.reference_mesh}`:null,i.length>=2?`grid ${i[0]}×${i[1]}`:null,a.length>=2?`epochs [${a[0]},${a[1]}]`:null,r.quantization_error!=null?`QE ${Number(r.quantization_error).toFixed(4)}`:null].filter(Boolean).join(" · ");return[s,m].filter(g=>g.length>0)}function ch(t,n){const r=t.summary??{},o=(r.files??[]).filter(d=>/\.(png|pdf|svg)$/i.test(d)),e=r.grid??[],i=r.meshes??[],a=r.quantization_error!=null?Number(r.quantization_error).toFixed(4):"N/A",s=r.topographic_error!=null?Number(r.topographic_error).toFixed(4):"N/A",m=r.epochs??[],g=[{label:"Grid",value:e.length>=2?`${e[0]}×${e[1]}`:"N/A"},{label:"Preset",value:String(r.preset??"generic")},{label:"Reference",value:String(r.reference_mesh??"N/A")},{label:"Meshes",value:String(i.length||"N/A")},{label:"Epochs",value:m.length>=2?`${m[0]}+${m[1]}`:"N/A"},{label:"QE",value:a},{label:"TE",value:s}],h=ah(o,n);return{type:"barmesh-results-explorer",jobId:n,title:"Mesh Convergence Results",subtitle:String(t.label??""),metadataStrip:sh(t,n),metrics:g,availableFigures:h,defaultFigureKey:ih(h),trainingMonitorUrl:`/viz/barmesh-training-monitor?mode=standalone&job_id=${encodeURIComponent(n)}`,standaloneUrl:`${window.location.origin}/viz/barmesh-results-explorer?mode=standalone&job_id=${encodeURIComponent(n)}`,relatedUrls:{trainingMonitor:`${window.location.origin}/viz/barmesh-training-monitor?mode=standalone&job_id=${encodeURIComponent(n)}`,resultsExplorer:`${window.location.origin}/viz/barmesh-results-explorer?mode=standalone&job_id=${encodeURIComponent(n)}`}}}function uh(t){if(!t||t.length===0){ft.style.display="none",ft.innerHTML="";return}ft.style.display="block",ft.innerHTML=t.map(n=>`<div class="metadata-line">${n}</div>`).join("")}function lh(t){Yf.innerHTML=t.map(n=>`<div class="metric"><span class="metric-label">${n.label}</span><span class="metric-value">${n.value}</span></div>`).join("")}function ol(t){const n=new Map;for(const r of t){const o=r.section??zt(r.key),e=n.get(o)??[];e.push(r),n.set(o,e)}qe.innerHTML="";for(const r of Zn){const o=n.get(r);if(!o||o.length===0)continue;const e=document.createElement("optgroup");e.label=Gf[r];for(const i of o){const a=document.createElement("option");a.value=i.key,a.textContent=`${i.label} (${i.filename})`,i.key===ue?.key&&(a.selected=!0),e.appendChild(a)}qe.appendChild(e)}}qe.addEventListener("change",()=>{const t=ae?.availableFigures.find(n=>n.key===qe.value);t&&al(t)});async function dh(t,n){const r=`${t}/${n}`,o=xo.get(r);if(o)return o;if(!re)return null;try{const i=(await re.callServerTool({name:"_barmesh_fetch_figure",arguments:{job_id:t,filename:n}})).content?.find(a=>a.type==="image");if(i){const a=`data:${i.mimeType};base64,${i.data}`;return xo.set(r,a),a}}catch{}return null}function mh(t){!re||!ae||re.updateModelContext({content:[{type:"text",text:`User is viewing the "${t.label}" figure (${t.filename}) of mesh convergence job ${ae.jobId}.`}]}).catch(()=>{})}function ph(t){return t.formats.length>1?` · formats: ${t.formats.join(", ")}`:""}function fh(t){const n=/\.(pdf|svg)$/i.test(t.downloadFilename);il.textContent=n?re?"Download PNG (preview)":`Download ${t.downloadFilename.split(".").pop()?.toUpperCase()} (high quality)`:"Download figure"}function hh(t){ne.style.display=t?"block":"none",nh.style.display=t?"none":"block"}async function al(t){ue=t,Xf.textContent=t.label,eh.textContent=`${t.filename}${ph(t)}`,th.textContent=t.caption??"",fh(t),mh(t),qe.value=t.key;let n=!1;if(t.url)ne.src=t.url,n=!0;else if(re&&ae){if(t.key===ae.defaultFigureKey&&Cn)ne.src=Cn,n=!0;else if(/\.(png|svg|jpe?g|webp)$/i.test(t.filename)){ne.removeAttribute("src");const r=await dh(ae.jobId,t.filename);r&&ue?.key===t.key&&(ne.src=r,n=!0)}}else/\.(png|svg|jpe?g|webp)$/i.test(t.filename)&&ne.removeAttribute("src");hh(n),ae&&ol(ae.availableFigures)}function gh(t){return t.standaloneUrl??window.location.href}function vh(t){const n=gh(t);t.standaloneUrl?(ht.href=t.standaloneUrl,ht.style.display="inline-flex"):cl&&(ht.href=window.location.href,ht.style.display="inline-flex");const r=t.relatedUrls?.trainingMonitor??t.trainingMonitorUrl??`/viz/barmesh-training-monitor?mode=standalone&job_id=${encodeURIComponent(t.jobId)}`;On.href=r,On.style.display="inline-flex",On.title="View live or completed training curves for this job",ce.style.display="inline-flex",ce.dataset.url=n;const o=t.relatedUrls?.trainingMonitor??t.trainingMonitorUrl;o&&(jo.href=o,jo.style.display="inline-flex")}function No(t){ae=t,nl.textContent=t.title,rl.textContent=t.subtitle?t.subtitle:`Job ${t.jobId}`,uh(t.metadataStrip),lh(t.metrics),vh(t);const n=t.availableFigures.find(r=>r.key===t.defaultFigureKey)??t.availableFigures[0]??null;ue=n,ol(t.availableFigures),n&&al(n),vt.style.display="none",Qf.style.display="block"}il.addEventListener("click",()=>{if(!ue)return;const t=document.createElement("a");if(ue.downloadUrl&&!re)t.href=ue.downloadUrl,t.download=ue.downloadFilename;else{const n=ne.src;if(!n)return;t.href=n,t.download=ue.filename}t.click()});ce.addEventListener("click",async()=>{const t=ce.dataset.url||ae?.standaloneUrl||window.location.href;try{await navigator.clipboard.writeText(t);const n=ce.textContent;ce.textContent="Copied!",setTimeout(()=>{ce.textContent=n??"Copy explorer URL"},1500)}catch{ce.textContent="Copy failed",setTimeout(()=>{ce.textContent="Copy explorer URL"},1500)}});ne.style.cursor="zoom-in";ne.addEventListener("click",()=>{if(!re||!ne.src)return;const t=re.getHostContext?.(),n=t?.availableDisplayModes;if(!Array.isArray(n)||!n.includes("fullscreen"))return;const r=t?.displayMode==="fullscreen"?"inline":"fullscreen";re.requestDisplayMode({mode:r}).then(o=>{ne.style.cursor=o.mode==="fullscreen"?"zoom-out":"zoom-in"}).catch(()=>{})});const sl=new URLSearchParams(window.location.search),cl=sl.get("mode")==="standalone",gt=sl.get("job_id");if(cl&>){const t="The local viz port is assigned per MCP session and changes when the proxy restarts. Re-run barmesh_results_explorer for a fresh URL, or set BARIVIA_VIZ_PORT for a persistent port.";(async()=>{for(let r=1;r<=3;r++)try{const o=await fetch(`/api/results/${gt}`);if(o.status===404){vt.textContent=`Results for job ${gt} were not found (HTTP 404). Compute may have finished but cfd_finalize is still rendering figures — poll barmesh_jobs(status) until finalize completes. ${t}`;return}if(!o.ok)throw new Error(`HTTP ${o.status}`);const e=await o.json();No(ch(e,gt));return}catch(o){if(r<3){await new Promise(e=>setTimeout(e,1e3*r));continue}vt.textContent=`Could not load results from the local viz server (${o instanceof Error?o.message:"error"}). ${t}`}})()}else{const t=new Yi({name:"Mesh Convergence Results",version:"1.0.0"},{},{autoResize:!0});re=t,t.ontoolinput=n=>{const r=n?.arguments??{},o=r.job_id!=null?String(r.job_id):"";o&&(nl.textContent="Mesh Convergence Results",rl.textContent=`Loading job ${o}...`)},t.ontoolresult=n=>{const r=n.content?.find(e=>e.type==="image");r&&(Cn=`data:${r.mimeType};base64,${r.data}`);const o=n.structuredContent;if(!o||typeof o!="object"){vt.textContent="The results explorer did not receive structured data.";return}No(o)},t.connect()}</script>
|
|
139
|
+
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:l().optional().describe("User's language and region preference in BCP 47 format."),timeZone:l().optional().describe("User's timezone in IANA format."),userAgent:l().optional().describe("Host application identifier."),platform:T([c("web"),c("desktop"),c("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p({touch:Z().optional().describe("Whether the device supports touch input."),hover:Z().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p({top:x().describe("Top safe area inset in pixels."),right:x().describe("Right safe area inset in pixels."),bottom:x().describe("Bottom safe area inset in pixels."),left:x().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),Vf=p({method:c("ui/notifications/host-context-changed"),params:tl.describe("Partial context update containing only changed fields.")});p({method:c("ui/update-model-context"),params:p({content:I(ut).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(l(),C().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})});p({method:c("ui/initialize"),params:p({appInfo:Nn.describe("App identification (name and version)."),appCapabilities:Ff.describe("Features and capabilities this app provides."),protocolVersion:l().describe("Protocol version this app supports.")})});var Wf=p({protocolVersion:l().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Nn.describe("Host application identification and version."),hostCapabilities:qf.describe("Features and capabilities provided by the host."),hostContext:tl.describe("Rich context about the host environment.")}).passthrough(),Kf={target:"draft-2020-12"};async function wo(t,n){let r=t["~standard"];if(r.jsonSchema)return r.jsonSchema[n](Kf);if(r.vendor==="zod"){let{z:o}=await dl(()=>Promise.resolve().then(()=>Rm),void 0,import.meta.url);return o.toJSONSchema(t,{io:n})}throw Error(`Schema (vendor: ${r.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function So(t,n,r=""){let o=await t["~standard"].validate(n);if(o.issues){let e=o.issues.map(i=>{let a=i.path?.map(s=>typeof s=="object"?s.key:s).join(".");return a?`${a}: ${i.message}`:i.message}).join("; ");throw Error(r+e)}return o.value}class Yi extends zf{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(n){if(this._initializedSent)return;let r=`[ext-apps] App.${n}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(r);console.warn(`${r}. This will throw in a future release.`)}eventSchemas={toolinput:Rf,toolinputpartial:Zf,toolresult:Bf,toolcancelled:Cf,hostcontextchanged:Vf};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(n){if(!Yi.ONE_SHOT_EVENTS.has(n)||this._everHadListener.has(n)||(this._everHadListener.add(n),!this._initializedSent))return;let r=`[ext-apps] "${String(n)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(r);console.warn(r)}setEventHandler(n,r){r&&this._assertHandlerTiming(n),super.setEventHandler(n,r)}addEventListener(n,r){this._assertHandlerTiming(n),super.addEventListener(n,r)}onEventDispatch(n,r){n==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...r})}constructor(n,r={},o={autoResize:!0}){super(o),this._appInfo=n,this._capabilities=r,this.options=o,o.allowUnsafeEval||J({jitless:!0}),this.setRequestHandler(Tn,e=>(console.log("Received ping:",e.params),{})),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(n){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=If(this._capabilities,n)}registerTool(n,r,o){if(this._registeredTools[n])throw Error(`Tool ${n} is already registered`);let e=this,i=()=>{e._initializedSent&&e._capabilities.tools?.listChanged&&e.sendToolListChanged()},a=r.inputSchema!==void 0,s={title:r.title,description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema,annotations:r.annotations,_meta:r._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(m){Object.assign(this,m),i()},remove(){e._registeredTools[n]===s&&(delete e._registeredTools[n],i())},handler:async(m,g)=>{if(!s.enabled)throw Error(`Tool ${n} is disabled`);let h;if(a){let d=s.inputSchema,b=d?await So(d,m??{},`Invalid input for tool ${n}: `):m??{};h=await o(b,g)}else h=await o(g);return s.outputSchema&&!h.isError&&(h.structuredContent=await So(s.outputSchema,h.structuredContent,`Invalid output for tool ${n}: `)),h}};return this._registeredTools[n]=s,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),s}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(n,r)=>{let o=this._registeredTools[n.name];if(!o)throw Error(`Tool ${n.name} not found`);return o.handler(n.arguments,r)},this.onlisttools=async(n,r)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,e])=>e.enabled).map(async([o,e])=>{let i={name:o,title:e.title,description:e.description,inputSchema:e.inputSchema?await wo(e.inputSchema,"input"):{type:"object",properties:{}}};return e.outputSchema&&(i.outputSchema=await wo(e.outputSchema,"output")),e.annotations&&(i.annotations=e.annotations),e._meta&&(i._meta=e._meta),i}))}))}async sendToolListChanged(n={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:n})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(n){this.setEventHandler("toolinput",n)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(n){this.setEventHandler("toolinputpartial",n)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(n){this.setEventHandler("toolresult",n)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(n){this.setEventHandler("toolcancelled",n)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(n){this.setEventHandler("hostcontextchanged",n)}_onteardown;get onteardown(){return this._onteardown}set onteardown(n){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,n),this._onteardown=n,this.replaceRequestHandler(Lf,(r,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(r.params,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(n){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,n),this._oncalltool=n,this.replaceRequestHandler(Qu,(r,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(r.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(n){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,n),this._onlisttools=n,this.replaceRequestHandler(Gu,(r,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(r.params,o)})}assertCapabilityForMethod(n){switch(n){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${n})`);break}}assertRequestHandlerCapability(n){switch(n){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${n})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${n} registered`)}}assertNotificationCapability(n){}assertTaskCapability(n){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(n){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(n,r){if(this._assertInitialized("callServerTool"),typeof n=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${n}"). Did you mean: callServerTool({ name: "${n}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:n},Un,{onprogress:()=>{},resetTimeoutOnProgress:!0,...r})}async readServerResource(n,r){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:n},Vu,r)}async listServerResources(n,r){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:n},Bu,r)}async createSamplingMessage(n,r){this._assertInitialized("createSamplingMessage");let o=n.tools?el:Xu;return await this.request({method:"sampling/createMessage",params:n},o,r)}sendMessage(n,r){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:n},Df,r)}sendLog(n){return this.notification({method:"notifications/message",params:n})}updateModelContext(n,r){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:n},Ei,r)}openLink(n,r){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:n},Pf,r)}sendOpenLink=this.openLink;downloadFile(n,r){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:n},Ef,r)}requestTeardown(n={}){return this.notification({method:"ui/notifications/request-teardown",params:n})}requestDisplayMode(n,r){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:n},Hf,r)}sendSizeChanged(n){return this.notification({method:"ui/notifications/size-changed",params:n})}setupSizeChangedNotifications(){let n=!1,r=0,o=0,e=()=>{n||(n=!0,requestAnimationFrame(()=>{n=!1;let a=document.documentElement,s=a.style.height;a.style.height="max-content";let m=Math.ceil(a.getBoundingClientRect().height);a.style.height=s;let g=Math.ceil(window.innerWidth);(g!==r||m!==o)&&(r=g,o=m,this.sendSizeChanged({width:g,height:m}))}))};e();let i=new ResizeObserver(e);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(n=new Nf(window.parent,window.parent),r){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(n);try{let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:xf}},Wf,r);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}}const Zn=["overview","distances","diagnostics","component"],Gf={overview:"Overview",distances:"Distances",diagnostics:"Diagnostics",component:"Component planes"};function zt(t){return t==="combined"?"overview":t==="overview_distances"||t.startsWith("KL_")||t.startsWith("EMD_")?"distances":t==="learning_curve"||t.startsWith("plot_vol")?"diagnostics":t.startsWith("divergence_")||t.startsWith("plot_")?"component":"diagnostics"}const Io={combined:0,overview_distances:1,KL_ref:10,KL_stepwise:11,KL_asymmetric:12,EMD_ref:13,EMD_stepwise:14,learning_curve:15,plot_vol_all_meshes:19,plot_vol_coarse_fine:20,divergence_kl:28,divergence_w1:29};function zo(t){return t in Io?Io[t]:t.startsWith("plot_vol")?25:t.startsWith("divergence_")?28:t.startsWith("plot_")?30:50}let ae=null,ue=null,re=null,Cn=null;const xo=new Map,vt=document.getElementById("loading"),Qf=document.getElementById("app"),nl=document.getElementById("title"),rl=document.getElementById("subtitle"),ft=document.getElementById("metadata-strip"),Yf=document.getElementById("metrics"),qe=document.getElementById("figure-select"),Xf=document.getElementById("figure-title"),eh=document.getElementById("figure-file"),th=document.getElementById("figure-caption"),ne=document.getElementById("main-image"),nh=document.getElementById("figure-empty"),ht=document.getElementById("open-standalone"),On=document.getElementById("open-monitor-btn"),ce=document.getElementById("copy-url"),jo=document.getElementById("related-monitor"),il=document.getElementById("download-current");function rh(t){return[...t].sort((n,r)=>Zn.indexOf(n.section??zt(n.key))-Zn.indexOf(r.section??zt(r.key))||zo(n.key)-zo(r.key)||n.label.localeCompare(r.label))}function ih(t){if(t.find(r=>r.key==="combined"))return"combined";const n=t.find(r=>r.url||/\.(png|svg)$/i.test(r.filename));return n?n.key:t.find(r=>r.key==="KL_ref")?"KL_ref":t[0]?.key}function oh(t){const n=t.replace(/\.(png|pdf|svg)$/i,"");return n==="combined"?"Component planes (overview)":n==="overview_distances"?"Distances overview (KL + EMD)":n==="learning_curve"?"Learning curve (QE by epoch)":n==="KL_ref"?"KL divergence vs reference":n==="KL_stepwise"?"KL divergence stepwise":n==="EMD_ref"?"Wasserstein (EMD) vs reference":n==="EMD_stepwise"?"Wasserstein (EMD) stepwise":n==="KL_asymmetric"?"Asymmetric mesh KL matrix (coarse↔fine)":n==="divergence_kl"?"Feature-plane symmetric KL (not mesh KL)":n==="divergence_w1"?"Feature-plane Wasserstein-1":n==="plot_vol_all_meshes"?"Volume: all meshes":n==="plot_vol_coarse_fine"?"Volume: coarse vs reference":n.startsWith("plot_vol_")?"Volume: stepwise":n.startsWith("plot_")?`Component: ${n.replace(/^plot_/,"").replace(/_/g," ")}`:n.replace(/_/g," ")}function ah(t,n){const r=new Map;for(const o of t){const e=o.match(/^(.*)\.(png|pdf|svg)$/i);if(!e)continue;const i=e[1],a=r.get(i)??new Set;a.add(e[2].toLowerCase()),r.set(i,a)}return rh([...r.entries()].map(([o,e])=>{const i=[...e],a=e.has("png")?`${o}.png`:e.has("svg")?`${o}.svg`:`${o}.${i[0]}`,s=e.has("svg")?`${o}.svg`:e.has("pdf")?`${o}.pdf`:`${o}.png`,m=/\.(png|svg)$/i.test(a),g=i.filter(h=>h==="pdf"||h==="svg");return{key:o,label:oh(a),filename:a,downloadFilename:s,formats:i,section:zt(o),caption:g.length>0?`High-quality ${g.join("/").toUpperCase()} available to download.`:void 0,url:m?`/api/results/${n}/image/${a}`:void 0,downloadUrl:`/api/results/${n}/image/${s}`}}))}function sh(t,n){const r=t.summary??{},o=t.label!=null?String(t.label):null,e=n.length>8?`${n.slice(0,8)}…`:n,i=r.grid??[],a=r.epochs??[],s=[o?`label ${o}`:null,`job ${e}`,String(r.job_type??"cfd_mesh_convergence")].filter(Boolean).join(" · "),m=[r.n_train_total!=null?`n_train ${r.n_train_total}`:null,r.reference_mesh!=null?`ref ${r.reference_mesh}`:null,i.length>=2?`grid ${i[0]}×${i[1]}`:null,a.length>=2?`epochs [${a[0]},${a[1]}]`:null,r.quantization_error!=null?`QE ${Number(r.quantization_error).toFixed(4)}`:null].filter(Boolean).join(" · ");return[s,m].filter(g=>g.length>0)}function ch(t,n){const r=t.summary??{},o=(r.files??[]).filter(d=>/\.(png|pdf|svg)$/i.test(d)),e=r.grid??[],i=r.meshes??[],a=r.quantization_error!=null?Number(r.quantization_error).toFixed(4):"N/A",s=r.topographic_error!=null?Number(r.topographic_error).toFixed(4):"N/A",m=r.epochs??[],g=[{label:"Grid",value:e.length>=2?`${e[0]}×${e[1]}`:"N/A"},{label:"Preset",value:String(r.preset??"generic")},{label:"Reference",value:String(r.reference_mesh??"N/A")},{label:"Meshes",value:String(i.length||"N/A")},{label:"Epochs",value:m.length>=2?`${m[0]}+${m[1]}`:"N/A"},{label:"QE",value:a},{label:"TE",value:s}],h=ah(o,n);return{type:"barmesh-results-explorer",jobId:n,title:"Mesh Convergence Results",subtitle:String(t.label??""),metadataStrip:sh(t,n),metrics:g,availableFigures:h,defaultFigureKey:ih(h),trainingMonitorUrl:`/viz/barmesh-training-monitor?mode=standalone&job_id=${encodeURIComponent(n)}`,standaloneUrl:`${window.location.origin}/viz/barmesh-results-explorer?mode=standalone&job_id=${encodeURIComponent(n)}`,relatedUrls:{trainingMonitor:`${window.location.origin}/viz/barmesh-training-monitor?mode=standalone&job_id=${encodeURIComponent(n)}`,resultsExplorer:`${window.location.origin}/viz/barmesh-results-explorer?mode=standalone&job_id=${encodeURIComponent(n)}`}}}function uh(t){if(!t||t.length===0){ft.style.display="none",ft.innerHTML="";return}ft.style.display="block",ft.innerHTML=t.map(n=>`<div class="metadata-line">${n}</div>`).join("")}function lh(t){Yf.innerHTML=t.map(n=>`<div class="metric"><span class="metric-label">${n.label}</span><span class="metric-value">${n.value}</span></div>`).join("")}function ol(t){const n=new Map;for(const r of t){const o=r.section??zt(r.key),e=n.get(o)??[];e.push(r),n.set(o,e)}qe.innerHTML="";for(const r of Zn){const o=n.get(r);if(!o||o.length===0)continue;const e=document.createElement("optgroup");e.label=Gf[r];for(const i of o){const a=document.createElement("option");a.value=i.key,a.textContent=`${i.label} (${i.filename})`,i.key===ue?.key&&(a.selected=!0),e.appendChild(a)}qe.appendChild(e)}}qe.addEventListener("change",()=>{const t=ae?.availableFigures.find(n=>n.key===qe.value);t&&al(t)});async function dh(t,n){const r=`${t}/${n}`,o=xo.get(r);if(o)return o;if(!re)return null;try{const i=(await re.callServerTool({name:"_barmesh_fetch_figure",arguments:{job_id:t,filename:n}})).content?.find(a=>a.type==="image");if(i){const a=`data:${i.mimeType};base64,${i.data}`;return xo.set(r,a),a}}catch{}return null}function mh(t){!re||!ae||re.updateModelContext({content:[{type:"text",text:`User is viewing the "${t.label}" figure (${t.filename}) of mesh convergence job ${ae.jobId}.`}]}).catch(()=>{})}function ph(t){return t.formats.length>1?` · formats: ${t.formats.join(", ")}`:""}function fh(t){const n=/\.(pdf|svg)$/i.test(t.downloadFilename);il.textContent=n?re?"Download PNG (preview)":`Download ${t.downloadFilename.split(".").pop()?.toUpperCase()} (high quality)`:"Download figure"}function hh(t){ne.style.display=t?"block":"none",nh.style.display=t?"none":"block"}async function al(t){ue=t,Xf.textContent=t.label,eh.textContent=`${t.filename}${ph(t)}`,th.textContent=t.caption??"",fh(t),mh(t),qe.value=t.key;let n=!1;if(t.url)ne.src=t.url,n=!0;else if(re&&ae){if(t.key===ae.defaultFigureKey&&Cn)ne.src=Cn,n=!0;else if(/\.(png|svg|jpe?g|webp)$/i.test(t.filename)){ne.removeAttribute("src");const r=await dh(ae.jobId,t.filename);r&&ue?.key===t.key&&(ne.src=r,n=!0)}}else/\.(png|svg|jpe?g|webp)$/i.test(t.filename)&&ne.removeAttribute("src");hh(n),ae&&ol(ae.availableFigures)}function gh(t){return t.standaloneUrl??window.location.href}function vh(t){const n=gh(t);t.standaloneUrl?(ht.href=t.standaloneUrl,ht.style.display="inline-flex"):cl&&(ht.href=window.location.href,ht.style.display="inline-flex");const r=t.relatedUrls?.trainingMonitor??t.trainingMonitorUrl??`/viz/barmesh-training-monitor?mode=standalone&job_id=${encodeURIComponent(t.jobId)}`;On.href=r,On.style.display="inline-flex",On.title="View live or completed training curves for this job",ce.style.display="inline-flex",ce.dataset.url=n;const o=t.relatedUrls?.trainingMonitor??t.trainingMonitorUrl;o&&(jo.href=o,jo.style.display="inline-flex")}function No(t){ae=t,nl.textContent=t.title,rl.textContent=t.subtitle?t.subtitle:`Job ${t.jobId}`,uh(t.metadataStrip),lh(t.metrics),vh(t);const n=t.availableFigures.find(r=>r.key===t.defaultFigureKey)??t.availableFigures[0]??null;ue=n,ol(t.availableFigures),n&&al(n),vt.style.display="none",Qf.style.display="block"}il.addEventListener("click",()=>{if(!ue)return;const t=document.createElement("a");if(ue.downloadUrl&&!re)t.href=ue.downloadUrl,t.download=ue.downloadFilename;else{const n=ne.src;if(!n)return;t.href=n,t.download=ue.filename}t.click()});ce.addEventListener("click",async()=>{const t=ce.dataset.url||ae?.standaloneUrl||window.location.href;try{await navigator.clipboard.writeText(t);const n=ce.textContent;ce.textContent="Copied!",setTimeout(()=>{ce.textContent=n??"Copy explorer URL"},1500)}catch{ce.textContent="Copy failed",setTimeout(()=>{ce.textContent="Copy explorer URL"},1500)}});ne.style.cursor="zoom-in";ne.addEventListener("click",()=>{if(!re||!ne.src)return;const t=re.getHostContext?.(),n=t?.availableDisplayModes;if(!Array.isArray(n)||!n.includes("fullscreen"))return;const r=t?.displayMode==="fullscreen"?"inline":"fullscreen";re.requestDisplayMode({mode:r}).then(o=>{ne.style.cursor=o.mode==="fullscreen"?"zoom-out":"zoom-in"}).catch(()=>{})});const sl=new URLSearchParams(window.location.search),cl=sl.get("mode")==="standalone",gt=sl.get("job_id");if(cl&>){const t="The local viz port is assigned per MCP session and changes when the proxy restarts. Re-run barmesh_results_explorer for a fresh URL, or set BARIVIA_VIZ_PORT for a persistent port.";(async()=>{for(let r=1;r<=3;r++)try{const o=await fetch(`/api/results/${gt}`);if(o.status===404){vt.innerHTML=`Results for job ${gt} were not found (HTTP 404). Compute may have finished but cfd_finalize is still rendering figures — poll barmesh_jobs(status) until finalize completes. ${t}<br><button type="button" id="viz-retry-load" style="margin-top:0.75rem">Retry</button>`,document.getElementById("viz-retry-load")?.addEventListener("click",()=>location.reload());return}if(!o.ok)throw new Error(`HTTP ${o.status}`);const e=await o.json();No(ch(e,gt));return}catch(o){if(r<3){await new Promise(e=>setTimeout(e,1e3*r));continue}vt.innerHTML=`Could not load results from the local viz server (${o instanceof Error?o.message:"error"}). ${t}<br><button type="button" id="viz-retry-load" style="margin-top:0.75rem">Retry</button>`,document.getElementById("viz-retry-load")?.addEventListener("click",()=>location.reload())}})()}else{const t=new Yi({name:"Mesh Convergence Results",version:"1.0.0"},{},{autoResize:!0});re=t,t.ontoolinput=n=>{const r=n?.arguments??{},o=r.job_id!=null?String(r.job_id):"";o&&(nl.textContent="Mesh Convergence Results",rl.textContent=`Loading job ${o}...`)},t.ontoolresult=n=>{const r=n.content?.find(e=>e.type==="image");r&&(Cn=`data:${r.mimeType};base64,${r.data}`);const o=n.structuredContent;if(!o||typeof o!="object"){vt.textContent="The results explorer did not receive structured data.";return}No(o)},t.connect()}</script>
|
|
140
140
|
</head>
|
|
141
141
|
<body>
|
|
142
142
|
<div id="loading">Loading mesh convergence results...</div>
|
|
@@ -125,7 +125,7 @@ Boolean requesting whether a visible border and background is provided by the ho
|
|
|
125
125
|
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:k().optional().describe("User's language and region preference in BCP 47 format."),timeZone:k().optional().describe("User's timezone in IANA format."),userAgent:k().optional().describe("Host application identifier."),platform:se([y("web"),y("desktop"),y("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:x({touch:we().optional().describe("Whether the device supports touch input."),hover:we().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:x({top:te().describe("Top safe area inset in pixels."),right:te().describe("Right safe area inset in pixels."),bottom:te().describe("Bottom safe area inset in pixels."),left:te().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),iS=x({method:y("ui/notifications/host-context-changed"),params:Wg.describe("Partial context update containing only changed fields.")});x({method:y("ui/update-model-context"),params:x({content:W(Bi).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:pe(k(),Ie().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})});x({method:y("ui/initialize"),params:x({appInfo:Na.describe("App identification (name and version)."),appCapabilities:eS.describe("Features and capabilities this app provides."),protocolVersion:k().describe("Protocol version this app supports.")})});var oS=x({protocolVersion:k().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Na.describe("Host application identification and version."),hostCapabilities:Xk.describe("Features and capabilities provided by the host."),hostContext:Wg.describe("Rich context about the host environment.")}).passthrough(),aS={target:"draft-2020-12"};async function Sd(e,n){let r=e["~standard"];if(r.jsonSchema)return r.jsonSchema[n](aS);if(r.vendor==="zod"){let{z:i}=await S_(()=>Promise.resolve().then(()=>Wy),void 0,import.meta.url);return i.toJSONSchema(e,{io:n})}throw Error(`Schema (vendor: ${r.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function wd(e,n,r=""){let i=await e["~standard"].validate(n);if(i.issues){let t=i.issues.map(o=>{let a=o.path?.map(l=>typeof l=="object"?l.key:l).join(".");return a?`${a}: ${o.message}`:o.message}).join("; ");throw Error(r+t)}return i.value}class uc extends Rk{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(n){if(this._initializedSent)return;let r=`[ext-apps] App.${n}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(r);console.warn(`${r}. This will throw in a future release.`)}eventSchemas={toolinput:Jk,toolinputpartial:Wk,toolresult:rS,toolcancelled:Gk,hostcontextchanged:iS};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(n){if(!uc.ONE_SHOT_EVENTS.has(n)||this._everHadListener.has(n)||(this._everHadListener.add(n),!this._initializedSent))return;let r=`[ext-apps] "${String(n)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(r);console.warn(r)}setEventHandler(n,r){r&&this._assertHandlerTiming(n),super.setEventHandler(n,r)}addEventListener(n,r){this._assertHandlerTiming(n),super.addEventListener(n,r)}onEventDispatch(n,r){n==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...r})}constructor(n,r={},i={autoResize:!0}){super(i),this._appInfo=n,this._capabilities=r,this.options=i,i.allowUnsafeEval||ct({jitless:!0}),this.setRequestHandler(ja,t=>(console.log("Received ping:",t.params),{})),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(n){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=Ck(this._capabilities,n)}registerTool(n,r,i){if(this._registeredTools[n])throw Error(`Tool ${n} is already registered`);let t=this,o=()=>{t._initializedSent&&t._capabilities.tools?.listChanged&&t.sendToolListChanged()},a=r.inputSchema!==void 0,l={title:r.title,description:r.description,inputSchema:r.inputSchema,outputSchema:r.outputSchema,annotations:r.annotations,_meta:r._meta,enabled:!0,enable(){this.enabled=!0,o()},disable(){this.enabled=!1,o()},update(c){Object.assign(this,c),o()},remove(){t._registeredTools[n]===l&&(delete t._registeredTools[n],o())},handler:async(c,m)=>{if(!l.enabled)throw Error(`Tool ${n} is disabled`);let h;if(a){let d=l.inputSchema,g=d?await wd(d,c??{},`Invalid input for tool ${n}: `):c??{};h=await i(g,m)}else h=await i(m);return l.outputSchema&&!h.isError&&(h.structuredContent=await wd(l.outputSchema,h.structuredContent,`Invalid output for tool ${n}: `)),h}};return this._registeredTools[n]=l,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),o(),l}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(n,r)=>{let i=this._registeredTools[n.name];if(!i)throw Error(`Tool ${n.name} not found`);return i.handler(n.arguments,r)},this.onlisttools=async(n,r)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([i,t])=>t.enabled).map(async([i,t])=>{let o={name:i,title:t.title,description:t.description,inputSchema:t.inputSchema?await Sd(t.inputSchema,"input"):{type:"object",properties:{}}};return t.outputSchema&&(o.outputSchema=await Sd(t.outputSchema,"output")),t.annotations&&(o.annotations=t.annotations),t._meta&&(o._meta=t._meta),o}))}))}async sendToolListChanged(n={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:n})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(n){this.setEventHandler("toolinput",n)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(n){this.setEventHandler("toolinputpartial",n)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(n){this.setEventHandler("toolresult",n)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(n){this.setEventHandler("toolcancelled",n)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(n){this.setEventHandler("hostcontextchanged",n)}_onteardown;get onteardown(){return this._onteardown}set onteardown(n){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,n),this._onteardown=n,this.replaceRequestHandler(Qk,(r,i)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(r.params,i)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(n){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,n),this._oncalltool=n,this.replaceRequestHandler(Hg,(r,i)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(r.params,i)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(n){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,n),this._onlisttools=n,this.replaceRequestHandler(qg,(r,i)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(r.params,i)})}assertCapabilityForMethod(n){switch(n){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${n})`);break}}assertRequestHandlerCapability(n){switch(n){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${n})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${n} registered`)}}assertNotificationCapability(n){}assertTaskCapability(n){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(n){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(n,r){if(this._assertInitialized("callServerTool"),typeof n=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${n}"). Did you mean: callServerTool({ name: "${n}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:n},Pa,{onprogress:()=>{},resetTimeoutOnProgress:!0,...r})}async readServerResource(n,r){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:n},Zg,r)}async listServerResources(n,r){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:n},Mg,r)}async createSamplingMessage(n,r){this._assertInitialized("createSamplingMessage");let i=n.tools?Jg:Bg;return await this.request({method:"sampling/createMessage",params:n},i,r)}sendMessage(n,r){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:n},Bk,r)}sendLog(n){return this.notification({method:"notifications/message",params:n})}updateModelContext(n,r){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:n},Vu,r)}openLink(n,r){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:n},Hk,r)}sendOpenLink=this.openLink;downloadFile(n,r){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:n},Vk,r)}requestTeardown(n={}){return this.notification({method:"ui/notifications/request-teardown",params:n})}requestDisplayMode(n,r){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:n},tS,r)}sendSizeChanged(n){return this.notification({method:"ui/notifications/size-changed",params:n})}setupSizeChangedNotifications(){let n=!1,r=0,i=0,t=()=>{n||(n=!0,requestAnimationFrame(()=>{n=!1;let a=document.documentElement,l=a.style.height;a.style.height="max-content";let c=Math.ceil(a.getBoundingClientRect().height);a.style.height=l;let m=Math.ceil(window.innerWidth);(m!==r||c!==i)&&(r=m,i=c,this.sendSizeChanged({width:m,height:c}))}))};t();let o=new ResizeObserver(t);return o.observe(document.documentElement),o.observe(document.body),()=>o.disconnect()}async connect(n=new Zk(window.parent,window.parent),r){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(n);try{let i=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:Ak}},oS,r);if(i===void 0)throw Error(`Server sent invalid initialize result: ${i}`);this._hostCapabilities=i.hostCapabilities,this._hostInfo=i.hostInfo,this._hostContext=i.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(i){throw this.close(),i}}}const sS=!0,et="u-",lS="uplot",uS=et+"hz",cS=et+"vt",dS=et+"title",fS=et+"wrap",mS=et+"under",pS=et+"over",hS=et+"axis",Yn=et+"off",gS=et+"select",vS=et+"cursor-x",_S=et+"cursor-y",bS=et+"cursor-pt",yS=et+"legend",$S=et+"live",kS=et+"inline",SS=et+"series",wS=et+"marker",Id=et+"label",IS=et+"value",ui="width",ci="height",ai="top",xd="bottom",xr="left",ms="right",cc="#000",zd=cc+"0",ps="mousemove",Td="mousedown",hs="mouseup",Nd="mouseenter",jd="mouseleave",Pd="dblclick",xS="resize",zS="scroll",Ed="change",So="dppxchange",dc="--",Gr=typeof window<"u",Es=Gr?document:null,Pr=Gr?window:null,TS=Gr?navigator:null;let be,so;function Os(){let e=devicePixelRatio;be!=e&&(be=e,so&&Ds(Ed,so,Os),so=matchMedia(`(min-resolution: ${be-.001}dppx) and (max-resolution: ${be+.001}dppx)`),Qn(Ed,so,Os),Pr.dispatchEvent(new CustomEvent(So)))}function Et(e,n){if(n!=null){let r=e.classList;!r.contains(n)&&r.add(n)}}function Us(e,n){let r=e.classList;r.contains(n)&&r.remove(n)}function Re(e,n,r){e.style[n]=r+"px"}function tn(e,n,r,i){let t=Es.createElement(e);return n!=null&&Et(t,n),r?.insertBefore(t,i),t}function Ht(e,n){return tn("div",e,n)}const Od=new WeakMap;function hn(e,n,r,i,t){let o="translate("+n+"px,"+r+"px)",a=Od.get(e);o!=a&&(e.style.transform=o,Od.set(e,o),n<0||r<0||n>i||r>t?Et(e,Yn):Us(e,Yn))}const Ud=new WeakMap;function Dd(e,n,r){let i=n+r,t=Ud.get(e);i!=t&&(Ud.set(e,i),e.style.background=n,e.style.borderColor=r)}const Cd=new WeakMap;function Rd(e,n,r,i){let t=n+""+r,o=Cd.get(e);t!=o&&(Cd.set(e,t),e.style.height=r+"px",e.style.width=n+"px",e.style.marginLeft=i?-n/2+"px":0,e.style.marginTop=i?-r/2+"px":0)}const fc={passive:!0},NS={...fc,capture:!0};function Qn(e,n,r,i){n.addEventListener(e,r,i?NS:fc)}function Ds(e,n,r,i){n.removeEventListener(e,r,fc)}Gr&&Os();function nn(e,n,r,i){let t;r=r||0,i=i||n.length-1;let o=i<=2147483647;for(;i-r>1;)t=o?r+i>>1:Dt((r+i)/2),n[t]<e?r=t:i=t;return e-n[r]<=n[i]-e?r:i}function Gg(e){return(r,i,t)=>{let o=-1,a=-1;for(let l=i;l<=t;l++)if(e(r[l])){o=l;break}for(let l=t;l>=i;l--)if(e(r[l])){a=l;break}return[o,a]}}const Kg=e=>e!=null,Yg=e=>e!=null&&e>0,Ea=Gg(Kg),jS=Gg(Yg);function PS(e,n,r,i=0,t=!1){let o=t?jS:Ea,a=t?Yg:Kg;[n,r]=o(e,n,r);let l=e[n],c=e[n];if(n>-1)if(i==1)l=e[n],c=e[r];else if(i==-1)l=e[r],c=e[n];else for(let m=n;m<=r;m++){let h=e[m];a(h)&&(h<l?l=h:h>c&&(c=h))}return[l??Te,c??-Te]}function Oa(e,n,r,i){let t=Zd(e),o=Zd(n);e==n&&(t==-1?(e*=r,n/=r):(e/=r,n*=r));let a=r==10?yn:Qg,l=t==1?Dt:Vt,c=o==1?Vt:Dt,m=l(a(Qe(e))),h=c(a(Qe(n))),d=Fr(r,m),g=Fr(r,h);return r==10&&(m<0&&(d=Ne(d,-m)),h<0&&(g=Ne(g,-h))),i||r==2?(e=d*t,n=g*o):(e=nv(e,d),n=Ua(n,g)),[e,n]}function mc(e,n,r,i){let t=Oa(e,n,r,i);return e==0&&(t[0]=0),n==0&&(t[1]=0),t}const pc=.1,Ad={mode:3,pad:pc},mi={pad:0,soft:null,mode:0},ES={min:mi,max:mi};function wo(e,n,r,i){return Da(r)?Md(e,n,r):(mi.pad=r,mi.soft=i?0:null,mi.mode=i?3:0,Md(e,n,ES))}function ve(e,n){return e??n}function OS(e,n,r){for(n=ve(n,0),r=ve(r,e.length-1);n<=r;){if(e[n]!=null)return!0;n++}return!1}function Md(e,n,r){let i=r.min,t=r.max,o=ve(i.pad,0),a=ve(t.pad,0),l=ve(i.hard,-Te),c=ve(t.hard,Te),m=ve(i.soft,Te),h=ve(t.soft,-Te),d=ve(i.mode,0),g=ve(t.mode,0),b=n-e,v=yn(b),w=$t(Qe(e),Qe(n)),z=yn(w),U=Qe(z-v);(b<1e-24||U>10)&&(b=0,(e==0||n==0)&&(b=1e-24,d==2&&m!=Te&&(o=0),g==2&&h!=-Te&&(a=0)));let I=b||w||1e3,N=yn(I),j=Fr(10,Dt(N)),G=I*(b==0?e==0?.1:1:o),M=Ne(nv(e-G,j/10),24),ne=e>=m&&(d==1||d==3&&M<=m||d==2&&M>=m)?m:Te,K=$t(l,M<ne&&e>=ne?ne:on(ne,M)),ce=I*(b==0?n==0?.1:1:a),ee=Ne(Ua(n+ce,j/10),24),C=n<=h&&(g==1||g==3&&ee>=h||g==2&&ee<=h)?h:-Te,oe=on(c,ee>C&&n<=C?C:$t(C,ee));return K==oe&&K==0&&(oe=100),[K,oe]}const US=new Intl.NumberFormat(Gr?TS.language:"en-US"),hc=e=>US.format(e),Rt=Math,po=Rt.PI,Qe=Rt.abs,Dt=Rt.floor,Ye=Rt.round,Vt=Rt.ceil,on=Rt.min,$t=Rt.max,Fr=Rt.pow,Zd=Rt.sign,yn=Rt.log10,Qg=Rt.log2,DS=(e,n=1)=>Rt.sinh(e)*n,gs=(e,n=1)=>Rt.asinh(e/n),Te=1/0;function Ld(e){return(yn((e^e>>31)-(e>>31))|0)+1}function Cs(e,n,r){return on($t(e,n),r)}function Xg(e){return typeof e=="function"}function de(e){return Xg(e)?e:()=>e}const CS=()=>{},ev=e=>e,tv=(e,n)=>n,RS=e=>null,Fd=e=>!0,qd=(e,n)=>e==n,AS=/\.\d*?(?=9{6,}|0{6,})/gm,nr=e=>{if(iv(e)||Dn.has(e))return e;const n=`${e}`,r=n.match(AS);if(r==null)return e;let i=r[0].length-1;if(n.indexOf("e-")!=-1){let[t,o]=n.split("e");return+`${nr(t)}e${o}`}return Ne(e,i)};function Gn(e,n){return nr(Ne(nr(e/n))*n)}function Ua(e,n){return nr(Vt(nr(e/n))*n)}function nv(e,n){return nr(Dt(nr(e/n))*n)}function Ne(e,n=0){if(iv(e))return e;let r=10**n,i=e*r*(1+Number.EPSILON);return Ye(i)/r}const Dn=new Map;function rv(e){return((""+e).split(".")[1]||"").length}function Ii(e,n,r,i){let t=[],o=i.map(rv);for(let a=n;a<r;a++){let l=Qe(a),c=Ne(Fr(e,a),l);for(let m=0;m<i.length;m++){let h=e==10?+`${i[m]}e${a}`:i[m]*c,d=(a>=0?0:l)+(a>=o[m]?0:o[m]),g=e==10?h:Ne(h,d);t.push(g),Dn.set(g,d)}}return t}const pi={},gc=[],qr=[null,null],Nn=Array.isArray,iv=Number.isInteger,MS=e=>e===void 0;function Hd(e){return typeof e=="string"}function Da(e){let n=!1;if(e!=null){let r=e.constructor;n=r==null||r==Object}return n}function ZS(e){return e!=null&&typeof e=="object"}const LS=Object.getPrototypeOf(Uint8Array),ov="__proto__";function Hr(e,n=Da){let r;if(Nn(e)){let i=e.find(t=>t!=null);if(Nn(i)||n(i)){r=Array(e.length);for(let t=0;t<e.length;t++)r[t]=Hr(e[t],n)}else r=e.slice()}else if(e instanceof LS)r=e.slice();else if(n(e)){r={};for(let i in e)i!=ov&&(r[i]=Hr(e[i],n))}else r=e;return r}function Je(e){let n=arguments;for(let r=1;r<n.length;r++){let i=n[r];for(let t in i)t!=ov&&(Da(e[t])?Je(e[t],Hr(i[t])):e[t]=Hr(i[t]))}return e}const FS=0,qS=1,HS=2;function VS(e,n,r){for(let i=0,t,o=-1;i<n.length;i++){let a=n[i];if(a>o){for(t=a-1;t>=0&&e[t]==null;)e[t--]=null;for(t=a+1;t<r&&e[t]==null;)e[o=t++]=null}}}function BS(e,n){if(GS(e)){let a=e[0].slice();for(let l=1;l<e.length;l++)a.push(...e[l].slice(1));return KS(a[0])||(a=WS(a)),a}let r=new Set;for(let a=0;a<e.length;a++){let c=e[a][0],m=c.length;for(let h=0;h<m;h++)r.add(c[h])}let i=[Array.from(r).sort((a,l)=>a-l)],t=i[0].length,o=new Map;for(let a=0;a<t;a++)o.set(i[0][a],a);for(let a=0;a<e.length;a++){let l=e[a],c=l[0];for(let m=1;m<l.length;m++){let h=l[m],d=Array(t).fill(void 0),g=n?n[a][m]:qS,b=[];for(let v=0;v<h.length;v++){let w=h[v],z=o.get(c[v]);w===null?g!=FS&&(d[z]=w,g==HS&&b.push(z)):d[z]=w}VS(d,b,t),i.push(d)}}return i}const JS=typeof queueMicrotask>"u"?e=>Promise.resolve().then(e):queueMicrotask;function WS(e){let n=e[0],r=n.length,i=Array(r);for(let o=0;o<i.length;o++)i[o]=o;i.sort((o,a)=>n[o]-n[a]);let t=[];for(let o=0;o<e.length;o++){let a=e[o],l=Array(r);for(let c=0;c<r;c++)l[c]=a[i[c]];t.push(l)}return t}function GS(e){let n=e[0][0],r=n.length;for(let i=1;i<e.length;i++){let t=e[i][0];if(t.length!=r)return!1;if(t!=n){for(let o=0;o<r;o++)if(t[o]!=n[o])return!1}}return!0}function KS(e,n=100){const r=e.length;if(r<=1)return!0;let i=0,t=r-1;for(;i<=t&&e[i]==null;)i++;for(;t>=i&&e[t]==null;)t--;if(t<=i)return!0;const o=$t(1,Dt((t-i+1)/n));for(let a=e[i],l=i+o;l<=t;l+=o){const c=e[l];if(c!=null){if(c<=a)return!1;a=c}}return!0}const av=["January","February","March","April","May","June","July","August","September","October","November","December"],sv=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function lv(e){return e.slice(0,3)}const YS=sv.map(lv),QS=av.map(lv),XS={MMMM:av,MMM:QS,WWWW:sv,WWW:YS};function si(e){return(e<10?"0":"")+e}function ew(e){return(e<10?"00":e<100?"0":"")+e}const tw={YYYY:e=>e.getFullYear(),YY:e=>(e.getFullYear()+"").slice(2),MMMM:(e,n)=>n.MMMM[e.getMonth()],MMM:(e,n)=>n.MMM[e.getMonth()],MM:e=>si(e.getMonth()+1),M:e=>e.getMonth()+1,DD:e=>si(e.getDate()),D:e=>e.getDate(),WWWW:(e,n)=>n.WWWW[e.getDay()],WWW:(e,n)=>n.WWW[e.getDay()],HH:e=>si(e.getHours()),H:e=>e.getHours(),h:e=>{let n=e.getHours();return n==0?12:n>12?n-12:n},AA:e=>e.getHours()>=12?"PM":"AM",aa:e=>e.getHours()>=12?"pm":"am",a:e=>e.getHours()>=12?"p":"a",mm:e=>si(e.getMinutes()),m:e=>e.getMinutes(),ss:e=>si(e.getSeconds()),s:e=>e.getSeconds(),fff:e=>ew(e.getMilliseconds())};function vc(e,n){n=n||XS;let r=[],i=/\{([a-z]+)\}|[^{]+/gi,t;for(;t=i.exec(e);)r.push(t[0][0]=="{"?tw[t[1]]:t[0]);return o=>{let a="";for(let l=0;l<r.length;l++)a+=typeof r[l]=="string"?r[l]:r[l](o,n);return a}}const nw=new Intl.DateTimeFormat().resolvedOptions().timeZone;function rw(e,n){let r;return n=="UTC"||n=="Etc/UTC"?r=new Date(+e+e.getTimezoneOffset()*6e4):n==nw?r=e:(r=new Date(e.toLocaleString("en-US",{timeZone:n})),r.setMilliseconds(e.getMilliseconds())),r}const uv=e=>e%1==0,Io=[1,2,2.5,5],iw=Ii(10,-32,0,Io),cv=Ii(10,0,32,Io),ow=cv.filter(uv),Kn=iw.concat(cv),_c=`
|
|
126
126
|
`,dv="{YYYY}",Vd=_c+dv,fv="{M}/{D}",di=_c+fv,lo=di+"/{YY}",mv="{aa}",aw="{h}:{mm}",Tr=aw+mv,Bd=_c+Tr,Jd=":{ss}",ke=null;function pv(e){let n=e*1e3,r=n*60,i=r*60,t=i*24,o=t*30,a=t*365,c=(e==1?Ii(10,0,3,Io).filter(uv):Ii(10,-3,0,Io)).concat([n,n*5,n*10,n*15,n*30,r,r*5,r*10,r*15,r*30,i,i*2,i*3,i*4,i*6,i*8,i*12,t,t*2,t*3,t*4,t*5,t*6,t*7,t*8,t*9,t*10,t*15,o,o*2,o*3,o*4,o*6,a,a*2,a*5,a*10,a*25,a*50,a*100]);const m=[[a,dv,ke,ke,ke,ke,ke,ke,1],[t*28,"{MMM}",Vd,ke,ke,ke,ke,ke,1],[t,fv,Vd,ke,ke,ke,ke,ke,1],[i,"{h}"+mv,lo,ke,di,ke,ke,ke,1],[r,Tr,lo,ke,di,ke,ke,ke,1],[n,Jd,lo+" "+Tr,ke,di+" "+Tr,ke,Bd,ke,1],[e,Jd+".{fff}",lo+" "+Tr,ke,di+" "+Tr,ke,Bd,ke,1]];function h(d){return(g,b,v,w,z,U)=>{let I=[],N=z>=a,j=z>=o&&z<a,G=d(v),M=Ne(G*e,3),ne=vs(G.getFullYear(),N?0:G.getMonth(),j||N?1:G.getDate()),K=Ne(ne*e,3);if(j||N){let ce=j?z/o:0,ee=N?z/a:0,C=M==K?M:Ne(vs(ne.getFullYear()+ee,ne.getMonth()+ce,1)*e,3),oe=new Date(Ye(C/e)),F=oe.getFullYear(),Y=oe.getMonth();for(let B=0;C<=w;B++){let fe=vs(F+ee*B,Y+ce*B,1),V=fe-d(Ne(fe*e,3));C=Ne((+fe+V)*e,3),C<=w&&I.push(C)}}else{let ce=z>=t?t:z,ee=Dt(v)-Dt(M),C=K+ee+Ua(M-K,ce);I.push(C);let oe=d(C),F=oe.getHours()+oe.getMinutes()/r+oe.getSeconds()/i,Y=z/i,B=g.axes[b]._space,fe=U/B;for(;C=Ne(C+z,e==1?0:3),!(C>w);)if(Y>1){let V=Dt(Ne(F+Y,6))%24,he=d(C).getHours()-V;he>1&&(he=-1),C-=he*i,F=(F+Y)%24;let xe=I[I.length-1];Ne((C-xe)/z,3)*fe>=.7&&I.push(C)}else I.push(C)}return I}}return[c,m,h]}const[sw,lw,uw]=pv(1),[cw,dw,fw]=pv(.001);Ii(2,-53,53,[1]);function Wd(e,n){return e.map(r=>r.map((i,t)=>t==0||t==8||i==null?i:n(t==1||r[8]==0?i:r[1]+i)))}function Gd(e,n){return(r,i,t,o,a)=>{let l=n.find(v=>a>=v[0])||n[n.length-1],c,m,h,d,g,b;return i.map(v=>{let w=e(v),z=w.getFullYear(),U=w.getMonth(),I=w.getDate(),N=w.getHours(),j=w.getMinutes(),G=w.getSeconds(),M=z!=c&&l[2]||U!=m&&l[3]||I!=h&&l[4]||N!=d&&l[5]||j!=g&&l[6]||G!=b&&l[7]||l[1];return c=z,m=U,h=I,d=N,g=j,b=G,M(w)})}}function mw(e,n){let r=vc(n);return(i,t,o,a,l)=>t.map(c=>r(e(c)))}function vs(e,n,r){return new Date(e,n,r)}function Kd(e,n){return n(e)}const pw="{YYYY}-{MM}-{DD} {h}:{mm}{aa}";function Yd(e,n){return(r,i,t,o)=>o==null?dc:n(e(i))}function hw(e,n){let r=e.series[n];return r.width?r.stroke(e,n):r.points.width?r.points.stroke(e,n):null}function gw(e,n){return e.series[n].fill(e,n)}const vw={show:!0,live:!0,isolate:!1,mount:CS,markers:{show:!0,width:2,stroke:hw,fill:gw,dash:"solid"},idx:null,idxs:null,values:[]};function _w(e,n){let r=e.cursor.points,i=Ht(),t=r.size(e,n);Re(i,ui,t),Re(i,ci,t);let o=t/-2;Re(i,"marginLeft",o),Re(i,"marginTop",o);let a=r.width(e,n,t);return a&&Re(i,"borderWidth",a),i}function bw(e,n){let r=e.series[n].points;return r._fill||r._stroke}function yw(e,n){let r=e.series[n].points;return r._stroke||r._fill}function $w(e,n){return e.series[n].points.size}const _s=[0,0];function kw(e,n,r){return _s[0]=n,_s[1]=r,_s}function uo(e,n,r,i=!0){return t=>{t.button==0&&(!i||t.target==n)&&r(t)}}function bs(e,n,r,i=!0){return t=>{(!i||t.target==n)&&r(t)}}const Sw={show:!0,x:!0,y:!0,lock:!1,move:kw,points:{one:!1,show:_w,size:$w,width:0,stroke:yw,fill:bw},bind:{mousedown:uo,mouseup:uo,click:uo,dblclick:uo,mousemove:bs,mouseleave:bs,mouseenter:bs},drag:{setScale:!0,x:!0,y:!1,dist:0,uni:null,click:(e,n)=>{n.stopPropagation(),n.stopImmediatePropagation()},_x:!1,_y:!1},focus:{dist:(e,n,r,i,t)=>i-t,prox:-1,bias:0},hover:{skip:[void 0],prox:null,bias:0},left:-10,top:-10,idx:null,dataIdx:null,idxs:null,event:null},hv={show:!0,stroke:"rgba(0,0,0,0.07)",width:2},bc=Je({},hv,{filter:tv}),gv=Je({},bc,{size:10}),vv=Je({},hv,{show:!1}),yc='12px system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',_v="bold "+yc,bv=1.5,Qd={show:!0,scale:"x",stroke:cc,space:50,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:_v,side:2,grid:bc,ticks:gv,border:vv,font:yc,lineGap:bv,rotate:0},ww="Value",Iw="Time",Xd={show:!0,scale:"x",auto:!1,sorted:1,min:Te,max:-Te,idxs:[]};function xw(e,n,r,i,t){return n.map(o=>o==null?"":hc(o))}function zw(e,n,r,i,t,o,a){let l=[],c=Dn.get(t)||0;r=a?r:Ne(Ua(r,t),c);for(let m=r;m<=i;m=Ne(m+t,c))l.push(Object.is(m,-0)?0:m);return l}function Rs(e,n,r,i,t,o,a){const l=[],c=e.scales[e.axes[n].scale].log,m=c==10?yn:Qg,h=Dt(m(r));t=Fr(c,h),c==10&&(t=Kn[nn(t,Kn)]);let d=r,g=t*c;c==10&&(g=Kn[nn(g,Kn)]);do l.push(d),d=d+t,c==10&&!Dn.has(d)&&(d=Ne(d,Dn.get(t))),d>=g&&(t=d,g=t*c,c==10&&(g=Kn[nn(g,Kn)]));while(d<=i);return l}function Tw(e,n,r,i,t,o,a){let c=e.scales[e.axes[n].scale].asinh,m=i>c?Rs(e,n,$t(c,r),i,t):[c],h=i>=0&&r<=0?[0]:[];return(r<-c?Rs(e,n,$t(c,-i),-r,t):[c]).reverse().map(g=>-g).concat(h,m)}const yv=/./,Nw=/[12357]/,jw=/[125]/,ef=/1/,As=(e,n,r,i)=>e.map((t,o)=>n==4&&t==0||o%i==0&&r.test(t.toExponential()[t<0?1:0])?t:null);function Pw(e,n,r,i,t){let o=e.axes[r],a=o.scale,l=e.scales[a],c=e.valToPos,m=o._space,h=c(10,a),d=c(9,a)-h>=m?yv:c(7,a)-h>=m?Nw:c(5,a)-h>=m?jw:ef;if(d==ef){let g=Qe(c(1,a)-h);if(g<m)return As(n.slice().reverse(),l.distr,d,Vt(m/g)).reverse()}return As(n,l.distr,d,1)}function Ew(e,n,r,i,t){let o=e.axes[r],a=o.scale,l=o._space,c=e.valToPos,m=Qe(c(1,a)-c(2,a));return m<l?As(n.slice().reverse(),3,yv,Vt(l/m)).reverse():n}function Ow(e,n,r,i){return i==null?dc:n==null?"":hc(n)}const tf={show:!0,scale:"y",stroke:cc,space:30,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:_v,side:3,grid:bc,ticks:gv,border:vv,font:yc,lineGap:bv,rotate:0};function Uw(e,n){let r=3+(e||1)*2;return Ne(r*n,3)}function Dw(e,n){let{scale:r,idxs:i}=e.series[0],t=e._data[0],o=e.valToPos(t[i[0]],r,!0),a=e.valToPos(t[i[1]],r,!0),l=Qe(a-o),c=e.series[n],m=l/(c.points.space*be);return i[1]-i[0]<=m}const nf={scale:null,auto:!0,sorted:0,min:Te,max:-Te},$v=(e,n,r,i,t)=>t,rf={show:!0,auto:!0,sorted:0,gaps:$v,alpha:1,facets:[Je({},nf,{scale:"x"}),Je({},nf,{scale:"y"})]},of={scale:"y",auto:!0,sorted:0,show:!0,spanGaps:!1,gaps:$v,alpha:1,points:{show:Dw,filter:null},values:null,min:Te,max:-Te,idxs:[],path:null,clip:null};function Cw(e,n,r,i,t){return r/10}const kv={time:sS,auto:!0,distr:1,log:10,asinh:1,min:null,max:null,dir:1,ori:0},Rw=Je({},kv,{time:!1,ori:1}),af={};function Sv(e,n){let r=af[e];return r||(r={key:e,plots:[],sub(i){r.plots.push(i)},unsub(i){r.plots=r.plots.filter(t=>t!=i)},pub(i,t,o,a,l,c,m){for(let h=0;h<r.plots.length;h++)r.plots[h]!=t&&r.plots[h].pub(i,t,o,a,l,c,m)}},e!=null&&(af[e]=r)),r}const Vr=1,Ms=2;function ar(e,n,r){const i=e.mode,t=e.series[n],o=i==2?e._data[n]:e._data,a=e.scales,l=e.bbox;let c=o[0],m=i==2?o[1]:o[n],h=i==2?a[t.facets[0].scale]:a[e.series[0].scale],d=i==2?a[t.facets[1].scale]:a[t.scale],g=l.left,b=l.top,v=l.width,w=l.height,z=e.valToPosH,U=e.valToPosV;return h.ori==0?r(t,c,m,h,d,z,U,g,b,v,w,Ra,Kr,Ma,Iv,zv):r(t,c,m,h,d,U,z,b,g,w,v,Aa,Yr,Sc,xv,Tv)}function $c(e,n){let r=0,i=0,t=ve(e.bands,gc);for(let o=0;o<t.length;o++){let a=t[o];a.series[0]==n?r=a.dir:a.series[1]==n&&(a.dir==1?i|=1:i|=2)}return[r,i==1?-1:i==2?1:i==3?2:0]}function Aw(e,n,r,i,t){let o=e.mode,a=e.series[n],l=o==2?a.facets[1].scale:a.scale,c=e.scales[l];return t==-1?c.min:t==1?c.max:c.distr==3?c.dir==1?c.min:c.max:0}function $n(e,n,r,i,t,o){return ar(e,n,(a,l,c,m,h,d,g,b,v,w,z)=>{let U=a.pxRound;const I=m.dir*(m.ori==0?1:-1),N=m.ori==0?Kr:Yr;let j,G;I==1?(j=r,G=i):(j=i,G=r);let M=U(d(l[j],m,w,b)),ne=U(g(c[j],h,z,v)),K=U(d(l[G],m,w,b)),ce=U(g(o==1?h.max:h.min,h,z,v)),ee=new Path2D(t);return N(ee,K,ce),N(ee,M,ce),N(ee,M,ne),ee})}function Ca(e,n,r,i,t,o){let a=null;if(e.length>0){a=new Path2D;const l=n==0?Ma:Sc;let c=r;for(let d=0;d<e.length;d++){let g=e[d];if(g[1]>g[0]){let b=g[0]-c;b>0&&l(a,c,i,b,i+o),c=g[1]}}let m=r+t-c,h=10;m>0&&l(a,c,i-h/2,m,i+o+h)}return a}function Mw(e,n,r){let i=e[e.length-1];i&&i[0]==n?i[1]=r:e.push([n,r])}function kc(e,n,r,i,t,o,a){let l=[],c=e.length;for(let m=t==1?r:i;m>=r&&m<=i;m+=t)if(n[m]===null){let d=m,g=m;if(t==1)for(;++m<=i&&n[m]===null;)g=m;else for(;--m>=r&&n[m]===null;)g=m;let b=o(e[d]),v=g==d?b:o(e[g]),w=d-t;b=a<=0&&w>=0&&w<c?o(e[w]):b;let U=g+t;v=a>=0&&U>=0&&U<c?o(e[U]):v,v>=b&&l.push([b,v])}return l}function sf(e){return e==0?ev:e==1?Ye:n=>Gn(n,e)}function wv(e){let n=e==0?Ra:Aa,r=e==0?(t,o,a,l,c,m)=>{t.arcTo(o,a,l,c,m)}:(t,o,a,l,c,m)=>{t.arcTo(a,o,c,l,m)},i=e==0?(t,o,a,l,c)=>{t.rect(o,a,l,c)}:(t,o,a,l,c)=>{t.rect(a,o,c,l)};return(t,o,a,l,c,m=0,h=0)=>{m==0&&h==0?i(t,o,a,l,c):(m=on(m,l/2,c/2),h=on(h,l/2,c/2),n(t,o+m,a),r(t,o+l,a,o+l,a+c,m),r(t,o+l,a+c,o,a+c,h),r(t,o,a+c,o,a,h),r(t,o,a,o+l,a,m),t.closePath())}}const Ra=(e,n,r)=>{e.moveTo(n,r)},Aa=(e,n,r)=>{e.moveTo(r,n)},Kr=(e,n,r)=>{e.lineTo(n,r)},Yr=(e,n,r)=>{e.lineTo(r,n)},Ma=wv(0),Sc=wv(1),Iv=(e,n,r,i,t,o)=>{e.arc(n,r,i,t,o)},xv=(e,n,r,i,t,o)=>{e.arc(r,n,i,t,o)},zv=(e,n,r,i,t,o,a)=>{e.bezierCurveTo(n,r,i,t,o,a)},Tv=(e,n,r,i,t,o,a)=>{e.bezierCurveTo(r,n,t,i,a,o)};function Nv(e){return(n,r,i,t,o)=>ar(n,r,(a,l,c,m,h,d,g,b,v,w,z)=>{let{pxRound:U,points:I}=a,N,j;m.ori==0?(N=Ra,j=Iv):(N=Aa,j=xv);const G=Ne(I.width*be,3);let M=(I.size-I.width)/2*be,ne=Ne(M*2,3),K=new Path2D,ce=new Path2D,{left:ee,top:C,width:oe,height:F}=n.bbox;Ma(ce,ee-ne,C-ne,oe+ne*2,F+ne*2);const Y=B=>{if(c[B]!=null){let fe=U(d(l[B],m,w,b)),V=U(g(c[B],h,z,v));N(K,fe+M,V),j(K,fe,V,M,0,po*2)}};if(o)o.forEach(Y);else for(let B=i;B<=t;B++)Y(B);return{stroke:G>0?K:null,fill:K,clip:ce,flags:Vr|Ms}})}function jv(e){return(n,r,i,t,o,a)=>{i!=t&&(o!=i&&a!=i&&e(n,r,i),o!=t&&a!=t&&e(n,r,t),e(n,r,a))}}const Zw=jv(Kr),Lw=jv(Yr);function Pv(e){const n=ve(e?.alignGaps,0);return(r,i,t,o)=>ar(r,i,(a,l,c,m,h,d,g,b,v,w,z)=>{[t,o]=Ea(c,t,o);let U=a.pxRound,I=F=>U(d(F,m,w,b)),N=F=>U(g(F,h,z,v)),j,G;m.ori==0?(j=Kr,G=Zw):(j=Yr,G=Lw);const M=m.dir*(m.ori==0?1:-1),ne={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:Vr},K=ne.stroke;let ce=!1;if(o-t>=w*4){let F=q=>r.posToVal(q,m.key,!0),Y=null,B=null,fe,V,St,Ae=I(l[M==1?t:o]),he=I(l[t]),xe=I(l[o]),le=F(M==1?he+1:xe-1);for(let q=M==1?t:o;q>=t&&q<=o;q+=M){let We=l[q],Me=(M==1?We<le:We>le)?Ae:I(We),$e=c[q];Me==Ae?$e!=null?(V=$e,Y==null?(j(K,Me,N(V)),fe=Y=B=V):V<Y?Y=V:V>B&&(B=V)):$e===null&&(ce=!0):(Y!=null&&G(K,Ae,N(Y),N(B),N(fe),N(V)),$e!=null?(V=$e,j(K,Me,N(V)),Y=B=fe=V):(Y=B=null,$e===null&&(ce=!0)),Ae=Me,le=F(Ae+M))}Y!=null&&Y!=B&&St!=Ae&&G(K,Ae,N(Y),N(B),N(fe),N(V))}else for(let F=M==1?t:o;F>=t&&F<=o;F+=M){let Y=c[F];Y===null?ce=!0:Y!=null&&j(K,I(l[F]),N(Y))}let[C,oe]=$c(r,i);if(a.fill!=null||C!=0){let F=ne.fill=new Path2D(K),Y=a.fillTo(r,i,a.min,a.max,C),B=N(Y),fe=I(l[t]),V=I(l[o]);M==-1&&([V,fe]=[fe,V]),j(F,V,B),j(F,fe,B)}if(!a.spanGaps){let F=[];ce&&F.push(...kc(l,c,t,o,M,I,n)),ne.gaps=F=a.gaps(r,i,t,o,F),ne.clip=Ca(F,m.ori,b,v,w,z)}return oe!=0&&(ne.band=oe==2?[$n(r,i,t,o,K,-1),$n(r,i,t,o,K,1)]:$n(r,i,t,o,K,oe)),ne})}function Fw(e){const n=ve(e.align,1),r=ve(e.ascDesc,!1),i=ve(e.alignGaps,0),t=ve(e.extend,!1);return(o,a,l,c)=>ar(o,a,(m,h,d,g,b,v,w,z,U,I,N)=>{[l,c]=Ea(d,l,c);let j=m.pxRound,{left:G,width:M}=o.bbox,ne=he=>j(v(he,g,I,z)),K=he=>j(w(he,b,N,U)),ce=g.ori==0?Kr:Yr;const ee={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:Vr},C=ee.stroke,oe=g.dir*(g.ori==0?1:-1);let F=K(d[oe==1?l:c]),Y=ne(h[oe==1?l:c]),B=Y,fe=Y;t&&n==-1&&(fe=G,ce(C,fe,F)),ce(C,Y,F);for(let he=oe==1?l:c;he>=l&&he<=c;he+=oe){let xe=d[he];if(xe==null)continue;let le=ne(h[he]),q=K(xe);n==1?ce(C,le,F):ce(C,B,q),ce(C,le,q),F=q,B=le}let V=B;t&&n==1&&(V=G+M,ce(C,V,F));let[St,Ae]=$c(o,a);if(m.fill!=null||St!=0){let he=ee.fill=new Path2D(C),xe=m.fillTo(o,a,m.min,m.max,St),le=K(xe);ce(he,V,le),ce(he,fe,le)}if(!m.spanGaps){let he=[];he.push(...kc(h,d,l,c,oe,ne,i));let xe=m.width*be/2,le=r||n==1?xe:-xe,q=r||n==-1?-xe:xe;he.forEach(We=>{We[0]+=le,We[1]+=q}),ee.gaps=he=m.gaps(o,a,l,c,he),ee.clip=Ca(he,g.ori,z,U,I,N)}return Ae!=0&&(ee.band=Ae==2?[$n(o,a,l,c,C,-1),$n(o,a,l,c,C,1)]:$n(o,a,l,c,C,Ae)),ee})}function lf(e,n,r,i,t,o,a=Te){if(e.length>1){let l=null;for(let c=0,m=1/0;c<e.length;c++)if(n[c]!==void 0){if(l!=null){let h=Qe(e[c]-e[l]);h<m&&(m=h,a=Qe(r(e[c],i,t,o)-r(e[l],i,t,o)))}l=c}}return a}function qw(e){e=e||pi;const n=ve(e.size,[.6,Te,1]),r=e.align||0,i=e.gap||0;let t=e.radius;t=t==null?[0,0]:typeof t=="number"?[t,0]:t;const o=de(t),a=1-n[0],l=ve(n[1],Te),c=ve(n[2],1),m=ve(e.disp,pi),h=ve(e.each,b=>{}),{fill:d,stroke:g}=m;return(b,v,w,z)=>ar(b,v,(U,I,N,j,G,M,ne,K,ce,ee,C)=>{let oe=U.pxRound,F=r,Y=i*be,B=l*be,fe=c*be,V,St;j.ori==0?[V,St]=o(b,v):[St,V]=o(b,v);const Ae=j.dir*(j.ori==0?1:-1);let he=j.ori==0?Ma:Sc,xe=j.ori==0?h:(Z,je,Ge,cr,Mn,un,Zn)=>{h(Z,je,Ge,Mn,cr,Zn,un)},le=ve(b.bands,gc).find(Z=>Z.series[0]==v),q=le!=null?le.dir:0,We=U.fillTo(b,v,U.min,U.max,q),ht=oe(ne(We,G,C,ce)),Me,$e,Kt,zt=ee,Le=oe(U.width*be),ln=!1,vn=null,At=null,Sn=null,sr=null;d!=null&&(Le==0||g!=null)&&(ln=!0,vn=d.values(b,v,w,z),At=new Map,new Set(vn).forEach(Z=>{Z!=null&&At.set(Z,new Path2D)}),Le>0&&(Sn=g.values(b,v,w,z),sr=new Map,new Set(Sn).forEach(Z=>{Z!=null&&sr.set(Z,new Path2D)})));let{x0:lr,size:Qr}=m;if(lr!=null&&Qr!=null){F=1,I=lr.values(b,v,w,z),lr.unit==2&&(I=I.map(Ge=>b.posToVal(K+Ge*ee,j.key,!0)));let Z=Qr.values(b,v,w,z);Qr.unit==2?$e=Z[0]*ee:$e=M(Z[0],j,ee,K)-M(0,j,ee,K),zt=lf(I,N,M,j,ee,K,zt),Kt=zt-$e+Y}else zt=lf(I,N,M,j,ee,K,zt),Kt=zt*a+Y,$e=zt-Kt;Kt<1&&(Kt=0),Le>=$e/2&&(Le=0),Kt<5&&(oe=ev);let Wi=Kt>0,Rn=zt-Kt-(Wi?Le:0);$e=oe(Cs(Rn,fe,B)),Me=(F==0?$e/2:F==Ae?0:$e)-F*Ae*((F==0?Y/2:0)+(Wi?Le/2:0));const gt={stroke:null,fill:null,clip:null,band:null,gaps:null,flags:0},ur=ln?null:new Path2D;let _n=null;if(le!=null)_n=b.data[le.series[1]];else{let{y0:Z,y1:je}=m;Z!=null&&je!=null&&(N=je.values(b,v,w,z),_n=Z.values(b,v,w,z))}let An=V*$e,re=St*$e;for(let Z=Ae==1?w:z;Z>=w&&Z<=z;Z+=Ae){let je=N[Z];if(je==null)continue;if(_n!=null){let wt=_n[Z]??0;if(je-wt==0)continue;ht=ne(wt,G,C,ce)}let Ge=j.distr!=2||m!=null?I[Z]:Z,cr=M(Ge,j,ee,K),Mn=ne(ve(je,We),G,C,ce),un=oe(cr-Me),Zn=oe($t(Mn,ht)),Tt=oe(on(Mn,ht)),Mt=Zn-Tt;if(je!=null){let wt=je<0?re:An,Yt=je<0?An:re;ln?(Le>0&&Sn[Z]!=null&&he(sr.get(Sn[Z]),un,Tt+Dt(Le/2),$e,$t(0,Mt-Le),wt,Yt),vn[Z]!=null&&he(At.get(vn[Z]),un,Tt+Dt(Le/2),$e,$t(0,Mt-Le),wt,Yt)):he(ur,un,Tt+Dt(Le/2),$e,$t(0,Mt-Le),wt,Yt),xe(b,v,Z,un-Le/2,Tt,$e+Le,Mt)}}return Le>0?gt.stroke=ln?sr:ur:ln||(gt._fill=U.width==0?U._fill:U._stroke??U._fill,gt.width=0),gt.fill=ln?At:ur,gt})}function Hw(e,n){const r=ve(n?.alignGaps,0);return(i,t,o,a)=>ar(i,t,(l,c,m,h,d,g,b,v,w,z,U)=>{[o,a]=Ea(m,o,a);let I=l.pxRound,N=V=>I(g(V,h,z,v)),j=V=>I(b(V,d,U,w)),G,M,ne;h.ori==0?(G=Ra,ne=Kr,M=zv):(G=Aa,ne=Yr,M=Tv);const K=h.dir*(h.ori==0?1:-1);let ce=N(c[K==1?o:a]),ee=ce,C=[],oe=[];for(let V=K==1?o:a;V>=o&&V<=a;V+=K)if(m[V]!=null){let Ae=c[V],he=N(Ae);C.push(ee=he),oe.push(j(m[V]))}const F={stroke:e(C,oe,G,ne,M,I),fill:null,clip:null,band:null,gaps:null,flags:Vr},Y=F.stroke;let[B,fe]=$c(i,t);if(l.fill!=null||B!=0){let V=F.fill=new Path2D(Y),St=l.fillTo(i,t,l.min,l.max,B),Ae=j(St);ne(V,ee,Ae),ne(V,ce,Ae)}if(!l.spanGaps){let V=[];V.push(...kc(c,m,o,a,K,N,r)),F.gaps=V=l.gaps(i,t,o,a,V),F.clip=Ca(V,h.ori,v,w,z,U)}return fe!=0&&(F.band=fe==2?[$n(i,t,o,a,Y,-1),$n(i,t,o,a,Y,1)]:$n(i,t,o,a,Y,fe)),F})}function Vw(e){return Hw(Bw,e)}function Bw(e,n,r,i,t,o){const a=e.length;if(a<2)return null;const l=new Path2D;if(r(l,e[0],n[0]),a==2)i(l,e[1],n[1]);else{let c=Array(a),m=Array(a-1),h=Array(a-1),d=Array(a-1);for(let g=0;g<a-1;g++)h[g]=n[g+1]-n[g],d[g]=e[g+1]-e[g],m[g]=h[g]/d[g];c[0]=m[0];for(let g=1;g<a-1;g++)m[g]===0||m[g-1]===0||m[g-1]>0!=m[g]>0?c[g]=0:(c[g]=3*(d[g-1]+d[g])/((2*d[g]+d[g-1])/m[g-1]+(d[g]+2*d[g-1])/m[g]),isFinite(c[g])||(c[g]=0));c[a-1]=m[a-2];for(let g=0;g<a-1;g++)t(l,e[g]+d[g]/3,n[g]+c[g]*d[g]/3,e[g+1]-d[g]/3,n[g+1]-c[g+1]*d[g]/3,e[g+1],n[g+1])}return l}const Zs=new Set;function uf(){for(let e of Zs)e.syncRect(!0)}Gr&&(Qn(xS,Pr,uf),Qn(zS,Pr,uf,!0),Qn(So,Pr,()=>{ut.pxRatio=be}));const Jw=Pv(),Ww=Nv();function cf(e,n,r,i){return(i?[e[0],e[1]].concat(e.slice(2)):[e[0]].concat(e.slice(1))).map((o,a)=>Ls(o,a,n,r))}function Gw(e,n){return e.map((r,i)=>i==0?{}:Je({},n,r))}function Ls(e,n,r,i){return Je({},n==0?r:i,e)}function Ev(e,n,r){return n==null?qr:[n,r]}const Kw=Ev;function Yw(e,n,r){return n==null?qr:wo(n,r,pc,!0)}function Ov(e,n,r,i){return n==null?qr:Oa(n,r,e.scales[i].log,!1)}const Qw=Ov;function Uv(e,n,r,i){return n==null?qr:mc(n,r,e.scales[i].log,!1)}const Xw=Uv;function eI(e,n,r,i,t){let o=$t(Ld(e),Ld(n)),a=n-e,l=nn(t/i*a,r);do{let c=r[l],m=i*c/a;if(m>=t&&o+(c<5?Dn.get(c):0)<=17)return[c,m]}while(++l<r.length);return[0,0]}function df(e){let n,r;return e=e.replace(/(\d+)px/,(i,t)=>(n=Ye((r=+t)*be))+"px"),[e,n,r]}function tI(e){e.show&&[e.font,e.labelFont].forEach(n=>{let r=Ne(n[2]*be,1);n[0]=n[0].replace(/[0-9.]+px/,r+"px"),n[1]=r})}function ut(e,n,r){const i={mode:ve(e.mode,1)},t=i.mode;function o(s,u,f,p){let _=u.valToPct(s);return p+f*(u.dir==-1?1-_:_)}function a(s,u,f,p){let _=u.valToPct(s);return p+f*(u.dir==-1?_:1-_)}function l(s,u,f,p){return u.ori==0?o(s,u,f,p):a(s,u,f,p)}i.valToPosH=o,i.valToPosV=a;let c=!1;i.status=0;const m=i.root=Ht(lS);if(e.id!=null&&(m.id=e.id),Et(m,e.class),e.title){let s=Ht(dS,m);s.textContent=e.title}const h=tn("canvas"),d=i.ctx=h.getContext("2d"),g=Ht(fS,m);Qn("click",g,s=>{s.target===v&&(Ue!=$r||Ze!=kr)&<.click(i,s)},!0);const b=i.under=Ht(mS,g);g.appendChild(h);const v=i.over=Ht(pS,g);e=Hr(e);const w=+ve(e.pxAlign,1),z=sf(w);(e.plugins||[]).forEach(s=>{s.opts&&(e=s.opts(i,e)||e)});const U=e.ms||.001,I=i.series=t==1?cf(e.series||[],Xd,of,!1):Gw(e.series||[null],rf),N=i.axes=cf(e.axes||[],Qd,tf,!0),j=i.scales={},G=i.bands=e.bands||[];G.forEach(s=>{s.fill=de(s.fill||null),s.dir=ve(s.dir,-1)});const M=t==2?I[1].facets[0].scale:I[0].scale,ne={axes:a_,series:t_},K=(e.drawOrder||["axes","series"]).map(s=>ne[s]);function ce(s){const u=s.distr==3?f=>yn(f>0?f:s.clamp(i,f,s.min,s.max,s.key)):s.distr==4?f=>gs(f,s.asinh):s.distr==100?f=>s.fwd(f):f=>f;return f=>{let p=u(f),{_min:_,_max:S}=s,T=S-_;return(p-_)/T}}function ee(s){let u=j[s];if(u==null){let f=(e.scales||pi)[s]||pi;if(f.from!=null){ee(f.from);let p=Je({},j[f.from],f,{key:s});p.valToPct=ce(p),j[s]=p}else{u=j[s]=Je({},s==M?kv:Rw,f),u.key=s;let p=u.time,_=u.range,S=Nn(_);if((s!=M||t==2&&!p)&&(S&&(_[0]==null||_[1]==null)&&(_={min:_[0]==null?Ad:{mode:1,hard:_[0],soft:_[0]},max:_[1]==null?Ad:{mode:1,hard:_[1],soft:_[1]}},S=!1),!S&&Da(_))){let T=_;_=(E,O,R)=>O==null?qr:wo(O,R,T)}u.range=de(_||(p?Kw:s==M?u.distr==3?Qw:u.distr==4?Xw:Ev:u.distr==3?Ov:u.distr==4?Uv:Yw)),u.auto=de(S?!1:u.auto),u.clamp=de(u.clamp||Cw),u._min=u._max=null,u.valToPct=ce(u)}}}ee("x"),ee("y"),t==1&&I.forEach(s=>{ee(s.scale)}),N.forEach(s=>{ee(s.scale)});for(let s in e.scales)ee(s);const C=j[M],oe=C.distr;let F,Y;C.ori==0?(Et(m,uS),F=o,Y=a):(Et(m,cS),F=a,Y=o);const B={};for(let s in j){let u=j[s];(u.min!=null||u.max!=null)&&(B[s]={min:u.min,max:u.max},u.min=u.max=null)}const fe=e.tzDate||(s=>new Date(Ye(s/U))),V=e.fmtDate||vc,St=U==1?uw(fe):fw(fe),Ae=Gd(fe,Wd(U==1?lw:dw,V)),he=Yd(fe,Kd(pw,V)),xe=[],le=i.legend=Je({},vw,e.legend),q=i.cursor=Je({},Sw,{drag:{y:t==2}},e.cursor),We=le.show,ht=q.show,Me=le.markers;le.idxs=xe,Me.width=de(Me.width),Me.dash=de(Me.dash),Me.stroke=de(Me.stroke),Me.fill=de(Me.fill);let $e,Kt,zt,Le=[],ln=[],vn,At=!1,Sn={};if(le.live){const s=I[1]?I[1].values:null;At=s!=null,vn=At?s(i,1,0):{_:0};for(let u in vn)Sn[u]=dc}if(We)if($e=tn("table",yS,m),zt=tn("tbody",null,$e),le.mount(i,$e),At){Kt=tn("thead",null,$e,zt);let s=tn("tr",null,Kt);tn("th",null,s);for(var sr in vn)tn("th",Id,s).textContent=sr}else Et($e,kS),le.live&&Et($e,$S);const lr={show:!0},Qr={show:!1};function Wi(s,u){if(u==0&&(At||!le.live||t==2))return qr;let f=[],p=tn("tr",SS,zt,zt.childNodes[u]);Et(p,s.class),s.show||Et(p,Yn);let _=tn("th",null,p);if(Me.show){let E=Ht(wS,_);if(u>0){let O=Me.width(i,u);O&&(E.style.border=O+"px "+Me.dash(i,u)+" "+Me.stroke(i,u)),E.style.background=Me.fill(i,u)}}let S=Ht(Id,_);s.label instanceof HTMLElement?S.appendChild(s.label):S.textContent=s.label,u>0&&(Me.show||(S.style.color=s.width>0?Me.stroke(i,u):Me.fill(i,u)),gt("click",_,E=>{if(q._lock)return;Fn(E);let O=I.indexOf(s);if((E.ctrlKey||E.metaKey)!=le.isolate){let R=I.some((A,L)=>L>0&&L!=O&&A.show);I.forEach((A,L)=>{L>0&&dn(L,R?L==O?lr:Qr:lr,!0,Be.setSeries)})}else dn(O,{show:!s.show},!0,Be.setSeries)},!1),fr&>(Nd,_,E=>{q._lock||(Fn(E),dn(I.indexOf(s),wr,!0,Be.setSeries))},!1));for(var T in vn){let E=tn("td",IS,p);E.textContent="--",f.push(E)}return[p,f]}const Rn=new Map;function gt(s,u,f,p=!0){const _=Rn.get(u)||{},S=q.bind[s](i,u,f,p);S&&(Qn(s,u,_[s]=S),Rn.set(u,_))}function ur(s,u,f){const p=Rn.get(u)||{};for(let _ in p)(s==null||_==s)&&(Ds(_,u,p[_]),delete p[_]);s==null&&Rn.delete(u)}let _n=0,An=0,re=0,Z=0,je=0,Ge=0,cr=je,Mn=Ge,un=re,Zn=Z,Tt=0,Mt=0,wt=0,Yt=0;i.bbox={};let Ha=!1,Gi=!1,dr=!1,Ln=!1,Ki=!1,Zt=!1;function Va(s,u,f){(f||s!=i.width||u!=i.height)&&xc(s,u),vr(!1),dr=!0,Gi=!0,_r()}function xc(s,u){i.width=_n=re=s,i.height=An=Z=u,je=Ge=0,Wv(),Gv();let f=i.bbox;Tt=f.left=Gn(je*be,.5),Mt=f.top=Gn(Ge*be,.5),wt=f.width=Gn(re*be,.5),Yt=f.height=Gn(Z*be,.5)}const Vv=3;function Bv(){let s=!1,u=0;for(;!s;){u++;let f=i_(u),p=o_(u);s=u==Vv||f&&p,s||(xc(i.width,i.height),Gi=!0)}}function Jv({width:s,height:u}){Va(s,u)}i.setSize=Jv;function Wv(){let s=!1,u=!1,f=!1,p=!1;N.forEach((_,S)=>{if(_.show&&_._show){let{side:T,_size:E}=_,O=T%2,R=_.label!=null?_.labelSize:0,A=E+R;A>0&&(O?(re-=A,T==3?(je+=A,p=!0):f=!0):(Z-=A,T==0?(Ge+=A,s=!0):u=!0))}}),qn[0]=s,qn[1]=f,qn[2]=u,qn[3]=p,re-=wn[1]+wn[3],je+=wn[3],Z-=wn[2]+wn[0],Ge+=wn[0]}function Gv(){let s=je+re,u=Ge+Z,f=je,p=Ge;function _(S,T){switch(S){case 1:return s+=T,s-T;case 2:return u+=T,u-T;case 3:return f-=T,f+T;case 0:return p-=T,p+T}}N.forEach((S,T)=>{if(S.show&&S._show){let E=S.side;S._pos=_(E,S._size),S.label!=null&&(S._lpos=_(E,S.labelSize))}})}if(q.dataIdx==null){let s=q.hover,u=s.skip=new Set(s.skip??[]);u.add(void 0);let f=s.prox=de(s.prox),p=s.bias??=0;q.dataIdx=(_,S,T,E)=>{if(S==0)return T;let O=T,R=f(_,S,T,E)??Te,A=R>=0&&R<Te,L=C.ori==0?re:Z,Q=q.left,_e=n[0],ge=n[S];if(u.has(ge[T])){O=null;let ue=null,J=null,H;if(p==0||p==-1)for(H=T;ue==null&&H-- >0;)u.has(ge[H])||(ue=H);if(p==0||p==1)for(H=T;J==null&&H++<ge.length;)u.has(ge[H])||(J=H);if(ue!=null||J!=null)if(A){let Ce=ue==null?-1/0:F(_e[ue],C,L,0),qe=J==null?1/0:F(_e[J],C,L,0),at=Q-Ce,ze=qe-Q;at<=ze?at<=R&&(O=ue):ze<=R&&(O=J)}else O=J==null?ue:ue==null?J:T-ue<=J-T?ue:J}else A&&Qe(Q-F(_e[T],C,L,0))>R&&(O=null);return O}}const Fn=s=>{q.event=s};q.idxs=xe,q._lock=!1;let mt=q.points;mt.show=de(mt.show),mt.size=de(mt.size),mt.stroke=de(mt.stroke),mt.width=de(mt.width),mt.fill=de(mt.fill);const cn=i.focus=Je({},e.focus||{alpha:.3},q.focus),fr=cn.prox>=0,mr=fr&&mt.one;let Lt=[],pr=[],hr=[];function zc(s,u){let f=mt.show(i,u);if(f instanceof HTMLElement)return Et(f,bS),Et(f,s.class),hn(f,-10,-10,re,Z),v.insertBefore(f,Lt[u]),f}function Tc(s,u){if(t==1||u>0){let f=t==1&&j[s.scale].time,p=s.value;s.value=f?Hd(p)?Yd(fe,Kd(p,V)):p||he:p||Ow,s.label=s.label||(f?Iw:ww)}if(mr||u>0){s.width=s.width==null?1:s.width,s.paths=s.paths||Jw||RS,s.fillTo=de(s.fillTo||Aw),s.pxAlign=+ve(s.pxAlign,w),s.pxRound=sf(s.pxAlign),s.stroke=de(s.stroke||null),s.fill=de(s.fill||null),s._stroke=s._fill=s._paths=s._focus=null;let f=Uw($t(1,s.width),1),p=s.points=Je({},{size:f,width:$t(1,f*.2),stroke:s.stroke,space:f*2,paths:Ww,_stroke:null,_fill:null},s.points);p.show=de(p.show),p.filter=de(p.filter),p.fill=de(p.fill),p.stroke=de(p.stroke),p.paths=de(p.paths),p.pxAlign=s.pxAlign}if(We){let f=Wi(s,u);Le.splice(u,0,f[0]),ln.splice(u,0,f[1]),le.values.push(null)}if(ht){xe.splice(u,0,null);let f=null;mr?u==0&&(f=zc(s,u)):u>0&&(f=zc(s,u)),Lt.splice(u,0,f),pr.splice(u,0,0),hr.splice(u,0,0)}ot("addSeries",u)}function Kv(s,u){u=u??I.length,s=t==1?Ls(s,u,Xd,of):Ls(s,u,{},rf),I.splice(u,0,s),Tc(I[u],u)}i.addSeries=Kv;function Yv(s){if(I.splice(s,1),We){le.values.splice(s,1),ln.splice(s,1);let u=Le.splice(s,1)[0];ur(null,u.firstChild),u.remove()}ht&&(xe.splice(s,1),Lt.splice(s,1)[0].remove(),pr.splice(s,1),hr.splice(s,1)),ot("delSeries",s)}i.delSeries=Yv;const qn=[!1,!1,!1,!1];function Qv(s,u){if(s._show=s.show,s.show){let f=s.side%2,p=j[s.scale];p==null&&(s.scale=f?I[1].scale:M,p=j[s.scale]);let _=p.time;s.size=de(s.size),s.space=de(s.space),s.rotate=de(s.rotate),Nn(s.incrs)&&s.incrs.forEach(T=>{!Dn.has(T)&&Dn.set(T,rv(T))}),s.incrs=de(s.incrs||(p.distr==2?ow:_?U==1?sw:cw:Kn)),s.splits=de(s.splits||(_&&p.distr==1?St:p.distr==3?Rs:p.distr==4?Tw:zw)),s.stroke=de(s.stroke),s.grid.stroke=de(s.grid.stroke),s.ticks.stroke=de(s.ticks.stroke),s.border.stroke=de(s.border.stroke);let S=s.values;s.values=Nn(S)&&!Nn(S[0])?de(S):_?Nn(S)?Gd(fe,Wd(S,V)):Hd(S)?mw(fe,S):S||Ae:S||xw,s.filter=de(s.filter||(p.distr>=3&&p.log==10?Pw:p.distr==3&&p.log==2?Ew:tv)),s.font=df(s.font),s.labelFont=df(s.labelFont),s._size=s.size(i,null,u,0),s._space=s._rotate=s._incrs=s._found=s._splits=s._values=null,s._size>0&&(qn[u]=!0,s._el=Ht(hS,g))}}function Xr(s,u,f,p){let[_,S,T,E]=f,O=u%2,R=0;return O==0&&(E||S)&&(R=u==0&&!_||u==2&&!T?Ye(Qd.size/3):0),O==1&&(_||T)&&(R=u==1&&!S||u==3&&!E?Ye(tf.size/2):0),R}const Nc=i.padding=(e.padding||[Xr,Xr,Xr,Xr]).map(s=>de(ve(s,Xr))),wn=i._padding=Nc.map((s,u)=>s(i,u,qn,0));let st,tt=null,nt=null;const Yi=t==1?I[0].idxs:null;let Qt=null,ei=!1;function jc(s,u){if(n=s??[],i.data=i._data=n,t==2){st=0;for(let f=1;f<I.length;f++)st+=n[f][0].length}else{n.length==0&&(i.data=i._data=n=[[]]),Qt=n[0],st=Qt.length;let f=n;if(oe==2){f=n.slice();let p=f[0]=Array(st);for(let _=0;_<st;_++)p[_]=_}i._data=n=f}if(vr(!0),ot("setData"),oe==2&&(dr=!0),u!==!1){let f=C;f.auto(i,ei)?Ba():xn(M,f.min,f.max),Ln=Ln||q.left>=0,Zt=!0,_r()}}i.setData=jc;function Ba(){ei=!0;let s,u;t==1&&(st>0?(tt=Yi[0]=0,nt=Yi[1]=st-1,s=n[0][tt],u=n[0][nt],oe==2?(s=tt,u=nt):s==u&&(oe==3?[s,u]=Oa(s,s,C.log,!1):oe==4?[s,u]=mc(s,s,C.log,!1):C.time?u=s+Ye(86400/U):[s,u]=wo(s,u,pc,!0))):(tt=Yi[0]=s=null,nt=Yi[1]=u=null)),xn(M,s,u)}let Qi,gr,Ja,Wa,Ga,Ka,Ya,Qa,Xa,It;function Pc(s,u,f,p,_,S){s??=zd,f??=gc,p??="butt",_??=zd,S??="round",s!=Qi&&(d.strokeStyle=Qi=s),_!=gr&&(d.fillStyle=gr=_),u!=Ja&&(d.lineWidth=Ja=u),S!=Ga&&(d.lineJoin=Ga=S),p!=Ka&&(d.lineCap=Ka=p),f!=Wa&&d.setLineDash(Wa=f)}function Ec(s,u,f,p){u!=gr&&(d.fillStyle=gr=u),s!=Ya&&(d.font=Ya=s),f!=Qa&&(d.textAlign=Qa=f),p!=Xa&&(d.textBaseline=Xa=p)}function es(s,u,f,p,_=0){if(p.length>0&&s.auto(i,ei)&&(u==null||u.min==null)){let S=ve(tt,0),T=ve(nt,p.length-1),E=f.min==null?PS(p,S,T,_,s.distr==3):[f.min,f.max];s.min=on(s.min,f.min=E[0]),s.max=$t(s.max,f.max=E[1])}}const Oc={min:null,max:null};function Xv(){for(let p in j){let _=j[p];B[p]==null&&(_.min==null||B[M]!=null&&_.auto(i,ei))&&(B[p]=Oc)}for(let p in j){let _=j[p];B[p]==null&&_.from!=null&&B[_.from]!=null&&(B[p]=Oc)}B[M]!=null&&vr(!0);let s={};for(let p in B){let _=B[p];if(_!=null){let S=s[p]=Hr(j[p],ZS);if(_.min!=null)Je(S,_);else if(p!=M||t==2)if(st==0&&S.from==null){let T=S.range(i,null,null,p);S.min=T[0],S.max=T[1]}else S.min=Te,S.max=-Te}}if(st>0){I.forEach((p,_)=>{if(t==1){let S=p.scale,T=B[S];if(T==null)return;let E=s[S];if(_==0){let O=E.range(i,E.min,E.max,S);E.min=O[0],E.max=O[1],tt=nn(E.min,n[0]),nt=nn(E.max,n[0]),nt-tt>1&&(n[0][tt]<E.min&&tt++,n[0][nt]>E.max&&nt--),p.min=Qt[tt],p.max=Qt[nt]}else p.show&&p.auto&&es(E,T,p,n[_],p.sorted);p.idxs[0]=tt,p.idxs[1]=nt}else if(_>0&&p.show&&p.auto){let[S,T]=p.facets,E=S.scale,O=T.scale,[R,A]=n[_],L=s[E],Q=s[O];L!=null&&es(L,B[E],S,R,S.sorted),Q!=null&&es(Q,B[O],T,A,T.sorted),p.min=T.min,p.max=T.max}});for(let p in s){let _=s[p],S=B[p];if(_.from==null&&(S==null||S.min==null)){let T=_.range(i,_.min==Te?null:_.min,_.max==-Te?null:_.max,p);_.min=T[0],_.max=T[1]}}}for(let p in s){let _=s[p];if(_.from!=null){let S=s[_.from];if(S.min==null)_.min=_.max=null;else{let T=_.range(i,S.min,S.max,p);_.min=T[0],_.max=T[1]}}}let u={},f=!1;for(let p in s){let _=s[p],S=j[p];if(S.min!=_.min||S.max!=_.max){S.min=_.min,S.max=_.max;let T=S.distr;S._min=T==3?yn(S.min):T==4?gs(S.min,S.asinh):T==100?S.fwd(S.min):S.min,S._max=T==3?yn(S.max):T==4?gs(S.max,S.asinh):T==100?S.fwd(S.max):S.max,u[p]=f=!0}}if(f){I.forEach((p,_)=>{t==2?_>0&&u.y&&(p._paths=null):u[p.scale]&&(p._paths=null)});for(let p in u)dr=!0,ot("setScale",p);ht&&q.left>=0&&(Ln=Zt=!0)}for(let p in B)B[p]=null}function e_(s){let u=Cs(tt-1,0,st-1),f=Cs(nt+1,0,st-1);for(;s[u]==null&&u>0;)u--;for(;s[f]==null&&f<st-1;)f++;return[u,f]}function t_(){if(st>0){let s=I.some(u=>u._focus)&&It!=cn.alpha;s&&(d.globalAlpha=It=cn.alpha),I.forEach((u,f)=>{if(f>0&&u.show&&(Uc(f,!1),Uc(f,!0),u._paths==null)){let p=It;It!=u.alpha&&(d.globalAlpha=It=u.alpha);let _=t==2?[0,n[f][0].length-1]:e_(n[f]);u._paths=u.paths(i,f,_[0],_[1]),It!=p&&(d.globalAlpha=It=p)}}),I.forEach((u,f)=>{if(f>0&&u.show){let p=It;It!=u.alpha&&(d.globalAlpha=It=u.alpha),u._paths!=null&&Dc(f,!1);{let _=u._paths!=null?u._paths.gaps:null,S=u.points.show(i,f,tt,nt,_),T=u.points.filter(i,f,S,_);(S||T)&&(u.points._paths=u.points.paths(i,f,tt,nt,T),Dc(f,!0))}It!=p&&(d.globalAlpha=It=p),ot("drawSeries",f)}}),s&&(d.globalAlpha=It=1)}}function Uc(s,u){let f=u?I[s].points:I[s];f._stroke=f.stroke(i,s),f._fill=f.fill(i,s)}function Dc(s,u){let f=u?I[s].points:I[s],{stroke:p,fill:_,clip:S,flags:T,_stroke:E=f._stroke,_fill:O=f._fill,_width:R=f.width}=f._paths;R=Ne(R*be,3);let A=null,L=R%2/2;u&&O==null&&(O=R>0?"#fff":E);let Q=f.pxAlign==1&&L>0;if(Q&&d.translate(L,L),!u){let _e=Tt-R/2,ge=Mt-R/2,ue=wt+R,J=Yt+R;A=new Path2D,A.rect(_e,ge,ue,J)}u?ts(E,R,f.dash,f.cap,O,p,_,T,S):n_(s,E,R,f.dash,f.cap,O,p,_,T,A,S),Q&&d.translate(-L,-L)}function n_(s,u,f,p,_,S,T,E,O,R,A){let L=!1;O!=0&&G.forEach((Q,_e)=>{if(Q.series[0]==s){let ge=I[Q.series[1]],ue=n[Q.series[1]],J=(ge._paths||pi).band;Nn(J)&&(J=Q.dir==1?J[0]:J[1]);let H,Ce=null;ge.show&&J&&OS(ue,tt,nt)?(Ce=Q.fill(i,_e)||S,H=ge._paths.clip):J=null,ts(u,f,p,_,Ce,T,E,O,R,A,H,J),L=!0}}),L||ts(u,f,p,_,S,T,E,O,R,A)}const Cc=Vr|Ms;function ts(s,u,f,p,_,S,T,E,O,R,A,L){Pc(s,u,f,p,_),(O||R||L)&&(d.save(),O&&d.clip(O),R&&d.clip(R)),L?(E&Cc)==Cc?(d.clip(L),A&&d.clip(A),eo(_,T),Xi(s,S,u)):E&Ms?(eo(_,T),d.clip(L),Xi(s,S,u)):E&Vr&&(d.save(),d.clip(L),A&&d.clip(A),eo(_,T),d.restore(),Xi(s,S,u)):(eo(_,T),Xi(s,S,u)),(O||R||L)&&d.restore()}function Xi(s,u,f){f>0&&(u instanceof Map?u.forEach((p,_)=>{d.strokeStyle=Qi=_,d.stroke(p)}):u!=null&&s&&d.stroke(u))}function eo(s,u){u instanceof Map?u.forEach((f,p)=>{d.fillStyle=gr=p,d.fill(f)}):u!=null&&s&&d.fill(u)}function r_(s,u,f,p){let _=N[s],S;if(p<=0)S=[0,0];else{let T=_._space=_.space(i,s,u,f,p),E=_._incrs=_.incrs(i,s,u,f,p,T);S=eI(u,f,E,p,T)}return _._found=S}function ns(s,u,f,p,_,S,T,E,O,R){let A=T%2/2;w==1&&d.translate(A,A),Pc(E,T,O,R,E),d.beginPath();let L,Q,_e,ge,ue=_+(p==0||p==3?-S:S);f==0?(Q=_,ge=ue):(L=_,_e=ue);for(let J=0;J<s.length;J++)u[J]!=null&&(f==0?L=_e=s[J]:Q=ge=s[J],d.moveTo(L,Q),d.lineTo(_e,ge));d.stroke(),w==1&&d.translate(-A,-A)}function i_(s){let u=!0;return N.forEach((f,p)=>{if(!f.show)return;let _=j[f.scale];if(_.min==null){f._show&&(u=!1,f._show=!1,vr(!1));return}else f._show||(u=!1,f._show=!0,vr(!1));let S=f.side,T=S%2,{min:E,max:O}=_,[R,A]=r_(p,E,O,T==0?re:Z);if(A==0)return;let L=_.distr==2,Q=f._splits=f.splits(i,p,E,O,R,A,L),_e=_.distr==2?Q.map(H=>Qt[H]):Q,ge=_.distr==2?Qt[Q[1]]-Qt[Q[0]]:R,ue=f._values=f.values(i,f.filter(i,_e,p,A,ge),p,A,ge);f._rotate=S==2?f.rotate(i,ue,p,A):0;let J=f._size;f._size=Vt(f.size(i,ue,p,s)),J!=null&&f._size!=J&&(u=!1)}),u}function o_(s){let u=!0;return Nc.forEach((f,p)=>{let _=f(i,p,qn,s);_!=wn[p]&&(u=!1),wn[p]=_}),u}function a_(){for(let s=0;s<N.length;s++){let u=N[s];if(!u.show||!u._show)continue;let f=u.side,p=f%2,_,S,T=u.stroke(i,s),E=f==0||f==3?-1:1,[O,R]=u._found;if(u.label!=null){let _t=u.labelGap*E,Pt=Ye((u._lpos+_t)*be);Ec(u.labelFont[0],T,"center",f==2?ai:xd),d.save(),p==1?(_=S=0,d.translate(Pt,Ye(Mt+Yt/2)),d.rotate((f==3?-po:po)/2)):(_=Ye(Tt+wt/2),S=Pt);let Bn=Xg(u.label)?u.label(i,s,O,R):u.label;d.fillText(Bn,_,S),d.restore()}if(R==0)continue;let A=j[u.scale],L=p==0?wt:Yt,Q=p==0?Tt:Mt,_e=u._splits,ge=A.distr==2?_e.map(_t=>Qt[_t]):_e,ue=A.distr==2?Qt[_e[1]]-Qt[_e[0]]:O,J=u.ticks,H=u.border,Ce=J.show?J.size:0,qe=Ye(Ce*be),at=Ye((u.alignTo==2?u._size-Ce-u.gap:u.gap)*be),ze=u._rotate*-po/180,He=z(u._pos*be),Nt=(qe+at)*E,vt=He+Nt;S=p==0?vt:0,_=p==1?vt:0;let Ft=u.font[0],Xt=u.align==1?xr:u.align==2?ms:ze>0?xr:ze<0?ms:p==0?"center":f==3?ms:xr,mn=ze||p==1?"middle":f==2?ai:xd;Ec(Ft,T,Xt,mn);let jt=u.font[1]*u.lineGap,qt=_e.map(_t=>z(l(_t,A,L,Q))),en=u._values;for(let _t=0;_t<en.length;_t++){let Pt=en[_t];if(Pt!=null){p==0?_=qt[_t]:S=qt[_t],Pt=""+Pt;let Bn=Pt.indexOf(`
|
|
127
127
|
`)==-1?[Pt]:Pt.split(/\n/gm);for(let bt=0;bt<Bn.length;bt++){let td=Bn[bt];ze?(d.save(),d.translate(_,S+bt*jt),d.rotate(ze),d.fillText(td,0,0),d.restore()):d.fillText(td,_,S+bt*jt)}}}J.show&&ns(qt,J.filter(i,ge,s,R,ue),p,f,He,qe,Ne(J.width*be,3),J.stroke(i,s),J.dash,J.cap);let pn=u.grid;pn.show&&ns(qt,pn.filter(i,ge,s,R,ue),p,p==0?2:1,p==0?Mt:Tt,p==0?Yt:wt,Ne(pn.width*be,3),pn.stroke(i,s),pn.dash,pn.cap),H.show&&ns([He],[1],p==0?1:0,p==0?1:2,p==1?Mt:Tt,p==1?Yt:wt,Ne(H.width*be,3),H.stroke(i,s),H.dash,H.cap)}ot("drawAxes")}function vr(s){I.forEach((u,f)=>{f>0&&(u._paths=null,s&&(t==1?(u.min=null,u.max=null):u.facets.forEach(p=>{p.min=null,p.max=null})))})}let to=!1,rs=!1,ti=[];function s_(){rs=!1;for(let s=0;s<ti.length;s++)ot(...ti[s]);ti.length=0}function _r(){to||(JS(Rc),to=!0)}function l_(s,u=!1){to=!0,rs=u,s(i),Rc(),u&&ti.length>0&&queueMicrotask(s_)}i.batch=l_;function Rc(){if(Ha&&(Xv(),Ha=!1),dr&&(Bv(),dr=!1),Gi){if(Re(b,xr,je),Re(b,ai,Ge),Re(b,ui,re),Re(b,ci,Z),Re(v,xr,je),Re(v,ai,Ge),Re(v,ui,re),Re(v,ci,Z),Re(g,ui,_n),Re(g,ci,An),h.width=Ye(_n*be),h.height=Ye(An*be),N.forEach(({_el:s,_show:u,_size:f,_pos:p,side:_})=>{if(s!=null)if(u){let S=_===3||_===0?f:0,T=_%2==1;Re(s,T?"left":"top",p-S),Re(s,T?"width":"height",f),Re(s,T?"top":"left",T?Ge:je),Re(s,T?"height":"width",T?Z:re),Us(s,Yn)}else Et(s,Yn)}),Qi=gr=Ja=Ga=Ka=Ya=Qa=Xa=Wa=null,It=1,ii(!0),je!=cr||Ge!=Mn||re!=un||Z!=Zn){vr(!1);let s=re/un,u=Z/Zn;if(ht&&!Ln&&q.left>=0){q.left*=s,q.top*=u,br&&hn(br,Ye(q.left),0,re,Z),yr&&hn(yr,0,Ye(q.top),re,Z);for(let f=0;f<Lt.length;f++){let p=Lt[f];p!=null&&(pr[f]*=s,hr[f]*=u,hn(p,Vt(pr[f]),Vt(hr[f]),re,Z))}}if(De.show&&!Ki&&De.left>=0&&De.width>0){De.left*=s,De.width*=s,De.top*=u,De.height*=u;for(let f in us)Re(Sr,f,De[f])}cr=je,Mn=Ge,un=re,Zn=Z}ot("setSize"),Gi=!1}_n>0&&An>0&&(d.clearRect(0,0,h.width,h.height),ot("drawClear"),K.forEach(s=>s()),ot("draw")),De.show&&Ki&&(no(De),Ki=!1),ht&&Ln&&(Vn(null,!0,!1),Ln=!1),le.show&&le.live&&Zt&&(ss(),Zt=!1),c||(c=!0,i.status=1,ot("ready")),ei=!1,to=!1}i.redraw=(s,u)=>{dr=u||!1,s!==!1?xn(M,C.min,C.max):_r()};function is(s,u){let f=j[s];if(f.from==null){if(st==0){let p=f.range(i,u.min,u.max,s);u.min=p[0],u.max=p[1]}if(u.min>u.max){let p=u.min;u.min=u.max,u.max=p}if(st>1&&u.min!=null&&u.max!=null&&u.max-u.min<1e-16)return;s==M&&f.distr==2&&st>0&&(u.min=nn(u.min,n[0]),u.max=nn(u.max,n[0]),u.min==u.max&&u.max++),B[s]=u,Ha=!0,_r()}}i.setScale=is;let os,as,br,yr,Ac,Mc,$r,kr,Zc,Lc,Ue,Ze,In=!1;const lt=q.drag;let rt=lt.x,it=lt.y;ht&&(q.x&&(os=Ht(vS,v)),q.y&&(as=Ht(_S,v)),C.ori==0?(br=os,yr=as):(br=as,yr=os),Ue=q.left,Ze=q.top);const De=i.select=Je({show:!0,over:!0,left:0,width:0,top:0,height:0},e.select),Sr=De.show?Ht(gS,De.over?v:b):null;function no(s,u){if(De.show){for(let f in s)De[f]=s[f],f in us&&Re(Sr,f,s[f]);u!==!1&&ot("setSelect")}}i.setSelect=no;function u_(s){if(I[s].show)We&&Us(Le[s],Yn);else if(We&&Et(Le[s],Yn),ht){let f=mr?Lt[0]:Lt[s];f!=null&&hn(f,-10,-10,re,Z)}}function xn(s,u,f){is(s,{min:u,max:f})}function dn(s,u,f,p){u.focus!=null&&p_(s),u.show!=null&&I.forEach((_,S)=>{S>0&&(s==S||s==null)&&(_.show=u.show,u_(S),t==2?(xn(_.facets[0].scale,null,null),xn(_.facets[1].scale,null,null)):xn(_.scale,null,null),_r())}),f!==!1&&ot("setSeries",s,u),p&&oi("setSeries",i,s,u)}i.setSeries=dn;function c_(s,u){Je(G[s],u)}function d_(s,u){s.fill=de(s.fill||null),s.dir=ve(s.dir,-1),u=u??G.length,G.splice(u,0,s)}function f_(s){s==null?G.length=0:G.splice(s,1)}i.addBand=d_,i.setBand=c_,i.delBand=f_;function m_(s,u){I[s].alpha=u,ht&&Lt[s]!=null&&(Lt[s].style.opacity=u),We&&Le[s]&&(Le[s].style.opacity=u)}let bn,zn,Hn;const wr={focus:!0};function p_(s){if(s!=Hn){let u=s==null,f=cn.alpha!=1;I.forEach((p,_)=>{if(t==1||_>0){let S=u||_==0||_==s;p._focus=u?null:S,f&&m_(_,S?1:cn.alpha)}}),Hn=s,f&&_r()}}We&&fr&>(jd,$e,s=>{q._lock||(Fn(s),Hn!=null&&dn(null,wr,!0,Be.setSeries))});function fn(s,u,f){let p=j[u];f&&(s=s/be-(p.ori==1?Ge:je));let _=re;p.ori==1&&(_=Z,s=_-s),p.dir==-1&&(s=_-s);let S=p._min,T=p._max,E=s/_,O=S+(T-S)*E,R=p.distr;return R==3?Fr(10,O):R==4?DS(O,p.asinh):R==100?p.bwd(O):O}function h_(s,u){let f=fn(s,M,u);return nn(f,n[0],tt,nt)}i.valToIdx=s=>nn(s,n[0]),i.posToIdx=h_,i.posToVal=fn,i.valToPos=(s,u,f)=>j[u].ori==0?o(s,j[u],f?wt:re,f?Tt:0):a(s,j[u],f?Yt:Z,f?Mt:0),i.setCursor=(s,u,f)=>{Ue=s.left,Ze=s.top,Vn(null,u,f)};function Fc(s,u){Re(Sr,xr,De.left=s),Re(Sr,ui,De.width=u)}function qc(s,u){Re(Sr,ai,De.top=s),Re(Sr,ci,De.height=u)}let ni=C.ori==0?Fc:qc,ri=C.ori==1?Fc:qc;function g_(){if(We&&le.live)for(let s=t==2?1:0;s<I.length;s++){if(s==0&&At)continue;let u=le.values[s],f=0;for(let p in u)ln[s][f++].firstChild.nodeValue=u[p]}}function ss(s,u){if(s!=null&&(s.idxs?s.idxs.forEach((f,p)=>{xe[p]=f}):MS(s.idx)||xe.fill(s.idx),le.idx=xe[0]),We&&le.live){for(let f=0;f<I.length;f++)(f>0||t==1&&!At)&&v_(f,xe[f]);g_()}Zt=!1,u!==!1&&ot("setLegend")}i.setLegend=ss;function v_(s,u){let f=I[s],p=s==0&&oe==2?Qt:n[s],_;At?_=f.values(i,s,u)??Sn:(_=f.value(i,u==null?null:p[u],s,u),_=_==null?Sn:{_}),le.values[s]=_}function Vn(s,u,f){Zc=Ue,Lc=Ze,[Ue,Ze]=q.move(i,Ue,Ze),q.left=Ue,q.top=Ze,ht&&(br&&hn(br,Ye(Ue),0,re,Z),yr&&hn(yr,0,Ye(Ze),re,Z));let p,_=tt>nt;bn=Te,zn=null;let S=C.ori==0?re:Z,T=C.ori==1?re:Z;if(Ue<0||st==0||_){p=q.idx=null;for(let E=0;E<I.length;E++){let O=Lt[E];O!=null&&hn(O,-10,-10,re,Z)}fr&&dn(null,wr,!0,s==null&&Be.setSeries),le.live&&(xe.fill(p),Zt=!0)}else{let E,O,R;t==1&&(E=C.ori==0?Ue:Ze,O=fn(E,M),p=q.idx=nn(O,n[0],tt,nt),R=F(n[0][p],C,S,0));let A=-10,L=-10,Q=0,_e=0,ge=!0,ue="",J="";for(let H=t==2?1:0;H<I.length;H++){let Ce=I[H],qe=xe[H],at=qe==null?null:t==1?n[H][qe]:n[H][1][qe],ze=q.dataIdx(i,H,p,O),He=ze==null?null:t==1?n[H][ze]:n[H][1][ze];if(Zt=Zt||He!=at||ze!=qe,xe[H]=ze,H>0&&Ce.show){let Nt=ze==null?-10:ze==p?R:F(t==1?n[0][ze]:n[H][0][ze],C,S,0),vt=He==null?-10:Y(He,t==1?j[Ce.scale]:j[Ce.facets[1].scale],T,0);if(fr&&He!=null){let Ft=C.ori==1?Ue:Ze,Xt=Qe(cn.dist(i,H,ze,vt,Ft));if(Xt<bn){let mn=cn.bias;if(mn!=0){let jt=fn(Ft,Ce.scale),qt=He>=0?1:-1,en=jt>=0?1:-1;en==qt&&(en==1?mn==1?He>=jt:He<=jt:mn==1?He<=jt:He>=jt)&&(bn=Xt,zn=H)}else bn=Xt,zn=H}}if(Zt||mr){let Ft,Xt;C.ori==0?(Ft=Nt,Xt=vt):(Ft=vt,Xt=Nt);let mn,jt,qt,en,pn,_t,Pt=!0,Bn=mt.bbox;if(Bn!=null){Pt=!1;let bt=Bn(i,H);qt=bt.left,en=bt.top,mn=bt.width,jt=bt.height}else qt=Ft,en=Xt,mn=jt=mt.size(i,H);if(_t=mt.fill(i,H),pn=mt.stroke(i,H),mr)H==zn&&bn<=cn.prox&&(A=qt,L=en,Q=mn,_e=jt,ge=Pt,ue=_t,J=pn);else{let bt=Lt[H];bt!=null&&(pr[H]=qt,hr[H]=en,Rd(bt,mn,jt,Pt),Dd(bt,_t,pn),hn(bt,Vt(qt),Vt(en),re,Z))}}}}if(mr){let H=cn.prox,Ce=Hn==null?bn<=H:bn>H||zn!=Hn;if(Zt||Ce){let qe=Lt[0];qe!=null&&(pr[0]=A,hr[0]=L,Rd(qe,Q,_e,ge),Dd(qe,ue,J),hn(qe,Vt(A),Vt(L),re,Z))}}}if(De.show&&In)if(s!=null){let[E,O]=Be.scales,[R,A]=Be.match,[L,Q]=s.cursor.sync.scales,_e=s.cursor.drag;if(rt=_e._x,it=_e._y,rt||it){let{left:ge,top:ue,width:J,height:H}=s.select,Ce=s.scales[L].ori,qe=s.posToVal,at,ze,He,Nt,vt,Ft=E!=null&&R(E,L),Xt=O!=null&&A(O,Q);Ft&&rt?(Ce==0?(at=ge,ze=J):(at=ue,ze=H),He=j[E],Nt=F(qe(at,L),He,S,0),vt=F(qe(at+ze,L),He,S,0),ni(on(Nt,vt),Qe(vt-Nt))):ni(0,S),Xt&&it?(Ce==1?(at=ge,ze=J):(at=ue,ze=H),He=j[O],Nt=Y(qe(at,Q),He,T,0),vt=Y(qe(at+ze,Q),He,T,0),ri(on(Nt,vt),Qe(vt-Nt))):ri(0,T)}else cs()}else{let E=Qe(Zc-Ac),O=Qe(Lc-Mc);if(C.ori==1){let Q=E;E=O,O=Q}rt=lt.x&&E>=lt.dist,it=lt.y&&O>=lt.dist;let R=lt.uni;R!=null?rt&&it&&(rt=E>=R,it=O>=R,!rt&&!it&&(O>E?it=!0:rt=!0)):lt.x&<.y&&(rt||it)&&(rt=it=!0);let A,L;rt&&(C.ori==0?(A=$r,L=Ue):(A=kr,L=Ze),ni(on(A,L),Qe(L-A)),it||ri(0,T)),it&&(C.ori==1?(A=$r,L=Ue):(A=kr,L=Ze),ri(on(A,L),Qe(L-A)),rt||ni(0,S)),!rt&&!it&&(ni(0,0),ri(0,0))}if(lt._x=rt,lt._y=it,s==null){if(f){if(ed!=null){let[E,O]=Be.scales;Be.values[0]=E!=null?fn(C.ori==0?Ue:Ze,E):null,Be.values[1]=O!=null?fn(C.ori==1?Ue:Ze,O):null}oi(ps,i,Ue,Ze,re,Z,p)}if(fr){let E=f&&Be.setSeries,O=cn.prox;Hn==null?bn<=O&&dn(zn,wr,!0,E):bn>O?dn(null,wr,!0,E):zn!=Hn&&dn(zn,wr,!0,E)}}Zt&&(le.idx=p,ss()),u!==!1&&ot("setCursor")}let Tn=null;Object.defineProperty(i,"rect",{get(){return Tn==null&&ii(!1),Tn}});function ii(s=!1){s?Tn=null:(Tn=v.getBoundingClientRect(),ot("syncRect",Tn))}function Hc(s,u,f,p,_,S,T){q._lock||In&&s!=null&&s.movementX==0&&s.movementY==0||(ls(s,u,f,p,_,S,T,!1,s!=null),s!=null?Vn(null,!0,!0):Vn(u,!0,!1))}function ls(s,u,f,p,_,S,T,E,O){if(Tn==null&&ii(!1),Fn(s),s!=null)f=s.clientX-Tn.left,p=s.clientY-Tn.top;else{if(f<0||p<0){Ue=-10,Ze=-10;return}let[R,A]=Be.scales,L=u.cursor.sync,[Q,_e]=L.values,[ge,ue]=L.scales,[J,H]=Be.match,Ce=u.axes[0].side%2==1,qe=C.ori==0?re:Z,at=C.ori==1?re:Z,ze=Ce?S:_,He=Ce?_:S,Nt=Ce?p:f,vt=Ce?f:p;if(ge!=null?f=J(R,ge)?l(Q,j[R],qe,0):-10:f=qe*(Nt/ze),ue!=null?p=H(A,ue)?l(_e,j[A],at,0):-10:p=at*(vt/He),C.ori==1){let Ft=f;f=p,p=Ft}}O&&(u==null||u.cursor.event.type==ps)&&((f<=1||f>=re-1)&&(f=Gn(f,re)),(p<=1||p>=Z-1)&&(p=Gn(p,Z))),E?(Ac=f,Mc=p,[$r,kr]=q.move(i,f,p)):(Ue=f,Ze=p)}const us={width:0,height:0,left:0,top:0};function cs(){no(us,!1)}let Vc,Bc,Jc,Wc;function Gc(s,u,f,p,_,S,T){In=!0,rt=it=lt._x=lt._y=!1,ls(s,u,f,p,_,S,T,!0,!1),s!=null&&(gt(hs,Es,Kc,!1),oi(Td,i,$r,kr,re,Z,null));let{left:E,top:O,width:R,height:A}=De;Vc=E,Bc=O,Jc=R,Wc=A}function Kc(s,u,f,p,_,S,T){In=lt._x=lt._y=!1,ls(s,u,f,p,_,S,T,!1,!0);let{left:E,top:O,width:R,height:A}=De,L=R>0||A>0,Q=Vc!=E||Bc!=O||Jc!=R||Wc!=A;if(L&&Q&&no(De),lt.setScale&&L&&Q){let _e=E,ge=R,ue=O,J=A;if(C.ori==1&&(_e=O,ge=A,ue=E,J=R),rt&&xn(M,fn(_e,M),fn(_e+ge,M)),it)for(let H in j){let Ce=j[H];H!=M&&Ce.from==null&&Ce.min!=Te&&xn(H,fn(ue+J,H),fn(ue,H))}cs()}else q.lock&&(q._lock=!q._lock,Vn(u,!0,s!=null));s!=null&&(ur(hs,Es),oi(hs,i,Ue,Ze,re,Z,null))}function __(s,u,f,p,_,S,T){if(q._lock)return;Fn(s);let E=In;if(In){let O=!0,R=!0,A=10,L,Q;C.ori==0?(L=rt,Q=it):(L=it,Q=rt),L&&Q&&(O=Ue<=A||Ue>=re-A,R=Ze<=A||Ze>=Z-A),L&&O&&(Ue=Ue<$r?0:re),Q&&R&&(Ze=Ze<kr?0:Z),Vn(null,!0,!0),In=!1}Ue=-10,Ze=-10,xe.fill(null),Vn(null,!0,!0),E&&(In=E)}function Yc(s,u,f,p,_,S,T){q._lock||(Fn(s),Ba(),cs(),s!=null&&oi(Pd,i,Ue,Ze,re,Z,null))}function Qc(){N.forEach(tI),Va(i.width,i.height,!0)}Qn(So,Pr,Qc);const Ir={};Ir.mousedown=Gc,Ir.mousemove=Hc,Ir.mouseup=Kc,Ir.dblclick=Yc,Ir.setSeries=(s,u,f,p)=>{let _=Be.match[2];f=_(i,u,f),f!=-1&&dn(f,p,!0,!1)},ht&&(gt(Td,v,Gc),gt(ps,v,Hc),gt(Nd,v,s=>{Fn(s),ii(!1)}),gt(jd,v,__),gt(Pd,v,Yc),Zs.add(i),i.syncRect=ii);const ro=i.hooks=e.hooks||{};function ot(s,u,f){rs?ti.push([s,u,f]):s in ro&&ro[s].forEach(p=>{p.call(null,i,u,f)})}(e.plugins||[]).forEach(s=>{for(let u in s.hooks)ro[u]=(ro[u]||[]).concat(s.hooks[u])});const Xc=(s,u,f)=>f,Be=Je({key:null,setSeries:!1,filters:{pub:Fd,sub:Fd},scales:[M,I[1]?I[1].scale:null],match:[qd,qd,Xc],values:[null,null]},q.sync);Be.match.length==2&&Be.match.push(Xc),q.sync=Be;const ed=Be.key,ds=Sv(ed);function oi(s,u,f,p,_,S,T){Be.filters.pub(s,u,f,p,_,S,T)&&ds.pub(s,u,f,p,_,S,T)}ds.sub(i);function b_(s,u,f,p,_,S,T){Be.filters.sub(s,u,f,p,_,S,T)&&Ir[s](null,u,f,p,_,S,T)}i.pub=b_;function y_(){ds.unsub(i),Zs.delete(i),Rn.clear(),Ds(So,Pr,Qc),m.remove(),$e?.remove(),ot("destroy")}i.destroy=y_;function fs(){ot("init",e,n),jc(n||e.data,!1),B[M]?is(M,B[M]):Ba(),Ki=De.show&&(De.width>0||De.height>0),Ln=Zt=!0,Va(e.width,e.height)}return I.forEach(Tc),N.forEach(Qv),r?r instanceof HTMLElement?(r.appendChild(m),fs()):r(i,fs):fs(),i}ut.assign=Je;ut.fmtNum=hc;ut.rangeNum=wo;ut.rangeLog=Oa;ut.rangeAsinh=mc;ut.orient=ar;ut.pxRatio=be;ut.join=BS;ut.fmtDate=vc,ut.tzDate=rw;ut.sync=Sv;{ut.addGap=Mw,ut.clipGaps=Ca;let e=ut.paths={points:Nv};e.linear=Pv,e.stepped=Fw,e.bars=qw,e.spline=Vw}function Fs(e,n=0){return e<=0?[]:Array.from({length:e},(r,i)=>n+i+1)}function nI(e,n){return e<=0&&n<=0?[]:[...Fs(e,0),...Fs(n,e)]}function Dv(e,n){return n==="failed"||n==="cancelled"||e.kernel_complete===!0?!0:n==="completed"}function Za(e){if(String(e.training_progress_phase??e.progress_phase??"").toLowerCase()==="floop"||String(e.job_type??e._job_type??"").toLowerCase().includes("floop"))return!0;const i=e.run_config;return!!(i&&typeof i=="object"&&String(i.model??"").toLowerCase().includes("floop")||String(e.model??"").toLowerCase().includes("floop"))}function ff(e){return Za(e)?"FLooP step":"Batch sample"}function ys(e,n){return n==="floop"||Za(e)?"QE (FLooP steps)":n==="convergence"?"QE convergence":"QE ordering"}function $s(e,n){const r=n==="floop"||Za(e)?"TE (FLooP steps)":n==="convergence"?"TE convergence":"TE ordering";return rI(r)}function rI(e){return`${e} (panel)`}function iI(e){const n=e.training_curve_source_batches,r=[],i=n&&typeof n.ordering=="number"?n.ordering:null,t=n&&typeof n.convergence=="number"?n.convergence:null,o=Array.isArray(e.ordering_errors)?e.ordering_errors.length:0,a=Array.isArray(e.convergence_errors)?e.convergence_errors.length:0;i!=null&&i>o&&r.push(`${o} of ${i.toLocaleString()} ordering batch samples`),t!=null&&t>a&&r.push(`${a} of ${t.toLocaleString()} convergence batch samples`);const l=e.te_evaluation,c=l?.te_panel_size,m=l?.te_panel_n_train;if(typeof c=="number"&&typeof m=="number"&&m>0){const b=l?.te_panel_stratified===!0?", stratified by mesh":"";r.push(`TE curve uses a fixed panel of ${c.toLocaleString()} of ${m.toLocaleString()} training rows${b}`)}const h=e.panel_topographic_error,d=e.map_topographic_error;return h!=null&&d!=null&&Number.isFinite(Number(h))&&Number.isFinite(Number(d))&&r.push(`Panel TE ${Number(h).toFixed(4)} · Map TE ${Number(d).toFixed(4)} (full training set)`),r.length===0?null:`${i!=null||t!=null?"Displaying uniformly subsampled QE+TE curves (≤1000 points/phase, joint indices): ":""}${r.join("; ")}.`.replace(/: ;/,":")}function ks(e,n){if(n<=0)return[];if(e.length===n)return e;if(e.length===0)return Array(n).fill(null);if(e.length>=n)return e.slice(0,n);const r=n-e.length;return[...Array(r).fill(null),...e]}function oI(e){return!Array.isArray(e)||e.length<2?null:`${e[0]}×${e[1]}`}function aI(e){return!Array.isArray(e)||e.length===0?null:e.length>=2?`${e[0]}+${e[1]}`:String(e[0])}function sI(e){return!Array.isArray(e)||e.length===0?null:e.map(String).join("→")}function lI(e){if(!Array.isArray(e)||e.length===0)return null;const n=e.map(String);return n.length<=6?n.join(", "):`${n.length} cols: ${n.slice(0,5).join(", ")}, …`}function uI(e){const n=e.run_config;return n&&typeof n=="object"?{...e,...n}:e}function cI(e){const n=uI(e),r=[];n.label&&r.push(["Label",String(n.label)]);const i=n.dataset_name??e.dataset_name,t=n.dataset_id??e.dataset_id;if(i){const m=t?` (${String(t).slice(0,8)}…)`:"";r.push(["Dataset",`${String(i)}${m}`])}else t&&r.push(["Dataset id",String(t)]);const o=lI(n.feature_columns??n.columns);o&&r.push(["Features",o]),n.batch_size!=null&&r.push(["Batch",String(n.batch_size)]),n.preset&&r.push(["Preset",String(n.preset)]);const a=oI(n.grid);a&&r.push(["Grid",a]);const l=aI(n.epochs);l&&r.push(["Epochs",l]),n.reference_mesh&&r.push(["Reference",String(n.reference_mesh)]);const c=sI(n.mesh_order);return c&&r.push(["Mesh order",c]),n.stratify_scale!=null&&r.push(["Stratify",String(n.stratify_scale)]),n.emd_method&&r.push(["EMD",String(n.emd_method)]),n.backend&&r.push(["Backend",String(n.backend)]),e.dataset_rows!=null&&r.push(["Rows",Number(e.dataset_rows).toLocaleString()]),e.attempt!=null&&Number(e.attempt)>1&&r.push(["Attempt",String(e.attempt)]),r}function Cv(e){return e==="completed"||e==="failed"||e==="cancelled"}function qs(e){const n=String(e.status??"");if(!Cv(n))return!0;if(n!=="completed"||e.finalize_failed===!0)return!1;const r=e.finalize_job_id!=null&&String(e.finalize_job_id)!==""?String(e.finalize_job_id):null,i=e.finalize_status!=null&&String(e.finalize_status)!==""?String(e.finalize_status):null;return r!=null&&i!=="completed"}function La(e){const n=String(e.status??"");return n!=="completed"?Cv(n):(e.finalize_job_id!=null&&String(e.finalize_job_id)!==""?String(e.finalize_job_id):null)?String(e.finalize_status??"")==="completed":!0}const Pn=new uc({name:"Mesh Training Monitor",version:"1.0.0"},{},{autoResize:!0});let mf=!1,pf=!1;const dI=document.getElementById("progress-fill"),fI=document.getElementById("progress-pct"),Hs=document.getElementById("elapsed"),mI=document.getElementById("phase"),co=document.getElementById("eta"),Vs=document.getElementById("job-id"),yt=document.getElementById("status-badge"),hf=document.getElementById("params"),Ot=document.getElementById("advisory-banner");document.getElementById("curve");const Ji=document.getElementById("chart-target"),Xn=document.getElementById("curve-fallback"),gf=document.getElementById("chart-legend"),pI=document.getElementById("metric-scalars"),Er=document.getElementById("cancel-btn"),rn=document.getElementById("open-results-btn"),hi=document.getElementById("copy-monitor-url"),vf=document.getElementById("open-standalone"),Ss=document.getElementById("hitgrid-container"),fo=document.getElementById("hitgrid-canvas"),hI=document.getElementById("hitgrid-meta"),_f=document.getElementById("fingerprint-container"),Rv=document.getElementById("fingerprint-chart-target"),gI=document.getElementById("fingerprint-legend"),vI=document.getElementById("fingerprint-meta"),_I=document.getElementById("fingerprint-fallback"),Or=document.getElementById("copy-results-url"),bf=document.getElementById("finalize-container"),bI=document.getElementById("finalize-job-id"),yI=document.getElementById("finalize-progress-fill"),$I=document.getElementById("finalize-progress-pct"),kI=document.getElementById("finalize-phase"),Bs=5e3,ws=2e3;let Fe="",Is=null,gi=null,vi=null,xs=!1,yf=!1,wc={},En=null,Ur=null;function Fa(e){return`/viz/barmesh-results-explorer?mode=standalone&job_id=${encodeURIComponent(e)}`}function qa(e){const n=e.relatedUrls;if(n?.resultsExplorer)return n.resultsExplorer;if(kn&&Fe)return`${window.location.origin}/viz/barmesh-results-explorer?mode=standalone&job_id=${encodeURIComponent(Fe)}`}function Av(e){const n=String(e.id??e.job_id??Fe);if(!n||!rn)return;rn.style.display="inline-flex";const r=String(e.status??"")==="completed"&&La(e),i=qa(e);rn.href=i??Fa(n),i&&(Or.style.display="inline-block",Or.dataset.url=i),r?(rn.classList.remove("nav-btn-disabled"),rn.title=kn?"Browse figures for this job":"Copy results explorer URL (MCP Apps block nested navigation)"):(rn.classList.add("nav-btn-disabled"),rn.title="Available when training and finalize (if any) complete")}async function Ic(e,n,r){try{await navigator.clipboard.writeText(e),n.textContent="Copied!",setTimeout(()=>{n.textContent=r},1500)}catch{window.prompt("Copy URL:",e)}}async function SI(e){const n=String(e.id??e.job_id??Fe);if(!n)return;const r=qa(e),i=Fa(n);if(kn){window.open(r??i,"_blank","noopener,noreferrer");return}r&&(await Ic(r,Or,"Copy results explorer link"),rn.textContent="Link copied",setTimeout(()=>{rn.textContent="Open results explorer"},1500));try{await Pn.callServerTool({name:"barmesh_results_explorer",arguments:{job_id:n}})}catch{}}async function wI(e){if(!yf&&!(String(e.status??"")!=="completed"||!La(e))&&(yf=!0,Av(e),kn)){const n=String(e.id??e.job_id??Fe);if(!n)return;window.open(qa(e)??Fa(n),"_blank","noopener,noreferrer")}}function fi(e){if(e<60)return`${e}s`;const n=Math.floor(e/60),r=e%60;return n<60?`${n}m ${r}s`:`${Math.floor(n/60)}h ${n%60}m`}function II(e){if(gi)return;Is=e;const n=()=>{if(Is==null)return;const r=Math.max(0,Math.round((Date.now()-Is)/1e3));Hs.textContent=fi(r)};n(),gi=setInterval(n,1e3)}function Nr(){gi&&(clearInterval(gi),gi=null)}function xI(e,n,r){const i=Dv(e,n);i&&Nr();const t=e.training_elapsed_sec!=null?Number(e.training_elapsed_sec):e.kernel_elapsed_sec!=null?Number(e.kernel_elapsed_sec):null,o=e.wall_elapsed_sec!=null?Number(e.wall_elapsed_sec):null;if(t!=null&&t>=0)Hs.textContent=i?`Training ${fi(Math.round(t))}`:fi(Math.round(t));else if(!i&&e.started_at&&typeof e.started_at=="string"){const l=Date.parse(e.started_at);Number.isNaN(l)||II(l)}else e.training_duration_seconds&&(Hs.textContent=`${e.training_duration_seconds}s`);if(i){if(r&&o!=null&&o>=0){const l=t!=null?Math.round(t):null;co.textContent=l==null||Math.abs(Math.round(o)-l)>=2?`Wall ${fi(Math.round(o))}`:""}else co.textContent="";return}const a=e.training_eta_sec!=null?Number(e.training_eta_sec):null;a!=null&&a>0?co.textContent=`ETA ~${fi(Math.round(a))}`:co.textContent=""}function xo(){const e=Ji.clientWidth;if(e>0)return Math.max(e,200);const n=Pn.getHostContext?.()?.containerDimensions,r=n?.width??n?.maxWidth;return Math.max(typeof r=="number"?r:360,200)}function Ut(e){return Array.isArray(e)?e.map(n=>Number(n)).filter(n=>Number.isFinite(n)):[]}function Js(e){return Ut(e.ordering_errors).length>0||Ut(e.convergence_errors).length>0||Ut(e.ordering_topographic_errors).length>0||Ut(e.convergence_topographic_errors).length>0}function mo(e){return Array(e).fill(null)}function Mv(){En&&(En.destroy(),En=null),Ji.innerHTML=""}function $f(){Ur&&(Ur.destroy(),Ur=null),Rv.innerHTML=""}function Zv(e,n){e.innerHTML=n.map(r=>`<span class="legend-item"><span class="${r.dash&&r.dash.length>0?"legend-swatch legend-swatch-dashed":"legend-swatch legend-swatch-solid"}" style="border-top-color:${r.stroke}"></span>${r.label}</span>`).join("")}function kf(e,n,r="Batch sample"){if(Mv(),e.length<2)return;Xn.style.display="none";const i=getComputedStyle(document.documentElement).getPropertyValue("--accent").trim()||"#4f46e5",t=getComputedStyle(document.documentElement).getPropertyValue("--coral").trim()||"#f97316",o=getComputedStyle(document.documentElement).getPropertyValue("--text2").trim()||"#666",a=getComputedStyle(document.documentElement).getPropertyValue("--border").trim()||"#e0e0e0",l=n.map(d=>({...d,stroke:d.stroke==="accent"?i:d.stroke==="coral"?t:d.stroke})),c={width:xo(),height:160,cursor:{show:!0},select:{show:!1,left:0,top:0,width:0,height:0},scales:{x:{time:!1},y:{auto:!0},y2:{auto:!0}},axes:[{stroke:o,grid:{stroke:a,width:1},font:"11px -apple-system, BlinkMacSystemFont, sans-serif",label:r,labelFont:"11px -apple-system, BlinkMacSystemFont, sans-serif",size:32},{scale:"y",stroke:o,grid:{stroke:a,width:1},font:"11px -apple-system, BlinkMacSystemFont, sans-serif",label:"QE",labelFont:"11px -apple-system, BlinkMacSystemFont, sans-serif",size:48},{scale:"y2",side:1,stroke:o,grid:{show:!1},font:"11px -apple-system, BlinkMacSystemFont, sans-serif",label:"TE",labelFont:"11px -apple-system, BlinkMacSystemFont, sans-serif",size:48}],series:[{},...l.map(d=>({label:d.label,scale:d.scale,stroke:d.stroke,width:d.scale==="y"?2:1.5,dash:d.dash,spanGaps:!1}))]},m=[e,...l.map(d=>d.values)];En=new ut(c,m,Ji),Zv(gf,l);const h=iI(Lv);h&&gf.insertAdjacentHTML("beforeend",`<div class="curve-source-note" style="margin-top:6px;font-size:11px;color:var(--text2);">${h}</div>`)}let Lv={};function zI(e,n){Dv(e,n);const r=e;Lv=r;const i=Ut(r.ordering_errors),t=Ut(r.convergence_errors),o=Ut(r.ordering_topographic_errors),a=Ut(r.convergence_topographic_errors);if(i.length===0&&t.length===0&&o.length===0&&a.length===0)return!1;const l=Za(r),c=i.length,m=t.length,h=l?Math.max(c,o.length,1):Math.max(c+m,1),d=l?Fs(h):nI(c,m);if(d.length<2)return!1;if(l){const U=i,I=ks(o,h),N=[{label:ys(r,"floop"),values:U,scale:"y",stroke:"accent"}];return o.length>0&&N.push({label:$s(r,"floop"),values:I,scale:"y2",stroke:"accent",dash:[4,4]}),kf(d,N,ff(r)),!0}const g=[...i,...mo(m)],b=[...mo(c),...t],v=[...ks(o,c),...mo(m)],w=[...mo(c),...ks(a,m)],z=[];return c>0&&z.push({label:ys(r,"ordering"),values:g,scale:"y",stroke:"accent"}),m>0&&z.push({label:ys(r,"convergence"),values:b,scale:"y",stroke:"coral"}),o.length>0&&z.push({label:$s(r,"ordering"),values:v,scale:"y2",stroke:"accent",dash:[4,4]}),a.length>0&&z.push({label:$s(r,"convergence"),values:w,scale:"y2",stroke:"coral",dash:[4,4]}),kf(d,z,ff(r)),!0}function TI(e){const n=Ut(e.hit_grid),r=Ut(e.hit_grid_dims);if(n.length===0||r.length<2){Ss.style.display="none";return}const i=Math.max(1,Math.round(r[0])),t=Math.max(1,Math.round(r[1]));if(i*t!==n.length){Ss.style.display="none";return}Ss.style.display="block",fo.width=i,fo.height=t,fo.style.height=`${Math.min(220,t*8)}px`;const o=fo.getContext("2d");if(!o)return;const a=n.reduce((w,z)=>z>w?z:w,0)||1,l=getComputedStyle(document.documentElement).getPropertyValue("--accent").trim()||"#4f46e5",c=/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(l.replace("#","")),m=c?parseInt(c[1],16):79,h=c?parseInt(c[2],16):70,d=c?parseInt(c[3],16):229,g=o.createImageData(i,t);let b=0;for(let w=0;w<n.length;w++){const z=n[w]/a;n[w]>0&&b++;const U=w%i,N=(Math.floor(w/i)*i+U)*4;g.data[N]=Math.round(245-z*(245-m)),g.data[N+1]=Math.round(245-z*(245-h)),g.data[N+2]=Math.round(245-z*(245-d)),g.data[N+3]=255}o.putImageData(g,0,0);const v=n.reduce((w,z)=>w+z,0);hI.textContent=`${i}×${t} nodes · ${b} occupied (${(b/n.length*100).toFixed(0)}%) · ${v} sampled hits · max ${a}`}function NI(e){const n=Ut(e.fingerprint_skl_epochs),r=Ut(e.fingerprint_skl_mean),i=Ut(e.fingerprint_skl_max);if(n.length<2||r.length<2){_f.style.display="none",$f();return}_f.style.display="block",_I.style.display="none";const t=getComputedStyle(document.documentElement).getPropertyValue("--accent").trim()||"#4f46e5",o=getComputedStyle(document.documentElement).getPropertyValue("--coral").trim()||"#f97316",a=getComputedStyle(document.documentElement).getPropertyValue("--text2").trim()||"#666",l=getComputedStyle(document.documentElement).getPropertyValue("--border").trim()||"#e0e0e0",c=Math.min(n.length,r.length),m=n.slice(0,c),d=[{label:"Mean SKL→ref (panel)",values:r.slice(0,c),stroke:t}];if(i.length>=2){const w=Math.min(c,i.length);d.push({label:"Max SKL→ref (panel)",values:i.slice(0,w),stroke:o,dash:[4,4]})}$f();const g={width:xo(),height:140,cursor:{show:!0},select:{show:!1,left:0,top:0,width:0,height:0},scales:{x:{time:!1},y:{auto:!0}},axes:[{stroke:a,grid:{stroke:l,width:1},font:"11px -apple-system, BlinkMacSystemFont, sans-serif",label:"Epoch",labelFont:"11px -apple-system, BlinkMacSystemFont, sans-serif",size:32},{scale:"y",stroke:a,grid:{stroke:l,width:1},font:"11px -apple-system, BlinkMacSystemFont, sans-serif",label:"ΔKL",labelFont:"11px -apple-system, BlinkMacSystemFont, sans-serif",size:48}],series:[{},...d.map(w=>({label:w.label,stroke:w.stroke,width:w.dash?1.5:2,dash:w.dash,spanGaps:!1}))]},b=[m,...d.map(w=>w.values.slice(0,c))];Ur=new ut(g,b,Rv),Zv(gI,d);const v=e.fingerprint_skl_reference!=null?String(e.fingerprint_skl_reference):"reference";vI.textContent=`Panel volume fingerprints vs ${v} (sampled TE panel, not full-mesh). Declining ΔKL means mesh fingerprints are stabilizing during training.`}function jI(e){const n=e.quantization_error??e.qe,r=e.panel_topographic_error??e.epoch_topographic_error??e.topographic_error,i=e.map_topographic_error,t=[];n!=null&&Number.isFinite(Number(n))&&t.push(`QE ${Number(n).toFixed(4)}`),r!=null&&Number.isFinite(Number(r))&&t.push(`Panel TE ${Number(r).toFixed(4)}`),i!=null&&Number.isFinite(Number(i))&&t.push(`Map TE ${Number(i).toFixed(4)}`),pI.textContent=t.length>0?t.join(" · "):""}function Fv(e){return e==="completed"||e==="failed"||e==="cancelled"}function PI(e){const n=e.standaloneUrl;if(n)return n;if(kn&&Fe)return`${window.location.origin}/viz/barmesh-training-monitor?mode=standalone&job_id=${encodeURIComponent(Fe)}`}function EI(e){const n=e.relatedUrls;if(n?.resultsExplorer)return n.resultsExplorer;if(kn&&Fe)return`${window.location.origin}/viz/barmesh-results-explorer?mode=standalone&job_id=${encodeURIComponent(Fe)}`}function OI(e){const n=PI(e);n&&(hi.style.display="inline-block",hi.dataset.url=n,vf.href=n,vf.style.display="inline-block")}hi.addEventListener("click",async()=>{const e=hi.dataset.url;e&&await Ic(e,hi,"Copy monitor URL")});Or.addEventListener("click",async()=>{const e=Or.dataset.url??qa(wc);e&&await Ic(e,Or,"Copy results explorer link")});rn.addEventListener("click",async e=>{e.preventDefault(),!rn.classList.contains("nav-btn-disabled")&&await SI(wc)});function UI(e,n){if(kn||mf||pf||!La(e))return;const r=String(e.id??e.job_id??Fe);if(!r)return;mf=!0;const i=[`Training job ${r} ${n}.`],t=e.quantization_error??e.qe,o=e.map_topographic_error??e.topographic_error,a=e.panel_topographic_error??e.epoch_topographic_error;t!=null&&Number.isFinite(Number(t))&&i.push(`Final QE: ${Number(t).toFixed(4)}`),a!=null&&Number.isFinite(Number(a))&&i.push(`Final panel TE: ${Number(a).toFixed(4)}`),o!=null&&Number.isFinite(Number(o))&&i.push(`Final map TE: ${Number(o).toFixed(4)}`),e.finalize_failed===!0?i.push(`Finalize failed${e.finalize_failure_stage?` [${String(e.finalize_failure_stage)}]`:""}: ${String(e.finalize_error??"results not uploaded")}. Results may be unavailable until finalize is retried.`):n==="completed"&&(i.push(`Use barmesh_results(action=get, job_id="${r}") for metrics, then barmesh_results_explorer(job_id="${r}") to browse figures.`),i.push(`Results explorer: ${Fa(r)}`)),wI(e),Pn.updateModelContext({content:[{type:"text",text:i.join(`
|
|
128
|
-
`)}]}).catch(()=>{pf=!0})}async function DI(e){const n=String(e.status??"");if(!Fv(n)||Js(e)||xs)return e;const r=String(e.id??e.job_id??Fe);if(!r)return e;xs=!0;try{if(kn){const o=await fetch(`/api/results/${r}/training-log`);if(!o.ok)return e;const a=await o.json();return{...e,...a}}const t=(await Pn.callServerTool({name:"barmesh_training_monitor",arguments:{job_id:r
|
|
128
|
+
`)}]}).catch(()=>{pf=!0})}async function DI(e){const n=String(e.status??"");if(!Fv(n)||Js(e)||xs)return e;const r=String(e.id??e.job_id??Fe);if(!r)return e;xs=!0;try{if(kn){const o=await fetch(`/api/results/${r}/training-log`);if(!o.ok)return e;const a=await o.json();return{...e,...a}}const t=(await Pn.callServerTool({name:"barmesh_training_monitor",arguments:{job_id:r}})).structuredContent;if(t&&typeof t=="object")return{...e,...t}}catch{xs=!1}return e}function zo(){vi&&(clearTimeout(vi),vi=null)}function Ws(e){zo(),vi=setTimeout(()=>{vi=null,CI()},e)}async function CI(){if(Fe)try{const e=await Pn.callServerTool({name:"barmesh_training_monitor",arguments:{job_id:Fe}});await qv(e)}catch{Ws(Bs)}}function qv(e){let n;const r=e.content?.find(o=>o.type==="image");r&&(n=`data:${r.mimeType};base64,${r.data}`);const i=e.structuredContent;if(i&&typeof i=="object"&&i.type==="barmesh-training-monitor"){if(Gs(i,n),String(i.status??"running"),qs(i)){const o=typeof i.refresh_interval_ms=="number"?i.refresh_interval_ms:Bs;Ws(o)}else zo();return}const t=e.content?.find(o=>o.type==="text");if(t?.type==="text"&&t.text)try{const o=JSON.parse(t.text);Gs(o,n),qs(o)?Ws(Bs):zo()}catch{n&&(Xn.style.display="none",Ji.innerHTML=`<img src="${n}" alt="Learning Curve" style="max-width:100%;border-radius:4px;" />`)}}function RI(e){const n=cI(e);if(n.length===0){hf.innerHTML="";return}hf.innerHTML=n.map(([r,i])=>`<div class="param"><span class="param-label">${r}: </span><span class="param-value">${i}</span></div>`).join("")}function AI(e,n,r){if(!n||!r){bf.style.display="none";return}bf.style.display="block",bI.textContent=`(${r.slice(0,8)}…)`;const i=e.finalize_progress!=null?Number(e.finalize_progress)*100:null,t=e.finalize_phase!=null&&String(e.finalize_phase)!==""?String(e.finalize_phase):String(e.finalize_status??"running"),o=i!=null&&Number.isFinite(i)?i:0;yI.style.width=`${o}%`,$I.textContent=`${o.toFixed(1)}%`,kI.textContent=t}async function Gs(e,n){let r=e;Fv(String(e.status??""))&&!Js(e)&&(r=await DI(e)),wc=r,r.id&&(Fe=r.id),r.job_id&&(Fe=r.job_id),Vs.textContent=Fe;let i=r.status??"running";const t=r.finalize_failed===!0,o=r.finalize_job_id!=null&&String(r.finalize_job_id)!==""?String(r.finalize_job_id):null,a=r.finalize_status!=null&&String(r.finalize_status)!==""?String(r.finalize_status):null;if(i==="completed"&&t)yt.textContent="training done · finalize failed",yt.className="status-badge status-failed",Er.style.display="none",Nr(),Ot.style.display="block",Ot.textContent=`Finalize job ${o??"unknown"} failed`+(r.finalize_failure_stage?` [${String(r.finalize_failure_stage)}]`:"")+`: ${String(r.finalize_error??"results not uploaded")}. Poll jobs(status) or retry finalize before results(get).`;else if(i==="completed"&&o&&a!=="completed")yt.textContent="training done · finalizing",yt.className="status-badge status-warning",Nr(),Ot.style.display="block",Ot.textContent="Finalize in progress — see progress below. Wait for finalize before barmesh_results(get).";else if(i==="completed"&&La(r)){yt.textContent="completed",yt.className="status-badge status-completed",Er.style.display="none",Nr(),Ot.style.display="block";const g=EI(r);Ot.innerHTML=g?`Job complete. <a href="${g}" target="_blank" rel="noreferrer">Open results explorer</a> to browse figures.`:`Job complete. Use barmesh_results_explorer(job_id="${Fe}") to browse figures.`}else yt.textContent=i,yt.className=`status-badge status-${i==="completed"?"completed":i==="failed"||i==="cancelled"?"failed":"running"}`,(i==="completed"||i==="failed"||i==="cancelled")&&(Er.style.display="none",Nr());const l=i==="completed"&&t||i==="completed"&&o!=null&&a!=="completed",c=(r.progress??0)*100;dI.style.width=`${c}%`,fI.textContent=`${c.toFixed(1)}%`;const m=r.progress_phase!=null&&String(r.progress_phase)!==""?String(r.progress_phase):i==="running"?"preprocessing (pending)":"—";mI.textContent=m,xI(r,i,l);const h=r.dataset_rows!=null?Number(r.dataset_rows):null,d=i==="running"&&c<5&&(m.startsWith("download")||m.startsWith("preprocessing")||m.includes("pending"));!l&&d&&h!=null&&h>1e6?(Ot.style.display="block",Ot.textContent=`Loading/normalizing ${h.toLocaleString()} rows — progress may stay near 0% until ingest completes.`):!l&&d&&c<1?(Ot.style.display="block",Ot.textContent="Early preprocessing (download/parse/normalize) — epoch counter starts after ingest completes."):l||(Ot.style.display="none"),RI(r),OI(r),AI(r,l,o),Av(r),jI(r),TI(r),NI(r),UI(r,i),Js(r)?zI(r,i):n?(Mv(),Xn.style.display="none",Ji.innerHTML=`<img src="${n}" alt="Learning Curve" style="max-width:100%;border-radius:4px;" />`):En||(Xn.style.display="block",Xn.textContent="Waiting for training data...")}function MI(){const e=new Date().toISOString().replace("T"," ").slice(0,19);yt.textContent=`cancelled at ${e} UTC`,yt.className="status-badge status-failed",Er.style.display="none",Nr(),zo()}const Hv=new URLSearchParams(window.location.search),kn=Hv.get("mode")==="standalone",zs=Hv.get("job_id");if(kn&&zs){Fe=zs,Vs.textContent=zs,Er.addEventListener("click",async()=>{if(Fe)try{(await fetch(`/api/jobs/${Fe}/cancel`,{method:"POST"})).ok?MI():yt.textContent="cancel failed"}catch{yt.textContent="cancel failed"}});const e=5;let n=0;const r=o=>{Ot.style.display="block",Ot.textContent=o},i="The local viz port is assigned per MCP session and changes when the proxy restarts. Re-run barmesh_training_monitor for a fresh URL, or set BARIVIA_VIZ_PORT in your MCP env for a persistent port.",t=async()=>{try{const o=await fetch(`/api/jobs/${Fe}`);if(!o.ok){if(n++,o.status===404){r(`Job ${Fe} was not found via the local viz server (HTTP 404). It may have been deleted, or this link points at a stale session. ${i}`);return}if(n>=e){r(`Could not load job status (HTTP ${o.status}) after ${n} attempts. ${i}`);return}setTimeout(t,ws);return}n=0;const a=await o.json();await Gs(a),qs(a)&&setTimeout(t,ws)}catch{if(n++,n>=e){r(`Cannot reach the local viz server (network error). The MCP proxy may have stopped or restarted. ${i}`);return}setTimeout(t,ws)}};t()}else Er.style.display="none",Pn.ontoolinput=e=>{const n=e?.arguments??{},r=n.job_id!=null?String(n.job_id):"";r&&(Fe=r,Vs.textContent=r),yt.textContent||(yt.textContent="loading",yt.className="status-badge status-running"),En||(Xn.style.display="block",Xn.textContent="Loading training data...")},Pn.ontoolresult=e=>{qv(e)},Pn.connect();window.addEventListener("resize",()=>{En&&En.setSize({width:xo(),height:160}),Ur&&Ur.setSize({width:xo(),height:140})});</script>
|
|
129
129
|
<style rel="stylesheet" crossorigin>.uplot,.uplot *,.uplot *:before,.uplot *:after{box-sizing:border-box}.uplot{font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";line-height:1.5;width:min-content}.u-title{text-align:center;font-size:18px;font-weight:700}.u-wrap{position:relative;-webkit-user-select:none;user-select:none}.u-over,.u-under{position:absolute}.u-under{overflow:hidden}.uplot canvas{display:block;position:relative;width:100%;height:100%}.u-axis{position:absolute}.u-legend{font-size:14px;margin:auto;text-align:center}.u-inline{display:block}.u-inline *{display:inline-block}.u-inline tr{margin-right:16px}.u-legend th{font-weight:600}.u-legend th>*{vertical-align:middle;display:inline-block}.u-legend .u-marker{width:1em;height:1em;margin-right:4px;background-clip:padding-box!important}.u-inline.u-live th:after{content:":";vertical-align:middle}.u-inline:not(.u-live) .u-value{display:none}.u-series>*{padding:4px}.u-series th{cursor:pointer}.u-legend .u-off>*{opacity:.3}.u-select{background:#00000012;position:absolute;pointer-events:none}.u-cursor-x,.u-cursor-y{position:absolute;left:0;top:0;pointer-events:none;will-change:transform}.u-hz .u-cursor-x,.u-vt .u-cursor-y{height:100%;border-right:1px dashed #607D8B}.u-hz .u-cursor-y,.u-vt .u-cursor-x{width:100%;border-bottom:1px dashed #607D8B}.u-cursor-pt{position:absolute;top:0;left:0;border-radius:50%;border:0 solid;pointer-events:none;will-change:transform;background-clip:padding-box!important}.u-axis.u-off,.u-select.u-off,.u-cursor-x.u-off,.u-cursor-y.u-off,.u-cursor-pt.u-off{display:none}</style>
|
|
130
130
|
</head>
|
|
131
131
|
<body>
|