zephyr-agent
Version:
Zephyr plugin agent
133 lines (132 loc) • 5.2 kB
JavaScript
import "node:module";
import { appendFileSync, mkdirSync } from "node:fs";
import { join, resolve } from "node:path";
import { stripAnsi } from "zephyr-edge-contract";
import { ZE_PATH } from "../node-persist/storage-keys.mjs";
import { redactString, safeStringifyForLogging, sanitizeForLogging } from "../security/redaction.mjs";
import { __webpack_require__ } from "../../rslib-runtime~0.mjs";
import { createRequire as __rspack_createRequire } from "node:module";
const __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
__webpack_require__.add({
"@toon-format/toon" (module) {
module.exports = __rspack_createRequire_require("@toon-format/toon");
}
});
let currentRunDir = null;
let runStartTime = null;
function getLogBasePath() {
const customPath = process.env['ZEPHYR_LOG_PATH'];
if (customPath) return resolve(customPath);
return join(ZE_PATH, 'logs');
}
function initializeLogRun() {
if (!runStartTime) runStartTime = Date.now();
if (!currentRunDir) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
const runId = `run-${timestamp}`;
const logBasePath = getLogBasePath();
currentRunDir = join(logBasePath, runId);
try {
mkdirSync(currentRunDir, {
recursive: true
});
} catch (error) {
console.error(redactString(`Failed to create log directory: ${String(error)}`));
}
}
return currentRunDir;
}
function getCurrentRunDir() {
return currentRunDir;
}
function resetLogRun() {
currentRunDir = null;
runStartTime = null;
}
function extractStructuredData(message) {
const jsonRegex = /\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}/g;
const matches = message.match(jsonRegex);
if (matches && matches.length > 0) {
const parsed = [];
let allValid = true;
for (const match of matches)try {
parsed.push(JSON.parse(match));
} catch {
allValid = false;
break;
}
if (allValid && parsed.length > 0) {
let cleanMessage = message.replace(jsonRegex, '').trim();
cleanMessage = cleanMessage.replace(/\s+/g, ' ').trim();
cleanMessage = cleanMessage.replace(/\s*(Response|Options|Payload|Data):\s*/gi, ' ').trim();
if (!cleanMessage) cleanMessage = 'Structured data';
const payload = 1 === parsed.length ? parsed[0] : parsed;
return {
message: cleanMessage,
payload
};
}
}
return {
message
};
}
function writeLogToFile(logData) {
const runDir = initializeLogRun();
const format = getLogFormat();
const extension = 'toon' === format ? 'toon' : 'log';
let filename;
if (logData.action?.startsWith('debug:')) {
const context = logData.action.replace('debug:', '');
filename = `debug-${context}.${extension}`;
} else if (logData.action) {
const actionName = logData.action.replace(/:/g, '-');
filename = `action-${actionName}.${extension}`;
} else filename = `${logData.level}.${extension}`;
const logFilePath = join(runDir, filename);
const cleanMsg = redactString(stripAnsi(logData.message));
const { message, payload } = extractStructuredData(cleanMsg);
const logEntry = {
level: logData.level,
message,
timestamp: logData.timestamp || Date.now()
};
if (logData.action) logEntry['action'] = logData.action;
if (payload) logEntry['payload'] = sanitizeForLogging(payload);
if (logData.data) logEntry['data'] = sanitizeForLogging(logData.data);
try {
let logLine;
if ('toon' === format) {
const { encode } = __webpack_require__("@toon-format/toon");
logLine = encode(sanitizeForLogging(logEntry)) + '\n';
} else logLine = safeStringifyForLogging(logEntry) + '\n';
appendFileSync(logFilePath, logLine, 'utf8');
} catch (error) {
console.error(redactString(`Failed to write to log file: ${String(error)}`));
}
}
function writeRunSummary(data) {
const runDir = getCurrentRunDir();
if (!runDir) return;
const summaryPath = join(runDir, 'summary.json');
const summary = {
...data,
startTime: runStartTime ? new Date(runStartTime).toISOString() : null,
endTime: new Date().toISOString(),
duration: data.duration || (runStartTime ? Date.now() - runStartTime : 0)
};
try {
appendFileSync(summaryPath, safeStringifyForLogging(summary, 2), 'utf8');
} catch (error) {
console.error(redactString(`Failed to write summary file: ${String(error)}`));
}
}
function isFileLoggingEnabled() {
return 'true' === process.env['ZEPHYR_LOG_TO_FILE'] || '1' === process.env['ZEPHYR_LOG_TO_FILE'];
}
function getLogFormat() {
const format = process.env['ZEPHYR_LOG_FORMAT'];
return 'toon' === format ? 'toon' : 'json';
}
export { getCurrentRunDir, getLogBasePath, getLogFormat, initializeLogRun, isFileLoggingEnabled, resetLogRun, writeLogToFile, writeRunSummary };
//# sourceMappingURL=file-logger.mjs.map