@open330/oac-dashboard 2026.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1224 @@
1
+ // src/server.ts
2
+ import { randomUUID as randomUUID2 } from "crypto";
3
+ import { readFile, readdir } from "fs/promises";
4
+ import { resolve } from "path";
5
+ import cors from "@fastify/cors";
6
+ import { contributionLogSchema } from "@open330/oac-tracking";
7
+ import { buildLeaderboard } from "@open330/oac-tracking";
8
+ import Fastify from "fastify";
9
+
10
+ // src/pipeline.ts
11
+ import { randomUUID } from "crypto";
12
+ import { buildExecutionPlan, estimateTokens } from "@open330/oac-budget";
13
+ import { createEventBus } from "@open330/oac-core";
14
+ import {
15
+ CompositeScanner,
16
+ GitHubIssuesScanner,
17
+ LintScanner,
18
+ TodoScanner,
19
+ rankTasks
20
+ } from "@open330/oac-discovery";
21
+ import { CodexAdapter, createSandbox, executeTask as workerExecuteTask } from "@open330/oac-execution";
22
+ import { cloneRepo, resolveRepo } from "@open330/oac-repo";
23
+ import { writeContributionLog } from "@open330/oac-tracking";
24
+ import { execa } from "execa";
25
+ function buildScanners() {
26
+ const scanners = [new LintScanner(), new TodoScanner()];
27
+ const names = ["lint", "todo"];
28
+ if (process.env.GITHUB_TOKEN) {
29
+ scanners.push(new GitHubIssuesScanner());
30
+ names.push("github-issues");
31
+ }
32
+ return { names, scanner: new CompositeScanner(scanners) };
33
+ }
34
+ async function executeWithCodex(input) {
35
+ const startedAt = Date.now();
36
+ const taskSlug = input.task.id.replace(/[^a-zA-Z0-9-]/g, "-").replace(/-+/g, "-").slice(0, 30);
37
+ const branchName = `oac/${Date.now()}-${taskSlug}`;
38
+ const sandbox = await createSandbox(input.repoPath, branchName, input.baseBranch);
39
+ const eventBus = createEventBus();
40
+ const sandboxInfo = {
41
+ branchName,
42
+ sandboxPath: sandbox.path,
43
+ cleanup: sandbox.cleanup
44
+ };
45
+ try {
46
+ const result = await workerExecuteTask(input.codexAdapter, input.task, sandbox, eventBus, {
47
+ tokenBudget: input.estimate.totalEstimatedTokens,
48
+ timeoutMs: input.timeoutSeconds * 1e3
49
+ });
50
+ const commitResult = await commitSandboxChanges(sandbox.path, input.task);
51
+ const filesChanged = commitResult.filesChanged.length > 0 ? commitResult.filesChanged : result.filesChanged.length > 0 ? result.filesChanged : [];
52
+ return {
53
+ execution: {
54
+ success: result.success || commitResult.hasChanges,
55
+ exitCode: result.exitCode,
56
+ totalTokensUsed: result.totalTokensUsed,
57
+ filesChanged,
58
+ duration: result.duration > 0 ? result.duration / 1e3 : (Date.now() - startedAt) / 1e3,
59
+ error: result.error
60
+ },
61
+ sandbox: sandboxInfo
62
+ };
63
+ } catch (error) {
64
+ const commitResult = await commitSandboxChanges(sandbox.path, input.task);
65
+ if (commitResult.hasChanges) {
66
+ return {
67
+ execution: {
68
+ success: true,
69
+ exitCode: 0,
70
+ totalTokensUsed: 0,
71
+ filesChanged: commitResult.filesChanged,
72
+ duration: (Date.now() - startedAt) / 1e3
73
+ },
74
+ sandbox: sandboxInfo
75
+ };
76
+ }
77
+ const message = error instanceof Error ? error.message : String(error);
78
+ return {
79
+ execution: {
80
+ success: false,
81
+ exitCode: 1,
82
+ totalTokensUsed: 0,
83
+ filesChanged: [],
84
+ duration: (Date.now() - startedAt) / 1e3,
85
+ error: message
86
+ },
87
+ sandbox: sandboxInfo
88
+ };
89
+ }
90
+ }
91
+ async function commitSandboxChanges(sandboxPath, task) {
92
+ try {
93
+ const statusResult = await execa("git", ["status", "--porcelain"], { cwd: sandboxPath });
94
+ if (!statusResult.stdout.trim()) {
95
+ return { hasChanges: false, filesChanged: [] };
96
+ }
97
+ await execa("git", ["add", "-A"], { cwd: sandboxPath });
98
+ await execa(
99
+ "git",
100
+ ["commit", "-m", `[OAC] ${task.title}
101
+
102
+ Automated contribution by OAC.`],
103
+ { cwd: sandboxPath }
104
+ );
105
+ const diffResult = await execa("git", ["diff", "--name-only", "HEAD~1", "HEAD"], {
106
+ cwd: sandboxPath
107
+ });
108
+ const changedFiles = diffResult.stdout.trim().split("\n").filter(Boolean);
109
+ return { hasChanges: true, filesChanged: changedFiles };
110
+ } catch {
111
+ return { hasChanges: false, filesChanged: [] };
112
+ }
113
+ }
114
+ async function createPullRequest(input) {
115
+ const { branchName, sandboxPath } = input.sandbox;
116
+ try {
117
+ await execa("git", ["push", "--set-upstream", "origin", branchName], { cwd: sandboxPath });
118
+ const prTitle = `[OAC] ${input.task.title}`;
119
+ const prBody = [
120
+ "## Summary",
121
+ "",
122
+ input.task.description || `Automated contribution for task "${input.task.title}".`,
123
+ "",
124
+ "## Context",
125
+ "",
126
+ `- **Task source:** ${input.task.source}`,
127
+ `- **Complexity:** ${input.task.complexity}`,
128
+ `- **Tokens used:** ${input.execution.totalTokensUsed}`,
129
+ `- **Files changed:** ${input.execution.filesChanged.length}`,
130
+ "",
131
+ "---",
132
+ "*This PR was automatically generated by [OAC](https://github.com/Open330/open-agent-contribution).*"
133
+ ].join("\n");
134
+ const ghResult = await execa(
135
+ "gh",
136
+ [
137
+ "pr",
138
+ "create",
139
+ "--repo",
140
+ input.repoFullName,
141
+ "--title",
142
+ prTitle,
143
+ "--body",
144
+ prBody,
145
+ "--head",
146
+ branchName,
147
+ "--base",
148
+ input.baseBranch
149
+ ],
150
+ { cwd: sandboxPath }
151
+ );
152
+ const prUrl = ghResult.stdout.trim();
153
+ const prNumberMatch = prUrl.match(/\/pull\/(\d+)/);
154
+ const prNumber = prNumberMatch ? Number.parseInt(prNumberMatch[1], 10) : 0;
155
+ return { number: prNumber, url: prUrl, status: "open" };
156
+ } catch {
157
+ return void 0;
158
+ }
159
+ }
160
+ function resolveGithubUsername() {
161
+ const candidates = [
162
+ process.env.GITHUB_USER,
163
+ process.env.GITHUB_USERNAME,
164
+ process.env.USER,
165
+ process.env.LOGNAME
166
+ ];
167
+ for (const c of candidates) {
168
+ const cleaned = c?.trim().replace(/[^A-Za-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
169
+ if (cleaned && cleaned.length <= 39 && /^(?!-)[A-Za-z0-9-]+(?<!-)$/.test(cleaned)) {
170
+ return cleaned;
171
+ }
172
+ }
173
+ return "oac-user";
174
+ }
175
+ async function executePipeline(config, onEvent) {
176
+ const runId = randomUUID();
177
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
178
+ const progress = {
179
+ tasksDiscovered: 0,
180
+ tasksSelected: 0,
181
+ tasksCompleted: 0,
182
+ tasksFailed: 0,
183
+ prsCreated: 0,
184
+ tokensUsed: 0,
185
+ prUrls: []
186
+ };
187
+ const state = {
188
+ runId,
189
+ status: "running",
190
+ stage: "resolving",
191
+ config,
192
+ startedAt,
193
+ progress
194
+ };
195
+ const emit = (event) => {
196
+ if (event.type === "run:stage") state.stage = event.stage;
197
+ if (event.type === "run:progress") state.progress = event.progress;
198
+ onEvent(event);
199
+ };
200
+ try {
201
+ emit({ type: "run:stage", stage: "resolving", message: `Resolving ${config.repo}...` });
202
+ const resolvedRepo = await resolveRepo(config.repo);
203
+ emit({ type: "run:stage", stage: "cloning", message: `Cloning ${resolvedRepo.fullName}...` });
204
+ await cloneRepo(resolvedRepo);
205
+ const { names, scanner } = buildScanners();
206
+ emit({
207
+ type: "run:stage",
208
+ stage: "scanning",
209
+ message: `Scanning with ${names.join(", ")}...`
210
+ });
211
+ const scannedTasks = await scanner.scan(resolvedRepo.localPath, {
212
+ repo: resolvedRepo
213
+ });
214
+ let candidateTasks = rankTasks(scannedTasks).filter((t) => t.priority >= 20);
215
+ if (config.source) {
216
+ candidateTasks = candidateTasks.filter((t) => t.source === config.source);
217
+ }
218
+ if (config.maxTasks) {
219
+ candidateTasks = candidateTasks.slice(0, config.maxTasks);
220
+ }
221
+ progress.tasksDiscovered = candidateTasks.length;
222
+ emit({ type: "run:progress", progress: { ...progress } });
223
+ if (candidateTasks.length === 0) {
224
+ emit({ type: "run:stage", stage: "completed", message: "No tasks discovered." });
225
+ state.status = "completed";
226
+ state.completedAt = (/* @__PURE__ */ new Date()).toISOString();
227
+ emit({ type: "run:completed", summary: { ...state } });
228
+ return state;
229
+ }
230
+ emit({
231
+ type: "run:stage",
232
+ stage: "estimating",
233
+ message: `Estimating tokens for ${candidateTasks.length} task(s)...`
234
+ });
235
+ const estimates = /* @__PURE__ */ new Map();
236
+ for (const task of candidateTasks) {
237
+ const est = await estimateTokens(task, config.provider);
238
+ estimates.set(task.id, est);
239
+ }
240
+ emit({ type: "run:stage", stage: "planning", message: "Building execution plan..." });
241
+ const plan = buildExecutionPlan(candidateTasks, estimates, config.tokens);
242
+ progress.tasksSelected = plan.selectedTasks.length;
243
+ emit({ type: "run:progress", progress: { ...progress } });
244
+ if (plan.selectedTasks.length === 0) {
245
+ emit({ type: "run:stage", stage: "completed", message: "No tasks fit within budget." });
246
+ state.status = "completed";
247
+ state.completedAt = (/* @__PURE__ */ new Date()).toISOString();
248
+ emit({ type: "run:completed", summary: { ...state } });
249
+ return state;
250
+ }
251
+ const concurrency = Math.max(1, config.concurrency ?? 1);
252
+ emit({
253
+ type: "run:stage",
254
+ stage: "executing",
255
+ message: `Executing ${plan.selectedTasks.length} task(s) (concurrency: ${concurrency})...`
256
+ });
257
+ const codexAdapter = new CodexAdapter();
258
+ const codexAvailability = await codexAdapter.checkAvailability();
259
+ const useRealExecution = config.provider.includes("codex") && codexAvailability.available;
260
+ const taskResults = await runWithConcurrency(
261
+ plan.selectedTasks,
262
+ concurrency,
263
+ async (entry) => {
264
+ emit({ type: "run:task-start", taskId: entry.task.id, title: entry.task.title });
265
+ progress.currentTask = entry.task.title;
266
+ emit({ type: "run:progress", progress: { ...progress } });
267
+ let execution;
268
+ let sandbox;
269
+ if (useRealExecution) {
270
+ const result2 = await executeWithCodex({
271
+ task: entry.task,
272
+ estimate: entry.estimate,
273
+ codexAdapter,
274
+ repoPath: resolvedRepo.localPath,
275
+ baseBranch: resolvedRepo.meta.defaultBranch,
276
+ timeoutSeconds: 300
277
+ });
278
+ execution = result2.execution;
279
+ sandbox = result2.sandbox;
280
+ } else {
281
+ await new Promise((r) => setTimeout(r, 500));
282
+ execution = {
283
+ success: true,
284
+ exitCode: 0,
285
+ totalTokensUsed: Math.round(entry.estimate.totalEstimatedTokens * 0.9),
286
+ filesChanged: entry.task.targetFiles.slice(0, 4),
287
+ duration: 0.5
288
+ };
289
+ }
290
+ let pr;
291
+ if (execution.success && sandbox && execution.filesChanged.length > 0) {
292
+ emit({
293
+ type: "run:stage",
294
+ stage: "creating-pr",
295
+ message: `Creating PR for "${entry.task.title}"...`
296
+ });
297
+ pr = await createPullRequest({
298
+ task: entry.task,
299
+ execution,
300
+ sandbox,
301
+ repoFullName: resolvedRepo.fullName,
302
+ baseBranch: resolvedRepo.meta.defaultBranch
303
+ });
304
+ if (pr) {
305
+ progress.prsCreated += 1;
306
+ progress.prUrls.push(pr.url);
307
+ }
308
+ }
309
+ if (execution.success) {
310
+ progress.tasksCompleted += 1;
311
+ } else {
312
+ progress.tasksFailed += 1;
313
+ }
314
+ progress.tokensUsed += execution.totalTokensUsed;
315
+ progress.currentTask = void 0;
316
+ const result = { task: entry.task, execution, sandbox, pr };
317
+ emit({
318
+ type: "run:task-done",
319
+ taskId: entry.task.id,
320
+ title: entry.task.title,
321
+ success: execution.success,
322
+ prUrl: pr?.url,
323
+ filesChanged: execution.filesChanged.length
324
+ });
325
+ emit({ type: "run:progress", progress: { ...progress } });
326
+ return result;
327
+ }
328
+ );
329
+ emit({ type: "run:stage", stage: "tracking", message: "Writing contribution log..." });
330
+ const contributionLog = {
331
+ version: "1.0",
332
+ runId,
333
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
334
+ contributor: { githubUsername: resolveGithubUsername() },
335
+ repo: {
336
+ fullName: resolvedRepo.fullName,
337
+ headSha: resolvedRepo.git.headSha,
338
+ defaultBranch: resolvedRepo.meta.defaultBranch
339
+ },
340
+ budget: {
341
+ provider: config.provider,
342
+ totalTokensBudgeted: config.tokens,
343
+ totalTokensUsed: progress.tokensUsed
344
+ },
345
+ tasks: taskResults.map((r) => ({
346
+ taskId: r.task.id,
347
+ title: r.task.title,
348
+ source: r.task.source,
349
+ complexity: r.task.complexity,
350
+ status: r.execution.success ? "success" : "failed",
351
+ tokensUsed: r.execution.totalTokensUsed,
352
+ duration: r.execution.duration,
353
+ filesChanged: r.execution.filesChanged,
354
+ pr: r.pr,
355
+ error: r.execution.error
356
+ })),
357
+ metrics: {
358
+ tasksDiscovered: progress.tasksDiscovered,
359
+ tasksAttempted: taskResults.length,
360
+ tasksSucceeded: progress.tasksCompleted,
361
+ tasksFailed: progress.tasksFailed,
362
+ totalDuration: (Date.now() - new Date(startedAt).getTime()) / 1e3,
363
+ totalFilesChanged: taskResults.reduce(
364
+ (sum, r) => sum + r.execution.filesChanged.length,
365
+ 0
366
+ ),
367
+ totalLinesAdded: 0,
368
+ totalLinesRemoved: 0
369
+ }
370
+ };
371
+ try {
372
+ await writeContributionLog(contributionLog, resolvedRepo.localPath);
373
+ } catch {
374
+ }
375
+ emit({ type: "run:stage", stage: "completed", message: "Run completed successfully." });
376
+ state.status = "completed";
377
+ state.completedAt = (/* @__PURE__ */ new Date()).toISOString();
378
+ emit({ type: "run:completed", summary: { ...state } });
379
+ return state;
380
+ } catch (error) {
381
+ const message = error instanceof Error ? error.message : String(error);
382
+ state.status = "failed";
383
+ state.stage = "failed";
384
+ state.error = message;
385
+ state.completedAt = (/* @__PURE__ */ new Date()).toISOString();
386
+ emit({ type: "run:error", error: message });
387
+ return state;
388
+ }
389
+ }
390
+ async function runWithConcurrency(items, concurrency, worker) {
391
+ if (items.length === 0) return [];
392
+ const results = new Array(items.length);
393
+ let nextIndex = 0;
394
+ const runWorker = async () => {
395
+ while (true) {
396
+ const currentIndex = nextIndex;
397
+ nextIndex += 1;
398
+ if (currentIndex >= items.length) return;
399
+ results[currentIndex] = await worker(items[currentIndex], currentIndex);
400
+ }
401
+ };
402
+ const workerCount = Math.min(concurrency, items.length);
403
+ await Promise.all(Array.from({ length: workerCount }, () => runWorker()));
404
+ return results;
405
+ }
406
+
407
+ // src/ui.ts
408
+ function renderDashboardHtml(port) {
409
+ return `<!DOCTYPE html>
410
+ <html lang="en">
411
+ <head>
412
+ <meta charset="UTF-8">
413
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
414
+ <title>OAC Dashboard</title>
415
+ <style>
416
+ :root {
417
+ --bg: #0a0a0a; --card: #111; --border: #222; --text: #e5e5e5;
418
+ --muted: #888; --accent: #3b82f6; --green: #22c55e; --red: #ef4444;
419
+ --yellow: #eab308; --purple: #a855f7;
420
+ }
421
+ * { margin: 0; padding: 0; box-sizing: border-box; }
422
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", monospace; background: var(--bg); color: var(--text); }
423
+ .container { max-width: 1200px; margin: 0 auto; padding: 24px; }
424
+ header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 32px; border-bottom: 1px solid var(--border); padding-bottom: 16px; }
425
+ header h1 { font-size: 24px; font-weight: 700; }
426
+ header h1 span { color: var(--accent); }
427
+ .badge { display: inline-block; padding: 2px 10px; border-radius: 12px; font-size: 12px; font-weight: 600; }
428
+ .badge-idle { background: #1a1a2e; color: var(--muted); }
429
+ .badge-running { background: #0a2a1a; color: var(--green); animation: pulse 2s infinite; }
430
+ .badge-completed { background: #0a2a1a; color: var(--green); }
431
+ .badge-failed { background: #2a0a0a; color: var(--red); }
432
+ @keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.6; } }
433
+ .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; }
434
+ @media (max-width: 768px) { .grid { grid-template-columns: 1fr; } }
435
+ .card { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 20px; }
436
+ .card h2 { font-size: 14px; color: var(--muted); text-transform: uppercase; letter-spacing: 1px; margin-bottom: 16px; }
437
+ .stat-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid var(--border); }
438
+ .stat-row:last-child { border-bottom: none; }
439
+ .stat-label { color: var(--muted); font-size: 13px; }
440
+ .stat-value { font-weight: 600; font-size: 14px; }
441
+ .full-width { grid-column: 1 / -1; }
442
+ table { width: 100%; border-collapse: collapse; font-size: 13px; }
443
+ th { text-align: left; color: var(--muted); font-weight: 500; padding: 8px 12px; border-bottom: 1px solid var(--border); }
444
+ td { padding: 8px 12px; border-bottom: 1px solid var(--border); }
445
+ tr:hover td { background: #1a1a1a; }
446
+ .rank { color: var(--yellow); font-weight: 700; }
447
+ .empty { color: var(--muted); text-align: center; padding: 40px 0; font-size: 14px; }
448
+ .event-log { font-family: "SF Mono", "Fira Code", monospace; font-size: 12px; max-height: 200px; overflow-y: auto; padding: 12px; background: #050505; border-radius: 8px; }
449
+ .event-line { padding: 2px 0; color: var(--muted); }
450
+ .event-line .time { color: var(--accent); margin-right: 8px; }
451
+ .connected { color: var(--green); }
452
+ .toolbar { display: flex; gap: 8px; margin-bottom: 20px; }
453
+ .btn { padding: 8px 16px; border-radius: 8px; border: 1px solid var(--border); background: var(--card); color: var(--text); cursor: pointer; font-size: 13px; transition: all 0.15s; }
454
+ .btn:hover { background: #1a1a1a; border-color: var(--accent); }
455
+ .btn:disabled { opacity: 0.4; cursor: not-allowed; }
456
+ .btn-primary { background: var(--accent); border-color: var(--accent); color: white; }
457
+ .btn-primary:hover:not(:disabled) { opacity: 0.9; }
458
+ footer { text-align: center; padding: 32px 0 16px; color: var(--muted); font-size: 12px; }
459
+
460
+ /* Start Run Form */
461
+ .run-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
462
+ .run-form .form-group { display: flex; flex-direction: column; gap: 4px; }
463
+ .run-form .form-group.full { grid-column: 1 / -1; }
464
+ .run-form label { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px; }
465
+ .run-form input, .run-form select {
466
+ padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border);
467
+ background: #050505; color: var(--text); font-size: 13px; font-family: inherit;
468
+ }
469
+ .run-form input:focus, .run-form select:focus { outline: none; border-color: var(--accent); }
470
+ .run-form .form-actions { grid-column: 1 / -1; display: flex; gap: 8px; margin-top: 4px; }
471
+
472
+ /* Stage Progress */
473
+ .stage-pipeline { display: flex; align-items: center; gap: 0; margin: 16px 0; overflow-x: auto; padding-bottom: 4px; }
474
+ .stage-dot { display: flex; align-items: center; gap: 0; white-space: nowrap; }
475
+ .stage-dot .dot {
476
+ width: 10px; height: 10px; border-radius: 50%; background: var(--border);
477
+ flex-shrink: 0; transition: background 0.3s;
478
+ }
479
+ .stage-dot .dot.active { background: var(--accent); animation: pulse 1.5s infinite; }
480
+ .stage-dot .dot.done { background: var(--green); }
481
+ .stage-dot .dot.error { background: var(--red); }
482
+ .stage-dot .label { font-size: 11px; color: var(--muted); margin-left: 4px; margin-right: 4px; }
483
+ .stage-dot .label.active { color: var(--accent); font-weight: 600; }
484
+ .stage-dot .label.done { color: var(--green); }
485
+ .stage-connector { width: 16px; height: 1px; background: var(--border); flex-shrink: 0; }
486
+ .stage-connector.done { background: var(--green); }
487
+
488
+ /* Task Results */
489
+ .task-results { margin-top: 12px; }
490
+ .task-result { display: flex; align-items: center; gap: 8px; padding: 6px 0; border-bottom: 1px solid var(--border); font-size: 13px; }
491
+ .task-result:last-child { border-bottom: none; }
492
+ .task-result .icon { font-size: 14px; }
493
+ .task-result a { color: var(--accent); text-decoration: none; }
494
+ .task-result a:hover { text-decoration: underline; }
495
+ .task-result .meta { color: var(--muted); font-size: 12px; margin-left: auto; }
496
+
497
+ .hidden { display: none !important; }
498
+ </style>
499
+ </head>
500
+ <body>
501
+ <div class="container">
502
+ <header>
503
+ <h1><span>OAC</span> Dashboard</h1>
504
+ <div>
505
+ <span id="status-badge" class="badge badge-idle">idle</span>
506
+ <span id="sse-indicator" style="margin-left: 8px; font-size: 11px; color: var(--muted);">connecting...</span>
507
+ </div>
508
+ </header>
509
+
510
+ <!-- Start Run Form -->
511
+ <div id="run-form-card" class="card" style="margin-bottom: 20px;">
512
+ <h2>Start Run</h2>
513
+ <div class="run-form">
514
+ <div class="form-group full">
515
+ <label for="run-repo">Repository (owner/repo or GitHub URL)</label>
516
+ <input type="text" id="run-repo" placeholder="e.g. Open330/open-agent-contribution" />
517
+ </div>
518
+ <div class="form-group">
519
+ <label for="run-provider">Agent Provider</label>
520
+ <select id="run-provider">
521
+ <option value="codex-cli">Codex CLI</option>
522
+ <option value="claude-code">Claude Code</option>
523
+ </select>
524
+ </div>
525
+ <div class="form-group">
526
+ <label for="run-tokens-mode">Token Budget</label>
527
+ <select id="run-tokens-mode" onchange="toggleTokenInput()">
528
+ <option value="fixed">Fixed</option>
529
+ <option value="unlimited">Unlimited (until rate-limited)</option>
530
+ </select>
531
+ </div>
532
+ <div class="form-group" id="run-tokens-value-group">
533
+ <label for="run-tokens">Token Amount</label>
534
+ <input type="number" id="run-tokens" value="100000" min="1000" step="1000" />
535
+ </div>
536
+ <div class="form-group">
537
+ <label for="run-max-tasks">Max Tasks</label>
538
+ <input type="number" id="run-max-tasks" value="5" min="1" max="50" />
539
+ </div>
540
+ <div class="form-group">
541
+ <label for="run-concurrency">Concurrency</label>
542
+ <input type="number" id="run-concurrency" value="2" min="1" max="10" />
543
+ </div>
544
+ <div class="form-group">
545
+ <label for="run-source">Source Filter</label>
546
+ <select id="run-source">
547
+ <option value="">All sources</option>
548
+ <option value="github-issue">GitHub Issues</option>
549
+ <option value="lint">Lint warnings</option>
550
+ <option value="todo">TODO comments</option>
551
+ <option value="test-gap">Test gaps</option>
552
+ </select>
553
+ </div>
554
+ <div class="form-actions">
555
+ <button id="run-start-btn" class="btn btn-primary" onclick="startRun()">Start Run</button>
556
+ <span id="run-error" style="color: var(--red); font-size: 13px; align-self: center;"></span>
557
+ </div>
558
+ </div>
559
+ </div>
560
+
561
+ <!-- Run Progress (shown during active run) -->
562
+ <div id="run-progress-card" class="card hidden" style="margin-bottom: 20px;">
563
+ <h2>Run Progress</h2>
564
+ <div id="stage-pipeline" class="stage-pipeline"></div>
565
+ <div id="run-progress-stats" style="margin-top: 8px;">
566
+ <div class="stat-row"><span class="stat-label">Tasks discovered</span><span class="stat-value" id="prog-discovered">0</span></div>
567
+ <div class="stat-row"><span class="stat-label">Tasks selected</span><span class="stat-value" id="prog-selected">0</span></div>
568
+ <div class="stat-row"><span class="stat-label">Completed</span><span class="stat-value" id="prog-completed">0</span></div>
569
+ <div class="stat-row"><span class="stat-label">Failed</span><span class="stat-value" id="prog-failed">0</span></div>
570
+ <div class="stat-row"><span class="stat-label">PRs created</span><span class="stat-value" id="prog-prs">0</span></div>
571
+ <div class="stat-row"><span class="stat-label">Tokens used</span><span class="stat-value" id="prog-tokens">0</span></div>
572
+ </div>
573
+ <div id="task-results" class="task-results"></div>
574
+ </div>
575
+
576
+ <div class="toolbar">
577
+ <button class="btn" onclick="fetchStatus()">Refresh Status</button>
578
+ <button class="btn" onclick="fetchLogs()">Refresh Logs</button>
579
+ <button class="btn" onclick="fetchLeaderboard()">Refresh Leaderboard</button>
580
+ </div>
581
+
582
+ <div class="grid">
583
+ <div class="card">
584
+ <h2>Run Status</h2>
585
+ <div id="status-content">
586
+ <div class="empty">Loading...</div>
587
+ </div>
588
+ </div>
589
+
590
+ <div class="card">
591
+ <h2>Quick Stats</h2>
592
+ <div id="stats-content">
593
+ <div class="empty">Loading...</div>
594
+ </div>
595
+ </div>
596
+
597
+ <div class="card full-width">
598
+ <h2>Contribution Log</h2>
599
+ <div id="logs-content">
600
+ <div class="empty">Loading...</div>
601
+ </div>
602
+ </div>
603
+
604
+ <div class="card full-width">
605
+ <h2>Leaderboard</h2>
606
+ <div id="leaderboard-content">
607
+ <div class="empty">Loading...</div>
608
+ </div>
609
+ </div>
610
+
611
+ <div class="card full-width">
612
+ <h2>Event Stream</h2>
613
+ <div id="event-log" class="event-log">
614
+ <div class="event-line" style="color: var(--muted);">Connecting to SSE...</div>
615
+ </div>
616
+ </div>
617
+ </div>
618
+
619
+ <footer>OAC v0.1.0 &mdash; Open Agent Contribution</footer>
620
+ </div>
621
+
622
+ <script>
623
+ const API = "";
624
+ const STAGES = ["resolving","cloning","scanning","estimating","planning","executing","creating-pr","tracking","completed"];
625
+ let activeRunId = null;
626
+
627
+ function formatDate(iso) {
628
+ if (!iso) return "-";
629
+ try { return new Date(iso).toLocaleString(); } catch { return iso; }
630
+ }
631
+
632
+ // ---- Start Run ----
633
+
634
+ function toggleTokenInput() {
635
+ const mode = document.getElementById("run-tokens-mode").value;
636
+ const group = document.getElementById("run-tokens-value-group");
637
+ if (mode === "unlimited") {
638
+ group.classList.add("hidden");
639
+ } else {
640
+ group.classList.remove("hidden");
641
+ }
642
+ }
643
+
644
+ async function startRun() {
645
+ const repo = document.getElementById("run-repo").value.trim();
646
+ const provider = document.getElementById("run-provider").value;
647
+ const tokensMode = document.getElementById("run-tokens-mode").value;
648
+ const tokens = tokensMode === "unlimited"
649
+ ? 9007199254740991
650
+ : parseInt(document.getElementById("run-tokens").value, 10);
651
+ const maxTasks = parseInt(document.getElementById("run-max-tasks").value, 10);
652
+ const concurrency = parseInt(document.getElementById("run-concurrency").value, 10) || 2;
653
+ const source = document.getElementById("run-source").value || undefined;
654
+ const errEl = document.getElementById("run-error");
655
+ const btn = document.getElementById("run-start-btn");
656
+
657
+ errEl.textContent = "";
658
+ if (!repo) { errEl.textContent = "Repository is required"; return; }
659
+ if (tokensMode !== "unlimited" && (!tokens || tokens < 1000)) { errEl.textContent = "Token budget must be >= 1000"; return; }
660
+
661
+ btn.disabled = true;
662
+ btn.textContent = "Starting...";
663
+
664
+ try {
665
+ const res = await fetch(API + "/api/v1/runs", {
666
+ method: "POST",
667
+ headers: { "Content-Type": "application/json" },
668
+ body: JSON.stringify({ repo, provider, tokens, maxTasks, concurrency, source }),
669
+ });
670
+ const data = await res.json();
671
+
672
+ if (!res.ok) {
673
+ errEl.textContent = data.error || "Failed to start run";
674
+ btn.disabled = false;
675
+ btn.textContent = "Start Run";
676
+ return;
677
+ }
678
+
679
+ activeRunId = data.runId;
680
+ showProgressCard();
681
+ } catch (e) {
682
+ errEl.textContent = "Network error: " + e.message;
683
+ btn.disabled = false;
684
+ btn.textContent = "Start Run";
685
+ }
686
+ }
687
+
688
+ function showProgressCard() {
689
+ document.getElementById("run-progress-card").classList.remove("hidden");
690
+ initStageList();
691
+ document.getElementById("task-results").innerHTML = "";
692
+ document.getElementById("prog-discovered").textContent = "0";
693
+ document.getElementById("prog-selected").textContent = "0";
694
+ document.getElementById("prog-completed").textContent = "0";
695
+ document.getElementById("prog-failed").textContent = "0";
696
+ document.getElementById("prog-prs").textContent = "0";
697
+ document.getElementById("prog-tokens").textContent = "0";
698
+
699
+ const badge = document.getElementById("status-badge");
700
+ badge.className = "badge badge-running";
701
+ badge.textContent = "running";
702
+ }
703
+
704
+ function initStageList() {
705
+ const pipeline = document.getElementById("stage-pipeline");
706
+ pipeline.innerHTML = "";
707
+ STAGES.forEach((stage, i) => {
708
+ const dot = document.createElement("div");
709
+ dot.className = "stage-dot";
710
+ dot.innerHTML = '<div class="dot" id="dot-' + stage + '"></div><span class="label" id="label-' + stage + '">' + stage + '</span>';
711
+ pipeline.appendChild(dot);
712
+ if (i < STAGES.length - 1) {
713
+ const conn = document.createElement("div");
714
+ conn.className = "stage-connector";
715
+ conn.id = "conn-" + stage;
716
+ pipeline.appendChild(conn);
717
+ }
718
+ });
719
+ }
720
+
721
+ function updateStage(currentStage) {
722
+ let reached = false;
723
+ STAGES.forEach((stage, i) => {
724
+ const dot = document.getElementById("dot-" + stage);
725
+ const label = document.getElementById("label-" + stage);
726
+ const conn = i < STAGES.length - 1 ? document.getElementById("conn-" + stage) : null;
727
+
728
+ if (!dot || !label) return;
729
+
730
+ if (stage === currentStage) {
731
+ reached = true;
732
+ dot.className = currentStage === "completed" ? "dot done" : "dot active";
733
+ label.className = currentStage === "completed" ? "label done" : "label active";
734
+ if (conn && currentStage === "completed") conn.className = "stage-connector done";
735
+ } else if (!reached) {
736
+ dot.className = "dot done";
737
+ label.className = "label done";
738
+ if (conn) conn.className = "stage-connector done";
739
+ } else {
740
+ dot.className = "dot";
741
+ label.className = "label";
742
+ if (conn) conn.className = "stage-connector";
743
+ }
744
+ });
745
+ }
746
+
747
+ function updateProgress(progress) {
748
+ document.getElementById("prog-discovered").textContent = progress.tasksDiscovered || 0;
749
+ document.getElementById("prog-selected").textContent = progress.tasksSelected || 0;
750
+ document.getElementById("prog-completed").textContent = progress.tasksCompleted || 0;
751
+ document.getElementById("prog-failed").textContent = progress.tasksFailed || 0;
752
+ document.getElementById("prog-prs").textContent = progress.prsCreated || 0;
753
+ document.getElementById("prog-tokens").textContent = (progress.tokensUsed || 0).toLocaleString();
754
+ }
755
+
756
+ function addTaskResult(data) {
757
+ const container = document.getElementById("task-results");
758
+ const div = document.createElement("div");
759
+ div.className = "task-result";
760
+ const icon = data.success ? "\\u2705" : "\\u274c";
761
+ let html = '<span class="icon">' + icon + '</span><span>' + escapeHtml(data.title) + '</span>';
762
+ if (data.prUrl) {
763
+ html += ' <a href="' + escapeHtml(data.prUrl) + '" target="_blank">PR \\u2197</a>';
764
+ }
765
+ html += '<span class="meta">' + (data.filesChanged || 0) + ' files</span>';
766
+ div.innerHTML = html;
767
+ container.appendChild(div);
768
+ }
769
+
770
+ function onRunCompleted(isError) {
771
+ const btn = document.getElementById("run-start-btn");
772
+ btn.disabled = false;
773
+ btn.textContent = "Start Run";
774
+ activeRunId = null;
775
+
776
+ const badge = document.getElementById("status-badge");
777
+ if (isError) {
778
+ badge.className = "badge badge-failed";
779
+ badge.textContent = "failed";
780
+ } else {
781
+ badge.className = "badge badge-completed";
782
+ badge.textContent = "completed";
783
+ }
784
+
785
+ // Refresh data
786
+ fetchStatus();
787
+ fetchLogs();
788
+ fetchLeaderboard();
789
+ }
790
+
791
+ function onRunError(errorMsg) {
792
+ const container = document.getElementById("task-results");
793
+ const div = document.createElement("div");
794
+ div.className = "task-result";
795
+ div.innerHTML = '<span class="icon">\\u274c</span><span style="color: var(--red);">Error: ' + escapeHtml(errorMsg) + '</span>';
796
+ container.appendChild(div);
797
+
798
+ // Mark failed stage
799
+ STAGES.forEach((stage) => {
800
+ const dot = document.getElementById("dot-" + stage);
801
+ if (dot && dot.className === "dot active") {
802
+ dot.className = "dot error";
803
+ }
804
+ });
805
+
806
+ onRunCompleted(true);
807
+ }
808
+
809
+ function escapeHtml(str) {
810
+ const div = document.createElement("div");
811
+ div.textContent = str || "";
812
+ return div.innerHTML;
813
+ }
814
+
815
+ // ---- Fetch functions ----
816
+
817
+ async function fetchStatus() {
818
+ try {
819
+ const res = await fetch(API + "/api/v1/status");
820
+ const data = await res.json();
821
+ const badge = document.getElementById("status-badge");
822
+
823
+ if (data.status === "running") {
824
+ badge.className = "badge badge-running";
825
+ badge.textContent = "running";
826
+ // Restore progress card if page was refreshed mid-run
827
+ if (!activeRunId) {
828
+ activeRunId = data.runId;
829
+ showProgressCard();
830
+ if (data.stage) updateStage(data.stage);
831
+ if (data.progress) updateProgress(data.progress);
832
+ }
833
+ } else if (data.status === "idle" && !activeRunId) {
834
+ badge.className = "badge badge-idle";
835
+ badge.textContent = "idle";
836
+ }
837
+
838
+ let html = "";
839
+ const displayKeys = ["status", "stage", "runId", "startedAt", "completedAt", "error"];
840
+ for (const key of displayKeys) {
841
+ if (data[key] !== undefined) {
842
+ html += '<div class="stat-row"><span class="stat-label">' + key + '</span><span class="stat-value">' + escapeHtml(String(data[key])) + '</span></div>';
843
+ }
844
+ }
845
+ if (!html) {
846
+ for (const [key, value] of Object.entries(data)) {
847
+ html += '<div class="stat-row"><span class="stat-label">' + key + '</span><span class="stat-value">' + escapeHtml(String(value)) + '</span></div>';
848
+ }
849
+ }
850
+ document.getElementById("status-content").innerHTML = html || '<div class="empty">No status data</div>';
851
+ } catch (e) {
852
+ document.getElementById("status-content").innerHTML = '<div class="empty">Failed to load status</div>';
853
+ }
854
+ }
855
+
856
+ async function fetchLogs() {
857
+ try {
858
+ const res = await fetch(API + "/api/v1/logs");
859
+ const data = await res.json();
860
+
861
+ if (!data.logs || data.logs.length === 0) {
862
+ document.getElementById("logs-content").innerHTML = '<div class="empty">No contributions yet. Run <code>oac run</code> to start contributing!</div>';
863
+ document.getElementById("stats-content").innerHTML = [
864
+ '<div class="stat-row"><span class="stat-label">Total Runs</span><span class="stat-value">0</span></div>',
865
+ '<div class="stat-row"><span class="stat-label">Total Tasks</span><span class="stat-value">0</span></div>',
866
+ '<div class="stat-row"><span class="stat-label">Total Tokens</span><span class="stat-value">0</span></div>',
867
+ '<div class="stat-row"><span class="stat-label">PRs Created</span><span class="stat-value">0</span></div>',
868
+ ].join("");
869
+ return;
870
+ }
871
+
872
+ const totalRuns = data.logs.length;
873
+ const totalTasks = data.logs.reduce((s, l) => s + (l.tasks?.length || 0), 0);
874
+ const totalTokens = data.logs.reduce((s, l) => s + (l.budget?.totalTokensUsed || 0), 0);
875
+ const totalPRs = data.logs.reduce((s, l) => s + (l.tasks?.filter(t => t.pr).length || 0), 0);
876
+
877
+ document.getElementById("stats-content").innerHTML = [
878
+ '<div class="stat-row"><span class="stat-label">Total Runs</span><span class="stat-value">' + totalRuns + '</span></div>',
879
+ '<div class="stat-row"><span class="stat-label">Total Tasks</span><span class="stat-value">' + totalTasks + '</span></div>',
880
+ '<div class="stat-row"><span class="stat-label">Total Tokens</span><span class="stat-value">' + totalTokens.toLocaleString() + '</span></div>',
881
+ '<div class="stat-row"><span class="stat-label">PRs Created</span><span class="stat-value">' + totalPRs + '</span></div>',
882
+ ].join("");
883
+
884
+ let html = '<table><thead><tr><th>Date</th><th>Repo</th><th>Tasks</th><th>Tokens</th><th>Agent</th></tr></thead><tbody>';
885
+ for (const log of data.logs.slice(0, 20)) {
886
+ html += '<tr>';
887
+ html += '<td>' + formatDate(log.timestamp) + '</td>';
888
+ html += '<td>' + escapeHtml(log.repo?.fullName || log.repoFullName || "-") + '</td>';
889
+ html += '<td>' + (log.tasks?.length || 0) + '</td>';
890
+ html += '<td>' + (log.budget?.totalTokensUsed || 0).toLocaleString() + '</td>';
891
+ html += '<td>' + escapeHtml(log.budget?.provider || log.agentProvider || "-") + '</td>';
892
+ html += '</tr>';
893
+ }
894
+ html += '</tbody></table>';
895
+ document.getElementById("logs-content").innerHTML = html;
896
+ } catch (e) {
897
+ document.getElementById("logs-content").innerHTML = '<div class="empty">Failed to load logs</div>';
898
+ }
899
+ }
900
+
901
+ async function fetchLeaderboard() {
902
+ try {
903
+ const res = await fetch(API + "/api/v1/leaderboard");
904
+ const data = await res.json();
905
+
906
+ if (!data.entries || data.entries.length === 0) {
907
+ document.getElementById("leaderboard-content").innerHTML = '<div class="empty">No contributors yet</div>';
908
+ return;
909
+ }
910
+
911
+ let html = '<table><thead><tr><th>#</th><th>User</th><th>Tasks</th><th>Tokens</th><th>PRs</th><th>Last Active</th></tr></thead><tbody>';
912
+ data.entries.forEach((entry, i) => {
913
+ html += '<tr>';
914
+ html += '<td class="rank">' + (i + 1) + '</td>';
915
+ html += '<td>' + escapeHtml(entry.githubUsername || "anonymous") + '</td>';
916
+ html += '<td>' + (entry.totalTasksCompleted || 0) + '</td>';
917
+ html += '<td>' + (entry.totalTokensDonated || 0).toLocaleString() + '</td>';
918
+ html += '<td>' + (entry.totalPRsCreated || 0) + '</td>';
919
+ html += '<td>' + formatDate(entry.lastContribution) + '</td>';
920
+ html += '</tr>';
921
+ });
922
+ html += '</tbody></table>';
923
+ document.getElementById("leaderboard-content").innerHTML = html;
924
+ } catch (e) {
925
+ document.getElementById("leaderboard-content").innerHTML = '<div class="empty">Failed to load leaderboard</div>';
926
+ }
927
+ }
928
+
929
+ // ---- SSE Connection ----
930
+
931
+ function connectSSE() {
932
+ const indicator = document.getElementById("sse-indicator");
933
+ const log = document.getElementById("event-log");
934
+
935
+ const es = new EventSource(API + "/api/v1/events");
936
+
937
+ es.addEventListener("connected", (e) => {
938
+ indicator.innerHTML = '<span class="connected">\\u25cf connected</span>';
939
+ addEventLine(log, "connected", "SSE stream connected");
940
+ });
941
+
942
+ es.addEventListener("heartbeat", (e) => {
943
+ // Silent heartbeat \u2014 no log spam
944
+ });
945
+
946
+ // Run events
947
+ es.addEventListener("run:stage", (e) => {
948
+ try {
949
+ const data = JSON.parse(e.data);
950
+ updateStage(data.stage);
951
+ addEventLine(log, "stage", data.message || data.stage);
952
+ } catch {}
953
+ });
954
+
955
+ es.addEventListener("run:progress", (e) => {
956
+ try {
957
+ const data = JSON.parse(e.data);
958
+ updateProgress(data.progress);
959
+ } catch {}
960
+ });
961
+
962
+ es.addEventListener("run:task-start", (e) => {
963
+ try {
964
+ const data = JSON.parse(e.data);
965
+ addEventLine(log, "task", "Starting: " + data.title);
966
+ } catch {}
967
+ });
968
+
969
+ es.addEventListener("run:task-done", (e) => {
970
+ try {
971
+ const data = JSON.parse(e.data);
972
+ const status = data.success ? "OK" : "FAILED";
973
+ let msg = "[" + status + "] " + data.title;
974
+ if (data.prUrl) msg += " - PR: " + data.prUrl;
975
+ addEventLine(log, "task", msg);
976
+ addTaskResult(data);
977
+ } catch {}
978
+ });
979
+
980
+ es.addEventListener("run:completed", (e) => {
981
+ try {
982
+ addEventLine(log, "completed", "Run finished successfully");
983
+ updateStage("completed");
984
+ onRunCompleted(false);
985
+ } catch {}
986
+ });
987
+
988
+ es.addEventListener("run:error", (e) => {
989
+ try {
990
+ const data = JSON.parse(e.data);
991
+ addEventLine(log, "error", data.error);
992
+ onRunError(data.error);
993
+ } catch {}
994
+ });
995
+
996
+ es.onerror = () => {
997
+ indicator.innerHTML = '<span style="color: var(--red);">\\u25cf disconnected</span>';
998
+ addEventLine(log, "error", "SSE disconnected, reconnecting...");
999
+ };
1000
+
1001
+ es.onmessage = (e) => {
1002
+ addEventLine(log, "message", e.data);
1003
+ };
1004
+ }
1005
+
1006
+ function addEventLine(container, type, data) {
1007
+ const now = new Date().toLocaleTimeString();
1008
+ const line = document.createElement("div");
1009
+ line.className = "event-line";
1010
+ line.innerHTML = '<span class="time">' + now + '</span> <strong>' + type + '</strong> ' + escapeHtml(String(data));
1011
+ container.appendChild(line);
1012
+ container.scrollTop = container.scrollHeight;
1013
+
1014
+ while (container.children.length > 100) {
1015
+ container.removeChild(container.firstChild);
1016
+ }
1017
+ }
1018
+
1019
+ // ---- Init ----
1020
+ fetchStatus();
1021
+ fetchLogs();
1022
+ fetchLeaderboard();
1023
+ connectSSE();
1024
+
1025
+ setInterval(() => { fetchStatus(); fetchLogs(); }, 30000);
1026
+ </script>
1027
+ </body>
1028
+ </html>`;
1029
+ }
1030
+
1031
+ // src/server.ts
1032
+ var DEFAULT_OPTIONS = {
1033
+ port: 3141,
1034
+ host: "0.0.0.0",
1035
+ openBrowser: false,
1036
+ oacDir: process.cwd()
1037
+ };
1038
+ var currentRun = null;
1039
+ var sseClients = /* @__PURE__ */ new Set();
1040
+ function broadcastEvent(event) {
1041
+ for (const send of sseClients) {
1042
+ try {
1043
+ send(event);
1044
+ } catch {
1045
+ }
1046
+ }
1047
+ }
1048
+ async function readContributionLogs(oacDir) {
1049
+ const contributionsPath = resolve(oacDir, ".oac", "contributions");
1050
+ let entries;
1051
+ try {
1052
+ entries = await readdir(contributionsPath, { withFileTypes: true, encoding: "utf8" });
1053
+ } catch {
1054
+ return [];
1055
+ }
1056
+ const files = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name).sort();
1057
+ const logs = [];
1058
+ for (const fileName of files) {
1059
+ try {
1060
+ const content = await readFile(resolve(contributionsPath, fileName), "utf8");
1061
+ const parsed = contributionLogSchema.safeParse(JSON.parse(content));
1062
+ if (parsed.success) {
1063
+ logs.push(parsed.data);
1064
+ }
1065
+ } catch {
1066
+ }
1067
+ }
1068
+ return logs;
1069
+ }
1070
+ async function readRunStatus(oacDir) {
1071
+ if (currentRun) {
1072
+ return currentRun;
1073
+ }
1074
+ try {
1075
+ const content = await readFile(resolve(oacDir, ".oac", "status.json"), "utf8");
1076
+ return JSON.parse(content);
1077
+ } catch {
1078
+ return { status: "idle", message: "No active runs" };
1079
+ }
1080
+ }
1081
+ async function createDashboardServer(options = {}) {
1082
+ const opts = { ...DEFAULT_OPTIONS, ...options };
1083
+ const app = Fastify({ logger: false });
1084
+ await app.register(cors, { origin: true });
1085
+ app.get("/", async (_request, reply) => {
1086
+ reply.type("text/html").send(renderDashboardHtml(opts.port));
1087
+ });
1088
+ app.get("/api/v1/status", async () => {
1089
+ return readRunStatus(opts.oacDir);
1090
+ });
1091
+ app.get("/api/v1/logs", async () => {
1092
+ const logs = await readContributionLogs(opts.oacDir);
1093
+ return { count: logs.length, logs };
1094
+ });
1095
+ app.get("/api/v1/leaderboard", async () => {
1096
+ const leaderboard = await buildLeaderboard(opts.oacDir);
1097
+ return leaderboard;
1098
+ });
1099
+ app.get("/api/v1/config", async () => {
1100
+ return {
1101
+ oacDir: opts.oacDir,
1102
+ port: opts.port,
1103
+ host: opts.host
1104
+ };
1105
+ });
1106
+ app.post("/api/v1/runs", async (request, reply) => {
1107
+ if (currentRun && currentRun.status === "running") {
1108
+ reply.code(409).send({ error: "A run is already in progress", runId: currentRun.runId });
1109
+ return;
1110
+ }
1111
+ const body = request.body;
1112
+ if (!body?.repo || !body.provider || !body.tokens) {
1113
+ reply.code(400).send({ error: "Missing required fields: repo, provider, tokens" });
1114
+ return;
1115
+ }
1116
+ const config = {
1117
+ repo: body.repo,
1118
+ provider: body.provider,
1119
+ tokens: body.tokens,
1120
+ concurrency: typeof body.concurrency === "number" ? body.concurrency : void 0,
1121
+ maxTasks: body.maxTasks,
1122
+ source: body.source
1123
+ };
1124
+ const runId = randomUUID2();
1125
+ currentRun = {
1126
+ runId,
1127
+ status: "running",
1128
+ stage: "resolving",
1129
+ config,
1130
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1131
+ progress: {
1132
+ tasksDiscovered: 0,
1133
+ tasksSelected: 0,
1134
+ tasksCompleted: 0,
1135
+ tasksFailed: 0,
1136
+ prsCreated: 0,
1137
+ tokensUsed: 0,
1138
+ prUrls: []
1139
+ }
1140
+ };
1141
+ executePipeline(config, (event) => {
1142
+ if (event.type === "run:stage" && currentRun) {
1143
+ currentRun.stage = event.stage;
1144
+ }
1145
+ if (event.type === "run:progress" && currentRun) {
1146
+ currentRun.progress = event.progress;
1147
+ }
1148
+ if (event.type === "run:completed" && currentRun) {
1149
+ currentRun.status = "completed";
1150
+ currentRun.completedAt = (/* @__PURE__ */ new Date()).toISOString();
1151
+ }
1152
+ if (event.type === "run:error" && currentRun) {
1153
+ currentRun.status = "failed";
1154
+ currentRun.error = event.error;
1155
+ currentRun.completedAt = (/* @__PURE__ */ new Date()).toISOString();
1156
+ }
1157
+ broadcastEvent(event);
1158
+ }).catch((err) => {
1159
+ if (currentRun) {
1160
+ currentRun.status = "failed";
1161
+ currentRun.error = err instanceof Error ? err.message : String(err);
1162
+ currentRun.completedAt = (/* @__PURE__ */ new Date()).toISOString();
1163
+ }
1164
+ });
1165
+ reply.code(202).send({ runId, status: "started" });
1166
+ });
1167
+ app.get("/api/v1/events", async (_request, reply) => {
1168
+ reply.raw.writeHead(200, {
1169
+ "Content-Type": "text/event-stream",
1170
+ "Cache-Control": "no-cache",
1171
+ Connection: "keep-alive"
1172
+ });
1173
+ reply.raw.write(
1174
+ `event: connected
1175
+ data: ${JSON.stringify({ time: (/* @__PURE__ */ new Date()).toISOString() })}
1176
+
1177
+ `
1178
+ );
1179
+ const sendEvent = (event) => {
1180
+ reply.raw.write(`event: ${event.type}
1181
+ data: ${JSON.stringify(event)}
1182
+
1183
+ `);
1184
+ };
1185
+ sseClients.add(sendEvent);
1186
+ const interval = setInterval(() => {
1187
+ reply.raw.write(
1188
+ `event: heartbeat
1189
+ data: ${JSON.stringify({ time: (/* @__PURE__ */ new Date()).toISOString() })}
1190
+
1191
+ `
1192
+ );
1193
+ }, 1e4);
1194
+ _request.raw.on("close", () => {
1195
+ clearInterval(interval);
1196
+ sseClients.delete(sendEvent);
1197
+ });
1198
+ });
1199
+ return app;
1200
+ }
1201
+ async function startDashboard(options = {}) {
1202
+ const opts = { ...DEFAULT_OPTIONS, ...options };
1203
+ const app = await createDashboardServer(opts);
1204
+ await app.listen({ port: opts.port, host: opts.host });
1205
+ const url = opts.host === "0.0.0.0" ? `http://localhost:${opts.port}` : `http://${opts.host}:${opts.port}`;
1206
+ console.log(`
1207
+ \u{1F680} OAC Dashboard running at ${url}`);
1208
+ console.log(` Network: http://0.0.0.0:${opts.port}`);
1209
+ console.log(`
1210
+ API: ${url}/api/v1/status`);
1211
+ console.log(` SSE: ${url}/api/v1/events
1212
+ `);
1213
+ if (opts.openBrowser) {
1214
+ const { exec } = await import("child_process");
1215
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
1216
+ exec(`${command} ${url}`);
1217
+ }
1218
+ }
1219
+ export {
1220
+ createDashboardServer,
1221
+ renderDashboardHtml,
1222
+ startDashboard
1223
+ };
1224
+ //# sourceMappingURL=index.js.map