// Codex configuration reads never call MCP discovery. The explicit status // action can discover tools for an already-loaded thread on its own daemon. import { lstat } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { CODEX_HOME } from "./codex-dir.mjs"; import { connectCodexLiveRpc, resolveCodexLiveEndpoint } from "./codex-live-rpc.mjs"; import { readCodexSkillCatalog } from "./codex-skills.mjs"; const MAX_SERVERS = 100; const MAX_TOOLS = 100; const MAX_SKILLS = 500; const record = value => value !== null && typeof value === "object" && !Array.isArray(value); const connectionStates = new Set(["notStarted", "starting", "connected", "authenticationRequired", "failed", "cancelled", "disabled"]); const pathKey = path => { const normalized = path.replace(/\\/g, "/"); return process.platform === "win32" ? normalized.toLowerCase() : normalized; }; async function codexSkillRoots(cwd, userDirectory = homedir()) { const projectDirs = []; let current = resolve(cwd); for (let depth = 0; depth < 32; depth++) { projectDirs.push(current); const marker = await lstat(join(current, ".git")).catch(() => null); if (marker?.isDirectory() || marker?.isFile()) break; const parent = dirname(current); if (parent === current || depth === 31) { projectDirs.splice(1); break; } current = parent; } const user = join(userDirectory, ".agents", "skills"); return [ ...projectDirs.map(dir => join(dir, ".agents", "skills")) .filter(dir => pathKey(dir) !== pathKey(user)).map(dir => ({ dir, scope: "project" })), { dir: user, scope: "user" }, ]; } export async function codexContextSkills(scope, scan, io = {}) { const [catalog, disk] = await Promise.all([ scope.rolloutPath ? (io.readCatalog ?? readCodexSkillCatalog)(scope.rolloutPath, { descriptions: true }) : null, codexSkillRoots(scope.cwd, io.userDirectory).then(roots => scan(roots, io)), ]); const remaining = new Map(disk.skills.map(row => [pathKey(row.path), row])); const rows = []; for (const [path, name] of catalog?.files ?? []) { if (rows.length === MAX_SKILLS) return { skills: rows, truncated: true }; const known = remaining.get(pathKey(path)); remaining.delete(pathKey(path)); rows.push({ name: name.slice(0, 120), path: known?.path ?? path.slice(0, 4096), scope: known?.scope ?? "other", description: (catalog.descriptions?.get(path) || known?.description || "").slice(0, 900), available: true }); } rows.push(...remaining.values()); return { skills: rows.slice(0, MAX_SKILLS), truncated: disk.truncated || rows.length > MAX_SKILLS }; } async function withExistingDaemon(scope, io, read) { const endpoint = await (io.resolveEndpoint ?? resolveCodexLiveEndpoint)(scope.codexHome ?? CODEX_HOME); const rpc = await (io.connect ?? connectCodexLiveRpc)(endpoint, { deadlineMs: 5000 }); try { return await read(rpc); } finally { rpc.close(); } } function configs(reply) { const block = reply?.config?.mcp_servers; if (!record(reply?.config)) throw new Error("configuration_unavailable"); if (!record(block)) return []; const layers = Array.isArray(reply.layers) ? reply.layers : []; return Object.entries(block).slice(0, MAX_SERVERS).flatMap(([name, config]) => { if (!name || !record(config)) return []; const layer = layers.find(item => !item?.disabledReason && record(item?.config?.mcp_servers) && Object.hasOwn(item.config.mcp_servers, name)); const type = layer?.name?.type; const scope = type === "user" ? "user" : type === "project" ? "project" : "other"; const transport = typeof config.command === "string" ? "stdio" : typeof config.url === "string" ? "http" : null; return [{ name: name.slice(0, 120), scope, transport, ...(config.enabled === false ? { connection: "disabled" } : {}) }]; }); } export async function codexMcpConfig(scope, io = {}) { try { return await withExistingDaemon(scope, io, async rpc => { const answer = await rpc.request("config/read", { cwd: scope.cwd, includeLayers: true }); return { servers: configs(answer), truncated: Object.keys(answer.config.mcp_servers ?? {}).length > MAX_SERVERS }; }); } catch { return { servers: [], unavailable: true }; } } async function threadLoaded(rpc, session) { let cursor; for (let page = 0; page < 5; page++) { const reply = await rpc.request("thread/loaded/list", { limit: 200, ...(cursor ? { cursor } : {}) }); if (!Array.isArray(reply?.data)) return false; if (reply.data.includes(session)) return true; cursor = reply.nextCursor; if (typeof cursor !== "string" || !cursor) break; } return false; } export async function codexMcpStatus(scope, session, io = {}) { return withExistingDaemon(scope, io, async rpc => { if (!await threadLoaded(rpc, session)) throw new Error("thread_unavailable"); const reply = await rpc.request("mcpServerStatus/list", { threadId: session, detail: "toolsAndAuthOnly", limit: MAX_SERVERS }); if (!Array.isArray(reply?.data)) throw new Error("status_unavailable"); const servers = reply.data.slice(0, MAX_SERVERS).flatMap(row => { if (typeof row?.name !== "string" || !row.name) return []; const tools = record(row.tools) ? Object.keys(row.tools) : []; return [{ name: row.name.slice(0, 120), scope: "other", transport: typeof row.httpOrigin === "string" ? "http" : null, ...(connectionStates.has(row.runtimeStatus) ? { connection: row.runtimeStatus } : {}), tools: tools.slice(0, MAX_TOOLS).map(tool => tool.slice(0, 120)), ...(tools.length > MAX_TOOLS ? { toolsTruncated: true } : {}), }]; }); return { servers, truncated: !!reply.nextCursor || reply.data.length > MAX_SERVERS }; }); }