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