harness uniformization

This commit is contained in:
2026-02-17 20:37:40 +00:00
parent 74e98e95e1
commit 3733e99ba8
17 changed files with 338 additions and 356 deletions
+268
View File
@@ -0,0 +1,268 @@
import { Hono } from 'hono';
import { mkdir, readdir, rename, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { getClaudeDir, getSessionDir, getArchivedSessionDir, getOpencodeDir, getOpencodeSessionDir } from '@@/data-path';
import type { HonoVariables } from '@@/create-router';
const OPENCODE_PORT = process.env.OPENCODE_PORT ?? '10006';
const OPENCODE_BASE = `http://localhost:${OPENCODE_PORT}`;
export const sessionsRouter = new Hono<{ Variables: HonoVariables }>();
// --- List all sessions (merged from both providers) ---
sessionsRouter.get('/sessions', async (ctx) => {
const { email } = ctx.get('user');
const [claudeSessions, opencodeSessions] = await Promise.all([fetchClaudeSessions(email), fetchOpencodeSessions(email)]);
const merged = [...claudeSessions, ...opencodeSessions].sort((a, b) => b.createdAt - a.createdAt);
return ctx.json(merged);
});
// --- Messages ---
sessionsRouter.get('/sessions/:provider/:id/messages', async (ctx) => {
const { email } = ctx.get('user');
const provider = ctx.req.param('provider');
const id = ctx.req.param('id');
if (provider === 'claude') {
const file = Bun.file(join(getSessionDir(email, id), 'messages.json'));
if (!(await file.exists())) return ctx.json([]);
return ctx.json(await file.json());
}
if (provider === 'opencode') {
return ctx.json(await fetchOpencodeMessages(id));
}
return ctx.json({ error: 'invalid provider' }, 400);
});
sessionsRouter.put('/sessions/:provider/:id/messages', async (ctx) => {
const { email } = ctx.get('user');
const provider = ctx.req.param('provider');
const id = ctx.req.param('id');
if (provider === 'opencode') return ctx.json({ error: 'opencode sessions are read-only' }, 400);
if (provider !== 'claude') return ctx.json({ error: 'invalid provider' }, 400);
const messages = ctx.get('body');
const dir = getSessionDir(email, id);
await Bun.write(join(dir, 'messages.json'), JSON.stringify(messages));
return ctx.json({ ok: true });
});
// --- Rename ---
sessionsRouter.put('/sessions/:provider/:id', async (ctx) => {
const { email } = ctx.get('user');
const provider = ctx.req.param('provider');
const id = ctx.req.param('id');
const body = ctx.get('body') as { title?: string };
if (!body?.title || typeof body.title !== 'string') return ctx.json({ error: 'title required' }, 400);
if (provider === 'claude') {
const dir = getSessionDir(email, id);
const metaFile = Bun.file(join(dir, 'meta.json'));
if (!(await metaFile.exists())) return ctx.json({ error: 'session not found' }, 404);
const meta = await metaFile.json();
meta.title = body.title.slice(0, 200);
await Bun.write(join(dir, 'meta.json'), JSON.stringify(meta));
return ctx.json({ ok: true });
}
if (provider === 'opencode') {
const dir = getOpencodeSessionDir(email, id);
const metaFile = Bun.file(join(dir, 'meta.json'));
if (!(await metaFile.exists())) return ctx.json({ error: 'session not found' }, 404);
const meta = await metaFile.json();
meta.title = body.title.slice(0, 200);
await Bun.write(join(dir, 'meta.json'), JSON.stringify(meta));
// Best-effort sync to OpenCode API
fetch(`${OPENCODE_BASE}/session/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: meta.title }),
}).catch(() => {});
return ctx.json({ ok: true });
}
return ctx.json({ error: 'invalid provider' }, 400);
});
// --- Delete ---
sessionsRouter.delete('/sessions/:provider/:id', async (ctx) => {
const { email } = ctx.get('user');
const provider = ctx.req.param('provider');
const id = ctx.req.param('id');
if (provider === 'claude') {
const dir = getSessionDir(email, id);
try {
await rm(dir, { recursive: true });
} catch {
// dir may not exist
}
return ctx.json({ ok: true });
}
if (provider === 'opencode') {
const dir = getOpencodeSessionDir(email, id);
try {
await rm(dir, { recursive: true });
} catch {
// dir may not exist
}
// Best-effort sync to OpenCode API
fetch(`${OPENCODE_BASE}/session/${id}`, { method: 'DELETE' }).catch(() => {});
return ctx.json({ ok: true });
}
return ctx.json({ error: 'invalid provider' }, 400);
});
// --- Archive (Claude only) ---
sessionsRouter.post('/sessions/:provider/:id/archive', async (ctx) => {
const { email } = ctx.get('user');
const provider = ctx.req.param('provider');
const id = ctx.req.param('id');
if (provider === 'opencode') return ctx.json({ error: 'opencode sessions cannot be archived' }, 400);
if (provider !== 'claude') return ctx.json({ error: 'invalid provider' }, 400);
const src = getSessionDir(email, id);
const dest = getArchivedSessionDir(email, id);
await mkdir(join(getClaudeDir(email), 'archived'), { recursive: true });
await rename(src, dest);
return ctx.json({ ok: true });
});
// --- Helpers ---
type SessionMeta = {
id: string;
title: string;
createdAt: number;
provider: 'claude' | 'opencode';
model?: string | null;
};
async function fetchClaudeSessions(email: string): Promise<SessionMeta[]> {
const dir = getClaudeDir(email);
try {
const entries = await readdir(dir);
const sessions = await Promise.all(
entries
.filter((name) => name !== 'archived')
.map(async (id) => {
try {
const metaFile = Bun.file(join(dir, id, 'meta.json'));
if (!(await metaFile.exists())) return null;
const meta = await metaFile.json();
return { ...meta, provider: 'claude' as const };
} catch {
return null;
}
}),
);
return sessions.filter((s): s is SessionMeta => s !== null);
} catch {
return [];
}
}
async function fetchOpencodeSessions(email: string): Promise<SessionMeta[]> {
const dir = getOpencodeDir(email);
try {
const entries = await readdir(dir);
const sessions = await Promise.all(
entries.map(async (id) => {
try {
const metaFile = Bun.file(join(dir, id, 'meta.json'));
if (!(await metaFile.exists())) return null;
const meta = await metaFile.json();
return { ...meta, provider: 'opencode' as const };
} catch {
return null;
}
}),
);
return sessions.filter((s): s is SessionMeta => s !== null);
} catch {
return [];
}
}
async function fetchOpencodeMessages(id: string) {
try {
const res = await fetch(`${OPENCODE_BASE}/session/${id}/message`);
if (!res.ok) return [];
const data = (await res.json()) as any[];
const messages = Array.isArray(data) ? data : Object.values(data);
const chatMessages: any[] = [];
for (const msg of messages) {
const role = msg.info?.role ?? msg.role;
if (role === 'user') {
const text = Array.isArray(msg.parts)
? msg.parts
.filter((p: any) => p.type === 'text')
.map((p: any) => p.text ?? p.content ?? '')
.join('')
: typeof msg.content === 'string'
? msg.content
: '';
if (text) chatMessages.push({ role: 'user', text });
} else if (role === 'assistant') {
if (Array.isArray(msg.parts)) {
for (const part of msg.parts) {
if (part.type === 'text' && (part.text || part.content)) {
chatMessages.push({ role: 'assistant', text: part.text ?? part.content ?? '' });
} else if (part.type === 'tool') {
chatMessages.push({
role: 'tool',
toolName: part.tool ?? 'unknown',
toolInput: part.state?.input ?? {},
toolUseId: part.callID ?? part.id ?? '',
output:
part.state?.output != null
? typeof part.state.output === 'string'
? part.state.output
: JSON.stringify(part.state.output)
: undefined,
isError: part.state?.status === 'error',
});
} else if (part.type === 'tool-invocation') {
const inv = part.toolInvocation ?? part;
chatMessages.push({
role: 'tool',
toolName: inv.toolName ?? 'unknown',
toolInput: inv.args ?? {},
toolUseId: inv.toolCallId ?? part.id ?? '',
output:
inv.result != null
? typeof inv.result === 'string'
? inv.result
: JSON.stringify(inv.result)
: undefined,
isError: !!part.isError,
});
}
}
}
}
}
return chatMessages;
} catch {
return [];
}
}