"use strict";
/**
 * Cursor Protobuf Encoder
 * Implements ConnectRPC protobuf wire format encoding
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapConnectRPCFrame = exports.encodeMcpTool = exports.encodeMessageId = exports.encodeMetadata = exports.encodeCursorSetting = exports.encodeModel = exports.encodeInstruction = exports.encodeMessage = exports.encodeToolResult = exports.concatArrays = exports.encodeField = exports.encodeVarint = void 0;
const zlib = __importStar(require("zlib"));
const cursor_protobuf_schema_js_1 = require("./cursor-protobuf-schema.js");
/**
 * Encode a varint (variable-length integer)
 */
function encodeVarint(value) {
    const bytes = [];
    let val = value >>> 0; // Ensure unsigned
    while (val >= 0x80) {
        bytes.push((val & 0x7f) | 0x80);
        val >>>= 7;
    }
    bytes.push(val & 0x7f);
    return new Uint8Array(bytes);
}
exports.encodeVarint = encodeVarint;
/**
 * Encode a protobuf field (tag + value)
 */
function encodeField(fieldNum, wireType, value) {
    const tag = (fieldNum << 3) | wireType;
    const tagBytes = encodeVarint(tag);
    if (wireType === cursor_protobuf_schema_js_1.WIRE_TYPE.VARINT) {
        const valueBytes = encodeVarint(value);
        return concatArrays(tagBytes, valueBytes);
    }
    if (wireType === cursor_protobuf_schema_js_1.WIRE_TYPE.LEN) {
        const dataBytes = typeof value === 'string'
            ? new TextEncoder().encode(value)
            : value instanceof Uint8Array
                ? value
                : new Uint8Array(0);
        const lengthBytes = encodeVarint(dataBytes.length);
        return concatArrays(tagBytes, lengthBytes, dataBytes);
    }
    return new Uint8Array(0);
}
exports.encodeField = encodeField;
/**
 * Concatenate multiple Uint8Arrays
 */
function concatArrays(...arrays) {
    const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
    const result = new Uint8Array(totalLength);
    let offset = 0;
    for (const arr of arrays) {
        result.set(arr, offset);
        offset += arr.length;
    }
    return result;
}
exports.concatArrays = concatArrays;
/**
 * Encode a tool result
 */
function encodeToolResult(toolResult) {
    const toolCallId = toolResult.tool_call_id || '';
    const toolName = toolResult.name || '';
    const toolIndex = toolResult.index || 0;
    const rawArgs = toolResult.raw_args || '{}';
    return concatArrays(encodeField(cursor_protobuf_schema_js_1.FIELD.ToolResult.CALL_ID, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, toolCallId), encodeField(cursor_protobuf_schema_js_1.FIELD.ToolResult.NAME, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, toolName), encodeField(cursor_protobuf_schema_js_1.FIELD.ToolResult.INDEX, cursor_protobuf_schema_js_1.WIRE_TYPE.VARINT, toolIndex), encodeField(cursor_protobuf_schema_js_1.FIELD.ToolResult.RAW_ARGS, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, rawArgs));
}
exports.encodeToolResult = encodeToolResult;
/**
 * Encode a conversation message
 */
function encodeMessage(content, role, messageId, isLast, hasTools, toolResults) {
    return concatArrays(encodeField(cursor_protobuf_schema_js_1.FIELD.Message.CONTENT, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, content), encodeField(cursor_protobuf_schema_js_1.FIELD.Message.ROLE, cursor_protobuf_schema_js_1.WIRE_TYPE.VARINT, role), encodeField(cursor_protobuf_schema_js_1.FIELD.Message.ID, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, messageId), ...(toolResults.length > 0
        ? toolResults.map((tr) => encodeField(cursor_protobuf_schema_js_1.FIELD.Message.TOOL_RESULTS, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, encodeToolResult(tr)))
        : []), encodeField(cursor_protobuf_schema_js_1.FIELD.Message.IS_AGENTIC, cursor_protobuf_schema_js_1.WIRE_TYPE.VARINT, hasTools ? 1 : 0), encodeField(cursor_protobuf_schema_js_1.FIELD.Message.UNIFIED_MODE, cursor_protobuf_schema_js_1.WIRE_TYPE.VARINT, hasTools ? cursor_protobuf_schema_js_1.UNIFIED_MODE.AGENT : cursor_protobuf_schema_js_1.UNIFIED_MODE.CHAT), ...(isLast && hasTools
        ? [encodeField(cursor_protobuf_schema_js_1.FIELD.Message.SUPPORTED_TOOLS, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, encodeVarint(1))]
        : []));
}
exports.encodeMessage = encodeMessage;
/**
 * Encode instruction text
 */
function encodeInstruction(text) {
    return text ? encodeField(cursor_protobuf_schema_js_1.FIELD.Instruction.TEXT, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, text) : new Uint8Array(0);
}
exports.encodeInstruction = encodeInstruction;
/**
 * Encode model information
 */
function encodeModel(modelName) {
    return concatArrays(encodeField(cursor_protobuf_schema_js_1.FIELD.Model.NAME, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, modelName), encodeField(cursor_protobuf_schema_js_1.FIELD.Model.EMPTY, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, new Uint8Array(0)));
}
exports.encodeModel = encodeModel;
/**
 * Encode cursor settings
 */
function encodeCursorSetting() {
    const unknown6 = concatArrays(encodeField(cursor_protobuf_schema_js_1.FIELD.Setting.U6_FIELD_1, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, new Uint8Array(0)), encodeField(cursor_protobuf_schema_js_1.FIELD.Setting.U6_FIELD_2, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, new Uint8Array(0)));
    return concatArrays(encodeField(cursor_protobuf_schema_js_1.FIELD.Setting.PATH, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, 'cursor\\aisettings'), encodeField(cursor_protobuf_schema_js_1.FIELD.Setting.UNKNOWN_3, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, new Uint8Array(0)), encodeField(cursor_protobuf_schema_js_1.FIELD.Setting.UNKNOWN_6, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, unknown6), encodeField(cursor_protobuf_schema_js_1.FIELD.Setting.UNKNOWN_8, cursor_protobuf_schema_js_1.WIRE_TYPE.VARINT, 1), encodeField(cursor_protobuf_schema_js_1.FIELD.Setting.UNKNOWN_9, cursor_protobuf_schema_js_1.WIRE_TYPE.VARINT, 1));
}
exports.encodeCursorSetting = encodeCursorSetting;
/**
 * Encode metadata
 */
function encodeMetadata() {
    return concatArrays(encodeField(cursor_protobuf_schema_js_1.FIELD.Metadata.PLATFORM, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, process.platform || 'linux'), encodeField(cursor_protobuf_schema_js_1.FIELD.Metadata.ARCH, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, process.arch || 'x64'), encodeField(cursor_protobuf_schema_js_1.FIELD.Metadata.VERSION, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, process.version || 'v20.0.0'), encodeField(cursor_protobuf_schema_js_1.FIELD.Metadata.CWD, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, process.cwd() || '/'), encodeField(cursor_protobuf_schema_js_1.FIELD.Metadata.TIMESTAMP, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, new Date().toISOString()));
}
exports.encodeMetadata = encodeMetadata;
/**
 * Encode message ID
 */
function encodeMessageId(messageId, role, summaryId) {
    return concatArrays(encodeField(cursor_protobuf_schema_js_1.FIELD.MessageId.ID, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, messageId), ...(summaryId ? [encodeField(cursor_protobuf_schema_js_1.FIELD.MessageId.SUMMARY, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, summaryId)] : []), encodeField(cursor_protobuf_schema_js_1.FIELD.MessageId.ROLE, cursor_protobuf_schema_js_1.WIRE_TYPE.VARINT, role));
}
exports.encodeMessageId = encodeMessageId;
/**
 * Encode MCP tool
 */
function encodeMcpTool(tool) {
    const toolName = tool.function?.name || tool.name || '';
    const toolDesc = tool.function?.description || tool.description || '';
    const inputSchema = tool.function?.parameters || tool.input_schema || {};
    return concatArrays(...(toolName ? [encodeField(cursor_protobuf_schema_js_1.FIELD.McpTool.NAME, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, toolName)] : []), ...(toolDesc ? [encodeField(cursor_protobuf_schema_js_1.FIELD.McpTool.DESC, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, toolDesc)] : []), ...(Object.keys(inputSchema).length > 0
        ? [encodeField(cursor_protobuf_schema_js_1.FIELD.McpTool.PARAMS, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, JSON.stringify(inputSchema))]
        : []), encodeField(cursor_protobuf_schema_js_1.FIELD.McpTool.SERVER, cursor_protobuf_schema_js_1.WIRE_TYPE.LEN, 'custom'));
}
exports.encodeMcpTool = encodeMcpTool;
/**
 * Wrap payload in ConnectRPC frame (5-byte header + payload)
 */
function wrapConnectRPCFrame(payload, compress = false) {
    let finalPayload = payload;
    let flags = cursor_protobuf_schema_js_1.COMPRESS_FLAG.NONE;
    if (compress) {
        finalPayload = new Uint8Array(zlib.gzipSync(Buffer.from(payload)));
        flags = cursor_protobuf_schema_js_1.COMPRESS_FLAG.GZIP;
    }
    const frame = new Uint8Array(5 + finalPayload.length);
    frame[0] = flags;
    frame[1] = (finalPayload.length >> 24) & 0xff;
    frame[2] = (finalPayload.length >> 16) & 0xff;
    frame[3] = (finalPayload.length >> 8) & 0xff;
    frame[4] = finalPayload.length & 0xff;
    frame.set(finalPayload, 5);
    return frame;
}
exports.wrapConnectRPCFrame = wrapConnectRPCFrame;
//# sourceMappingURL=cursor-protobuf-encoder.js.map