Skip to content
TypeScript

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

Julius Marminge8b14660b2787
diff --git a/apps/mobile/src/features/threads/LinkRequestCard.tsx b/apps/mobile/src/features/threads/LinkRequestCard.tsx
new file mode 100644
index 00000000000..ef5516b8d09
--- /dev/null
+++ b/apps/mobile/src/features/threads/LinkRequestCard.tsx
@@ -0,0 +1,514 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ type LinkableMachine,
+ linkRequestAnswerInput,
+ linkRequestDefaultAccess,
+ linkRequestDisplay,
+ linkRequestFailureMessage,
+ linkRequestInitialMachine,
+ type LinkRequestItem,
+ linkRequestTargetName,
+ rankMachinesByHint,
+} from "@t3tools/client-runtime/link-request";
+import {
+ isAtomCommandInterrupted,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
+import {
+ AuthAccessWriteScope,
+ type AuthMcpClientAccess,
+ type EnvironmentId,
+ type OrchestrationV2ProjectedTurnItem,
+} from "@t3tools/contracts";
+import * as Option from "effect/Option";
+import * as Result from "effect/Result";
+import { useMemo, useRef, useState } from "react";
+import { Modal, Platform, Pressable, ScrollView, View, type ColorValue } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+
+import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
+import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
+import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
+import { useLinkableMachines } from "../../state/peerLinks";
+import { mintPairingCodeOn } from "../../state/peerPairingCode";
+import { serverEnvironment } from "../../state/server";
+import { useEnvironmentScope, usePreparedConnection } from "../../state/session";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { SettingsChoiceRow } from "../settings/components/SettingsChoiceRow";
+import { SettingsSection } from "../settings/components/SettingsSection";
+import { Button } from "../../components/ui/Button";
+import { RUNTIME_MODE_CHOICES } from "./thread-settings-options";
+
+/** The same five levels as web's access picker: read-only, then the runtime modes. */
+const ACCESS_CHOICES: ReadonlyArray<{
+ readonly access: AuthMcpClientAccess;
+ readonly label: string;
+ readonly description: string;
+}> = [
+ {
+ access: "read-only",
+ label: "Read only",
+ description: "Read projects and threads. Cannot start, message or change anything.",
+ },
+ ...RUNTIME_MODE_CHOICES.map((choice) => ({ ...choice, access: choice.mode })),
+];
+const accessLabel = (access: AuthMcpClientAccess) =>
+ ACCESS_CHOICES.find((choice) => choice.access === access)?.label ?? access;
+
+const LINK_SYMBOL: AppSymbolName = { ios: "link", android: "desktop_windows" };
+
+/** The machine list's row for linking by an address typed in. */
+const ANOTHER_ADDRESS = "another-address";
+
+/** Whether the agent left the machine for the user to pick. */
+const picksMachine = (item: LinkRequestItem) =>
+ item.environmentId === undefined && item.url === undefined;
+
+/**
+ * Feed card for a link an agent asked the user to make. The user picks the
+ * access in a sheet; the pairing code lives only in that sheet's state and
+ * the RPC payload, and is never logged, alerted, or persisted.
+ */
+export function LinkRequestCard(props: {
+ readonly environmentId: EnvironmentId;
+ readonly projectedItem: OrchestrationV2ProjectedTurnItem;
+ readonly iconColor: ColorValue;
+}) {
+ const { item, visibility } = props.projectedItem;
+ if (item.type !== "link_request") return null;
+ const display = linkRequestDisplay(item, visibility, accessLabel);
+ if (display.kind === "pending") {
+ return <PendingLinkRequest environmentId={props.environmentId} item={item} />;
+ }
+ const icon: AppSymbolName =
+ display.kind === "pending-elsewhere"
+ ? LINK_SYMBOL
+ : display.outcome === "linked"
+ ? "checkmark"
+ : display.outcome === "failed"
+ ? "xmark"
+ : "minus";
+ return (
+ <View className="mb-3 min-h-9 flex-row items-center gap-2 px-1">
+ <SymbolView name={icon} size={13} tintColor={props.iconColor} type="monochrome" />
+ <Text className="flex-1 font-sans text-sm text-foreground-muted" numberOfLines={2}>
+ {display.label}
+ </Text>
+ </View>
+ );
+}
+
+function PendingLinkRequest(props: {
+ readonly environmentId: EnvironmentId;
+ readonly item: LinkRequestItem;
+}) {
+ const { item } = props;
+ const [open, setOpen] = useState(false);
+ const [declining, setDeclining] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const answer = useAtomCommand(serverEnvironment.answerLinkRequest, {
+ label: "decline link request",
+ reportFailure: false,
+ reportDefect: false,
+ });
+ const canAnswer = useAtomValue(
+ serverEnvironment.answerLinkRequest.permissionAtom(props.environmentId),
+ );
+ const target = linkRequestTargetName(item);
+
+ const decline = async () => {
+ const input = linkRequestAnswerInput(item, { type: "decline" });
+ if (input === null) return;
+ setDeclining(true);
+ setError(null);
+ const result = await answer({ environmentId: props.environmentId, input }).finally(() =>
+ setDeclining(false),
+ );
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
+ }
+ };
+
+ return (
+ <View className="mb-3 gap-3 rounded-[20px] border border-border bg-card-alt p-4">
+ <View className="gap-1">
+ <Text className="font-t3-bold text-base text-foreground">
+ {picksMachine(item)
+ ? "Link a machine to this environment"
+ : `Link ${target} to this environment`}
+ </Text>
+ {item.reason.trim() ? (
+ <Text className="font-sans text-sm leading-5 text-foreground-muted">{item.reason}</Text>
+ ) : null}
+ {item.label !== undefined && item.url !== undefined ? (
+ <Text className="font-sans text-xs text-foreground-muted" numberOfLines={1}>
+ {item.url}
+ </Text>
+ ) : null}
+ </View>
+ {error !== null ? (
+ <Text
+ accessibilityRole="alert"
+ accessibilityLiveRegion="polite"
+ className="font-sans text-sm text-danger-foreground"
+ >
+ {error}
+ </Text>
+ ) : null}
+ {canAnswer ? (
+ <>
+ <Button
+ label={picksMachine(item) ? "Choose machine…" : "Review link…"}
+ disabled={declining}
+ onPress={() => setOpen(true)}
+ tone="primary"
+ fullWidth
+ />
+ <View className="flex-row justify-end">
+ <Pressable
+ accessibilityRole="button"
+ accessibilityState={{ disabled: declining }}
+ disabled={declining}
+ hitSlop={8}
+ className="px-1 py-1 active:opacity-60 disabled:opacity-50"
+ onPress={() => void decline()}
+ >
+ <Text className="font-sans text-xs text-foreground-muted">Decline</Text>
+ </Pressable>
+ </View>
+ </>
+ ) : (
+ <Text className="font-sans text-xs text-foreground-muted">
+ Only a session that manages access here can answer this.
+ </Text>
+ )}
+ {open ? (
+ <LinkRequestSheet
+ environmentId={props.environmentId}
+ item={item}
+ onClose={() => setOpen(false)}
+ />
+ ) : null}
+ </View>
+ );
+}
+
+/** What the sheet links; see web's LinkRequestDialog for the same rules. */
+type SheetTarget =
+ | { readonly kind: "none" }
+ | {
+ readonly kind: "machine";
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly urls: ReadonlyArray<string>;
+ readonly linked: boolean;
+ }
+ | { readonly kind: "address" };
+
+function resolveTarget(
+ item: LinkRequestItem,
+ machines: ReadonlyArray<LinkableMachine>,
+ choice: string | null,
+): SheetTarget {
+ if (item.environmentId === undefined && item.url !== undefined) return { kind: "address" };
+ const chosen = item.environmentId ?? choice;
+ if (chosen === null) return { kind: "none" };
+ if (chosen === ANOTHER_ADDRESS) return { kind: "address" };
+ const machine = machines.find((candidate) => candidate.environmentId === chosen);
+ return {
+ kind: "machine",
+ environmentId: machine?.environmentId ?? (chosen as EnvironmentId),
+ label: machine?.label ?? linkRequestTargetName(item),
+ urls: [...new Set([...(machine?.urls ?? []), ...(item.url === undefined ? [] : [item.url])])],
+ linked: machine?.linked ?? false,
+ };
+}
+
+function LinkRequestSheet(props: {
+ readonly environmentId: EnvironmentId;
+ readonly item: LinkRequestItem;
+ readonly onClose: () => void;
+}) {
+ const { item } = props;
+ const insets = useSafeAreaInsets();
+ const pickMachine = picksMachine(item);
+ const listed = useLinkableMachines(props.environmentId, true);
+ const machines = useMemo(() => rankMachinesByHint(listed, item.hint), [listed, item.hint]);
+ const [choice, setChoice] = useState<string | null>(null);
+ const [address, setAddress] = useState(item.url ?? "");
+ const [access, setAccess] = useState<AuthMcpClientAccess>(() => linkRequestDefaultAccess(item));
+ const [pairingCode, setPairingCode] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [mintFailed, setMintFailed] = useState<ReadonlySet<EnvironmentId>>(new Set());
+ // Submit then a tap can both run before a re-render; this guard is synchronous.
+ const inFlight = useRef(false);
+ const answer = useAtomCommand(serverEnvironment.answerLinkRequest, {
+ label: "answer link request",
+ // The failure cause holds the request, and with it the code; keep it out of the console.
+ reportFailure: false,
+ reportDefect: false,
+ });
+ const selected = choice ?? linkRequestInitialMachine(item, machines);
+ const target = resolveTarget(item, machines, selected);
+ const targetName = target.kind === "machine" ? target.label : linkRequestTargetName(item);
+ // This phone can mint a code there when it is connected to that environment
+ // with a session that may create pairing links.
+ const targetId = target.kind === "machine" ? target.environmentId : null;
+ const connected = usePreparedConnection(targetId);
+ const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
+ const canMint =
+ targetId !== null && Option.isSome(connected) && mayMint && !mintFailed.has(targetId);
+ const needsAddress =
+ target.kind === "address" || (target.kind === "machine" && target.urls.length === 0);
+ const useExisting = target.kind === "machine" && target.linked;
+ const ready =
+ target.kind !== "none" &&
+ (useExisting ||
+ ((!needsAddress || address.trim().length > 0) && (canMint || pairingCode.trim().length > 0)));
+
+ const prepareAnswer = async () => {
+ if (target.kind === "none") return null;
+ if (target.kind === "machine" && target.linked) {
+ return linkRequestAnswerInput(item, {
+ type: "use-existing",
+ environmentId: target.environmentId,
+ });
+ }
+ let code = pairingCode;
+ if (canMint && targetId !== null) {
+ const minted = await mintPairingCodeOn(targetId, access);
+ if (Result.isFailure(minted)) {
+ setMintFailed((failed) => new Set(failed).add(targetId));
+ setError(linkRequestFailureMessage(minted.failure));
+ return null;
+ }
+ code = minted.success;
+ }
+ return linkRequestAnswerInput(item, {
+ type: "link",
+ target:
+ target.kind === "address"
+ ? { url: address }
+ : { ...target, urls: needsAddress ? [address.trim()] : target.urls },
+ access,
+ pairingCode: code,
+ });
+ };
+
+ const submit = async () => {
+ if (inFlight.current || target.kind === "none") return;
+ inFlight.current = true;
+ setBusy(true);
+ setError(null);
+ const input = await prepareAnswer();
+ const result =
+ input === null ? null : await answer({ environmentId: props.environmentId, input });
+ inFlight.current = false;
+ setBusy(false);
+ if (result === null) return;
+ if (result._tag === "Success") {
+ setPairingCode("");
+ props.onClose();
+ } else if (!isAtomCommandInterrupted(result)) {
+ setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
+ }
+ };
+
+ return (
+ <Modal
+ animationType="slide"
+ presentationStyle={Platform.OS === "ios" ? "pageSheet" : "fullScreen"}
+ // An answer that lands after a close would still link, and would close a reopened sheet.
+ onRequestClose={() => {
+ if (!busy) props.onClose();
+ }}
+ >
+ <ScrollView
+ className="flex-1 bg-sheet-solid"
+ contentContainerClassName="gap-5 p-5"
+ contentContainerStyle={{ paddingBottom: insets.bottom + 20 }}
+ keyboardShouldPersistTaps="handled"
+ >
+ <View className="gap-1">
+ <Text className="font-t3-bold text-lg text-foreground">
+ {pickMachine ? "Link a machine" : `Link ${targetName}`}
+ </Text>
+ <Text className="font-sans text-sm leading-5 text-foreground-muted">
+ Agents here can then launch, message and wait on threads there. It appears in that
+ machine's Connections, where it can be revoked.
+ </Text>
+ {!pickMachine && item.url !== undefined ? (
+ <Text className="font-sans text-xs text-foreground-muted" numberOfLines={1}>
+ {item.url}
+ </Text>
+ ) : null}
+ </View>
+ {pickMachine ? (
+ <SettingsSection title="Machine">
+ {machines.map((machine, index) => (
+ <MachineRow
+ key={machine.environmentId}
+ machine={machine}
+ selected={selected === machine.environmentId}
+ separated={index > 0}
+ disabled={busy}
+ onPress={() => {
+ setChoice(machine.environmentId);
+ setError(null);
+ }}
+ />
+ ))}
+ <SettingsChoiceRow
+ label="Another address…"
+ description="Link a machine this app does not know, by its https or Tailscale address."
+ selected={selected === ANOTHER_ADDRESS}
+ separated={machines.length > 0}
+ disabled={busy}
+ onPress={() => {
+ setChoice(ANOTHER_ADDRESS);
+ setError(null);
+ }}
+ />
+ </SettingsSection>
+ ) : null}
+ {needsAddress && !(item.url !== undefined && item.environmentId === undefined) ? (
+ <View className="gap-2">
+ <TextInput
+ accessibilityLabel="Address"
+ placeholder="https://machine.tailnet.ts.net"
+ value={address}
+ onChangeText={setAddress}
+ editable={!busy}
+ autoCorrect={false}
+ autoCapitalize="none"
+ keyboardType="url"
+ spellCheck={false}
+ />
+ {target.kind === "machine" ? (
+ <Text className="font-sans text-xs text-foreground-muted">
+ This app has no address for {target.label} that another machine can reach. Enter its
+ https or Tailscale address.
+ </Text>
+ ) : null}
+ </View>
+ ) : null}
+ {useExisting ? (
+ <Text className="font-sans text-sm leading-5 text-foreground-muted">
+ This environment is already linked to {targetName}. The agent can use that link as it
+ is; change its access in Settings → Connections.
+ </Text>
+ ) : target.kind === "none" ? null : (
+ <>
+ {canMint ? null : (
+ <View className="gap-2">
+ <TextInput
+ accessibilityLabel="Pairing code"
+ placeholder="Paste the code"
+ value={pairingCode}
+ onChangeText={setPairingCode}
+ editable={!busy}
+ autoCorrect={false}
+ autoCapitalize="none"
+ autoComplete="one-time-code"
+ textContentType="oneTimeCode"
+ spellCheck={false}
+ />
+ <Text className="font-sans text-xs text-foreground-muted">
+ Create a link on {targetName}: Settings → Connections → Create link, then paste
+ its code here.
+ </Text>
+ </View>
+ )}
+ <SettingsSection title="What agents here may do there">
+ {ACCESS_CHOICES.map((choice, index) => (
+ <SettingsChoiceRow
+ key={choice.access}
+ label={choice.label}
+ description={choice.description}
+ selected={choice.access === access}
+ separated={index > 0}
+ disabled={busy}
+ onPress={() => setAccess(choice.access)}
+ />
+ ))}
+ </SettingsSection>
+ <Text className="font-sans text-xs text-foreground-muted">
+ An agent here never gets more there than its own mode here either. Threads it starts
+ there cannot change that environment's own threads, projects or settings.
+ </Text>
+ </>
+ )}
+ {error !== null ? (
+ <Text
+ accessibilityRole="alert"
+ accessibilityLiveRegion="polite"
+ className="font-sans text-sm text-danger-foreground"
+ >
+ {error}
+ </Text>
+ ) : null}
+ <Button
+ label={busy ? "Linking…" : useExisting ? "Use this link" : "Link"}
+ disabled={busy || !ready}
+ onPress={() => void submit()}
+ tone="primary"
+ fullWidth
+ />
+ <Button label="Cancel" tone="secondary" disabled={busy} onPress={props.onClose} fullWidth />
+ </ScrollView>
+ </Modal>
+ );
+}
+
+/** One machine in the sheet's list: its glyph, name, and whether it is linked or reachable. */
+function MachineRow(props: {
+ readonly machine: LinkableMachine;
+ readonly selected: boolean;
+ readonly separated: boolean;
+ readonly disabled: boolean;
+ readonly onPress: () => void;
+}) {
+ const { machine } = props;
+ const status = machine.linked
+ ? "Linked"
+ : machine.connected
+ ? null
+ : machine.connectOnly
+ ? "T3 Connect"
+ : "Not connected";
+ return (
+ <Pressable
+ accessibilityRole="radio"
+ accessibilityState={{ checked: props.selected, disabled: props.disabled }}
+ className={
+ props.separated
+ ? "flex-row items-center gap-3 border-t border-border-subtle p-4 active:opacity-70"
+ : "flex-row items-center gap-3 p-4 active:opacity-70"
+ }
+ disabled={props.disabled}
+ onPress={props.onPress}
+ >
+ <EnvironmentMachineSymbol
+ kind={machine.machine}
+ size={18}
+ tintColorClassName="accent-foreground-muted"
+ />
+ <View className="min-w-0 flex-1 gap-0.5">
+ <Text className="text-lg text-foreground android:text-base" numberOfLines={1}>
+ {machine.label}
+ </Text>
+ {status === null ? null : <Text className="text-sm text-foreground-muted">{status}</Text>}
+ </View>
+ {props.selected ? (
+ <SymbolView
+ name="checkmark"
+ size={18}
+ tintColorClassName="accent-icon"
+ type="monochrome"
+ weight="semibold"
+ />
+ ) : null}
+ </Pressable>
+ );
+}
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index 36fe66a0264..ca9e6ba18d0 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -18,6 +18,7 @@ import { ThreadContextDivider } from "./thread-context-divider";
import { ThreadHandoffDivider, ThreadHandoffRow } from "./thread-handoff-row";
import { GuestBubbleTint, GuestMessageName } from "./guestMessageStyle";
import { ThreadGuestPendingMessage, useThreadGuestShare } from "./ThreadGuestShareBar";
+import { LinkRequestCard } from "./LinkRequestCard";
import { SecretRequestCard } from "./SecretRequestCard";
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import {
@@ -192,6 +193,7 @@ import {
threadFeedRunIsUnsettled,
isContextCompactionActivityGroup,
isContextHandoffActivityGroup,
+ isLinkRequestActivityGroup,
isSecretRequestActivityGroup,
type ThreadFeedEntry,
type ThreadFeedLatestRun,
@@ -1419,6 +1421,16 @@ function renderFeedEntry(
);
}
+ if (entry.type === "activity-group" && isLinkRequestActivityGroup(entry)) {
+ return (
+ <LinkRequestCard
+ environmentId={props.environmentId}
+ projectedItem={entry.activities[0]!.projectedItem}
+ iconColor={iconSubtleColor}
+ />
+ );
+ }
+
if (entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) {
const label = entry.activities[0]!.summary;
const item = entry.activities[0]!.projectedItem.item;
diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts
index 7525868e5b0..2373b7da0bc 100644
--- a/apps/mobile/src/lib/filePreview.test.ts
+++ b/apps/mobile/src/lib/filePreview.test.ts
@@ -271,6 +271,7 @@ vi.mock("../features/threads/thread-context-divider", () => ({}));
vi.mock("../features/threads/thread-handoff-row", () => ({}));
vi.mock("../features/threads/ThreadGuestShareBar", () => ({ useThreadGuestShare: () => null }));
vi.mock("../features/threads/SecretRequestCard", () => ({}));
+vi.mock("../features/threads/LinkRequestCard", () => ({ LinkRequestCard: () => null }));
vi.mock("../features/threads/worktree-setup-card", () => ({}));
vi.mock("../features/threads/CopyTextButton", () => ({ CopyTextButton: () => null }));
vi.mock("../features/threads/thread-work-log", () => ({ THREAD_DISCLOSURE_TRANSITION_MS: 100 }));
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts
index 0038bc9bf4c..f0f36b119a0 100644
--- a/apps/mobile/src/lib/threadActivity.ts
+++ b/apps/mobile/src/lib/threadActivity.ts
@@ -408,6 +408,12 @@ export function isSecretRequestActivityGroup(entry: ThreadFeedActivityGroup): bo
);
}
+export function isLinkRequestActivityGroup(entry: ThreadFeedActivityGroup): boolean {
+ return (
+ entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "link_request"
+ );
+}
+
function isUserInputActivityGroup(entry: ThreadFeedActivityGroup): boolean {
return entry.activities.some((activity) => activity.workEntry.questionAnswer !== undefined);
}
@@ -516,7 +522,8 @@ function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
item.type === "thread_created" ||
item.type === "system_notice" ||
item.type === "proposed_plan" ||
- item.type === "secret_request"
+ item.type === "secret_request" ||
+ item.type === "link_request"
);
}
@@ -638,6 +645,8 @@ function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
return "zap";
case "secret_request":
return "lock";
+ case "link_request":
+ return "globe";
}
}
@@ -697,6 +706,8 @@ function itemSummary(
return "Thread created";
case "secret_request":
return item.label;
+ case "link_request":
+ return `Link ${item.label ?? item.url ?? "an environment"}`;
case "dynamic_tool": {
const classified = classifyToolActivity({
itemType: "dynamic_tool_call",
@@ -755,6 +766,7 @@ function itemPreview(item: OrchestrationV2TurnItem): string | null {
case "thread_created":
return item.targetThreadId;
case "secret_request":
+ case "link_request":
return item.reason || null;
case "subagent":
return item.result ?? item.progress ?? item.prompt;
diff --git a/apps/mobile/src/state/peerLinks.ts b/apps/mobile/src/state/peerLinks.ts
index 66a29130053..c0b36dfadec 100644
--- a/apps/mobile/src/state/peerLinks.ts
+++ b/apps/mobile/src/state/peerLinks.ts
@@ -1,5 +1,48 @@
+import { useAtomValue } from "@effect/atom-react";
+import { linkableMachines } from "@t3tools/client-runtime/link-request";
import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks";
+import type { EnvironmentId } from "@t3tools/contracts";
+import { useEffect, useEffectEvent, useMemo } from "react";
import { connectionAtomRuntime } from "../connection/runtime";
+import { useEnvironments } from "./environments";
+import { relayEnvironmentDiscovery } from "./relay";
+import { useEnvironmentQuery } from "./query";
+import { useAtomCommand } from "./use-atom-command";
export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);
+
+/**
+ * The user's other machines, for picking one to link `environmentId` to,
+ * including those only on their T3 Connect account. Reads that environment's
+ * links only while `enabled`, since listing them asks every linked machine
+ * whether it answers.
+ */
+export function useLinkableMachines(environmentId: EnvironmentId, enabled: boolean) {
+ const { environments } = useEnvironments();
+ const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
+ const refreshDiscovery = useAtomCommand(relayEnvironmentDiscovery.refresh, {
+ reportFailure: false,
+ });
+ // Connect hosts are listed only once something asked for them, so ask on open.
+ const discoverIfUnasked = useEffectEvent(() => {
+ if (discovery.environments.size === 0 && !discovery.refreshing) void refreshDiscovery();
+ });
+ // 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
+ useEffect(() => {
+ if (enabled) discoverIfUnasked();
+ }, [enabled]);
+ const links = useEnvironmentQuery(
+ enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null,
+ );
+ return useMemo(
+ () =>
+ linkableMachines({
+ environments,
+ threadEnvironmentId: environmentId,
+ links: links.data?.links ?? [],
+ connect: discovery.environments,
+ }),
+ [discovery.environments, environmentId, environments, links.data],
+ );
+}
diff --git a/apps/mobile/src/state/peerPairingCode.ts b/apps/mobile/src/state/peerPairingCode.ts
new file mode 100644
index 00000000000..6cf4c6dc334
--- /dev/null
+++ b/apps/mobile/src/state/peerPairingCode.ts
@@ -0,0 +1,24 @@
+import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode";
+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import type { AuthMcpClientAccess, EnvironmentId } from "@t3tools/contracts";
+import * as Result from "effect/Result";
+
+import { connectionAtomRuntime } from "../connection/runtime";
+import { appAtomRegistry } from "./atom-registry";
+
+const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime);
+
+/**
+ * A fresh pairing code minted on `environmentId` with this client's session
+ * there, for linking with `access`. Fails with `PeerPairingCodeError` when the
+ * session may not create one.
+ */
+export async function mintPairingCodeOn(
+ environmentId: EnvironmentId,
+ access: AuthMcpClientAccess,
+): Promise<Result.Result<string, unknown>> {
+ const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: access });
+ return result._tag === "Success"
+ ? Result.succeed(result.value)
+ : Result.fail(squashAtomCommandFailure(result));
+}
diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts
index 476a3b9f33e..4ddb5066cb1 100644
--- a/apps/server/src/auth/EnvironmentAuth.ts
+++ b/apps/server/src/auth/EnvironmentAuth.ts
@@ -2,9 +2,6 @@ import {
AuthAccessTokenType,
AuthAccessWriteScope,
AuthOrchestrationOperateScope,
- AuthOrchestrationReadScope,
- AuthSettingsWriteScope,
- AuthSourceControlWriteScope,
AuthStandardClientScopes,
type AuthAccessTokenResult,
type AuthBrowserSessionResult,
@@ -24,6 +21,7 @@ import {
type AuthWebSocketTicketUse,
DpopFailureReason,
type DpopFailureReason as DpopFailureReasonType,
+ mcpClientScopes,
} from "@t3tools/contracts";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import * as Context from "effect/Context";
@@ -74,20 +72,6 @@ export interface IssuedBearerSession {
const MCP_CLIENT_SUBJECT = "mcp-client";
const MCP_CLIENT_SESSION_TTL = Duration.days(30);
-export const mcpClientScopes = (
- access: AuthMcpClientAccess,
-): ReadonlyArray<AuthEnvironmentScope> =>
- access === "read-only"
- ? [AuthOrchestrationReadScope]
- : access === "full-access"
- ? [
- AuthOrchestrationReadScope,
- AuthOrchestrationOperateScope,
- AuthSettingsWriteScope,
- AuthSourceControlWriteScope,
- ]
- : [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
-
export interface McpClientSession {
readonly sessionId: AuthSessionId;
readonly label: string;
diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts
index 0846056dafe..5c73cc03fff 100644
--- a/apps/server/src/auth/McpOAuth.test.ts
+++ b/apps/server/src/auth/McpOAuth.test.ts
@@ -1,8 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
+ AuthMcpClientAccess,
AuthStandardClientScopes,
type AuthCreatePairingCredentialInput,
EnvironmentHttpApi,
+ mcpClientScopes,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Context from "effect/Context";
@@ -480,6 +482,23 @@ it.live(
),
);
+it.live("a code minted with an access level's scopes approves that access", () =>
+ withRoutes((handler, auth) =>
+ Effect.gen(function* () {
+ const params = authorizeParams(yield* registeredClientId(handler));
+ for (const access of AuthMcpClientAccess.literals) {
+ const code = yield* auth.issuePairingCredential({ scopes: [...mcpClientScopes(access)] });
+ const approval = yield* decide(handler, params, {
+ _tag: "pairing-code",
+ access,
+ code: code.credential,
+ });
+ expect(approval.status, access).toBe(200);
+ }
+ }),
+ ),
+);
+
it.live("one-click approves only access the browser session holds the scopes for", () =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts
index 064304bce7a..3be31570b4d 100644
--- a/apps/server/src/auth/McpOAuth.ts
+++ b/apps/server/src/auth/McpOAuth.ts
@@ -14,6 +14,7 @@ import {
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
MCP_PEER_LINK_SOFTWARE_ID,
+ mcpClientScopes,
} from "@t3tools/contracts";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import * as Clock from "effect/Clock";
@@ -436,9 +437,7 @@ const make = Effect.gen(function* () {
if (
session === undefined ||
!timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||
- !EnvironmentAuth.mcpClientScopes(decision.access).every((scope) =>
- session.scopes.includes(scope),
- )
+ !mcpClientScopes(decision.access).every((scope) => session.scopes.includes(scope))
) {
return yield* new McpOAuthPageError({
description: "Your session cannot approve this request. Enter a pairing code instead.",
@@ -523,7 +522,7 @@ const make = Effect.gen(function* () {
access_token: issued.token,
token_type: "Bearer",
expires_in: Math.max(0, Math.floor((issued.expiresAt.epochMilliseconds - now) / 1000)),
- scope: encodeOAuthScope(EnvironmentAuth.mcpClientScopes(pending.access)),
+ scope: encodeOAuthScope(mcpClientScopes(pending.access)),
};
},
);
diff --git a/apps/server/src/auth/mcpOAuthHttp.ts b/apps/server/src/auth/mcpOAuthHttp.ts
index 398116e71c2..dfb272605bc 100644
--- a/apps/server/src/auth/mcpOAuthHttp.ts
+++ b/apps/server/src/auth/mcpOAuthHttp.ts
@@ -3,6 +3,7 @@ import {
type AuthMcpAuthorizationRequest,
AuthMcpClientAccess,
EnvironmentHttpApi,
+ mcpClientScopes,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Result from "effect/Result";
@@ -10,7 +11,6 @@ import { HttpServerRequest, HttpServerResponse } from "effect/http";
import * as HttpEffect from "effect/http/HttpEffect";
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
-import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as McpOAuth from "./McpOAuth.ts";
import { renderErrorPage } from "./mcpOAuthHtml.ts";
@@ -121,9 +121,7 @@ export const layer = HttpApiBuilder.group(
: {
csrfToken: session.csrfToken,
oneClickAccess: AuthMcpClientAccess.literals.filter((access) =>
- EnvironmentAuth.mcpClientScopes(access).every((scope) =>
- session.scopes.includes(scope),
- ),
+ mcpClientScopes(access).every((scope) => session.scopes.includes(scope)),
),
}),
};
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index 1721bc950cb..ea9e8a05564 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -901,6 +901,10 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null {
return `Created thread ${item.targetThreadId} with ${item.targetProviderInstanceId} (${item.targetModel}).`;
case "secret_request":
return `Asked the user for ${item.label}: ${item.secretStatus}.`;
+ case "link_request":
+ return item.linkStatus === "linked"
+ ? `Linked ${item.linkedLabel ?? item.label ?? item.url ?? "an environment"} (${item.linkedAccess}).`
+ : `Asked the user to link ${item.label ?? item.url ?? "an environment"}: ${item.linkStatus}.`;
case "subagent":
return item.result ?? item.progress ?? item.prompt;
case "dynamic_tool":
diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
index c73ee930425..dde77d48409 100644
--- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
@@ -48,6 +48,8 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as PeerForwarding from "../peer/PeerForwarding.ts";
+import * as PeerLinkRequests from "../peer/PeerLinkRequests.ts";
+import * as PeerLinks from "../peer/PeerLinks.ts";
const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe(
Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
@@ -229,6 +231,8 @@ describe("orchestrator MCP toolkit", () => {
Layer.provide(ServerSettings.layerTest()),
Layer.provide(layerUnusedScheduledTaskStub),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
Layer.provideMerge(
SecretRequests.layer.pipe(
diff --git a/apps/server/src/mcp/linkOrigin.test.ts b/apps/server/src/mcp/linkOrigin.test.ts
index 59e7ba59921..c17f4ba579d 100644
--- a/apps/server/src/mcp/linkOrigin.test.ts
+++ b/apps/server/src/mcp/linkOrigin.test.ts
@@ -44,6 +44,8 @@ import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as PeerForwarding from "../peer/PeerForwarding.ts";
import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
+import * as PeerLinkRequests from "../peer/PeerLinkRequests.ts";
+import * as PeerLinks from "../peer/PeerLinks.ts";
// A linked environment's session drives this one's real orchestrator through
// its real T3 tools. What the link starts carries its origin, and the link
@@ -157,6 +159,8 @@ const layerTools = Layer.mergeAll(
),
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
Layer.provide(
diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts
index e0eb6f6c811..a978dbc4d1f 100644
--- a/apps/server/src/mcp/toolkits/core.test.ts
+++ b/apps/server/src/mcp/toolkits/core.test.ts
@@ -56,6 +56,8 @@ import { dispatchFailure } from "../threadAccess.ts";
import * as EnvironmentHandlers from "./environment/handlers.ts";
import * as AttachmentHandlers from "./attachment/handlers.ts";
import * as PeerForwarding from "../../peer/PeerForwarding.ts";
+import * as PeerLinkRequests from "../../peer/PeerLinkRequests.ts";
+import * as PeerLinks from "../../peer/PeerLinks.ts";
const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe(
Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
@@ -75,6 +77,8 @@ const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe(
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
);
const threadId = ThreadId.make("mcp-core-thread");
@@ -602,6 +606,8 @@ it.effect("refuses act-as-caller tools to a client caller", () =>
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
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
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
),
),
@@ -748,6 +756,8 @@ it.effect.each(["t3_thread_interrupt", "t3_workflow_stop"])(
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
),
),
),
@@ -839,6 +849,8 @@ it.effect("discovers workflow stop targets and requires orchestration capability
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
index 5d26408314a..3db297bc0d3 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
@@ -3,6 +3,8 @@ import { OrchestratorToolkit } from "./tools.ts";
import * as Effect from "effect/Effect";
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
+import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts";
+import * as PeerLinks from "../../../peer/PeerLinks.ts";
import { readCaller } from "../../threadAccess.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
@@ -189,6 +191,29 @@ const handlers = {
return yield* forwarding.links(scope);
}),
),
+ // A link lets every agent here reach the other environment, so it is an
+ // environment setting: full access, and never for linked work.
+ t3_environment_link: McpToolAccess.writesEnvironment((input) =>
+ Effect.gen(function* () {
+ const scope = yield* McpInvocationContext.McpInvocationContext;
+ const requests = yield* PeerLinkRequests.PeerLinkRequests;
+ return yield* requests.request(scope, input);
+ }),
+ ),
+ t3_environment_unlink: McpToolAccess.writesEnvironment(({ environmentId }) =>
+ Effect.gen(function* () {
+ const links = yield* PeerLinks.PeerLinks;
+ const removed = yield* links
+ .unlink(environmentId)
+ .pipe(
+ Effect.mapError(
+ (error) =>
+ new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
+ ),
+ );
+ return { environmentId, removed };
+ }),
+ ),
t3_thread_interrupt: McpToolAccess.writesThreads(
(input) => [input.threadId],
(input) =>
diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
index 7dbf65e011f..859004d9ce6 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
@@ -2,7 +2,11 @@ import {
OrchestratorMcpCapabilitiesInput,
OrchestratorMcpCapabilitiesResult,
OrchestrationV2StopWorkflowInput,
+ OrchestratorMcpEnvironmentLinkInput,
+ OrchestratorMcpEnvironmentLinkResult,
OrchestratorMcpEnvironmentLinksResult,
+ OrchestratorMcpEnvironmentUnlinkInput,
+ OrchestratorMcpEnvironmentUnlinkResult,
OrchestratorMcpCreateThreadsInput,
OrchestratorMcpCreateThreadsResult,
OrchestratorMcpDelegateTaskInput,
@@ -40,6 +44,8 @@ import * as Struct from "effect/Struct";
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
+import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts";
+import * as PeerLinks from "../../../peer/PeerLinks.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts";
import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts";
@@ -51,6 +57,12 @@ const dependencies = [
];
/** Listing this environment's links. */
const linkDependencies = [...dependencies, PeerForwarding.PeerForwarding];
+/** Making and forgetting links. */
+const linkingDependencies = [
+ ...dependencies,
+ PeerLinkRequests.PeerLinkRequests,
+ PeerLinks.PeerLinks,
+];
const threadMetadataDependencies = [
McpInvocationContext.McpInvocationContext,
ThreadManagementService.ThreadManagementService,
@@ -295,7 +307,7 @@ const ThreadInterruptTool = Tool.make("t3_thread_interrupt", {
const EnvironmentLinksTool = Tool.make("t3_environment_links", {
description:
- "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.",
+ "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`.",
success: OrchestratorMcpEnvironmentLinksResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
@@ -306,6 +318,32 @@ const EnvironmentLinksTool = Tool.make("t3_environment_links", {
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);
+const EnvironmentLinkTool = Tool.make("t3_environment_link", {
+ description:
+ "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.",
+ parameters: OrchestratorMcpEnvironmentLinkInput,
+ success: OrchestratorMcpEnvironmentLinkResult,
+ failure: OrchestratorMcpFailure,
+ failureMode: "return",
+ dependencies: linkingDependencies,
+})
+ .annotate(Tool.Title, "Link another environment")
+ .annotate(Tool.Destructive, false)
+ .annotate(Tool.OpenWorld, true);
+
+const EnvironmentUnlinkTool = Tool.make("t3_environment_unlink", {
+ description:
+ "Forget a linked environment. That machine's Connections list its session until revoked there.",
+ parameters: OrchestratorMcpEnvironmentUnlinkInput,
+ success: OrchestratorMcpEnvironmentUnlinkResult,
+ failure: OrchestratorMcpFailure,
+ failureMode: "return",
+ dependencies: linkingDependencies,
+})
+ .annotate(Tool.Title, "Forget a linked environment")
+ .annotate(Tool.Destructive, true)
+ .annotate(Tool.Idempotent, true);
+
export const OrchestratorToolkit = Toolkit.make(
OrchestratorCapabilitiesTool,
DelegateTaskTool,
@@ -325,4 +363,6 @@ export const OrchestratorToolkit = Toolkit.make(
ThreadWaitTool,
ThreadInterruptTool,
EnvironmentLinksTool,
+ EnvironmentLinkTool,
+ EnvironmentUnlinkTool,
);
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index 4f32e7d8f15..a4c6dc41208 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -62,6 +62,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.peerLinksList]: "peerLinks",
[WS_METHODS.peerLinksLink]: "peerLinks",
[WS_METHODS.peerLinksUnlink]: "peerLinks",
+ [WS_METHODS.peerLinksAnswerRequest]: "peerLinks",
[WS_METHODS.serverUpdateSettings]: "server",
[WS_METHODS.serverSearchAcpRegistry]: "server",
[WS_METHODS.serverPrepareAcpRegistryAgent]: "server",
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index c4f3fe5ebd8..12338186078 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -526,6 +526,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
case "thread.created.record":
return command.parentThreadId;
case "secret_request.record":
+ case "link_request.record":
return command.threadId;
case "thread.fork":
case "thread.merge_back":
@@ -3854,6 +3855,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
now,
cancelQueuedDelivery: false,
});
+ yield* closePendingLinkRequests({ command, events, threadId: command.threadId, now });
}
// 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
},
);
+ /**
+ * Records or updates the card for a link an agent asked the user to make.
+ * The pairing code goes straight to the link and never through orchestration.
+ */
+ const dispatchLinkRequestRecord = Effect.fn("orchestrationV2.dispatch.linkRequestRecord")(
+ function* (
+ command: Extract<OrchestrationV2InternalCommand, { readonly type: "link_request.record" }>,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
+ ) {
+ const projection = yield* projectionStore
+ .getThreadRecords(
+ command.threadId,
+ ["runs", "nodes", "turnItems", "attempts", "providerTurns"],
+ { turnItemTypes: ["link_request"], messageRoles: [] },
+ )
+ .pipe(
+ Effect.mapError(
+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
+ ),
+ );
+ const run = projection.runs.find((candidate) => candidate.id === command.runId);
+ if (run === undefined) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Run ${command.runId} was not found.`,
+ });
+ }
+ const existing = projection.turnItems.find((item) => item.id === command.turnItemId);
+ if (existing !== undefined && existing.type !== "link_request") {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Turn item ${command.turnItemId} is not a link request.`,
+ });
+ }
+ if (existing !== undefined && existing.runId !== command.runId) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Link request ${command.turnItemId} belongs to another run.`,
+ });
+ }
+ // Only a new card needs its run's current root and a live run. An answer
+ // may land long after a steer restarted the run or the run ended, and the
+ // link it reports is already made.
+ if (existing === undefined && run.rootNodeId !== command.nodeId) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`,
+ });
+ }
+ if (
+ existing === undefined &&
+ (!isBlockingRun(run) || (yield* stopReachedRun(command, command.threadId, run.id)))
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Run ${command.runId} is not active.`,
+ });
+ }
+ const nodeId = existing?.nodeId ?? command.nodeId;
+ const now = yield* DateTime.now;
+ // A request is answered once, and a retry finds its card as it was
+ // asked: either one records the card unchanged.
+ const unchanged =
+ existing !== undefined &&
+ (existing.linkStatus !== "pending" || command.linkStatus === "pending");
+ const pending = command.linkStatus === "pending";
+ const {
+ type: _type,
+ commandId: _commandId,
+ turnItemId: _turnItemId,
+ wake,
+ ...fields
+ } = command;
+ const turnItem: OrchestrationV2TurnItem = unchanged
+ ? existing
+ : {
+ ...fields,
+ id: command.turnItemId,
+ // An update keeps where the card was asked, even after a restart.
+ ...(existing === undefined
+ ? {
+ providerThreadId: run.providerThreadId,
+ providerTurnId: providerTurnForRun(projection, run)?.id ?? null,
+ }
+ : {
+ nodeId: existing.nodeId,
+ providerThreadId: existing.providerThreadId,
+ providerTurnId: existing.providerTurnId,
+ }),
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: existing?.ordinal ?? (yield* nextTurnItemOrdinal(projection)),
+ status: pending
+ ? "waiting"
+ : command.linkStatus === "linked"
+ ? "completed"
+ : command.linkStatus === "failed"
+ ? "failed"
+ : "cancelled",
+ title: command.label ?? command.url ?? "Link an environment",
+ startedAt: existing?.startedAt ?? now,
+ completedAt: pending ? null : now,
+ updatedAt: now,
+ type: "link_request",
+ };
+ yield* emit(
+ events,
+ command,
+ )({
+ type: "turn-item.updated",
+ threadId: command.threadId,
+ runId: command.runId,
+ nodeId,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: turnItem,
+ });
+ // The agent asked without waiting, so the answer reaches it as a
+ // notification: it starts a turn, or follows the one running. Only the
+ // answer that closes the card wakes it, and never a closed thread.
+ if (
+ wake === undefined ||
+ unchanged ||
+ projection.thread.archivedAt !== null ||
+ projection.thread.deletedAt !== null
+ ) {
+ return;
+ }
+ yield* dispatchMessage(
+ {
+ type: "message.dispatch",
+ commandId: command.commandId,
+ threadId: command.threadId,
+ messageId: wake.messageId,
+ text: wake.text,
+ notification: wake.notification,
+ attachments: [],
+ dispatchMode: { type: "queue_after_active" },
+ createdBy: "agent",
+ creationSource: "server",
+ },
+ events,
+ effects,
+ );
+ },
+ );
+
+ /**
+ * Closes the link cards still waiting for the user. Their agent stopped
+ * waiting long ago, so nobody is woken: stopping or archiving the thread
+ * means the user is done with it.
+ */
+ const closePendingLinkRequests = Effect.fn("orchestrationV2.closePendingLinkRequests")(
+ function* (input: {
+ readonly command: OrchestrationV2ServerCommand;
+ readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
+ readonly threadId: ThreadId;
+ readonly now: DateTime.Utc;
+ }) {
+ const { turnItems } = yield* projectionStore
+ .getThreadRecords(input.threadId, ["turnItems"], {
+ turnItemTypes: ["link_request"],
+ turnItemStatuses: ["waiting"],
+ messageRoles: [],
+ })
+ .pipe(mapDispatchError(input.command));
+ for (const item of turnItems) {
+ if (item.type !== "link_request" || item.linkStatus !== "pending") continue;
+ yield* emit(
+ input.events,
+ input.command,
+ )({
+ type: "turn-item.updated",
+ threadId: input.threadId,
+ ...(item.runId === null ? {} : { runId: item.runId }),
+ ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
+ occurredAt: input.now,
+ payload: {
+ ...item,
+ status: "cancelled",
+ linkStatus: "cancelled",
+ completedAt: input.now,
+ updatedAt: input.now,
+ },
+ });
+ }
+ },
+ );
+
const dispatchRuntimeRequestRespond = Effect.fn("Orchestrator.dispatchRuntimeRequestRespond")(
function* (
command: Extract<OrchestrationV2Command, { readonly type: "runtime-request.respond" }>,
@@ -10145,6 +10342,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
now: input.now,
});
}
+ yield* closePendingLinkRequests({ ...input, threadId: thread.id });
});
const dispatchBackgroundWorkSettle = Effect.fn("Orchestrator.dispatchBackgroundWorkSettle")(
@@ -12528,6 +12726,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
case "secret_request.record":
yield* dispatchSecretRequestRecord(command, events);
break;
+ case "link_request.record":
+ yield* dispatchLinkRequestRecord(command, events, effects);
+ break;
default:
return yield* dispatchUnsupported(command);
}
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index 224e57c822e..5f7247c0a59 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -1139,6 +1139,7 @@ type ShellThreadRow = {
readonly blocking_failure_payload_json: string | null;
readonly pending_request_payload_json: string | null;
readonly pending_secret_request_payload_json: string | null;
+ readonly pending_link_request_payload_json: string | null;
readonly latest_user_message_at: string | null;
readonly latest_user_authored_message_at: string | null;
readonly has_actionable_proposed_plan: number;
@@ -1563,7 +1564,8 @@ function pendingRuntimeRequestSummary(
function secretRequestAsPendingInput(
item: OrchestrationV2TurnItem | null,
): OrchestrationV2PendingRuntimeRequestSummary | null {
- if (item?.type !== "secret_request" || item.nodeId === null) return null;
+ if ((item?.type !== "secret_request" && item?.type !== "link_request") || item.nodeId === null)
+ return null;
return {
id: RuntimeRequestId.make(item.id),
kind: "user_input",
@@ -1572,6 +1574,14 @@ function secretRequestAsPendingInput(
};
}
+/**
+ * A secret card is answered while its agent waits in the run. A link card's
+ * agent asked without waiting, so the card waits on the user after its run.
+ */
+const waitsOnUser = (item: OrchestrationV2TurnItem, liveRunIds: ReadonlySet<RunId>) =>
+ item.type === "link_request" ||
+ (item.type === "secret_request" && item.runId !== null && liveRunIds.has(item.runId));
+
export function threadShellFromProjection(
projection: OrchestrationV2ThreadProjection,
): OrchestrationV2ThreadShell {
@@ -1611,13 +1621,7 @@ export function threadShellFromProjection(
pendingRuntimeRequest =
secretRequestAsPendingInput(
projection.turnItems
- .filter(
- (item) =>
- item.type === "secret_request" &&
- item.status === "waiting" &&
- item.runId !== null &&
- liveRunIds.has(item.runId),
- )
+ .filter((item) => item.status === "waiting" && waitsOnUser(item, liveRunIds))
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
@@ -5926,6 +5930,15 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
ORDER BY secret.updated_at DESC, secret.turn_item_id DESC
LIMIT 1
) AS pending_secret_request_payload_json,
+ (
+ SELECT link.payload_json
+ FROM orchestration_v2_projection_turn_items link
+ INDEXED BY orchestration_v2_projection_turn_items_waiting_link_idx
+ WHERE link.thread_id = t.thread_id
+ AND link.type = 'link_request' AND link.status = 'waiting'
+ ORDER BY link.updated_at DESC, link.turn_item_id DESC
+ LIMIT 1
+ ) AS pending_link_request_payload_json,
(
SELECT message.updated_at
FROM orchestration_v2_projection_messages message
@@ -6220,6 +6233,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
SELECT 1 FROM orchestration_v2_projection_runtime_requests request
WHERE request.thread_id = t.thread_id AND request.status = 'pending'
)
+ AND NOT EXISTS (
+ SELECT 1 FROM orchestration_v2_projection_turn_items link
+ INDEXED BY orchestration_v2_projection_turn_items_waiting_link_idx
+ WHERE link.thread_id = t.thread_id
+ AND link.type = 'link_request' AND link.status = 'waiting'
+ )
ORDER BY t.updated_at ASC, t.thread_id ASC
`;
if (rows.length === 0) return [];
@@ -6384,6 +6403,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
pendingTurnItemsByThreadId,
} = input;
const thread = yield* decodeThreadPayload(row.payload_json);
+ const waitingCards = [
+ row.pending_secret_request_payload_json === null
+ ? null
+ : yield* decodeTurnItemPayload(row.pending_secret_request_payload_json),
+ row.pending_link_request_payload_json === null
+ ? null
+ : yield* decodeTurnItemPayload(row.pending_link_request_payload_json),
+ ].filter((item) => item !== null);
let pendingRuntimeRequest =
row.pending_request_payload_json !== null
? pendingRuntimeRequestSummary(
@@ -6392,11 +6419,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
: null;
if (
(pendingRuntimeRequest === null || pendingRuntimeRequest.blocking === false) &&
- row.pending_secret_request_payload_json !== null
+ waitingCards.length > 0
) {
pendingRuntimeRequest =
secretRequestAsPendingInput(
- yield* decodeTurnItemPayload(row.pending_secret_request_payload_json),
+ waitingCards.toSorted(
+ (left, right) =>
+ DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
+ )[0] ?? null,
) ?? pendingRuntimeRequest;
}
let terminalFailureItem =
diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts
index d0a97adb106..2fd9b13a35c 100644
--- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts
@@ -418,6 +418,89 @@ it.effect("cancels a stale waiting run when no checkpoint capture can finish it"
}).pipe(Effect.provide(layer));
});
+it.effect("recovery closes a secret card's form but leaves a link card open", () => {
+ const threadId = ThreadId.make("thread_secret_recovery");
+ const runId = RunId.make("run_secret_recovery");
+ let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
+ null;
+ const projection = {
+ thread: { id: threadId },
+ runtimeRequests: [],
+ providerSessions: [],
+ providerThreads: [],
+ providerTurns: [],
+ runs: [{ id: runId, status: "running", providerInstanceId: ProviderInstanceId.make("codex") }],
+ attempts: [],
+ nodes: [],
+ subagents: [],
+ messages: [],
+ turnItems: [
+ {
+ id: "turn-item:secret-request:recovery",
+ threadId,
+ runId,
+ nodeId: null,
+ type: "secret_request",
+ status: "waiting",
+ secretStatus: "pending",
+ label: "GitHub token",
+ reason: "Used as GH_TOKEN.",
+ },
+ {
+ id: "turn-item:link-request:recovery",
+ threadId,
+ runId,
+ nodeId: null,
+ type: "link_request",
+ status: "waiting",
+ linkStatus: "pending",
+ url: "https://box.example.ts.net",
+ reason: "Run the suite there.",
+ },
+ ],
+ } as unknown as OrchestrationV2ThreadProjection;
+ const layer = ProviderRuntimeRecovery.layer.pipe(
+ Layer.provide(ServerSettings.layerTest()),
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
+ getRecoveryThreadIds: () => Effect.succeed([threadId]),
+ getRuntimeRecoveryProjection: () => Effect.succeed(projection),
+ }),
+ Layer.mock(EventSink.EventSinkV2)({
+ commitCommand: (input) => {
+ committedInput = input;
+ return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
+ },
+ }),
+ IdAllocator.layer,
+ Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
+ runRecoveryOnce: Effect.succeed(false),
+ }),
+ Layer.mock(EffectOutbox.EffectOutboxV2)({
+ listByCommandId: () => Effect.succeed([]),
+ reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
+ }),
+ ),
+ ),
+ );
+
+ return Effect.gen(function* () {
+ yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
+ const cards = (committedInput?.events ?? []).flatMap((event) =>
+ event.type === "turn-item.updated" ? [event.payload] : [],
+ );
+ const secret = cards.find((card) => card.type === "secret_request");
+ assert.equal(secret?.status, "cancelled");
+ assert.equal(secret?.type === "secret_request" ? secret.secretStatus : null, "cancelled");
+ // Nothing in memory waits on a link card; the user can still answer it.
+ assert.equal(
+ cards.some((card) => card.type === "link_request"),
+ false,
+ );
+ }).pipe(Effect.provide(layer));
+});
+
it.effect.each(["queued", "preparing"] as const)("recovers $0 work after restart", (status) => {
const threadId = ThreadId.make("thread_queued_restart");
const runId = RunId.make("run_queued_restart");
diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
index 82ae02fb54a..910dc97bfda 100644
--- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
+++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
@@ -440,6 +440,8 @@ export const make = Effect.gen(function* () {
candidate.runId === run.id &&
(candidate.nodeId === null || !messageRequestNodeIds.has(candidate.nodeId)) &&
!isAppOwnedDelegationItem(candidate) &&
+ // A link card waits on the user, not the run, and answers by message.
+ candidate.type !== "link_request" &&
(candidate.status === "pending" ||
candidate.status === "running" ||
candidate.status === "waiting"),
diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts
index 59a4e810c9b..50be4068206 100644
--- a/apps/server/src/peer/PeerForwarding.test.ts
+++ b/apps/server/src/peer/PeerForwarding.test.ts
@@ -38,6 +38,7 @@ import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
import { liveThreadShell } from "../mcp/McpToolAccess.testkit.ts";
import * as PeerForwarding from "./PeerForwarding.ts";
import * as PeerLinks from "./PeerLinks.ts";
+import * as PeerLinkRequests from "./PeerLinkRequests.ts";
import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";
const laptop = descriptorOf("environment-laptop", "Laptop");
@@ -230,6 +231,8 @@ const serveBox = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) =>
Layer.provide(ServerSettings.layerTest()),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
),
);
@@ -307,6 +310,7 @@ const makeLaptop = Effect.gen(function* () {
Layer.mock(SecretRequests.SecretRequests)({}),
ServerSettings.layerTest(),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
+ Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
),
),
Layer.fresh,
diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts
index be9db1e4895..ddcf3d0fa06 100644
--- a/apps/server/src/peer/PeerForwarding.ts
+++ b/apps/server/src/peer/PeerForwarding.ts
@@ -213,6 +213,13 @@ const make = Effect.gen(function* () {
) as Effect.Effect<Tool.Success<typeof tool>, OrchestratorMcpFailure>)
: forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, params);
+ /**
+ * The next step for an agent whose machine is not linked: without it, an
+ * empty list reads as a dead end and agents go looking elsewhere.
+ */
+ const NOT_LISTED =
+ "Not listed: not linked yet. Call t3_environment_link with a hint from the user's words.";
+
const listLinks: PeerForwarding["Service"]["links"] = Effect.fn("PeerForwarding.listLinks")(
function* (scope) {
yield* callerLimits(scope);
@@ -232,6 +239,7 @@ const make = Effect.gen(function* () {
expiresAt: DateTime.formatIso(link.expiresAt),
lastError: link.lastError,
})),
+ notListed: NOT_LISTED,
};
},
);
diff --git a/apps/server/src/peer/PeerLinkRequests.test.ts b/apps/server/src/peer/PeerLinkRequests.test.ts
new file mode 100644
index 00000000000..b7353beb649
--- /dev/null
+++ b/apps/server/src/peer/PeerLinkRequests.test.ts
@@ -0,0 +1,979 @@
+import { NodeHttpServer } from "@effect/platform-node";
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import {
+ CommandId,
+ EventId,
+ MessageId,
+ NodeId,
+ OrchestratorMcpFailure,
+ ProjectId,
+ ProviderDriverKind,
+ ProviderInstanceId,
+ ProviderThreadId,
+ type RuntimeMode,
+ RunId,
+ ThreadId,
+ TurnItemId,
+} from "@t3tools/contracts";
+import { expect, it } from "@effect/vitest";
+import * as Clock from "effect/Clock";
+import * as Context from "effect/Context";
+import * as DateTime from "effect/DateTime";
+import * as Deferred from "effect/Deferred";
+import * as Duration from "effect/Duration";
+import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import * as HttpServer from "effect/http/HttpServer";
+import * as HttpServerResponse from "effect/http/HttpServerResponse";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/sql/SqlClient";
+import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
+
+import * as ServerConfig from "../config.ts";
+import * as McpHttpServer from "../mcp/McpHttpServer.ts";
+import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
+import * as McpToolAccess from "../mcp/McpToolAccess.ts";
+import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
+import * as EventSink from "../orchestration-v2/EventSink.ts";
+import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
+import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
+import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
+import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
+import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
+import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
+import * as SqlitePersistence from "../persistence/Sqlite.ts";
+import * as ProjectService from "../project/ProjectService.ts";
+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
+import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
+import * as SecretRequests from "../secrets/SecretRequests.ts";
+import * as ServerSettings from "../serverSettings.ts";
+import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
+import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
+import * as PeerForwarding from "./PeerForwarding.ts";
+import * as PeerLinkRequests from "./PeerLinkRequests.ts";
+import * as PeerLinks from "./PeerLinks.ts";
+import {
+ descriptorOf,
+ layerLinkingEnvironment,
+ linkTo,
+ servePeer,
+ type ServedPeer,
+} from "./PeerLinks.testkit.ts";
+import * as RemoteDelegation from "./RemoteDelegation.ts";
+
+// The laptop's agent asks the user to link the box. The laptop is its real
+// orchestrator and toolkit; the box is its real descriptor and MCP OAuth on a
+// socket. The user's answer goes through PeerLinkRequests, as the card's does.
+
+const laptop = descriptorOf("environment-laptop", "Laptop");
+const box = descriptorOf("environment-box", "Box");
+const instanceId = ProviderInstanceId.make("codex");
+const driver = ProviderDriverKind.make("codex");
+const modelSelection = { instanceId, model: "gpt-5.4" };
+const threadId = ThreadId.make("thread:laptop");
+const runId = RunId.make("run:laptop");
+const rootNode = NodeId.make("node:laptop:root");
+
+/** The box needs no tools of its own: linking only signs in to its /mcp. */
+const NoTools = Toolkit.make(
+ Tool.make("noop", { success: Schema.Struct({}), failure: OrchestratorMcpFailure }),
+);
+const serveBox = servePeer(
+ box,
+ McpHttpServer.toolkitRegistration(
+ NoTools,
+ McpToolAccess.toLayer(NoTools, { noop: McpToolAccess.reads(() => Effect.succeed({})) }),
+ ),
+);
+
+const adapter = {
+ instanceId,
+ driver,
+ getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
+ openSession: () => Effect.die("No provider process needed"),
+} as ProviderAdapter.ProviderAdapterV2["Service"];
+
+const mcpClient = McpSchema.McpServerClient.of({
+ clientId: 1,
+ protocolVersion: "2025-06-18",
+ clientCapabilities: {},
+ clientInfo: { name: "peer-link-requests", version: "1" },
+ initializePayload: {
+ protocolVersion: "2025-06-18",
+ capabilities: {},
+ clientInfo: { name: "peer-link-requests", version: "1" },
+ },
+ getClient: Effect.die("unused"),
+});
+
+const scope: McpInvocationContext.McpInvocationScope = {
+ environmentId: laptop.environmentId,
+ requestNamespace: "provider-session:laptop",
+ thread: {
+ threadId,
+ providerSessionId: "provider-session:laptop",
+ providerInstanceId: instanceId,
+ },
+ client: undefined,
+ capabilities: new Set(["orchestration"]),
+ issuedAt: 1,
+};
+
+/** The laptop: a real orchestrator, its orchestrator toolkit, and its links. */
+const makeLaptop = Effect.gen(function* () {
+ const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);
+ // The orchestrator's own database, apart from the one links are kept in.
+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);
+ const layerDatabase = Layer.succeedContext(database);
+ const layerOrchestrator = Layer.mergeAll(
+ layerDatabase,
+ ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
+ ProviderReplayHarness.layerWithRegistry(
+ { name: "peer-link-requests" },
+ ProviderAdapterRegistry.layerFromAdapters([adapter]),
+ { databaseLayer: layerDatabase, runEffectWorker: false },
+ ),
+ ).pipe(
+ Layer.provide(
+ Layer.succeed(ProviderContinuationRequests.ProviderContinuationRequests, {
+ offer: () => Effect.void,
+ take: Effect.never,
+ }),
+ ),
+ );
+ const layerThreads = ThreadManagement.layer.pipe(
+ Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
+ Layer.provideMerge(Layer.merge(layerOrchestrator, ServerSettings.layerTest())),
+ );
+ const layerHere = McpHttpServer.layerOrchestratorToolkit.pipe(
+ Layer.provideMerge(McpServer.McpServer.layer),
+ Layer.provideMerge(PeerLinkRequests.layer),
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
+ Layer.provide(Layer.succeedContext(linking)),
+ Layer.provide(NodeCrypto.layer),
+ Layer.provideMerge(layerThreads),
+ Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
+ Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
+ Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
+ Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
+ Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
+ Layer.provide(Layer.mock(ThreadLaunch.ThreadLaunchService)({})),
+ Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
+ Layer.provide(
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-requests-" }).pipe(
+ Layer.provide(NodeServices.layer),
+ ),
+ ),
+ Layer.provide(NodeServices.layer),
+ Layer.fresh,
+ );
+ const here = yield* Layer.build(layerHere);
+ const server = Context.get(here, McpServer.McpServer);
+ return {
+ links: Context.get(linking, PeerLinks.PeerLinks),
+ linksSql: Context.get(linking, SqlClient.SqlClient),
+ requests: Context.get(here, PeerLinkRequests.PeerLinkRequests),
+ orchestrator: Context.get(here, Orchestrator.OrchestratorV2),
+ sink: Context.get(here, EventSink.EventSinkV2),
+ projections: Context.get(here, ProjectionStore.ProjectionStoreV2),
+ sql: Context.get(database, SqlClient.SqlClient),
+ call: (args: Record<string, unknown>, callScope = scope) =>
+ server
+ .callTool({ name: "t3_environment_link", arguments: args })
+ .pipe(
+ Effect.provideService(McpInvocationContext.McpInvocationContext, callScope),
+ Effect.provideService(McpSchema.McpServerClient, mcpClient),
+ ),
+ };
+});
+type Laptop = Effect.Success<typeof makeLaptop>;
+
+/** The laptop's thread, mid-turn when its agent asks, in `runtimeMode`. */
+const seedThread = (
+ a: Laptop,
+ runtimeMode: RuntimeMode = "full-access",
+ linkOrigin?: { readonly sessionId: string; readonly label: string },
+) =>
+ Effect.gen(function* () {
+ const now = yield* DateTime.now;
+ const providerThreadId = ProviderThreadId.make("provider-thread:laptop");
+ yield* a.orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:create:laptop"),
+ threadId,
+ projectId: ProjectId.make("project:laptop"),
+ title: "Laptop",
+ modelSelection,
+ runtimeMode,
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ ...(linkOrigin === undefined ? {} : { linkOrigin }),
+ });
+ yield* a.sink.write({
+ commandId: CommandId.make("command:seed:laptop"),
+ events: [
+ {
+ id: EventId.make("event:seed-provider-thread"),
+ type: "provider-thread.updated",
+ threadId,
+ driver,
+ providerInstanceId: instanceId,
+ occurredAt: now,
+ payload: {
+ id: providerThreadId,
+ driver,
+ providerInstanceId: instanceId,
+ providerSessionId: null,
+ appThreadId: threadId,
+ ownerNodeId: rootNode,
+ nativeThreadRef: { driver, nativeId: "native:laptop", strength: "strong" },
+ nativeConversationHeadRef: null,
+ status: "active",
+ firstRunOrdinal: 1,
+ lastRunOrdinal: 1,
+ handoffIds: [],
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ },
+ },
+ {
+ id: EventId.make("event:seed-node"),
+ type: "node.updated",
+ threadId,
+ runId,
+ nodeId: rootNode,
+ driver,
+ providerInstanceId: instanceId,
+ occurredAt: now,
+ payload: {
+ id: rootNode,
+ threadId,
+ runId,
+ parentNodeId: null,
+ rootNodeId: rootNode,
+ kind: "root_turn",
+ status: "running",
+ countsForRun: true,
+ providerThreadId,
+ providerTurnId: null,
+ nativeItemRef: null,
+ runtimeRequestId: null,
+ checkpointScopeId: null,
+ startedAt: now,
+ completedAt: null,
+ },
+ },
+ {
+ id: EventId.make("event:seed-run"),
+ type: "run.updated",
+ threadId,
+ runId,
+ nodeId: rootNode,
+ providerInstanceId: instanceId,
+ occurredAt: now,
+ payload: {
+ id: runId,
+ threadId,
+ ordinal: 1,
+ providerInstanceId: instanceId,
+ modelSelection,
+ providerThreadId,
+ userMessageId: MessageId.make("message:seed-user"),
+ rootNodeId: rootNode,
+ activeAttemptId: null,
+ status: "running",
+ requestedAt: now,
+ startedAt: now,
+ completedAt: null,
+ checkpointId: null,
+ contextHandoffId: null,
+ },
+ },
+ ],
+ });
+ });
+
+const cardOf = (a: Laptop) =>
+ a.orchestrator
+ .getThreadProjection(threadId)
+ .pipe(
+ Effect.map((projection) => projection.turnItems.find((item) => item.type === "link_request")),
+ );
+
+/** The open card the agent's call left, as the user's client sees it. */
+const pendingCard = (a: Laptop) =>
+ Effect.gen(function* () {
+ const card = yield* cardOf(a);
+ expect(card).toMatchObject({ status: "waiting", linkStatus: "pending" });
+ return card as Extract<NonNullable<typeof card>, { readonly type: "link_request" }>;
+ });
+
+/** The outcome notifications the thread received: what the agent reads and the user sees. */
+const outcomeMessages = (a: Laptop) =>
+ a.orchestrator.getThreadProjection(threadId).pipe(
+ Effect.map((projection) => ({
+ messages: projection.messages.filter((message) => message.notification !== undefined),
+ items: projection.turnItems.filter((item) => item.type === "notification"),
+ })),
+ );
+
+/** The agent's turn ends; the card outlives it. */
+const endRun = (a: Laptop) =>
+ Effect.gen(function* () {
+ const projection = yield* a.orchestrator.getThreadProjection(threadId);
+ const run = projection.runs.find((candidate) => candidate.id === runId)!;
+ const now = yield* DateTime.now;
+ yield* a.sink.write({
+ commandId: CommandId.make("command:end-run:laptop"),
+ events: [
+ {
+ id: EventId.make("event:end-run"),
+ type: "run.updated",
+ threadId,
+ runId,
+ nodeId: rootNode,
+ providerInstanceId: instanceId,
+ occurredAt: now,
+ payload: { ...run, status: "completed", completedAt: now },
+ },
+ ],
+ });
+ });
+
+/** A steer restarts the agent's turn: its run gets a new root node. */
+const restartRun = (a: Laptop) =>
+ Effect.gen(function* () {
+ const projection = yield* a.orchestrator.getThreadProjection(threadId);
+ const run = projection.runs.find((candidate) => candidate.id === runId)!;
+ const node = projection.nodes.find((candidate) => candidate.id === rootNode)!;
+ const restarted = NodeId.make("node:laptop:root:2");
+ const now = yield* DateTime.now;
+ yield* a.sink.write({
+ commandId: CommandId.make("command:restart-run:laptop"),
+ events: [
+ {
+ id: EventId.make("event:restart-node"),
+ type: "node.updated",
+ threadId,
+ runId,
+ nodeId: restarted,
+ driver,
+ providerInstanceId: instanceId,
+ occurredAt: now,
+ payload: { ...node, id: restarted, rootNodeId: restarted, startedAt: now },
+ },
+ {
+ id: EventId.make("event:restart-run"),
+ type: "run.updated",
+ threadId,
+ runId,
+ nodeId: restarted,
+ providerInstanceId: instanceId,
+ occurredAt: now,
+ payload: { ...run, rootNodeId: restarted },
+ },
+ ],
+ });
+ });
+
+/** What `request` records for a new card, as if it read the run before anything changed. */
+const recordPendingCard = (a: Laptop, key: string) =>
+ a.orchestrator.dispatch({
+ type: "link_request.record",
+ commandId: CommandId.make(`command:pending:${key}`),
+ threadId,
+ runId,
+ nodeId: rootNode,
+ turnItemId: TurnItemId.make(`turn-item:link-request:${key}`),
+ reason: "",
+ linkStatus: "pending",
+ });
+
+/**
+ * Every row of every table in the laptop's database, as text, to scan for
+ * anything leaked: events, projections, receipts and outbox alike.
+ */
+const storedText = (a: Laptop) =>
+ Effect.gen(function* () {
+ const tables = yield* a.sql<{ name: string }>`
+ SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
+ `;
+ const rows = yield* Effect.forEach(tables, ({ name }) =>
+ a.sql.unsafe<Record<string, unknown>>(`SELECT * FROM "${name}"`),
+ );
+ const text = rows
+ .flat()
+ .map((row) => JSON.stringify(row))
+ .join("\n");
+ // The scan saw the card itself, so it read what the thread recorded.
+ expect(text).toContain("link_request");
+ return text;
+ });
+
+const errorOf = (result: McpSchema.CallToolResult) => {
+ const text = result.content[0];
+ return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined;
+};
+
+/** Runs `effect` a year from now, when every link made today has expired. */
+const afterLinksExpire = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
+ Effect.gen(function* () {
+ const clock = yield* Clock.Clock;
+ const ahead = Duration.days(365);
+ const later = () => clock.currentTimeMillisUnsafe() + Duration.toMillis(ahead);
+ const laterNanos = () => clock.currentTimeNanosUnsafe() + Duration.toNanosUnsafe(ahead);
+ return yield* effect.pipe(
+ Effect.provideService(Clock.Clock, {
+ currentTimeMillisUnsafe: later,
+ currentTimeMillis: Effect.sync(later),
+ currentTimeNanosUnsafe: laterNanos,
+ currentTimeNanos: Effect.sync(laterNanos),
+ monotonicTimeNanosUnsafe: () => clock.monotonicTimeNanosUnsafe(),
+ monotonicTimeNanos: clock.monotonicTimeNanos,
+ sleep: (duration) => clock.sleep(duration),
+ }),
+ );
+ });
+
+const withBoth = <A, E, R>(body: (a: Laptop, b: ServedPeer) => Effect.Effect<A, E, R>) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const b = yield* serveBox;
+ const a = yield* makeLaptop;
+ return yield* body(a, b);
+ }),
+ ).pipe(Effect.provide(NodeHttpServer.layerTest));
+
+it.live("the agent asks without waiting, and the user links the box after its turn ended", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ const asked = yield* a.call({
+ url: b.url,
+ reason: "Run the suite on the box.",
+ requestedAccess: "approval-required",
+ clientRequestId: "link-box",
+ });
+ const card = yield* pendingCard(a);
+ // The call returns at once: no tool call outlives a provider's timeout.
+ expect(asked.isError).toBe(false);
+ expect(asked.structuredContent).toEqual({ status: "pending", turnItemId: card.id });
+ // The card names the box, found by asking its address.
+ expect(card).toMatchObject({
+ url: b.url,
+ reason: "Run the suite on the box.",
+ environmentId: box.environmentId,
+ label: "Box",
+ requestedAccess: "approval-required",
+ });
+ // The agent waits on the user, so the thread asks for input.
+ expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject(
+ { kind: "user_input" },
+ );
+
+ // The agent ends its turn; the card stays answerable, and the thread still asks.
+ yield* endRun(a);
+ expect(yield* cardOf(a)).toMatchObject({ status: "waiting", linkStatus: "pending" });
+ expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject(
+ { kind: "user_input" },
+ );
+ expect(
+ ProjectionStore.threadShellFromProjection(
+ yield* a.orchestrator.getThreadProjection(threadId),
+ ).pendingRuntimeRequest,
+ ).toMatchObject({ kind: "user_input" });
+ expect(yield* a.projections.getSettlementCandidates(threadId)).toEqual([]);
+
+ // The user's client mints a code on the box and picks more than the agent suggested.
+ const pairing = yield* b.auth.issuePairingCredential();
+ yield* a.requests.answer({
+ threadId,
+ turnItemId: card.id,
+ answer: { type: "link", urls: [b.url], access: "auto", pairingCode: pairing.credential },
+ });
+
+ const link = yield* a.links.get(box.environmentId);
+ expect(Option.getOrUndefined(link)?.access).toBe("auto");
+ expect(yield* cardOf(a)).toMatchObject({
+ status: "completed",
+ linkStatus: "linked",
+ linkedEnvironmentId: box.environmentId,
+ linkedLabel: "Box",
+ linkedAccess: "auto",
+ });
+ expect((yield* b.linkedSessions).length).toBe(1);
+
+ // The agent hears it as a notification in its thread, not a user message.
+ const { messages, items } = yield* outcomeMessages(a);
+ expect(messages).toHaveLength(1);
+ expect(messages[0]).toMatchObject({
+ role: "user",
+ createdBy: "agent",
+ creationSource: "server",
+ notification: { outcome: "completed", summary: "Linked Box" },
+ });
+ expect(messages[0]!.text).toContain(box.environmentId);
+ expect(messages[0]!.text).toContain("auto");
+ expect(items).toHaveLength(1);
+ expect(items[0]).toMatchObject({ type: "notification", summary: "Linked Box" });
+
+ // The code appears in nothing the thread recorded or the agent received.
+ expect(yield* storedText(a)).not.toContain(pairing.credential);
+
+ // A card is answered once.
+ const again = yield* a.requests
+ .answer({ threadId, turnItemId: card.id, answer: { type: "decline" } })
+ .pipe(Effect.flip);
+ expect(again.reason).toBe("already_answered");
+
+ // A retry that lost the first result gets the card's outcome, and records nothing.
+ const before = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.length;
+ const retried = yield* a.call({ url: b.url, clientRequestId: "link-box" });
+ expect(retried.structuredContent).toEqual({
+ status: "linked",
+ environmentId: box.environmentId,
+ label: "Box",
+ access: "auto",
+ });
+ expect((yield* a.orchestrator.getThreadProjection(threadId)).turnItems).toHaveLength(before);
+ expect((yield* outcomeMessages(a)).messages).toHaveLength(1);
+ }),
+ ),
+);
+
+it.live("a retry of a pending request returns pending and shows no second card", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ const first = yield* a.call({ url: b.url, clientRequestId: "link-box" });
+ const retried = yield* a.call({ url: b.url, clientRequestId: "link-box" });
+ expect(retried.structuredContent).toEqual(first.structuredContent);
+ const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
+ (item) => item.type === "link_request",
+ );
+ expect(cards).toHaveLength(1);
+ }),
+ ),
+);
+
+it.live("a later provider session reusing a clientRequestId gets a card of its own", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ const first = yield* a.call({ url: b.url, clientRequestId: "link" });
+ const later = yield* a.call(
+ { environmentId: box.environmentId, clientRequestId: "link" },
+ {
+ ...scope,
+ requestNamespace: "provider-session:laptop-2",
+ thread: { ...scope.thread!, providerSessionId: "provider-session:laptop-2" },
+ },
+ );
+ expect(later.structuredContent).toMatchObject({ status: "pending" });
+ expect(later.structuredContent).not.toEqual(first.structuredContent);
+ const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
+ (item) => item.type === "link_request",
+ );
+ expect(cards).toHaveLength(2);
+ }),
+ ),
+);
+
+it.live("a declined request links nothing and tells the agent", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ yield* a.call({ url: b.url });
+ const card = yield* pendingCard(a);
+ yield* a.requests.answer({ threadId, turnItemId: card.id, answer: { type: "decline" } });
+ expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
+ expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "declined" });
+ const { messages } = yield* outcomeMessages(a);
+ expect(messages).toHaveLength(1);
+ expect(messages[0]).toMatchObject({
+ notification: { outcome: "cancelled", summary: "Declined to link Box" },
+ });
+ expect(messages[0]!.text).toContain("declined");
+ }),
+ ),
+);
+
+it.live("stopping the thread closes its open card, which then takes no answer", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ yield* a.call({ url: b.url });
+ const card = yield* pendingCard(a);
+ yield* a.orchestrator.dispatch({
+ type: "thread.stop",
+ commandId: CommandId.make("command:stop:laptop"),
+ threadId,
+ });
+ expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
+ const late = yield* a.requests
+ .answer({
+ threadId,
+ turnItemId: card.id,
+ answer: { type: "link", urls: [b.url], access: "auto", pairingCode: "late-code" },
+ })
+ .pipe(Effect.flip);
+ expect(late.reason).toBe("already_answered");
+ expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
+ // An answer already linking when Stop landed keeps the card closed and wakes nobody.
+ yield* a.orchestrator.dispatch({
+ type: "link_request.record",
+ commandId: CommandId.make("command:late-answer:laptop"),
+ threadId,
+ runId,
+ nodeId: rootNode,
+ turnItemId: card.id,
+ url: card.url,
+ reason: card.reason,
+ linkStatus: "declined",
+ wake: {
+ messageId: MessageId.make("message:late-answer"),
+ text: "The user declined.",
+ notification: {
+ source: { kind: "background_task" },
+ outcome: "cancelled",
+ summary: "Declined",
+ },
+ },
+ });
+ expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
+ // The user stopped the thread: nothing wakes the agent.
+ expect((yield* outcomeMessages(a)).messages).toHaveLength(0);
+ }),
+ ),
+);
+
+it.live("a request that read the run before Stop shows no card once Stop lands", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ yield* a.call({ url: b.url });
+ const open = yield* pendingCard(a);
+ yield* a.orchestrator.dispatch({
+ type: "thread.stop",
+ commandId: CommandId.make("command:stop:laptop"),
+ threadId,
+ });
+ const late = yield* recordPendingCard(a, "after-stop").pipe(Effect.flip);
+ expect(String(late.cause)).toContain("not active");
+ const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
+ (item) => item.type === "link_request",
+ );
+ expect(cards.map((card) => card.id)).toEqual([open.id]);
+ }),
+ ),
+);
+
+it.live("a card shows up only while its run is going, and takes an answer after", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ yield* a.call({ url: b.url });
+ const card = yield* pendingCard(a);
+ yield* endRun(a);
+ const late = yield* recordPendingCard(a, "after-end").pipe(Effect.flip);
+ expect(String(late.cause)).toContain("not active");
+ yield* a.requests.answer({ threadId, turnItemId: card.id, answer: { type: "decline" } });
+ expect(yield* cardOf(a)).toMatchObject({ linkStatus: "declined" });
+ }),
+ ),
+);
+
+it.live("a steer that restarts the turn leaves its open card answerable", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ yield* a.call({ url: b.url });
+ const card = yield* pendingCard(a);
+ yield* restartRun(a);
+ const pairing = yield* b.auth.issuePairingCredential();
+ yield* a.requests.answer({
+ threadId,
+ turnItemId: card.id,
+ answer: { type: "link", urls: [b.url], access: "auto", pairingCode: pairing.credential },
+ });
+ // The card keeps the node it was asked from, and the agent hears the answer.
+ expect(yield* cardOf(a)).toMatchObject({
+ linkStatus: "linked",
+ nodeId: rootNode,
+ linkedEnvironmentId: box.environmentId,
+ });
+ expect((yield* outcomeMessages(a)).messages).toHaveLength(1);
+ }),
+ ),
+);
+
+it.live("a slow machine holds up only its own card's answer", () =>
+ withBoth((a, b) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ // A machine that takes the descriptor request and answers when the test says.
+ const reached = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const slow = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest));
+ const server = Context.get(slow, HttpServer.HttpServer);
+ yield* server.serve(
+ Deferred.succeed(reached, undefined).pipe(
+ Effect.andThen(Deferred.await(release)),
+ Effect.as(HttpServerResponse.empty({ status: 404 })),
+ ),
+ );
+ if (server.address._tag === "UnixPathAddress") return yield* Effect.die("expected TCP");
+ const slowUrl = `http://127.0.0.1:${server.address.port}`;
+
+ yield* seedThread(a);
+ // Recorded directly: asking would probe the slow machine before the answer does.
+ const slowCard = { id: TurnItemId.make("turn-item:link-request:slow") };
+ yield* a.orchestrator.dispatch({
+ type: "link_request.record",
+ commandId: CommandId.make("command:pending:slow"),
+ threadId,
+ runId,
+ nodeId: rootNode,
+ turnItemId: slowCard.id,
+ url: slowUrl,
+ reason: "",
+ linkStatus: "pending",
+ });
+ yield* a.call({ url: b.url, clientRequestId: "box" });
+ const boxCard = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.find(
+ (item) => item.type === "link_request" && item.url === b.url,
+ )!;
+
+ const slowAnswer = yield* a.requests
+ .answer({
+ threadId,
+ turnItemId: slowCard.id,
+ answer: { type: "link", urls: [slowUrl], access: "auto", pairingCode: "code" },
+ })
+ .pipe(Effect.forkChild);
+ yield* Deferred.await(reached);
+
+ // While the slow machine holds its card, the user answers the other one.
+ yield* a.requests.answer({ threadId, turnItemId: boxCard.id, answer: { type: "decline" } });
+ const items = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems;
+ expect(items.find((item) => item.id === boxCard.id)).toMatchObject({
+ linkStatus: "declined",
+ });
+ expect(items.find((item) => item.id === slowCard.id)).toMatchObject({
+ linkStatus: "pending",
+ });
+
+ yield* Deferred.succeed(release, undefined);
+ yield* Fiber.join(slowAnswer);
+ const failed = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.find(
+ (item) => item.id === slowCard.id,
+ );
+ expect(failed).toMatchObject({ linkStatus: "failed" });
+ }),
+ ),
+ ),
+);
+
+it.live("archiving the thread closes its open card", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ yield* a.call({ url: b.url });
+ yield* pendingCard(a);
+ yield* endRun(a);
+ yield* a.orchestrator.dispatch({
+ type: "thread.archive",
+ commandId: CommandId.make("command:archive:laptop"),
+ threadId,
+ });
+ expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
+ }),
+ ),
+);
+
+it.live("a code the box refuses fails the request with its reason, and links nothing", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ yield* a.call({ url: b.url });
+ const card = yield* pendingCard(a);
+ yield* a.requests.answer({
+ threadId,
+ turnItemId: card.id,
+ answer: {
+ type: "link",
+ urls: [b.url],
+ access: "auto",
+ pairingCode: "not-a-real-code",
+ },
+ });
+ const failed = yield* cardOf(a);
+ expect(failed).toMatchObject({ status: "failed", linkStatus: "failed" });
+ const reason = failed?.type === "link_request" ? failed.failure : undefined;
+ expect(reason?.length).toBeGreaterThan(0);
+ const { messages } = yield* outcomeMessages(a);
+ expect(messages[0]).toMatchObject({ notification: { outcome: "failed" } });
+ expect(messages[0]!.text).toContain(reason);
+ expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
+ expect(yield* storedText(a)).not.toContain("not-a-real-code");
+ }),
+ ),
+);
+
+it.live("an agent below full access may not ask, and no card is shown", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a, "auto");
+ const refused = yield* a.call({ url: b.url });
+ expect(errorOf(refused)).toMatchObject({ code: "capability_denied" });
+ expect(yield* cardOf(a)).toBeUndefined();
+ }),
+ ),
+);
+
+it.live("work another environment's link started may not ask, and no card is shown", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a, "full-access", { sessionId: "session:desk", label: "T3 Code · Desk" });
+ const refused = yield* a.call({ url: b.url });
+ expect(errorOf(refused)).toMatchObject({ code: "capability_denied" });
+ expect(errorOf(refused).message).toContain("T3 Code · Desk");
+ expect(yield* cardOf(a)).toBeUndefined();
+ }),
+ ),
+);
+
+it.live(
+ "an agent that names no machine leaves the pick to the user, who links one by its addresses",
+ () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ const asked = yield* a.call({ reason: "Delegate the build to the vps.", hint: "vps" });
+ expect(asked.structuredContent).toMatchObject({ status: "pending" });
+ const card = yield* pendingCard(a);
+ expect(card).toMatchObject({ reason: "Delegate the build to the vps.", hint: "vps" });
+ expect(card.url).toBeUndefined();
+ expect(card.environmentId).toBeUndefined();
+
+ // The user picks the box; their client knows a stale address for it first.
+ const pairing = yield* b.auth.issuePairingCredential();
+ yield* a.requests.answer({
+ threadId,
+ turnItemId: card.id,
+ answer: {
+ type: "link",
+ environmentId: box.environmentId,
+ label: "Box",
+ urls: ["http://127.0.0.1:9", b.url],
+ access: "auto",
+ pairingCode: pairing.credential,
+ },
+ });
+ expect(Option.getOrUndefined(yield* a.links.get(box.environmentId))).toMatchObject({
+ urls: [b.url],
+ access: "auto",
+ });
+ expect(yield* cardOf(a)).toMatchObject({
+ linkStatus: "linked",
+ linkedEnvironmentId: box.environmentId,
+ });
+ expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("linked Box");
+ }),
+ ),
+);
+
+it.live("naming a machine that is already linked returns the link at once, with no card", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ const pairing = yield* b.auth.issuePairingCredential();
+ yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
+ const asked = yield* a.call({ environmentId: box.environmentId });
+ expect(asked.structuredContent).toEqual({
+ status: "linked",
+ environmentId: box.environmentId,
+ label: "Box",
+ access: "auto",
+ });
+ expect(yield* cardOf(a)).toBeUndefined();
+
+ // Not both: the address could name another machine than the id.
+ const both = yield* a.call({ environmentId: box.environmentId, url: b.url });
+ expect(errorOf(both)).toMatchObject({ code: "invalid_request" });
+ }),
+ ),
+);
+
+it.live("a link that expired goes through the card, so the user can link it again", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ yield* linkTo(a.links, b, "read-only");
+ const asked = yield* a.call({ environmentId: box.environmentId }).pipe(afterLinksExpire);
+ expect(asked.structuredContent).toMatchObject({ status: "pending" });
+ const card = yield* pendingCard(a);
+
+ // Keeping the expired link is no answer: the card fails and says why.
+ yield* a.requests
+ .answer({
+ threadId,
+ turnItemId: card.id,
+ answer: { type: "use-existing", environmentId: box.environmentId },
+ })
+ .pipe(afterLinksExpire);
+ expect(yield* cardOf(a)).toMatchObject({ linkStatus: "failed" });
+ expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("expired");
+ }),
+ ),
+);
+
+it.live("a link made before links were fenced goes through the card, as an expired one", () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ yield* linkTo(a.links, b);
+ yield* a.linksSql`UPDATE peer_environment_links SET fenced = 0`;
+ const asked = yield* a.call({ environmentId: box.environmentId });
+ expect(asked.structuredContent).toMatchObject({ status: "pending" });
+ yield* pendingCard(a);
+ }),
+ ),
+);
+
+it.live(
+ "a card for a machine named by id keeps it, and the user may keep a link it already has",
+ () =>
+ withBoth((a, b) =>
+ Effect.gen(function* () {
+ yield* seedThread(a);
+ yield* a.call({ environmentId: box.environmentId });
+ const card = yield* pendingCard(a);
+ expect(card.environmentId).toBe(box.environmentId);
+ // Linked from Settings meanwhile; the card answers with that link.
+ const pairing = yield* b.auth.issuePairingCredential();
+ yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "read-only" });
+ yield* a.requests.answer({
+ threadId,
+ turnItemId: card.id,
+ answer: { type: "use-existing", environmentId: box.environmentId },
+ });
+ expect(yield* cardOf(a)).toMatchObject({
+ linkStatus: "linked",
+ linkedAccess: "read-only",
+ });
+ expect((yield* b.linkedSessions).length).toBe(1);
+ }),
+ ),
+);
diff --git a/apps/server/src/peer/PeerLinkRequests.ts b/apps/server/src/peer/PeerLinkRequests.ts
new file mode 100644
index 00000000000..12a96831d3d
--- /dev/null
+++ b/apps/server/src/peer/PeerLinkRequests.ts
@@ -0,0 +1,412 @@
+/**
+ * Links an agent asks the user to make. The user picks the machine and access in a card, and
+ * their client answers with its addresses and a pairing code that goes straight to
+ * `PeerLinks.link`, never into the transcript or the agent's context. Asking does not wait
+ * (provider CLIs abandon a long tool call): the answer reaches the agent as a notification.
+ */
+import {
+ CommandId,
+ type EnvironmentId,
+ MessageId,
+ type NodeId,
+ type OrchestrationV2Notification,
+ type OrchestrationV2TurnItem,
+ type OrchestratorMcpEnvironmentLinkInput,
+ type OrchestratorMcpEnvironmentLinkResult,
+ OrchestratorMcpFailure,
+ type PeerLink,
+ PeerLinkError,
+ PeerLinkRequestError,
+ type PeerLinkRequestAnswerInput,
+ type RunId,
+ type ThreadId,
+ TurnItemId,
+} from "@t3tools/contracts";
+import * as Context from "effect/Context";
+import * as Crypto from "effect/Crypto";
+import * as DateTime from "effect/DateTime";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as KeyedLock from "@t3tools/shared/KeyedLock";
+
+import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
+import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
+import * as PeerLinks from "./PeerLinks.ts";
+
+type LinkRequestItem = Extract<OrchestrationV2TurnItem, { readonly type: "link_request" }>;
+
+/** The request as it was asked, which every update of its card repeats. */
+type LinkRequestAsk = Pick<
+ LinkRequestItem,
+ "id" | "threadId" | "url" | "reason" | "environmentId" | "label" | "hint" | "requestedAccess"
+> & { readonly runId: RunId; readonly nodeId: NodeId };
+
+/** The notification that tells the agent how its card ended. */
+type LinkRequestWake = {
+ readonly messageId: MessageId;
+ readonly text: string;
+ readonly notification: OrchestrationV2Notification;
+};
+
+/** What a card update may change. */
+type LinkRequestOutcome = Pick<
+ LinkRequestItem,
+ "linkStatus" | "linkedEnvironmentId" | "linkedLabel" | "linkedAccess" | "failure"
+>;
+
+const errorMessage = (error: unknown) =>
+ error instanceof Error ? error.message : typeof error === "string" ? error : "unknown error";
+
+export class PeerLinkRequests extends Context.Service<
+ PeerLinkRequests,
+ {
+ /**
+ * Shows a link card in the calling thread and returns at once. A retry
+ * with the same clientRequestId returns the card's current outcome.
+ */
+ readonly request: (
+ scope: McpInvocationContext.McpInvocationScope,
+ input: OrchestratorMcpEnvironmentLinkInput,
+ ) => Effect.Effect<OrchestratorMcpEnvironmentLinkResult, OrchestratorMcpFailure>;
+ /**
+ * Answers a pending card and tells the agent. Linking uses the pairing
+ * code once; a link the other environment refuses closes the card as
+ * failed, with its reason.
+ */
+ readonly answer: (
+ input: PeerLinkRequestAnswerInput,
+ ) => Effect.Effect<void, PeerLinkRequestError>;
+ }
+>()("t3/peer/PeerLinkRequests") {}
+
+const make = Effect.gen(function* () {
+ const threadManagement = yield* ThreadManagementService.ThreadManagementService;
+ const peerLinks = yield* PeerLinks.PeerLinks;
+ const crypto = yield* Crypto.Crypto;
+
+ const readCard = (threadId: ThreadId, turnItemId: TurnItemId) =>
+ threadManagement
+ .getThreadRecords(threadId, ["turnItems"], {
+ turnItemTypes: ["link_request"],
+ messageRoles: [],
+ })
+ .pipe(
+ Effect.map((records) => {
+ const item = records.turnItems.find((candidate) => candidate.id === turnItemId);
+ // A deleted thread's cards went with it.
+ return item?.type === "link_request" && records.thread.deletedAt === null
+ ? item
+ : undefined;
+ }),
+ );
+
+ /**
+ * The stored link to `environmentId`, or nothing once it has expired: an
+ * expired link needs a new pairing code, which only the card asks for.
+ */
+ const usableLink = (environmentId: EnvironmentId) =>
+ Effect.all([peerLinks.get(environmentId), DateTime.now]).pipe(
+ Effect.map(([linked, now]) =>
+ Option.filter(linked, (link) => DateTime.isGreaterThan(link.expiresAt, now)),
+ ),
+ );
+
+ const record = (
+ card: LinkRequestAsk,
+ outcome: LinkRequestOutcome,
+ commandId: CommandId,
+ wake?: LinkRequestWake,
+ ) =>
+ threadManagement.dispatch({
+ type: "link_request.record",
+ commandId,
+ threadId: card.threadId,
+ runId: card.runId,
+ nodeId: card.nodeId,
+ turnItemId: card.id,
+ ...(card.url === undefined ? {} : { url: card.url }),
+ reason: card.reason,
+ ...(card.environmentId === undefined ? {} : { environmentId: card.environmentId }),
+ ...(card.label === undefined ? {} : { label: card.label }),
+ ...(card.hint === undefined ? {} : { hint: card.hint }),
+ ...(card.requestedAccess === undefined ? {} : { requestedAccess: card.requestedAccess }),
+ ...outcome,
+ ...(wake === undefined ? {} : { wake }),
+ });
+
+ const request: PeerLinkRequests["Service"]["request"] = Effect.fn("PeerLinkRequests.request")(
+ function* (scope, input) {
+ // The card is shown in, and answered from, the caller's own thread.
+ const threadScope = yield* McpInvocationContext.requireThreadScope(
+ scope,
+ "t3_environment_link",
+ );
+ const threadId = threadScope.thread.threadId;
+ const unreadable = (error: unknown) =>
+ new OrchestratorMcpFailure({
+ code: "orchestration_error",
+ message: `Unable to read the link request: ${errorMessage(error)}`,
+ });
+ if (input.url !== undefined && input.environmentId !== undefined) {
+ return yield* new OrchestratorMcpFailure({
+ code: "invalid_request",
+ message:
+ "Pass either environmentId or url, not both. Pass neither to let the user pick the machine.",
+ });
+ }
+ // A machine already linked needs no card: the agent can use it now.
+ if (input.environmentId !== undefined) {
+ const linked = yield* usableLink(input.environmentId).pipe(
+ Effect.mapError(
+ (error) =>
+ new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
+ ),
+ );
+ if (Option.isSome(linked)) {
+ return {
+ status: "linked",
+ environmentId: linked.value.environmentId,
+ label: linked.value.label,
+ access: linked.value.access,
+ } as const;
+ }
+ }
+ const key = input.clientRequestId ?? (yield* crypto.randomUUIDv4().pipe(Effect.orDie));
+ // Turn item ids are global; scope the key to this thread and provider
+ // session, since a later session may reuse it. A retry with the same
+ // clientRequestId finds this card and records nothing.
+ const turnItemId = TurnItemId.make(
+ `turn-item:link-request:${encodeURIComponent(threadId)}:${encodeURIComponent(scope.requestNamespace)}:${encodeURIComponent(key)}`,
+ );
+ if (input.clientRequestId !== undefined) {
+ const existing = yield* readCard(threadId, turnItemId).pipe(Effect.mapError(unreadable));
+ if (existing !== undefined) return resultOf(existing);
+ }
+ const parent = yield* threadManagement
+ .getThreadRecords(threadId, ["runs"], { messageRoles: [] })
+ .pipe(Effect.mapError(unreadable));
+ const run = ThreadManagementService.latestActiveRun(parent);
+ if (
+ run === undefined ||
+ run.rootNodeId === null ||
+ run.providerInstanceId !== threadScope.thread.providerInstanceId
+ ) {
+ return yield* new OrchestratorMcpFailure({
+ code: "parent_not_active",
+ message:
+ "Asking to link an environment requires an active run owned by this MCP provider session.",
+ });
+ }
+ // Best effort: the card names the machine at an address the agent was
+ // given, and the client finds it by id.
+ const peer = input.url === undefined ? Option.none() : yield* peerLinks.describe(input.url);
+ yield* record(
+ {
+ id: turnItemId,
+ threadId,
+ runId: run.id,
+ nodeId: run.rootNodeId,
+ ...(input.url === undefined ? {} : { url: input.url }),
+ reason: input.reason ?? "",
+ ...(Option.isSome(peer)
+ ? { environmentId: peer.value.environmentId, label: peer.value.label }
+ : input.environmentId === undefined
+ ? {}
+ : { environmentId: input.environmentId }),
+ ...(input.hint === undefined ? {} : { hint: input.hint }),
+ ...(input.requestedAccess === undefined
+ ? {}
+ : { requestedAccess: input.requestedAccess }),
+ },
+ { linkStatus: "pending" },
+ CommandId.make(
+ `command:mcp:${encodeURIComponent(scope.requestNamespace)}:link-pending:${encodeURIComponent(key)}`,
+ ),
+ ).pipe(
+ Effect.mapError(
+ (error) =>
+ new OrchestratorMcpFailure({
+ code: "orchestration_error",
+ message: `Could not record the link request: ${errorMessage(error)}`,
+ }),
+ ),
+ );
+ return pendingResult(turnItemId);
+ },
+ Effect.withSpan("PeerLinkRequests.request"),
+ );
+
+ const linkedOutcome = (linked: PeerLink): LinkRequestOutcome => ({
+ linkStatus: "linked",
+ linkedEnvironmentId: linked.environmentId,
+ linkedLabel: linked.label,
+ linkedAccess: linked.access,
+ });
+
+ /** Links the machine the user picked, or finds the link they chose to keep. */
+ const answerOutcome = (
+ answer: PeerLinkRequestAnswerInput["answer"],
+ ): Effect.Effect<LinkRequestOutcome> => {
+ switch (answer.type) {
+ case "decline":
+ return Effect.succeed({ linkStatus: "declined" });
+ case "use-existing":
+ return usableLink(answer.environmentId).pipe(
+ Effect.flatMap(
+ Option.match({
+ onNone: () =>
+ Effect.fail(
+ new PeerLinkError({
+ reason: "unknown_link",
+ message:
+ "That environment is no longer linked here, or its link expired. Link it again.",
+ }),
+ ),
+ onSome: (linked) => Effect.succeed(linkedOutcome(linked)),
+ }),
+ ),
+ Effect.catch((error) =>
+ Effect.succeed<LinkRequestOutcome>({ linkStatus: "failed", failure: error.message }),
+ ),
+ );
+ case "link": {
+ const [url, ...alternateUrls] = answer.urls;
+ return peerLinks
+ .link({
+ url,
+ ...(alternateUrls.length === 0 ? {} : { alternateUrls }),
+ pairingCode: answer.pairingCode,
+ access: answer.access,
+ ...(answer.environmentId === undefined
+ ? {}
+ : { expectedEnvironmentId: answer.environmentId }),
+ ...(answer.label === undefined ? {} : { expectedLabel: answer.label }),
+ })
+ .pipe(
+ Effect.map(linkedOutcome),
+ Effect.catch((error) =>
+ Effect.succeed<LinkRequestOutcome>({ linkStatus: "failed", failure: error.message }),
+ ),
+ );
+ }
+ }
+ };
+
+ // One answer per card at a time: two answers racing on one card must not
+ // both link. Other cards go on while a slow peer holds one.
+ const answerLocks = yield* KeyedLock.make<TurnItemId>();
+ const answer: PeerLinkRequests["Service"]["answer"] = Effect.fn("PeerLinkRequests.answer")(
+ function* (input) {
+ yield* Effect.annotateCurrentSpan({
+ "orchestration_v2.thread_id": input.threadId,
+ "link_request.answer": input.answer.type,
+ });
+ const card = yield* readCard(input.threadId, input.turnItemId).pipe(
+ Effect.mapError((cause) => new PeerLinkRequestError({ reason: "load_failed", cause })),
+ );
+ if (card === undefined || card.runId === null || card.nodeId === null) {
+ return yield* new PeerLinkRequestError({ reason: "not_found" });
+ }
+ // Any time while the card is open: the agent hears the answer as a
+ // notification, whether or not its run is still going.
+ if (card.linkStatus !== "pending") {
+ return yield* new PeerLinkRequestError({ reason: "already_answered" });
+ }
+ const outcome = yield* answerOutcome(input.answer);
+ // If Stop closed the card while linking, the card keeps that; the link
+ // itself stands and Settings lists it.
+ yield* record(
+ { ...card, runId: card.runId, nodeId: card.nodeId },
+ outcome,
+ CommandId.make(`link-request:${card.id}:${outcome.linkStatus}`),
+ {
+ messageId: MessageId.make(`message:link-request:${card.id}`),
+ ...outcomeNotice(card, outcome),
+ },
+ ).pipe(
+ Effect.mapError((cause) => new PeerLinkRequestError({ reason: "record_failed", cause })),
+ );
+ },
+ (effect, input) =>
+ effect.pipe(
+ (effect) => answerLocks.withLock(input.turnItemId, effect),
+ Effect.withSpan("PeerLinkRequests.answer"),
+ ),
+ );
+
+ return PeerLinkRequests.of({ request, answer });
+});
+
+const pendingResult = (turnItemId: TurnItemId): OrchestratorMcpEnvironmentLinkResult => ({
+ status: "pending",
+ turnItemId,
+});
+
+/** What a retry hears: the card's outcome, without anything the user typed. */
+const resultOf = (card: LinkRequestItem): OrchestratorMcpEnvironmentLinkResult => {
+ switch (card.linkStatus) {
+ case "pending":
+ return pendingResult(card.id);
+ case "linked":
+ return {
+ status: "linked",
+ environmentId: card.linkedEnvironmentId!,
+ label: card.linkedLabel ?? linkTarget(card),
+ access: card.linkedAccess!,
+ };
+ case "failed":
+ return { status: "failed", message: card.failure ?? "The link could not be made." };
+ case "declined":
+ case "cancelled":
+ return { status: card.linkStatus };
+ }
+};
+
+/** What the agent's words call the target: its name, its address, or the user's pick. */
+const linkTarget = (card: Pick<LinkRequestItem, "url" | "label" | "environmentId">) =>
+ card.label ?? card.url ?? card.environmentId ?? "a machine";
+
+/**
+ * The notification an answer sends the agent: what the card says, and what
+ * to do next. It carries the outcome only, never the pairing code.
+ */
+const outcomeNotice = (
+ card: Pick<LinkRequestItem, "url" | "label" | "environmentId">,
+ outcome: LinkRequestOutcome,
+): Omit<LinkRequestWake, "messageId"> => {
+ const target = linkTarget(card);
+ switch (outcome.linkStatus) {
+ case "linked": {
+ const label = outcome.linkedLabel ?? target;
+ return {
+ text: `The user linked ${label} with ${outcome.linkedAccess} access. Pass environmentId ${outcome.linkedEnvironmentId} to act there.`,
+ notification: {
+ source: { kind: "background_task" },
+ outcome: "completed",
+ summary: `Linked ${label}`,
+ },
+ };
+ }
+ case "failed":
+ return {
+ text: `Linking ${target} failed: ${outcome.failure ?? "the other environment refused"}. Call t3_environment_link again if the user still wants it.`,
+ notification: {
+ source: { kind: "background_task" },
+ outcome: "failed",
+ summary: `Could not link ${target}`,
+ },
+ };
+ default:
+ return {
+ text: `The user declined to link ${target}.`,
+ notification: {
+ source: { kind: "background_task" },
+ outcome: "cancelled",
+ summary: `Declined to link ${target}`,
+ },
+ };
+ }
+};
+
+export const layer = Layer.effect(PeerLinkRequests, make);
diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts
index 0e27c19b5d6..2d6a0c267e3 100644
--- a/apps/server/src/peer/PeerLinks.test.ts
+++ b/apps/server/src/peer/PeerLinks.test.ts
@@ -19,6 +19,7 @@ import {
HttpServerResponse,
} from "effect/http";
+import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as McpHttpServer from "../mcp/McpHttpServer.ts";
import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
import * as McpToolAccess from "../mcp/McpToolAccess.ts";
@@ -73,8 +74,11 @@ const serveB = (descriptor: ExecutionEnvironmentDescriptor) =>
servePeer(descriptor, McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers));
/** Environment A, which links to B. */
-const makeA = (descriptor: ExecutionEnvironmentDescriptor) =>
- layerLinkingEnvironment(descriptor).pipe(
+const makeA = (
+ descriptor: ExecutionEnvironmentDescriptor,
+ secrets?: typeof ServerSecretStore.layer,
+) =>
+ layerLinkingEnvironment(descriptor, secrets).pipe(
Layer.build,
Effect.map((context) => ({
links: Context.get(context, PeerLinks.PeerLinks),
@@ -100,6 +104,12 @@ const probe = (
const linkedSessions = (b: ServedPeer) => b.linkedSessions;
+/** Another environment on a socket of its own, answering as `descriptor`. */
+const serveApart = (descriptor: ExecutionEnvironmentDescriptor) =>
+ Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
+ Effect.flatMap((server) => serveB(descriptor).pipe(Effect.provideContext(server))),
+ );
+
it.effect("links with a pairing code, and the peer holds its agents to the limits they carry", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -145,6 +155,46 @@ it.effect("links with a pairing code, and the peer holds its agents to the limit
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+it.effect("a link whose row cannot be stored keeps none of its token", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const b = yield* serveB(box);
+ const held = yield* Ref.make<ReadonlySet<string>>(new Set());
+ const noted = Layer.effect(
+ ServerSecretStore.ServerSecretStore,
+ Effect.map(ServerSecretStore.make, (store) =>
+ ServerSecretStore.ServerSecretStore.of({
+ ...store,
+ set: (name, value) =>
+ store
+ .set(name, value)
+ .pipe(Effect.andThen(Ref.update(held, (names) => new Set([...names, name])))),
+ remove: (name) =>
+ store
+ .remove(name)
+ .pipe(
+ Effect.andThen(
+ Ref.update(held, (names) => new Set([...names].filter((at) => at !== name))),
+ ),
+ ),
+ }),
+ ),
+ );
+ const a = yield* makeA(laptop, noted);
+ yield* a.sql`
+ CREATE TRIGGER refuse_link BEFORE INSERT ON peer_environment_links
+ BEGIN SELECT RAISE(ABORT, 'database or disk is full'); END
+ `;
+ const pairing = yield* b.auth.issuePairingCredential();
+ const failed = yield* a.links
+ .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
+ .pipe(Effect.flip);
+ expect(failed.reason).toBe("storage");
+ expect(yield* Ref.get(held)).toEqual(new Set());
+ }),
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
+);
+
it.effect("two links racing to one peer leave the stored access matching the token", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -300,6 +350,8 @@ it.effect("tells the agent to link again once the peer revokes the link or it ex
// A link stored before links were marked: its session there is not a
// link's, so the peer would not fence its work even though it can.
yield* a.sql`UPDATE peer_environment_links SET fenced = 0`;
+ // Linking again is its only way back, as for an expired link.
+ expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
const legacy = yield* probe(a).pipe(Effect.flip);
expect(legacy.code).toBe("capability_denied");
expect(legacy.message).toContain("Link it again");
@@ -372,3 +424,66 @@ it.effect(
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+
+it.effect(
+ "linking a picked machine skips an address that answers as another, and never signs in there",
+ () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
+ const b = yield* serveB(box);
+ const a = yield* makeA(laptop);
+ const pairing = yield* b.auth.issuePairingCredential();
+ const linked = yield* a.links.link({
+ url: impostor.url,
+ alternateUrls: [b.url],
+ pairingCode: pairing.credential,
+ access: "auto",
+ expectedEnvironmentId: box.environmentId,
+ });
+ expect(linked).toMatchObject({ environmentId: box.environmentId, urls: [b.url] });
+ yield* probe(a);
+ expect(yield* linkedSessions(impostor)).toEqual([]);
+ expect(yield* Ref.get(impostor.bearers)).toEqual([]);
+ expect((yield* linkedSessions(b)).length).toBe(1);
+ }),
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
+);
+
+it.effect("linking a picked machine that answers nowhere names it and links nothing", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
+ const a = yield* makeA(laptop);
+ const failed = yield* a.links
+ .link({
+ url: impostor.url,
+ alternateUrls: ["http://192.168.1.20:3773"],
+ pairingCode: "unused",
+ access: "auto",
+ expectedEnvironmentId: box.environmentId,
+ expectedLabel: "Box",
+ })
+ .pipe(Effect.flip);
+ expect(failed.reason).toBe("unreachable");
+ expect(failed.message).toBe(
+ `This environment could not reach Box at ${impostor.url}, http://192.168.1.20:3773.`,
+ );
+ expect(yield* a.links.list).toEqual([]);
+ expect(yield* linkedSessions(impostor)).toEqual([]);
+
+ // Every address refused: the message says why.
+ const refused = yield* a.links
+ .link({
+ url: "http://192.168.1.20:3773",
+ pairingCode: "unused",
+ access: "auto",
+ expectedEnvironmentId: box.environmentId,
+ expectedLabel: "Box",
+ })
+ .pipe(Effect.flip);
+ expect(refused.message).toContain("could not reach Box");
+ expect(refused.message).toContain("plain http");
+ }),
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
+);
diff --git a/apps/server/src/peer/PeerLinks.testkit.ts b/apps/server/src/peer/PeerLinks.testkit.ts
index 59be493d92d..6c41af9e363 100644
--- a/apps/server/src/peer/PeerLinks.testkit.ts
+++ b/apps/server/src/peer/PeerLinks.testkit.ts
@@ -148,11 +148,14 @@ export type ServedPeer = Effect.Success<ReturnType<typeof servePeer>>;
* The environment that links: its own database and secret store, reaching
* peers over plain HTTP. Provide it to anything built on its links.
*/
-export const layerLinkingEnvironment = (descriptor: ExecutionEnvironmentDescriptor) =>
+export const layerLinkingEnvironment = (
+ descriptor: ExecutionEnvironmentDescriptor,
+ secrets: typeof ServerSecretStore.layer = ServerSecretStore.layer,
+) =>
PeerMcpClient.layer.pipe(
Layer.provideMerge(PeerLinks.layer),
Layer.provideMerge(Sqlite.layerMemory),
- Layer.provide(Layer.mergeAll(ServerSecretStore.layer, FetchHttpClient.layer)),
+ Layer.provide(Layer.mergeAll(secrets, FetchHttpClient.layer)),
// Services that act for this environment, such as delegation, name it too.
Layer.provideMerge(
Layer.succeed(ServerEnvironment.ServerEnvironment, {
diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts
index 958e368805d..04b59b677e9 100644
--- a/apps/server/src/peer/PeerLinks.ts
+++ b/apps/server/src/peer/PeerLinks.ts
@@ -21,6 +21,7 @@ import * as Base64Url from "effect/encoding/Base64Url";
import * as Hex from "effect/encoding/Hex";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
+import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/sql/SqlClient";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
@@ -58,6 +59,15 @@ export class PeerLinks extends Context.Service<
PeerLinks,
{
readonly link: (input: PeerLinkCreateInput) => Effect.Effect<PeerLink, PeerLinkError>;
+ /**
+ * The environment answering at `url`, or nothing when it is not a usable
+ * address or does not answer as T3 Code. Sends no credential.
+ */
+ readonly describe: (
+ url: string,
+ ) => Effect.Effect<
+ Option.Option<{ readonly environmentId: EnvironmentId; readonly label: string }>
+ >;
readonly list: Effect.Effect<ReadonlyArray<PeerLinkSummary>, PeerLinkError>;
/** The stored link, without asking the peer whether it answers. */
readonly get: (
@@ -182,7 +192,9 @@ const make = Effect.gen(function* () {
urls: yield* decodeUrls(row.urls_json),
access: yield* decodeAccess(row.access),
linkedAt: DateTime.makeUnsafe(row.linked_at),
- expiresAt: DateTime.makeUnsafe(row.expires_at),
+ // Its token predates link fencing, so the peer would not fence its work:
+ // like an expired link, only a new pairing code brings it back.
+ expiresAt: DateTime.makeUnsafe(row.fenced === 1 ? row.expires_at : row.linked_at),
lastReachedAt: row.last_reached_at === null ? null : DateTime.makeUnsafe(row.last_reached_at),
lastError: row.last_error,
} satisfies PeerLink;
@@ -317,8 +329,53 @@ const make = Effect.gen(function* () {
),
);
- const link: PeerLinks["Service"]["link"] = Effect.fn("PeerLinks.link")(function* (input) {
- const origins = yield* Effect.forEach([input.url, ...(input.alternateUrls ?? [])], peerOrigin);
+ /**
+ * The addresses that answer as `environmentId`, in the order given, with
+ * what the first one answered. Addresses this environment would not send
+ * credentials to are skipped; when every one is, the failure says why.
+ */
+ const answeringAs = Effect.fn("PeerLinks.answeringAs")(function* (
+ urls: ReadonlyArray<string>,
+ environmentId: EnvironmentId,
+ name: string,
+ ) {
+ const checked = yield* Effect.forEach(
+ urls,
+ (url) =>
+ Effect.gen(function* () {
+ const origin = yield* peerOrigin(url);
+ return { origin, descriptor: yield* describe(origin) };
+ }).pipe(Effect.result),
+ { concurrency: "unbounded" },
+ );
+ const matching = checked.flatMap((result) =>
+ Result.isSuccess(result) &&
+ Option.isSome(result.success.descriptor) &&
+ result.success.descriptor.value.environmentId === environmentId
+ ? [{ origin: result.success.origin, descriptor: result.success.descriptor.value }]
+ : [],
+ );
+ const first = matching[0];
+ if (first === undefined) {
+ const refusals = checked.flatMap((result) =>
+ Result.isFailure(result) ? [result.failure.message] : [],
+ );
+ return yield* new PeerLinkError({
+ reason: "unreachable",
+ message:
+ refusals.length === checked.length
+ ? `This environment could not reach ${name}: ${refusals.join(" ")}`
+ : `This environment could not reach ${name} at ${urls.join(", ")}.`,
+ });
+ }
+ // Each address is kept once, even when two spellings share an origin.
+ const origins = [...new Set(matching.map((found) => found.origin))];
+ return { primary: first.origin, peer: first.descriptor, origins };
+ });
+
+ /** The peer at `url`, with every address checked for credentials first. */
+ const answeringAt = Effect.fn("PeerLinks.answeringAt")(function* (urls: ReadonlyArray<string>) {
+ const origins = yield* Effect.forEach(urls, peerOrigin);
const primary = origins[0]!;
const descriptor = yield* describe(primary);
if (Option.isNone(descriptor)) {
@@ -327,7 +384,21 @@ const make = Effect.gen(function* () {
message: `Nothing at ${primary} answered as a T3 Code environment.`,
});
}
- const peer = descriptor.value;
+ return { primary, peer: descriptor.value, origins };
+ });
+
+ const link: PeerLinks["Service"]["link"] = Effect.fn("PeerLinks.link")(function* (input) {
+ const urls = [input.url, ...(input.alternateUrls ?? [])];
+ // The user picked a machine: link through the addresses that prove to
+ // be it, so a reused LAN address never receives the pairing code.
+ const { primary, peer, origins } =
+ input.expectedEnvironmentId === undefined
+ ? yield* answeringAt(urls)
+ : yield* answeringAs(
+ urls,
+ input.expectedEnvironmentId,
+ input.expectedLabel ?? input.expectedEnvironmentId,
+ );
const self = yield* environment.getDescriptor;
if (peer.environmentId === self.environmentId) {
return yield* new PeerLinkError({
@@ -359,9 +430,11 @@ const make = Effect.gen(function* () {
yield* secrets
.set(secretName, new TextEncoder().encode(issued.access_token))
.pipe(Effect.catch(failStorage));
- const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage));
- const previous = yield* readRow(peer.environmentId);
- yield* sql`
+ // A token no row names could never be removed.
+ const previous = yield* Effect.gen(function* () {
+ const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage));
+ const previous = yield* readRow(peer.environmentId);
+ yield* sql`
INSERT INTO peer_environment_links (
environment_id, secret_name, label, urls_json, access, linked_at, expires_at,
last_reached_at, last_error, fenced
@@ -381,6 +454,8 @@ const make = Effect.gen(function* () {
last_reached_at = excluded.last_reached_at,
last_error = NULL
`.pipe(Effect.catch(failStorage));
+ return previous;
+ }).pipe(Effect.onError(() => secrets.remove(secretName).pipe(Effect.ignore)));
// Linking again replaces the old token. A racing link may leave its own
// behind; it is unused either way.
if (Option.isSome(previous) && previous.value.secret_name !== secretName) {
@@ -389,6 +464,13 @@ const make = Effect.gen(function* () {
return linked;
});
+ const describeUrl: PeerLinks["Service"]["describe"] = (url) =>
+ peerOrigin(url).pipe(
+ Effect.flatMap(describe),
+ Effect.map(Option.map((peer) => ({ environmentId: peer.environmentId, label: peer.label }))),
+ Effect.orElseSucceed(() => Option.none()),
+ );
+
const statusOf = (link: PeerLink, now: DateTime.Utc) =>
DateTime.isLessThanOrEqualTo(link.expiresAt, now)
? Effect.succeed<PeerLinkStatus>("expired")
@@ -453,14 +535,6 @@ const make = Effect.gen(function* () {
message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`,
});
}
- // Its token was issued before links were marked as links, so the peer
- // never fences the work it carries, whatever version it runs now.
- if (row.value.fenced !== 1) {
- return yield* new PeerLinkError({
- reason: "incompatible",
- message: `The link to ${link.label} was made by an older T3 Code. Link it again with a new pairing code from ${link.label}.`,
- });
- }
const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage));
if (Option.isNone(stored)) {
return yield* new PeerLinkError({
@@ -516,7 +590,15 @@ const make = Effect.gen(function* () {
Effect.ignoreCause({ log: true }),
);
- return PeerLinks.of({ link, list, get, unlink, resolve, recordOutcome });
+ return PeerLinks.of({
+ link,
+ describe: describeUrl,
+ list,
+ get,
+ unlink,
+ resolve,
+ recordOutcome,
+ });
});
export const layer = Layer.effect(PeerLinks, make);
diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts
index 249a5a90729..5d3661ba1fc 100644
--- a/apps/server/src/peer/RemoteDelegation.test.ts
+++ b/apps/server/src/peer/RemoteDelegation.test.ts
@@ -62,6 +62,7 @@ import * as PeerForwarding from "./PeerForwarding.ts";
import * as PeerLinks from "./PeerLinks.ts";
import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";
import * as RemoteDelegation from "./RemoteDelegation.ts";
+import * as PeerLinkRequests from "./PeerLinkRequests.ts";
// The laptop's agent delegates a task to the box through a link. The box is
// its real /mcp behind real OAuth, with one thread the test finishes; the
@@ -468,6 +469,8 @@ const boxToolkitLayer = (thread: BoxThread) => {
Layer.provide(layerBoxLaunches),
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
Layer.provide(
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/p" }),
),
@@ -584,6 +587,7 @@ const makeLaptop = (
),
),
Layer.provide(Layer.succeedContext(linking)),
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
Layer.provide(NodeCrypto.layer),
Layer.provideMerge(layerThreads),
Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index 86a795612d4..cc395406eb5 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -74,6 +74,7 @@ import Migration0068 from "./Migrations/068_ShellStopRequestIndex.ts";
import Migration0069 from "./Migrations/069_ThreadMessageSearch.ts";
import Migration0070 from "./Migrations/070_PeerLinks.ts";
import Migration0071 from "./Migrations/071_PeerLinkFence.ts";
+import Migration0072 from "./Migrations/072_WaitingLinkRequestIndex.ts";
const migrationEntries = [
[1, "OrchestrationEvents", Migration0001],
@@ -148,6 +149,7 @@ const migrationEntries = [
[69, "ThreadMessageSearch", Migration0069],
[70, "PeerLinks", Migration0070],
[71, "PeerLinkFence", Migration0071],
+ [72, "WaitingLinkRequestIndex", Migration0072],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
diff --git a/apps/server/src/persistence/Migrations/072_WaitingLinkRequestIndex.ts b/apps/server/src/persistence/Migrations/072_WaitingLinkRequestIndex.ts
new file mode 100644
index 00000000000..e025a00d49b
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/072_WaitingLinkRequestIndex.ts
@@ -0,0 +1,13 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ // Keep this predicate aligned with ProjectionStore's waiting link card query.
+ yield* sql`
+ CREATE INDEX orchestration_v2_projection_turn_items_waiting_link_idx
+ ON orchestration_v2_projection_turn_items(thread_id, updated_at DESC, turn_item_id DESC)
+ WHERE type = 'link_request' AND status = 'waiting'
+ `;
+});
diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
index 802f77beb34..91e40578091 100644
--- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
@@ -51,6 +51,7 @@ describe("V2 preview upgrade", () => {
[69, "ThreadMessageSearch"],
[70, "PeerLinks"],
[71, "PeerLinkFence"],
+ [72, "WaitingLinkRequestIndex"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -145,6 +146,7 @@ describe("V2 preview upgrade", () => {
[69, "ThreadMessageSearch"],
[70, "PeerLinks"],
[71, "PeerLinkFence"],
+ [72, "WaitingLinkRequestIndex"],
]);
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
);
diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts
index 99a8493eaaf..ad19948c068 100644
--- a/apps/server/src/provider/AgentContextBudget.test.ts
+++ b/apps/server/src/provider/AgentContextBudget.test.ts
@@ -23,6 +23,8 @@ import { ThreadLaunchService } from "../orchestration-v2/ThreadLaunchService.ts"
import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
import { ThreadSearch } from "../orchestration-v2/ThreadSearch.ts";
import { PeerForwarding } from "../peer/PeerForwarding.ts";
+import { PeerLinkRequests } from "../peer/PeerLinkRequests.ts";
+import { PeerLinks } from "../peer/PeerLinks.ts";
import { RemoteDelegation } from "../peer/RemoteDelegation.ts";
import { PreviewManager } from "../preview/Manager.ts";
import { PreviewBrowser } from "../preview/PreviewBrowser.ts";
@@ -51,6 +53,8 @@ const toolHandlerServices = Layer.mergeAll(
Layer.mock(McpProviderSessions)({}),
Layer.mock(OrchestratorV2)({}),
Layer.mock(PeerForwarding)({}),
+ Layer.mock(PeerLinkRequests)({}),
+ Layer.mock(PeerLinks)({}),
Layer.mock(PreviewAutomationBroker)({}),
Layer.mock(PreviewBrowser)({}),
Layer.mock(PreviewManager)({}),
diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json
index 41a9242f28a..beec65c80d1 100644
--- a/apps/server/src/provider/agentContextBudget.json
+++ b/apps/server/src/provider/agentContextBudget.json
@@ -1,5 +1,5 @@
{
- "claudeSystemAppendBytes": 5086,
- "codexAdditionalContextBytes": 5638,
- "mcpToolListJsonBytes": 44745
+ "claudeSystemAppendBytes": 5258,
+ "codexAdditionalContextBytes": 5810,
+ "mcpToolListJsonBytes": 45861
}
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 161e3275a74..b6bf149e801 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -69,6 +69,7 @@ import * as TerminalManager from "./terminal/Manager.ts";
import * as McpHttpServer from "./mcp/McpHttpServer.ts";
import * as PeerForwarding from "./peer/PeerForwarding.ts";
import * as RemoteDelegation from "./peer/RemoteDelegation.ts";
+import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
import * as PeerLinks from "./peer/PeerLinks.ts";
import * as PeerMcpClient from "./peer/PeerMcpClient.ts";
import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
@@ -741,6 +742,8 @@ const layerMakeRoutes = Layer.mergeAll(
),
// delegate_task to a linked environment, from /mcp and the follower above.
Layer.provide(RemoteDelegation.layer.pipe(Layer.provide(ProjectionStoreV2.layer))),
+ // Links agents ask for: shown in a thread from /mcp, answered over WebSocket.
+ Layer.provide(PeerLinkRequests.layer),
// Share the service so HTTP/WS clients single-flight reads and invalidate each other's cached patches.
Layer.provide(layerPullRequestService),
// The same activity instance RunExecutionService reports to, by layer memoization.
diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts
index fee74872657..ebd38173533 100644
--- a/apps/server/src/ws.test.ts
+++ b/apps/server/src/ws.test.ts
@@ -54,6 +54,7 @@ import * as ModelManifest from "./provider/ModelManifest.ts";
import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts";
import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
+import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
import * as PeerLinks from "./peer/PeerLinks.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as PreviewManager from "./preview/Manager.ts";
@@ -421,6 +422,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
Layer.mock(OtlpEndpointCheck.OtlpEndpointCheck)({}),
Layer.mock(PairingGrantStore.PairingGrantStore)({}),
Layer.mock(PeerLinks.PeerLinks)({}),
+ Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
Layer.mock(PortScanner.PortDiscovery)({}),
Layer.mock(PreviewManager.PreviewManager)({}),
Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({}),
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 0bf9b91bed3..66f39ab2298 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -2,6 +2,7 @@ import { OrchestrationDispatchCommandError } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
+import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts";
import * as PeerLinks from "./peer/PeerLinks.ts";
import * as DateTime from "effect/DateTime";
@@ -1345,6 +1346,7 @@ export const layerWsRpc = (
const databaseStorage = yield* DatabaseStorage.DatabaseStorage;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const peerLinks = yield* PeerLinks.PeerLinks;
+ const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests;
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -2542,6 +2544,10 @@ export const layerWsRpc = (
[WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input),
[WS_METHODS.peerLinksUnlink]: ({ environmentId }) =>
peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))),
+ [WS_METHODS.peerLinksAnswerRequest]: (input) =>
+ Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(
+ Effect.andThen(peerLinkRequests.answer(input)),
+ ),
[WS_METHODS.serverGetSettings]: (_input) =>
serverSettings.getSettings.pipe(Effect.map(ServerSettings.redactServerSettingsForClient)),
[WS_METHODS.serverUpdateSettings]:
@@ -3313,6 +3319,7 @@ export const layer = Layer.unwrap(
const pullRequests = yield* PullRequestService.PullRequestService;
const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
const peerLinks = yield* PeerLinks.PeerLinks;
+ const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests;
const sql = yield* SqlClient.SqlClient;
return HttpRouter.add(
"GET",
@@ -3401,6 +3408,7 @@ export const layer = Layer.unwrap(
),
),
Layer.provide(Layer.succeed(PeerLinks.PeerLinks, peerLinks)),
+ Layer.provide(Layer.succeed(PeerLinkRequests.PeerLinkRequests, peerLinkRequests)),
Layer.provide(
SourceControlDiscovery.layer.pipe(
Layer.provide(
diff --git a/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsx
index 3ca5160e277..aa5c526911c 100644
--- a/apps/web/src/components/auth/ConnectAgentSurface.tsx
+++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx
@@ -279,7 +279,7 @@ function ConnectAgentHeading({
);
}
-export function AccessOption({
+function AccessOption({
access,
selected,
}: {
diff --git a/apps/web/src/components/chat/LinkRequestCard.tsx b/apps/web/src/components/chat/LinkRequestCard.tsx
new file mode 100644
index 00000000000..9d9327368a5
--- /dev/null
+++ b/apps/web/src/components/chat/LinkRequestCard.tsx
@@ -0,0 +1,510 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ type LinkableMachine,
+ linkRequestAnswerInput,
+ linkRequestDefaultAccess,
+ linkRequestDisplay,
+ linkRequestFailureMessage,
+ linkRequestInitialMachine,
+ type LinkRequestItem,
+ linkRequestTargetName,
+ rankMachinesByHint,
+} from "@t3tools/client-runtime/link-request";
+import {
+ isAtomCommandInterrupted,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
+import {
+ AuthAccessWriteScope,
+ type AuthMcpClientAccess,
+ type EnvironmentId,
+ type OrchestrationV2ProjectedTurnItem,
+} from "@t3tools/contracts";
+import * as Option from "effect/Option";
+import * as Result from "effect/Result";
+import { CheckIcon, LinkIcon, MinusIcon, XIcon } from "lucide-react";
+import { useId, useRef, useState } from "react";
+
+import { useEnvironmentScope, usePreparedConnection } from "../../state/session";
+import { mintPairingCodeOn } from "../../state/peerPairingCode";
+import { useLinkableMachines } from "../../state/peerLinks";
+import { serverEnvironment } from "../../state/server";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { accessConfig } from "../auth/ConnectAgentSurface";
+import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
+import { LinkAccessPicker } from "../settings/LinkAccessPicker";
+import { ANOTHER_ADDRESS, LinkMachineBadge } from "../settings/LinkMachineSelect";
+import { Button } from "../ui/button";
+import { Dialog } from "../ui/dialog";
+import { Input } from "../ui/input";
+import { Radio, RadioGroup } from "../ui/radio-group";
+import { WizardFooter, WizardHeader, WizardPanel, WizardPopup, WizardSteps } from "../ui/wizard";
+import { WorkLogRow } from "./WorkLog";
+
+const accessLabel = (access: AuthMcpClientAccess) => accessConfig[access].label;
+
+/** Whether the agent left the machine for the user to pick. */
+const picksMachine = (item: LinkRequestItem) =>
+ item.environmentId === undefined && item.url === undefined;
+
+/**
+ * Inline card for a link an agent asked the user to make. The user picks the
+ * access in a dialog; the pairing code lives only in that dialog's state and
+ * the RPC payload, and is never logged, toasted, or persisted.
+ */
+export function LinkRequestCard(props: {
+ readonly environmentId: EnvironmentId;
+ readonly item: LinkRequestItem;
+ readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
+}) {
+ const { item } = props;
+ const display = linkRequestDisplay(item, props.visibility, accessLabel);
+ if (display.kind === "answered" || display.kind === "pending-elsewhere") {
+ const Icon =
+ display.kind === "pending-elsewhere"
+ ? LinkIcon
+ : display.outcome === "linked"
+ ? CheckIcon
+ : display.outcome === "failed"
+ ? XIcon
+ : MinusIcon;
+ return (
+ <WorkLogRow
+ data-v2-item-type={item.type}
+ icon={<Icon className="size-3.5 text-icon-muted" aria-hidden />}
+ label={display.label}
+ />
+ );
+ }
+ return <PendingLinkRequest environmentId={props.environmentId} item={item} />;
+}
+
+function PendingLinkRequest(props: {
+ readonly environmentId: EnvironmentId;
+ readonly item: LinkRequestItem;
+}) {
+ const { item } = props;
+ const [open, setOpen] = useState(false);
+ const [declining, setDeclining] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const answer = useAtomCommand(serverEnvironment.answerLinkRequest, {
+ label: "decline link request",
+ reportFailure: false,
+ reportDefect: false,
+ });
+ const canAnswer = useAtomValue(
+ serverEnvironment.answerLinkRequest.permissionAtom(props.environmentId),
+ );
+ const target = linkRequestTargetName(item);
+
+ const decline = async () => {
+ const input = linkRequestAnswerInput(item, { type: "decline" });
+ if (input === null) return;
+ setDeclining(true);
+ setError(null);
+ const result = await answer({ environmentId: props.environmentId, input }).finally(() =>
+ setDeclining(false),
+ );
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
+ }
+ };
+
+ return (
+ <div
+ data-v2-item-type={item.type}
+ className="flex min-w-0 flex-col gap-3 rounded-xl border border-border/60 bg-card p-4"
+ >
+ <div className="flex min-w-0 flex-col gap-1">
+ <p className="text-sm font-medium text-foreground">
+ {picksMachine(item)
+ ? "Link a machine to this environment"
+ : `Link ${target} to this environment`}
+ </p>
+ {item.reason.trim() ? <p className="text-sm text-muted-foreground">{item.reason}</p> : null}
+ {item.label !== undefined && item.url !== undefined ? (
+ <p className="truncate text-xs text-muted-foreground/80">{item.url}</p>
+ ) : null}
+ </div>
+ {error !== null ? (
+ <p role="alert" className="text-xs text-destructive">
+ {error}
+ </p>
+ ) : null}
+ {canAnswer ? (
+ <div className="flex min-w-0 items-center justify-end gap-2">
+ <Button
+ type="button"
+ size="xs"
+ variant="ghost-muted"
+ disabled={declining}
+ onClick={() => void decline()}
+ >
+ Decline
+ </Button>
+ <Button type="button" size="xs" disabled={declining} onClick={() => setOpen(true)}>
+ {picksMachine(item) ? "Choose machine…" : "Review link…"}
+ </Button>
+ </div>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ Only a session that manages access here can answer this.
+ </p>
+ )}
+ <LinkRequestDialog
+ environmentId={props.environmentId}
+ item={item}
+ open={open}
+ onOpenChange={setOpen}
+ />
+ </div>
+ );
+}
+
+/**
+ * What the dialog links: a machine from the client's catalog, or an address.
+ * `urls` is empty when the client knows no direct address for the machine,
+ * so the user types one.
+ */
+type DialogTarget =
+ | { readonly kind: "none" }
+ | {
+ readonly kind: "machine";
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly urls: ReadonlyArray<string>;
+ readonly linked: boolean;
+ }
+ | { readonly kind: "address" };
+
+function resolveTarget(
+ item: LinkRequestItem,
+ machines: ReadonlyArray<LinkableMachine>,
+ choice: string | null,
+): DialogTarget {
+ if (item.environmentId === undefined && item.url !== undefined) return { kind: "address" };
+ const chosen = item.environmentId ?? choice;
+ if (chosen === null) return { kind: "none" };
+ if (chosen === ANOTHER_ADDRESS) return { kind: "address" };
+ const machine = machines.find((candidate) => candidate.environmentId === chosen);
+ return {
+ kind: "machine",
+ environmentId: machine?.environmentId ?? (chosen as EnvironmentId),
+ label: machine?.label ?? linkRequestTargetName(item),
+ urls: [...new Set([...(machine?.urls ?? []), ...(item.url === undefined ? [] : [item.url])])],
+ linked: machine?.linked ?? false,
+ };
+}
+
+/** The dialog's steps: where to link, then what agents may do there. */
+type LinkStep = "machine" | "access";
+
+function LinkRequestDialog(props: {
+ readonly environmentId: EnvironmentId;
+ readonly item: LinkRequestItem;
+ readonly open: boolean;
+ readonly onOpenChange: (open: boolean) => void;
+}) {
+ const { item } = props;
+ const formId = useId();
+ const pickMachine = picksMachine(item);
+ const listed = useLinkableMachines(props.environmentId, props.open);
+ const machines = rankMachinesByHint(listed, item.hint);
+ // Null until the user picks; until then the hint's best match is picked.
+ const [choice, setChoice] = useState<string | null>(null);
+ const [address, setAddress] = useState(item.url ?? "");
+ const [access, setAccess] = useState<AuthMcpClientAccess>(() => linkRequestDefaultAccess(item));
+ const [pairingCode, setPairingCode] = useState("");
+ const [step, setStep] = useState<LinkStep>("machine");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ // Machines whose minting already failed, so the dialog asks for a code instead.
+ const [mintFailed, setMintFailed] = useState<ReadonlySet<EnvironmentId>>(new Set());
+ // Enter then a click can both run before a re-render; this guard is synchronous.
+ const inFlight = useRef(false);
+ const answer = useAtomCommand(serverEnvironment.answerLinkRequest, {
+ label: "answer link request",
+ // The failure cause holds the request, and with it the code; keep it out of the console.
+ reportFailure: false,
+ reportDefect: false,
+ });
+ const selected = choice ?? linkRequestInitialMachine(item, machines);
+ const target = resolveTarget(item, machines, selected);
+ const targetName = target.kind === "machine" ? target.label : linkRequestTargetName(item);
+ // This client can mint a code there when it is connected to that
+ // environment with a session that may create pairing links.
+ const targetId = target.kind === "machine" ? target.environmentId : null;
+ const connected = usePreparedConnection(targetId);
+ const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
+ const canMint =
+ targetId !== null && Option.isSome(connected) && mayMint && !mintFailed.has(targetId);
+ const needsAddress =
+ target.kind === "address" || (target.kind === "machine" && target.urls.length === 0);
+ // An address the agent gave is already filled in; only one the user must type is asked for.
+ const asksAddress = needsAddress && !(item.url !== undefined && item.environmentId === undefined);
+ const useExisting = target.kind === "machine" && target.linked;
+ // A named machine with an address it answers at has nothing to choose before access.
+ const steps: ReadonlyArray<LinkStep> =
+ pickMachine || asksAddress ? ["machine", "access"] : ["access"];
+ const current: LinkStep = steps.includes(step) ? step : "access";
+ const machineReady =
+ target.kind !== "none" && (useExisting || !needsAddress || address.trim().length > 0);
+ const ready = machineReady && (useExisting || canMint || pairingCode.trim().length > 0);
+
+ const reset = () => {
+ setChoice(null);
+ setAddress(item.url ?? "");
+ setAccess(linkRequestDefaultAccess(item));
+ setPairingCode("");
+ setStep("machine");
+ setError(null);
+ };
+
+ // Every close resets, so a reopened dialog never shows the last answer or its pairing code.
+ const close = () => {
+ props.onOpenChange(false);
+ reset();
+ };
+
+ // Settles to the answer to send, an error to show, or nothing to do.
+ const prepareAnswer = async () => {
+ if (target.kind === "none") return null;
+ if (target.kind === "machine" && target.linked) {
+ return linkRequestAnswerInput(item, {
+ type: "use-existing",
+ environmentId: target.environmentId,
+ });
+ }
+ let code = pairingCode;
+ if (canMint && targetId !== null) {
+ const minted = await mintPairingCodeOn(targetId, access);
+ if (Result.isFailure(minted)) {
+ setMintFailed((failed) => new Set(failed).add(targetId));
+ setError(linkRequestFailureMessage(minted.failure));
+ return null;
+ }
+ code = minted.success;
+ }
+ return linkRequestAnswerInput(item, {
+ type: "link",
+ target:
+ target.kind === "address"
+ ? { url: address }
+ : { ...target, urls: needsAddress ? [address.trim()] : target.urls },
+ access,
+ pairingCode: code,
+ });
+ };
+
+ const submit = async () => {
+ if (inFlight.current || target.kind === "none") return;
+ inFlight.current = true;
+ setBusy(true);
+ setError(null);
+ const input = await prepareAnswer();
+ const result =
+ input === null ? null : await answer({ environmentId: props.environmentId, input });
+ inFlight.current = false;
+ setBusy(false);
+ if (result === null) return;
+ if (result._tag === "Success") {
+ // The card switches to its answered row once the item updates.
+ close();
+ } else if (!isAtomCommandInterrupted(result)) {
+ setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
+ }
+ };
+
+ // The machine step ends the dialog when the machine is linked here already.
+ const finishesHere = current === "access" || useExisting;
+
+ return (
+ <Dialog
+ open={props.open}
+ onOpenChange={(next) => {
+ // An answer that lands after a close would still link, and would close a reopened dialog.
+ if (!next && busy) return;
+ if (next) props.onOpenChange(true);
+ else close();
+ }}
+ >
+ <WizardPopup>
+ <WizardHeader
+ title={pickMachine ? "Link a machine" : `Link ${targetName}`}
+ description="Agents here can then launch, message and wait on threads there. Revoke it in that machine's Connections."
+ >
+ {steps.length > 1 && !useExisting ? (
+ <WizardSteps
+ steps={["Machine", "Access"]}
+ currentStep={steps.indexOf(current)}
+ summaries={[target.kind === "none" ? null : targetName, null]}
+ showSummaries
+ isStepDisabled={(index) => busy || (index === 1 && !machineReady)}
+ onStepChange={(index) => {
+ const next = steps[index];
+ if (next !== undefined) setStep(next);
+ }}
+ />
+ ) : null}
+ </WizardHeader>
+ <WizardPanel holdHeight={busy}>
+ <form
+ id={formId}
+ className="space-y-4"
+ autoComplete="off"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (finishesHere) void submit();
+ else if (machineReady) setStep("access");
+ }}
+ >
+ {current === "machine" ? (
+ <>
+ {pickMachine ? (
+ <MachinePicker
+ machines={machines}
+ value={selected}
+ disabled={busy}
+ onChange={(next) => {
+ setChoice(next);
+ setError(null);
+ }}
+ />
+ ) : null}
+ {asksAddress ? (
+ <label className="block space-y-1.5">
+ <span className="block text-xs font-medium text-foreground">Address</span>
+ <Input
+ value={address}
+ onChange={(event) => setAddress(event.target.value)}
+ placeholder="https://machine.tailnet.ts.net"
+ disabled={busy}
+ nativeInput
+ spellCheck={false}
+ />
+ {target.kind === "machine" ? (
+ <span className="block text-xs text-muted-foreground">
+ This app has no address for {target.label} that another machine can reach.
+ Enter its https or Tailscale address.
+ </span>
+ ) : null}
+ </label>
+ ) : null}
+ </>
+ ) : (
+ <>
+ {item.url !== undefined && !pickMachine ? (
+ <p className="truncate text-xs text-muted-foreground">{item.url}</p>
+ ) : null}
+ {useExisting ? null : (
+ <>
+ {canMint ? null : (
+ <label className="block space-y-1.5">
+ <span className="block text-xs font-medium text-foreground">
+ Pairing code
+ </span>
+ <Input
+ value={pairingCode}
+ onChange={(event) => setPairingCode(event.target.value)}
+ placeholder="Paste the code"
+ disabled={busy}
+ autoComplete="one-time-code"
+ nativeInput
+ spellCheck={false}
+ />
+ <span className="block text-xs text-muted-foreground">
+ Create a link on {targetName}: Settings → Connections → Create link, then
+ paste its code here.
+ </span>
+ </label>
+ )}
+ <LinkAccessPicker value={access} onChange={setAccess} disabled={busy} />
+ </>
+ )}
+ </>
+ )}
+ {useExisting ? (
+ <p className="text-xs text-muted-foreground">
+ This environment is already linked to {targetName}. The agent can use that link as
+ it is; change its access in Settings → Connections.
+ </p>
+ ) : null}
+ {error !== null ? (
+ <p role="alert" className="text-xs text-destructive">
+ {error}
+ </p>
+ ) : null}
+ </form>
+ </WizardPanel>
+ <WizardFooter>
+ {current === "access" && steps.length > 1 ? (
+ <Button
+ variant="outline"
+ type="button"
+ disabled={busy}
+ onClick={() => {
+ setStep("machine");
+ setError(null);
+ }}
+ >
+ Back
+ </Button>
+ ) : (
+ <Button variant="outline" type="button" disabled={busy} onClick={close}>
+ Cancel
+ </Button>
+ )}
+ <Button
+ form={formId}
+ type="submit"
+ disabled={busy || (finishesHere ? !ready : !machineReady)}
+ >
+ {busy ? "Linking…" : useExisting ? "Use this link" : finishesHere ? "Link" : "Continue"}
+ </Button>
+ </WizardFooter>
+ </WizardPopup>
+ </Dialog>
+ );
+}
+
+/** The user's other machines, best match for the agent's hint first, then an address. */
+function MachinePicker(props: {
+ readonly machines: ReadonlyArray<LinkableMachine>;
+ readonly value: string | null;
+ readonly disabled: boolean;
+ readonly onChange: (value: string) => void;
+}) {
+ const labelId = useId();
+ return (
+ <div className="space-y-2">
+ <span id={labelId} className="block text-xs font-medium">
+ Machine
+ </span>
+ <RadioGroup
+ aria-labelledby={labelId}
+ value={props.value}
+ disabled={props.disabled}
+ onValueChange={(next) => props.onChange(next as string)}
+ >
+ {props.machines.map((machine) => (
+ <label
+ key={machine.environmentId}
+ className="flex cursor-pointer items-center gap-2.5 rounded-lg border px-3 py-2 text-sm"
+ >
+ <Radio value={machine.environmentId} />
+ <EnvironmentMachineIcon
+ kind={machine.machine}
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ <span className="min-w-0 flex-1 truncate font-medium">{machine.label}</span>
+ <LinkMachineBadge machine={machine} />
+ </label>
+ ))}
+ <label className="flex cursor-pointer items-center gap-2.5 rounded-lg border px-3 py-2 text-sm">
+ <Radio value={ANOTHER_ADDRESS} />
+ <span className="min-w-0 flex-1 font-medium">Another address…</span>
+ </label>
+ </RadioGroup>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/chat/TimelineV2EventRow.tsx b/apps/web/src/components/chat/TimelineV2EventRow.tsx
index 650c930cd11..04d6effdd45 100644
--- a/apps/web/src/components/chat/TimelineV2EventRow.tsx
+++ b/apps/web/src/components/chat/TimelineV2EventRow.tsx
@@ -18,6 +18,7 @@ import {
SubagentElapsed,
V2LifecycleRow,
} from "./V2LifecycleRow";
+import { LinkRequestCard } from "./LinkRequestCard";
import { SecretRequestCard } from "./SecretRequestCard";
import { TimelineRowCtx, type TimelineRow } from "./timelineRowContext";
import { v2EventPresentation, subagentGroupTiming } from "./TimelineV2EventRow.logic";
@@ -37,6 +38,15 @@ export function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind:
/>
);
}
+ if (item.type === "link_request") {
+ return (
+ <LinkRequestCard
+ environmentId={ctx.activeThreadEnvironmentId}
+ item={item}
+ visibility={visibility}
+ />
+ );
+ }
if (isV2LifecycleItem(item)) {
return (
<V2LifecycleRow
diff --git a/apps/web/src/components/settings/LinkAccessPicker.tsx b/apps/web/src/components/settings/LinkAccessPicker.tsx
new file mode 100644
index 00000000000..407f05f934a
--- /dev/null
+++ b/apps/web/src/components/settings/LinkAccessPicker.tsx
@@ -0,0 +1,63 @@
+import { AuthMcpClientAccess } from "@t3tools/contracts";
+import { useId } from "react";
+
+import { accessConfig } from "../auth/ConnectAgentSurface";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+
+/** What agents here may do in an environment being linked, with what that does not allow. */
+export function LinkAccessPicker({
+ value,
+ onChange,
+ disabled = false,
+}: {
+ readonly value: AuthMcpClientAccess;
+ readonly onChange: (access: AuthMcpClientAccess) => void;
+ readonly disabled?: boolean;
+}) {
+ const labelId = useId();
+ const selected = accessConfig[value];
+ return (
+ <div className="space-y-1.5">
+ <span id={labelId} className="block text-xs font-medium">
+ What agents here may do there
+ </span>
+ <Select
+ value={value}
+ disabled={disabled}
+ onValueChange={(next) => {
+ if (next !== null) onChange(next as AuthMcpClientAccess);
+ }}
+ >
+ <SelectTrigger aria-labelledby={labelId}>
+ <SelectValue>
+ <span className="flex items-center gap-2">
+ <selected.icon aria-hidden className="size-4" />
+ {selected.label}
+ </span>
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup alignItemWithTrigger={false}>
+ {AuthMcpClientAccess.literals.map((option) => {
+ const { label, description, icon: Icon } = accessConfig[option];
+ return (
+ <SelectItem key={option} value={option} hideIndicator>
+ <span className="grid min-w-0 gap-0.5 py-0.5">
+ <span className="inline-flex items-center gap-1.5 font-medium text-foreground">
+ <Icon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
+ {label}
+ </span>
+ <span className="text-xs leading-4 text-muted-foreground">{description}</span>
+ </span>
+ </SelectItem>
+ );
+ })}
+ </SelectPopup>
+ </Select>
+ <p className="text-xs text-muted-foreground">
+ {selected.description} An agent never gets more access there than its own mode here. Below
+ full access, it can change only threads this link started, not that machine's own threads,
+ projects or settings.
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/settings/LinkMachineSelect.tsx b/apps/web/src/components/settings/LinkMachineSelect.tsx
new file mode 100644
index 00000000000..9977f0bfc69
--- /dev/null
+++ b/apps/web/src/components/settings/LinkMachineSelect.tsx
@@ -0,0 +1,87 @@
+import type { LinkableMachine } from "@t3tools/client-runtime/link-request";
+import { useId } from "react";
+
+import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
+import { Badge } from "../ui/badge";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+
+/** The machine choice for linking by an address typed in. */
+export const ANOTHER_ADDRESS = "another-address";
+
+/** Whether a machine is linked already, or how this app knows it when not connected to it. */
+export function LinkMachineBadge({ machine }: { readonly machine: LinkableMachine }) {
+ if (machine.linked) {
+ return (
+ <Badge variant="success" size="sm">
+ Linked
+ </Badge>
+ );
+ }
+ if (machine.connected) return null;
+ return (
+ <Badge variant="outline" size="sm">
+ {machine.connectOnly ? "T3 Connect" : "Not connected"}
+ </Badge>
+ );
+}
+
+function MachineName({ machine }: { readonly machine: LinkableMachine }) {
+ return (
+ <span className="flex min-w-0 items-center gap-2">
+ <EnvironmentMachineIcon kind={machine.machine} className="size-4 shrink-0 opacity-80" />
+ <span className="min-w-0 truncate">{machine.label}</span>
+ </span>
+ );
+}
+
+/** The user's other machines, including those on their T3 Connect account, then an address. */
+export function LinkMachineSelect({
+ machines,
+ value,
+ onChange,
+ disabled,
+}: {
+ readonly machines: ReadonlyArray<LinkableMachine>;
+ readonly value: string | null;
+ readonly onChange: (value: string) => void;
+ readonly disabled: boolean;
+}) {
+ const labelId = useId();
+ return (
+ <div className="space-y-1.5">
+ <span id={labelId} className="block text-xs font-medium text-foreground">
+ Machine
+ </span>
+ <Select
+ value={value}
+ disabled={disabled}
+ onValueChange={(next) => {
+ if (next !== null) onChange(next as string);
+ }}
+ >
+ <SelectTrigger aria-labelledby={labelId}>
+ <SelectValue>
+ {(selected: string | null) => {
+ if (selected === ANOTHER_ADDRESS) return "Another address…";
+ const machine = machines.find((candidate) => candidate.environmentId === selected);
+ return machine === undefined ? "Choose a machine" : <MachineName machine={machine} />;
+ }}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup alignItemWithTrigger={false}>
+ {machines.map((machine) => (
+ <SelectItem key={machine.environmentId} value={machine.environmentId} hideIndicator>
+ <span className="flex min-w-0 items-center justify-between gap-3">
+ <MachineName machine={machine} />
+ <LinkMachineBadge machine={machine} />
+ </span>
+ </SelectItem>
+ ))}
+ <SelectItem value={ANOTHER_ADDRESS} hideIndicator>
+ Another address…
+ </SelectItem>
+ </SelectPopup>
+ </Select>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
index c4804281f54..3b19489dd1e 100644
--- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
+++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
@@ -1,19 +1,29 @@
import { useAtomValue } from "@effect/atom-react";
-import { AuthMcpClientAccess, type EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts";
+import { linkRequestFailureMessage } from "@t3tools/client-runtime/link-request";
+import {
+ AuthAccessWriteScope,
+ type AuthMcpClientAccess,
+ type EnvironmentId,
+ type PeerLinkSummary,
+} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";
import * as DateTime from "effect/DateTime";
+import * as Option from "effect/Option";
+import * as Result from "effect/Result";
import { PlusIcon } from "lucide-react";
-import { useId, useState } from "react";
+import { useId, useRef, useState } from "react";
import { requestConfirmDialog } from "~/confirmDialog";
-import { peerLinkEnvironment } from "~/state/peerLinks";
+import { mintPairingCodeOn } from "~/state/peerPairingCode";
+import { peerLinkEnvironment, useLinkableMachines } from "~/state/peerLinks";
import { useEnvironmentQuery } from "~/state/query";
+import { useEnvironmentScope, usePreparedConnection } from "~/state/session";
import { useAtomCommand } from "~/state/use-atom-command";
-import { AccessOption, accessConfig } from "../auth/ConnectAgentSurface";
+import { accessConfig } from "../auth/ConnectAgentSurface";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { Button } from "../ui/button";
import {
@@ -28,9 +38,10 @@ import {
DialogTrigger,
} from "../ui/dialog";
import { Input } from "../ui/input";
-import { RadioGroup } from "../ui/radio-group";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
+import { LinkAccessPicker } from "./LinkAccessPicker";
+import { ANOTHER_ADDRESS, LinkMachineSelect } from "./LinkMachineSelect";
import { SettingsRow, SettingsSection } from "./settingsLayout";
import { useNowMinute } from "../../hooks/useNowMinute";
import { searchableSetting } from "./settingsSearch";
@@ -157,28 +168,77 @@ function LinkedEnvironmentRow({
function LinkEnvironmentAction({ environmentId }: { readonly environmentId: EnvironmentId }) {
const [open, setOpen] = useState(false);
- const [url, setUrl] = useState("");
+ const machines = useLinkableMachines(environmentId, open);
+ // Null until the user picks; with no other machines known, only an address is left.
+ const [choice, setChoice] = useState<string | null>(null);
+ const [address, setAddress] = useState("");
const [pairingCode, setPairingCode] = useState("");
const [access, setAccess] = useState<AuthMcpClientAccess>("approval-required");
const [busy, setBusy] = useState(false);
+ // Machines whose minting already failed, so the dialog asks for a code instead.
+ const [mintFailed, setMintFailed] = useState<ReadonlySet<EnvironmentId>>(new Set());
+ // Enter then a click can both run before a re-render; this guard is synchronous.
+ const inFlight = useRef(false);
const formId = useId();
- const accessLabelId = `${formId}-access`;
const link = useAtomCommand(peerLinkEnvironment.link, { label: "link environment" });
+ const selected = choice ?? (machines.length === 0 ? ANOTHER_ADDRESS : null);
+ const machine = machines.find((candidate) => candidate.environmentId === selected) ?? null;
+ // This client can mint a code there when it is connected to that
+ // environment with a session that may create pairing links.
+ const targetId = machine?.environmentId ?? null;
+ const connected = usePreparedConnection(targetId);
+ const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
+ const canMint =
+ targetId !== null && Option.isSome(connected) && mayMint && !mintFailed.has(targetId);
+ const needsAddress = selected === ANOTHER_ADDRESS || machine?.urls.length === 0;
+ const ready =
+ selected !== null &&
+ (!needsAddress || address.trim().length > 0) &&
+ (canMint || pairingCode.trim().length > 0);
const handleOpenChange = (next: boolean) => {
setOpen(next);
if (!next) {
- setUrl("");
+ setChoice(null);
+ setAddress("");
setPairingCode("");
setAccess("approval-required");
+ setMintFailed(new Set());
}
};
+ // Settles to the code to link with, or null after reporting why there is none.
+ const resolvePairingCode = async () => {
+ if (!canMint || targetId === null) return pairingCode.trim();
+ const minted = await mintPairingCodeOn(targetId, access);
+ if (Result.isSuccess(minted)) return minted.success;
+ setMintFailed((failed) => new Set(failed).add(targetId));
+ failureToast("Could not link the environment", linkRequestFailureMessage(minted.failure));
+ return null;
+ };
const submit = async () => {
+ const [url, ...alternateUrls] =
+ machine === null || needsAddress ? [address.trim()] : machine.urls;
+ if (inFlight.current || !ready || url === undefined) return;
+ inFlight.current = true;
setBusy(true);
- const result = await link({
- environmentId,
- input: { url: url.trim(), pairingCode: pairingCode.trim(), access },
- });
+ const code = await resolvePairingCode();
+ const result =
+ code === null
+ ? null
+ : await link({
+ environmentId,
+ input: {
+ url,
+ ...(alternateUrls.length > 0 ? { alternateUrls } : {}),
+ ...(machine === null
+ ? {}
+ : { expectedEnvironmentId: machine.environmentId, expectedLabel: machine.label }),
+ pairingCode: code,
+ access,
+ },
+ });
+ inFlight.current = false;
setBusy(false);
+ if (result === null) return;
if (result._tag === "Success") {
toastManager.add({ type: "success", title: `Linked ${result.value.label}` });
handleOpenChange(false);
@@ -214,66 +274,81 @@ function LinkEnvironmentAction({ environmentId }: { readonly environmentId: Envi
<form
id={formId}
className="space-y-4"
+ autoComplete="off"
onSubmit={(event) => {
event.preventDefault();
void submit();
}}
>
- <label className="block space-y-1.5">
- <span className="block text-xs font-medium text-foreground">Address</span>
- <Input
- value={url}
- onChange={(event) => setUrl(event.target.value)}
- placeholder="https://box.example.ts.net"
- disabled={busy}
- autoFocus
- nativeInput
- spellCheck={false}
- />
- </label>
- <label className="block space-y-1.5">
- <span className="block text-xs font-medium text-foreground">Pairing code</span>
- <Input
- value={pairingCode}
- onChange={(event) => setPairingCode(event.target.value)}
- placeholder="From that environment's Connections, or t3 pair there"
+ {machines.length > 0 ? (
+ <LinkMachineSelect
+ machines={machines}
+ value={selected}
disabled={busy}
- autoComplete="one-time-code"
- nativeInput
- spellCheck={false}
+ onChange={setChoice}
/>
- </label>
- <div className="space-y-2">
- <span id={accessLabelId} className="block text-xs font-medium">
- What agents here may do there
- </span>
- <RadioGroup
- aria-labelledby={accessLabelId}
- disabled={busy}
- value={access}
- onValueChange={(value) => setAccess(value as AuthMcpClientAccess)}
- >
- {AuthMcpClientAccess.literals.map((option) => (
- <AccessOption key={option} access={option} selected={option === access} />
- ))}
- </RadioGroup>
+ ) : null}
+ {machine?.linked ? (
<p className="text-xs text-muted-foreground">
- An agent never gets more access there than its own mode here. Below full access, it
- can change only threads this link started, not that environment's own threads,
- projects or settings.
+ Already linked. Linking again renews it with the access you pick.
</p>
- </div>
+ ) : null}
+ {needsAddress ? (
+ <label className="block space-y-1.5">
+ <span className="block text-xs font-medium text-foreground">Address</span>
+ <Input
+ value={address}
+ onChange={(event) => {
+ setAddress(event.target.value);
+ // Machines found after typing began must not hide the address being typed.
+ if (choice === null) setChoice(ANOTHER_ADDRESS);
+ }}
+ placeholder="https://box.example.ts.net"
+ disabled={busy}
+ autoFocus={machines.length === 0}
+ nativeInput
+ spellCheck={false}
+ />
+ {machine !== null ? (
+ <span className="block text-xs text-muted-foreground">
+ This app has no address for {machine.label} that another machine can reach.
+ Enter its https or Tailscale address.
+ </span>
+ ) : null}
+ </label>
+ ) : null}
+ {selected === null || canMint ? null : (
+ <label className="block space-y-1.5">
+ <span className="block text-xs font-medium text-foreground">Pairing code</span>
+ <Input
+ value={pairingCode}
+ onChange={(event) => setPairingCode(event.target.value)}
+ placeholder={
+ machine === null
+ ? "From that environment's Connections, or t3 pair there"
+ : "Paste the code"
+ }
+ disabled={busy}
+ autoComplete="one-time-code"
+ nativeInput
+ spellCheck={false}
+ />
+ {machine !== null ? (
+ <span className="block text-xs text-muted-foreground">
+ Create a link on {machine.label}: Settings → Connections → Create link, then
+ paste its code here.
+ </span>
+ ) : null}
+ </label>
+ )}
+ <LinkAccessPicker value={access} onChange={setAccess} disabled={busy} />
</form>
</DialogPanel>
<DialogFooter variant="bare">
<DialogClose disabled={busy} render={<Button variant="outline" type="button" />}>
Cancel
</DialogClose>
- <Button
- form={formId}
- type="submit"
- disabled={busy || url.trim().length === 0 || pairingCode.trim().length === 0}
- >
+ <Button form={formId} type="submit" disabled={busy || !ready}>
{busy ? "Linking…" : "Link"}
</Button>
</DialogFooter>
diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts
index 7fef6c52fe3..eb61b244075 100644
--- a/apps/web/src/session-logic.ts
+++ b/apps/web/src/session-logic.ts
@@ -300,6 +300,7 @@ const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"
"run_interrupt_request",
"run_interrupt_result",
"secret_request",
+ "link_request",
"subagent",
]);
@@ -308,6 +309,7 @@ const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"
"thread_created",
// Still answerable after a steer supersedes the attempt that asked.
"secret_request",
+ "link_request",
]);
export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
diff --git a/apps/web/src/state/peerLinks.ts b/apps/web/src/state/peerLinks.ts
index c3b6a16d124..4cb8c3f5ed1 100644
--- a/apps/web/src/state/peerLinks.ts
+++ b/apps/web/src/state/peerLinks.ts
@@ -1,9 +1,15 @@
+import { useAtomValue } from "@effect/atom-react";
+import { linkableMachines } from "@t3tools/client-runtime/link-request";
import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks";
-import { AuthAccessReadScope } from "@t3tools/contracts";
+import { AuthAccessReadScope, type EnvironmentId } from "@t3tools/contracts";
+import { useEffect, useEffectEvent } from "react";
import { connectionAtomRuntime } from "../connection/runtime";
import { useEnvironments } from "./environments";
+import { relayEnvironmentDiscovery } from "./relay";
+import { useEnvironmentQuery } from "./query";
import { useEnvironmentsWithScope } from "./session";
+import { useAtomCommand } from "./use-atom-command";
export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);
@@ -17,3 +23,34 @@ export function usePeerLinkHosts() {
const readable = useEnvironmentsWithScope(supported, AuthAccessReadScope);
return supported.filter((environment) => readable.has(environment.environmentId));
}
+
+/**
+ * The user's other machines, for picking one to link `environmentId` to,
+ * including those only on their T3 Connect account. Reads that environment's
+ * links only while `enabled`, since listing them asks every linked machine
+ * whether it answers.
+ */
+export function useLinkableMachines(environmentId: EnvironmentId, enabled: boolean) {
+ const { environments } = useEnvironments();
+ const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
+ const refreshDiscovery = useAtomCommand(relayEnvironmentDiscovery.refresh, {
+ reportFailure: false,
+ });
+ // Connect hosts are listed only once something asked for them, so ask on open.
+ const discoverIfUnasked = useEffectEvent(() => {
+ if (discovery.environments.size === 0 && !discovery.refreshing) void refreshDiscovery();
+ });
+ // 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
+ useEffect(() => {
+ if (enabled) discoverIfUnasked();
+ }, [enabled]);
+ const links = useEnvironmentQuery(
+ enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null,
+ );
+ return linkableMachines({
+ environments,
+ threadEnvironmentId: environmentId,
+ links: links.data?.links ?? [],
+ connect: discovery.environments,
+ });
+}
diff --git a/apps/web/src/state/peerPairingCode.ts b/apps/web/src/state/peerPairingCode.ts
new file mode 100644
index 00000000000..3ac16819ecc
--- /dev/null
+++ b/apps/web/src/state/peerPairingCode.ts
@@ -0,0 +1,24 @@
+import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode";
+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import type { AuthMcpClientAccess, EnvironmentId } from "@t3tools/contracts";
+import * as Result from "effect/Result";
+
+import { connectionAtomRuntime } from "../connection/runtime";
+import { appAtomRegistry } from "../rpc/atomRegistry";
+
+const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime);
+
+/**
+ * A fresh pairing code minted on `environmentId` with this client's session
+ * there, for linking with `access`. Fails with `PeerPairingCodeError` when the
+ * session may not create one.
+ */
+export async function mintPairingCodeOn(
+ environmentId: EnvironmentId,
+ access: AuthMcpClientAccess,
+): Promise<Result.Result<string, unknown>> {
+ const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: access });
+ return result._tag === "Success"
+ ? Result.succeed(result.value)
+ : Result.fail(squashAtomCommandFailure(result));
+}
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index a14285d9744..801dabf3b31 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -253,10 +253,17 @@ Link two machines, such as your laptop and a VPS, and agents on one can work on
the other: launch, message, wait on and stop its threads, answer their
questions, and manage its queues, projects and scheduled tasks. On the machine
you will work from, open **Settings → Connections → Linked environments**,
-choose **Link**, and enter the other machine's address and a pairing code from
-it. From a terminal, use
+choose **Link**, and pick the other machine or enter its address. The list
+holds the machines this app knows and those on your T3 Connect account. If this
+app is connected to that machine with a session that manages access there, it
+makes the pairing code itself; otherwise paste one from that machine's
+**Settings → Connections**. From a terminal, use
`t3 environment link <address> --pairing-code <code> --access <mode>`.
+You can also ask an agent to link a machine by name, such as "delegate this to
+my vps". It shows a card in the thread where you pick the machine the same way
+and the access, then approve.
+
- The access you pick is the most agents from this machine may do there. An
agent also never gets more there than its own mode here.
- Threads a link starts are marked **From** and this machine's name there.
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 949ef95e0fb..c08c6e59a2e 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -55,6 +55,10 @@
"types": "./src/secretRequest.ts",
"default": "./src/secretRequest.ts"
},
+ "./link-request": {
+ "types": "./src/linkRequest.ts",
+ "default": "./src/linkRequest.ts"
+ },
"./scheduled-task-webhook": {
"types": "./src/scheduledTaskWebhook.ts",
"default": "./src/scheduledTaskWebhook.ts"
@@ -211,6 +215,10 @@
"types": "./src/state/peerLinks.ts",
"default": "./src/state/peerLinks.ts"
},
+ "./state/peerPairingCode": {
+ "types": "./src/state/peerPairingCode.ts",
+ "default": "./src/state/peerPairingCode.ts"
+ },
"./state/preview": {
"types": "./src/state/preview.ts",
"default": "./src/state/preview.ts"
diff --git a/packages/client-runtime/src/linkRequest.test.ts b/packages/client-runtime/src/linkRequest.test.ts
new file mode 100644
index 00000000000..f6ea56259c9
--- /dev/null
+++ b/packages/client-runtime/src/linkRequest.test.ts
@@ -0,0 +1,377 @@
+import { EnvironmentId, type ServerConfig, ThreadId, TurnItemId } from "@t3tools/contracts";
+import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
+import * as Option from "effect/Option";
+import { describe, expect, it } from "vite-plus/test";
+
+import { BearerConnectionProfile } from "./connection/catalog.ts";
+import { BearerConnectionTarget, RelayConnectionTarget } from "./connection/model.ts";
+import type { EnvironmentPresentation } from "./connection/presentation.ts";
+import type { RelayDiscoveredEnvironment } from "./relay/discovery.ts";
+import {
+ linkableMachines,
+ linkRequestAnswerInput,
+ linkRequestDisplay,
+ linkRequestFailureMessage,
+ linkRequestInitialMachine,
+ rankMachinesByHint,
+} from "./linkRequest.ts";
+
+const item = {
+ id: TurnItemId.make("turn-item:link-request:1"),
+ threadId: ThreadId.make("thread-1"),
+};
+const asked = { url: "https://box.example.ts.net", label: "Box" };
+const accessLabel = (access: string) => `<${access}>`;
+
+describe("linkRequestDisplay", () => {
+ it("names the environment linked and the access the user chose", () => {
+ expect(
+ linkRequestDisplay(
+ { ...asked, linkStatus: "linked", linkedLabel: "Box", linkedAccess: "auto" },
+ "local",
+ accessLabel,
+ ),
+ ).toEqual({ kind: "answered", outcome: "linked", label: "Linked Box · <auto>" });
+ });
+
+ it("shows why a link failed, and never offers the actions outside the asking thread", () => {
+ expect(
+ linkRequestDisplay(
+ { ...asked, linkStatus: "failed", failure: "Pairing code expired." },
+ "local",
+ accessLabel,
+ ),
+ ).toMatchObject({ outcome: "failed", label: "Could not link: Pairing code expired." });
+ expect(
+ linkRequestDisplay({ ...asked, linkStatus: "pending" }, "inherited", accessLabel),
+ ).toMatchObject({ kind: "pending-elsewhere" });
+ });
+});
+
+describe("linkRequestAnswerInput", () => {
+ const vps = {
+ environmentId: EnvironmentId.make("environment-vps"),
+ label: "VPS",
+ urls: ["https://vps.ts.net", "http://10.0.0.2:3773"],
+ };
+
+ it("answers with the machine picked and every address known for it", () => {
+ expect(
+ linkRequestAnswerInput(item, {
+ type: "link",
+ target: vps,
+ access: "auto",
+ pairingCode: " abc ",
+ }),
+ ).toEqual({
+ threadId: item.threadId,
+ turnItemId: item.id,
+ answer: { type: "link", ...vps, access: "auto", pairingCode: "abc" },
+ });
+ expect(
+ linkRequestAnswerInput(item, {
+ type: "link",
+ target: { url: " https://box.ts.net " },
+ access: "auto",
+ pairingCode: "abc",
+ }),
+ ).toMatchObject({ answer: { urls: ["https://box.ts.net"] } });
+ });
+
+ it("refuses a blank code, a blank address, or a machine with no address", () => {
+ const blank = (target: Parameters<typeof linkRequestAnswerInput>[1] & { type: "link" }) =>
+ linkRequestAnswerInput(item, target);
+ expect(blank({ type: "link", target: vps, access: "auto", pairingCode: " " })).toBeNull();
+ expect(
+ blank({ type: "link", target: { url: " " }, access: "auto", pairingCode: "abc" }),
+ ).toBeNull();
+ expect(
+ blank({ type: "link", target: { ...vps, urls: [] }, access: "auto", pairingCode: "abc" }),
+ ).toBeNull();
+ });
+});
+
+const presentation = (
+ id: string,
+ label: string,
+ options: {
+ readonly saved?: ReadonlyArray<string>;
+ readonly reported?: ReadonlyArray<string>;
+ readonly connected?: boolean;
+ } = {},
+): EnvironmentPresentation & { readonly environmentId: EnvironmentId } => {
+ const environmentId = EnvironmentId.make(id);
+ const [first, ...rest] = (options.saved ?? []).map((httpBaseUrl, index) => {
+ const connectionId = `${id}-${index}`;
+ return {
+ target: new BearerConnectionTarget({ environmentId, label, connectionId }),
+ profile: Option.some(
+ new BearerConnectionProfile({
+ connectionId,
+ environmentId,
+ label,
+ httpBaseUrl,
+ wsBaseUrl: httpBaseUrl,
+ }),
+ ),
+ };
+ });
+ return {
+ environmentId,
+ entry: {
+ ...(first ?? {
+ target: new RelayConnectionTarget({ environmentId, label }),
+ profile: Option.none(),
+ }),
+ ...(rest.length === 0 ? {} : { alternateRoutes: rest }),
+ enabled: true,
+ },
+ connection: {
+ phase: options.connected === false ? "offline" : "connected",
+ error: null,
+ traceId: null,
+ },
+ serverConfig:
+ options.reported === undefined
+ ? null
+ : ({
+ environment: { platform: { machine: "laptop" } },
+ directEndpoints: options.reported.map((httpBaseUrl) => ({
+ kind: "tailnet",
+ httpBaseUrl,
+ })),
+ } as unknown as ServerConfig),
+ };
+};
+
+const discovered = (
+ id: string,
+ label: string,
+ machine?: "mac-mini",
+): RelayDiscoveredEnvironment => ({
+ environment: {
+ environmentId: EnvironmentId.make(id),
+ label,
+ endpoint: {
+ httpBaseUrl: `https://${id}.t3.example`,
+ wsBaseUrl: `wss://${id}.t3.example`,
+ providerKind: "cloudflare_tunnel",
+ },
+ linkedAt: "2026-10-01T00:00:00.000Z",
+ },
+ availability: "online",
+ status:
+ machine === undefined
+ ? Option.none()
+ : Option.some({
+ environmentId: EnvironmentId.make(id),
+ endpoint: {
+ httpBaseUrl: `https://${id}.t3.example`,
+ wsBaseUrl: `wss://${id}.t3.example`,
+ providerKind: "cloudflare_tunnel",
+ },
+ status: "online",
+ checkedAt: "2026-10-01T00:00:00.000Z",
+ descriptor: {
+ environmentId: EnvironmentId.make(id),
+ label,
+ platform: { os: "darwin", arch: "arm64", machine },
+ serverVersion: "1.0.0",
+ capabilities: {},
+ },
+ } as unknown as RelayEnvironmentStatusResponse),
+ error: Option.none(),
+});
+
+describe("linkableMachines", () => {
+ it("lists the other machines with reported addresses before saved ones, once each", () => {
+ const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
+ const vps = presentation("environment-vps", "VPS", {
+ saved: ["https://vps.example.com", "https://vps.ts.net"],
+ reported: ["https://vps.ts.net"],
+ });
+ const mini = presentation("environment-mini", "Mini", { connected: false });
+ expect(
+ linkableMachines({
+ environments: [here, vps, mini],
+ threadEnvironmentId: here.environmentId,
+ links: [{ environmentId: mini.environmentId, status: "unreachable" }],
+ connect: new Map(),
+ }),
+ ).toEqual([
+ {
+ environmentId: vps.environmentId,
+ label: "VPS",
+ machine: "laptop",
+ connected: true,
+ connectOnly: false,
+ linked: false,
+ urls: ["https://vps.ts.net", "https://vps.example.com"],
+ },
+ {
+ environmentId: mini.environmentId,
+ label: "Mini",
+ machine: "server",
+ connected: false,
+ connectOnly: false,
+ linked: true,
+ urls: [],
+ },
+ ]);
+ });
+
+ it("reaches a machine saved only over T3 Connect at its Connect address", () => {
+ const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
+ const box = presentation("environment-box", "Box");
+ const [listed] = linkableMachines({
+ environments: [here, box],
+ threadEnvironmentId: here.environmentId,
+ links: [],
+ connect: new Map([[box.environmentId, discovered(box.environmentId, "Box")]]),
+ });
+ expect(listed?.urls).toEqual(["https://environment-box.t3.example"]);
+ // Until discovery has found it, there is no address to offer.
+ expect(
+ linkableMachines({
+ environments: [here, box],
+ threadEnvironmentId: here.environmentId,
+ links: [],
+ connect: new Map(),
+ })[0]?.urls,
+ ).toEqual([]);
+ });
+
+ it("also offers the Connect address of a machine saved by direct address, last", () => {
+ const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
+ const vps = presentation("environment-vps", "VPS", {
+ saved: ["http://192.168.1.20:3773"],
+ reported: ["https://vps.ts.net"],
+ });
+ const [listed] = linkableMachines({
+ environments: [here, vps],
+ threadEnvironmentId: here.environmentId,
+ links: [],
+ connect: new Map([[vps.environmentId, discovered(vps.environmentId, "VPS")]]),
+ });
+ expect(listed?.urls).toEqual([
+ "https://vps.ts.net",
+ "http://192.168.1.20:3773",
+ "https://environment-vps.t3.example",
+ ]);
+ });
+
+ it("no longer counts a machine as linked once its link expired", () => {
+ const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
+ const vps = presentation("environment-vps", "VPS", { saved: ["https://vps.ts.net"] });
+ const mini = presentation("environment-mini", "Mini", { saved: ["http://mini.local:3773"] });
+ const listed = linkableMachines({
+ environments: [here, vps, mini],
+ threadEnvironmentId: here.environmentId,
+ links: [
+ { environmentId: vps.environmentId, status: "expired" },
+ { environmentId: mini.environmentId, status: "unreachable" },
+ { environmentId: EnvironmentId.make("environment-old"), status: "expired" },
+ ],
+ connect: new Map([["environment-old", discovered("environment-old", "Old box")]]),
+ });
+ expect(listed.map((machine) => [machine.label, machine.linked])).toEqual([
+ ["VPS", false],
+ ["Mini", true],
+ ["Old box", false],
+ ]);
+ });
+
+ it("offers machines only on T3 Connect after the saved ones, at their Connect address", () => {
+ const here = presentation("environment-here", "Here", { saved: ["http://localhost:3773"] });
+ const vps = presentation("environment-vps", "VPS", { saved: ["https://vps.ts.net"] });
+ const listed = linkableMachines({
+ environments: [here, vps],
+ threadEnvironmentId: here.environmentId,
+ links: [{ environmentId: EnvironmentId.make("environment-old"), status: "reachable" }],
+ connect: new Map([
+ // This environment and saved machines are listed once, as saved.
+ [here.environmentId, discovered(here.environmentId, "Here")],
+ [vps.environmentId, discovered(vps.environmentId, "VPS")],
+ ["environment-mini", discovered("environment-mini", "Mac mini", "mac-mini")],
+ ["environment-old", discovered("environment-old", "Old box")],
+ ]),
+ });
+ expect(listed.map((machine) => [machine.label, machine.connectOnly])).toEqual([
+ ["VPS", false],
+ ["Mac mini", true],
+ ["Old box", true],
+ ]);
+ expect(listed[1]).toEqual({
+ environmentId: EnvironmentId.make("environment-mini"),
+ label: "Mac mini",
+ machine: "mac-mini",
+ connected: false,
+ connectOnly: true,
+ linked: false,
+ urls: ["https://environment-mini.t3.example"],
+ });
+ expect(listed[2]).toMatchObject({ machine: "server", linked: true });
+ });
+});
+
+describe("rankMachinesByHint", () => {
+ const machines = [
+ { label: "Old vps box" },
+ { label: "VPS-2" },
+ { label: "Mac mini" },
+ { label: "vps" },
+ ];
+
+ it("puts an exact name first, then a prefix, then a substring, keeping order within each", () => {
+ expect(rankMachinesByHint(machines, " VPS ").map((machine) => machine.label)).toEqual([
+ "vps",
+ "VPS-2",
+ "Old vps box",
+ "Mac mini",
+ ]);
+ expect(rankMachinesByHint(machines, undefined)).toBe(machines);
+ });
+
+ it("preselects the card's machine, or the hint's match, and nothing for a hint that matches none", () => {
+ const listed = [
+ { environmentId: EnvironmentId.make("environment-mini"), label: "Mac mini" },
+ { environmentId: EnvironmentId.make("environment-vps"), label: "Hetzner VPS" },
+ ].map(
+ (machine) =>
+ ({
+ ...machine,
+ machine: "server",
+ connected: true,
+ connectOnly: false,
+ linked: false,
+ urls: [],
+ }) as const,
+ );
+ expect(linkRequestInitialMachine({ hint: "vps" }, listed)).toBe("environment-vps");
+ // Agents pass the user's words, which name the machine among others.
+ expect(linkRequestInitialMachine({ hint: "my mac mini" }, listed)).toBe("environment-mini");
+ expect(linkRequestInitialMachine({ hint: "my mac" }, listed)).toBe("environment-mini");
+ expect(linkRequestInitialMachine({ hint: "the hetzner vps box" }, listed)).toBe(
+ "environment-vps",
+ );
+ expect(linkRequestInitialMachine({ hint: "desk" }, listed)).toBeNull();
+ expect(linkRequestInitialMachine({ hint: "minimal" }, listed)).toBeNull();
+ expect(
+ linkRequestInitialMachine(
+ { environmentId: EnvironmentId.make("environment-x"), hint: "vps" },
+ listed,
+ ),
+ ).toBe("environment-x");
+ });
+});
+
+describe("linkRequestFailureMessage", () => {
+ it("passes through only known user-facing errors", () => {
+ expect(
+ linkRequestFailureMessage({ _tag: "PeerLinkRequestError", message: "Already answered." }),
+ ).toBe("Already answered.");
+ expect(linkRequestFailureMessage({ _tag: "SchemaError", message: "code=abc" })).toBe(
+ "Could not answer the request. Try again.",
+ );
+ });
+});
diff --git a/packages/client-runtime/src/linkRequest.ts b/packages/client-runtime/src/linkRequest.ts
new file mode 100644
index 00000000000..8df10bda472
--- /dev/null
+++ b/packages/client-runtime/src/linkRequest.ts
@@ -0,0 +1,284 @@
+import {
+ type AuthMcpClientAccess,
+ type EnvironmentId,
+ type EnvironmentMachineKind,
+ type OrchestrationV2TurnItem,
+ type PeerLinkRequestAnswerInput,
+ type PeerLinkSummary,
+ resolveEnvironmentMachineKind,
+} from "@t3tools/contracts";
+import * as Option from "effect/Option";
+
+import type { EnvironmentPresentation } from "./connection/presentation.ts";
+import { connectionRoutes, routeHttpBaseUrl } from "./connection/routes.ts";
+import type { RelayDiscoveredEnvironment } from "./relay/discovery.ts";
+
+export type LinkRequestItem = Extract<OrchestrationV2TurnItem, { readonly type: "link_request" }>;
+
+/** The access a request opens with: the agent's suggestion, else supervised. */
+export const linkRequestDefaultAccess = (
+ item: Pick<LinkRequestItem, "requestedAccess">,
+): AuthMcpClientAccess => item.requestedAccess ?? "approval-required";
+
+/** What the card calls the other environment: its own name, else the address asked for. */
+export const linkRequestTargetName = (item: Pick<LinkRequestItem, "label" | "url">): string =>
+ item.label?.trim() || item.url || "a machine";
+
+/** A machine the user could link a thread's environment to. */
+export interface LinkableMachine {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly machine: EnvironmentMachineKind;
+ readonly connected: boolean;
+ /** Found on the user's T3 Connect account rather than saved in this client. */
+ readonly connectOnly: boolean;
+ /** Whether the thread's environment already has a link to it. */
+ readonly linked: boolean;
+ /**
+ * Where the client knows it answers, most preferred first: the addresses it
+ * reports, then its saved routes, then its T3 Connect address. The server
+ * keeps only those that answer as this machine. Empty for a machine reached
+ * only over SSH, whose forward lives in this client.
+ */
+ readonly urls: ReadonlyArray<string>;
+}
+
+/**
+ * The catalog's machines other than the thread's own, in catalog order, then those only T3
+ * Connect knows. `links` are the thread environment's; an expired one no longer counts as
+ * linked. `connect` is what relay discovery found, and a server reaches a machine there as a
+ * browser does, so its Connect address is usable.
+ */
+export function linkableMachines(input: {
+ readonly environments: ReadonlyArray<
+ EnvironmentPresentation & { readonly environmentId: EnvironmentId }
+ >;
+ readonly threadEnvironmentId: EnvironmentId;
+ readonly links: ReadonlyArray<Pick<PeerLinkSummary, "environmentId" | "status">>;
+ readonly connect: ReadonlyMap<string, RelayDiscoveredEnvironment>;
+}): ReadonlyArray<LinkableMachine> {
+ const linkedIds = new Set(
+ input.links.flatMap((link) => (link.status === "expired" ? [] : [link.environmentId])),
+ );
+ const saved = input.environments
+ .filter((environment) => environment.environmentId !== input.threadEnvironmentId)
+ .map((environment) => {
+ const reported = (environment.serverConfig?.directEndpoints ?? []).map(
+ (endpoint) => endpoint.httpBaseUrl,
+ );
+ const routes = connectionRoutes(environment.entry).flatMap((route) => {
+ const url = route.target._tag === "RelayConnectionTarget" ? null : routeHttpBaseUrl(route);
+ return url === null ? [] : [url];
+ });
+ const connect = input.connect.get(environment.environmentId)?.environment.endpoint;
+ return {
+ environmentId: environment.environmentId,
+ label: environment.entry.target.label,
+ machine: resolveEnvironmentMachineKind(environment.serverConfig),
+ connected: environment.connection.phase === "connected",
+ connectOnly: false,
+ linked: linkedIds.has(environment.environmentId),
+ urls: [
+ ...new Set([
+ ...reported,
+ ...routes,
+ ...(connect === undefined ? [] : [connect.httpBaseUrl]),
+ ]),
+ ],
+ };
+ });
+ const savedIds = new Set<string>(saved.map((machine) => machine.environmentId));
+ const connectOnly = [...input.connect.values()]
+ .filter(
+ ({ environment }) =>
+ environment.environmentId !== input.threadEnvironmentId &&
+ !savedIds.has(environment.environmentId),
+ )
+ .map(({ environment, status }) => {
+ const descriptor = Option.getOrUndefined(status)?.descriptor;
+ return {
+ environmentId: environment.environmentId,
+ label: environment.label,
+ machine: resolveEnvironmentMachineKind(
+ descriptor === undefined ? null : { environment: descriptor },
+ ),
+ connected: false,
+ connectOnly: true,
+ linked: linkedIds.has(environment.environmentId),
+ urls: [environment.endpoint.httpBaseUrl],
+ };
+ });
+ return [...saved, ...connectOnly];
+}
+
+const words = (text: string) =>
+ ` ${text
+ .toLowerCase()
+ .split(/[^\p{L}\p{N}]+/u)
+ .join(" ")
+ .trim()} `;
+const NO_MATCH = 4;
+
+/**
+ * How well a machine's name matches the agent's hint, which is often the
+ * user's own words ("my box"): exact, prefix, substring, then a hint that
+ * names it among other words ("the box on hetzner").
+ */
+const hintRank = (label: string, hint: string) => {
+ const name = label.trim().toLowerCase();
+ const wanted = hint
+ .trim()
+ .toLowerCase()
+ .replace(/^(?:my|our|the)\s+/, "");
+ if (name === wanted) return 0;
+ if (name.startsWith(wanted)) return 1;
+ if (name.includes(wanted)) return 2;
+ if (words(wanted).includes(words(name))) return 3;
+ return NO_MATCH;
+};
+
+/** The machines best match for the agent's hint first, each rank in catalog order. */
+export function rankMachinesByHint<T extends { readonly label: string }>(
+ machines: ReadonlyArray<T>,
+ hint: string | undefined,
+): ReadonlyArray<T> {
+ if (hint === undefined || hint.trim().length === 0) return machines;
+ return machines
+ .map((machine, index) => ({ machine, index, rank: hintRank(machine.label, hint) }))
+ .sort((a, b) => a.rank - b.rank || a.index - b.index)
+ .map(({ machine }) => machine);
+}
+
+/** The machine a card opens on: the one it names, else the hint's best match. */
+export function linkRequestInitialMachine(
+ item: Pick<LinkRequestItem, "environmentId" | "hint">,
+ machines: ReadonlyArray<LinkableMachine>,
+): EnvironmentId | null {
+ if (item.environmentId !== undefined) return item.environmentId;
+ if (item.hint === undefined) return null;
+ const [best] = rankMachinesByHint(machines, item.hint);
+ return best !== undefined && hintRank(best.label, item.hint) < NO_MATCH
+ ? best.environmentId
+ : null;
+}
+
+/** What a link request card shows: the actions while pending, otherwise a one-line outcome. */
+export type LinkRequestDisplay =
+ | { readonly kind: "pending" }
+ | { readonly kind: "pending-elsewhere"; readonly label: string }
+ | {
+ readonly kind: "answered";
+ readonly outcome: "linked" | "declined" | "ended" | "failed";
+ readonly label: string;
+ };
+
+/**
+ * `visibility` is the projected row's: a request inherited from another
+ * thread (a fork) can only be answered where it was asked. `accessLabel`
+ * names an access level the way the client's access picker does.
+ */
+export function linkRequestDisplay(
+ item: Pick<
+ LinkRequestItem,
+ "linkStatus" | "label" | "url" | "linkedLabel" | "linkedAccess" | "failure"
+ >,
+ visibility: "local" | "inherited" | "synthetic",
+ accessLabel: (access: AuthMcpClientAccess) => string,
+): LinkRequestDisplay {
+ switch (item.linkStatus) {
+ case "pending":
+ return visibility === "local"
+ ? { kind: "pending" }
+ : { kind: "pending-elsewhere", label: "Waiting for an answer in the original thread" };
+ case "linked":
+ return {
+ kind: "answered",
+ outcome: "linked",
+ label: `Linked ${item.linkedLabel ?? linkRequestTargetName(item)}${
+ item.linkedAccess === undefined ? "" : ` · ${accessLabel(item.linkedAccess)}`
+ }`,
+ };
+ case "declined":
+ return { kind: "answered", outcome: "declined", label: "Declined" };
+ case "failed":
+ return {
+ kind: "answered",
+ outcome: "failed",
+ label: `Could not link: ${item.failure ?? "the other environment refused"}`,
+ };
+ case "cancelled":
+ return { kind: "answered", outcome: "ended", label: "Request ended" };
+ }
+}
+
+/**
+ * Builds the RPC payload for an answer. A link with a blank code returns null,
+ * since the server rejects it; callers keep Link disabled instead.
+ */
+export function linkRequestAnswerInput(
+ item: Pick<LinkRequestItem, "id" | "threadId">,
+ answer:
+ | {
+ readonly type: "link";
+ /** The machine picked, or an address typed in its place. */
+ readonly target:
+ | Pick<LinkableMachine, "environmentId" | "label" | "urls">
+ | { readonly url: string };
+ readonly access: AuthMcpClientAccess;
+ readonly pairingCode: string;
+ }
+ | { readonly type: "use-existing"; readonly environmentId: EnvironmentId }
+ | { readonly type: "decline" },
+): PeerLinkRequestAnswerInput | null {
+ const base = { threadId: item.threadId, turnItemId: item.id };
+ if (answer.type !== "link") return { ...base, answer };
+ const pairingCode = answer.pairingCode.trim();
+ if (pairingCode.length === 0) return null;
+ const { target } = answer;
+ if ("url" in target) {
+ const url = target.url.trim();
+ if (url.length === 0) return null;
+ return { ...base, answer: { type: "link", urls: [url], access: answer.access, pairingCode } };
+ }
+ const [first, ...rest] = target.urls;
+ if (first === undefined) return null;
+ return {
+ ...base,
+ answer: {
+ type: "link",
+ environmentId: target.environmentId,
+ label: target.label,
+ urls: [first, ...rest],
+ access: answer.access,
+ pairingCode,
+ },
+ };
+}
+
+/** Failures whose message is written for the user and never echoes the request payload. */
+const USER_FACING_FAILURE_TAGS = new Set([
+ "PeerLinkRequestError",
+ "EnvironmentAuthorizationError",
+ "PeerPairingCodeError",
+]);
+
+/**
+ * Inline error copy for a failed answer. Only known errors pass their message
+ * through: anything else (transport or encoding failures) gets the generic
+ * copy, so the pairing code can never surface in the UI.
+ */
+export function linkRequestFailureMessage(failure: unknown): string {
+ if (
+ typeof failure === "object" &&
+ failure !== null &&
+ "_tag" in failure &&
+ typeof failure._tag === "string" &&
+ USER_FACING_FAILURE_TAGS.has(failure._tag) &&
+ "message" in failure &&
+ typeof failure.message === "string" &&
+ failure.message.trim().length > 0
+ ) {
+ return failure.message;
+ }
+ return "Could not answer the request. Try again.";
+}
diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts
index 86fa9563653..ed28cd13e3a 100644
--- a/packages/client-runtime/src/state/commandPermissions.test.ts
+++ b/packages/client-runtime/src/state/commandPermissions.test.ts
@@ -423,6 +423,30 @@ it.effect(
),
);
+it.effect("requires access management to answer a link request", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const registry = yield* setup;
+ registry.set(sessions(env), AsyncResult.success(grant(true)));
+ const answer = createCommandPermissions(runtime, WS_METHODS.peerLinksAnswerRequest);
+ expect(registry.get(answer.permissionAtom(env))).toBe(false);
+ expect((yield* answer.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe(
+ AuthAccessWriteScope,
+ );
+ registry.set(
+ sessions(env),
+ AsyncResult.success({
+ ...grant(false),
+ scopes: [AuthAccessWriteScope],
+ permissions: [AuthAccessWriteScope],
+ }),
+ );
+ expect(registry.get(answer.permissionAtom(env))).toBe(true);
+ yield* answer.authorize(registry, env);
+ }),
+ ),
+);
+
it.effect("honors exact empty permissions and preserves legacy parent grants", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/packages/client-runtime/src/state/peerPairingCode.ts b/packages/client-runtime/src/state/peerPairingCode.ts
new file mode 100644
index 00000000000..814eeb88d54
--- /dev/null
+++ b/packages/client-runtime/src/state/peerPairingCode.ts
@@ -0,0 +1,95 @@
+/**
+ * A one-use pairing code for linking, minted on the environment being linked to with the
+ * user's own session there, so a link card can be answered without fetching a code by hand.
+ * It carries exactly what an agent sign-in with the chosen access needs.
+ */
+import { type AuthMcpClientAccess, mcpClientScopes } from "@t3tools/contracts";
+import * as Data from "effect/Data";
+import * as Effect from "effect/Effect";
+import type * as HttpClient from "effect/http/HttpClient";
+import * as Option from "effect/Option";
+import type { Atom } from "effect/reactivity";
+import * as SubscriptionRef from "effect/SubscriptionRef";
+
+import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
+import type { PreparedConnection } from "../connection/model.ts";
+import type { EnvironmentRegistry } from "../connection/registry.ts";
+import * as EnvironmentSupervisor from "../connection/supervisor.ts";
+import * as ManagedRelay from "../relay/managedRelay.ts";
+import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
+import { createEnvironmentCommand } from "./runtime.ts";
+
+const MINT_TIMEOUT_MS = 8_000;
+const PEER_PAIRING_CODE_LABEL = "T3 Code link";
+
+/** Minting failed; the user can still paste a code from the other environment. */
+export class PeerPairingCodeError extends Data.TaggedError("PeerPairingCodeError")<{
+ readonly reason: "not_allowed" | "unavailable";
+ readonly cause: unknown;
+}> {
+ override get message(): string {
+ return this.reason === "not_allowed"
+ ? "Your session there cannot create pairing codes. Paste a code from there instead."
+ : "Could not get a pairing code from there. Paste a code from there instead.";
+ }
+}
+
+const mintPeerPairingCode = Effect.fn("clientRuntime.state.mintPeerPairingCode")(function* (
+ prepared: PreparedConnection,
+ access: AuthMcpClientAccess,
+): Effect.fn.Return<string, PeerPairingCodeError, HttpClient.HttpClient> {
+ const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
+ const remoteAuthorization = yield* Effect.serviceOption(
+ RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
+ );
+ const minted = yield* executeAuthenticatedEnvironmentHttpRequest({
+ prepared,
+ signer,
+ remoteAuthorization,
+ group: "auth",
+ method: "POST",
+ url: (urls) => urls.pairingCredential(),
+ timeoutMs: MINT_TIMEOUT_MS,
+ request: ({ client, headers }) =>
+ client.pairingCredential({
+ headers,
+ payload: { label: PEER_PAIRING_CODE_LABEL, scopes: mcpClientScopes(access) },
+ }),
+ }).pipe(
+ Effect.mapError(
+ (cause) =>
+ new PeerPairingCodeError({
+ reason:
+ cause._tag === "EnvironmentScopeRequiredError" ||
+ cause._tag === "EnvironmentOperationForbiddenError"
+ ? "not_allowed"
+ : "unavailable",
+ cause,
+ }),
+ ),
+ );
+ return minted.credential;
+});
+
+/**
+ * Mints a code on the environment it runs in. Each run mints its own: a code
+ * is one-use, so two overlapping answers must never share one.
+ */
+export function createPeerPairingCodeCommand<R, E>(
+ runtime: Atom.AtomRuntime<EnvironmentRegistry | HttpClient.HttpClient | R, E>,
+) {
+ return createEnvironmentCommand(runtime, {
+ label: "environment-data:peer-pairing-code:mint",
+ execute: Effect.fn(function* (access: AuthMcpClientAccess) {
+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
+ const prepared = yield* SubscriptionRef.get(supervisor.prepared);
+ if (Option.isNone(prepared)) {
+ return yield* new PeerPairingCodeError({
+ reason: "unavailable",
+ cause: "The environment is not connected.",
+ });
+ }
+ return yield* mintPeerPairingCode(prepared.value, access);
+ }),
+ });
+}
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index f9f1f914070..77db29b9e94 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -1525,6 +1525,16 @@ export function createServerEnvironmentAtoms<R, E>(
JSON.stringify([environmentId, input.threadId, input.turnItemId]),
},
}),
+ // Like a secret card's answer: off the config lane, one per card at a time.
+ answerLinkRequest: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:peer-links:answer-request",
+ tag: WS_METHODS.peerLinksAnswerRequest,
+ concurrency: {
+ mode: "singleFlight",
+ key: ({ environmentId, input }) =>
+ JSON.stringify([environmentId, input.threadId, input.turnItemId]),
+ },
+ }),
refreshUsageRates: createEnvironmentRpcCommand(runtime, {
label: "environment-data:server:refresh-usage-rates",
tag: WS_METHODS.serverRefreshUsageRates,
diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts
index 1aed057817c..1e9629d5803 100644
--- a/packages/client-runtime/src/t3ToolSummary.ts
+++ b/packages/client-runtime/src/t3ToolSummary.ts
@@ -339,6 +339,16 @@ export function summarizeT3ToolCalls(
case "environment-links":
label = phrase("Listed", "list", `linked environments ${times}`);
break;
+ case "environment-link":
+ label = phrase("Asked to link", "ask to link", quantity(selected.length, "environment"));
+ break;
+ case "environment-unlink":
+ label = phrase(
+ "Forgot",
+ "forget",
+ quantity(countEntities(entityIds("environmentId")), "linked environment"),
+ );
+ break;
case "attachment-prepare":
label = phrase(
"Prepared",
diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts
index fbdf2c3a34e..7e4cc84b741 100644
--- a/packages/contracts/src/auth.ts
+++ b/packages/contracts/src/auth.ts
@@ -408,6 +408,19 @@ export const AuthMcpClientAccess = Schema.Literals([
]);
export type AuthMcpClientAccess = typeof AuthMcpClientAccess.Type;
+/** The scopes an agent session gets for an access level, and a pairing code must carry. */
+export const mcpClientScopes = (access: AuthMcpClientAccess): ReadonlyArray<AuthGrantScope> =>
+ access === "read-only"
+ ? [AuthOrchestrationReadScope]
+ : access === "full-access"
+ ? [
+ AuthOrchestrationReadScope,
+ AuthOrchestrationOperateScope,
+ AuthSettingsWriteScope,
+ AuthSourceControlWriteScope,
+ ]
+ : [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
+
export const AuthMcpProtectedResourceMetadata = Schema.Struct({
resource: Schema.String,
authorization_servers: Schema.Array(Schema.String),
diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts
index 5ff35ad1334..364b3d191af 100644
--- a/packages/contracts/src/clientRpcPermissions.ts
+++ b/packages/contracts/src/clientRpcPermissions.ts
@@ -54,6 +54,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
[WS_METHODS.guestShareCreate]: AuthAccessWriteScope,
[WS_METHODS.peerLinksLink]: AuthAccessWriteScope,
[WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope,
+ // A link lets every agent here reach the other environment: Settings' bar.
+ [WS_METHODS.peerLinksAnswerRequest]: AuthAccessWriteScope,
} as const;
export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES;
diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts
index 2ee6f3d3bd0..18d7c03cd77 100644
--- a/packages/contracts/src/orchestrationV2.ts
+++ b/packages/contracts/src/orchestrationV2.ts
@@ -1506,6 +1506,42 @@ const OrchestrationV2SecretRequestFields = {
secretStatus: OrchestrationV2SecretRequestStatus,
} as const;
+export const OrchestrationV2LinkRequestStatus = Schema.Literals([
+ "pending",
+ "linked",
+ "declined",
+ "cancelled",
+ "failed",
+]);
+export type OrchestrationV2LinkRequestStatus = typeof OrchestrationV2LinkRequestStatus.Type;
+
+/**
+ * An agent asked the user to link another environment. The user picks the
+ * access; the pairing code never passes through orchestration, so the item
+ * carries only what was asked and how it ended.
+ */
+const OrchestrationV2LinkRequestFields = {
+ type: Schema.Literal("link_request"),
+ /** The address the agent named, if it named one. */
+ url: Schema.optional(TrimmedNonEmptyString),
+ reason: Schema.String,
+ /**
+ * The environment the agent named, or the one answering at `url`. Without
+ * either the user picks the machine in the card.
+ */
+ environmentId: Schema.optional(EnvironmentId),
+ label: Schema.optional(Schema.String),
+ /** A phrase from the user's words, such as "vps", that preselects a machine. */
+ hint: Schema.optional(Schema.String),
+ /** The access the agent suggested; the user's choice is final. */
+ requestedAccess: Schema.optional(AuthMcpClientAccess),
+ linkStatus: OrchestrationV2LinkRequestStatus,
+ linkedEnvironmentId: Schema.optional(EnvironmentId),
+ linkedLabel: Schema.optional(Schema.String),
+ linkedAccess: Schema.optional(AuthMcpClientAccess),
+ failure: Schema.optional(Schema.String),
+} as const;
+
export const OrchestrationV2TurnItem = Schema.Union([
Schema.Struct({
...OrchestrationV2TurnItemBaseFields,
@@ -1695,6 +1731,10 @@ export const OrchestrationV2TurnItem = Schema.Union([
...OrchestrationV2TurnItemBaseFields,
...OrchestrationV2SecretRequestFields,
}),
+ Schema.Struct({
+ ...OrchestrationV2TurnItemBaseFields,
+ ...OrchestrationV2LinkRequestFields,
+ }),
Schema.Struct({
...OrchestrationV2TurnItemBaseFields,
type: Schema.Literal("subagent"),
@@ -2530,6 +2570,10 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
...OrchestrationV2TurnItemJsonBaseFields,
...OrchestrationV2SecretRequestFields,
}),
+ Schema.Struct({
+ ...OrchestrationV2TurnItemJsonBaseFields,
+ ...OrchestrationV2LinkRequestFields,
+ }),
Schema.Struct({
...OrchestrationV2TurnItemJsonBaseFields,
type: Schema.Literal("subagent"),
@@ -3434,6 +3478,37 @@ const OrchestrationV2InternalCommand = Schema.Union([
delivery: Schema.optional(OrchestrationV2SecretRequestDelivery),
secretStatus: OrchestrationV2SecretRequestStatus,
}),
+ /**
+ * Records or updates a link an agent asked the user to make. Internal so no
+ * client can mark a request linked without the link being made.
+ */
+ Schema.Struct({
+ type: Schema.Literal("link_request.record"),
+ commandId: CommandId,
+ threadId: ThreadId,
+ runId: RunId,
+ nodeId: NodeId,
+ turnItemId: TurnItemId,
+ url: Schema.optional(TrimmedNonEmptyString),
+ reason: Schema.String,
+ environmentId: Schema.optional(EnvironmentId),
+ label: Schema.optional(Schema.String),
+ hint: Schema.optional(Schema.String),
+ requestedAccess: Schema.optional(AuthMcpClientAccess),
+ linkStatus: OrchestrationV2LinkRequestStatus,
+ linkedEnvironmentId: Schema.optional(EnvironmentId),
+ linkedLabel: Schema.optional(Schema.String),
+ linkedAccess: Schema.optional(AuthMcpClientAccess),
+ failure: Schema.optional(Schema.String),
+ /** Tells the agent how the card ended, in the same commit that closes it. */
+ wake: Schema.optional(
+ Schema.Struct({
+ messageId: MessageId,
+ text: Schema.String,
+ notification: OrchestrationV2Notification,
+ }),
+ ),
+ }),
]);
export type OrchestrationV2InternalCommand = typeof OrchestrationV2InternalCommand.Type;
diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts
index 97911133f4d..9b9100287f9 100644
--- a/packages/contracts/src/orchestratorMcp.ts
+++ b/packages/contracts/src/orchestratorMcp.ts
@@ -619,6 +619,8 @@ export type OrchestratorMcpEnvironmentLink = typeof OrchestratorMcpEnvironmentLi
export const OrchestratorMcpEnvironmentLinksResult = Schema.Struct({
environmentId: EnvironmentId,
links: Schema.Array(OrchestratorMcpEnvironmentLink),
+ /** What to do when the machine the user means is not among `links`. */
+ notListed: Schema.String,
});
export type OrchestratorMcpEnvironmentLinksResult =
typeof OrchestratorMcpEnvironmentLinksResult.Type;
@@ -764,6 +766,74 @@ export const OrchestratorMcpRequestSecretResult = Schema.Union([
]);
export type OrchestratorMcpRequestSecretResult = typeof OrchestratorMcpRequestSecretResult.Type;
+export const OrchestratorMcpEnvironmentLinkInput = Schema.Struct({
+ environmentId: Schema.optional(EnvironmentId).annotate({
+ description:
+ "The machine, when known, e.g. from a mentioned machine. Otherwise the user picks it in the card.",
+ }),
+ url: Schema.optional(TrimmedNonEmptyString).annotate({
+ description:
+ "Only an address the user gave: https, Tailscale, LAN or loopback. Never guess one.",
+ }),
+ hint: Schema.optional(TrimmedNonEmptyString).annotate({
+ description: 'The user\'s words for the machine, e.g. "vps". Preselects it in the card.',
+ }),
+ reason: Schema.optional(TrimmedNonEmptyString).annotate({
+ description: "One sentence for the card.",
+ }),
+ requestedAccess: Schema.optional(AuthMcpClientAccess).annotate({
+ description: "Suggested access. The user picks; default approval-required.",
+ }),
+ clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
+});
+export type OrchestratorMcpEnvironmentLinkInput = typeof OrchestratorMcpEnvironmentLinkInput.Type;
+
+export const OrchestratorMcpEnvironmentLinkResult = Schema.Union([
+ Schema.Struct({
+ status: Schema.Literal("pending").annotate({
+ description:
+ "The card is waiting for the user. Their answer arrives as a message in this thread.",
+ }),
+ turnItemId: TurnItemId,
+ }),
+ Schema.Struct({
+ status: Schema.Literal("linked"),
+ environmentId: EnvironmentId.annotate({
+ description: "Pass it as environmentId to act there; t3_environment_links lists it.",
+ }),
+ label: Schema.String,
+ access: AuthMcpClientAccess.annotate({ description: "The access the user chose." }),
+ }),
+ Schema.Struct({
+ status: Schema.Literals(["declined", "cancelled"]).annotate({
+ description:
+ "declined: the user chose not to. cancelled: the card closed unanswered, when the thread was stopped or archived.",
+ }),
+ }),
+ Schema.Struct({
+ status: Schema.Literal("failed"),
+ message: Schema.String.annotate({
+ description: "Why the other environment refused the link, as the user saw it.",
+ }),
+ }),
+]);
+export type OrchestratorMcpEnvironmentLinkResult = typeof OrchestratorMcpEnvironmentLinkResult.Type;
+
+export const OrchestratorMcpEnvironmentUnlinkInput = Schema.Struct({
+ environmentId: EnvironmentId.annotate({
+ description: "The linked environment to forget, from t3_environment_links.",
+ }),
+});
+export type OrchestratorMcpEnvironmentUnlinkInput =
+ typeof OrchestratorMcpEnvironmentUnlinkInput.Type;
+
+export const OrchestratorMcpEnvironmentUnlinkResult = Schema.Struct({
+ environmentId: EnvironmentId,
+ removed: Schema.Boolean,
+});
+export type OrchestratorMcpEnvironmentUnlinkResult =
+ typeof OrchestratorMcpEnvironmentUnlinkResult.Type;
+
export const OrchestratorMcpDeleteScheduledTaskInput = Schema.Struct({
environmentId: OrchestratorMcpEnvironmentTarget,
scheduledTaskId: ScheduledTaskId,
diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts
index 022b1b9b9f8..7882e8d2c74 100644
--- a/packages/contracts/src/peerLink.ts
+++ b/packages/contracts/src/peerLink.ts
@@ -1,7 +1,7 @@
import * as Schema from "effect/Schema";
import { AuthMcpClientAccess } from "./auth.ts";
-import { EnvironmentId, TrimmedNonEmptyString } from "./baseSchemas.ts";
+import { EnvironmentId, ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts";
/**
* A link from this environment to another one (the peer). This environment
@@ -40,6 +40,13 @@ export const PeerLinkCreateInput = Schema.Struct({
/** A pairing code from the peer (`t3 pair` there, or its Connections settings). */
pairingCode: TrimmedNonEmptyString,
access: AuthMcpClientAccess,
+ /**
+ * The environment the user means. Addresses that answer as another one are
+ * skipped, and only those that answer as this one are kept.
+ */
+ expectedEnvironmentId: Schema.optionalKey(EnvironmentId),
+ /** What the user calls that environment, to name it when it cannot be reached. */
+ expectedLabel: Schema.optionalKey(TrimmedNonEmptyString),
});
export type PeerLinkCreateInput = typeof PeerLinkCreateInput.Type;
@@ -64,3 +71,60 @@ export class PeerLinkError extends Schema.TaggedError<PeerLinkError>()("PeerLink
message: Schema.String,
cause: Schema.optionalKey(Schema.Defect()),
}) {}
+
+/**
+ * The user's answer to an agent asking to link an environment. The pairing
+ * code is used once to link and is never recorded; the thread learns only the
+ * outcome and the access the user chose.
+ */
+export const PeerLinkRequestAnswerInput = Schema.Struct({
+ threadId: ThreadId,
+ turnItemId: TurnItemId,
+ answer: Schema.Union([
+ Schema.Struct({
+ type: Schema.Literal("link"),
+ /** The machine the user picked, when they picked one rather than typing an address. */
+ environmentId: Schema.optionalKey(EnvironmentId),
+ /** What the client calls that machine. */
+ label: Schema.optionalKey(TrimmedNonEmptyString),
+ /** The addresses the client knows for that machine, most preferred first. */
+ urls: Schema.NonEmptyArray(TrimmedNonEmptyString),
+ access: AuthMcpClientAccess,
+ pairingCode: TrimmedNonEmptyString,
+ }),
+ /** Answers with a machine this environment is already linked to, as it is. */
+ Schema.Struct({ type: Schema.Literal("use-existing"), environmentId: EnvironmentId }),
+ Schema.Struct({ type: Schema.Literal("decline") }),
+ ]),
+});
+export type PeerLinkRequestAnswerInput = typeof PeerLinkRequestAnswerInput.Type;
+
+const PEER_LINK_REQUEST_FAILURE_MESSAGES = {
+ load_failed: "Could not load the link request.",
+ not_found: "This link request no longer exists.",
+ already_answered: "This link request was already answered.",
+ record_failed: "Could not update the link request.",
+} as const;
+
+export const PeerLinkRequestFailureReason = Schema.Literals(
+ Object.keys(PEER_LINK_REQUEST_FAILURE_MESSAGES) as Array<
+ keyof typeof PEER_LINK_REQUEST_FAILURE_MESSAGES
+ >,
+);
+export type PeerLinkRequestFailureReason = typeof PeerLinkRequestFailureReason.Type;
+
+/**
+ * Answering a link request failed before anything was linked. A link the
+ * other environment refused is not this error: the card records it as failed.
+ */
+export class PeerLinkRequestError extends Schema.TaggedError<PeerLinkRequestError>()(
+ "PeerLinkRequestError",
+ {
+ reason: PeerLinkRequestFailureReason,
+ cause: Schema.optionalKey(Schema.Defect()),
+ },
+) {
+ override get message(): string {
+ return PEER_LINK_REQUEST_FAILURE_MESSAGES[this.reason];
+ }
+}
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index e0a6486668e..9c32c6de25b 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -22,6 +22,8 @@ import {
PeerLinkError,
PeerLinkRemoveInput,
PeerLinkRemoveResult,
+ PeerLinkRequestAnswerInput,
+ PeerLinkRequestError,
PeerLinkSummary,
} from "./peerLink.ts";
import {
@@ -497,6 +499,7 @@ export const WS_METHODS = {
peerLinksList: "peerLinks.list",
peerLinksLink: "peerLinks.link",
peerLinksUnlink: "peerLinks.unlink",
+ peerLinksAnswerRequest: "peerLinks.answerRequest",
serverGetSettings: "server.getSettings",
serverUpdateSettings: "server.updateSettings",
serverDiscoverSourceControl: "server.discoverSourceControl",
@@ -797,6 +800,11 @@ const WsPeerLinksUnlinkRpc = Rpc.make(WS_METHODS.peerLinksUnlink, {
error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]),
});
+const WsPeerLinksAnswerRequestRpc = Rpc.make(WS_METHODS.peerLinksAnswerRequest, {
+ payload: PeerLinkRequestAnswerInput,
+ error: Schema.Union([PeerLinkRequestError, EnvironmentAuthorizationError]),
+});
+
const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, {
payload: Schema.Struct({}),
success: ServerSettings,
@@ -1977,6 +1985,7 @@ export const WsRpcGroup = RpcGroup.make(
WsPeerLinksListRpc,
WsPeerLinksLinkRpc,
WsPeerLinksUnlinkRpc,
+ WsPeerLinksAnswerRequestRpc,
WsServerDiscoverSourceControlRpc,
WsServerSearchAcpRegistryRpc,
WsServerPrepareAcpRegistryAgentRpc,
diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts
index 7790bed28f9..5ce74766c40 100644
--- a/packages/provider-core/src/server/orchestrationInstructions.ts
+++ b/packages/provider-core/src/server/orchestrationInstructions.ts
@@ -14,6 +14,7 @@ Ordinary coding tasks need no T3 tools.
`- \`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.
- Given a thread id, \`t3_thread_read\` it before you answer about it.
- 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\`.
+- 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.
- 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.
- 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.
- T3 tools may load late. Try the name once before you call it absent.`,
diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts
index 4c30698db8c..5848861f47a 100644
--- a/packages/shared/src/t3McpToolPresentation.ts
+++ b/packages/shared/src/t3McpToolPresentation.ts
@@ -52,6 +52,8 @@ export type T3McpToolSummaryAction =
| "project-clone"
| "environment-read"
| "environment-links"
+ | "environment-link"
+ | "environment-unlink"
| "environment-update"
| "attachment-prepare"
| "attachment-discard"
@@ -326,6 +328,14 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
["List", "Listing", "Listed", "linked environments"],
"environment-links",
),
+ t3_environment_link: tool(
+ ["Ask to link", "Asking to link", "Asked to link", "an environment"],
+ "environment-link",
+ ),
+ t3_environment_unlink: tool(
+ ["Forget", "Forgetting", "Forgot", "a linked environment"],
+ "environment-unlink",
+ ),
t3_environment_preferences_update: tool(
["Update", "Updating", "Updated", "environment preferences"],
"environment-update",