Skip to content
TypeScript

feat(server): work a linked environment starts stays within its link (#16695)

Julius Marminge6918c35a367a
diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts
index 59b0077da04..476a3b9f33e 100644
--- a/apps/server/src/auth/EnvironmentAuth.ts
+++ b/apps/server/src/auth/EnvironmentAuth.ts
@@ -92,6 +92,8 @@ export interface McpClientSession {
readonly sessionId: AuthSessionId;
readonly label: string;
readonly access: AuthMcpClientAccess;
+ /** Another T3 Code environment's link, whose work here stays within it. */
+ readonly peerLink: boolean;
}
export interface AuthenticatedSession {
@@ -555,6 +557,7 @@ export class EnvironmentAuth extends Context.Service<
readonly issueMcpClientSession: (input: {
readonly label: string;
readonly access: AuthMcpClientAccess;
+ readonly peerLink: boolean;
readonly client: AuthClientMetadata;
}) => Effect.Effect<
{
@@ -1305,6 +1308,7 @@ export const make = Effect.gen(function* () {
access: session.scopes.includes(AuthOrchestrationOperateScope)
? (session.runtimeModeCeiling ?? "approval-required")
: "read-only",
+ peerLink: session.peerLink === true,
} satisfies McpClientSession)
: Effect.fail(
new ServerAuthInvalidCredentialError({
@@ -1324,6 +1328,7 @@ export const make = Effect.gen(function* () {
scopes: mcpClientScopes(input.access),
ttl: MCP_CLIENT_SESSION_TTL,
...(input.access === "read-only" ? {} : { runtimeModeCeiling: input.access }),
+ peerLink: input.peerLink,
client: { ...input.client, label: input.label, deviceType: "bot" },
})
.pipe(
diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts
index 24cb4f4ddea..064304bce7a 100644
--- a/apps/server/src/auth/McpOAuth.ts
+++ b/apps/server/src/auth/McpOAuth.ts
@@ -13,6 +13,7 @@ import {
type AuthEnvironmentScope,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
+ MCP_PEER_LINK_SOFTWARE_ID,
} from "@t3tools/contracts";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import * as Clock from "effect/Clock";
@@ -132,6 +133,8 @@ const ClientIdPayload = Schema.Struct({
v: Schema.Literal(1),
n: Schema.String,
r: Schema.Array(Schema.String),
+ /** Registered as another T3 Code environment's peer link. */
+ p: Schema.optionalKey(Schema.Literal(1)),
});
const decodeClientIdPayload = Schema.decodeUnknownOption(Schema.fromJsonString(ClientIdPayload));
@@ -139,6 +142,7 @@ export interface McpOAuthClient {
readonly clientId: string;
readonly name: string;
readonly redirectUris: ReadonlyArray<string>;
+ readonly peerLink: boolean;
}
export class McpOAuthPageError extends Schema.TaggedError<McpOAuthPageError>()(
@@ -172,6 +176,7 @@ export interface AuthorizationRequest {
interface PendingCode {
readonly clientId: string;
readonly clientName: string;
+ readonly peerLink: boolean;
readonly redirectUri: string;
readonly codeChallenge: string;
readonly resource: string;
@@ -240,8 +245,10 @@ const make = Effect.gen(function* () {
const sign = (domain: string, payload: string) => signPayload(`${domain}.${payload}`, signingKey);
- const signClientId = (name: string, redirectUris: ReadonlyArray<string>) => {
- const body = base64UrlEncode(JSON.stringify({ v: 1, n: name, r: redirectUris }));
+ const signClientId = (name: string, redirectUris: ReadonlyArray<string>, peerLink: boolean) => {
+ const body = base64UrlEncode(
+ JSON.stringify({ v: 1, n: name, r: redirectUris, ...(peerLink ? { p: 1 } : {}) }),
+ );
return `${body}.${sign("mcp-client-id", body)}`;
};
@@ -257,7 +264,12 @@ const make = Effect.gen(function* () {
}
return Option.getOrUndefined(
decodeClientIdPayload(json).pipe(
- Option.map((payload) => ({ clientId, name: payload.n, redirectUris: payload.r })),
+ Option.map((payload) => ({
+ clientId,
+ name: payload.n,
+ redirectUris: payload.r,
+ peerLink: payload.p === 1,
+ })),
),
);
};
@@ -303,7 +315,13 @@ const make = Effect.gen(function* () {
});
}
// RFC 7591 allows ignoring unsupported registration options; all clients use public PKCE.
- return { clientId: signClientId(name, redirectUris), name, redirectUris };
+ const peerLink = metadata.software_id === MCP_PEER_LINK_SOFTWARE_ID;
+ return {
+ clientId: signClientId(name, redirectUris, peerLink),
+ name,
+ redirectUris,
+ peerLink,
+ };
},
);
@@ -385,6 +403,7 @@ const make = Effect.gen(function* () {
next.set(code, {
clientId: authorization.client.clientId,
clientName: authorization.client.name,
+ peerLink: authorization.client.peerLink,
redirectUri: authorization.redirectUri,
codeChallenge: authorization.codeChallenge,
resource: authorization.resource,
@@ -488,6 +507,7 @@ const make = Effect.gen(function* () {
.issueMcpClientSession({
label: pending.clientName,
access: pending.access,
+ peerLink: pending.peerLink,
client: deriveAuthClientMetadata({ request }),
})
.pipe(
@@ -540,6 +560,7 @@ export const layerMcpClientAuthenticator = Layer.effect(
sessionId: client.sessionId,
label: client.label,
access: client.access,
+ linked: client.peerLink,
},
capabilities: new Set<McpInvocationContext.McpCapability>([
"orchestration",
diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts
index d1926980129..e11e4bc4e11 100644
--- a/apps/server/src/auth/SessionStore.ts
+++ b/apps/server/src/auth/SessionStore.ts
@@ -60,6 +60,8 @@ export interface VerifiedSession {
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
readonly proofKeyThumbprint?: string;
readonly runtimeModeCeiling?: RuntimeMode;
+ /** An MCP client that is another T3 Code environment's peer link. */
+ readonly peerLink?: true;
}
export interface VerifiedWebSocketTicket extends VerifiedSession {
@@ -381,6 +383,7 @@ export class SessionStore extends Context.Service<
readonly client?: AuthClientMetadata;
readonly proofKeyThumbprint?: string;
readonly runtimeModeCeiling?: RuntimeMode;
+ readonly peerLink?: boolean;
readonly replaceActiveForSubjectAndMethod?: boolean;
readonly replaceSessionId?: AuthSessionId;
}) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
@@ -441,6 +444,8 @@ const SessionClaims = Schema.Struct({
method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),
jkt: Schema.optionalKey(Schema.String),
rtc: Schema.optionalKey(RuntimeMode),
+ /** Signed, so a client cannot shed its peer link's limits. */
+ plk: Schema.optionalKey(Schema.Literal(1)),
iat: Schema.Number,
exp: Schema.Number,
});
@@ -679,6 +684,7 @@ const make = Effect.gen(function* () {
method: input?.method ?? "browser-session-cookie",
...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}),
+ ...(input?.peerLink === true ? { plk: 1 as const } : {}),
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
@@ -860,6 +866,7 @@ const make = Effect.gen(function* () {
scopes: claims.scopes,
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}),
+ ...(claims.plk === 1 ? { peerLink: true as const } : {}),
} satisfies VerifiedSession;
},
);
diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts
index c14035b6795..777213bc9ff 100644
--- a/apps/server/src/cli/thread.ts
+++ b/apps/server/src/cli/thread.ts
@@ -221,6 +221,7 @@ const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* <A, E,
// The CLI runs as the machine's owner. New threads still start at
// the project's default mode, never at this ceiling by default.
access: "full-access",
+ peerLink: false,
client: { deviceType: "bot" },
}),
(session) =>
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index 04c857b6360..fe47ea862d0 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -267,6 +267,7 @@ export const make = Effect.gen(function* () {
serverBrowser: true,
peerLinks: true,
mcpModeLimitHeader: true,
+ linkFence: true,
},
};
diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts
index 23b9acf9f15..570dc04ccd7 100644
--- a/apps/server/src/mcp/McpHttpServer.test.ts
+++ b/apps/server/src/mcp/McpHttpServer.test.ts
@@ -982,6 +982,7 @@ it.effect(
(input) => input,
(_, modes) =>
Effect.succeed({ modes: `${modes.runtimeMode}/${modes.interactionMode}` }),
+ "stamped",
),
}),
).pipe(
diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts
index 3553f0c3a77..8e0f55f36b9 100644
--- a/apps/server/src/mcp/McpInvocationContext.ts
+++ b/apps/server/src/mcp/McpInvocationContext.ts
@@ -34,6 +34,11 @@ export interface McpClientCaller {
readonly sessionId: string;
readonly label: string;
readonly access: AuthMcpClientAccess;
+ /**
+ * Another T3 Code environment's peer link. What it starts here carries its
+ * session as `linkOrigin`, and it changes only that work (`linkOrigin.ts`).
+ */
+ readonly linked?: boolean | undefined;
/**
* Narrower modes the client asked for on this request (`T3-Mode-Limit`):
* another environment passing on the limits of the agent it calls for.
diff --git a/apps/server/src/mcp/McpToolAccess.test.ts b/apps/server/src/mcp/McpToolAccess.test.ts
index e3c49f5cbdf..14888108502 100644
--- a/apps/server/src/mcp/McpToolAccess.test.ts
+++ b/apps/server/src/mcp/McpToolAccess.test.ts
@@ -144,6 +144,7 @@ const probeHandlers: McpToolAccess.Handlers<typeof ProbeToolkit.tools> = {
starts_threads: McpToolAccess.startsThreads(
(input) => input,
(_, modes) => Effect.succeed({ ran: `${modes.runtimeMode}/${modes.interactionMode}` }),
+ "stamped",
),
writes_environment: McpToolAccess.writesEnvironment(() => ran),
};
@@ -231,6 +232,15 @@ const mismatchedProvider = {
const supervisedClient = clientCaller("approval-required");
const fullAccessClient = clientCaller("full-access");
const readOnlyClient = clientCaller("read-only");
+const linkedClient: McpInvocationContext.McpInvocationScope = {
+ ...supervisedClient,
+ client: { ...supervisedClient.client!, linked: true },
+};
+// A full-access link's agents can do anything this environment's user can.
+const fullAccessLinkedClient: McpInvocationContext.McpInvocationScope = {
+ ...fullAccessClient,
+ client: { ...fullAccessClient.client!, linked: true },
+};
const previewOnly = { ...fullAccess, capabilities: new Set(["preview"] as const) };
it.effect.each([
@@ -265,6 +275,10 @@ it.effect.each([
["writes_with_capability", previewOnly, {}, "ran"],
["writes_with_capability", readOnlyClient, {}, "capability_denied"],
["writes_with_capability", ended, {}, "parent_not_active"],
+ ["writes", linkedClient, {}, "capability_denied"],
+ ["writes_with_capability", linkedClient, {}, "capability_denied"],
+ ["writes", fullAccessLinkedClient, {}, "ran"],
+ ["writes_with_capability", fullAccessLinkedClient, {}, "ran"],
["writes_threads", supervised, {}, "ran"],
["writes_threads", supervised, { threadId: planThreadId }, "ran"],
@@ -374,7 +388,7 @@ const linkedProbeServer = McpHttpServer.toolkitRegistration(
writes: McpToolAccess.writes(ranHere),
writes_with_capability: McpToolAccess.writesWithCapability(ranHere),
writes_threads: McpToolAccess.writesThreads((input) => [input.threadId], ranHere),
- starts_threads: McpToolAccess.startsThreads((input) => input, ranHere),
+ starts_threads: McpToolAccess.startsThreads((input) => input, ranHere, "stamped"),
writes_environment: McpToolAccess.writesEnvironment(ranHere),
}),
).pipe(
diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts
index d2e218dea0d..7e6821e5139 100644
--- a/apps/server/src/mcp/McpToolAccess.ts
+++ b/apps/server/src/mcp/McpToolAccess.ts
@@ -1,5 +1,6 @@
import {
type EnvironmentId,
+ type OrchestrationV2LinkOrigin,
OrchestratorMcpEnvironmentTarget,
OrchestratorMcpFailure,
type ProviderInteractionMode,
@@ -20,6 +21,7 @@ import {
type DispatchModeRefusal,
} from "../orchestration-v2/DispatchModeLimit.ts";
import * as PeerForwarding from "../peer/PeerForwarding.ts";
+import { assertNotLinked, assertSameLink, callerLinkOrigin } from "./linkOrigin.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
import { resolveInteractionMode, resolveRuntimeMode } from "./OrchestratorMcpService.ts";
import {
@@ -135,16 +137,39 @@ export const actsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A,
undefined,
);
-export const writes = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
+/**
+ * Changes something that belongs to no thread, such as a pending upload or a
+ * scheduled task. Work a linked environment started may not: none of it
+ * carries the link's origin, so none of it is that link's.
+ */
+export const writes = <P, A, E, R>(
+ handle: (params: P) => Effect.Effect<A, E, R>,
+ options?: {
+ /** Whether a linked caller may make it, as for uploads its own sends need. */
+ readonly linkedCallers?: "allowed";
+ },
+) =>
declare(
- (params: P) => orchestratingCaller.pipe(Effect.flatMap(() => handle(params))),
+ (params: P) =>
+ orchestratingCaller.pipe(
+ Effect.tap((caller) =>
+ options?.linkedCallers === "allowed"
+ ? Effect.void
+ : assertNotLinked(caller, "change this environment's scheduled tasks"),
+ ),
+ Effect.flatMap(() => handle(params)),
+ ),
() => orchestratingCaller,
);
-/** Requires handler capability checks, not thread control. */
+/** Requires handler capability checks, not thread control; linked work is refused the same way. */
export const writesWithCapability = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
declare(
- (params: P) => writingCaller.pipe(Effect.flatMap(() => handle(params))),
+ (params: P) =>
+ writingCaller.pipe(
+ Effect.tap((caller) => assertNotLinked(caller, "start work here that is not its link's")),
+ Effect.flatMap(() => handle(params)),
+ ),
() => writingCaller,
);
@@ -163,6 +188,7 @@ export const writesThreads = <P, A, E, R>(
.pipe(Effect.mapError(unavailable));
if (target !== null && target.deletedAt === null) {
yield* assertTargetWithinLimits(caller.limits, target);
+ yield* assertSameLink(caller, target);
}
}
// 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) =>
export interface StartedModes {
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
+ /** The linked environment the caller acts for. The thread must carry it. */
+ readonly linkOrigin: OrchestrationV2LinkOrigin | undefined;
}
+/**
+ * Starts threads with the modes `modes` requests, which may not be broader
+ * than the caller's. `linked` says what a linked caller gets: threads stamped
+ * with its `linkOrigin`, or a refusal where the tool cannot carry one.
+ */
export const startsThreads = <P, A, E, R>(
modes: (params: P) => {
readonly runtimeMode?: RuntimeMode | undefined;
readonly interactionMode?: ProviderInteractionMode | undefined;
},
handle: (params: P, modes: StartedModes) => Effect.Effect<A, E, R>,
+ linked: "stamped" | { readonly refused: string },
) => {
- const started = Effect.fn("McpToolAccess.started")(function* (params: P) {
- const { limits } = yield* writingCaller;
+ const started = Effect.fn("McpToolAccess.started")(function* (caller: Caller, params: P) {
const requested = modes(params);
return {
- runtimeMode: yield* resolveRuntimeMode(limits.runtimeMode, requested.runtimeMode),
+ runtimeMode: yield* resolveRuntimeMode(caller.limits.runtimeMode, requested.runtimeMode),
interactionMode: yield* resolveInteractionMode(
- limits.interactionMode,
+ caller.limits.interactionMode,
requested.interactionMode,
),
+ linkOrigin: callerLinkOrigin(caller),
} satisfies StartedModes;
});
return declare(
- (params: P) => Effect.flatMap(started(params), (modes) => handle(params, modes)),
- started,
+ (params: P) =>
+ Effect.gen(function* () {
+ const caller = yield* writingCaller;
+ if (linked !== "stamped") yield* assertNotLinked(caller, linked.refused);
+ return yield* handle(params, yield* started(caller, params));
+ }),
+ (params: P) => Effect.flatMap(writingCaller, (caller) => started(caller, params)),
);
};
@@ -251,13 +290,29 @@ export const writesEnvironment = <P, A, E, R>(
params: P,
check: Effect.Effect<Caller, OrchestratorMcpFailure, CheckServices>,
) => Effect.Effect<A, E, R>,
+ options?: {
+ /**
+ * Whether a linked caller may make it, as for adding a project: it leaves
+ * everything already here as it was.
+ */
+ readonly linkedCallers?: "allowed";
+ },
) => {
const check = orchestratingCaller.pipe(
+ Effect.tap((caller) =>
+ options?.linkedCallers === "allowed"
+ ? Effect.void
+ : assertNotLinked(caller, "change projects or environment settings"),
+ ),
Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)),
);
return declare(
(params: P) => check.pipe(Effect.flatMap(() => handle(params, check))),
- () => check,
+ // Linked work never reaches a link at all; that is checked as the call goes.
+ () =>
+ orchestratingCaller.pipe(
+ Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)),
+ ),
);
};
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index 481c2c97045..f2ce8c8bb1c 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -2584,6 +2584,9 @@ const make = Effect.gen(function* () {
interactionMode,
branch: parent.thread.branch,
worktreePath: parent.thread.worktreePath,
+ ...(parent.thread.linkOrigin === undefined
+ ? {}
+ : { linkOrigin: parent.thread.linkOrigin }),
})
.pipe(
Effect.mapError((error) =>
diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts
index 8f02ee15464..267df07f243 100644
--- a/apps/server/src/mcp/WorktreeMcpService.ts
+++ b/apps/server/src/mcp/WorktreeMcpService.ts
@@ -357,7 +357,9 @@ const make = Effect.gen(function* () {
scriptName: result.scriptName,
terminalId: result.terminalId,
}
- : { status: "no-script" },
+ : result.status === "skipped-for-link"
+ ? { status: "skipped" }
+ : { status: "no-script" },
),
reportFailed("worktree handoff setup script failed"),
);
diff --git a/apps/server/src/mcp/linkOrigin.test.ts b/apps/server/src/mcp/linkOrigin.test.ts
new file mode 100644
index 00000000000..c990fbf68e8
--- /dev/null
+++ b/apps/server/src/mcp/linkOrigin.test.ts
@@ -0,0 +1,387 @@
+import * as DocumentText from "../provider/DocumentText.ts";
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, it } from "@effect/vitest";
+import {
+ CommandId,
+ ContextTransferId,
+ EnvironmentId,
+ NodeId,
+ type OrchestrationV2Run,
+ ProjectId,
+ ProviderDriverKind,
+ ProviderInstanceId,
+ RunId,
+ ThreadId,
+} from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import { McpSchema, McpServer } from "effect/ai";
+
+import * as ServerConfig from "../config.ts";
+import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
+import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
+import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
+import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
+import { makeSubagentChildThread } from "@t3tools/provider-core/server/subagentProjection";
+import * as ThreadForkService from "../orchestration-v2/ThreadForkService.ts";
+import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
+import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
+import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
+import * as SqlitePersistence from "../persistence/Sqlite.ts";
+import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
+import * as ProjectService from "../project/ProjectService.ts";
+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
+import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
+import * as ServerSettings from "../serverSettings.ts";
+import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
+import * as SecretRequests from "../secrets/SecretRequests.ts";
+import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
+import * as McpHttpServer from "./McpHttpServer.ts";
+import * as McpInvocationContext from "./McpInvocationContext.ts";
+import * as PeerForwarding from "../peer/PeerForwarding.ts";
+import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
+
+// A linked environment's session drives this one's real orchestrator through
+// its real T3 tools. What the link starts carries its origin, and the link
+// changes only that.
+
+const instanceId = ProviderInstanceId.make("codex");
+const projectId = ProjectId.make("project:link-origin");
+const adapter = {
+ instanceId,
+ driver: ProviderDriverKind.make("codex"),
+ getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
+ openSession: () => Effect.die("No provider process needed for these commands"),
+} as ProviderAdapter.ProviderAdapterV2["Service"];
+const layerDatabase = SqlitePersistence.layerMemory;
+const layerOrchestrator = Layer.mergeAll(
+ layerDatabase,
+ ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
+ ProviderReplayHarness.layerWithRegistry(
+ { name: "link-origin" },
+ ProviderAdapterRegistry.layerFromAdapters([adapter]),
+ { databaseLayer: layerDatabase, runEffectWorker: false },
+ ),
+);
+const layerOrchestration = ThreadManagement.layer.pipe(
+ Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
+ Layer.provideMerge(Layer.merge(layerOrchestrator, ServerSettings.layerTest())),
+);
+
+/** Launches dispatch the real thread.create, and nothing more: no workspace, no run. */
+const layerLaunches = Layer.effect(
+ ThreadLaunch.ThreadLaunchService,
+ Effect.gen(function* () {
+ const threads = yield* ThreadManagement.ThreadManagementService;
+ return ThreadLaunch.ThreadLaunchService.of({
+ launch: (input: ThreadLaunch.ThreadLaunchInput) =>
+ threads
+ .dispatch({
+ type: "thread.create",
+ commandId: input.commandId,
+ threadId: input.threadId!,
+ projectId: input.projectId,
+ title: input.title,
+ modelSelection: input.modelSelection,
+ runtimeMode: input.runtimeMode,
+ interactionMode: input.interactionMode,
+ branch: null,
+ worktreePath: null,
+ ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),
+ createdBy: input.createdBy,
+ creationSource: input.creationSource,
+ })
+ .pipe(
+ Effect.flatMap(() => threads.getThreadProjection(input.threadId!)),
+ Effect.map((projection) => ({
+ threadId: input.threadId!,
+ projection,
+ resumed: false,
+ })),
+ Effect.orDie,
+ ),
+ } as unknown as ThreadLaunch.ThreadLaunchService["Service"]);
+ }),
+);
+
+const layerTools = Layer.mergeAll(
+ McpHttpServer.layerOrchestratorToolkit,
+ McpHttpServer.layerThreadToolkit,
+ McpHttpServer.layerProjectRegistration,
+).pipe(
+ Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
+ Layer.provideMerge(McpServer.McpServer.layer),
+ Layer.provide(layerLaunches),
+ Layer.provide(NodeCrypto.layer),
+ Layer.provide(
+ Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
+ ),
+ Layer.provide(
+ Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
+ list: () => Effect.succeed([]),
+ }),
+ ),
+ Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
+ Layer.provide(
+ Layer.mock(ProjectService.ProjectService)({
+ getById: () => Effect.succeedNone,
+ create: (input) =>
+ Effect.succeed({
+ id: input.projectId,
+ title: input.title,
+ workspaceRoot: input.workspaceRoot,
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-10-18T00:00:00.000Z",
+ updatedAt: "2026-10-18T00:00:00.000Z",
+ deletedAt: null,
+ }),
+ update: (input) =>
+ Effect.succeed({
+ id: input.projectId,
+ title: input.title ?? "Untitled",
+ workspaceRoot: "/p/t3code",
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-10-18T00:00:00.000Z",
+ updatedAt: "2026-10-18T00:00:00.000Z",
+ deletedAt: null,
+ }),
+ }),
+ ),
+ Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
+ Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
+ Layer.provide(
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/p" }),
+ ),
+ Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
+ Layer.provide(
+ Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
+ cloneRepository: (input) =>
+ Effect.succeed({
+ cwd: input.destinationPath,
+ remoteUrl: "https://github.com/pingdotgg/t3code.git",
+ repository: null,
+ }),
+ }),
+ ),
+ Layer.provide(
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-link-origin-" }).pipe(
+ Layer.provide(NodeServices.layer),
+ ),
+ ),
+ Layer.provide(NodeServices.layer),
+);
+
+const mcpClient = McpSchema.McpServerClient.of({
+ clientId: 1,
+ protocolVersion: "2025-06-18",
+ clientCapabilities: {},
+ clientInfo: { name: "link-origin", version: "1" },
+ initializePayload: {
+ protocolVersion: "2025-06-18",
+ capabilities: {},
+ clientInfo: { name: "link-origin", version: "1" },
+ },
+ getClient: Effect.die("unused"),
+});
+
+const clientScope = (
+ sessionId: string,
+ linked: boolean,
+ access: McpInvocationContext.McpClientCaller["access"],
+): McpInvocationContext.McpInvocationScope => ({
+ environmentId: EnvironmentId.make("environment:box"),
+ requestNamespace: `client:${sessionId}`,
+ thread: undefined,
+ client: { sessionId, label: `T3 Code · ${sessionId}`, access, linked },
+ capabilities: new Set(["orchestration", "worktree", "pull-requests"]),
+ issuedAt: 0,
+});
+const laptop = clientScope("laptop", true, "auto");
+const desk = clientScope("desk", true, "auto");
+const trusted = clientScope("trusted", true, "full-access");
+const claudeCode = clientScope("claude-code", false, "full-access");
+
+const call = (
+ scope: McpInvocationContext.McpInvocationScope,
+ name: string,
+ args: Record<string, unknown>,
+) =>
+ McpServer.McpServer.pipe(
+ Effect.flatMap((server) => server.callTool({ name, arguments: args })),
+ Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
+ Effect.provideService(McpSchema.McpServerClient, mcpClient),
+ );
+
+const failureCode = (result: McpSchema.CallToolResult) => {
+ const text = result.content[0];
+ return result.isError === true && text?.type === "text"
+ ? (JSON.parse(text.text) as { code: string }).code
+ : undefined;
+};
+
+const launch = (scope: McpInvocationContext.McpInvocationScope, title: string) =>
+ call(scope, "t3_thread_launch", {
+ projectId,
+ title,
+ modelSelection: { instanceId, model: "gpt-5" },
+ }).pipe(
+ Effect.map((result) => {
+ assert.equal(result.isError, false, JSON.stringify(result.content));
+ return (result.structuredContent as { threadId: ThreadId }).threadId;
+ }),
+ );
+
+const usersOwnThread = Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const threadId = ThreadId.make("thread:users-own");
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("create:users-own"),
+ threadId,
+ projectId,
+ title: "The user's own",
+ modelSelection: { instanceId, model: "gpt-5" },
+ // Within an `auto` link's modes, so only the fence decides.
+ runtimeMode: "auto",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdBy: "user",
+ creationSource: "web",
+ });
+ return threadId;
+});
+
+it.layer(Layer.provideMerge(layerTools, layerOrchestration))("work a link starts", (it) => {
+ it.effect("is stamped, and so is the work it derives", () =>
+ Effect.gen(function* () {
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const launched = yield* launch(laptop, "Started from the laptop");
+ const shell = yield* projections.getThreadShell(launched);
+ assert.deepEqual(shell?.linkOrigin, {
+ sessionId: "laptop",
+ label: "T3 Code · laptop",
+ access: "auto",
+ });
+
+ // A subagent of it and a fork of it are built from its thread, origin included.
+ const thread = (yield* ThreadManagement.ThreadManagementService.pipe(
+ Effect.flatMap((threads) => threads.getThreadProjection(launched)),
+ )).thread;
+ const child = makeSubagentChildThread({
+ parentThread: thread,
+ childThreadId: ThreadId.make("thread:child"),
+ parentNodeId: NodeId.make("node:child"),
+ activeProviderThreadId: null,
+ providerInstanceId: instanceId,
+ modelSelection: { instanceId, model: "gpt-5" },
+ title: "Child",
+ now: thread.createdAt,
+ createdBy: "agent",
+ creationSource: "mcp",
+ });
+ assert.deepEqual(child.linkOrigin, shell?.linkOrigin);
+ const fork = yield* ThreadForkService.ThreadForkServiceV2.pipe(
+ Effect.flatMap((forks) =>
+ forks.plan({
+ sourceProjection: { thread },
+ sourceRun: { id: RunId.make("run:source"), status: "completed" } as OrchestrationV2Run,
+ sourceProviderThread: undefined,
+ canonicalSourcePoint: { threadId: launched },
+ transferId: ContextTransferId.make("transfer:fork"),
+ targetThreadId: ThreadId.make("thread:fork"),
+ createdBy: "agent",
+ creationSource: "mcp",
+ createdAt: thread.createdAt,
+ }),
+ ),
+ Effect.provide(ThreadForkService.layer),
+ );
+ assert.deepEqual(fork.targetThread.linkOrigin, shell?.linkOrigin);
+
+ // An ordinary outside agent's launch is not a link's.
+ const plain = yield* launch(claudeCode, "Started by Claude Code");
+ assert.equal((yield* projections.getThreadShell(plain))?.linkOrigin, undefined);
+ }),
+ );
+
+ it.effect("changes only that link's threads below full access", () =>
+ Effect.gen(function* () {
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const users = yield* usersOwnThread;
+ const ownLaunch = yield* launch(laptop, "The laptop's");
+ const rename = (scope: McpInvocationContext.McpInvocationScope, threadId: ThreadId) =>
+ call(scope, "t3_thread_update", {
+ threadId,
+ action: "rename",
+ title: `Renamed by ${scope.client!.sessionId}`,
+ });
+
+ // The link may change what it started.
+ assert.equal((yield* rename(laptop, ownLaunch)).isError, false);
+ assert.equal((yield* projections.getThreadShell(ownLaunch))?.title, "Renamed by laptop");
+ // Not the user's own thread, nor another link's.
+ assert.equal(failureCode(yield* rename(laptop, users)), "capability_denied");
+ assert.equal(failureCode(yield* rename(desk, ownLaunch)), "capability_denied");
+ assert.equal((yield* projections.getThreadShell(users))?.title, "The user's own");
+ // An ordinary outside agent is not fenced.
+ assert.equal((yield* rename(claudeCode, users)).isError, false);
+ // Naming this environment's own id is still this environment's thread.
+ for (const [name, args] of [
+ ["t3_thread_send", { message: "From the laptop." }],
+ ["t3_thread_interrupt", {}],
+ ] as const) {
+ const result = yield* call(laptop, name, {
+ ...args,
+ environmentId: laptop.environmentId,
+ threadId: users,
+ });
+ assert.equal(failureCode(result), "capability_denied", name);
+ }
+
+ // Nor scheduled tasks, which belong to no thread.
+ assert.equal(
+ failureCode(yield* call(laptop, "delete_scheduled_task", { scheduledTaskId: "any" })),
+ "capability_denied",
+ );
+
+ // Reads are not fenced.
+ const read = yield* call(laptop, "t3_thread_read", { threadId: users });
+ assert.equal(read.isError, false);
+ }),
+ );
+
+ it.effect("is not fenced when the link has full access, but still says where it came from", () =>
+ Effect.gen(function* () {
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const users = yield* usersOwnThread;
+ const launched = yield* launch(trusted, "Started from the desk");
+ assert.deepEqual((yield* projections.getThreadShell(launched))?.linkOrigin, {
+ sessionId: "trusted",
+ label: "T3 Code · trusted",
+ access: "full-access",
+ });
+
+ const renamed = yield* call(trusted, "t3_thread_update", {
+ threadId: users,
+ action: "rename",
+ title: "Renamed from the desk",
+ });
+ assert.equal(renamed.isError, false, JSON.stringify(renamed.content));
+ for (const [name, args] of [
+ ["t3_project_update", { projectId, title: "The desk's now" }],
+ ["t3_project_create", { title: "t3code", workspaceRoot: "/p/t3code" }],
+ ] as const) {
+ const changed = yield* call(trusted, name, args);
+ assert.equal(changed.isError, false, `${name}: ${JSON.stringify(changed.content)}`);
+ }
+ }),
+ );
+});
diff --git a/apps/server/src/mcp/linkOrigin.ts b/apps/server/src/mcp/linkOrigin.ts
new file mode 100644
index 00000000000..7373fd51d2b
--- /dev/null
+++ b/apps/server/src/mcp/linkOrigin.ts
@@ -0,0 +1,60 @@
+import {
+ linkOriginIsFenced,
+ OrchestratorMcpFailure,
+ type OrchestrationV2LinkOrigin,
+ type OrchestrationV2ThreadShell,
+} from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+
+import type { Caller } from "./threadAccess.ts";
+
+/**
+ * Below full access, work a link starts here (all of it carries that session in `linkOrigin`)
+ * may change only work from the same link: not the user's threads, projects or settings, nor
+ * this environment's links. Reads are not fenced. It is a routing rule for T3's tools; agents
+ * still run as this environment's user, so a full-access link is not fenced at all.
+ */
+
+/** The link a caller acts for: its own session, or the link that started its thread. */
+export const callerLinkOrigin = (
+ caller: Pick<Caller, "scope" | "caller">,
+): OrchestrationV2LinkOrigin | undefined =>
+ caller.caller?.linkOrigin ??
+ (caller.scope.client?.linked === true
+ ? {
+ sessionId: caller.scope.client.sessionId,
+ label: caller.scope.client.label,
+ access: caller.scope.client.access,
+ }
+ : undefined);
+
+/** The link that fences a caller, if any: one paired below full access. */
+const fencingLinkOrigin = (caller: Pick<Caller, "scope" | "caller">) => {
+ const origin = callerLinkOrigin(caller);
+ return origin !== undefined && linkOriginIsFenced(origin) ? origin : undefined;
+};
+
+const outsideLink = (origin: OrchestrationV2LinkOrigin, message: string) =>
+ new OrchestratorMcpFailure({
+ code: "capability_denied",
+ 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.`,
+ });
+
+/** A thread a fenced caller may change: one its own link started. */
+export const assertSameLink = (
+ caller: Pick<Caller, "scope" | "caller">,
+ target: Pick<OrchestrationV2ThreadShell, "id" | "linkOrigin">,
+) => {
+ const origin = fencingLinkOrigin(caller);
+ return origin === undefined || target.linkOrigin?.sessionId === origin.sessionId
+ ? Effect.void
+ : Effect.fail(outsideLink(origin, `it may change only threads that link started.`));
+};
+
+/** Fenced work never changes what the environment already has: projects, settings, scheduled runs. */
+export const assertNotLinked = (caller: Pick<Caller, "scope" | "caller">, what: string) => {
+ const origin = fencingLinkOrigin(caller);
+ return origin === undefined
+ ? Effect.void
+ : Effect.fail(outsideLink(origin, `it cannot ${what}.`));
+};
diff --git a/apps/server/src/mcp/toolkits/attachment/handlers.ts b/apps/server/src/mcp/toolkits/attachment/handlers.ts
index 4c7f168f601..b2248976235 100644
--- a/apps/server/src/mcp/toolkits/attachment/handlers.ts
+++ b/apps/server/src/mcp/toolkits/attachment/handlers.ts
@@ -46,31 +46,37 @@ export const layer = McpToolAccess.toLayer(
Effect.sync(() => {
const uploadOwners = new Map<string, { readonly owner: string; readonly issuedAt: number }>();
return {
- t3_attachment_prepare_upload: McpToolAccess.writes((input) =>
- Effect.gen(function* () {
- const result = yield* Upload.issueAttachmentUploadUrl(input.upload).pipe(
- Effect.mapError(unavailable),
- );
- const now = yield* Clock.currentTimeMillis;
- for (const [id, entry] of uploadOwners) {
- if (now - entry.issuedAt > UPLOAD_OWNER_TTL_MS) uploadOwners.delete(id);
- }
- uploadOwners.set(result.attachmentId, { owner: yield* uploadOwner, issuedAt: now });
- return result;
- }),
+ // A pending upload belongs to its caller until a send claims it, so
+ // linked callers may stage the uploads their own sends need.
+ t3_attachment_prepare_upload: McpToolAccess.writes(
+ (input) =>
+ Effect.gen(function* () {
+ const result = yield* Upload.issueAttachmentUploadUrl(input.upload).pipe(
+ Effect.mapError(unavailable),
+ );
+ const now = yield* Clock.currentTimeMillis;
+ for (const [id, entry] of uploadOwners) {
+ if (now - entry.issuedAt > UPLOAD_OWNER_TTL_MS) uploadOwners.delete(id);
+ }
+ uploadOwners.set(result.attachmentId, { owner: yield* uploadOwner, issuedAt: now });
+ return result;
+ }),
+ { linkedCallers: "allowed" },
),
- t3_attachment_discard: McpToolAccess.writes((input) =>
- Effect.gen(function* () {
- if (uploadOwners.get(input.attachmentId)?.owner !== (yield* uploadOwner)) {
- return yield* new OrchestratorMcpFailure({
- code: "invalid_request",
- message: "Only the caller that prepared a pending upload can discard it.",
- });
- }
- yield* Upload.deletePendingAttachment(input.attachmentId);
- uploadOwners.delete(input.attachmentId);
- return {};
- }),
+ t3_attachment_discard: McpToolAccess.writes(
+ (input) =>
+ Effect.gen(function* () {
+ if (uploadOwners.get(input.attachmentId)?.owner !== (yield* uploadOwner)) {
+ return yield* new OrchestratorMcpFailure({
+ code: "invalid_request",
+ message: "Only the caller that prepared a pending upload can discard it.",
+ });
+ }
+ yield* Upload.deletePendingAttachment(input.attachmentId);
+ uploadOwners.delete(input.attachmentId);
+ return {};
+ }),
+ { linkedCallers: "allowed" },
),
t3_thread_send_attachments: McpToolAccess.writesThreads(
(input) => [input.threadId],
diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
index 1dfd6a70f04..5d26408314a 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
@@ -95,6 +95,8 @@ const handlers = {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
return yield* service.scheduleTask(scope, { ...input, prompt, schedule });
}),
+ // A scheduled run starts long after its caller, with nothing to carry the link.
+ { refused: "schedule tasks in this environment" },
),
McpToolAccess.writes(
({ scheduledTaskId, prompt, title, schedule, enabled, bindToCurrentThread }) =>
diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts
index c380775e299..55034630b2c 100644
--- a/apps/server/src/mcp/toolkits/project/handlers.ts
+++ b/apps/server/src/mcp/toolkits/project/handlers.ts
@@ -76,7 +76,7 @@ const access = Effect.gen(function* () {
export const layer = McpToolAccess.toLayer(ProjectToolkit, {
t3_thread_launch: McpToolAccess.startsThreads(
(input) => input,
- (input, { runtimeMode, interactionMode }) =>
+ (input, { runtimeMode, interactionMode, linkOrigin }) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext.McpInvocationContext;
const context = yield* readCaller();
@@ -216,6 +216,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
}),
createdBy: "agent",
creationSource: "mcp",
+ ...(linkOrigin === undefined ? {} : { linkOrigin }),
}).pipe(
Effect.mapError((error) => {
if (error._tag === "AttachmentClaimError") {
@@ -244,6 +245,8 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
status: run?.status ?? null,
};
}),
+ // The launched thread carries the caller's link, if it has one.
+ "stamped",
),
t3_project_list: McpToolAccess.reads((input) =>
Effect.gen(function* () {
@@ -267,48 +270,53 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
return result.value;
}),
),
- t3_project_create: McpToolAccess.writesEnvironment(({ workspaceRoot, ...input }) =>
- Effect.gen(function* () {
- const projects = yield* Project.ProjectService;
- if (workspaceRoot === undefined) {
- // Only updates record model defaults; reject defaults that creation would silently drop.
- if (
- input.scripts !== undefined ||
- input.createWorkspaceRootIfMissing !== undefined ||
- input.defaultModelSelection !== undefined
- )
- return yield* new OrchestratorMcpFailure({
- code: "invalid_request",
- message:
- "A project started from its title takes only a title; set scripts or defaultModelSelection afterwards with t3_project_update.",
- });
- const folders = yield* ManagedProjectFolders.ManagedProjectFolders;
- const created = yield* folders
- .createNamedProject({ name: input.title })
- .pipe(
+ t3_project_create: McpToolAccess.writesEnvironment(
+ ({ workspaceRoot, ...input }) =>
+ Effect.gen(function* () {
+ const projects = yield* Project.ProjectService;
+ if (workspaceRoot === undefined) {
+ // Only updates record model defaults; reject defaults that creation would silently drop.
+ if (
+ input.scripts !== undefined ||
+ input.createWorkspaceRootIfMissing !== undefined ||
+ input.defaultModelSelection !== undefined
+ )
+ return yield* new OrchestratorMcpFailure({
+ code: "invalid_request",
+ message:
+ "A project started from its title takes only a title; set scripts or defaultModelSelection afterwards with t3_project_update.",
+ });
+ const folders = yield* ManagedProjectFolders.ManagedProjectFolders;
+ const created = yield* folders.createNamedProject({ name: input.title }).pipe(
Effect.mapError(
(error) =>
- new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
- ),
- );
- const project = yield* projects
- .getById(created.projectId)
- .pipe(
- Effect.mapError(unavailable),
- Effect.flatMap(
- Option.match({ onNone: () => Effect.fail(unavailable()), onSome: Effect.succeed }),
+ new OrchestratorMcpFailure({
+ code: "orchestration_error",
+ message: error.message,
+ }),
),
);
- return {
- ...project,
- ...(created.commitError === undefined ? {} : { commitError: created.commitError }),
- };
- }
- const commandId = yield* newCommandId();
- return yield* projects
- .create({ ...input, workspaceRoot, commandId, projectId: ProjectId.make(commandId) })
- .pipe(Effect.mapError(projectFailure));
- }),
+ const project = yield* projects
+ .getById(created.projectId)
+ .pipe(
+ Effect.mapError(unavailable),
+ Effect.flatMap(
+ Option.match({ onNone: () => Effect.fail(unavailable()), onSome: Effect.succeed }),
+ ),
+ );
+ return {
+ ...project,
+ ...(created.commitError === undefined ? {} : { commitError: created.commitError }),
+ };
+ }
+ const commandId = yield* newCommandId();
+ return yield* projects
+ .create({ ...input, workspaceRoot, commandId, projectId: ProjectId.make(commandId) })
+ .pipe(Effect.mapError(projectFailure));
+ }),
+ // Linked work may bring the repository it works in; an existing
+ // registered workspace is still refused.
+ { linkedCallers: "allowed" },
),
t3_project_update: McpToolAccess.writesEnvironment((input) =>
Effect.gen(function* () {
@@ -326,18 +334,21 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
.pipe(Effect.mapError(projectFailure));
}),
),
- t3_project_clone: McpToolAccess.writesEnvironment((input) =>
- Effect.gen(function* () {
- const repositories = yield* Repositories.SourceControlRepositoryService;
- return yield* repositories.cloneRepository(input).pipe(
- Effect.mapError(
- (error) =>
- new OrchestratorMcpFailure({
- code: "orchestration_error",
- message: error.detail,
- }),
- ),
- );
- }),
+ t3_project_clone: McpToolAccess.writesEnvironment(
+ (input) =>
+ Effect.gen(function* () {
+ const repositories = yield* Repositories.SourceControlRepositoryService;
+ return yield* repositories.cloneRepository(input).pipe(
+ Effect.mapError(
+ (error) =>
+ new OrchestratorMcpFailure({
+ code: "orchestration_error",
+ message: error.detail,
+ }),
+ ),
+ );
+ }),
+ // An existing destination is never adopted.
+ { linkedCallers: "allowed" },
),
});
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index e27f32ef844..e627b466360 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -2539,6 +2539,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
worktreePath: command.worktreePath,
activeProviderThreadId: null,
pullRequests: [],
+ ...(command.linkOrigin === undefined ? {} : { linkOrigin: command.linkOrigin }),
lineage: {
parentThreadId: null,
relationshipToParent: null,
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index ed064325bfe..dff0bd31fa9 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -1657,6 +1657,9 @@ export function threadShellFromProjection(
...(projection.thread.historyOrigin === undefined
? {}
: { historyOrigin: projection.thread.historyOrigin }),
+ ...(projection.thread.linkOrigin === undefined
+ ? {}
+ : { linkOrigin: projection.thread.linkOrigin }),
latestRunId: latestRun?.id ?? null,
latestRunRequestedAt: latestRun?.requestedAt ?? null,
latestRunStartedAt: latestRun?.startedAt ?? null,
@@ -1933,6 +1936,9 @@ function shellFromState(input: {
...(input.state.thread.historyOrigin === undefined
? {}
: { historyOrigin: input.state.thread.historyOrigin }),
+ ...(input.state.thread.linkOrigin === undefined
+ ? {}
+ : { linkOrigin: input.state.thread.linkOrigin }),
latestRunId: input.state.latestRunId,
latestRunRequestedAt: input.state.latestRunRequestedAt,
latestRunStartedAt: input.state.latestRunStartedAt,
diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts
index 763ef25b436..faef398df10 100644
--- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts
+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts
@@ -9,6 +9,7 @@ import {
type ModelSelection,
type OrchestrationV2Actor,
type OrchestrationV2CreationSource,
+ type OrchestrationV2LinkOrigin,
type OrchestrationV2ProviderThreadNativeMetadata,
type OrchestrationV2ThreadProjection,
type ProviderDriverKind,
@@ -97,6 +98,8 @@ export interface ThreadLaunchInput {
};
readonly createdBy: OrchestrationV2Actor;
readonly creationSource: OrchestrationV2CreationSource;
+ /** The linked environment this launch is for, if one asked for it. */
+ readonly linkOrigin?: OrchestrationV2LinkOrigin;
}
type PreparationInput = Pick<
@@ -912,6 +915,7 @@ const make = Effect.gen(function* () {
...(input.importedNativeThread === undefined
? {}
: { importedNativeThread: input.importedNativeThread }),
+ ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),
createdBy: input.createdBy,
creationSource: input.creationSource,
});
diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts
index 0314008c636..2b75cd7633b 100644
--- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts
@@ -2,6 +2,7 @@ import { expect, it } from "@effect/vitest";
import {
CommandId,
MessageId,
+ type OrchestrationV2Command,
type OrchestrationV2Run,
type OrchestrationV2ProviderThread,
ProviderThreadId,
@@ -32,6 +33,38 @@ import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"
import * as ThreadManagementService from "./ThreadManagementService.ts";
import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
+it("stamps authoritative provenance on commands that create threads or messages", () => {
+ const command: OrchestrationV2Command = {
+ type: "thread.create",
+ createdBy: "agent",
+ creationSource: "mcp",
+ commandId: CommandId.make("command:thread-management:create"),
+ threadId: ThreadId.make("thread:thread-management:create"),
+ projectId: ProjectId.make("project:thread-management"),
+ title: "Thread management",
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("codex"),
+ model: "gpt-5-codex",
+ },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ // A client cannot claim a linked environment's origin for its own thread.
+ linkOrigin: { sessionId: "forged", label: "Somewhere else" },
+ };
+
+ const stamped = ThreadManagementService.withCreationProvenance(command, {
+ createdBy: "user",
+ creationSource: "web",
+ });
+ expect(stamped).toMatchObject({
+ createdBy: "user",
+ creationSource: "web",
+ });
+ expect(stamped).not.toHaveProperty("linkOrigin");
+});
+
const layerReceiptsTest = CommandReceiptStore.layer.pipe(
Layer.provide(SqlitePersistence.layerMemory),
);
diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts
index 9a80f8d2841..6f5656ce83b 100644
--- a/apps/server/src/orchestration-v2/ThreadManagementService.ts
+++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts
@@ -70,7 +70,11 @@ export function withCreationProvenance(
provenance: ThreadManagementProvenance,
): OrchestrationV2Command {
switch (command.type) {
- case "thread.create":
+ case "thread.create": {
+ // Only the server stamps a link's origin, so a client cannot set one.
+ const { linkOrigin: _linkOrigin, ...rest } = command;
+ return { ...rest, ...provenance };
+ }
case "message.dispatch":
case "thread.fork":
case "thread.merge_back":
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts
index eb6f9d1d3ea..e382beb55ed 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.ts
@@ -262,6 +262,8 @@ const layerThreadManagementProvided = ThreadManagementService.layerWithLegacyImp
);
export const layerProjectSetupScriptRunner = ProjectSetupScriptRunner.layer.pipe(
Layer.provide(layerProjectService),
+ // Whether a thread came from a linked environment, which skips setup.
+ Layer.provide(ProjectionStore.layer),
);
const layerManagedProjectFoldersProvided = ManagedProjectFolders.layer.pipe(
Layer.provide(layerProjectService),
diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts
index eec5e9940f3..6a4fb2937c0 100644
--- a/apps/server/src/peer/PeerForwarding.test.ts
+++ b/apps/server/src/peer/PeerForwarding.test.ts
@@ -5,6 +5,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import {
EnvironmentId,
type OrchestrationV2Run,
+ type OrchestrationV2ThreadShell,
type SourceControlCloneRepositoryInput,
ProjectId,
ProviderInstanceId,
@@ -63,20 +64,33 @@ const nothingSeen: Seen = {
stops: [],
};
+/** The box user's own thread, which no link started. */
+const usersThread = ThreadId.make("thread:box-users-own");
+
/**
- * B's threads: one `auto` thread in `boxProject`, whose run finishes on the
- * third wait. Every send and wait is recorded.
+ * B's threads: one `auto` thread in `boxProject` that the laptop's link
+ * started, whose run finishes on the third wait, and the box user's own.
+ * Every send and wait is recorded.
*/
-const boxThreads = (seen: Ref.Ref<Seen>) => {
- const shell = { ...liveThreadShell(boxThread, { runtimeMode: "auto" }), projectId: boxProject };
+const boxThreads = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) => {
+ const base = { ...liveThreadShell(boxThread, { runtimeMode: "auto" }), projectId: boxProject };
+ const linked = Ref.get(linkSession).pipe(
+ Effect.map((sessionId) => ({ ...base, linkOrigin: { sessionId, label: "T3 Code · Laptop" } })),
+ );
+ const users = { ...liveThreadShell(usersThread, { runtimeMode: "auto" }), projectId: boxProject };
const run = (status: OrchestrationV2Run["status"]) =>
({ id: boxRun, status }) as unknown as OrchestrationV2Run;
- const projection = { thread: shell, runs: [run("running")], runtimeRequests: [] } as never;
+ const shellOf = (threadId: ThreadId): Effect.Effect<OrchestrationV2ThreadShell | null> =>
+ threadId === boxThread ? linked : Effect.succeed(threadId === usersThread ? users : null);
+ const projectionOf = (threadId: ThreadId) =>
+ shellOf(threadId).pipe(
+ Effect.map((thread) => ({ thread, runs: [run("running")], runtimeRequests: [] }) as never),
+ );
return Layer.mock(ThreadManagement.ThreadManagementService)({
- getThreadShell: (threadId) => Effect.succeed(threadId === boxThread ? shell : null),
- getProjectThreadRecords: () => Effect.succeed(projection),
- getThreadRecords: () => Effect.succeed(projection),
- listProjectThreads: () => Effect.succeed([shell] as never),
+ getThreadShell: shellOf,
+ getProjectThreadRecords: (input) => projectionOf(input.threadId),
+ getThreadRecords: (threadId) => projectionOf(threadId),
+ listProjectThreads: () => linked.pipe(Effect.map((shell) => [shell] as never)),
sendToThread: (input) =>
Ref.update(seen, (current) => ({ ...current, sends: [...current.sends, input] })).pipe(
Effect.as({ run: run("running"), delivery: "started" } as never),
@@ -179,8 +193,12 @@ const boxProjects = (seen: Ref.Ref<Seen>) =>
}),
);
-/** The orchestrator and project toolkits on B's real `/mcp`, behind its real OAuth. */
-const serveBox = (seen: Ref.Ref<Seen>) =>
+/**
+ * The orchestrator and project toolkits on B's real `/mcp`, behind its real
+ * OAuth. `linkSession` is filled in once A links, so B's fixture thread reads
+ * as one that link started.
+ */
+const serveBox = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) =>
servePeer(
box,
Layer.mergeAll(
@@ -190,7 +208,7 @@ const serveBox = (seen: Ref.Ref<Seen>) =>
).pipe(
Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
Layer.provide(NodeCrypto.layer),
- Layer.provide(boxThreads(seen)),
+ Layer.provide(boxThreads(seen, linkSession)),
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
Layer.provide(boxLaunches(seen)),
Layer.provide(
@@ -259,12 +277,18 @@ const makeLaptop = Effect.gen(function* () {
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: (threadId) =>
Effect.succeed(
- liveThreadShell(
- threadId,
- threadId === ThreadId.make("thread:laptop-plan")
- ? { runtimeMode: "full-access", interactionMode: "plan" }
- : { runtimeMode: "full-access" },
- ),
+ threadId === ThreadId.make("thread:laptop-from-desk")
+ ? {
+ ...liveThreadShell(threadId, { runtimeMode: "full-access" }),
+ // Work another environment's link started on this laptop.
+ linkOrigin: { sessionId: "session:desk", label: "T3 Code · Desk" },
+ }
+ : liveThreadShell(
+ threadId,
+ threadId === ThreadId.make("thread:laptop-plan")
+ ? { runtimeMode: "full-access", interactionMode: "plan" }
+ : { runtimeMode: "full-access" },
+ ),
),
getProjectThreadRecords: ({ threadId }) =>
Effect.succeed({
@@ -324,9 +348,11 @@ it.effect("an agent here works on a linked environment's threads within its own
Effect.scoped(
Effect.gen(function* () {
const seen = yield* Ref.make<Seen>(nothingSeen);
- const b = yield* serveBox(seen);
+ const linkSession = yield* Ref.make("");
+ const b = yield* serveBox(seen, linkSession);
const a = yield* makeLaptop;
yield* linkTo(a.links, b, "auto");
+ yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
const listed = yield* a.call("thread:laptop-full", "t3_environment_links", {});
expect(listed.structuredContent).toMatchObject({
@@ -392,9 +418,11 @@ it.effect("keeps a forwarded wait short and its retries scoped to the caller", (
Effect.scoped(
Effect.gen(function* () {
const seen = yield* Ref.make<Seen>(nothingSeen);
- const b = yield* serveBox(seen);
+ const linkSession = yield* Ref.make("");
+ const b = yield* serveBox(seen, linkSession);
const a = yield* makeLaptop;
yield* linkTo(a.links, b, "auto");
+ yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
const waited = yield* a.call("thread:laptop-full", "t3_thread_wait", {
environmentId: box.environmentId,
@@ -442,9 +470,11 @@ it.effect("launches in a linked environment with the caller's modes, retry-safe"
Effect.scoped(
Effect.gen(function* () {
const seen = yield* Ref.make<Seen>(nothingSeen);
- const b = yield* serveBox(seen);
+ const linkSession = yield* Ref.make("");
+ const b = yield* serveBox(seen, linkSession);
const a = yield* makeLaptop;
yield* linkTo(a.links, b, "full-access");
+ yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
const codex = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" };
const launch = (caller: string, args: Record<string, unknown> = {}) =>
a.call(caller, "t3_thread_launch", {
@@ -493,7 +523,7 @@ it.effect("brings a repository to a linked environment, only through full access
Effect.scoped(
Effect.gen(function* () {
const seen = yield* Ref.make<Seen>(nothingSeen);
- const b = yield* serveBox(seen);
+ const b = yield* serveBox(seen, yield* Ref.make(""));
const a = yield* makeLaptop;
const clone = { repository: "pingdotgg/t3code", destinationPath: "/home/box/t3code" };
const register = { title: "t3code", workspaceRoot: "/home/box/t3code" };
@@ -543,9 +573,11 @@ it.effect("runs any tool that takes a linked environment there", () =>
Effect.scoped(
Effect.gen(function* () {
const seen = yield* Ref.make<Seen>(nothingSeen);
- const b = yield* serveBox(seen);
+ const linkSession = yield* Ref.make("");
+ const b = yield* serveBox(seen, linkSession);
const a = yield* makeLaptop;
yield* linkTo(a.links, b, "auto");
+ yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
const there = yield* a.call("thread:laptop-full", "t3_thread_configure", {
environmentId: box.environmentId,
@@ -576,9 +608,11 @@ it.effect("refuses what a linked environment cannot take before anything leaves"
Effect.scoped(
Effect.gen(function* () {
const seen = yield* Ref.make<Seen>(nothingSeen);
- const b = yield* serveBox(seen);
+ const linkSession = yield* Ref.make("");
+ const b = yield* serveBox(seen, linkSession);
const a = yield* makeLaptop;
yield* linkTo(a.links, b, "auto");
+ yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
yield* Ref.set(b.bearers, []);
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"
expect(failureOf(refused), name).toMatchObject({ code: "capability_denied" });
}
expect(yield* Ref.get(b.bearers)).toEqual([]);
+
+ // Work a desk's link started here never uses this laptop's links: the
+ // box would see the laptop, not the desk, so its fence could not hold.
+ for (const [name, args] of [
+ ["t3_thread_read", { environmentId: box.environmentId, threadId: boxThread }],
+ [
+ "t3_thread_send",
+ { environmentId: box.environmentId, threadId: boxThread, message: "From the desk." },
+ ],
+ [
+ "t3_thread_launch",
+ { environmentId: box.environmentId, projectId: boxProject, title: "x" },
+ ],
+ ] as const) {
+ const relayed = yield* a.call("thread:laptop-from-desk", name, args);
+ expect(failureOf(relayed), name).toMatchObject({ code: "capability_denied" });
+ }
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts
index 09963c76c64..05b9db6afa9 100644
--- a/apps/server/src/peer/PeerForwarding.ts
+++ b/apps/server/src/peer/PeerForwarding.ts
@@ -14,6 +14,7 @@ import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import type * as Tool from "effect/ai/Tool";
+import { assertNotLinked } from "../mcp/linkOrigin.ts";
import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
import { readCaller, unavailable } from "../mcp/threadAccess.ts";
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
@@ -74,12 +75,14 @@ const make = Effect.gen(function* () {
const threads = yield* ThreadManagement.ThreadManagementService;
/**
- * The caller's own limits here, which travel with every call it forwards.
- * The peer sees only the link's credential, so a credential that may not
- * control threads here is refused here.
+ * The caller's own limits, which travel with every forwarded call: the peer sees only the
+ * link's credential, so a caller that may not control threads here is refused here. Work a
+ * link started never uses this environment's links, since the peer would see this
+ * environment's session instead of that link, and its fence could not hold.
*/
const callerLimits = (scope: Scope) =>
readCaller().pipe(
+ Effect.tap((caller) => assertNotLinked(caller, "use this environment's links")),
Effect.map((caller) => caller.limits),
Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
Effect.provideService(ThreadManagement.ThreadManagementService, threads),
diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts
index 00452fec1f4..0e27c19b5d6 100644
--- a/apps/server/src/peer/PeerLinks.test.ts
+++ b/apps/server/src/peer/PeerLinks.test.ts
@@ -8,6 +8,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/sql/SqlClient";
import * as TestClock from "effect/testing/TestClock";
import { Tool, Toolkit } from "effect/ai";
import {
@@ -78,6 +79,7 @@ const makeA = (descriptor: ExecutionEnvironmentDescriptor) =>
Effect.map((context) => ({
links: Context.get(context, PeerLinks.PeerLinks),
peer: Context.get(context, PeerMcpClient.PeerMcpClient),
+ sql: Context.get(context, SqlClient.SqlClient),
})),
);
@@ -280,6 +282,35 @@ it.effect("tells the agent to link again once the peer revokes the link or it ex
expect(revoked.code).toBe("capability_denied");
expect(revoked.message).toContain("revoked there");
+ yield* a.links.link({
+ url: b.url,
+ pairingCode: (yield* b.auth.issuePairingCredential()).credential,
+ access: "auto",
+ });
+ // A link made with a peer that later answers without the fence, as
+ // one made before the fence or a peer moved back to such a version.
+ yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
+ yield* Ref.set(b.bearers, []);
+ const unfenced = yield* probe(a).pipe(Effect.flip);
+ expect(unfenced.code).toBe("capability_denied");
+ expect(unfenced.message).toContain("cannot keep a linked agent's limits");
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
+ yield* Ref.set(b.descriptor, box);
+
+ // A link stored before links were marked: its session there is not a
+ // link's, so the peer would not fence its work even though it can.
+ yield* a.sql`UPDATE peer_environment_links SET fenced = 0`;
+ const legacy = yield* probe(a).pipe(Effect.flip);
+ expect(legacy.code).toBe("capability_denied");
+ expect(legacy.message).toContain("Link it again");
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
+ yield* a.links.link({
+ url: b.url,
+ pairingCode: (yield* b.auth.issuePairingCredential()).credential,
+ access: "auto",
+ });
+ yield* probe(a);
+
yield* TestClock.adjust(Duration.days(31));
expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
yield* Ref.set(b.bearers, []);
@@ -305,6 +336,12 @@ it.effect(
.link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
.pipe(Effect.flip);
expect(older.reason).toBe("incompatible");
+ // Nor one whose link's work could reach the user's own threads there.
+ yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
+ const unfenced = yield* a.links
+ .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
+ .pipe(Effect.flip);
+ expect(unfenced.reason).toBe("incompatible");
// Plain http to a LAN address would carry the code and token in clear.
const lan = yield* a.links
diff --git a/apps/server/src/peer/PeerLinks.testkit.ts b/apps/server/src/peer/PeerLinks.testkit.ts
index 97af4ffde0e..da9dbc2a1b8 100644
--- a/apps/server/src/peer/PeerLinks.testkit.ts
+++ b/apps/server/src/peer/PeerLinks.testkit.ts
@@ -43,7 +43,12 @@ export const descriptorOf = (
label,
platform: { os: "linux", arch: "x64" },
serverVersion: "0.0.0-test",
- capabilities: { repositoryIdentity: true, mcpModeLimitHeader: true, ...capabilities },
+ capabilities: {
+ repositoryIdentity: true,
+ mcpModeLimitHeader: true,
+ linkFence: true,
+ ...capabilities,
+ },
});
/**
@@ -146,9 +151,9 @@ export type ServedPeer = Effect.Success<ReturnType<typeof servePeer>>;
export const layerLinkingEnvironment = (descriptor: ExecutionEnvironmentDescriptor) =>
PeerMcpClient.layer.pipe(
Layer.provideMerge(PeerLinks.layer),
+ Layer.provideMerge(Sqlite.layerMemory),
Layer.provide(
Layer.mergeAll(
- Sqlite.layerMemory,
ServerSecretStore.layer,
FetchHttpClient.layer,
Layer.succeed(ServerEnvironment.ServerEnvironment, {
diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts
index 4d438700d4a..958e368805d 100644
--- a/apps/server/src/peer/PeerLinks.ts
+++ b/apps/server/src/peer/PeerLinks.ts
@@ -4,6 +4,8 @@ import {
AuthMcpTokenError,
EnvironmentHttpApi,
EnvironmentId,
+ type ExecutionEnvironmentCapabilities,
+ MCP_PEER_LINK_SOFTWARE_ID,
type PeerLink,
type PeerLinkCreateInput,
PeerLinkError,
@@ -85,6 +87,7 @@ interface PeerLinkRow {
readonly expires_at: string;
readonly last_reached_at: string | null;
readonly last_error: string | null;
+ readonly fenced: number;
}
const decodeUrls = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
@@ -136,6 +139,10 @@ const peerOrigin = (url: string) => {
return Effect.succeed(parsed.origin);
};
+/** Whether a peer holds a linked agent to its limits and keeps its work within its link. */
+const linkLimitsHold = (peer: { readonly capabilities: ExecutionEnvironmentCapabilities }) =>
+ peer.capabilities.mcpModeLimitHeader === true && peer.capabilities.linkFence === true;
+
const make = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const secrets = yield* ServerSecretStore.ServerSecretStore;
@@ -200,7 +207,13 @@ const make = Effect.gen(function* () {
// Only the peer's own refusals are rejections. A dropped connection or
// an answer this version cannot read is classified below.
const registered = yield* client.mcpOAuth
- .register({ payload: { client_name: clientName, redirect_uris: [LINK_REDIRECT_URI] } })
+ .register({
+ payload: {
+ client_name: clientName,
+ redirect_uris: [LINK_REDIRECT_URI],
+ software_id: MCP_PEER_LINK_SOFTWARE_ID,
+ },
+ })
.pipe(
// A plain Schema.Error has no tag to catch by.
Effect.catchIf(Schema.is(AuthMcpRegistrationError), (error) =>
@@ -322,7 +335,7 @@ const make = Effect.gen(function* () {
message: "That address is this environment.",
});
}
- if (peer.capabilities.mcpModeLimitHeader !== true) {
+ if (!linkLimitsHold(peer)) {
return yield* new PeerLinkError({
reason: "incompatible",
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* () {
yield* sql`
INSERT INTO peer_environment_links (
environment_id, secret_name, label, urls_json, access, linked_at, expires_at,
- last_reached_at, last_error
+ last_reached_at, last_error, fenced
) VALUES (
${linked.environmentId}, ${secretName}, ${linked.label}, ${urlsJson}, ${linked.access},
${DateTime.formatIso(linked.linkedAt)}, ${DateTime.formatIso(linked.expiresAt)},
- ${DateTime.formatIso(now)}, NULL
+ ${DateTime.formatIso(now)}, NULL, 1
)
ON CONFLICT (environment_id) DO UPDATE SET
secret_name = excluded.secret_name,
+ fenced = excluded.fenced,
label = excluded.label,
urls_json = excluded.urls_json,
access = excluded.access,
@@ -439,6 +453,14 @@ const make = Effect.gen(function* () {
message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`,
});
}
+ // Its token was issued before links were marked as links, so the peer
+ // never fences the work it carries, whatever version it runs now.
+ if (row.value.fenced !== 1) {
+ return yield* new PeerLinkError({
+ reason: "incompatible",
+ message: `The link to ${link.label} was made by an older T3 Code. Link it again with a new pairing code from ${link.label}.`,
+ });
+ }
const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage));
if (Option.isNone(stored)) {
return yield* new PeerLinkError({
@@ -448,11 +470,14 @@ const make = Effect.gen(function* () {
}
// The token goes only to an address that proves it is this peer, so a
// reused LAN address or a moved hostname never receives it.
+ let fenced = true;
const url = yield* Effect.findFirst(link.urls, (candidate) =>
describe(candidate).pipe(
- Effect.map(
- (found) => Option.isSome(found) && found.value.environmentId === environmentId,
- ),
+ Effect.map((found) => {
+ if (Option.isNone(found) || found.value.environmentId !== environmentId) return false;
+ fenced = linkLimitsHold(found.value);
+ return true;
+ }),
),
);
if (Option.isNone(url)) {
@@ -461,6 +486,14 @@ const make = Effect.gen(function* () {
message: `${link.label} did not answer at ${link.urls.join(", ")}.`,
});
}
+ // A link made before the peer had to fence linked work, or a peer moved
+ // back to such a version, would carry work past those limits.
+ if (!fenced) {
+ return yield* new PeerLinkError({
+ reason: "incompatible",
+ message: `${link.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
+ });
+ }
return { link, url: url.value, token: new TextDecoder().decode(stored.value) };
},
);
diff --git a/apps/server/src/peer/PeerMcpClient.ts b/apps/server/src/peer/PeerMcpClient.ts
index 710b7c26c6e..e85e39aebfd 100644
--- a/apps/server/src/peer/PeerMcpClient.ts
+++ b/apps/server/src/peer/PeerMcpClient.ts
@@ -70,7 +70,7 @@ const fromLinkError = (error: PeerLinkError) =>
code:
error.reason === "unknown_link"
? "invalid_request"
- : error.reason === "expired"
+ : error.reason === "expired" || error.reason === "incompatible"
? "capability_denied"
: "orchestration_error",
message: error.message,
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index 9b352d271b2..86a795612d4 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -73,6 +73,7 @@ import Migration0067 from "./Migrations/067_WebhookDedupe.ts";
import Migration0068 from "./Migrations/068_ShellStopRequestIndex.ts";
import Migration0069 from "./Migrations/069_ThreadMessageSearch.ts";
import Migration0070 from "./Migrations/070_PeerLinks.ts";
+import Migration0071 from "./Migrations/071_PeerLinkFence.ts";
const migrationEntries = [
[1, "OrchestrationEvents", Migration0001],
@@ -146,6 +147,7 @@ const migrationEntries = [
[68, "ShellStopRequestIndex", Migration0068],
[69, "ThreadMessageSearch", Migration0069],
[70, "PeerLinks", Migration0070],
+ [71, "PeerLinkFence", Migration0071],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
diff --git a/apps/server/src/persistence/Migrations/071_PeerLinkFence.ts b/apps/server/src/persistence/Migrations/071_PeerLinkFence.ts
new file mode 100644
index 00000000000..8b2ca3039d1
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/071_PeerLinkFence.ts
@@ -0,0 +1,12 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ // Whether the link's session was issued as a link, which the peer fences.
+ // Links stored before it are not, and must be made again.
+ yield* sql`
+ ALTER TABLE peer_environment_links ADD COLUMN fenced INTEGER NOT NULL DEFAULT 0
+ `;
+});
diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
index 3e699b30dfe..802f77beb34 100644
--- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
@@ -50,6 +50,7 @@ describe("V2 preview upgrade", () => {
[68, "ShellStopRequestIndex"],
[69, "ThreadMessageSearch"],
[70, "PeerLinks"],
+ [71, "PeerLinkFence"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -143,6 +144,7 @@ describe("V2 preview upgrade", () => {
[68, "ShellStopRequestIndex"],
[69, "ThreadMessageSearch"],
[70, "PeerLinks"],
+ [71, "PeerLinkFence"],
]);
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
);
diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts
index c295a06ac39..29a15a6f071 100644
--- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts
+++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts
@@ -11,6 +11,7 @@ import { TestClock } from "effect/testing";
import * as ServerSettings from "../serverSettings.ts";
import * as TerminalManager from "../terminal/Manager.ts";
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
import * as ProjectService from "./ProjectService.ts";
import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
@@ -58,6 +59,9 @@ const makeHarness = Effect.fn(function* (options: {
Layer.mergeAll(
terminals,
Layer.mock(ProjectService.ProjectService)({}),
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
+ getThreadShell: () => Effect.succeed(null),
+ }),
ServerSettings.layerTest(),
NodeCrypto.layer,
),
diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts
index 612bb773d07..075e5843754 100644
--- a/apps/server/src/project/ProjectSetupScriptRunner.ts
+++ b/apps/server/src/project/ProjectSetupScriptRunner.ts
@@ -1,4 +1,4 @@
-import { ProjectId, type ProjectScript } from "@t3tools/contracts";
+import { linkOriginIsFenced, ProjectId, type ProjectScript, ThreadId } from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import {
projectScriptRuntimeEnv,
@@ -17,6 +17,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as TerminalManager from "../terminal/Manager.ts";
import * as ProjectService from "./ProjectService.ts";
@@ -46,8 +47,18 @@ export interface ProjectSetupScriptOutputLine {
readonly line: string;
}
+/**
+ * A thread a link below full access started does not run this project's setup
+ * script: the script is the user's own code, and such a link only grants T3's
+ * tools (see `mcp/linkOrigin.ts`).
+ */
+export interface ProjectSetupScriptRunnerResultSkippedForLink {
+ readonly status: "skipped-for-link";
+}
+
export type ProjectSetupScriptRunnerResult =
| ProjectSetupScriptRunnerResultNoScript
+ | ProjectSetupScriptRunnerResultSkippedForLink
| ProjectSetupScriptRunnerResultStarted;
export interface ProjectSetupScriptRunnerInput {
@@ -74,7 +85,7 @@ export class ProjectSetupScriptOperationError extends Schema.TaggedError<Project
projectId: Schema.optional(Schema.String),
projectCwd: Schema.optional(Schema.String),
worktreePath: Schema.String,
- operation: Schema.Literals(["resolveProject", "readSettings", "openTerminal"]),
+ operation: Schema.Literals(["readThread", "resolveProject", "readSettings", "openTerminal"]),
cause: Schema.Defect(),
},
) {
@@ -181,6 +192,7 @@ function wrapCommandForCompletion(
/** @public */
export const make = Effect.gen(function* () {
const projects = yield* ProjectService.ProjectService;
+ const threads = yield* ProjectionStore.ProjectionStoreV2;
const terminalManager = yield* TerminalManager.TerminalManager;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const crypto = yield* Crypto.Crypto;
@@ -345,6 +357,19 @@ export const make = Effect.gen(function* () {
...(input.projectId === undefined ? {} : { projectId: input.projectId }),
...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
};
+ // A thread whose origin cannot be read might be a link's: run nothing.
+ const thread = yield* threads.getThreadShell(ThreadId.make(input.threadId)).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ProjectSetupScriptOperationError({
+ ...errorContext,
+ operation: "readThread",
+ cause,
+ }),
+ ),
+ );
+ if (thread?.linkOrigin !== undefined && linkOriginIsFenced(thread.linkOrigin))
+ return { status: "skipped-for-link" } as const;
const suppliedProject = input.project;
const projectById =
suppliedProject ??
diff --git a/docs/internals/remote.md b/docs/internals/remote.md
index 1d2510b7d94..5bc642e8d14 100644
--- a/docs/internals/remote.md
+++ b/docs/internals/remote.md
@@ -97,8 +97,31 @@ Unlinking on the linking side only forgets the token.
receiving `/mcp` sends nothing while a wait is open and T3 Connect's edge
drops idle requests after about 100 s.
+**Work a link paired below full access starts stays within that link.** The
+receiving environment knows a session is a peer link because the linking side
+registers its OAuth client with the `t3code-peer-link` software id, and the
+marker is signed into the session. Threads that session launches carry it, with
+the access it was paired with, as an immutable `linkOrigin`, and so do the
+subagents, forks and `create_threads` they derive. The rules live in
+[`mcp/linkOrigin.ts`](../../apps/server/src/mcp/linkOrigin.ts) and run in the
+shared access declarations, not tool by tool:
+
+- linked work may change only threads with the same origin, not the user's own
+ threads and not another link's;
+- it cannot change projects, settings or scheduled tasks, nor use the receiving
+ environment's own links;
+- its project setup scripts are skipped
+ ([`ProjectSetupScriptRunner`](../../apps/server/src/project/ProjectSetupScriptRunner.ts)
+ checks every path that runs them).
+
+Reads are not fenced, and a client's own `thread.create` can never carry
+`linkOrigin`.
+
The link is routing, not isolation: an agent the link starts runs as the
-receiving environment's user, inside the limits above.
+receiving environment's user. **A full-access link is therefore not fenced**:
+its agents can already do anything that user can, so the fence would only stop
+T3's own tools. Its work still carries `linkOrigin`, so clients show where it
+came from. A stamp without the access, from before it was recorded, is fenced.
## Hosted web is a client
diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts
index 779740fd08a..fbdf2c3a34e 100644
--- a/packages/contracts/src/auth.ts
+++ b/packages/contracts/src/auth.ts
@@ -431,8 +431,16 @@ export const AuthMcpAuthorizationServerMetadata = Schema.Struct({
});
export type AuthMcpAuthorizationServerMetadata = typeof AuthMcpAuthorizationServerMetadata.Type;
+/**
+ * The `software_id` another T3 Code environment registers with when it links
+ * to this one. Its session is then a peer link: the work it starts here stays
+ * within that link. Claiming it only ever adds limits.
+ */
+export const MCP_PEER_LINK_SOFTWARE_ID = "t3code-peer-link";
+
export const AuthMcpClientRegistration = Schema.Struct({
client_name: Schema.optionalKey(Schema.String),
+ software_id: Schema.optionalKey(Schema.String),
redirect_uris: Schema.optionalKey(Schema.Array(Schema.String)),
token_endpoint_auth_method: Schema.optionalKey(Schema.String),
});
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index e0986dbb340..7f3f5ee18c2 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -142,6 +142,10 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
a linked environment's calls keep its agent's limits. Another environment
links to this one only when it is set. */
mcpModeLimitHeader: Schema.optionalKey(Schema.Boolean),
+ /** Work a linked environment starts here stays within its link
+ (`linkOrigin`). Another environment links to this one only when it is
+ set, since without it that work could change the user's own threads. */
+ linkFence: Schema.optionalKey(Schema.Boolean),
});
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts
index f4e83039722..8ce02f8b650 100644
--- a/packages/contracts/src/orchestrationV2.ts
+++ b/packages/contracts/src/orchestrationV2.ts
@@ -40,6 +40,7 @@ import {
TrimmedNonEmptyString,
TurnItemId,
} from "./baseSchemas.ts";
+import { AuthMcpClientAccess } from "./auth.ts";
import { ChatAttachment } from "./chatAttachment.ts";
import { ThreadGuestShare } from "./guestShare.ts";
import {
@@ -103,6 +104,28 @@ const OrchestrationV2CreationFields = {
creationSource: OrchestrationV2CreationSource,
} as const;
+/**
+ * The linked environment whose agent started this work here: the MCP client
+ * session it signed in with, that session's label, and the access it was
+ * paired with. Set when the thread is created and never changed; work derived
+ * from it carries the same origin.
+ */
+export const OrchestrationV2LinkOrigin = Schema.Struct({
+ sessionId: TrimmedNonEmptyString,
+ label: Schema.String,
+ access: Schema.optional(AuthMcpClientAccess),
+});
+export type OrchestrationV2LinkOrigin = typeof OrchestrationV2LinkOrigin.Type;
+
+/**
+ * Work from a link paired below full access may change only work from the same
+ * link. A full-access link's agents already run as this environment's user,
+ * so fencing T3's own tools would stop nothing they could not do anyway. An
+ * origin stamped before access was recorded stays fenced.
+ */
+export const linkOriginIsFenced = (origin: OrchestrationV2LinkOrigin) =>
+ origin.access !== "full-access";
+
export const OrchestrationV2NativeRefStrength = Schema.Literals(["strong", "weak", "none"]);
export type OrchestrationV2NativeRefStrength = typeof OrchestrationV2NativeRefStrength.Type;
@@ -414,6 +437,7 @@ export const OrchestrationV2AppThread = Schema.Struct({
branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
activeProviderThreadId: Schema.NullOr(ProviderThreadId),
historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),
+ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),
lineage: OrchestrationV2AppThreadLineage,
forkedFrom: Schema.NullOr(
Schema.Union([
@@ -1942,6 +1966,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
forkedFrom: Schema.NullOr(OrchestrationV2AppThread.fields.forkedFrom),
activeProviderThreadId: Schema.NullOr(ProviderThreadId),
historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),
+ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),
latestRunId: Schema.NullOr(RunId),
latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
@@ -2774,6 +2799,8 @@ export const OrchestrationV2Command = Schema.Union([
interactionMode: ProviderInteractionMode,
branch: Schema.NullOr(TrimmedNonEmptyString),
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
+ /** Only the server sets this; a client's thread.create never carries one. */
+ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),
importedNativeThread: Schema.optional(
Schema.Struct({
ref: Schema.Struct({