Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EnvironmentId,
5 OrchestratorMcpFailure,
6 ProjectId,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Ref from "effect/Ref";
14import * as Schema from "effect/Schema";
15import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
16
17import * as SqlitePersistence from "../persistence/Sqlite.ts";
18import { DispatchModeLimit } from "../orchestration-v2/DispatchModeLimit.ts";
19import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
20import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
21import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
22import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
23import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
24import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
25import * as McpHttpServer from "./McpHttpServer.ts";
26import * as McpInvocationContext from "./McpInvocationContext.ts";
27import * as McpToolAccess from "./McpToolAccess.ts";
28import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
29
30// A Supervised outside agent renames a thread through a `writesThreads` tool.
31// The thread's user raises it to full access after the tool's check but
32// before its write: the race the orchestrator closes under the thread's lock.
33
34const instanceId = ProviderInstanceId.make("codex");
35const adapter = {
36 instanceId,
37 driver: ProviderDriverKind.make("codex"),
38 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
39 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
40 openSession: () => Effect.die("No provider process needed for metadata commands"),
41} as ProviderAdapter.ProviderAdapterV2["Service"];
42const layerDatabase = SqlitePersistence.layerMemory;
43const layerOrchestrator = Layer.mergeAll(
44 layerDatabase,
45 ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
46 ProviderReplayHarness.layerWithRegistry(
47 { name: "mcp-mode-race" },
48 ProviderAdapterRegistry.layerFromAdapters([adapter]),
49 { databaseLayer: layerDatabase, runEffectWorker: false },
50 ),
51);
52
53const RenameTool = Tool.make("rename", {
54 parameters: Schema.Struct({ threadId: ThreadId }),
55 success: Schema.Struct({ renamed: Schema.Boolean }),
56 failure: OrchestratorMcpFailure,
57 failureMode: "return",
58 dependencies: [
59 McpInvocationContext.McpInvocationContext,
60 ThreadManagement.ThreadManagementService,
61 ],
62});
63const RenameToolkit = Toolkit.make(RenameTool);
64
65const supervisedClient: McpInvocationContext.McpInvocationScope = {
66 environmentId: EnvironmentId.make("environment"),
67 requestNamespace: "client:race",
68 thread: undefined,
69 client: { sessionId: "race", label: "Claude Code", access: "approval-required" },
70 capabilities: new Set(["orchestration"]),
71 issuedAt: 0,
72};
73
74const mcpClient = McpSchema.McpServerClient.of({
75 clientId: 1,
76 protocolVersion: "2025-06-18",
77 clientCapabilities: {},
78 clientInfo: { name: "mcp-race", version: "1" },
79 initializePayload: {
80 protocolVersion: "2025-06-18",
81 capabilities: {},
82 clientInfo: { name: "mcp-race", version: "1" },
83 },
84 getClient: Effect.die("unused"),
85});
86
87const decodeOutcome = Schema.decodeUnknownEffect(
88 Schema.fromJsonString(
89 Schema.Union([
90 Schema.Struct({ renamed: Schema.Boolean }),
91 Schema.Struct({ code: Schema.String }),
92 ]),
93 ),
94);
95
96/** Renames `threadId` as the Supervised client; the user may raise it in between. */
97const renameRacingTheUser = (threadId: ThreadId, userRaises: boolean) =>
98 Effect.gen(function* () {
99 const orchestrator = yield* Orchestrator.OrchestratorV2;
100 const threads = yield* ThreadManagement.ThreadManagementService;
101 const raised = yield* Ref.make(false);
102 const handlers = McpToolAccess.toLayer(RenameToolkit, {
103 rename: McpToolAccess.writesThreads(
104 (input) => [input.threadId],
105 (input) =>
106 Effect.gen(function* () {
107 // The tool's own check has passed; the user acts before the write.
108 if (userRaises) {
109 // The user's own command carries no limit, so it lands.
110 yield* orchestrator
111 .dispatch({
112 type: "thread.runtime-mode.set",
113 commandId: CommandId.make("user-raise"),
114 threadId: input.threadId,
115 runtimeMode: "full-access",
116 })
117 .pipe(Effect.provideService(DispatchModeLimit, undefined), Effect.orDie);
118 yield* Ref.set(raised, true);
119 }
120 yield* threads
121 .dispatch({
122 type: "thread.metadata.update",
123 commandId: CommandId.make(`agent-rename:${userRaises}`),
124 threadId: input.threadId,
125 title: "Renamed by the agent",
126 })
127 .pipe(
128 Effect.mapError(
129 () =>
130 new OrchestratorMcpFailure({
131 code: "orchestration_error",
132 message: "The rename failed.",
133 }),
134 ),
135 );
136 return { renamed: true };
137 }),
138 ),
139 });
140 const outcome = yield* McpServer.McpServer.pipe(
141 Effect.flatMap((server) => server.callTool({ name: "rename", arguments: { threadId } })),
142 Effect.flatMap(({ content }) =>
143 decodeOutcome(content.map((part) => (part.type === "text" ? part.text : "")).join("")),
144 ),
145 Effect.provideService(McpInvocationContext.McpInvocationContext, supervisedClient),
146 Effect.provideService(McpSchema.McpServerClient, mcpClient),
147 Effect.provide(
148 McpHttpServer.toolkitRegistration(RenameToolkit, handlers).pipe(
149 Layer.provideMerge(McpServer.McpServer.layer),
150 ),
151 ),
152 );
153 assert.equal(yield* Ref.get(raised), userRaises);
154 return outcome;
155 });
156
157const createSupervisedThread = (threadId: ThreadId) =>
158 Effect.gen(function* () {
159 const orchestrator = yield* Orchestrator.OrchestratorV2;
160 yield* orchestrator.dispatch({
161 type: "thread.create",
162 commandId: CommandId.make(`create:${threadId}`),
163 threadId,
164 projectId: ProjectId.make("project:mcp-race"),
165 title: "Before",
166 modelSelection: { instanceId, model: "gpt-5" },
167 runtimeMode: "approval-required",
168 interactionMode: "default",
169 branch: null,
170 worktreePath: null,
171 createdBy: "user",
172 creationSource: "web",
173 });
174 });
175
176it.layer(layerOrchestrator)("writesThreads against a mode raise", (it) => {
177 it.effect("refuses the write when the user raises the thread after the check", () =>
178 Effect.gen(function* () {
179 const projections = yield* ProjectionStore.ProjectionStoreV2;
180 const threadId = ThreadId.make("thread:race-raised");
181 yield* createSupervisedThread(threadId);
182 const outcome = yield* renameRacingTheUser(threadId, true);
183 assert.deepEqual(outcome, { code: "runtime_mode_escalation_denied" });
184 const shell = yield* projections.getThreadShell(threadId);
185 assert.equal(shell?.runtimeMode, "full-access");
186 assert.equal(shell?.title, "Before");
187 }).pipe(Effect.provide(ThreadManagement.layer)),
188 );
189
190 it.effect("lets the write through when the thread stays within the caller's modes", () =>
191 Effect.gen(function* () {
192 const projections = yield* ProjectionStore.ProjectionStoreV2;
193 const threadId = ThreadId.make("thread:race-steady");
194 yield* createSupervisedThread(threadId);
195 const outcome = yield* renameRacingTheUser(threadId, false);
196 assert.deepEqual(outcome, { renamed: true });
197 assert.equal((yield* projections.getThreadShell(threadId))?.title, "Renamed by the agent");
198 }).pipe(Effect.provide(ThreadManagement.layer)),
199 );
200});