modelpace 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,150 @@
1
+ import fs from 'node:fs';
2
+ import http from 'node:http';
3
+ import { evaluateWindow } from '../core/pacing.mjs';
4
+
5
+ const STYLE = fs.readFileSync(new URL('./dashboard.css', import.meta.url), 'utf8');
6
+ const CLIENT = fs.readFileSync(new URL('./client.js', import.meta.url), 'utf8');
7
+
8
+ const DAY_MS = 86_400_000;
9
+ const day = (ms) => new Date(ms).toISOString().slice(0, 10);
10
+
11
+ function quotaView(snapshot, nowMs) {
12
+ const instances = [];
13
+ const poolMap = new Map();
14
+ for (const instance of Object.values(snapshot?.instances ?? {})) {
15
+ const windows = (instance.windows ?? [])
16
+ .map((win) => evaluateWindow(win, { now: nowMs }))
17
+ .filter((win) => win.valid)
18
+ .map(({ valid, ...win }) => win);
19
+ for (const win of windows) {
20
+ if (!win.pool) continue;
21
+ if (!poolMap.has(win.pool)) poolMap.set(win.pool, []);
22
+ poolMap.get(win.pool).push({ instance: instance.displayName ?? instance.instanceId, window: win });
23
+ }
24
+ instances.push({
25
+ id: instance.instanceId,
26
+ displayName: instance.displayName ?? instance.instanceId,
27
+ driver: instance.driver ?? null,
28
+ plan: instance.plan ?? null,
29
+ status: instance.status ?? 'unknown',
30
+ windows,
31
+ resetCredits: instance.resetCredits ?? null,
32
+ });
33
+ }
34
+ return { instances, pools: [...poolMap].map(([pool, windows]) => ({ pool, windows })) };
35
+ }
36
+
37
+ const decisionView = (decision) =>
38
+ decision
39
+ ? {
40
+ action: decision.action,
41
+ slot: decision.slot,
42
+ task: decision.task,
43
+ tier: decision.tier,
44
+ nextCheckAt: decision.nextCheckAt,
45
+ recommended: decision.recommended
46
+ ? { instanceId: decision.recommended.instanceId, model: decision.recommended.model }
47
+ : null,
48
+ candidates: decision.candidates.map((c) => ({
49
+ candidateId: c.candidateId,
50
+ instanceId: c.instanceId,
51
+ model: c.model,
52
+ eligible: c.eligible,
53
+ quotaState: c.quotaState,
54
+ qualityTier: c.qualityTier,
55
+ speedLongRate: c.speedLongRate ?? null,
56
+ paceScore: c.paceScore ?? null,
57
+ rejectionReasons: c.rejectionReasons ?? [],
58
+ warnings: c.warnings ?? [],
59
+ })),
60
+ }
61
+ : null;
62
+
63
+ const scoresView = (summary) => ({
64
+ minSamples: summary?.minSamples ?? 5,
65
+ cells: (summary?.cells ?? []).map(({ identity, task, n, s, f, passRate, interval90, durationMedianMin, costMedian, costCurrency }) => ({
66
+ identity, task, n, s, f, passRate, interval90, durationMedianMin, costMedian, costCurrency,
67
+ })),
68
+ });
69
+
70
+ /** 把派发决策、用量快照、验收评分与速度排行整理成页面数据(不含原始派发记录)。 */
71
+ export function buildDashboardData({ decision = null, snapshot = null, scoresSummary = null, speedRanking = [], options = {} } = {}) {
72
+ const nowMs = options.now ?? Date.now();
73
+ const days = options.days ?? 30;
74
+ return {
75
+ generatedAt: new Date(nowMs).toISOString(),
76
+ live: options.live === true,
77
+ quota: quotaView(snapshot, nowMs),
78
+ speed: {
79
+ days,
80
+ sinceDay: day(nowMs - days * DAY_MS),
81
+ untilDay: day(nowMs),
82
+ ranking: speedRanking,
83
+ warnings: options.warnings ?? [],
84
+ },
85
+ scores: scoresView(scoresSummary),
86
+ decision: decisionView(decision),
87
+ };
88
+ }
89
+
90
+ const embedJson = (value) =>
91
+ JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
92
+
93
+ /** 输出完全自包含的单文件 HTML:无外部资源,样式与脚本内联。 */
94
+ export function renderDashboardHtml(input = {}) {
95
+ const data = buildDashboardData(input);
96
+ return `<!doctype html>
97
+ <html lang="en">
98
+ <head>
99
+ <meta charset="utf-8">
100
+ <meta name="viewport" content="width=device-width, initial-scale=1">
101
+ <title>modelpace dashboard</title>
102
+ <style>${STYLE}</style>
103
+ </head>
104
+ <body>
105
+ <div id="t3d-root"></div>
106
+ <script type="application/json" id="t3d-data">${embedJson(data)}</script>
107
+ <script>${CLIENT}</script>
108
+ </body>
109
+ </html>
110
+ `;
111
+ }
112
+
113
+ /**
114
+ * 本地轻量服务:GET / 返回页面,GET /api/data 返回当前数据;每次请求重新取数,页面每 15 秒刷新。
115
+ * 默认只绑定本机回环地址。
116
+ */
117
+ export async function startDashboardServer({ port = 0, host = '127.0.0.1', load, options = {} } = {}) {
118
+ const server = http.createServer(async (req, res) => {
119
+ const url = new URL(req.url ?? '/', 'http://localhost');
120
+ if (req.method !== 'GET' || !['/', '/api/data'].includes(url.pathname)) {
121
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }).end('Not found\n');
122
+ return;
123
+ }
124
+ try {
125
+ const input = { ...(await load()), options: { ...options, live: true, now: Date.now() } };
126
+ if (url.pathname === '/api/data') {
127
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
128
+ res.end(JSON.stringify(buildDashboardData(input)));
129
+ } else {
130
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
131
+ res.end(renderDashboardHtml(input));
132
+ }
133
+ } catch (error) {
134
+ res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }).end(`${error?.message ?? error}\n`);
135
+ }
136
+ });
137
+ await new Promise((resolve, reject) => {
138
+ server.once('error', reject);
139
+ server.listen(port, host, resolve);
140
+ });
141
+ const address = server.address();
142
+ return {
143
+ server,
144
+ url: `http://${host === '::1' ? '[::1]' : host}:${address.port}/`,
145
+ close: () => new Promise((resolve) => {
146
+ server.close(() => resolve());
147
+ server.closeAllConnections();
148
+ }),
149
+ };
150
+ }