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