@devries-cameron20 / t3code Mirror · read-only / commits / 8b14660b27
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 22, 14:30 UTC

feat(server,web,mobile): an agent sets up a link to another environment (#17129)

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Julius Marminge committed Oct 27, 2026 at 14:04 UTC 8b14660b27872c4ebc061ea2049632ae2762e471
62 files changed +4642 -122
apps/mobile/src/features/threads/LinkRequestCard.tsx new
+514
@@ -0,0 +1,514 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import {
3 + type LinkableMachine,
4 + linkRequestAnswerInput,
5 + linkRequestDefaultAccess,
6 + linkRequestDisplay,
7 + linkRequestFailureMessage,
8 + linkRequestInitialMachine,
9 + type LinkRequestItem,
10 + linkRequestTargetName,
11 + rankMachinesByHint,
12 +} from "@t3tools/client-runtime/link-request";
13 +import {
14 + isAtomCommandInterrupted,
15 + squashAtomCommandFailure,
16 +} from "@t3tools/client-runtime/state/runtime";
17 +import {
18 + AuthAccessWriteScope,
19 + type AuthMcpClientAccess,
20 + type EnvironmentId,
21 + type OrchestrationV2ProjectedTurnItem,
22 +} from "@t3tools/contracts";
23 +import * as Option from "effect/Option";
24 +import * as Result from "effect/Result";
25 +import { useMemo, useRef, useState } from "react";
26 +import { Modal, Platform, Pressable, ScrollView, View, type ColorValue } from "react-native";
27 +import { useSafeAreaInsets } from "react-native-safe-area-context";
28 +
29 +import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
30 +import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
31 +import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
32 +import { useLinkableMachines } from "../../state/peerLinks";
33 +import { mintPairingCodeOn } from "../../state/peerPairingCode";
34 +import { serverEnvironment } from "../../state/server";
35 +import { useEnvironmentScope, usePreparedConnection } from "../../state/session";
36 +import { useAtomCommand } from "../../state/use-atom-command";
37 +import { SettingsChoiceRow } from "../settings/components/SettingsChoiceRow";
38 +import { SettingsSection } from "../settings/components/SettingsSection";
39 +import { Button } from "../../components/ui/Button";
40 +import { RUNTIME_MODE_CHOICES } from "./thread-settings-options";
41 +
42 +/** The same five levels as web's access picker: read-only, then the runtime modes. */
43 +const ACCESS_CHOICES: ReadonlyArray<{
44 + readonly access: AuthMcpClientAccess;
45 + readonly label: string;
46 + readonly description: string;
47 +}> = [
48 + {
49 + access: "read-only",
50 + label: "Read only",
51 + description: "Read projects and threads. Cannot start, message or change anything.",
52 + },
53 + ...RUNTIME_MODE_CHOICES.map((choice) => ({ ...choice, access: choice.mode })),
54 +];
55 +const accessLabel = (access: AuthMcpClientAccess) =>
56 + ACCESS_CHOICES.find((choice) => choice.access === access)?.label ?? access;
57 +
58 +const LINK_SYMBOL: AppSymbolName = { ios: "link", android: "desktop_windows" };
59 +
60 +/** The machine list's row for linking by an address typed in. */
61 +const ANOTHER_ADDRESS = "another-address";
62 +
63 +/** Whether the agent left the machine for the user to pick. */
64 +const picksMachine = (item: LinkRequestItem) =>
65 + item.environmentId === undefined && item.url === undefined;
66 +
67 +/**
68 + * Feed card for a link an agent asked the user to make. The user picks the
69 + * access in a sheet; the pairing code lives only in that sheet's state and
70 + * the RPC payload, and is never logged, alerted, or persisted.
71 + */
72 +export function LinkRequestCard(props: {
73 + readonly environmentId: EnvironmentId;
74 + readonly projectedItem: OrchestrationV2ProjectedTurnItem;
75 + readonly iconColor: ColorValue;
76 +}) {
77 + const { item, visibility } = props.projectedItem;
78 + if (item.type !== "link_request") return null;
79 + const display = linkRequestDisplay(item, visibility, accessLabel);
80 + if (display.kind === "pending") {
81 + return <PendingLinkRequest environmentId={props.environmentId} item={item} />;
82 + }
83 + const icon: AppSymbolName =
84 + display.kind === "pending-elsewhere"
85 + ? LINK_SYMBOL
86 + : display.outcome === "linked"
87 + ? "checkmark"
88 + : display.outcome === "failed"
89 + ? "xmark"
90 + : "minus";
91 + return (
92 + <View className="mb-3 min-h-9 flex-row items-center gap-2 px-1">
93 + <SymbolView name={icon} size={13} tintColor={props.iconColor} type="monochrome" />
94 + <Text className="flex-1 font-sans text-sm text-foreground-muted" numberOfLines={2}>
95 + {display.label}
96 + </Text>
97 + </View>
98 + );
99 +}
100 +
101 +function PendingLinkRequest(props: {
102 + readonly environmentId: EnvironmentId;
103 + readonly item: LinkRequestItem;
104 +}) {
105 + const { item } = props;
106 + const [open, setOpen] = useState(false);
107 + const [declining, setDeclining] = useState(false);
108 + const [error, setError] = useState<string | null>(null);
109 + const answer = useAtomCommand(serverEnvironment.answerLinkRequest, {
110 + label: "decline link request",
111 + reportFailure: false,
112 + reportDefect: false,
113 + });
114 + const canAnswer = useAtomValue(
115 + serverEnvironment.answerLinkRequest.permissionAtom(props.environmentId),
116 + );
117 + const target = linkRequestTargetName(item);
118 +
119 + const decline = async () => {
120 + const input = linkRequestAnswerInput(item, { type: "decline" });
121 + if (input === null) return;
122 + setDeclining(true);
123 + setError(null);
124 + const result = await answer({ environmentId: props.environmentId, input }).finally(() =>
125 + setDeclining(false),
126 + );
127 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
128 + setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
129 + }
130 + };
131 +
132 + return (
133 + <View className="mb-3 gap-3 rounded-[20px] border border-border bg-card-alt p-4">
134 + <View className="gap-1">
135 + <Text className="font-t3-bold text-base text-foreground">
136 + {picksMachine(item)
137 + ? "Link a machine to this environment"
138 + : `Link ${target} to this environment`}
139 + </Text>
140 + {item.reason.trim() ? (
141 + <Text className="font-sans text-sm leading-5 text-foreground-muted">{item.reason}</Text>
142 + ) : null}
143 + {item.label !== undefined && item.url !== undefined ? (
144 + <Text className="font-sans text-xs text-foreground-muted" numberOfLines={1}>
145 + {item.url}
146 + </Text>
147 + ) : null}
148 + </View>
149 + {error !== null ? (
150 + <Text
151 + accessibilityRole="alert"
152 + accessibilityLiveRegion="polite"
153 + className="font-sans text-sm text-danger-foreground"
154 + >
155 + {error}
156 + </Text>
157 + ) : null}
158 + {canAnswer ? (
159 + <>
160 + <Button
161 + label={picksMachine(item) ? "Choose machine…" : "Review link…"}
162 + disabled={declining}
163 + onPress={() => setOpen(true)}
164 + tone="primary"
165 + fullWidth
166 + />
167 + <View className="flex-row justify-end">
168 + <Pressable
169 + accessibilityRole="button"
170 + accessibilityState={{ disabled: declining }}
171 + disabled={declining}
172 + hitSlop={8}
173 + className="px-1 py-1 active:opacity-60 disabled:opacity-50"
174 + onPress={() => void decline()}
175 + >
176 + <Text className="font-sans text-xs text-foreground-muted">Decline</Text>
177 + </Pressable>
178 + </View>
179 + </>
180 + ) : (
181 + <Text className="font-sans text-xs text-foreground-muted">
182 + Only a session that manages access here can answer this.
183 + </Text>
184 + )}
185 + {open ? (
186 + <LinkRequestSheet
187 + environmentId={props.environmentId}
188 + item={item}
189 + onClose={() => setOpen(false)}
190 + />
191 + ) : null}
192 + </View>
193 + );
194 +}
195 +
196 +/** What the sheet links; see web's LinkRequestDialog for the same rules. */
197 +type SheetTarget =
198 + | { readonly kind: "none" }
199 + | {
200 + readonly kind: "machine";
201 + readonly environmentId: EnvironmentId;
202 + readonly label: string;
203 + readonly urls: ReadonlyArray<string>;
204 + readonly linked: boolean;
205 + }
206 + | { readonly kind: "address" };
207 +
208 +function resolveTarget(
209 + item: LinkRequestItem,
210 + machines: ReadonlyArray<LinkableMachine>,
211 + choice: string | null,
212 +): SheetTarget {
213 + if (item.environmentId === undefined && item.url !== undefined) return { kind: "address" };
214 + const chosen = item.environmentId ?? choice;
215 + if (chosen === null) return { kind: "none" };
216 + if (chosen === ANOTHER_ADDRESS) return { kind: "address" };
217 + const machine = machines.find((candidate) => candidate.environmentId === chosen);
218 + return {
219 + kind: "machine",
220 + environmentId: machine?.environmentId ?? (chosen as EnvironmentId),
221 + label: machine?.label ?? linkRequestTargetName(item),
222 + urls: [...new Set([...(machine?.urls ?? []), ...(item.url === undefined ? [] : [item.url])])],
223 + linked: machine?.linked ?? false,
224 + };
225 +}
226 +
227 +function LinkRequestSheet(props: {
228 + readonly environmentId: EnvironmentId;
229 + readonly item: LinkRequestItem;
230 + readonly onClose: () => void;
231 +}) {
232 + const { item } = props;
233 + const insets = useSafeAreaInsets();
234 + const pickMachine = picksMachine(item);
235 + const listed = useLinkableMachines(props.environmentId, true);
236 + const machines = useMemo(() => rankMachinesByHint(listed, item.hint), [listed, item.hint]);
237 + const [choice, setChoice] = useState<string | null>(null);
238 + const [address, setAddress] = useState(item.url ?? "");
239 + const [access, setAccess] = useState<AuthMcpClientAccess>(() => linkRequestDefaultAccess(item));
240 + const [pairingCode, setPairingCode] = useState("");
241 + const [busy, setBusy] = useState(false);
242 + const [error, setError] = useState<string | null>(null);
243 + const [mintFailed, setMintFailed] = useState<ReadonlySet<EnvironmentId>>(new Set());
244 + // Submit then a tap can both run before a re-render; this guard is synchronous.
245 + const inFlight = useRef(false);
246 + const answer = useAtomCommand(serverEnvironment.answerLinkRequest, {
247 + label: "answer link request",
248 + // The failure cause holds the request, and with it the code; keep it out of the console.
249 + reportFailure: false,
250 + reportDefect: false,
251 + });
252 + const selected = choice ?? linkRequestInitialMachine(item, machines);
253 + const target = resolveTarget(item, machines, selected);
254 + const targetName = target.kind === "machine" ? target.label : linkRequestTargetName(item);
255 + // This phone can mint a code there when it is connected to that environment
256 + // with a session that may create pairing links.
257 + const targetId = target.kind === "machine" ? target.environmentId : null;
258 + const connected = usePreparedConnection(targetId);
259 + const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
260 + const canMint =
261 + targetId !== null && Option.isSome(connected) && mayMint && !mintFailed.has(targetId);
262 + const needsAddress =
263 + target.kind === "address" || (target.kind === "machine" && target.urls.length === 0);
264 + const useExisting = target.kind === "machine" && target.linked;
265 + const ready =
266 + target.kind !== "none" &&
267 + (useExisting ||
268 + ((!needsAddress || address.trim().length > 0) && (canMint || pairingCode.trim().length > 0)));
269 +
270 + const prepareAnswer = async () => {
271 + if (target.kind === "none") return null;
272 + if (target.kind === "machine" && target.linked) {
273 + return linkRequestAnswerInput(item, {
274 + type: "use-existing",
275 + environmentId: target.environmentId,
276 + });
277 + }
278 + let code = pairingCode;
279 + if (canMint && targetId !== null) {
280 + const minted = await mintPairingCodeOn(targetId, access);
281 + if (Result.isFailure(minted)) {
282 + setMintFailed((failed) => new Set(failed).add(targetId));
283 + setError(linkRequestFailureMessage(minted.failure));
284 + return null;
285 + }
286 + code = minted.success;
287 + }
288 + return linkRequestAnswerInput(item, {
289 + type: "link",
290 + target:
291 + target.kind === "address"
292 + ? { url: address }
293 + : { ...target, urls: needsAddress ? [address.trim()] : target.urls },
294 + access,
295 + pairingCode: code,
296 + });
297 + };
298 +
299 + const submit = async () => {
300 + if (inFlight.current || target.kind === "none") return;
301 + inFlight.current = true;
302 + setBusy(true);
303 + setError(null);
304 + const input = await prepareAnswer();
305 + const result =
306 + input === null ? null : await answer({ environmentId: props.environmentId, input });
307 + inFlight.current = false;
308 + setBusy(false);
309 + if (result === null) return;
310 + if (result._tag === "Success") {
311 + setPairingCode("");
312 + props.onClose();
313 + } else if (!isAtomCommandInterrupted(result)) {
314 + setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
315 + }
316 + };
317 +
318 + return (
319 + <Modal
320 + animationType="slide"
321 + presentationStyle={Platform.OS === "ios" ? "pageSheet" : "fullScreen"}
322 + // An answer that lands after a close would still link, and would close a reopened sheet.
323 + onRequestClose={() => {
324 + if (!busy) props.onClose();
325 + }}
326 + >
327 + <ScrollView
328 + className="flex-1 bg-sheet-solid"
329 + contentContainerClassName="gap-5 p-5"
330 + contentContainerStyle={{ paddingBottom: insets.bottom + 20 }}
331 + keyboardShouldPersistTaps="handled"
332 + >
333 + <View className="gap-1">
334 + <Text className="font-t3-bold text-lg text-foreground">
335 + {pickMachine ? "Link a machine" : `Link ${targetName}`}
336 + </Text>
337 + <Text className="font-sans text-sm leading-5 text-foreground-muted">
338 + Agents here can then launch, message and wait on threads there. It appears in that
339 + machine's Connections, where it can be revoked.
340 + </Text>
341 + {!pickMachine && item.url !== undefined ? (
342 + <Text className="font-sans text-xs text-foreground-muted" numberOfLines={1}>
343 + {item.url}
344 + </Text>
345 + ) : null}
346 + </View>
347 + {pickMachine ? (
348 + <SettingsSection title="Machine">
349 + {machines.map((machine, index) => (
350 + <MachineRow
351 + key={machine.environmentId}
352 + machine={machine}
353 + selected={selected === machine.environmentId}
354 + separated={index > 0}
355 + disabled={busy}
356 + onPress={() => {
357 + setChoice(machine.environmentId);
358 + setError(null);
359 + }}
360 + />
361 + ))}
362 + <SettingsChoiceRow
363 + label="Another address…"
364 + description="Link a machine this app does not know, by its https or Tailscale address."
365 + selected={selected === ANOTHER_ADDRESS}
366 + separated={machines.length > 0}
367 + disabled={busy}
368 + onPress={() => {
369 + setChoice(ANOTHER_ADDRESS);
370 + setError(null);
371 + }}
372 + />
373 + </SettingsSection>
374 + ) : null}
375 + {needsAddress && !(item.url !== undefined && item.environmentId === undefined) ? (
376 + <View className="gap-2">
377 + <TextInput
378 + accessibilityLabel="Address"
379 + placeholder="https://machine.tailnet.ts.net"
380 + value={address}
381 + onChangeText={setAddress}
382 + editable={!busy}
383 + autoCorrect={false}
384 + autoCapitalize="none"
385 + keyboardType="url"
386 + spellCheck={false}
387 + />
388 + {target.kind === "machine" ? (
389 + <Text className="font-sans text-xs text-foreground-muted">
390 + This app has no address for {target.label} that another machine can reach. Enter its
391 + https or Tailscale address.
392 + </Text>
393 + ) : null}
394 + </View>
395 + ) : null}
396 + {useExisting ? (
397 + <Text className="font-sans text-sm leading-5 text-foreground-muted">
398 + This environment is already linked to {targetName}. The agent can use that link as it
399 + is; change its access in Settings → Connections.
400 + </Text>
401 + ) : target.kind === "none" ? null : (
402 + <>
403 + {canMint ? null : (
404 + <View className="gap-2">
405 + <TextInput
406 + accessibilityLabel="Pairing code"
407 + placeholder="Paste the code"
408 + value={pairingCode}
409 + onChangeText={setPairingCode}
410 + editable={!busy}
411 + autoCorrect={false}
412 + autoCapitalize="none"
413 + autoComplete="one-time-code"
414 + textContentType="oneTimeCode"
415 + spellCheck={false}
416 + />
417 + <Text className="font-sans text-xs text-foreground-muted">
418 + Create a link on {targetName}: Settings → Connections → Create link, then paste
419 + its code here.
420 + </Text>
421 + </View>
422 + )}
423 + <SettingsSection title="What agents here may do there">
424 + {ACCESS_CHOICES.map((choice, index) => (
425 + <SettingsChoiceRow
426 + key={choice.access}
427 + label={choice.label}
428 + description={choice.description}
429 + selected={choice.access === access}
430 + separated={index > 0}
431 + disabled={busy}
432 + onPress={() => setAccess(choice.access)}
433 + />
434 + ))}
435 + </SettingsSection>
436 + <Text className="font-sans text-xs text-foreground-muted">
437 + An agent here never gets more there than its own mode here either. Threads it starts
438 + there cannot change that environment's own threads, projects or settings.
439 + </Text>
440 + </>
441 + )}
442 + {error !== null ? (
443 + <Text
444 + accessibilityRole="alert"
445 + accessibilityLiveRegion="polite"
446 + className="font-sans text-sm text-danger-foreground"
447 + >
448 + {error}
449 + </Text>
450 + ) : null}
451 + <Button
452 + label={busy ? "Linking…" : useExisting ? "Use this link" : "Link"}
453 + disabled={busy || !ready}
454 + onPress={() => void submit()}
455 + tone="primary"
456 + fullWidth
457 + />
458 + <Button label="Cancel" tone="secondary" disabled={busy} onPress={props.onClose} fullWidth />
459 + </ScrollView>
460 + </Modal>
461 + );
462 +}
463 +
464 +/** One machine in the sheet's list: its glyph, name, and whether it is linked or reachable. */
465 +function MachineRow(props: {
466 + readonly machine: LinkableMachine;
467 + readonly selected: boolean;
468 + readonly separated: boolean;
469 + readonly disabled: boolean;
470 + readonly onPress: () => void;
471 +}) {
472 + const { machine } = props;
473 + const status = machine.linked
474 + ? "Linked"
475 + : machine.connected
476 + ? null
477 + : machine.connectOnly
478 + ? "T3 Connect"
479 + : "Not connected";
480 + return (
481 + <Pressable
482 + accessibilityRole="radio"
483 + accessibilityState={{ checked: props.selected, disabled: props.disabled }}
484 + className={
485 + props.separated
486 + ? "flex-row items-center gap-3 border-t border-border-subtle p-4 active:opacity-70"
487 + : "flex-row items-center gap-3 p-4 active:opacity-70"
488 + }
489 + disabled={props.disabled}
490 + onPress={props.onPress}
491 + >
492 + <EnvironmentMachineSymbol
493 + kind={machine.machine}
494 + size={18}
495 + tintColorClassName="accent-foreground-muted"
496 + />
497 + <View className="min-w-0 flex-1 gap-0.5">
498 + <Text className="text-lg text-foreground android:text-base" numberOfLines={1}>
499 + {machine.label}
500 + </Text>
501 + {status === null ? null : <Text className="text-sm text-foreground-muted">{status}</Text>}
502 + </View>
503 + {props.selected ? (
504 + <SymbolView
505 + name="checkmark"
506 + size={18}
507 + tintColorClassName="accent-icon"
508 + type="monochrome"
509 + weight="semibold"
510 + />
511 + ) : null}
512 + </Pressable>
513 + );
514 +}
apps/mobile/src/features/threads/ThreadFeed.tsx
+12
@@ -18,6 +18,7 @@ import { ThreadContextDivider } from "./thread-context-divider";
18 import { ThreadHandoffDivider, ThreadHandoffRow } from "./thread-handoff-row";
19 import { GuestBubbleTint, GuestMessageName } from "./guestMessageStyle";
20 import { ThreadGuestPendingMessage, useThreadGuestShare } from "./ThreadGuestShareBar";
21 +import { LinkRequestCard } from "./LinkRequestCard";
22 import { SecretRequestCard } from "./SecretRequestCard";
23 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
24 import {
@@ -192,6 +193,7 @@ import {
193 threadFeedRunIsUnsettled,
194 isContextCompactionActivityGroup,
195 isContextHandoffActivityGroup,
196 + isLinkRequestActivityGroup,
197 isSecretRequestActivityGroup,
198 type ThreadFeedEntry,
199 type ThreadFeedLatestRun,
@@ -1419,6 +1421,16 @@ function renderFeedEntry(
1421 );
1422 }
1423
1424 + if (entry.type === "activity-group" && isLinkRequestActivityGroup(entry)) {
1425 + return (
1426 + <LinkRequestCard
1427 + environmentId={props.environmentId}
1428 + projectedItem={entry.activities[0]!.projectedItem}
1429 + iconColor={iconSubtleColor}
1430 + />
1431 + );
1432 + }
1433 +
1434 if (entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) {
1435 const label = entry.activities[0]!.summary;
1436 const item = entry.activities[0]!.projectedItem.item;
apps/mobile/src/lib/filePreview.test.ts
+1
@@ -271,6 +271,7 @@ vi.mock("../features/threads/thread-context-divider", () => ({}));
271 vi.mock("../features/threads/thread-handoff-row", () => ({}));
272 vi.mock("../features/threads/ThreadGuestShareBar", () => ({ useThreadGuestShare: () => null }));
273 vi.mock("../features/threads/SecretRequestCard", () => ({}));
274 +vi.mock("../features/threads/LinkRequestCard", () => ({ LinkRequestCard: () => null }));
275 vi.mock("../features/threads/worktree-setup-card", () => ({}));
276 vi.mock("../features/threads/CopyTextButton", () => ({ CopyTextButton: () => null }));
277 vi.mock("../features/threads/thread-work-log", () => ({ THREAD_DISCLOSURE_TRANSITION_MS: 100 }));
apps/mobile/src/lib/threadActivity.ts
+13 -1
@@ -408,6 +408,12 @@ export function isSecretRequestActivityGroup(entry: ThreadFeedActivityGroup): bo
408 );
409 }
410
411 +export function isLinkRequestActivityGroup(entry: ThreadFeedActivityGroup): boolean {
412 + return (
413 + entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "link_request"
414 + );
415 +}
416 +
417 function isUserInputActivityGroup(entry: ThreadFeedActivityGroup): boolean {
418 return entry.activities.some((activity) => activity.workEntry.questionAnswer !== undefined);
419 }
@@ -516,7 +522,8 @@ function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
522 item.type === "thread_created" ||
523 item.type === "system_notice" ||
524 item.type === "proposed_plan" ||
519 - item.type === "secret_request"
525 + item.type === "secret_request" ||
526 + item.type === "link_request"
527 );
528 }
529
@@ -638,6 +645,8 @@ function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
645 return "zap";
646 case "secret_request":
647 return "lock";
648 + case "link_request":
649 + return "globe";
650 }
651 }
652
@@ -697,6 +706,8 @@ function itemSummary(
706 return "Thread created";
707 case "secret_request":
708 return item.label;
709 + case "link_request":
710 + return `Link ${item.label ?? item.url ?? "an environment"}`;
711 case "dynamic_tool": {
712 const classified = classifyToolActivity({
713 itemType: "dynamic_tool_call",
@@ -755,6 +766,7 @@ function itemPreview(item: OrchestrationV2TurnItem): string | null {
766 case "thread_created":
767 return item.targetThreadId;
768 case "secret_request":
769 + case "link_request":
770 return item.reason || null;
771 case "subagent":
772 return item.result ?? item.progress ?? item.prompt;
apps/mobile/src/state/peerLinks.ts
+43
@@ -1,5 +1,48 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { linkableMachines } from "@t3tools/client-runtime/link-request";
3 import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks";
4 +import type { EnvironmentId } from "@t3tools/contracts";
5 +import { useEffect, useEffectEvent, useMemo } from "react";
6
7 import { connectionAtomRuntime } from "../connection/runtime";
8 +import { useEnvironments } from "./environments";
9 +import { relayEnvironmentDiscovery } from "./relay";
10 +import { useEnvironmentQuery } from "./query";
11 +import { useAtomCommand } from "./use-atom-command";
12
13 export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);
14 +
15 +/**
16 + * The user's other machines, for picking one to link `environmentId` to,
17 + * including those only on their T3 Connect account. Reads that environment's
18 + * links only while `enabled`, since listing them asks every linked machine
19 + * whether it answers.
20 + */
21 +export function useLinkableMachines(environmentId: EnvironmentId, enabled: boolean) {
22 + const { environments } = useEnvironments();
23 + const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
24 + const refreshDiscovery = useAtomCommand(relayEnvironmentDiscovery.refresh, {
25 + reportFailure: false,
26 + });
27 + // Connect hosts are listed only once something asked for them, so ask on open.
28 + const discoverIfUnasked = useEffectEvent(() => {
29 + if (discovery.environments.size === 0 && !discovery.refreshing) void refreshDiscovery();
30 + });
31 + // oxlint-disable-next-line t3code/react-effect-budget -- discovery follows the picker's visibility, which a card's mount or a dialog's open sets
32 + useEffect(() => {
33 + if (enabled) discoverIfUnasked();
34 + }, [enabled]);
35 + const links = useEnvironmentQuery(
36 + enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null,
37 + );
38 + return useMemo(
39 + () =>
40 + linkableMachines({
41 + environments,
42 + threadEnvironmentId: environmentId,
43 + links: links.data?.links ?? [],
44 + connect: discovery.environments,
45 + }),
46 + [discovery.environments, environmentId, environments, links.data],
47 + );
48 +}
apps/mobile/src/state/peerPairingCode.ts new
+24
@@ -0,0 +1,24 @@
1 +import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode";
2 +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3 +import type { AuthMcpClientAccess, EnvironmentId } from "@t3tools/contracts";
4 +import * as Result from "effect/Result";
5 +
6 +import { connectionAtomRuntime } from "../connection/runtime";
7 +import { appAtomRegistry } from "./atom-registry";
8 +
9 +const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime);
10 +
11 +/**
12 + * A fresh pairing code minted on `environmentId` with this client's session
13 + * there, for linking with `access`. Fails with `PeerPairingCodeError` when the
14 + * session may not create one.
15 + */
16 +export async function mintPairingCodeOn(
17 + environmentId: EnvironmentId,
18 + access: AuthMcpClientAccess,
19 +): Promise<Result.Result<string, unknown>> {
20 + const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: access });
21 + return result._tag === "Success"
22 + ? Result.succeed(result.value)
23 + : Result.fail(squashAtomCommandFailure(result));
24 +}
apps/server/src/auth/EnvironmentAuth.ts
+1 -17
@@ -2,9 +2,6 @@ import {
2 AuthAccessTokenType,
3 AuthAccessWriteScope,
4 AuthOrchestrationOperateScope,
5 - AuthOrchestrationReadScope,
6 - AuthSettingsWriteScope,
7 - AuthSourceControlWriteScope,
5 AuthStandardClientScopes,
6 type AuthAccessTokenResult,
7 type AuthBrowserSessionResult,
@@ -24,6 +21,7 @@ import {
21 type AuthWebSocketTicketUse,
22 DpopFailureReason,
23 type DpopFailureReason as DpopFailureReasonType,
24 + mcpClientScopes,
25 } from "@t3tools/contracts";
26 import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
27 import * as Context from "effect/Context";
@@ -74,20 +72,6 @@ export interface IssuedBearerSession {
72 const MCP_CLIENT_SUBJECT = "mcp-client";
73 const MCP_CLIENT_SESSION_TTL = Duration.days(30);
74
77 -export const mcpClientScopes = (
78 - access: AuthMcpClientAccess,
79 -): ReadonlyArray<AuthEnvironmentScope> =>
80 - access === "read-only"
81 - ? [AuthOrchestrationReadScope]
82 - : access === "full-access"
83 - ? [
84 - AuthOrchestrationReadScope,
85 - AuthOrchestrationOperateScope,
86 - AuthSettingsWriteScope,
87 - AuthSourceControlWriteScope,
88 - ]
89 - : [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
90 -
75 export interface McpClientSession {
76 readonly sessionId: AuthSessionId;
77 readonly label: string;
apps/server/src/auth/McpOAuth.test.ts
+19
@@ -1,8 +1,10 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import {
3 + AuthMcpClientAccess,
4 AuthStandardClientScopes,
5 type AuthCreatePairingCredentialInput,
6 EnvironmentHttpApi,
7 + mcpClientScopes,
8 } from "@t3tools/contracts";
9 import { expect, it } from "@effect/vitest";
10 import * as Context from "effect/Context";
@@ -480,6 +482,23 @@ it.live(
482 ),
483 );
484
485 +it.live("a code minted with an access level's scopes approves that access", () =>
486 + withRoutes((handler, auth) =>
487 + Effect.gen(function* () {
488 + const params = authorizeParams(yield* registeredClientId(handler));
489 + for (const access of AuthMcpClientAccess.literals) {
490 + const code = yield* auth.issuePairingCredential({ scopes: [...mcpClientScopes(access)] });
491 + const approval = yield* decide(handler, params, {
492 + _tag: "pairing-code",
493 + access,
494 + code: code.credential,
495 + });
496 + expect(approval.status, access).toBe(200);
497 + }
498 + }),
499 + ),
500 +);
501 +
502 it.live("one-click approves only access the browser session holds the scopes for", () =>
503 withRoutes((handler, auth) =>
504 Effect.gen(function* () {
apps/server/src/auth/McpOAuth.ts
+3 -4
@@ -14,6 +14,7 @@ import {
14 AuthOrchestrationOperateScope,
15 AuthOrchestrationReadScope,
16 MCP_PEER_LINK_SOFTWARE_ID,
17 + mcpClientScopes,
18 } from "@t3tools/contracts";
19 import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
20 import * as Clock from "effect/Clock";
@@ -436,9 +437,7 @@ const make = Effect.gen(function* () {
437 if (
438 session === undefined ||
439 !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||
439 - !EnvironmentAuth.mcpClientScopes(decision.access).every((scope) =>
440 - session.scopes.includes(scope),
441 - )
440 + !mcpClientScopes(decision.access).every((scope) => session.scopes.includes(scope))
441 ) {
442 return yield* new McpOAuthPageError({
443 description: "Your session cannot approve this request. Enter a pairing code instead.",
@@ -523,7 +522,7 @@ const make = Effect.gen(function* () {
522 access_token: issued.token,
523 token_type: "Bearer",
524 expires_in: Math.max(0, Math.floor((issued.expiresAt.epochMilliseconds - now) / 1000)),
526 - scope: encodeOAuthScope(EnvironmentAuth.mcpClientScopes(pending.access)),
525 + scope: encodeOAuthScope(mcpClientScopes(pending.access)),
526 };
527 },
528 );
apps/server/src/auth/mcpOAuthHttp.ts
+2 -4
@@ -3,6 +3,7 @@ import {
3 type AuthMcpAuthorizationRequest,
4 AuthMcpClientAccess,
5 EnvironmentHttpApi,
6 + mcpClientScopes,
7 } from "@t3tools/contracts";
8 import * as Effect from "effect/Effect";
9 import * as Result from "effect/Result";
@@ -10,7 +11,6 @@ import { HttpServerRequest, HttpServerResponse } from "effect/http";
11 import * as HttpEffect from "effect/http/HttpEffect";
12 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
13
13 -import * as EnvironmentAuth from "./EnvironmentAuth.ts";
14 import * as McpOAuth from "./McpOAuth.ts";
15 import { renderErrorPage } from "./mcpOAuthHtml.ts";
16
@@ -121,9 +121,7 @@ export const layer = HttpApiBuilder.group(
121 : {
122 csrfToken: session.csrfToken,
123 oneClickAccess: AuthMcpClientAccess.literals.filter((access) =>
124 - EnvironmentAuth.mcpClientScopes(access).every((scope) =>
125 - session.scopes.includes(scope),
126 - ),
124 + mcpClientScopes(access).every((scope) => session.scopes.includes(scope)),
125 ),
126 }),
127 };
apps/server/src/mcp/OrchestratorMcpService.ts
+4
@@ -901,6 +901,10 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null {
901 return `Created thread ${item.targetThreadId} with ${item.targetProviderInstanceId} (${item.targetModel}).`;
902 case "secret_request":
903 return `Asked the user for ${item.label}: ${item.secretStatus}.`;
904 + case "link_request":
905 + return item.linkStatus === "linked"
906 + ? `Linked ${item.linkedLabel ?? item.label ?? item.url ?? "an environment"} (${item.linkedAccess}).`
907 + : `Asked the user to link ${item.label ?? item.url ?? "an environment"}: ${item.linkStatus}.`;
908 case "subagent":
909 return item.result ?? item.progress ?? item.prompt;
910 case "dynamic_tool":
apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+4
@@ -48,6 +48,8 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
48 import * as McpHttpServer from "./McpHttpServer.ts";
49 import * as McpInvocationContext from "./McpInvocationContext.ts";
50 import * as PeerForwarding from "../peer/PeerForwarding.ts";
51 +import * as PeerLinkRequests from "../peer/PeerLinkRequests.ts";
52 +import * as PeerLinks from "../peer/PeerLinks.ts";
53
54 const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe(
55 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
@@ -229,6 +231,8 @@ describe("orchestrator MCP toolkit", () => {
231 Layer.provide(ServerSettings.layerTest()),
232 Layer.provide(layerUnusedScheduledTaskStub),
233 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
234 + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
235 + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
236 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
237 Layer.provideMerge(
238 SecretRequests.layer.pipe(
apps/server/src/mcp/linkOrigin.test.ts
+4
@@ -44,6 +44,8 @@ import * as McpHttpServer from "./McpHttpServer.ts";
44 import * as McpInvocationContext from "./McpInvocationContext.ts";
45 import * as PeerForwarding from "../peer/PeerForwarding.ts";
46 import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
47 +import * as PeerLinkRequests from "../peer/PeerLinkRequests.ts";
48 +import * as PeerLinks from "../peer/PeerLinks.ts";
49
50 // A linked environment's session drives this one's real orchestrator through
51 // its real T3 tools. What the link starts carries its origin, and the link
@@ -157,6 +159,8 @@ const layerTools = Layer.mergeAll(
159 ),
160 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
161 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
162 + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
163 + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
164 Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
165 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
166 Layer.provide(
apps/server/src/mcp/toolkits/core.test.ts
+12
@@ -56,6 +56,8 @@ import { dispatchFailure } from "../threadAccess.ts";
56 import * as EnvironmentHandlers from "./environment/handlers.ts";
57 import * as AttachmentHandlers from "./attachment/handlers.ts";
58 import * as PeerForwarding from "../../peer/PeerForwarding.ts";
59 +import * as PeerLinkRequests from "../../peer/PeerLinkRequests.ts";
60 +import * as PeerLinks from "../../peer/PeerLinks.ts";
61
62 const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe(
63 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
@@ -75,6 +77,8 @@ const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe(
77 Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
78 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
79 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
80 + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
81 + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
82 );
83
84 const threadId = ThreadId.make("mcp-core-thread");
@@ -602,6 +606,8 @@ it.effect("refuses act-as-caller tools to a client caller", () =>
606 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
607 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
608 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
609 + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
610 + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
611 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
612 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
613 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
@@ -661,6 +667,8 @@ it.effect("a caller cannot rewrite a scheduled task that runs above its own mode
667 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
668 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
669 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
670 + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
671 + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
672 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
673 ),
674 ),
@@ -748,6 +756,8 @@ it.effect.each(["t3_thread_interrupt", "t3_workflow_stop"])(
756 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
757 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
758 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
759 + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
760 + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
761 ),
762 ),
763 ),
@@ -839,6 +849,8 @@ it.effect("discovers workflow stop targets and requires orchestration capability
849 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
850 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
851 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
852 + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
853 + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
854 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
855 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
856 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
apps/server/src/mcp/toolkits/orchestrator/handlers.ts
+25
@@ -3,6 +3,8 @@ import { OrchestratorToolkit } from "./tools.ts";
3 import * as Effect from "effect/Effect";
4
5 import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
6 +import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts";
7 +import * as PeerLinks from "../../../peer/PeerLinks.ts";
8 import { readCaller } from "../../threadAccess.ts";
9 import * as McpInvocationContext from "../../McpInvocationContext.ts";
10 import * as McpToolAccess from "../../McpToolAccess.ts";
@@ -189,6 +191,29 @@ const handlers = {
191 return yield* forwarding.links(scope);
192 }),
193 ),
194 + // A link lets every agent here reach the other environment, so it is an
195 + // environment setting: full access, and never for linked work.
196 + t3_environment_link: McpToolAccess.writesEnvironment((input) =>
197 + Effect.gen(function* () {
198 + const scope = yield* McpInvocationContext.McpInvocationContext;
199 + const requests = yield* PeerLinkRequests.PeerLinkRequests;
200 + return yield* requests.request(scope, input);
201 + }),
202 + ),
203 + t3_environment_unlink: McpToolAccess.writesEnvironment(({ environmentId }) =>
204 + Effect.gen(function* () {
205 + const links = yield* PeerLinks.PeerLinks;
206 + const removed = yield* links
207 + .unlink(environmentId)
208 + .pipe(
209 + Effect.mapError(
210 + (error) =>
211 + new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
212 + ),
213 + );
214 + return { environmentId, removed };
215 + }),
216 + ),
217 t3_thread_interrupt: McpToolAccess.writesThreads(
218 (input) => [input.threadId],
219 (input) =>
apps/server/src/mcp/toolkits/orchestrator/tools.ts
+41 -1
@@ -2,7 +2,11 @@ import {
2 OrchestratorMcpCapabilitiesInput,
3 OrchestratorMcpCapabilitiesResult,
4 OrchestrationV2StopWorkflowInput,
5 + OrchestratorMcpEnvironmentLinkInput,
6 + OrchestratorMcpEnvironmentLinkResult,
7 OrchestratorMcpEnvironmentLinksResult,
8 + OrchestratorMcpEnvironmentUnlinkInput,
9 + OrchestratorMcpEnvironmentUnlinkResult,
10 OrchestratorMcpCreateThreadsInput,
11 OrchestratorMcpCreateThreadsResult,
12 OrchestratorMcpDelegateTaskInput,
@@ -40,6 +44,8 @@ import * as Struct from "effect/Struct";
44
45 import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
46 import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
47 +import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts";
48 +import * as PeerLinks from "../../../peer/PeerLinks.ts";
49 import * as McpInvocationContext from "../../McpInvocationContext.ts";
50 import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts";
51 import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts";
@@ -51,6 +57,12 @@ const dependencies = [
57 ];
58 /** Listing this environment's links. */
59 const linkDependencies = [...dependencies, PeerForwarding.PeerForwarding];
60 +/** Making and forgetting links. */
61 +const linkingDependencies = [
62 + ...dependencies,
63 + PeerLinkRequests.PeerLinkRequests,
64 + PeerLinks.PeerLinks,
65 +];
66 const threadMetadataDependencies = [
67 McpInvocationContext.McpInvocationContext,
68 ThreadManagementService.ThreadManagementService,
@@ -295,7 +307,7 @@ const ThreadInterruptTool = Tool.make("t3_thread_interrupt", {
307
308 const EnvironmentLinksTool = Tool.make("t3_environment_links", {
309 description:
298 - "List the other T3 Code environments this one is linked to, such as the user's other machines, and whether each answers now. Pass one's environmentId to any tool that takes environmentId, such as t3_thread_launch, t3_thread_send, t3_pending_request_respond, t3_queue_list or t3_project_list, to act there; delegate_task takes it as target.environmentId. A linked environment lets this one's agents do at most its access there, and never more than the calling agent may do here. An expired link has to be linked again from a new pairing code.",
310 + "List linked environments (the user's other machines) and whether each answers now. Pass one's `environmentId` to a tool to act there; `delegate_task` takes `target.environmentId`. Expired: link it again with `t3_environment_link`.",
311 success: OrchestratorMcpEnvironmentLinksResult,
312 failure: OrchestratorMcpFailure,
313 failureMode: "return",
@@ -306,6 +318,32 @@ const EnvironmentLinksTool = Tool.make("t3_environment_links", {
318 .annotate(Tool.Destructive, false)
319 .annotate(Tool.Idempotent, true);
320
321 +const EnvironmentLinkTool = Tool.make("t3_environment_link", {
322 + description:
323 + "Ask the user to link another machine, in a card. For a machine the user names that is not linked. Pass `hint` from their words, `environmentId` when one names it (already linked: returns `linked`), `url` only when the user gave an address. Returns `pending`; the outcome arrives as a message in this thread. Do not wait, poll, or call it again to check. Never ask for a pairing code in chat.",
324 + parameters: OrchestratorMcpEnvironmentLinkInput,
325 + success: OrchestratorMcpEnvironmentLinkResult,
326 + failure: OrchestratorMcpFailure,
327 + failureMode: "return",
328 + dependencies: linkingDependencies,
329 +})
330 + .annotate(Tool.Title, "Link another environment")
331 + .annotate(Tool.Destructive, false)
332 + .annotate(Tool.OpenWorld, true);
333 +
334 +const EnvironmentUnlinkTool = Tool.make("t3_environment_unlink", {
335 + description:
336 + "Forget a linked environment. That machine's Connections list its session until revoked there.",
337 + parameters: OrchestratorMcpEnvironmentUnlinkInput,
338 + success: OrchestratorMcpEnvironmentUnlinkResult,
339 + failure: OrchestratorMcpFailure,
340 + failureMode: "return",
341 + dependencies: linkingDependencies,
342 +})
343 + .annotate(Tool.Title, "Forget a linked environment")
344 + .annotate(Tool.Destructive, true)
345 + .annotate(Tool.Idempotent, true);
346 +
347 export const OrchestratorToolkit = Toolkit.make(
348 OrchestratorCapabilitiesTool,
349 DelegateTaskTool,
@@ -325,4 +363,6 @@ export const OrchestratorToolkit = Toolkit.make(
363 ThreadWaitTool,
364 ThreadInterruptTool,
365 EnvironmentLinksTool,
366 + EnvironmentLinkTool,
367 + EnvironmentUnlinkTool,
368 );
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -62,6 +62,7 @@ const RPC_AGGREGATES = {
62 [WS_METHODS.peerLinksList]: "peerLinks",
63 [WS_METHODS.peerLinksLink]: "peerLinks",
64 [WS_METHODS.peerLinksUnlink]: "peerLinks",
65 + [WS_METHODS.peerLinksAnswerRequest]: "peerLinks",
66 [WS_METHODS.serverUpdateSettings]: "server",
67 [WS_METHODS.serverSearchAcpRegistry]: "server",
68 [WS_METHODS.serverPrepareAcpRegistryAgent]: "server",
apps/server/src/orchestration-v2/Orchestrator.ts
+201
@@ -526,6 +526,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
526 case "thread.created.record":
527 return command.parentThreadId;
528 case "secret_request.record":
529 + case "link_request.record":
530 return command.threadId;
531 case "thread.fork":
532 case "thread.merge_back":
@@ -3854,6 +3855,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3855 now,
3856 cancelQueuedDelivery: false,
3857 });
3858 + yield* closePendingLinkRequests({ command, events, threadId: command.threadId, now });
3859 }
3860
3861 // Archive and settle stop idle background work; serialized commands prevent starts racing detach.
@@ -8250,6 +8252,201 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8252 },
8253 );
8254
8255 + /**
8256 + * Records or updates the card for a link an agent asked the user to make.
8257 + * The pairing code goes straight to the link and never through orchestration.
8258 + */
8259 + const dispatchLinkRequestRecord = Effect.fn("orchestrationV2.dispatch.linkRequestRecord")(
8260 + function* (
8261 + command: Extract<OrchestrationV2InternalCommand, { readonly type: "link_request.record" }>,
8262 + events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
8263 + effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
8264 + ) {
8265 + const projection = yield* projectionStore
8266 + .getThreadRecords(
8267 + command.threadId,
8268 + ["runs", "nodes", "turnItems", "attempts", "providerTurns"],
8269 + { turnItemTypes: ["link_request"], messageRoles: [] },
8270 + )
8271 + .pipe(
8272 + Effect.mapError(
8273 + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
8274 + ),
8275 + );
8276 + const run = projection.runs.find((candidate) => candidate.id === command.runId);
8277 + if (run === undefined) {
8278 + return yield* new OrchestratorDispatchError({
8279 + commandId: command.commandId,
8280 + commandType: command.type,
8281 + cause: `Run ${command.runId} was not found.`,
8282 + });
8283 + }
8284 + const existing = projection.turnItems.find((item) => item.id === command.turnItemId);
8285 + if (existing !== undefined && existing.type !== "link_request") {
8286 + return yield* new OrchestratorDispatchError({
8287 + commandId: command.commandId,
8288 + commandType: command.type,
8289 + cause: `Turn item ${command.turnItemId} is not a link request.`,
8290 + });
8291 + }
8292 + if (existing !== undefined && existing.runId !== command.runId) {
8293 + return yield* new OrchestratorDispatchError({
8294 + commandId: command.commandId,
8295 + commandType: command.type,
8296 + cause: `Link request ${command.turnItemId} belongs to another run.`,
8297 + });
8298 + }
8299 + // Only a new card needs its run's current root and a live run. An answer
8300 + // may land long after a steer restarted the run or the run ended, and the
8301 + // link it reports is already made.
8302 + if (existing === undefined && run.rootNodeId !== command.nodeId) {
8303 + return yield* new OrchestratorDispatchError({
8304 + commandId: command.commandId,
8305 + commandType: command.type,
8306 + cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`,
8307 + });
8308 + }
8309 + if (
8310 + existing === undefined &&
8311 + (!isBlockingRun(run) || (yield* stopReachedRun(command, command.threadId, run.id)))
8312 + ) {
8313 + return yield* new OrchestratorDispatchError({
8314 + commandId: command.commandId,
8315 + commandType: command.type,
8316 + cause: `Run ${command.runId} is not active.`,
8317 + });
8318 + }
8319 + const nodeId = existing?.nodeId ?? command.nodeId;
8320 + const now = yield* DateTime.now;
8321 + // A request is answered once, and a retry finds its card as it was
8322 + // asked: either one records the card unchanged.
8323 + const unchanged =
8324 + existing !== undefined &&
8325 + (existing.linkStatus !== "pending" || command.linkStatus === "pending");
8326 + const pending = command.linkStatus === "pending";
8327 + const {
8328 + type: _type,
8329 + commandId: _commandId,
8330 + turnItemId: _turnItemId,
8331 + wake,
8332 + ...fields
8333 + } = command;
8334 + const turnItem: OrchestrationV2TurnItem = unchanged
8335 + ? existing
8336 + : {
8337 + ...fields,
8338 + id: command.turnItemId,
8339 + // An update keeps where the card was asked, even after a restart.
8340 + ...(existing === undefined
8341 + ? {
8342 + providerThreadId: run.providerThreadId,
8343 + providerTurnId: providerTurnForRun(projection, run)?.id ?? null,
8344 + }
8345 + : {
8346 + nodeId: existing.nodeId,
8347 + providerThreadId: existing.providerThreadId,
8348 + providerTurnId: existing.providerTurnId,
8349 + }),
8350 + nativeItemRef: null,
8351 + parentItemId: null,
8352 + ordinal: existing?.ordinal ?? (yield* nextTurnItemOrdinal(projection)),
8353 + status: pending
8354 + ? "waiting"
8355 + : command.linkStatus === "linked"
8356 + ? "completed"
8357 + : command.linkStatus === "failed"
8358 + ? "failed"
8359 + : "cancelled",
8360 + title: command.label ?? command.url ?? "Link an environment",
8361 + startedAt: existing?.startedAt ?? now,
8362 + completedAt: pending ? null : now,
8363 + updatedAt: now,
8364 + type: "link_request",
8365 + };
8366 + yield* emit(
8367 + events,
8368 + command,
8369 + )({
8370 + type: "turn-item.updated",
8371 + threadId: command.threadId,
8372 + runId: command.runId,
8373 + nodeId,
8374 + providerInstanceId: run.providerInstanceId,
8375 + occurredAt: now,
8376 + payload: turnItem,
8377 + });
8378 + // The agent asked without waiting, so the answer reaches it as a
8379 + // notification: it starts a turn, or follows the one running. Only the
8380 + // answer that closes the card wakes it, and never a closed thread.
8381 + if (
8382 + wake === undefined ||
8383 + unchanged ||
8384 + projection.thread.archivedAt !== null ||
8385 + projection.thread.deletedAt !== null
8386 + ) {
8387 + return;
8388 + }
8389 + yield* dispatchMessage(
8390 + {
8391 + type: "message.dispatch",
8392 + commandId: command.commandId,
8393 + threadId: command.threadId,
8394 + messageId: wake.messageId,
8395 + text: wake.text,
8396 + notification: wake.notification,
8397 + attachments: [],
8398 + dispatchMode: { type: "queue_after_active" },
8399 + createdBy: "agent",
8400 + creationSource: "server",
8401 + },
8402 + events,
8403 + effects,
8404 + );
8405 + },
8406 + );
8407 +
8408 + /**
8409 + * Closes the link cards still waiting for the user. Their agent stopped
8410 + * waiting long ago, so nobody is woken: stopping or archiving the thread
8411 + * means the user is done with it.
8412 + */
8413 + const closePendingLinkRequests = Effect.fn("orchestrationV2.closePendingLinkRequests")(
8414 + function* (input: {
8415 + readonly command: OrchestrationV2ServerCommand;
8416 + readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
8417 + readonly threadId: ThreadId;
8418 + readonly now: DateTime.Utc;
8419 + }) {
8420 + const { turnItems } = yield* projectionStore
8421 + .getThreadRecords(input.threadId, ["turnItems"], {
8422 + turnItemTypes: ["link_request"],
8423 + turnItemStatuses: ["waiting"],
8424 + messageRoles: [],
8425 + })
8426 + .pipe(mapDispatchError(input.command));
8427 + for (const item of turnItems) {
8428 + if (item.type !== "link_request" || item.linkStatus !== "pending") continue;
8429 + yield* emit(
8430 + input.events,
8431 + input.command,
8432 + )({
8433 + type: "turn-item.updated",
8434 + threadId: input.threadId,
8435 + ...(item.runId === null ? {} : { runId: item.runId }),
8436 + ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
8437 + occurredAt: input.now,
8438 + payload: {
8439 + ...item,
8440 + status: "cancelled",
8441 + linkStatus: "cancelled",
8442 + completedAt: input.now,
8443 + updatedAt: input.now,
8444 + },
8445 + });
8446 + }
8447 + },
8448 + );
8449 +
8450 const dispatchRuntimeRequestRespond = Effect.fn("Orchestrator.dispatchRuntimeRequestRespond")(
8451 function* (
8452 command: Extract<OrchestrationV2Command, { readonly type: "runtime-request.respond" }>,
@@ -10145,6 +10342,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10342 now: input.now,
10343 });
10344 }
10345 + yield* closePendingLinkRequests({ ...input, threadId: thread.id });
10346 });
10347
10348 const dispatchBackgroundWorkSettle = Effect.fn("Orchestrator.dispatchBackgroundWorkSettle")(
@@ -12528,6 +12726,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12726 case "secret_request.record":
12727 yield* dispatchSecretRequestRecord(command, events);
12728 break;
12729 + case "link_request.record":
12730 + yield* dispatchLinkRequestRecord(command, events, effects);
12731 + break;
12732 default:
12733 return yield* dispatchUnsupported(command);
12734 }
apps/server/src/orchestration-v2/ProjectionStore.ts
+40 -10
@@ -1139,6 +1139,7 @@ type ShellThreadRow = {
1139 readonly blocking_failure_payload_json: string | null;
1140 readonly pending_request_payload_json: string | null;
1141 readonly pending_secret_request_payload_json: string | null;
1142 + readonly pending_link_request_payload_json: string | null;
1143 readonly latest_user_message_at: string | null;
1144 readonly latest_user_authored_message_at: string | null;
1145 readonly has_actionable_proposed_plan: number;
@@ -1563,7 +1564,8 @@ function pendingRuntimeRequestSummary(
1564 function secretRequestAsPendingInput(
1565 item: OrchestrationV2TurnItem | null,
1566 ): OrchestrationV2PendingRuntimeRequestSummary | null {
1566 - if (item?.type !== "secret_request" || item.nodeId === null) return null;
1567 + if ((item?.type !== "secret_request" && item?.type !== "link_request") || item.nodeId === null)
1568 + return null;
1569 return {
1570 id: RuntimeRequestId.make(item.id),
1571 kind: "user_input",
@@ -1572,6 +1574,14 @@ function secretRequestAsPendingInput(
1574 };
1575 }
1576
1577 +/**
1578 + * A secret card is answered while its agent waits in the run. A link card's
1579 + * agent asked without waiting, so the card waits on the user after its run.
1580 + */
1581 +const waitsOnUser = (item: OrchestrationV2TurnItem, liveRunIds: ReadonlySet<RunId>) =>
1582 + item.type === "link_request" ||
1583 + (item.type === "secret_request" && item.runId !== null && liveRunIds.has(item.runId));
1584 +
1585 export function threadShellFromProjection(
1586 projection: OrchestrationV2ThreadProjection,
1587 ): OrchestrationV2ThreadShell {
@@ -1611,13 +1621,7 @@ export function threadShellFromProjection(
1621 pendingRuntimeRequest =
1622 secretRequestAsPendingInput(
1623 projection.turnItems
1614 - .filter(
1615 - (item) =>
1616 - item.type === "secret_request" &&
1617 - item.status === "waiting" &&
1618 - item.runId !== null &&
1619 - liveRunIds.has(item.runId),
1620 - )
1624 + .filter((item) => item.status === "waiting" && waitsOnUser(item, liveRunIds))
1625 .toSorted(
1626 (left, right) =>
1627 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
@@ -5926,6 +5930,15 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5930 ORDER BY secret.updated_at DESC, secret.turn_item_id DESC
5931 LIMIT 1
5932 ) AS pending_secret_request_payload_json,
5933 + (
5934 + SELECT link.payload_json
5935 + FROM orchestration_v2_projection_turn_items link
5936 + INDEXED BY orchestration_v2_projection_turn_items_waiting_link_idx
5937 + WHERE link.thread_id = t.thread_id
5938 + AND link.type = 'link_request' AND link.status = 'waiting'
5939 + ORDER BY link.updated_at DESC, link.turn_item_id DESC
5940 + LIMIT 1
5941 + ) AS pending_link_request_payload_json,
5942 (
5943 SELECT message.updated_at
5944 FROM orchestration_v2_projection_messages message
@@ -6220,6 +6233,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6233 SELECT 1 FROM orchestration_v2_projection_runtime_requests request
6234 WHERE request.thread_id = t.thread_id AND request.status = 'pending'
6235 )
6236 + AND NOT EXISTS (
6237 + SELECT 1 FROM orchestration_v2_projection_turn_items link
6238 + INDEXED BY orchestration_v2_projection_turn_items_waiting_link_idx
6239 + WHERE link.thread_id = t.thread_id
6240 + AND link.type = 'link_request' AND link.status = 'waiting'
6241 + )
6242 ORDER BY t.updated_at ASC, t.thread_id ASC
6243 `;
6244 if (rows.length === 0) return [];
@@ -6384,6 +6403,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6403 pendingTurnItemsByThreadId,
6404 } = input;
6405 const thread = yield* decodeThreadPayload(row.payload_json);
6406 + const waitingCards = [
6407 + row.pending_secret_request_payload_json === null
6408 + ? null
6409 + : yield* decodeTurnItemPayload(row.pending_secret_request_payload_json),
6410 + row.pending_link_request_payload_json === null
6411 + ? null
6412 + : yield* decodeTurnItemPayload(row.pending_link_request_payload_json),
6413 + ].filter((item) => item !== null);
6414 let pendingRuntimeRequest =
6415 row.pending_request_payload_json !== null
6416 ? pendingRuntimeRequestSummary(
@@ -6392,11 +6419,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6419 : null;
6420 if (
6421 (pendingRuntimeRequest === null || pendingRuntimeRequest.blocking === false) &&
6395 - row.pending_secret_request_payload_json !== null
6422 + waitingCards.length > 0
6423 ) {
6424 pendingRuntimeRequest =
6425 secretRequestAsPendingInput(
6399 - yield* decodeTurnItemPayload(row.pending_secret_request_payload_json),
6426 + waitingCards.toSorted(
6427 + (left, right) =>
6428 + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
6429 + )[0] ?? null,
6430 ) ?? pendingRuntimeRequest;
6431 }
6432 let terminalFailureItem =
apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts
+83
@@ -418,6 +418,89 @@ it.effect("cancels a stale waiting run when no checkpoint capture can finish it"
418 }).pipe(Effect.provide(layer));
419 });
420
421 +it.effect("recovery closes a secret card's form but leaves a link card open", () => {
422 + const threadId = ThreadId.make("thread_secret_recovery");
423 + const runId = RunId.make("run_secret_recovery");
424 + let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
425 + null;
426 + const projection = {
427 + thread: { id: threadId },
428 + runtimeRequests: [],
429 + providerSessions: [],
430 + providerThreads: [],
431 + providerTurns: [],
432 + runs: [{ id: runId, status: "running", providerInstanceId: ProviderInstanceId.make("codex") }],
433 + attempts: [],
434 + nodes: [],
435 + subagents: [],
436 + messages: [],
437 + turnItems: [
438 + {
439 + id: "turn-item:secret-request:recovery",
440 + threadId,
441 + runId,
442 + nodeId: null,
443 + type: "secret_request",
444 + status: "waiting",
445 + secretStatus: "pending",
446 + label: "GitHub token",
447 + reason: "Used as GH_TOKEN.",
448 + },
449 + {
450 + id: "turn-item:link-request:recovery",
451 + threadId,
452 + runId,
453 + nodeId: null,
454 + type: "link_request",
455 + status: "waiting",
456 + linkStatus: "pending",
457 + url: "https://box.example.ts.net",
458 + reason: "Run the suite there.",
459 + },
460 + ],
461 + } as unknown as OrchestrationV2ThreadProjection;
462 + const layer = ProviderRuntimeRecovery.layer.pipe(
463 + Layer.provide(ServerSettings.layerTest()),
464 + Layer.provide(
465 + Layer.mergeAll(
466 + Layer.mock(ProjectionStore.ProjectionStoreV2)({
467 + getRecoveryThreadIds: () => Effect.succeed([threadId]),
468 + getRuntimeRecoveryProjection: () => Effect.succeed(projection),
469 + }),
470 + Layer.mock(EventSink.EventSinkV2)({
471 + commitCommand: (input) => {
472 + committedInput = input;
473 + return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
474 + },
475 + }),
476 + IdAllocator.layer,
477 + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
478 + runRecoveryOnce: Effect.succeed(false),
479 + }),
480 + Layer.mock(EffectOutbox.EffectOutboxV2)({
481 + listByCommandId: () => Effect.succeed([]),
482 + reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
483 + }),
484 + ),
485 + ),
486 + );
487 +
488 + return Effect.gen(function* () {
489 + yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
490 + const cards = (committedInput?.events ?? []).flatMap((event) =>
491 + event.type === "turn-item.updated" ? [event.payload] : [],
492 + );
493 + const secret = cards.find((card) => card.type === "secret_request");
494 + assert.equal(secret?.status, "cancelled");
495 + assert.equal(secret?.type === "secret_request" ? secret.secretStatus : null, "cancelled");
496 + // Nothing in memory waits on a link card; the user can still answer it.
497 + assert.equal(
498 + cards.some((card) => card.type === "link_request"),
499 + false,
500 + );
501 + }).pipe(Effect.provide(layer));
502 +});
503 +
504 it.effect.each(["queued", "preparing"] as const)("recovers $0 work after restart", (status) => {
505 const threadId = ThreadId.make("thread_queued_restart");
506 const runId = RunId.make("run_queued_restart");
apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
+2
@@ -440,6 +440,8 @@ export const make = Effect.gen(function* () {
440 candidate.runId === run.id &&
441 (candidate.nodeId === null || !messageRequestNodeIds.has(candidate.nodeId)) &&
442 !isAppOwnedDelegationItem(candidate) &&
443 + // A link card waits on the user, not the run, and answers by message.
444 + candidate.type !== "link_request" &&
445 (candidate.status === "pending" ||
446 candidate.status === "running" ||
447 candidate.status === "waiting"),
apps/server/src/peer/PeerForwarding.test.ts
+4
@@ -38,6 +38,7 @@ import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
38 import { liveThreadShell } from "../mcp/McpToolAccess.testkit.ts";
39 import * as PeerForwarding from "./PeerForwarding.ts";
40 import * as PeerLinks from "./PeerLinks.ts";
41 +import * as PeerLinkRequests from "./PeerLinkRequests.ts";
42 import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";
43
44 const laptop = descriptorOf("environment-laptop", "Laptop");
@@ -230,6 +231,8 @@ const serveBox = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) =>
231 Layer.provide(ServerSettings.layerTest()),
232 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
233 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
234 + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
235 + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
236 ),
237 );
238
@@ -307,6 +310,7 @@ const makeLaptop = Effect.gen(function* () {
310 Layer.mock(SecretRequests.SecretRequests)({}),
311 ServerSettings.layerTest(),
312 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
313 + Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
314 ),
315 ),
316 Layer.fresh,
apps/server/src/peer/PeerForwarding.ts
+8
@@ -213,6 +213,13 @@ const make = Effect.gen(function* () {
213 ) as Effect.Effect<Tool.Success<typeof tool>, OrchestratorMcpFailure>)
214 : forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, params);
215
216 + /**
217 + * The next step for an agent whose machine is not linked: without it, an
218 + * empty list reads as a dead end and agents go looking elsewhere.
219 + */
220 + const NOT_LISTED =
221 + "Not listed: not linked yet. Call t3_environment_link with a hint from the user's words.";
222 +
223 const listLinks: PeerForwarding["Service"]["links"] = Effect.fn("PeerForwarding.listLinks")(
224 function* (scope) {
225 yield* callerLimits(scope);
@@ -232,6 +239,7 @@ const make = Effect.gen(function* () {
239 expiresAt: DateTime.formatIso(link.expiresAt),
240 lastError: link.lastError,
241 })),
242 + notListed: NOT_LISTED,
243 };
244 },
245 );
apps/server/src/peer/PeerLinkRequests.test.ts new
+979
@@ -0,0 +1,979 @@
1 +import { NodeHttpServer } from "@effect/platform-node";
2 +import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3 +import * as NodeServices from "@effect/platform-node/NodeServices";
4 +import {
5 + CommandId,
6 + EventId,
7 + MessageId,
8 + NodeId,
9 + OrchestratorMcpFailure,
10 + ProjectId,
11 + ProviderDriverKind,
12 + ProviderInstanceId,
13 + ProviderThreadId,
14 + type RuntimeMode,
15 + RunId,
16 + ThreadId,
17 + TurnItemId,
18 +} from "@t3tools/contracts";
19 +import { expect, it } from "@effect/vitest";
20 +import * as Clock from "effect/Clock";
21 +import * as Context from "effect/Context";
22 +import * as DateTime from "effect/DateTime";
23 +import * as Deferred from "effect/Deferred";
24 +import * as Duration from "effect/Duration";
25 +import * as Effect from "effect/Effect";
26 +import * as Fiber from "effect/Fiber";
27 +import * as HttpServer from "effect/http/HttpServer";
28 +import * as HttpServerResponse from "effect/http/HttpServerResponse";
29 +import * as Layer from "effect/Layer";
30 +import * as Option from "effect/Option";
31 +import * as Schema from "effect/Schema";
32 +import * as SqlClient from "effect/sql/SqlClient";
33 +import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
34 +
35 +import * as ServerConfig from "../config.ts";
36 +import * as McpHttpServer from "../mcp/McpHttpServer.ts";
37 +import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
38 +import * as McpToolAccess from "../mcp/McpToolAccess.ts";
39 +import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
40 +import * as EventSink from "../orchestration-v2/EventSink.ts";
41 +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
42 +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
43 +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
44 +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
45 +import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
46 +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
47 +import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
48 +import * as SqlitePersistence from "../persistence/Sqlite.ts";
49 +import * as ProjectService from "../project/ProjectService.ts";
50 +import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
51 +import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
52 +import * as SecretRequests from "../secrets/SecretRequests.ts";
53 +import * as ServerSettings from "../serverSettings.ts";
54 +import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
55 +import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
56 +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
57 +import * as PeerForwarding from "./PeerForwarding.ts";
58 +import * as PeerLinkRequests from "./PeerLinkRequests.ts";
59 +import * as PeerLinks from "./PeerLinks.ts";
60 +import {
61 + descriptorOf,
62 + layerLinkingEnvironment,
63 + linkTo,
64 + servePeer,
65 + type ServedPeer,
66 +} from "./PeerLinks.testkit.ts";
67 +import * as RemoteDelegation from "./RemoteDelegation.ts";
68 +
69 +// The laptop's agent asks the user to link the box. The laptop is its real
70 +// orchestrator and toolkit; the box is its real descriptor and MCP OAuth on a
71 +// socket. The user's answer goes through PeerLinkRequests, as the card's does.
72 +
73 +const laptop = descriptorOf("environment-laptop", "Laptop");
74 +const box = descriptorOf("environment-box", "Box");
75 +const instanceId = ProviderInstanceId.make("codex");
76 +const driver = ProviderDriverKind.make("codex");
77 +const modelSelection = { instanceId, model: "gpt-5.4" };
78 +const threadId = ThreadId.make("thread:laptop");
79 +const runId = RunId.make("run:laptop");
80 +const rootNode = NodeId.make("node:laptop:root");
81 +
82 +/** The box needs no tools of its own: linking only signs in to its /mcp. */
83 +const NoTools = Toolkit.make(
84 + Tool.make("noop", { success: Schema.Struct({}), failure: OrchestratorMcpFailure }),
85 +);
86 +const serveBox = servePeer(
87 + box,
88 + McpHttpServer.toolkitRegistration(
89 + NoTools,
90 + McpToolAccess.toLayer(NoTools, { noop: McpToolAccess.reads(() => Effect.succeed({})) }),
91 + ),
92 +);
93 +
94 +const adapter = {
95 + instanceId,
96 + driver,
97 + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
98 + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
99 + openSession: () => Effect.die("No provider process needed"),
100 +} as ProviderAdapter.ProviderAdapterV2["Service"];
101 +
102 +const mcpClient = McpSchema.McpServerClient.of({
103 + clientId: 1,
104 + protocolVersion: "2025-06-18",
105 + clientCapabilities: {},
106 + clientInfo: { name: "peer-link-requests", version: "1" },
107 + initializePayload: {
108 + protocolVersion: "2025-06-18",
109 + capabilities: {},
110 + clientInfo: { name: "peer-link-requests", version: "1" },
111 + },
112 + getClient: Effect.die("unused"),
113 +});
114 +
115 +const scope: McpInvocationContext.McpInvocationScope = {
116 + environmentId: laptop.environmentId,
117 + requestNamespace: "provider-session:laptop",
118 + thread: {
119 + threadId,
120 + providerSessionId: "provider-session:laptop",
121 + providerInstanceId: instanceId,
122 + },
123 + client: undefined,
124 + capabilities: new Set(["orchestration"]),
125 + issuedAt: 1,
126 +};
127 +
128 +/** The laptop: a real orchestrator, its orchestrator toolkit, and its links. */
129 +const makeLaptop = Effect.gen(function* () {
130 + const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);
131 + // The orchestrator's own database, apart from the one links are kept in.
132 + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);
133 + const layerDatabase = Layer.succeedContext(database);
134 + const layerOrchestrator = Layer.mergeAll(
135 + layerDatabase,
136 + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
137 + ProviderReplayHarness.layerWithRegistry(
138 + { name: "peer-link-requests" },
139 + ProviderAdapterRegistry.layerFromAdapters([adapter]),
140 + { databaseLayer: layerDatabase, runEffectWorker: false },
141 + ),
142 + ).pipe(
143 + Layer.provide(
144 + Layer.succeed(ProviderContinuationRequests.ProviderContinuationRequests, {
145 + offer: () => Effect.void,
146 + take: Effect.never,
147 + }),
148 + ),
149 + );
150 + const layerThreads = ThreadManagement.layer.pipe(
151 + Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
152 + Layer.provideMerge(Layer.merge(layerOrchestrator, ServerSettings.layerTest())),
153 + );
154 + const layerHere = McpHttpServer.layerOrchestratorToolkit.pipe(
155 + Layer.provideMerge(McpServer.McpServer.layer),
156 + Layer.provideMerge(PeerLinkRequests.layer),
157 + Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
158 + Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
159 + Layer.provide(Layer.succeedContext(linking)),
160 + Layer.provide(NodeCrypto.layer),
161 + Layer.provideMerge(layerThreads),
162 + Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
163 + Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
164 + Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
165 + Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
166 + Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
167 + Layer.provide(Layer.mock(ThreadLaunch.ThreadLaunchService)({})),
168 + Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
169 + Layer.provide(
170 + ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-requests-" }).pipe(
171 + Layer.provide(NodeServices.layer),
172 + ),
173 + ),
174 + Layer.provide(NodeServices.layer),
175 + Layer.fresh,
176 + );
177 + const here = yield* Layer.build(layerHere);
178 + const server = Context.get(here, McpServer.McpServer);
179 + return {
180 + links: Context.get(linking, PeerLinks.PeerLinks),
181 + linksSql: Context.get(linking, SqlClient.SqlClient),
182 + requests: Context.get(here, PeerLinkRequests.PeerLinkRequests),
183 + orchestrator: Context.get(here, Orchestrator.OrchestratorV2),
184 + sink: Context.get(here, EventSink.EventSinkV2),
185 + projections: Context.get(here, ProjectionStore.ProjectionStoreV2),
186 + sql: Context.get(database, SqlClient.SqlClient),
187 + call: (args: Record<string, unknown>, callScope = scope) =>
188 + server
189 + .callTool({ name: "t3_environment_link", arguments: args })
190 + .pipe(
191 + Effect.provideService(McpInvocationContext.McpInvocationContext, callScope),
192 + Effect.provideService(McpSchema.McpServerClient, mcpClient),
193 + ),
194 + };
195 +});
196 +type Laptop = Effect.Success<typeof makeLaptop>;
197 +
198 +/** The laptop's thread, mid-turn when its agent asks, in `runtimeMode`. */
199 +const seedThread = (
200 + a: Laptop,
201 + runtimeMode: RuntimeMode = "full-access",
202 + linkOrigin?: { readonly sessionId: string; readonly label: string },
203 +) =>
204 + Effect.gen(function* () {
205 + const now = yield* DateTime.now;
206 + const providerThreadId = ProviderThreadId.make("provider-thread:laptop");
207 + yield* a.orchestrator.dispatch({
208 + type: "thread.create",
209 + createdBy: "user",
210 + creationSource: "web",
211 + commandId: CommandId.make("command:create:laptop"),
212 + threadId,
213 + projectId: ProjectId.make("project:laptop"),
214 + title: "Laptop",
215 + modelSelection,
216 + runtimeMode,
217 + interactionMode: "default",
218 + branch: null,
219 + worktreePath: null,
220 + ...(linkOrigin === undefined ? {} : { linkOrigin }),
221 + });
222 + yield* a.sink.write({
223 + commandId: CommandId.make("command:seed:laptop"),
224 + events: [
225 + {
226 + id: EventId.make("event:seed-provider-thread"),
227 + type: "provider-thread.updated",
228 + threadId,
229 + driver,
230 + providerInstanceId: instanceId,
231 + occurredAt: now,
232 + payload: {
233 + id: providerThreadId,
234 + driver,
235 + providerInstanceId: instanceId,
236 + providerSessionId: null,
237 + appThreadId: threadId,
238 + ownerNodeId: rootNode,
239 + nativeThreadRef: { driver, nativeId: "native:laptop", strength: "strong" },
240 + nativeConversationHeadRef: null,
241 + status: "active",
242 + firstRunOrdinal: 1,
243 + lastRunOrdinal: 1,
244 + handoffIds: [],
245 + forkedFrom: null,
246 + createdAt: now,
247 + updatedAt: now,
248 + },
249 + },
250 + {
251 + id: EventId.make("event:seed-node"),
252 + type: "node.updated",
253 + threadId,
254 + runId,
255 + nodeId: rootNode,
256 + driver,
257 + providerInstanceId: instanceId,
258 + occurredAt: now,
259 + payload: {
260 + id: rootNode,
261 + threadId,
262 + runId,
263 + parentNodeId: null,
264 + rootNodeId: rootNode,
265 + kind: "root_turn",
266 + status: "running",
267 + countsForRun: true,
268 + providerThreadId,
269 + providerTurnId: null,
270 + nativeItemRef: null,
271 + runtimeRequestId: null,
272 + checkpointScopeId: null,
273 + startedAt: now,
274 + completedAt: null,
275 + },
276 + },
277 + {
278 + id: EventId.make("event:seed-run"),
279 + type: "run.updated",
280 + threadId,
281 + runId,
282 + nodeId: rootNode,
283 + providerInstanceId: instanceId,
284 + occurredAt: now,
285 + payload: {
286 + id: runId,
287 + threadId,
288 + ordinal: 1,
289 + providerInstanceId: instanceId,
290 + modelSelection,
291 + providerThreadId,
292 + userMessageId: MessageId.make("message:seed-user"),
293 + rootNodeId: rootNode,
294 + activeAttemptId: null,
295 + status: "running",
296 + requestedAt: now,
297 + startedAt: now,
298 + completedAt: null,
299 + checkpointId: null,
300 + contextHandoffId: null,
301 + },
302 + },
303 + ],
304 + });
305 + });
306 +
307 +const cardOf = (a: Laptop) =>
308 + a.orchestrator
309 + .getThreadProjection(threadId)
310 + .pipe(
311 + Effect.map((projection) => projection.turnItems.find((item) => item.type === "link_request")),
312 + );
313 +
314 +/** The open card the agent's call left, as the user's client sees it. */
315 +const pendingCard = (a: Laptop) =>
316 + Effect.gen(function* () {
317 + const card = yield* cardOf(a);
318 + expect(card).toMatchObject({ status: "waiting", linkStatus: "pending" });
319 + return card as Extract<NonNullable<typeof card>, { readonly type: "link_request" }>;
320 + });
321 +
322 +/** The outcome notifications the thread received: what the agent reads and the user sees. */
323 +const outcomeMessages = (a: Laptop) =>
324 + a.orchestrator.getThreadProjection(threadId).pipe(
325 + Effect.map((projection) => ({
326 + messages: projection.messages.filter((message) => message.notification !== undefined),
327 + items: projection.turnItems.filter((item) => item.type === "notification"),
328 + })),
329 + );
330 +
331 +/** The agent's turn ends; the card outlives it. */
332 +const endRun = (a: Laptop) =>
333 + Effect.gen(function* () {
334 + const projection = yield* a.orchestrator.getThreadProjection(threadId);
335 + const run = projection.runs.find((candidate) => candidate.id === runId)!;
336 + const now = yield* DateTime.now;
337 + yield* a.sink.write({
338 + commandId: CommandId.make("command:end-run:laptop"),
339 + events: [
340 + {
341 + id: EventId.make("event:end-run"),
342 + type: "run.updated",
343 + threadId,
344 + runId,
345 + nodeId: rootNode,
346 + providerInstanceId: instanceId,
347 + occurredAt: now,
348 + payload: { ...run, status: "completed", completedAt: now },
349 + },
350 + ],
351 + });
352 + });
353 +
354 +/** A steer restarts the agent's turn: its run gets a new root node. */
355 +const restartRun = (a: Laptop) =>
356 + Effect.gen(function* () {
357 + const projection = yield* a.orchestrator.getThreadProjection(threadId);
358 + const run = projection.runs.find((candidate) => candidate.id === runId)!;
359 + const node = projection.nodes.find((candidate) => candidate.id === rootNode)!;
360 + const restarted = NodeId.make("node:laptop:root:2");
361 + const now = yield* DateTime.now;
362 + yield* a.sink.write({
363 + commandId: CommandId.make("command:restart-run:laptop"),
364 + events: [
365 + {
366 + id: EventId.make("event:restart-node"),
367 + type: "node.updated",
368 + threadId,
369 + runId,
370 + nodeId: restarted,
371 + driver,
372 + providerInstanceId: instanceId,
373 + occurredAt: now,
374 + payload: { ...node, id: restarted, rootNodeId: restarted, startedAt: now },
375 + },
376 + {
377 + id: EventId.make("event:restart-run"),
378 + type: "run.updated",
379 + threadId,
380 + runId,
381 + nodeId: restarted,
382 + providerInstanceId: instanceId,
383 + occurredAt: now,
384 + payload: { ...run, rootNodeId: restarted },
385 + },
386 + ],
387 + });
388 + });
389 +
390 +/** What `request` records for a new card, as if it read the run before anything changed. */
391 +const recordPendingCard = (a: Laptop, key: string) =>
392 + a.orchestrator.dispatch({
393 + type: "link_request.record",
394 + commandId: CommandId.make(`command:pending:${key}`),
395 + threadId,
396 + runId,
397 + nodeId: rootNode,
398 + turnItemId: TurnItemId.make(`turn-item:link-request:${key}`),
399 + reason: "",
400 + linkStatus: "pending",
401 + });
402 +
403 +/**
404 + * Every row of every table in the laptop's database, as text, to scan for
405 + * anything leaked: events, projections, receipts and outbox alike.
406 + */
407 +const storedText = (a: Laptop) =>
408 + Effect.gen(function* () {
409 + const tables = yield* a.sql<{ name: string }>`
410 + SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
411 + `;
412 + const rows = yield* Effect.forEach(tables, ({ name }) =>
413 + a.sql.unsafe<Record<string, unknown>>(`SELECT * FROM "${name}"`),
414 + );
415 + const text = rows
416 + .flat()
417 + .map((row) => JSON.stringify(row))
418 + .join("\n");
419 + // The scan saw the card itself, so it read what the thread recorded.
420 + expect(text).toContain("link_request");
421 + return text;
422 + });
423 +
424 +const errorOf = (result: McpSchema.CallToolResult) => {
425 + const text = result.content[0];
426 + return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined;
427 +};
428 +
429 +/** Runs `effect` a year from now, when every link made today has expired. */
430 +const afterLinksExpire = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
431 + Effect.gen(function* () {
432 + const clock = yield* Clock.Clock;
433 + const ahead = Duration.days(365);
434 + const later = () => clock.currentTimeMillisUnsafe() + Duration.toMillis(ahead);
435 + const laterNanos = () => clock.currentTimeNanosUnsafe() + Duration.toNanosUnsafe(ahead);
436 + return yield* effect.pipe(
437 + Effect.provideService(Clock.Clock, {
438 + currentTimeMillisUnsafe: later,
439 + currentTimeMillis: Effect.sync(later),
440 + currentTimeNanosUnsafe: laterNanos,
441 + currentTimeNanos: Effect.sync(laterNanos),
442 + monotonicTimeNanosUnsafe: () => clock.monotonicTimeNanosUnsafe(),
443 + monotonicTimeNanos: clock.monotonicTimeNanos,
444 + sleep: (duration) => clock.sleep(duration),
445 + }),
446 + );
447 + });
448 +
449 +const withBoth = <A, E, R>(body: (a: Laptop, b: ServedPeer) => Effect.Effect<A, E, R>) =>
450 + Effect.scoped(
451 + Effect.gen(function* () {
452 + const b = yield* serveBox;
453 + const a = yield* makeLaptop;
454 + return yield* body(a, b);
455 + }),
456 + ).pipe(Effect.provide(NodeHttpServer.layerTest));
457 +
458 +it.live("the agent asks without waiting, and the user links the box after its turn ended", () =>
459 + withBoth((a, b) =>
460 + Effect.gen(function* () {
461 + yield* seedThread(a);
462 + const asked = yield* a.call({
463 + url: b.url,
464 + reason: "Run the suite on the box.",
465 + requestedAccess: "approval-required",
466 + clientRequestId: "link-box",
467 + });
468 + const card = yield* pendingCard(a);
469 + // The call returns at once: no tool call outlives a provider's timeout.
470 + expect(asked.isError).toBe(false);
471 + expect(asked.structuredContent).toEqual({ status: "pending", turnItemId: card.id });
472 + // The card names the box, found by asking its address.
473 + expect(card).toMatchObject({
474 + url: b.url,
475 + reason: "Run the suite on the box.",
476 + environmentId: box.environmentId,
477 + label: "Box",
478 + requestedAccess: "approval-required",
479 + });
480 + // The agent waits on the user, so the thread asks for input.
481 + expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject(
482 + { kind: "user_input" },
483 + );
484 +
485 + // The agent ends its turn; the card stays answerable, and the thread still asks.
486 + yield* endRun(a);
487 + expect(yield* cardOf(a)).toMatchObject({ status: "waiting", linkStatus: "pending" });
488 + expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject(
489 + { kind: "user_input" },
490 + );
491 + expect(
492 + ProjectionStore.threadShellFromProjection(
493 + yield* a.orchestrator.getThreadProjection(threadId),
494 + ).pendingRuntimeRequest,
495 + ).toMatchObject({ kind: "user_input" });
496 + expect(yield* a.projections.getSettlementCandidates(threadId)).toEqual([]);
497 +
498 + // The user's client mints a code on the box and picks more than the agent suggested.
499 + const pairing = yield* b.auth.issuePairingCredential();
500 + yield* a.requests.answer({
501 + threadId,
502 + turnItemId: card.id,
503 + answer: { type: "link", urls: [b.url], access: "auto", pairingCode: pairing.credential },
504 + });
505 +
506 + const link = yield* a.links.get(box.environmentId);
507 + expect(Option.getOrUndefined(link)?.access).toBe("auto");
508 + expect(yield* cardOf(a)).toMatchObject({
509 + status: "completed",
510 + linkStatus: "linked",
511 + linkedEnvironmentId: box.environmentId,
512 + linkedLabel: "Box",
513 + linkedAccess: "auto",
514 + });
515 + expect((yield* b.linkedSessions).length).toBe(1);
516 +
517 + // The agent hears it as a notification in its thread, not a user message.
518 + const { messages, items } = yield* outcomeMessages(a);
519 + expect(messages).toHaveLength(1);
520 + expect(messages[0]).toMatchObject({
521 + role: "user",
522 + createdBy: "agent",
523 + creationSource: "server",
524 + notification: { outcome: "completed", summary: "Linked Box" },
525 + });
526 + expect(messages[0]!.text).toContain(box.environmentId);
527 + expect(messages[0]!.text).toContain("auto");
528 + expect(items).toHaveLength(1);
529 + expect(items[0]).toMatchObject({ type: "notification", summary: "Linked Box" });
530 +
531 + // The code appears in nothing the thread recorded or the agent received.
532 + expect(yield* storedText(a)).not.toContain(pairing.credential);
533 +
534 + // A card is answered once.
535 + const again = yield* a.requests
536 + .answer({ threadId, turnItemId: card.id, answer: { type: "decline" } })
537 + .pipe(Effect.flip);
538 + expect(again.reason).toBe("already_answered");
539 +
540 + // A retry that lost the first result gets the card's outcome, and records nothing.
541 + const before = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.length;
542 + const retried = yield* a.call({ url: b.url, clientRequestId: "link-box" });
543 + expect(retried.structuredContent).toEqual({
544 + status: "linked",
545 + environmentId: box.environmentId,
546 + label: "Box",
547 + access: "auto",
548 + });
549 + expect((yield* a.orchestrator.getThreadProjection(threadId)).turnItems).toHaveLength(before);
550 + expect((yield* outcomeMessages(a)).messages).toHaveLength(1);
551 + }),
552 + ),
553 +);
554 +
555 +it.live("a retry of a pending request returns pending and shows no second card", () =>
556 + withBoth((a, b) =>
557 + Effect.gen(function* () {
558 + yield* seedThread(a);
559 + const first = yield* a.call({ url: b.url, clientRequestId: "link-box" });
560 + const retried = yield* a.call({ url: b.url, clientRequestId: "link-box" });
561 + expect(retried.structuredContent).toEqual(first.structuredContent);
562 + const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
563 + (item) => item.type === "link_request",
564 + );
565 + expect(cards).toHaveLength(1);
566 + }),
567 + ),
568 +);
569 +
570 +it.live("a later provider session reusing a clientRequestId gets a card of its own", () =>
571 + withBoth((a, b) =>
572 + Effect.gen(function* () {
573 + yield* seedThread(a);
574 + const first = yield* a.call({ url: b.url, clientRequestId: "link" });
575 + const later = yield* a.call(
576 + { environmentId: box.environmentId, clientRequestId: "link" },
577 + {
578 + ...scope,
579 + requestNamespace: "provider-session:laptop-2",
580 + thread: { ...scope.thread!, providerSessionId: "provider-session:laptop-2" },
581 + },
582 + );
583 + expect(later.structuredContent).toMatchObject({ status: "pending" });
584 + expect(later.structuredContent).not.toEqual(first.structuredContent);
585 + const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
586 + (item) => item.type === "link_request",
587 + );
588 + expect(cards).toHaveLength(2);
589 + }),
590 + ),
591 +);
592 +
593 +it.live("a declined request links nothing and tells the agent", () =>
594 + withBoth((a, b) =>
595 + Effect.gen(function* () {
596 + yield* seedThread(a);
597 + yield* a.call({ url: b.url });
598 + const card = yield* pendingCard(a);
599 + yield* a.requests.answer({ threadId, turnItemId: card.id, answer: { type: "decline" } });
600 + expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
601 + expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "declined" });
602 + const { messages } = yield* outcomeMessages(a);
603 + expect(messages).toHaveLength(1);
604 + expect(messages[0]).toMatchObject({
605 + notification: { outcome: "cancelled", summary: "Declined to link Box" },
606 + });
607 + expect(messages[0]!.text).toContain("declined");
608 + }),
609 + ),
610 +);
611 +
612 +it.live("stopping the thread closes its open card, which then takes no answer", () =>
613 + withBoth((a, b) =>
614 + Effect.gen(function* () {
615 + yield* seedThread(a);
616 + yield* a.call({ url: b.url });
617 + const card = yield* pendingCard(a);
618 + yield* a.orchestrator.dispatch({
619 + type: "thread.stop",
620 + commandId: CommandId.make("command:stop:laptop"),
621 + threadId,
622 + });
623 + expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
624 + const late = yield* a.requests
625 + .answer({
626 + threadId,
627 + turnItemId: card.id,
628 + answer: { type: "link", urls: [b.url], access: "auto", pairingCode: "late-code" },
629 + })
630 + .pipe(Effect.flip);
631 + expect(late.reason).toBe("already_answered");
632 + expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
633 + // An answer already linking when Stop landed keeps the card closed and wakes nobody.
634 + yield* a.orchestrator.dispatch({
635 + type: "link_request.record",
636 + commandId: CommandId.make("command:late-answer:laptop"),
637 + threadId,
638 + runId,
639 + nodeId: rootNode,
640 + turnItemId: card.id,
641 + url: card.url,
642 + reason: card.reason,
643 + linkStatus: "declined",
644 + wake: {
645 + messageId: MessageId.make("message:late-answer"),
646 + text: "The user declined.",
647 + notification: {
648 + source: { kind: "background_task" },
649 + outcome: "cancelled",
650 + summary: "Declined",
651 + },
652 + },
653 + });
654 + expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
655 + // The user stopped the thread: nothing wakes the agent.
656 + expect((yield* outcomeMessages(a)).messages).toHaveLength(0);
657 + }),
658 + ),
659 +);
660 +
661 +it.live("a request that read the run before Stop shows no card once Stop lands", () =>
662 + withBoth((a, b) =>
663 + Effect.gen(function* () {
664 + yield* seedThread(a);
665 + yield* a.call({ url: b.url });
666 + const open = yield* pendingCard(a);
667 + yield* a.orchestrator.dispatch({
668 + type: "thread.stop",
669 + commandId: CommandId.make("command:stop:laptop"),
670 + threadId,
671 + });
672 + const late = yield* recordPendingCard(a, "after-stop").pipe(Effect.flip);
673 + expect(String(late.cause)).toContain("not active");
674 + const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
675 + (item) => item.type === "link_request",
676 + );
677 + expect(cards.map((card) => card.id)).toEqual([open.id]);
678 + }),
679 + ),
680 +);
681 +
682 +it.live("a card shows up only while its run is going, and takes an answer after", () =>
683 + withBoth((a, b) =>
684 + Effect.gen(function* () {
685 + yield* seedThread(a);
686 + yield* a.call({ url: b.url });
687 + const card = yield* pendingCard(a);
688 + yield* endRun(a);
689 + const late = yield* recordPendingCard(a, "after-end").pipe(Effect.flip);
690 + expect(String(late.cause)).toContain("not active");
691 + yield* a.requests.answer({ threadId, turnItemId: card.id, answer: { type: "decline" } });
692 + expect(yield* cardOf(a)).toMatchObject({ linkStatus: "declined" });
693 + }),
694 + ),
695 +);
696 +
697 +it.live("a steer that restarts the turn leaves its open card answerable", () =>
698 + withBoth((a, b) =>
699 + Effect.gen(function* () {
700 + yield* seedThread(a);
701 + yield* a.call({ url: b.url });
702 + const card = yield* pendingCard(a);
703 + yield* restartRun(a);
704 + const pairing = yield* b.auth.issuePairingCredential();
705 + yield* a.requests.answer({
706 + threadId,
707 + turnItemId: card.id,
708 + answer: { type: "link", urls: [b.url], access: "auto", pairingCode: pairing.credential },
709 + });
710 + // The card keeps the node it was asked from, and the agent hears the answer.
711 + expect(yield* cardOf(a)).toMatchObject({
712 + linkStatus: "linked",
713 + nodeId: rootNode,
714 + linkedEnvironmentId: box.environmentId,
715 + });
716 + expect((yield* outcomeMessages(a)).messages).toHaveLength(1);
717 + }),
718 + ),
719 +);
720 +
721 +it.live("a slow machine holds up only its own card's answer", () =>
722 + withBoth((a, b) =>
723 + Effect.scoped(
724 + Effect.gen(function* () {
725 + // A machine that takes the descriptor request and answers when the test says.
726 + const reached = yield* Deferred.make<void>();
727 + const release = yield* Deferred.make<void>();
728 + const slow = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest));
729 + const server = Context.get(slow, HttpServer.HttpServer);
730 + yield* server.serve(
731 + Deferred.succeed(reached, undefined).pipe(
732 + Effect.andThen(Deferred.await(release)),
733 + Effect.as(HttpServerResponse.empty({ status: 404 })),
734 + ),
735 + );
736 + if (server.address._tag === "UnixPathAddress") return yield* Effect.die("expected TCP");
737 + const slowUrl = `http://127.0.0.1:${server.address.port}`;
738 +
739 + yield* seedThread(a);
740 + // Recorded directly: asking would probe the slow machine before the answer does.
741 + const slowCard = { id: TurnItemId.make("turn-item:link-request:slow") };
742 + yield* a.orchestrator.dispatch({
743 + type: "link_request.record",
744 + commandId: CommandId.make("command:pending:slow"),
745 + threadId,
746 + runId,
747 + nodeId: rootNode,
748 + turnItemId: slowCard.id,
749 + url: slowUrl,
750 + reason: "",
751 + linkStatus: "pending",
752 + });
753 + yield* a.call({ url: b.url, clientRequestId: "box" });
754 + const boxCard = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.find(
755 + (item) => item.type === "link_request" && item.url === b.url,
756 + )!;
757 +
758 + const slowAnswer = yield* a.requests
759 + .answer({
760 + threadId,
761 + turnItemId: slowCard.id,
762 + answer: { type: "link", urls: [slowUrl], access: "auto", pairingCode: "code" },
763 + })
764 + .pipe(Effect.forkChild);
765 + yield* Deferred.await(reached);
766 +
767 + // While the slow machine holds its card, the user answers the other one.
768 + yield* a.requests.answer({ threadId, turnItemId: boxCard.id, answer: { type: "decline" } });
769 + const items = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems;
770 + expect(items.find((item) => item.id === boxCard.id)).toMatchObject({
771 + linkStatus: "declined",
772 + });
773 + expect(items.find((item) => item.id === slowCard.id)).toMatchObject({
774 + linkStatus: "pending",
775 + });
776 +
777 + yield* Deferred.succeed(release, undefined);
778 + yield* Fiber.join(slowAnswer);
779 + const failed = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.find(
780 + (item) => item.id === slowCard.id,
781 + );
782 + expect(failed).toMatchObject({ linkStatus: "failed" });
783 + }),
784 + ),
785 + ),
786 +);
787 +
788 +it.live("archiving the thread closes its open card", () =>
789 + withBoth((a, b) =>
790 + Effect.gen(function* () {
791 + yield* seedThread(a);
792 + yield* a.call({ url: b.url });
793 + yield* pendingCard(a);
794 + yield* endRun(a);
795 + yield* a.orchestrator.dispatch({
796 + type: "thread.archive",
797 + commandId: CommandId.make("command:archive:laptop"),
798 + threadId,
799 + });
800 + expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
801 + }),
802 + ),
803 +);
804 +
805 +it.live("a code the box refuses fails the request with its reason, and links nothing", () =>
806 + withBoth((a, b) =>
807 + Effect.gen(function* () {
808 + yield* seedThread(a);
809 + yield* a.call({ url: b.url });
810 + const card = yield* pendingCard(a);
811 + yield* a.requests.answer({
812 + threadId,
813 + turnItemId: card.id,
814 + answer: {
815 + type: "link",
816 + urls: [b.url],
817 + access: "auto",
818 + pairingCode: "not-a-real-code",
819 + },
820 + });
821 + const failed = yield* cardOf(a);
822 + expect(failed).toMatchObject({ status: "failed", linkStatus: "failed" });
823 + const reason = failed?.type === "link_request" ? failed.failure : undefined;
824 + expect(reason?.length).toBeGreaterThan(0);
825 + const { messages } = yield* outcomeMessages(a);
826 + expect(messages[0]).toMatchObject({ notification: { outcome: "failed" } });
827 + expect(messages[0]!.text).toContain(reason);
828 + expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
829 + expect(yield* storedText(a)).not.toContain("not-a-real-code");
830 + }),
831 + ),
832 +);
833 +
834 +it.live("an agent below full access may not ask, and no card is shown", () =>
835 + withBoth((a, b) =>
836 + Effect.gen(function* () {
837 + yield* seedThread(a, "auto");
838 + const refused = yield* a.call({ url: b.url });
839 + expect(errorOf(refused)).toMatchObject({ code: "capability_denied" });
840 + expect(yield* cardOf(a)).toBeUndefined();
841 + }),
842 + ),
843 +);
844 +
845 +it.live("work another environment's link started may not ask, and no card is shown", () =>
846 + withBoth((a, b) =>
847 + Effect.gen(function* () {
848 + yield* seedThread(a, "full-access", { sessionId: "session:desk", label: "T3 Code · Desk" });
849 + const refused = yield* a.call({ url: b.url });
850 + expect(errorOf(refused)).toMatchObject({ code: "capability_denied" });
851 + expect(errorOf(refused).message).toContain("T3 Code · Desk");
852 + expect(yield* cardOf(a)).toBeUndefined();
853 + }),
854 + ),
855 +);
856 +
857 +it.live(
858 + "an agent that names no machine leaves the pick to the user, who links one by its addresses",
859 + () =>
860 + withBoth((a, b) =>
861 + Effect.gen(function* () {
862 + yield* seedThread(a);
863 + const asked = yield* a.call({ reason: "Delegate the build to the vps.", hint: "vps" });
864 + expect(asked.structuredContent).toMatchObject({ status: "pending" });
865 + const card = yield* pendingCard(a);
866 + expect(card).toMatchObject({ reason: "Delegate the build to the vps.", hint: "vps" });
867 + expect(card.url).toBeUndefined();
868 + expect(card.environmentId).toBeUndefined();
869 +
870 + // The user picks the box; their client knows a stale address for it first.
871 + const pairing = yield* b.auth.issuePairingCredential();
872 + yield* a.requests.answer({
873 + threadId,
874 + turnItemId: card.id,
875 + answer: {
876 + type: "link",
877 + environmentId: box.environmentId,
878 + label: "Box",
879 + urls: ["http://127.0.0.1:9", b.url],
880 + access: "auto",
881 + pairingCode: pairing.credential,
882 + },
883 + });
884 + expect(Option.getOrUndefined(yield* a.links.get(box.environmentId))).toMatchObject({
885 + urls: [b.url],
886 + access: "auto",
887 + });
888 + expect(yield* cardOf(a)).toMatchObject({
889 + linkStatus: "linked",
890 + linkedEnvironmentId: box.environmentId,
891 + });
892 + expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("linked Box");
893 + }),
894 + ),
895 +);
896 +
897 +it.live("naming a machine that is already linked returns the link at once, with no card", () =>
898 + withBoth((a, b) =>
899 + Effect.gen(function* () {
900 + yield* seedThread(a);
901 + const pairing = yield* b.auth.issuePairingCredential();
902 + yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
903 + const asked = yield* a.call({ environmentId: box.environmentId });
904 + expect(asked.structuredContent).toEqual({
905 + status: "linked",
906 + environmentId: box.environmentId,
907 + label: "Box",
908 + access: "auto",
909 + });
910 + expect(yield* cardOf(a)).toBeUndefined();
911 +
912 + // Not both: the address could name another machine than the id.
913 + const both = yield* a.call({ environmentId: box.environmentId, url: b.url });
914 + expect(errorOf(both)).toMatchObject({ code: "invalid_request" });
915 + }),
916 + ),
917 +);
918 +
919 +it.live("a link that expired goes through the card, so the user can link it again", () =>
920 + withBoth((a, b) =>
921 + Effect.gen(function* () {
922 + yield* seedThread(a);
923 + yield* linkTo(a.links, b, "read-only");
924 + const asked = yield* a.call({ environmentId: box.environmentId }).pipe(afterLinksExpire);
925 + expect(asked.structuredContent).toMatchObject({ status: "pending" });
926 + const card = yield* pendingCard(a);
927 +
928 + // Keeping the expired link is no answer: the card fails and says why.
929 + yield* a.requests
930 + .answer({
931 + threadId,
932 + turnItemId: card.id,
933 + answer: { type: "use-existing", environmentId: box.environmentId },
934 + })
935 + .pipe(afterLinksExpire);
936 + expect(yield* cardOf(a)).toMatchObject({ linkStatus: "failed" });
937 + expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("expired");
938 + }),
939 + ),
940 +);
941 +
942 +it.live("a link made before links were fenced goes through the card, as an expired one", () =>
943 + withBoth((a, b) =>
944 + Effect.gen(function* () {
945 + yield* seedThread(a);
946 + yield* linkTo(a.links, b);
947 + yield* a.linksSql`UPDATE peer_environment_links SET fenced = 0`;
948 + const asked = yield* a.call({ environmentId: box.environmentId });
949 + expect(asked.structuredContent).toMatchObject({ status: "pending" });
950 + yield* pendingCard(a);
951 + }),
952 + ),
953 +);
954 +
955 +it.live(
956 + "a card for a machine named by id keeps it, and the user may keep a link it already has",
957 + () =>
958 + withBoth((a, b) =>
959 + Effect.gen(function* () {
960 + yield* seedThread(a);
961 + yield* a.call({ environmentId: box.environmentId });
962 + const card = yield* pendingCard(a);
963 + expect(card.environmentId).toBe(box.environmentId);
964 + // Linked from Settings meanwhile; the card answers with that link.
965 + const pairing = yield* b.auth.issuePairingCredential();
966 + yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "read-only" });
967 + yield* a.requests.answer({
968 + threadId,
969 + turnItemId: card.id,
970 + answer: { type: "use-existing", environmentId: box.environmentId },
971 + });
972 + expect(yield* cardOf(a)).toMatchObject({
973 + linkStatus: "linked",
974 + linkedAccess: "read-only",
975 + });
976 + expect((yield* b.linkedSessions).length).toBe(1);
977 + }),
978 + ),
979 +);
apps/server/src/peer/PeerLinkRequests.ts new
+412
@@ -0,0 +1,412 @@
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 Crypto from "effect/Crypto";
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" | "label" | "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 returns the card's current outcome.
67 + */
68 + readonly request: (
69 + scope: McpInvocationContext.McpInvocationScope,
70 + input: OrchestratorMcpEnvironmentLinkInput,
71 + ) => Effect.Effect<OrchestratorMcpEnvironmentLinkResult, OrchestratorMcpFailure>;
72 + /**
73 + * Answers a pending card and tells the agent. Linking uses the pairing
74 + * code once; a link the other environment refuses closes the card as
75 + * failed, with its reason.
76 + */
77 + readonly answer: (
78 + input: PeerLinkRequestAnswerInput,
79 + ) => Effect.Effect<void, PeerLinkRequestError>;
80 + }
81 +>()("t3/peer/PeerLinkRequests") {}
82 +
83 +const make = Effect.gen(function* () {
84 + const threadManagement = yield* ThreadManagementService.ThreadManagementService;
85 + const peerLinks = yield* PeerLinks.PeerLinks;
86 + const crypto = yield* Crypto.Crypto;
87 +
88 + const readCard = (threadId: ThreadId, turnItemId: TurnItemId) =>
89 + threadManagement
90 + .getThreadRecords(threadId, ["turnItems"], {
91 + turnItemTypes: ["link_request"],
92 + messageRoles: [],
93 + })
94 + .pipe(
95 + Effect.map((records) => {
96 + const item = records.turnItems.find((candidate) => candidate.id === turnItemId);
97 + // A deleted thread's cards went with it.
98 + return item?.type === "link_request" && records.thread.deletedAt === null
99 + ? item
100 + : undefined;
101 + }),
102 + );
103 +
104 + /**
105 + * The stored link to `environmentId`, or nothing once it has expired: an
106 + * expired link needs a new pairing code, which only the card asks for.
107 + */
108 + const usableLink = (environmentId: EnvironmentId) =>
109 + Effect.all([peerLinks.get(environmentId), DateTime.now]).pipe(
110 + Effect.map(([linked, now]) =>
111 + Option.filter(linked, (link) => DateTime.isGreaterThan(link.expiresAt, now)),
112 + ),
113 + );
114 +
115 + const record = (
116 + card: LinkRequestAsk,
117 + outcome: LinkRequestOutcome,
118 + commandId: CommandId,
119 + wake?: LinkRequestWake,
120 + ) =>
121 + threadManagement.dispatch({
122 + type: "link_request.record",
123 + commandId,
124 + threadId: card.threadId,
125 + runId: card.runId,
126 + nodeId: card.nodeId,
127 + turnItemId: card.id,
128 + ...(card.url === undefined ? {} : { url: card.url }),
129 + reason: card.reason,
130 + ...(card.environmentId === undefined ? {} : { environmentId: card.environmentId }),
131 + ...(card.label === undefined ? {} : { label: card.label }),
132 + ...(card.hint === undefined ? {} : { hint: card.hint }),
133 + ...(card.requestedAccess === undefined ? {} : { requestedAccess: card.requestedAccess }),
134 + ...outcome,
135 + ...(wake === undefined ? {} : { wake }),
136 + });
137 +
138 + const request: PeerLinkRequests["Service"]["request"] = Effect.fn("PeerLinkRequests.request")(
139 + function* (scope, input) {
140 + // The card is shown in, and answered from, the caller's own thread.
141 + const threadScope = yield* McpInvocationContext.requireThreadScope(
142 + scope,
143 + "t3_environment_link",
144 + );
145 + const threadId = threadScope.thread.threadId;
146 + const unreadable = (error: unknown) =>
147 + new OrchestratorMcpFailure({
148 + code: "orchestration_error",
149 + message: `Unable to read the link request: ${errorMessage(error)}`,
150 + });
151 + if (input.url !== undefined && input.environmentId !== undefined) {
152 + return yield* new OrchestratorMcpFailure({
153 + code: "invalid_request",
154 + message:
155 + "Pass either environmentId or url, not both. Pass neither to let the user pick the machine.",
156 + });
157 + }
158 + // A machine already linked needs no card: the agent can use it now.
159 + if (input.environmentId !== undefined) {
160 + const linked = yield* usableLink(input.environmentId).pipe(
161 + Effect.mapError(
162 + (error) =>
163 + new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
164 + ),
165 + );
166 + if (Option.isSome(linked)) {
167 + return {
168 + status: "linked",
169 + environmentId: linked.value.environmentId,
170 + label: linked.value.label,
171 + access: linked.value.access,
172 + } as const;
173 + }
174 + }
175 + const key = input.clientRequestId ?? (yield* crypto.randomUUIDv4().pipe(Effect.orDie));
176 + // Turn item ids are global; scope the key to this thread and provider
177 + // session, since a later session may reuse it. A retry with the same
178 + // clientRequestId finds this card and records nothing.
179 + const turnItemId = TurnItemId.make(
180 + `turn-item:link-request:${encodeURIComponent(threadId)}:${encodeURIComponent(scope.requestNamespace)}:${encodeURIComponent(key)}`,
181 + );
182 + if (input.clientRequestId !== undefined) {
183 + const existing = yield* readCard(threadId, turnItemId).pipe(Effect.mapError(unreadable));
184 + if (existing !== undefined) return resultOf(existing);
185 + }
186 + const parent = yield* threadManagement
187 + .getThreadRecords(threadId, ["runs"], { messageRoles: [] })
188 + .pipe(Effect.mapError(unreadable));
189 + const run = ThreadManagementService.latestActiveRun(parent);
190 + if (
191 + run === undefined ||
192 + run.rootNodeId === null ||
193 + run.providerInstanceId !== threadScope.thread.providerInstanceId
194 + ) {
195 + return yield* new OrchestratorMcpFailure({
196 + code: "parent_not_active",
197 + message:
198 + "Asking to link an environment requires an active run owned by this MCP provider session.",
199 + });
200 + }
201 + // Best effort: the card names the machine at an address the agent was
202 + // given, and the client finds it by id.
203 + const peer = input.url === undefined ? Option.none() : yield* peerLinks.describe(input.url);
204 + yield* record(
205 + {
206 + id: turnItemId,
207 + threadId,
208 + runId: run.id,
209 + nodeId: run.rootNodeId,
210 + ...(input.url === undefined ? {} : { url: input.url }),
211 + reason: input.reason ?? "",
212 + ...(Option.isSome(peer)
213 + ? { environmentId: peer.value.environmentId, label: peer.value.label }
214 + : input.environmentId === undefined
215 + ? {}
216 + : { environmentId: input.environmentId }),
217 + ...(input.hint === undefined ? {} : { hint: input.hint }),
218 + ...(input.requestedAccess === undefined
219 + ? {}
220 + : { requestedAccess: input.requestedAccess }),
221 + },
222 + { linkStatus: "pending" },
223 + CommandId.make(
224 + `command:mcp:${encodeURIComponent(scope.requestNamespace)}:link-pending:${encodeURIComponent(key)}`,
225 + ),
226 + ).pipe(
227 + Effect.mapError(
228 + (error) =>
229 + new OrchestratorMcpFailure({
230 + code: "orchestration_error",
231 + message: `Could not record the link request: ${errorMessage(error)}`,
232 + }),
233 + ),
234 + );
235 + return pendingResult(turnItemId);
236 + },
237 + Effect.withSpan("PeerLinkRequests.request"),
238 + );
239 +
240 + const linkedOutcome = (linked: PeerLink): LinkRequestOutcome => ({
241 + linkStatus: "linked",
242 + linkedEnvironmentId: linked.environmentId,
243 + linkedLabel: linked.label,
244 + linkedAccess: linked.access,
245 + });
246 +
247 + /** Links the machine the user picked, or finds the link they chose to keep. */
248 + const answerOutcome = (
249 + answer: PeerLinkRequestAnswerInput["answer"],
250 + ): Effect.Effect<LinkRequestOutcome> => {
251 + switch (answer.type) {
252 + case "decline":
253 + return Effect.succeed({ linkStatus: "declined" });
254 + case "use-existing":
255 + return usableLink(answer.environmentId).pipe(
256 + Effect.flatMap(
257 + Option.match({
258 + onNone: () =>
259 + Effect.fail(
260 + new PeerLinkError({
261 + reason: "unknown_link",
262 + message:
263 + "That environment is no longer linked here, or its link expired. Link it again.",
264 + }),
265 + ),
266 + onSome: (linked) => Effect.succeed(linkedOutcome(linked)),
267 + }),
268 + ),
269 + Effect.catch((error) =>
270 + Effect.succeed<LinkRequestOutcome>({ linkStatus: "failed", failure: error.message }),
271 + ),
272 + );
273 + case "link": {
274 + const [url, ...alternateUrls] = answer.urls;
275 + return peerLinks
276 + .link({
277 + url,
278 + ...(alternateUrls.length === 0 ? {} : { alternateUrls }),
279 + pairingCode: answer.pairingCode,
280 + access: answer.access,
281 + ...(answer.environmentId === undefined
282 + ? {}
283 + : { expectedEnvironmentId: answer.environmentId }),
284 + ...(answer.label === undefined ? {} : { expectedLabel: answer.label }),
285 + })
286 + .pipe(
287 + Effect.map(linkedOutcome),
288 + Effect.catch((error) =>
289 + Effect.succeed<LinkRequestOutcome>({ linkStatus: "failed", failure: error.message }),
290 + ),
291 + );
292 + }
293 + }
294 + };
295 +
296 + // One answer per card at a time: two answers racing on one card must not
297 + // both link. Other cards go on while a slow peer holds one.
298 + const answerLocks = yield* KeyedLock.make<TurnItemId>();
299 + const answer: PeerLinkRequests["Service"]["answer"] = Effect.fn("PeerLinkRequests.answer")(
300 + function* (input) {
301 + yield* Effect.annotateCurrentSpan({
302 + "orchestration_v2.thread_id": input.threadId,
303 + "link_request.answer": input.answer.type,
304 + });
305 + const card = yield* readCard(input.threadId, input.turnItemId).pipe(
306 + Effect.mapError((cause) => new PeerLinkRequestError({ reason: "load_failed", cause })),
307 + );
308 + if (card === undefined || card.runId === null || card.nodeId === null) {
309 + return yield* new PeerLinkRequestError({ reason: "not_found" });
310 + }
311 + // Any time while the card is open: the agent hears the answer as a
312 + // notification, whether or not its run is still going.
313 + if (card.linkStatus !== "pending") {
314 + return yield* new PeerLinkRequestError({ reason: "already_answered" });
315 + }
316 + const outcome = yield* answerOutcome(input.answer);
317 + // If Stop closed the card while linking, the card keeps that; the link
318 + // itself stands and Settings lists it.
319 + yield* record(
320 + { ...card, runId: card.runId, nodeId: card.nodeId },
321 + outcome,
322 + CommandId.make(`link-request:${card.id}:${outcome.linkStatus}`),
323 + {
324 + messageId: MessageId.make(`message:link-request:${card.id}`),
325 + ...outcomeNotice(card, outcome),
326 + },
327 + ).pipe(
328 + Effect.mapError((cause) => new PeerLinkRequestError({ reason: "record_failed", cause })),
329 + );
330 + },
331 + (effect, input) =>
332 + effect.pipe(
333 + (effect) => answerLocks.withLock(input.turnItemId, effect),
334 + Effect.withSpan("PeerLinkRequests.answer"),
335 + ),
336 + );
337 +
338 + return PeerLinkRequests.of({ request, answer });
339 +});
340 +
341 +const pendingResult = (turnItemId: TurnItemId): OrchestratorMcpEnvironmentLinkResult => ({
342 + status: "pending",
343 + turnItemId,
344 +});
345 +
346 +/** What a retry hears: the card's outcome, without anything the user typed. */
347 +const resultOf = (card: LinkRequestItem): OrchestratorMcpEnvironmentLinkResult => {
348 + switch (card.linkStatus) {
349 + case "pending":
350 + return pendingResult(card.id);
351 + case "linked":
352 + return {
353 + status: "linked",
354 + environmentId: card.linkedEnvironmentId!,
355 + label: card.linkedLabel ?? linkTarget(card),
356 + access: card.linkedAccess!,
357 + };
358 + case "failed":
359 + return { status: "failed", message: card.failure ?? "The link could not be made." };
360 + case "declined":
361 + case "cancelled":
362 + return { status: card.linkStatus };
363 + }
364 +};
365 +
366 +/** What the agent's words call the target: its name, its address, or the user's pick. */
367 +const linkTarget = (card: Pick<LinkRequestItem, "url" | "label" | "environmentId">) =>
368 + card.label ?? card.url ?? card.environmentId ?? "a machine";
369 +
370 +/**
371 + * The notification an answer sends the agent: what the card says, and what
372 + * to do next. It carries the outcome only, never the pairing code.
373 + */
374 +const outcomeNotice = (
375 + card: Pick<LinkRequestItem, "url" | "label" | "environmentId">,
376 + outcome: LinkRequestOutcome,
377 +): Omit<LinkRequestWake, "messageId"> => {
378 + const target = linkTarget(card);
379 + switch (outcome.linkStatus) {
380 + case "linked": {
381 + const label = outcome.linkedLabel ?? target;
382 + return {
383 + text: `The user linked ${label} with ${outcome.linkedAccess} access. Pass environmentId ${outcome.linkedEnvironmentId} to act there.`,
384 + notification: {
385 + source: { kind: "background_task" },
386 + outcome: "completed",
387 + summary: `Linked ${label}`,
388 + },
389 + };
390 + }
391 + case "failed":
392 + return {
393 + text: `Linking ${target} failed: ${outcome.failure ?? "the other environment refused"}. Call t3_environment_link again if the user still wants it.`,
394 + notification: {
395 + source: { kind: "background_task" },
396 + outcome: "failed",
397 + summary: `Could not link ${target}`,
398 + },
399 + };
400 + default:
401 + return {
402 + text: `The user declined to link ${target}.`,
403 + notification: {
404 + source: { kind: "background_task" },
405 + outcome: "cancelled",
406 + summary: `Declined to link ${target}`,
407 + },
408 + };
409 + }
410 +};
411 +
412 +export const layer = Layer.effect(PeerLinkRequests, make);
apps/server/src/peer/PeerLinks.test.ts
+117 -2
@@ -19,6 +19,7 @@ import {
19 HttpServerResponse,
20 } from "effect/http";
21
22 +import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
23 import * as McpHttpServer from "../mcp/McpHttpServer.ts";
24 import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
25 import * as McpToolAccess from "../mcp/McpToolAccess.ts";
@@ -73,8 +74,11 @@ const serveB = (descriptor: ExecutionEnvironmentDescriptor) =>
74 servePeer(descriptor, McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers));
75
76 /** Environment A, which links to B. */
76 -const makeA = (descriptor: ExecutionEnvironmentDescriptor) =>
77 - layerLinkingEnvironment(descriptor).pipe(
77 +const makeA = (
78 + descriptor: ExecutionEnvironmentDescriptor,
79 + secrets?: typeof ServerSecretStore.layer,
80 +) =>
81 + layerLinkingEnvironment(descriptor, secrets).pipe(
82 Layer.build,
83 Effect.map((context) => ({
84 links: Context.get(context, PeerLinks.PeerLinks),
@@ -100,6 +104,12 @@ const probe = (
104
105 const linkedSessions = (b: ServedPeer) => b.linkedSessions;
106
107 +/** Another environment on a socket of its own, answering as `descriptor`. */
108 +const serveApart = (descriptor: ExecutionEnvironmentDescriptor) =>
109 + Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
110 + Effect.flatMap((server) => serveB(descriptor).pipe(Effect.provideContext(server))),
111 + );
112 +
113 it.effect("links with a pairing code, and the peer holds its agents to the limits they carry", () =>
114 Effect.scoped(
115 Effect.gen(function* () {
@@ -145,6 +155,46 @@ it.effect("links with a pairing code, and the peer holds its agents to the limit
155 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
156 );
157
158 +it.effect("a link whose row cannot be stored keeps none of its token", () =>
159 + Effect.scoped(
160 + Effect.gen(function* () {
161 + const b = yield* serveB(box);
162 + const held = yield* Ref.make<ReadonlySet<string>>(new Set());
163 + const noted = Layer.effect(
164 + ServerSecretStore.ServerSecretStore,
165 + Effect.map(ServerSecretStore.make, (store) =>
166 + ServerSecretStore.ServerSecretStore.of({
167 + ...store,
168 + set: (name, value) =>
169 + store
170 + .set(name, value)
171 + .pipe(Effect.andThen(Ref.update(held, (names) => new Set([...names, name])))),
172 + remove: (name) =>
173 + store
174 + .remove(name)
175 + .pipe(
176 + Effect.andThen(
177 + Ref.update(held, (names) => new Set([...names].filter((at) => at !== name))),
178 + ),
179 + ),
180 + }),
181 + ),
182 + );
183 + const a = yield* makeA(laptop, noted);
184 + yield* a.sql`
185 + CREATE TRIGGER refuse_link BEFORE INSERT ON peer_environment_links
186 + BEGIN SELECT RAISE(ABORT, 'database or disk is full'); END
187 + `;
188 + const pairing = yield* b.auth.issuePairingCredential();
189 + const failed = yield* a.links
190 + .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
191 + .pipe(Effect.flip);
192 + expect(failed.reason).toBe("storage");
193 + expect(yield* Ref.get(held)).toEqual(new Set());
194 + }),
195 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
196 +);
197 +
198 it.effect("two links racing to one peer leave the stored access matching the token", () =>
199 Effect.scoped(
200 Effect.gen(function* () {
@@ -300,6 +350,8 @@ it.effect("tells the agent to link again once the peer revokes the link or it ex
350 // A link stored before links were marked: its session there is not a
351 // link's, so the peer would not fence its work even though it can.
352 yield* a.sql`UPDATE peer_environment_links SET fenced = 0`;
353 + // Linking again is its only way back, as for an expired link.
354 + expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
355 const legacy = yield* probe(a).pipe(Effect.flip);
356 expect(legacy.code).toBe("capability_denied");
357 expect(legacy.message).toContain("Link it again");
@@ -372,3 +424,66 @@ it.effect(
424 }),
425 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
426 );
427 +
428 +it.effect(
429 + "linking a picked machine skips an address that answers as another, and never signs in there",
430 + () =>
431 + Effect.scoped(
432 + Effect.gen(function* () {
433 + const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
434 + const b = yield* serveB(box);
435 + const a = yield* makeA(laptop);
436 + const pairing = yield* b.auth.issuePairingCredential();
437 + const linked = yield* a.links.link({
438 + url: impostor.url,
439 + alternateUrls: [b.url],
440 + pairingCode: pairing.credential,
441 + access: "auto",
442 + expectedEnvironmentId: box.environmentId,
443 + });
444 + expect(linked).toMatchObject({ environmentId: box.environmentId, urls: [b.url] });
445 + yield* probe(a);
446 + expect(yield* linkedSessions(impostor)).toEqual([]);
447 + expect(yield* Ref.get(impostor.bearers)).toEqual([]);
448 + expect((yield* linkedSessions(b)).length).toBe(1);
449 + }),
450 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
451 +);
452 +
453 +it.effect("linking a picked machine that answers nowhere names it and links nothing", () =>
454 + Effect.scoped(
455 + Effect.gen(function* () {
456 + const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
457 + const a = yield* makeA(laptop);
458 + const failed = yield* a.links
459 + .link({
460 + url: impostor.url,
461 + alternateUrls: ["http://192.168.1.20:3773"],
462 + pairingCode: "unused",
463 + access: "auto",
464 + expectedEnvironmentId: box.environmentId,
465 + expectedLabel: "Box",
466 + })
467 + .pipe(Effect.flip);
468 + expect(failed.reason).toBe("unreachable");
469 + expect(failed.message).toBe(
470 + `This environment could not reach Box at ${impostor.url}, http://192.168.1.20:3773.`,
471 + );
472 + expect(yield* a.links.list).toEqual([]);
473 + expect(yield* linkedSessions(impostor)).toEqual([]);
474 +
475 + // Every address refused: the message says why.
476 + const refused = yield* a.links
477 + .link({
478 + url: "http://192.168.1.20:3773",
479 + pairingCode: "unused",
480 + access: "auto",
481 + expectedEnvironmentId: box.environmentId,
482 + expectedLabel: "Box",
483 + })
484 + .pipe(Effect.flip);
485 + expect(refused.message).toContain("could not reach Box");
486 + expect(refused.message).toContain("plain http");
487 + }),
488 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
489 +);
apps/server/src/peer/PeerLinks.testkit.ts
+5 -2
@@ -148,11 +148,14 @@ export type ServedPeer = Effect.Success<ReturnType<typeof servePeer>>;
148 * The environment that links: its own database and secret store, reaching
149 * peers over plain HTTP. Provide it to anything built on its links.
150 */
151 -export const layerLinkingEnvironment = (descriptor: ExecutionEnvironmentDescriptor) =>
151 +export const layerLinkingEnvironment = (
152 + descriptor: ExecutionEnvironmentDescriptor,
153 + secrets: typeof ServerSecretStore.layer = ServerSecretStore.layer,
154 +) =>
155 PeerMcpClient.layer.pipe(
156 Layer.provideMerge(PeerLinks.layer),
157 Layer.provideMerge(Sqlite.layerMemory),
155 - Layer.provide(Layer.mergeAll(ServerSecretStore.layer, FetchHttpClient.layer)),
158 + Layer.provide(Layer.mergeAll(secrets, FetchHttpClient.layer)),
159 // Services that act for this environment, such as delegation, name it too.
160 Layer.provideMerge(
161 Layer.succeed(ServerEnvironment.ServerEnvironment, {
apps/server/src/peer/PeerLinks.ts
+98 -16
@@ -21,6 +21,7 @@ import * as Base64Url from "effect/encoding/Base64Url";
21 import * as Hex from "effect/encoding/Hex";
22 import * as Layer from "effect/Layer";
23 import * as Option from "effect/Option";
24 +import * as Result from "effect/Result";
25 import * as Schema from "effect/Schema";
26 import * as SqlClient from "effect/sql/SqlClient";
27 import * as FetchHttpClient from "effect/http/FetchHttpClient";
@@ -58,6 +59,15 @@ export class PeerLinks extends Context.Service<
59 PeerLinks,
60 {
61 readonly link: (input: PeerLinkCreateInput) => Effect.Effect<PeerLink, PeerLinkError>;
62 + /**
63 + * The environment answering at `url`, or nothing when it is not a usable
64 + * address or does not answer as T3 Code. Sends no credential.
65 + */
66 + readonly describe: (
67 + url: string,
68 + ) => Effect.Effect<
69 + Option.Option<{ readonly environmentId: EnvironmentId; readonly label: string }>
70 + >;
71 readonly list: Effect.Effect<ReadonlyArray<PeerLinkSummary>, PeerLinkError>;
72 /** The stored link, without asking the peer whether it answers. */
73 readonly get: (
@@ -182,7 +192,9 @@ const make = Effect.gen(function* () {
192 urls: yield* decodeUrls(row.urls_json),
193 access: yield* decodeAccess(row.access),
194 linkedAt: DateTime.makeUnsafe(row.linked_at),
185 - expiresAt: DateTime.makeUnsafe(row.expires_at),
195 + // Its token predates link fencing, so the peer would not fence its work:
196 + // like an expired link, only a new pairing code brings it back.
197 + expiresAt: DateTime.makeUnsafe(row.fenced === 1 ? row.expires_at : row.linked_at),
198 lastReachedAt: row.last_reached_at === null ? null : DateTime.makeUnsafe(row.last_reached_at),
199 lastError: row.last_error,
200 } satisfies PeerLink;
@@ -317,8 +329,53 @@ const make = Effect.gen(function* () {
329 ),
330 );
331
320 - const link: PeerLinks["Service"]["link"] = Effect.fn("PeerLinks.link")(function* (input) {
321 - const origins = yield* Effect.forEach([input.url, ...(input.alternateUrls ?? [])], peerOrigin);
332 + /**
333 + * The addresses that answer as `environmentId`, in the order given, with
334 + * what the first one answered. Addresses this environment would not send
335 + * credentials to are skipped; when every one is, the failure says why.
336 + */
337 + const answeringAs = Effect.fn("PeerLinks.answeringAs")(function* (
338 + urls: ReadonlyArray<string>,
339 + environmentId: EnvironmentId,
340 + name: string,
341 + ) {
342 + const checked = yield* Effect.forEach(
343 + urls,
344 + (url) =>
345 + Effect.gen(function* () {
346 + const origin = yield* peerOrigin(url);
347 + return { origin, descriptor: yield* describe(origin) };
348 + }).pipe(Effect.result),
349 + { concurrency: "unbounded" },
350 + );
351 + const matching = checked.flatMap((result) =>
352 + Result.isSuccess(result) &&
353 + Option.isSome(result.success.descriptor) &&
354 + result.success.descriptor.value.environmentId === environmentId
355 + ? [{ origin: result.success.origin, descriptor: result.success.descriptor.value }]
356 + : [],
357 + );
358 + const first = matching[0];
359 + if (first === undefined) {
360 + const refusals = checked.flatMap((result) =>
361 + Result.isFailure(result) ? [result.failure.message] : [],
362 + );
363 + return yield* new PeerLinkError({
364 + reason: "unreachable",
365 + message:
366 + refusals.length === checked.length
367 + ? `This environment could not reach ${name}: ${refusals.join(" ")}`
368 + : `This environment could not reach ${name} at ${urls.join(", ")}.`,
369 + });
370 + }
371 + // Each address is kept once, even when two spellings share an origin.
372 + const origins = [...new Set(matching.map((found) => found.origin))];
373 + return { primary: first.origin, peer: first.descriptor, origins };
374 + });
375 +
376 + /** The peer at `url`, with every address checked for credentials first. */
377 + const answeringAt = Effect.fn("PeerLinks.answeringAt")(function* (urls: ReadonlyArray<string>) {
378 + const origins = yield* Effect.forEach(urls, peerOrigin);
379 const primary = origins[0]!;
380 const descriptor = yield* describe(primary);
381 if (Option.isNone(descriptor)) {
@@ -327,7 +384,21 @@ const make = Effect.gen(function* () {
384 message: `Nothing at ${primary} answered as a T3 Code environment.`,
385 });
386 }
330 - const peer = descriptor.value;
387 + return { primary, peer: descriptor.value, origins };
388 + });
389 +
390 + const link: PeerLinks["Service"]["link"] = Effect.fn("PeerLinks.link")(function* (input) {
391 + const urls = [input.url, ...(input.alternateUrls ?? [])];
392 + // The user picked a machine: link through the addresses that prove to
393 + // be it, so a reused LAN address never receives the pairing code.
394 + const { primary, peer, origins } =
395 + input.expectedEnvironmentId === undefined
396 + ? yield* answeringAt(urls)
397 + : yield* answeringAs(
398 + urls,
399 + input.expectedEnvironmentId,
400 + input.expectedLabel ?? input.expectedEnvironmentId,
401 + );
402 const self = yield* environment.getDescriptor;
403 if (peer.environmentId === self.environmentId) {
404 return yield* new PeerLinkError({
@@ -359,9 +430,11 @@ const make = Effect.gen(function* () {
430 yield* secrets
431 .set(secretName, new TextEncoder().encode(issued.access_token))
432 .pipe(Effect.catch(failStorage));
362 - const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage));
363 - const previous = yield* readRow(peer.environmentId);
364 - yield* sql`
433 + // A token no row names could never be removed.
434 + const previous = yield* Effect.gen(function* () {
435 + const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage));
436 + const previous = yield* readRow(peer.environmentId);
437 + yield* sql`
438 INSERT INTO peer_environment_links (
439 environment_id, secret_name, label, urls_json, access, linked_at, expires_at,
440 last_reached_at, last_error, fenced
@@ -381,6 +454,8 @@ const make = Effect.gen(function* () {
454 last_reached_at = excluded.last_reached_at,
455 last_error = NULL
456 `.pipe(Effect.catch(failStorage));
457 + return previous;
458 + }).pipe(Effect.onError(() => secrets.remove(secretName).pipe(Effect.ignore)));
459 // Linking again replaces the old token. A racing link may leave its own
460 // behind; it is unused either way.
461 if (Option.isSome(previous) && previous.value.secret_name !== secretName) {
@@ -389,6 +464,13 @@ const make = Effect.gen(function* () {
464 return linked;
465 });
466
467 + const describeUrl: PeerLinks["Service"]["describe"] = (url) =>
468 + peerOrigin(url).pipe(
469 + Effect.flatMap(describe),
470 + Effect.map(Option.map((peer) => ({ environmentId: peer.environmentId, label: peer.label }))),
471 + Effect.orElseSucceed(() => Option.none()),
472 + );
473 +
474 const statusOf = (link: PeerLink, now: DateTime.Utc) =>
475 DateTime.isLessThanOrEqualTo(link.expiresAt, now)
476 ? Effect.succeed<PeerLinkStatus>("expired")
@@ -453,14 +535,6 @@ const make = Effect.gen(function* () {
535 message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`,
536 });
537 }
456 - // Its token was issued before links were marked as links, so the peer
457 - // never fences the work it carries, whatever version it runs now.
458 - if (row.value.fenced !== 1) {
459 - return yield* new PeerLinkError({
460 - reason: "incompatible",
461 - message: `The link to ${link.label} was made by an older T3 Code. Link it again with a new pairing code from ${link.label}.`,
462 - });
463 - }
538 const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage));
539 if (Option.isNone(stored)) {
540 return yield* new PeerLinkError({
@@ -516,7 +590,15 @@ const make = Effect.gen(function* () {
590 Effect.ignoreCause({ log: true }),
591 );
592
519 - return PeerLinks.of({ link, list, get, unlink, resolve, recordOutcome });
593 + return PeerLinks.of({
594 + link,
595 + describe: describeUrl,
596 + list,
597 + get,
598 + unlink,
599 + resolve,
600 + recordOutcome,
601 + });
602 });
603
604 export const layer = Layer.effect(PeerLinks, make);
apps/server/src/peer/RemoteDelegation.test.ts
+4
@@ -62,6 +62,7 @@ import * as PeerForwarding from "./PeerForwarding.ts";
62 import * as PeerLinks from "./PeerLinks.ts";
63 import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";
64 import * as RemoteDelegation from "./RemoteDelegation.ts";
65 +import * as PeerLinkRequests from "./PeerLinkRequests.ts";
66
67 // The laptop's agent delegates a task to the box through a link. The box is
68 // its real /mcp behind real OAuth, with one thread the test finishes; the
@@ -468,6 +469,8 @@ const boxToolkitLayer = (thread: BoxThread) => {
469 Layer.provide(layerBoxLaunches),
470 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
471 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
472 + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
473 + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
474 Layer.provide(
475 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/p" }),
476 ),
@@ -584,6 +587,7 @@ const makeLaptop = (
587 ),
588 ),
589 Layer.provide(Layer.succeedContext(linking)),
590 + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
591 Layer.provide(NodeCrypto.layer),
592 Layer.provideMerge(layerThreads),
593 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
apps/server/src/persistence/Migrations.ts
+2
@@ -74,6 +74,7 @@ import Migration0068 from "./Migrations/068_ShellStopRequestIndex.ts";
74 import Migration0069 from "./Migrations/069_ThreadMessageSearch.ts";
75 import Migration0070 from "./Migrations/070_PeerLinks.ts";
76 import Migration0071 from "./Migrations/071_PeerLinkFence.ts";
77 +import Migration0072 from "./Migrations/072_WaitingLinkRequestIndex.ts";
78
79 const migrationEntries = [
80 [1, "OrchestrationEvents", Migration0001],
@@ -148,6 +149,7 @@ const migrationEntries = [
149 [69, "ThreadMessageSearch", Migration0069],
150 [70, "PeerLinks", Migration0070],
151 [71, "PeerLinkFence", Migration0071],
152 + [72, "WaitingLinkRequestIndex", Migration0072],
153 ] as const;
154
155 export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/072_WaitingLinkRequestIndex.ts new
+13
@@ -0,0 +1,13 @@
1 +import * as Effect from "effect/Effect";
2 +import * as SqlClient from "effect/sql/SqlClient";
3 +
4 +export default Effect.gen(function* () {
5 + const sql = yield* SqlClient.SqlClient;
6 +
7 + // Keep this predicate aligned with ProjectionStore's waiting link card query.
8 + yield* sql`
9 + CREATE INDEX orchestration_v2_projection_turn_items_waiting_link_idx
10 + ON orchestration_v2_projection_turn_items(thread_id, updated_at DESC, turn_item_id DESC)
11 + WHERE type = 'link_request' AND status = 'waiting'
12 + `;
13 +});
apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+2
@@ -51,6 +51,7 @@ describe("V2 preview upgrade", () => {
51 [69, "ThreadMessageSearch"],
52 [70, "PeerLinks"],
53 [71, "PeerLinkFence"],
54 + [72, "WaitingLinkRequestIndex"],
55 ]);
56 assert.deepStrictEqual(yield* runMigrations(), []);
57 assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -145,6 +146,7 @@ describe("V2 preview upgrade", () => {
146 [69, "ThreadMessageSearch"],
147 [70, "PeerLinks"],
148 [71, "PeerLinkFence"],
149 + [72, "WaitingLinkRequestIndex"],
150 ]);
151 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
152 );
apps/server/src/provider/AgentContextBudget.test.ts
+4
@@ -23,6 +23,8 @@ import { ThreadLaunchService } from "../orchestration-v2/ThreadLaunchService.ts"
23 import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
24 import { ThreadSearch } from "../orchestration-v2/ThreadSearch.ts";
25 import { PeerForwarding } from "../peer/PeerForwarding.ts";
26 +import { PeerLinkRequests } from "../peer/PeerLinkRequests.ts";
27 +import { PeerLinks } from "../peer/PeerLinks.ts";
28 import { RemoteDelegation } from "../peer/RemoteDelegation.ts";
29 import { PreviewManager } from "../preview/Manager.ts";
30 import { PreviewBrowser } from "../preview/PreviewBrowser.ts";
@@ -51,6 +53,8 @@ const toolHandlerServices = Layer.mergeAll(
53 Layer.mock(McpProviderSessions)({}),
54 Layer.mock(OrchestratorV2)({}),
55 Layer.mock(PeerForwarding)({}),
56 + Layer.mock(PeerLinkRequests)({}),
57 + Layer.mock(PeerLinks)({}),
58 Layer.mock(PreviewAutomationBroker)({}),
59 Layer.mock(PreviewBrowser)({}),
60 Layer.mock(PreviewManager)({}),
apps/server/src/provider/agentContextBudget.json
+3 -3
@@ -1,5 +1,5 @@
1 {
2 - "claudeSystemAppendBytes": 5086,
3 - "codexAdditionalContextBytes": 5638,
4 - "mcpToolListJsonBytes": 44745
2 + "claudeSystemAppendBytes": 5258,
3 + "codexAdditionalContextBytes": 5810,
4 + "mcpToolListJsonBytes": 45861
5 }
apps/server/src/server.ts
+3
@@ -69,6 +69,7 @@ import * as TerminalManager from "./terminal/Manager.ts";
69 import * as McpHttpServer from "./mcp/McpHttpServer.ts";
70 import * as PeerForwarding from "./peer/PeerForwarding.ts";
71 import * as RemoteDelegation from "./peer/RemoteDelegation.ts";
72 +import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
73 import * as PeerLinks from "./peer/PeerLinks.ts";
74 import * as PeerMcpClient from "./peer/PeerMcpClient.ts";
75 import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
@@ -741,6 +742,8 @@ const layerMakeRoutes = Layer.mergeAll(
742 ),
743 // delegate_task to a linked environment, from /mcp and the follower above.
744 Layer.provide(RemoteDelegation.layer.pipe(Layer.provide(ProjectionStoreV2.layer))),
745 + // Links agents ask for: shown in a thread from /mcp, answered over WebSocket.
746 + Layer.provide(PeerLinkRequests.layer),
747 // Share the service so HTTP/WS clients single-flight reads and invalidate each other's cached patches.
748 Layer.provide(layerPullRequestService),
749 // The same activity instance RunExecutionService reports to, by layer memoization.
apps/server/src/ws.test.ts
+2
@@ -54,6 +54,7 @@ import * as ModelManifest from "./provider/ModelManifest.ts";
54 import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
55 import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts";
56 import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
57 +import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
58 import * as PeerLinks from "./peer/PeerLinks.ts";
59 import * as PortScanner from "./preview/PortScanner.ts";
60 import * as PreviewManager from "./preview/Manager.ts";
@@ -421,6 +422,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
422 Layer.mock(OtlpEndpointCheck.OtlpEndpointCheck)({}),
423 Layer.mock(PairingGrantStore.PairingGrantStore)({}),
424 Layer.mock(PeerLinks.PeerLinks)({}),
425 + Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
426 Layer.mock(PortScanner.PortDiscovery)({}),
427 Layer.mock(PreviewManager.PreviewManager)({}),
428 Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({}),
apps/server/src/ws.ts
+8
@@ -2,6 +2,7 @@ import { OrchestrationDispatchCommandError } from "@t3tools/contracts";
2 import * as Context from "effect/Context";
3 import * as Crypto from "effect/Crypto";
4 import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
5 +import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
6 import * as PeerLinks from "./peer/PeerLinks.ts";
7
8 import * as DateTime from "effect/DateTime";
@@ -1345,6 +1346,7 @@ export const layerWsRpc = (
1346 const databaseStorage = yield* DatabaseStorage.DatabaseStorage;
1347 const serverSettings = yield* ServerSettings.ServerSettingsService;
1348 const peerLinks = yield* PeerLinks.PeerLinks;
1349 + const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests;
1350 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
1351 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
1352 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -2542,6 +2544,10 @@ export const layerWsRpc = (
2544 [WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input),
2545 [WS_METHODS.peerLinksUnlink]: ({ environmentId }) =>
2546 peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))),
2547 + [WS_METHODS.peerLinksAnswerRequest]: (input) =>
2548 + Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(
2549 + Effect.andThen(peerLinkRequests.answer(input)),
2550 + ),
2551 [WS_METHODS.serverGetSettings]: (_input) =>
2552 serverSettings.getSettings.pipe(Effect.map(ServerSettings.redactServerSettingsForClient)),
2553 [WS_METHODS.serverUpdateSettings]:
@@ -3313,6 +3319,7 @@ export const layer = Layer.unwrap(
3319 const pullRequests = yield* PullRequestService.PullRequestService;
3320 const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
3321 const peerLinks = yield* PeerLinks.PeerLinks;
3322 + const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests;
3323 const sql = yield* SqlClient.SqlClient;
3324 return HttpRouter.add(
3325 "GET",
@@ -3401,6 +3408,7 @@ export const layer = Layer.unwrap(
3408 ),
3409 ),
3410 Layer.provide(Layer.succeed(PeerLinks.PeerLinks, peerLinks)),
3411 + Layer.provide(Layer.succeed(PeerLinkRequests.PeerLinkRequests, peerLinkRequests)),
3412 Layer.provide(
3413 SourceControlDiscovery.layer.pipe(
3414 Layer.provide(
apps/web/src/components/auth/ConnectAgentSurface.tsx
+1 -1
@@ -279,7 +279,7 @@ function ConnectAgentHeading({
279 );
280 }
281
282 -export function AccessOption({
282 +function AccessOption({
283 access,
284 selected,
285 }: {
apps/web/src/components/chat/LinkRequestCard.tsx new
+510
@@ -0,0 +1,510 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import {
3 + type LinkableMachine,
4 + linkRequestAnswerInput,
5 + linkRequestDefaultAccess,
6 + linkRequestDisplay,
7 + linkRequestFailureMessage,
8 + linkRequestInitialMachine,
9 + type LinkRequestItem,
10 + linkRequestTargetName,
11 + rankMachinesByHint,
12 +} from "@t3tools/client-runtime/link-request";
13 +import {
14 + isAtomCommandInterrupted,
15 + squashAtomCommandFailure,
16 +} from "@t3tools/client-runtime/state/runtime";
17 +import {
18 + AuthAccessWriteScope,
19 + type AuthMcpClientAccess,
20 + type EnvironmentId,
21 + type OrchestrationV2ProjectedTurnItem,
22 +} from "@t3tools/contracts";
23 +import * as Option from "effect/Option";
24 +import * as Result from "effect/Result";
25 +import { CheckIcon, LinkIcon, MinusIcon, XIcon } from "lucide-react";
26 +import { useId, useRef, useState } from "react";
27 +
28 +import { useEnvironmentScope, usePreparedConnection } from "../../state/session";
29 +import { mintPairingCodeOn } from "../../state/peerPairingCode";
30 +import { useLinkableMachines } from "../../state/peerLinks";
31 +import { serverEnvironment } from "../../state/server";
32 +import { useAtomCommand } from "../../state/use-atom-command";
33 +import { accessConfig } from "../auth/ConnectAgentSurface";
34 +import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
35 +import { LinkAccessPicker } from "../settings/LinkAccessPicker";
36 +import { ANOTHER_ADDRESS, LinkMachineBadge } from "../settings/LinkMachineSelect";
37 +import { Button } from "../ui/button";
38 +import { Dialog } from "../ui/dialog";
39 +import { Input } from "../ui/input";
40 +import { Radio, RadioGroup } from "../ui/radio-group";
41 +import { WizardFooter, WizardHeader, WizardPanel, WizardPopup, WizardSteps } from "../ui/wizard";
42 +import { WorkLogRow } from "./WorkLog";
43 +
44 +const accessLabel = (access: AuthMcpClientAccess) => accessConfig[access].label;
45 +
46 +/** Whether the agent left the machine for the user to pick. */
47 +const picksMachine = (item: LinkRequestItem) =>
48 + item.environmentId === undefined && item.url === undefined;
49 +
50 +/**
51 + * Inline card for a link an agent asked the user to make. The user picks the
52 + * access in a dialog; the pairing code lives only in that dialog's state and
53 + * the RPC payload, and is never logged, toasted, or persisted.
54 + */
55 +export function LinkRequestCard(props: {
56 + readonly environmentId: EnvironmentId;
57 + readonly item: LinkRequestItem;
58 + readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
59 +}) {
60 + const { item } = props;
61 + const display = linkRequestDisplay(item, props.visibility, accessLabel);
62 + if (display.kind === "answered" || display.kind === "pending-elsewhere") {
63 + const Icon =
64 + display.kind === "pending-elsewhere"
65 + ? LinkIcon
66 + : display.outcome === "linked"
67 + ? CheckIcon
68 + : display.outcome === "failed"
69 + ? XIcon
70 + : MinusIcon;
71 + return (
72 + <WorkLogRow
73 + data-v2-item-type={item.type}
74 + icon={<Icon className="size-3.5 text-icon-muted" aria-hidden />}
75 + label={display.label}
76 + />
77 + );
78 + }
79 + return <PendingLinkRequest environmentId={props.environmentId} item={item} />;
80 +}
81 +
82 +function PendingLinkRequest(props: {
83 + readonly environmentId: EnvironmentId;
84 + readonly item: LinkRequestItem;
85 +}) {
86 + const { item } = props;
87 + const [open, setOpen] = useState(false);
88 + const [declining, setDeclining] = useState(false);
89 + const [error, setError] = useState<string | null>(null);
90 + const answer = useAtomCommand(serverEnvironment.answerLinkRequest, {
91 + label: "decline link request",
92 + reportFailure: false,
93 + reportDefect: false,
94 + });
95 + const canAnswer = useAtomValue(
96 + serverEnvironment.answerLinkRequest.permissionAtom(props.environmentId),
97 + );
98 + const target = linkRequestTargetName(item);
99 +
100 + const decline = async () => {
101 + const input = linkRequestAnswerInput(item, { type: "decline" });
102 + if (input === null) return;
103 + setDeclining(true);
104 + setError(null);
105 + const result = await answer({ environmentId: props.environmentId, input }).finally(() =>
106 + setDeclining(false),
107 + );
108 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
109 + setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
110 + }
111 + };
112 +
113 + return (
114 + <div
115 + data-v2-item-type={item.type}
116 + className="flex min-w-0 flex-col gap-3 rounded-xl border border-border/60 bg-card p-4"
117 + >
118 + <div className="flex min-w-0 flex-col gap-1">
119 + <p className="text-sm font-medium text-foreground">
120 + {picksMachine(item)
121 + ? "Link a machine to this environment"
122 + : `Link ${target} to this environment`}
123 + </p>
124 + {item.reason.trim() ? <p className="text-sm text-muted-foreground">{item.reason}</p> : null}
125 + {item.label !== undefined && item.url !== undefined ? (
126 + <p className="truncate text-xs text-muted-foreground/80">{item.url}</p>
127 + ) : null}
128 + </div>
129 + {error !== null ? (
130 + <p role="alert" className="text-xs text-destructive">
131 + {error}
132 + </p>
133 + ) : null}
134 + {canAnswer ? (
135 + <div className="flex min-w-0 items-center justify-end gap-2">
136 + <Button
137 + type="button"
138 + size="xs"
139 + variant="ghost-muted"
140 + disabled={declining}
141 + onClick={() => void decline()}
142 + >
143 + Decline
144 + </Button>
145 + <Button type="button" size="xs" disabled={declining} onClick={() => setOpen(true)}>
146 + {picksMachine(item) ? "Choose machine…" : "Review link…"}
147 + </Button>
148 + </div>
149 + ) : (
150 + <p className="text-xs text-muted-foreground">
151 + Only a session that manages access here can answer this.
152 + </p>
153 + )}
154 + <LinkRequestDialog
155 + environmentId={props.environmentId}
156 + item={item}
157 + open={open}
158 + onOpenChange={setOpen}
159 + />
160 + </div>
161 + );
162 +}
163 +
164 +/**
165 + * What the dialog links: a machine from the client's catalog, or an address.
166 + * `urls` is empty when the client knows no direct address for the machine,
167 + * so the user types one.
168 + */
169 +type DialogTarget =
170 + | { readonly kind: "none" }
171 + | {
172 + readonly kind: "machine";
173 + readonly environmentId: EnvironmentId;
174 + readonly label: string;
175 + readonly urls: ReadonlyArray<string>;
176 + readonly linked: boolean;
177 + }
178 + | { readonly kind: "address" };
179 +
180 +function resolveTarget(
181 + item: LinkRequestItem,
182 + machines: ReadonlyArray<LinkableMachine>,
183 + choice: string | null,
184 +): DialogTarget {
185 + if (item.environmentId === undefined && item.url !== undefined) return { kind: "address" };
186 + const chosen = item.environmentId ?? choice;
187 + if (chosen === null) return { kind: "none" };
188 + if (chosen === ANOTHER_ADDRESS) return { kind: "address" };
189 + const machine = machines.find((candidate) => candidate.environmentId === chosen);
190 + return {
191 + kind: "machine",
192 + environmentId: machine?.environmentId ?? (chosen as EnvironmentId),
193 + label: machine?.label ?? linkRequestTargetName(item),
194 + urls: [...new Set([...(machine?.urls ?? []), ...(item.url === undefined ? [] : [item.url])])],
195 + linked: machine?.linked ?? false,
196 + };
197 +}
198 +
199 +/** The dialog's steps: where to link, then what agents may do there. */
200 +type LinkStep = "machine" | "access";
201 +
202 +function LinkRequestDialog(props: {
203 + readonly environmentId: EnvironmentId;
204 + readonly item: LinkRequestItem;
205 + readonly open: boolean;
206 + readonly onOpenChange: (open: boolean) => void;
207 +}) {
208 + const { item } = props;
209 + const formId = useId();
210 + const pickMachine = picksMachine(item);
211 + const listed = useLinkableMachines(props.environmentId, props.open);
212 + const machines = rankMachinesByHint(listed, item.hint);
213 + // Null until the user picks; until then the hint's best match is picked.
214 + const [choice, setChoice] = useState<string | null>(null);
215 + const [address, setAddress] = useState(item.url ?? "");
216 + const [access, setAccess] = useState<AuthMcpClientAccess>(() => linkRequestDefaultAccess(item));
217 + const [pairingCode, setPairingCode] = useState("");
218 + const [step, setStep] = useState<LinkStep>("machine");
219 + const [busy, setBusy] = useState(false);
220 + const [error, setError] = useState<string | null>(null);
221 + // Machines whose minting already failed, so the dialog asks for a code instead.
222 + const [mintFailed, setMintFailed] = useState<ReadonlySet<EnvironmentId>>(new Set());
223 + // Enter then a click can both run before a re-render; this guard is synchronous.
224 + const inFlight = useRef(false);
225 + const answer = useAtomCommand(serverEnvironment.answerLinkRequest, {
226 + label: "answer link request",
227 + // The failure cause holds the request, and with it the code; keep it out of the console.
228 + reportFailure: false,
229 + reportDefect: false,
230 + });
231 + const selected = choice ?? linkRequestInitialMachine(item, machines);
232 + const target = resolveTarget(item, machines, selected);
233 + const targetName = target.kind === "machine" ? target.label : linkRequestTargetName(item);
234 + // This client can mint a code there when it is connected to that
235 + // environment with a session that may create pairing links.
236 + const targetId = target.kind === "machine" ? target.environmentId : null;
237 + const connected = usePreparedConnection(targetId);
238 + const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
239 + const canMint =
240 + targetId !== null && Option.isSome(connected) && mayMint && !mintFailed.has(targetId);
241 + const needsAddress =
242 + target.kind === "address" || (target.kind === "machine" && target.urls.length === 0);
243 + // An address the agent gave is already filled in; only one the user must type is asked for.
244 + const asksAddress = needsAddress && !(item.url !== undefined && item.environmentId === undefined);
245 + const useExisting = target.kind === "machine" && target.linked;
246 + // A named machine with an address it answers at has nothing to choose before access.
247 + const steps: ReadonlyArray<LinkStep> =
248 + pickMachine || asksAddress ? ["machine", "access"] : ["access"];
249 + const current: LinkStep = steps.includes(step) ? step : "access";
250 + const machineReady =
251 + target.kind !== "none" && (useExisting || !needsAddress || address.trim().length > 0);
252 + const ready = machineReady && (useExisting || canMint || pairingCode.trim().length > 0);
253 +
254 + const reset = () => {
255 + setChoice(null);
256 + setAddress(item.url ?? "");
257 + setAccess(linkRequestDefaultAccess(item));
258 + setPairingCode("");
259 + setStep("machine");
260 + setError(null);
261 + };
262 +
263 + // Every close resets, so a reopened dialog never shows the last answer or its pairing code.
264 + const close = () => {
265 + props.onOpenChange(false);
266 + reset();
267 + };
268 +
269 + // Settles to the answer to send, an error to show, or nothing to do.
270 + const prepareAnswer = async () => {
271 + if (target.kind === "none") return null;
272 + if (target.kind === "machine" && target.linked) {
273 + return linkRequestAnswerInput(item, {
274 + type: "use-existing",
275 + environmentId: target.environmentId,
276 + });
277 + }
278 + let code = pairingCode;
279 + if (canMint && targetId !== null) {
280 + const minted = await mintPairingCodeOn(targetId, access);
281 + if (Result.isFailure(minted)) {
282 + setMintFailed((failed) => new Set(failed).add(targetId));
283 + setError(linkRequestFailureMessage(minted.failure));
284 + return null;
285 + }
286 + code = minted.success;
287 + }
288 + return linkRequestAnswerInput(item, {
289 + type: "link",
290 + target:
291 + target.kind === "address"
292 + ? { url: address }
293 + : { ...target, urls: needsAddress ? [address.trim()] : target.urls },
294 + access,
295 + pairingCode: code,
296 + });
297 + };
298 +
299 + const submit = async () => {
300 + if (inFlight.current || target.kind === "none") return;
301 + inFlight.current = true;
302 + setBusy(true);
303 + setError(null);
304 + const input = await prepareAnswer();
305 + const result =
306 + input === null ? null : await answer({ environmentId: props.environmentId, input });
307 + inFlight.current = false;
308 + setBusy(false);
309 + if (result === null) return;
310 + if (result._tag === "Success") {
311 + // The card switches to its answered row once the item updates.
312 + close();
313 + } else if (!isAtomCommandInterrupted(result)) {
314 + setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
315 + }
316 + };
317 +
318 + // The machine step ends the dialog when the machine is linked here already.
319 + const finishesHere = current === "access" || useExisting;
320 +
321 + return (
322 + <Dialog
323 + open={props.open}
324 + onOpenChange={(next) => {
325 + // An answer that lands after a close would still link, and would close a reopened dialog.
326 + if (!next && busy) return;
327 + if (next) props.onOpenChange(true);
328 + else close();
329 + }}
330 + >
331 + <WizardPopup>
332 + <WizardHeader
333 + title={pickMachine ? "Link a machine" : `Link ${targetName}`}
334 + description="Agents here can then launch, message and wait on threads there. Revoke it in that machine's Connections."
335 + >
336 + {steps.length > 1 && !useExisting ? (
337 + <WizardSteps
338 + steps={["Machine", "Access"]}
339 + currentStep={steps.indexOf(current)}
340 + summaries={[target.kind === "none" ? null : targetName, null]}
341 + showSummaries
342 + isStepDisabled={(index) => busy || (index === 1 && !machineReady)}
343 + onStepChange={(index) => {
344 + const next = steps[index];
345 + if (next !== undefined) setStep(next);
346 + }}
347 + />
348 + ) : null}
349 + </WizardHeader>
350 + <WizardPanel holdHeight={busy}>
351 + <form
352 + id={formId}
353 + className="space-y-4"
354 + autoComplete="off"
355 + onSubmit={(event) => {
356 + event.preventDefault();
357 + if (finishesHere) void submit();
358 + else if (machineReady) setStep("access");
359 + }}
360 + >
361 + {current === "machine" ? (
362 + <>
363 + {pickMachine ? (
364 + <MachinePicker
365 + machines={machines}
366 + value={selected}
367 + disabled={busy}
368 + onChange={(next) => {
369 + setChoice(next);
370 + setError(null);
371 + }}
372 + />
373 + ) : null}
374 + {asksAddress ? (
375 + <label className="block space-y-1.5">
376 + <span className="block text-xs font-medium text-foreground">Address</span>
377 + <Input
378 + value={address}
379 + onChange={(event) => setAddress(event.target.value)}
380 + placeholder="https://machine.tailnet.ts.net"
381 + disabled={busy}
382 + nativeInput
383 + spellCheck={false}
384 + />
385 + {target.kind === "machine" ? (
386 + <span className="block text-xs text-muted-foreground">
387 + This app has no address for {target.label} that another machine can reach.
388 + Enter its https or Tailscale address.
389 + </span>
390 + ) : null}
391 + </label>
392 + ) : null}
393 + </>
394 + ) : (
395 + <>
396 + {item.url !== undefined && !pickMachine ? (
397 + <p className="truncate text-xs text-muted-foreground">{item.url}</p>
398 + ) : null}
399 + {useExisting ? null : (
400 + <>
401 + {canMint ? null : (
402 + <label className="block space-y-1.5">
403 + <span className="block text-xs font-medium text-foreground">
404 + Pairing code
405 + </span>
406 + <Input
407 + value={pairingCode}
408 + onChange={(event) => setPairingCode(event.target.value)}
409 + placeholder="Paste the code"
410 + disabled={busy}
411 + autoComplete="one-time-code"
412 + nativeInput
413 + spellCheck={false}
414 + />
415 + <span className="block text-xs text-muted-foreground">
416 + Create a link on {targetName}: Settings → Connections → Create link, then
417 + paste its code here.
418 + </span>
419 + </label>
420 + )}
421 + <LinkAccessPicker value={access} onChange={setAccess} disabled={busy} />
422 + </>
423 + )}
424 + </>
425 + )}
426 + {useExisting ? (
427 + <p className="text-xs text-muted-foreground">
428 + This environment is already linked to {targetName}. The agent can use that link as
429 + it is; change its access in Settings → Connections.
430 + </p>
431 + ) : null}
432 + {error !== null ? (
433 + <p role="alert" className="text-xs text-destructive">
434 + {error}
435 + </p>
436 + ) : null}
437 + </form>
438 + </WizardPanel>
439 + <WizardFooter>
440 + {current === "access" && steps.length > 1 ? (
441 + <Button
442 + variant="outline"
443 + type="button"
444 + disabled={busy}
445 + onClick={() => {
446 + setStep("machine");
447 + setError(null);
448 + }}
449 + >
450 + Back
451 + </Button>
452 + ) : (
453 + <Button variant="outline" type="button" disabled={busy} onClick={close}>
454 + Cancel
455 + </Button>
456 + )}
457 + <Button
458 + form={formId}
459 + type="submit"
460 + disabled={busy || (finishesHere ? !ready : !machineReady)}
461 + >
462 + {busy ? "Linking…" : useExisting ? "Use this link" : finishesHere ? "Link" : "Continue"}
463 + </Button>
464 + </WizardFooter>
465 + </WizardPopup>
466 + </Dialog>
467 + );
468 +}
469 +
470 +/** The user's other machines, best match for the agent's hint first, then an address. */
471 +function MachinePicker(props: {
472 + readonly machines: ReadonlyArray<LinkableMachine>;
473 + readonly value: string | null;
474 + readonly disabled: boolean;
475 + readonly onChange: (value: string) => void;
476 +}) {
477 + const labelId = useId();
478 + return (
479 + <div className="space-y-2">
480 + <span id={labelId} className="block text-xs font-medium">
481 + Machine
482 + </span>
483 + <RadioGroup
484 + aria-labelledby={labelId}
485 + value={props.value}
486 + disabled={props.disabled}
487 + onValueChange={(next) => props.onChange(next as string)}
488 + >
489 + {props.machines.map((machine) => (
490 + <label
491 + key={machine.environmentId}
492 + className="flex cursor-pointer items-center gap-2.5 rounded-lg border px-3 py-2 text-sm"
493 + >
494 + <Radio value={machine.environmentId} />
495 + <EnvironmentMachineIcon
496 + kind={machine.machine}
497 + className="size-4 shrink-0 text-muted-foreground"
498 + />
499 + <span className="min-w-0 flex-1 truncate font-medium">{machine.label}</span>
500 + <LinkMachineBadge machine={machine} />
501 + </label>
502 + ))}
503 + <label className="flex cursor-pointer items-center gap-2.5 rounded-lg border px-3 py-2 text-sm">
504 + <Radio value={ANOTHER_ADDRESS} />
505 + <span className="min-w-0 flex-1 font-medium">Another address…</span>
506 + </label>
507 + </RadioGroup>
508 + </div>
509 + );
510 +}
apps/web/src/components/chat/TimelineV2EventRow.tsx
+10
@@ -18,6 +18,7 @@ import {
18 SubagentElapsed,
19 V2LifecycleRow,
20 } from "./V2LifecycleRow";
21 +import { LinkRequestCard } from "./LinkRequestCard";
22 import { SecretRequestCard } from "./SecretRequestCard";
23 import { TimelineRowCtx, type TimelineRow } from "./timelineRowContext";
24 import { v2EventPresentation, subagentGroupTiming } from "./TimelineV2EventRow.logic";
@@ -37,6 +38,15 @@ export function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind:
38 />
39 );
40 }
41 + if (item.type === "link_request") {
42 + return (
43 + <LinkRequestCard
44 + environmentId={ctx.activeThreadEnvironmentId}
45 + item={item}
46 + visibility={visibility}
47 + />
48 + );
49 + }
50 if (isV2LifecycleItem(item)) {
51 return (
52 <V2LifecycleRow
apps/web/src/components/settings/LinkAccessPicker.tsx new
+63
@@ -0,0 +1,63 @@
1 +import { AuthMcpClientAccess } from "@t3tools/contracts";
2 +import { useId } from "react";
3 +
4 +import { accessConfig } from "../auth/ConnectAgentSurface";
5 +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
6 +
7 +/** What agents here may do in an environment being linked, with what that does not allow. */
8 +export function LinkAccessPicker({
9 + value,
10 + onChange,
11 + disabled = false,
12 +}: {
13 + readonly value: AuthMcpClientAccess;
14 + readonly onChange: (access: AuthMcpClientAccess) => void;
15 + readonly disabled?: boolean;
16 +}) {
17 + const labelId = useId();
18 + const selected = accessConfig[value];
19 + return (
20 + <div className="space-y-1.5">
21 + <span id={labelId} className="block text-xs font-medium">
22 + What agents here may do there
23 + </span>
24 + <Select
25 + value={value}
26 + disabled={disabled}
27 + onValueChange={(next) => {
28 + if (next !== null) onChange(next as AuthMcpClientAccess);
29 + }}
30 + >
31 + <SelectTrigger aria-labelledby={labelId}>
32 + <SelectValue>
33 + <span className="flex items-center gap-2">
34 + <selected.icon aria-hidden className="size-4" />
35 + {selected.label}
36 + </span>
37 + </SelectValue>
38 + </SelectTrigger>
39 + <SelectPopup alignItemWithTrigger={false}>
40 + {AuthMcpClientAccess.literals.map((option) => {
41 + const { label, description, icon: Icon } = accessConfig[option];
42 + return (
43 + <SelectItem key={option} value={option} hideIndicator>
44 + <span className="grid min-w-0 gap-0.5 py-0.5">
45 + <span className="inline-flex items-center gap-1.5 font-medium text-foreground">
46 + <Icon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
47 + {label}
48 + </span>
49 + <span className="text-xs leading-4 text-muted-foreground">{description}</span>
50 + </span>
51 + </SelectItem>
52 + );
53 + })}
54 + </SelectPopup>
55 + </Select>
56 + <p className="text-xs text-muted-foreground">
57 + {selected.description} An agent never gets more access there than its own mode here. Below
58 + full access, it can change only threads this link started, not that machine's own threads,
59 + projects or settings.
60 + </p>
61 + </div>
62 + );
63 +}
apps/web/src/components/settings/LinkMachineSelect.tsx new
+87
@@ -0,0 +1,87 @@
1 +import type { LinkableMachine } from "@t3tools/client-runtime/link-request";
2 +import { useId } from "react";
3 +
4 +import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
5 +import { Badge } from "../ui/badge";
6 +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
7 +
8 +/** The machine choice for linking by an address typed in. */
9 +export const ANOTHER_ADDRESS = "another-address";
10 +
11 +/** Whether a machine is linked already, or how this app knows it when not connected to it. */
12 +export function LinkMachineBadge({ machine }: { readonly machine: LinkableMachine }) {
13 + if (machine.linked) {
14 + return (
15 + <Badge variant="success" size="sm">
16 + Linked
17 + </Badge>
18 + );
19 + }
20 + if (machine.connected) return null;
21 + return (
22 + <Badge variant="outline" size="sm">
23 + {machine.connectOnly ? "T3 Connect" : "Not connected"}
24 + </Badge>
25 + );
26 +}
27 +
28 +function MachineName({ machine }: { readonly machine: LinkableMachine }) {
29 + return (
30 + <span className="flex min-w-0 items-center gap-2">
31 + <EnvironmentMachineIcon kind={machine.machine} className="size-4 shrink-0 opacity-80" />
32 + <span className="min-w-0 truncate">{machine.label}</span>
33 + </span>
34 + );
35 +}
36 +
37 +/** The user's other machines, including those on their T3 Connect account, then an address. */
38 +export function LinkMachineSelect({
39 + machines,
40 + value,
41 + onChange,
42 + disabled,
43 +}: {
44 + readonly machines: ReadonlyArray<LinkableMachine>;
45 + readonly value: string | null;
46 + readonly onChange: (value: string) => void;
47 + readonly disabled: boolean;
48 +}) {
49 + const labelId = useId();
50 + return (
51 + <div className="space-y-1.5">
52 + <span id={labelId} className="block text-xs font-medium text-foreground">
53 + Machine
54 + </span>
55 + <Select
56 + value={value}
57 + disabled={disabled}
58 + onValueChange={(next) => {
59 + if (next !== null) onChange(next as string);
60 + }}
61 + >
62 + <SelectTrigger aria-labelledby={labelId}>
63 + <SelectValue>
64 + {(selected: string | null) => {
65 + if (selected === ANOTHER_ADDRESS) return "Another address…";
66 + const machine = machines.find((candidate) => candidate.environmentId === selected);
67 + return machine === undefined ? "Choose a machine" : <MachineName machine={machine} />;
68 + }}
69 + </SelectValue>
70 + </SelectTrigger>
71 + <SelectPopup alignItemWithTrigger={false}>
72 + {machines.map((machine) => (
73 + <SelectItem key={machine.environmentId} value={machine.environmentId} hideIndicator>
74 + <span className="flex min-w-0 items-center justify-between gap-3">
75 + <MachineName machine={machine} />
76 + <LinkMachineBadge machine={machine} />
77 + </span>
78 + </SelectItem>
79 + ))}
80 + <SelectItem value={ANOTHER_ADDRESS} hideIndicator>
81 + Another address…
82 + </SelectItem>
83 + </SelectPopup>
84 + </Select>
85 + </div>
86 + );
87 +}
apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
+132 -57
@@ -1,19 +1,29 @@
1 import { useAtomValue } from "@effect/atom-react";
2 -import { AuthMcpClientAccess, type EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts";
2 +import { linkRequestFailureMessage } from "@t3tools/client-runtime/link-request";
3 +import {
4 + AuthAccessWriteScope,
5 + type AuthMcpClientAccess,
6 + type EnvironmentId,
7 + type PeerLinkSummary,
8 +} from "@t3tools/contracts";
9 import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12 } from "@t3tools/client-runtime/state/runtime";
13 import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";
14 import * as DateTime from "effect/DateTime";
15 +import * as Option from "effect/Option";
16 +import * as Result from "effect/Result";
17 import { PlusIcon } from "lucide-react";
10 -import { useId, useState } from "react";
18 +import { useId, useRef, useState } from "react";
19
20 import { requestConfirmDialog } from "~/confirmDialog";
13 -import { peerLinkEnvironment } from "~/state/peerLinks";
21 +import { mintPairingCodeOn } from "~/state/peerPairingCode";
22 +import { peerLinkEnvironment, useLinkableMachines } from "~/state/peerLinks";
23 import { useEnvironmentQuery } from "~/state/query";
24 +import { useEnvironmentScope, usePreparedConnection } from "~/state/session";
25 import { useAtomCommand } from "~/state/use-atom-command";
16 -import { AccessOption, accessConfig } from "../auth/ConnectAgentSurface";
26 +import { accessConfig } from "../auth/ConnectAgentSurface";
27 import { ConnectionStatusDot } from "../ConnectionStatusDot";
28 import { Button } from "../ui/button";
29 import {
@@ -28,9 +38,10 @@ import {
38 DialogTrigger,
39 } from "../ui/dialog";
40 import { Input } from "../ui/input";
31 -import { RadioGroup } from "../ui/radio-group";
41 import { stackedThreadToast, toastManager } from "../ui/toast";
42 import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
43 +import { LinkAccessPicker } from "./LinkAccessPicker";
44 +import { ANOTHER_ADDRESS, LinkMachineSelect } from "./LinkMachineSelect";
45 import { SettingsRow, SettingsSection } from "./settingsLayout";
46 import { useNowMinute } from "../../hooks/useNowMinute";
47 import { searchableSetting } from "./settingsSearch";
@@ -157,28 +168,77 @@ function LinkedEnvironmentRow({
168
169 function LinkEnvironmentAction({ environmentId }: { readonly environmentId: EnvironmentId }) {
170 const [open, setOpen] = useState(false);
160 - const [url, setUrl] = useState("");
171 + const machines = useLinkableMachines(environmentId, open);
172 + // Null until the user picks; with no other machines known, only an address is left.
173 + const [choice, setChoice] = useState<string | null>(null);
174 + const [address, setAddress] = useState("");
175 const [pairingCode, setPairingCode] = useState("");
176 const [access, setAccess] = useState<AuthMcpClientAccess>("approval-required");
177 const [busy, setBusy] = useState(false);
178 + // Machines whose minting already failed, so the dialog asks for a code instead.
179 + const [mintFailed, setMintFailed] = useState<ReadonlySet<EnvironmentId>>(new Set());
180 + // Enter then a click can both run before a re-render; this guard is synchronous.
181 + const inFlight = useRef(false);
182 const formId = useId();
165 - const accessLabelId = `${formId}-access`;
183 const link = useAtomCommand(peerLinkEnvironment.link, { label: "link environment" });
184 + const selected = choice ?? (machines.length === 0 ? ANOTHER_ADDRESS : null);
185 + const machine = machines.find((candidate) => candidate.environmentId === selected) ?? null;
186 + // This client can mint a code there when it is connected to that
187 + // environment with a session that may create pairing links.
188 + const targetId = machine?.environmentId ?? null;
189 + const connected = usePreparedConnection(targetId);
190 + const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
191 + const canMint =
192 + targetId !== null && Option.isSome(connected) && mayMint && !mintFailed.has(targetId);
193 + const needsAddress = selected === ANOTHER_ADDRESS || machine?.urls.length === 0;
194 + const ready =
195 + selected !== null &&
196 + (!needsAddress || address.trim().length > 0) &&
197 + (canMint || pairingCode.trim().length > 0);
198 const handleOpenChange = (next: boolean) => {
199 setOpen(next);
200 if (!next) {
170 - setUrl("");
201 + setChoice(null);
202 + setAddress("");
203 setPairingCode("");
204 setAccess("approval-required");
205 + setMintFailed(new Set());
206 }
207 };
208 + // Settles to the code to link with, or null after reporting why there is none.
209 + const resolvePairingCode = async () => {
210 + if (!canMint || targetId === null) return pairingCode.trim();
211 + const minted = await mintPairingCodeOn(targetId, access);
212 + if (Result.isSuccess(minted)) return minted.success;
213 + setMintFailed((failed) => new Set(failed).add(targetId));
214 + failureToast("Could not link the environment", linkRequestFailureMessage(minted.failure));
215 + return null;
216 + };
217 const submit = async () => {
218 + const [url, ...alternateUrls] =
219 + machine === null || needsAddress ? [address.trim()] : machine.urls;
220 + if (inFlight.current || !ready || url === undefined) return;
221 + inFlight.current = true;
222 setBusy(true);
177 - const result = await link({
178 - environmentId,
179 - input: { url: url.trim(), pairingCode: pairingCode.trim(), access },
180 - });
223 + const code = await resolvePairingCode();
224 + const result =
225 + code === null
226 + ? null
227 + : await link({
228 + environmentId,
229 + input: {
230 + url,
231 + ...(alternateUrls.length > 0 ? { alternateUrls } : {}),
232 + ...(machine === null
233 + ? {}
234 + : { expectedEnvironmentId: machine.environmentId, expectedLabel: machine.label }),
235 + pairingCode: code,
236 + access,
237 + },
238 + });
239 + inFlight.current = false;
240 setBusy(false);
241 + if (result === null) return;
242 if (result._tag === "Success") {
243 toastManager.add({ type: "success", title: `Linked ${result.value.label}` });
244 handleOpenChange(false);
@@ -214,66 +274,81 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi
274 <form
275 id={formId}
276 className="space-y-4"
277 + autoComplete="off"
278 onSubmit={(event) => {
279 event.preventDefault();
280 void submit();
281 }}
282 >
222 - <label className="block space-y-1.5">
223 - <span className="block text-xs font-medium text-foreground">Address</span>
224 - <Input
225 - value={url}
226 - onChange={(event) => setUrl(event.target.value)}
227 - placeholder="https://box.example.ts.net"
228 - disabled={busy}
229 - autoFocus
230 - nativeInput
231 - spellCheck={false}
232 - />
233 - </label>
234 - <label className="block space-y-1.5">
235 - <span className="block text-xs font-medium text-foreground">Pairing code</span>
236 - <Input
237 - value={pairingCode}
238 - onChange={(event) => setPairingCode(event.target.value)}
239 - placeholder="From that environment's Connections, or t3 pair there"
283 + {machines.length > 0 ? (
284 + <LinkMachineSelect
285 + machines={machines}
286 + value={selected}
287 disabled={busy}
241 - autoComplete="one-time-code"
242 - nativeInput
243 - spellCheck={false}
288 + onChange={setChoice}
289 />
245 - </label>
246 - <div className="space-y-2">
247 - <span id={accessLabelId} className="block text-xs font-medium">
248 - What agents here may do there
249 - </span>
250 - <RadioGroup
251 - aria-labelledby={accessLabelId}
252 - disabled={busy}
253 - value={access}
254 - onValueChange={(value) => setAccess(value as AuthMcpClientAccess)}
255 - >
256 - {AuthMcpClientAccess.literals.map((option) => (
257 - <AccessOption key={option} access={option} selected={option === access} />
258 - ))}
259 - </RadioGroup>
290 + ) : null}
291 + {machine?.linked ? (
292 <p className="text-xs text-muted-foreground">
261 - An agent never gets more access there than its own mode here. Below full access, it
262 - can change only threads this link started, not that environment's own threads,
263 - projects or settings.
293 + Already linked. Linking again renews it with the access you pick.
294 </p>
265 - </div>
295 + ) : null}
296 + {needsAddress ? (
297 + <label className="block space-y-1.5">
298 + <span className="block text-xs font-medium text-foreground">Address</span>
299 + <Input
300 + value={address}
301 + onChange={(event) => {
302 + setAddress(event.target.value);
303 + // Machines found after typing began must not hide the address being typed.
304 + if (choice === null) setChoice(ANOTHER_ADDRESS);
305 + }}
306 + placeholder="https://box.example.ts.net"
307 + disabled={busy}
308 + autoFocus={machines.length === 0}
309 + nativeInput
310 + spellCheck={false}
311 + />
312 + {machine !== null ? (
313 + <span className="block text-xs text-muted-foreground">
314 + This app has no address for {machine.label} that another machine can reach.
315 + Enter its https or Tailscale address.
316 + </span>
317 + ) : null}
318 + </label>
319 + ) : null}
320 + {selected === null || canMint ? null : (
321 + <label className="block space-y-1.5">
322 + <span className="block text-xs font-medium text-foreground">Pairing code</span>
323 + <Input
324 + value={pairingCode}
325 + onChange={(event) => setPairingCode(event.target.value)}
326 + placeholder={
327 + machine === null
328 + ? "From that environment's Connections, or t3 pair there"
329 + : "Paste the code"
330 + }
331 + disabled={busy}
332 + autoComplete="one-time-code"
333 + nativeInput
334 + spellCheck={false}
335 + />
336 + {machine !== null ? (
337 + <span className="block text-xs text-muted-foreground">
338 + Create a link on {machine.label}: Settings → Connections → Create link, then
339 + paste its code here.
340 + </span>
341 + ) : null}
342 + </label>
343 + )}
344 + <LinkAccessPicker value={access} onChange={setAccess} disabled={busy} />
345 </form>
346 </DialogPanel>
347 <DialogFooter variant="bare">
348 <DialogClose disabled={busy} render={<Button variant="outline" type="button" />}>
349 Cancel
350 </DialogClose>
272 - <Button
273 - form={formId}
274 - type="submit"
275 - disabled={busy || url.trim().length === 0 || pairingCode.trim().length === 0}
276 - >
351 + <Button form={formId} type="submit" disabled={busy || !ready}>
352 {busy ? "Linking…" : "Link"}
353 </Button>
354 </DialogFooter>
apps/web/src/session-logic.ts
+2
@@ -300,6 +300,7 @@ const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"
300 "run_interrupt_request",
301 "run_interrupt_result",
302 "secret_request",
303 + "link_request",
304 "subagent",
305 ]);
306
@@ -308,6 +309,7 @@ const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"
309 "thread_created",
310 // Still answerable after a steer supersedes the attempt that asked.
311 "secret_request",
312 + "link_request",
313 ]);
314
315 export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
apps/web/src/state/peerLinks.ts
+38 -1
@@ -1,9 +1,15 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { linkableMachines } from "@t3tools/client-runtime/link-request";
3 import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks";
2 -import { AuthAccessReadScope } from "@t3tools/contracts";
4 +import { AuthAccessReadScope, type EnvironmentId } from "@t3tools/contracts";
5 +import { useEffect, useEffectEvent } from "react";
6
7 import { connectionAtomRuntime } from "../connection/runtime";
8 import { useEnvironments } from "./environments";
9 +import { relayEnvironmentDiscovery } from "./relay";
10 +import { useEnvironmentQuery } from "./query";
11 import { useEnvironmentsWithScope } from "./session";
12 +import { useAtomCommand } from "./use-atom-command";
13
14 export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);
15
@@ -17,3 +23,34 @@ export function usePeerLinkHosts() {
23 const readable = useEnvironmentsWithScope(supported, AuthAccessReadScope);
24 return supported.filter((environment) => readable.has(environment.environmentId));
25 }
26 +
27 +/**
28 + * The user's other machines, for picking one to link `environmentId` to,
29 + * including those only on their T3 Connect account. Reads that environment's
30 + * links only while `enabled`, since listing them asks every linked machine
31 + * whether it answers.
32 + */
33 +export function useLinkableMachines(environmentId: EnvironmentId, enabled: boolean) {
34 + const { environments } = useEnvironments();
35 + const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
36 + const refreshDiscovery = useAtomCommand(relayEnvironmentDiscovery.refresh, {
37 + reportFailure: false,
38 + });
39 + // Connect hosts are listed only once something asked for them, so ask on open.
40 + const discoverIfUnasked = useEffectEvent(() => {
41 + if (discovery.environments.size === 0 && !discovery.refreshing) void refreshDiscovery();
42 + });
43 + // oxlint-disable-next-line t3code/react-effect-budget -- discovery follows the picker's visibility, which a card's mount or a dialog's open sets
44 + useEffect(() => {
45 + if (enabled) discoverIfUnasked();
46 + }, [enabled]);
47 + const links = useEnvironmentQuery(
48 + enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null,
49 + );
50 + return linkableMachines({
51 + environments,
52 + threadEnvironmentId: environmentId,
53 + links: links.data?.links ?? [],
54 + connect: discovery.environments,
55 + });
56 +}
apps/web/src/state/peerPairingCode.ts new
+24
@@ -0,0 +1,24 @@
1 +import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode";
2 +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3 +import type { AuthMcpClientAccess, EnvironmentId } from "@t3tools/contracts";
4 +import * as Result from "effect/Result";
5 +
6 +import { connectionAtomRuntime } from "../connection/runtime";
7 +import { appAtomRegistry } from "../rpc/atomRegistry";
8 +
9 +const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime);
10 +
11 +/**
12 + * A fresh pairing code minted on `environmentId` with this client's session
13 + * there, for linking with `access`. Fails with `PeerPairingCodeError` when the
14 + * session may not create one.
15 + */
16 +export async function mintPairingCodeOn(
17 + environmentId: EnvironmentId,
18 + access: AuthMcpClientAccess,
19 +): Promise<Result.Result<string, unknown>> {
20 + const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: access });
21 + return result._tag === "Success"
22 + ? Result.succeed(result.value)
23 + : Result.fail(squashAtomCommandFailure(result));
24 +}
docs/user/remote-access.md
+9 -2
@@ -253,10 +253,17 @@ Link two machines, such as your laptop and a VPS, and agents on one can work on
253 the other: launch, message, wait on and stop its threads, answer their
254 questions, and manage its queues, projects and scheduled tasks. On the machine
255 you will work from, open **Settings → Connections → Linked environments**,
256 -choose **Link**, and enter the other machine's address and a pairing code from
257 -it. From a terminal, use
256 +choose **Link**, and pick the other machine or enter its address. The list
257 +holds the machines this app knows and those on your T3 Connect account. If this
258 +app is connected to that machine with a session that manages access there, it
259 +makes the pairing code itself; otherwise paste one from that machine's
260 +**Settings → Connections**. From a terminal, use
261 `t3 environment link <address> --pairing-code <code> --access <mode>`.
262
263 +You can also ask an agent to link a machine by name, such as "delegate this to
264 +my vps". It shows a card in the thread where you pick the machine the same way
265 +and the access, then approve.
266 +
267 - The access you pick is the most agents from this machine may do there. An
268 agent also never gets more there than its own mode here.
269 - Threads a link starts are marked **From** and this machine's name there.
packages/client-runtime/package.json
+8
@@ -55,6 +55,10 @@
55 "types": "./src/secretRequest.ts",
56 "default": "./src/secretRequest.ts"
57 },
58 + "./link-request": {
59 + "types": "./src/linkRequest.ts",
60 + "default": "./src/linkRequest.ts"
61 + },
62 "./scheduled-task-webhook": {
63 "types": "./src/scheduledTaskWebhook.ts",
64 "default": "./src/scheduledTaskWebhook.ts"
@@ -211,6 +215,10 @@
215 "types": "./src/state/peerLinks.ts",
216 "default": "./src/state/peerLinks.ts"
217 },
218 + "./state/peerPairingCode": {
219 + "types": "./src/state/peerPairingCode.ts",
220 + "default": "./src/state/peerPairingCode.ts"
221 + },
222 "./state/preview": {
223 "types": "./src/state/preview.ts",
224 "default": "./src/state/preview.ts"
packages/client-runtime/src/linkRequest.test.ts new
+377
@@ -0,0 +1,377 @@
1 +import { EnvironmentId, type ServerConfig, ThreadId, TurnItemId } from "@t3tools/contracts";
2 +import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
3 +import * as Option from "effect/Option";
4 +import { describe, expect, it } from "vite-plus/test";
5 +
6 +import { BearerConnectionProfile } from "./connection/catalog.ts";
7 +import { BearerConnectionTarget, RelayConnectionTarget } from "./connection/model.ts";
8 +import type { EnvironmentPresentation } from "./connection/presentation.ts";
9 +import type { RelayDiscoveredEnvironment } from "./relay/discovery.ts";
10 +import {
11 + linkableMachines,
12 + linkRequestAnswerInput,
13 + linkRequestDisplay,
14 + linkRequestFailureMessage,
15 + linkRequestInitialMachine,
16 + rankMachinesByHint,
17 +} from "./linkRequest.ts";
18 +
19 +const item = {
20 + id: TurnItemId.make("turn-item:link-request:1"),
21 + threadId: ThreadId.make("thread-1"),
22 +};
23 +const asked = { url: "https://box.example.ts.net", label: "Box" };
24 +const accessLabel = (access: string) => `<${access}>`;
25 +
26 +describe("linkRequestDisplay", () => {
27 + it("names the environment linked and the access the user chose", () => {
28 + expect(
29 + linkRequestDisplay(
30 + { ...asked, linkStatus: "linked", linkedLabel: "Box", linkedAccess: "auto" },
31 + "local",
32 + accessLabel,
33 + ),
34 + ).toEqual({ kind: "answered", outcome: "linked", label: "Linked Box · <auto>" });
35 + });
36 +
37 + it("shows why a link failed, and never offers the actions outside the asking thread", () => {
38 + expect(
39 + linkRequestDisplay(
40 + { ...asked, linkStatus: "failed", failure: "Pairing code expired." },
41 + "local",
42 + accessLabel,
43 + ),
44 + ).toMatchObject({ outcome: "failed", label: "Could not link: Pairing code expired." });
45 + expect(
46 + linkRequestDisplay({ ...asked, linkStatus: "pending" }, "inherited", accessLabel),
47 + ).toMatchObject({ kind: "pending-elsewhere" });
48 + });
49 +});
50 +
51 +describe("linkRequestAnswerInput", () => {
52 + const vps = {
53 + environmentId: EnvironmentId.make("environment-vps"),
54 + label: "VPS",
55 + urls: ["https://vps.ts.net", "http://10.0.0.2:3773"],
56 + };
57 +
58 + it("answers with the machine picked and every address known for it", () => {
59 + expect(
60 + linkRequestAnswerInput(item, {
61 + type: "link",
62 + target: vps,
63 + access: "auto",
64 + pairingCode: " abc ",
65 + }),
66 + ).toEqual({
67 + threadId: item.threadId,
68 + turnItemId: item.id,
69 + answer: { type: "link", ...vps, access: "auto", pairingCode: "abc" },
70 + });
71 + expect(
72 + linkRequestAnswerInput(item, {
73 + type: "link",
74 + target: { url: " https://box.ts.net " },
75 + access: "auto",
76 + pairingCode: "abc",
77 + }),
78 + ).toMatchObject({ answer: { urls: ["https://box.ts.net"] } });
79 + });
80 +
81 + it("refuses a blank code, a blank address, or a machine with no address", () => {
82 + const blank = (target: Parameters<typeof linkRequestAnswerInput>[1] & { type: "link" }) =>
83 + linkRequestAnswerInput(item, target);
84 + expect(blank({ type: "link", target: vps, access: "auto", pairingCode: " " })).toBeNull();
85 + expect(
86 + blank({ type: "link", target: { url: " " }, access: "auto", pairingCode: "abc" }),
87 + ).toBeNull();
88 + expect(
89 + blank({ type: "link", target: { ...vps, urls: [] }, access: "auto", pairingCode: "abc" }),
90 + ).toBeNull();
91 + });
92 +});
93 +
94 +const presentation = (
95 + id: string,
96 + label: string,
97 + options: {
98 + readonly saved?: ReadonlyArray<string>;
99 + readonly reported?: ReadonlyArray<string>;
100 + readonly connected?: boolean;
101 + } = {},
102 +): EnvironmentPresentation & { readonly environmentId: EnvironmentId } => {
103 + const environmentId = EnvironmentId.make(id);
104 + const [first, ...rest] = (options.saved ?? []).map((httpBaseUrl, index) => {
105 + const connectionId = `${id}-${index}`;
106 + return {
107 + target: new BearerConnectionTarget({ environmentId, label, connectionId }),
108 + profile: Option.some(
109 + new BearerConnectionProfile({
110 + connectionId,
111 + environmentId,
112 + label,
113 + httpBaseUrl,
114 + wsBaseUrl: httpBaseUrl,
115 + }),
116 + ),
117 + };
118 + });
119 + return {
120 + environmentId,
121 + entry: {
122 + ...(first ?? {
123 + target: new RelayConnectionTarget({ environmentId, label }),
124 + profile: Option.none(),
125 + }),
126 + ...(rest.length === 0 ? {} : { alternateRoutes: rest }),
127 + enabled: true,
128 + },
129 + connection: {
130 + phase: options.connected === false ? "offline" : "connected",
131 + error: null,
132 + traceId: null,
133 + },
134 + serverConfig:
135 + options.reported === undefined
136 + ? null
137 + : ({
138 + environment: { platform: { machine: "laptop" } },
139 + directEndpoints: options.reported.map((httpBaseUrl) => ({
140 + kind: "tailnet",
141 + httpBaseUrl,
142 + })),
143 + } as unknown as ServerConfig),
144 + };
145 +};
146 +
147 +const discovered = (
148 + id: string,
149 + label: string,
150 + machine?: "mac-mini",
151 +): RelayDiscoveredEnvironment => ({
152 + environment: {
153 + environmentId: EnvironmentId.make(id),
154 + label,
155 + endpoint: {
156 + httpBaseUrl: `https://${id}.t3.example`,
157 + wsBaseUrl: `wss://${id}.t3.example`,
158 + providerKind: "cloudflare_tunnel",
159 + },
160 + linkedAt: "2026-10-01T00:00:00.000Z",
161 + },
162 + availability: "online",
163 + status:
164 + machine === undefined
165 + ? Option.none()
166 + : Option.some({
167 + environmentId: EnvironmentId.make(id),
168 + endpoint: {
169 + httpBaseUrl: `https://${id}.t3.example`,
170 + wsBaseUrl: `wss://${id}.t3.example`,
171 + providerKind: "cloudflare_tunnel",
172 + },
173 + status: "online",
174 + checkedAt: "2026-10-01T00:00:00.000Z",
175 + descriptor: {
176 + environmentId: EnvironmentId.make(id),
177 + label,
178 + platform: { os: "darwin", arch: "arm64", machine },
179 + serverVersion: "1.0.0",
180 + capabilities: {},
181 + },
182 + } as unknown as RelayEnvironmentStatusResponse),
183 + error: Option.none(),
184 +});
185 +
186 +describe("linkableMachines", () => {
187 + it("lists the other machines with reported addresses before saved ones, once each", () => {
188 + const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
189 + const vps = presentation("environment-vps", "VPS", {
190 + saved: ["https://vps.example.com", "https://vps.ts.net"],
191 + reported: ["https://vps.ts.net"],
192 + });
193 + const mini = presentation("environment-mini", "Mini", { connected: false });
194 + expect(
195 + linkableMachines({
196 + environments: [here, vps, mini],
197 + threadEnvironmentId: here.environmentId,
198 + links: [{ environmentId: mini.environmentId, status: "unreachable" }],
199 + connect: new Map(),
200 + }),
201 + ).toEqual([
202 + {
203 + environmentId: vps.environmentId,
204 + label: "VPS",
205 + machine: "laptop",
206 + connected: true,
207 + connectOnly: false,
208 + linked: false,
209 + urls: ["https://vps.ts.net", "https://vps.example.com"],
210 + },
211 + {
212 + environmentId: mini.environmentId,
213 + label: "Mini",
214 + machine: "server",
215 + connected: false,
216 + connectOnly: false,
217 + linked: true,
218 + urls: [],
219 + },
220 + ]);
221 + });
222 +
223 + it("reaches a machine saved only over T3 Connect at its Connect address", () => {
224 + const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
225 + const box = presentation("environment-box", "Box");
226 + const [listed] = linkableMachines({
227 + environments: [here, box],
228 + threadEnvironmentId: here.environmentId,
229 + links: [],
230 + connect: new Map([[box.environmentId, discovered(box.environmentId, "Box")]]),
231 + });
232 + expect(listed?.urls).toEqual(["https://environment-box.t3.example"]);
233 + // Until discovery has found it, there is no address to offer.
234 + expect(
235 + linkableMachines({
236 + environments: [here, box],
237 + threadEnvironmentId: here.environmentId,
238 + links: [],
239 + connect: new Map(),
240 + })[0]?.urls,
241 + ).toEqual([]);
242 + });
243 +
244 + it("also offers the Connect address of a machine saved by direct address, last", () => {
245 + const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
246 + const vps = presentation("environment-vps", "VPS", {
247 + saved: ["http://192.168.1.20:3773"],
248 + reported: ["https://vps.ts.net"],
249 + });
250 + const [listed] = linkableMachines({
251 + environments: [here, vps],
252 + threadEnvironmentId: here.environmentId,
253 + links: [],
254 + connect: new Map([[vps.environmentId, discovered(vps.environmentId, "VPS")]]),
255 + });
256 + expect(listed?.urls).toEqual([
257 + "https://vps.ts.net",
258 + "http://192.168.1.20:3773",
259 + "https://environment-vps.t3.example",
260 + ]);
261 + });
262 +
263 + it("no longer counts a machine as linked once its link expired", () => {
264 + const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
265 + const vps = presentation("environment-vps", "VPS", { saved: ["https://vps.ts.net"] });
266 + const mini = presentation("environment-mini", "Mini", { saved: ["http://mini.local:3773"] });
267 + const listed = linkableMachines({
268 + environments: [here, vps, mini],
269 + threadEnvironmentId: here.environmentId,
270 + links: [
271 + { environmentId: vps.environmentId, status: "expired" },
272 + { environmentId: mini.environmentId, status: "unreachable" },
273 + { environmentId: EnvironmentId.make("environment-old"), status: "expired" },
274 + ],
275 + connect: new Map([["environment-old", discovered("environment-old", "Old box")]]),
276 + });
277 + expect(listed.map((machine) => [machine.label, machine.linked])).toEqual([
278 + ["VPS", false],
279 + ["Mini", true],
280 + ["Old box", false],
281 + ]);
282 + });
283 +
284 + it("offers machines only on T3 Connect after the saved ones, at their Connect address", () => {
285 + const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
286 + const vps = presentation("environment-vps", "VPS", { saved: ["https://vps.ts.net"] });
287 + const listed = linkableMachines({
288 + environments: [here, vps],
289 + threadEnvironmentId: here.environmentId,
290 + links: [{ environmentId: EnvironmentId.make("environment-old"), status: "reachable" }],
291 + connect: new Map([
292 + // This environment and saved machines are listed once, as saved.
293 + [here.environmentId, discovered(here.environmentId, "Here")],
294 + [vps.environmentId, discovered(vps.environmentId, "VPS")],
295 + ["environment-mini", discovered("environment-mini", "Mac mini", "mac-mini")],
296 + ["environment-old", discovered("environment-old", "Old box")],
297 + ]),
298 + });
299 + expect(listed.map((machine) => [machine.label, machine.connectOnly])).toEqual([
300 + ["VPS", false],
301 + ["Mac mini", true],
302 + ["Old box", true],
303 + ]);
304 + expect(listed[1]).toEqual({
305 + environmentId: EnvironmentId.make("environment-mini"),
306 + label: "Mac mini",
307 + machine: "mac-mini",
308 + connected: false,
309 + connectOnly: true,
310 + linked: false,
311 + urls: ["https://environment-mini.t3.example"],
312 + });
313 + expect(listed[2]).toMatchObject({ machine: "server", linked: true });
314 + });
315 +});
316 +
317 +describe("rankMachinesByHint", () => {
318 + const machines = [
319 + { label: "Old vps box" },
320 + { label: "VPS-2" },
321 + { label: "Mac mini" },
322 + { label: "vps" },
323 + ];
324 +
325 + it("puts an exact name first, then a prefix, then a substring, keeping order within each", () => {
326 + expect(rankMachinesByHint(machines, " VPS ").map((machine) => machine.label)).toEqual([
327 + "vps",
328 + "VPS-2",
329 + "Old vps box",
330 + "Mac mini",
331 + ]);
332 + expect(rankMachinesByHint(machines, undefined)).toBe(machines);
333 + });
334 +
335 + it("preselects the card's machine, or the hint's match, and nothing for a hint that matches none", () => {
336 + const listed = [
337 + { environmentId: EnvironmentId.make("environment-mini"), label: "Mac mini" },
338 + { environmentId: EnvironmentId.make("environment-vps"), label: "Hetzner VPS" },
339 + ].map(
340 + (machine) =>
341 + ({
342 + ...machine,
343 + machine: "server",
344 + connected: true,
345 + connectOnly: false,
346 + linked: false,
347 + urls: [],
348 + }) as const,
349 + );
350 + expect(linkRequestInitialMachine({ hint: "vps" }, listed)).toBe("environment-vps");
351 + // Agents pass the user's words, which name the machine among others.
352 + expect(linkRequestInitialMachine({ hint: "my mac mini" }, listed)).toBe("environment-mini");
353 + expect(linkRequestInitialMachine({ hint: "my mac" }, listed)).toBe("environment-mini");
354 + expect(linkRequestInitialMachine({ hint: "the hetzner vps box" }, listed)).toBe(
355 + "environment-vps",
356 + );
357 + expect(linkRequestInitialMachine({ hint: "desk" }, listed)).toBeNull();
358 + expect(linkRequestInitialMachine({ hint: "minimal" }, listed)).toBeNull();
359 + expect(
360 + linkRequestInitialMachine(
361 + { environmentId: EnvironmentId.make("environment-x"), hint: "vps" },
362 + listed,
363 + ),
364 + ).toBe("environment-x");
365 + });
366 +});
367 +
368 +describe("linkRequestFailureMessage", () => {
369 + it("passes through only known user-facing errors", () => {
370 + expect(
371 + linkRequestFailureMessage({ _tag: "PeerLinkRequestError", message: "Already answered." }),
372 + ).toBe("Already answered.");
373 + expect(linkRequestFailureMessage({ _tag: "SchemaError", message: "code=abc" })).toBe(
374 + "Could not answer the request. Try again.",
375 + );
376 + });
377 +});
packages/client-runtime/src/linkRequest.ts new
+284
@@ -0,0 +1,284 @@
1 +import {
2 + type AuthMcpClientAccess,
3 + type EnvironmentId,
4 + type EnvironmentMachineKind,
5 + type OrchestrationV2TurnItem,
6 + type PeerLinkRequestAnswerInput,
7 + type PeerLinkSummary,
8 + resolveEnvironmentMachineKind,
9 +} from "@t3tools/contracts";
10 +import * as Option from "effect/Option";
11 +
12 +import type { EnvironmentPresentation } from "./connection/presentation.ts";
13 +import { connectionRoutes, routeHttpBaseUrl } from "./connection/routes.ts";
14 +import type { RelayDiscoveredEnvironment } from "./relay/discovery.ts";
15 +
16 +export type LinkRequestItem = Extract<OrchestrationV2TurnItem, { readonly type: "link_request" }>;
17 +
18 +/** The access a request opens with: the agent's suggestion, else supervised. */
19 +export const linkRequestDefaultAccess = (
20 + item: Pick<LinkRequestItem, "requestedAccess">,
21 +): AuthMcpClientAccess => item.requestedAccess ?? "approval-required";
22 +
23 +/** What the card calls the other environment: its own name, else the address asked for. */
24 +export const linkRequestTargetName = (item: Pick<LinkRequestItem, "label" | "url">): string =>
25 + item.label?.trim() || item.url || "a machine";
26 +
27 +/** A machine the user could link a thread's environment to. */
28 +export interface LinkableMachine {
29 + readonly environmentId: EnvironmentId;
30 + readonly label: string;
31 + readonly machine: EnvironmentMachineKind;
32 + readonly connected: boolean;
33 + /** Found on the user's T3 Connect account rather than saved in this client. */
34 + readonly connectOnly: boolean;
35 + /** Whether the thread's environment already has a link to it. */
36 + readonly linked: boolean;
37 + /**
38 + * Where the client knows it answers, most preferred first: the addresses it
39 + * reports, then its saved routes, then its T3 Connect address. The server
40 + * keeps only those that answer as this machine. Empty for a machine reached
41 + * only over SSH, whose forward lives in this client.
42 + */
43 + readonly urls: ReadonlyArray<string>;
44 +}
45 +
46 +/**
47 + * The catalog's machines other than the thread's own, in catalog order, then those only T3
48 + * Connect knows. `links` are the thread environment's; an expired one no longer counts as
49 + * linked. `connect` is what relay discovery found, and a server reaches a machine there as a
50 + * browser does, so its Connect address is usable.
51 + */
52 +export function linkableMachines(input: {
53 + readonly environments: ReadonlyArray<
54 + EnvironmentPresentation & { readonly environmentId: EnvironmentId }
55 + >;
56 + readonly threadEnvironmentId: EnvironmentId;
57 + readonly links: ReadonlyArray<Pick<PeerLinkSummary, "environmentId" | "status">>;
58 + readonly connect: ReadonlyMap<string, RelayDiscoveredEnvironment>;
59 +}): ReadonlyArray<LinkableMachine> {
60 + const linkedIds = new Set(
61 + input.links.flatMap((link) => (link.status === "expired" ? [] : [link.environmentId])),
62 + );
63 + const saved = input.environments
64 + .filter((environment) => environment.environmentId !== input.threadEnvironmentId)
65 + .map((environment) => {
66 + const reported = (environment.serverConfig?.directEndpoints ?? []).map(
67 + (endpoint) => endpoint.httpBaseUrl,
68 + );
69 + const routes = connectionRoutes(environment.entry).flatMap((route) => {
70 + const url = route.target._tag === "RelayConnectionTarget" ? null : routeHttpBaseUrl(route);
71 + return url === null ? [] : [url];
72 + });
73 + const connect = input.connect.get(environment.environmentId)?.environment.endpoint;
74 + return {
75 + environmentId: environment.environmentId,
76 + label: environment.entry.target.label,
77 + machine: resolveEnvironmentMachineKind(environment.serverConfig),
78 + connected: environment.connection.phase === "connected",
79 + connectOnly: false,
80 + linked: linkedIds.has(environment.environmentId),
81 + urls: [
82 + ...new Set([
83 + ...reported,
84 + ...routes,
85 + ...(connect === undefined ? [] : [connect.httpBaseUrl]),
86 + ]),
87 + ],
88 + };
89 + });
90 + const savedIds = new Set<string>(saved.map((machine) => machine.environmentId));
91 + const connectOnly = [...input.connect.values()]
92 + .filter(
93 + ({ environment }) =>
94 + environment.environmentId !== input.threadEnvironmentId &&
95 + !savedIds.has(environment.environmentId),
96 + )
97 + .map(({ environment, status }) => {
98 + const descriptor = Option.getOrUndefined(status)?.descriptor;
99 + return {
100 + environmentId: environment.environmentId,
101 + label: environment.label,
102 + machine: resolveEnvironmentMachineKind(
103 + descriptor === undefined ? null : { environment: descriptor },
104 + ),
105 + connected: false,
106 + connectOnly: true,
107 + linked: linkedIds.has(environment.environmentId),
108 + urls: [environment.endpoint.httpBaseUrl],
109 + };
110 + });
111 + return [...saved, ...connectOnly];
112 +}
113 +
114 +const words = (text: string) =>
115 + ` ${text
116 + .toLowerCase()
117 + .split(/[^\p{L}\p{N}]+/u)
118 + .join(" ")
119 + .trim()} `;
120 +const NO_MATCH = 4;
121 +
122 +/**
123 + * How well a machine's name matches the agent's hint, which is often the
124 + * user's own words ("my box"): exact, prefix, substring, then a hint that
125 + * names it among other words ("the box on hetzner").
126 + */
127 +const hintRank = (label: string, hint: string) => {
128 + const name = label.trim().toLowerCase();
129 + const wanted = hint
130 + .trim()
131 + .toLowerCase()
132 + .replace(/^(?:my|our|the)\s+/, "");
133 + if (name === wanted) return 0;
134 + if (name.startsWith(wanted)) return 1;
135 + if (name.includes(wanted)) return 2;
136 + if (words(wanted).includes(words(name))) return 3;
137 + return NO_MATCH;
138 +};
139 +
140 +/** The machines best match for the agent's hint first, each rank in catalog order. */
141 +export function rankMachinesByHint<T extends { readonly label: string }>(
142 + machines: ReadonlyArray<T>,
143 + hint: string | undefined,
144 +): ReadonlyArray<T> {
145 + if (hint === undefined || hint.trim().length === 0) return machines;
146 + return machines
147 + .map((machine, index) => ({ machine, index, rank: hintRank(machine.label, hint) }))
148 + .sort((a, b) => a.rank - b.rank || a.index - b.index)
149 + .map(({ machine }) => machine);
150 +}
151 +
152 +/** The machine a card opens on: the one it names, else the hint's best match. */
153 +export function linkRequestInitialMachine(
154 + item: Pick<LinkRequestItem, "environmentId" | "hint">,
155 + machines: ReadonlyArray<LinkableMachine>,
156 +): EnvironmentId | null {
157 + if (item.environmentId !== undefined) return item.environmentId;
158 + if (item.hint === undefined) return null;
159 + const [best] = rankMachinesByHint(machines, item.hint);
160 + return best !== undefined && hintRank(best.label, item.hint) < NO_MATCH
161 + ? best.environmentId
162 + : null;
163 +}
164 +
165 +/** What a link request card shows: the actions while pending, otherwise a one-line outcome. */
166 +export type LinkRequestDisplay =
167 + | { readonly kind: "pending" }
168 + | { readonly kind: "pending-elsewhere"; readonly label: string }
169 + | {
170 + readonly kind: "answered";
171 + readonly outcome: "linked" | "declined" | "ended" | "failed";
172 + readonly label: string;
173 + };
174 +
175 +/**
176 + * `visibility` is the projected row's: a request inherited from another
177 + * thread (a fork) can only be answered where it was asked. `accessLabel`
178 + * names an access level the way the client's access picker does.
179 + */
180 +export function linkRequestDisplay(
181 + item: Pick<
182 + LinkRequestItem,
183 + "linkStatus" | "label" | "url" | "linkedLabel" | "linkedAccess" | "failure"
184 + >,
185 + visibility: "local" | "inherited" | "synthetic",
186 + accessLabel: (access: AuthMcpClientAccess) => string,
187 +): LinkRequestDisplay {
188 + switch (item.linkStatus) {
189 + case "pending":
190 + return visibility === "local"
191 + ? { kind: "pending" }
192 + : { kind: "pending-elsewhere", label: "Waiting for an answer in the original thread" };
193 + case "linked":
194 + return {
195 + kind: "answered",
196 + outcome: "linked",
197 + label: `Linked ${item.linkedLabel ?? linkRequestTargetName(item)}${
198 + item.linkedAccess === undefined ? "" : ` · ${accessLabel(item.linkedAccess)}`
199 + }`,
200 + };
201 + case "declined":
202 + return { kind: "answered", outcome: "declined", label: "Declined" };
203 + case "failed":
204 + return {
205 + kind: "answered",
206 + outcome: "failed",
207 + label: `Could not link: ${item.failure ?? "the other environment refused"}`,
208 + };
209 + case "cancelled":
210 + return { kind: "answered", outcome: "ended", label: "Request ended" };
211 + }
212 +}
213 +
214 +/**
215 + * Builds the RPC payload for an answer. A link with a blank code returns null,
216 + * since the server rejects it; callers keep Link disabled instead.
217 + */
218 +export function linkRequestAnswerInput(
219 + item: Pick<LinkRequestItem, "id" | "threadId">,
220 + answer:
221 + | {
222 + readonly type: "link";
223 + /** The machine picked, or an address typed in its place. */
224 + readonly target:
225 + | Pick<LinkableMachine, "environmentId" | "label" | "urls">
226 + | { readonly url: string };
227 + readonly access: AuthMcpClientAccess;
228 + readonly pairingCode: string;
229 + }
230 + | { readonly type: "use-existing"; readonly environmentId: EnvironmentId }
231 + | { readonly type: "decline" },
232 +): PeerLinkRequestAnswerInput | null {
233 + const base = { threadId: item.threadId, turnItemId: item.id };
234 + if (answer.type !== "link") return { ...base, answer };
235 + const pairingCode = answer.pairingCode.trim();
236 + if (pairingCode.length === 0) return null;
237 + const { target } = answer;
238 + if ("url" in target) {
239 + const url = target.url.trim();
240 + if (url.length === 0) return null;
241 + return { ...base, answer: { type: "link", urls: [url], access: answer.access, pairingCode } };
242 + }
243 + const [first, ...rest] = target.urls;
244 + if (first === undefined) return null;
245 + return {
246 + ...base,
247 + answer: {
248 + type: "link",
249 + environmentId: target.environmentId,
250 + label: target.label,
251 + urls: [first, ...rest],
252 + access: answer.access,
253 + pairingCode,
254 + },
255 + };
256 +}
257 +
258 +/** Failures whose message is written for the user and never echoes the request payload. */
259 +const USER_FACING_FAILURE_TAGS = new Set([
260 + "PeerLinkRequestError",
261 + "EnvironmentAuthorizationError",
262 + "PeerPairingCodeError",
263 +]);
264 +
265 +/**
266 + * Inline error copy for a failed answer. Only known errors pass their message
267 + * through: anything else (transport or encoding failures) gets the generic
268 + * copy, so the pairing code can never surface in the UI.
269 + */
270 +export function linkRequestFailureMessage(failure: unknown): string {
271 + if (
272 + typeof failure === "object" &&
273 + failure !== null &&
274 + "_tag" in failure &&
275 + typeof failure._tag === "string" &&
276 + USER_FACING_FAILURE_TAGS.has(failure._tag) &&
277 + "message" in failure &&
278 + typeof failure.message === "string" &&
279 + failure.message.trim().length > 0
280 + ) {
281 + return failure.message;
282 + }
283 + return "Could not answer the request. Try again.";
284 +}
packages/client-runtime/src/state/commandPermissions.test.ts
+24
@@ -423,6 +423,30 @@ it.effect(
423 ),
424 );
425
426 +it.effect("requires access management to answer a link request", () =>
427 + Effect.scoped(
428 + Effect.gen(function* () {
429 + const registry = yield* setup;
430 + registry.set(sessions(env), AsyncResult.success(grant(true)));
431 + const answer = createCommandPermissions(runtime, WS_METHODS.peerLinksAnswerRequest);
432 + expect(registry.get(answer.permissionAtom(env))).toBe(false);
433 + expect((yield* answer.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe(
434 + AuthAccessWriteScope,
435 + );
436 + registry.set(
437 + sessions(env),
438 + AsyncResult.success({
439 + ...grant(false),
440 + scopes: [AuthAccessWriteScope],
441 + permissions: [AuthAccessWriteScope],
442 + }),
443 + );
444 + expect(registry.get(answer.permissionAtom(env))).toBe(true);
445 + yield* answer.authorize(registry, env);
446 + }),
447 + ),
448 +);
449 +
450 it.effect("honors exact empty permissions and preserves legacy parent grants", () =>
451 Effect.scoped(
452 Effect.gen(function* () {
packages/client-runtime/src/state/peerPairingCode.ts new
+95
@@ -0,0 +1,95 @@
1 +/**
2 + * A one-use pairing code for linking, minted on the environment being linked to with the
3 + * user's own session there, so a link card can be answered without fetching a code by hand.
4 + * It carries exactly what an agent sign-in with the chosen access needs.
5 + */
6 +import { type AuthMcpClientAccess, mcpClientScopes } from "@t3tools/contracts";
7 +import * as Data from "effect/Data";
8 +import * as Effect from "effect/Effect";
9 +import type * as HttpClient from "effect/http/HttpClient";
10 +import * as Option from "effect/Option";
11 +import type { Atom } from "effect/reactivity";
12 +import * as SubscriptionRef from "effect/SubscriptionRef";
13 +
14 +import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
15 +import type { PreparedConnection } from "../connection/model.ts";
16 +import type { EnvironmentRegistry } from "../connection/registry.ts";
17 +import * as EnvironmentSupervisor from "../connection/supervisor.ts";
18 +import * as ManagedRelay from "../relay/managedRelay.ts";
19 +import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
20 +import { createEnvironmentCommand } from "./runtime.ts";
21 +
22 +const MINT_TIMEOUT_MS = 8_000;
23 +const PEER_PAIRING_CODE_LABEL = "T3 Code link";
24 +
25 +/** Minting failed; the user can still paste a code from the other environment. */
26 +export class PeerPairingCodeError extends Data.TaggedError("PeerPairingCodeError")<{
27 + readonly reason: "not_allowed" | "unavailable";
28 + readonly cause: unknown;
29 +}> {
30 + override get message(): string {
31 + return this.reason === "not_allowed"
32 + ? "Your session there cannot create pairing codes. Paste a code from there instead."
33 + : "Could not get a pairing code from there. Paste a code from there instead.";
34 + }
35 +}
36 +
37 +const mintPeerPairingCode = Effect.fn("clientRuntime.state.mintPeerPairingCode")(function* (
38 + prepared: PreparedConnection,
39 + access: AuthMcpClientAccess,
40 +): Effect.fn.Return<string, PeerPairingCodeError, HttpClient.HttpClient> {
41 + const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
42 + const remoteAuthorization = yield* Effect.serviceOption(
43 + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
44 + );
45 + const minted = yield* executeAuthenticatedEnvironmentHttpRequest({
46 + prepared,
47 + signer,
48 + remoteAuthorization,
49 + group: "auth",
50 + method: "POST",
51 + url: (urls) => urls.pairingCredential(),
52 + timeoutMs: MINT_TIMEOUT_MS,
53 + request: ({ client, headers }) =>
54 + client.pairingCredential({
55 + headers,
56 + payload: { label: PEER_PAIRING_CODE_LABEL, scopes: mcpClientScopes(access) },
57 + }),
58 + }).pipe(
59 + Effect.mapError(
60 + (cause) =>
61 + new PeerPairingCodeError({
62 + reason:
63 + cause._tag === "EnvironmentScopeRequiredError" ||
64 + cause._tag === "EnvironmentOperationForbiddenError"
65 + ? "not_allowed"
66 + : "unavailable",
67 + cause,
68 + }),
69 + ),
70 + );
71 + return minted.credential;
72 +});
73 +
74 +/**
75 + * Mints a code on the environment it runs in. Each run mints its own: a code
76 + * is one-use, so two overlapping answers must never share one.
77 + */
78 +export function createPeerPairingCodeCommand<R, E>(
79 + runtime: Atom.AtomRuntime<EnvironmentRegistry | HttpClient.HttpClient | R, E>,
80 +) {
81 + return createEnvironmentCommand(runtime, {
82 + label: "environment-data:peer-pairing-code:mint",
83 + execute: Effect.fn(function* (access: AuthMcpClientAccess) {
84 + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
85 + const prepared = yield* SubscriptionRef.get(supervisor.prepared);
86 + if (Option.isNone(prepared)) {
87 + return yield* new PeerPairingCodeError({
88 + reason: "unavailable",
89 + cause: "The environment is not connected.",
90 + });
91 + }
92 + return yield* mintPeerPairingCode(prepared.value, access);
93 + }),
94 + });
95 +}
packages/client-runtime/src/state/server.ts
+10
@@ -1525,6 +1525,16 @@ export function createServerEnvironmentAtoms<R, E>(
1525 JSON.stringify([environmentId, input.threadId, input.turnItemId]),
1526 },
1527 }),
1528 + // Like a secret card's answer: off the config lane, one per card at a time.
1529 + answerLinkRequest: createEnvironmentRpcCommand(runtime, {
1530 + label: "environment-data:server:peer-links:answer-request",
1531 + tag: WS_METHODS.peerLinksAnswerRequest,
1532 + concurrency: {
1533 + mode: "singleFlight",
1534 + key: ({ environmentId, input }) =>
1535 + JSON.stringify([environmentId, input.threadId, input.turnItemId]),
1536 + },
1537 + }),
1538 refreshUsageRates: createEnvironmentRpcCommand(runtime, {
1539 label: "environment-data:server:refresh-usage-rates",
1540 tag: WS_METHODS.serverRefreshUsageRates,
packages/client-runtime/src/t3ToolSummary.ts
+10
@@ -339,6 +339,16 @@ export function summarizeT3ToolCalls(
339 case "environment-links":
340 label = phrase("Listed", "list", `linked environments ${times}`);
341 break;
342 + case "environment-link":
343 + label = phrase("Asked to link", "ask to link", quantity(selected.length, "environment"));
344 + break;
345 + case "environment-unlink":
346 + label = phrase(
347 + "Forgot",
348 + "forget",
349 + quantity(countEntities(entityIds("environmentId")), "linked environment"),
350 + );
351 + break;
352 case "attachment-prepare":
353 label = phrase(
354 "Prepared",
packages/contracts/src/auth.ts
+13
@@ -408,6 +408,19 @@ export const AuthMcpClientAccess = Schema.Literals([
408 ]);
409 export type AuthMcpClientAccess = typeof AuthMcpClientAccess.Type;
410
411 +/** The scopes an agent session gets for an access level, and a pairing code must carry. */
412 +export const mcpClientScopes = (access: AuthMcpClientAccess): ReadonlyArray<AuthGrantScope> =>
413 + access === "read-only"
414 + ? [AuthOrchestrationReadScope]
415 + : access === "full-access"
416 + ? [
417 + AuthOrchestrationReadScope,
418 + AuthOrchestrationOperateScope,
419 + AuthSettingsWriteScope,
420 + AuthSourceControlWriteScope,
421 + ]
422 + : [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
423 +
424 export const AuthMcpProtectedResourceMetadata = Schema.Struct({
425 resource: Schema.String,
426 authorization_servers: Schema.Array(Schema.String),
packages/contracts/src/clientRpcPermissions.ts
+2
@@ -54,6 +54,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
54 [WS_METHODS.guestShareCreate]: AuthAccessWriteScope,
55 [WS_METHODS.peerLinksLink]: AuthAccessWriteScope,
56 [WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope,
57 + // A link lets every agent here reach the other environment: Settings' bar.
58 + [WS_METHODS.peerLinksAnswerRequest]: AuthAccessWriteScope,
59 } as const;
60 export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES;
61
packages/contracts/src/orchestrationV2.ts
+75
@@ -1506,6 +1506,42 @@ const OrchestrationV2SecretRequestFields = {
1506 secretStatus: OrchestrationV2SecretRequestStatus,
1507 } as const;
1508
1509 +export const OrchestrationV2LinkRequestStatus = Schema.Literals([
1510 + "pending",
1511 + "linked",
1512 + "declined",
1513 + "cancelled",
1514 + "failed",
1515 +]);
1516 +export type OrchestrationV2LinkRequestStatus = typeof OrchestrationV2LinkRequestStatus.Type;
1517 +
1518 +/**
1519 + * An agent asked the user to link another environment. The user picks the
1520 + * access; the pairing code never passes through orchestration, so the item
1521 + * carries only what was asked and how it ended.
1522 + */
1523 +const OrchestrationV2LinkRequestFields = {
1524 + type: Schema.Literal("link_request"),
1525 + /** The address the agent named, if it named one. */
1526 + url: Schema.optional(TrimmedNonEmptyString),
1527 + reason: Schema.String,
1528 + /**
1529 + * The environment the agent named, or the one answering at `url`. Without
1530 + * either the user picks the machine in the card.
1531 + */
1532 + environmentId: Schema.optional(EnvironmentId),
1533 + label: Schema.optional(Schema.String),
1534 + /** A phrase from the user's words, such as "vps", that preselects a machine. */
1535 + hint: Schema.optional(Schema.String),
1536 + /** The access the agent suggested; the user's choice is final. */
1537 + requestedAccess: Schema.optional(AuthMcpClientAccess),
1538 + linkStatus: OrchestrationV2LinkRequestStatus,
1539 + linkedEnvironmentId: Schema.optional(EnvironmentId),
1540 + linkedLabel: Schema.optional(Schema.String),
1541 + linkedAccess: Schema.optional(AuthMcpClientAccess),
1542 + failure: Schema.optional(Schema.String),
1543 +} as const;
1544 +
1545 export const OrchestrationV2TurnItem = Schema.Union([
1546 Schema.Struct({
1547 ...OrchestrationV2TurnItemBaseFields,
@@ -1695,6 +1731,10 @@ export const OrchestrationV2TurnItem = Schema.Union([
1731 ...OrchestrationV2TurnItemBaseFields,
1732 ...OrchestrationV2SecretRequestFields,
1733 }),
1734 + Schema.Struct({
1735 + ...OrchestrationV2TurnItemBaseFields,
1736 + ...OrchestrationV2LinkRequestFields,
1737 + }),
1738 Schema.Struct({
1739 ...OrchestrationV2TurnItemBaseFields,
1740 type: Schema.Literal("subagent"),
@@ -2530,6 +2570,10 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
2570 ...OrchestrationV2TurnItemJsonBaseFields,
2571 ...OrchestrationV2SecretRequestFields,
2572 }),
2573 + Schema.Struct({
2574 + ...OrchestrationV2TurnItemJsonBaseFields,
2575 + ...OrchestrationV2LinkRequestFields,
2576 + }),
2577 Schema.Struct({
2578 ...OrchestrationV2TurnItemJsonBaseFields,
2579 type: Schema.Literal("subagent"),
@@ -3434,6 +3478,37 @@ const OrchestrationV2InternalCommand = Schema.Union([
3478 delivery: Schema.optional(OrchestrationV2SecretRequestDelivery),
3479 secretStatus: OrchestrationV2SecretRequestStatus,
3480 }),
3481 + /**
3482 + * Records or updates a link an agent asked the user to make. Internal so no
3483 + * client can mark a request linked without the link being made.
3484 + */
3485 + Schema.Struct({
3486 + type: Schema.Literal("link_request.record"),
3487 + commandId: CommandId,
3488 + threadId: ThreadId,
3489 + runId: RunId,
3490 + nodeId: NodeId,
3491 + turnItemId: TurnItemId,
3492 + url: Schema.optional(TrimmedNonEmptyString),
3493 + reason: Schema.String,
3494 + environmentId: Schema.optional(EnvironmentId),
3495 + label: Schema.optional(Schema.String),
3496 + hint: Schema.optional(Schema.String),
3497 + requestedAccess: Schema.optional(AuthMcpClientAccess),
3498 + linkStatus: OrchestrationV2LinkRequestStatus,
3499 + linkedEnvironmentId: Schema.optional(EnvironmentId),
3500 + linkedLabel: Schema.optional(Schema.String),
3501 + linkedAccess: Schema.optional(AuthMcpClientAccess),
3502 + failure: Schema.optional(Schema.String),
3503 + /** Tells the agent how the card ended, in the same commit that closes it. */
3504 + wake: Schema.optional(
3505 + Schema.Struct({
3506 + messageId: MessageId,
3507 + text: Schema.String,
3508 + notification: OrchestrationV2Notification,
3509 + }),
3510 + ),
3511 + }),
3512 ]);
3513 export type OrchestrationV2InternalCommand = typeof OrchestrationV2InternalCommand.Type;
3514
packages/contracts/src/orchestratorMcp.ts
+70
@@ -619,6 +619,8 @@ export type OrchestratorMcpEnvironmentLink = typeof OrchestratorMcpEnvironmentLi
619 export const OrchestratorMcpEnvironmentLinksResult = Schema.Struct({
620 environmentId: EnvironmentId,
621 links: Schema.Array(OrchestratorMcpEnvironmentLink),
622 + /** What to do when the machine the user means is not among `links`. */
623 + notListed: Schema.String,
624 });
625 export type OrchestratorMcpEnvironmentLinksResult =
626 typeof OrchestratorMcpEnvironmentLinksResult.Type;
@@ -764,6 +766,74 @@ export const OrchestratorMcpRequestSecretResult = Schema.Union([
766 ]);
767 export type OrchestratorMcpRequestSecretResult = typeof OrchestratorMcpRequestSecretResult.Type;
768
769 +export const OrchestratorMcpEnvironmentLinkInput = Schema.Struct({
770 + environmentId: Schema.optional(EnvironmentId).annotate({
771 + description:
772 + "The machine, when known, e.g. from a mentioned machine. Otherwise the user picks it in the card.",
773 + }),
774 + url: Schema.optional(TrimmedNonEmptyString).annotate({
775 + description:
776 + "Only an address the user gave: https, Tailscale, LAN or loopback. Never guess one.",
777 + }),
778 + hint: Schema.optional(TrimmedNonEmptyString).annotate({
779 + description: 'The user\'s words for the machine, e.g. "vps". Preselects it in the card.',
780 + }),
781 + reason: Schema.optional(TrimmedNonEmptyString).annotate({
782 + description: "One sentence for the card.",
783 + }),
784 + requestedAccess: Schema.optional(AuthMcpClientAccess).annotate({
785 + description: "Suggested access. The user picks; default approval-required.",
786 + }),
787 + clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
788 +});
789 +export type OrchestratorMcpEnvironmentLinkInput = typeof OrchestratorMcpEnvironmentLinkInput.Type;
790 +
791 +export const OrchestratorMcpEnvironmentLinkResult = Schema.Union([
792 + Schema.Struct({
793 + status: Schema.Literal("pending").annotate({
794 + description:
795 + "The card is waiting for the user. Their answer arrives as a message in this thread.",
796 + }),
797 + turnItemId: TurnItemId,
798 + }),
799 + Schema.Struct({
800 + status: Schema.Literal("linked"),
801 + environmentId: EnvironmentId.annotate({
802 + description: "Pass it as environmentId to act there; t3_environment_links lists it.",
803 + }),
804 + label: Schema.String,
805 + access: AuthMcpClientAccess.annotate({ description: "The access the user chose." }),
806 + }),
807 + Schema.Struct({
808 + status: Schema.Literals(["declined", "cancelled"]).annotate({
809 + description:
810 + "declined: the user chose not to. cancelled: the card closed unanswered, when the thread was stopped or archived.",
811 + }),
812 + }),
813 + Schema.Struct({
814 + status: Schema.Literal("failed"),
815 + message: Schema.String.annotate({
816 + description: "Why the other environment refused the link, as the user saw it.",
817 + }),
818 + }),
819 +]);
820 +export type OrchestratorMcpEnvironmentLinkResult = typeof OrchestratorMcpEnvironmentLinkResult.Type;
821 +
822 +export const OrchestratorMcpEnvironmentUnlinkInput = Schema.Struct({
823 + environmentId: EnvironmentId.annotate({
824 + description: "The linked environment to forget, from t3_environment_links.",
825 + }),
826 +});
827 +export type OrchestratorMcpEnvironmentUnlinkInput =
828 + typeof OrchestratorMcpEnvironmentUnlinkInput.Type;
829 +
830 +export const OrchestratorMcpEnvironmentUnlinkResult = Schema.Struct({
831 + environmentId: EnvironmentId,
832 + removed: Schema.Boolean,
833 +});
834 +export type OrchestratorMcpEnvironmentUnlinkResult =
835 + typeof OrchestratorMcpEnvironmentUnlinkResult.Type;
836 +
837 export const OrchestratorMcpDeleteScheduledTaskInput = Schema.Struct({
838 environmentId: OrchestratorMcpEnvironmentTarget,
839 scheduledTaskId: ScheduledTaskId,
packages/contracts/src/peerLink.ts
+65 -1
@@ -1,7 +1,7 @@
1 import * as Schema from "effect/Schema";
2
3 import { AuthMcpClientAccess } from "./auth.ts";
4 -import { EnvironmentId, TrimmedNonEmptyString } from "./baseSchemas.ts";
4 +import { EnvironmentId, ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts";
5
6 /**
7 * A link from this environment to another one (the peer). This environment
@@ -40,6 +40,13 @@ export const PeerLinkCreateInput = Schema.Struct({
40 /** A pairing code from the peer (`t3 pair` there, or its Connections settings). */
41 pairingCode: TrimmedNonEmptyString,
42 access: AuthMcpClientAccess,
43 + /**
44 + * The environment the user means. Addresses that answer as another one are
45 + * skipped, and only those that answer as this one are kept.
46 + */
47 + expectedEnvironmentId: Schema.optionalKey(EnvironmentId),
48 + /** What the user calls that environment, to name it when it cannot be reached. */
49 + expectedLabel: Schema.optionalKey(TrimmedNonEmptyString),
50 });
51 export type PeerLinkCreateInput = typeof PeerLinkCreateInput.Type;
52
@@ -64,3 +71,60 @@ export class PeerLinkError extends Schema.TaggedError<PeerLinkError>()("PeerLink
71 message: Schema.String,
72 cause: Schema.optionalKey(Schema.Defect()),
73 }) {}
74 +
75 +/**
76 + * The user's answer to an agent asking to link an environment. The pairing
77 + * code is used once to link and is never recorded; the thread learns only the
78 + * outcome and the access the user chose.
79 + */
80 +export const PeerLinkRequestAnswerInput = Schema.Struct({
81 + threadId: ThreadId,
82 + turnItemId: TurnItemId,
83 + answer: Schema.Union([
84 + Schema.Struct({
85 + type: Schema.Literal("link"),
86 + /** The machine the user picked, when they picked one rather than typing an address. */
87 + environmentId: Schema.optionalKey(EnvironmentId),
88 + /** What the client calls that machine. */
89 + label: Schema.optionalKey(TrimmedNonEmptyString),
90 + /** The addresses the client knows for that machine, most preferred first. */
91 + urls: Schema.NonEmptyArray(TrimmedNonEmptyString),
92 + access: AuthMcpClientAccess,
93 + pairingCode: TrimmedNonEmptyString,
94 + }),
95 + /** Answers with a machine this environment is already linked to, as it is. */
96 + Schema.Struct({ type: Schema.Literal("use-existing"), environmentId: EnvironmentId }),
97 + Schema.Struct({ type: Schema.Literal("decline") }),
98 + ]),
99 +});
100 +export type PeerLinkRequestAnswerInput = typeof PeerLinkRequestAnswerInput.Type;
101 +
102 +const PEER_LINK_REQUEST_FAILURE_MESSAGES = {
103 + load_failed: "Could not load the link request.",
104 + not_found: "This link request no longer exists.",
105 + already_answered: "This link request was already answered.",
106 + record_failed: "Could not update the link request.",
107 +} as const;
108 +
109 +export const PeerLinkRequestFailureReason = Schema.Literals(
110 + Object.keys(PEER_LINK_REQUEST_FAILURE_MESSAGES) as Array<
111 + keyof typeof PEER_LINK_REQUEST_FAILURE_MESSAGES
112 + >,
113 +);
114 +export type PeerLinkRequestFailureReason = typeof PeerLinkRequestFailureReason.Type;
115 +
116 +/**
117 + * Answering a link request failed before anything was linked. A link the
118 + * other environment refused is not this error: the card records it as failed.
119 + */
120 +export class PeerLinkRequestError extends Schema.TaggedError<PeerLinkRequestError>()(
121 + "PeerLinkRequestError",
122 + {
123 + reason: PeerLinkRequestFailureReason,
124 + cause: Schema.optionalKey(Schema.Defect()),
125 + },
126 +) {
127 + override get message(): string {
128 + return PEER_LINK_REQUEST_FAILURE_MESSAGES[this.reason];
129 + }
130 +}
packages/contracts/src/rpc.ts
+9
@@ -22,6 +22,8 @@ import {
22 PeerLinkError,
23 PeerLinkRemoveInput,
24 PeerLinkRemoveResult,
25 + PeerLinkRequestAnswerInput,
26 + PeerLinkRequestError,
27 PeerLinkSummary,
28 } from "./peerLink.ts";
29 import {
@@ -497,6 +499,7 @@ export const WS_METHODS = {
499 peerLinksList: "peerLinks.list",
500 peerLinksLink: "peerLinks.link",
501 peerLinksUnlink: "peerLinks.unlink",
502 + peerLinksAnswerRequest: "peerLinks.answerRequest",
503 serverGetSettings: "server.getSettings",
504 serverUpdateSettings: "server.updateSettings",
505 serverDiscoverSourceControl: "server.discoverSourceControl",
@@ -797,6 +800,11 @@ const WsPeerLinksUnlinkRpc = Rpc.make(WS_METHODS.peerLinksUnlink, {
800 error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]),
801 });
802
803 +const WsPeerLinksAnswerRequestRpc = Rpc.make(WS_METHODS.peerLinksAnswerRequest, {
804 + payload: PeerLinkRequestAnswerInput,
805 + error: Schema.Union([PeerLinkRequestError, EnvironmentAuthorizationError]),
806 +});
807 +
808 const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, {
809 payload: Schema.Struct({}),
810 success: ServerSettings,
@@ -1977,6 +1985,7 @@ export const WsRpcGroup = RpcGroup.make(
1985 WsPeerLinksListRpc,
1986 WsPeerLinksLinkRpc,
1987 WsPeerLinksUnlinkRpc,
1988 + WsPeerLinksAnswerRequestRpc,
1989 WsServerDiscoverSourceControlRpc,
1990 WsServerSearchAcpRegistryRpc,
1991 WsServerPrepareAcpRegistryAgentRpc,
packages/provider-core/src/server/orchestrationInstructions.ts
+1
@@ -14,6 +14,7 @@ Ordinary coding tasks need no T3 tools.
14 `- \`t3_thread_launch\` and \`create_threads\` make new top-level threads, only when the user asks for a new thread. "Subagent", "delegate", and "parallel" never mean one. Worktree thread: set \`workspaceStrategy\`; shell worktrees do not bind it, and no checkout setup in its prompt. No \`workspaceStrategy\`: project root, not your worktree.
15 - Given a thread id, \`t3_thread_read\` it before you answer about it.
16 - Another machine: \`t3_environment_links\` lists linked ones. Pass its \`environmentId\` to a T3 tool to act there. Ids are then that machine's, so pass \`threadId\`.
17 +- A machine the user names that is not linked ("delegate this to my vps"): call \`t3_environment_link\` with a \`hint\` from their words. Never ask for a pairing code in chat.
18 - In your reply, a thread's first mention is its \`link\` verbatim. No \`link\`: \`[title](t3-thread://v1/<exact id>)\`. Never a plain title or bare id. A thread on a linked machine: its title and machine, not its link.
19 - A secret: call \`request_secret\` yourself. Pass its \`secretRef\` to a T3 tool, or use \`delivery: "file"\` for a shell command. Never ask in chat or invent one. When asked only to schedule, \`schedule_task\` without running its prompt.
20 - T3 tools may load late. Try the name once before you call it absent.`,
packages/shared/src/t3McpToolPresentation.ts
+10
@@ -52,6 +52,8 @@ export type T3McpToolSummaryAction =
52 | "project-clone"
53 | "environment-read"
54 | "environment-links"
55 + | "environment-link"
56 + | "environment-unlink"
57 | "environment-update"
58 | "attachment-prepare"
59 | "attachment-discard"
@@ -326,6 +328,14 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
328 ["List", "Listing", "Listed", "linked environments"],
329 "environment-links",
330 ),
331 + t3_environment_link: tool(
332 + ["Ask to link", "Asking to link", "Asked to link", "an environment"],
333 + "environment-link",
334 + ),
335 + t3_environment_unlink: tool(
336 + ["Forget", "Forgetting", "Forgot", "a linked environment"],
337 + "environment-unlink",
338 + ),
339 t3_environment_preferences_update: tool(
340 ["Update", "Updating", "Updated", "environment preferences"],
341 "environment-update",