Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpProviderSessions.ts

152 lines5.6 KB

1// @effect-diagnostics nodeBuiltinImport:off -- Pure synchronous hashing keeps page matching bounded without a runtime dependency.
2import * as NodeCrypto from "node:crypto";
3import type { ThreadId } from "@t3tools/contracts";
4import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
5import * as Context from "effect/Context";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Ref from "effect/Ref";
9​
10import type { McpProviderSessionConfig } from "./mcpSession.ts";
11​
12// Other providers may never consume these references.
13const MAX_KEPT_HTML_RENDERS = 64;
14​
15// Antigravity truncates long HTML arguments to a marked tail of at most 8,000 characters.
16const BOUNDED_TEXT_MARKER = "[Earlier output truncated]\n\n";
17const KEPT_HTML_END_LENGTH = 8_000;
18​
19interface KeptHtmlRender {
20 readonly title: string;
21 readonly height: number;
22 readonly htmlLength: number;
23 readonly htmlHash: string;
24 readonly htmlEnd: string;
25 readonly reference: HtmlRenderReference;
27​
28const hashHtml = (html: string) => NodeCrypto.createHash("sha256").update(html).digest("hex");
29​
30export class McpProviderSessions extends Context.Service<
31 McpProviderSessions,
32 {
33 readonly set: (config: McpProviderSessionConfig) => Effect.Effect<void>;
34 readonly read: (threadId: ThreadId) => Effect.Effect<McpProviderSessionConfig | undefined>;
35 readonly clear: (threadId: ThreadId) => Effect.Effect<void>;
36 readonly recordHtmlRender: (
37 threadId: ThreadId,
38 input: { readonly html: string; readonly title: string; readonly height: number },
39 reference: HtmlRenderReference,
40 ) => Effect.Effect<void>;
41 // A reported attachment consumes that exact page; otherwise only unique input matches count.
42 readonly takeHtmlRender: (
43 threadId: ThreadId,
44 input: { readonly html?: unknown; readonly title?: unknown; readonly height?: unknown },
45 reported?: HtmlRenderReference,
46 ) => Effect.Effect<HtmlRenderReference | undefined>;
47 }
48>()("@t3tools/provider-core/server/McpProviderSessions") {}
49​
50const matchingPageIndex = (
51 kept: ReadonlyArray<KeptHtmlRender>,
52 input: { readonly html?: unknown; readonly title?: unknown; readonly height?: unknown },
53): number => {
54 const html = input.html;
55 if (typeof html !== "string" || html.length === 0) {
56 return -1;
57 }
58 const height =
59 typeof input.height === "string" && input.height.trim() !== ""
60 ? Number(input.height)
61 : input.height;
62 const htmlHash = hashHtml(html);
63 const tail = html.startsWith(BOUNDED_TEXT_MARKER)
64 ? html.slice(BOUNDED_TEXT_MARKER.length)
65 : undefined;
66 const matches = kept.flatMap((page, index) =>
67 page.title === input.title &&
68 page.height === height &&
69 (page.htmlHash === htmlHash ||
70 (tail !== undefined &&
71 tail.length > 0 &&
72 tail.length < page.htmlLength &&
73 page.htmlEnd.endsWith(tail)))
74 ? [index]
75 : [],
76 );
77 return matches.length === 1 ? matches[0]! : -1;
78};
79​
80const make = Effect.gen(function* () {
81 const sessions = yield* Ref.make(new Map<ThreadId, McpProviderSessionConfig>());
82 const htmlRenders = yield* Ref.make(new Map<ThreadId, ReadonlyArray<KeptHtmlRender>>());
83 return McpProviderSessions.of({
84 set: Effect.fn("McpProviderSessions.set")(function* (config) {
85 const current = yield* Ref.get(sessions);
86 if (current.get(config.threadId)?.providerSessionId !== config.providerSessionId) {
87 yield* Ref.update(htmlRenders, (kept) => {
88 const next = new Map(kept);
89 next.delete(config.threadId);
90 return next;
91 });
92 }
93 yield* Ref.update(sessions, (current) => new Map(current).set(config.threadId, config));
94 }),
95 read: (threadId) => Ref.get(sessions).pipe(Effect.map((current) => current.get(threadId))),
96 clear: (threadId) =>
97 Ref.update(sessions, (current) => {
98 const next = new Map(current);
99 next.delete(threadId);
100 return next;
101 }).pipe(
102 Effect.andThen(
103 Ref.update(htmlRenders, (current) => {
104 const next = new Map(current);
105 next.delete(threadId);
106 return next;
107 }),
108 ),
109 ),
110 recordHtmlRender: (threadId, input, reference) =>
111 Ref.update(htmlRenders, (current) =>
112 new Map(current).set(
113 threadId,
114 [
115 ...(current.get(threadId) ?? []),
116 {
117 title: input.title,
118 height: input.height,
119 htmlLength: input.html.length,
120 htmlHash: hashHtml(input.html),
121 // Copy the tail so its backing storage cannot retain the entire HTML string.
122 htmlEnd: Buffer.from(input.html.slice(-KEPT_HTML_END_LENGTH), "utf16le").toString(
123 "utf16le",
124 ),
125 reference,
126 },
127 ].slice(-MAX_KEPT_HTML_RENDERS),
128 ),
129 ),
130 takeHtmlRender: (threadId, input, reported) =>
131 Ref.modify(htmlRenders, (current) => {
132 const kept = current.get(threadId) ?? [];
133 const index =
134 reported === undefined
135 ? matchingPageIndex(kept, input)
136 : kept.findIndex((page) => page.reference.attachmentId === reported.attachmentId);
137 if (index === -1) {
138 return [undefined, current];
139 }
140 const rest = kept.filter((_, keptIndex) => keptIndex !== index);
141 const next = new Map(current);
142 if (rest.length === 0) {
143 next.delete(threadId);
144 } else {
145 next.set(threadId, rest);
146 }
147 return [kept[index]!.reference, next];
148 }),
149 });
150});
151​
152export const layer = Layer.effect(McpProviderSessions, make);