Open History to see the last commit
1import * as DocumentText from "../provider/DocumentText.ts";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, it } from "@effect/vitest";
5import {
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";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import { McpSchema, McpServer } from "effect/ai";
20
21import * as ServerConfig from "../config.ts";
22import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
23import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
24import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
25import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
26import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
27import { makeSubagentChildThread } from "@t3tools/provider-core/server/subagentProjection";
28import * as ThreadForkService from "../orchestration-v2/ThreadForkService.ts";
29import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
30import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
31import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
32import * as SqlitePersistence from "../persistence/Sqlite.ts";
33import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
34import * as ProjectService from "../project/ProjectService.ts";
35import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
36import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
37import * as ServerSettings from "../serverSettings.ts";
38import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
39import * as SecretRequests from "../secrets/SecretRequests.ts";
40import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
41import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
42import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
43import * as McpHttpServer from "./McpHttpServer.ts";
44import * as McpInvocationContext from "./McpInvocationContext.ts";
45import * as PeerForwarding from "../peer/PeerForwarding.ts";
46import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
47import * as PeerLinkRequests from "../peer/PeerLinkRequests.ts";
48import * as PeerLinks from "../peer/PeerLinks.ts";
49
50// A linked environment's session drives this one's real orchestrator through
51// its real T3 tools. What the link starts carries its origin, and the link
52// changes only that.
53
54const instanceId = ProviderInstanceId.make("codex");
55const projectId = ProjectId.make("project:link-origin");
56const adapter = {
57 instanceId,
58 driver: ProviderDriverKind.make("codex"),
59 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
60 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
61 openSession: () => Effect.die("No provider process needed for these commands"),
62} as ProviderAdapter.ProviderAdapterV2["Service"];
63const layerDatabase = SqlitePersistence.layerMemory;
64const layerOrchestrator = Layer.mergeAll(
65 layerDatabase,
66 ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
67 ProviderReplayHarness.layerWithRegistry(
68 { name: "link-origin" },
69 ProviderAdapterRegistry.layerFromAdapters([adapter]),
70 { databaseLayer: layerDatabase, runEffectWorker: false },
71 ),
72);
73const layerOrchestration = ThreadManagement.layer.pipe(
74 Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
75 Layer.provideMerge(Layer.merge(layerOrchestrator, ServerSettings.layerTest())),
76);
77
78/** Launches dispatch the real thread.create, and nothing more: no workspace, no run. */
79const layerLaunches = Layer.effect(
80 ThreadLaunch.ThreadLaunchService,
81 Effect.gen(function* () {
82 const threads = yield* ThreadManagement.ThreadManagementService;
83 return ThreadLaunch.ThreadLaunchService.of({
84 launch: (input: ThreadLaunch.ThreadLaunchInput) =>
85 threads
86 .dispatch({
87 type: "thread.create",
88 commandId: input.commandId,
89 threadId: input.threadId!,
90 projectId: input.projectId,
91 title: input.title,
92 modelSelection: input.modelSelection,
93 runtimeMode: input.runtimeMode,
94 interactionMode: input.interactionMode,
95 branch: null,
96 worktreePath: null,
97 ...(input.linkOrigin === undefined ? {} : { linkOrigin: input.linkOrigin }),
98 ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }),
99 createdBy: input.createdBy,
100 creationSource: input.creationSource,
101 })
102 .pipe(
103 Effect.flatMap(() => threads.getThreadProjection(input.threadId!)),
104 Effect.map((projection) => ({
105 threadId: input.threadId!,
106 projection,
107 resumed: false,
108 })),
109 Effect.orDie,
110 ),
111 } as unknown as ThreadLaunch.ThreadLaunchService["Service"]);
112 }),
113);
114
115const layerTools = Layer.mergeAll(
116 McpHttpServer.layerOrchestratorToolkit,
117 McpHttpServer.layerThreadToolkit,
118 McpHttpServer.layerProjectRegistration,
119).pipe(
120 Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
121 Layer.provideMerge(McpServer.McpServer.layer),
122 Layer.provide(layerLaunches),
123 Layer.provide(NodeCrypto.layer),
124 Layer.provide(
125 Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
126 ),
127 Layer.provide(
128 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
129 list: () => Effect.succeed([]),
130 }),
131 ),
132 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
133 Layer.provide(
134 Layer.mock(ProjectService.ProjectService)({
135 getById: () => Effect.succeedNone,
136 create: (input) =>
137 Effect.succeed({
138 id: input.projectId,
139 title: input.title,
140 workspaceRoot: input.workspaceRoot,
141 defaultModelSelection: null,
142 scripts: [],
143 createdAt: "2026-10-18T00:00:00.000Z",
144 updatedAt: "2026-10-18T00:00:00.000Z",
145 deletedAt: null,
146 }),
147 update: (input) =>
148 Effect.succeed({
149 id: input.projectId,
150 title: input.title ?? "Untitled",
151 workspaceRoot: "/p/t3code",
152 defaultModelSelection: null,
153 scripts: [],
154 createdAt: "2026-10-18T00:00:00.000Z",
155 updatedAt: "2026-10-18T00:00:00.000Z",
156 deletedAt: null,
157 }),
158 }),
159 ),
160 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
161 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
162 Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
163 Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
164 Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
165 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
166 Layer.provide(
167 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/p" }),
168 ),
169 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
170 Layer.provide(
171 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
172 cloneRepository: (input) =>
173 Effect.succeed({
174 cwd: input.destinationPath,
175 remoteUrl: "https://github.com/pingdotgg/t3code.git",
176 repository: null,
177 }),
178 }),
179 ),
180 Layer.provide(
181 ServerConfig.layerTest(process.cwd(), { prefix: "t3-link-origin-" }).pipe(
182 Layer.provide(NodeServices.layer),
183 ),
184 ),
185 Layer.provide(NodeServices.layer),
186);
187
188const mcpClient = McpSchema.McpServerClient.of({
189 clientId: 1,
190 protocolVersion: "2025-06-18",
191 clientCapabilities: {},
192 clientInfo: { name: "link-origin", version: "1" },
193 initializePayload: {
194 protocolVersion: "2025-06-18",
195 capabilities: {},
196 clientInfo: { name: "link-origin", version: "1" },
197 },
198 getClient: Effect.die("unused"),
199});
200
201const clientScope = (
202 sessionId: string,
203 linked: boolean,
204 access: McpInvocationContext.McpClientCaller["access"],
205): McpInvocationContext.McpInvocationScope => ({
206 environmentId: EnvironmentId.make("environment:box"),
207 requestNamespace: `client:${sessionId}`,
208 thread: undefined,
209 client: { sessionId, label: `T3 Code · ${sessionId}`, access, linked },
210 capabilities: new Set(["orchestration", "worktree", "pull-requests"]),
211 issuedAt: 0,
212});
213const laptop = clientScope("laptop", true, "auto");
214const desk = clientScope("desk", true, "auto");
215const trusted = clientScope("trusted", true, "full-access");
216const claudeCode = clientScope("claude-code", false, "full-access");
217
218const call = (
219 scope: McpInvocationContext.McpInvocationScope,
220 name: string,
221 args: Record<string, unknown>,
222) =>
223 McpServer.McpServer.pipe(
224 Effect.flatMap((server) => server.callTool({ name, arguments: args })),
225 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
226 Effect.provideService(McpSchema.McpServerClient, mcpClient),
227 );
228
229const failureCode = (result: McpSchema.CallToolResult) => {
230 const text = result.content[0];
231 return result.isError === true && text?.type === "text"
232 ? (JSON.parse(text.text) as { code: string }).code
233 : undefined;
234};
235
236const launch = (
237 scope: McpInvocationContext.McpInvocationScope,
238 title: string,
239 extra: Record<string, unknown> = {},
240) =>
241 call(scope, "t3_thread_launch", {
242 projectId,
243 title,
244 modelSelection: { instanceId, model: "gpt-5" },
245 ...extra,
246 }).pipe(
247 Effect.map((result) => {
248 assert.equal(result.isError, false, JSON.stringify(result.content));
249 return (result.structuredContent as { threadId: ThreadId }).threadId;
250 }),
251 );
252
253const usersOwnThread = Effect.gen(function* () {
254 const orchestrator = yield* Orchestrator.OrchestratorV2;
255 const threadId = ThreadId.make("thread:users-own");
256 yield* orchestrator.dispatch({
257 type: "thread.create",
258 commandId: CommandId.make("create:users-own"),
259 threadId,
260 projectId,
261 title: "The user's own",
262 modelSelection: { instanceId, model: "gpt-5" },
263 // Within an `auto` link's modes, so only the fence decides.
264 runtimeMode: "auto",
265 interactionMode: "default",
266 branch: null,
267 worktreePath: null,
268 createdBy: "user",
269 creationSource: "web",
270 });
271 return threadId;
272});
273
274it.layer(Layer.provideMerge(layerTools, layerOrchestration))("work a link starts", (it) => {
275 it.effect("is stamped, and so is the work it derives", () =>
276 Effect.gen(function* () {
277 const projections = yield* ProjectionStore.ProjectionStoreV2;
278 const launched = yield* launch(laptop, "Started from the laptop");
279 const shell = yield* projections.getThreadShell(launched);
280 assert.deepEqual(shell?.linkOrigin, {
281 sessionId: "laptop",
282 label: "T3 Code · laptop",
283 access: "auto",
284 });
285
286 // A subagent of it and a fork of it are built from its thread, origin included.
287 const thread = (yield* ThreadManagement.ThreadManagementService.pipe(
288 Effect.flatMap((threads) => threads.getThreadProjection(launched)),
289 )).thread;
290 const child = makeSubagentChildThread({
291 parentThread: thread,
292 childThreadId: ThreadId.make("thread:child"),
293 parentNodeId: NodeId.make("node:child"),
294 activeProviderThreadId: null,
295 providerInstanceId: instanceId,
296 modelSelection: { instanceId, model: "gpt-5" },
297 title: "Child",
298 now: thread.createdAt,
299 createdBy: "agent",
300 creationSource: "mcp",
301 });
302 assert.deepEqual(child.linkOrigin, shell?.linkOrigin);
303 const fork = yield* ThreadForkService.ThreadForkServiceV2.pipe(
304 Effect.flatMap((forks) =>
305 forks.plan({
306 sourceProjection: { thread },
307 sourceRun: { id: RunId.make("run:source"), status: "completed" } as OrchestrationV2Run,
308 sourceProviderThread: undefined,
309 canonicalSourcePoint: { threadId: launched },
310 transferId: ContextTransferId.make("transfer:fork"),
311 targetThreadId: ThreadId.make("thread:fork"),
312 createdBy: "agent",
313 creationSource: "mcp",
314 createdAt: thread.createdAt,
315 }),
316 ),
317 Effect.provide(ThreadForkService.layer),
318 );
319 assert.deepEqual(fork.targetThread.linkOrigin, shell?.linkOrigin);
320
321 // An ordinary outside agent's launch is not a link's.
322 const plain = yield* launch(claudeCode, "Started by Claude Code");
323 assert.equal((yield* projections.getThreadShell(plain))?.linkOrigin, undefined);
324
325 // A link's delegated task names its parent there; only a link's launch may.
326 const delegatedFrom = {
327 environmentId: "environment-laptop",
328 threadId: "thread:laptop-parent",
329 title: "Laptop parent",
330 };
331 const task = yield* launch(laptop, "Delegated from the laptop", { delegatedFrom });
332 assert.deepEqual((yield* projections.getThreadShell(task))?.delegatedFrom, delegatedFrom);
333 const claimed = yield* launch(claudeCode, "Claims a parent", { delegatedFrom });
334 assert.equal((yield* projections.getThreadShell(claimed))?.delegatedFrom, undefined);
335 }),
336 );
337
338 it.effect("changes only that link's threads below full access", () =>
339 Effect.gen(function* () {
340 const projections = yield* ProjectionStore.ProjectionStoreV2;
341 const users = yield* usersOwnThread;
342 const ownLaunch = yield* launch(laptop, "The laptop's");
343 const rename = (scope: McpInvocationContext.McpInvocationScope, threadId: ThreadId) =>
344 call(scope, "t3_thread_update", {
345 threadId,
346 action: "rename",
347 title: `Renamed by ${scope.client!.sessionId}`,
348 });
349
350 // The link may change what it started.
351 assert.equal((yield* rename(laptop, ownLaunch)).isError, false);
352 assert.equal((yield* projections.getThreadShell(ownLaunch))?.title, "Renamed by laptop");
353 // Not the user's own thread, nor another link's.
354 assert.equal(failureCode(yield* rename(laptop, users)), "capability_denied");
355 assert.equal(failureCode(yield* rename(desk, ownLaunch)), "capability_denied");
356 assert.equal((yield* projections.getThreadShell(users))?.title, "The user's own");
357 // An ordinary outside agent is not fenced.
358 assert.equal((yield* rename(claudeCode, users)).isError, false);
359 // Naming this environment's own id is still this environment's thread.
360 for (const [name, args] of [
361 ["t3_thread_send", { message: "From the laptop." }],
362 ["t3_thread_interrupt", {}],
363 ] as const) {
364 const result = yield* call(laptop, name, {
365 ...args,
366 environmentId: laptop.environmentId,
367 threadId: users,
368 });
369 assert.equal(failureCode(result), "capability_denied", name);
370 }
371
372 // Nor scheduled tasks, which belong to no thread.
373 assert.equal(
374 failureCode(yield* call(laptop, "delete_scheduled_task", { scheduledTaskId: "any" })),
375 "capability_denied",
376 );
377
378 // Reads are not fenced.
379 const read = yield* call(laptop, "t3_thread_read", { threadId: users });
380 assert.equal(read.isError, false);
381 }),
382 );
383
384 it.effect("is not fenced when the link has full access, but still says where it came from", () =>
385 Effect.gen(function* () {
386 const projections = yield* ProjectionStore.ProjectionStoreV2;
387 const users = yield* usersOwnThread;
388 const launched = yield* launch(trusted, "Started from the desk");
389 assert.deepEqual((yield* projections.getThreadShell(launched))?.linkOrigin, {
390 sessionId: "trusted",
391 label: "T3 Code · trusted",
392 access: "full-access",
393 });
394
395 const renamed = yield* call(trusted, "t3_thread_update", {
396 threadId: users,
397 action: "rename",
398 title: "Renamed from the desk",
399 });
400 assert.equal(renamed.isError, false, JSON.stringify(renamed.content));
401 for (const [name, args] of [
402 ["t3_project_update", { projectId, title: "The desk's now" }],
403 ["t3_project_create", { title: "t3code", workspaceRoot: "/p/t3code" }],
404 ] as const) {
405 const changed = yield* call(trusted, name, args);
406 assert.equal(changed.isError, false, `${name}: ${JSON.stringify(changed.content)}`);
407 }
408 }),
409 );
410});