@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 449 lines 17.3 KB
Raw
1 import { NodeHttpServer } from "@effect/platform-node";
2 import { expect, it } from "@effect/vitest";
3 import {
4 EnvironmentId,
5 OrchestrationV2LinkedSender,
6 OrchestratorMcpFailure,
7 ThreadId,
8 } from "@t3tools/contracts";
9 import * as Context from "effect/Context";
10 import * as DateTime from "effect/DateTime";
11 import * as Deferred from "effect/Deferred";
12 import * as Duration from "effect/Duration";
13 import * as Effect from "effect/Effect";
14 import * as Fiber from "effect/Fiber";
15 import * as Layer from "effect/Layer";
16 import * as Option from "effect/Option";
17 import * as Queue from "effect/Queue";
18 import * as Ref from "effect/Ref";
19 import * as Schema from "effect/Schema";
20 import { Tool, Toolkit } from "effect/ai";
21 import * as TestClock from "effect/testing/TestClock";
22 import { HttpClient, HttpClientResponse } from "effect/http";
23
24 import * as McpHttpServer from "../mcp/McpHttpServer.ts";
25 import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
26 import * as McpToolAccess from "../mcp/McpToolAccess.ts";
27 import * as PeerLinks from "./PeerLinks.ts";
28 import * as PeerMcpClient from "./PeerMcpClient.ts";
29 import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";
30
31 const Result = Schema.Struct({ modes: Schema.String });
32 const toolkit = Toolkit.make(
33 Tool.make("probe", {
34 description: "Returns this request's mode limits.",
35 success: Result,
36 dependencies: [McpInvocationContext.McpInvocationContext],
37 }),
38 Tool.make("hold", {
39 description: "Holds a tool request open.",
40 success: Result,
41 dependencies: [McpInvocationContext.McpInvocationContext],
42 }),
43 Tool.make("refuse", {
44 description: "Refuses the call.",
45 success: Result,
46 failure: OrchestratorMcpFailure,
47 failureMode: "return",
48 }),
49 );
50
51 /** One `probe` call to a linked peer at a remote address, answered by `http`. */
52 const probeThrough = Effect.fn(function* (http: HttpClient.HttpClient) {
53 const box = descriptorOf("environment-box", "Box");
54 const context = yield* Layer.build(
55 PeerMcpClient.layer.pipe(
56 Layer.provide(
57 Layer.mergeAll(
58 Layer.succeed(HttpClient.HttpClient, http),
59 Layer.mock(PeerLinks.PeerLinks)({
60 resolve: () =>
61 Effect.succeed({
62 link: {
63 environmentId: box.environmentId,
64 label: box.label,
65 urls: ["https://peer.example"],
66 access: "auto",
67 linkedAt: DateTime.makeUnsafe(0),
68 expiresAt: DateTime.makeUnsafe(1),
69 lastReachedAt: null,
70 lastError: null,
71 },
72 url: "https://peer.example",
73 token: "fixture",
74 capabilities: box.capabilities,
75 }),
76 recordOutcome: () => Effect.void,
77 }),
78 ),
79 ),
80 ),
81 );
82 return Context.get(context, PeerMcpClient.PeerMcpClient).call({
83 environmentId: box.environmentId,
84 tool: "probe",
85 arguments: {},
86 limits: { runtimeMode: "approval-required", interactionMode: "plan" },
87 success: Result,
88 });
89 });
90
91 const probeResult = JSON.stringify({
92 result: { content: [{ type: "text", text: '{"modes":"approval-required/plan"}' }] },
93 });
94
95 const refusal = new OrchestratorMcpFailure({
96 code: "thread_not_found",
97 message: "Thread thread-gone was not found.",
98 });
99
100 const senderToolkit = Toolkit.make(
101 Tool.make("sender", {
102 description: "Returns the thread this request is made for.",
103 success: Schema.Struct({ senderThread: Schema.NullOr(OrchestrationV2LinkedSender) }),
104 dependencies: [McpInvocationContext.McpInvocationContext],
105 }),
106 );
107
108 it.effect("tells the peer which thread a call is made for", () =>
109 Effect.scoped(
110 Effect.gen(function* () {
111 const handlers = McpToolAccess.toLayer(senderToolkit, {
112 sender: McpToolAccess.reads(() =>
113 McpInvocationContext.McpInvocationContext.pipe(
114 Effect.map((scope) => ({ senderThread: scope.client?.senderThread ?? null })),
115 ),
116 ),
117 });
118 const box = descriptorOf("environment-box", "Box");
119 const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(senderToolkit, handlers));
120 const context = yield* Layer.build(
121 layerLinkingEnvironment(descriptorOf("environment-a", "A")),
122 );
123 const links = Context.get(context, PeerLinks.PeerLinks);
124 const client = Context.get(context, PeerMcpClient.PeerMcpClient);
125 yield* linkTo(links, b);
126 // A thread id may hold any character; it arrives as sent.
127 const sender = {
128 environmentId: EnvironmentId.make("environment-a"),
129 threadId: ThreadId.make("import:claude/orc lead"),
130 title: "orc lead / opus → fable",
131 };
132 const call = (input: { readonly sender?: typeof sender }) =>
133 client.call({
134 environmentId: box.environmentId,
135 tool: "sender",
136 arguments: {},
137 limits: { runtimeMode: "full-access", interactionMode: "default" },
138 ...input,
139 success: Schema.Struct({ senderThread: Schema.NullOr(OrchestrationV2LinkedSender) }),
140 });
141 expect(yield* call({ sender })).toEqual({ senderThread: sender });
142 expect(yield* call({})).toEqual({ senderThread: null });
143 // A long title is cut to whole characters rather than breaking the call.
144 const long = yield* call({ sender: { ...sender, title: "🧵".repeat(5000) } });
145 expect(long.senderThread?.title).toBe("🧵".repeat(200));
146 // A title holding an unpaired surrogate still lets the call through.
147 const broken = yield* call({ sender: { ...sender, title: "Review \ud800" } });
148 expect(broken.senderThread?.title).toBe("Review \ufffd");
149 }),
150 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
151 );
152
153 it.effect.each([false, true])(
154 "reuses an initialized session before its first call finishes (cancelled: %s)",
155 (cancelFirst) =>
156 Effect.scoped(
157 Effect.gen(function* () {
158 const entered = yield* Deferred.make<void>();
159 const release = yield* Deferred.make<void>();
160 const modes = McpInvocationContext.McpInvocationContext.pipe(
161 Effect.map((scope) => {
162 const ceiling = McpInvocationContext.clientModeCeiling(scope.client);
163 return { modes: `${ceiling.runtimeMode}/${ceiling.interactionMode}` };
164 }),
165 );
166 const handlers = McpToolAccess.toLayer(toolkit, {
167 probe: McpToolAccess.reads(() => modes),
168 refuse: McpToolAccess.reads(() => Effect.fail(refusal)),
169 hold: McpToolAccess.reads(() =>
170 Deferred.succeed(entered, undefined).pipe(
171 Effect.andThen(Deferred.await(release)),
172 Effect.andThen(modes),
173 ),
174 ),
175 });
176 const box = descriptorOf("environment-box", "Box");
177 const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(toolkit, handlers));
178 const context = yield* Layer.build(
179 layerLinkingEnvironment(descriptorOf("environment-a", "A")),
180 );
181 const links = Context.get(context, PeerLinks.PeerLinks);
182 const client = Context.get(context, PeerMcpClient.PeerMcpClient);
183 yield* linkTo(links, b);
184 const held = yield* client
185 .call({
186 environmentId: box.environmentId,
187 tool: "hold",
188 arguments: {},
189 limits: { runtimeMode: "full-access", interactionMode: "default" },
190 success: Result,
191 })
192 .pipe(Effect.forkScoped);
193 yield* Deferred.await(entered);
194 if (cancelFirst) yield* Fiber.interrupt(held);
195 const before = (yield* Ref.get(b.bearers)).length;
196 expect(
197 yield* client.call({
198 environmentId: box.environmentId,
199 tool: "probe",
200 arguments: {},
201 limits: { runtimeMode: "approval-required", interactionMode: "plan" },
202 success: Result,
203 }),
204 ).toEqual({ modes: "approval-required/plan" });
205 // One tool POST; no second initialize or initialized notification.
206 expect((yield* Ref.get(b.bearers)).length - before).toBe(1);
207 yield* Deferred.succeed(release, undefined);
208 if (!cancelFirst) expect(yield* Fiber.join(held)).toEqual({ modes: "auto/default" });
209 }),
210 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
211 );
212
213 it.effect("keeps a link healthy when the peer refuses a call", () =>
214 Effect.scoped(
215 Effect.gen(function* () {
216 const handlers = McpToolAccess.toLayer(toolkit, {
217 probe: McpToolAccess.reads(() => Effect.succeed({ modes: "" })),
218 hold: McpToolAccess.reads(() => Effect.succeed({ modes: "" })),
219 refuse: McpToolAccess.reads(() => Effect.fail(refusal)),
220 });
221 const box = descriptorOf("environment-box", "Box");
222 const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(toolkit, handlers));
223 const context = yield* Layer.build(
224 layerLinkingEnvironment(descriptorOf("environment-a", "A")),
225 );
226 const links = Context.get(context, PeerLinks.PeerLinks);
227 const client = Context.get(context, PeerMcpClient.PeerMcpClient);
228 yield* linkTo(links, b);
229 yield* links.recordOutcome(box.environmentId, { error: "earlier outage" });
230 const refused = yield* client
231 .call({
232 environmentId: box.environmentId,
233 tool: "refuse",
234 arguments: {},
235 limits: { runtimeMode: "full-access", interactionMode: "default" },
236 success: Result,
237 })
238 .pipe(Effect.flip);
239 // The agent hears the peer's own refusal; the link answered, so it is not failing.
240 expect(refused).toMatchObject({ code: refusal.code, message: refusal.message });
241 const link = yield* links.get(box.environmentId);
242 expect(link._tag === "Some" ? link.value.lastError : "missing").toBeNull();
243 }),
244 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
245 );
246
247 it.effect("keeps the expiry the peer answers with, so a used link outlives its first 30 days", () =>
248 Effect.scoped(
249 Effect.gen(function* () {
250 const handlers = McpToolAccess.toLayer(toolkit, {
251 probe: McpToolAccess.reads(() => Effect.succeed({ modes: "" })),
252 hold: McpToolAccess.reads(() => Effect.succeed({ modes: "" })),
253 refuse: McpToolAccess.reads(() => Effect.fail(refusal)),
254 });
255 const box = descriptorOf("environment-box", "Box");
256 const b = yield* servePeer(box, McpHttpServer.toolkitRegistration(toolkit, handlers));
257 const context = yield* Layer.build(
258 layerLinkingEnvironment(descriptorOf("environment-a", "A")),
259 );
260 const links = Context.get(context, PeerLinks.PeerLinks);
261 const client = Context.get(context, PeerMcpClient.PeerMcpClient);
262 const linked = yield* linkTo(links, b);
263 const day = 24 * 60 * 60 * 1000;
264 const call = client.call({
265 environmentId: box.environmentId,
266 tool: "probe",
267 arguments: {},
268 limits: { runtimeMode: "full-access", interactionMode: "default" },
269 success: Result,
270 });
271 const storedExpiry = links
272 .get(box.environmentId)
273 .pipe(
274 Effect.map((link) => (Option.isSome(link) ? link.value.expiresAt.epochMilliseconds : 0)),
275 );
276 const expiryThere = b.linkedSessions.pipe(
277 Effect.map((sessions) => sessions[0]?.expiresAt.epochMilliseconds),
278 );
279 const linkedAt = linked.linkedAt.epochMilliseconds;
280 expect(yield* storedExpiry).toBe(linkedAt + 30 * day);
281
282 yield* TestClock.adjust("20 days");
283 yield* call;
284 expect(yield* expiryThere).toBe(linkedAt + 50 * day);
285 expect(yield* storedExpiry).toBe(linkedAt + 50 * day);
286
287 yield* TestClock.adjust("20 days");
288 expect(yield* call).toEqual({ modes: "" });
289 expect(yield* storedExpiry).toBe(linkedAt + 70 * day);
290
291 // Idle for the whole window, the link expires on both sides.
292 yield* TestClock.adjust("30 days");
293 expect((yield* call.pipe(Effect.flip)).code).toBe("capability_denied");
294 expect((yield* links.list)[0]?.status).toBe("expired");
295 expect(yield* b.linkedSessions).toEqual([]);
296 }),
297 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
298 );
299
300 it.effect("renews a missing peer session once and reuses its replacement", () =>
301 Effect.gen(function* () {
302 const sessionHeaders: Array<string | undefined> = [];
303 const statuses = [200, 202, 404, 200, 202, 200, 200, 200];
304 const outcomes: Array<string | null> = [];
305 const expiries: Array<string> = [];
306 const http = HttpClient.make((request) =>
307 Effect.sync(() => {
308 const index = sessionHeaders.length;
309 sessionHeaders.push(request.headers["mcp-session-id"]);
310 const status = statuses[index];
311 if (status === undefined) throw new Error("Unexpected retry");
312 return HttpClientResponse.fromWeb(
313 request,
314 new Response(
315 index === 7
316 ? "{}"
317 : index >= 5
318 ? JSON.stringify({
319 result: {
320 content: [{ type: "text", text: '{"modes":"approval-required/plan"}' }],
321 },
322 })
323 : "",
324 {
325 status,
326 headers:
327 index === 0
328 ? {
329 "mcp-session-id": "old",
330 [McpInvocationContext.LINK_EXPIRES_AT_HEADER]: "1970-01-02T00:00:00.000Z",
331 }
332 : index === 3
333 ? { "mcp-session-id": "renewed" }
334 : {},
335 },
336 ),
337 );
338 }),
339 );
340 const box = descriptorOf("environment-box", "Box");
341 const context = yield* Layer.build(
342 PeerMcpClient.layer.pipe(
343 Layer.provide(
344 Layer.mergeAll(
345 Layer.succeed(HttpClient.HttpClient, http),
346 Layer.mock(PeerLinks.PeerLinks)({
347 resolve: () =>
348 Effect.succeed({
349 link: {
350 environmentId: box.environmentId,
351 label: box.label,
352 urls: ["https://peer.example"],
353 access: "auto",
354 linkedAt: DateTime.makeUnsafe(0),
355 expiresAt: DateTime.makeUnsafe(1),
356 lastReachedAt: null,
357 lastError: null,
358 },
359 url: "https://peer.example",
360 token: "fixture",
361 capabilities: box.capabilities,
362 }),
363 recordOutcome: (_, outcome) => Effect.sync(() => outcomes.push(outcome.error)),
364 recordExpiry: (_, expiresAt) =>
365 Effect.sync(() => expiries.push(DateTime.formatIso(expiresAt))),
366 }),
367 ),
368 ),
369 ),
370 );
371 const client = Context.get(context, PeerMcpClient.PeerMcpClient);
372 for (let call = 0; call < 2; call++) {
373 expect(
374 yield* client.call({
375 environmentId: box.environmentId,
376 tool: "probe",
377 arguments: {},
378 limits: { runtimeMode: "approval-required", interactionMode: "plan" },
379 success: Result,
380 }),
381 ).toEqual({ modes: "approval-required/plan" });
382 }
383 // An answer with neither a result nor an error is the link's problem, not the call's.
384 const empty = yield* client
385 .call({
386 environmentId: box.environmentId,
387 tool: "probe",
388 arguments: {},
389 limits: { runtimeMode: "approval-required", interactionMode: "plan" },
390 success: Result,
391 })
392 .pipe(Effect.flip);
393 expect(outcomes).toEqual([null, null, empty.message]);
394 // Only the handshake answered with an expiry, and it is kept.
395 expect(expiries).toEqual(["1970-01-02T00:00:00.000Z"]);
396 expect(sessionHeaders).toEqual([
397 undefined,
398 "old",
399 "old",
400 undefined,
401 "renewed",
402 "renewed",
403 "renewed",
404 "renewed",
405 ]);
406 }),
407 );
408
409 it.effect("bounds the session handshake, not a tool call that waits longer", () =>
410 Effect.gen(function* () {
411 const arrived = yield* Queue.unbounded<number>();
412 const answer = yield* Deferred.make<void>();
413 let requests = 0;
414 const http = HttpClient.make((request) =>
415 Effect.gen(function* () {
416 const index = requests++;
417 yield* Queue.offer(arrived, index);
418 // The first initialize, then the next initialized notification, never answer;
419 // the third session's tool call answers late.
420 if (index === 0 || index === 2) return yield* Effect.never;
421 if (index === 5) yield* Deferred.await(answer);
422 return HttpClientResponse.fromWeb(
423 request,
424 new Response(index === 5 ? probeResult : "", {
425 status: index === 4 ? 202 : 200,
426 headers: { "mcp-session-id": "session" },
427 }),
428 );
429 }),
430 );
431 const probe = yield* probeThrough(http);
432
433 for (const requestsBeforeStall of [1, 2]) {
434 const stalled = yield* probe.pipe(Effect.flip, Effect.forkScoped);
435 yield* Queue.takeN(arrived, requestsBeforeStall);
436 yield* TestClock.adjust(Duration.seconds(10));
437 expect(yield* Fiber.join(stalled)).toMatchObject({
438 code: "orchestration_error",
439 message: "The linked environment stopped answering.",
440 });
441 }
442
443 const waiting = yield* Effect.forkScoped(probe);
444 yield* Queue.takeN(arrived, 3);
445 yield* TestClock.adjust(Duration.minutes(1));
446 yield* Deferred.succeed(answer, undefined);
447 expect(yield* Fiber.join(waiting)).toEqual({ modes: "approval-required/plan" });
448 }),
449 );