Skip to content

Commit 3deb99f

Browse files
feat(server,web,mobile): an agent sets up a link to another environment
A user asks an agent to "delegate this to my vps" without knowing any address, so t3_environment_link needs none. The agent passes a hint from the user's words, an environmentId when it knows the machine, or an address only when the user gave one. The tool records a card in the thread and returns pending at once, so no provider's tool-call timeout can close it. A machine already linked here returns linked at once, with no card. The card lets the user pick the machine from the ones their app knows (preselected by the hint; "Another address…" for one it does not), and the access (default supervised, or the agent's suggestion). The client answers with every address it knows for that machine and a one-use pairing code, minted there with the user's own session when it can, or pasted. The server links through the first address that answers as that machine, never sends the code to one that answers as another, and keeps only the matching addresses. A machine already linked is answered with "Use this link". The answer reaches the agent as a notification in its thread: linked (with the environment id, label and the access chosen), declined, or failed with the reason. The pairing code is never recorded. Stopping or archiving the thread closes a pending card; a retry with the same clientRequestId returns the card's current outcome. t3_environment_unlink undoes a link. Both tools need a full-access caller and are refused for linked work. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent cb8a72b commit 3deb99f

49 files changed

Lines changed: 3720 additions & 44 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/mobile/src/features/threads/LinkRequestCard.tsx‎

Lines changed: 507 additions & 0 deletions
Large diffs are not rendered by default.

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { useMarkdownImageSource } from "../../native/useMarkdownImageSource";
55
import { enrichedContextLinkPresentation } from "../../lib/enrichedLinkPresentation";
66
import { ThreadContextDivider } from "./thread-context-divider";
77
import { ThreadHandoffDivider, ThreadHandoffRow } from "./thread-handoff-row";
8+
import { LinkRequestCard } from "./LinkRequestCard";
89
import { SecretRequestCard } from "./SecretRequestCard";
910
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
1011
import {
@@ -175,6 +176,7 @@ import {
175176
threadFeedRunIsUnsettled,
176177
isContextCompactionActivityGroup,
177178
isContextHandoffActivityGroup,
179+
isLinkRequestActivityGroup,
178180
isSecretRequestActivityGroup,
179181
type ThreadFeedEntry,
180182
type ThreadFeedLatestRun,
@@ -1109,6 +1111,16 @@ function renderFeedEntry(
11091111
);
11101112
}
11111113

1114+
if (entry.type === "activity-group" && isLinkRequestActivityGroup(entry)) {
1115+
return (
1116+
<LinkRequestCard
1117+
environmentId={props.environmentId}
1118+
projectedItem={entry.activities[0]!.projectedItem}
1119+
iconColor={iconSubtleColor}
1120+
/>
1121+
);
1122+
}
1123+
11121124
if (entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) {
11131125
const label = entry.activities[0]!.summary;
11141126
const active =

‎apps/mobile/src/lib/threadActivity.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,12 @@ export function isSecretRequestActivityGroup(entry: ThreadFeedActivityGroup): bo
346346
);
347347
}
348348

349+
export function isLinkRequestActivityGroup(entry: ThreadFeedActivityGroup): boolean {
350+
return (
351+
entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "link_request"
352+
);
353+
}
354+
349355
function isUserInputActivityGroup(entry: ThreadFeedActivityGroup): boolean {
350356
return entry.activities.some((activity) => activity.workEntry.questionAnswer !== undefined);
351357
}
@@ -453,7 +459,8 @@ function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
453459
item.type === "fork" ||
454460
item.type === "thread_created" ||
455461
item.type === "system_notice" ||
456-
item.type === "secret_request"
462+
item.type === "secret_request" ||
463+
item.type === "link_request"
457464
);
458465
}
459466

@@ -574,6 +581,8 @@ function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
574581
return "zap";
575582
case "secret_request":
576583
return "lock";
584+
case "link_request":
585+
return "globe";
577586
}
578587
}
579588

@@ -630,6 +639,8 @@ function itemSummary(
630639
return "Thread created";
631640
case "secret_request":
632641
return item.label;
642+
case "link_request":
643+
return `Link ${item.label ?? item.url ?? "an environment"}`;
633644
case "dynamic_tool": {
634645
const classified = classifyToolActivity({
635646
itemType: "dynamic_tool_call",
@@ -688,6 +699,7 @@ function itemPreview(item: OrchestrationV2TurnItem): string | null {
688699
case "thread_created":
689700
return item.targetThreadId;
690701
case "secret_request":
702+
case "link_request":
691703
return item.reason || null;
692704
case "subagent":
693705
return item.result ?? item.progress ?? item.prompt;

‎apps/mobile/src/state/peerLinks.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,40 @@
1+
import { useAtomValue } from "@effect/atom-react";
2+
import { linkableMachines } from "@t3tools/client-runtime/link-request";
13
import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks";
4+
import type { EnvironmentId } from "@t3tools/contracts";
5+
import { useMemo } from "react";
26

37
import { connectionAtomRuntime } from "../connection/runtime";
8+
import { useEnvironments } from "./environments";
9+
import { relayEnvironmentDiscovery } from "./relay";
10+
import { useEnvironmentQuery } from "./query";
411

512
export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);
13+
14+
/**
15+
* The user's other machines, for picking one to link `environmentId` to.
16+
* Reads that environment's links only while `enabled`, since listing them
17+
* asks every linked machine whether it answers.
18+
*/
19+
export function useLinkableMachines(environmentId: EnvironmentId, enabled: boolean) {
20+
const { environments } = useEnvironments();
21+
const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
22+
const links = useEnvironmentQuery(
23+
enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null,
24+
);
25+
return useMemo(
26+
() =>
27+
linkableMachines({
28+
environments,
29+
threadEnvironmentId: environmentId,
30+
linkedIds: new Set(links.data?.links.map((link) => link.environmentId)),
31+
connectAddresses: new Map(
32+
[...discovery.environments].map(([id, found]) => [
33+
id,
34+
found.environment.endpoint.httpBaseUrl,
35+
]),
36+
),
37+
}),
38+
[discovery.environments, environmentId, environments, links.data],
39+
);
40+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { mintPeerPairingCode } from "@t3tools/client-runtime/state/peerPairingCode";
2+
import type { EnvironmentId } from "@t3tools/contracts";
3+
import * as Effect from "effect/Effect";
4+
import * as Option from "effect/Option";
5+
import { Atom, AtomRegistry } from "effect/reactivity";
6+
7+
import { connectionAtomRuntime } from "../connection/runtime";
8+
import { appAtomRegistry } from "./atom-registry";
9+
import { environmentSession } from "./session";
10+
11+
// Each read mints a new one-use code; nothing keeps one once it is read.
12+
const peerPairingCodeAtom = Atom.family((environmentId: EnvironmentId) =>
13+
connectionAtomRuntime
14+
.atom((get) => {
15+
const prepared = Option.getOrNull(
16+
get(environmentSession.preparedConnectionValueAtom(environmentId)),
17+
);
18+
if (prepared === null) return Effect.never;
19+
return mintPeerPairingCode(prepared);
20+
})
21+
.pipe(Atom.withLabel(`mobile-peer-pairing-code:${environmentId}`)),
22+
);
23+
24+
/**
25+
* A fresh pairing code minted on `environmentId` with this client's session
26+
* there, for answering a link request. Fails with `PeerPairingCodeError` when
27+
* the session may not create one.
28+
*/
29+
export function mintPairingCodeOn(environmentId: EnvironmentId): Promise<string> {
30+
const atom = peerPairingCodeAtom(environmentId);
31+
appAtomRegistry.refresh(atom);
32+
return Effect.runPromise(
33+
Effect.scoped(
34+
Effect.gen(function* () {
35+
yield* AtomRegistry.mount(appAtomRegistry, atom);
36+
return yield* AtomRegistry.getResult(appAtomRegistry, atom, {
37+
suspendOnWaiting: true,
38+
}).pipe(Effect.timeout("15 seconds"));
39+
}),
40+
),
41+
);
42+
}

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -761,6 +761,10 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null {
761761
return `Created thread ${item.targetThreadId} with ${item.targetProviderInstanceId} (${item.targetModel}).`;
762762
case "secret_request":
763763
return `Asked the user for ${item.label}: ${item.secretStatus}.`;
764+
case "link_request":
765+
return item.linkStatus === "linked"
766+
? `Linked ${item.linkedLabel ?? item.label ?? item.url ?? "an environment"} (${item.linkedAccess}).`
767+
: `Asked the user to link ${item.label ?? item.url ?? "an environment"}: ${item.linkStatus}.`;
764768
case "subagent":
765769
return item.result ?? item.progress ?? item.prompt;
766770
case "dynamic_tool":

‎apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
8282
import * as McpHttpServer from "./McpHttpServer.ts";
8383
import * as McpInvocationContext from "./McpInvocationContext.ts";
8484
import * as PeerForwarding from "../peer/PeerForwarding.ts";
85+
import * as PeerLinkRequests from "../peer/PeerLinkRequests.ts";
86+
import * as PeerLinks from "../peer/PeerLinks.ts";
8587
import { delegatedTaskRun, hasPendingChildRuns } from "./OrchestratorMcpService.ts";
8688
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
8789

@@ -696,6 +698,8 @@ describe("orchestrator MCP toolkit", () => {
696698
Layer.provide(ServerSettings.layerTest()),
697699
Layer.provide(layerScheduledTaskStub),
698700
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
701+
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
702+
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
699703
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
700704
Layer.provide(
701705
Layer.mock(ProjectService.ProjectService)({
@@ -3831,6 +3835,8 @@ describe("orchestrator MCP toolkit", () => {
38313835
Layer.provide(ServerSettings.layerTest()),
38323836
Layer.provide(layerUnusedScheduledTaskStub),
38333837
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
3838+
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
3839+
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
38343840
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
38353841
Layer.provideMerge(
38363842
SecretRequests.layer.pipe(

‎apps/server/src/mcp/linkOrigin.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ import * as McpHttpServer from "./McpHttpServer.ts";
4343
import * as McpInvocationContext from "./McpInvocationContext.ts";
4444
import * as PeerForwarding from "../peer/PeerForwarding.ts";
4545
import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
46+
import * as PeerLinkRequests from "../peer/PeerLinkRequests.ts";
47+
import * as PeerLinks from "../peer/PeerLinks.ts";
4648

4749
// A linked environment's session drives this one's real orchestrator through
4850
// its real T3 tools. What the link starts carries its origin, and the link
@@ -134,6 +136,8 @@ const layerTools = Layer.mergeAll(
134136
),
135137
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
136138
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
139+
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
140+
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
137141
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
138142
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
139143
Layer.provide(

‎apps/server/src/mcp/toolkits/core.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ import { ProjectToolkit } from "./project/tools.ts";
5959
import { AttachmentToolkit } from "./attachment/tools.ts";
6060
import * as AttachmentHandlers from "./attachment/handlers.ts";
6161
import * as PeerForwarding from "../../peer/PeerForwarding.ts";
62+
import * as PeerLinkRequests from "../../peer/PeerLinkRequests.ts";
63+
import * as PeerLinks from "../../peer/PeerLinks.ts";
6264
import { ThreadToolkit } from "./thread/tools.ts";
6365
import { WorktreeToolkit } from "./worktree/tools.ts";
6466
import { DeviceToolkit } from "./device/tools.ts";
@@ -90,6 +92,8 @@ const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe(
9092
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
9193
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
9294
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
95+
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
96+
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
9397
);
9498

9599
it("publishes unique tool names with reference-free object-root inputs", () => {
@@ -592,6 +596,8 @@ it.effect("refuses act-as-caller tools to a client caller", () =>
592596
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
593597
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
594598
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
599+
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
600+
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
595601
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
596602
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
597603
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
@@ -649,6 +655,8 @@ it.effect("a caller cannot rewrite a scheduled task that runs above its own mode
649655
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
650656
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
651657
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
658+
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
659+
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
652660
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
653661
),
654662
),
@@ -736,6 +744,8 @@ it.effect.each(["t3_thread_interrupt", "t3_workflow_stop"])(
736744
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
737745
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
738746
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
747+
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
748+
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
739749
),
740750
),
741751
),
@@ -827,6 +837,8 @@ it.effect("discovers workflow stop targets and requires orchestration capability
827837
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
828838
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
829839
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
840+
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
841+
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
830842
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
831843
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
832844
Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),

‎apps/server/src/mcp/toolkits/orchestrator/handlers.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import type * as Tool from "effect/ai/Tool";
55
import { OrchestratorToolkit } from "./tools.ts";
66

77
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
8+
import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts";
9+
import * as PeerLinks from "../../../peer/PeerLinks.ts";
810
import { readCaller } from "../../threadAccess.ts";
911
import * as McpInvocationContext from "../../McpInvocationContext.ts";
1012
import * as McpToolAccess from "../../McpToolAccess.ts";
@@ -195,6 +197,29 @@ const handlers = {
195197
return yield* forwarding.links(scope);
196198
}),
197199
),
200+
// A link lets every agent here reach the other environment, so it is an
201+
// environment setting: full access, and never for linked work.
202+
t3_environment_link: McpToolAccess.writesEnvironment((input) =>
203+
Effect.gen(function* () {
204+
const scope = yield* McpInvocationContext.McpInvocationContext;
205+
const requests = yield* PeerLinkRequests.PeerLinkRequests;
206+
return yield* requests.request(scope, input);
207+
}),
208+
),
209+
t3_environment_unlink: McpToolAccess.writesEnvironment(({ environmentId }) =>
210+
Effect.gen(function* () {
211+
const links = yield* PeerLinks.PeerLinks;
212+
const removed = yield* links
213+
.unlink(environmentId)
214+
.pipe(
215+
Effect.mapError(
216+
(error) =>
217+
new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
218+
),
219+
);
220+
return { environmentId, removed };
221+
}),
222+
),
198223
t3_thread_interrupt: McpToolAccess.writesThreads(
199224
// A thread in a linked environment is checked there, where it lives.
200225
// This environment's own id names a thread here, which is checked here.

0 commit comments

Comments
 (0)