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