refactor(provider-core): MCP provider sessions live in a McpProviderSessions service (#17446)

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-09 09:15:22 -07:00
1 parent 68ab16f308
commit 784b5625f9
48 files changed
+1471 -657

No files matched your search

@@ -59,6 +59,7 @@ import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
import {
@@ -3810,7 +3811,9 @@ describe("orchestrator MCP toolkit", () => {
Layer.provideMerge(McpServer.McpServer.layer),
Layer.provideMerge(layerOrchestration),
Layer.provide(
CodexOrchestratorReplayHarness.makeProviderAdapterRegistryLayer(transcript),
CodexOrchestratorReplayHarness.makeProviderAdapterRegistryLayer(transcript).pipe(
Layer.provide(McpProviderSessions.layer),
),
),
Layer.provide(layerProviderRegistry),
Layer.provide(layerUnusedScheduledTaskStub),
@@ -30,6 +30,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ModelManifest from "../provider/ModelManifest.ts";
import * as ProviderInstanceRegistryHydration from "../provider/ProviderInstanceRegistryHydration.ts";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime";
import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger";
@@ -144,6 +145,7 @@ const layerLive = RuntimeLayer.layer.pipe(
Layer.provide(layerBackgroundPolicy),
Layer.provide(ProviderTurnStartServiceTestkit.layer),
Layer.provide(layerPlatformTest),
Layer.provide(McpProviderSessions.layer),
);
const waitForIdle = Effect.fn("AcpRegistryOrchestratorV2Live.waitForIdle")(function* (
@@ -54,7 +54,7 @@ import type * as EffectAcpProtocol from "effect-acp/protocol";
import type * as EffectAcpSchema from "effect-acp/compat";
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
import {
extractXAiAcpSubagentEndNotice,
@@ -96,7 +96,12 @@ const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({});
const layerHost = layerTestProviderHost().pipe(Layer.provide(NodeServices.layer));
const layerTest = Layer.mergeAll(NodeServices.layer, IdAllocator.layer, layerHost);
const layerTest = Layer.mergeAll(
NodeServices.layer,
IdAllocator.layer,
McpProviderSessions.layer,
layerHost,
);
const ACP_TEST_DRIVER = ProviderDriverKind.make("acp-test");
const decodeUnknownJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
@@ -708,7 +713,7 @@ describe("AcpAdapterV2", () => {
const instanceId = ProviderInstanceId.make("acp-test-self-contained-mcp-bridge");
const threadId = ThreadId.make("thread-acp-self-contained-mcp-bridge");
McpProviderSession.setMcpProviderSession({
yield* (yield* McpProviderSessions.McpProviderSessions).set({
environmentId: EnvironmentId.make("environment-acp-self-contained-mcp-bridge"),
threadId,
providerSessionId: "mcp-session-acp-self-contained-mcp-bridge",
@@ -717,11 +722,6 @@ describe("AcpAdapterV2", () => {
authorizationHeader: "Bearer self-contained-mcp-bridge-token",
browserToolsAvailable: false,
});
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
McpProviderSession.clearMcpProviderSession(threadId);
}),
);
let runtimeInput: AcpAdapterV2RuntimeInput | undefined;
const makeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath });
@@ -772,7 +772,7 @@ describe("AcpAdapterV2", () => {
const protocolEvents = yield* Queue.unbounded<EffectAcpProtocol.AcpProtocolLogEvent>();
const instanceId = ProviderInstanceId.make("acp-test-instruction-transitions");
const threadId = ThreadId.make("thread-acp-instruction-transitions");
McpProviderSession.setMcpProviderSession({
yield* (yield* McpProviderSessions.McpProviderSessions).set({
environmentId: EnvironmentId.make("environment-acp-instruction-transitions"),
threadId,
providerSessionId: "mcp-session-acp-instruction-transitions",
@@ -781,9 +781,6 @@ describe("AcpAdapterV2", () => {
authorizationHeader: "Bearer instruction-transition-token",
browserToolsAvailable: false,
});
yield* Effect.addFinalizer(() =>
Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId)),
);
const adapter = yield* makeAcpAdapterV2({
instanceId,
flavor: {
@@ -2197,7 +2194,7 @@ describe("AcpAdapterV2", () => {
});
const sourceThreadId = ThreadId.make("thread-acp-native-fork-source");
const targetThreadId = ThreadId.make("thread-acp-native-fork-target");
McpProviderSession.setMcpProviderSession({
yield* (yield* McpProviderSessions.McpProviderSessions).set({
environmentId: EnvironmentId.make("environment-acp-native-fork-source"),
threadId: sourceThreadId,
providerSessionId: "mcp-session-acp-native-fork-source",
@@ -2206,7 +2203,7 @@ describe("AcpAdapterV2", () => {
authorizationHeader: "Bearer source-thread-token",
browserToolsAvailable: true,
});
McpProviderSession.setMcpProviderSession({
yield* (yield* McpProviderSessions.McpProviderSessions).set({
environmentId: EnvironmentId.make("environment-acp-native-fork"),
threadId: targetThreadId,
providerSessionId: "mcp-session-acp-native-fork",
@@ -2215,12 +2212,6 @@ describe("AcpAdapterV2", () => {
authorizationHeader: "Bearer target-thread-token",
browserToolsAvailable: true,
});
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
McpProviderSession.clearMcpProviderSession(sourceThreadId);
McpProviderSession.clearMcpProviderSession(targetThreadId);
}),
);
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
@@ -2640,7 +2631,7 @@ describe("AcpAdapterV2", () => {
);
const instanceId = ProviderInstanceId.make("acp-test-rollback-session");
const rollbackThreadId = ThreadId.make("thread-acp-rollback-session-target");
McpProviderSession.setMcpProviderSession({
yield* (yield* McpProviderSessions.McpProviderSessions).set({
environmentId: EnvironmentId.make("environment-acp-rollback-session-target"),
threadId: rollbackThreadId,
providerSessionId: "mcp-session-acp-rollback-session-target",
@@ -2649,9 +2640,6 @@ describe("AcpAdapterV2", () => {
authorizationHeader: "Bearer rollback-target-token",
browserToolsAvailable: false,
});
yield* Effect.addFinalizer(() =>
Effect.sync(() => McpProviderSession.clearMcpProviderSession(rollbackThreadId)),
);
const runtimeInputs: Array<AcpAdapterV2RuntimeInput> = [];
const makeRuntime = makeMockRuntime({
childProcessSpawner,
@@ -14,6 +14,7 @@ import { ChildProcessSpawner } from "effect/process";
import * as EffectAcpErrors from "effect-acp/errors";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
import * as ServerSettings from "../../serverSettings.ts";
import type {
@@ -84,6 +85,7 @@ const layerRegistry = Layer.succeed(
const layerTest = Layer.mergeAll(
NodeServices.layer,
IdAllocator.layer,
McpProviderSessions.layer,
layerHost,
layerRegistry,
ServerSettings.layerTest(),
@@ -23,6 +23,7 @@ import { ChildProcessSpawner } from "effect/process";
import type * as EffectAcpSchema from "effect-acp/compat";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts";
@@ -129,6 +130,7 @@ describe("AntigravityAdapterV2 flavor", () => {
const layerSession = Layer.mergeAll(
NodeServices.layer,
IdAllocator.layer,
McpProviderSessions.layer,
layerTestProviderHost().pipe(Layer.provide(NodeServices.layer)),
);
File diff suppressed because it is too large. Load diff
@@ -117,6 +117,7 @@ import {
normalizeMcpText,
} from "@t3tools/provider-core/server/mcpToolPresentation";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import {
makeProviderFailure,
@@ -973,7 +974,7 @@ export const CLAUDE_T3_MCP_TOOL_TIMEOUT_MS = 65 * 60 * 1_000;
const CLAUDE_T3_MCP_AUTHORIZATION_ENV = "T3_CODE_MCP_AUTHORIZATION";
export function claudeMcpQueryOverrides(input: {
readonly threadId: ThreadId;
readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined;
readonly readOnlySandbox: boolean;
readonly allowedTools?: ReadonlyArray<string>;
}): {
@@ -981,7 +982,7 @@ export function claudeMcpQueryOverrides(input: {
readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
readonly mcpEnvironment?: Readonly<Record<string, string>>;
} {
const session = McpProviderSession.readMcpProviderSession(input.threadId);
const session = input.mcpSession;
if (session === undefined) {
return input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools };
}
@@ -3026,9 +3027,10 @@ export interface ClaudeAdapterV2Options {
};
}
export function makeClaudeAdapterV2(
export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
adapterOptions: ClaudeAdapterV2Options,
): ProviderAdapter.ProviderAdapterV2["Service"] {
) {
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const { attachmentsDir, fileSystem, path, crypto, idAllocator, queryRunner } = adapterOptions;
const continuationRequests = adapterOptions.continuationRequests ?? {
offer: () => Effect.void,
@@ -7261,7 +7263,7 @@ export function makeClaudeAdapterV2(
) {
const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy);
const mcpOverrides = claudeMcpQueryOverrides({
threadId: turnInput.threadId,
mcpSession: yield* mcpSessions.read(turnInput.threadId),
readOnlySandbox:
sandboxPolicyKindForClaudeRuntimePolicy(turnInput.runtimePolicy) === "readOnly",
...(queryPolicy.allowedTools === undefined
@@ -8156,13 +8158,14 @@ export function makeClaudeAdapterV2(
),
),
});
}
});
export type ClaudeAdapterV2DriverEnv =
| ClaudeAgentSdkQueryRunner
| Crypto.Crypto
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| Path.Path
| ServerConfig.ServerConfig;
@@ -8186,7 +8189,7 @@ export const createClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2Driver.create")(
expandHomePath(config.binaryPath),
claudeEnvironment,
);
return makeClaudeAdapterV2({
return yield* makeClaudeAdapterV2({
instanceId,
settings: { ...config, enabled, binaryPath },
environment: claudeEnvironment,
@@ -8234,7 +8237,7 @@ const makeDefaultClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2.layer")(function*
const serverConfig = yield* ServerConfig.ServerConfig;
const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
return makeClaudeAdapterV2({
return yield* makeClaudeAdapterV2({
instanceId: CLAUDE_DEFAULT_INSTANCE_ID,
settings: DEFAULT_CLAUDE_SETTINGS,
environment: hostEnvironment,
@@ -8255,6 +8258,7 @@ const layer: Layer.Layer<
| Crypto.Crypto
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| Path.Path
| ServerConfig.ServerConfig
> = Layer.effect(ProviderAdapter.ProviderAdapterV2, makeDefaultClaudeAdapterV2());
@@ -54,7 +54,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process";
import packageJson from "../../../package.json" with { type: "json" };
import * as ServerConfig from "../../config.ts";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as EffectWorker from "../EffectWorker.ts";
@@ -639,7 +639,7 @@ describe("CodexAdapterV2 runtime policy", () => {
describe("CodexAdapterV2 process spawning", () => {
it("injects cwd, model, and MCP authorization into thread-scoped params", () => {
const threadId = ThreadId.make("thread-codex-mcp");
McpProviderSession.setMcpProviderSession({
const mcpSession = {
environmentId: EnvironmentId.make("environment-codex-mcp"),
threadId,
providerSessionId: "mcp-session-codex",
@@ -647,38 +647,34 @@ describe("CodexAdapterV2 process spawning", () => {
endpoint: "http://127.0.0.1:43123/mcp",
authorizationHeader: "Bearer secret-codex-token",
browserToolsAvailable: true,
});
};
try {
assert.deepEqual(
CodexAdapterV2.codexThreadRuntimeParams({
threadId,
modelSelection: { model: "gpt-5.4" },
runtimePolicy: {
runtimeMode: "full-access",
interactionMode: "default",
cwd: "/workspace/thread-codex-mcp",
},
}),
{
assert.deepEqual(
CodexAdapterV2.codexThreadRuntimeParams({
mcpSession,
modelSelection: { model: "gpt-5.4" },
runtimePolicy: {
runtimeMode: "full-access",
interactionMode: "default",
cwd: "/workspace/thread-codex-mcp",
model: "gpt-5.4",
config: {
"tools.update_plan.enabled": true,
mcp_servers: {
"t3-code": {
url: "http://127.0.0.1:43123/mcp",
http_headers: {
Authorization: "Bearer secret-codex-token",
},
},
}),
{
cwd: "/workspace/thread-codex-mcp",
model: "gpt-5.4",
config: {
"tools.update_plan.enabled": true,
mcp_servers: {
"t3-code": {
url: "http://127.0.0.1:43123/mcp",
http_headers: {
Authorization: "Bearer secret-codex-token",
},
},
},
},
);
} finally {
McpProviderSession.clearMcpProviderSession(threadId);
}
},
);
});
it.effect("resolves Windows command shims through the shared spawn policy", () =>
@@ -822,7 +818,9 @@ describe("CodexAdapterV2 process spawning", () => {
assert.deepEqual(spawnedCommands, [path.join(NodeOS.homedir(), "bin", "codex")]);
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer)),
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
Effect.provideService(HostProcessPlatform, "linux"),
),
);
@@ -1716,7 +1714,7 @@ describe("CodexAdapterV2 session initialize", () => {
beforeEmitInbound === undefined ? {} : { beforeEmitInbound },
);
let initializeRequests = 0;
const adapter = CodexAdapterV2.makeCodexAdapterV2({
const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({
instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID,
settings: DEFAULT_CODEX_SETTINGS,
environment: {},
@@ -1811,7 +1809,12 @@ describe("CodexAdapterV2 session initialize", () => {
providerThreads.map((providerThread) => providerThread.nativeThreadRef?.nativeId),
["concurrent-first", "concurrent-second"],
);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("retries initialize after a failed handshake", () =>
@@ -1837,7 +1840,12 @@ describe("CodexAdapterV2 session initialize", () => {
const providerThread = yield* session.ensureThread("thread-initialize-retry");
assert.equal(providerThread.nativeThreadRef?.nativeId, "initialize-retry");
assert.equal(session.initializeRequests(), 2);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("completes the handshake after a caller is interrupted mid-initialize", () =>
@@ -1880,7 +1888,12 @@ describe("CodexAdapterV2 session initialize", () => {
const providerThread = yield* session.ensureThread("thread-initialize-interrupted");
assert.equal(providerThread.nativeThreadRef?.nativeId, "initialize-interrupted");
assert.equal(session.initializeRequests(), 2);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
});
@@ -1940,7 +1953,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
),
};
const adapter = CodexAdapterV2.makeCodexAdapterV2({
const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({
instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID,
settings: DEFAULT_CODEX_SETTINGS,
environment: {},
@@ -2121,7 +2134,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
);
assert.equal(requests.filter((method) => method === "turn/start").length, 1);
assert.isBelow(requests.indexOf("thread/inject_items"), requests.indexOf("turn/start"));
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("identifies sessions to Codex with the same client info as main", () =>
@@ -2157,7 +2175,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
},
},
]);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("unsubscribes from the native thread when it is unloaded", () =>
@@ -2195,7 +2218,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.isDefined(harness.runtime.unloadThread);
yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread });
assert.deepEqual(requests, ["initialize", "thread/start", "thread/unsubscribe"]);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("keeps the app-server failure as the cause when an unload is rejected", () =>
@@ -2229,7 +2257,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.equal(error._tag, "ProviderAdapterProtocolError");
const cause = error._tag === "ProviderAdapterProtocolError" ? error.cause : undefined;
assert.equal((cause as { _tag?: string } | undefined)?._tag, "CodexAppServerRequestError");
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("waits for native start before interrupting an acknowledged queued turn", () =>
@@ -2323,7 +2356,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.equal(harness.terminalEvents()[0]?.status, "interrupted");
assert.lengthOf(harness.terminalEvents(), 1);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("settles Stop when a queued native turn fails before starting", () =>
@@ -2405,7 +2443,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.lengthOf(harness.terminalEvents(), 1);
assert.isFalse(interruptSent, "A terminal native turn must not receive turn/interrupt");
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("bounds Stop when a queued native turn never starts", () =>
@@ -2465,7 +2508,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.lengthOf(harness.terminalEvents(), 1);
assert.isFalse(interruptSent, "An unstarted native turn must not receive turn/interrupt");
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("sends currency-sigil skill mentions to Codex as $ mentions", () =>
@@ -2524,7 +2572,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
text: "then £ship it",
},
});
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
const assistantMessages = (events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>) =>
@@ -2674,7 +2727,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
});
}
assert.isEmpty(assistantMessages(harness.events));
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -2748,7 +2805,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
],
});
const harness = yield* makeCodexReplayHarness(transcript);
McpProviderSession.setMcpProviderSession({
yield* (yield* McpProviderSessions.McpProviderSessions).set({
environmentId: EnvironmentId.make("test"),
threadId: harness.threadId,
providerSessionId: "context-session",
@@ -2757,9 +2814,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
authorizationHeader: "Bearer test",
browserToolsAvailable: true,
});
yield* Effect.addFinalizer(() =>
Effect.sync(() => McpProviderSession.clearMcpProviderSession(harness.threadId)),
);
yield* harness.runtime.startTurn(
makeCodexTestTurnInput({
threadId: harness.threadId,
@@ -2771,7 +2825,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
);
yield* harness.firstTerminal;
assert.equal(harness.terminalEvents()[0]?.status, "completed");
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -2847,7 +2905,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
);
assert.equal(items[0]?.id, items[1]?.id);
assert.equal(harness.terminalEvents()[0]?.status, "completed");
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -2895,7 +2957,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
assert.equal(resumed.status, "idle");
assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3050,7 +3116,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
);
assert.equal(resumed.status, "idle");
assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3132,7 +3202,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
restartContinuationOfRunId: RunId.make("run-before-restart"),
});
assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3280,7 +3354,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.isAtLeast(recoveredIndex, 0);
assert.isAbove(resumedCommandIndex, recoveredIndex);
assert.isAbove(terminalIndex, resumedCommandIndex);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3379,7 +3457,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
["compaction", 1782622565000],
],
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3543,7 +3625,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
);
}
assert.deepEqual(assistantMessages(harness.events), []);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3672,7 +3758,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assistantMessages(harness.events).map((event) => event.message.text),
["CODEX_RECOVERY_OK"],
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3715,7 +3805,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
})),
[{ text: "CODEX_RECOVERY_OK", streaming: false }],
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3759,7 +3853,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assistantMessages(harness.events).map((event) => event.message.text),
["CODEX_RECOVERY_OK"],
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3878,7 +3976,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
new Set(assistantMessages(harness.events).map((event) => event.message.id)).size,
1,
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3906,7 +4008,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assistantMessages(harness.events).map((event) => event.message.text),
[""],
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3935,7 +4041,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assistantMessages(harness.events).map((event) => event.message.text),
[""],
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3964,7 +4074,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assistantMessages(harness.events).map((event) => event.message.text),
["Working on it.", ""],
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -3993,7 +4107,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assistantMessages(harness.events).map((event) => event.message.text),
["CODEX_RECOVERY_OK"],
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -4022,7 +4140,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assistantMessages(harness.events).map((event) => event.message.text),
["CODEX_RECOVERY_OK"],
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -4051,7 +4173,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assistantMessages(harness.events).map((event) => event.message.text),
["", "CODEX_RECOVERY_OK"],
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -4207,7 +4333,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
);
assert.lengthOf(harness.terminalEvents(), 1);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -4362,7 +4492,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.lengthOf(harness.terminalEvents(), 1);
assert.equal(harness.terminalEvents()[0]?.status, "completed");
assert.lengthOf(harness.continuationRequests, 0);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
},
);
@@ -4722,7 +4856,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.lengthOf(harness.continuationRequests, 0);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
assert.lengthOf(harness.terminalEvents(), 1);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -5011,7 +5149,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
);
assert.isAtLeast(commandUpdates.length, 2, "start + interrupt terminalization");
assert.equal(commandUpdates[commandUpdates.length - 1]?.turnItem.status, "interrupted");
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -5239,7 +5381,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.equal(harness.subagentUpdates().at(-1)?.subagent.status, "interrupted");
assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -5324,7 +5470,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted root terminal");
assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -5412,7 +5562,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted root terminal");
assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -5523,7 +5677,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.equal(lateChildUpdates.at(-1)?.providerTurn.status, "interrupted");
assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -5688,7 +5846,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
);
assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -5953,7 +6115,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
commandUpdatesBeforeLateEvents.length,
"late starts and completions must not project after timeout",
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -6060,7 +6226,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted terminal");
assert.equal(harness.terminalEvents()[0]?.status, "interrupted");
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -6296,7 +6466,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.isDefined(item);
}
if (scenario.name === "retry") assert.equal(terminal.retry?.attempt, 1);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -6394,7 +6568,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
assert.lengthOf(harness.continuationRequests, 0);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -6555,7 +6733,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.include(stored, "connect-src https://api.weather.test");
assert.isBelow(stored.indexOf("Content-Security-Policy"), stored.indexOf("<script>"));
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -6641,7 +6823,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
const output = rows[0]!.turnItem.type === "dynamic_tool" ? rows[0]!.turnItem.output : null;
assert.isUndefined((output as Record<string, unknown> | null)?.[MCP_APP_OUTPUT_KEY]);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -6883,7 +7069,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
);
assert.lengthOf(harness.terminalEvents(), 1);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -7117,7 +7307,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
]);
}
assert.equal(metadataRequests, name === "current Codex Sol" ? 1 : 2);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -7174,7 +7368,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
yield* harness.firstTerminal;
assert.equal(harness.subagentUpdates().at(-1)?.subagent.model, model);
assert.deepEqual(metadataRequests, ["thread/read", "thread/resume"]);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -7273,7 +7471,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
{ id: "reasoningEffort", value: "low" },
{ id: "serviceTier", value: "ultrafast" },
]);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -7335,7 +7537,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.isFalse(yield* harness.hasPendingBackgroundWork);
assert.lengthOf(harness.terminalEvents(), 1);
assert.lengthOf(harness.continuationRequests, 0);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -7415,7 +7621,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.isNull(row?.completedAt);
assert.isNotNull(row?.startedAt);
assert.equal(DateTime.toEpochMillis(row!.startedAt!), 1782622470000);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -7577,7 +7787,11 @@ describe("CodexAdapterV2 post-settle continuation", () => {
DateTime.toEpochMillis(first.subagent.completedAt!),
);
}
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -7725,7 +7939,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
"thread/rollback",
"thread/rollback must not be sent to a legacy Codex thread",
);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect(
@@ -7864,7 +8083,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.notEqual(forkedProviderThread.id, harness.providerThread.id);
assert.equal(forkedProviderThread.forkedFrom?.providerTurnId, firstTurn.id);
assert.deepEqual(outbound.slice(-2), ["thread/turns/list", "thread/revert"]);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect(
@@ -7966,7 +8190,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
"thread/rollback",
"thread/rollback must not be sent to a legacy Codex fork",
);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("propagates native thread/fork failures as typed fork errors", () =>
@@ -8022,7 +8251,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.instanceOf(error, ProviderAdapter.ProviderAdapterForkThreadError);
assert.include(errorCauseChainText(error), "fork exploded");
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
describe("native goals", () => {
@@ -8186,7 +8420,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
],
);
assert.equal(providerGoals(harness.events).at(-1), "complete");
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("settles /goal pause with a reply instead of a native turn", () =>
@@ -8230,7 +8469,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
"Goal paused. Send /goal resume to continue.",
);
assert.equal(providerGoals(harness.events).at(-1), "paused");
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("settles a run held for the next goal turn when Stop arrives in between", () =>
@@ -8321,7 +8565,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
harness.terminalEvents().map((event) => event.status),
["interrupted"],
);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("moves a Stop that names an earlier goal turn to the turn Codex continued with", () =>
@@ -8400,7 +8649,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
harness.terminalEvents().map((event) => event.status),
["interrupted"],
);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("stops a held goal run's background command when Stop arrives between turns", () =>
@@ -8502,7 +8756,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
"the background command to be interrupted",
);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("moves Stop to a continuation Codex starts while the goal pause is in flight", () =>
@@ -8584,7 +8843,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
harness.terminalEvents().map((event) => event.status),
["interrupted"],
);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("stops a subagent an earlier goal turn left running when Stop settles the run", () =>
@@ -8681,7 +8945,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
"the subagent turn to be interrupted",
);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("stops an earlier goal turn's subagent when the run settles during the pause", () =>
@@ -8794,7 +9063,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
"the subagent turn to be interrupted",
);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
it.effect("pauses an active goal before Stop interrupts its turn", () =>
@@ -8858,7 +9132,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
harness.terminalEvents().map((event) => event.status),
["interrupted"],
);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);
});
});
@@ -108,6 +108,7 @@ import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEve
import { codexAppServerArgs, resolveCodexLaunchArgs } from "../../provider/codexLaunchArgs.ts";
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import {
MCP_APP_EXTENSION_ID,
MCP_APP_MIME_TYPE,
@@ -1296,7 +1297,7 @@ export class CodexAppServerClientFactory extends Context.Service<
export const CODEX_THREAD_CONFIG = { "tools.update_plan.enabled": true } as const;
export function codexThreadRuntimeParams(input: {
readonly threadId: ThreadId | null;
readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined;
readonly modelSelection?: { readonly model: string };
readonly runtimePolicy?: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
}): {
@@ -1304,8 +1305,7 @@ export function codexThreadRuntimeParams(input: {
readonly model?: string;
readonly config: Readonly<Record<string, Schema.Json>>;
} {
const mcpSession =
input.threadId === null ? undefined : McpProviderSession.readMcpProviderSession(input.threadId);
const { mcpSession } = input;
return {
...(input.runtimePolicy?.cwd == null ? {} : { cwd: input.runtimePolicy.cwd }),
...(input.modelSelection === undefined ? {} : { model: input.modelSelection.model }),
@@ -1549,6 +1549,7 @@ export type CodexAdapterV2DriverEnv =
| Crypto.Crypto
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| Path.Path
| ServerConfig;
@@ -1585,7 +1586,7 @@ export const createCodexAdapterV2 = (
homePath: homeLayout.effectiveHomePath ?? "",
} satisfies CodexSettings;
return makeCodexAdapterV2({
return yield* makeCodexAdapterV2({
instanceId,
settings,
environment: mergeProviderInstanceEnvironment(environment, hostEnvironment),
@@ -1613,6 +1614,7 @@ const layer: Layer.Layer<
| Crypto.Crypto
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| ServerConfig
> = Layer.effect(
ProviderAdapter.ProviderAdapterV2,
@@ -1625,7 +1627,7 @@ const layer: Layer.Layer<
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const serverConfig = yield* ServerConfig;
return makeCodexAdapterV2({
return yield* makeCodexAdapterV2({
instanceId: CODEX_DEFAULT_INSTANCE_ID,
settings: DEFAULT_CODEX_SETTINGS,
environment: hostEnvironment,
@@ -1667,9 +1669,12 @@ export interface CodexAdapterV2Options {
};
}
export function makeCodexAdapterV2(
export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
adapterOptions: CodexAdapterV2Options,
): ProviderAdapter.ProviderAdapterV2["Service"] {
) {
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const readMcpSession = (threadId: ThreadId | null) =>
threadId === null ? Effect.succeed(undefined) : mcpSessions.read(threadId);
const { clientFactory, crypto, fileSystem, idAllocator, serverConfig } = adapterOptions;
const continuationRequests = adapterOptions.continuationRequests;
@@ -6166,7 +6171,7 @@ export function makeCodexAdapterV2(
) =>
Effect.gen(function* () {
const threadId = yield* getNativeThreadId(turnInput.providerThread);
const mcpSession = McpProviderSession.readMcpProviderSession(turnInput.threadId);
const mcpSession = yield* mcpSessions.read(turnInput.threadId);
const turnStartParams = yield* buildCodexTurnStartParams({
nativeThreadId: threadId,
codexInput,
@@ -6445,11 +6450,12 @@ export function makeCodexAdapterV2(
}),
ensureThread: (threadInput) =>
ensureInitialized.pipe(
Effect.andThen(
Effect.andThen(mcpSessions.read(threadInput.threadId)),
Effect.flatMap((mcpSession) =>
client.request(
"thread/start",
codexThreadRuntimeParams({
threadId: threadInput.threadId,
mcpSession,
modelSelection: threadInput.modelSelection,
runtimePolicy: threadInput.runtimePolicy,
}),
@@ -6482,7 +6488,9 @@ export function makeCodexAdapterV2(
threadId: nativeThreadId,
excludeTurns: true,
...codexThreadRuntimeParams({
threadId: threadInput.threadId ?? threadInput.providerThread.appThreadId,
mcpSession: yield* readMcpSession(
threadInput.threadId ?? threadInput.providerThread.appThreadId,
),
...(threadInput.modelSelection === undefined
? {}
: { modelSelection: threadInput.modelSelection }),
@@ -7210,7 +7218,7 @@ export function makeCodexAdapterV2(
threadId,
excludeTurns: true,
...codexThreadRuntimeParams({
threadId: threadInput.providerThread.appThreadId,
mcpSession: yield* readMcpSession(threadInput.providerThread.appThreadId),
modelSelection: input.modelSelection,
runtimePolicy: input.runtimePolicy,
}),
@@ -7259,7 +7267,7 @@ export function makeCodexAdapterV2(
? {}
: { lastTurnId: boundary.lastTurnId }),
...codexThreadRuntimeParams({
threadId: threadInput.targetThreadId,
mcpSession: yield* mcpSessions.read(threadInput.targetThreadId),
...(threadInput.modelSelection === undefined
? {}
: { modelSelection: threadInput.modelSelection }),
@@ -7344,4 +7352,4 @@ export function makeCodexAdapterV2(
),
),
});
}
});
@@ -719,6 +719,7 @@ export const recordCursorAgentSdkReplayTranscript = Effect.fn(
: { override: input.runtimePolicyOverride }),
}),
threadId,
mcpSession: undefined,
});
const sendOptions = {
model: cursorSdkModelSelection(input.modelSelection),
@@ -26,6 +26,7 @@ import { buildInitialGrokProviderSnapshot } from "@t3tools/provider-grok/testing
import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
import * as ProviderInstanceRegistry from "../../provider/ProviderInstanceRegistry.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as RuntimePolicy from "../RuntimePolicy.ts";
import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy";
@@ -309,7 +310,12 @@ describe("Grok permission prompts", () => {
describe("Grok launch permission mode", () => {
const layerHost = layerTestProviderHost().pipe(Layer.provide(NodeServices.layer));
const layerTest = Layer.mergeAll(NodeServices.layer, IdAllocator.layer, layerHost);
const layerTest = Layer.mergeAll(
NodeServices.layer,
IdAllocator.layer,
McpProviderSessions.layer,
layerHost,
);
// Opens a session through the adapter's own Grok runtime factory and returns
// the argv it tried to launch. The spawn fails after recording, so no
@@ -39,7 +39,7 @@ import { TestClock } from "effect/testing";
import { describe } from "vite-plus/test";
import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import {
@@ -403,7 +403,7 @@ const history = {
cursor: {},
};
describe("OpenCode2 adapter", () => {
it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
it.effect("switches the session's model and variant before a turn that changed them", () =>
Effect.gen(function* () {
const { runtime, thread } = yield* resumed([
@@ -2486,29 +2486,6 @@ describe("OpenCode2 adapter", () => {
}).pipe(Effect.scoped),
);
it.live("returns the server it reconnected to once the session closes", () =>
Effect.gen(function* () {
// A spawned server stops after it has no borrowers for a while, so a
// session must not keep holding the connection it reconnected with.
const borrowers = { current: 0 };
yield* Effect.gen(function* () {
yield* openCode2ReplayRuntime(
[
...opening,
{ type: "runtime_exit", status: "success" },
out("event.subscribe"),
event("server.connected", {}),
],
{ borrowers },
);
// Reconnected: the dropped connection is returned and the new one is held.
yield* Effect.sleep("200 millis");
assert.equal(borrowers.current, 1);
}).pipe(Effect.scoped);
assert.equal(borrowers.current, 0);
}),
);
it.effect(
"backfills and ends a subagent's turn whose execution ended while the stream was down",
() =>
@@ -2697,7 +2674,8 @@ describe("OpenCode2 adapter", () => {
"registers T3's MCP server for the thread alone and removes it when the thread unloads",
() =>
Effect.gen(function* () {
McpProviderSession.setMcpProviderSession({
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
yield* mcpSessions.set({
environmentId: EnvironmentId.make("environment:opencode2-adapter"),
threadId,
providerSessionId: "mcp:opencode2-adapter",
@@ -2706,9 +2684,7 @@ describe("OpenCode2 adapter", () => {
authorizationHeader: "Bearer thread-credential",
browserToolsAvailable: false,
});
yield* Effect.addFinalizer(() =>
Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId)),
);
yield* Effect.addFinalizer(() => mcpSessions.clear(threadId));
const server = "t3-code-thread_opencode2-adapter";
const { runtime, thread } = yield* resumed([
// Registered for the session's directory under the thread's own name;
@@ -2744,7 +2720,8 @@ describe("OpenCode2 adapter", () => {
"thread:delegated-task:command%3Amcp%3A48bef2bf-6d0e-4f7a-9c3b-2e5d8a1f7c40%3Adelegate-task%3Asubproject-b-round1",
);
const server = "t3-code-aa73fa1e03099934";
McpProviderSession.setMcpProviderSession({
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
yield* mcpSessions.set({
environmentId: EnvironmentId.make("environment:opencode2-adapter"),
threadId: child,
providerSessionId: "mcp:opencode2-adapter",
@@ -2753,9 +2730,7 @@ describe("OpenCode2 adapter", () => {
authorizationHeader: "Bearer thread-credential",
browserToolsAvailable: false,
});
yield* Effect.addFinalizer(() =>
Effect.sync(() => McpProviderSession.clearMcpProviderSession(child)),
);
yield* Effect.addFinalizer(() => mcpSessions.clear(child));
const runtime = yield* openCode2ReplayRuntimeWithInstructions([
...opening,
out("session.get", { sessionID: SESSION }),
@@ -3992,6 +3967,31 @@ describe("OpenCode2 adapter", () => {
);
});
describe("OpenCode2 adapter server connection", () => {
it.live("returns the server it reconnected to once the session closes", () =>
Effect.gen(function* () {
// A spawned server stops after it has no borrowers for a while, so a
// session must not keep holding the connection it reconnected with.
const borrowers = { current: 0 };
yield* Effect.gen(function* () {
yield* openCode2ReplayRuntime(
[
...opening,
{ type: "runtime_exit", status: "success" },
out("event.subscribe"),
event("server.connected", {}),
],
{ borrowers },
);
// Reconnected: the dropped connection is returned and the new one is held.
yield* Effect.sleep("200 millis");
assert.equal(borrowers.current, 1);
}).pipe(Effect.scoped);
assert.equal(borrowers.current, 0);
}).pipe(Effect.provide(McpProviderSessions.layer)),
);
});
/** The provider turn the adapter derives for `turnInput`'s attempt. */
const providerTurnId = Effect.gen(function* () {
const ids = yield* IdAllocator.IdAllocatorV2;
@@ -4001,7 +4001,7 @@ const providerTurnId = Effect.gen(function* () {
});
}).pipe(Effect.provide(IdAllocator.layer));
describe("OpenCode reported model variants", () => {
it.layer(McpProviderSessions.layer)("OpenCode reported model variants", (it) => {
it.effect(
"updates reported variants from selected-model and step events without duplicate updates",
() =>
@@ -32,6 +32,7 @@ import * as ClaudeAdapterV2 from "./Adapters/ClaudeAdapterV2.ts";
import * as EffectWorker from "./EffectWorker.ts";
import * as EventSink from "./EventSink.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
import * as Orchestrator from "./Orchestrator.ts";
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
@@ -131,7 +132,7 @@ it.effect.each(["child completion", "scheduled message", "user steering"] as con
const offers: SDKUserMessage[] = [];
const nativeQueue: SDKUserMessage[] = [];
const batchAbort = new AbortController();
const adapter = ClaudeAdapterV2.makeClaudeAdapterV2({
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
instanceId: modelSelection.instanceId,
settings,
environment: {},
@@ -423,6 +424,10 @@ it.effect.each(["child completion", "scheduled message", "user steering"] as con
),
),
);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
@@ -30,6 +30,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ModelManifest from "../provider/ModelManifest.ts";
import * as ProviderInstanceRegistryHydration from "../provider/ProviderInstanceRegistryHydration.ts";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime";
import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger";
@@ -124,6 +125,7 @@ const layerLive = RuntimeLayer.layer.pipe(
Layer.provide(ResetCreditCoordinator.layer),
Layer.provide(layerBackgroundPolicy),
Layer.provide(layerPlatformTest),
Layer.provide(McpProviderSessions.layer),
);
const waitForIdle = Effect.fn("CursorOrchestratorV2Live.waitForIdle")(function* (
@@ -1,4 +1,5 @@
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import {
@@ -130,6 +131,7 @@ const layerTest = Layer.mergeAll(RuntimeLayer.layer, RuntimeLayer.layerEventSink
}),
),
Layer.provide(McpSessionRegistryTestkit.layer),
Layer.provide(McpProviderSessions.layer),
Layer.provide(SqlitePersistence.layerMemory),
Layer.provide(layerCheckpointStoreTest),
Layer.provide(layerServerConfig),
@@ -30,6 +30,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ModelManifest from "../provider/ModelManifest.ts";
import * as ProviderInstanceRegistryHydration from "../provider/ProviderInstanceRegistryHydration.ts";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime";
import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger";
@@ -123,6 +124,7 @@ const layerLive = RuntimeLayer.layer.pipe(
Layer.provide(ResetCreditCoordinator.layer),
Layer.provide(layerBackgroundPolicy),
Layer.provide(layerPlatformTest),
Layer.provide(McpProviderSessions.layer),
);
const waitForIdle = Effect.fn("GrokOrchestratorV2Live.waitForIdle")(function* (threadId: ThreadId) {
@@ -55,6 +55,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ModelManifest from "../provider/ModelManifest.ts";
import * as ProviderInstanceRegistryHydration from "../provider/ProviderInstanceRegistryHydration.ts";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as OpenCode2Client from "@t3tools/provider-opencode/server/v2/OpenCode2Client";
import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime";
@@ -217,6 +218,7 @@ const layerOrchestration = RuntimeLayer.layer.pipe(
Layer.provide(ResetCreditCoordinator.layer),
Layer.provide(layerBackgroundPolicy),
Layer.provide(layerPlatformTest),
Layer.provide(McpProviderSessions.layer),
);
// Starts the continuation run a provider wake asks for, as the production layer does.
@@ -1,4 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { assert, it } from "@effect/vitest";
import { ProjectId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -152,6 +153,7 @@ const layerRuntime = (dbPath: string) => {
}),
),
Layer.provide(McpSessionRegistryTestkit.layer),
Layer.provide(McpProviderSessions.layer),
Layer.provideMerge(SqlitePersistence.layerFromPath(dbPath)),
Layer.provide(layerCheckpointStore),
Layer.provide(layerServerConfig),
@@ -36,6 +36,7 @@ import { ProviderWorkspaceMissingError } from "../provider/Errors.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ServerSettings from "../serverSettings.ts";
@@ -302,7 +303,7 @@ function unimplemented(detail: string) {
);
}
function makeProviderAdapter(
const makeProviderAdapter = Effect.fnUntraced(function* (
state: Ref.Ref<TestProviderRuntimeState>,
options: {
readonly failEventStream?: boolean;
@@ -324,7 +325,8 @@ function makeProviderAdapter(
/** Completed when a hanging scope close reaches its wedged finalizer. */
readonly scopeCloseReached?: Deferred.Deferred<void>;
} = {},
): ProviderAdapter.ProviderAdapterV2["Service"] {
) {
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const countClose = Effect.addFinalizer(() =>
Ref.update(state, (current) => ({
...current,
@@ -340,7 +342,7 @@ function makeProviderAdapter(
: Deferred.succeed(options.scopeCloseReached, undefined)
).pipe(Effect.andThen(Effect.never)),
);
return {
return ProviderAdapter.ProviderAdapterV2.of({
instanceId: ProviderInstanceId.make("codex"),
driver: CODEX_DRIVER,
getCapabilities: () => Effect.succeed(options.capabilities ?? CodexCapabilities),
@@ -352,19 +354,15 @@ function makeProviderAdapter(
if (options.hangSessionScopeClose === true) yield* hangClose;
}
if (options.mcpConfigs !== undefined && options.spawnBeforeOpen === true) {
yield* Ref.update(options.mcpConfigs, (configs) => [
...configs,
McpProviderSession.readMcpProviderSession(input.threadId),
]);
const mcpConfig = yield* mcpSessions.read(input.threadId);
yield* Ref.update(options.mcpConfigs, (configs) => [...configs, mcpConfig]);
}
if (options.beforeOpen !== undefined) {
yield* options.beforeOpen(input);
}
if (options.mcpConfigs !== undefined && options.spawnBeforeOpen !== true) {
yield* Ref.update(options.mcpConfigs, (configs) => [
...configs,
McpProviderSession.readMcpProviderSession(input.threadId),
]);
const mcpConfig = yield* mcpSessions.read(input.threadId);
yield* Ref.update(options.mcpConfigs, (configs) => [...configs, mcpConfig]);
}
const now = yield* DateTime.now;
const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event, Cause.Done>();
@@ -440,8 +438,8 @@ function makeProviderAdapter(
forkThread: () => unimplemented("forkThread unused in test"),
} satisfies ProviderAdapter.ProviderAdapterV2SessionRuntime;
}),
};
}
});
});
function layerTest(input: {
readonly state: Ref.Ref<TestProviderRuntimeState>;
@@ -482,7 +480,7 @@ function layerTest(input: {
: input.failReleaseEventWrites
? layerFailingReleaseEventSink
: layerTestEventSink;
const layerRegistry = ProviderAdapterRegistry.layerSingle(
const layerRegistry = Layer.unwrap(
makeProviderAdapter(input.state, {
failEventStream: input.failEventStream ?? false,
...(input.capabilities === undefined ? {} : { capabilities: input.capabilities }),
@@ -503,7 +501,7 @@ function layerTest(input: {
...(input.scopeCloseReached === undefined
? {}
: { scopeCloseReached: input.scopeCloseReached }),
}),
}).pipe(Effect.map(ProviderAdapterRegistry.layerSingle)),
);
const layerConfiguredMcpRegistry =
input.pauseResolve === undefined
@@ -524,13 +522,14 @@ function layerTest(input: {
layerConfiguredEventSink,
IdAllocator.layer,
layerConfiguredMcpRegistry,
McpProviderSessions.layer,
ProviderSessionManager.layerWithOptions({
idleTimeoutMs: input.idleTimeoutMs,
...(input.maxIdlePinMs === undefined ? {} : { maxIdlePinMs: input.maxIdlePinMs }),
}).pipe(
Layer.provide(
Layer.mergeAll(
layerRegistry,
layerRegistry.pipe(Layer.provideMerge(McpProviderSessions.layer)),
layerConfiguredEventSink,
IdAllocator.layer,
layerProviderEventIngestorTest,
@@ -1106,6 +1105,7 @@ it.effect("ProviderSessionManagerV2 cleans up an open interrupted mid-handshake"
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-interrupted-open");
@@ -1133,7 +1133,7 @@ it.effect("ProviderSessionManagerV2 cleans up an open interrupted mid-handshake"
// for it revoked.
assert.equal((yield* Ref.get(state)).closeCount, 1);
assert.isUndefined(yield* registry.resolve(token!));
assert.isUndefined(McpProviderSession.readMcpProviderSession(threadId));
assert.isUndefined(yield* mcpSessions.read(threadId));
assert.isTrue(Option.isNone(yield* manager.get(providerSessionId)));
// Nothing of the interrupted open is left behind: the next open starts a
@@ -1188,6 +1188,7 @@ it.effect("ProviderSessionManagerV2 cleans up an interrupted open whose scope cl
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-interrupted-hung-open");
const providerSessionId = yield* idAllocator.allocate.providerSession({
@@ -1212,7 +1213,7 @@ it.effect("ProviderSessionManagerV2 cleans up an interrupted open whose scope cl
// The session cleanup already ran, ahead of the stuck close.
assert.isUndefined(yield* registry.resolve(token!));
assert.isUndefined(McpProviderSession.readMcpProviderSession(threadId));
assert.isUndefined(yield* mcpSessions.read(threadId));
assert.equal((yield* Ref.get(state)).closeCount, 0);
// The close is time-boxed, so the interrupter returns and the session's
@@ -1750,6 +1751,7 @@ it.effect(
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-mcp");
const providerSessionId = yield* idAllocator.allocate.providerSession({
@@ -1782,7 +1784,7 @@ it.effect(
);
yield* manager.close(providerSessionId);
assert.isUndefined(McpProviderSession.readMcpProviderSession(threadId));
assert.isUndefined(yield* mcpSessions.read(threadId));
assert.isUndefined(yield* registry.resolve(token!));
});
@@ -1915,6 +1917,7 @@ it.effect("ProviderSessionManagerV2 revokes MCP credentials when release persist
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-mcp-release-failure");
const providerSessionId = yield* idAllocator.allocate.providerSession({
@@ -1939,7 +1942,7 @@ it.effect("ProviderSessionManagerV2 revokes MCP credentials when release persist
const closeError = yield* manager.close(providerSessionId).pipe(Effect.flip);
assert.equal(closeError._tag, "ProviderSessionCloseError");
assert.isUndefined(McpProviderSession.readMcpProviderSession(threadId));
assert.isUndefined(yield* mcpSessions.read(threadId));
assert.isUndefined(yield* registry.resolve(token!));
});
@@ -1968,6 +1971,7 @@ it.effect(
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const now = yield* DateTime.now;
const owner = ThreadId.make("thread-provider-session-manager-attach-race-owner");
const threadId = ThreadId.make("thread-provider-session-manager-attach-race");
@@ -2007,7 +2011,7 @@ it.effect(
yield* Fiber.join(second);
// The second attach owns the thread's attachment and credential.
const config = McpProviderSession.readMcpProviderSession(threadId);
const config = yield* mcpSessions.read(threadId);
assert.isDefined(config);
const token = config!.authorizationHeader.replace(/^Bearer\s+/, "");
assert.equal((yield* registry.resolve(token))?.thread.threadId, threadId);
@@ -2031,6 +2035,7 @@ it.effect(
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const eventStore = yield* EventStore.EventStoreV2;
const now = yield* DateTime.now;
const owner = ThreadId.make("thread-provider-session-manager-stale-attach-owner");
@@ -2075,14 +2080,14 @@ it.effect(
modelSelection,
runtimePolicy,
});
const config = McpProviderSession.readMcpProviderSession(threadId);
const config = yield* mcpSessions.read(threadId);
assert.isDefined(config);
yield* Fiber.interrupt(stale);
// The replacement keeps the thread and its credential.
assert.equal(
McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId,
(yield* mcpSessions.read(threadId))?.providerSessionId,
config!.providerSessionId,
);
const token = config!.authorizationHeader.replace(/^Bearer\s+/, "");
@@ -2126,6 +2131,7 @@ it.effect(
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const now = yield* DateTime.now;
const owner = ThreadId.make("thread-provider-session-manager-resolve-stop-owner");
const threadId = ThreadId.make("thread-provider-session-manager-resolve-stop");
@@ -2157,7 +2163,7 @@ it.effect(
// The thread gets a credential, then detaches and keeps it for a re-attach.
yield* resume;
yield* manager.detach({ providerSessionId, threadId });
const config = McpProviderSession.readMcpProviderSession(threadId);
const config = yield* mcpSessions.read(threadId);
assert.isDefined(config);
const token = config!.authorizationHeader.replace(/^Bearer\s+/, "");
@@ -2189,6 +2195,7 @@ it.effect("ProviderSessionManagerV2 duplicate detach preserves replacement MCP c
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-replacement-mcp");
const oldSessionId = yield* idAllocator.allocate.providerSession({
@@ -2222,14 +2229,14 @@ it.effect("ProviderSessionManagerV2 duplicate detach preserves replacement MCP c
const replacementToken = replacement?.authorizationHeader.replace(/^Bearer\s+/, "");
assert.isDefined(replacementToken);
assert.equal(
McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId,
(yield* mcpSessions.read(threadId))?.providerSessionId,
replacement?.providerSessionId,
);
yield* manager.detach({ providerSessionId: oldSessionId, threadId });
assert.equal(
McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId,
(yield* mcpSessions.read(threadId))?.providerSessionId,
replacement?.providerSessionId,
);
assert.equal((yield* registry.resolve(replacementToken!))?.thread.threadId, threadId);
@@ -2261,6 +2268,7 @@ it.effect(
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-superseded-mcp");
const oldSessionId = yield* idAllocator.allocate.providerSession({
@@ -2296,7 +2304,7 @@ it.effect(
const replacementToken = replacement?.authorizationHeader.replace(/^Bearer\s+/, "");
assert.isDefined(replacementToken);
assert.equal(
McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId,
(yield* mcpSessions.read(threadId))?.providerSessionId,
replacement?.providerSessionId,
);
@@ -2305,7 +2313,7 @@ it.effect(
yield* manager.detach({ providerSessionId: oldSessionId, threadId });
assert.equal(
McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId,
(yield* mcpSessions.read(threadId))?.providerSessionId,
replacement?.providerSessionId,
);
assert.equal((yield* registry.resolve(replacementToken!))?.thread.threadId, threadId);
@@ -2337,6 +2345,7 @@ it.effect(
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-stable-mcp");
const providerSessionId = yield* idAllocator.allocate.providerSession({
@@ -2379,7 +2388,7 @@ it.effect(
runtimePolicy,
});
assert.equal(
McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId,
(yield* mcpSessions.read(threadId))?.providerSessionId,
original?.providerSessionId,
"re-attach must reuse the existing credential, not rotate it",
);
@@ -2415,6 +2424,7 @@ it.effect(
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-stale-record");
const s1 = yield* idAllocator.allocate.providerSession({
@@ -2437,7 +2447,7 @@ it.effect(
// The credential dies externally, so S2's attach must rotate to C2.
yield* registry.revokeThread(threadId);
yield* manager.open({ threadId, providerSessionId: s2, modelSelection, runtimePolicy });
const rotated = McpProviderSession.readMcpProviderSession(threadId);
const rotated = yield* mcpSessions.read(threadId);
assert.isDefined(rotated);
const rotatedToken = rotated?.authorizationHeader.replace(/^Bearer\s+/, "");
assert.isDefined(yield* registry.resolve(rotatedToken!));
@@ -2470,6 +2480,7 @@ it.effect(
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-open-race");
const s1 = yield* idAllocator.allocate.providerSession({
@@ -2498,7 +2509,7 @@ it.effect(
yield* Ref.set(duringOpen, manager.close(s1).pipe(Effect.orDie));
yield* manager.open({ threadId, providerSessionId: s2, modelSelection, runtimePolicy });
const slot = McpProviderSession.readMcpProviderSession(threadId);
const slot = yield* mcpSessions.read(threadId);
assert.equal(
slot?.providerSessionId,
original?.providerSessionId,
@@ -2542,6 +2553,7 @@ it.effect("ProviderSessionManagerV2 terminal detach revokes the thread's MCP cre
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-terminal-detach");
const providerSessionId = yield* idAllocator.allocate.providerSession({
@@ -2566,7 +2578,7 @@ it.effect("ProviderSessionManagerV2 terminal detach revokes the thread's MCP cre
revokeMcpCredential: true,
});
assert.isUndefined(yield* registry.resolve(token!));
assert.isUndefined(McpProviderSession.readMcpProviderSession(threadId));
assert.isUndefined(yield* mcpSessions.read(threadId));
});
yield* effect.pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1_000, mcpConfigs })));
@@ -40,7 +40,7 @@ import {
} from "../observability/Metrics.ts";
import { ProviderWorkspaceMissingError } from "../provider/Errors.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ServerSettings from "../serverSettings.ts";
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
import * as EventSink from "./EventSink.ts";
@@ -331,6 +331,7 @@ export const layerWithOptions = (
| EventSink.EventSinkV2
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| McpSessionRegistry.McpSessionRegistry
| ProjectionStore.ProjectionStoreV2
| ProviderEventIngestor.ProviderEventIngestorV2
@@ -342,6 +343,7 @@ export const layerWithOptions = (
const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2;
const fileSystem = yield* FileSystem.FileSystem;
const mcpSessionRegistry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
/**
* Optional so the many focused tests that assemble this layer by hand do
* not each need a settings stub; the production composition always
@@ -472,10 +474,9 @@ export const layerWithOptions = (
providerInstanceId: ProviderInstanceId,
): Effect.Effect<PreparedMcpCredential> =>
options.configureMcp === false
? Effect.sync((): PreparedMcpCredential => {
McpProviderSession.clearMcpProviderSession(threadId);
return { mcpCredentialId: undefined, issued: false };
})
? mcpSessions
.clear(threadId)
.pipe(Effect.as<PreparedMcpCredential>({ mcpCredentialId: undefined, issued: false }))
: mcpPrepareLock.withLock(
threadId,
Effect.gen(function* () {
@@ -492,7 +493,7 @@ export const layerWithOptions = (
>(["orchestration", "worktree", "pull-requests"]);
if (browserToolsAvailable) capabilities.add("preview");
if (deviceToolsAvailable) capabilities.add("device");
const existing = McpProviderSession.readMcpProviderSession(threadId);
const existing = yield* mcpSessions.read(threadId);
if (existing !== undefined) {
// Reserve before the async resolve so a release cannot
// revoke the credential between validation and reservation.
@@ -529,7 +530,7 @@ export const layerWithOptions = (
browserToolsAvailable,
capabilities,
});
McpProviderSession.setMcpProviderSession(credential.config);
yield* mcpSessions.set(credential.config);
reserveMcpCredential(threadId, credential.config.providerSessionId);
return { mcpCredentialId: credential.config.providerSessionId, issued: true };
}),
@@ -544,19 +545,12 @@ export const layerWithOptions = (
mcpCredentialId === undefined
? mcpSessionRegistry
.revokeThread(threadId)
.pipe(
Effect.tap(() =>
Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId)),
),
)
.pipe(Effect.tap(() => mcpSessions.clear(threadId)))
: mcpSessionRegistry.revokeProviderSession(mcpCredentialId).pipe(
Effect.tap(() =>
Effect.sync(() => {
if (
McpProviderSession.readMcpProviderSession(threadId)?.providerSessionId ===
mcpCredentialId
) {
McpProviderSession.clearMcpProviderSession(threadId);
Effect.gen(function* () {
if ((yield* mcpSessions.read(threadId))?.providerSessionId === mcpCredentialId) {
yield* mcpSessions.clear(threadId);
}
}),
),
@@ -1,4 +1,5 @@
import { limitRecoveryCommand } from "./UsageLimitRecoveryWorker.ts";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
@@ -272,6 +273,7 @@ const layerTest = Layer.mergeAll(
ThreadCommandExecutor.layer,
).pipe(
Layer.provide(McpSessionRegistryTestkit.layer),
Layer.provide(McpProviderSessions.layer),
Layer.provide(SqlitePersistence.layerMemory),
Layer.provide(layerCheckpointStoreTest),
Layer.provide(layerServerConfig),
@@ -284,6 +286,7 @@ const layerTest = Layer.mergeAll(
const layerLegacyImportTest = RuntimeLayer.layer.pipe(
Layer.provide(McpSessionRegistryTestkit.layer),
Layer.provide(McpProviderSessions.layer),
Layer.provideMerge(SqlitePersistence.layerMemory),
Layer.provide(layerCheckpointStoreTest),
Layer.provide(layerServerConfig),
@@ -323,6 +326,7 @@ const layerProjectDeletionTest = Layer.mergeAll(
}),
),
Layer.provide(McpSessionRegistryTestkit.layer),
Layer.provide(McpProviderSessions.layer),
Layer.provide(SqlitePersistence.layerMemory),
Layer.provide(layerCheckpointStoreTest),
Layer.provide(layerServerConfig),
@@ -467,6 +471,7 @@ const layerSharedApplicationDataPlaneTest = Layer.mergeAll(
}),
),
Layer.provide(McpSessionRegistryTestkit.layer),
Layer.provide(McpProviderSessions.layer),
Layer.provideMerge(SqlitePersistence.layerMemory),
Layer.provide(layerCheckpointStoreTest),
Layer.provide(layerServerConfig),
@@ -16,6 +16,7 @@ import * as ServerConfig from "../../config.ts";
import * as SqlitePersistence from "../../persistence/Sqlite.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as ThreadManagementService from "../ThreadManagementService.ts";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as McpSessionRegistryTestkit from "../../mcp/McpSessionRegistry.testkit.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
@@ -170,7 +171,11 @@ export interface OrchestratorV2ProviderReplayHarness<
readonly makeProviderAdapterRegistryLayer: (
transcript: Transcript,
options?: { readonly replayGate?: ProviderReplayGate },
) => Layer.Layer<ProviderAdapterRegistry.ProviderAdapterRegistryV2, Error>;
) => Layer.Layer<
ProviderAdapterRegistry.ProviderAdapterRegistryV2,
Error,
McpProviderSessions.McpProviderSessions
>;
}
export function runOrchestratorV2ProviderReplayScenario<
@@ -249,7 +254,11 @@ export function layerProviderReplay<Transcript extends ProviderReplayTranscript,
export function layerWithRegistry<Error>(
scenario: Pick<OrchestratorV2ProviderReplayScenario, "name" | "runtimePolicyOverride">,
registryLayer: Layer.Layer<ProviderAdapterRegistry.ProviderAdapterRegistryV2, Error>,
registryLayer: Layer.Layer<
ProviderAdapterRegistry.ProviderAdapterRegistryV2,
Error,
McpProviderSessions.McpProviderSessions
>,
options: {
readonly databaseLayer?: Layer.Layer<
SqlClient.SqlClient,
@@ -286,7 +295,9 @@ export function layerWithRegistry<Error>(
// runtimeLayer.ts; layer memoization keeps it a single instance.
const layerContinuationRequests =
options.runContinuationWorker === true ? ProviderContinuationRequests.layer : Layer.empty;
const layerProvidedRegistry = registryLayer.pipe(Layer.provide(layerContinuationRequests));
const layerProvidedRegistry = registryLayer.pipe(
Layer.provide(Layer.merge(layerContinuationRequests, McpProviderSessions.layer)),
);
const layerServerSettings = ServerSettings.layerTest({
responseStreamingMode: "turn",
...(options.continueThreadsAfterServerUpdate === undefined
@@ -347,6 +358,7 @@ export function layerWithRegistry<Error>(
layerProvidedRegistry,
layerEventSinkProvided,
IdAllocator.layer,
McpProviderSessions.layer,
McpSessionRegistryTestkit.layer,
layerProviderEventIngestorProvided,
layerStores,
@@ -30,6 +30,7 @@ import {
resolveAntigravityInstanceDirectories,
} from "../antigravityAuthSupport.ts";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ModelManifest from "../ModelManifest.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import { AntigravityDriver } from "./AntigravityDriver.ts";
@@ -264,6 +265,7 @@ const layerDeps = ServerConfig.layerTest(process.cwd(), {
),
Layer.provideMerge(ModelManifest.layerTest),
Layer.provideMerge(IdAllocator.layer),
Layer.provideMerge(McpProviderSessions.layer),
);
const layerTest = ProviderHostLive.layer.pipe(
Layer.provideMerge(ServerSecretStore.layer),
@@ -1,4 +1,5 @@
import { withAgentDeviceEnvironment } from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { AntigravitySettings, ProviderDriverKind, ProviderSetupError } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
@@ -73,6 +74,7 @@ export type AntigravityDriverEnv =
| Crypto.Crypto
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| ModelCatalog.ModelCatalog
| Path.Path
| ProviderEventLoggers.ProviderEventLoggers;
@@ -27,6 +27,7 @@ import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as ModelManifest from "../ModelManifest.ts";
import {
@@ -45,6 +46,7 @@ const layerDeps = ServerConfig.layerTest(process.cwd(), {
}).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(IdAllocator.layer),
Layer.provideMerge(McpProviderSessions.layer),
Layer.provideMerge(
Layer.mock(CodexAdapterV2.CodexAppServerClientFactory)({
open: () => Effect.die("Maintenance resolution must not open a Codex session"),
@@ -36,6 +36,7 @@ import {
ProviderInstanceId,
} from "@t3tools/contracts";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import type { GrokSettings } from "@t3tools/provider-grok/settings";
import type { CursorSettings } from "@t3tools/provider-cursor/settings";
import { HostProcessPlatform, isHostWindows } from "@t3tools/shared/hostProcess";
@@ -230,6 +231,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
),
),
Layer.provideMerge(ProviderLatestVersions.layer),
Layer.provideMerge(McpProviderSessions.layer),
Layer.provideMerge(ModelManifest.layerTest),
Layer.provideMerge(ResetCreditCoordinator.layerTest),
);
@@ -612,6 +614,7 @@ describe("ProviderInstanceRegistry — all drivers slice", () => {
),
),
Layer.provideMerge(ProviderLatestVersions.layer),
Layer.provideMerge(McpProviderSessions.layer),
Layer.provideMerge(ModelManifest.layerTest),
Layer.provideMerge(ResetCreditCoordinator.layerTest),
);
@@ -46,6 +46,7 @@ import * as ModelManifest from "./ModelManifest.ts";
import { applyProviderCompatibility } from "./providerCompatibility.ts";
import * as ResetCreditCoordinator from "./resetCreditCoordinator.ts";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime";
import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
@@ -2761,6 +2762,7 @@ it.layer(
),
),
Layer.provideMerge(ProviderLatestVersions.layer),
Layer.provideMerge(McpProviderSessions.layer),
Layer.provideMerge(ModelManifest.layerTest),
Layer.provideMerge(ResetCreditCoordinator.layerTest),
Layer.provideMerge(
@@ -2865,6 +2867,7 @@ it.layer(
),
),
Layer.provideMerge(ProviderLatestVersions.layer),
Layer.provideMerge(McpProviderSessions.layer),
Layer.provideMerge(ModelManifest.layerTest),
Layer.provideMerge(ResetCreditCoordinator.layerTest),
Layer.provideMerge(
@@ -2984,6 +2987,7 @@ it.layer(
),
),
Layer.provideMerge(ProviderLatestVersions.layer),
Layer.provideMerge(McpProviderSessions.layer),
Layer.provideMerge(ModelManifest.layerTest),
Layer.provideMerge(ResetCreditCoordinator.layerTest),
Layer.provideMerge(
@@ -3043,6 +3047,7 @@ it.layer(
),
),
Layer.provideMerge(ProviderLatestVersions.layer),
Layer.provideMerge(McpProviderSessions.layer),
Layer.provideMerge(ModelManifest.layerTest),
Layer.provideMerge(ResetCreditCoordinator.layerTest),
Layer.provideMerge(
+2
View File
@@ -45,6 +45,7 @@ import * as ModelManifest from "./provider/ModelManifest.ts";
import * as ResetCreditCoordinator from "./provider/resetCreditCoordinator.ts";
import * as EventNdjsonLogger from "./provider/EventNdjsonLogger.ts";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime";
import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger";
import * as ProviderHostLive from "./provider/ProviderHostLive.ts";
@@ -636,6 +637,7 @@ const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe(
ModelManifest.layerModelCatalog.pipe(Layer.provideMerge(ModelManifest.layer)),
ResetCreditCoordinator.layer,
ProviderLatestVersions.layer,
McpProviderSessions.layer,
),
),
// `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
@@ -18,6 +18,7 @@ import type * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/process";
import * as EffectAcpErrors from "effect-acp/errors";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import {
normalizeAcpRegistryCommands,
@@ -259,6 +260,7 @@ export type AcpRegistryAdapterV2DriverEnv =
| AcpRegistrySupport.AcpRegistryCatalog
| IdAllocator.IdAllocatorV2
| Path.Path
| McpProviderSessions.McpProviderSessions
| ProviderEventLoggers.ProviderEventLoggers
| ProviderHost.ProviderHost;
+58 -43
View File
@@ -59,6 +59,7 @@ import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/tool
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import { makeAcpMcpOverAcpBridge, type AcpMcpOverAcpBridge } from "./mcpOverAcpBridge.ts";
import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import {
applyAcpAgentTerminalUpdate,
@@ -677,9 +678,10 @@ interface AcpMcpContext {
readonly authorization?: string;
}
function acpMcpContext(threadId: ThreadId | null, self: SelfInvocation): AcpMcpContext {
if (threadId === null) return { servers: [], acpServers: [] };
const session = McpProviderSession.readMcpProviderSession(threadId);
function acpMcpContext(
session: McpProviderSession.McpProviderSessionConfig | undefined,
self: SelfInvocation,
): AcpMcpContext {
if (session === undefined) {
return { servers: [], acpServers: [] };
}
@@ -714,15 +716,7 @@ function acpMcpContext(threadId: ThreadId | null, self: SelfInvocation): AcpMcpC
};
}
function acpMcpServers(
threadId: ThreadId | null,
self: SelfInvocation,
): ReadonlyArray<EffectAcpSchema.McpServer> {
return acpMcpContext(threadId, self).servers;
}
function acpMcpActivation(threadId: ThreadId | null, self: SelfInvocation) {
const context = acpMcpContext(threadId, self);
function acpMcpActivation(context: AcpMcpContext) {
return { mcpServers: context.servers, acpMcpServers: context.acpServers };
}
@@ -1494,7 +1488,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const host = yield* ProviderHost.ProviderHost;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const { flavor, selfInvocation: self } = options;
const readMcpContext = (threadId: ThreadId | null) =>
threadId === null
? Effect.succeed(acpMcpContext(undefined, self))
: mcpSessions.read(threadId).pipe(Effect.map((session) => acpMcpContext(session, self)));
const driver = flavor.driver;
const continuationRequests = options.continuationRequests;
const postSettleContinuationEnabled =
@@ -1550,32 +1549,32 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
readonly sessionId: string | null;
}
let pendingTerminalEnvironment: PendingTerminalEnvironment | null = {
environment: acpMcpContext(input.threadId, self).processEnvironment,
environment: (yield* readMcpContext(input.threadId)).processEnvironment,
claimUnknownSession: input.initialNativeThreadId === undefined,
sessionId: input.initialNativeThreadId ?? null,
};
const prepareTerminalEnvironment = (
threadId: ThreadId | null,
mcpContext: AcpMcpContext,
sessionId?: string,
): void => {
pendingTerminalEnvironment = {
environment: acpMcpContext(threadId, self).processEnvironment,
environment: mcpContext.processEnvironment,
claimUnknownSession: false,
sessionId: sessionId ?? null,
};
};
const prepareClaimableTerminalEnvironment = (threadId: ThreadId | null): void => {
const prepareClaimableTerminalEnvironment = (mcpContext: AcpMcpContext): void => {
pendingTerminalEnvironment = {
environment: acpMcpContext(threadId, self).processEnvironment,
environment: mcpContext.processEnvironment,
claimUnknownSession: true,
sessionId: null,
};
};
const rememberTerminalEnvironment = (
sessionId: string,
threadId: ThreadId | null,
mcpContext: AcpMcpContext,
): void => {
const environment = acpMcpContext(threadId, self).processEnvironment;
const environment = mcpContext.processEnvironment;
pendingTerminalEnvironment = null;
if (environment === undefined) {
terminalEnvironmentBySessionId.delete(sessionId);
@@ -2097,12 +2096,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
).pipe(Effect.asVoid);
const makeRuntimeInput = (
runtimeGeneration: number,
threadId: ThreadId | null,
mcpContext: AcpMcpContext,
resumeSessionId?: string,
onTermination: AcpAdapterV2RuntimeInput["onTermination"] = () =>
handleRuntimeTerminationAtGeneration(runtimeGeneration),
): AcpAdapterV2RuntimeInput => {
const mcpContext = acpMcpContext(threadId, self);
return {
cwd: input.runtimePolicy.cwd ?? process.cwd(),
runtimePolicy: input.runtimePolicy,
@@ -5989,10 +5987,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
/** Builds the MCP-over-ACP bridge for one runtime, disposed with that runtime's scope. */
const makeRuntimeMcpBridge = Effect.fnUntraced(function* (
threadId: ThreadId | null,
mcpContext: AcpMcpContext,
scope: Scope.Scope,
) {
const mcpContext = acpMcpContext(threadId, self);
if (mcpContext.endpoint === undefined || mcpContext.authorization === undefined) {
return undefined;
}
@@ -6013,10 +6010,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
yield* Scope.close(runtimeScope, Exit.void);
}
runtimeScope = yield* Scope.make();
runtimeMcpBridge = yield* makeRuntimeMcpBridge(threadId, runtimeScope);
const mcpContext = yield* readMcpContext(threadId);
runtimeMcpBridge = yield* makeRuntimeMcpBridge(mcpContext, runtimeScope);
const runtimeGeneration = yield* Ref.get(runtimeCallbackGeneration);
runtime = yield* flavor
.makeRuntime(makeRuntimeInput(runtimeGeneration, threadId, resumeSessionId))
.makeRuntime(makeRuntimeInput(runtimeGeneration, mcpContext, resumeSessionId))
.pipe(
Effect.provideService(Scope.Scope, runtimeScope),
Effect.provideService(Crypto.Crypto, crypto),
@@ -6084,12 +6082,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
});
let replacementMcpBridge: AcpMcpOverAcpBridge | undefined;
const startup = Effect.gen(function* () {
replacementMcpBridge = yield* makeRuntimeMcpBridge(threadId, replacementScope);
const mcpContext = yield* readMcpContext(threadId);
replacementMcpBridge = yield* makeRuntimeMcpBridge(mcpContext, replacementScope);
const replacementRuntime = yield* flavor
.makeRuntime(
makeRuntimeInput(
replacementGeneration,
threadId,
mcpContext,
undefined,
handleCandidateTermination,
),
@@ -6150,7 +6149,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
runtimeScope = replacementScope;
runtimeMcpBridge = replacementMcpBridge;
yield* Ref.set(runtimeCallbackGeneration, replacementGeneration);
prepareTerminalEnvironment(threadId, replacementExit.value.started.sessionId);
prepareTerminalEnvironment(
yield* readMcpContext(threadId),
replacementExit.value.started.sessionId,
);
yield* wireAcpRuntimeTerminalHandlers(replacementExit.value.replacementRuntime);
yield* commitSessionState(replacementExit.value.started);
while (true) {
@@ -6224,12 +6226,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
});
itemIdentityVersion = 2;
yield* Ref.set(runtimeRestartRequired, false);
prepareClaimableTerminalEnvironment(input.threadId);
prepareClaimableTerminalEnvironment(yield* readMcpContext(input.threadId));
return yield* startAcpRuntime(input.threadId);
});
yield* Ref.set(activeSessionId, started.sessionId);
yield* Ref.set(activeSessionSetup, started);
rememberTerminalEnvironment(started.sessionId, input.threadId);
rememberTerminalEnvironment(started.sessionId, yield* readMcpContext(input.threadId));
const capabilities = negotiatedCapabilities(flavor.capabilities, started);
const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true;
const canResumeSession =
@@ -6250,8 +6252,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
if (initialFailure !== undefined) {
return yield* initialFailure;
}
const activationOptions = acpMcpActivation(threadId, self);
prepareTerminalEnvironment(threadId, sessionId);
const mcpContext = yield* readMcpContext(threadId);
const activationOptions = acpMcpActivation(mcpContext);
prepareTerminalEnvironment(mcpContext, sessionId);
const activated = canLoadSession
? yield* runtime.loadSession(sessionId, activationOptions)
: canResumeSession
@@ -6260,7 +6263,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
driver,
detail: `ACP driver cannot load or resume session ${sessionId}`,
});
rememberTerminalEnvironment(activated.sessionId, threadId);
rememberTerminalEnvironment(activated.sessionId, yield* readMcpContext(threadId));
return activated;
});
@@ -6771,7 +6774,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
const prompt: Array<EffectAcpSchema.ContentBlock> = [];
const instructionState = {
interactionMode: turnInput.runtimePolicy.interactionMode,
hasT3Mcp: acpMcpServers(turnInput.threadId, self).length > 0,
hasT3Mcp: (yield* readMcpContext(turnInput.threadId)).servers.length > 0,
} satisfies T3AcpInstructionState;
const previousInstructionState = (yield* Ref.get(promptInstructionStates)).get(sessionId);
const messageText = providerMessageTextWithAttachmentPaths({
@@ -7820,14 +7823,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
loadingMessageId: null,
loadingIndex: 0,
});
prepareTerminalEnvironment(snapshotInput.providerThread.appThreadId, sessionId);
const mcpContext = yield* readMcpContext(
snapshotInput.providerThread.appThreadId,
);
prepareTerminalEnvironment(mcpContext, sessionId);
const activated = yield* runtime.loadSession(
sessionId,
acpMcpActivation(snapshotInput.providerThread.appThreadId, self),
acpMcpActivation(mcpContext),
);
rememberTerminalEnvironment(
activated.sessionId,
snapshotInput.providerThread.appThreadId,
yield* readMcpContext(snapshotInput.providerThread.appThreadId),
);
yield* Ref.set(activeSessionId, activated.sessionId);
yield* Ref.set(activeSessionSetup, activated);
@@ -7883,14 +7889,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
// loading any of the rolled-back conversation.
yield* awaitRuntimeTeardown();
itemIdentityVersion = 2;
prepareTerminalEnvironment(rollbackInput.providerThread.appThreadId);
prepareTerminalEnvironment(
yield* readMcpContext(rollbackInput.providerThread.appThreadId),
);
const replacement = yield* startReplacementAcpRuntime(
rollbackInput.providerThread.appThreadId,
(candidate) =>
Effect.gen(function* () {
rememberTerminalEnvironment(
candidate.sessionId,
rollbackInput.providerThread.appThreadId,
yield* readMcpContext(rollbackInput.providerThread.appThreadId),
);
yield* Ref.set(runtimeRestartRequired, false);
yield* Ref.set(activeSessionId, candidate.sessionId);
@@ -7983,12 +7991,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
driver,
forkInput.sourceProviderThread,
);
prepareTerminalEnvironment(forkInput.targetThreadId);
const mcpContext = yield* readMcpContext(forkInput.targetThreadId);
prepareTerminalEnvironment(mcpContext);
const forked = yield* runtime.forkSession(
sourceSessionId,
acpMcpActivation(forkInput.targetThreadId, self),
acpMcpActivation(mcpContext),
);
rememberTerminalEnvironment(
forked.sessionId,
yield* readMcpContext(forkInput.targetThreadId),
);
rememberTerminalEnvironment(forked.sessionId, forkInput.targetThreadId);
yield* Ref.set(activeSessionId, forked.sessionId);
yield* Ref.set(activeSessionSetup, forked);
yield* Ref.set(activeSelection, null);
@@ -8051,4 +8063,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
});
});
export type AcpAdapterV2Env = FileSystem.FileSystem | IdAllocator.IdAllocatorV2;
export type AcpAdapterV2Env =
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions;
+4
View File
@@ -63,6 +63,10 @@
"types": "./src/server/managedProvider.ts",
"import": "./src/server/managedProvider.ts"
},
"./server/McpProviderSessions": {
"types": "./src/server/McpProviderSessions.ts",
"import": "./src/server/McpProviderSessions.ts"
},
"./server/mcpSession": {
"types": "./src/server/mcpSession.ts",
"import": "./src/server/mcpSession.ts"
@@ -0,0 +1,40 @@
/**
* The T3 MCP credential each thread's provider session should expose to its
* agent. The session manager writes it before a session starts; adapters read
* it when they build provider launch options.
*
* @module provider-core/server/McpProviderSessions
*/
import type { ThreadId } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import type { McpProviderSessionConfig } from "./mcpSession.ts";
export class McpProviderSessions extends Context.Service<
McpProviderSessions,
{
readonly set: (config: McpProviderSessionConfig) => Effect.Effect<void>;
readonly read: (threadId: ThreadId) => Effect.Effect<McpProviderSessionConfig | undefined>;
readonly clear: (threadId: ThreadId) => Effect.Effect<void>;
}
>()("@t3tools/provider-core/server/McpProviderSessions") {}
const make = Effect.gen(function* () {
const sessions = yield* Ref.make(new Map<ThreadId, McpProviderSessionConfig>());
return McpProviderSessions.of({
set: (config) =>
Ref.update(sessions, (current) => new Map(current).set(config.threadId, config)),
read: (threadId) => Ref.get(sessions).pipe(Effect.map((current) => current.get(threadId))),
clear: (threadId) =>
Ref.update(sessions, (current) => {
const next = new Map(current);
next.delete(threadId);
return next;
}),
});
});
export const layer = Layer.effect(McpProviderSessions, make);
@@ -40,21 +40,3 @@ export function withAgentDeviceEnvironment(
...(shimDir ? { PATH: basePath ? `${shimDir}${separator}${basePath}` : shimDir } : {}),
};
}
const sessionsByThread = new Map<ThreadId, McpProviderSessionConfig>();
export function setMcpProviderSession(config: McpProviderSessionConfig): void {
sessionsByThread.set(config.threadId, config);
}
export function readMcpProviderSession(threadId: ThreadId): McpProviderSessionConfig | undefined {
return sessionsByThread.get(threadId);
}
export function clearMcpProviderSession(threadId: ThreadId): void {
sessionsByThread.delete(threadId);
}
function clearAllMcpProviderSessions(): void {
sessionsByThread.clear();
}
@@ -23,8 +23,8 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import {
cursorMcpServers,
@@ -199,7 +199,12 @@ describe("CursorAdapterV2", () => {
: "failed",
);
assert.isNotNull(rows.at(-1)?.subagent.completedAt);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
),
),
);
it.effect("fails standalone SDK transport diagnostics and sends compaction as /compress", () =>
@@ -344,7 +349,12 @@ describe("CursorAdapterV2", () => {
Stream.runHead,
);
assert.equal(sentMessages[1], "/compress");
}).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
),
),
);
it.effect("projects Cursor directory trees and lint diagnostics as file search results", () =>
@@ -746,7 +756,12 @@ describe("CursorAdapterV2", () => {
},
],
);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
),
),
);
it("maps Cursor auto and model parameters to SDK selections", () => {
@@ -843,6 +858,7 @@ describe("CursorAdapterV2", () => {
},
runtimePolicy: { runtimeMode, interactionMode: "default", cwd: "/workspace" },
threadId: ThreadId.make("thread-cursor-setting-sources"),
mcpSession: undefined,
});
assert.deepEqual(options.local?.settingSources, [
"project",
@@ -856,7 +872,7 @@ describe("CursorAdapterV2", () => {
it("injects thread-scoped MCP credentials without logging them", () => {
const threadId = ThreadId.make("thread-cursor-mcp");
McpProviderSession.setMcpProviderSession({
const mcpSession = {
environmentId: EnvironmentId.make("environment-cursor-mcp"),
threadId,
providerSessionId: "mcp-session-cursor",
@@ -864,40 +880,37 @@ describe("CursorAdapterV2", () => {
endpoint: "http://127.0.0.1:43123/mcp",
authorizationHeader: "Bearer secret-cursor-mcp-token",
browserToolsAvailable: true,
};
assert.deepEqual(cursorMcpServers(mcpSession), {
"t3-code": {
type: "http",
url: "http://127.0.0.1:43123/mcp",
headers: {
Authorization: "Bearer secret-cursor-mcp-token",
},
},
});
try {
assert.deepEqual(cursorMcpServers(threadId), {
"t3-code": {
type: "http",
url: "http://127.0.0.1:43123/mcp",
headers: {
Authorization: "Bearer secret-cursor-mcp-token",
},
},
});
const options = makeCursorAgentOptions({
apiKey: "secret-cursor-api-key",
modelSelection: {
instanceId: ProviderInstanceId.make("cursor"),
model: "composer-2.5",
},
runtimePolicy: {
runtimeMode: "full-access",
interactionMode: "default",
cwd: "/workspace",
},
threadId,
mcpSession,
});
assert.deepEqual(options.mcpServers, cursorMcpServers(mcpSession));
const options = makeCursorAgentOptions({
apiKey: "secret-cursor-api-key",
modelSelection: {
instanceId: ProviderInstanceId.make("cursor"),
model: "composer-2.5",
},
runtimePolicy: {
runtimeMode: "full-access",
interactionMode: "default",
cwd: "/workspace",
},
threadId,
});
assert.deepEqual(options.mcpServers, cursorMcpServers(threadId));
const logged = JSON.stringify(CursorAgentSdk.loggedCursorAgentOptions(options));
assert.notInclude(logged, "secret-cursor-api-key");
assert.notInclude(logged, "secret-cursor-mcp-token");
} finally {
McpProviderSession.clearMcpProviderSession(threadId);
}
const logged = JSON.stringify(CursorAgentSdk.loggedCursorAgentOptions(options));
assert.notInclude(logged, "secret-cursor-api-key");
assert.notInclude(logged, "secret-cursor-mcp-token");
});
it("recognizes direct and SDK-wrapped abort failures as cancellation", () => {
+14 -6
View File
@@ -44,6 +44,7 @@ import * as Stream from "effect/Stream";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import { CursorTransportFailure } from "./transportFailure.ts";
import { cursorSdkModelSelection } from "./sdkModel.ts";
@@ -201,8 +202,9 @@ export function cursorRuntimeAgentPolicy(
};
}
export function cursorMcpServers(threadId: ThreadId): Record<string, McpServerConfig> | undefined {
const session = McpProviderSession.readMcpProviderSession(threadId);
export function cursorMcpServers(
session: McpProviderSession.McpProviderSessionConfig | undefined,
): Record<string, McpServerConfig> | undefined {
if (session === undefined) {
return undefined;
}
@@ -306,9 +308,10 @@ export function makeCursorAgentOptions(input: {
readonly modelSelection: ModelSelection;
readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
readonly threadId: ThreadId;
readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined;
}): AgentOptions {
const policy = cursorRuntimeAgentPolicy(input.runtimePolicy);
const mcpServers = cursorMcpServers(input.threadId);
const mcpServers = cursorMcpServers(input.mcpSession);
return {
model: cursorSdkModelSelection(input.modelSelection),
name: `T3 Code ${input.threadId}`,
@@ -854,6 +857,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const runner = yield* CursorAgentSdk.CursorAgentSdkRunner;
const host = yield* ProviderHost.ProviderHost;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const adapterOptions = options;
const apiKey = adapterOptions.environment.CURSOR_API_KEY?.trim() || undefined;
@@ -2091,6 +2095,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
modelSelection: openInput.modelSelection,
runtimePolicy: openInput.runtimePolicy,
threadId: openInput.threadId,
mcpSession: yield* mcpSessions.read(openInput.threadId),
}),
threadId: openInput.threadId,
providerSessionId: input.providerSessionId,
@@ -2106,6 +2111,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
let cursorSkillNames: ReadonlySet<string> | undefined;
const resolveUserMessage = Effect.fnUntraced(function* (
turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
mcpServers: Record<string, McpServerConfig> | undefined,
) {
const rawText = turnInput.message.text;
if (rawText.trim() === "/compress" && turnInput.message.attachments.length === 0) {
@@ -2135,7 +2141,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
resolveAttachmentPath: host.resolveAttachmentPath,
}),
runOrdinal: turnInput.runOrdinal,
hasT3Mcp: cursorMcpServers(turnInput.threadId) !== undefined,
hasT3Mcp: mcpServers !== undefined,
});
const images = yield* Effect.forEach(
turnInput.message.attachments.filter(isProviderNativeImageAttachment),
@@ -2197,8 +2203,8 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
modelSelection: turnInput.modelSelection,
runtimePolicy: turnInput.runtimePolicy,
});
const message = yield* resolveUserMessage(turnInput);
const mcpServers = cursorMcpServers(turnInput.threadId);
const mcpServers = cursorMcpServers(yield* mcpSessions.read(turnInput.threadId));
const message = yield* resolveUserMessage(turnInput, mcpServers);
const pendingUpdates: Array<InteractionUpdate> = [];
let context: ActiveCursorTurn | null = null;
const sdkRun = yield* agent.session.send({
@@ -2603,6 +2609,7 @@ export type CursorAdapterV2DriverEnv =
| FileSystem.FileSystem
| Path.Path
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| ProviderHost.ProviderHost;
export const CursorAdapterV2Driver: ProviderAdapterDriver<
@@ -2646,6 +2653,7 @@ const layer: Layer.Layer<
| FileSystem.FileSystem
| Path.Path
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| ProviderHost.ProviderHost
> = Layer.effect(
ProviderAdapter.ProviderAdapterV2,
@@ -15,12 +15,14 @@ import { layerTestProviderHost } from "@t3tools/provider-testing/host";
import { CursorDriver } from "./driver.ts";
import * as CursorAgentSdk from "./CursorAgentSdk.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import { Cursor } from "./sdk.ts";
const layerTest = layerTestProviderHost({ runBackgroundWork: false }).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(IdAllocator.layer),
Layer.provideMerge(McpProviderSessions.layer),
Layer.provideMerge(
Layer.mock(CursorAgentSdk.CursorAgentSdkRunner)({
open: () => Effect.die("Maintenance resolution must not open a Cursor session"),
@@ -23,6 +23,7 @@ import type * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/process";
import * as EffectAcpErrors from "effect-acp/errors";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
import {
@@ -352,6 +353,7 @@ export type GrokAdapterV2DriverEnv =
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| Path.Path
| McpProviderSessions.McpProviderSessions
| ProviderEventLoggers.ProviderEventLoggers
| ProviderHost.ProviderHost;
@@ -405,6 +407,7 @@ const layer: Layer.Layer<
| Crypto.Crypto
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| ProviderEventLoggers.ProviderEventLoggers
| ProviderHost.ProviderHost
> = Layer.effect(
@@ -15,10 +15,12 @@ import { layerTestProviderHost } from "@t3tools/provider-testing/host";
import { GrokDriver } from "./driver.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
const layerTest = layerTestProviderHost({ runBackgroundWork: false }).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(IdAllocator.layer),
Layer.provideMerge(McpProviderSessions.layer),
Layer.provideMerge(ProviderLatestVersions.layer),
Layer.provideMerge(
Layer.succeed(
@@ -31,7 +31,7 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import type { MuseItem } from "./protocol.ts";
import type { MuseSdkHost } from "./sdk.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -42,6 +42,7 @@ import { makeMuseAdapterV2, type MuseAdapterV2Options } from "./adapter.ts";
const testLayer = Layer.mergeAll(
NodeServices.layer,
IdAllocator.layer,
McpProviderSessions.layer,
layerTestProviderHost().pipe(Layer.provide(NodeServices.layer)),
);
const MUSE_PROVIDER = ProviderDriverKind.make("muse");
@@ -351,10 +352,7 @@ const approval = (turnId: string) => ({
describe("MuseAdapterV2", () => {
it.effect("connects the thread's MCP credential on native start and resume", () =>
Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.sync(() => McpProviderSession.clearMcpProviderSession(THREAD_ID)),
);
McpProviderSession.setMcpProviderSession({
yield* (yield* McpProviderSessions.McpProviderSessions).set({
environmentId: EnvironmentId.make("test-environment"),
threadId: THREAD_ID,
providerSessionId: "test-session",
@@ -384,10 +382,7 @@ describe("MuseAdapterV2", () => {
it.effect("rejects a host without session MCP support before opening a native session", () =>
Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.sync(() => McpProviderSession.clearMcpProviderSession(THREAD_ID)),
);
McpProviderSession.setMcpProviderSession({
yield* (yield* McpProviderSessions.McpProviderSessions).set({
environmentId: EnvironmentId.make("test-environment"),
threadId: THREAD_ID,
providerSessionId: "test-session",
+4 -2
View File
@@ -37,6 +37,7 @@ import * as Stream from "effect/Stream";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import { museModelCapabilities, resolveMuseReasoningEffort } from "./modelCatalog.ts";
import {
@@ -248,6 +249,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const providerHost = yield* ProviderHost.ProviderHost;
const fileSystem = yield* FileSystem.FileSystem;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const protocolError = (detail: string, payload?: unknown) =>
new ProviderAdapter.ProviderAdapterProtocolError({
@@ -1364,7 +1366,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
);
const launchHost = Effect.fnUntraced(function* () {
const epoch = ++hostEpoch;
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
const mcpSession = yield* mcpSessions.read(input.threadId);
const created = yield* Effect.acquireRelease(
createMuseSdkHostEffect(
{
@@ -1478,7 +1480,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
let missingNativeSession = false;
return yield* Effect.gen(function* () {
nativeSessionId = requestedId ?? host.connection.mintCommandId();
const mcpSession = McpProviderSession.readMcpProviderSession(args.threadId);
const mcpSession = yield* mcpSessions.read(args.threadId);
if (mcpSession && !host.initializeResult.grantedCapabilities.includes("sessionMcp"))
return yield* protocolError(
"Update Muse Code to a version that supports session MCP servers",
@@ -10,6 +10,7 @@ import { ChildProcessSpawner } from "effect/process";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import { makeMuseTextGeneration } from "./textGeneration.ts";
import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
@@ -43,6 +44,7 @@ const decodeMuseSettings = Schema.decodeSync(MuseSettings);
export type MuseDriverEnv =
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| ProviderHost.ProviderHost
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
@@ -36,6 +36,7 @@ import { layerTestProviderHost } from "@t3tools/provider-testing/host";
import type * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import {
advanceOpenCodePromptAdmission,
@@ -378,7 +379,10 @@ describe("OpenCodeAdapterV2", () => {
hasSubagents: false,
},
);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect.each(["permission", "question"] as const)(
@@ -456,7 +460,10 @@ describe("OpenCodeAdapterV2", () => {
deliver = true;
// Failed delivery leaves the request available for an explicit retry.
yield* harness.runtime.respondToRuntimeRequest(response);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("aborts external root and descendants before closing the event stream", () =>
@@ -494,7 +501,10 @@ describe("OpenCodeAdapterV2", () => {
"children:child",
"stream.close",
]);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect.each(["enumeration", "abort", "not-found", "timeout"] as const)(
@@ -548,7 +558,10 @@ describe("OpenCodeAdapterV2", () => {
const result = yield* Fiber.join(stop);
assert.equal(Exit.isSuccess(result), failure === "not-found");
if (failure === "timeout") assert.isTrue(childSignal?.aborted);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect(
@@ -712,7 +725,10 @@ describe("OpenCodeAdapterV2", () => {
const assistant = items.filter((item) => item.type === "assistant_message");
assert.equal(assistant.at(-1)?.text, "Tool results received");
assert.equal(assistant.at(-1)?.status, "completed");
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
// Event order from a live OpenCode 1.18.32 run of a `task` call with
@@ -807,7 +823,10 @@ describe("OpenCodeAdapterV2", () => {
yield* push(status(child, "idle"));
yield* push({ type: "session.idle", properties: { sessionID: child } });
assert.isFalse(yield* hasPendingBackgroundWork, "an idle child must not pin idle release");
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("titles OpenCode reads and searches from their input", () =>
@@ -902,7 +921,10 @@ describe("OpenCodeAdapterV2", () => {
);
assert.ok(emptyWebSearch?.type === "web_search");
assert.equal(emptyWebSearch.results, undefined);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("presents OpenCode MCP calls without treating remote tools as local edits", () =>
@@ -1058,7 +1080,10 @@ describe("OpenCodeAdapterV2", () => {
assert.equal(items[3]?.toolName, "ambiguous_server_edit_document");
assert.isUndefined(items[3]?.toolSource);
assert.equal(statusReads, 1);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect.each(["failure", "timeout"] as const)("retries MCP status after %s", (failure) =>
@@ -1146,7 +1171,10 @@ describe("OpenCodeAdapterV2", () => {
kind: "integration",
});
if (failure === "timeout") assert.isTrue(signal?.aborted);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("admits a native command on its user receipt before generation completes", () =>
@@ -1209,7 +1237,10 @@ describe("OpenCodeAdapterV2", () => {
yield* Fiber.join(start);
assert.equal(promptCalls, 0);
release.resolve();
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("sends unadvertised slash commands as ordinary prompts", () =>
@@ -1236,7 +1267,10 @@ describe("OpenCodeAdapterV2", () => {
});
yield* harness.startTurn("/unknown words");
assert.deepEqual(prompts, [[{ type: "text", text: "/unknown words" }]]);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("compacts with the native summarize API and emits a completed compaction", () =>
@@ -1291,7 +1325,10 @@ describe("OpenCodeAdapterV2", () => {
assert.isTrue(
events.some((event) => event.type === "turn.terminal" && event.status === "completed"),
);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("ends a turn on the provider thread it started on", () =>
@@ -1330,7 +1367,10 @@ describe("OpenCodeAdapterV2", () => {
Stream.runHead,
);
assert.equal(Option.getOrUndefined(terminal)?.providerThreadId, forkedRow.id);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("does not restore messages beyond OpenCode's persisted revert boundary", () =>
@@ -1415,7 +1455,10 @@ describe("OpenCodeAdapterV2", () => {
["user-kept", "assistant-kept"],
);
assert.equal(snapshot.providerThread.nativeConversationHeadRef?.nativeId, "user-kept");
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("keeps a newly admitted prompt alive across stale idle and delayed busy evidence", () =>
@@ -1732,7 +1775,10 @@ describe("OpenCodeAdapterV2", () => {
);
const interrupted = yield* runtime.readThreadSnapshot({ providerThread });
assert.equal(interrupted.providerTurns.at(-1)?.status, "interrupted");
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("interrupts an initial prompt while its SDK request is pending", () =>
@@ -1897,7 +1943,10 @@ describe("OpenCodeAdapterV2", () => {
(event.type === "provider_session.updated" && event.providerSession.status === "error"),
),
);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("fails an active turn when the OpenCode event stream ends cleanly", () =>
@@ -1940,7 +1989,10 @@ describe("OpenCodeAdapterV2", () => {
assert.equal(terminal?.failure?.class, "transport_error");
assert.equal(terminal?.threadDisposition, "broken");
assert.equal((yield* Effect.exit(harness.startTurn()))._tag, "Failure");
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("fails compaction when its response races stream termination", () =>
@@ -2001,7 +2053,10 @@ describe("OpenCodeAdapterV2", () => {
event.turnItem.status === "completed",
),
);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("does not register a turn after the OpenCode event stream ends", () =>
@@ -2059,7 +2114,10 @@ describe("OpenCodeAdapterV2", () => {
assert.isTrue(Exit.isFailure(yield* Fiber.join(start)));
assert.equal(promptCalls, 0);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it("holds stale idle through prompt admission until the new user message is observed", () => {
@@ -2237,7 +2295,10 @@ describe("OpenCodeAdapterV2", () => {
assert.lengthOf(terminals, 1);
assert.equal(terminals[0]?.status, "completed");
assert.isNull(terminals[0]?.failure ?? null);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("does not let a queued status retry adopt a newer steer generation", () =>
@@ -2340,7 +2401,10 @@ describe("OpenCodeAdapterV2", () => {
});
assert.equal(statusCallCount, 1);
assert.equal(afterRetry.providerTurns.at(-1)?.status, "running");
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
it.effect("ignores a delayed status reply after steering starts a newer admission", () =>
@@ -2411,7 +2475,7 @@ describe("OpenCodeAdapterV2", () => {
assert.include(serialized, '"protocol":"opencode-sdk.sse"');
assert.include(serialized, '"method":"session.prompt"');
assert.include(serialized, '"fieldCount":2');
}).pipe(Effect.provide(IdAllocator.layer)),
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
);
it.effect("adopts the handed-over provider thread identity on session create", () =>
@@ -2520,6 +2584,7 @@ describe("OpenCodeAdapterV2", () => {
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
layerTestProviderHost().pipe(Layer.provide(NodeServices.layer)),
),
),
@@ -2718,5 +2783,8 @@ it.effect.each([false, true])(
assert.equal(result.messages.length, 0);
assert.deepEqual(calls, ["fork", "permissions"]);
}
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
}).pipe(
Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
Effect.scoped,
),
);
@@ -55,7 +55,7 @@ import * as Stream from "effect/Stream";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import {
structuralProtocolMethod,
@@ -947,6 +947,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
const runtime = yield* OpenCodeRuntime.OpenCodeRuntime;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const host = yield* ProviderHost.ProviderHost;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
return ProviderAdapter.ProviderAdapterV2.of({
instanceId: options.instanceId,
@@ -971,7 +972,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
: {}),
});
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
const mcpSession = yield* mcpSessions.read(input.threadId);
const hasT3Mcp = mcpSession !== undefined && !connection.external;
const orchestrationSystemPrompt = t3OrchestrationSystemPrompt(hasT3Mcp);
if (hasT3Mcp) {
@@ -3728,6 +3729,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
export type OpenCodeAdapterV2DriverEnv =
| OpenCodeRuntime.OpenCodeRuntime
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| ProviderEventLoggers.ProviderEventLoggers
| ProviderHost.ProviderHost;
@@ -17,6 +17,7 @@ import { ChildProcessSpawner } from "effect/process";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as ProviderMaintenance from "@t3tools/provider-core/server/maintenanceResolver";
import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
@@ -49,6 +50,7 @@ const openCode2Runtime = {
const layer = Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
ProviderLatestVersions.layer,
layerTestProviderHost(),
Layer.succeed(
@@ -212,6 +214,7 @@ const changingRuntime = {
} as unknown as OpenCodeRuntime.OpenCodeRuntimeShape;
const layerUpdate = Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
ProviderLatestVersions.layer,
layerTestProviderHost(),
Layer.succeed(
@@ -74,7 +74,7 @@ import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as OpenCode2Client from "./OpenCode2Client.ts";
import * as OpenCode2Server from "./OpenCode2Server.ts";
import * as OpenCodeRuntime from "../OpenCodeRuntime.ts";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import { t3OrchestrationSystemPrompt } from "@t3tools/provider-core/server/orchestrationInstructions";
import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens";
@@ -831,6 +831,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
const server = yield* OpenCode2Server.OpenCode2Server;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const host = yield* ProviderHost.ProviderHost;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
const crypto = yield* Crypto.Crypto;
const driver = OPENCODE_PROVIDER;
@@ -3251,7 +3252,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
state: ThreadState,
turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
) {
const mcpSession = McpProviderSession.readMcpProviderSession(turnInput.threadId);
const mcpSession = yield* mcpSessions.read(turnInput.threadId);
const directory = turnInput.runtimePolicy.cwd ?? host.paths.cwd;
const name = yield* mcpServerNameFor(turnInput.threadId);
// An external server may not reach T3's MCP endpoint, as with 1.x.
@@ -33,7 +33,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import { handoffBudget } from "@t3tools/provider-core/server/handoffBudget";
@@ -49,6 +49,7 @@ import { makePiRpcConnection, type PiRpcRecord } from "./rpc.ts";
const layerTest = Layer.mergeAll(
NodeServices.layer,
IdAllocator.layer,
McpProviderSessions.layer,
layerTestProviderHost().pipe(Layer.provide(NodeServices.layer)),
);
@@ -1285,7 +1286,7 @@ describe("PiAdapterV2", () => {
it.effect("injects the T3 MCP extension and bearer when a session exists", () =>
Effect.gen(function* () {
McpProviderSession.setMcpProviderSession({
yield* (yield* McpProviderSessions.McpProviderSessions).set({
environmentId: EnvironmentId.make("environment-pi-mcp"),
threadId: THREAD_ID,
providerSessionId: "mcp-session-pi",
@@ -1306,11 +1307,7 @@ describe("PiAdapterV2", () => {
assert.equal(spawn.env.T3_MCP_URL, "http://127.0.0.1:43123/mcp");
assert.equal(spawn.env.T3_MCP_BEARER_TOKEN, "secret-pi-token");
assert.equal(spawn.env.T3_PI_RUNTIME_MODE, "full-access");
}).pipe(
Effect.ensuring(Effect.sync(() => McpProviderSession.clearMcpProviderSession(THREAD_ID))),
Effect.scoped,
Effect.provide(layerTest),
),
}).pipe(Effect.scoped, Effect.provide(layerTest)),
);
it.effect("rejects a resume while a turn is active", () =>
+4 -2
View File
@@ -62,7 +62,7 @@ import { ChildProcessSpawner } from "effect/process";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { parsePiCompactCommand, type PiCompactCommand } from "./commands.ts";
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -390,6 +390,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const host = yield* ProviderHost.ProviderHost;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const { continuationRequests } = options;
const protocolError = (detail: string, payload?: unknown) =>
@@ -409,7 +410,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
) {
const scope = yield* Effect.scope;
const cwd = input.runtimePolicy.cwd ?? host.paths.cwd;
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
const mcpSession = yield* mcpSessions.read(input.threadId);
const provideCacheFs = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem>) =>
effect.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
@@ -3261,6 +3262,7 @@ export type PiAdapterV2DriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| ProviderHost.ProviderHost;
export const PiAdapterV2Driver: ProviderAdapterDriver<PiSettings, PiAdapterV2DriverEnv> = {
@@ -15,6 +15,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
import type { PiSettings } from "../settings.ts";
import { PiDriver } from "./driver.ts";
@@ -26,6 +27,7 @@ const layerTest = Layer.mergeAll(
runBackgroundWork: false,
}),
IdAllocator.layer,
McpProviderSessions.layer,
ProviderLatestVersions.layer,
Layer.succeed(
HttpClient.HttpClient,