The best way to control Claude Code, Codex and more from any computer or phone
feat(server): work a linked environment starts stays within its link (#16695)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Julius Marminge committed
Oct 27, 2026 at 14:04 UTC
6918c35a367a63739baa74d056f06ba40e5ede25
37 files changed
+1002
-134
apps/server/src/auth/EnvironmentAuth.ts
+5
@@ -92,6 +92,8 @@ export interface McpClientSession {
92
readonly sessionId: AuthSessionId;
93
readonly label: string;
94
readonly access: AuthMcpClientAccess;
95
+ /** Another T3 Code environment's link, whose work here stays within it. */
96
+ readonly peerLink: boolean;
97
}
98
99
export interface AuthenticatedSession {
@@ -555,6 +557,7 @@ export class EnvironmentAuth extends Context.Service<
557
readonly issueMcpClientSession: (input: {
558
readonly label: string;
559
readonly access: AuthMcpClientAccess;
560
+ readonly peerLink: boolean;
561
readonly client: AuthClientMetadata;
562
}) => Effect.Effect<
563
{
@@ -1305,6 +1308,7 @@ export const make = Effect.gen(function* () {
1308
access: session.scopes.includes(AuthOrchestrationOperateScope)
1309
? (session.runtimeModeCeiling ?? "approval-required")
1310
: "read-only",
1311
+ peerLink: session.peerLink === true,
1312
} satisfies McpClientSession)
1313
: Effect.fail(
1314
new ServerAuthInvalidCredentialError({
@@ -1324,6 +1328,7 @@ export const make = Effect.gen(function* () {
1328
scopes: mcpClientScopes(input.access),
1329
ttl: MCP_CLIENT_SESSION_TTL,
1330
...(input.access === "read-only" ? {} : { runtimeModeCeiling: input.access }),
1331
+ peerLink: input.peerLink,
1332
client: { ...input.client, label: input.label, deviceType: "bot" },
1333
})
1334
.pipe(
apps/server/src/auth/McpOAuth.ts
+25
-4
@@ -13,6 +13,7 @@ import {
13
type AuthEnvironmentScope,
14
AuthOrchestrationOperateScope,
15
AuthOrchestrationReadScope,
16
+ MCP_PEER_LINK_SOFTWARE_ID,
17
} from "@t3tools/contracts";
18
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
19
import * as Clock from "effect/Clock";
@@ -132,6 +133,8 @@ const ClientIdPayload = Schema.Struct({
133
v: Schema.Literal(1),
134
n: Schema.String,
135
r: Schema.Array(Schema.String),
136
+ /** Registered as another T3 Code environment's peer link. */
137
+ p: Schema.optionalKey(Schema.Literal(1)),
138
});
139
const decodeClientIdPayload = Schema.decodeUnknownOption(Schema.fromJsonString(ClientIdPayload));
140
@@ -139,6 +142,7 @@ export interface McpOAuthClient {
142
readonly clientId: string;
143
readonly name: string;
144
readonly redirectUris: ReadonlyArray<string>;
145
+ readonly peerLink: boolean;
146
}
147
148
export class McpOAuthPageError extends Schema.TaggedError<McpOAuthPageError>()(
@@ -172,6 +176,7 @@ export interface AuthorizationRequest {
176
interface PendingCode {
177
readonly clientId: string;
178
readonly clientName: string;
179
+ readonly peerLink: boolean;
180
readonly redirectUri: string;
181
readonly codeChallenge: string;
182
readonly resource: string;
@@ -240,8 +245,10 @@ const make = Effect.gen(function* () {
245
246
const sign = (domain: string, payload: string) => signPayload(`${domain}.${payload}`, signingKey);
247
243
- const signClientId = (name: string, redirectUris: ReadonlyArray<string>) => {
244
- const body = base64UrlEncode(JSON.stringify({ v: 1, n: name, r: redirectUris }));
248
+ const signClientId = (name: string, redirectUris: ReadonlyArray<string>, peerLink: boolean) => {
249
+ const body = base64UrlEncode(
250
+ JSON.stringify({ v: 1, n: name, r: redirectUris, ...(peerLink ? { p: 1 } : {}) }),
251
+ );
252
return `${body}.${sign("mcp-client-id", body)}`;
253
};
254
@@ -257,7 +264,12 @@ const make = Effect.gen(function* () {
264
}
265
return Option.getOrUndefined(
266
decodeClientIdPayload(json).pipe(
260
- Option.map((payload) => ({ clientId, name: payload.n, redirectUris: payload.r })),
267
+ Option.map((payload) => ({
268
+ clientId,
269
+ name: payload.n,
270
+ redirectUris: payload.r,
271
+ peerLink: payload.p === 1,
272
+ })),
273
),
274
);
275
};
@@ -303,7 +315,13 @@ const make = Effect.gen(function* () {
315
});
316
}
317
// RFC 7591 allows ignoring unsupported registration options; all clients use public PKCE.
306
- return { clientId: signClientId(name, redirectUris), name, redirectUris };
318
+ const peerLink = metadata.software_id === MCP_PEER_LINK_SOFTWARE_ID;
319
+ return {
320
+ clientId: signClientId(name, redirectUris, peerLink),
321
+ name,
322
+ redirectUris,
323
+ peerLink,
324
+ };
325
},
326
);
327
@@ -385,6 +403,7 @@ const make = Effect.gen(function* () {
403
next.set(code, {
404
clientId: authorization.client.clientId,
405
clientName: authorization.client.name,
406
+ peerLink: authorization.client.peerLink,
407
redirectUri: authorization.redirectUri,
408
codeChallenge: authorization.codeChallenge,
409
resource: authorization.resource,
@@ -488,6 +507,7 @@ const make = Effect.gen(function* () {
507
.issueMcpClientSession({
508
label: pending.clientName,
509
access: pending.access,
510
+ peerLink: pending.peerLink,
511
client: deriveAuthClientMetadata({ request }),
512
})
513
.pipe(
@@ -540,6 +560,7 @@ export const layerMcpClientAuthenticator = Layer.effect(
560
sessionId: client.sessionId,
561
label: client.label,
562
access: client.access,
563
+ linked: client.peerLink,
564
},
565
capabilities: new Set<McpInvocationContext.McpCapability>([
566
"orchestration",
apps/server/src/auth/SessionStore.ts
+7
@@ -60,6 +60,8 @@ export interface VerifiedSession {
60
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
61
readonly proofKeyThumbprint?: string;
62
readonly runtimeModeCeiling?: RuntimeMode;
63
+ /** An MCP client that is another T3 Code environment's peer link. */
64
+ readonly peerLink?: true;
65
}
66
67
export interface VerifiedWebSocketTicket extends VerifiedSession {
@@ -381,6 +383,7 @@ export class SessionStore extends Context.Service<
383
readonly client?: AuthClientMetadata;
384
readonly proofKeyThumbprint?: string;
385
readonly runtimeModeCeiling?: RuntimeMode;
386
+ readonly peerLink?: boolean;
387
readonly replaceActiveForSubjectAndMethod?: boolean;
388
readonly replaceSessionId?: AuthSessionId;
389
}) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
@@ -441,6 +444,8 @@ const SessionClaims = Schema.Struct({
444
method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),
445
jkt: Schema.optionalKey(Schema.String),
446
rtc: Schema.optionalKey(RuntimeMode),
447
+ /** Signed, so a client cannot shed its peer link's limits. */
448
+ plk: Schema.optionalKey(Schema.Literal(1)),
449
iat: Schema.Number,
450
exp: Schema.Number,
451
});
@@ -679,6 +684,7 @@ const make = Effect.gen(function* () {
684
method: input?.method ?? "browser-session-cookie",
685
...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
686
...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}),
687
+ ...(input?.peerLink === true ? { plk: 1 as const } : {}),
688
iat: issuedAt.epochMilliseconds,
689
exp: expiresAt.epochMilliseconds,
690
};
@@ -860,6 +866,7 @@ const make = Effect.gen(function* () {
866
scopes: claims.scopes,
867
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
868
...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}),
869
+ ...(claims.plk === 1 ? { peerLink: true as const } : {}),
870
} satisfies VerifiedSession;
871
},
872
);
apps/server/src/cli/thread.ts
+1
@@ -221,6 +221,7 @@ const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* <A, E,
221
// The CLI runs as the machine's owner. New threads still start at
222
// the project's default mode, never at this ceiling by default.
223
access: "full-access",
224
+ peerLink: false,
225
client: { deviceType: "bot" },
226
}),
227
(session) =>
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -267,6 +267,7 @@ export const make = Effect.gen(function* () {
267
serverBrowser: true,
268
peerLinks: true,
269
mcpModeLimitHeader: true,
270
+ linkFence: true,
271
},
272
};
273
apps/server/src/mcp/McpHttpServer.test.ts
+1
@@ -982,6 +982,7 @@ it.effect(
982
(input) => input,
983
(_, modes) =>
984
Effect.succeed({ modes: `${modes.runtimeMode}/${modes.interactionMode}` }),
985
+ "stamped",
986
),
987
}),
988
).pipe(
apps/server/src/mcp/McpInvocationContext.ts
+5
@@ -34,6 +34,11 @@ export interface McpClientCaller {
34
readonly sessionId: string;
35
readonly label: string;
36
readonly access: AuthMcpClientAccess;
37
+ /**
38
+ * Another T3 Code environment's peer link. What it starts here carries its
39
+ * session as `linkOrigin`, and it changes only that work (`linkOrigin.ts`).
40
+ */
41
+ readonly linked?: boolean | undefined;
42
/**
43
* Narrower modes the client asked for on this request (`T3-Mode-Limit`):
44
* another environment passing on the limits of the agent it calls for.
apps/server/src/mcp/McpToolAccess.test.ts
+15
-1
@@ -144,6 +144,7 @@ const probeHandlers: McpToolAccess.Handlers<typeof ProbeToolkit.tools> = {
144
starts_threads: McpToolAccess.startsThreads(
145
(input) => input,
146
(_, modes) => Effect.succeed({ ran: `${modes.runtimeMode}/${modes.interactionMode}` }),
147
+ "stamped",
148
),
149
writes_environment: McpToolAccess.writesEnvironment(() => ran),
150
};
@@ -231,6 +232,15 @@ const mismatchedProvider = {
232
const supervisedClient = clientCaller("approval-required");
233
const fullAccessClient = clientCaller("full-access");
234
const readOnlyClient = clientCaller("read-only");
235
+const linkedClient: McpInvocationContext.McpInvocationScope = {
236
+ ...supervisedClient,
237
+ client: { ...supervisedClient.client!, linked: true },
238
+};
239
+// A full-access link's agents can do anything this environment's user can.
240
+const fullAccessLinkedClient: McpInvocationContext.McpInvocationScope = {
241
+ ...fullAccessClient,
242
+ client: { ...fullAccessClient.client!, linked: true },
243
+};
244
const previewOnly = { ...fullAccess, capabilities: new Set(["preview"] as const) };
245
246
it.effect.each([
@@ -265,6 +275,10 @@ it.effect.each([
275
["writes_with_capability", previewOnly, {}, "ran"],
276
["writes_with_capability", readOnlyClient, {}, "capability_denied"],
277
["writes_with_capability", ended, {}, "parent_not_active"],
278
+ ["writes", linkedClient, {}, "capability_denied"],
279
+ ["writes_with_capability", linkedClient, {}, "capability_denied"],
280
+ ["writes", fullAccessLinkedClient, {}, "ran"],
281
+ ["writes_with_capability", fullAccessLinkedClient, {}, "ran"],
282
283
["writes_threads", supervised, {}, "ran"],
284
["writes_threads", supervised, { threadId: planThreadId }, "ran"],
@@ -374,7 +388,7 @@ const linkedProbeServer = McpHttpServer.toolkitRegistration(
388
writes: McpToolAccess.writes(ranHere),
389
writes_with_capability: McpToolAccess.writesWithCapability(ranHere),
390
writes_threads: McpToolAccess.writesThreads((input) => [input.threadId], ranHere),
377
- starts_threads: McpToolAccess.startsThreads((input) => input, ranHere),
391
+ starts_threads: McpToolAccess.startsThreads((input) => input, ranHere, "stamped"),
392
writes_environment: McpToolAccess.writesEnvironment(ranHere),
393
}),
394
).pipe(
apps/server/src/mcp/McpToolAccess.ts
+66
-11
@@ -1,5 +1,6 @@
1
import {
2
type EnvironmentId,
3
+ type OrchestrationV2LinkOrigin,
4
OrchestratorMcpEnvironmentTarget,
5
OrchestratorMcpFailure,
6
type ProviderInteractionMode,
@@ -20,6 +21,7 @@ import {
21
type DispatchModeRefusal,
22
} from "../orchestration-v2/DispatchModeLimit.ts";
23
import * as PeerForwarding from "../peer/PeerForwarding.ts";
24
+import { assertNotLinked, assertSameLink, callerLinkOrigin } from "./linkOrigin.ts";
25
import * as McpInvocationContext from "./McpInvocationContext.ts";
26
import { resolveInteractionMode, resolveRuntimeMode } from "./OrchestratorMcpService.ts";
27
import {
@@ -135,16 +137,39 @@ export const actsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A,
137
undefined,
138
);
139
138
-export const writes = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
140
+/**
141
+ * Changes something that belongs to no thread, such as a pending upload or a
142
+ * scheduled task. Work a linked environment started may not: none of it
143
+ * carries the link's origin, so none of it is that link's.
144
+ */
145
+export const writes = <P, A, E, R>(
146
+ handle: (params: P) => Effect.Effect<A, E, R>,
147
+ options?: {
148
+ /** Whether a linked caller may make it, as for uploads its own sends need. */
149
+ readonly linkedCallers?: "allowed";
150
+ },
151
+) =>
152
declare(
140
- (params: P) => orchestratingCaller.pipe(Effect.flatMap(() => handle(params))),
153
+ (params: P) =>
154
+ orchestratingCaller.pipe(
155
+ Effect.tap((caller) =>
156
+ options?.linkedCallers === "allowed"
157
+ ? Effect.void
158
+ : assertNotLinked(caller, "change this environment's scheduled tasks"),
159
+ ),
160
+ Effect.flatMap(() => handle(params)),
161
+ ),
162
() => orchestratingCaller,
163
);
164
144
-/** Requires handler capability checks, not thread control. */
165
+/** Requires handler capability checks, not thread control; linked work is refused the same way. */
166
export const writesWithCapability = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
167
declare(
147
- (params: P) => writingCaller.pipe(Effect.flatMap(() => handle(params))),
168
+ (params: P) =>
169
+ writingCaller.pipe(
170
+ Effect.tap((caller) => assertNotLinked(caller, "start work here that is not its link's")),
171
+ Effect.flatMap(() => handle(params)),
172
+ ),
173
() => writingCaller,
174
);
175
@@ -163,6 +188,7 @@ export const writesThreads = <P, A, E, R>(
188
.pipe(Effect.mapError(unavailable));
189
if (target !== null && target.deletedAt === null) {
190
yield* assertTargetWithinLimits(caller.limits, target);
191
+ yield* assertSameLink(caller, target);
192
}
193
}
194
// Modes can rise after this check; the orchestrator rechecks under lock and records refusal before handlers wrap errors.
@@ -193,29 +219,42 @@ const escalationDenied = (refusal: DispatchModeRefusal) =>
219
export interface StartedModes {
220
readonly runtimeMode: RuntimeMode;
221
readonly interactionMode: ProviderInteractionMode;
222
+ /** The linked environment the caller acts for. The thread must carry it. */
223
+ readonly linkOrigin: OrchestrationV2LinkOrigin | undefined;
224
}
225
226
+/**
227
+ * Starts threads with the modes `modes` requests, which may not be broader
228
+ * than the caller's. `linked` says what a linked caller gets: threads stamped
229
+ * with its `linkOrigin`, or a refusal where the tool cannot carry one.
230
+ */
231
export const startsThreads = <P, A, E, R>(
232
modes: (params: P) => {
233
readonly runtimeMode?: RuntimeMode | undefined;
234
readonly interactionMode?: ProviderInteractionMode | undefined;
235
},
236
handle: (params: P, modes: StartedModes) => Effect.Effect<A, E, R>,
237
+ linked: "stamped" | { readonly refused: string },
238
) => {
205
- const started = Effect.fn("McpToolAccess.started")(function* (params: P) {
206
- const { limits } = yield* writingCaller;
239
+ const started = Effect.fn("McpToolAccess.started")(function* (caller: Caller, params: P) {
240
const requested = modes(params);
241
return {
209
- runtimeMode: yield* resolveRuntimeMode(limits.runtimeMode, requested.runtimeMode),
242
+ runtimeMode: yield* resolveRuntimeMode(caller.limits.runtimeMode, requested.runtimeMode),
243
interactionMode: yield* resolveInteractionMode(
211
- limits.interactionMode,
244
+ caller.limits.interactionMode,
245
requested.interactionMode,
246
),
247
+ linkOrigin: callerLinkOrigin(caller),
248
} satisfies StartedModes;
249
});
250
return declare(
217
- (params: P) => Effect.flatMap(started(params), (modes) => handle(params, modes)),
218
- started,
251
+ (params: P) =>
252
+ Effect.gen(function* () {
253
+ const caller = yield* writingCaller;
254
+ if (linked !== "stamped") yield* assertNotLinked(caller, linked.refused);
255
+ return yield* handle(params, yield* started(caller, params));
256
+ }),
257
+ (params: P) => Effect.flatMap(writingCaller, (caller) => started(caller, params)),
258
);
259
};
260
@@ -251,13 +290,29 @@ export const writesEnvironment = <P, A, E, R>(
290
params: P,
291
check: Effect.Effect<Caller, OrchestratorMcpFailure, CheckServices>,
292
) => Effect.Effect<A, E, R>,
293
+ options?: {
294
+ /**
295
+ * Whether a linked caller may make it, as for adding a project: it leaves
296
+ * everything already here as it was.
297
+ */
298
+ readonly linkedCallers?: "allowed";
299
+ },
300
) => {
301
const check = orchestratingCaller.pipe(
302
+ Effect.tap((caller) =>
303
+ options?.linkedCallers === "allowed"
304
+ ? Effect.void
305
+ : assertNotLinked(caller, "change projects or environment settings"),
306
+ ),
307
Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)),
308
);
309
return declare(
310
(params: P) => check.pipe(Effect.flatMap(() => handle(params, check))),
260
- () => check,
311
+ // Linked work never reaches a link at all; that is checked as the call goes.
312
+ () =>
313
+ orchestratingCaller.pipe(
314
+ Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)),
315
+ ),
316
);
317
};
318
apps/server/src/mcp/OrchestratorMcpService.ts
+3
@@ -2584,6 +2584,9 @@ const make = Effect.gen(function* () {
2584
interactionMode,
2585
branch: parent.thread.branch,
2586
worktreePath: parent.thread.worktreePath,
2587
+ ...(parent.thread.linkOrigin === undefined
2588
+ ? {}
2589
+ : { linkOrigin: parent.thread.linkOrigin }),
2590
})
2591
.pipe(
2592
Effect.mapError((error) =>
apps/server/src/mcp/WorktreeMcpService.ts
+3
-1
@@ -357,7 +357,9 @@ const make = Effect.gen(function* () {
357
scriptName: result.scriptName,
358
terminalId: result.terminalId,
359
}
360
- : { status: "no-script" },
360
+ : result.status === "skipped-for-link"
361
+ ? { status: "skipped" }
362
+ : { status: "no-script" },
363
),
364
reportFailed("worktree handoff setup script failed"),
365
);
apps/server/src/mcp/linkOrigin.test.ts
new
+387
@@ -0,0 +1,387 @@
1
+import * as DocumentText from "../provider/DocumentText.ts";
2
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3
+import * as NodeServices from "@effect/platform-node/NodeServices";
4
+import { assert, it } from "@effect/vitest";
5
+import {
6
+ CommandId,
7
+ ContextTransferId,
8
+ EnvironmentId,
9
+ NodeId,
10
+ type OrchestrationV2Run,
11
+ ProjectId,
12
+ ProviderDriverKind,
13
+ ProviderInstanceId,
14
+ RunId,
15
+ ThreadId,
16
+} from "@t3tools/contracts";
17
+import * as Effect from "effect/Effect";
18
+import * as Layer from "effect/Layer";
19
+import { McpSchema, McpServer } from "effect/ai";
20
+
21
+import * as ServerConfig from "../config.ts";
22
+import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
23
+import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
24
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
25
+import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
26
+import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
27
+import { makeSubagentChildThread } from "@t3tools/provider-core/server/subagentProjection";
28
+import * as ThreadForkService from "../orchestration-v2/ThreadForkService.ts";
29
+import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
30
+import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
31
+import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
32
+import * as SqlitePersistence from "../persistence/Sqlite.ts";
33
+import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
34
+import * as ProjectService from "../project/ProjectService.ts";
35
+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
36
+import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
37
+import * as ServerSettings from "../serverSettings.ts";
38
+import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
39
+import * as SecretRequests from "../secrets/SecretRequests.ts";
40
+import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
41
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
42
+import * as McpHttpServer from "./McpHttpServer.ts";
43
+import * as McpInvocationContext from "./McpInvocationContext.ts";
44
+import * as PeerForwarding from "../peer/PeerForwarding.ts";
45
+import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
46
+
47
+// A linked environment's session drives this one's real orchestrator through
48
+// its real T3 tools. What the link starts carries its origin, and the link
49
+// changes only that.
50
+
51
+const instanceId = ProviderInstanceId.make("codex");
52
+const projectId = ProjectId.make("project:link-origin");
53
+const adapter = {
54
+ instanceId,
55
+ driver: ProviderDriverKind.make("codex"),
56
+ getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
57
+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
58
+ openSession: () => Effect.die("No provider process needed for these commands"),
59
+} as ProviderAdapter.ProviderAdapterV2["Service"];
60
+const layerDatabase = SqlitePersistence.layerMemory;
61
+const layerOrchestrator = Layer.mergeAll(
62
+ layerDatabase,
63
+ ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
64
+ ProviderReplayHarness.layerWithRegistry(
65
+ { name: "link-origin" },
66
+ ProviderAdapterRegistry.layerFromAdapters([adapter]),
67
+ { databaseLayer: layerDatabase, runEffectWorker: false },
68
+ ),
69
+);
70
+const layerOrchestration = ThreadManagement.layer.pipe(
71
+ Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
72
+ Layer.provideMerge(Layer.merge(layerOrchestrator, ServerSettings.layerTest())),
73
+);
74
+
75
+/** Launches dispatch the real thread.create, and nothing more: no workspace, no run. */
76
+const layerLaunches = Layer.effect(
77
+ ThreadLaunch.ThreadLaunchService,
78
+ Effect.gen(function* () {
79
+ const threads = yield* ThreadManagement.ThreadManagementService;
80
+ return ThreadLaunch.ThreadLaunchService.of({
81
+ launch: (input: ThreadLaunch.ThreadLaunchInput) =>
82
+ threads
83
+ .dispatch({
84
+ type: "thread.create",
85
+ commandId: input.commandId,
86
+ threadId: input.threadId!,
87
+ projectId: input.projectId,
88
+ title: input.title,
89
+ modelSelection: input.modelSelection,
90
+ runtimeMode: input.runtimeMode,
91
+ interactionMode: input.interactionMode,
92
+ branch: null,
93
+ worktreePath: null,
94
+ ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),
95
+ createdBy: input.createdBy,
96
+ creationSource: input.creationSource,
97
+ })
98
+ .pipe(
99
+ Effect.flatMap(() => threads.getThreadProjection(input.threadId!)),
100
+ Effect.map((projection) => ({
101
+ threadId: input.threadId!,
102
+ projection,
103
+ resumed: false,
104
+ })),
105
+ Effect.orDie,
106
+ ),
107
+ } as unknown as ThreadLaunch.ThreadLaunchService["Service"]);
108
+ }),
109
+);
110
+
111
+const layerTools = Layer.mergeAll(
112
+ McpHttpServer.layerOrchestratorToolkit,
113
+ McpHttpServer.layerThreadToolkit,
114
+ McpHttpServer.layerProjectRegistration,
115
+).pipe(
116
+ Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
117
+ Layer.provideMerge(McpServer.McpServer.layer),
118
+ Layer.provide(layerLaunches),
119
+ Layer.provide(NodeCrypto.layer),
120
+ Layer.provide(
121
+ Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
122
+ ),
123
+ Layer.provide(
124
+ Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
125
+ list: () => Effect.succeed([]),
126
+ }),
127
+ ),
128
+ Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
129
+ Layer.provide(
130
+ Layer.mock(ProjectService.ProjectService)({
131
+ getById: () => Effect.succeedNone,
132
+ create: (input) =>
133
+ Effect.succeed({
134
+ id: input.projectId,
135
+ title: input.title,
136
+ workspaceRoot: input.workspaceRoot,
137
+ defaultModelSelection: null,
138
+ scripts: [],
139
+ createdAt: "2026-10-18T00:00:00.000Z",
140
+ updatedAt: "2026-10-18T00:00:00.000Z",
141
+ deletedAt: null,
142
+ }),
143
+ update: (input) =>
144
+ Effect.succeed({
145
+ id: input.projectId,
146
+ title: input.title ?? "Untitled",
147
+ workspaceRoot: "/p/t3code",
148
+ defaultModelSelection: null,
149
+ scripts: [],
150
+ createdAt: "2026-10-18T00:00:00.000Z",
151
+ updatedAt: "2026-10-18T00:00:00.000Z",
152
+ deletedAt: null,
153
+ }),
154
+ }),
155
+ ),
156
+ Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
157
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
158
+ Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
159
+ Layer.provide(
160
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/p" }),
161
+ ),
162
+ Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
163
+ Layer.provide(
164
+ Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
165
+ cloneRepository: (input) =>
166
+ Effect.succeed({
167
+ cwd: input.destinationPath,
168
+ remoteUrl: "https://github.com/pingdotgg/t3code.git",
169
+ repository: null,
170
+ }),
171
+ }),
172
+ ),
173
+ Layer.provide(
174
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-link-origin-" }).pipe(
175
+ Layer.provide(NodeServices.layer),
176
+ ),
177
+ ),
178
+ Layer.provide(NodeServices.layer),
179
+);
180
+
181
+const mcpClient = McpSchema.McpServerClient.of({
182
+ clientId: 1,
183
+ protocolVersion: "2025-06-18",
184
+ clientCapabilities: {},
185
+ clientInfo: { name: "link-origin", version: "1" },
186
+ initializePayload: {
187
+ protocolVersion: "2025-06-18",
188
+ capabilities: {},
189
+ clientInfo: { name: "link-origin", version: "1" },
190
+ },
191
+ getClient: Effect.die("unused"),
192
+});
193
+
194
+const clientScope = (
195
+ sessionId: string,
196
+ linked: boolean,
197
+ access: McpInvocationContext.McpClientCaller["access"],
198
+): McpInvocationContext.McpInvocationScope => ({
199
+ environmentId: EnvironmentId.make("environment:box"),
200
+ requestNamespace: `client:${sessionId}`,
201
+ thread: undefined,
202
+ client: { sessionId, label: `T3 Code · ${sessionId}`, access, linked },
203
+ capabilities: new Set(["orchestration", "worktree", "pull-requests"]),
204
+ issuedAt: 0,
205
+});
206
+const laptop = clientScope("laptop", true, "auto");
207
+const desk = clientScope("desk", true, "auto");
208
+const trusted = clientScope("trusted", true, "full-access");
209
+const claudeCode = clientScope("claude-code", false, "full-access");
210
+
211
+const call = (
212
+ scope: McpInvocationContext.McpInvocationScope,
213
+ name: string,
214
+ args: Record<string, unknown>,
215
+) =>
216
+ McpServer.McpServer.pipe(
217
+ Effect.flatMap((server) => server.callTool({ name, arguments: args })),
218
+ Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
219
+ Effect.provideService(McpSchema.McpServerClient, mcpClient),
220
+ );
221
+
222
+const failureCode = (result: McpSchema.CallToolResult) => {
223
+ const text = result.content[0];
224
+ return result.isError === true && text?.type === "text"
225
+ ? (JSON.parse(text.text) as { code: string }).code
226
+ : undefined;
227
+};
228
+
229
+const launch = (scope: McpInvocationContext.McpInvocationScope, title: string) =>
230
+ call(scope, "t3_thread_launch", {
231
+ projectId,
232
+ title,
233
+ modelSelection: { instanceId, model: "gpt-5" },
234
+ }).pipe(
235
+ Effect.map((result) => {
236
+ assert.equal(result.isError, false, JSON.stringify(result.content));
237
+ return (result.structuredContent as { threadId: ThreadId }).threadId;
238
+ }),
239
+ );
240
+
241
+const usersOwnThread = Effect.gen(function* () {
242
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
243
+ const threadId = ThreadId.make("thread:users-own");
244
+ yield* orchestrator.dispatch({
245
+ type: "thread.create",
246
+ commandId: CommandId.make("create:users-own"),
247
+ threadId,
248
+ projectId,
249
+ title: "The user's own",
250
+ modelSelection: { instanceId, model: "gpt-5" },
251
+ // Within an `auto` link's modes, so only the fence decides.
252
+ runtimeMode: "auto",
253
+ interactionMode: "default",
254
+ branch: null,
255
+ worktreePath: null,
256
+ createdBy: "user",
257
+ creationSource: "web",
258
+ });
259
+ return threadId;
260
+});
261
+
262
+it.layer(Layer.provideMerge(layerTools, layerOrchestration))("work a link starts", (it) => {
263
+ it.effect("is stamped, and so is the work it derives", () =>
264
+ Effect.gen(function* () {
265
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
266
+ const launched = yield* launch(laptop, "Started from the laptop");
267
+ const shell = yield* projections.getThreadShell(launched);
268
+ assert.deepEqual(shell?.linkOrigin, {
269
+ sessionId: "laptop",
270
+ label: "T3 Code · laptop",
271
+ access: "auto",
272
+ });
273
+
274
+ // A subagent of it and a fork of it are built from its thread, origin included.
275
+ const thread = (yield* ThreadManagement.ThreadManagementService.pipe(
276
+ Effect.flatMap((threads) => threads.getThreadProjection(launched)),
277
+ )).thread;
278
+ const child = makeSubagentChildThread({
279
+ parentThread: thread,
280
+ childThreadId: ThreadId.make("thread:child"),
281
+ parentNodeId: NodeId.make("node:child"),
282
+ activeProviderThreadId: null,
283
+ providerInstanceId: instanceId,
284
+ modelSelection: { instanceId, model: "gpt-5" },
285
+ title: "Child",
286
+ now: thread.createdAt,
287
+ createdBy: "agent",
288
+ creationSource: "mcp",
289
+ });
290
+ assert.deepEqual(child.linkOrigin, shell?.linkOrigin);
291
+ const fork = yield* ThreadForkService.ThreadForkServiceV2.pipe(
292
+ Effect.flatMap((forks) =>
293
+ forks.plan({
294
+ sourceProjection: { thread },
295
+ sourceRun: { id: RunId.make("run:source"), status: "completed" } as OrchestrationV2Run,
296
+ sourceProviderThread: undefined,
297
+ canonicalSourcePoint: { threadId: launched },
298
+ transferId: ContextTransferId.make("transfer:fork"),
299
+ targetThreadId: ThreadId.make("thread:fork"),
300
+ createdBy: "agent",
301
+ creationSource: "mcp",
302
+ createdAt: thread.createdAt,
303
+ }),
304
+ ),
305
+ Effect.provide(ThreadForkService.layer),
306
+ );
307
+ assert.deepEqual(fork.targetThread.linkOrigin, shell?.linkOrigin);
308
+
309
+ // An ordinary outside agent's launch is not a link's.
310
+ const plain = yield* launch(claudeCode, "Started by Claude Code");
311
+ assert.equal((yield* projections.getThreadShell(plain))?.linkOrigin, undefined);
312
+ }),
313
+ );
314
+
315
+ it.effect("changes only that link's threads below full access", () =>
316
+ Effect.gen(function* () {
317
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
318
+ const users = yield* usersOwnThread;
319
+ const ownLaunch = yield* launch(laptop, "The laptop's");
320
+ const rename = (scope: McpInvocationContext.McpInvocationScope, threadId: ThreadId) =>
321
+ call(scope, "t3_thread_update", {
322
+ threadId,
323
+ action: "rename",
324
+ title: `Renamed by ${scope.client!.sessionId}`,
325
+ });
326
+
327
+ // The link may change what it started.
328
+ assert.equal((yield* rename(laptop, ownLaunch)).isError, false);
329
+ assert.equal((yield* projections.getThreadShell(ownLaunch))?.title, "Renamed by laptop");
330
+ // Not the user's own thread, nor another link's.
331
+ assert.equal(failureCode(yield* rename(laptop, users)), "capability_denied");
332
+ assert.equal(failureCode(yield* rename(desk, ownLaunch)), "capability_denied");
333
+ assert.equal((yield* projections.getThreadShell(users))?.title, "The user's own");
334
+ // An ordinary outside agent is not fenced.
335
+ assert.equal((yield* rename(claudeCode, users)).isError, false);
336
+ // Naming this environment's own id is still this environment's thread.
337
+ for (const [name, args] of [
338
+ ["t3_thread_send", { message: "From the laptop." }],
339
+ ["t3_thread_interrupt", {}],
340
+ ] as const) {
341
+ const result = yield* call(laptop, name, {
342
+ ...args,
343
+ environmentId: laptop.environmentId,
344
+ threadId: users,
345
+ });
346
+ assert.equal(failureCode(result), "capability_denied", name);
347
+ }
348
+
349
+ // Nor scheduled tasks, which belong to no thread.
350
+ assert.equal(
351
+ failureCode(yield* call(laptop, "delete_scheduled_task", { scheduledTaskId: "any" })),
352
+ "capability_denied",
353
+ );
354
+
355
+ // Reads are not fenced.
356
+ const read = yield* call(laptop, "t3_thread_read", { threadId: users });
357
+ assert.equal(read.isError, false);
358
+ }),
359
+ );
360
+
361
+ it.effect("is not fenced when the link has full access, but still says where it came from", () =>
362
+ Effect.gen(function* () {
363
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
364
+ const users = yield* usersOwnThread;
365
+ const launched = yield* launch(trusted, "Started from the desk");
366
+ assert.deepEqual((yield* projections.getThreadShell(launched))?.linkOrigin, {
367
+ sessionId: "trusted",
368
+ label: "T3 Code · trusted",
369
+ access: "full-access",
370
+ });
371
+
372
+ const renamed = yield* call(trusted, "t3_thread_update", {
373
+ threadId: users,
374
+ action: "rename",
375
+ title: "Renamed from the desk",
376
+ });
377
+ assert.equal(renamed.isError, false, JSON.stringify(renamed.content));
378
+ for (const [name, args] of [
379
+ ["t3_project_update", { projectId, title: "The desk's now" }],
380
+ ["t3_project_create", { title: "t3code", workspaceRoot: "/p/t3code" }],
381
+ ] as const) {
382
+ const changed = yield* call(trusted, name, args);
383
+ assert.equal(changed.isError, false, `${name}: ${JSON.stringify(changed.content)}`);
384
+ }
385
+ }),
386
+ );
387
+});
apps/server/src/mcp/linkOrigin.ts
new
+60
@@ -0,0 +1,60 @@
1
+import {
2
+ linkOriginIsFenced,
3
+ OrchestratorMcpFailure,
4
+ type OrchestrationV2LinkOrigin,
5
+ type OrchestrationV2ThreadShell,
6
+} from "@t3tools/contracts";
7
+import * as Effect from "effect/Effect";
8
+
9
+import type { Caller } from "./threadAccess.ts";
10
+
11
+/**
12
+ * Below full access, work a link starts here (all of it carries that session in `linkOrigin`)
13
+ * may change only work from the same link: not the user's threads, projects or settings, nor
14
+ * this environment's links. Reads are not fenced. It is a routing rule for T3's tools; agents
15
+ * still run as this environment's user, so a full-access link is not fenced at all.
16
+ */
17
+
18
+/** The link a caller acts for: its own session, or the link that started its thread. */
19
+export const callerLinkOrigin = (
20
+ caller: Pick<Caller, "scope" | "caller">,
21
+): OrchestrationV2LinkOrigin | undefined =>
22
+ caller.caller?.linkOrigin ??
23
+ (caller.scope.client?.linked === true
24
+ ? {
25
+ sessionId: caller.scope.client.sessionId,
26
+ label: caller.scope.client.label,
27
+ access: caller.scope.client.access,
28
+ }
29
+ : undefined);
30
+
31
+/** The link that fences a caller, if any: one paired below full access. */
32
+const fencingLinkOrigin = (caller: Pick<Caller, "scope" | "caller">) => {
33
+ const origin = callerLinkOrigin(caller);
34
+ return origin !== undefined && linkOriginIsFenced(origin) ? origin : undefined;
35
+};
36
+
37
+const outsideLink = (origin: OrchestrationV2LinkOrigin, message: string) =>
38
+ new OrchestratorMcpFailure({
39
+ code: "capability_denied",
40
+ message: `This work was started from ${origin.label} through a linked environment, so ${message} A link paired with full access is not limited this way.`,
41
+ });
42
+
43
+/** A thread a fenced caller may change: one its own link started. */
44
+export const assertSameLink = (
45
+ caller: Pick<Caller, "scope" | "caller">,
46
+ target: Pick<OrchestrationV2ThreadShell, "id" | "linkOrigin">,
47
+) => {
48
+ const origin = fencingLinkOrigin(caller);
49
+ return origin === undefined || target.linkOrigin?.sessionId === origin.sessionId
50
+ ? Effect.void
51
+ : Effect.fail(outsideLink(origin, `it may change only threads that link started.`));
52
+};
53
+
54
+/** Fenced work never changes what the environment already has: projects, settings, scheduled runs. */
55
+export const assertNotLinked = (caller: Pick<Caller, "scope" | "caller">, what: string) => {
56
+ const origin = fencingLinkOrigin(caller);
57
+ return origin === undefined
58
+ ? Effect.void
59
+ : Effect.fail(outsideLink(origin, `it cannot ${what}.`));
60
+};
apps/server/src/mcp/toolkits/attachment/handlers.ts
+30
-24
@@ -46,31 +46,37 @@ export const layer = McpToolAccess.toLayer(
46
Effect.sync(() => {
47
const uploadOwners = new Map<string, { readonly owner: string; readonly issuedAt: number }>();
48
return {
49
- t3_attachment_prepare_upload: McpToolAccess.writes((input) =>
50
- Effect.gen(function* () {
51
- const result = yield* Upload.issueAttachmentUploadUrl(input.upload).pipe(
52
- Effect.mapError(unavailable),
53
- );
54
- const now = yield* Clock.currentTimeMillis;
55
- for (const [id, entry] of uploadOwners) {
56
- if (now - entry.issuedAt > UPLOAD_OWNER_TTL_MS) uploadOwners.delete(id);
57
- }
58
- uploadOwners.set(result.attachmentId, { owner: yield* uploadOwner, issuedAt: now });
59
- return result;
60
- }),
49
+ // A pending upload belongs to its caller until a send claims it, so
50
+ // linked callers may stage the uploads their own sends need.
51
+ t3_attachment_prepare_upload: McpToolAccess.writes(
52
+ (input) =>
53
+ Effect.gen(function* () {
54
+ const result = yield* Upload.issueAttachmentUploadUrl(input.upload).pipe(
55
+ Effect.mapError(unavailable),
56
+ );
57
+ const now = yield* Clock.currentTimeMillis;
58
+ for (const [id, entry] of uploadOwners) {
59
+ if (now - entry.issuedAt > UPLOAD_OWNER_TTL_MS) uploadOwners.delete(id);
60
+ }
61
+ uploadOwners.set(result.attachmentId, { owner: yield* uploadOwner, issuedAt: now });
62
+ return result;
63
+ }),
64
+ { linkedCallers: "allowed" },
65
),
62
- t3_attachment_discard: McpToolAccess.writes((input) =>
63
- Effect.gen(function* () {
64
- if (uploadOwners.get(input.attachmentId)?.owner !== (yield* uploadOwner)) {
65
- return yield* new OrchestratorMcpFailure({
66
- code: "invalid_request",
67
- message: "Only the caller that prepared a pending upload can discard it.",
68
- });
69
- }
70
- yield* Upload.deletePendingAttachment(input.attachmentId);
71
- uploadOwners.delete(input.attachmentId);
72
- return {};
73
- }),
66
+ t3_attachment_discard: McpToolAccess.writes(
67
+ (input) =>
68
+ Effect.gen(function* () {
69
+ if (uploadOwners.get(input.attachmentId)?.owner !== (yield* uploadOwner)) {
70
+ return yield* new OrchestratorMcpFailure({
71
+ code: "invalid_request",
72
+ message: "Only the caller that prepared a pending upload can discard it.",
73
+ });
74
+ }
75
+ yield* Upload.deletePendingAttachment(input.attachmentId);
76
+ uploadOwners.delete(input.attachmentId);
77
+ return {};
78
+ }),
79
+ { linkedCallers: "allowed" },
80
),
81
t3_thread_send_attachments: McpToolAccess.writesThreads(
82
(input) => [input.threadId],
apps/server/src/mcp/toolkits/orchestrator/handlers.ts
+2
@@ -95,6 +95,8 @@ const handlers = {
95
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
96
return yield* service.scheduleTask(scope, { ...input, prompt, schedule });
97
}),
98
+ // A scheduled run starts long after its caller, with nothing to carry the link.
99
+ { refused: "schedule tasks in this environment" },
100
),
101
McpToolAccess.writes(
102
({ scheduledTaskId, prompt, title, schedule, enabled, bindToCurrentThread }) =>
apps/server/src/mcp/toolkits/project/handlers.ts
+63
-52
@@ -76,7 +76,7 @@ const access = Effect.gen(function* () {
76
export const layer = McpToolAccess.toLayer(ProjectToolkit, {
77
t3_thread_launch: McpToolAccess.startsThreads(
78
(input) => input,
79
- (input, { runtimeMode, interactionMode }) =>
79
+ (input, { runtimeMode, interactionMode, linkOrigin }) =>
80
Effect.gen(function* () {
81
const scope = yield* McpInvocationContext.McpInvocationContext;
82
const context = yield* readCaller();
@@ -216,6 +216,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
216
}),
217
createdBy: "agent",
218
creationSource: "mcp",
219
+ ...(linkOrigin === undefined ? {} : { linkOrigin }),
220
}).pipe(
221
Effect.mapError((error) => {
222
if (error._tag === "AttachmentClaimError") {
@@ -244,6 +245,8 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
245
status: run?.status ?? null,
246
};
247
}),
248
+ // The launched thread carries the caller's link, if it has one.
249
+ "stamped",
250
),
251
t3_project_list: McpToolAccess.reads((input) =>
252
Effect.gen(function* () {
@@ -267,48 +270,53 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
270
return result.value;
271
}),
272
),
270
- t3_project_create: McpToolAccess.writesEnvironment(({ workspaceRoot, ...input }) =>
271
- Effect.gen(function* () {
272
- const projects = yield* Project.ProjectService;
273
- if (workspaceRoot === undefined) {
274
- // Only updates record model defaults; reject defaults that creation would silently drop.
275
- if (
276
- input.scripts !== undefined ||
277
- input.createWorkspaceRootIfMissing !== undefined ||
278
- input.defaultModelSelection !== undefined
279
- )
280
- return yield* new OrchestratorMcpFailure({
281
- code: "invalid_request",
282
- message:
283
- "A project started from its title takes only a title; set scripts or defaultModelSelection afterwards with t3_project_update.",
284
- });
285
- const folders = yield* ManagedProjectFolders.ManagedProjectFolders;
286
- const created = yield* folders
287
- .createNamedProject({ name: input.title })
288
- .pipe(
273
+ t3_project_create: McpToolAccess.writesEnvironment(
274
+ ({ workspaceRoot, ...input }) =>
275
+ Effect.gen(function* () {
276
+ const projects = yield* Project.ProjectService;
277
+ if (workspaceRoot === undefined) {
278
+ // Only updates record model defaults; reject defaults that creation would silently drop.
279
+ if (
280
+ input.scripts !== undefined ||
281
+ input.createWorkspaceRootIfMissing !== undefined ||
282
+ input.defaultModelSelection !== undefined
283
+ )
284
+ return yield* new OrchestratorMcpFailure({
285
+ code: "invalid_request",
286
+ message:
287
+ "A project started from its title takes only a title; set scripts or defaultModelSelection afterwards with t3_project_update.",
288
+ });
289
+ const folders = yield* ManagedProjectFolders.ManagedProjectFolders;
290
+ const created = yield* folders.createNamedProject({ name: input.title }).pipe(
291
Effect.mapError(
292
(error) =>
291
- new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
292
- ),
293
- );
294
- const project = yield* projects
295
- .getById(created.projectId)
296
- .pipe(
297
- Effect.mapError(unavailable),
298
- Effect.flatMap(
299
- Option.match({ onNone: () => Effect.fail(unavailable()), onSome: Effect.succeed }),
293
+ new OrchestratorMcpFailure({
294
+ code: "orchestration_error",
295
+ message: error.message,
296
+ }),
297
),
298
);
302
- return {
303
- ...project,
304
- ...(created.commitError === undefined ? {} : { commitError: created.commitError }),
305
- };
306
- }
307
- const commandId = yield* newCommandId();
308
- return yield* projects
309
- .create({ ...input, workspaceRoot, commandId, projectId: ProjectId.make(commandId) })
310
- .pipe(Effect.mapError(projectFailure));
311
- }),
299
+ const project = yield* projects
300
+ .getById(created.projectId)
301
+ .pipe(
302
+ Effect.mapError(unavailable),
303
+ Effect.flatMap(
304
+ Option.match({ onNone: () => Effect.fail(unavailable()), onSome: Effect.succeed }),
305
+ ),
306
+ );
307
+ return {
308
+ ...project,
309
+ ...(created.commitError === undefined ? {} : { commitError: created.commitError }),
310
+ };
311
+ }
312
+ const commandId = yield* newCommandId();
313
+ return yield* projects
314
+ .create({ ...input, workspaceRoot, commandId, projectId: ProjectId.make(commandId) })
315
+ .pipe(Effect.mapError(projectFailure));
316
+ }),
317
+ // Linked work may bring the repository it works in; an existing
318
+ // registered workspace is still refused.
319
+ { linkedCallers: "allowed" },
320
),
321
t3_project_update: McpToolAccess.writesEnvironment((input) =>
322
Effect.gen(function* () {
@@ -326,18 +334,21 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
334
.pipe(Effect.mapError(projectFailure));
335
}),
336
),
329
- t3_project_clone: McpToolAccess.writesEnvironment((input) =>
330
- Effect.gen(function* () {
331
- const repositories = yield* Repositories.SourceControlRepositoryService;
332
- return yield* repositories.cloneRepository(input).pipe(
333
- Effect.mapError(
334
- (error) =>
335
- new OrchestratorMcpFailure({
336
- code: "orchestration_error",
337
- message: error.detail,
338
- }),
339
- ),
340
- );
341
- }),
337
+ t3_project_clone: McpToolAccess.writesEnvironment(
338
+ (input) =>
339
+ Effect.gen(function* () {
340
+ const repositories = yield* Repositories.SourceControlRepositoryService;
341
+ return yield* repositories.cloneRepository(input).pipe(
342
+ Effect.mapError(
343
+ (error) =>
344
+ new OrchestratorMcpFailure({
345
+ code: "orchestration_error",
346
+ message: error.detail,
347
+ }),
348
+ ),
349
+ );
350
+ }),
351
+ // An existing destination is never adopted.
352
+ { linkedCallers: "allowed" },
353
),
354
});
apps/server/src/orchestration-v2/Orchestrator.ts
+1
@@ -2539,6 +2539,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2539
worktreePath: command.worktreePath,
2540
activeProviderThreadId: null,
2541
pullRequests: [],
2542
+ ...(command.linkOrigin === undefined ? {} : { linkOrigin: command.linkOrigin }),
2543
lineage: {
2544
parentThreadId: null,
2545
relationshipToParent: null,
apps/server/src/orchestration-v2/ProjectionStore.ts
+6
@@ -1657,6 +1657,9 @@ export function threadShellFromProjection(
1657
...(projection.thread.historyOrigin === undefined
1658
? {}
1659
: { historyOrigin: projection.thread.historyOrigin }),
1660
+ ...(projection.thread.linkOrigin === undefined
1661
+ ? {}
1662
+ : { linkOrigin: projection.thread.linkOrigin }),
1663
latestRunId: latestRun?.id ?? null,
1664
latestRunRequestedAt: latestRun?.requestedAt ?? null,
1665
latestRunStartedAt: latestRun?.startedAt ?? null,
@@ -1933,6 +1936,9 @@ function shellFromState(input: {
1936
...(input.state.thread.historyOrigin === undefined
1937
? {}
1938
: { historyOrigin: input.state.thread.historyOrigin }),
1939
+ ...(input.state.thread.linkOrigin === undefined
1940
+ ? {}
1941
+ : { linkOrigin: input.state.thread.linkOrigin }),
1942
latestRunId: input.state.latestRunId,
1943
latestRunRequestedAt: input.state.latestRunRequestedAt,
1944
latestRunStartedAt: input.state.latestRunStartedAt,
apps/server/src/orchestration-v2/ThreadLaunchService.ts
+4
@@ -9,6 +9,7 @@ import {
9
type ModelSelection,
10
type OrchestrationV2Actor,
11
type OrchestrationV2CreationSource,
12
+ type OrchestrationV2LinkOrigin,
13
type OrchestrationV2ProviderThreadNativeMetadata,
14
type OrchestrationV2ThreadProjection,
15
type ProviderDriverKind,
@@ -97,6 +98,8 @@ export interface ThreadLaunchInput {
98
};
99
readonly createdBy: OrchestrationV2Actor;
100
readonly creationSource: OrchestrationV2CreationSource;
101
+ /** The linked environment this launch is for, if one asked for it. */
102
+ readonly linkOrigin?: OrchestrationV2LinkOrigin;
103
}
104
105
type PreparationInput = Pick<
@@ -912,6 +915,7 @@ const make = Effect.gen(function* () {
915
...(input.importedNativeThread === undefined
916
? {}
917
: { importedNativeThread: input.importedNativeThread }),
918
+ ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),
919
createdBy: input.createdBy,
920
creationSource: input.creationSource,
921
});
apps/server/src/orchestration-v2/ThreadManagementService.test.ts
+33
@@ -2,6 +2,7 @@ import { expect, it } from "@effect/vitest";
2
import {
3
CommandId,
4
MessageId,
5
+ type OrchestrationV2Command,
6
type OrchestrationV2Run,
7
type OrchestrationV2ProviderThread,
8
ProviderThreadId,
@@ -32,6 +33,38 @@ import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"
33
import * as ThreadManagementService from "./ThreadManagementService.ts";
34
import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
35
36
+it("stamps authoritative provenance on commands that create threads or messages", () => {
37
+ const command: OrchestrationV2Command = {
38
+ type: "thread.create",
39
+ createdBy: "agent",
40
+ creationSource: "mcp",
41
+ commandId: CommandId.make("command:thread-management:create"),
42
+ threadId: ThreadId.make("thread:thread-management:create"),
43
+ projectId: ProjectId.make("project:thread-management"),
44
+ title: "Thread management",
45
+ modelSelection: {
46
+ instanceId: ProviderInstanceId.make("codex"),
47
+ model: "gpt-5-codex",
48
+ },
49
+ runtimeMode: "full-access",
50
+ interactionMode: "default",
51
+ branch: null,
52
+ worktreePath: null,
53
+ // A client cannot claim a linked environment's origin for its own thread.
54
+ linkOrigin: { sessionId: "forged", label: "Somewhere else" },
55
+ };
56
+
57
+ const stamped = ThreadManagementService.withCreationProvenance(command, {
58
+ createdBy: "user",
59
+ creationSource: "web",
60
+ });
61
+ expect(stamped).toMatchObject({
62
+ createdBy: "user",
63
+ creationSource: "web",
64
+ });
65
+ expect(stamped).not.toHaveProperty("linkOrigin");
66
+});
67
+
68
const layerReceiptsTest = CommandReceiptStore.layer.pipe(
69
Layer.provide(SqlitePersistence.layerMemory),
70
);
apps/server/src/orchestration-v2/ThreadManagementService.ts
+5
-1
@@ -70,7 +70,11 @@ export function withCreationProvenance(
70
provenance: ThreadManagementProvenance,
71
): OrchestrationV2Command {
72
switch (command.type) {
73
- case "thread.create":
73
+ case "thread.create": {
74
+ // Only the server stamps a link's origin, so a client cannot set one.
75
+ const { linkOrigin: _linkOrigin, ...rest } = command;
76
+ return { ...rest, ...provenance };
77
+ }
78
case "message.dispatch":
79
case "thread.fork":
80
case "thread.merge_back":
apps/server/src/orchestration-v2/runtimeLayer.ts
+2
@@ -262,6 +262,8 @@ const layerThreadManagementProvided = ThreadManagementService.layerWithLegacyImp
262
);
263
export const layerProjectSetupScriptRunner = ProjectSetupScriptRunner.layer.pipe(
264
Layer.provide(layerProjectService),
265
+ // Whether a thread came from a linked environment, which skips setup.
266
+ Layer.provide(ProjectionStore.layer),
267
);
268
const layerManagedProjectFoldersProvided = ManagedProjectFolders.layer.pipe(
269
Layer.provide(layerProjectService),
apps/server/src/peer/PeerForwarding.test.ts
+76
-24
@@ -5,6 +5,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
5
import {
6
EnvironmentId,
7
type OrchestrationV2Run,
8
+ type OrchestrationV2ThreadShell,
9
type SourceControlCloneRepositoryInput,
10
ProjectId,
11
ProviderInstanceId,
@@ -63,20 +64,33 @@ const nothingSeen: Seen = {
64
stops: [],
65
};
66
67
+/** The box user's own thread, which no link started. */
68
+const usersThread = ThreadId.make("thread:box-users-own");
69
+
70
/**
67
- * B's threads: one `auto` thread in `boxProject`, whose run finishes on the
68
- * third wait. Every send and wait is recorded.
71
+ * B's threads: one `auto` thread in `boxProject` that the laptop's link
72
+ * started, whose run finishes on the third wait, and the box user's own.
73
+ * Every send and wait is recorded.
74
*/
70
-const boxThreads = (seen: Ref.Ref<Seen>) => {
71
- const shell = { ...liveThreadShell(boxThread, { runtimeMode: "auto" }), projectId: boxProject };
75
+const boxThreads = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) => {
76
+ const base = { ...liveThreadShell(boxThread, { runtimeMode: "auto" }), projectId: boxProject };
77
+ const linked = Ref.get(linkSession).pipe(
78
+ Effect.map((sessionId) => ({ ...base, linkOrigin: { sessionId, label: "T3 Code · Laptop" } })),
79
+ );
80
+ const users = { ...liveThreadShell(usersThread, { runtimeMode: "auto" }), projectId: boxProject };
81
const run = (status: OrchestrationV2Run["status"]) =>
82
({ id: boxRun, status }) as unknown as OrchestrationV2Run;
74
- const projection = { thread: shell, runs: [run("running")], runtimeRequests: [] } as never;
83
+ const shellOf = (threadId: ThreadId): Effect.Effect<OrchestrationV2ThreadShell | null> =>
84
+ threadId === boxThread ? linked : Effect.succeed(threadId === usersThread ? users : null);
85
+ const projectionOf = (threadId: ThreadId) =>
86
+ shellOf(threadId).pipe(
87
+ Effect.map((thread) => ({ thread, runs: [run("running")], runtimeRequests: [] }) as never),
88
+ );
89
return Layer.mock(ThreadManagement.ThreadManagementService)({
76
- getThreadShell: (threadId) => Effect.succeed(threadId === boxThread ? shell : null),
77
- getProjectThreadRecords: () => Effect.succeed(projection),
78
- getThreadRecords: () => Effect.succeed(projection),
79
- listProjectThreads: () => Effect.succeed([shell] as never),
90
+ getThreadShell: shellOf,
91
+ getProjectThreadRecords: (input) => projectionOf(input.threadId),
92
+ getThreadRecords: (threadId) => projectionOf(threadId),
93
+ listProjectThreads: () => linked.pipe(Effect.map((shell) => [shell] as never)),
94
sendToThread: (input) =>
95
Ref.update(seen, (current) => ({ ...current, sends: [...current.sends, input] })).pipe(
96
Effect.as({ run: run("running"), delivery: "started" } as never),
@@ -179,8 +193,12 @@ const boxProjects = (seen: Ref.Ref<Seen>) =>
193
}),
194
);
195
182
-/** The orchestrator and project toolkits on B's real `/mcp`, behind its real OAuth. */
183
-const serveBox = (seen: Ref.Ref<Seen>) =>
196
+/**
197
+ * The orchestrator and project toolkits on B's real `/mcp`, behind its real
198
+ * OAuth. `linkSession` is filled in once A links, so B's fixture thread reads
199
+ * as one that link started.
200
+ */
201
+const serveBox = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) =>
202
servePeer(
203
box,
204
Layer.mergeAll(
@@ -190,7 +208,7 @@ const serveBox = (seen: Ref.Ref<Seen>) =>
208
).pipe(
209
Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
210
Layer.provide(NodeCrypto.layer),
193
- Layer.provide(boxThreads(seen)),
211
+ Layer.provide(boxThreads(seen, linkSession)),
212
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
213
Layer.provide(boxLaunches(seen)),
214
Layer.provide(
@@ -259,12 +277,18 @@ const makeLaptop = Effect.gen(function* () {
277
Layer.mock(ThreadManagement.ThreadManagementService)({
278
getThreadShell: (threadId) =>
279
Effect.succeed(
262
- liveThreadShell(
263
- threadId,
264
- threadId === ThreadId.make("thread:laptop-plan")
265
- ? { runtimeMode: "full-access", interactionMode: "plan" }
266
- : { runtimeMode: "full-access" },
267
- ),
280
+ threadId === ThreadId.make("thread:laptop-from-desk")
281
+ ? {
282
+ ...liveThreadShell(threadId, { runtimeMode: "full-access" }),
283
+ // Work another environment's link started on this laptop.
284
+ linkOrigin: { sessionId: "session:desk", label: "T3 Code · Desk" },
285
+ }
286
+ : liveThreadShell(
287
+ threadId,
288
+ threadId === ThreadId.make("thread:laptop-plan")
289
+ ? { runtimeMode: "full-access", interactionMode: "plan" }
290
+ : { runtimeMode: "full-access" },
291
+ ),
292
),
293
getProjectThreadRecords: ({ threadId }) =>
294
Effect.succeed({
@@ -324,9 +348,11 @@ it.effect("an agent here works on a linked environment's threads within its own
348
Effect.scoped(
349
Effect.gen(function* () {
350
const seen = yield* Ref.make<Seen>(nothingSeen);
327
- const b = yield* serveBox(seen);
351
+ const linkSession = yield* Ref.make("");
352
+ const b = yield* serveBox(seen, linkSession);
353
const a = yield* makeLaptop;
354
yield* linkTo(a.links, b, "auto");
355
+ yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
356
357
const listed = yield* a.call("thread:laptop-full", "t3_environment_links", {});
358
expect(listed.structuredContent).toMatchObject({
@@ -392,9 +418,11 @@ it.effect("keeps a forwarded wait short and its retries scoped to the caller", (
418
Effect.scoped(
419
Effect.gen(function* () {
420
const seen = yield* Ref.make<Seen>(nothingSeen);
395
- const b = yield* serveBox(seen);
421
+ const linkSession = yield* Ref.make("");
422
+ const b = yield* serveBox(seen, linkSession);
423
const a = yield* makeLaptop;
424
yield* linkTo(a.links, b, "auto");
425
+ yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
426
427
const waited = yield* a.call("thread:laptop-full", "t3_thread_wait", {
428
environmentId: box.environmentId,
@@ -442,9 +470,11 @@ it.effect("launches in a linked environment with the caller's modes, retry-safe"
470
Effect.scoped(
471
Effect.gen(function* () {
472
const seen = yield* Ref.make<Seen>(nothingSeen);
445
- const b = yield* serveBox(seen);
473
+ const linkSession = yield* Ref.make("");
474
+ const b = yield* serveBox(seen, linkSession);
475
const a = yield* makeLaptop;
476
yield* linkTo(a.links, b, "full-access");
477
+ yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
478
const codex = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" };
479
const launch = (caller: string, args: Record<string, unknown> = {}) =>
480
a.call(caller, "t3_thread_launch", {
@@ -493,7 +523,7 @@ it.effect("brings a repository to a linked environment, only through full access
523
Effect.scoped(
524
Effect.gen(function* () {
525
const seen = yield* Ref.make<Seen>(nothingSeen);
496
- const b = yield* serveBox(seen);
526
+ const b = yield* serveBox(seen, yield* Ref.make(""));
527
const a = yield* makeLaptop;
528
const clone = { repository: "pingdotgg/t3code", destinationPath: "/home/box/t3code" };
529
const register = { title: "t3code", workspaceRoot: "/home/box/t3code" };
@@ -543,9 +573,11 @@ it.effect("runs any tool that takes a linked environment there", () =>
573
Effect.scoped(
574
Effect.gen(function* () {
575
const seen = yield* Ref.make<Seen>(nothingSeen);
546
- const b = yield* serveBox(seen);
576
+ const linkSession = yield* Ref.make("");
577
+ const b = yield* serveBox(seen, linkSession);
578
const a = yield* makeLaptop;
579
yield* linkTo(a.links, b, "auto");
580
+ yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
581
582
const there = yield* a.call("thread:laptop-full", "t3_thread_configure", {
583
environmentId: box.environmentId,
@@ -576,9 +608,11 @@ it.effect("refuses what a linked environment cannot take before anything leaves"
608
Effect.scoped(
609
Effect.gen(function* () {
610
const seen = yield* Ref.make<Seen>(nothingSeen);
579
- const b = yield* serveBox(seen);
611
+ const linkSession = yield* Ref.make("");
612
+ const b = yield* serveBox(seen, linkSession);
613
const a = yield* makeLaptop;
614
yield* linkTo(a.links, b, "auto");
615
+ yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
616
yield* Ref.set(b.bearers, []);
617
618
const unknown = yield* a.call("thread:laptop-full", "t3_thread_read", {
@@ -620,6 +654,24 @@ it.effect("refuses what a linked environment cannot take before anything leaves"
654
expect(failureOf(refused), name).toMatchObject({ code: "capability_denied" });
655
}
656
expect(yield* Ref.get(b.bearers)).toEqual([]);
657
+
658
+ // Work a desk's link started here never uses this laptop's links: the
659
+ // box would see the laptop, not the desk, so its fence could not hold.
660
+ for (const [name, args] of [
661
+ ["t3_thread_read", { environmentId: box.environmentId, threadId: boxThread }],
662
+ [
663
+ "t3_thread_send",
664
+ { environmentId: box.environmentId, threadId: boxThread, message: "From the desk." },
665
+ ],
666
+ [
667
+ "t3_thread_launch",
668
+ { environmentId: box.environmentId, projectId: boxProject, title: "x" },
669
+ ],
670
+ ] as const) {
671
+ const relayed = yield* a.call("thread:laptop-from-desk", name, args);
672
+ expect(failureOf(relayed), name).toMatchObject({ code: "capability_denied" });
673
+ }
674
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
675
}),
676
).pipe(Effect.provide(NodeHttpServer.layerTest)),
677
);
apps/server/src/peer/PeerForwarding.ts
+6
-3
@@ -14,6 +14,7 @@ import * as Layer from "effect/Layer";
14
import * as Schema from "effect/Schema";
15
import type * as Tool from "effect/ai/Tool";
16
17
+import { assertNotLinked } from "../mcp/linkOrigin.ts";
18
import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
19
import { readCaller, unavailable } from "../mcp/threadAccess.ts";
20
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
@@ -74,12 +75,14 @@ const make = Effect.gen(function* () {
75
const threads = yield* ThreadManagement.ThreadManagementService;
76
77
/**
77
- * The caller's own limits here, which travel with every call it forwards.
78
- * The peer sees only the link's credential, so a credential that may not
79
- * control threads here is refused here.
78
+ * The caller's own limits, which travel with every forwarded call: the peer sees only the
79
+ * link's credential, so a caller that may not control threads here is refused here. Work a
80
+ * link started never uses this environment's links, since the peer would see this
81
+ * environment's session instead of that link, and its fence could not hold.
82
*/
83
const callerLimits = (scope: Scope) =>
84
readCaller().pipe(
85
+ Effect.tap((caller) => assertNotLinked(caller, "use this environment's links")),
86
Effect.map((caller) => caller.limits),
87
Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
88
Effect.provideService(ThreadManagement.ThreadManagementService, threads),
apps/server/src/peer/PeerLinks.test.ts
+37
@@ -8,6 +8,7 @@ import * as Layer from "effect/Layer";
8
import * as Option from "effect/Option";
9
import * as Ref from "effect/Ref";
10
import * as Schema from "effect/Schema";
11
+import * as SqlClient from "effect/sql/SqlClient";
12
import * as TestClock from "effect/testing/TestClock";
13
import { Tool, Toolkit } from "effect/ai";
14
import {
@@ -78,6 +79,7 @@ const makeA = (descriptor: ExecutionEnvironmentDescriptor) =>
79
Effect.map((context) => ({
80
links: Context.get(context, PeerLinks.PeerLinks),
81
peer: Context.get(context, PeerMcpClient.PeerMcpClient),
82
+ sql: Context.get(context, SqlClient.SqlClient),
83
})),
84
);
85
@@ -280,6 +282,35 @@ it.effect("tells the agent to link again once the peer revokes the link or it ex
282
expect(revoked.code).toBe("capability_denied");
283
expect(revoked.message).toContain("revoked there");
284
285
+ yield* a.links.link({
286
+ url: b.url,
287
+ pairingCode: (yield* b.auth.issuePairingCredential()).credential,
288
+ access: "auto",
289
+ });
290
+ // A link made with a peer that later answers without the fence, as
291
+ // one made before the fence or a peer moved back to such a version.
292
+ yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
293
+ yield* Ref.set(b.bearers, []);
294
+ const unfenced = yield* probe(a).pipe(Effect.flip);
295
+ expect(unfenced.code).toBe("capability_denied");
296
+ expect(unfenced.message).toContain("cannot keep a linked agent's limits");
297
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
298
+ yield* Ref.set(b.descriptor, box);
299
+
300
+ // A link stored before links were marked: its session there is not a
301
+ // link's, so the peer would not fence its work even though it can.
302
+ yield* a.sql`UPDATE peer_environment_links SET fenced = 0`;
303
+ const legacy = yield* probe(a).pipe(Effect.flip);
304
+ expect(legacy.code).toBe("capability_denied");
305
+ expect(legacy.message).toContain("Link it again");
306
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
307
+ yield* a.links.link({
308
+ url: b.url,
309
+ pairingCode: (yield* b.auth.issuePairingCredential()).credential,
310
+ access: "auto",
311
+ });
312
+ yield* probe(a);
313
+
314
yield* TestClock.adjust(Duration.days(31));
315
expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
316
yield* Ref.set(b.bearers, []);
@@ -305,6 +336,12 @@ it.effect(
336
.link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
337
.pipe(Effect.flip);
338
expect(older.reason).toBe("incompatible");
339
+ // Nor one whose link's work could reach the user's own threads there.
340
+ yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
341
+ const unfenced = yield* a.links
342
+ .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
343
+ .pipe(Effect.flip);
344
+ expect(unfenced.reason).toBe("incompatible");
345
346
// Plain http to a LAN address would carry the code and token in clear.
347
const lan = yield* a.links
apps/server/src/peer/PeerLinks.testkit.ts
+7
-2
@@ -43,7 +43,12 @@ export const descriptorOf = (
43
label,
44
platform: { os: "linux", arch: "x64" },
45
serverVersion: "0.0.0-test",
46
- capabilities: { repositoryIdentity: true, mcpModeLimitHeader: true, ...capabilities },
46
+ capabilities: {
47
+ repositoryIdentity: true,
48
+ mcpModeLimitHeader: true,
49
+ linkFence: true,
50
+ ...capabilities,
51
+ },
52
});
53
54
/**
@@ -146,9 +151,9 @@ export type ServedPeer = Effect.Success<ReturnType<typeof servePeer>>;
151
export const layerLinkingEnvironment = (descriptor: ExecutionEnvironmentDescriptor) =>
152
PeerMcpClient.layer.pipe(
153
Layer.provideMerge(PeerLinks.layer),
154
+ Layer.provideMerge(Sqlite.layerMemory),
155
Layer.provide(
156
Layer.mergeAll(
151
- Sqlite.layerMemory,
157
ServerSecretStore.layer,
158
FetchHttpClient.layer,
159
Layer.succeed(ServerEnvironment.ServerEnvironment, {
apps/server/src/peer/PeerLinks.ts
+40
-7
@@ -4,6 +4,8 @@ import {
4
AuthMcpTokenError,
5
EnvironmentHttpApi,
6
EnvironmentId,
7
+ type ExecutionEnvironmentCapabilities,
8
+ MCP_PEER_LINK_SOFTWARE_ID,
9
type PeerLink,
10
type PeerLinkCreateInput,
11
PeerLinkError,
@@ -85,6 +87,7 @@ interface PeerLinkRow {
87
readonly expires_at: string;
88
readonly last_reached_at: string | null;
89
readonly last_error: string | null;
90
+ readonly fenced: number;
91
}
92
93
const decodeUrls = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
@@ -136,6 +139,10 @@ const peerOrigin = (url: string) => {
139
return Effect.succeed(parsed.origin);
140
};
141
142
+/** Whether a peer holds a linked agent to its limits and keeps its work within its link. */
143
+const linkLimitsHold = (peer: { readonly capabilities: ExecutionEnvironmentCapabilities }) =>
144
+ peer.capabilities.mcpModeLimitHeader === true && peer.capabilities.linkFence === true;
145
+
146
const make = Effect.gen(function* () {
147
const sql = yield* SqlClient.SqlClient;
148
const secrets = yield* ServerSecretStore.ServerSecretStore;
@@ -200,7 +207,13 @@ const make = Effect.gen(function* () {
207
// Only the peer's own refusals are rejections. A dropped connection or
208
// an answer this version cannot read is classified below.
209
const registered = yield* client.mcpOAuth
203
- .register({ payload: { client_name: clientName, redirect_uris: [LINK_REDIRECT_URI] } })
210
+ .register({
211
+ payload: {
212
+ client_name: clientName,
213
+ redirect_uris: [LINK_REDIRECT_URI],
214
+ software_id: MCP_PEER_LINK_SOFTWARE_ID,
215
+ },
216
+ })
217
.pipe(
218
// A plain Schema.Error has no tag to catch by.
219
Effect.catchIf(Schema.is(AuthMcpRegistrationError), (error) =>
@@ -322,7 +335,7 @@ const make = Effect.gen(function* () {
335
message: "That address is this environment.",
336
});
337
}
325
- if (peer.capabilities.mcpModeLimitHeader !== true) {
338
+ if (!linkLimitsHold(peer)) {
339
return yield* new PeerLinkError({
340
reason: "incompatible",
341
message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
@@ -351,14 +364,15 @@ const make = Effect.gen(function* () {
364
yield* sql`
365
INSERT INTO peer_environment_links (
366
environment_id, secret_name, label, urls_json, access, linked_at, expires_at,
354
- last_reached_at, last_error
367
+ last_reached_at, last_error, fenced
368
) VALUES (
369
${linked.environmentId}, ${secretName}, ${linked.label}, ${urlsJson}, ${linked.access},
370
${DateTime.formatIso(linked.linkedAt)}, ${DateTime.formatIso(linked.expiresAt)},
358
- ${DateTime.formatIso(now)}, NULL
371
+ ${DateTime.formatIso(now)}, NULL, 1
372
)
373
ON CONFLICT (environment_id) DO UPDATE SET
374
secret_name = excluded.secret_name,
375
+ fenced = excluded.fenced,
376
label = excluded.label,
377
urls_json = excluded.urls_json,
378
access = excluded.access,
@@ -439,6 +453,14 @@ const make = Effect.gen(function* () {
453
message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`,
454
});
455
}
456
+ // Its token was issued before links were marked as links, so the peer
457
+ // never fences the work it carries, whatever version it runs now.
458
+ if (row.value.fenced !== 1) {
459
+ return yield* new PeerLinkError({
460
+ reason: "incompatible",
461
+ message: `The link to ${link.label} was made by an older T3 Code. Link it again with a new pairing code from ${link.label}.`,
462
+ });
463
+ }
464
const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage));
465
if (Option.isNone(stored)) {
466
return yield* new PeerLinkError({
@@ -448,11 +470,14 @@ const make = Effect.gen(function* () {
470
}
471
// The token goes only to an address that proves it is this peer, so a
472
// reused LAN address or a moved hostname never receives it.
473
+ let fenced = true;
474
const url = yield* Effect.findFirst(link.urls, (candidate) =>
475
describe(candidate).pipe(
453
- Effect.map(
454
- (found) => Option.isSome(found) && found.value.environmentId === environmentId,
455
- ),
476
+ Effect.map((found) => {
477
+ if (Option.isNone(found) || found.value.environmentId !== environmentId) return false;
478
+ fenced = linkLimitsHold(found.value);
479
+ return true;
480
+ }),
481
),
482
);
483
if (Option.isNone(url)) {
@@ -461,6 +486,14 @@ const make = Effect.gen(function* () {
486
message: `${link.label} did not answer at ${link.urls.join(", ")}.`,
487
});
488
}
489
+ // A link made before the peer had to fence linked work, or a peer moved
490
+ // back to such a version, would carry work past those limits.
491
+ if (!fenced) {
492
+ return yield* new PeerLinkError({
493
+ reason: "incompatible",
494
+ message: `${link.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
495
+ });
496
+ }
497
return { link, url: url.value, token: new TextDecoder().decode(stored.value) };
498
},
499
);
apps/server/src/peer/PeerMcpClient.ts
+1
-1
@@ -70,7 +70,7 @@ const fromLinkError = (error: PeerLinkError) =>
70
code:
71
error.reason === "unknown_link"
72
? "invalid_request"
73
- : error.reason === "expired"
73
+ : error.reason === "expired" || error.reason === "incompatible"
74
? "capability_denied"
75
: "orchestration_error",
76
message: error.message,
apps/server/src/persistence/Migrations.ts
+2
@@ -73,6 +73,7 @@ import Migration0067 from "./Migrations/067_WebhookDedupe.ts";
73
import Migration0068 from "./Migrations/068_ShellStopRequestIndex.ts";
74
import Migration0069 from "./Migrations/069_ThreadMessageSearch.ts";
75
import Migration0070 from "./Migrations/070_PeerLinks.ts";
76
+import Migration0071 from "./Migrations/071_PeerLinkFence.ts";
77
78
const migrationEntries = [
79
[1, "OrchestrationEvents", Migration0001],
@@ -146,6 +147,7 @@ const migrationEntries = [
147
[68, "ShellStopRequestIndex", Migration0068],
148
[69, "ThreadMessageSearch", Migration0069],
149
[70, "PeerLinks", Migration0070],
150
+ [71, "PeerLinkFence", Migration0071],
151
] as const;
152
153
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/071_PeerLinkFence.ts
new
+12
@@ -0,0 +1,12 @@
1
+import * as Effect from "effect/Effect";
2
+import * as SqlClient from "effect/sql/SqlClient";
3
+
4
+export default Effect.gen(function* () {
5
+ const sql = yield* SqlClient.SqlClient;
6
+
7
+ // Whether the link's session was issued as a link, which the peer fences.
8
+ // Links stored before it are not, and must be made again.
9
+ yield* sql`
10
+ ALTER TABLE peer_environment_links ADD COLUMN fenced INTEGER NOT NULL DEFAULT 0
11
+ `;
12
+});
apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+2
@@ -50,6 +50,7 @@ describe("V2 preview upgrade", () => {
50
[68, "ShellStopRequestIndex"],
51
[69, "ThreadMessageSearch"],
52
[70, "PeerLinks"],
53
+ [71, "PeerLinkFence"],
54
]);
55
assert.deepStrictEqual(yield* runMigrations(), []);
56
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -143,6 +144,7 @@ describe("V2 preview upgrade", () => {
144
[68, "ShellStopRequestIndex"],
145
[69, "ThreadMessageSearch"],
146
[70, "PeerLinks"],
147
+ [71, "PeerLinkFence"],
148
]);
149
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
150
);
apps/server/src/project/ProjectSetupScriptRunner.test.ts
+4
@@ -11,6 +11,7 @@ import { TestClock } from "effect/testing";
11
12
import * as ServerSettings from "../serverSettings.ts";
13
import * as TerminalManager from "../terminal/Manager.ts";
14
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
15
import * as ProjectService from "./ProjectService.ts";
16
import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
17
@@ -58,6 +59,9 @@ const makeHarness = Effect.fn(function* (options: {
59
Layer.mergeAll(
60
terminals,
61
Layer.mock(ProjectService.ProjectService)({}),
62
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
63
+ getThreadShell: () => Effect.succeed(null),
64
+ }),
65
ServerSettings.layerTest(),
66
NodeCrypto.layer,
67
),
apps/server/src/project/ProjectSetupScriptRunner.ts
+27
-2
@@ -1,4 +1,4 @@
1
-import { ProjectId, type ProjectScript } from "@t3tools/contracts";
1
+import { linkOriginIsFenced, ProjectId, type ProjectScript, ThreadId } from "@t3tools/contracts";
2
import * as HostProcess from "@t3tools/shared/HostProcess";
3
import {
4
projectScriptRuntimeEnv,
@@ -17,6 +17,7 @@ import * as Layer from "effect/Layer";
17
import * as Option from "effect/Option";
18
import * as Schema from "effect/Schema";
19
20
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
21
import * as ServerSettings from "../serverSettings.ts";
22
import * as TerminalManager from "../terminal/Manager.ts";
23
import * as ProjectService from "./ProjectService.ts";
@@ -46,8 +47,18 @@ export interface ProjectSetupScriptOutputLine {
47
readonly line: string;
48
}
49
50
+/**
51
+ * A thread a link below full access started does not run this project's setup
52
+ * script: the script is the user's own code, and such a link only grants T3's
53
+ * tools (see `mcp/linkOrigin.ts`).
54
+ */
55
+export interface ProjectSetupScriptRunnerResultSkippedForLink {
56
+ readonly status: "skipped-for-link";
57
+}
58
+
59
export type ProjectSetupScriptRunnerResult =
60
| ProjectSetupScriptRunnerResultNoScript
61
+ | ProjectSetupScriptRunnerResultSkippedForLink
62
| ProjectSetupScriptRunnerResultStarted;
63
64
export interface ProjectSetupScriptRunnerInput {
@@ -74,7 +85,7 @@ export class ProjectSetupScriptOperationError extends Schema.TaggedError<Project
85
projectId: Schema.optional(Schema.String),
86
projectCwd: Schema.optional(Schema.String),
87
worktreePath: Schema.String,
77
- operation: Schema.Literals(["resolveProject", "readSettings", "openTerminal"]),
88
+ operation: Schema.Literals(["readThread", "resolveProject", "readSettings", "openTerminal"]),
89
cause: Schema.Defect(),
90
},
91
) {
@@ -181,6 +192,7 @@ function wrapCommandForCompletion(
192
/** @public */
193
export const make = Effect.gen(function* () {
194
const projects = yield* ProjectService.ProjectService;
195
+ const threads = yield* ProjectionStore.ProjectionStoreV2;
196
const terminalManager = yield* TerminalManager.TerminalManager;
197
const serverSettings = yield* ServerSettings.ServerSettingsService;
198
const crypto = yield* Crypto.Crypto;
@@ -345,6 +357,19 @@ export const make = Effect.gen(function* () {
357
...(input.projectId === undefined ? {} : { projectId: input.projectId }),
358
...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
359
};
360
+ // A thread whose origin cannot be read might be a link's: run nothing.
361
+ const thread = yield* threads.getThreadShell(ThreadId.make(input.threadId)).pipe(
362
+ Effect.mapError(
363
+ (cause) =>
364
+ new ProjectSetupScriptOperationError({
365
+ ...errorContext,
366
+ operation: "readThread",
367
+ cause,
368
+ }),
369
+ ),
370
+ );
371
+ if (thread?.linkOrigin !== undefined && linkOriginIsFenced(thread.linkOrigin))
372
+ return { status: "skipped-for-link" } as const;
373
const suppliedProject = input.project;
374
const projectById =
375
suppliedProject ??
docs/internals/remote.md
+24
-1
@@ -97,8 +97,31 @@ Unlinking on the linking side only forgets the token.
97
receiving `/mcp` sends nothing while a wait is open and T3 Connect's edge
98
drops idle requests after about 100 s.
99
100
+**Work a link paired below full access starts stays within that link.** The
101
+receiving environment knows a session is a peer link because the linking side
102
+registers its OAuth client with the `t3code-peer-link` software id, and the
103
+marker is signed into the session. Threads that session launches carry it, with
104
+the access it was paired with, as an immutable `linkOrigin`, and so do the
105
+subagents, forks and `create_threads` they derive. The rules live in
106
+[`mcp/linkOrigin.ts`](../../apps/server/src/mcp/linkOrigin.ts) and run in the
107
+shared access declarations, not tool by tool:
108
+
109
+- linked work may change only threads with the same origin, not the user's own
110
+ threads and not another link's;
111
+- it cannot change projects, settings or scheduled tasks, nor use the receiving
112
+ environment's own links;
113
+- its project setup scripts are skipped
114
+ ([`ProjectSetupScriptRunner`](../../apps/server/src/project/ProjectSetupScriptRunner.ts)
115
+ checks every path that runs them).
116
+
117
+Reads are not fenced, and a client's own `thread.create` can never carry
118
+`linkOrigin`.
119
+
120
The link is routing, not isolation: an agent the link starts runs as the
101
-receiving environment's user, inside the limits above.
121
+receiving environment's user. **A full-access link is therefore not fenced**:
122
+its agents can already do anything that user can, so the fence would only stop
123
+T3's own tools. Its work still carries `linkOrigin`, so clients show where it
124
+came from. A stamp without the access, from before it was recorded, is fenced.
125
126
## Hosted web is a client
127
packages/contracts/src/auth.ts
+8
@@ -431,8 +431,16 @@ export const AuthMcpAuthorizationServerMetadata = Schema.Struct({
431
});
432
export type AuthMcpAuthorizationServerMetadata = typeof AuthMcpAuthorizationServerMetadata.Type;
433
434
+/**
435
+ * The `software_id` another T3 Code environment registers with when it links
436
+ * to this one. Its session is then a peer link: the work it starts here stays
437
+ * within that link. Claiming it only ever adds limits.
438
+ */
439
+export const MCP_PEER_LINK_SOFTWARE_ID = "t3code-peer-link";
440
+
441
export const AuthMcpClientRegistration = Schema.Struct({
442
client_name: Schema.optionalKey(Schema.String),
443
+ software_id: Schema.optionalKey(Schema.String),
444
redirect_uris: Schema.optionalKey(Schema.Array(Schema.String)),
445
token_endpoint_auth_method: Schema.optionalKey(Schema.String),
446
});
packages/contracts/src/environment.ts
+4
@@ -142,6 +142,10 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
142
a linked environment's calls keep its agent's limits. Another environment
143
links to this one only when it is set. */
144
mcpModeLimitHeader: Schema.optionalKey(Schema.Boolean),
145
+ /** Work a linked environment starts here stays within its link
146
+ (`linkOrigin`). Another environment links to this one only when it is
147
+ set, since without it that work could change the user's own threads. */
148
+ linkFence: Schema.optionalKey(Schema.Boolean),
149
});
150
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
151
packages/contracts/src/orchestrationV2.ts
+27
@@ -40,6 +40,7 @@ import {
40
TrimmedNonEmptyString,
41
TurnItemId,
42
} from "./baseSchemas.ts";
43
+import { AuthMcpClientAccess } from "./auth.ts";
44
import { ChatAttachment } from "./chatAttachment.ts";
45
import { ThreadGuestShare } from "./guestShare.ts";
46
import {
@@ -103,6 +104,28 @@ const OrchestrationV2CreationFields = {
104
creationSource: OrchestrationV2CreationSource,
105
} as const;
106
107
+/**
108
+ * The linked environment whose agent started this work here: the MCP client
109
+ * session it signed in with, that session's label, and the access it was
110
+ * paired with. Set when the thread is created and never changed; work derived
111
+ * from it carries the same origin.
112
+ */
113
+export const OrchestrationV2LinkOrigin = Schema.Struct({
114
+ sessionId: TrimmedNonEmptyString,
115
+ label: Schema.String,
116
+ access: Schema.optional(AuthMcpClientAccess),
117
+});
118
+export type OrchestrationV2LinkOrigin = typeof OrchestrationV2LinkOrigin.Type;
119
+
120
+/**
121
+ * Work from a link paired below full access may change only work from the same
122
+ * link. A full-access link's agents already run as this environment's user,
123
+ * so fencing T3's own tools would stop nothing they could not do anyway. An
124
+ * origin stamped before access was recorded stays fenced.
125
+ */
126
+export const linkOriginIsFenced = (origin: OrchestrationV2LinkOrigin) =>
127
+ origin.access !== "full-access";
128
+
129
export const OrchestrationV2NativeRefStrength = Schema.Literals(["strong", "weak", "none"]);
130
export type OrchestrationV2NativeRefStrength = typeof OrchestrationV2NativeRefStrength.Type;
131
@@ -414,6 +437,7 @@ export const OrchestrationV2AppThread = Schema.Struct({
437
branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
438
activeProviderThreadId: Schema.NullOr(ProviderThreadId),
439
historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),
440
+ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),
441
lineage: OrchestrationV2AppThreadLineage,
442
forkedFrom: Schema.NullOr(
443
Schema.Union([
@@ -1942,6 +1966,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
1966
forkedFrom: Schema.NullOr(OrchestrationV2AppThread.fields.forkedFrom),
1967
activeProviderThreadId: Schema.NullOr(ProviderThreadId),
1968
historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),
1969
+ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),
1970
latestRunId: Schema.NullOr(RunId),
1971
latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
1972
latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
@@ -2774,6 +2799,8 @@ export const OrchestrationV2Command = Schema.Union([
2799
interactionMode: ProviderInteractionMode,
2800
branch: Schema.NullOr(TrimmedNonEmptyString),
2801
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
2802
+ /** Only the server sets this; a client's thread.create never carries one. */
2803
+ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),
2804
importedNativeThread: Schema.optional(
2805
Schema.Struct({
2806
ref: Schema.Struct({