import { failNativeRequired, isNativeDisabledByEnv } from './native-router-hotpath-policy.js';
import { loadNativeRouterHotpathBindingForInternalUse } from './native-router-hotpath.js';
function readNativeFunction(name) {
    const binding = loadNativeRouterHotpathBindingForInternalUse();
    const fn = binding?.[name];
    return typeof fn === 'function' ? fn : null;
}
function safeStringify(value) {
    try {
        return JSON.stringify(value);
    }
    catch {
        return undefined;
    }
}
function parseOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        if (!Array.isArray(row.messages)) {
            return null;
        }
        const output = {
            messages: row.messages
        };
        if (row.rawRequest && typeof row.rawRequest === 'object' && !Array.isArray(row.rawRequest)) {
            output.rawRequest = row.rawRequest;
        }
        if (Array.isArray(row.capturedToolResults)) {
            output.capturedToolResults = row.capturedToolResults.filter((entry) => Boolean(entry) && typeof entry === 'object' && !Array.isArray(entry));
        }
        return output;
    }
    catch {
        return null;
    }
}
function parseEnsureMessagesArrayOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        const messages = Array.isArray(row.messages) ? row.messages : [];
        return { messages };
    }
    catch {
        return null;
    }
}
function parseBridgeHistoryOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        if (!Array.isArray(row.input) || !Array.isArray(row.originalSystemMessages)) {
            return null;
        }
        const originalSystemMessages = row.originalSystemMessages.filter((entry) => typeof entry === 'string');
        if (originalSystemMessages.length !== row.originalSystemMessages.length) {
            return null;
        }
        const output = {
            input: row.input,
            originalSystemMessages
        };
        if (typeof row.combinedSystemInstruction === 'string' && row.combinedSystemInstruction.trim().length) {
            output.combinedSystemInstruction = row.combinedSystemInstruction;
        }
        if (typeof row.latestUserInstruction === 'string' && row.latestUserInstruction.trim().length) {
            output.latestUserInstruction = row.latestUserInstruction;
        }
        return output;
    }
    catch {
        return null;
    }
}
function parseBridgeInputToChatOutput(raw) {
    const parsed = parseRecord(raw);
    if (!parsed || !Array.isArray(parsed.messages)) {
        return null;
    }
    const messages = parsed.messages.filter((entry) => Boolean(entry) && typeof entry === 'object' && !Array.isArray(entry));
    return { messages };
}
function parseBridgeActionState(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        if (!Array.isArray(row.messages)) {
            return null;
        }
        const output = {
            messages: row.messages
        };
        if (row.requiredAction && typeof row.requiredAction === 'object' && !Array.isArray(row.requiredAction)) {
            output.requiredAction = row.requiredAction;
        }
        if (Array.isArray(row.capturedToolResults)) {
            output.capturedToolResults = row.capturedToolResults.filter((entry) => Boolean(entry) && typeof entry === 'object' && !Array.isArray(entry));
        }
        if (row.rawRequest && typeof row.rawRequest === 'object' && !Array.isArray(row.rawRequest)) {
            output.rawRequest = row.rawRequest;
        }
        if (row.rawResponse && typeof row.rawResponse === 'object' && !Array.isArray(row.rawResponse)) {
            output.rawResponse = row.rawResponse;
        }
        if (row.metadata && typeof row.metadata === 'object' && !Array.isArray(row.metadata)) {
            output.metadata = row.metadata;
        }
        return output;
    }
    catch {
        return null;
    }
}
function parseApplyBridgeNormalizeHistoryOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        if (!Array.isArray(row.messages)) {
            return null;
        }
        const output = {
            messages: row.messages
        };
        if (row.bridgeHistory && typeof row.bridgeHistory === 'object' && !Array.isArray(row.bridgeHistory)) {
            output.bridgeHistory = row.bridgeHistory;
        }
        return output;
    }
    catch {
        return null;
    }
}
function parseApplyBridgeCaptureToolResultsOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        const output = {};
        if (Array.isArray(row.capturedToolResults)) {
            output.capturedToolResults = row.capturedToolResults.filter((entry) => Boolean(entry) && typeof entry === 'object' && !Array.isArray(entry));
        }
        if (row.metadata && typeof row.metadata === 'object' && !Array.isArray(row.metadata)) {
            output.metadata = row.metadata;
        }
        return output;
    }
    catch {
        return null;
    }
}
function parseApplyBridgeEnsureToolPlaceholdersOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        if (!Array.isArray(row.messages)) {
            return null;
        }
        const output = {
            messages: row.messages
        };
        if (Array.isArray(row.toolOutputs)) {
            output.toolOutputs = row.toolOutputs.filter((entry) => Boolean(entry) && typeof entry === 'object' && !Array.isArray(entry));
        }
        return output;
    }
    catch {
        return null;
    }
}
function parseEnsureBridgeOutputFieldsOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        if (!Array.isArray(row.messages)) {
            return null;
        }
        return {
            messages: row.messages
        };
    }
    catch {
        return null;
    }
}
function parseApplyBridgeMetadataActionOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        const output = {};
        if (row.rawRequest && typeof row.rawRequest === 'object' && !Array.isArray(row.rawRequest)) {
            output.rawRequest = row.rawRequest;
        }
        if (row.rawResponse && typeof row.rawResponse === 'object' && !Array.isArray(row.rawResponse)) {
            output.rawResponse = row.rawResponse;
        }
        if (row.metadata && typeof row.metadata === 'object' && !Array.isArray(row.metadata)) {
            output.metadata = row.metadata;
        }
        return output;
    }
    catch {
        return null;
    }
}
function parseApplyBridgeReasoningExtractOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        if (!Array.isArray(row.messages)) {
            return null;
        }
        return {
            messages: row.messages
        };
    }
    catch {
        return null;
    }
}
function parseApplyBridgeResponsesOutputReasoningOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        if (!Array.isArray(row.messages)) {
            return null;
        }
        return {
            messages: row.messages
        };
    }
    catch {
        return null;
    }
}
function parseApplyBridgeInjectSystemInstructionOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        if (!Array.isArray(row.messages)) {
            return null;
        }
        return {
            messages: row.messages
        };
    }
    catch {
        return null;
    }
}
function parseApplyBridgeEnsureSystemInstructionOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        if (!Array.isArray(row.messages)) {
            return null;
        }
        const output = {
            messages: row.messages
        };
        if (row.metadata && typeof row.metadata === 'object' && !Array.isArray(row.metadata)) {
            output.metadata = row.metadata;
        }
        return output;
    }
    catch {
        return null;
    }
}
function parseNormalizeMessageReasoningToolsOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        if (!row.message || typeof row.message !== 'object' || Array.isArray(row.message)) {
            return null;
        }
        const toolCallsAdded = typeof row.toolCallsAdded === 'number' && Number.isFinite(row.toolCallsAdded)
            ? Math.max(0, Math.floor(row.toolCallsAdded))
            : null;
        if (toolCallsAdded === null) {
            return null;
        }
        const output = {
            message: row.message,
            toolCallsAdded
        };
        if (typeof row.cleanedReasoning === 'string') {
            output.cleanedReasoning = row.cleanedReasoning;
        }
        return output;
    }
    catch {
        return null;
    }
}
function parseRecord(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        return parsed;
    }
    catch {
        return null;
    }
}
export function normalizeBridgeToolCallIdsWithNative(input) {
    const capability = 'normalizeBridgeToolCallIdsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        messages: input.messages,
        rawRequest: input.rawRequest,
        capturedToolResults: input.capturedToolResults,
        idPrefix: input.idPrefix
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function applyBridgeNormalizeToolIdentifiersWithNative(input) {
    const capability = 'applyBridgeNormalizeToolIdentifiersJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        stage: input.stage,
        protocol: input.protocol,
        moduleType: input.moduleType,
        messages: input.messages,
        rawRequest: input.rawRequest,
        capturedToolResults: input.capturedToolResults,
        idPrefix: input.idPrefix
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function buildBridgeHistoryWithNative(input) {
    const capability = 'buildBridgeHistoryJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        messages: input.messages,
        tools: input.tools
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseBridgeHistoryOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function applyBridgeNormalizeHistoryWithNative(input) {
    const capability = 'applyBridgeNormalizeHistoryJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        messages: input.messages,
        tools: input.tools
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseApplyBridgeNormalizeHistoryOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function applyBridgeCaptureToolResultsWithNative(input) {
    const capability = 'applyBridgeCaptureToolResultsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        stage: input.stage,
        capturedToolResults: input.capturedToolResults,
        rawRequest: input.rawRequest,
        rawResponse: input.rawResponse,
        metadata: input.metadata
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseApplyBridgeCaptureToolResultsOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function applyBridgeEnsureToolPlaceholdersWithNative(input) {
    const capability = 'applyBridgeEnsureToolPlaceholdersJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        stage: input.stage,
        messages: input.messages,
        capturedToolResults: input.capturedToolResults,
        rawRequest: input.rawRequest,
        rawResponse: input.rawResponse
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseApplyBridgeEnsureToolPlaceholdersOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function convertBridgeInputToChatMessagesWithNative(input) {
    const capability = 'convertBridgeInputToChatMessagesJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        input: input.input,
        tools: input.tools,
        toolResultFallbackText: input.toolResultFallbackText,
        normalizeFunctionName: input.normalizeFunctionName
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseBridgeInputToChatOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function coerceBridgeRoleWithNative(role) {
    const capability = 'coerceBridgeRoleJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ role });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = JSON.parse(raw);
        return typeof parsed === 'string' ? parsed : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function serializeToolOutputWithNative(input) {
    const capability = 'serializeToolOutputJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ output: input.output });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string') {
            return fail('empty result');
        }
        const parsed = JSON.parse(raw);
        return typeof parsed === 'string' || parsed === null ? parsed : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function serializeToolArgumentsWithNative(input) {
    const capability = 'serializeToolArgumentsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ args: input.args });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = JSON.parse(raw);
        return typeof parsed === 'string' ? parsed : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function ensureMessagesArrayWithNative(input) {
    const capability = 'ensureMessagesArrayJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ state: input.state });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseEnsureMessagesArrayOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function harvestToolsWithNative(input) {
    const capability = 'harvestToolsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ signal: input.signal, context: input.context });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return fail('invalid payload');
        }
        const row = parsed;
        if (!Array.isArray(row.deltaEvents)) {
            return fail('invalid payload');
        }
        return row;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function ensureBridgeOutputFieldsWithNative(input) {
    const capability = 'ensureBridgeOutputFieldsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        messages: input.messages,
        toolFallback: input.toolFallback,
        assistantFallback: input.assistantFallback
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseEnsureBridgeOutputFieldsOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function applyBridgeMetadataActionWithNative(input) {
    const capability = 'applyBridgeMetadataActionJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        actionName: input.actionName,
        stage: input.stage,
        options: input.options,
        rawRequest: input.rawRequest,
        rawResponse: input.rawResponse,
        metadata: input.metadata
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseApplyBridgeMetadataActionOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function applyBridgeReasoningExtractWithNative(input) {
    const capability = 'applyBridgeReasoningExtractJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        messages: input.messages,
        dropFromContent: input.dropFromContent,
        idPrefixBase: input.idPrefixBase
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseApplyBridgeReasoningExtractOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function applyBridgeResponsesOutputReasoningWithNative(input) {
    const capability = 'applyBridgeResponsesOutputReasoningJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        messages: input.messages,
        rawResponse: input.rawResponse,
        idPrefix: input.idPrefix
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseApplyBridgeResponsesOutputReasoningOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function applyBridgeInjectSystemInstructionWithNative(input) {
    const capability = 'applyBridgeInjectSystemInstructionJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        stage: input.stage,
        options: input.options,
        messages: input.messages,
        rawRequest: input.rawRequest
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseApplyBridgeInjectSystemInstructionOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function applyBridgeEnsureSystemInstructionWithNative(input) {
    const capability = 'applyBridgeEnsureSystemInstructionJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        stage: input.stage,
        messages: input.messages,
        metadata: input.metadata
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseApplyBridgeEnsureSystemInstructionOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function runBridgeActionPipelineWithNative(input) {
    const capability = 'runBridgeActionPipelineJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        stage: input.stage,
        actions: input.actions,
        protocol: input.protocol,
        moduleType: input.moduleType,
        requestId: input.requestId,
        state: input.state
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseBridgeActionState(raw);
        if (!parsed) {
            return null;
        }
        return parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeMessageReasoningToolsWithNative(message, idPrefix) {
    const capability = 'normalizeMessageReasoningToolsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const messageJson = safeStringify(message);
    if (!messageJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(messageJson, typeof idPrefix === 'string' && idPrefix.trim().length ? idPrefix.trim() : undefined);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseNormalizeMessageReasoningToolsOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeChatResponseReasoningToolsWithNative(response, idPrefixBase) {
    const capability = 'normalizeChatResponseReasoningToolsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const responseJson = safeStringify(response);
    if (!responseJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(responseJson, typeof idPrefixBase === 'string' && idPrefixBase.trim().length ? idPrefixBase.trim() : undefined);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
