232 lines
10 KiB
TypeScript
232 lines
10 KiB
TypeScript
/*
|
|
* The `services` live plugin in the mock (ai-agent-plugins `plugins/services`):
|
|
* the homelab's services catalogue under Projects → Services (`nav:
|
|
* "projects"`), claiming the `service:` pills (`tag: "service"`, `subpath`) and
|
|
* providing `services.index` — what `/api/plugins/services-index` answers.
|
|
* Its actions (`index`, `detail`, `file`) read the mock db's services.
|
|
*
|
|
* The page is the real plugin's document when a dev copied it to
|
|
* `/mock-plugin-ui/services/services.html` (like the pets' overlay); without
|
|
* it a small stand-in draws the list and a service's page, exercising the
|
|
* frame's `open` / `openTag` / `openComposer` bridges.
|
|
*/
|
|
import { getDb, serviceSummary, type MockService } from "./db";
|
|
|
|
const PID = "services";
|
|
|
|
const json = (body: unknown, status = 200) =>
|
|
new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
|
|
|
export const SERVICES_PAGE = {
|
|
id: "services",
|
|
label: "Services",
|
|
nav: "projects",
|
|
icon: "server",
|
|
pluginId: PID,
|
|
pluginName: "Services",
|
|
description: "The homelab's services catalogue",
|
|
to: `/plugins/${PID}/services`,
|
|
subpath: true,
|
|
tag: "service",
|
|
// counts under the id it had as a core page (lib/telemetry setPluginPages)
|
|
feature: "page.services",
|
|
};
|
|
|
|
export const SERVICES_BRIEF = {
|
|
id: PID,
|
|
kind: "app",
|
|
name: "Services",
|
|
icon: "server",
|
|
iconUrl: `/mock-plugin-art/${PID}/icon.svg`,
|
|
color: "#8a6a32",
|
|
description: SERVICES_PAGE.description,
|
|
config: {},
|
|
};
|
|
|
|
/** The key `/api/plugins/ui`'s `provides` carries while the plugin is on. */
|
|
export const SERVICES_PROVIDES = "services.index";
|
|
|
|
/** On for the owner, off for a guest (the lab is the owner's); `?mockServices=0` turns it off. */
|
|
export function servicesPluginOn(guest: boolean): boolean {
|
|
if (guest) return false;
|
|
try {
|
|
return new URLSearchParams(window.location.search).get("mockServices") !== "0";
|
|
} catch {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
/** The index rows, newest commit first — the `index` action and `/api/plugins/services-index`. */
|
|
export function servicesIndex() {
|
|
return getDb()
|
|
.services.map(serviceSummary)
|
|
.sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
|
|
}
|
|
|
|
function detail(s: MockService) {
|
|
const containers = (s.containers ?? []).map((name, i) => ({
|
|
key: name,
|
|
containerName: name,
|
|
image: (s.images ?? [])[i] ?? null,
|
|
build: null,
|
|
profiles: s.profiles ?? [],
|
|
restart: "unless-stopped",
|
|
networkMode: null,
|
|
networks: ["main"],
|
|
ports: i === 0 ? ["127.0.0.1:8080:8080"] : [],
|
|
dependsOn: i === 0 && (s.containers ?? []).length > 1 ? [(s.containers ?? [])[1]] : [],
|
|
envKeys: i === 0 ? ["TZ", "LOG_LEVEL", "DATABASE_URL"] : ["POSTGRES_PASSWORD"],
|
|
envFiles: [".env"],
|
|
volumes: [],
|
|
hasHealthcheck: i === 0,
|
|
composeFile: "docker-compose.yml",
|
|
}));
|
|
const hosts = (s.urls ?? []).map((u) => u.replace(/^https?:\/\//, ""));
|
|
const routers = s.hasTraefik
|
|
? [
|
|
{
|
|
name: s.dir,
|
|
kind: "http",
|
|
rule: hosts.map((h) => `Host(\`${h}\`)`).join(" || "),
|
|
hosts,
|
|
url: (s.urls ?? [])[0] ?? null,
|
|
entryPoints: ["websecure"],
|
|
service: s.dir,
|
|
middlewares: s.auth === "auth" ? ["auth-chain"] : s.auth === "public" ? ["public"] : [],
|
|
tls: true,
|
|
priority: null,
|
|
},
|
|
]
|
|
: [];
|
|
return {
|
|
...serviceSummary(s),
|
|
goal: s.goal,
|
|
containersDetail: containers,
|
|
composeFiles: ["docker-compose.yml"],
|
|
topNetworks: ["main"],
|
|
routers,
|
|
traefikServices: routers.map((r) => ({ name: r.name, servers: [`http://${s.dir}:8080`] })),
|
|
middlewares: [],
|
|
envKeys: ["TZ", "LOG_LEVEL", "DATABASE_URL", "POSTGRES_PASSWORD"],
|
|
homepage: null,
|
|
keyFiles: [
|
|
{ name: "docker-compose.yml", bytes: 640 },
|
|
...(s.hasTraefik ? [{ name: "traefik.yml", bytes: 320 }] : []),
|
|
...(s.readme ? [{ name: "README.md", bytes: s.readme.length }] : []),
|
|
],
|
|
tree: [
|
|
{ name: "docker-compose.yml", path: "docker-compose.yml", type: "file", size: 640, text: true, secret: false },
|
|
...(s.hasTraefik
|
|
? [{ name: "traefik.yml", path: "traefik.yml", type: "file", size: 320, text: true, secret: false }]
|
|
: []),
|
|
{ name: ".env", path: ".env", type: "file", size: 90, text: false, secret: true },
|
|
...(s.readme ? [{ name: "README.md", path: "README.md", type: "file", size: s.readme.length, text: true, secret: false }] : []),
|
|
],
|
|
readme: s.readme,
|
|
claudeMd: s.claudeMd,
|
|
commits: s.commits,
|
|
conversations: getDb()
|
|
.conversations.filter((c) => !c.parentConversation && (c.meta?.services ?? []).includes(s.dir))
|
|
.slice(0, 10)
|
|
.map((c) => ({
|
|
id: c.id,
|
|
sessionId: c.sessionId,
|
|
title: c.title,
|
|
model: c.model ?? null,
|
|
harness: c.meta?.harness ?? null,
|
|
state: c.meta?.state ?? null,
|
|
startedAt: c.startedAt ?? null,
|
|
endedAt: c.endedAt ?? null,
|
|
cost: c.cost ?? 0,
|
|
tokens: 0,
|
|
durationMs: 0,
|
|
})),
|
|
memories: null,
|
|
goalsActive: true,
|
|
text: `# ${s.name}\n${s.description}`,
|
|
};
|
|
}
|
|
|
|
function fileText(s: MockService, path: string): string | null {
|
|
if (path === "README.md") return s.readme;
|
|
if (path === "docker-compose.yml")
|
|
return `services:\n ${s.dir}:\n image: ${(s.images ?? [])[0] ?? "nginx:alpine"}\n container_name: ${s.dir}\n profiles: [${(s.profiles ?? []).join(", ")}]\n`;
|
|
if (path === "traefik.yml" && s.hasTraefik)
|
|
return `http:\n routers:\n ${s.dir}:\n rule: Host(\`${(s.urls ?? [""])[0].replace(/^https?:\/\//, "")}\`)\n service: ${s.dir}\n`;
|
|
return null;
|
|
}
|
|
|
|
/** The stand-in page (no real document copied in): the list on `/`, a service on `/<dir>`. */
|
|
const PAGE_HTML = `<!doctype html><html><head><meta charset="utf-8" />
|
|
<style>html,body{background:transparent}.svc{cursor:pointer}.svc:hover{border-color:hsl(var(--primary) / .5)}
|
|
.link{color:hsl(var(--primary));cursor:pointer;text-decoration:underline}</style></head>
|
|
<body><div class="aia-page" id="root"></div>
|
|
<script>
|
|
var A = window.aiAgentPlugin, root = document.getElementById("root"), slug = (A.init.subpath || "").split("/")[0];
|
|
function esc(s){ return String(s == null ? "" : s).replace(/[&<>"]/g, function(c){ return { "&": "&", "<": "<", ">": ">", '"': """ }[c]; }); }
|
|
function list(d){
|
|
var rows = (d && d.services) || [];
|
|
A.setHeader({ subtitle: rows.length + " services" });
|
|
root.innerHTML = '<div class="aia-grid">' + rows.map(function(s){
|
|
return '<div class="aia-card svc" data-dir="' + esc(s.dir) + '"><div class="aia-row"><span class="aia-title" style="flex:1">' + esc(s.name)
|
|
+ '</span>' + (s.auth ? '<span class="aia-badge">' + esc(s.auth) + '</span>' : '') + '</div>'
|
|
+ '<div class="aia-small aia-muted">' + esc(s.description) + '</div></div>';
|
|
}).join("") + '</div>';
|
|
Array.prototype.forEach.call(root.querySelectorAll(".svc"), function(el){
|
|
el.onclick = function(){ A.openTag("service", el.getAttribute("data-dir")); };
|
|
});
|
|
}
|
|
function page(d){
|
|
if (!d || d.error) { root.innerHTML = '<div class="aia-empty"><strong>Service not found</strong></div>'; return; }
|
|
A.setHeader({ subtitle: d.name, actions: [{ id: "new", label: "New conversation", icon: "plus", primary: true }] });
|
|
var canCommit = !!(A.init.openers && A.init.openers.commit);
|
|
root.innerHTML = '<div class="aia-card"><div class="aia-row"><span class="link" id="back">← Services</span></div>'
|
|
+ '<h2 class="aia-title">' + esc(d.name) + '</h2><p class="aia-muted">' + esc(d.description) + '</p>'
|
|
+ '<div class="aia-small">' + (d.urls || []).map(esc).join(" · ") + '</div></div>'
|
|
+ '<div class="aia-card"><b>Recent commits</b>' + (d.commits || []).map(function(c){
|
|
return '<div class="aia-row aia-small"><code ' + (canCommit ? 'class="link commit" data-sha="' + esc(c.hash) + '"' : '') + '>'
|
|
+ esc(c.hash) + '</code> ' + esc(c.subject) + '</div>';
|
|
}).join("") + '</div>'
|
|
+ (d.readme ? '<div class="aia-card"><b>README.md</b><pre class="aia-small" style="white-space:pre-wrap">' + esc(d.readme) + '</pre></div>' : '');
|
|
document.getElementById("back").onclick = function(){ A.navigate(A.init.tagPages && A.init.tagPages.service || "/projects"); };
|
|
Array.prototype.forEach.call(root.querySelectorAll(".commit"), function(el){
|
|
el.onclick = function(){ A.open("commit", { repo: "service:" + d.dir, sha: el.getAttribute("data-sha") }); };
|
|
});
|
|
}
|
|
A.onHeaderAction(function(id){ if (id === "new") A.openComposer({ tags: ["service:" + slug] }); });
|
|
if (slug) A.query("detail", { slug: slug }, page); else A.query("index", {}, list);
|
|
</script></body></html>`;
|
|
|
|
async function readPayload(method: string, body: unknown): Promise<Record<string, unknown>> {
|
|
if (method === "GET") return {};
|
|
const read = typeof body === "function" ? await (body as () => Promise<unknown>)().catch(() => ({})) : body;
|
|
return (read && typeof read === "object" ? read : {}) as Record<string, unknown>;
|
|
}
|
|
|
|
/** The mock's answers for the services plugin (null: not its). `body` is the
|
|
* handlers' lazy body reader. */
|
|
export async function handleServicesPlugin(p: string, method: string, body: unknown, guest: boolean): Promise<Response | null> {
|
|
if (p === "/api/plugins/services-index" && method === "GET") {
|
|
if (guest) return json({ detail: "owner only" }, 403);
|
|
return json({ services: servicesPluginOn(guest) ? servicesIndex() : [] });
|
|
}
|
|
if (!p.startsWith(`/api/plugins/${PID}/`)) return null;
|
|
if (!servicesPluginOn(guest)) return json({ detail: "not found" }, 404);
|
|
if (p === `/api/plugins/${PID}/ui/page/services` && method === "GET") {
|
|
// The SPA fallback answers a missing file with the app's index.html: only a plugin document will do.
|
|
const r = await fetch(`/mock-plugin-ui/${PID}/services.html`).catch(() => null);
|
|
const doc = r?.ok ? await r.text() : "";
|
|
return new Response(doc.includes("aiAgentPlugin") ? doc : PAGE_HTML, { status: 200 });
|
|
}
|
|
const act = /^\/api\/plugins\/services\/actions\/(index|detail|file)$/.exec(p);
|
|
if (!act) return null;
|
|
const payload = await readPayload(method, body);
|
|
if (act[1] === "index") return json({ services: servicesIndex() });
|
|
const slug = String(payload.slug ?? "");
|
|
const s = getDb().services.find((x) => x.dir === slug);
|
|
if (!s) return json({ detail: { kind: "not_found", message: "service not found" } }, 404);
|
|
if (act[1] === "detail") return json(detail(s));
|
|
const text = fileText(s, String(payload.path ?? ""));
|
|
return text == null ? json({ detail: { kind: "not_found", message: "file not found or not previewable" } }, 404) : json({ text });
|
|
}
|