Skip to content

Commit 9a58f9b

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 ba435f8 commit 9a58f9b

42 files changed

Lines changed: 3559 additions & 45 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
@@ -1,5 +1,6 @@
11
import { ThreadContextDivider } from "./thread-context-divider";
22
import { ThreadHandoffRow } from "./thread-handoff-row";
3+
import { LinkRequestCard } from "./LinkRequestCard";
34
import { SecretRequestCard } from "./SecretRequestCard";
45
import {
56
WorktreeWorkingHeader,
@@ -164,6 +165,7 @@ import {
164165
threadFeedRunIsUnsettled,
165166
isContextCompactionActivityGroup,
166167
isContextHandoffActivityGroup,
168+
isLinkRequestActivityGroup,
167169
isSecretRequestActivityGroup,
168170
type ThreadFeedEntry,
169171
type ThreadFeedLatestRun,
@@ -1654,6 +1656,16 @@ function renderFeedEntry(
16541656
);
16551657
}
16561658

1659+
if (entry.type === "activity-group" && isLinkRequestActivityGroup(entry)) {
1660+
return (
1661+
<LinkRequestCard
1662+
environmentId={props.environmentId}
1663+
projectedItem={entry.activities[0]!.projectedItem}
1664+
iconColor={iconSubtleColor}
1665+
/>
1666+
);
1667+
}
1668+
16571669
if (entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) {
16581670
const label = entry.activities[0]!.summary;
16591671
const active =

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

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,12 @@ export function isSecretRequestActivityGroup(entry: ThreadFeedActivityGroup): bo
351351
);
352352
}
353353

354+
export function isLinkRequestActivityGroup(entry: ThreadFeedActivityGroup): boolean {
355+
return (
356+
entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "link_request"
357+
);
358+
}
359+
354360
function isUserInputActivityGroup(entry: ThreadFeedActivityGroup): boolean {
355361
return entry.activities.some((activity) => activity.workEntry.questionAnswer !== undefined);
356362
}
@@ -455,7 +461,8 @@ function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
455461
item.type === "thread_created" ||
456462
item.type === "system_notice" ||
457463
// An answerable card: it must stand alone and never fold away with the run.
458-
item.type === "secret_request"
464+
item.type === "secret_request" ||
465+
item.type === "link_request"
459466
);
460467
}
461468

@@ -575,6 +582,8 @@ function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
575582
return "zap";
576583
case "secret_request":
577584
return "lock";
585+
case "link_request":
586+
return "globe";
578587
}
579588
}
580589

@@ -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: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,31 @@
1+
import { linkableMachines } from "@t3tools/client-runtime/link-request";
12
import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks";
3+
import type { EnvironmentId } from "@t3tools/contracts";
4+
import { useMemo } from "react";
25

36
import { connectionAtomRuntime } from "../connection/runtime";
7+
import { useEnvironments } from "./environments";
8+
import { useEnvironmentQuery } from "./query";
49

510
export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);
11+
12+
/**
13+
* The user's other machines, for picking one to link `environmentId` to.
14+
* Reads that environment's links only while `enabled`, since listing them
15+
* asks every linked machine whether it answers.
16+
*/
17+
export function useLinkableMachines(environmentId: EnvironmentId, enabled: boolean) {
18+
const { environments } = useEnvironments();
19+
const links = useEnvironmentQuery(
20+
enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null,
21+
);
22+
return useMemo(
23+
() =>
24+
linkableMachines({
25+
environments,
26+
threadEnvironmentId: environmentId,
27+
linkedIds: new Set(links.data?.links.map((link) => link.environmentId)),
28+
}),
29+
[environmentId, environments, links.data],
30+
);
31+
}
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
@@ -794,6 +794,10 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null {
794794
return `Created thread ${item.targetThreadId} with ${item.targetProviderInstanceId} (${item.targetModel}).`;
795795
case "secret_request":
796796
return `Asked the user for ${item.label}: ${item.secretStatus}.`;
797+
case "link_request":
798+
return item.linkStatus === "linked"
799+
? `Linked ${item.linkedLabel ?? item.label ?? item.url ?? "an environment"} (${item.linkedAccess}).`
800+
: `Asked the user to link ${item.label ?? item.url ?? "an environment"}: ${item.linkStatus}.`;
797801
case "subagent":
798802
return item.result ?? item.progress ?? item.prompt;
799803
case "dynamic_tool":

‎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 { Tool } from "effect/ai";
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 * as RemoteDelegation from "../../../peer/RemoteDelegation.ts";
911
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
1012
import * as McpInvocationContext from "../../McpInvocationContext.ts";
@@ -214,6 +216,29 @@ const handlers = {
214216
return yield* forwarding.links(scope);
215217
}),
216218
),
219+
// A link lets every agent here reach the other environment, so it is an
220+
// environment setting: full access, and never for linked work.
221+
t3_environment_link: McpToolAccess.writesEnvironment((input) =>
222+
Effect.gen(function* () {
223+
const scope = yield* McpInvocationContext.McpInvocationContext;
224+
const requests = yield* PeerLinkRequests.PeerLinkRequests;
225+
return yield* requests.request(scope, input);
226+
}),
227+
),
228+
t3_environment_unlink: McpToolAccess.writesEnvironment(({ environmentId }) =>
229+
Effect.gen(function* () {
230+
const links = yield* PeerLinks.PeerLinks;
231+
const removed = yield* links
232+
.unlink(environmentId)
233+
.pipe(
234+
Effect.mapError(
235+
(error) =>
236+
new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
237+
),
238+
);
239+
return { environmentId, removed };
240+
}),
241+
),
217242
t3_thread_interrupt: McpToolAccess.writesThreads(
218243
// A thread in a linked environment is checked there, where it lives.
219244
// This environment's own id names a thread here, which is checked here.

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

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import {
22
OrchestratorMcpCapabilitiesInput,
33
OrchestratorMcpCapabilitiesResult,
4+
OrchestratorMcpEnvironmentLinkInput,
5+
OrchestratorMcpEnvironmentLinkResult,
46
OrchestratorMcpEnvironmentLinksResult,
7+
OrchestratorMcpEnvironmentUnlinkInput,
8+
OrchestratorMcpEnvironmentUnlinkResult,
59
OrchestratorMcpCreateThreadsInput,
610
OrchestratorMcpCreateThreadsResult,
711
OrchestratorMcpDelegateTaskInput,
@@ -36,6 +40,8 @@ import { Tool, Toolkit } from "effect/ai";
3640

3741
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
3842
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
43+
import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts";
44+
import * as PeerLinks from "../../../peer/PeerLinks.ts";
3945
import * as RemoteDelegation from "../../../peer/RemoteDelegation.ts";
4046
import * as McpInvocationContext from "../../McpInvocationContext.ts";
4147
import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts";
@@ -50,6 +56,12 @@ const dependencies = [
5056
const forwardingDependencies = [...dependencies, PeerForwarding.PeerForwarding];
5157
/** Delegated tasks whose child may run in a linked environment. */
5258
const delegationDependencies = [...dependencies, RemoteDelegation.RemoteDelegation];
59+
/** Making and forgetting links. */
60+
const linkingDependencies = [
61+
...dependencies,
62+
PeerLinkRequests.PeerLinkRequests,
63+
PeerLinks.PeerLinks,
64+
];
5365
const threadMetadataDependencies = [
5466
McpInvocationContext.McpInvocationContext,
5567
ThreadManagementService.ThreadManagementService,
@@ -267,7 +279,7 @@ const ThreadInterruptTool = Tool.make("t3_thread_interrupt", {
267279

268280
const EnvironmentLinksTool = Tool.make("t3_environment_links", {
269281
description:
270-
"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 t3_project_list, t3_thread_launch, t3_thread_list, t3_thread_read, t3_thread_send, t3_thread_wait, t3_thread_interrupt, or orchestrator_capabilities to act there. 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.",
282+
"List the other T3 Code environments this one is linked to, such as the user's other machines, and whether each answers now. A machine the user names that is not listed is not linked yet: call t3_environment_link for it rather than looking elsewhere. Pass one's environmentId to t3_project_list, t3_thread_launch, t3_thread_list, t3_thread_read, t3_thread_send, t3_thread_wait, t3_thread_interrupt, or orchestrator_capabilities to act there. 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.",
271283
success: OrchestratorMcpEnvironmentLinksResult,
272284
failure: OrchestratorMcpFailure,
273285
failureMode: "return",
@@ -278,6 +290,32 @@ const EnvironmentLinksTool = Tool.make("t3_environment_links", {
278290
.annotate(Tool.Destructive, false)
279291
.annotate(Tool.Idempotent, true);
280292

293+
const EnvironmentLinkTool = Tool.make("t3_environment_link", {
294+
description:
295+
'Ask the user to link another T3 Code environment, such as their VPS or another machine, so agents here can work there (t3_environment_links). Call it when the user asks to link, connect, or delegate to another machine. You usually do not know where it answers, so pass no address: pass a hint from their words ("vps") and the card lets the user pick the machine. Pass environmentId when a machine the user mentioned names it; if it is already linked, this returns linked at once. Pass url only when the user gave an address. The card lets the user pick the access agents here get there and approve it; their app signs in there with their own session, or they paste a pairing code from there into the card. It returns pending at once: the user answers in the card whenever they get to it, and the outcome (linked with the environmentId to pass to other tools, declined, or failed with the reason) arrives as a message in this thread. End your turn or keep working; do not poll or call it again to check. Never ask for a pairing code in chat.',
296+
parameters: OrchestratorMcpEnvironmentLinkInput,
297+
success: OrchestratorMcpEnvironmentLinkResult,
298+
failure: OrchestratorMcpFailure,
299+
failureMode: "return",
300+
dependencies: linkingDependencies,
301+
})
302+
.annotate(Tool.Title, "Link another environment")
303+
.annotate(Tool.Destructive, false)
304+
.annotate(Tool.OpenWorld, true);
305+
306+
const EnvironmentUnlinkTool = Tool.make("t3_environment_unlink", {
307+
description:
308+
"Forget a linked environment, so agents here stop working there. The session there stays listed in that environment's Connections until it is revoked there.",
309+
parameters: OrchestratorMcpEnvironmentUnlinkInput,
310+
success: OrchestratorMcpEnvironmentUnlinkResult,
311+
failure: OrchestratorMcpFailure,
312+
failureMode: "return",
313+
dependencies: linkingDependencies,
314+
})
315+
.annotate(Tool.Title, "Forget a linked environment")
316+
.annotate(Tool.Destructive, true)
317+
.annotate(Tool.Idempotent, true);
318+
281319
export const OrchestratorToolkit = Toolkit.make(
282320
OrchestratorCapabilitiesTool,
283321
DelegateTaskTool,
@@ -296,4 +334,6 @@ export const OrchestratorToolkit = Toolkit.make(
296334
ThreadWaitTool,
297335
ThreadInterruptTool,
298336
EnvironmentLinksTool,
337+
EnvironmentLinkTool,
338+
EnvironmentUnlinkTool,
299339
);

‎apps/server/src/observability/RpcInstrumentation.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ const RPC_AGGREGATES = {
5656
[WS_METHODS.peerLinksList]: "peerLinks",
5757
[WS_METHODS.peerLinksLink]: "peerLinks",
5858
[WS_METHODS.peerLinksUnlink]: "peerLinks",
59+
[WS_METHODS.peerLinksAnswerRequest]: "peerLinks",
5960
[WS_METHODS.serverUpdateSettings]: "server",
6061
[WS_METHODS.serverSearchAcpRegistry]: "server",
6162
[WS_METHODS.serverPrepareAcpRegistryAgent]: "server",

0 commit comments

Comments
 (0)