// hosts/codex/adapter.ts — Main Codex host adapter (SPEC-592)
// Decision gate: Codex supports MCP-over-stdio natively (both STDIO and Streamable HTTP).
// No REST shim needed. See website/en/guide/hosts/codex.md for evidence.
import { appendEntry, getLastHash } from '../../storage/audit-trail-store.js';
import { detectCodexWorkspace } from './workspace-scope.js';
import { createHash } from 'node:crypto';
// Tools that have no Codex-native equivalent and require single-turn inline fallback.
// Codex does not support persistent agent teams, subagent spawning, or multi-turn plan mode.
const FALLBACK_TOOLS = new Set([
    'execute_sdd_flow', // orchestrates multi-agent teams
    'plan_mode', // interactive multi-turn planning
    'agent_swarm_status', // requires persistent subagent state
]);
/**
 * Detect whether the current environment is a Codex workspace.
 * Checks .openai/ directory, OPENAI_WORKSPACE_ID, CODEX_ENV, and CODEX_AGENT_ID.
 */
export function detectCodexEnvironment(projectPath) {
    return detectCodexWorkspace(projectPath);
}
/**
 * Activate the Codex adapter on an MCP server.
 * Registers Codex-compatible tool contracts and wires the audit-log bridge.
 * Safe to call on non-Codex environments — returns inactive result without side effects.
 */
export function activateCodexAdapter(projectPath, toolContracts) {
    const markers = detectCodexEnvironment(projectPath);
    const isCodex = markers.hasWorkspaceEnv || markers.hasCodexEnv || markers.configDir !== undefined;
    if (!isCodex) {
        return {
            active: false,
            markers,
            toolsRegistered: 0,
            fallbackTools: [],
            activatedAt: new Date().toISOString(),
        };
    }
    const fallbackTools = [];
    let toolsRegistered = 0;
    for (const contract of toolContracts) {
        if (FALLBACK_TOOLS.has(contract.name)) {
            fallbackTools.push(contract.name);
            logFallbackWarning(projectPath, contract.name);
        }
        toolsRegistered++;
    }
    const activatedAt = new Date().toISOString();
    appendAuditEntry(projectPath, 'codex_adapter_activated', {
        toolsRegistered,
        fallbackTools,
        activatedAt,
        workspaceId: markers.workspaceId,
        isEnterprise: markers.isEnterprise,
    });
    return { active: true, markers, toolsRegistered, fallbackTools, activatedAt };
}
/**
 * Bridge: append a structured event to the EU AI Act audit trail.
 * Used for adapter lifecycle events and RBAC decisions.
 * Never throws — audit must not affect tool execution.
 */
export function appendAuditEntry(projectPath, toolName, metadata) {
    try {
        const prevHash = getLastHash();
        const ts = new Date().toISOString();
        const id = `codex-${ts}-${toolName}`;
        const content = `${id}|${ts}|${toolName}|${JSON.stringify(metadata)}|${prevHash}`;
        const hash = createHash('sha256').update(content).digest('hex');
        appendEntry({
            id,
            timestamp: ts,
            toolName,
            inputSummary: JSON.stringify(metadata).slice(0, 200),
            outputType: 'success',
            durationMs: 0,
            projectPath,
            prevHash,
            hash,
        });
    }
    catch {
        /* audit must never affect tool execution */
    }
}
/**
 * Log a graceful fallback warning when a tool has no Codex-native equivalent.
 * Emits a single-line info message and writes to audit trail.
 */
function logFallbackWarning(projectPath, toolName) {
    // Single-line info per spec: "no Codex-native equivalent, falling back to inline execution"
    // eslint-disable-next-line no-console
    console.info(`[planu/codex] ${toolName}: no Codex-native equivalent — falling back to single-turn inline execution`);
    appendAuditEntry(projectPath, 'codex_fallback_activated', {
        tool: toolName,
        reason: 'no Codex-native equivalent (subagents/Agent Teams not supported)',
        strategy: 'single-turn inline execution',
    });
}
//# sourceMappingURL=adapter.js.map