diff --git a/.github/fork-seams.json b/.github/fork-seams.json index c6f865372994..c734f19ef72c 100644 --- a/.github/fork-seams.json +++ b/.github/fork-seams.json @@ -193,14 +193,10 @@ }, "apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts": { "why": "MCP profiles part 5: each Codex thread gets its profile's outside MCP servers switched off in its own per-thread config (mcp_servers..enabled = false for every server Codex's config/read lists for the thread's folder that the profile leaves out, launch-argument servers included; T3's own entries stay), and a turn is refused, saying why and the fix, when the thread's live servers (mcpServerStatus/list) still include one outside its profile. The adapter's app-server client factory is wrapped by apps/server/src/fork/codexMcpProfile.ts; the overrides travel per request, so other threads on the shared app-server keep their own sets. Additions only; tested in apps/server/src/fork/codexMcpProfile.test.ts.", - "added": [], - "announced": { - "since": "2026-11-21", - "added": [ - "import * as CodexMcpProfile from \"../../fork/codexMcpProfile.ts\"; // Fork: MCP profiles", - "...(yield* CodexMcpProfile.profiledClientFactory(clientFactory)), // Fork: MCP profiles" - ] - } + "added": [ + "import * as CodexMcpProfile from \"../../fork/codexMcpProfile.ts\"; // Fork: MCP profiles", + "...(yield* CodexMcpProfile.profiledClientFactory(clientFactory)), // Fork: MCP profiles" + ] }, "apps/server/src/orchestration-v2/ProviderTurnStartService.ts": { "why": "MCP profiles part 2: a Claude turn its MCP profile refuses never reached Claude, like the other refusals in this list.", diff --git a/FORK_CHANGES.md b/FORK_CHANGES.md index 79d3a5c548b3..a36f77c2a81b 100644 --- a/FORK_CHANGES.md +++ b/FORK_CHANGES.md @@ -33,7 +33,7 @@ setting is missing here or a setting named here does not exist. | A local, read-only "is T3 busy?" answer: `GET /api/fork/activity` on loopback, and `t3 __fork-report --base-dir --activity`, which asks it and exits 0 only when nothing is working. | A host quiet check reads T3's own turns and approvals instead of guessing from processes. | `server.activityProbe` | off | [#547](https://github.com/scuttletoby/t3code/pull/547) | | `t3 serve --hold-work` starts a server on a copy of a T3 home with all agent work and T3 Connect held. | Look at a new build's threads and migrations on a copy before it replaces a running T3. | none | only with the flag | [#175](https://github.com/scuttletoby/t3code/pull/175) | | Docs: one machine for new work through upstream's load-balancing weights; settings saved with an early draft's client setting for it still load. | Upstream already has the feature, so the fork's own setting was removed. | none | - | [#25](https://github.com/scuttletoby/t3code/pull/25) | -| MCP profiles: named profiles (which outside MCP servers and T3 tool groups a thread gets), a default, a sub-agent rule, a pick per thread and the rules that pick one. Claude applies the outside servers and refuses a turn when its profile cannot. A task delegated to another machine carries its parent's profile, and a narrower one goes only to a Claude instance on a machine that applies it (one can refuse such tasks). Only Claude applies profiles: a turn on any other provider whose profile is narrower than `all` is refused as it starts. Settings → Fork lists, adds, edits and deletes profiles, sets the default and the sub-agent rule (also per project) and each thread's pick. | Fewer tools per thread saves tokens and keeps agents from tools they should not use. | `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles`, `server.mcpCarriedProfiles`, `projectOverride.mcpProfile`, `projectOverride.mcpSubagentProfile` | off | [#227](https://github.com/scuttletoby/t3code/pull/227), [#528](https://github.com/scuttletoby/t3code/pull/528), [#640](https://github.com/scuttletoby/t3code/issues/640), [#672](https://github.com/scuttletoby/t3code/issues/672) | +| MCP profiles: named profiles (which outside MCP servers and T3 tool groups a thread gets), a default, a sub-agent rule, a pick per thread and the rules that pick one. Claude and Codex apply the outside servers (Codex per thread on its shared app-server, as `mcp_servers..enabled = false`) and refuse a turn when its profile cannot. A task delegated to another machine carries its parent's profile, and a narrower one goes only to a Claude instance on a machine that applies it (one can refuse such tasks). Only Claude and Codex apply profiles: a turn on any other provider whose profile is narrower than `all` is refused as it starts. Settings → Fork lists, adds, edits and deletes profiles, sets the default and the sub-agent rule (also per project) and each thread's pick. | Fewer tools per thread saves tokens and keeps agents from tools they should not use. | `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles`, `server.mcpCarriedProfiles`, `projectOverride.mcpProfile`, `projectOverride.mcpSubagentProfile` | off | [#227](https://github.com/scuttletoby/t3code/pull/227), [#528](https://github.com/scuttletoby/t3code/pull/528), [#640](https://github.com/scuttletoby/t3code/issues/640), [#672](https://github.com/scuttletoby/t3code/issues/672) | | Playtest mode, part 1: settings for a project's playtest adapter (claim, renew, push and release steps only the person sets) and the contract those steps follow. Nothing starts a session yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#260](https://github.com/scuttletoby/t3code/pull/260) | | Playtest mode, part 2: the session store and service: start (claim), rounds of push steps, end (release), kept across restarts. A session keeps the steps it started with. No tool calls it yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#261](https://github.com/scuttletoby/t3code/pull/261) | | Playtest mode, part 3: the worker renews claims, ends idle, too-long and gone-thread sessions, finishes what a restart cut, and tells the thread once when T3 ended a session. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#262](https://github.com/scuttletoby/t3code/pull/262) | diff --git a/apps/server/src/fork/claudeMcpProfile.ts b/apps/server/src/fork/claudeMcpProfile.ts index 42df3a618a57..1d0517bc5541 100644 --- a/apps/server/src/fork/claudeMcpProfile.ts +++ b/apps/server/src/fork/claudeMcpProfile.ts @@ -15,6 +15,7 @@ import { MCP_CARRIED_PROFILES_REFUSE, MCP_PROFILE_ALL, type OrchestrationV2AppThread, + ProjectId, type ServerSettings, type ThreadId, isDelegatedAppThread, @@ -530,13 +531,8 @@ export const makeMcpProfileSettings = Effect.gen(function* () { type McpOverrides = { readonly mcpServers?: Readonly> | undefined }; -/** - * One settings read, or a refusal, then threads' resolved profiles (or refusals) from it: two - * threads compared against one file. Settings as {@link makeMcpProfileSettings} reads them; without - * the settings service (tests), the default settings' (`all`, cut to a profile another machine - * carried). - */ -export const makeThreadMcpProfileReads = Effect.gen(function* () { +/** {@link makeThreadMcpProfileReads}, and the store's thread reads it uses. */ +const makeLineageReads = Effect.gen(function* () { const settingsService = yield* Effect.serviceOption(ServerSettingsService.ServerSettingsService); const sql = yield* Effect.serviceOption(SqlClient.SqlClient); // The adapter built alone (upstream's adapter tests): default settings and no store, so nothing @@ -562,12 +558,21 @@ export const makeThreadMcpProfileReads = Effect.gen(function* () { ? undefined : () => Effect.succeed(null); const readSettings = yield* makeMcpProfileSettings; - return Effect.map( + const reads = Effect.map( readSettings, (settings) => (thread: LineageThread) => mcpProfileForThread(settings, thread, findThread), ); + return { reads, findThread }; }); +/** + * One settings read, or a refusal, then threads' resolved profiles (or refusals) from it: two + * threads compared against one file. Settings as {@link makeMcpProfileSettings} reads them; without + * the settings service (tests), the default settings' (`all`, cut to a profile another machine + * carried). + */ +export const makeThreadMcpProfileReads = Effect.map(makeLineageReads, ({ reads }) => reads); + /** * A thread's resolved profile, or a refusal, from the settings {@link makeMcpProfileSettings} * reads on each call; see {@link makeThreadMcpProfileReads}. @@ -579,6 +584,32 @@ export const makeThreadMcpProfiles = Effect.gen(function* () { }); }); +/** + * A thread's resolved profile, or a refusal, found by its id alone (a Codex thread request carries + * only the id). A thread the store cannot give refuses, as an unreadable parent does. With no store + * and no settings service (upstream's adapter tests) it is read as a root thread: `all`. + */ +export const makeThreadMcpProfilesById = Effect.gen(function* () { + const { reads, findThread } = yield* makeLineageReads; + return Effect.fn("ClaudeMcpProfile.profileForId")(function* (threadId: ThreadId) { + const read = yield* reads; + if (findThread === undefined) { + return yield* read({ + id: threadId, + projectId: ProjectId.make("unknown-project"), + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + } as LineageThread); + } + const thread = yield* findThread(threadId); + if (thread === null) { + return yield* new ClaudeMcpProfileError({ + reason: `T3 cannot read this thread from its store, so its MCP profile cannot be worked out and it cannot start: retry, or ${FIX}.`, + }); + } + return yield* read(thread); + }); +}); + /** The thread's Claude plan, or a refusal, from {@link makeThreadMcpProfiles}. */ export const makeClaudeMcpProfiles = Effect.gen(function* () { const profileFor = yield* makeThreadMcpProfiles; diff --git a/apps/server/src/fork/codexMcpProfile.test.ts b/apps/server/src/fork/codexMcpProfile.test.ts new file mode 100644 index 000000000000..9d392ef8cb61 --- /dev/null +++ b/apps/server/src/fork/codexMcpProfile.test.ts @@ -0,0 +1,1312 @@ +/** + * Fork: a thread's MCP profile on Codex (MCP profile design, part 5). The wrapped client runs over + * a fake app-server that keeps a config per thread as Codex does: a resume of a loaded thread keeps + * its old config, config/read lists config.toml, launch-argument and project servers, and + * mcpServerStatus/list reports each thread's own servers. + */ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { + CodexSettings, + EventId, + type OrchestrationV2AppThread, + ProjectId, + ProviderInstanceId, + ProviderSessionId, + ProviderThreadId, + ThreadId, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import type * as CodexClient from "effect-codex-app-server/client"; +import * as CodexError from "effect-codex-app-server/errors"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { makeTurnInput } from "../orchestration-v2/Adapters/AcpAdapterV2.testkit.ts"; +import * as CodexAdapterV2 from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import { makeReplayServerConfig } from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as ServerConfig from "../config.ts"; +import * as PortScanner from "../preview/PortScanner.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ServerSettingsService from "../serverSettings.ts"; +import { ClaudeMcpProfileError } from "./claudeMcpProfile.ts"; +import { + codexConfiguredMcpServers, + codexMcpProfileConfig, + codexMcpServersOutsideProfile, + profiledClientFactory, + withCodexMcpProfiles, + type ProfileById, +} from "./codexMcpProfile.ts"; +import type { McpProfileResolved, McpProfileSet } from "./mcpProfile.ts"; + +type Client = CodexClient.CodexAppServerClient["Service"]; +type Json = Record; + +const decodeCodexSettings = Schema.decodeSync(CodexSettings); +const POLICY = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", +}); +const THREAD_KEY = "shell_environment_policy.set.T3CODE_THREAD_ID"; +const T3_SERVER = { url: "http://127.0.0.1:1/mcp", http_headers: { Authorization: "Bearer x" } }; +const FIX = 'pick "all" for this thread, or fix the profile in Settings'; + +/** A thread/start answer as Codex gives it, enough for the adapter to read. */ +const STARTED = { + thread: { + id: "", + sessionId: "session", + projectId: null, + forkedFromId: null, + preview: "", + ephemeral: false, + modelProvider: "openai", + createdAt: 1782622440, + updatedAt: 1782622440, + status: { type: "idle" }, + path: "/tmp/thread.jsonl", + cwd: "/workspace", + cliVersion: "0.144.0", + source: "vscode", + threadSource: null, + agentNickname: null, + agentRole: null, + gitInfo: null, + name: null, + turns: [], + }, + model: "gpt-5.4", + modelProvider: "openai", + serviceTier: null, + cwd: "/workspace", + instructionSources: [], + approvalPolicy: "on-request", + approvalsReviewer: "user", + sandbox: { type: "workspaceWrite", writableRoots: [], networkAccess: false }, + reasoningEffort: "medium", +}; + +interface FakeThread { + readonly id: string; + readonly cwd: string; + config: Json; + loaded: boolean; +} + +/** + * A Codex app-server as far as profiles see it: `servers` config.toml, `launchArgs` `-c` servers, + * `project` each workspace's `.codex/config.toml`, `plugins` servers no config entry switches off, + * `apps` ChatGPT sign-in (adds `codex_apps`, unlisted by config/read, while `features.apps` is on). + * Statuses use Codex's own words. + */ +const makeFakeCodex = ( + setup: { + readonly servers?: ReadonlyArray; + readonly launchArgs?: ReadonlyArray; + readonly project?: Readonly>>; + readonly plugins?: ReadonlyArray; + readonly apps?: boolean; + } = {}, +) => { + const threads = new Map(); + const calls: Array<{ readonly method: string; readonly params: Json }> = []; + /** Methods that fail, or return what `answers` gives instead of the fake's answer. */ + const failing = new Set(); + const answers = new Map(); + /** Requests that say they arrived, then wait on a gate before answering (to stop one half-way). */ + const gates = new Map< + string, + { readonly reached: Deferred.Deferred; readonly open: Deferred.Deferred } + >(); + let next = 0; + let pageSize = 2; + let endlessPages = false; + + const configured = (cwd: string) => [ + ...(setup.servers ?? []), + ...(setup.launchArgs ?? []), + ...(setup.project?.[cwd] ?? []), + ]; + const fail = (method: string) => + new CodexError.CodexAppServerRequestError({ code: -32603, errorMessage: "boom", method }); + const reply = ( + method: string, + params: Json, + ): Effect.Effect => { + if (failing.has(method)) return Effect.fail(fail(method)); + if (answers.has(method)) return Effect.succeed(answers.get(method)); + const thread = (id: unknown) => threads.get(String(id)); + switch (method) { + case "thread/start": { + const id = `native-${++next}`; + const cwd = typeof params.cwd === "string" ? params.cwd : "/workspace"; + threads.set(id, { id, cwd, config: { ...(params.config as Json) }, loaded: true }); + return Effect.succeed({ ...STARTED, cwd, thread: { ...STARTED.thread, id, cwd } }); + } + case "thread/resume": { + const found = thread(params.threadId); + if (found === undefined) return Effect.fail(fail(method)); + // Codex keeps a loaded thread's config: a resume then changes nothing. + if (!found.loaded) { + found.config = { ...(params.config as Json) }; + found.loaded = true; + } + return Effect.succeed({ thread: { id: found.id, cwd: found.cwd } }); + } + case "thread/fork": { + const source = thread(params.threadId); + if (source === undefined) return Effect.fail(fail(method)); + const id = `native-${++next}`; + const cwd = typeof params.cwd === "string" ? params.cwd : source.cwd; + threads.set(id, { id, cwd, config: { ...(params.config as Json) }, loaded: true }); + return Effect.succeed({ thread: { id, cwd } }); + } + case "thread/read": { + const found = thread(params.threadId); + return found === undefined + ? Effect.fail(fail(method)) + : Effect.succeed({ thread: { id: found.id, cwd: found.cwd } }); + } + case "config/read": { + const cwd = typeof params.cwd === "string" ? params.cwd : ""; + return Effect.succeed({ + config: { mcp_servers: Object.fromEntries(configured(cwd).map((name) => [name, {}])) }, + }); + } + case "mcpServerStatus/list": { + const found = thread(params.threadId); + if (found === undefined || !found.loaded) return Effect.fail(fail(method)); + const names = [ + ...configured(found.cwd), + ...(setup.plugins ?? []), + ...(setup.apps === true && found.config["features.apps"] !== false ? ["codex_apps"] : []), + ...Object.keys(found.config) + .filter((key) => /^mcp_servers\.[^.]+$/.test(key)) + .map((key) => key.slice("mcp_servers.".length)), + ]; + const data = [...new Set(names)].map((name) => ({ + name, + runtimeStatus: + found.config[`mcp_servers.${name}.enabled`] === false && !setup.plugins?.includes(name) + ? "disabled" + : "connected", + tools: {}, + })); + const start = typeof params.cursor === "string" ? Number(params.cursor) : 0; + const end = start + pageSize; + return Effect.succeed({ + data: data.slice(start, end), + nextCursor: endlessPages || end < data.length ? String(end) : null, + }); + } + default: + return Effect.succeed({ turn: { id: `turn-${++next}` } }); + } + }; + /** Waiters for the `count`-th request of a method (a forked check reaching a milestone). */ + const waiters: Array<{ + readonly method: string; + readonly count: number; + readonly done: Deferred.Deferred; + }> = []; + const wake = Effect.forEach( + waiters, + (waiter) => + calls.filter((call) => call.method === waiter.method).length >= waiter.count + ? Deferred.succeed(waiter.done, undefined) + : Effect.void, + { discard: true }, + ); + const request = (method: string, params: unknown) => + Effect.gen(function* () { + calls.push({ method, params: (params ?? {}) as Json }); + yield* wake; + const gate = gates.get(method); + if (gate !== undefined) { + yield* Deferred.succeed(gate.reached, undefined); + yield* Deferred.await(gate.open); + } + return yield* reply(method, (params ?? {}) as Json); + }); + /** Notification handlers, in the order they were added, as the real client keeps them. */ + const handlers = new Map< + string, + Array<(payload: unknown) => Effect.Effect> + >(); + const client = { + request, + raw: { request, requests: undefined as never }, + notify: () => Effect.void, + awaitTermination: Effect.never, + handleServerRequest: () => Effect.void, + handleServerNotification: ( + method: string, + handler: (payload: unknown) => Effect.Effect, + ) => Effect.sync(() => void handlers.set(method, [...(handlers.get(method) ?? []), handler])), + handleUnknownServerRequest: () => Effect.void, + handleUnknownServerNotification: () => Effect.void, + } as unknown as Client; + return { + client, + threads, + calls, + failing, + answers, + gates, + /** Waits until `method` has been requested `count` times in all (it may already have been). */ + reached: (method: string, count: number) => + Effect.gen(function* () { + const done = yield* Deferred.make(); + waiters.push({ method, count, done }); + yield* wake; + yield* Deferred.await(done); + }), + /** Codex sends a notification: every handler for it runs, in order. */ + emit: (method: string, payload: unknown) => + Effect.forEach(handlers.get(method) ?? [], (handler) => handler(payload), { + discard: true, + }).pipe(Effect.orDie), + setPageSize: (size: number) => void (pageSize = size), + setEndlessPages: () => void (endlessPages = true), + /** + * Codex spawns a sub-agent of a loaded thread: the child copies the parent's loaded config, + * servers switched off included (codex-rs core/src/agent/child_config.rs). + */ + spawnChild: (parent: string) => { + const source = threads.get(parent)!; + const id = `native-${++next}`; + threads.set(id, { id, cwd: source.cwd, config: { ...source.config }, loaded: true }); + return id; + }, + /** Codex lets the thread go (idle): its next resume loads it with the config sent then. */ + unload: (id: string) => void (threads.get(id)!.loaded = false), + sent: (method: string) => calls.filter((call) => call.method === method), + }; +}; + +const resolved = ( + name: string, + servers: McpProfileSet["servers"], + t3Tools: McpProfileSet["t3Tools"] = "all", +): McpProfileResolved => ({ + _tag: "Resolved", + name, + source: "thread-pick", + profile: { servers, t3Tools }, + narrowedByParent: false, + unknownToolGroups: [], +}); +const ALL = resolved("all", "all"); +const isRefusal = Schema.is(ClaudeMcpProfileError); + +/** Each T3 thread's profile, or its refusal; a thread not listed gets `all`. */ +const makeProfiles = (entries: Record = {}) => { + const profiles = new Map( + Object.entries(entries), + ); + const profileFor: ProfileById = (threadId) => { + const entry = profiles.get(threadId) ?? ALL; + return entry._tag === "ClaudeMcpProfileError" ? Effect.fail(entry) : Effect.succeed(entry); + }; + return { profiles, profileFor }; +}; + +/** The config CodexAdapterV2 sends for a T3 thread: its id and T3's own servers. */ +const threadConfig = (threadId: string) => ({ + approvals_reviewer: "user", + [THREAD_KEY]: threadId, + "mcp_servers.t3-code": { ...T3_SERVER, disabled_tools: ["t3_thread_wait"] }, + "mcp_servers.t3-code-direct": { ...T3_SERVER, enabled_tools: ["t3_thread_wait"] }, +}); + +/** `ok`, or the message the user reads for the failure (as a turn's error shows it). */ +const outcome = (effect: Effect.Effect) => + effect.pipe( + Effect.exit, + Effect.map((exit) => + exit._tag === "Success" + ? "ok" + : makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message, + ), + ); + +const start = (client: Client, threadId: string, cwd = "/workspace") => + client.request("thread/start", { cwd, config: threadConfig(threadId) } as never) as Effect.Effect< + { readonly thread: { readonly id: string } }, + CodexError.CodexAppServerError + >; +const resume = (client: Client, nativeId: string, threadId?: string) => + client.raw.request("thread/resume", { + threadId: nativeId, + excludeTurns: true, + ...(threadId === undefined ? {} : { config: threadConfig(threadId) }), + } as never); +const turn = (client: Client, nativeId: string) => + client.request("turn/start", { threadId: nativeId, input: [] } as never); +const offKeys = (config: Json) => + Object.keys(config) + .filter((key) => key.startsWith("mcp_servers.") && key.endsWith(".enabled")) + .sort(); + +/** What the adapter's own turn/completed handler is given, through the wrapped client. */ +const completions = (client: Client) => + Effect.gen(function* () { + const seen: Array<{ readonly id: string; readonly status: string; readonly error?: unknown }> = + []; + yield* client.handleServerNotification("turn/completed", (payload) => + Effect.sync(() => void seen.push(payload.turn as never)), + ); + return seen; + }); +const turnStarted = (threadId: string, turnId: string) => ({ + threadId, + turn: { id: turnId, items: [], status: "inProgress", error: null }, +}); +const turnCompleted = (threadId: string, turnId: string, status = "interrupted") => ({ + threadId, + turn: { id: turnId, items: [], status, error: null }, +}); +const STOPPED = "T3 stopped this turn, which Codex started on its own for the thread's goal"; +/** The item Codex reports when a thread spawns sub-agents (collab tools, multi-agent v1). */ +const spawned = (threadId: string, children: ReadonlyArray) => ({ + threadId, + turnId: "parent-turn", + item: { + type: "collabAgentToolCall", + id: "call-1", + tool: "spawnAgent", + status: "completed", + senderThreadId: threadId, + receiverThreadIds: children, + agentsStates: {}, + }, +}); +/** The item Codex reports for a sub-agent's life (multi-agent v2). */ +const subAgentActivity = (threadId: string, child: string) => ({ + threadId, + turnId: "parent-turn", + item: { + type: "subAgentActivity", + id: "act-1", + kind: "started", + agentPath: "/a", + agentThreadId: child, + }, +}); + +describe("codexMcpProfile helpers", () => { + it("turns off every configured server the profile leaves out, never T3's own", () => { + assert.deepStrictEqual( + codexMcpProfileConfig("mine", { servers: ["alpha"], t3Tools: "all" }, [ + "alpha", + "beta", + "t3-code", + "t3-code-direct", + ]), + { "mcp_servers.beta.enabled": false, "features.apps": false }, + ); + assert.deepStrictEqual( + codexMcpProfileConfig("all", { servers: "all", t3Tools: "all" }, ["alpha"]), + {}, + ); + // A kept name that is not set up keeps nothing and is not an error (design §9). + assert.deepStrictEqual( + codexMcpProfileConfig("mine", { servers: ["nowhere"], t3Tools: "all" }, []), + { "features.apps": false }, + ); + // Codex's connectors server is never listed by config/read: kept only by name. + assert.deepStrictEqual( + codexMcpProfileConfig("apps", { servers: ["codex_apps"], t3Tools: "all" }, ["beta"]), + { "mcp_servers.beta.enabled": false }, + ); + }); + + it("refuses a profile it cannot apply, with the fix", () => { + const tools = codexMcpProfileConfig("lean", { servers: "all", t3Tools: ["threads"] }, []); + assert.isTrue(isRefusal(tools)); + assert.include((tools as ClaudeMcpProfileError).reason, 'set its t3Tools to "all"'); + const named = codexMcpProfileConfig("mine", { servers: [], t3Tools: "all" }, ["a.b"]); + assert.isTrue(isRefusal(named)); + assert.include((named as ClaudeMcpProfileError).reason, '"a.b"'); + assert.include((named as ClaudeMcpProfileError).reason, FIX); + }); + + it("reads server names from config/read, and nothing else as a list", () => { + assert.deepStrictEqual(codexConfiguredMcpServers({ mcp_servers: { a: {}, b: {} } }), [ + "a", + "b", + ]); + assert.deepStrictEqual(codexConfiguredMcpServers({}), []); + assert.deepStrictEqual(codexConfiguredMcpServers({ mcp_servers: null }), []); + assert.isUndefined(codexConfiguredMcpServers({ mcp_servers: ["a"] })); + assert.isUndefined(codexConfiguredMcpServers(undefined)); + }); + + it("finds live servers outside the profile that Codex did not disable", () => { + const statuses = [ + { name: "alpha", runtimeStatus: "connected" }, + { name: "beta", runtimeStatus: "disabled" }, + { name: "gamma", runtimeStatus: "starting" }, + { name: "t3-code", runtimeStatus: "connected" }, + ]; + assert.deepStrictEqual(codexMcpServersOutsideProfile(["alpha"], statuses), ["gamma"]); + assert.deepStrictEqual(codexMcpServersOutsideProfile("all", statuses), []); + }); + + it("only Codex's own word for a switched-off server counts as off", () => { + // codex-rs 0.171.0 McpServerRuntimeStatus, as the app-server sends it (camelCase): a server + // with enabled = false reports "disabled"; every other word, none, or an unknown one is on. + const words = [ + "notStarted", + "starting", + "connected", + "authenticationRequired", + "failed", + "cancelled", + "unknown", + "Disabled", + ]; + const statuses = [ + ...words.map((word) => ({ name: word, runtimeStatus: word })), + { name: "none", runtimeStatus: null }, + { name: "missing" }, + { name: "off", runtimeStatus: "disabled" }, + ]; + assert.deepStrictEqual(codexMcpServersOutsideProfile([], statuses), [ + ...words, + "none", + "missing", + ]); + }); +}); + +describe("withCodexMcpProfiles", () => { + it.effect( + "a left-out server gets enabled=false on that thread only; kept and T3's own stay as sent", + () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"], launchArgs: ["gamma"] }); + const { profileFor } = makeProfiles({ narrow: resolved("alpha-only", ["alpha"]) }); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const narrow = (yield* start(client, "narrow")).thread.id; + const wide = (yield* start(client, "wide")).thread.id; + const [narrowSent, wideSent] = fake + .sent("thread/start") + .map((call) => call.params.config as Json); + // beta from config.toml and gamma from a launch argument; alpha is kept. + assert.deepStrictEqual(offKeys(narrowSent!), [ + "mcp_servers.beta.enabled", + "mcp_servers.gamma.enabled", + ]); + assert.isFalse(narrowSent!["mcp_servers.beta.enabled"]); + // Everything the adapter sent is still there, unchanged. + for (const [key, value] of Object.entries(threadConfig("narrow"))) { + assert.deepStrictEqual(narrowSent![key], value); + } + // The other thread on the same app-server is sent exactly what the adapter sent. + assert.deepStrictEqual(wideSent, threadConfig("wide")); + assert.deepStrictEqual(fake.threads.get(wide)!.config, threadConfig("wide")); + assert.strictEqual(yield* outcome(turn(client, narrow)), "ok"); + assert.strictEqual(yield* outcome(turn(client, wide)), "ok"); + assert.strictEqual(fake.sent("turn/start").length, 2); + }), + ); + + it.effect.each([ + { order: "narrow first", first: "a", second: "b" }, + { order: "narrow second", first: "b", second: "a" }, + ] as const)("two threads on one app-server keep their own sets ($order)", ({ first, second }) => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta", "gamma"] }); + const { profileFor } = makeProfiles({ + a: resolved("alpha-only", ["alpha"]), + b: resolved("beta-gamma", ["beta", "gamma"]), + }); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const ids: Record = {}; + ids[first] = (yield* start(client, first)).thread.id; + ids[second] = (yield* start(client, second)).thread.id; + assert.deepStrictEqual(offKeys(fake.threads.get(ids.a!)!.config), [ + "mcp_servers.beta.enabled", + "mcp_servers.gamma.enabled", + ]); + assert.deepStrictEqual(offKeys(fake.threads.get(ids.b!)!.config), [ + "mcp_servers.alpha.enabled", + ]); + // Each turn is checked against its own thread's servers and profile. + assert.strictEqual(yield* outcome(turn(client, ids.a!)), "ok"); + assert.strictEqual(yield* outcome(turn(client, ids.b!)), "ok"); + // A resume of one names that thread, whichever opened the session. + fake.unload(ids.a!); + yield* resume(client, ids.a!, "a"); + assert.deepStrictEqual(offKeys(fake.threads.get(ids.a!)!.config), [ + "mcp_servers.beta.enabled", + "mcp_servers.gamma.enabled", + ]); + }), + ); + + it.effect("project servers come from config/read in the thread's workspace, forks included", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha"], project: { "/proj": ["delta"] } }); + const { profileFor } = makeProfiles({ + p: resolved("none", []), + forked: resolved("none", []), + }); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const p = (yield* start(client, "p", "/proj")).thread.id; + assert.deepStrictEqual(offKeys(fake.threads.get(p)!.config), [ + "mcp_servers.alpha.enabled", + "mcp_servers.delta.enabled", + ]); + assert.deepStrictEqual(fake.sent("config/read")[0]!.params, { + cwd: "/proj", + includeLayers: false, + }); + // A fork without a cwd is loaded where its source is: read from Codex. + const fork = (yield* client.request("thread/fork", { + threadId: p, + config: threadConfig("forked"), + } as never)) as { readonly thread: { readonly id: string } }; + assert.strictEqual(fake.sent("thread/read").length, 1); + assert.deepStrictEqual(offKeys(fake.threads.get(fork.thread.id)!.config), [ + "mcp_servers.alpha.enabled", + "mcp_servers.delta.enabled", + ]); + assert.strictEqual(yield* outcome(turn(client, fork.thread.id)), "ok"); + }), + ); + + it.effect("a profile that cannot be worked out refuses with its reason; nothing loads", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha"] }); + const { profileFor } = makeProfiles({ + missing: new ClaudeMcpProfileError({ + reason: `MCP profile "gone" is not in Settings, so this thread cannot start: ${FIX}.`, + }), + }); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const message = yield* outcome(start(client, "missing")); + assert.include(message, 'MCP profile "gone" is not in Settings'); + assert.include(message, FIX); + assert.deepStrictEqual(fake.sent("thread/start"), []); + }), + ); + + it.effect("a profile that limits T3's tools, or a server name Codex cannot take, refuses", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "my server"] }); + const { profileFor } = makeProfiles({ + tools: resolved("lean", "all", ["threads"]), + named: resolved("none", []), + }); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + assert.include(yield* outcome(start(client, "tools")), 'set its t3Tools to "all"'); + const named = yield* outcome(start(client, "named")); + assert.include(named, '"my server"'); + assert.include(named, FIX); + assert.deepStrictEqual(fake.sent("thread/start"), []); + }), + ); + + it.effect.each([ + { + case: "config/read fails", + set: (fake: ReturnType) => void fake.failing.add("config/read"), + }, + { + case: "config/read gives no server table", + set: (fake: ReturnType) => + void fake.answers.set("config/read", { config: { mcp_servers: "x" } }), + }, + ])("refuses, never loads with every server, when $case", ({ set }) => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha"] }); + set(fake); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("none", []) }).profileFor, + ); + const message = yield* outcome(start(client, "t")); + assert.include(message, "could not read which MCP servers Codex has set up"); + assert.include(message, FIX); + assert.deepStrictEqual(fake.sent("thread/start"), []); + }), + ); + + it.effect("a thread with no profile (all) costs no extra request, as before profiles", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha"] }); + const client = yield* withCodexMcpProfiles(fake.client, makeProfiles().profileFor); + const id = (yield* start(client, "old")).thread.id; + yield* turn(client, id); + // Requests without a T3 thread (no profile anywhere on this app-server) pass as before. + yield* resume(client, id); + yield* client.request("thread/goal/set", { threadId: id, status: "active" } as never); + assert.deepStrictEqual( + fake.calls.map((call) => call.method), + ["thread/start", "turn/start", "thread/resume", "thread/goal/set"], + ); + assert.deepStrictEqual(fake.calls[0]!.params.config, threadConfig("old")); + }), + ); + + it.effect("an empty server list turns off only Codex's connectors, and the thread runs", () => + Effect.gen(function* () { + const fake = makeFakeCodex(); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("none", []) }).profileFor, + ); + const id = (yield* start(client, "t")).thread.id; + assert.deepStrictEqual(fake.threads.get(id)!.config, { + ...threadConfig("t"), + "features.apps": false, + }); + assert.strictEqual(yield* outcome(turn(client, id)), "ok"); + }), + ); + + it.effect("runs again: starting or resuming twice sends the same set", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("a", ["alpha"]) }).profileFor, + ); + const first = (yield* start(client, "t")).thread.id; + const second = (yield* start(client, "t")).thread.id; + assert.deepStrictEqual(fake.threads.get(first)!.config, fake.threads.get(second)!.config); + fake.unload(first); + yield* resume(client, first, "t"); + yield* resume(client, first, "t"); + const resumes = fake.sent("thread/resume").map((call) => call.params.config); + assert.deepStrictEqual(resumes[0], resumes[1]); + assert.deepStrictEqual(offKeys(fake.threads.get(first)!.config), [ + "mcp_servers.beta.enabled", + ]); + assert.strictEqual(yield* outcome(turn(client, first)), "ok"); + }), + ); + + it.effect( + "a profile narrowed while Codex has the thread loaded refuses its turns until Codex reloads it", + () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const { profiles, profileFor } = makeProfiles(); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(client, "t")).thread.id; + profiles.set("t", resolved("a", ["alpha"])); + // Codex keeps the loaded thread's servers, so this resume changes nothing there. + yield* resume(client, id, "t"); + const message = yield* outcome(turn(client, id)); + assert.include(message, "Codex still has beta switched on for this thread"); + assert.include(message, "once Codex loads it again"); + assert.include(message, FIX); + assert.deepStrictEqual(fake.sent("turn/start"), []); + // A goal starts work too; a paused goal does not. + assert.include( + yield* outcome( + client.request("thread/goal/set", { threadId: id, status: "active" } as never), + ), + "beta switched on", + ); + assert.strictEqual( + yield* outcome( + client.request("thread/goal/set", { threadId: id, status: "paused" } as never), + ), + "ok", + ); + fake.unload(id); + yield* resume(client, id, "t"); + assert.strictEqual(yield* outcome(turn(client, id)), "ok"); + }), + ); + + it.effect( + "a profile narrowed during a running goal: the next turn Codex starts is stopped, with why", + () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const { profiles, profileFor } = makeProfiles(); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const seen = yield* completions(client); + const id = (yield* start(client, "t")).thread.id; + assert.strictEqual( + yield* outcome( + client.request("thread/goal/set", { threadId: id, status: "active" } as never), + ), + "ok", + ); + // The goal runs; the profile is narrowed while Codex has the thread loaded. + profiles.set("t", resolved("a", ["alpha"])); + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + yield* fake.reached("turn/interrupt", 1); + // The goal is paused before the turn is interrupted, so Codex starts no next one. + const stops = fake.calls.filter( + (call) => call.method === "thread/goal/set" || call.method === "turn/interrupt", + ); + assert.deepStrictEqual(stops.slice(-2), [ + { method: "thread/goal/set", params: { threadId: id, status: "paused" } }, + { method: "turn/interrupt", params: { threadId: id, turnId: "goal-2" } }, + ]); + yield* fake.emit("turn/completed", turnCompleted(id, "goal-2")); + assert.strictEqual(seen.length, 1); + assert.strictEqual(seen[0]!.status, "failed"); + const message = (seen[0]!.error as { readonly message: string }).message; + assert.include(message, STOPPED); + assert.include(message, "paused the goal"); + assert.include(message, "Codex still has beta switched on for this thread"); + assert.include(message, FIX); + // Another turn's end is passed on as Codex sent it. + yield* fake.emit("turn/completed", turnCompleted(id, "other", "completed")); + assert.deepStrictEqual(seen[1], turnCompleted(id, "other", "completed").turn as never); + }), + ); + + it.effect("an unchanged profile: a turn Codex starts for the goal runs untouched", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("a", ["alpha"]) }).profileFor, + ); + const seen = yield* completions(client); + const id = (yield* start(client, "t")).thread.id; + const reads = fake.sent("mcpServerStatus/list").length; + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + yield* fake.reached("mcpServerStatus/list", reads + 1); + yield* fake.emit("turn/completed", turnCompleted(id, "goal-2", "completed")); + assert.deepStrictEqual(fake.sent("turn/interrupt"), []); + assert.deepStrictEqual(fake.sent("thread/goal/set"), []); + assert.deepStrictEqual(seen, [turnCompleted(id, "goal-2", "completed").turn as never]); + }), + ); + + it.effect( + "a profile that breaks during a goal stops its next turn with the profile's reason", + () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const { profiles, profileFor } = makeProfiles({ t: resolved("a", ["alpha"]) }); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const seen = yield* completions(client); + const id = (yield* start(client, "t")).thread.id; + profiles.set( + "t", + new ClaudeMcpProfileError({ reason: `MCP profile "a" is not in Settings: ${FIX}.` }), + ); + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + yield* fake.reached("turn/interrupt", 1); + yield* fake.emit("turn/completed", turnCompleted(id, "goal-2", "completed")); + assert.strictEqual(seen[0]!.status, "failed"); + assert.include( + (seen[0]!.error as { readonly message: string }).message, + "is not in Settings", + ); + }), + ); + + it.effect( + "runs again and restarts mid-goal: each Codex-started turn is checked; a reload applies the profile", + () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const { profiles, profileFor } = makeProfiles(); + const before = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(before, "t")).thread.id; + profiles.set("t", resolved("a", ["alpha"])); + // Codex starts goal turns again and again: each one is stopped, none slips through. + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + yield* fake.reached("turn/interrupt", 1); + yield* fake.emit("turn/started", turnStarted(id, "goal-3")); + yield* fake.reached("turn/interrupt", 2); + // The app-server restarts mid-goal: T3 loads the thread again, now with beta off, and + // the goal's next turn runs. + fake.unload(id); + const after = yield* withCodexMcpProfiles(fake.client, profileFor); + yield* resume(after, id, "t"); + assert.deepStrictEqual(offKeys(fake.threads.get(id)!.config), ["mcp_servers.beta.enabled"]); + const reads = fake.sent("mcpServerStatus/list").length; + yield* fake.emit("turn/started", turnStarted(id, "goal-4")); + // Both wrappers listen on this fake; the old one's check sees the new config too. + yield* fake.reached("mcpServerStatus/list", reads + 2); + assert.strictEqual(fake.sent("turn/interrupt").length, 2); + }), + ); + + it.effect("T3's tools narrowed after the thread loaded on all: its next turn is refused", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha"] }); + const { profiles, profileFor } = makeProfiles(); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(client, "t")).thread.id; + // Every server kept, only T3's tools limited: no server is outside the profile. + profiles.set("t", resolved("lean", "all", ["threads"])); + const message = yield* outcome(turn(client, id)); + assert.include(message, 'MCP profile "lean" limits T3\'s own tools'); + assert.include(message, 'set its t3Tools to "all"'); + assert.deepStrictEqual(fake.sent("turn/start"), []); + }), + ); + + it.effect( + "a refused resume is not swapped for a fresh session: the next start of that thread refuses once", + () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("a", ["alpha"]) }).profileFor, + ); + const id = (yield* start(client, "t")).thread.id; + fake.unload(id); + // One failed read refuses the resume... + fake.failing.add("config/read"); + assert.include(yield* outcome(resume(client, id, "t")), "could not read which MCP servers"); + fake.failing.delete("config/read"); + // ...and T3's fallback, a new Codex session for the same thread, is refused with it. + const fresh = yield* outcome(start(client, "t")); + assert.include(fresh, "could not read which MCP servers"); + assert.include(fresh, "did not move the thread to a new Codex session"); + assert.strictEqual(fake.sent("thread/start").length, 1); + // Retrying the turn resumes the same Codex thread; later starts are not held. + yield* resume(client, id, "t"); + assert.deepStrictEqual(offKeys(fake.threads.get(id)!.config), ["mcp_servers.beta.enabled"]); + assert.strictEqual(yield* outcome(start(client, "t")), "ok"); + // Stopped half-way: a refused resume followed by no start leaves one refusal, not more. + fake.unload(id); + fake.failing.add("config/read"); + yield* outcome(resume(client, id, "t")); + fake.failing.delete("config/read"); + assert.include(yield* outcome(start(client, "t")), "new Codex session"); + assert.strictEqual(yield* outcome(start(client, "t")), "ok"); + }), + ); + + it.effect("Codex's connectors server is switched off unless the profile keeps it by name", () => + Effect.gen(function* () { + // With ChatGPT sign-in Codex adds codex_apps, which config/read never lists. + const fake = makeFakeCodex({ servers: ["alpha"], apps: true }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ a: resolved("a", ["alpha"]), apps: resolved("apps", ["codex_apps"]) }) + .profileFor, + ); + const narrow = (yield* start(client, "a")).thread.id; + assert.isFalse(fake.threads.get(narrow)!.config["features.apps"]); + assert.strictEqual(yield* outcome(turn(client, narrow)), "ok"); + const kept = (yield* start(client, "apps")).thread.id; + assert.notProperty(fake.threads.get(kept)!.config, "features.apps"); + assert.strictEqual(yield* outcome(turn(client, kept)), "ok"); + // A thread on all keeps it too. + const all = (yield* start(client, "wide")).thread.id; + assert.notProperty(fake.threads.get(all)!.config, "features.apps"); + }), + ); + + it.effect( + "a Codex sub-agent copies the servers T3 switched off in its parent's own thread config", + () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"], apps: true }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("a", ["alpha"]) }).profileFor, + ); + const seen = yield* completions(client); + const id = (yield* start(client, "t")).thread.id; + // What T3 sends at load is what a child copies: the off keys sit in the thread's config. + assert.deepStrictEqual(fake.sent("thread/start")[0]!.params.config, { + ...threadConfig("t"), + "mcp_servers.beta.enabled": false, + "features.apps": false, + }); + const child = fake.spawnChild(id); + // Seen twice (started and completed): runs again, adopted once. + yield* fake.emit("item/started", spawned(id, [])); + yield* fake.emit("item/completed", spawned(id, [child])); + yield* fake.emit("item/completed", spawned(id, [child])); + const reads = fake.sent("mcpServerStatus/list").length; + yield* fake.emit("turn/started", turnStarted(child, "child-1")); + yield* fake.reached("mcpServerStatus/list", reads + 1); + assert.strictEqual(fake.sent("mcpServerStatus/list")[reads]!.params.threadId, child); + yield* fake.emit("turn/completed", turnCompleted(child, "child-1", "completed")); + assert.deepStrictEqual(fake.sent("turn/interrupt"), []); + assert.deepStrictEqual(seen, [turnCompleted(child, "child-1", "completed").turn as never]); + }), + ); + + type Spawn = (parent: string, child: string) => readonly [string, unknown]; + const spawns: ReadonlyArray = [ + ["spawnAgent", (parent, child) => ["item/completed", spawned(parent, [child])]], + ["subAgentActivity", (parent, child) => ["item/started", subAgentActivity(parent, child)]], + ]; + it.effect.each(spawns)( + "a profile narrowed while a Codex sub-agent runs (%s): its next turn is stopped, with why", + ([, spawn]) => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const { profiles, profileFor } = makeProfiles(); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const seen = yield* completions(client); + const id = (yield* start(client, "t")).thread.id; + const child = fake.spawnChild(id); + const [method, payload] = spawn(id, child); + yield* fake.emit(method, payload); + profiles.set("t", resolved("a", ["alpha"])); + yield* fake.emit("turn/started", turnStarted(child, "child-2")); + yield* fake.reached("turn/interrupt", 1); + assert.deepStrictEqual(fake.sent("turn/interrupt")[0]!.params, { + threadId: child, + turnId: "child-2", + }); + yield* fake.emit("turn/completed", turnCompleted(child, "child-2")); + assert.strictEqual(seen[0]!.status, "failed"); + assert.include( + (seen[0]!.error as { readonly message: string }).message, + "Codex still has beta switched on for this thread", + ); + // A sub-agent T3 later resumes (to read its model) loads under its parent's profile. + fake.unload(child); + yield* resume(client, child); + assert.deepStrictEqual(offKeys(fake.threads.get(child)!.config), [ + "mcp_servers.beta.enabled", + ]); + }), + ); + + it.effect("a widened profile runs at once: the thread keeps fewer servers until reloaded", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const { profiles, profileFor } = makeProfiles({ t: resolved("a", ["alpha"]) }); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(client, "t")).thread.id; + profiles.set("t", ALL); + assert.strictEqual(yield* outcome(turn(client, id)), "ok"); + // The status list is read only for a profile narrower than all. + assert.deepStrictEqual(fake.sent("mcpServerStatus/list").length, 0); + }), + ); + + it.effect("a plugin server Codex will not switch off refuses the turn", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha"], plugins: ["plug"] }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("a", ["alpha"]) }).profileFor, + ); + const id = (yield* start(client, "t")).thread.id; + const message = yield* outcome(turn(client, id)); + assert.include(message, "Codex still has plug switched on"); + assert.include(message, "a Codex plugin can also add a server"); + }), + ); + + it.effect("the server list is read across pages, and refuses when it cannot be read", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["a1", "a2", "a3", "a4", "a5"] }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("a", ["a1"]) }).profileFor, + ); + const id = (yield* start(client, "t")).thread.id; + assert.strictEqual(yield* outcome(turn(client, id)), "ok"); + assert.isAbove(fake.sent("mcpServerStatus/list").length, 2); + fake.setEndlessPages(); + assert.include(yield* outcome(turn(client, id)), "could not read which MCP servers"); + fake.failing.add("mcpServerStatus/list"); + assert.include(yield* outcome(turn(client, id)), "could not read which MCP servers"); + assert.strictEqual(fake.sent("turn/start").length, 1); + }), + ); + + it.effect("app-server restarted: a fresh client knows no thread until T3 loads it again", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const { profileFor } = makeProfiles({ t: resolved("a", ["alpha"]) }); + const before = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(before, "t")).thread.id; + // The new process: same threads on disk, none loaded, and a new wrapped client. + fake.unload(id); + const after = yield* withCodexMcpProfiles(fake.client, profileFor); + // Nothing narrowed on it yet, so a turn on a thread it never loaded is left to Codex. + yield* resume(after, id, "t"); + assert.deepStrictEqual(offKeys(fake.threads.get(id)!.config), ["mcp_servers.beta.enabled"]); + assert.strictEqual(yield* outcome(turn(after, id)), "ok"); + }), + ); + + it.effect("with a profile in use, a thread T3 did not load itself is refused", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("a", ["alpha"]) }).profileFor, + ); + yield* start(client, "t"); + // Codex's own sub-agent thread, resumed with no T3 thread id (a model lookup). + const child = (yield* fake.client.request("thread/start", {} as never)) as { + readonly thread: { readonly id: string }; + }; + fake.unload(child.thread.id); + assert.include( + yield* outcome(resume(client, child.thread.id)), + "cannot tell which T3 thread this Codex thread belongs to", + ); + assert.strictEqual(fake.sent("thread/resume").length, 0); + assert.include( + yield* outcome(turn(client, child.thread.id)), + "did not load this Codex thread", + ); + assert.strictEqual(fake.sent("turn/start").length, 0); + }), + ); + + it.effect("stopped half-way: a turn interrupted in its check never starts; a retry runs", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("a", ["alpha"]) }).profileFor, + ); + const id = (yield* start(client, "t")).thread.id; + const gate = { reached: yield* Deferred.make(), open: yield* Deferred.make() }; + fake.gates.set("mcpServerStatus/list", gate); + const fiber = yield* Effect.forkChild(turn(client, id)); + yield* Deferred.await(gate.reached); + yield* Fiber.interrupt(fiber); + assert.strictEqual(fake.sent("turn/start").length, 0); + fake.gates.delete("mcpServerStatus/list"); + assert.strictEqual(yield* outcome(turn(client, id)), "ok"); + assert.strictEqual(fake.sent("turn/start").length, 1); + }), + ); + + it.effect("stopped half-way: a load interrupted while servers are read sends nothing", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("a", ["alpha"]) }).profileFor, + ); + const gate = { reached: yield* Deferred.make(), open: yield* Deferred.make() }; + fake.gates.set("config/read", gate); + const fiber = yield* Effect.forkChild(start(client, "t")); + yield* Deferred.await(gate.reached); + yield* Fiber.interrupt(fiber); + assert.strictEqual(fake.sent("thread/start").length, 0); + fake.gates.delete("config/read"); + const id = (yield* start(client, "t")).thread.id; + assert.deepStrictEqual(offKeys(fake.threads.get(id)!.config), ["mcp_servers.beta.enabled"]); + }), + ); +}); + +describe("profiledClientFactory (settings and thread store)", () => { + const NOW = DateTime.makeUnsafe("2026-11-21T00:00:00.000Z"); + const PROJECT = ProjectId.make("project"); + const CODEX = ProviderInstanceId.make("codex"); + const storedThread = (id: string, parent?: string): OrchestrationV2AppThread => { + const threadId = ThreadId.make(id); + const base = makeTurnInput({ + threadId, + instanceId: CODEX, + providerThread: { + id: ProviderThreadId.make(`provider-thread:${id}`), + threadId, + providerInstanceId: CODEX, + } as never, + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", + }), + now: NOW, + }).appThread; + return { + ...base, + projectId: PROJECT, + lineage: { + parentThreadId: parent === undefined ? null : ThreadId.make(parent), + relationshipToParent: parent === undefined ? null : "subagent", + rootThreadId: ThreadId.make(parent ?? id), + }, + }; + }; + + const withFactory = ( + settings: Record, + stored: ReadonlyArray, + body: (input: { + readonly fake: ReturnType; + readonly client: Client; + }) => Effect.Effect, + ) => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + for (const thread of stored) { + yield* store.apply({ + id: EventId.make(`seed:${thread.id}`), + type: "thread.created", + threadId: thread.id, + occurredAt: NOW, + payload: thread, + } as never); + } + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const opened: Array = []; + const factory: CodexAdapterV2.CodexAppServerClientFactoryShape = { + open: (input) => Effect.sync(() => void opened.push(input)).pipe(Effect.as(fake.client)), + }; + const { clientFactory } = yield* profiledClientFactory(factory); + const client = yield* clientFactory!.open({ threadId: ThreadId.make("opener") } as never); + assert.strictEqual(opened.length, 1); + return yield* body({ fake, client }); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + ServerSettingsService.ServerSettingsService.layerTest(settings as never), + ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)), + ).pipe(Layer.provideMerge(NodeServices.layer)), + ), + ); + + it.effect( + "a thread's pick from Settings applies on Codex, by the thread each request names", + () => + withFactory( + { + mcpProfiles: { "alpha-only": { servers: ["alpha"], t3Tools: "all" } }, + mcpThreadProfiles: { picked: "alpha-only" }, + }, + [storedThread("picked"), storedThread("plain")], + ({ fake, client }) => + Effect.gen(function* () { + const picked = (yield* start(client, "picked")).thread.id; + const plain = (yield* start(client, "plain")).thread.id; + assert.deepStrictEqual(offKeys(fake.threads.get(picked)!.config), [ + "mcp_servers.beta.enabled", + ]); + assert.deepStrictEqual(fake.threads.get(plain)!.config, threadConfig("plain")); + assert.strictEqual(yield* outcome(turn(client, picked)), "ok"); + }), + ), + ); + + it.effect("a sub-agent is cut to its parent's profile", () => + withFactory( + { mcpThreadProfiles: { parent: "t3-only" } }, + [storedThread("parent"), storedThread("child", "parent")], + ({ fake, client }) => + Effect.gen(function* () { + const child = (yield* start(client, "child")).thread.id; + assert.deepStrictEqual(offKeys(fake.threads.get(child)!.config), [ + "mcp_servers.alpha.enabled", + "mcp_servers.beta.enabled", + ]); + }), + ), + ); + + it.effect("a missing profile, or a thread the store does not have, refuses", () => + withFactory( + { mcpThreadProfiles: { lost: "gone" } }, + [storedThread("lost")], + ({ fake, client }) => + Effect.gen(function* () { + const lost = yield* outcome(start(client, "lost")); + assert.include(lost, '"gone"'); + const unknown = yield* outcome(start(client, "not-stored")); + assert.include(unknown, "cannot read this thread from its store"); + assert.include(unknown, FIX); + assert.deepStrictEqual(fake.sent("thread/start"), []); + }), + ), + ); +}); + +describe("CodexAdapterV2 with MCP profiles (the seam lines)", () => { + it.effect("a thread the adapter starts gets its profile's servers turned off", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"], launchArgs: ["gamma"] }); + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("adapter-thread"); + const NOW = DateTime.makeUnsafe("2026-11-21T00:00:00.000Z"); + yield* store.apply({ + id: EventId.make("seed:adapter-thread"), + type: "thread.created", + threadId, + occurredAt: NOW, + payload: { + ...makeTurnInput({ + threadId, + instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + providerThread: { id: ProviderThreadId.make("p"), threadId } as never, + runtimePolicy: POLICY, + now: NOW, + }).appThread, + projectId: ProjectId.make("project"), + }, + } as never); + const adapter = yield* CodexAdapterV2.createCodexAdapterV2({ + instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + displayName: undefined, + environment: [], + enabled: true, + config: decodeCodexSettings({}), + }).pipe( + Effect.provideService(CodexAdapterV2.CodexAppServerClientFactory, { + open: () => Effect.succeed(fake.client), + }), + ); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("session-mcp-profile"), + modelSelection: { instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, model: "gpt-5.4" }, + runtimePolicy: POLICY, + }); + yield* runtime.ensureThread({ + threadId, + modelSelection: { instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, model: "gpt-5.4" }, + runtimePolicy: POLICY, + }); + const [sent] = fake.sent("thread/start"); + assert.deepStrictEqual(offKeys(sent!.params.config as Json), [ + "mcp_servers.beta.enabled", + "mcp_servers.gamma.enabled", + ]); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + Layer.effect( + ServerConfig.ServerConfig, + makeReplayServerConfig("codex-mcp-profile").pipe(Effect.orDie), + ), + IdAllocator.layer, + PortScanner.layerTest, + McpProviderSessions.layer, + ServerSettingsService.ServerSettingsService.layerTest({ + mcpProfiles: { "alpha-only": { servers: ["alpha"], t3Tools: "all" } }, + mcpThreadProfiles: { "adapter-thread": "alpha-only" }, + } as never), + ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)), + ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ), + ), + ); +}); diff --git a/apps/server/src/fork/codexMcpProfile.ts b/apps/server/src/fork/codexMcpProfile.ts new file mode 100644 index 000000000000..91963694ec31 --- /dev/null +++ b/apps/server/src/fork/codexMcpProfile.ts @@ -0,0 +1,433 @@ +/** + * Fork: MCP profiles on Codex (design part 5). Each thread T3 loads on the shared app-server gets + * `mcp_servers..enabled = false` in its own config for every server Codex's config/read lists + * that its profile leaves out; each turn first checks the thread's live servers, and refuses. + */ +import { MCP_PROFILE_ALL, ThreadId } from "@t3tools/contracts"; +import type * as CodexClient from "effect-codex-app-server/client"; +import * as CodexError from "effect-codex-app-server/errors"; +import type * as CodexSchema from "effect-codex-app-server/schema"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import type { CodexAppServerClientFactoryShape } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import { AGENT_THREAD_ENV } from "../preview/PortScanner.ts"; +import { ClaudeMcpProfileError, makeThreadMcpProfilesById } from "./claudeMcpProfile.ts"; +import { isEveryMcpTool, type McpProfileResolved, type McpProfileSet } from "./mcpProfile.ts"; + +type Client = CodexClient.CodexAppServerClient["Service"]; +type Send = ( + method: string, + params: unknown, +) => Effect.Effect; +/** A thread's resolved profile, or a refusal, by its T3 thread id. */ +export type ProfileById = ( + threadId: ThreadId, +) => Effect.Effect; + +/** T3's own servers (CodexAdapterV2 sends them per thread); a profile never turns them off. */ +const CODEX_T3_MCP_SERVERS: ReadonlySet = new Set(["t3-code", "t3-code-direct"]); +/** + * Codex's built-in connectors server. Codex adds it (with ChatGPT sign-in) only while its `apps` + * feature is on, and config/read never lists it; `mcp_servers.codex_apps.enabled = false` is + * refused as an invalid transport, so a profile that leaves it out switches the feature off. + */ +const CODEX_APPS_MCP_SERVER = "codex_apps"; +const CODEX_APPS_OFF = "features.apps"; +/** The per-thread config key CodexAdapterV2 puts the T3 thread id in. */ +const THREAD_ID_KEY = `shell_environment_policy.set.${AGENT_THREAD_ENV}`; +/** Names Codex accepts for an MCP server; any other could not be written as a dotted key. */ +const SERVER_NAME = /^[A-Za-z0-9_-]+$/; +/** How long config/read, thread/read or mcpServerStatus/list may take before the turn refuses. */ +const CODEX_READ_TIMEOUT = "30 seconds"; +/** Status pages read before giving up; a page holds every server on Codex today. */ +const MAX_STATUS_PAGES = 20; +/** Not -32600: the adapter reads that code with "thread not found:" as an unloaded thread. */ +const REFUSAL_CODE = -32001; +const FIX = `pick "${MCP_PROFILE_ALL}" for this thread, or fix the profile in Settings`; +/** What a refusal of a turn Codex started on its own says happened. */ +const STOPPED = + "T3 stopped this turn, which Codex started on its own for the thread's goal, and paused the goal"; + +const isRefusal = Schema.is(ClaudeMcpProfileError); +const isRecord = (value: unknown): value is Readonly> => + typeof value === "object" && value !== null && !Array.isArray(value); +const stringField = (value: unknown, key: string): string | undefined => + isRecord(value) && typeof value[key] === "string" ? value[key] : undefined; + +/** Server names in a config/read result's `mcp_servers`; `undefined` when it is not a table. */ +export function codexConfiguredMcpServers(config: unknown): ReadonlyArray | undefined { + if (!isRecord(config)) return undefined; + const servers = config.mcp_servers; + if (servers === undefined || servers === null) return []; + return isRecord(servers) ? Object.keys(servers) : undefined; +} + +/** + * The per-thread config that turns off every configured server the profile does not keep (and + * Codex's connectors server, see {@link CODEX_APPS_MCP_SERVER}), or the refusal. T3's own servers + * stay; a kept name that is not configured keeps nothing (design §9). + */ +export function codexMcpProfileConfig( + name: string, + profile: McpProfileSet, + configured: ReadonlyArray, +): Readonly> | ClaudeMcpProfileError { + if (profile.t3Tools !== "all") { + return new ClaudeMcpProfileError({ + reason: `MCP profile "${name}" limits T3's own tools, which this version cannot apply yet, so this thread cannot start: set its t3Tools to "all", or ${FIX}.`, + }); + } + const kept = profile.servers; + if (kept === "all") return {}; + const off = configured.filter( + (server) => !CODEX_T3_MCP_SERVERS.has(server) && !kept.includes(server), + ); + const unnamed = off.filter((server) => !SERVER_NAME.test(server)); + if (unnamed.length > 0) { + return new ClaudeMcpProfileError({ + reason: `MCP profile "${name}" could not be applied: Codex has the MCP server ${unnamed.map((server) => JSON.stringify(server)).join(", ")} set up, and T3 cannot switch off a server with that name, so this thread cannot start. Rename it in Codex's config, or ${FIX}.`, + }); + } + return Object.fromEntries([ + ...off.map((server) => [`mcp_servers.${server}.enabled`, false] as const), + ...(kept.includes(CODEX_APPS_MCP_SERVER) ? [] : [[CODEX_APPS_OFF, false] as const]), + ]); +} + +/** Servers the thread has that the profile leaves out and Codex did not disable. */ +export function codexMcpServersOutsideProfile( + kept: McpProfileSet["servers"], + statuses: ReadonlyArray<{ readonly name: string; readonly runtimeStatus?: string | null }>, +): ReadonlyArray { + if (kept === "all") return []; + return statuses + .filter( + (server) => + server.runtimeStatus !== "disabled" && + !CODEX_T3_MCP_SERVERS.has(server.name) && + !kept.includes(server.name), + ) + .map((server) => server.name); +} + +/** The text a refusal gives the user. */ +const reasonOf = (error: CodexError.CodexAppServerError): string => + error._tag === "CodexAppServerRequestError" && isRefusal(error.cause) + ? error.cause.reason + : `T3 could not check this thread's MCP servers (${error.message}): retry, or ${FIX}.`; + +/** A failed request whose reason the user reads (failure.ts shows a ClaudeMcpProfileError cause). */ +const refusal = (method: string, cause: ClaudeMcpProfileError) => + new CodexError.CodexAppServerRequestError({ + code: REFUSAL_CODE, + errorMessage: cause.reason, + method, + cause, + }); + +const LOADS: ReadonlySet = new Set(["thread/start", "thread/resume", "thread/fork"]); + +/** + * The client with the thread's profile applied to each thread it loads and checked before each + * turn. One per app-server: what it learns (which Codex thread is which T3 thread) ends with it, so + * a restarted app-server starts empty and every thread is loaded, and checked, again. + */ +export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* ( + client: Client, + profileFor: ProfileById, +) { + const scope = yield* Effect.scope; + /** + * Codex thread id to T3 thread id, for each thread loaded through this client with one and for + * each Codex sub-agent of such a thread (its parent's T3 thread). + */ + const known = new Map(); + /** Turns stopped here because their profile was narrower, by Codex turn id: the reason. */ + const stoppedTurns = new Map(); + /** + * T3 threads whose resume a profile check refused, with the reason. T3 answers a failed resume + * by starting the thread in a fresh Codex session (with a summary, not its history); the next + * start of such a thread is refused too, once, so a passing hiccup cannot cost the history. + */ + const refusedResumes = new Map(); + /** Set once a thread here got a profile narrower than `all`. */ + let narrowed = false; + const read = (method: string, params: unknown) => + (client.raw.request as unknown as Send)(method, params).pipe( + Effect.timeout(CODEX_READ_TIMEOUT), + ); + + const profileOf = (method: string, threadId: ThreadId) => + profileFor(threadId).pipe(Effect.mapError((cause) => refusal(method, cause))); + + /** The workspace Codex loads the thread in: the request's, else the stored thread's. */ + const workspaceOf = (method: string, params: Readonly>) => { + const cwd = stringField(params, "cwd"); + const source = stringField(params, "threadId"); + if (cwd !== undefined || method === "thread/start" || source === undefined) { + return Effect.succeed(cwd); + } + return read("thread/read", { threadId: source, includeTurns: false }).pipe( + Effect.map((response) => + stringField(isRecord(response) ? response.thread : undefined, "cwd"), + ), + Effect.orElseSucceed(() => undefined), + ); + }; + + const cannotList = (method: string, name: string) => + refusal( + method, + new ClaudeMcpProfileError({ + reason: `T3 could not read which MCP servers Codex has set up for profile "${name}", so this thread cannot start: retry, or ${FIX}.`, + }), + ); + + const load = Effect.fn("CodexMcpProfile.load")(function* ( + send: Send, + method: string, + params: unknown, + ) { + const request = isRecord(params) ? params : {}; + const config = isRecord(request.config) ? request.config : {}; + const nativeId = method === "thread/resume" ? stringField(request, "threadId") : undefined; + const fromConfig = stringField(config, THREAD_ID_KEY); + const threadId = + fromConfig === undefined + ? nativeId === undefined + ? undefined + : known.get(nativeId) + : ThreadId.make(fromConfig); + if (threadId === undefined) { + // A Codex thread T3 did not load and saw no parent spawn (e.g. a sub-agent from before an + // app-server restart): its T3 thread is not known, so with a profile in use it is not loaded. + if (narrowed) { + return yield* refusal( + method, + new ClaudeMcpProfileError({ + reason: `T3 cannot tell which T3 thread this Codex thread belongs to, so its MCP profile cannot be applied and it was not loaded: ${FIX}.`, + }), + ); + } + return yield* send(method, params); + } + const resumeRefused = method === "thread/start" ? refusedResumes.get(threadId) : undefined; + if (resumeRefused !== undefined) { + refusedResumes.delete(threadId); + return yield* refusal( + method, + new ClaudeMcpProfileError({ + reason: `${resumeRefused} T3 did not move the thread to a new Codex session instead, which would lose its history; retrying the turn resumes it.`, + }), + ); + } + const off = yield* offFor(method, threadId, request).pipe( + Effect.tapError((error) => + method === "thread/resume" + ? Effect.sync(() => void refusedResumes.set(threadId, reasonOf(error))) + : Effect.void, + ), + ); + const response = yield* send( + method, + Object.keys(off).length === 0 ? params : { ...request, config: { ...config, ...off } }, + ); + refusedResumes.delete(threadId); + const loaded = stringField(isRecord(response) ? response.thread : undefined, "id"); + if (loaded !== undefined) known.set(loaded, threadId); + return response; + }); + + /** The per-thread config that applies the thread's profile as it loads, or the refusal. */ + const offFor = Effect.fn("CodexMcpProfile.offFor")(function* ( + method: string, + threadId: ThreadId, + request: Readonly>, + ) { + const resolved = yield* profileOf(method, threadId); + let off: Readonly> = {}; + if (!isEveryMcpTool(resolved.profile)) { + const cwd = yield* workspaceOf(method, request); + const configured = yield* read("config/read", { + ...(cwd === undefined ? {} : { cwd }), + includeLayers: false, + }).pipe( + Effect.map((response) => + codexConfiguredMcpServers(isRecord(response) ? response.config : undefined), + ), + Effect.orElseSucceed(() => undefined), + ); + if (configured === undefined) return yield* cannotList(method, resolved.name); + const planned = codexMcpProfileConfig(resolved.name, resolved.profile, configured); + if (isRefusal(planned)) return yield* refusal(method, planned); + off = planned; + narrowed = true; + } + return off; + }); + + /** Refuses a turn on a thread whose live servers include one its profile leaves out. */ + const check = Effect.fn("CodexMcpProfile.check")(function* (method: string, params: unknown) { + const nativeId = stringField(params, "threadId"); + const threadId = nativeId === undefined ? undefined : known.get(nativeId); + if (threadId === undefined) { + if (!narrowed) return; + return yield* refusal( + method, + new ClaudeMcpProfileError({ + reason: `T3 did not load this Codex thread itself, so it cannot tell which MCP servers the thread has, and runs no turn on it: ${FIX}.`, + }), + ); + } + const resolved = yield* profileOf(method, threadId); + // A thread loaded narrower than its profile is now stays narrower until Codex reloads it. + if (isEveryMcpTool(resolved.profile)) return; + const planned = codexMcpProfileConfig(resolved.name, resolved.profile, []); + if (isRefusal(planned)) return yield* refusal(method, planned); + const statuses: Array<{ readonly name: string; readonly runtimeStatus?: string | null }> = []; + let cursor: string | undefined; + for (let page = 0; ; page++) { + if (page === MAX_STATUS_PAGES) return yield* cannotList(method, resolved.name); + const response = yield* read("mcpServerStatus/list", { + threadId: nativeId, + detail: "toolsAndAuthOnly", + ...(cursor === undefined ? {} : { cursor }), + }).pipe(Effect.orElseSucceed(() => undefined)); + const data = isRecord(response) ? response.data : undefined; + if (!Array.isArray(data)) return yield* cannotList(method, resolved.name); + for (const entry of data) { + const name = stringField(entry, "name"); + if (name === undefined) return yield* cannotList(method, resolved.name); + statuses.push({ name, runtimeStatus: stringField(entry, "runtimeStatus") ?? null }); + } + cursor = isRecord(response) ? stringField(response, "nextCursor") : undefined; + if (cursor === undefined) break; + } + const outside = codexMcpServersOutsideProfile(resolved.profile.servers, statuses); + if (outside.length === 0) return; + return yield* refusal( + method, + new ClaudeMcpProfileError({ + reason: `MCP profile "${resolved.name}" could not be applied: Codex still has ${outside.join(", ")} switched on for this thread, so T3 runs no turn on it. Codex sets a thread's MCP servers only when it loads the thread, so a profile changed while the thread was loaded applies once Codex loads it again (after it has been idle for a while, or after T3 restarts); a Codex plugin can also add a server T3 cannot switch off. Until then, ${FIX}.`, + }), + ); + }); + + /** Model work Codex starts on a thread at this request; a paused goal starts none. */ + const startsWork = (method: string, params: unknown) => + method === "turn/start" || + (method === "thread/goal/set" && stringField(params, "status") !== "paused"); + + const intercept = + (send: Send): Send => + (method, params) => + LOADS.has(method) + ? load(send, method, params) + : startsWork(method, params) + ? check(method, params).pipe(Effect.andThen(send(method, params))) + : send(method, params); + + /** + * A turn Codex started on its own (a goal's next turn) never passed `turn/start`, so every turn + * that starts is checked again; one the check refuses is stopped: its goal is paused (so Codex + * starts no next one) and the turn interrupted, and it ends failed with the reason. + */ + const watchTurn = (threadId: string, turnId: string) => + (known.has(threadId) + ? check("turn/started", { threadId }).pipe(Effect.asVoid) + : Effect.void + ).pipe( + Effect.catch((error) => + Effect.gen(function* () { + stoppedTurns.set(turnId, `${STOPPED}. ${reasonOf(error)}`); + const raw = client.raw.request as unknown as Send; + yield* raw("thread/goal/set", { threadId, status: "paused" }).pipe(Effect.ignore); + yield* raw("turn/interrupt", { threadId, turnId }).pipe(Effect.ignore); + }), + ), + Effect.forkIn(scope, { startImmediately: true }), + Effect.asVoid, + ); + yield* client.handleServerNotification("turn/started", (payload) => + watchTurn(payload.threadId, payload.turn.id), + ); + + /** + * Codex's own sub-agents copy their parent's loaded config, servers switched off included + * (codex-rs core/src/agent/child_config.rs), and run their own turns; each one is counted as its + * parent's T3 thread, so those turns are checked against the same profile as the parent's. + */ + const adoptChildren = ( + payload: + | CodexSchema.V2ItemStartedNotification["item"] + | CodexSchema.V2ItemCompletedNotification["item"], + parent: string, + ) => { + const threadId = known.get(parent); + if (threadId === undefined) return; + const children = + payload.type === "collabAgentToolCall" + ? payload.receiverThreadIds + : payload.type === "subAgentActivity" + ? [payload.agentThreadId] + : []; + for (const child of children) if (!known.has(child)) known.set(child, threadId); + }; + yield* client.handleServerNotification("item/started", (payload) => + Effect.sync(() => adoptChildren(payload.item, payload.threadId)), + ); + yield* client.handleServerNotification("item/completed", (payload) => + Effect.sync(() => adoptChildren(payload.item, payload.threadId)), + ); + + /** A stopped turn ends failed with the reason, whatever Codex reports, so the user reads why. */ + const completedWithReason = ( + payload: CodexSchema.V2TurnCompletedNotification, + ): CodexSchema.V2TurnCompletedNotification => { + const reason = stoppedTurns.get(payload.turn.id); + if (reason === undefined) return payload; + stoppedTurns.delete(payload.turn.id); + return { ...payload, turn: { ...payload.turn, status: "failed", error: { message: reason } } }; + }; + + const wrapped: Client = { + ...client, + request: intercept(client.request as unknown as Send) as unknown as Client["request"], + raw: { + ...client.raw, + request: intercept( + client.raw.request as unknown as Send, + ) as unknown as Client["raw"]["request"], + }, + handleServerNotification: (method, handler) => + method === "turn/completed" + ? client.handleServerNotification("turn/completed", (payload) => + (handler as (p: typeof payload) => ReturnType)( + completedWithReason(payload), + ), + ) + : client.handleServerNotification(method, handler), + }; + return wrapped; +}); + +/** + * CodexAdapterV2's client factory with each app-server's client wrapped in + * {@link withCodexMcpProfiles}; spread over the adapter's options, so its key replaces theirs. + * Typed optional only so the spread may follow upstream's own `clientFactory` key (TS2783); it is + * always set. + */ +export const profiledClientFactory = Effect.fn("CodexMcpProfile.clientFactory")(function* ( + factory: CodexAppServerClientFactoryShape, +) { + const profileFor = yield* makeThreadMcpProfilesById; + const clientFactory: CodexAppServerClientFactoryShape = { + open: (input) => + factory + .open(input) + .pipe(Effect.flatMap((client) => withCodexMcpProfiles(client, profileFor))), + }; + const options: { readonly clientFactory?: CodexAppServerClientFactoryShape } = { clientFactory }; + return options; +}); diff --git a/apps/server/src/fork/mcpProfile.ts b/apps/server/src/fork/mcpProfile.ts index 865bf7d8e2bc..d67f7cbb0aa2 100644 --- a/apps/server/src/fork/mcpProfile.ts +++ b/apps/server/src/fork/mcpProfile.ts @@ -107,11 +107,21 @@ export function mcpT3ToolGroup( } /** - * The drivers whose threads apply an MCP profile: Claude only (fork/claudeMcpProfile.ts). Any - * other provider would give a thread every MCP server and T3 tool, so a turn there whose profile - * is narrower than `all` is refused as it starts (fork/mcpProfileTurnCheck.ts), and a delegation - * refuses to send a narrower profile to one on another machine (fork/remoteMcpProfile.ts). + * The drivers whose threads apply an MCP profile: Claude (fork/claudeMcpProfile.ts) and Codex + * (fork/codexMcpProfile.ts). Any other provider would give a thread every MCP server and T3 tool, + * so a turn there whose profile is narrower than `all` is refused as it starts + * (fork/mcpProfileTurnCheck.ts). */ export const MCP_PROFILE_DRIVERS: ReadonlySet = new Set([ ProviderDriverKind.make("claudeAgent"), + ProviderDriverKind.make("codex"), +]); + +/** + * The drivers a delegation sends a narrower profile to on another machine + * (fork/remoteMcpProfile.ts): Claude only, since a machine that carries profiles may run a T3 + * from before Codex applied them. + */ +export const MCP_PROFILE_REMOTE_DRIVERS: ReadonlySet = new Set([ + ProviderDriverKind.make("claudeAgent"), ]); diff --git a/apps/server/src/fork/mcpProfileTurnCheck.test.ts b/apps/server/src/fork/mcpProfileTurnCheck.test.ts index a0547ff8031b..29d53b557bd4 100644 --- a/apps/server/src/fork/mcpProfileTurnCheck.test.ts +++ b/apps/server/src/fork/mcpProfileTurnCheck.test.ts @@ -1,5 +1,5 @@ /** - * Fork: a turn on a provider that cannot apply MCP profiles (all but Claude) refuses when its + * Fork: a turn on a provider that cannot apply MCP profiles (all but Claude and Codex) refuses when its * thread's profile is narrower than `all`. The check wraps upstream's provider instance * registry as server.ts wires it, over upstream's settings test service and a real thread store * (SQLite in memory), so each route a thread takes to such a provider meets it at turn start. @@ -115,7 +115,7 @@ const appThread = ( } = {}, ): OrchestrationV2AppThread => { const threadId = ThreadId.make(id); - const base = turn(threadId, CODEX).appThread; + const base = turn(threadId, OPENCODE).appThread; return { ...base, projectId: PROJECT, @@ -242,13 +242,13 @@ const withCheck = ( }; const CUT = - /MCP profile \("all", cut down to its parent thread's\) is narrower than "all", and codex/; + /MCP profile \("all", cut down to its parent thread's\) is narrower than "all", and opencode/; const REFUSED = - /MCP profile "t3-only" is narrower than "all", and codex \(provider instance codex\) does not apply MCP profiles/; + /MCP profile "t3-only" is narrower than "all", and opencode \(provider instance opencode-work\) does not apply MCP profiles/; describe("mcpProfileTurnCheck", () => { it("checks every driver but those that apply profiles", () => { - assert.deepStrictEqual([...MCP_PROFILE_DRIVERS], ["claudeAgent"]); + assert.deepStrictEqual([...MCP_PROFILE_DRIVERS], ["claudeAgent", "codex"]); }); it.effect("with no profile anywhere (old and empty state), every provider runs as before", () => @@ -256,12 +256,12 @@ describe("mcpProfileTurnCheck", () => { Effect.gen(function* () { const own = appThread("own"); for (const id of [CLAUDE, CODEX, OPENCODE]) assert.strictEqual(yield* start(own, id), "ok"); - assert.strictEqual(yield* start(own, CODEX, "resume"), "ok"); + assert.strictEqual(yield* start(own, OPENCODE, "resume"), "ok"); assert.deepStrictEqual(calls, [ "start:claudeAgent:own", "start:codex:own", "start:opencode-work:own", - "resume:codex:own", + "resume:opencode-work:own", ]); }), ), @@ -271,19 +271,22 @@ describe("mcpProfileTurnCheck", () => { withCheck({ mcpProfile: "t3-only" }, [], ({ calls, raw, start }) => Effect.gen(function* () { const own = appThread("switched"); - // Claude applies the profile itself: its instance is upstream's, untouched. + // Claude and Codex apply the profile themselves: their instances are upstream's, untouched. const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; assert.strictEqual(yield* registry.getInstance(CLAUDE), raw[0]); assert.strictEqual(yield* start(own, CLAUDE), "ok"); - // The same thread, switched to Codex or any other non-Claude provider. - assert.match(yield* start(own, CODEX), REFUSED); - assert.match(yield* start(own, CODEX, "resume"), REFUSED); + assert.strictEqual(yield* registry.getInstance(CODEX), raw[1]); + assert.strictEqual(yield* start(own, CODEX), "ok"); + // The same thread, switched to a provider that does not apply profiles. + assert.match(yield* start(own, OPENCODE), REFUSED); + assert.match(yield* start(own, OPENCODE, "resume"), REFUSED); assert.include(yield* start(own, OPENCODE), "opencode (provider instance opencode-work)"); // Some providers compact by running a `/compact` prompt: it is held back too. - assert.match(yield* start(own, CODEX, "compact"), REFUSED); + assert.match(yield* start(own, OPENCODE, "compact"), REFUSED); assert.strictEqual(yield* start(own, CLAUDE, "compact"), "ok"); assert.deepStrictEqual(calls, [ "start:claudeAgent:switched", + "start:codex:switched", "compact:claudeAgent:switched", ]); }), @@ -293,9 +296,9 @@ describe("mcpProfileTurnCheck", () => { it.effect("the message says how to get the turn running", () => withCheck({ mcpProfile: "t3-only" }, [], ({ start }) => Effect.gen(function* () { - const message = yield* start(appThread("own"), CODEX); + const message = yield* start(appThread("own"), OPENCODE); assert.include(message, "so this turn was not started"); - assert.include(message, 'Switch the thread to a Claude instance, or pick "all"'); + assert.include(message, 'Switch the thread to a Claude or Codex instance, or pick "all"'); // Retrying cannot help, so upstream's turn-start guidance is not what the user reads. assert.notInclude(message, "Retry"); assert.notInclude(message, "server logs"); @@ -314,8 +317,8 @@ describe("mcpProfileTurnCheck", () => { Effect.gen(function* () { const own = appThread("own"); assert.include( - yield* start(own, CODEX), - 'MCP profile "servers-only" is narrower than "all", and codex', + yield* start(own, OPENCODE), + 'MCP profile "servers-only" is narrower than "all", and opencode', ); assert.strictEqual(yield* start(own, CLAUDE), "ok"); assert.deepStrictEqual(calls, ["start:claudeAgent:own"]); @@ -323,66 +326,66 @@ describe("mcpProfileTurnCheck", () => { ), ); - it.effect("a thread made by t3_thread_launch in a narrowed project refuses on Codex", () => + it.effect("a thread made by t3_thread_launch in a narrowed project refuses on OpenCode", () => withCheck( { projectSettingsOverrides: { [PROJECT]: { mcpProfile: "t3-only" } } }, [], ({ calls, start }) => Effect.gen(function* () { const launched = appThread("launched", { creationSource: "mcp", delegatedFrom: null }); - assert.match(yield* start(launched, CODEX), REFUSED); + assert.match(yield* start(launched, OPENCODE), REFUSED); assert.strictEqual(yield* start(launched, CLAUDE), "ok"); assert.deepStrictEqual(calls, ["start:claudeAgent:launched"]); }), ), ); - it.effect("a local delegation of a narrowed parent refuses on Codex; all's runs", () => + it.effect("a local delegation of a narrowed parent refuses on OpenCode; all's runs", () => Effect.gen(function* () { const parent = appThread("parent"); const child = appThread("child", { parent: "parent" }); const picks = { mcpThreadProfiles: { [parent.id]: "t3-only" } } as Mcp; yield* withCheck(picks, [parent], ({ calls, start }) => Effect.gen(function* () { - assert.match(yield* start(child, CODEX), CUT); + assert.match(yield* start(child, OPENCODE), CUT); assert.deepStrictEqual(calls, []); }), ); - // A sub-agent rule narrows only delegated children: the parent itself still runs on Codex. + // A sub-agent rule narrows only delegated children: the parent itself still runs on OpenCode. yield* withCheck({ mcpSubagentProfile: "t3-only" }, [parent], ({ start }) => Effect.gen(function* () { - assert.match(yield* start(child, CODEX), REFUSED); - assert.strictEqual(yield* start(parent, CODEX), "ok"); + assert.match(yield* start(child, OPENCODE), REFUSED); + assert.strictEqual(yield* start(parent, OPENCODE), "ok"); }), ); yield* withCheck({}, [parent], ({ start }) => Effect.gen(function* () { - assert.strictEqual(yield* start(child, CODEX), "ok"); + assert.strictEqual(yield* start(child, OPENCODE), "ok"); }), ); }), ); - it.effect("a child whose parent the store does not have refuses on Codex", () => + it.effect("a child whose parent the store does not have refuses on OpenCode", () => withCheck({}, [], ({ calls, start }) => Effect.gen(function* () { const orphan = appThread("orphan", { parent: "gone" }); - assert.include(yield* start(orphan, CODEX), "parent thread cannot be read"); + assert.include(yield* start(orphan, OPENCODE), "parent thread cannot be read"); assert.deepStrictEqual(calls, []); }), ), ); - it.effect("a task another machine delegated with a narrower profile refuses on Codex", () => + it.effect("a task another machine delegated with a narrower profile refuses on OpenCode", () => withCheck({}, [], ({ calls, start }) => Effect.gen(function* () { const task = appThread("task", { delegatedFrom: delegatedFrom(T3_ONLY) }); - assert.match(yield* start(task, CODEX), CUT); + assert.match(yield* start(task, OPENCODE), CUT); const all = appThread("task-all", { delegatedFrom: delegatedFrom({ name: "all", servers: "all", t3Tools: "all" }), }); - assert.strictEqual(yield* start(all, CODEX), "ok"); - assert.deepStrictEqual(calls, ["start:codex:task-all"]); + assert.strictEqual(yield* start(all, OPENCODE), "ok"); + assert.deepStrictEqual(calls, ["start:opencode-work:task-all"]); }), ), ); @@ -392,12 +395,12 @@ describe("mcpProfileTurnCheck", () => { const task = appThread("old-task", { delegatedFrom: delegatedFrom() }); yield* withCheck({ mcpSubagentProfile: "t3-only" }, [], ({ start }) => Effect.gen(function* () { - assert.match(yield* start(task, CODEX), REFUSED); + assert.match(yield* start(task, OPENCODE), REFUSED); }), ); yield* withCheck({}, [], ({ start }) => Effect.gen(function* () { - assert.strictEqual(yield* start(task, CODEX), "ok"); + assert.strictEqual(yield* start(task, OPENCODE), "ok"); }), ); }), @@ -407,14 +410,14 @@ describe("mcpProfileTurnCheck", () => { withCheck({ mcpProfile: "t3-only" }, [], ({ calls, start }) => Effect.gen(function* () { const own = appThread("own"); - const first = yield* start(own, CODEX); - assert.strictEqual(yield* start(own, CODEX), first); + const first = yield* start(own, OPENCODE); + assert.strictEqual(yield* start(own, OPENCODE), first); const settings = yield* ServerSettingsService.ServerSettingsService; yield* settings.updateSettings({ mcpThreadProfiles: { [own.id]: "all" } } as never); - assert.strictEqual(yield* start(own, CODEX), "ok"); + assert.strictEqual(yield* start(own, OPENCODE), "ok"); yield* settings.updateSettings({ mcpThreadProfiles: { [own.id]: "t3-only" } } as never); - assert.match(yield* start(own, CODEX), REFUSED); - assert.deepStrictEqual(calls, ["start:codex:own"]); + assert.match(yield* start(own, OPENCODE), REFUSED); + assert.deepStrictEqual(calls, ["start:opencode-work:own"]); }), ), ); @@ -423,12 +426,12 @@ describe("mcpProfileTurnCheck", () => { withCheck({}, [], () => Effect.gen(function* () { const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; - const codex = yield* registry.getInstance(CODEX); - assert.strictEqual(yield* registry.getInstance(CODEX), codex); + const other = yield* registry.getInstance(OPENCODE); + assert.strictEqual(yield* registry.getInstance(OPENCODE), other); const listed = yield* registry.listInstances; assert.strictEqual( - listed.find((entry) => entry.instanceId === CODEX), - codex, + listed.find((entry) => entry.instanceId === OPENCODE), + other, ); assert.isUndefined(yield* registry.getInstance(ProviderInstanceId.make("none"))); }), @@ -463,13 +466,13 @@ describe("mcpProfileTurnCheck", () => { ({ calls, start }) => Effect.gen(function* () { const own = appThread("own"); - const fiber = yield* Effect.forkChild(start(own, CODEX)); + const fiber = yield* Effect.forkChild(start(own, OPENCODE)); yield* Deferred.await(reading); yield* Fiber.interrupt(fiber); assert.deepStrictEqual(calls, []); // The next turn reads again and starts. - assert.strictEqual(yield* start(own, CODEX), "ok"); - assert.deepStrictEqual(calls, ["start:codex:own"]); + assert.strictEqual(yield* start(own, OPENCODE), "ok"); + assert.deepStrictEqual(calls, ["start:opencode-work:own"]); }), blocking, ); @@ -500,12 +503,12 @@ describe("mcpProfileTurnCheck", () => { ({ start }) => Effect.gen(function* () { // No settings.json (missing state): the defaults, so this machine's own thread runs. - assert.strictEqual(yield* start(appThread("own"), CODEX), "ok"); + assert.strictEqual(yield* start(appThread("own"), OPENCODE), "ok"); // settings.json that cannot be read as a file: a carried narrower task is refused. const { settingsPath } = yield* ServerConfig.ServerConfig; yield* (yield* FileSystem.FileSystem).makeDirectory(settingsPath); const task = appThread("task", { delegatedFrom: delegatedFrom(T3_ONLY) }); - assert.notStrictEqual(yield* start(task, CODEX), "ok"); + assert.notStrictEqual(yield* start(task, OPENCODE), "ok"); }), failing, ); diff --git a/apps/server/src/fork/mcpProfileTurnCheck.ts b/apps/server/src/fork/mcpProfileTurnCheck.ts index bbee64063dd8..443bb8c22d87 100644 --- a/apps/server/src/fork/mcpProfileTurnCheck.ts +++ b/apps/server/src/fork/mcpProfileTurnCheck.ts @@ -60,7 +60,7 @@ const refusalReason = (resolved: McpProfileResolved, instance: ProviderInstance) const profile = resolved.narrowedByParent ? `("${resolved.name}", cut down to its parent thread's)` : `"${resolved.name}"`; - return `This thread's MCP profile ${profile} is narrower than "${MCP_PROFILE_ALL}", and ${instance.driverKind} (provider instance ${instance.instanceId}) does not apply MCP profiles (only Claude does), so this turn was not started: it would get every MCP server and T3 tool. Switch the thread to a Claude instance, or pick "${MCP_PROFILE_ALL}" for this thread in Settings.`; + return `This thread's MCP profile ${profile} is narrower than "${MCP_PROFILE_ALL}", and ${instance.driverKind} (provider instance ${instance.instanceId}) does not apply MCP profiles (only Claude and Codex do), so this turn was not started: it would get every MCP server and T3 tool. Switch the thread to a Claude or Codex instance, or pick "${MCP_PROFILE_ALL}" for this thread in Settings.`; }; /** diff --git a/apps/server/src/fork/remoteMcpProfile.ts b/apps/server/src/fork/remoteMcpProfile.ts index 534dbe76f137..bf313b67790c 100644 --- a/apps/server/src/fork/remoteMcpProfile.ts +++ b/apps/server/src/fork/remoteMcpProfile.ts @@ -20,7 +20,7 @@ import * as PeerForwarding from "../peer/PeerForwarding.ts"; import * as PeerLinks from "../peer/PeerLinks.ts"; import { type LineageThread, makeThreadMcpProfiles } from "./claudeMcpProfile.ts"; import { readForkFeatures } from "./forkFeatures.ts"; -import { MCP_PROFILE_DRIVERS, carryMcpProfile, isEveryMcpTool } from "./mcpProfile.ts"; +import { MCP_PROFILE_REMOTE_DRIVERS, carryMcpProfile, isEveryMcpTool } from "./mcpProfile.ts"; /** `orchestrator_capabilities` there, as peer/RemoteDelegation.ts describes it: its providers. */ const RemoteCapabilitiesTool = Tool.make("orchestrator_capabilities", { @@ -113,7 +113,7 @@ export const makeCarry = Effect.fn("RemoteMcpProfile.makeCarry")(function* ( (yield* forwarding.call(scope, RemoteCapabilitiesTool, environmentId, {})).providers.find( (provider) => provider.providerInstanceId === instanceId, )?.driverKind; - if (driverKind === undefined || !MCP_PROFILE_DRIVERS.has(driverKind)) { + if (driverKind === undefined || !MCP_PROFILE_REMOTE_DRIVERS.has(driverKind)) { return yield* new OrchestratorMcpFailure({ code: "capability_denied", message: `${ diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 09036b09e3f7..d60a1abed92d 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -111,6 +111,7 @@ import { FetchHttpClient, HttpClient } from "effect/http"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { resolveAttachmentPath, resolveAttachmentPathById } from "../../attachmentStore.ts"; +import * as CodexMcpProfile from "../../fork/codexMcpProfile.ts"; // Fork: MCP profiles import * as PortScanner from "../../preview/PortScanner.ts"; import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts"; import { ServerConfig } from "../../config.ts"; @@ -1956,6 +1957,7 @@ export const createCodexAdapterV2 = Effect.fn("CodexAdapterV2.createCodexAdapter continuationRequests, watchCommandStops: portDiscovery.watchAgentCommandStops, ...hooks, + ...(yield* CodexMcpProfile.profiledClientFactory(clientFactory)), // Fork: MCP profiles }); }); diff --git a/docs/fork/README.md b/docs/fork/README.md index 47b1b8b8913d..418c78f7797b 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -871,12 +871,41 @@ through, and a fork of a thread whose parent cannot be read is refused. On another machine, a fork, a change to a scheduled task and `run_scheduled_task_now` are refused for such a thread, as a thread started there gets that machine's profile. -Only Claude threads apply profiles. A Codex thread, or one on any other provider, would get every +A Codex thread applies the profile's `servers` too. Codex runs one app-server for all of an +instance's threads, so T3 sets the servers per thread, as it sets its own `t3-code` entry: when it +loads a thread (starts, resumes or forks it), it asks that app-server which MCP servers are set up +for the thread's folder (Codex's `config.toml`, a project's `.codex/config.toml`, and servers added +by `-c mcp_servers…` in the Codex launch arguments) and gives that thread +`mcp_servers..enabled = false` for each one the profile leaves out, and `features.apps = false` +unless the profile names `codex_apps` (Codex's connectors server, which it adds with a ChatGPT +sign-in and which that list never shows). T3's own servers stay. Other threads on the same +app-server keep their own sets. Codex's own sub-agents copy their parent's loaded config, these +settings included. Before each turn (and before a goal is set running) T3 reads the thread's live +servers from Codex and does not start the turn, saying why and how to go on (pick `all` for the +thread, or fix the profile), when one the profile leaves out is still switched on. Turns Codex +starts on its own (a goal's next turn, a sub-agent's turn) are checked as they start: one that +fails is stopped, the goal is paused, and the turn ends failed with the reason. A turn fails this +check when the profile was narrowed while Codex had the thread loaded (Codex reads a thread's +config only as it loads it, so the change counts once it loads the thread again: after it has been +idle a while, or after T3 restarts) and for a server a Codex plugin adds, which T3 cannot switch off +this way. A turn is also refused when the profile is missing or broken, its `t3Tools` is not +`"all"`, Codex's servers cannot be listed, a server's name cannot be written as a config key, the +thread is not in T3's store, or (once any thread on that app-server has a narrower profile) Codex +asks to load or run a thread T3 cannot match to one of its own. Codex answers the server list only +once the thread's servers have started, and T3 waits up to 30 seconds for each read: a kept server +slower to start than that refuses the turn, which can be sent again once it is up. When a resume is +refused (for example a read failed once), T3 does not move the thread to a fresh Codex session, +which would lose its history: the turn fails, and sending it again resumes the thread. A thread on +`all` sends Codex nothing extra, but T3 still works out its profile from the settings and the +thread store at each load and turn, so a thread missing from the store refuses there too. A turn already running when the profile is narrowed keeps its servers +until it ends. + +Only Claude and Codex threads apply profiles. A thread on any other provider would get every MCP server and every T3 tool whatever its profile says. So its turn is not started when its profile is narrower than `all` ([#672](https://github.com/scuttletoby/t3code/issues/672)): the machine that runs the turn checks the thread's profile as the turn starts (also a resumed turn, and a compaction, which some providers run as a `/compact` prompt) and refuses it, saying why and how to go on (switch -the thread to a Claude instance, or pick `all` for it). That covers every way a thread gets there: a +the thread to a Claude or Codex instance, or pick `all` for it). That covers every way a thread gets there: a thread switched to another provider (`t3_thread_configure`, or in the app), a thread made by `t3_thread_launch` in a project whose profile is narrower, a task delegated on this machine (a child gets its parent's profile, or `mcpSubagentProfile`), and a task another machine sent, also one from