Open History to see the last commit
1import { OrchestratorMcpFailure } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3
4import * as HtmlRender from "../../../htmlRender/HtmlRender.ts";
5import * as McpInvocationContext from "../../McpInvocationContext.ts";
6import { readMutationCaller } from "../../threadAccess.ts";
7import { HtmlPreviewToolkit, HtmlRenderToolkit, type HtmlToolkit } from "./tools.ts";
8
9const INVALID_PAGE_ERRORS = new Set([
10 "HtmlRenderImagesNotFoundError",
11 "HtmlRenderImageTooLargeError",
12 "HtmlRenderPageTooLargeError",
13]);
14
15// Every HTML render error message is built on the server and tells the agent what to do next.
16const toFailure = (error: { readonly _tag: string; readonly message: string }) =>
17 new OrchestratorMcpFailure({
18 code: INVALID_PAGE_ERRORS.has(error._tag) ? "invalid_request" : "orchestration_error",
19 message: error.message,
20 });
21
22const handlers = {
23 html_preview: (input) =>
24 Effect.gen(function* () {
25 // The headless browser runs on the host and can open local files, so
26 // only agents T3 launched, which already work on this machine, get it.
27 yield* McpInvocationContext.requireThreadScope(
28 yield* McpInvocationContext.McpInvocationContext,
29 "html_preview",
30 );
31 const htmlRender = yield* HtmlRender.HtmlRender;
32 const { png, ...preview } = yield* htmlRender.preview(input).pipe(Effect.mapError(toFailure));
33 return {
34 ...preview,
35 screenshot: {
36 mimeType: "image/png" as const,
37 data: png,
38 width: preview.width,
39 height: preview.capturedHeight,
40 },
41 };
42 }),
43 html_render: (input) =>
44 Effect.gen(function* () {
45 // The page is stored in the calling thread, so it needs that thread's
46 // live run, like any other write.
47 const { scope } = yield* readMutationCaller();
48 const { thread } = yield* McpInvocationContext.requireThreadScope(scope, "html_render");
49 const htmlRender = yield* HtmlRender.HtmlRender;
50 const reference = yield* htmlRender
51 .publish({ threadId: thread.threadId, ...input })
52 .pipe(Effect.mapError(toFailure));
53 return {
54 htmlRender: reference,
55 message:
56 "Shown to the reader above your reply. Don't mention or describe the page; reply with only what it doesn't already say.",
57 };
58 }),
59} satisfies Parameters<typeof HtmlToolkit.toLayer>[0];
60
61export const layerPreview = HtmlPreviewToolkit.toLayer({
62 html_preview: handlers.html_preview,
63});
64
65export const layerRender = HtmlRenderToolkit.toLayer({
66 html_render: handlers.html_render,
67});