@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 494 lines 18.2 KB
Raw
1 /**
2 * Links an agent asks the user to make. The user picks the machine and access in a card, and
3 * their client answers with its addresses and a pairing code that goes straight to
4 * `PeerLinks.link`, never into the transcript or the agent's context. Asking does not wait
5 * (provider CLIs abandon a long tool call): the answer reaches the agent as a notification.
6 */
7 import {
8 CommandId,
9 type EnvironmentId,
10 MessageId,
11 type NodeId,
12 type OrchestrationV2Notification,
13 type OrchestrationV2TurnItem,
14 type OrchestratorMcpEnvironmentLinkInput,
15 type OrchestratorMcpEnvironmentLinkResult,
16 OrchestratorMcpFailure,
17 type PeerLink,
18 PeerLinkError,
19 PeerLinkRequestError,
20 type PeerLinkRequestAnswerInput,
21 type RunId,
22 type ThreadId,
23 TurnItemId,
24 } from "@t3tools/contracts";
25 import * as Context from "effect/Context";
26 import * as SecureRandom from "effect/crypto/SecureRandom";
27 import * as DateTime from "effect/DateTime";
28 import * as Effect from "effect/Effect";
29 import * as Layer from "effect/Layer";
30 import * as Option from "effect/Option";
31 import * as KeyedLock from "@t3tools/shared/KeyedLock";
32
33 import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
34 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
35 import * as PeerLinks from "./PeerLinks.ts";
36
37 type LinkRequestItem = Extract<OrchestrationV2TurnItem, { readonly type: "link_request" }>;
38
39 /** The request as it was asked, which every update of its card repeats. */
40 type LinkRequestAsk = Pick<
41 LinkRequestItem,
42 "id" | "threadId" | "url" | "reason" | "environmentId" | "hint" | "requestedAccess"
43 > & { readonly runId: RunId; readonly nodeId: NodeId };
44
45 /** The notification that tells the agent how its card ended. */
46 type LinkRequestWake = {
47 readonly messageId: MessageId;
48 readonly text: string;
49 readonly notification: OrchestrationV2Notification;
50 };
51
52 /** What a card update may change. */
53 type LinkRequestOutcome = Pick<
54 LinkRequestItem,
55 "linkStatus" | "linkedEnvironmentId" | "linkedLabel" | "linkedAccess" | "failure"
56 >;
57
58 const errorMessage = (error: unknown) =>
59 error instanceof Error ? error.message : typeof error === "string" ? error : "unknown error";
60
61 export class PeerLinkRequests extends Context.Service<
62 PeerLinkRequests,
63 {
64 /**
65 * Shows a link card in the calling thread and returns at once. A retry
66 * with the same clientRequestId and MCP credential returns the card's
67 * current outcome.
68 */
69 readonly request: (
70 scope: McpInvocationContext.McpInvocationScope,
71 input: OrchestratorMcpEnvironmentLinkInput,
72 ) => Effect.Effect<OrchestratorMcpEnvironmentLinkResult, OrchestratorMcpFailure>;
73 /**
74 * Answers a pending card and tells the agent. Linking uses the pairing
75 * code once; a link the other environment refuses closes the card as
76 * failed, with its reason.
77 */
78 readonly answer: (
79 input: PeerLinkRequestAnswerInput,
80 ) => Effect.Effect<void, PeerLinkRequestError>;
81 }
82 >()("t3/peer/PeerLinkRequests") {}
83
84 const make = Effect.gen(function* () {
85 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
86 const peerLinks = yield* PeerLinks.PeerLinks;
87 const random = yield* SecureRandom.SecureRandom;
88
89 const readCard = (threadId: ThreadId, turnItemId: TurnItemId) =>
90 threadManagement
91 .getThreadRecords(threadId, ["turnItems"], {
92 turnItemTypes: ["link_request"],
93 messageRoles: [],
94 })
95 .pipe(
96 Effect.map((records) => {
97 const item = records.turnItems.find((candidate) => candidate.id === turnItemId);
98 // A deleted thread's cards went with it.
99 return item?.type === "link_request" && records.thread.deletedAt === null
100 ? item
101 : undefined;
102 }),
103 );
104
105 /**
106 * The stored link to `environmentId`, or nothing once it has expired: an
107 * expired link needs a new pairing code, which only the card asks for.
108 */
109 const usableLink = (environmentId: EnvironmentId) =>
110 Effect.all([peerLinks.get(environmentId), DateTime.now]).pipe(
111 Effect.map(([linked, now]) =>
112 Option.filter(linked, (link) => DateTime.isGreaterThan(link.expiresAt, now)),
113 ),
114 );
115
116 const record = (
117 card: LinkRequestAsk,
118 outcome: LinkRequestOutcome,
119 commandId: CommandId,
120 wake?: LinkRequestWake,
121 answeringTurnItemIds?: ReadonlyArray<TurnItemId>,
122 ) =>
123 threadManagement.dispatch({
124 type: "link_request.record",
125 commandId,
126 threadId: card.threadId,
127 runId: card.runId,
128 nodeId: card.nodeId,
129 turnItemId: card.id,
130 ...(card.url === undefined ? {} : { url: card.url }),
131 reason: card.reason,
132 ...(card.environmentId === undefined ? {} : { environmentId: card.environmentId }),
133 ...(card.hint === undefined ? {} : { hint: card.hint }),
134 ...(card.requestedAccess === undefined ? {} : { requestedAccess: card.requestedAccess }),
135 ...outcome,
136 ...(wake === undefined ? {} : { wake }),
137 ...(answeringTurnItemIds === undefined ? {} : { answeringTurnItemIds }),
138 });
139
140 const linkedOutcome = (linked: PeerLink): LinkRequestOutcome => ({
141 linkStatus: "linked",
142 linkedEnvironmentId: linked.environmentId,
143 linkedLabel: linked.label,
144 linkedAccess: linked.access,
145 });
146
147 // One answer per card at a time: two answers racing on one card must not
148 // both link. Other cards go on while a slow peer holds one.
149 const answerLocks = yield* KeyedLock.make<TurnItemId>();
150 // Per thread, held only to read a card before answering and to record the
151 // answer, never while linking. A link ends older cards for the same
152 // machine, but not one already being answered (its key is in answerLocks);
153 // an answer that starts after that reads the ended card and links nothing.
154 const lifecycleLocks = yield* KeyedLock.make<ThreadId>();
155
156 /**
157 * Closes a card still waiting when its agent retries naming a machine linked
158 * meanwhile. Nothing wakes the agent: the retry itself returns the link.
159 */
160 const closeAsLinked = (threadId: ThreadId, turnItemId: TurnItemId, linked: PeerLink) =>
161 answerLocks.withLock(
162 turnItemId,
163 lifecycleLocks.withLock(
164 threadId,
165 Effect.gen(function* () {
166 const card = yield* readCard(threadId, turnItemId);
167 if (
168 card === undefined ||
169 card.linkStatus !== "pending" ||
170 card.runId === null ||
171 card.nodeId === null
172 ) {
173 return;
174 }
175 yield* record(
176 { ...card, runId: card.runId, nodeId: card.nodeId },
177 linkedOutcome(linked),
178 CommandId.make(`link-request:${card.id}:linked-on-retry`),
179 undefined,
180 yield* answerLocks.activeKeys,
181 );
182 }),
183 ),
184 );
185
186 const request: PeerLinkRequests["Service"]["request"] = Effect.fn("PeerLinkRequests.request")(
187 function* (scope, input) {
188 // The card is shown in, and answered from, the caller's own thread.
189 const threadScope = yield* McpInvocationContext.requireThreadScope(
190 scope,
191 "t3_environment_link",
192 );
193 const threadId = threadScope.thread.threadId;
194 if (!(yield* peerLinks.enabled)) {
195 return yield* new OrchestratorMcpFailure({
196 code: "capability_denied",
197 message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
198 });
199 }
200 const unreadable = (error: unknown) =>
201 new OrchestratorMcpFailure({
202 code: "orchestration_error",
203 message: `Unable to read the link request: ${errorMessage(error)}`,
204 });
205 if (input.url !== undefined && input.environmentId !== undefined) {
206 return yield* new OrchestratorMcpFailure({
207 code: "invalid_request",
208 message:
209 "Pass either environmentId or url, not both. Pass neither to let the user pick the machine.",
210 });
211 }
212 // A machine already linked needs no card: the agent can use it now.
213 if (input.environmentId !== undefined) {
214 const linked = yield* usableLink(input.environmentId).pipe(
215 Effect.mapError(
216 (error) =>
217 new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
218 ),
219 );
220 if (Option.isSome(linked)) {
221 if (input.clientRequestId !== undefined) {
222 yield* closeAsLinked(
223 threadId,
224 cardId(threadId, scope.requestNamespace, input.clientRequestId),
225 linked.value,
226 ).pipe(
227 Effect.mapError(
228 (error) =>
229 new OrchestratorMcpFailure({
230 code: "orchestration_error",
231 message: `Could not close the link request: ${errorMessage(error)}`,
232 }),
233 ),
234 );
235 }
236 return {
237 status: "linked",
238 environmentId: linked.value.environmentId,
239 label: linked.value.label,
240 access: linked.value.access,
241 } as const;
242 }
243 }
244 const key = input.clientRequestId ?? (yield* random.uuidV4());
245 // A retry with the same clientRequestId finds this card and records nothing.
246 const turnItemId = cardId(threadId, scope.requestNamespace, key);
247 if (input.clientRequestId !== undefined) {
248 const existing = yield* readCard(threadId, turnItemId).pipe(Effect.mapError(unreadable));
249 if (existing !== undefined) return resultOf(existing);
250 }
251 const parent = yield* threadManagement
252 .getThreadRecords(threadId, ["runs"], { messageRoles: [] })
253 .pipe(Effect.mapError(unreadable));
254 const run = ThreadManagementService.latestActiveRun(parent);
255 if (
256 run === undefined ||
257 run.rootNodeId === null ||
258 run.providerInstanceId !== threadScope.thread.providerInstanceId
259 ) {
260 return yield* new OrchestratorMcpFailure({
261 code: "parent_not_active",
262 message:
263 "Asking to link an environment requires an active run owned by this MCP provider session.",
264 });
265 }
266 // Anything can answer at an address as any machine, so a card for an
267 // address names none. The client names it from addresses it already has.
268 yield* record(
269 {
270 id: turnItemId,
271 threadId,
272 runId: run.id,
273 nodeId: run.rootNodeId,
274 ...(input.url === undefined ? {} : { url: input.url }),
275 reason: input.reason ?? "",
276 ...(input.environmentId === undefined ? {} : { environmentId: input.environmentId }),
277 ...(input.hint === undefined ? {} : { hint: input.hint }),
278 ...(input.requestedAccess === undefined
279 ? {}
280 : { requestedAccess: input.requestedAccess }),
281 },
282 { linkStatus: "pending" },
283 CommandId.make(
284 `command:mcp:${encodeURIComponent(scope.requestNamespace)}:link-pending:${encodeURIComponent(key)}`,
285 ),
286 ).pipe(
287 Effect.mapError(
288 (error) =>
289 new OrchestratorMcpFailure({
290 code: "orchestration_error",
291 message: `Could not record the link request: ${errorMessage(error)}`,
292 }),
293 ),
294 );
295 return pendingResult(turnItemId);
296 },
297 Effect.withSpan("PeerLinkRequests.request"),
298 );
299
300 /** Links the machine the user picked, or finds the link they chose to keep. */
301 const answerOutcome = (
302 answer: PeerLinkRequestAnswerInput["answer"],
303 ): Effect.Effect<LinkRequestOutcome> => {
304 switch (answer.type) {
305 case "decline":
306 return Effect.succeed({ linkStatus: "declined" });
307 case "use-existing":
308 return usableLink(answer.environmentId).pipe(
309 Effect.flatMap(
310 Option.match({
311 onNone: () =>
312 Effect.fail(
313 new PeerLinkError({
314 reason: "unknown_link",
315 message:
316 "That environment is no longer linked here, or its link expired. Link it again.",
317 }),
318 ),
319 onSome: (linked) => Effect.succeed(linkedOutcome(linked)),
320 }),
321 ),
322 Effect.catch((error) =>
323 Effect.succeed<LinkRequestOutcome>({ linkStatus: "failed", failure: error.message }),
324 ),
325 );
326 case "link": {
327 const [url, ...alternateUrls] = answer.urls;
328 return peerLinks
329 .link({
330 url,
331 ...(alternateUrls.length === 0 ? {} : { alternateUrls }),
332 pairingCode: answer.pairingCode,
333 access: answer.access,
334 ...(answer.environmentId === undefined
335 ? {}
336 : { expectedEnvironmentId: answer.environmentId }),
337 ...(answer.label === undefined ? {} : { expectedLabel: answer.label }),
338 })
339 .pipe(
340 Effect.map(linkedOutcome),
341 Effect.catch((error) =>
342 Effect.succeed<LinkRequestOutcome>({ linkStatus: "failed", failure: error.message }),
343 ),
344 );
345 }
346 }
347 };
348
349 const answer: PeerLinkRequests["Service"]["answer"] = Effect.fn("PeerLinkRequests.answer")(
350 function* (input) {
351 yield* Effect.annotateCurrentSpan({
352 "orchestration_v2.thread_id": input.threadId,
353 "link_request.answer": input.answer.type,
354 });
355 const card = yield* lifecycleLocks.withLock(
356 input.threadId,
357 Effect.gen(function* () {
358 const card = yield* readCard(input.threadId, input.turnItemId).pipe(
359 Effect.mapError((cause) => new PeerLinkRequestError({ reason: "load_failed", cause })),
360 );
361 if (card === undefined || card.runId === null || card.nodeId === null) {
362 return yield* new PeerLinkRequestError({ reason: "not_found" });
363 }
364 // Any time while the card is open: the agent hears the answer as a
365 // notification, whether or not its run is still going.
366 if (card.linkStatus !== "pending") {
367 return yield* new PeerLinkRequestError({ reason: "already_answered" });
368 }
369 return { ...card, runId: card.runId, nodeId: card.nodeId };
370 }),
371 );
372 // An id beside an address is what answered there, recorded by an older
373 // server. Linking that machine could send its pairing code to the address.
374 const outcome: LinkRequestOutcome =
375 card.url !== undefined &&
376 card.environmentId !== undefined &&
377 input.answer.type === "link" &&
378 input.answer.environmentId !== undefined
379 ? {
380 linkStatus: "failed",
381 failure: "This request is from before an update. Ask for the link again.",
382 }
383 : yield* answerOutcome(input.answer);
384 // If Stop closed the card while linking, the card keeps that; the link
385 // itself stands and Settings lists it.
386 yield* lifecycleLocks.withLock(
387 input.threadId,
388 Effect.flatMap(answerLocks.activeKeys, (answering) =>
389 record(
390 card,
391 outcome,
392 CommandId.make(`link-request:${card.id}:${outcome.linkStatus}`),
393 {
394 messageId: MessageId.make(`message:link-request:${card.id}`),
395 ...outcomeNotice(card, outcome),
396 },
397 answering,
398 ),
399 ).pipe(
400 Effect.mapError((cause) => new PeerLinkRequestError({ reason: "record_failed", cause })),
401 ),
402 );
403 },
404 (effect, input) =>
405 effect.pipe(
406 (effect) => answerLocks.withLock(input.turnItemId, effect),
407 Effect.withSpan("PeerLinkRequests.answer"),
408 ),
409 );
410
411 return PeerLinkRequests.of({ request, answer });
412 });
413
414 /**
415 * Turn item ids are global; scope the key to this thread and provider session,
416 * since a later session may reuse it.
417 */
418 const cardId = (threadId: ThreadId, requestNamespace: string, key: string) =>
419 TurnItemId.make(
420 `turn-item:link-request:${encodeURIComponent(threadId)}:${encodeURIComponent(requestNamespace)}:${encodeURIComponent(key)}`,
421 );
422
423 const pendingResult = (turnItemId: TurnItemId): OrchestratorMcpEnvironmentLinkResult => ({
424 status: "pending",
425 turnItemId,
426 });
427
428 /** What a retry hears: the card's outcome, without anything the user typed. */
429 const resultOf = (card: LinkRequestItem): OrchestratorMcpEnvironmentLinkResult => {
430 switch (card.linkStatus) {
431 case "pending":
432 return pendingResult(card.id);
433 case "linked":
434 return {
435 status: "linked",
436 environmentId: card.linkedEnvironmentId!,
437 label: card.linkedLabel ?? linkTarget(card),
438 access: card.linkedAccess!,
439 };
440 case "failed":
441 return { status: "failed", message: card.failure ?? "The link could not be made." };
442 case "declined":
443 case "cancelled":
444 return { status: card.linkStatus };
445 }
446 };
447
448 /** What the agent's words call the target: its address, its id, or the user's pick. */
449 const linkTarget = (card: Pick<LinkRequestItem, "url" | "environmentId">) =>
450 card.url ?? card.environmentId ?? "a machine";
451
452 /**
453 * The notification an answer sends the agent: what the card says, and what
454 * to do next. It carries the outcome only, never the pairing code.
455 */
456 const outcomeNotice = (
457 card: Pick<LinkRequestItem, "url" | "environmentId">,
458 outcome: LinkRequestOutcome,
459 ): Omit<LinkRequestWake, "messageId"> => {
460 const target = linkTarget(card);
461 switch (outcome.linkStatus) {
462 case "linked": {
463 const label = outcome.linkedLabel ?? target;
464 return {
465 text: `The user linked ${label} with ${outcome.linkedAccess} access. Pass environmentId ${outcome.linkedEnvironmentId} to act there.`,
466 notification: {
467 source: { kind: "background_task" },
468 outcome: "completed",
469 summary: `Linked ${label}`,
470 },
471 };
472 }
473 case "failed":
474 return {
475 text: `Linking ${target} failed: ${outcome.failure ?? "the other environment refused"}. Call t3_environment_link again if the user still wants it.`,
476 notification: {
477 source: { kind: "background_task" },
478 outcome: "failed",
479 summary: `Could not link ${target}`,
480 },
481 };
482 default:
483 return {
484 text: `The user declined to link ${target}.`,
485 notification: {
486 source: { kind: "background_task" },
487 outcome: "cancelled",
488 summary: `Declined to link ${target}`,
489 },
490 };
491 }
492 };
493
494 export const layer = Layer.effect(PeerLinkRequests, make);