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