/*
 * 文件定位：Agent 运行态实现层 / OAO AgentManifest 编译面。
 * 核心目的：把 PraxisAgent class 或 instance 编译为 runtime 只读执行合同。
 * 能力要求1：支持 class 与 instance 两种 OAO authoring 输入，并生成稳定 manifestHash。
 * 能力要求2：Harness 保持声明式，runtime 后续只执行 AgentManifest，不直接执行 Agent class 内部逻辑。
 * 边界：只定义 agent 编译合同，不启动进程、不读取文件、不调用模型、不执行工具。
 * 对接：需要服务 PraxisRuntimeKernel、runtime.invocationMethod、runtime.modelAdapter 和 runtime.execEngine。
 * 实现提示：Agent Archetype 只编译声明式 spec 和 stable refs，不能把函数体或 provider 字段形状塞进 runtime 执行真相。
 */
import { createHash } from "node:crypto";
import { createBaseToolSupportCatalog } from "./runtime.execEngine/baseToolSupportCatalog.js";
export class PromptPack {
    promptPackId;
    base;
    patches;
    inherits;
    sceneTriggers;
    stateMachineMutations;
    auditRefs;
    materials;
    designOwner;
    metadata;
}
export const STATE_PLANE_STANDARD_CONTROLS = [
    "pause",
    "resume",
    "interrupt",
    "approve",
    "deny",
    "rollback",
    "inspect",
    "repair",
    "configure",
    "rotateSecretRef",
];
export class PraxisAgent {
    modelFleet;
    storage;
    promptPack;
    mainLoop;
    sandbox;
    toolPolicy;
    session;
    statePlane;
    behaviors;
    hooks;
}
export class PraxisAgentArchetype extends PraxisAgent {
}
export function model(modelName, input = {}) {
    return {
        provider: input.provider ?? "openai",
        model: modelName,
        endpointShape: input.endpointShape ?? "responses",
        carrierId: input.carrierId,
        credentialRef: input.credentialRef,
        reasoning: input.reasoning,
        baseURL: input.baseURL,
        clientName: input.clientName,
        clientVersion: input.clientVersion,
        metadata: input.metadata,
    };
}
function endpointFamilyFor(endpointPath) {
    if (endpointPath === "/v1/chat/completions")
        return "chat_completions";
    return endpointPath.slice("/v1/".length);
}
function protocolFamilyFor(endpointPath) {
    if (endpointPath === "/v1/messages")
        return "anthropic-messages";
    if (endpointPath === "/v1/responses")
        return "openai-responses";
    if (endpointPath === "/v1/chat/completions")
        return "openai-compatible";
    if (endpointPath === "/v1/images")
        return "openai-images";
    if (endpointPath === "/v1/batches")
        return "openai-batches";
    if (endpointPath === "/v1/realtime")
        return "openai-realtime";
    return "custom";
}
export function endpoint(endpointPath, input) {
    const endpointFamily = endpointFamilyFor(endpointPath);
    return {
        endpointId: input.endpointId ?? `${input.role}:${endpointFamily}`,
        endpoint: endpointPath,
        endpointFamily,
        protocolFamily: input.protocolFamily ?? protocolFamilyFor(endpointPath),
        role: input.role,
        provider: input.provider,
        model: input.model,
        carrierId: input.carrierId,
        baseURL: input.baseURL,
        credentialRef: input.credentialRef,
        probe: input.probe,
        capabilityMatrix: input.capabilityMatrix,
        failurePolicy: input.failurePolicy,
        metadata: input.metadata,
    };
}
export const modelFleet = {
    auto(endpoints, input = {}) {
        const normalizedEndpoints = Object.fromEntries(Object.entries(endpoints).map(([ref, spec]) => [ref, { ...spec, endpointId: spec.endpointId || ref }]));
        return {
            mode: "auto",
            endpoints: normalizedEndpoints,
            primaryRef: input.primaryRef ?? (normalizedEndpoints.primary === undefined ? Object.keys(normalizedEndpoints)[0] : "primary"),
            probeStrategy: input.probeStrategy ?? "lazy",
            capabilityMatrix: input.capabilityMatrix,
            failurePolicy: input.failurePolicy,
            metadata: input.metadata,
        };
    },
};
export function tool(toolId, input = {}) {
    return { toolId, ...input };
}
export function tools(items) {
    return items;
}
export function policy(input = {}) {
    return input;
}
export const storage = {
    memory(input = {}) {
        return {
            kind: "memory",
            init: input.init ?? "never",
            metadata: input.metadata,
        };
    },
    sqlite(input = {}) {
        return {
            kind: "sqlite",
            path: input.path,
            homeRef: input.homeRef,
            workspaceRef: input.workspaceRef,
            sessionStoreRef: input.sessionStoreRef ?? "session.sqlite.workspace",
            artifactRootRef: input.artifactRootRef,
            cacheRootRef: input.cacheRootRef,
            sandboxRootRef: input.sandboxRootRef,
            init: input.init ?? "on-run",
            metadata: input.metadata,
        };
    },
    raxWorkspace(input = {}) {
        return {
            kind: "rax-workspace",
            path: input.path,
            homeRef: input.homeRef ?? "rax.home",
            workspaceRef: input.workspaceRef ?? "rax.workspace",
            sessionStoreRef: input.sessionStoreRef ?? "session.sqlite.workspace",
            artifactRootRef: input.artifactRootRef ?? "artifact.workspace",
            cacheRootRef: input.cacheRootRef ?? "cache.workspace",
            sandboxRootRef: input.sandboxRootRef ?? "sandbox.workspace",
            init: input.init ?? "on-run",
            metadata: input.metadata,
        };
    },
};
export const loop = Object.assign((input = { strategy: "tool-calling-v1" }) => input, {
    standard(input = {}) {
        return { strategy: "tool-calling-v1", ...input };
    },
    single(input = {}) {
        return { strategy: "single", ...input };
    },
    custom(strategy, input = {}) {
        return { strategy, ...input };
    },
});
export const mainLoop = {
    standard(input = {}) {
        const directRefs = {
            buildPrompt: input.buildPromptRef,
            chooseModel: input.chooseModelRef,
            beforeTool: input.beforeToolRef,
            afterTool: input.afterToolRef,
            onApproval: input.onApprovalRef,
            onError: input.onErrorRef,
            onResume: input.onResumeRef,
        };
        const hookInput = {
            ...directRefs,
            ...(input.hooks ?? {}),
        };
        const hooks = Object.entries(hookInput).map(([name, ref]) => {
            if (ref === undefined)
                return undefined;
            const hook = name;
            return typeof ref === "string"
                ? { hook, handlerRef: ref }
                : { hook, ...ref };
        }).filter((hook) => hook !== undefined);
        return {
            kind: "praxis.mainLoopSpec",
            strategy: "standard",
            hooks,
            stepRecordCompatible: true,
            modelDecisionCompatible: true,
            ephemeralProcedureCompatible: true,
            promptPackCompatible: true,
            metadata: input.metadata,
        };
    },
    custom(input) {
        const standard = this.standard(input);
        return {
            ...standard,
            kind: "praxis.mainLoopSpec",
            strategy: input.strategy,
        };
    },
};
export function markdown(text, ref) {
    return ref === undefined ? { kind: "markdown", text } : { kind: "markdown", text, ref };
}
export function markdownFile(path, ref) {
    return ref === undefined ? { kind: "markdownFile", path } : { kind: "markdownFile", path, ref };
}
function defaultPromptPatchId(targetRef, operation, input = {}) {
    const qualifiers = [
        input.sceneTrigger?.trim() ? `scene:${input.sceneTrigger.trim()}` : undefined,
        input.stateTrigger?.trim() ? `state:${input.stateTrigger.trim()}` : undefined,
    ].filter((value) => value !== undefined);
    return [targetRef, operation, ...qualifiers].join(":");
}
export function append(targetRef, material, input = {}) {
    return { ...input, patchId: input.patchId?.trim() || defaultPromptPatchId(targetRef, "append", input), operation: "append", targetRef, material };
}
export function prepend(targetRef, material, input = {}) {
    return { ...input, patchId: input.patchId?.trim() || defaultPromptPatchId(targetRef, "prepend", input), operation: "prepend", targetRef, material };
}
export function overwrite(targetRef, material, input = {}) {
    return { ...input, patchId: input.patchId?.trim() || defaultPromptPatchId(targetRef, "overwrite", input), operation: "overwrite", targetRef, material };
}
export function replaceLastLines(targetRef, lastLines, material, input = {}) {
    return {
        ...input,
        patchId: input.patchId?.trim() || `${defaultPromptPatchId(targetRef, "replaceLastLines", input)}:${lastLines}`,
        operation: "replaceLastLines",
        targetRef,
        lastLines,
        material,
    };
}
export const sandbox = {
    hostObserved(input = {}) {
        return {
            sandboxId: input.sandboxId ?? "sandbox.hostObserved",
            profile: "host-observed",
            filesystem: input.filesystem ?? "workspace-only",
            network: input.network ?? "deny-by-default",
            shell: input.shell ?? "approval-for-write",
            scratchRoot: input.scratchRoot ?? ".rax_workspace/sandbox",
            resourceLimits: input.resourceLimits ?? {},
            reusableProfileRef: input.reusableProfileRef,
            providerFamily: "host-observed",
            isolationLevel: "none",
            dependencyRefs: [],
            mountPolicy: {
                workspaceRootRef: "rax.workspace",
                allowedReadRoots: ["workspace", ".rax_workspace"],
                allowedWriteRoots: [".rax_workspace"],
                readonlyRoot: false,
            },
            networkPolicy: { outbound: "approval" },
            processPolicy: {
                allowShell: true,
                maxProcesses: input.resourceLimits?.maxProcesses,
            },
            platformSupport: {
                linux: "supported",
                macos: "supported",
                windows: "supported",
            },
            metadata: {
                isolation: "none",
                observation: "runtime records, gates, budgets, and approvals still apply",
                ...(input.metadata ?? {}),
            },
        };
    },
    temp(input = {}) {
        return {
            sandboxId: input.sandboxId ?? "sandbox.temp",
            profile: "temp",
            filesystem: input.filesystem ?? "workspace-only",
            network: input.network ?? "deny-by-default",
            shell: input.shell ?? "approval-for-write",
            scratchRoot: input.scratchRoot ?? ".rax_workspace/sandbox/temp",
            resourceLimits: input.resourceLimits ?? {},
            reusableProfileRef: input.reusableProfileRef,
            metadata: input.metadata,
        };
    },
    workspaceOnly(input = {}) {
        return {
            sandboxId: input.sandboxId ?? "sandbox.workspaceOnly",
            profile: "workspace-only",
            providerFamily: "workspace-policy",
            isolationLevel: "workspace-policy",
            dependencyRefs: input.dependencyRefs ?? [],
            filesystem: input.filesystem ?? "workspace-only",
            network: input.network ?? "deny-by-default",
            shell: input.shell ?? "approval-for-write",
            mountPolicy: input.mountPolicy ?? {
                workspaceRootRef: "rax.workspace",
                allowedReadRoots: ["workspace", ".rax_workspace"],
                allowedWriteRoots: ["workspace", ".rax_workspace"],
                readonlyRoot: false,
            },
            networkPolicy: input.networkPolicy ?? { outbound: "deny" },
            processPolicy: input.processPolicy ?? {
                allowShell: true,
                maxProcesses: input.resourceLimits?.maxProcesses,
            },
            platformSupport: input.platformSupport ?? {
                linux: "supported",
                macos: "supported",
                windows: "supported",
            },
            scratchRoot: input.scratchRoot ?? ".rax_workspace/sandbox/workspace",
            resourceLimits: input.resourceLimits ?? {},
            reusableProfileRef: input.reusableProfileRef,
            metadata: input.metadata,
        };
    },
    linuxBubblewrap(input = {}) {
        const resourceLimits = {
            maxProcesses: 8192,
            memoryWarningPercent: 85,
            memoryAlertPercent: 90,
            memoryThrottlePercent: 100,
            ...(input.resourceLimits ?? {}),
        };
        return {
            ...sandbox.workspaceOnly(input),
            sandboxId: input.sandboxId ?? "sandbox.linuxBubblewrap",
            profile: "linux-bubblewrap",
            providerFamily: "linux-bubblewrap",
            isolationLevel: "process-namespace",
            dependencyRefs: input.dependencyRefs ?? ["binary:bwrap"],
            mountPolicy: input.mountPolicy ?? {
                workspaceRootRef: "rax.workspace",
                allowedReadRoots: ["workspace", ".rax_workspace"],
                allowedWriteRoots: [".rax_workspace/sandbox", ".rax_workspace/sandbox/artifacts"],
                readonlyRoot: true,
            },
            networkPolicy: input.networkPolicy ?? { outbound: "provider-policy" },
            resourceLimits,
            platformSupport: input.platformSupport ?? {
                linux: "supported",
                macos: "unsupported",
                windows: "unsupported",
            },
            metadata: {
                provider: "bubblewrap",
                providerVersion: "v2",
                flatpakCompatible: true,
                fallback: "explicit-only",
                home: ".rax_workspace/sandbox/home",
                tmp: ".rax_workspace/sandbox/tmp",
                artifacts: ".rax_workspace/sandbox/artifacts",
                governanceOwner: "toolPolicy",
                ...(input.metadata ?? {}),
            },
        };
    },
    linuxBubblewrapReadonly(input = {}) {
        return sandbox.linuxBubblewrap({
            ...input,
            sandboxId: input.sandboxId ?? "sandbox.linuxBubblewrap.readonly",
            mountPolicy: {
                workspaceRootRef: "rax.workspace",
                allowedReadRoots: ["workspace", ".rax_workspace"],
                allowedWriteRoots: [".rax_workspace/sandbox", ".rax_workspace/artifacts"],
                readonlyRoot: true,
                ...(input.mountPolicy ?? {}),
            },
            networkPolicy: input.networkPolicy ?? { outbound: "deny" },
            metadata: { profileVariant: "readonly", ...(input.metadata ?? {}) },
        });
    },
    linuxBubblewrapWorkspaceWrite(input = {}) {
        return sandbox.linuxBubblewrap({
            ...input,
            sandboxId: input.sandboxId ?? "sandbox.linuxBubblewrap.workspaceWrite",
            mountPolicy: {
                workspaceRootRef: "rax.workspace",
                allowedReadRoots: ["workspace", ".rax_workspace"],
                allowedWriteRoots: ["workspace", ".rax_workspace"],
                readonlyRoot: false,
                ...(input.mountPolicy ?? {}),
            },
            metadata: { profileVariant: "workspace-write", ...(input.metadata ?? {}) },
        });
    },
    linuxBubblewrapNetworked(input = {}) {
        return sandbox.linuxBubblewrap({
            ...input,
            sandboxId: input.sandboxId ?? "sandbox.linuxBubblewrap.networked",
            networkPolicy: input.networkPolicy ?? { outbound: "allow" },
            metadata: { profileVariant: "networked", ...(input.metadata ?? {}) },
        });
    },
    rootlessContainer(input = {}) {
        return {
            ...sandbox.workspaceOnly(input),
            sandboxId: input.sandboxId ?? "sandbox.rootlessContainer",
            profile: "rootless-container",
            providerFamily: "rootless-container",
            isolationLevel: "container",
            dependencyRefs: input.dependencyRefs ?? ["binary:podman|docker"],
            platformSupport: input.platformSupport ?? {
                linux: "requires-provider",
                macos: "requires-provider",
                windows: "requires-provider",
            },
            metadata: { contractOnly: true, ...(input.metadata ?? {}) },
        };
    },
    windowsSandbox(input = {}) {
        return {
            ...sandbox.workspaceOnly(input),
            sandboxId: input.sandboxId ?? "sandbox.windowsSandbox",
            profile: "windows-sandbox",
            providerFamily: "windows-sandbox",
            isolationLevel: "light-vm",
            dependencyRefs: input.dependencyRefs ?? ["windows:Windows-Sandbox"],
            platformSupport: input.platformSupport ?? {
                linux: "unsupported",
                macos: "unsupported",
                windows: "contract-only",
            },
            metadata: { contractOnly: true, ...(input.metadata ?? {}) },
        };
    },
    macosContainerization(input = {}) {
        return {
            ...sandbox.workspaceOnly(input),
            sandboxId: input.sandboxId ?? "sandbox.macosContainerization",
            profile: "macos-containerization",
            providerFamily: "macos-containerization",
            isolationLevel: "container",
            dependencyRefs: input.dependencyRefs ?? ["macos:containerization"],
            platformSupport: input.platformSupport ?? {
                linux: "unsupported",
                macos: "contract-only",
                windows: "unsupported",
            },
            metadata: { contractOnly: true, ...(input.metadata ?? {}) },
        };
    },
    remoteWorker(input = {}) {
        return {
            ...sandbox.workspaceOnly(input),
            sandboxId: input.sandboxId ?? "sandbox.remoteWorker",
            profile: "remote-worker",
            providerFamily: "remote-worker",
            isolationLevel: "remote",
            dependencyRefs: input.dependencyRefs ?? ["remote:raxos-worker"],
            platformSupport: input.platformSupport ?? {
                linux: "requires-provider",
                macos: "requires-provider",
                windows: "requires-provider",
            },
            metadata: { contractOnly: true, ...(input.metadata ?? {}) },
        };
    },
    profile(input) {
        return input;
    },
};
function rule(action, decision, approval, metadata = {}) {
    return {
        scope: "action",
        action,
        decision,
        risk: action,
        log: "full",
        approval,
        metadata,
    };
}
function buildToolPolicyProfile(profile, input, decisions) {
    return {
        matrixId: input.matrixId ?? `toolPolicy.${profile}`,
        profile,
        defaultDecision: decisions.defaultDecision,
        familyRules: [],
        groupRules: [],
        toolRules: [],
        actionRules: [
            rule("safe", decisions.safe, decisions.safeApproval, { boundaryChecks: true }),
            rule("risky", decisions.risky, decisions.riskyApproval, { resourceControls: true }),
            rule("dangerous", decisions.dangerous, decisions.dangerousApproval, { destructiveOrExternalEffect: true }),
        ],
        readinessPolicy: "observe",
        eventLogLevel: "full",
        metadata: {
            riskScale: "safe/risky/dangerous",
            ...(input.metadata ?? {}),
        },
    };
}
export const toolPolicies = {
    custom(input = {}) {
        return {
            matrixId: input.matrixId ?? "toolPolicy.custom",
            profile: "custom",
            defaultDecision: input.defaultDecision ?? "guarded",
            familyRules: input.familyRules ?? [],
            groupRules: input.groupRules ?? [],
            toolRules: input.toolRules ?? [],
            actionRules: input.actionRules ?? [],
            readinessPolicy: input.readinessPolicy ?? "observe",
            eventLogLevel: input.eventLogLevel ?? "full",
            metadata: {
                developerAuthored: true,
                ...(input.metadata ?? {}),
            },
        };
    },
    bapr(input = {}) {
        return buildToolPolicyProfile("bapr", input, {
            defaultDecision: "allow",
            safe: "allow",
            risky: "allow",
            dangerous: "allow",
            safeApproval: "none",
            riskyApproval: "none",
            dangerousApproval: "none",
        });
    },
    yolo(input = {}) {
        return buildToolPolicyProfile("yolo", input, {
            defaultDecision: "guarded",
            safe: "allow",
            risky: "allow",
            dangerous: "approval",
            safeApproval: "none",
            riskyApproval: "none",
            dangerousApproval: "required",
        });
    },
    permissive(input = {}) {
        return buildToolPolicyProfile("permissive", input, {
            defaultDecision: "guarded",
            safe: "allow",
            risky: "guarded",
            dangerous: "approval",
            safeApproval: "none",
            riskyApproval: "on-risk",
            dangerousApproval: "required",
        });
    },
    standard(input = {}) {
        return buildToolPolicyProfile("standard", input, {
            defaultDecision: "guarded",
            safe: "guarded",
            risky: "approval",
            dangerous: "approval",
            safeApproval: "none",
            riskyApproval: "on-risk",
            dangerousApproval: "required",
        });
    },
    restricted(input = {}) {
        return buildToolPolicyProfile("restricted", input, {
            defaultDecision: "approval",
            safe: "approval",
            risky: "approval",
            dangerous: "approval",
            safeApproval: "required",
            riskyApproval: "required",
            dangerousApproval: "required",
        });
    },
    codingAgentFull(input = {}) {
        return {
            matrixId: input.matrixId ?? "toolPolicy.codingAgentFull",
            profile: "codingAgentFull",
            defaultDecision: "deny",
            familyRules: [
                { scope: "family", family: "codeBase", action: "read", decision: input.read ?? "allow", risk: "low", log: "full", approval: "none" },
                { scope: "family", family: "codeBase", action: "write", decision: input.write ?? "approval", risk: "medium", log: "full", approval: "required" },
                { scope: "family", family: "shellBase", decision: input.shell ?? "guarded", risk: "high", log: "full", approval: "on-risk" },
                { scope: "family", family: "gitBase", decision: input.git ?? "approval-on-destructive", risk: "destructive", log: "full", approval: "on-destructive" },
            ],
            groupRules: [],
            toolRules: [],
            actionRules: [],
            readinessPolicy: "observe",
            eventLogLevel: "full",
            metadata: input.metadata,
        };
    },
};
export function session(input = {}) {
    const persistence = input.persistence ?? "memory";
    return {
        persistence,
        resume: input.resume ?? "manual",
        thread: input.thread ?? "ephemeral",
        logs: input.logs ?? "summary",
        storeRef: input.storeRef ?? (persistence === "sqlite" ? "session.sqlite.workspace" : undefined),
        metadata: input.metadata,
    };
}
export function statePlane(input = {}) {
    return {
        expose: input.expose ?? ["phase", "lastAction", "toolCalls", "errors"],
        control: input.control ?? [],
        audit: input.audit ?? "summary",
        metadata: input.metadata,
    };
}
export function harness(input) {
    return input;
}
function isAgentClass(value) {
    return typeof value === "function";
}
function hasText(value) {
    return typeof value === "string" && value.trim().length > 0;
}
function cleanList(values) {
    return [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];
}
function isRecord(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}
function stableJson(value) {
    if (value === null || typeof value !== "object") {
        return JSON.stringify(value);
    }
    if (Array.isArray(value)) {
        return `[${value.map(stableJson).join(",")}]`;
    }
    const record = value;
    return `{${Object.keys(record)
        .sort()
        .filter((key) => record[key] !== undefined)
        .map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`)
        .join(",")}}`;
}
function manifestHash(manifest) {
    return createHash("sha256").update(stableJson(manifest)).digest("hex");
}
function createFrameworkCoreContract(input) {
    return {
        kind: "praxis.frameworkCoreContract",
        contractVersion: "praxis.frameworkCore.v1",
        phase: "framework-core",
        runtimeTruth: "agentManifest",
        promptPack: {
            layer: "formal",
            providerPayloadBuilder: false,
            sourceCategories: ["declared-built-in", "process-product", "user-request"],
            bindRef: "runtime.execEngine.bindPromptPack",
            loweringRef: "runtime.modelAdapter.promptLoweringRuntime",
            promptPackId: input.promptPack.promptPackId,
        },
        mainLoop: {
            layer: "formal",
            arbitraryUserJs: false,
            stepRecordCompatible: true,
            modelDecisionCompatible: true,
            ephemeralProcedureCompatible: true,
            bindRef: "runtime.execEngine.bindCoreLogic",
            strategy: input.mainLoop.strategy,
        },
        modelDecision: {
            providerNeutral: true,
            variants: ["finalOutput", "toolCall", "ephemeralProcedurePlan", "requestApproval", "continue", "fail"],
        },
        baseToolGovernance: {
            identityAxis: "family/group/toolId",
            canonicalMountChain: [
                "adaptRuntimeToolInvocation",
                "bridgeExecEngineInvocation",
                "createBaseToolRegistry.lookupHandler",
                "BaseToolHandler.invoke",
                "BaseToolExecutorPort",
            ],
            policyMatrixId: input.toolPolicy.matrixId,
            sandboxId: input.sandbox.sandboxId,
        },
        sessionStateEvent: {
            session: input.session,
            statePlane: input.statePlane,
            records: ["session", "state", "event", "modelInvocation", "toolInvocation", "mainLoopStep"],
        },
        approval: {
            interfaceSurface: true,
            defaultBehavior: "public-safe-pending",
        },
        inspectionDebug: {
            manifestInspectable: true,
            debugSnapshotReady: false,
            selfRepairContractReady: false,
        },
        officialModuleBridge: {
            tap: "contract-only",
            cmp: "contract-only",
            mp: "contract-only",
            multiagent: "contract-only",
        },
        verificationGates: [
            "manifest-hash-stable",
            "top-level-harness-consistent",
            "no-raw-secrets",
            "provider-neutral-prompt-pack",
            "baseTool-registry-chain-required",
        ],
    };
}
function normalizedFailure(code, message) {
    return { ok: false, code, message };
}
function normalizeIdentity(identity) {
    if (typeof identity === "string") {
        const id = identity.trim();
        return id.length > 0 ? { id } : undefined;
    }
    if (identity === undefined || !hasText(identity.id)) {
        return undefined;
    }
    return {
        id: identity.id.trim(),
        name: identity.name?.trim() || undefined,
        version: identity.version?.trim() || undefined,
        description: identity.description?.trim() || undefined,
    };
}
function defaultEndpointForModel(modelSpec, identityId) {
    const endpointPath = modelSpec.endpointShape === "messages"
        ? "/v1/messages"
        : modelSpec.endpointShape === "chat_completions"
            ? "/v1/chat/completions"
            : modelSpec.endpointShape === "custom"
                ? "/v1/responses"
                : "/v1/responses";
    return endpoint(endpointPath, {
        endpointId: "primary",
        role: modelSpec.endpointShape === "messages" ? "reasoning" : "background",
        provider: modelSpec.provider,
        model: modelSpec.model,
        carrierId: modelSpec.carrierId ?? `${identityId}:carrier:${modelSpec.provider}:${modelSpec.model}`,
        baseURL: modelSpec.baseURL,
        credentialRef: modelSpec.credentialRef,
    });
}
function normalizeModelFleet(input, modelSpec, identityId) {
    const fleet = input ?? modelFleet.auto({ primary: defaultEndpointForModel(modelSpec, identityId) });
    const endpointEntries = Object.entries(fleet.endpoints ?? {});
    if (endpointEntries.length === 0) {
        return normalizedFailure("INVALID_MODEL_FLEET", "modelFleet requires at least one endpoint");
    }
    const endpointPaths = [
        "/v1/messages",
        "/v1/responses",
        "/v1/chat/completions",
        "/v1/images",
        "/v1/batches",
        "/v1/realtime",
    ];
    const endpoints = Object.fromEntries(endpointEntries.map(([ref, spec]) => {
        if (!hasText(ref) || !hasText(spec.endpointId)) {
            return [ref, undefined];
        }
        if (!endpointPaths.includes(spec.endpoint)) {
            return [ref, undefined];
        }
        return [ref.trim(), {
                ...spec,
                endpointId: spec.endpointId.trim(),
                endpointFamily: endpointFamilyFor(spec.endpoint),
                protocolFamily: spec.protocolFamily ?? protocolFamilyFor(spec.endpoint),
                role: spec.role,
            }];
    }));
    if (Object.values(endpoints).some((spec) => spec === undefined)) {
        return normalizedFailure("INVALID_MODEL_FLEET", "modelFleet endpoints must use supported /v1 endpoint families and stable ids");
    }
    const primaryRef = fleet.primaryRef?.trim() || endpointEntries[0]?.[0];
    if (primaryRef === undefined || endpoints[primaryRef] === undefined) {
        return normalizedFailure("INVALID_MODEL_FLEET", "modelFleet primaryRef must point to a declared endpoint");
    }
    return {
        ok: true,
        value: {
            mode: fleet.mode,
            endpoints: endpoints,
            primaryRef,
            probeStrategy: fleet.probeStrategy ?? "lazy",
            capabilityMatrix: fleet.capabilityMatrix,
            failurePolicy: fleet.failurePolicy,
            metadata: fleet.metadata ?? {},
        },
    };
}
function materialHasContent(material) {
    if (material === undefined)
        return true;
    if (material.kind === "markdown")
        return hasText(material.text);
    if (material.kind === "markdownFile")
        return hasText(material.path);
    return hasText(material.ref);
}
function normalizePromptPatch(patch) {
    return {
        ...patch,
        patchId: patch.patchId.trim(),
        targetRef: patch.targetRef.trim(),
        sceneTrigger: patch.sceneTrigger?.trim() || undefined,
        stateTrigger: patch.stateTrigger?.trim() || undefined,
        auditRefs: cleanList(patch.auditRefs),
    };
}
function normalizePromptPack(input, identityId) {
    const source = input ?? {};
    const base = source.base;
    if (!materialHasContent(base)) {
        return normalizedFailure("INVALID_PROMPT_PACK", "promptPack base material must reference markdown, markdownFile, or materialRef content");
    }
    const patchIds = new Set();
    const normalizedPatches = [];
    const normalizedStateMutations = [];
    for (const [collectionName, target] of [
        ["patches", normalizedPatches],
        ["stateMachineMutations", normalizedStateMutations],
    ]) {
        for (const patch of source[collectionName] ?? []) {
            if (!hasText(patch.patchId) || !hasText(patch.targetRef) || !materialHasContent(patch.material)) {
                return normalizedFailure("INVALID_PROMPT_PACK", "promptPack patches require patchId, targetRef, and material");
            }
            if (patch.operation === "replaceLastLines" && (patch.lastLines === undefined || patch.lastLines < 1)) {
                return normalizedFailure("INVALID_PROMPT_PACK", "replaceLastLines patch requires a positive lastLines value");
            }
            if (patch.operation === "range" && (patch.range === undefined || patch.range.startLine < 1 || patch.range.endLine < patch.range.startLine)) {
                return normalizedFailure("INVALID_PROMPT_PACK", "range prompt patch requires a valid line range");
            }
            const normalized = normalizePromptPatch(patch);
            if (patchIds.has(normalized.patchId)) {
                return normalizedFailure("INVALID_PROMPT_PACK", `promptPack patchId must be unique: ${normalized.patchId}`);
            }
            patchIds.add(normalized.patchId);
            target.push(normalized);
        }
    }
    return {
        ok: true,
        value: {
            promptPackId: source.promptPackId?.trim() || `${identityId}:promptPack`,
            base,
            inherits: cleanList(source.inherits),
            patches: normalizedPatches,
            sceneTriggers: cleanList(source.sceneTriggers),
            stateMachineMutations: normalizedStateMutations,
            auditRefs: cleanList(source.auditRefs),
            materials: source.materials ?? [],
            designOwner: source.designOwner ?? (input === undefined ? "runtime-shim" : "archetype"),
            metadata: source.metadata ?? {},
        },
    };
}
function normalizeMainLoop(input) {
    const spec = input ?? mainLoop.standard();
    for (const hook of spec.hooks) {
        if (!hasText(hook.hook)) {
            return normalizedFailure("INVALID_MAIN_LOOP", "mainLoop hook requires a stable hook name");
        }
        if (Object.values(hook).some((value) => typeof value === "function")) {
            return normalizedFailure("INVALID_MAIN_LOOP", "mainLoop hooks must compile to stable refs, not function bodies");
        }
        if (!hasText(hook.strategyRef) && !hasText(hook.handlerRef) && !hasText(hook.policyRef)) {
            return normalizedFailure("INVALID_MAIN_LOOP", "mainLoop hook requires strategyRef, handlerRef, or policyRef");
        }
    }
    return {
        ok: true,
        value: {
            ...spec,
            hooks: spec.hooks.map((hook) => ({
                hook: hook.hook,
                strategyRef: hook.strategyRef?.trim() || undefined,
                handlerRef: hook.handlerRef?.trim() || undefined,
                policyRef: hook.policyRef?.trim() || undefined,
                metadata: hook.metadata,
            })),
            metadata: spec.metadata ?? {},
        },
    };
}
function normalizeSandbox(input) {
    const spec = input ?? sandbox.hostObserved();
    if (!hasText(spec.sandboxId) || !hasText(spec.profile) || !hasText(spec.filesystem) || !hasText(spec.network) || !hasText(spec.shell)) {
        return normalizedFailure("INVALID_SANDBOX", "sandbox requires stable sandboxId, profile, filesystem, network, and shell fields");
    }
    const resourceLimits = spec.resourceLimits ?? {};
    for (const [key, value] of Object.entries(resourceLimits)) {
        if (key === "metadata" || value === undefined)
            continue;
        if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
            return normalizedFailure("INVALID_SANDBOX", "sandbox resource limits must be positive finite numbers");
        }
    }
    return {
        ok: true,
        value: {
            ...spec,
            sandboxId: spec.sandboxId.trim(),
            profile: spec.profile.trim(),
            providerFamily: spec.providerFamily?.trim() ?? (spec.profile === "host-observed"
                ? "host-observed"
                : spec.profile === "workspace-only" || spec.profile === "workspace"
                    ? "workspace-policy"
                    : spec.profile),
            isolationLevel: spec.isolationLevel?.trim() ?? (spec.profile === "host-observed"
                ? "none"
                : spec.profile === "workspace-only" || spec.profile === "workspace"
                    ? "workspace-policy"
                    : "custom"),
            dependencyRefs: cleanList(spec.dependencyRefs),
            filesystem: spec.filesystem.trim(),
            network: spec.network.trim(),
            shell: spec.shell.trim(),
            scratchRoot: spec.scratchRoot?.trim() || ".rax_workspace/sandbox",
            mountPolicy: spec.mountPolicy === undefined ? undefined : {
                ...spec.mountPolicy,
                allowedReadRoots: cleanList(spec.mountPolicy.allowedReadRoots),
                allowedWriteRoots: cleanList(spec.mountPolicy.allowedWriteRoots),
                tmpfsRefs: cleanList(spec.mountPolicy.tmpfsRefs),
                metadata: spec.mountPolicy.metadata ?? {},
            },
            networkPolicy: spec.networkPolicy === undefined ? undefined : {
                ...spec.networkPolicy,
                allowedHosts: cleanList(spec.networkPolicy.allowedHosts),
                metadata: spec.networkPolicy.metadata ?? {},
            },
            processPolicy: spec.processPolicy === undefined ? undefined : {
                ...spec.processPolicy,
                allowedCommands: cleanList(spec.processPolicy.allowedCommands),
                metadata: spec.processPolicy.metadata ?? {},
            },
            platformSupport: spec.platformSupport === undefined ? undefined : {
                ...spec.platformSupport,
                minimumVersions: spec.platformSupport.minimumVersions ?? {},
                metadata: spec.platformSupport.metadata ?? {},
            },
            resourceLimits,
            metadata: spec.metadata ?? {},
        },
    };
}
function normalizeToolPolicy(input) {
    const spec = input ?? toolPolicies.standard({ matrixId: "toolPolicy.standard.default" });
    if (!hasText(spec.matrixId) || !hasText(spec.profile)) {
        return normalizedFailure("INVALID_TOOL_POLICY", "tool policy matrix requires stable matrixId and profile");
    }
    const familyRules = spec.familyRules ?? [];
    const groupRules = spec.groupRules ?? [];
    const toolRules = spec.toolRules ?? [];
    const actionRules = spec.actionRules ?? [];
    for (const rule of [...familyRules, ...groupRules, ...toolRules, ...actionRules]) {
        if (!hasText(rule.decision)) {
            return normalizedFailure("INVALID_TOOL_POLICY", "BaseTool policy rules require a decision");
        }
        if (rule.scope === "family" && !hasText(rule.family)) {
            return normalizedFailure("INVALID_TOOL_POLICY", "family-level BaseTool policy requires family");
        }
        if (rule.scope === "group" && (!hasText(rule.family) || !hasText(rule.group))) {
            return normalizedFailure("INVALID_TOOL_POLICY", "group-level BaseTool policy requires family and group");
        }
        if (rule.scope === "toolId" && !hasText(rule.toolId)) {
            return normalizedFailure("INVALID_TOOL_POLICY", "toolId-level BaseTool policy requires toolId");
        }
        if (rule.scope === "action" && !hasText(rule.action)) {
            return normalizedFailure("INVALID_TOOL_POLICY", "action-level BaseTool policy requires action");
        }
    }
    return {
        ok: true,
        value: {
            ...spec,
            matrixId: spec.matrixId.trim(),
            profile: spec.profile.trim(),
            familyRules,
            groupRules,
            toolRules,
            actionRules,
            metadata: spec.metadata ?? {},
        },
    };
}
function normalizeHarnessTools(input) {
    const selectedTools = input ?? [];
    const catalogByToolId = new Map(createBaseToolSupportCatalog().map((entry) => [entry.toolId, entry]));
    const normalized = [];
    const seenToolIds = new Set();
    for (const selectedTool of selectedTools) {
        if (!hasText(selectedTool.toolId)) {
            return normalizedFailure("INVALID_TOOL_SPEC", "harness tools require stable toolId");
        }
        const toolId = selectedTool.toolId.trim();
        const entry = catalogByToolId.get(toolId);
        if (entry === undefined) {
            return normalizedFailure("INVALID_TOOL_SPEC", `harness references unknown BaseTool: ${toolId}`);
        }
        const family = selectedTool.family?.trim();
        if (family !== undefined && family.length > 0 && family !== entry.family && family !== entry.storageFamily) {
            return normalizedFailure("INVALID_TOOL_SPEC", `harness tool ${toolId} family must match ${entry.storageFamily} or ${entry.family}`);
        }
        const group = selectedTool.group?.trim();
        if (group !== undefined && group.length > 0 && group !== entry.group) {
            return normalizedFailure("INVALID_TOOL_SPEC", `harness tool ${toolId} group must match ${entry.group}`);
        }
        if (seenToolIds.has(toolId)) {
            continue;
        }
        seenToolIds.add(toolId);
        normalized.push({
            ...selectedTool,
            toolId,
            family: entry.storageFamily,
            group: entry.group,
            description: selectedTool.description ?? entry.title,
            metadata: {
                baseToolFamily: entry.family,
                riskLevel: entry.riskLevel,
                ...(selectedTool.metadata ?? {}),
            },
        });
    }
    return { ok: true, value: normalized };
}
function normalizeSession(input) {
    const spec = input ?? session();
    if (!hasText(spec.persistence) || !hasText(spec.resume) || !hasText(spec.thread) || !hasText(spec.logs)) {
        return normalizedFailure("INVALID_SESSION", "session spec requires persistence, resume, thread, and logs");
    }
    return {
        ok: true,
        value: {
            ...spec,
            storeRef: spec.storeRef ?? (spec.persistence === "sqlite" ? "session.sqlite.workspace" : undefined),
            metadata: spec.metadata ?? {},
        },
    };
}
function normalizeStorage(input, sessionSpec) {
    const spec = input ?? (sessionSpec.persistence === "sqlite" ? storage.raxWorkspace() : storage.memory());
    if (!hasText(spec.kind)) {
        return normalizedFailure("INVALID_MANIFEST", "storage spec requires a stable kind");
    }
    if (spec.path !== undefined && !hasText(spec.path)) {
        return normalizedFailure("INVALID_MANIFEST", "storage path must be non-empty when provided");
    }
    if (spec.init !== undefined && !["manual", "on-run", "never"].includes(spec.init)) {
        return normalizedFailure("INVALID_MANIFEST", "storage init policy must be manual, on-run, or never");
    }
    if ((spec.kind === "sqlite" || spec.kind === "rax-workspace") && sessionSpec.persistence === "sqlite") {
        return {
            ok: true,
            value: {
                ...spec,
                homeRef: spec.homeRef ?? "rax.home",
                workspaceRef: spec.workspaceRef ?? "rax.workspace",
                sessionStoreRef: spec.sessionStoreRef ?? sessionSpec.storeRef ?? "session.sqlite.workspace",
                artifactRootRef: spec.artifactRootRef ?? "artifact.workspace",
                cacheRootRef: spec.cacheRootRef ?? "cache.workspace",
                sandboxRootRef: spec.sandboxRootRef ?? "sandbox.workspace",
                init: spec.init ?? "on-run",
                metadata: spec.metadata ?? {},
            },
        };
    }
    return {
        ok: true,
        value: {
            ...spec,
            init: spec.init ?? (spec.kind === "memory" ? "never" : "manual"),
            metadata: spec.metadata ?? {},
        },
    };
}
function normalizeStatePlane(input) {
    const spec = input ?? { expose: ["phase", "lastAction", "toolCalls", "errors"], control: [], audit: "summary" };
    const expose = cleanList(spec.expose);
    const control = cleanList(spec.control);
    if (expose.length === 0) {
        return normalizedFailure("INVALID_STATE_PLANE", "statePlane expose list must contain at least one stable field");
    }
    return { ok: true, value: { expose, control, audit: spec.audit, metadata: spec.metadata ?? {} } };
}
function normalizeHarness(input, authoring, normalizedTools) {
    const loopSpec = input.loop ?? { strategy: "tool-calling-v1", maxModelTurns: 2, maxToolCalls: 4 };
    const contextRefs = cleanList(input.contextRefs ?? input.context?.refs);
    const memoryRefs = cleanList(input.memoryRefs ?? (input.memory?.pool === undefined ? undefined : [input.memory.pool]));
    return {
        modelRef: input.modelRef?.trim() || `${authoring.identityId}:model:${authoring.model.provider}:${authoring.model.model}`,
        modelFleetRef: input.modelFleetRef?.trim() || `${authoring.identityId}:modelFleet`,
        promptPackRef: input.promptPackRef?.trim() || authoring.promptPack.promptPackId,
        toolPolicyRef: input.toolPolicyRef?.trim() || authoring.toolPolicy.matrixId,
        mainLoopRef: input.mainLoopRef?.trim() || `mainLoop:${authoring.mainLoop.strategy}`,
        sandboxRef: input.sandboxRef?.trim() || authoring.sandbox.sandboxId,
        storageRef: input.storageRef?.trim() || authoring.storage.workspaceRef || authoring.storage.kind || "storage.default",
        sessionRef: input.sessionRef?.trim() || authoring.session.storeRef || `session:${authoring.session.persistence}`,
        statePlaneRef: input.statePlaneRef?.trim() || "statePlane.default",
        interfaceRefs: cleanList(input.interfaceRefs),
        contextRefs,
        memoryRefs,
        context: input.context ?? {},
        memory: input.memory ?? { mode: "session", pool: memoryRefs[0] },
        storage: authoring.storage,
        promptPack: {
            promptPackId: authoring.promptPack.promptPackId,
            base: authoring.promptPack.base,
            inherits: authoring.promptPack.inherits,
            patches: authoring.promptPack.patches,
            sceneTriggers: authoring.promptPack.sceneTriggers,
            stateMachineMutations: authoring.promptPack.stateMachineMutations,
            auditRefs: authoring.promptPack.auditRefs,
            materials: authoring.promptPack.materials,
            designOwner: authoring.promptPack.designOwner,
            metadata: authoring.promptPack.metadata,
        },
        tools: normalizedTools,
        policy: input.policy ?? {},
        loop: {
            strategy: loopSpec.strategy,
            maxModelTurns: loopSpec.maxModelTurns ?? 2,
            maxToolCalls: loopSpec.maxToolCalls ?? 4,
            metadata: loopSpec.metadata,
        },
        modelFleet: authoring.modelFleet,
        mainLoop: authoring.mainLoop,
        sandbox: authoring.sandbox,
        toolPolicy: authoring.toolPolicy,
        session: authoring.session,
        statePlane: authoring.statePlane,
        frameworkCore: authoring.frameworkCore,
        modules: input.modules ?? {},
        runtimeRequirements: cleanList(input.runtimeRequirements),
        metadata: input.metadata ?? {},
    };
}
function failure(code, message, boundary) {
    return {
        ok: false,
        error: { code, message, boundary, publicSafe: true },
        events: ["runtime.agentManifest.compile.rejected"],
    };
}
export function compileAgent(input, options = {}) {
    if (input === undefined) {
        return failure("MISSING_AGENT", "compileAgent requires a PraxisAgent class or instance", "input");
    }
    let agent;
    let source;
    try {
        if (isAgentClass(input)) {
            agent = new input();
            source = {
                kind: "class",
                className: input.name || undefined,
                constructorSideEffectsAllowed: false,
            };
        }
        else {
            agent = input;
            source = {
                kind: "instance",
                className: input.constructor.name || undefined,
                constructorSideEffectsAllowed: false,
            };
        }
    }
    catch {
        return failure("INVALID_AGENT_CLASS", "compileAgent could not instantiate the provided Agent class", "agent-object");
    }
    const identity = normalizeIdentity(agent.identity);
    if (identity === undefined) {
        return failure("MISSING_IDENTITY", "PraxisAgent requires a stable identity", "agent-object");
    }
    if (agent.model === undefined) {
        return failure("MISSING_MODEL", "PraxisAgent requires a model spec", "agent-object");
    }
    if (!hasText(agent.model.model)) {
        return failure("MISSING_MODEL_NAME", "PraxisAgent model spec requires a model name", "agent-object");
    }
    if (agent.harness === undefined) {
        return failure("MISSING_HARNESS", "PraxisAgent requires a declarative harness", "agent-object");
    }
    const compiledAt = options.compiledAt ?? new Date().toISOString();
    const modelSpec = {
        ...agent.model,
        provider: agent.model.provider,
        model: agent.model.model.trim(),
        endpointShape: agent.model.endpointShape ?? "responses",
        carrierId: agent.model.carrierId ?? `${identity.id}:carrier:${agent.model.provider}:${agent.model.model.trim()}`,
    };
    const modelFleetSpec = normalizeModelFleet(agent.modelFleet ?? agent.harness.modelFleet, modelSpec, identity.id);
    if (!modelFleetSpec.ok) {
        return failure(modelFleetSpec.code, modelFleetSpec.message, "agent-object");
    }
    const promptPackSpec = normalizePromptPack(agent.promptPack ?? agent.harness.promptPack, identity.id);
    if (!promptPackSpec.ok) {
        return failure(promptPackSpec.code, promptPackSpec.message, "agent-object");
    }
    const mainLoopSpec = normalizeMainLoop(agent.mainLoop ?? agent.harness.mainLoop);
    if (!mainLoopSpec.ok) {
        return failure(mainLoopSpec.code, mainLoopSpec.message, "agent-object");
    }
    const sandboxSpec = normalizeSandbox(agent.sandbox ?? agent.harness.sandbox);
    if (!sandboxSpec.ok) {
        return failure(sandboxSpec.code, sandboxSpec.message, "agent-object");
    }
    const toolPolicySpec = normalizeToolPolicy(agent.toolPolicy ?? agent.harness.toolPolicy);
    if (!toolPolicySpec.ok) {
        return failure(toolPolicySpec.code, toolPolicySpec.message, "agent-object");
    }
    const harnessTools = normalizeHarnessTools(agent.harness.tools);
    if (!harnessTools.ok) {
        return failure(harnessTools.code, harnessTools.message, "agent-object");
    }
    const sessionSpec = normalizeSession(agent.session ?? agent.harness.session);
    if (!sessionSpec.ok) {
        return failure(sessionSpec.code, sessionSpec.message, "agent-object");
    }
    const storageSpec = normalizeStorage(agent.storage ?? agent.harness.storage, sessionSpec.value);
    if (!storageSpec.ok) {
        return failure(storageSpec.code, storageSpec.message, "agent-object");
    }
    const statePlaneSpec = normalizeStatePlane(agent.statePlane ?? agent.harness.statePlane);
    if (!statePlaneSpec.ok) {
        return failure(statePlaneSpec.code, statePlaneSpec.message, "agent-object");
    }
    const authoring = {
        identityId: identity.id,
        model: modelSpec,
        modelFleet: modelFleetSpec.value,
        promptPack: promptPackSpec.value,
        mainLoop: mainLoopSpec.value,
        storage: storageSpec.value,
        sandbox: sandboxSpec.value,
        toolPolicy: toolPolicySpec.value,
        session: sessionSpec.value,
        statePlane: statePlaneSpec.value,
        frameworkCore: createFrameworkCoreContract({
            promptPack: promptPackSpec.value,
            mainLoop: mainLoopSpec.value,
            sandbox: sandboxSpec.value,
            toolPolicy: toolPolicySpec.value,
            session: sessionSpec.value,
            statePlane: statePlaneSpec.value,
        }),
    };
    const manifestWithoutHash = {
        kind: "praxis.agentManifest",
        schemaVersion: "praxis.agentManifest.v1",
        manifestId: options.manifestId ?? `${identity.id}:manifest`,
        compiledAt,
        source,
        identity,
        model: modelSpec,
        modelFleet: authoring.modelFleet,
        promptPack: authoring.promptPack,
        mainLoop: authoring.mainLoop,
        storage: authoring.storage,
        sandbox: authoring.sandbox,
        toolPolicy: authoring.toolPolicy,
        session: authoring.session,
        statePlane: authoring.statePlane,
        frameworkCore: authoring.frameworkCore,
        harness: normalizeHarness(agent.harness, authoring, harnessTools.value),
        behaviors: agent.behaviors,
        hooks: agent.hooks,
        verification: {
            compiled: true,
            harnessDeclarative: true,
            runtimeExecutesManifestOnly: true,
        },
    };
    return {
        ok: true,
        manifest: {
            ...manifestWithoutHash,
            manifestHash: manifestHash(manifestWithoutHash),
        },
        events: ["runtime.agentManifest.compiled"],
    };
}
function manifestValidationFailure(code, message, boundary) {
    return {
        ok: false,
        error: { code, message, boundary, publicSafe: true },
        events: ["runtime.agentManifest.validation.rejected"],
    };
}
function manifestWithoutHash(manifest) {
    const { manifestHash: _manifestHash, ...withoutHash } = manifest;
    return withoutHash;
}
function looksLikeRawSecretKey(key) {
    return /(^|_)(api[-_]?key|secret|access[-_]?token|refresh[-_]?token|password|bearer)(_|$)/i.test(key);
}
function containsRawSecretShape(value) {
    if (value === null || value === undefined) {
        return false;
    }
    if (Array.isArray(value)) {
        return value.some(containsRawSecretShape);
    }
    if (!isRecord(value)) {
        return false;
    }
    return Object.entries(value).some(([key, nested]) => looksLikeRawSecretKey(key) || containsRawSecretShape(nested));
}
export function validateAgentManifest(input) {
    if (!isRecord(input)) {
        return manifestValidationFailure("MISSING_MANIFEST", "AgentManifest validation requires a manifest object", "input");
    }
    if (input.kind !== "praxis.agentManifest") {
        return manifestValidationFailure("INVALID_KIND", "AgentManifest kind must be praxis.agentManifest", "manifest");
    }
    if (input.schemaVersion !== "praxis.agentManifest.v1") {
        return manifestValidationFailure("INVALID_SCHEMA_VERSION", "AgentManifest schemaVersion must be praxis.agentManifest.v1", "manifest");
    }
    const manifest = input;
    if (!hasText(manifest.manifestId)) {
        return manifestValidationFailure("MISSING_MANIFEST_ID", "AgentManifest requires a stable manifestId", "manifest");
    }
    if (!hasText(manifest.manifestHash)) {
        return manifestValidationFailure("MISSING_HASH", "AgentManifest requires a manifestHash", "manifest");
    }
    if (manifest.frameworkCore?.kind !== "praxis.frameworkCoreContract") {
        return manifestValidationFailure("MISSING_FRAMEWORK_CORE", "AgentManifest requires a frameworkCore contract", "manifest");
    }
    if (containsRawSecretShape(manifest.model) || containsRawSecretShape(manifest.modelFleet)) {
        return manifestValidationFailure("RAW_SECRET_REJECTED", "AgentManifest must contain credential refs, not raw provider secrets", "security");
    }
    const expectedHash = manifestHash(manifestWithoutHash(manifest));
    if (manifest.manifestHash !== expectedHash) {
        return manifestValidationFailure("HASH_MISMATCH", "AgentManifest hash does not match its stable contents", "manifest");
    }
    if (manifest.harness?.promptPack?.promptPackId !== manifest.promptPack?.promptPackId ||
        manifest.harness?.promptPackRef !== manifest.promptPack?.promptPackId ||
        manifest.harness?.toolPolicyRef !== manifest.toolPolicy?.matrixId ||
        manifest.harness?.sandboxRef !== manifest.sandbox?.sandboxId ||
        manifest.harness?.mainLoop?.strategy !== manifest.mainLoop?.strategy ||
        manifest.harness?.storage?.kind !== manifest.storage?.kind ||
        manifest.harness?.storage?.sessionStoreRef !== manifest.storage?.sessionStoreRef ||
        manifest.harness?.sandbox?.sandboxId !== manifest.sandbox?.sandboxId ||
        manifest.harness?.toolPolicy?.matrixId !== manifest.toolPolicy?.matrixId ||
        manifest.harness?.frameworkCore?.promptPack?.promptPackId !== manifest.frameworkCore.promptPack.promptPackId) {
        return manifestValidationFailure("HARNESS_VIEW_MISMATCH", "AgentManifest top-level authoring fields must mirror harness view", "consistency");
    }
    return {
        ok: true,
        manifest,
        events: ["runtime.agentManifest.validation.accepted"],
    };
}
export function inspectAgentManifest(manifest) {
    return {
        manifestId: manifest.manifestId,
        manifestHash: manifest.manifestHash,
        identityId: manifest.identity.id,
        model: {
            provider: manifest.model.provider,
            model: manifest.model.model,
            carrierId: manifest.model.carrierId,
            endpointShape: manifest.model.endpointShape,
            fleetMode: manifest.modelFleet.mode,
            endpoints: Object.keys(manifest.modelFleet.endpoints),
        },
        promptPack: {
            promptPackId: manifest.promptPack.promptPackId,
            designOwner: manifest.promptPack.designOwner,
            patchCount: manifest.promptPack.patches.length + manifest.promptPack.stateMachineMutations.length,
            materialCount: manifest.promptPack.materials.length,
        },
        mainLoop: {
            strategy: manifest.mainLoop.strategy,
            hookCount: manifest.mainLoop.hooks.length,
            formalLayer: manifest.frameworkCore.mainLoop.layer === "formal",
        },
        governance: {
            sandboxProfile: manifest.sandbox.profile,
            sandboxId: manifest.sandbox.sandboxId,
            toolPolicyProfile: manifest.toolPolicy.profile,
            policyMatrixId: manifest.toolPolicy.matrixId,
        },
        sessionState: {
            persistence: manifest.session.persistence,
            resume: manifest.session.resume,
            thread: manifest.session.thread,
            storageKind: manifest.storage.kind ?? "unknown",
            sessionStoreRef: manifest.storage.sessionStoreRef ?? manifest.session.storeRef,
            exposedState: manifest.statePlane.expose,
            controls: manifest.statePlane.control,
        },
        frameworkCore: {
            contractVersion: manifest.frameworkCore.contractVersion,
            promptPackBindRef: manifest.frameworkCore.promptPack.bindRef,
            mainLoopBindRef: manifest.frameworkCore.mainLoop.bindRef,
            officialModules: manifest.frameworkCore.officialModuleBridge,
        },
        runtimeRequirements: manifest.harness.runtimeRequirements,
        verificationGates: manifest.frameworkCore.verificationGates,
    };
}
