@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 188 lines 6.87 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off -- Pure synchronous hashing keeps page matching bounded without a runtime dependency.
2 import * as NodeCrypto from "node:crypto";
3 import type { ThreadId } from "@t3tools/contracts";
4 import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
5 import * as Context from "effect/Context";
6 import * as Effect from "effect/Effect";
7 import * as Layer from "effect/Layer";
8 import * as Ref from "effect/Ref";
9
10 import type { McpProviderSessionConfig } from "./mcpSession.ts";
11
12 // Other providers may never consume these references.
13 const MAX_KEPT_HTML_RENDERS = 64;
14
15 // Antigravity truncates long HTML arguments to a marked tail of at most 8,000 characters.
16 const BOUNDED_TEXT_MARKER = "[Earlier output truncated]\n\n";
17 const KEPT_HTML_END_LENGTH = 8_000;
18
19 interface KeptHtmlRender {
20 readonly path: string | undefined;
21 readonly title: string;
22 readonly height: number;
23 readonly htmlLength: number;
24 readonly htmlHash: string;
25 readonly htmlEnd: string;
26 readonly reference: HtmlRenderReference;
27 }
28
29 const hashHtml = (html: string) => NodeCrypto.createHash("sha256").update(html).digest("hex");
30
31 export class McpProviderSessions extends Context.Service<
32 McpProviderSessions,
33 {
34 readonly set: (config: McpProviderSessionConfig) => Effect.Effect<void>;
35 readonly read: (threadId: ThreadId) => Effect.Effect<McpProviderSessionConfig | undefined>;
36 readonly clear: (threadId: ThreadId) => Effect.Effect<void>;
37 readonly recordHtmlRender: (
38 threadId: ThreadId,
39 input: {
40 readonly html: string;
41 readonly path?: string | undefined;
42 readonly title: string;
43 readonly height: number;
44 },
45 reference: HtmlRenderReference,
46 ) => Effect.Effect<void>;
47 // A reported attachment consumes that exact page; otherwise the oldest page for a path, or a
48 // unique inline match.
49 readonly takeHtmlRender: (
50 threadId: ThreadId,
51 input: PageInput,
52 reported?: HtmlRenderReference,
53 ) => Effect.Effect<HtmlRenderReference | undefined>;
54 }
55 >()("@t3tools/provider-core/server/McpProviderSessions") {}
56
57 interface PageInput {
58 readonly html?: unknown;
59 readonly path?: unknown;
60 readonly title?: unknown;
61 readonly height?: unknown;
62 }
63
64 const matchingPageIndex = (kept: ReadonlyArray<KeptHtmlRender>, input: PageInput): number => {
65 const height =
66 typeof input.height === "string" && input.height.trim() !== ""
67 ? Number(input.height)
68 : input.height;
69 const sameFrame = (page: KeptHtmlRender) => page.title === input.title && page.height === height;
70 const path = input.path;
71 // The handler refuses a call with both sources, so it published nothing to recover. Its decoder
72 // reads null as an omitted source.
73 if (path !== undefined && path !== null && input.html !== undefined && input.html !== null) {
74 return -1;
75 }
76 if (typeof path === "string" && path.length > 0) {
77 // An edited file is published again under the same path; completions arrive in publish order.
78 return kept.findIndex((page) => page.path === path && sameFrame(page));
79 }
80 const html = input.html;
81 if (typeof html !== "string" || html.length === 0) {
82 return -1;
83 }
84 const htmlHash = hashHtml(html);
85 const tail = html.startsWith(BOUNDED_TEXT_MARKER)
86 ? html.slice(BOUNDED_TEXT_MARKER.length)
87 : undefined;
88 const matches = kept.flatMap((page, index) =>
89 page.path === undefined &&
90 sameFrame(page) &&
91 (page.htmlHash === htmlHash ||
92 (tail !== undefined &&
93 tail.length > 0 &&
94 tail.length < page.htmlLength &&
95 page.htmlEnd.endsWith(tail)))
96 ? [index]
97 : [],
98 );
99 // Identical pages are interchangeable, so repeats are taken in publish order.
100 if (matches.length > 1 && matches.every((index) => kept[index]!.htmlHash === htmlHash)) {
101 return matches[0]!;
102 }
103 return matches.length === 1 ? matches[0]! : -1;
104 };
105
106 const make = Effect.gen(function* () {
107 const sessions = yield* Ref.make(new Map<ThreadId, McpProviderSessionConfig>());
108 const htmlRenders = yield* Ref.make(new Map<ThreadId, ReadonlyArray<KeptHtmlRender>>());
109 return McpProviderSessions.of({
110 set: Effect.fn("McpProviderSessions.set")(function* (config) {
111 const current = yield* Ref.get(sessions);
112 if (current.get(config.threadId)?.providerSessionId !== config.providerSessionId) {
113 yield* Ref.update(htmlRenders, (kept) => {
114 const next = new Map(kept);
115 next.delete(config.threadId);
116 return next;
117 });
118 }
119 yield* Ref.update(sessions, (current) => new Map(current).set(config.threadId, config));
120 }),
121 read: Effect.fn("McpProviderSessions.read")(function (threadId) {
122 return Ref.get(sessions).pipe(Effect.map((current) => current.get(threadId)));
123 }),
124 clear: Effect.fn("McpProviderSessions.clear")(function (threadId) {
125 return Ref.update(sessions, (current) => {
126 const next = new Map(current);
127 next.delete(threadId);
128 return next;
129 }).pipe(
130 Effect.andThen(
131 Ref.update(htmlRenders, (current) => {
132 const next = new Map(current);
133 next.delete(threadId);
134 return next;
135 }),
136 ),
137 );
138 }),
139 recordHtmlRender: Effect.fn("McpProviderSessions.recordHtmlRender")(
140 function (threadId, input, reference) {
141 return Ref.update(htmlRenders, (current) =>
142 new Map(current).set(
143 threadId,
144 [
145 ...(current.get(threadId) ?? []),
146 {
147 path: input.path,
148 title: input.title,
149 height: input.height,
150 htmlLength: input.html.length,
151 htmlHash: hashHtml(input.html),
152 // Copy the tail so its backing storage cannot retain the entire HTML string.
153 htmlEnd: Buffer.from(input.html.slice(-KEPT_HTML_END_LENGTH), "utf16le").toString(
154 "utf16le",
155 ),
156 reference,
157 },
158 ].slice(-MAX_KEPT_HTML_RENDERS),
159 ),
160 );
161 },
162 ),
163 takeHtmlRender: Effect.fn("McpProviderSessions.takeHtmlRender")(
164 function (threadId, input, reported) {
165 return Ref.modify(htmlRenders, (current) => {
166 const kept = current.get(threadId) ?? [];
167 const index =
168 reported === undefined
169 ? matchingPageIndex(kept, input)
170 : kept.findIndex((page) => page.reference.attachmentId === reported.attachmentId);
171 if (index === -1) {
172 return [undefined, current];
173 }
174 const rest = kept.filter((_, keptIndex) => keptIndex !== index);
175 const next = new Map(current);
176 if (rest.length === 0) {
177 next.delete(threadId);
178 } else {
179 next.set(threadId, rest);
180 }
181 return [kept[index]!.reference, next];
182 });
183 },
184 ),
185 });
186 });
187
188 export const layer = Layer.effect(McpProviderSessions, make);