Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PeerLinkRequests.ts

419 lines15.6 KB

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