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