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 parseJson(raw) {
    try {
        return JSON.parse(raw);
    }
    catch {
        return null;
    }
}
function parseRecord(raw) {
    const parsed = parseJson(raw);
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
        return null;
    }
    return parsed;
}
function parseExtractToolCallsOutput(raw) {
    const parsed = parseJson(raw);
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
        return null;
    }
    const row = parsed;
    if (typeof row.cleanedText !== 'string' || !Array.isArray(row.toolCalls)) {
        return null;
    }
    const toolCalls = row.toolCalls.filter((entry) => entry && typeof entry === 'object');
    return {
        cleanedText: row.cleanedText,
        toolCalls
    };
}
function parseReasoningItems(raw) {
    const parsed = parseJson(raw);
    if (!Array.isArray(parsed)) {
        return null;
    }
    const out = [];
    for (const entry of parsed) {
        if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
            return null;
        }
        const row = entry;
        if (row.type !== 'reasoning' || typeof row.content !== 'string') {
            return null;
        }
        out.push({ type: 'reasoning', content: row.content });
    }
    return out;
}
function parseExtractReasoningSegmentsOutput(raw) {
    const parsed = parseJson(raw);
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
        return null;
    }
    const row = parsed;
    if (typeof row.text !== 'string' || !Array.isArray(row.segments)) {
        return null;
    }
    const segments = row.segments.filter((entry) => typeof entry === 'string');
    if (segments.length !== row.segments.length) {
        return null;
    }
    return { text: row.text, segments };
}
function parseNormalizeReasoningOutput(raw) {
    const parsed = parseJson(raw);
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
        return null;
    }
    const row = parsed;
    return { payload: row.payload };
}
function parseToolCallLiteArray(raw) {
    const parsed = parseJson(raw);
    if (!Array.isArray(parsed)) {
        return null;
    }
    const out = [];
    for (const entry of parsed) {
        if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
            return null;
        }
        const row = entry;
        if (typeof row.name !== 'string' || typeof row.args !== 'string') {
            return null;
        }
        const id = typeof row.id === 'string' && row.id.trim().length ? row.id : undefined;
        out.push({ id, name: row.name, args: row.args });
    }
    return out;
}
function parseArray(raw) {
    const parsed = parseJson(raw);
    return Array.isArray(parsed) ? parsed : null;
}
function parseToolDefinitionOutput(raw) {
    const parsed = parseRecord(raw);
    return parsed;
}
function parseResponsesConversationResumeResult(raw) {
    const parsed = parseRecord(raw);
    if (!parsed) {
        return null;
    }
    const payload = parsed.payload;
    const meta = parsed.meta;
    if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
        return null;
    }
    if (!meta || typeof meta !== 'object' || Array.isArray(meta)) {
        return null;
    }
    return {
        payload: payload,
        meta: meta
    };
}
function parseToolDefinitionArray(raw) {
    const parsed = parseArray(raw);
    if (!parsed)
        return null;
    const output = [];
    for (const entry of parsed) {
        if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
            output.push(entry);
        }
    }
    return output;
}
function parseString(raw) {
    const parsed = parseJson(raw);
    return typeof parsed === 'string' ? parsed : null;
}
function parseStringArray(raw) {
    const parsed = parseArray(raw);
    if (!parsed)
        return null;
    const out = [];
    for (const item of parsed) {
        if (typeof item !== "string") {
            return null;
        }
        out.push(item);
    }
    return out;
}
export function parseLenientJsonishWithNative(value) {
    const capability = 'parseLenientJsonishJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const valueJson = safeStringify(value ?? null);
    if (!valueJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(valueJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        return parsed === null ? fail('invalid payload') : parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function repairArgumentsToStringWithNative(value) {
    const capability = 'repairArgumentsToStringJsonishJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const valueJson = safeStringify(value ?? null);
    if (!valueJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(valueJson);
        if (typeof raw !== 'string') {
            return fail('invalid payload');
        }
        return raw;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function extractToolCallsFromReasoningTextWithNative(text, idPrefix) {
    const capability = 'extractToolCallsFromReasoningTextJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(String(text ?? ''), idPrefix);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseExtractToolCallsOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function extractReasoningSegmentsWithNative(source) {
    const capability = 'extractReasoningSegmentsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ source: String(source ?? '') });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseExtractReasoningSegmentsOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeAssistantTextToToolCallsWithNative(message, options) {
    const capability = 'normalizeAssistantTextToToolCallsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const msgJson = safeStringify(message ?? null);
    if (!msgJson) {
        return fail('json stringify failed');
    }
    const optionsJson = options ? safeStringify(options) : undefined;
    try {
        const raw = fn(msgJson, optionsJson);
        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);
    }
}
export function normalizeReasoningInChatPayloadWithNative(payload) {
    const capability = 'normalizeReasoningInChatPayloadJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ payload: payload ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseNormalizeReasoningOutput(raw);
        return parsed ? parsed.payload : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeReasoningInResponsesPayloadWithNative(payload, options) {
    const capability = 'normalizeReasoningInResponsesPayloadJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ payload: payload ?? null, options: options ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseNormalizeReasoningOutput(raw);
        return parsed ? parsed.payload : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeReasoningInGeminiPayloadWithNative(payload) {
    const capability = 'normalizeReasoningInGeminiPayloadJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ payload: payload ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseNormalizeReasoningOutput(raw);
        return parsed ? parsed.payload : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeReasoningInAnthropicPayloadWithNative(payload) {
    const capability = 'normalizeReasoningInAnthropicPayloadJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ payload: payload ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseNormalizeReasoningOutput(raw);
        return parsed ? parsed.payload : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeReasoningInOpenAIPayloadWithNative(payload) {
    const capability = 'normalizeReasoningInOpenAIPayloadJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ payload: payload ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseNormalizeReasoningOutput(raw);
        return parsed ? parsed.payload : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function bridgeToolToChatDefinitionWithNative(tool, options) {
    const capability = 'bridgeToolToChatDefinitionJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ tool, options: options ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseToolDefinitionOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function chatToolToBridgeDefinitionWithNative(tool, options) {
    const capability = 'chatToolToBridgeDefinitionJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ tool, options: options ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseToolDefinitionOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function mapBridgeToolsToChatWithNative(rawTools, options) {
    const capability = 'mapBridgeToolsToChatWithOptionsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ tools: Array.isArray(rawTools) ? rawTools : [], options: options ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseToolDefinitionArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function mapChatToolsToBridgeWithNative(rawTools, options) {
    const capability = 'mapChatToolsToBridgeWithOptionsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ tools: Array.isArray(rawTools) ? rawTools : [], options: options ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseToolDefinitionArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function collectToolCallsFromResponsesWithNative(response) {
    const capability = 'collectToolCallsFromResponsesJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(response ?? {});
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseToolDefinitionArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function resolveFinishReasonWithNative(response, toolCalls) {
    const capability = 'resolveFinishReasonJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const responseJson = safeStringify(response ?? {});
    const toolCallsJson = safeStringify(Array.isArray(toolCalls) ? toolCalls : []);
    if (!responseJson || !toolCallsJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(responseJson, toolCallsJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        return parseString(raw) ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function buildChatResponseFromResponsesWithNative(payload) {
    const capability = 'buildChatResponseFromResponsesJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(payload ?? null);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        return parseRecord(raw) ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function hasValidThoughtSignatureWithNative(block, options) {
    const capability = 'hasValidThoughtSignatureJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ block: block ?? null, options: options ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        return typeof parsed === 'boolean' ? parsed : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function sanitizeThinkingBlockWithNative(block) {
    const capability = 'sanitizeThinkingBlockJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ block: block ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        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);
    }
}
export function filterInvalidThinkingBlocksWithNative(messages, options) {
    const capability = 'filterInvalidThinkingBlocksJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ messages: Array.isArray(messages) ? messages : [], options: options ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function removeTrailingUnsignedThinkingBlocksWithNative(blocks, options) {
    const capability = 'removeTrailingUnsignedThinkingBlocksJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ blocks: Array.isArray(blocks) ? blocks : [], options: options ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function sanitizeReasoningTaggedTextWithNative(text) {
    const capability = 'sanitizeReasoningTaggedTextJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(String(text ?? ''));
        if (typeof raw !== 'string') {
            return fail('invalid payload');
        }
        return raw;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function ensureBridgeInstructionsWithNative(payload) {
    const capability = 'ensureBridgeInstructionsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(payload ?? {});
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        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);
    }
}
export function repairFindMetaWithNative(script) {
    const capability = 'repairFindMetaJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(script ?? '');
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(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 splitCommandStringWithNative(input) {
    const capability = 'splitCommandStringJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(input ?? '');
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseStringArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function packShellArgsWithNative(input) {
    const capability = 'packShellArgsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(input ?? {});
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        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);
    }
}
export function flattenByCommaWithNative(items) {
    const capability = 'flattenByCommaJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(Array.isArray(items) ? items : []);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseStringArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function chunkStringWithNative(s, minParts = 3, maxParts = 12, targetChunk = 12) {
    const capability = 'chunkStringJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ s, minParts, maxParts, targetChunk });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseStringArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function deriveToolCallKeyWithNative(call) {
    const capability = 'deriveToolCallKeyJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const callJson = safeStringify(call ?? null);
    if (!callJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(callJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        if (parsed === null) {
            return null;
        }
        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 normalizeIdValueWithNative(value, forceGenerate = false) {
    const capability = 'normalizeIdValueJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ value, forceGenerate });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(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 extractToolCallIdWithNative(obj) {
    const capability = 'extractToolCallIdJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ obj: obj ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        return typeof parsed === 'string' ? parsed : undefined;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function createToolCallIdTransformerWithNative(style) {
    const capability = 'createToolCallIdTransformerJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ style });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        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);
    }
}
export function transformToolCallIdWithNative(state, id) {
    const capability = 'transformToolCallIdJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ state, id });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed || typeof parsed.id !== 'string' || !parsed.state || typeof parsed.state !== 'object') {
            return fail('invalid payload');
        }
        return parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function enforceToolCallIdStyleWithNative(messages, state) {
    const capability = 'enforceToolCallIdStyleJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ messages: Array.isArray(messages) ? messages : [], state });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed || !Array.isArray(parsed.messages) || !parsed.state || typeof parsed.state !== 'object') {
            return fail('invalid payload');
        }
        return parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeResponsesToolCallIdsWithNative(payload) {
    const capability = 'normalizeResponsesToolCallIdsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(payload ?? null);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        return parseRecord(raw) ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function resolveToolCallIdStyleWithNative(metadata) {
    const capability = 'resolveToolCallIdStyleJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const metadataJson = safeStringify(metadata ?? null);
    if (!metadataJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(metadataJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(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 stripInternalToolingMetadataWithNative(metadata) {
    const capability = 'stripInternalToolingMetadataJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const metadataJson = safeStringify(metadata ?? null);
    if (!metadataJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(metadataJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        return parseRecord(raw) ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function buildProviderProtocolErrorWithNative(input) {
    const capability = 'buildProviderProtocolErrorJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({
        message: input.message,
        code: input.code,
        protocol: input.protocol,
        providerType: input.providerType,
        category: input.category,
        details: input.details
    });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        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);
    }
}
function parseToolCallResult(raw) {
    if (!raw || raw === 'null') {
        return null;
    }
    return parseToolCallLiteArray(raw);
}
function callTextMarkupExtractor(capability, payload) {
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(payload ?? null);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string') {
            return fail('invalid payload');
        }
        const parsed = parseToolCallResult(raw);
        return parsed ?? null;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function extractJsonToolCallsFromTextWithNative(text, options) {
    return callTextMarkupExtractor('extractJsonToolCallsFromTextJson', {
        text: String(text ?? ''),
        options: options ?? null
    });
}
export function extractXMLToolCallsFromTextWithNative(text) {
    return callTextMarkupExtractor('extractXmlToolCallsFromTextJson', {
        text: String(text ?? '')
    });
}
export function extractSimpleXmlToolsFromTextWithNative(text) {
    return callTextMarkupExtractor('extractSimpleXmlToolsFromTextJson', {
        text: String(text ?? '')
    });
}
export function extractParameterXmlToolsFromTextWithNative(text) {
    return callTextMarkupExtractor('extractParameterXmlToolsFromTextJson', {
        text: String(text ?? '')
    });
}
export function extractInvokeToolsFromTextWithNative(text) {
    return callTextMarkupExtractor('extractInvokeToolsFromTextJson', {
        text: String(text ?? '')
    });
}
export function extractToolNamespaceXmlBlocksFromTextWithNative(text) {
    return callTextMarkupExtractor('extractToolNamespaceXmlBlocksFromTextJson', {
        text: String(text ?? '')
    });
}
export function extractApplyPatchCallsFromTextWithNative(text) {
    return callTextMarkupExtractor('extractApplyPatchCallsFromTextJson', {
        text: String(text ?? '')
    });
}
export function extractBareExecCommandFromTextWithNative(text) {
    return callTextMarkupExtractor('extractBareExecCommandFromTextJson', {
        text: String(text ?? '')
    });
}
export function extractExecuteBlocksFromTextWithNative(text) {
    return callTextMarkupExtractor('extractExecuteBlocksFromTextJson', {
        text: String(text ?? '')
    });
}
export function extractExploredListDirectoryCallsFromTextWithNative(text) {
    return callTextMarkupExtractor('extractExploredListDirectoryCallsFromTextJson', {
        text: String(text ?? '')
    });
}
export function extractQwenToolCallTokensFromTextWithNative(text) {
    return callTextMarkupExtractor('extractQwenToolCallTokensFromTextJson', {
        text: String(text ?? '')
    });
}
export function mergeToolCallsWithNative(existing, additions) {
    const capability = 'mergeToolCallsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const existingJson = safeStringify(existing ?? []);
    const additionsJson = safeStringify(additions ?? []);
    if (!existingJson || !additionsJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(existingJson, additionsJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        if (!Array.isArray(parsed)) {
            return fail('invalid payload');
        }
        return parsed.filter((entry) => entry && typeof entry === 'object');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function mapReasoningContentToResponsesOutputWithNative(reasoningContent) {
    const capability = 'mapReasoningContentToResponsesOutputJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const contentJson = safeStringify(reasoningContent ?? null);
    if (!contentJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(contentJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseReasoningItems(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function validateToolArgumentsWithNative(toolName, args) {
    const capability = 'validateToolArgumentsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ toolName, args: args ?? null });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed || typeof parsed.repaired !== 'string' || typeof parsed.success !== 'boolean') {
            return fail('invalid payload');
        }
        const error = typeof parsed.error === 'string' ? parsed.error : undefined;
        return { repaired: parsed.repaired, success: parsed.success, ...(error ? { error } : {}) };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function repairToolCallsWithNative(toolCalls) {
    const capability = 'repairToolCallsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(Array.isArray(toolCalls) ? toolCalls : []);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseArray(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        return parsed.filter((entry) => entry && typeof entry === 'object' && !Array.isArray(entry) && typeof entry.arguments === 'string');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function isImagePathWithNative(pathValue) {
    const capability = 'isImagePathJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const pathJson = safeStringify(pathValue ?? null);
    if (!pathJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(pathJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        return typeof parsed === 'boolean' ? parsed : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function extractStreamingToolCallsWithNative(input) {
    const capability = 'extractStreamingToolCallsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(input ?? {});
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        const buffer = typeof parsed.buffer === 'string' ? parsed.buffer : '';
        const idCounter = typeof parsed.idCounter === 'number' ? parsed.idCounter : input.idCounter;
        const toolCalls = Array.isArray(parsed.toolCalls)
            ? parsed.toolCalls.filter((entry) => entry && typeof entry === 'object' && !Array.isArray(entry))
                .map((entry) => entry)
            : [];
        return { buffer, idCounter, toolCalls };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function createStreamingToolExtractorStateWithNative(idPrefix) {
    const capability = 'createStreamingToolExtractorStateJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(idPrefix ? { idPrefix } : {});
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        return parseRecord(raw) ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function resetStreamingToolExtractorStateWithNative(state) {
    const capability = 'resetStreamingToolExtractorStateJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(state ?? {});
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        return parseRecord(raw) ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function feedStreamingToolExtractorWithNative(input) {
    const capability = 'feedStreamingToolExtractorJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(input ?? {});
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed || !parsed.state || typeof parsed.state !== 'object' || Array.isArray(parsed.state)) {
            return fail('invalid payload');
        }
        const toolCalls = Array.isArray(parsed.toolCalls)
            ? parsed.toolCalls.filter((entry) => entry && typeof entry === 'object' && !Array.isArray(entry))
                .map((entry) => entry)
            : [];
        return { state: parsed.state, toolCalls };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function isCompactionRequestWithNative(payload) {
    const capability = 'isCompactionRequestJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(payload ?? null);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        return typeof parsed === 'boolean' ? parsed : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function encodeMetadataPassthroughWithNative(parameters, prefix, keys) {
    const capability = 'encodeMetadataPassthroughJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const parametersJson = safeStringify(parameters ?? null);
    const keysJson = safeStringify(Array.isArray(keys) ? keys : []);
    if (!parametersJson || !keysJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(parametersJson, String(prefix || ''), keysJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        if (parsed === null) {
            return undefined;
        }
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return fail('invalid payload');
        }
        const out = {};
        for (const [key, value] of Object.entries(parsed)) {
            if (typeof key !== 'string' || typeof value !== 'string') {
                return fail('invalid payload');
            }
            out[key] = value;
        }
        return Object.keys(out).length ? out : undefined;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function extractMetadataPassthroughWithNative(metadataField, prefix, keys) {
    const capability = 'extractMetadataPassthroughJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const metadataJson = safeStringify(metadataField ?? null);
    const keysJson = safeStringify(Array.isArray(keys) ? keys : []);
    if (!metadataJson || !keysJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(metadataJson, String(prefix || ''), keysJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        const metadata = parsed.metadata && typeof parsed.metadata === 'object' && !Array.isArray(parsed.metadata)
            ? parsed.metadata
            : undefined;
        const passthrough = parsed.passthrough && typeof parsed.passthrough === 'object' && !Array.isArray(parsed.passthrough)
            ? parsed.passthrough
            : undefined;
        return {
            ...(metadata ? { metadata } : {}),
            ...(passthrough ? { passthrough } : {})
        };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function ensureProtocolStateWithNative(metadata, protocol) {
    const capability = 'ensureProtocolStateJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const metadataJson = safeStringify(metadata ?? {});
    if (!metadataJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(metadataJson, String(protocol ?? ''));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        const metadataOut = parsed.metadata && typeof parsed.metadata === 'object' && !Array.isArray(parsed.metadata)
            ? parsed.metadata
            : undefined;
        const nodeOut = parsed.node && typeof parsed.node === 'object' && !Array.isArray(parsed.node)
            ? parsed.node
            : undefined;
        if (!metadataOut || !nodeOut) {
            return fail('invalid payload');
        }
        return { metadata: metadataOut, node: nodeOut };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function getProtocolStateWithNative(metadata, protocol) {
    const capability = 'getProtocolStateJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const metadataJson = safeStringify(metadata ?? null);
    if (!metadataJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(metadataJson, String(protocol ?? ''));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        if (parsed === null) {
            return undefined;
        }
        return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
            ? parsed
            : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function readRuntimeMetadataWithNative(carrier) {
    const capability = 'readRuntimeMetadataJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const carrierJson = safeStringify(carrier ?? null);
    if (!carrierJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(carrierJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        if (parsed === null) {
            return undefined;
        }
        return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
            ? parsed
            : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function ensureRuntimeMetadataCarrierWithNative(carrier) {
    const capability = 'ensureRuntimeMetadataJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const carrierJson = safeStringify(carrier);
    if (!carrierJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(carrierJson);
        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);
    }
}
export function cloneRuntimeMetadataWithNative(carrier) {
    const capability = 'cloneRuntimeMetadataJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const carrierJson = safeStringify(carrier ?? null);
    if (!carrierJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(carrierJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        if (parsed === null) {
            return undefined;
        }
        return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
            ? parsed
            : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function injectMcpToolsForChatWithNative(tools, discoveredServers) {
    const capability = 'injectMcpToolsForChatJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const toolsJson = safeStringify(Array.isArray(tools) ? tools : []);
    const serversJson = safeStringify(Array.isArray(discoveredServers) ? discoveredServers : []);
    if (!toolsJson || !serversJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(toolsJson, serversJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        return Array.isArray(parsed) ? parsed : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeArgsBySchemaWithNative(input, schema) {
    const capability = 'normalizeArgsBySchemaJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const inputJson = safeStringify(input ?? null);
    const schemaJson = safeStringify(schema ?? null);
    if (!inputJson || !schemaJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(inputJson, schemaJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed || typeof parsed.ok !== 'boolean') {
            return fail('invalid payload');
        }
        const value = parsed.value && typeof parsed.value === 'object' && !Array.isArray(parsed.value)
            ? parsed.value
            : undefined;
        const errors = Array.isArray(parsed.errors)
            ? parsed.errors.filter((entry) => typeof entry === 'string')
            : undefined;
        return {
            ok: parsed.ok,
            ...(value ? { value } : {}),
            ...(errors && errors.length ? { errors } : {})
        };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeToolsWithNative(tools) {
    const capability = 'normalizeToolsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const toolsJson = safeStringify(tools ?? null);
    if (!toolsJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(toolsJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        return Array.isArray(parsed) ? parsed : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function extractOutputSegmentsWithNative(source, itemsKey = 'output') {
    const capability = 'extractOutputSegmentsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const sourceJson = safeStringify(source ?? null);
    if (!sourceJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(sourceJson, String(itemsKey || 'output'));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        const textParts = Array.isArray(parsed.textParts)
            ? parsed.textParts.filter((entry) => typeof entry === 'string')
            : [];
        const reasoningParts = Array.isArray(parsed.reasoningParts)
            ? parsed.reasoningParts.filter((entry) => typeof entry === 'string')
            : [];
        return { textParts, reasoningParts };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeContentPartWithNative(part, reasoningCollector) {
    const capability = 'normalizeOutputContentPartJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const partJson = safeStringify(part ?? null);
    const collectorJson = safeStringify(Array.isArray(reasoningCollector) ? reasoningCollector : []);
    if (!partJson || !collectorJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(partJson, collectorJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        const normalized = parsed.normalized === null
            ? null
            : parsed.normalized && typeof parsed.normalized === 'object' && !Array.isArray(parsed.normalized)
                ? parsed.normalized
                : fail('invalid payload');
        const nextCollector = Array.isArray(parsed.reasoningCollector)
            ? parsed.reasoningCollector.filter((entry) => typeof entry === 'string')
            : [];
        return { normalized, reasoningCollector: nextCollector };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeMessageContentPartsWithNative(parts, reasoningCollector) {
    const capability = 'normalizeMessageContentPartsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const partsJson = safeStringify(parts ?? null);
    const collectorJson = safeStringify(Array.isArray(reasoningCollector) ? reasoningCollector : []);
    if (!partsJson || !collectorJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(partsJson, collectorJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        const normalizedParts = Array.isArray(parsed.normalizedParts)
            ? parsed.normalizedParts.filter((entry) => !!entry && typeof entry === 'object' && !Array.isArray(entry))
            : [];
        const reasoningChunks = Array.isArray(parsed.reasoningChunks)
            ? parsed.reasoningChunks.filter((entry) => typeof entry === 'string')
            : [];
        return { normalizedParts, reasoningChunks };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeChatMessageContentWithNative(content) {
    const capability = 'normalizeChatMessageContentJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const contentJson = safeStringify(content ?? null);
    if (!contentJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(contentJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        const contentText = typeof parsed.contentText === 'string' ? parsed.contentText : undefined;
        const reasoningText = typeof parsed.reasoningText === 'string' ? parsed.reasoningText : undefined;
        return {
            ...(contentText ? { contentText } : {}),
            ...(reasoningText ? { reasoningText } : {})
        };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeOpenaiMessageWithNative(message, disableShellCoerce) {
    const capability = 'normalizeOpenaiMessageJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(message ?? null);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson, Boolean(disableShellCoerce));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        try {
            return JSON.parse(raw);
        }
        catch {
            return fail('invalid payload');
        }
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeOpenaiToolWithNative(tool) {
    const capability = 'normalizeOpenaiToolJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(tool ?? null);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        try {
            return JSON.parse(raw);
        }
        catch {
            return fail('invalid payload');
        }
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeOpenaiChatMessagesWithNative(messages) {
    const capability = 'normalizeOpenaiChatMessagesJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(messages ?? null);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        return Array.isArray(parsed) ? parsed : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeOpenaiToolCallWithNative(toolCall, disableShellCoerce) {
    const capability = 'normalizeOpenaiToolCallJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(toolCall ?? null);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson, Boolean(disableShellCoerce));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        try {
            return JSON.parse(raw);
        }
        catch {
            return fail('invalid payload');
        }
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function prepareGeminiToolsForBridgeWithNative(rawTools, missing) {
    const capability = 'prepareGeminiToolsForBridgeJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const rawToolsJson = safeStringify(rawTools ?? null);
    const missingJson = safeStringify(Array.isArray(missing) ? missing : []);
    if (!rawToolsJson || !missingJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(rawToolsJson, missingJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        const defs = Array.isArray(parsed.defs)
            ? parsed.defs.filter((entry) => !!entry && typeof entry === 'object' && !Array.isArray(entry))
            : undefined;
        const nextMissing = Array.isArray(parsed.missing)
            ? parsed.missing.filter((entry) => !!entry && typeof entry === 'object' && !Array.isArray(entry))
            : [];
        return {
            ...(defs && defs.length ? { defs } : {}),
            missing: nextMissing
        };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function buildGeminiToolsFromBridgeWithNative(defs, mode = 'default') {
    const capability = 'buildGeminiToolsFromBridgeJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const defsJson = safeStringify(defs ?? null);
    if (!defsJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(defsJson, mode);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        if (parsed == null) {
            return undefined;
        }
        if (!Array.isArray(parsed)) {
            return fail('invalid payload');
        }
        return parsed.filter((entry) => !!entry && typeof entry === 'object' && !Array.isArray(entry));
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function pickResponsesPersistedFieldsWithNative(payload) {
    const capability = 'pickResponsesPersistedFieldsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(payload ?? null);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        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);
    }
}
export function convertResponsesOutputToInputItemsWithNative(response) {
    const capability = 'convertResponsesOutputToInputItemsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const responseJson = safeStringify(response ?? null);
    if (!responseJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(responseJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        if (!Array.isArray(parsed)) {
            return fail('invalid payload');
        }
        return parsed.filter((entry) => !!entry && typeof entry === 'object' && !Array.isArray(entry));
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function prepareResponsesConversationEntryWithNative(payload, context) {
    const capability = 'prepareResponsesConversationEntryJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(payload ?? null);
    const contextJson = safeStringify(context ?? null);
    if (!payloadJson || !contextJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson, contextJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        const basePayload = parsed.basePayload;
        const input = parsed.input;
        const tools = parsed.tools;
        if (!basePayload || typeof basePayload !== 'object' || Array.isArray(basePayload) || !Array.isArray(input)) {
            return fail('invalid payload');
        }
        return {
            basePayload: basePayload,
            input: input.filter((entry) => !!entry && typeof entry === 'object' && !Array.isArray(entry)),
            tools: Array.isArray(tools)
                ? tools.filter((entry) => !!entry && typeof entry === 'object' && !Array.isArray(entry))
                : undefined
        };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function resumeResponsesConversationPayloadWithNative(entry, responseId, submitPayload, requestId) {
    const capability = 'resumeResponsesConversationPayloadJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const entryJson = safeStringify(entry ?? null);
    const submitPayloadJson = safeStringify(submitPayload ?? null);
    if (!entryJson || !submitPayloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(entryJson, String(responseId ?? ''), submitPayloadJson, requestId);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseResponsesConversationResumeResult(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function enforceChatBudgetWithNative(chat, allowedBytes, systemTextLimit) {
    const capability = 'enforceChatBudgetJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const chatJson = safeStringify(chat ?? null);
    if (!chatJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(chatJson, Number(allowedBytes), Number(systemTextLimit));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function resolveBudgetForModelWithNative(modelId, fallback) {
    const capability = 'resolveBudgetForModelJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const fallbackJson = safeStringify(fallback ?? null);
    if (!fallbackJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(String(modelId ?? ''), fallbackJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        const maxBytes = Number(parsed.maxBytes);
        const safetyRatio = Number(parsed.safetyRatio);
        const allowedBytes = Number(parsed.allowedBytes);
        const source = typeof parsed.source === 'string' ? parsed.source : 'unknown';
        if (!Number.isFinite(maxBytes) || !Number.isFinite(safetyRatio) || !Number.isFinite(allowedBytes)) {
            return fail('invalid payload');
        }
        return { maxBytes, safetyRatio, allowedBytes, source };
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function injectMcpToolsForResponsesWithNative(tools, discoveredServers) {
    const capability = 'injectMcpToolsForResponsesJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const toolsJson = safeStringify(Array.isArray(tools) ? tools : []);
    const serversJson = safeStringify(Array.isArray(discoveredServers) ? discoveredServers : []);
    if (!toolsJson || !serversJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(toolsJson, serversJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        return Array.isArray(parsed) ? parsed : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeFunctionCallIdWithNative(input) {
    const capability = 'normalizeFunctionCallIdJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const inputJson = safeStringify(input ?? {});
    if (!inputJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(inputJson);
        return typeof raw === 'string' && raw ? raw : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeFunctionCallOutputIdWithNative(input) {
    const capability = 'normalizeFunctionCallOutputIdJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const inputJson = safeStringify(input ?? {});
    if (!inputJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(inputJson);
        return typeof raw === 'string' && raw ? raw : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeResponsesCallIdWithNative(input) {
    const capability = 'normalizeResponsesCallIdJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const inputJson = safeStringify(input ?? {});
    if (!inputJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(inputJson);
        return typeof raw === 'string' && raw ? raw : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function clampResponsesInputItemIdWithNative(rawValue) {
    const capability = 'clampResponsesInputItemIdJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const rawJson = safeStringify(rawValue ?? null);
    if (!rawJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(rawJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseJson(raw);
        if (parsed === null) {
            return undefined;
        }
        return typeof parsed === 'string' ? parsed : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
