-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.ts
More file actions
713 lines (644 loc) · 26.6 KB
/
Copy pathdashboard.ts
File metadata and controls
713 lines (644 loc) · 26.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
import { Hono } from "hono";
import * as fs from "fs";
import { serve } from "@hono/node-server";
import { AgenticBlackboard, BlackboardData, SystemLog, AgentIntent } from "./blackboard.js";
import { ArchitecturalScout, NodeDetector, PythonDetector } from "../detectors/project-scout.js";
import * as path from "path";
import { fileURLToPath } from "url";
import { streamSSE } from "hono/streaming";
import { getDisplayVersion } from "./version.js";
import { RuntimeLogger } from "./logger.js";
import { ConfigManager } from "./config.js";
import { randomUUID } from "crypto";
import { TimelineProvider } from "../history/timeline.js";
import { EventStore } from "../history/event-store.js";
import { AutoPilotStatus } from "./autopilot-status.js";
import { createABEvaluationRecord } from "../evaluation/prompt-evaluator.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export function resolveDashboardHost(configuredHost = process.env.PROMPT_REFINER_DASHBOARD_HOST): string {
const host = configuredHost?.trim() || "127.0.0.1";
if (isLoopbackHost(host) || process.env.PROMPT_REFINER_DASHBOARD_ALLOW_REMOTE === "true") {
return host;
}
RuntimeLogger.warn("Ignoring non-loopback dashboard host without PROMPT_REFINER_DASHBOARD_ALLOW_REMOTE=true", { host });
return "127.0.0.1";
}
interface DashboardState {
selectedPath: string;
projects: string[];
globalLogs: SystemLog[];
logs: SystemLog[];
intents: AgentIntent[];
lastRefinement: BlackboardData["lastRefinement"] | null;
stack: string;
framework: string;
pattern: string;
stats: {
commits: number;
prompts: number;
lessons: number;
};
}
interface SemanticEventDetails {
taskName?: unknown;
provider?: unknown;
model?: unknown;
latencyMs?: unknown;
fallbackFrom?: unknown;
}
interface SemanticEventRow {
timestamp: string;
details_json: string;
}
function safeString(value: unknown, maxLength = 120): string | null {
return typeof value === "string" && value.length > 0 ? value.slice(0, maxLength) : null;
}
function sanitizeEndpoint(rawUrl: string): string {
try {
const url = new URL(rawUrl);
return `${url.protocol}//${url.hostname}${url.port ? `:${url.port}` : ""}`;
} catch {
return "invalid";
}
}
export function isSameOriginRequest(origin: string | undefined, requestUrl: string): boolean {
if (!origin) {
return false;
}
try {
return new URL(origin).origin === new URL(requestUrl).origin;
} catch {
return false;
}
}
export function isJsonContentType(contentType: string | undefined): boolean {
const mediaType = contentType?.split(";")[0]?.trim().toLowerCase();
return mediaType === "application/json" || Boolean(mediaType?.endsWith("+json"));
}
function isLoopbackHost(host: string): boolean {
const normalized = host.toLowerCase();
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "[::1]";
}
function redactSensitive(value: string): string {
return value
.replace(/(ghp_|github_pat_|sk-|xox[baprs]-)[a-z0-9_\-]+/gi, "$1[REDACTED]")
.replace(/(token|api[_-]?key|password|secret|authorization)\s*[:=]\s*["']?[^"'\s,;]+/gi, "$1=[REDACTED]")
.slice(0, 2_000);
}
export class CommandCenterDashboard {
private static rootPath: string = ".";
private static server: { close: (callback?: (error?: Error) => void) => void } | null = null;
static async setLastRefinement(original: string, refined: string, projectPath: string = ".", gain: number = 0) {
await AgenticBlackboard.setLastRefinement(original, refined, projectPath, gain);
}
static log(message: string, projectPath: string = ".") {
AgenticBlackboard.postLog(message, projectPath);
}
private static getVisibleProjects(): string[] {
const globalData = AgenticBlackboard.getGlobalData();
const uniqueProjects = new Set<string>([
path.resolve(this.rootPath),
...(globalData.projects || []).map(projectPath => path.resolve(projectPath))
]);
return [...uniqueProjects].filter(projectPath => fs.existsSync(projectPath));
}
private static logRouteError(routeName: string, error: unknown, selectedPath?: string) {
const message = redactSensitive(error instanceof Error ? error.stack || error.message : String(error));
RuntimeLogger.error(`Dashboard route failed: ${routeName}`, {
selectedPath: selectedPath || this.rootPath,
error: message,
});
console.error(`[Dashboard:${routeName}]`, message);
AgenticBlackboard.postLog(`Dashboard ${routeName} error: ${message.split("\n")[0]}`, selectedPath || this.rootPath);
}
private static resolveSelectedPath(projectParam?: string | null): string {
const projects = new Set<string>(this.getVisibleProjects());
const requestedPath = projectParam ? path.resolve(projectParam) : path.resolve(this.rootPath);
if (projects.has(requestedPath)) {
return requestedPath;
}
return path.resolve(this.rootPath);
}
private static async buildState(selectedPath: string): Promise<DashboardState> {
const globalData = AgenticBlackboard.getGlobalData();
const visibleProjects = this.getVisibleProjects();
const arch = await ArchitecturalScout.detectPatterns(selectedPath);
const node = await NodeDetector.detect(selectedPath);
const py = await PythonDetector.detect(selectedPath);
const store = EventStore.getInstance();
const repoId = store.ensureRepository(selectedPath).id;
// Fallbacks in case the table is missing or errors out during initialization
let stats = { commits: 0, prompts: 0, lessons: 0 };
try {
stats = store.getRepositoryStats(repoId);
} catch (e) {
RuntimeLogger.warn("Failed to retrieve dashboard stats from db", e);
}
return {
selectedPath,
projects: visibleProjects,
globalLogs: globalData.logs || [],
logs: AgenticBlackboard.getLogs(selectedPath),
intents: AgenticBlackboard.getActiveIntents(selectedPath),
lastRefinement: AgenticBlackboard.getLastRefinement(selectedPath),
stack: node.language || py.language || "Unknown",
framework: node.framework || py.framework || "Unknown",
pattern: arch.length > 0 ? arch.slice(0, 1).join(", ") : "Standard",
stats,
};
}
private static buildHealth(selectedPath: string) {
const repoId = EventStore.getInstance().ensureRepository(selectedPath).id;
const config = ConfigManager.getSemanticConfig(selectedPath);
const db = (EventStore.getInstance() as any).db;
const rows = db.prepare(`
SELECT timestamp, details_json
FROM events
WHERE repo_id = ? AND event_type = 'semantic_request_completed'
ORDER BY timestamp DESC
LIMIT 100
`).all(repoId) as SemanticEventRow[];
const events = rows.map(row => {
let details: SemanticEventDetails = {};
try {
details = JSON.parse(row.details_json) as SemanticEventDetails;
} catch {
// Malformed historical telemetry is ignored rather than exposed.
}
return {
timestamp: row.timestamp,
taskName: safeString(details.taskName),
provider: safeString(details.provider) || "unknown",
model: safeString(details.model) || "unknown",
latencyMs: typeof details.latencyMs === "number" && Number.isFinite(details.latencyMs)
? Math.max(0, Math.round(details.latencyMs))
: null,
fallbackFrom: Array.isArray(details.fallbackFrom)
? details.fallbackFrom.map(item => safeString(item, 80)).filter((item): item is string => item !== null).slice(0, 10)
: [],
};
});
const providerMetrics = new Map<string, {
completions: number;
latencyTotal: number;
latencyCount: number;
lastSuccessAt: string;
models: Set<string>;
}>();
for (const event of events) {
const metric = providerMetrics.get(event.provider) || {
completions: 0,
latencyTotal: 0,
latencyCount: 0,
lastSuccessAt: event.timestamp,
models: new Set<string>(),
};
metric.completions += 1;
if (event.latencyMs !== null) {
metric.latencyTotal += event.latencyMs;
metric.latencyCount += 1;
}
metric.models.add(event.model);
providerMetrics.set(event.provider, metric);
}
const totalLatency = events.reduce((sum, event) => sum + (event.latencyMs || 0), 0);
const latencyCount = events.filter(event => event.latencyMs !== null).length;
const semanticEnabled = config.localEnabled || config.mcpSamplingEnabled;
return {
runtime: {
status: "online",
uptimeSeconds: Math.floor(process.uptime()),
nodeVersion: process.version,
checkedAt: new Date().toISOString(),
},
semantic: {
status: !semanticEnabled ? "disabled" : events.length > 0 ? "healthy" : "configured",
local: {
enabled: config.localEnabled,
endpoint: sanitizeEndpoint(config.baseUrl),
models: config.models,
timeoutMs: config.timeoutMs,
allowNonLoopback: config.allowNonLoopback,
},
mcpSampling: { enabled: config.mcpSamplingEnabled },
totals: {
completed: events.length,
averageLatencyMs: latencyCount > 0 ? Math.round(totalLatency / latencyCount) : null,
fallbackCompletions: events.filter(event => event.fallbackFrom.length > 0).length,
},
lastSuccess: events[0] || null,
providers: [...providerMetrics.entries()].map(([provider, metric]) => ({
provider,
completions: metric.completions,
averageLatencyMs: metric.latencyCount > 0 ? Math.round(metric.latencyTotal / metric.latencyCount) : null,
lastSuccessAt: metric.lastSuccessAt,
models: [...metric.models],
})),
},
};
}
static createApp(defaultPath = ".") {
this.rootPath = defaultPath;
const app = new Hono();
app.get("/api/state", async (c) => {
const selectedPath = this.resolveSelectedPath(c.req.query("project"));
try {
const state = await this.buildState(selectedPath);
return c.json(state);
} catch (error) {
this.logRouteError("api/state", error, selectedPath);
return c.json({ error: "Dashboard state unavailable", selectedPath }, 500);
}
});
app.get("/api/timeline", async (c) => {
try {
const store = EventStore.getInstance();
const repoId = store.ensureRepository(this.resolveSelectedPath(c.req.query("project"))).id;
const provider = new TimelineProvider();
const timeline = provider.getUnifiedTimeline(50, repoId);
return c.json(timeline);
} catch (error) {
this.logRouteError("api/timeline", error);
return c.json({ error: "Timeline unavailable" }, 500);
}
});
app.get("/api/commits", async (c) => {
try {
const store = EventStore.getInstance();
const repoId = store.ensureRepository(this.resolveSelectedPath(c.req.query("project"))).id;
const db = (store as any).db;
const commits = db.prepare(`
SELECT c.*, e.prompt_id, e.id as execution_id
FROM commits c
LEFT JOIN execution_commits ec ON c.id = ec.commit_id
LEFT JOIN executions e ON ec.execution_id = e.id
WHERE c.repo_id = ?
ORDER BY c.committed_at DESC LIMIT 50
`).all(repoId);
return c.json(commits);
} catch (error) {
this.logRouteError("api/commits", error);
return c.json({ error: "Commits unavailable" }, 500);
}
});
app.get("/api/lessons", async (c) => {
try {
const store = EventStore.getInstance();
const repoId = store.ensureRepository(this.resolveSelectedPath(c.req.query("project"))).id;
const db = (store as any).db;
const lessons = db.prepare("SELECT * FROM lessons WHERE repo_id = ? ORDER BY created_at DESC").all(repoId);
return c.json(lessons);
} catch (error) {
this.logRouteError("api/lessons", error);
return c.json({ error: "Lessons unavailable" }, 500);
}
});
app.get("/api/templates", async (c) => {
try {
const store = EventStore.getInstance();
const repoId = store.ensureRepository(this.resolveSelectedPath(c.req.query("project"))).id;
const db = (store as any).db;
const templates = db.prepare("SELECT * FROM prompt_templates WHERE repo_id = ? ORDER BY success_score DESC").all(repoId);
return c.json(templates);
} catch (error) {
this.logRouteError("api/templates", error);
return c.json({ error: "Templates unavailable" }, 500);
}
});
app.post("/api/review/:kind/:id", async (c) => {
const selectedPath = this.resolveSelectedPath(c.req.query("project"));
try {
if (!isSameOriginRequest(c.req.header("origin"), c.req.url)) {
return c.json({ error: "Cross-origin review requests are not allowed" }, 403);
}
if (!isJsonContentType(c.req.header("content-type"))) {
return c.json({ error: "Review requests must use application/json" }, 415);
}
const kind = c.req.param("kind");
if (kind !== "lesson" && kind !== "template") {
return c.json({ error: "Unsupported review candidate type" }, 400);
}
let body: { decision?: unknown };
try {
body = await c.req.json() as { decision?: unknown };
} catch {
return c.json({ error: "Review request body must be valid JSON" }, 400);
}
if (body.decision !== "approve" && body.decision !== "reject") {
return c.json({ error: "Decision must be approve or reject" }, 400);
}
const id = c.req.param("id");
if (!id || id.length > 200) {
return c.json({ error: "Review candidate ID is invalid" }, 400);
}
const store = EventStore.getInstance();
const repoId = store.ensureRepository(selectedPath).id;
const approved = body.decision === "approve";
const changed = kind === "lesson"
? store.reviewLesson(repoId, id, approved)
: store.reviewTemplate(repoId, id, approved);
if (!changed) {
return c.json({ error: `Pending ${kind} not found for selected repository` }, 404);
}
store.recordEvent({
id: `evt_dashboard_review_${Date.now()}_${Math.floor(Math.random() * 100000)}`,
event_type: `${kind}_reviewed`,
repo_id: repoId,
summary: `${kind === "lesson" ? "Lesson" : "Template"} ${approved ? "approved" : "rejected"} from dashboard`,
details_json: JSON.stringify({ candidateId: id, decision: body.decision }),
});
this.log(`${kind === "lesson" ? "Lesson" : "Template"} ${approved ? "approved" : "rejected"}: ${id}`, selectedPath);
return c.json({ id, kind, decision: body.decision, repoId });
} catch (error) {
this.logRouteError("api/review", error, selectedPath);
return c.json({ error: "Review request failed" }, 500);
}
});
app.get("/api/autopilot", (c) => {
try {
return c.json(AutoPilotStatus.getSnapshot());
} catch (error) {
this.logRouteError("api/autopilot", error);
return c.json({ error: "Auto-pilot status unavailable" }, 500);
}
});
app.get("/api/health", async (c) => {
const selectedPath = this.resolveSelectedPath(c.req.query("project"));
try {
return c.json(this.buildHealth(selectedPath));
} catch (error) {
this.logRouteError("api/health", error, selectedPath);
return c.json({ error: "Provider health unavailable" }, 500);
}
});
app.post("/proxy/v1/chat/completions", async (c) => {
const selectedPath = this.resolveSelectedPath(c.req.query("project"));
try {
if (!isJsonContentType(c.req.header("content-type"))) {
return c.json({ error: "Proxy requests must use application/json" }, 415);
}
const config = ConfigManager.getSemanticConfig(selectedPath);
let upstreamBase: URL;
try {
upstreamBase = new URL(config.baseUrl.endsWith("/") ? config.baseUrl : `${config.baseUrl}/`);
} catch {
return c.json({ error: "Configured semantic baseUrl is invalid" }, 400);
}
if (!config.allowNonLoopback && !isLoopbackHost(upstreamBase.hostname)) {
return c.json({ error: "Proxy upstream must be loopback unless allowNonLoopback is enabled" }, 403);
}
let body: any;
try {
body = await c.req.json();
} catch {
return c.json({ error: "Proxy request body must be valid JSON" }, 400);
}
const store = EventStore.getInstance();
const repoId = store.ensureRepository(selectedPath).id;
// Extract prompt
const messages = Array.isArray(body.messages) ? body.messages : [];
const lastMessage = messages[messages.length - 1];
const originalPrompt = typeof lastMessage?.content === "string" && lastMessage.content.trim()
? lastMessage.content
: "Unknown proxy prompt";
let forwardedPrompt = originalPrompt;
// Attempt Minified Template Caching Swap
const templates = store.getTemplates(repoId).filter(t => t.approved === 1 && t.deprecated === 0);
let wasMinified = false;
for (const tpl of templates) {
if (tpl.category !== "Minified" || !tpl.usageNotes) {
continue;
}
let matchesTemplate = false;
try {
matchesTemplate = new RegExp(tpl.usageNotes).test(originalPrompt);
} catch (error) {
RuntimeLogger.warn("Ignoring invalid minified template usage regex", { templateId: tpl.id, error });
}
if (matchesTemplate) {
forwardedPrompt = tpl.templateText;
if (lastMessage && typeof lastMessage.content === "string") {
lastMessage.content = forwardedPrompt;
}
wasMinified = true;
break;
}
}
const promptId = `prm_${randomUUID()}`;
const execId = `exec_${randomUUID()}`;
store.recordPrompt({
id: promptId,
client: "API_PROXY",
agent_name: "ProxyClient",
raw_prompt: originalPrompt,
normalized_prompt: wasMinified ? forwardedPrompt : undefined,
repo_id: repoId
});
const upstreamUrl = new URL("chat/completions", upstreamBase).toString();
let upstreamResponse: Response;
try {
upstreamResponse = await fetch(upstreamUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
...(c.req.header("authorization") ? { "Authorization": c.req.header("authorization") as string } : {}),
},
body: JSON.stringify(body),
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
store.recordExecution({
id: execId,
prompt_id: promptId,
workflow_name: "proxy_forward",
executor_name: "LocalLLM",
status: "failed",
result_summary: `Network error reaching upstream: ${message}`,
artifacts_json: JSON.stringify({ error: redactSensitive(message) }),
});
return c.json({ error: "Proxy request failed" }, 502);
}
if (!upstreamResponse.ok) {
const errText = await upstreamResponse.text();
store.recordExecution({
id: execId,
prompt_id: promptId,
workflow_name: "proxy_forward",
executor_name: "LocalLLM",
status: "failed",
result_summary: `Upstream error: ${upstreamResponse.status} ${upstreamResponse.statusText}`,
artifacts_json: JSON.stringify({ error: redactSensitive(errText) }),
});
return new Response(errText, {
status: upstreamResponse.status,
headers: upstreamResponse.headers,
});
}
store.recordExecution({
id: execId,
prompt_id: promptId,
workflow_name: "proxy_forward",
executor_name: "LocalLLM",
status: "completed",
result_summary: `Proxied successfully to ${sanitizeEndpoint(config.baseUrl)}`,
artifacts_json: "{}",
});
return new Response(upstreamResponse.body, {
status: upstreamResponse.status,
headers: upstreamResponse.headers,
});
} catch (error) {
this.logRouteError("proxy/v1/chat/completions", error, selectedPath);
return c.json({ error: "Proxy request failed" }, 502);
}
});
app.get("/api/tournaments", async (c) => {
const selectedPath = this.resolveSelectedPath(c.req.query("project"));
try {
const repoId = EventStore.getInstance().ensureRepository(selectedPath).id;
const tournaments = EventStore.getInstance().getTournaments(repoId);
return c.json(tournaments);
} catch (error) {
this.logRouteError("api/tournaments", error, selectedPath);
return c.json({ error: "Failed to fetch tournaments" }, 500);
}
});
app.post("/api/tournaments/run", async (c) => {
const selectedPath = this.resolveSelectedPath(c.req.query("project"));
try {
if (!isSameOriginRequest(c.req.header("origin"), c.req.url)) {
return c.json({ error: "Cross-origin tournament requests are not allowed" }, 403);
}
if (!isJsonContentType(c.req.header("content-type"))) {
return c.json({ error: "Tournament requests must use application/json" }, 415);
}
let body: { baseline?: unknown; variantA?: unknown; variantB?: unknown };
try {
body = await c.req.json() as { baseline?: unknown; variantA?: unknown; variantB?: unknown };
} catch {
return c.json({ error: "Tournament request body must be valid JSON" }, 400);
}
const { baseline, variantA, variantB } = body;
if (
typeof baseline !== "string" || baseline.trim().length === 0 ||
typeof variantA !== "string" || variantA.trim().length === 0 ||
typeof variantB !== "string" || variantB.trim().length === 0
) {
return c.json({ error: "Tournament baseline, variantA, and variantB must be non-empty strings" }, 400);
}
const experiment = createABEvaluationRecord({
experimentId: `exp_${randomUUID()}`,
baselinePrompt: baseline,
variantA: { id: "A", prompt: variantA },
variantB: { id: "B", prompt: variantB }
});
const repoId = EventStore.getInstance().ensureRepository(selectedPath).id;
EventStore.getInstance().recordTournament({
id: experiment.experimentId,
repo_id: repoId,
baseline_prompt: baseline,
variant_a: variantA,
variant_b: variantB,
winner_observed: experiment.heuristicPreference,
details_json: JSON.stringify(experiment)
});
return c.json(experiment);
} catch (error) {
this.logRouteError("api/tournaments/run", error, selectedPath);
return c.json({ error: "Failed to run tournament" }, 500);
}
});
app.get("/api/events", async (c) => {
try {
return streamSSE(c, async (stream) => {
let closed = false;
const pushUpdate = () => {
if (closed) {
return;
}
void stream.writeSSE({
event: "update",
data: "update",
id: String(Date.now()),
});
};
const unsubscribe = AgenticBlackboard.onUpdate(pushUpdate);
c.req.raw.signal.addEventListener("abort", () => {
closed = true;
unsubscribe();
}, { once: true });
await stream.writeSSE({ event: "ready", data: "connected", id: String(Date.now()) });
while (!closed) {
await stream.sleep(30000);
await stream.writeSSE({ event: "ping", data: "ping", id: String(Date.now()) });
}
});
} catch (error) {
this.logRouteError("api/events", error, this.rootPath);
return c.text("Dashboard event stream unavailable", 500);
}
});
app.get("/", async (c) => {
const selectedPath = this.resolveSelectedPath(c.req.query("project"));
try {
const state = await this.buildState(selectedPath);
const serializedState = JSON.stringify(state).replace(/</g, "\\u003c");
// Robust path resolution: try __dirname first, then project root relative
const possiblePaths = [
path.join(__dirname, "dashboard.html"),
path.join(process.cwd(), "universal-refiner", "src", "core", "dashboard.html"),
path.join(process.cwd(), "src", "core", "dashboard.html"),
path.join(process.cwd(), "dist", "src", "core", "dashboard.html")
];
let html = "";
let found = false;
for (const p of possiblePaths) {
if (fs.existsSync(p)) {
html = fs.readFileSync(p, "utf-8");
found = true;
break;
}
}
if (!found) {
throw new Error(`Could not find dashboard.html in any of: ${possiblePaths.join(", ")}`);
}
// Inject data and version
html = html.replace("{{STATE_JSON}}", serializedState);
html = html.replace("V1.0.0", `V${getDisplayVersion()}`);
return c.html(html);
} catch (error) {
this.logRouteError("/", error, selectedPath);
return c.html(`<!DOCTYPE html><html><body style="font-family:Segoe UI,sans-serif;background:#020617;color:#f8fafc;padding:2rem;"><h1>Dashboard Error</h1><p>The dashboard failed to render. See sanitized runtime logs.</p></body></html>`, 500);
}
});
return app;
}
static start(port = 3000, defaultPath = ".") {
const app = this.createApp(defaultPath);
try {
const server = serve({ fetch: app.fetch, port, hostname: resolveDashboardHost() });
this.server = server;
server.on("error", (e: any) => {
if (e.code === "EADDRINUSE") {
console.error(`[Command Center] Port ${port} taken.`);
RuntimeLogger.error(`Dashboard port ${port} already in use`, e);
} else {
RuntimeLogger.error(`Dashboard server emitted error on port ${port}`, e);
}
});
} catch (error) {
RuntimeLogger.error(`Dashboard failed to start on port ${port}`, error);
throw error;
}
}
static async stop(): Promise<void> {
const server = this.server;
this.server = null;
if (!server) {
return;
}
await new Promise<void>((resolve, reject) => {
server.close((error?: Error) => error ? reject(error) : resolve());
});
}
}