← Files RivetARCHIVED FILE

node_modules/rivet-design/dist/cli/callerModel.js

5.73 KB · Nov 7, 2026 · 13:16 UTC

↓ Download file

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.callerModelArgsFromToolMeta = exports.withCallerSessionModel = exports.readCallerSessionModel = void 0;
const fs_1 = __importDefault(require("fs"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const SESSION_LOG_TAIL_BYTES = 4 * 1024 * 1024;
const SESSION_MODEL_WAIT_MS = 1500;
const SESSION_MODEL_POLL_INTERVAL_MS = 100;
const CLAUDE_SYNTHETIC_MODEL = '<synthetic>';
const CODEX_TURN_METADATA_KEY = 'x-codex-turn-metadata';
const nonEmptyString = (value) => typeof value === 'string' && value.trim() ? value.trim() : undefined;
const readDirectory = (directory) => {
    try {
        return fs_1.default.readdirSync(directory);
    }
    catch {
        return [];
    }
};
const readTailLines = (filePath) => {
    const handle = fs_1.default.openSync(filePath, 'r');
    try {
        const { size } = fs_1.default.fstatSync(handle);
        const length = Math.min(size, SESSION_LOG_TAIL_BYTES);
        const buffer = Buffer.alloc(length);
        fs_1.default.readSync(handle, buffer, 0, length, size - length);
        const lines = buffer.toString('utf8').split('\n');
        return length < size ? lines.slice(1) : lines;
    }
    finally {
        fs_1.default.closeSync(handle);
    }
};
const latestModelIn = (filePath, modelOf) => {
    const lines = readTailLines(filePath);
    for (let index = lines.length - 1; index >= 0; index--) {
        let entry;
        try {
            entry = JSON.parse(lines[index]);
        }
        catch {
            continue;
        }
        const model = entry && typeof entry === 'object' ? modelOf(entry) : undefined;
        if (model)
            return model;
    }
    return undefined;
};
const claudeSessionLog = (sessionId, { env = process.env, homeDir = os_1.default.homedir() }) => ({
    filePath: () => {
        const projectsDir = path_1.default.join(env.CLAUDE_CONFIG_DIR ?? path_1.default.join(homeDir, '.claude'), 'projects');
        return readDirectory(projectsDir)
            .map((project) => path_1.default.join(projectsDir, project, `${sessionId}.jsonl`))
            .find((candidate) => fs_1.default.existsSync(candidate));
    },
    modelOf: (entry) => {
        if (entry.type !== 'assistant' || entry.isSidechain === true) {
            return undefined;
        }
        const model = nonEmptyString(entry.message?.model);
        return model === CLAUDE_SYNTHETIC_MODEL ? undefined : model;
    },
});
const newestFirst = (directory) => readDirectory(directory).sort().reverse();
const codexSessionLog = (threadId, { env = process.env, homeDir = os_1.default.homedir() }) => ({
    filePath: () => {
        const sessionsDir = path_1.default.join(env.CODEX_HOME ?? path_1.default.join(homeDir, '.codex'), 'sessions');
        const rolloutSuffix = `-${threadId}.jsonl`;
        for (const year of newestFirst(sessionsDir)) {
            for (const month of newestFirst(path_1.default.join(sessionsDir, year))) {
                for (const day of newestFirst(path_1.default.join(sessionsDir, year, month))) {
                    const dayDir = path_1.default.join(sessionsDir, year, month, day);
                    const rollout = readDirectory(dayDir).find((name) => name.startsWith('rollout-') && name.endsWith(rolloutSuffix));
                    if (rollout)
                        return path_1.default.join(dayDir, rollout);
                }
            }
        }
        return undefined;
    },
    modelOf: (entry) => entry.type === 'turn_context'
        ? nonEmptyString(entry.payload?.model)
        : undefined,
});
const callerSessionLogFor = (agent, environment) => {
    const env = environment.env ?? process.env;
    if (agent === 'claude') {
        const sessionId = nonEmptyString(env.CLAUDE_CODE_SESSION_ID);
        return sessionId ? claudeSessionLog(sessionId, environment) : undefined;
    }
    if (agent === 'codex') {
        const threadId = nonEmptyString(env.CODEX_THREAD_ID);
        return threadId ? codexSessionLog(threadId, environment) : undefined;
    }
    return undefined;
};
const modelFromSessionLog = (log) => {
    try {
        const filePath = log.filePath();
        return filePath ? latestModelIn(filePath, log.modelOf) : undefined;
    }
    catch {
        return undefined;
    }
};
const readCallerSessionModel = (agent, environment = {}) => {
    const log = callerSessionLogFor(agent, environment);
    return log ? modelFromSessionLog(log) : undefined;
};
exports.readCallerSessionModel = readCallerSessionModel;
const sleep = (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs));
const withCallerSessionModel = async (handoff, environment = {}) => {
    if (!handoff)
        return handoff;
    const log = callerSessionLogFor(handoff.agent, environment);
    if (!log)
        return handoff;
    const deadline = Date.now() + (environment.waitMs ?? SESSION_MODEL_WAIT_MS);
    for (;;) {
        const model = modelFromSessionLog(log);
        if (model)
            return { ...handoff, model };
        if (Date.now() >= deadline)
            return handoff;
        await sleep(SESSION_MODEL_POLL_INTERVAL_MS);
    }
};
exports.withCallerSessionModel = withCallerSessionModel;
const callerModelArgsFromToolMeta = (meta) => {
    if (typeof meta !== 'object' || meta === null)
        return [];
    const turn = meta[CODEX_TURN_METADATA_KEY];
    const model = typeof turn === 'object' && turn !== null
        ? nonEmptyString(turn.model)
        : undefined;
    return model ? ['--caller-model', model] : [];
};
exports.callerModelArgsFromToolMeta = callerModelArgsFromToolMeta;
//# sourceMappingURL=callerModel.js.map

SHA-256: f555fcbcf324e3ecee5b9a2db6dd684ffbcb55cae7968f97e14ebc1d892e1e17