export const cameraStopRecordingDescriptor = {
    toolId: "computeruse.cameraStopRecording",
    capability: "stop-camera-recording",
    route: "agent_executionEngine.basic_toolLayer.baseTools.computeruseBase.cameraAccess",
    defaultDryRun: true,
    defaultRetentionPolicy: "session-scoped",
    allowedStorageSchemes: ["artifact://", "session://", "runtime://", "memory://"],
    tapOwnsApproval: true,
    runtimeEntry: "BaseToolExecutorPort.computeruse.stopRecording",
    permissionsRequired: ["camera:stop-recording", "recording:session", "artifact:write"],
    unsafeSideEffects: true,
};
function isRecord(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}
function cleanString(value, maxLength = 1024) {
    return typeof value === "string" && value.trim().length > 0 && !value.includes("\0") && value.trim().length <= maxLength
        ? 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 cleanRetentionPolicy(value) {
    if (value === undefined)
        return cameraStopRecordingDescriptor.defaultRetentionPolicy;
    return value === "ephemeral" || value === "session-only" || value === "session-scoped" || value === "persistent"
        ? value
        : undefined;
}
function hasAllowedStorageScheme(value) {
    return cameraStopRecordingDescriptor.allowedStorageSchemes.some((scheme) => value.startsWith(scheme));
}
function auditEvent(type, context, recordingId, metadata) {
    return {
        type,
        toolId: cameraStopRecordingDescriptor.toolId,
        invocationId: context?.invocationId ?? "computeruse.cameraStopRecording:dry-run",
        dryRun: context?.dryRun !== false,
        recordingId,
        metadata: {
            ...(context?.auditMetadata ?? {}),
            ...(metadata ?? {}),
        },
    };
}
function failure(code, message, boundary, context, recordingId) {
    return {
        ok: false,
        toolId: cameraStopRecordingDescriptor.toolId,
        error: {
            code,
            message,
            boundary,
            publicSafe: true,
            safeForRuntimeInspection: true,
            internalDetailExposed: false,
        },
        audit: [auditEvent("agentCore.basicTool.computeruse.cameraStopRecording.rejected", context, recordingId, { code })],
        events: ["basicTool.computeruse.cameraStopRecording.rejected"],
    };
}
function normalizeContext(value) {
    if (value === undefined)
        return {};
    if (!isRecord(value))
        return failure("INVALID_CONTEXT", "computeruse.cameraStopRecording 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.cameraStopRecording 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 normalizeTarget(request, context) {
    const targetValue = request.target;
    if (targetValue !== undefined && !isRecord(targetValue)) {
        return failure("INVALID_TARGET", "computeruse.cameraStopRecording target must be an object when provided", "input", context);
    }
    const target = isRecord(targetValue) ? targetValue : {};
    const recordingValue = target.recordingId ?? target.recordingRef ?? request.recordingId ?? request.recordingRef;
    const purposeValue = target.purpose ?? request.purpose;
    const storageTargetValue = target.storageTarget ?? request.storageTarget;
    const retentionPolicyValue = target.retentionPolicy ?? request.retentionPolicy;
    const destinationValue = target.destinationHint ?? target.persistHint ?? request.destinationHint ?? request.persistHint;
    const recordingId = cleanString(recordingValue, 256);
    const purpose = cleanString(purposeValue);
    const storageTarget = cleanString(storageTargetValue);
    const retentionPolicy = cleanRetentionPolicy(retentionPolicyValue);
    const destinationHint = cleanString(destinationValue);
    if (recordingValue === undefined) {
        return failure("MISSING_RECORDING_ID", "computeruse.cameraStopRecording requires target.recordingId", "input", context);
    }
    if (recordingId === undefined) {
        return failure("INVALID_RECORDING_ID", "computeruse.cameraStopRecording recordingId must be a safe string", "input", context);
    }
    if (purposeValue === undefined) {
        return failure("MISSING_PURPOSE", "computeruse.cameraStopRecording requires an explicit purpose", "input", context, recordingId);
    }
    if (purpose === undefined) {
        return failure("INVALID_PURPOSE", "computeruse.cameraStopRecording purpose must be a safe string", "input", context, recordingId);
    }
    if (storageTargetValue !== undefined && (storageTarget === undefined || !hasAllowedStorageScheme(storageTarget))) {
        return failure("INVALID_STORAGE_TARGET", "computeruse.cameraStopRecording storageTarget must use artifact://, session://, runtime://, or memory://", "input", context, recordingId);
    }
    if (retentionPolicy === undefined) {
        return failure("INVALID_RETENTION_POLICY", "computeruse.cameraStopRecording retentionPolicy must be ephemeral, session-only, session-scoped, or persistent", "input", context, recordingId);
    }
    if (destinationValue !== undefined && destinationHint === undefined) {
        return failure("INVALID_DESTINATION_HINT", "computeruse.cameraStopRecording destinationHint must be a safe string", "input", context, recordingId);
    }
    return { recordingId, purpose, storageTarget, retentionPolicy, destinationHint };
}
function ensureScopes(target, 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.cameraStopRecording scope ${denied[0]} is outside runtime governance`, "scope", context, target.recordingId);
}
function ensureStaticGates(target, context) {
    if (context.contract?.accepted === false || context.contract?.allowed === false) {
        return failure("CONTRACT_REJECTED", context.contract.reason ?? "computeruse.cameraStopRecording was rejected by runtime contract surface", "contract", context, target.recordingId);
    }
    if (context.governance?.accepted === false || context.governance?.allowed === false) {
        return failure("GOVERNANCE_REJECTED", context.governance.reason ?? "computeruse.cameraStopRecording was rejected by runtime governance", "governance", context, target.recordingId);
    }
    return undefined;
}
function ensureRealExecutionGuard(target, 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.cameraStopRecording dryRun:false requires an affirmative runtime guard", "governance", context, target.recordingId);
}
function baseOutput(target, acceptedScopes, dryRun, providerCalled) {
    return {
        kind: "agentCore.basicTool.computeruse.cameraStopRecording",
        target,
        dispatch: dryRun ? "dry-run" : "runtime-computeruse",
        dryRun,
        providerCalled,
        executionBlocked: dryRun,
        unsafeSideEffects: true,
        permissionsRequired: ["camera:stop-recording", "recording:session", "artifact:write"],
        requiresTapApproval: true,
        acceptedScopes,
        runtimeEntry: {
            port: "BaseToolExecutorPort.computeruse.stopRecording",
            operation: "computeruse.cameraStopRecording.stop",
            runtimeOwnsCameraAccess: true,
            runtimeOwnsRecordingSession: true,
            runtimeOwnsArtifactStorage: true,
            baseToolOwnsTapStrategy: false,
        },
    };
}
function normalizeProviderResult(value, context, target) {
    if (!isRecord(value) || cleanString(value.artifactId) === undefined || cleanString(value.mimeType) === undefined) {
        return failure("PROVIDER_FAILURE", "computeruse.cameraStopRecording runtime provider returned a malformed public-safe recording artifact envelope", "provider", context, target.recordingId);
    }
    return {
        artifactId: cleanString(value.artifactId) ?? "",
        mimeType: cleanString(value.mimeType) ?? "",
        storageUri: cleanString(value.storageUri),
        retentionPolicy: cleanRetentionPolicy(value.retentionPolicy),
        metadata: cleanAuditMetadata(value.metadata),
    };
}
function normalizeRequest(request) {
    if (request === undefined)
        request = {};
    if (!isRecord(request)) {
        return failure("INVALID_REQUEST", "computeruse.cameraStopRecording 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;
    if (context.runtimeId === undefined) {
        return failure("MISSING_RUNTIME_ID", "computeruse.cameraStopRecording requires context.runtimeId for audit", "input", context, target.recordingId);
    }
    const scopes = ensureScopes(target, context);
    if (scopes !== undefined)
        return scopes;
    const staticGates = ensureStaticGates(target, context);
    if (staticGates !== undefined)
        return staticGates;
    const realGuard = ensureRealExecutionGuard(target, context);
    if (realGuard !== undefined)
        return realGuard;
    return {
        target,
        context,
        metadata: cleanAuditMetadata(request.metadata),
        provider: typeof request.provider === "function" ? request.provider : undefined,
    };
}
export async function executeCameraStopRecording(request = {}) {
    const normalized = normalizeRequest(request);
    if ("ok" in normalized)
        return normalized;
    const { target, context, metadata, provider } = normalized;
    const acceptedScopes = context.requestedScopes ?? [];
    const dryRun = context.dryRun !== false;
    if (dryRun) {
        return {
            ok: true,
            toolId: cameraStopRecordingDescriptor.toolId,
            output: {
                ...baseOutput(target, acceptedScopes, true, false),
                artifactEnvelope: {
                    resource: "camera-recording",
                    stopRequested: false,
                    stopped: false,
                    metadataOnly: true,
                    recordingId: target.recordingId,
                    retentionPolicy: target.retentionPolicy,
                },
            },
            audit: [auditEvent("agentCore.basicTool.computeruse.cameraStopRecording.dryRun", context, target.recordingId, metadata)],
            events: ["basicTool.computeruse.cameraStopRecording.dryRun"],
        };
    }
    if (provider === undefined) {
        return failure("PROVIDER_UNAVAILABLE", "computeruse.cameraStopRecording requires runtime executor.computeruse.stopRecording for dryRun:false", "provider", context, target.recordingId);
    }
    let providerResult;
    try {
        const result = await provider({
            operation: "computeruse.cameraStopRecording.stop",
            target,
            context: {
                runtimeId: context.runtimeId,
                sessionId: context.sessionId,
                invocationId: context.invocationId,
                auditMetadata: {
                    ...(context.auditMetadata ?? {}),
                    ...(metadata ?? {}),
                },
            },
        });
        const normalizedResult = normalizeProviderResult(result, context, target);
        if ("ok" in normalizedResult)
            return normalizedResult;
        providerResult = normalizedResult;
    }
    catch {
        return failure("PROVIDER_FAILURE", "computeruse.cameraStopRecording runtime provider failed without exposing private details", "provider", context, target.recordingId);
    }
    return {
        ok: true,
        toolId: cameraStopRecordingDescriptor.toolId,
        output: {
            ...baseOutput(target, acceptedScopes, false, true),
            artifactEnvelope: {
                resource: "camera-recording",
                stopRequested: true,
                stopped: true,
                metadataOnly: false,
                recordingId: target.recordingId,
                artifactId: providerResult.artifactId,
                mimeType: providerResult.mimeType,
                storageUri: providerResult.storageUri,
                retentionPolicy: providerResult.retentionPolicy ?? target.retentionPolicy,
            },
            providerMetadata: providerResult.metadata,
        },
        audit: [auditEvent("agentCore.basicTool.computeruse.cameraStopRecording.stopped", context, target.recordingId, providerResult.metadata)],
        events: ["basicTool.computeruse.cameraStopRecording.stopped"],
    };
}
export const planCameraStopRecording = executeCameraStopRecording;
