Archived
Add pi web POC
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import Fastify from "fastify";
|
||||
import fastifyStatic from "@fastify/static";
|
||||
import fastifyWebsocket from "@fastify/websocket";
|
||||
import { ProjectStore } from "./storage/projectStore.js";
|
||||
import { ProjectService } from "./projects/projectService.js";
|
||||
import { WorkspaceService } from "./workspaces/workspaceService.js";
|
||||
import { SessionEventHub } from "./realtime/sessionEventHub.js";
|
||||
import { PiSessionService } from "./sessions/piSessionService.js";
|
||||
|
||||
const app = Fastify({ logger: true });
|
||||
await app.register(fastifyWebsocket);
|
||||
|
||||
const projects = new ProjectService(new ProjectStore());
|
||||
const workspaces = new WorkspaceService();
|
||||
const eventHub = new SessionEventHub();
|
||||
const sessions = new PiSessionService(eventHub);
|
||||
|
||||
app.get("/api/projects", async () => projects.list());
|
||||
|
||||
app.post<{ Body: { name?: string; path: string } }>("/api/projects", async (request, reply) => {
|
||||
try {
|
||||
return await projects.add(request.body);
|
||||
} catch (error) {
|
||||
return reply.code(400).send({ error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
});
|
||||
|
||||
app.get<{ Params: { projectId: string } }>("/api/projects/:projectId/workspaces", async (request, reply) => {
|
||||
try {
|
||||
const project = await projects.requireProject(request.params.projectId);
|
||||
return await workspaces.list(project);
|
||||
} catch (error) {
|
||||
return reply.code(404).send({ error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
});
|
||||
|
||||
app.get<{ Querystring: { cwd?: string } }>("/api/sessions", async (request, reply) => {
|
||||
if (!request.query.cwd) return reply.code(400).send({ error: "cwd query parameter is required" });
|
||||
return sessions.list(request.query.cwd);
|
||||
});
|
||||
|
||||
app.post<{ Body: { cwd: string } }>("/api/sessions", async (request, reply) => {
|
||||
try {
|
||||
return await sessions.start(request.body.cwd);
|
||||
} catch (error) {
|
||||
return reply.code(400).send({ error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
});
|
||||
|
||||
app.get<{ Params: { sessionId: string } }>("/api/sessions/:sessionId/messages", async (request, reply) => {
|
||||
try {
|
||||
return await sessions.messages(request.params.sessionId);
|
||||
} catch (error) {
|
||||
return reply.code(404).send({ error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
});
|
||||
|
||||
app.post<{ Params: { sessionId: string }; Body: { text: string } }>("/api/sessions/:sessionId/prompt", async (request, reply) => {
|
||||
try {
|
||||
await sessions.prompt(request.params.sessionId, request.body.text);
|
||||
return { accepted: true };
|
||||
} catch (error) {
|
||||
return reply.code(400).send({ error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
});
|
||||
|
||||
app.post<{ Params: { sessionId: string } }>("/api/sessions/:sessionId/abort", async (request) => {
|
||||
await sessions.abort(request.params.sessionId);
|
||||
return { aborted: true };
|
||||
});
|
||||
|
||||
app.post<{ Params: { sessionId: string } }>("/api/sessions/:sessionId/close", async (request) => {
|
||||
sessions.close(request.params.sessionId);
|
||||
return { closed: true };
|
||||
});
|
||||
|
||||
app.get<{ Params: { sessionId: string } }>("/api/sessions/:sessionId/events", { websocket: true }, (socket, request) => {
|
||||
eventHub.add(request.params.sessionId, socket);
|
||||
});
|
||||
|
||||
const clientDist = join(process.cwd(), "dist", "client");
|
||||
if (existsSync(clientDist)) {
|
||||
await app.register(fastifyStatic, { root: clientDist });
|
||||
app.setNotFoundHandler((_request, reply) => reply.sendFile("index.html"));
|
||||
}
|
||||
|
||||
const port = Number(process.env.PI_WEB_PORT ?? process.env.PORT ?? 3000);
|
||||
const host = process.env.PI_WEB_HOST ?? "127.0.0.1";
|
||||
await app.listen({ port, host });
|
||||
@@ -0,0 +1,24 @@
|
||||
import { realpath, stat } from "node:fs/promises";
|
||||
import type { ProjectStore } from "../storage/projectStore.js";
|
||||
import type { Project } from "../types.js";
|
||||
|
||||
export class ProjectService {
|
||||
constructor(private readonly store: ProjectStore) {}
|
||||
|
||||
list(): Promise<Project[]> {
|
||||
return this.store.list();
|
||||
}
|
||||
|
||||
async add(input: { name?: string; path: string }): Promise<Project> {
|
||||
const resolved = await realpath(input.path);
|
||||
const s = await stat(resolved);
|
||||
if (!s.isDirectory()) throw new Error("Project path must be a directory");
|
||||
return this.store.add({ name: input.name, path: resolved });
|
||||
}
|
||||
|
||||
async requireProject(id: string): Promise<Project> {
|
||||
const project = await this.store.get(id);
|
||||
if (!project) throw new Error("Project not found");
|
||||
return project;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { WebSocket } from "ws";
|
||||
|
||||
export class SessionEventHub {
|
||||
private readonly socketsBySession = new Map<string, Set<WebSocket>>();
|
||||
|
||||
add(sessionId: string, socket: WebSocket): void {
|
||||
let sockets = this.socketsBySession.get(sessionId);
|
||||
if (!sockets) {
|
||||
sockets = new Set();
|
||||
this.socketsBySession.set(sessionId, sockets);
|
||||
}
|
||||
sockets.add(socket);
|
||||
socket.on("close", () => sockets?.delete(socket));
|
||||
}
|
||||
|
||||
publish(sessionId: string, event: unknown): void {
|
||||
const payload = JSON.stringify(event);
|
||||
for (const socket of this.socketsBySession.get(sessionId) ?? []) {
|
||||
if (socket.readyState === socket.OPEN) socket.send(payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import {
|
||||
AuthStorage,
|
||||
createAgentSession,
|
||||
ModelRegistry,
|
||||
SessionManager,
|
||||
type AgentSession,
|
||||
} from "@mariozechner/pi-coding-agent";
|
||||
import type { ClientSession } from "../types.js";
|
||||
import type { SessionEventHub } from "../realtime/sessionEventHub.js";
|
||||
|
||||
interface ActiveSession {
|
||||
session: AgentSession;
|
||||
unsubscribe: () => void;
|
||||
}
|
||||
|
||||
export class PiSessionService {
|
||||
private readonly active = new Map<string, ActiveSession>();
|
||||
private readonly authStorage = AuthStorage.create();
|
||||
private readonly modelRegistry = ModelRegistry.create(this.authStorage);
|
||||
|
||||
constructor(private readonly events: SessionEventHub) {}
|
||||
|
||||
async list(cwd: string): Promise<ClientSession[]> {
|
||||
const sessions = await SessionManager.list(cwd);
|
||||
return sessions.map((s) => ({
|
||||
id: s.id,
|
||||
path: s.path,
|
||||
cwd: s.cwd,
|
||||
name: s.name,
|
||||
created: s.created.toISOString(),
|
||||
modified: s.modified.toISOString(),
|
||||
messageCount: s.messageCount,
|
||||
firstMessage: s.firstMessage,
|
||||
}));
|
||||
}
|
||||
|
||||
async start(cwd: string): Promise<ClientSession> {
|
||||
const { session } = await this.create(SessionManager.create(cwd), cwd);
|
||||
return {
|
||||
id: session.sessionId,
|
||||
path: session.sessionFile ?? "",
|
||||
cwd,
|
||||
created: new Date().toISOString(),
|
||||
modified: new Date().toISOString(),
|
||||
messageCount: session.messages.length,
|
||||
firstMessage: "",
|
||||
};
|
||||
}
|
||||
|
||||
async messages(sessionId: string): Promise<unknown[]> {
|
||||
const session = await this.getOrOpen(sessionId);
|
||||
return session.messages;
|
||||
}
|
||||
|
||||
async prompt(sessionId: string, text: string): Promise<void> {
|
||||
const session = await this.getOrOpen(sessionId);
|
||||
void session.prompt(text).catch((error) => {
|
||||
this.events.publish(sessionId, { type: "session.error", message: error instanceof Error ? error.message : String(error) });
|
||||
});
|
||||
}
|
||||
|
||||
async abort(sessionId: string): Promise<void> {
|
||||
const active = this.active.get(sessionId);
|
||||
if (active) await active.session.abort();
|
||||
}
|
||||
|
||||
close(sessionId: string): void {
|
||||
const active = this.active.get(sessionId);
|
||||
if (!active) return;
|
||||
active.unsubscribe();
|
||||
active.session.dispose();
|
||||
this.active.delete(sessionId);
|
||||
}
|
||||
|
||||
private async getOrOpen(sessionId: string): Promise<AgentSession> {
|
||||
const active = this.active.get(sessionId);
|
||||
if (active) return active.session;
|
||||
|
||||
const match = (await SessionManager.listAll()).find((s) => s.id === sessionId || s.id.startsWith(sessionId));
|
||||
if (!match) throw new Error("Session not found");
|
||||
return (await this.create(SessionManager.open(match.path), match.cwd)).session;
|
||||
}
|
||||
|
||||
private async create(sessionManager: SessionManager, cwd: string): Promise<ActiveSession> {
|
||||
const { session } = await createAgentSession({
|
||||
cwd,
|
||||
sessionManager,
|
||||
authStorage: this.authStorage,
|
||||
modelRegistry: this.modelRegistry,
|
||||
});
|
||||
|
||||
const unsubscribe = session.subscribe((event) => {
|
||||
this.events.publish(session.sessionId, toClientEvent(event));
|
||||
});
|
||||
|
||||
const active = { session, unsubscribe };
|
||||
this.active.set(session.sessionId, active);
|
||||
return active;
|
||||
}
|
||||
}
|
||||
|
||||
function toClientEvent(event: any): unknown {
|
||||
if (event.type === "message_update" && event.assistantMessageEvent?.type === "text_delta") {
|
||||
return { type: "assistant.delta", text: event.assistantMessageEvent.delta };
|
||||
}
|
||||
if (event.type === "tool_execution_start") {
|
||||
return { type: "tool.start", toolName: event.toolName, toolCallId: event.toolCallId };
|
||||
}
|
||||
if (event.type === "tool_execution_end") {
|
||||
return { type: "tool.end", toolName: event.toolName, toolCallId: event.toolCallId, isError: event.isError };
|
||||
}
|
||||
if (event.type === "agent_start") return { type: "agent.start" };
|
||||
if (event.type === "agent_end") return { type: "agent.end" };
|
||||
if (event.type === "message_end") return { type: "message.end" };
|
||||
return { type: "pi.event", eventType: event.type };
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Project } from "../types.js";
|
||||
|
||||
interface ProjectFile {
|
||||
projects: Project[];
|
||||
}
|
||||
|
||||
export class ProjectStore {
|
||||
constructor(private readonly filePath = join(homedir(), ".pi-web", "projects.json")) {}
|
||||
|
||||
async list(): Promise<Project[]> {
|
||||
return (await this.read()).projects;
|
||||
}
|
||||
|
||||
async add(input: { name?: string; path: string }): Promise<Project> {
|
||||
const data = await this.read();
|
||||
const path = input.path;
|
||||
const existing = data.projects.find((p) => p.path === path);
|
||||
if (existing) return existing;
|
||||
|
||||
const project: Project = {
|
||||
id: randomUUID(),
|
||||
name: input.name?.trim() || path.split("/").filter(Boolean).at(-1) || path,
|
||||
path,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
data.projects.push(project);
|
||||
await this.write(data);
|
||||
return project;
|
||||
}
|
||||
|
||||
async get(id: string): Promise<Project | undefined> {
|
||||
return (await this.list()).find((p) => p.id === id);
|
||||
}
|
||||
|
||||
private async read(): Promise<ProjectFile> {
|
||||
try {
|
||||
return JSON.parse(await readFile(this.filePath, "utf8")) as ProjectFile;
|
||||
} catch (error: any) {
|
||||
if (error?.code === "ENOENT") return { projects: [] };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async write(data: ProjectFile): Promise<void> {
|
||||
await mkdir(dirname(this.filePath), { recursive: true });
|
||||
await writeFile(this.filePath, `${JSON.stringify(data, null, 2)}\n`, "utf8");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export interface Project {
|
||||
id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface Workspace {
|
||||
id: string;
|
||||
projectId: string;
|
||||
path: string;
|
||||
label: string;
|
||||
branch?: string;
|
||||
isMain: boolean;
|
||||
isGitWorktree: boolean;
|
||||
}
|
||||
|
||||
export interface ClientSession {
|
||||
id: string;
|
||||
path: string;
|
||||
cwd: string;
|
||||
name?: string;
|
||||
created: string;
|
||||
modified: string;
|
||||
messageCount: number;
|
||||
firstMessage: string;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export interface GitWorktreeInfo {
|
||||
path: string;
|
||||
branch?: string;
|
||||
bare?: boolean;
|
||||
detached?: boolean;
|
||||
}
|
||||
|
||||
export async function isGitRepository(path: string): Promise<boolean> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync("git", ["-C", path, "rev-parse", "--is-inside-work-tree"]);
|
||||
return stdout.trim() === "true";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function discoverGitWorktrees(path: string): Promise<GitWorktreeInfo[]> {
|
||||
const { stdout } = await execFileAsync("git", ["-C", path, "worktree", "list", "--porcelain"]);
|
||||
const chunks = stdout.trim().split(/\n\s*\n/).filter(Boolean);
|
||||
|
||||
return chunks.map((chunk) => {
|
||||
const info: GitWorktreeInfo = { path: "" };
|
||||
for (const line of chunk.split("\n")) {
|
||||
const [key, ...rest] = line.split(" ");
|
||||
const value = rest.join(" ");
|
||||
if (key === "worktree") info.path = value;
|
||||
if (key === "branch") info.branch = value.replace(/^refs\/heads\//, "");
|
||||
if (key === "bare") info.bare = true;
|
||||
if (key === "detached") info.detached = true;
|
||||
}
|
||||
return info;
|
||||
}).filter((w) => w.path);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import type { Project } from "../types.js";
|
||||
import type { Workspace } from "../types.js";
|
||||
import { discoverGitWorktrees, isGitRepository } from "./gitWorktreeDiscovery.js";
|
||||
|
||||
const idFor = (value: string) => createHash("sha1").update(value).digest("hex").slice(0, 12);
|
||||
|
||||
export class WorkspaceService {
|
||||
async list(project: Project): Promise<Workspace[]> {
|
||||
if (!(await isGitRepository(project.path))) {
|
||||
return [this.single(project)];
|
||||
}
|
||||
|
||||
const worktrees = await discoverGitWorktrees(project.path);
|
||||
if (worktrees.length === 0) return [this.single(project)];
|
||||
|
||||
return worktrees.map((worktree) => ({
|
||||
id: idFor(`${project.id}:${worktree.path}`),
|
||||
projectId: project.id,
|
||||
path: worktree.path,
|
||||
label: worktree.branch || (worktree.detached ? "detached" : worktree.path.split("/").filter(Boolean).at(-1) || worktree.path),
|
||||
branch: worktree.branch,
|
||||
isMain: worktree.path === project.path,
|
||||
isGitWorktree: true,
|
||||
}));
|
||||
}
|
||||
|
||||
private single(project: Project): Workspace {
|
||||
return {
|
||||
id: idFor(`${project.id}:${project.path}`),
|
||||
projectId: project.id,
|
||||
path: project.path,
|
||||
label: project.name,
|
||||
isMain: true,
|
||||
isGitWorktree: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user