export const mouseScrollDescriptor = {
    toolId: "computeruse.mouseScroll",
    capability: "scroll-pointer",
    route: "agent_executionEngine.basic_toolLayer.baseTools.computeruseBase.mouseEmulation",
    defaultDryRun: true,
    defaultCoordinateSpace: "screen",
    defaultDurationMs: 0,
    maxScrollDelta: 100_000,
    maxCoordinate: 100_000,
    maxDurationMs: 10_000,
    tapOwnsApproval: true,
    runtimeEntry: "BaseToolExecutorPort.computeruse.pointerAction",
    permissionsRequired: ["pointer:write", "ui:action"],
    unsafeSideEffects: true,
};
function isRecord(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}
function cleanString(value) {
    return typeof value === "string" && value.trim().length > 0 && !value.includes("\0") ? value.trim() : undefined;
}
function cleanStringList(value) {
    if (value === undefined)
        return undefined;
    if (!Array.isArray(value))
        return undefined;
    const cleaned = [];
    for (const item of value) {
        const text = cleanString(item);
        if (text === undefined)
            return undefined;
        if (!cleaned.includes(text))
            cleaned.push(text);
    }
    return cleaned;
}
function cleanGate(value) {
    if (value === undefined)
        return undefined;
    if (!isRecord(value))
        return undefined;
    const gate = {};
    if (typeof value.accepted === "boolean")
        gate.accepted = value.accepted;
    if (typeof value.allowed === "boolean")
        gate.allowed = value.allowed;
    const reason = cleanString(value.reason);
    if (reason !== undefined)
        gate.reason = reason;
    return gate;
}
function cleanAuditMetadata(value) {
    return isRecord(value) ? value : undefined;
}
function cleanCoordinateSpace(value) {
    if (value === undefined)
        return mouseScrollDescriptor.defaultCoordinateSpace;
    return value === "screen" || value === "window" || value === "normalized" ? value : undefined;
}
function cleanDuration(value) {
    if (value === undefined)
        return mouseScrollDescriptor.defaultDurationMs;
    return typeof value === "number" &&
        Number.isInteger(value) &&
        value >= 0 &&
        value <= mouseScrollDescriptor.maxDurationMs
        ? value
        : undefined;
}
function cleanCoordinate(value) {
    return typeof value === "number" &&
        Number.isFinite(value) &&
        value >= 0 &&
        value <= mouseScrollDescriptor.maxCoordinate
        ? Math.round(value)
        : undefined;
}
function cleanDelta(value) {
    return typeof value === "number" &&
        Number.isFinite(value) &&
        Math.abs(value) <= mouseScrollDescriptor.maxScrollDelta
        ? Math.round(value)
        : undefined;
}
function auditEvent(type, context, metadata) {
    return {
        type,
        toolId: mouseScrollDescriptor.toolId,
        invocationId: context?.invocationId ?? "computeruse.mouseScroll:dry-run",
        dryRun: context?.dryRun !== false,
        metadata: {
            ...(context?.auditMetadata ?? {}),
            ...(metadata ?? {}),
        },
    };
}
function failure(code, message, boundary, context) {
    return {
        ok: false,
        toolId: mouseScrollDescriptor.toolId,
        error: {
            code,
            message,
            boundary,
            publicSafe: true,
            safeForRuntimeInspection: true,
            internalDetailExposed: false,
        },
        audit: [auditEvent("agentCore.basicTool.computeruse.mouseScroll.rejected", context, { code })],
        events: ["basicTool.computeruse.mouseScroll.rejected"],
    };
}
function normalizeContext(value) {
    if (value === undefined)
        return {};
    if (!isRecord(value))
        return failure("INVALID_CONTEXT", "computeruse.mouseScroll context must be an object", "input", undefined);
    const requestedScopes = cleanStringList(value.requestedScopes);
    const allowedScopes = cleanStringList(value.allowedScopes);
    const guard = cleanGate(value.guard);
    const contract = cleanGate(value.contract);
    const governance = cleanGate(value.governance);
    if ((value.requestedScopes !== undefined && requestedScopes === undefined) ||
        (value.allowedScopes !== undefined && allowedScopes === undefined) ||
        (value.guard !== undefined && guard === undefined) ||
        (value.contract !== undefined && contract === undefined) ||
        (value.governance !== undefined && governance === undefined) ||
        (value.dryRun !== undefined && typeof value.dryRun !== "boolean")) {
        return failure("INVALID_CONTEXT", "computeruse.mouseScroll context contains malformed guard, governance, or scope fields", "input", undefined);
    }
    return {
        runtimeId: cleanString(value.runtimeId),
        sessionId: cleanString(value.sessionId),
        invocationId: cleanString(value.invocationId),
        dryRun: typeof value.dryRun === "boolean" ? value.dryRun : undefined,
        guard,
        contract,
        governance,
        requestedScopes,
        allowedScopes,
        auditMetadata: cleanAuditMetadata(value.auditMetadata),
    };
}
function normalizePoint(value, context) {
    if (value === undefined)
        return undefined;
    if (!isRecord(value)) {
        return failure("INVALID_POINT", "computeruse.mouseScroll at must be an object when provided", "input", context);
    }
    const x = cleanCoordinate(value.x);
    const y = cleanCoordinate(value.y);
    if (x === undefined || y === undefined) {
        return failure("INVALID_POINT", "computeruse.mouseScroll at must use finite non-negative coordinates", "input", context);
    }
    return { x, y };
}
function normalizeTarget(request, context) {
    const targetValue = request.target;
    if (targetValue !== undefined && !isRecord(targetValue)) {
        return failure("INVALID_TARGET", "computeruse.mouseScroll target must be an object when provided", "input", context);
    }
    const target = isRecord(targetValue) ? targetValue : {};
    if ((target.deltaX ?? request.deltaX) === undefined && (target.deltaY ?? request.deltaY) === undefined) {
        return failure("MISSING_SCROLL_DELTA", "computeruse.mouseScroll requires deltaX and/or deltaY", "input", context);
    }
    const deltaX = cleanDelta(target.deltaX ?? request.deltaX ?? 0);
    const deltaY = cleanDelta(target.deltaY ?? request.deltaY ?? 0);
    if (deltaX === undefined || deltaY === undefined || (deltaX === 0 && deltaY === 0)) {
        return failure("INVALID_SCROLL_DELTA", `computeruse.mouseScroll deltaX/deltaY must be finite bounded values and not both zero`, "input", context);
    }
    const at = normalizePoint(target.at ?? request.at, context);
    if (at !== undefined && "ok" in at)
        return at;
    const coordinateSpace = cleanCoordinateSpace(target.coordinateSpace ?? request.coordinateSpace);
    if (coordinateSpace === undefined) {
        return failure("INVALID_COORDINATE_SPACE", "computeruse.mouseScroll coordinateSpace must be screen, window, or normalized", "input", context);
    }
    const durationMs = cleanDuration(target.durationMs ?? request.durationMs);
    if (durationMs === undefined) {
        return failure("INVALID_DURATION", `computeruse.mouseScroll durationMs must be an integer from 0 to ${mouseScrollDescriptor.maxDurationMs}`, "input", context);
    }
    const displayId = cleanString(target.displayId ?? request.displayId);
    if ((target.displayId ?? request.displayId) !== undefined && displayId === undefined) {
        return failure("INVALID_DISPLAY_ID", "computeruse.mouseScroll displayId must be a safe string", "input", context);
    }
    const windowId = cleanString(target.windowId ?? request.windowId);
    if ((target.windowId ?? request.windowId) !== undefined && windowId === undefined) {
        return failure("INVALID_WINDOW_ID", "computeruse.mouseScroll windowId must be a safe string", "input", context);
    }
    return { deltaX, deltaY, unit: "pixel", coordinateSpace, at, displayId, windowId, durationMs };
}
function ensureScopes(context) {
    const requested = context.requestedScopes ?? [];
    const allowed = context.allowedScopes ?? [];
    if (requested.length === 0)
        return undefined;
    const denied = requested.filter((scope) => !allowed.includes(scope));
    if (denied.length === 0)
        return undefined;
    return failure("SCOPE_DENIED", `computeruse.mouseScroll scope ${denied[0]} is outside runtime governance`, "scope", context);
}
function ensureStaticGates(context) {
    if (context.contract?.accepted === false || context.contract?.allowed === false) {
        return failure("CONTRACT_REJECTED", context.contract.reason ?? "computeruse.mouseScroll was rejected by runtime contract surface", "contract", context);
    }
    if (context.governance?.accepted === false || context.governance?.allowed === false) {
        return failure("GOVERNANCE_REJECTED", context.governance.reason ?? "computeruse.mouseScroll was rejected by runtime governance", "governance", context);
    }
    return undefined;
}
function ensureRealExecutionGuard(context) {
    if (context.dryRun !== false)
        return undefined;
    if (context.guard?.accepted === true || context.guard?.allowed === true)
        return undefined;
    return failure("GOVERNANCE_REJECTED", context.guard?.reason ?? "computeruse.mouseScroll dryRun:false requires an affirmative runtime guard", "governance", context);
}
function baseOutput(target, purpose, acceptedScopes, dryRun, providerCalled) {
    return {
        kind: "agentCore.basicTool.computeruse.mouseScroll",
        target: {
            ...target,
            usesCurrentCursor: target.at === undefined,
        },
        purpose,
        dispatch: dryRun ? "dry-run" : "runtime-computeruse",
        dryRun,
        providerCalled,
        executionBlocked: dryRun,
        unsafeSideEffects: true,
        permissionsRequired: mouseScrollDescriptor.permissionsRequired,
        requiresTapApproval: true,
        acceptedScopes,
        runtimeEntry: {
            port: "BaseToolExecutorPort.computeruse.pointerAction",
            operation: "computeruse.mouseScroll.pointerAction",
            runtimeOwnsPointerEvents: true,
            runtimeOwnsInputPolicy: true,
            baseToolOwnsTapStrategy: false,
        },
    };
}
function normalizeProviderResult(value, context) {
    if (!isRecord(value) || cleanString(value.actionId) === undefined) {
        return failure("PROVIDER_FAILURE", "computeruse.mouseScroll runtime provider returned a malformed public-safe action envelope", "provider", context);
    }
    return {
        actionId: cleanString(value.actionId) ?? "",
        metadata: cleanAuditMetadata(value.metadata),
    };
}
const publicSafeProviderFailurePrefix = "PUBLIC_SAFE_PROVIDER_FAILURE:";
function publicSafeProviderFailureMessage(error) {
    const message = error instanceof Error && error.message.trim().length > 0 ? error.message.trim() : undefined;
    if (message === undefined || !message.startsWith(publicSafeProviderFailurePrefix))
        return undefined;
    const publicSafeMessage = message.slice(publicSafeProviderFailurePrefix.length).trim();
    return publicSafeMessage.length > 0 ? publicSafeMessage : undefined;
}
function normalizeRequest(request) {
    if (request === undefined)
        request = {};
    if (!isRecord(request))
        return failure("INVALID_REQUEST", "computeruse.mouseScroll request must be an object", "input", undefined);
    const context = normalizeContext(request.context);
    if ("ok" in context)
        return context;
    const target = normalizeTarget(request, context);
    if ("ok" in target)
        return target;
    const purpose = cleanString(request.purpose);
    if (purpose === undefined) {
        return failure("MISSING_PURPOSE", "computeruse.mouseScroll requires an explicit purpose", "input", context);
    }
    if (context.runtimeId === undefined) {
        return failure("MISSING_RUNTIME_ID", "computeruse.mouseScroll requires context.runtimeId for audit", "input", context);
    }
    const scopes = ensureScopes(context);
    if (scopes !== undefined)
        return scopes;
    const staticGates = ensureStaticGates(context);
    if (staticGates !== undefined)
        return staticGates;
    const realGuard = ensureRealExecutionGuard(context);
    if (realGuard !== undefined)
        return realGuard;
    return {
        target,
        context,
        purpose,
        metadata: cleanAuditMetadata(request.metadata),
        provider: typeof request.provider === "function" ? request.provider : undefined,
    };
}
export async function executeMouseScroll(request = {}) {
    const normalized = normalizeRequest(request);
    if ("ok" in normalized)
        return normalized;
    const { target, context, purpose, metadata, provider } = normalized;
    const acceptedScopes = context.requestedScopes ?? [];
    const dryRun = context.dryRun !== false;
    if (dryRun) {
        return {
            ok: true,
            toolId: mouseScrollDescriptor.toolId,
            output: {
                ...baseOutput(target, purpose, acceptedScopes, true, false),
                actionEnvelope: {
                    resource: "pointer",
                    action: "scroll",
                    executed: false,
                    metadataOnly: true,
                },
            },
            audit: [auditEvent("agentCore.basicTool.computeruse.mouseScroll.dryRun", context, metadata)],
            events: ["basicTool.computeruse.mouseScroll.dryRun"],
        };
    }
    if (provider === undefined) {
        return failure("PROVIDER_UNAVAILABLE", "computeruse.mouseScroll requires runtime executor.computeruse.pointerAction for dryRun:false", "provider", context);
    }
    let providerResult;
    try {
        const result = await provider({
            operation: "computeruse.mouseScroll.pointerAction",
            target,
            purpose,
            context: {
                runtimeId: context.runtimeId,
                sessionId: context.sessionId,
                invocationId: context.invocationId,
                auditMetadata: {
                    ...(context.auditMetadata ?? {}),
                    ...(metadata ?? {}),
                },
            },
        });
        const normalizedResult = normalizeProviderResult(result, context);
        if ("ok" in normalizedResult)
            return normalizedResult;
        providerResult = normalizedResult;
    }
    catch (error) {
        const providerMessage = publicSafeProviderFailureMessage(error);
        return failure("PROVIDER_FAILURE", providerMessage === undefined
            ? "computeruse.mouseScroll runtime provider failed without exposing private details"
            : `computeruse.mouseScroll runtime provider failed: ${providerMessage}`, "provider", context);
    }
    return {
        ok: true,
        toolId: mouseScrollDescriptor.toolId,
        output: {
            ...baseOutput(target, purpose, acceptedScopes, false, true),
            actionEnvelope: {
                resource: "pointer",
                action: "scroll",
                executed: true,
                metadataOnly: false,
                actionId: providerResult.actionId,
            },
            providerMetadata: providerResult.metadata,
        },
        audit: [
            auditEvent("agentCore.basicTool.computeruse.mouseScroll.scrolled", context, {
                actionId: providerResult.actionId,
                ...(providerResult.metadata ?? {}),
            }),
        ],
        events: ["basicTool.computeruse.mouseScroll.scrolled"],
    };
}
export function planMouseScroll(request = {}) {
    return executeMouseScroll(request);
}
