This repository was archived by the owner on Oct 4, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
650 lines (553 loc) · 18.4 KB
/
Copy pathserver.ts
File metadata and controls
650 lines (553 loc) · 18.4 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
import { Database } from "bun:sqlite";
import { Buffer } from "node:buffer";
import { existsSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { extname, join, normalize } from "node:path";
const PORT = Number(process.env.OCV_PORT) || 3456;
const DB_PATH =
process.env.OCV_DB_PATH ||
join(homedir(), ".local", "share", "opencode", "opencode.db");
const PUBLIC_DIR = join(import.meta.dir, "public");
if (!existsSync(DB_PATH)) {
console.error(`OpenCode database not found at: ${DB_PATH}`);
process.exit(1);
}
let db: Database;
try {
db = new Database(DB_PATH, { readonly: true });
} catch (error) {
console.error("Failed to open OpenCode database in read-only mode:", error);
process.exit(1);
}
type JsonObject = Record<string, unknown>;
type ProjectRow = {
id: string;
worktree: string | null;
name: string | null;
icon_color: string | null;
time_created: number | string | null;
time_updated: number | string | null;
};
type SessionRow = {
id: string;
project_id?: string | null;
project_name?: string | null;
project_worktree?: string | null;
title: string | null;
summary: string | null;
directory: string | null;
time_created: number | string | null;
time_updated: number | string | null;
};
type Scope = "all" | "user" | "assistant";
type SessionDetailRow = {
id: string;
project_id: string | null;
parent_id: string | null;
title: string | null;
summary: string | null;
directory: string | null;
time_created: number | string | null;
time_updated: number | string | null;
};
type MessagePartJoinRow = {
id: string;
time_created: number | string | null;
time_updated: number | string | null;
message_data: string | null;
part_id: string | null;
part_data: string | null;
part_time: number | string | null;
};
const corsHeaders: HeadersInit = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
const allowedPartTypes = new Set([
"text",
"reasoning",
"tool",
"patch",
"file",
"agent",
"step-finish",
"step-start",
"snapshot",
"compaction",
"retry",
]);
const projectStmt = db.query<ProjectRow>(
"SELECT id, worktree, name, icon_color, time_created, time_updated FROM project ORDER BY time_updated DESC",
);
const sessionsCountNoQueryStmt = db.query<{ total: number }>(
`SELECT COUNT(*) as total
FROM session
WHERE project_id = ? AND parent_id IS NULL`,
);
const projectSessionsNoQueryStmt = db.query<SessionRow>(
`SELECT id, title, NULL as summary, directory, time_created, time_updated
FROM session
WHERE project_id = ? AND parent_id IS NULL
ORDER BY time_updated DESC, id DESC
LIMIT ? OFFSET ?`,
);
function buildSearchStatements(scope: Scope) {
const roleClause =
scope === "all" ? "" : `AND json_extract(m.data, '$.role') = '${scope}'`;
const commonWhere = `
WHERE s.project_id = ?
AND s.parent_id IS NULL
AND (
instr(lower(s.title), ?) > 0
OR EXISTS (
SELECT 1
FROM message m
JOIN part p ON p.message_id = m.id
WHERE m.session_id = s.id
AND json_extract(p.data, '$.type') IN ('text','reasoning')
AND instr(lower(json_extract(p.data, '$.text')), ?) > 0
${roleClause}
)
)
`;
return {
list: db.query<SessionRow>(
`SELECT s.id, s.title, NULL as summary, s.directory, s.time_created, s.time_updated
FROM session s
${commonWhere}
ORDER BY s.time_updated DESC, s.id DESC
LIMIT ? OFFSET ?`,
),
count: db.query<{ total: number }>(
`SELECT COUNT(*) as total
FROM session s
${commonWhere}`,
),
};
}
const searchStmts: Record<Scope, ReturnType<typeof buildSearchStatements>> = {
all: buildSearchStatements("all"),
user: buildSearchStatements("user"),
assistant: buildSearchStatements("assistant"),
};
function buildGlobalSearchStatements(scope: Scope) {
const roleClause =
scope === "all" ? "" : `AND json_extract(m.data, '$.role') = '${scope}'`;
const commonWhere = `
WHERE s.parent_id IS NULL
AND (
instr(lower(s.title), ?) > 0
OR EXISTS (
SELECT 1
FROM message m
JOIN part p ON p.message_id = m.id
WHERE m.session_id = s.id
AND json_extract(p.data, '$.type') IN ('text','reasoning')
AND instr(lower(json_extract(p.data, '$.text')), ?) > 0
${roleClause}
)
)
`;
return {
list: db.query<SessionRow>(
`SELECT s.id, s.project_id, project.name as project_name, project.worktree as project_worktree,
s.title, NULL as summary, s.directory, s.time_created, s.time_updated
FROM session s
LEFT JOIN project ON project.id = s.project_id
${commonWhere}
ORDER BY s.time_updated DESC, s.id DESC
LIMIT ? OFFSET ?`,
),
count: db.query<{ total: number }>(
`SELECT COUNT(*) as total
FROM session s
${commonWhere}`,
),
};
}
const globalSearchStmts: Record<Scope, ReturnType<typeof buildGlobalSearchStatements>> = {
all: buildGlobalSearchStatements("all"),
user: buildGlobalSearchStatements("user"),
assistant: buildGlobalSearchStatements("assistant"),
};
const sessionStmt = db.query<SessionDetailRow>(
"SELECT id, project_id, parent_id, title, NULL as summary, directory, time_created, time_updated FROM session WHERE id = ?",
);
const sessionMessagesStmt = db.query<MessagePartJoinRow>(
`SELECT m.id, m.time_created, m.time_updated, m.data as message_data,
p.id as part_id, p.data as part_data, p.time_created as part_time
FROM message m
LEFT JOIN part p ON p.message_id = m.id
WHERE m.session_id = ?
ORDER BY m.time_created ASC, p.time_created ASC`,
);
const subagentsStmt = db.query<SessionRow>(
`SELECT id, title, NULL as summary, NULL as directory, time_created, time_updated
FROM session
WHERE parent_id = ?
ORDER BY time_created ASC`,
);
const partImageStmt = db.query<{ data: string }>("SELECT data FROM part WHERE id = ?");
function parseJSON(value: string | null): JsonObject | null {
if (!value) return null;
try {
const parsed = JSON.parse(value) as unknown;
if (parsed && typeof parsed === "object") return parsed as JsonObject;
return null;
} catch {
return null;
}
}
function getString(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
function isBase64ImageData(value: unknown): boolean {
return typeof value === "string" && value.startsWith("data:image");
}
function sanitizePartData(partData: JsonObject, partType: string): JsonObject {
const sanitizedPartData: JsonObject = { ...partData };
if (partType === "file") {
const fileUrl = getString(sanitizedPartData.url);
if (fileUrl && fileUrl.startsWith("data:image")) {
sanitizedPartData.url = "[base64-image]";
sanitizedPartData.hasImage = true;
}
}
if (partType === "tool") {
const state = sanitizedPartData.state;
if (state && typeof state === "object" && !Array.isArray(state)) {
const stateObject = state as JsonObject;
const attachments = stateObject.attachments;
if (Array.isArray(attachments)) {
const hasBase64ImageAttachment = attachments.some((attachment) => {
if (isBase64ImageData(attachment)) {
return true;
}
if (attachment && typeof attachment === "object") {
const attachmentObject = attachment as JsonObject;
return (
isBase64ImageData(attachmentObject.url) ||
isBase64ImageData(attachmentObject.data) ||
isBase64ImageData(attachmentObject.content)
);
}
return false;
});
if (hasBase64ImageAttachment) {
sanitizedPartData.state = {
...stateObject,
attachments: [],
};
sanitizedPartData.hasAttachments = true;
}
}
}
}
return sanitizedPartData;
}
function extractPartImageDataUri(partData: JsonObject): string | null {
const url = partData.url;
if (typeof url === "string" && url.startsWith("data:image")) {
return url;
}
const state = partData.state;
if (!state || typeof state !== "object" || Array.isArray(state)) {
return null;
}
const attachments = (state as JsonObject).attachments;
if (!Array.isArray(attachments)) {
return null;
}
for (const attachment of attachments) {
if (typeof attachment === "string" && attachment.startsWith("data:image")) {
return attachment;
}
if (attachment && typeof attachment === "object" && !Array.isArray(attachment)) {
const attachmentUrl = (attachment as JsonObject).url;
if (typeof attachmentUrl === "string" && attachmentUrl.startsWith("data:image")) {
return attachmentUrl;
}
}
}
return null;
}
function getPagination(url: URL): { page: number; limit: number; offset: number } {
const pageParam = Number(url.searchParams.get("page") ?? "1");
const limitParam = Number(url.searchParams.get("limit") ?? "50");
const page = Number.isFinite(pageParam) && pageParam > 0 ? Math.floor(pageParam) : 1;
const limit =
Number.isFinite(limitParam) && limitParam > 0 ? Math.min(Math.floor(limitParam), 200) : 50;
return { page, limit, offset: (page - 1) * limit };
}
function normalizeScope(raw: string | null): Scope {
const value = (raw ?? "all").toLowerCase();
return value === "user" || value === "assistant" ? value : "all";
}
function json(data: unknown, status = 200): Response {
return new Response(JSON.stringify(data), {
status,
headers: {
...corsHeaders,
"Content-Type": "application/json; charset=utf-8",
},
});
}
function withCors(response: Response): Response {
const headers = new Headers(response.headers);
for (const [key, value] of Object.entries(corsHeaders)) {
headers.set(key, value);
}
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}
function notFound(message = "Not found"): Response {
return json({ error: message }, 404);
}
function badRequest(message: string): Response {
return json({ error: message }, 400);
}
async function serveStatic(pathname: string): Promise<Response> {
const relativePath = pathname === "/" ? "index.html" : pathname.slice(1);
const safePath = normalize(relativePath).replace(/^\.{2}(\/|\\|$)/, "");
const filePath = join(PUBLIC_DIR, safePath);
if (!filePath.startsWith(PUBLIC_DIR)) {
return notFound();
}
if (!existsSync(filePath) || !statSync(filePath).isFile()) {
return notFound();
}
const file = Bun.file(filePath);
if (extname(filePath) === ".html") {
return withCors(
new Response(file, {
headers: {
"Content-Type": "text/html; charset=utf-8",
},
}),
);
}
return withCors(new Response(file));
}
const server = Bun.serve({
port: PORT,
async fetch(req) {
const url = new URL(req.url);
const { pathname } = url;
if (req.method === "OPTIONS") {
return new Response(null, { status: 204, headers: corsHeaders });
}
if (req.method !== "GET") {
return json({ error: "Method not allowed" }, 405);
}
try {
const partImageMatch = pathname.match(/^\/api\/parts\/([^/]+)\/image$/);
if (partImageMatch) {
const partId = decodeURIComponent(partImageMatch[1]);
const row = partImageStmt.get(partId) as { data: string } | null;
if (!row?.data) {
return notFound("Part not found");
}
const partData = parseJSON(row.data);
if (!partData) {
return notFound("Invalid part data");
}
const dataUri = extractPartImageDataUri(partData);
if (!dataUri) {
return notFound("No image in part");
}
const match = dataUri.match(/^data:(image\/[^;]+);base64,([\s\S]+)$/);
if (!match) {
return notFound("Invalid image data");
}
const mime = match[1];
const base64Payload = match[2].replace(/\s+/g, "");
const buffer = Buffer.from(base64Payload, "base64");
if (!buffer.length) {
return notFound("Invalid image data");
}
return new Response(buffer, {
headers: {
...corsHeaders,
"Content-Type": mime,
"Cache-Control": "public, max-age=86400",
},
});
}
if (pathname === "/api/projects") {
const projects = projectStmt.all();
return json({ projects });
}
const projectSessionsMatch = pathname.match(/^\/api\/projects\/([^/]+)\/sessions$/);
if (projectSessionsMatch) {
const projectId = decodeURIComponent(projectSessionsMatch[1]);
const { page, limit, offset } = getPagination(url);
const qRaw = (url.searchParams.get("q") ?? "").trim();
const scope = normalizeScope(url.searchParams.get("scope"));
if (!qRaw) {
const totalRow = sessionsCountNoQueryStmt.get(projectId) as { total: number } | null;
const sessions = projectSessionsNoQueryStmt.all(projectId, limit, offset);
return json({
projectId,
page,
limit,
total: totalRow?.total ?? 0,
sessions,
q: "",
scope,
});
}
const needle = qRaw.toLowerCase();
const stmts = searchStmts[scope];
const totalRow = stmts.count.get(projectId, needle, needle) as { total: number } | null;
const sessions = stmts.list.all(projectId, needle, needle, limit, offset);
return json({
projectId,
page,
limit,
total: totalRow?.total ?? 0,
sessions,
q: qRaw,
scope,
});
}
if (pathname === "/api/sessions/search") {
const { page, limit, offset } = getPagination(url);
const qRaw = (url.searchParams.get("q") ?? "").trim();
const scope = normalizeScope(url.searchParams.get("scope"));
if (!qRaw) {
return json({
page,
limit,
total: 0,
sessions: [],
q: "",
scope,
});
}
const needle = qRaw.toLowerCase();
const stmts = globalSearchStmts[scope];
const totalRow = stmts.count.get(needle, needle) as { total: number } | null;
const sessions = stmts.list.all(needle, needle, limit, offset);
return json({
page,
limit,
total: totalRow?.total ?? 0,
sessions,
q: qRaw,
scope,
});
}
const sessionDetailMatch = pathname.match(/^\/api\/sessions\/([^/]+)$/);
if (sessionDetailMatch) {
const sessionId = decodeURIComponent(sessionDetailMatch[1]);
const session = sessionStmt.get(sessionId) as SessionDetailRow | null;
if (!session) {
return notFound("Session not found");
}
const rows = sessionMessagesStmt.all(sessionId);
const subagentRows = subagentsStmt.all(sessionId);
const messageMap = new Map<
string,
{
id: string;
_type?: "subagent";
time_created: number | string | null;
time_updated: number | string | null;
title?: string | null;
summary?: string | null;
role: string | null;
modelID: string | null;
providerID: string | null;
agent: string | null;
cost: number | null;
tokens: unknown;
parts: Array<
{
id: string;
time_created: number | string | null;
} & JsonObject
>;
}
>();
for (const row of rows) {
if (!messageMap.has(row.id)) {
const messageData = parseJSON(row.message_data);
const costValue = messageData?.cost;
messageMap.set(row.id, {
id: row.id,
time_created: row.time_created,
time_updated: row.time_updated,
role: getString(messageData?.role),
modelID: getString(messageData?.modelID),
providerID: getString(messageData?.providerID),
agent: getString(messageData?.agent),
cost: typeof costValue === "number" ? costValue : null,
tokens: messageData?.tokens ?? null,
parts: [],
});
}
if (!row.part_id || !row.part_data) {
continue;
}
const partData = parseJSON(row.part_data);
const partType = getString(partData?.type);
if (!partData || !partType || !allowedPartTypes.has(partType)) {
continue;
}
const message = messageMap.get(row.id);
if (!message) continue;
const sanitizedPartData = sanitizePartData(partData, partType);
message.parts.push({
id: row.part_id,
time_created: row.part_time,
...sanitizedPartData,
});
}
const messages = Array.from(messageMap.values());
for (const sub of subagentRows) {
messages.push({
id: sub.id,
_type: "subagent",
time_created: sub.time_created,
time_updated: sub.time_updated,
title: sub.title,
summary: sub.summary,
role: null,
modelID: null,
providerID: null,
agent: null,
cost: null,
tokens: null,
parts: [],
});
}
messages.sort((a, b) => {
const taValue = Number(a.time_created);
const tbValue = Number(b.time_created);
const ta = Number.isFinite(taValue) ? taValue : 0;
const tb = Number.isFinite(tbValue) ? tbValue : 0;
return ta - tb;
});
return json({
session,
messages,
});
}
const subagentsMatch = pathname.match(/^\/api\/sessions\/([^/]+)\/subagents$/);
if (subagentsMatch) {
const sessionId = decodeURIComponent(subagentsMatch[1]);
const subagents = subagentsStmt.all(sessionId);
return json({ sessionId, subagents });
}
return await serveStatic(pathname);
} catch (error) {
console.error("Request error:", error);
return json({ error: "Internal server error" }, 500);
}
},
});
console.log(`OpenCode Viewer running at http://localhost:${server.port}`);