/*
 * 文件定位：Agent 运行态实现层 / 执行引擎运行态绑定面 / BaseTool 开发者目录。
 * 核心目的：把 storage-owned 175 个 BaseTool 暴露成可校验的 authoring helper，避免开发者手写散乱 toolId。
 * 边界：这里只生成 ToolSpec，不执行工具、不定义工具语义、不替代 BaseTool registry。
 */
import { createBaseToolRegistry } from "../../agent_executionEngine/basic_toolLayer/baseTools/baseToolRegistry.js";
import { tool, tools } from "../runtimeAgentManifest.js";
import { createBaseToolRealityLedger, } from "./baseToolRealityLedger.js";
let cachedRegistry;
function baseToolRegistry() {
    cachedRegistry ??= createBaseToolRegistry();
    return cachedRegistry;
}
function registryInputSchema(toolId) {
    const lookup = baseToolRegistry().lookup(toolId);
    if (!lookup.ok)
        return undefined;
    const schema = lookup.definition.inputSchema;
    if (schema.kind !== "json-schema" || typeof schema.schema !== "object" || schema.schema === null || Array.isArray(schema.schema)) {
        return undefined;
    }
    return schema.schema;
}
function registryDescription(toolId) {
    const lookup = baseToolRegistry().lookup(toolId);
    if (!lookup.ok)
        return undefined;
    const description = lookup.definition.description?.trim();
    return description || undefined;
}
const ledgerByToolId = () => {
    return new Map(createBaseToolRealityLedger().map((entry) => [entry.toolId, entry]));
};
function developerEntry(entry) {
    return {
        toolId: entry.toolId,
        family: entry.family,
        storageFamily: entry.storageFamily,
        group: entry.group,
        title: entry.title,
        riskLevel: entry.riskLevel,
        capabilityClass: entry.capabilityClass,
        projection: entry.projection,
        modelRequired: entry.modelRequired,
    };
}
function toToolSpec(entry, input = {}) {
    const definitionDescription = registryDescription(entry.toolId);
    return tool(entry.toolId, {
        ...input,
        family: entry.storageFamily,
        group: entry.group,
        description: input.description ?? (definitionDescription ? `${entry.title}: ${definitionDescription}` : entry.title),
        inputSchema: input.inputSchema ?? registryInputSchema(entry.toolId),
        metadata: {
            authoringSurface: "runtime.execEngine.baseToolDeveloperCatalog",
            baseToolFamily: entry.family,
            capabilityClass: entry.capabilityClass,
            projection: entry.projection,
            modelRequired: entry.modelRequired,
            riskLevel: entry.riskLevel,
            ...(input.metadata ?? {}),
        },
    });
}
function knownTool(toolId, input = {}) {
    const entry = ledgerByToolId().get(toolId);
    if (entry === undefined) {
        return tool(toolId, {
            ...input,
            metadata: {
                authoringSurface: "runtime.execEngine.baseToolDeveloperCatalog",
                catalogError: "BASE_TOOL_NOT_FOUND",
                ...(input.metadata ?? {}),
            },
        });
    }
    return toToolSpec(entry, input);
}
export function listBaseToolDeveloperCatalog() {
    return createBaseToolRealityLedger()
        .map(developerEntry)
        .sort((left, right) => left.toolId.localeCompare(right.toolId));
}
export function tryBaseToolById(toolId, input = {}) {
    const normalizedToolId = toolId.trim();
    const entry = ledgerByToolId().get(normalizedToolId);
    if (entry === undefined) {
        return {
            ok: false,
            error: {
                code: "BASE_TOOL_NOT_FOUND",
                message: `BaseTool ${normalizedToolId} is not present in the runtime developer catalog`,
                publicSafe: true,
            },
        };
    }
    return {
        ok: true,
        tool: toToolSpec(entry, input),
        entry: developerEntry(entry),
    };
}
export const baseTools = {
    all() {
        return listBaseToolDeveloperCatalog();
    },
    family(storageFamily) {
        return listBaseToolDeveloperCatalog().filter((entry) => entry.storageFamily === storageFamily || entry.family === storageFamily);
    },
    byId: tryBaseToolById,
    code: {
        read: (input) => knownTool("code.read", input),
        scan: (input) => knownTool("code.scan", input),
        searchRipgrep: (input) => knownTool("code.search_Ripgrep", input),
        replaceFile: (input) => knownTool("code.replaceFile", input),
        modify: (input) => knownTool("code.modify", input),
        overwrite: (input) => knownTool("code.overwrite", input),
        delete: (input) => knownTool("code.delete", input),
        format: (input) => knownTool("code.format", input),
        testCode: (input) => knownTool("code.testCode", input),
        benchmark: (input) => knownTool("code.benchmark", input),
        debugRun: (input) => knownTool("code.debugRun", input),
        debugCaptureState: (input) => knownTool("code.debugCaptureState", input),
        debugCollectLogs: (input) => knownTool("code.debugCollectLogs", input),
        lsp: {
            locateDefinition: (input) => knownTool("code.lsp_locateDefinition", input),
            traceReferences: (input) => knownTool("code.lsp_traceReferences", input),
            inspectDiagnostics: (input) => knownTool("code.lsp_inspectDiagnostics", input),
            renameSymbol: (input) => knownTool("code.lsp_renameSymbol", input),
            completeCode: (input) => knownTool("code.lsp_completeCode", input),
        },
    },
    git: {
        getRepositoryStatus: (input) => knownTool("git.getRepositoryStatus", input),
        getWorkingTreeDiff: (input) => knownTool("git.getWorkingTreeDiff", input),
        getCommitHistory: (input) => knownTool("git.getCommitHistory", input),
        showGitObjectDetails: (input) => knownTool("git.showGitObjectDetails", input),
        traceLineOwnership: (input) => knownTool("git.traceLineOwnership", input),
        addToStaging: (input) => knownTool("git.addToStaging", input),
        resetStagingOrCommit: (input) => knownTool("git.resetStagingOrCommit", input),
        restoreWorkingTree: (input) => knownTool("git.restoreWorkingTree", input),
        stashChanges: (input) => knownTool("git.stashChanges", input),
        fetchRemoteUpdates: (input) => knownTool("git.fetchRemoteUpdates", input),
        pullRemoteChanges: (input) => knownTool("git.pullRemoteChanges", input),
        pushLocalChanges: (input) => knownTool("git.pushLocalChanges", input),
    },
    shell: {
        commandExecution: (input) => knownTool("shell.commandExecution", input),
        invocationExecution: (input) => knownTool("shell.invocationExecution", input),
        scriptExecution: (input) => knownTool("shell.scriptExecution", input),
        backgroundExecution: (input) => knownTool("shell.backgroundExecution", input),
        foregroundExecution: (input) => knownTool("shell.foregroundExecution", input),
        processSpawning: (input) => knownTool("shell.processSpawning", input),
        processTermination: (input) => knownTool("shell.processTermination", input),
        outputCapture: (input) => knownTool("shell.outputCapture", input),
        commandValidation: (input) => knownTool("shell.commandValidation", input),
        permissionControl: (input) => knownTool("shell.permissionControl", input),
        sandboxEnforcement: (input) => knownTool("shell.sandboxEnforcement", input),
    },
    search: {
        fetch: (input) => knownTool("search.fetch", input),
        searchEngine: (input) => knownTool("search.searchEngine", input),
        nativeSearch: (input) => knownTool("search.nativeSearch", input),
        ground: (input) => knownTool("search.ground", input),
    },
    skill: {
        generate: (input) => knownTool("skill.generate", input),
        iterate: (input) => knownTool("skill.iterate", input),
        management: (input) => knownTool("skill.management", input),
        remove: (input) => knownTool("skill.remove", input),
        ripgrep: (input) => knownTool("skill.ripgrep", input),
        summarize: (input) => knownTool("skill.summarize", input),
    },
    mcp: {
        connect: (input) => knownTool("mcp.connect", input),
        ping: (input) => knownTool("mcp.ping", input),
        listTools: (input) => knownTool("mcp.listTools", input),
        call: (input) => knownTool("mcp.call", input),
        stream: (input) => knownTool("mcp.stream", input),
        listResources: (input) => knownTool("mcp.listResources", input),
        readResource: (input) => knownTool("mcp.readResource", input),
    },
    omni: {
        viewImage: (input) => knownTool("omni.viewImage", input),
        generateImage: (input) => knownTool("omni.generateImage", input),
        imageFormatConversion: (input) => knownTool("omni.imageFormatConversion", input),
        listenAudio: (input) => knownTool("omni.listenAudio", input),
        generateAudio: (input) => knownTool("omni.generateAudio", input),
        viewVideo: (input) => knownTool("omni.viewVideo", input),
        generateVideo: (input) => knownTool("omni.generateVideo", input),
    },
    computeruse: {
        fullscreenScreenshot: (input) => knownTool("computeruse.fullscreenScreenshot", input),
        windowScreenshot: (input) => knownTool("computeruse.windowScreenshot", input),
        mouseClick: (input) => knownTool("computeruse.mouseClick", input),
        mouseMove: (input) => knownTool("computeruse.mouseMove", input),
        keyboardInputEmulation: (input) => knownTool("computeruse.keyboardInputEmulation", input),
        cameraCapturePhoto: (input) => knownTool("computeruse.cameraCapturePhoto", input),
        microphoneStartRecording: (input) => knownTool("computeruse.microphoneStartRecording", input),
    },
};
export const toolSets = {
    coding: {
        readonly(input = {}) {
            return tools([
                baseTools.code.read(),
                baseTools.code.scan(),
                baseTools.code.searchRipgrep(),
                ...(input.includeGit === true ? toolSets.git.inspection() : []),
                ...(input.includeSearch === true ? [baseTools.search.nativeSearch(), baseTools.search.fetch()] : []),
            ]);
        },
        full(input = {}) {
            return tools([
                ...toolSets.coding.readonly({ ...input, includeGit: input.includeGit ?? true }),
                baseTools.code.replaceFile(),
                baseTools.code.modify(),
                baseTools.code.overwrite(),
                baseTools.code.delete(),
                baseTools.code.format(),
                baseTools.code.testCode(),
                baseTools.code.benchmark(),
                baseTools.git.addToStaging(),
                baseTools.git.restoreWorkingTree(),
                ...(input.includeShell === true ? toolSets.shell.safe() : []),
            ]);
        },
    },
    git: {
        inspection() {
            return tools([
                baseTools.git.getRepositoryStatus(),
                baseTools.git.getWorkingTreeDiff(),
                baseTools.git.getCommitHistory(),
                baseTools.git.showGitObjectDetails(),
                baseTools.git.traceLineOwnership(),
            ]);
        },
    },
    shell: {
        safe() {
            return tools([
                baseTools.shell.commandValidation(),
                baseTools.shell.permissionControl(),
                baseTools.shell.sandboxEnforcement(),
                baseTools.shell.outputCapture(),
                baseTools.shell.commandExecution(),
            ]);
        },
    },
    research: {
        web() {
            return tools([
                baseTools.search.searchEngine(),
                baseTools.search.fetch(),
                baseTools.search.ground(),
            ]);
        },
    },
    skill: {
        context() {
            return tools([
                baseTools.skill.management(),
                baseTools.skill.summarize(),
            ]);
        },
        search() {
            return tools([
                ...toolSets.skill.context(),
                baseTools.skill.ripgrep(),
            ]);
        },
        authoring() {
            return tools([
                baseTools.skill.generate(),
                baseTools.skill.iterate(),
                baseTools.skill.remove(),
            ]);
        },
        full() {
            return tools([
                ...toolSets.skill.search(),
                ...toolSets.skill.authoring(),
            ]);
        },
    },
};
export const baseToolDeveloperCatalogDescriptor = {
    surface: "runtime.execEngine.baseToolDeveloperCatalog",
    validatesAgainst: "runtime.execEngine.baseToolRealityLedger",
    publicHelpers: ["baseTools", "toolSets", "tryBaseToolById", "listBaseToolDeveloperCatalog"],
    toolSpecFamilyUsesStorageFamily: true,
    skillBaseIsContextMaterialNotModelProvider: true,
    doesNotExecuteTools: true,
};
