};
}
export function renderArtifactMarkdown(markdown: string): string {
let text = markdown.replace(/\r\n?/g, "\n");
if (text.startsWith("---\n")) {
const frontmatterEnd = text.indexOf("\n---\n", 4);
if (frontmatterEnd >= 0) text = text.slice(frontmatterEnd + 5);
}
const lines = text.split("\n");
let html = "";
let paragraph: string[] = [];
let list: "ul" | "ol" | undefined;
let code = false;
let codeLines: string[] = [];
const flushParagraph = (): void => {
if (paragraph.length === 0) return;
html += `${renderInlineMarkdown(paragraph.join(" "))}
`;
paragraph = [];
};
const closeList = (): void => {
if (!list) return;
html += `${list}>`;
list = undefined;
};
const flushCode = (): void => {
html += `${escapeArtifactHtml(codeLines.join("\n"))}
`;
codeLines = [];
};
for (const line of lines) {
if (line.startsWith("```")) {
flushParagraph();
closeList();
if (code) flushCode();
code = !code;
continue;
}
if (code) {
codeLines.push(line);
continue;
}
const heading = line.match(/^(#{1,6})\s+(.+)$/);
const unordered = line.match(/^\s*[-*+]\s+(.+)$/);
const ordered = line.match(/^\s*\d+[.)]\s+(.+)$/);
const quote = line.match(/^>\s?(.*)$/);
if (heading) {
flushParagraph();
closeList();
const level = heading[1]!.length;
html += `${renderInlineMarkdown(heading[2]!)}`;
continue;
}
if (unordered || ordered) {
flushParagraph();
const next = unordered ? "ul" : "ol";
if (list !== next) {
closeList();
list = next;
html += `<${list}>`;
}
html += `${renderInlineMarkdown((unordered ?? ordered)![1]!)}`;
continue;
}
if (quote) {
flushParagraph();
closeList();
html += `${renderInlineMarkdown(quote[1]!)}
`;
continue;
}
if (!line.trim()) {
flushParagraph();
closeList();
continue;
}
paragraph.push(line.trim());
}
flushParagraph();
closeList();
if (code) flushCode();
return html;
}
function renderInlineMarkdown(value: string): string {
return escapeArtifactHtml(value)
.replace(/`([^`]+)`/g, "$1")
.replace(/\*\*\*([^*]+)\*\*\*/g, "$1")
.replace(/\*\*([^*]+)\*\*/g, "$1")
.replace(/\*([^*]+)\*/g, "$1")
.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, '$1');
}
function escapeArtifactHtml(value: string): string {
return value.replace(/[&<>"']/g, (character) => ({
"&": "&", "<": "<", ">": ">", '"': """, "'": "'",
})[character]!);
}
async function loadBlueskyPostInlay(uri: string, expectedCid?: string): Promise {
const cacheKey = `${uri}\u0000${expectedCid ?? "current"}`;
const cached = blueskyInlayCache.get(cacheKey);
if (cached && cached.expiresAt > Date.now()) return cached.value;
blueskyInlayCache.delete(cacheKey);
const endpoint = new URL("https://public.api.bsky.app/xrpc/app.bsky.feed.getPosts");
endpoint.searchParams.append("uris", uri);
const response = await fetch(endpoint, {
headers: { accept: "application/json" },
signal: AbortSignal.timeout(4_000),
});
if (!response.ok) throw new Error(`Bluesky AppView returned ${response.status}`);
const parsed = blueskyPostResponseSchema.parse(await response.json());
const post = parsed.posts.find((candidate) => candidate.uri === uri);
if (!post || (expectedCid && post.cid !== expectedCid)) throw new Error("Bluesky post did not match the observed strong reference");
const embed = blueskyEmbed(post.embed);
const value: BlueskyPostInlay = {
uri: post.uri,
cid: post.cid,
url: atUriToBlueskyUrl(post.uri),
author: blueskyAuthor(post.author),
text: post.record.text ?? "",
...(post.record.createdAt ? { createdAt: post.record.createdAt } : {}),
images: embed.images,
...(embed.external ? { external: embed.external } : {}),
...(embed.quote ? { quote: embed.quote } : {}),
counts: {
replies: post.replyCount ?? 0,
reposts: post.repostCount ?? 0,
likes: post.likeCount ?? 0,
},
};
blueskyInlayCache.set(cacheKey, { expiresAt: Date.now() + BLUESKY_INLAY_CACHE_TTL_MS, value });
while (blueskyInlayCache.size > 512) {
const oldest = blueskyInlayCache.keys().next().value as string | undefined;
if (!oldest) break;
blueskyInlayCache.delete(oldest);
}
return value;
}
async function loadAroundFont(): Promise {
const fontPath = path.resolve(process.cwd(), "public/assets/around-regular.woff2");
const stat = await fs.lstat(fontPath);
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Around font is not a regular file");
const bytes = await fs.readFile(fontPath);
if (bytes.length < 4 || bytes.length > 65_536 || bytes.subarray(0, 4).toString("ascii") !== "wOF2") {
throw new Error("Around font is invalid");
}
return bytes;
}
async function loadBlueskyMedia(source: string): Promise<{ contentType: string; bytes: Buffer }> {
const cached = blueskyMediaCache.get(source);
if (cached && cached.expiresAt > Date.now()) return cached;
if (cached) removeBlueskyMediaCacheEntry(source, cached);
const response = await fetch(source, {
headers: { accept: "image/webp,image/png,image/jpeg,image/gif" },
redirect: "error",
signal: AbortSignal.timeout(5_000),
});
if (!response.ok || !response.body) throw new Error("Bluesky CDN request failed");
const contentType = (response.headers.get("content-type") ?? "").split(";", 1)[0]!.trim().toLowerCase();
if (!BLUESKY_MEDIA_CONTENT_TYPES.has(contentType)) {
await response.body.cancel();
throw new Error("Bluesky CDN media type is unsupported");
}
const declaredLength = response.headers.get("content-length");
if (declaredLength && (!/^\d+$/.test(declaredLength) || Number(declaredLength) > BLUESKY_MEDIA_MAX_BYTES)) {
await response.body.cancel();
throw new Error("Bluesky CDN media is oversized");
}
const reader = response.body.getReader();
const chunks: Buffer[] = [];
let totalBytes = 0;
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
const bytes = Buffer.from(chunk.value);
totalBytes += bytes.length;
if (totalBytes > BLUESKY_MEDIA_MAX_BYTES) {
await reader.cancel();
throw new Error("Bluesky CDN media is oversized");
}
chunks.push(bytes);
}
const bytes = Buffer.concat(chunks, totalBytes);
if (!matchesImageMagic(bytes, contentType)) throw new Error("Bluesky CDN media bytes are invalid");
const entry = { expiresAt: Date.now() + BLUESKY_MEDIA_CACHE_TTL_MS, contentType, bytes };
blueskyMediaCache.set(source, entry);
blueskyMediaCacheBytes += bytes.length;
trimBlueskyMediaCache();
return entry;
}
function trimBlueskyMediaCache(): void {
const now = Date.now();
for (const [key, entry] of blueskyMediaCache) {
if (entry.expiresAt <= now) removeBlueskyMediaCacheEntry(key, entry);
}
while (blueskyMediaCache.size > BLUESKY_MEDIA_CACHE_MAX_ENTRIES || blueskyMediaCacheBytes > BLUESKY_MEDIA_CACHE_MAX_BYTES) {
const oldest = blueskyMediaCache.entries().next().value as [string, { expiresAt: number; contentType: string; bytes: Buffer }] | undefined;
if (!oldest) break;
removeBlueskyMediaCacheEntry(oldest[0], oldest[1]);
}
}
function removeBlueskyMediaCacheEntry(
key: string,
entry: { expiresAt: number; contentType: string; bytes: Buffer },
): void {
if (!blueskyMediaCache.delete(key)) return;
blueskyMediaCacheBytes = Math.max(0, blueskyMediaCacheBytes - entry.bytes.length);
}
function matchesImageMagic(bytes: Buffer, contentType: string): boolean {
if (contentType === "image/jpeg") return bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
if (contentType === "image/png") return bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
if (contentType === "image/webp") return bytes.length >= 12 && bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP";
if (contentType === "image/gif") return bytes.length >= 6 && ["GIF87a", "GIF89a"].includes(bytes.subarray(0, 6).toString("ascii"));
return false;
}
function blueskyEmbed(value: unknown): Pick {
const embed = objectValue(value);
const type = stringValue(embed?.$type);
const media = type === "app.bsky.embed.recordWithMedia#view" ? objectValue(embed?.media) : embed;
const images = Array.isArray(media?.images)
? media.images.flatMap((candidate) => {
const image = objectValue(candidate);
const thumb = blueskyMediaProxyPath(image?.thumb);
const fullsize = safeHttpsUrl(image?.fullsize);
if (!thumb || !fullsize) return [];
return [{ thumb, fullsize, alt: stringValue(image?.alt) ?? "" }];
})
: [];
const externalView = objectValue(media?.external);
const externalUri = safeHttpUrl(externalView?.uri);
const externalThumb = blueskyMediaProxyPath(externalView?.thumb);
const external = externalUri
? {
uri: externalUri,
title: stringValue(externalView?.title) ?? externalUri,
description: stringValue(externalView?.description) ?? "",
...(externalThumb ? { thumb: externalThumb } : {}),
}
: undefined;
const recordContainer = type === "app.bsky.embed.recordWithMedia#view" ? objectValue(embed?.record) : embed;
const recordView = objectValue(recordContainer?.record);
const quoteAuthor = objectValue(recordView?.author);
const quoteValue = objectValue(recordView?.value);
const quoteUri = stringValue(recordView?.uri);
const quote = quoteUri && BLUESKY_POST_URI_PATTERN.test(quoteUri) && quoteAuthor && quoteValue
? {
uri: quoteUri,
url: atUriToBlueskyUrl(quoteUri),
author: blueskyAuthor(quoteAuthor),
text: stringValue(quoteValue.text) ?? "",
}
: undefined;
return { images, ...(external ? { external } : {}), ...(quote ? { quote } : {}) };
}
function blueskyAuthor(value: Record): BlueskyPostInlay["author"] {
const handle = stringValue(value.handle) ?? "unknown.handle";
const avatar = blueskyMediaProxyPath(value.avatar);
return {
displayName: stringValue(value.displayName)?.trim() || handle,
handle,
...(avatar ? { avatar } : {}),
};
}
function objectValue(value: unknown): Record | undefined {
return value !== null && typeof value === "object" && !Array.isArray(value)
? value as Record
: undefined;
}
function stringValue(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function safeHttpsUrl(value: unknown): string | undefined {
const url = safeHttpUrl(value);
return url?.startsWith("https://") ? url : undefined;
}
function blueskyMediaProxyPath(value: unknown): string | undefined {
const source = safeBlueskyMediaUrl(value);
return source ? `api/inlays/bluesky-media?url=${encodeURIComponent(source)}` : undefined;
}
function safeBlueskyMediaUrl(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
try {
const url = new URL(value);
if (url.protocol !== "https:" || url.hostname !== "cdn.bsky.app" || url.port !== "" || url.username || url.password) return undefined;
if (!url.pathname.startsWith("/img/") || url.hash) return undefined;
return url.toString();
} catch {
return undefined;
}
}
function safeHttpUrl(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
try {
const url = new URL(value);
return url.protocol === "https:" || url.protocol === "http:" ? url.toString() : undefined;
} catch {
return undefined;
}
}
function atUriToBlueskyUrl(uri: string): string {
const match = uri.match(BLUESKY_POST_URI_PATTERN);
if (!match) return uri;
const parts = uri.slice(5).split("/");
return `https://bsky.app/profile/${blueskyActorPathSegment(parts[0]!)}/post/${encodeURIComponent(parts[2]!)}`;
}
function blueskyActorPathSegment(value: string): string {
return encodeURIComponent(value).replaceAll("%3A", ":");
}
export function renderInspectorHtml(): string {
const html = `
Stream
`;
return html;
}
function sendJson(response: ServerResponse, status: number, value: unknown): void {
send(response, status, "application/json; charset=utf-8", JSON.stringify(value));
}
function sendBytes(response: ServerResponse, status: number, contentType: string, body: Buffer, cacheControl: string): void {
response.writeHead(status, {
"content-type": contentType,
"content-length": String(body.length),
"cache-control": cacheControl,
"x-content-type-options": "nosniff",
});
response.end(body);
}
function streamInspectorActivity(
store: JazzThoughtStore,
request: IncomingMessage,
response: ServerResponse,
): void {
response.writeHead(200, {
"content-type": "text/event-stream; charset=utf-8",
"cache-control": "no-store, no-transform",
connection: "keep-alive",
"x-accel-buffering": "no",
"x-content-type-options": "nosniff",
});
if (request.method === "HEAD") {
response.end();
return;
}
response.write("retry: 2000\n\n");
let timer: NodeJS.Timeout | undefined;
const notify = () => {
if (timer || response.writableEnded || response.destroyed) return;
timer = setTimeout(() => {
timer = undefined;
if (!response.writableEnded && !response.destroyed) {
response.write(`event: change\ndata: ${JSON.stringify({ at: new Date().toISOString() })}\n\n`);
}
}, 100);
timer.unref();
};
const unsubscribe = store.subscribeInspectorActivity(notify);
const heartbeat = setInterval(() => {
if (!response.writableEnded && !response.destroyed) response.write(": keepalive\n\n");
}, 15_000);
heartbeat.unref();
const close = () => {
request.off("aborted", close);
response.off("close", close);
if (timer) clearTimeout(timer);
clearInterval(heartbeat);
unsubscribe();
};
request.once("aborted", close);
response.once("close", close);
}
function send(response: ServerResponse, status: number, contentType: string, body: string): void {
response.writeHead(status, {
"content-type": contentType,
"cache-control": "no-store",
"content-security-policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'unsafe-inline' https://fonts.googleapis.com; connect-src 'self'; img-src 'self' data:; font-src 'self' https://fonts.gstatic.com; worker-src 'self'; frame-ancestors 'none'; base-uri 'none'",
"x-content-type-options": "nosniff",
"x-frame-options": "DENY",
});
response.end(body);
}
async function readBody(request: IncomingMessage, maxBytes: number): Promise {
const declared = request.headers["content-length"];
if (typeof declared === "string" && (!/^\d+$/.test(declared) || Number(declared) > maxBytes)) {
throw new Error("Request body too large");
}
const parts: Buffer[] = [];
let bytes = 0;
for await (const part of request) {
const buffer = Buffer.isBuffer(part) ? part : Buffer.from(part);
bytes += buffer.length;
if (bytes > maxBytes) throw new Error("Request body too large");
parts.push(buffer);
}
if (bytes === 0) throw new Error("Request body is empty");
return Buffer.concat(parts);
}
function isLoopback(host: string): boolean {
return host === "127.0.0.1" || host === "::1" || host === "localhost";
}
function inspectorRunSummary(run: AgentRun) {
return {
id: run.id,
agentId: run.agentId,
agentVersion: run.agentVersion,
status: run.status,
provider: run.provider,
model: run.model,
createdAt: run.createdAt,
...(run.startedAt ? { startedAt: run.startedAt } : {}),
...(run.completedAt ? { completedAt: run.completedAt } : {}),
...(run.errorText ? { errorText: run.errorText } : {}),
...(typeof run.result?.summary === "string" ? { summary: run.result.summary } : {}),
};
}
function eventBelongsToRun(event: ThoughtEvent, run: AgentRun, inputsById: Map): boolean {
const payloadRunId = typeof event.payload.runId === "string" ? event.payload.runId : undefined;
return payloadRunId === run.id
|| run.inputEventIds.includes(event.id)
|| run.outputEventIds.includes(event.id)
|| run.inputEventIds.some((id) => batchReferencesEvent(inputsById.get(id), event.id));
}
function batchReferencesEvent(input: ThoughtEvent | undefined, eventId: string): boolean {
if (input?.type !== "stream.thought.derived.event.batch" || !Array.isArray(input.payload.members)) return false;
return input.payload.members.some((reference) => (
reference !== null
&& typeof reference === "object"
&& !Array.isArray(reference)
&& (reference as Record).eventId === eventId
));
}
async function loadRunEvidenceEvents(store: JazzThoughtStore, runs: AgentRun[]): Promise {
const terminalEvents = await store.listEvents({ types: RUN_TERMINAL_EVENT_TYPES });
const referencedOutputIds = [
...runs.flatMap((run) => run.outputEventIds),
...terminalEvents.map((event) => event.payload.outputEventId).filter((id): id is string => typeof id === "string"),
];
const outputEvents = await store.getEvents(referencedOutputIds);
return [...new Map([...terminalEvents, ...outputEvents].map((event) => [event.id, event])).values()];
}
async function buildInspectorActivity(store: JazzThoughtStore) {
return buildRecentRootActivity(store);
}
async function buildInspectorSystem(
store: JazzThoughtStore,
runs?: AgentRun[],
) {
const effectiveRuns = runs ?? await store.listRuns();
const [agents, sources, evidenceEvents] = await Promise.all([
store.listAgents(),
buildSourceHealth(store),
loadRunEvidenceEvents(store, effectiveRuns),
]);
const runEvidence = auditRunEvidence(effectiveRuns, evidenceEvents);
const adapterSelections = agents
.map((agent) => ({
id: agent.id,
version: agent.version,
enabled: agent.enabled,
adapter: adapterSelectionFromSpec(agent.spec),
}))
.filter((agent) => agent.adapter !== undefined);
const adapterCatalogs = [...new Map(adapterSelections.map((selection) => [
`${selection.adapter!.digest}:${selection.adapter!.generation}`,
{ digest: selection.adapter!.digest, generation: selection.adapter!.generation },
])).values()];
return {
runs: effectiveRuns.slice().reverse().map(inspectorRunSummary),
agents,
sources,
adapterInventory: { catalogs: adapterCatalogs, selections: adapterSelections },
runEvidence,
evidenceContradictions: runEvidence.filter((report) => !report.consistent).length,
};
}
async function expandRun(store: JazzThoughtStore, run: AgentRun): Promise<{
run: AgentRun;
kind: "rule" | "model";
description: string;
inputs: ThoughtEvent[];
outputs: ThoughtEvent[];
trace: Awaited>;
}> {
const [inputs, outputs, trace] = await Promise.all([
Promise.all(run.inputEventIds.map((id) => store.getEvent(id))),
Promise.all(run.outputEventIds.map((id) => store.getEvent(id))),
store.listTrace(run.id),
]);
const presentInputs = inputs.filter((event): event is ThoughtEvent => Boolean(event));
return {
run,
kind: run.provider === "deterministic" && run.model === "deterministic" ? "rule" : "model",
description: describeRunResult(run, presentInputs),
inputs: presentInputs,
outputs: outputs.filter((event): event is ThoughtEvent => Boolean(event)),
trace,
};
}