@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
87 lines • 4.03 kB
JavaScript
import { closeSync, fchmodSync, mkdirSync, openSync, writeSync } from "node:fs";
import { dirname, join } from "node:path";
import { APP_NAME } from "../config.js";
import { envValue } from "./brand.js";
import { rotateLogIfNeeded } from "./log-file-rotation.js";
const DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
const MAX_STRING_LENGTH = 200;
const DEBUG_PREFIX = `[${APP_NAME}-session]`;
const BLOCKED_KEY = /^(?:__proto__|constructor|prototype|headers?|env(?:ironment)?|authorization|credential(?:s)?|password|secret|token|api_?key|client_?secret)$/i;
const ALLOWED_DATA_KEY = /^(?:action|attemptId|disposition|stage|error|mode|count|willRetry|deferAdmission|delivered|restored|cause|accepted|skipped|rejectionCause|reason|durationMs|kind|retryable|phase|op|bytes|generation|requestId|tokens|tokensBefore|tokensAfter|contextWindow|attempt|aborted|sessionId|role|provider|model|source|actor|from|to|duringTurn|persistDefault|extension|handlerEvent|queuedId|ageMs|seat|until|shared|toolCallId|parentToolCallId|toolName|thresholdMs|elapsedMs|queueDepth|queueHead)$/;
const SENSITIVE_TEXT = /((?:authorization\s*[:=]\s*(?:bearer|basic)\s+)|(?:bearer\s+)|(?:[?&](?:api[_-]?key|token|secret|password|auth(?:orization)?)=))[^\s&,"'}\]]+/gi;
export function createSessionLogger(agentDir, options = {}) {
if (typeof agentDir !== "string" || agentDir.length === 0) {
return { debug: () => { }, info: () => { }, warn: () => { } };
}
const filePath = join(agentDir, "logs", "session.log");
const maxBytes = validMaxBytes(options.maxBytes);
let reportedWriteFailure = false;
function log(level, event, data) {
try {
const line = formatLine(level, event, options.context ? { ...options.context(), ...data } : data);
options.sink?.(line);
writeLine(filePath, line, maxBytes);
if (options.mirrorToStderr ?? envValue("SESSION_DEBUG") === "1") {
console.error(DEBUG_PREFIX, line);
}
}
catch (error) {
if (!reportedWriteFailure) {
reportedWriteFailure = true;
console.error("Unable to write session log", error);
}
}
}
return {
debug: (event, data) => log("debug", event, data),
info: (event, data) => log("info", event, data),
warn: (event, data) => log("warn", event, data),
};
}
function validMaxBytes(value) {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : DEFAULT_MAX_BYTES;
}
function formatLine(level, event, data) {
const entry = {
ts: new Date().toISOString(),
level,
event: safeText(event),
};
if (data !== undefined) {
for (const [key, value] of Object.entries(data)) {
if (ALLOWED_DATA_KEY.test(key) && !BLOCKED_KEY.test(key)) {
const safeValue = serializeValue(value);
if (safeValue !== undefined)
entry[key] = safeValue;
}
}
}
return JSON.stringify(entry);
}
function writeLine(filePath, line, maxBytes) {
mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
const text = `${line}\n`;
rotateLogIfNeeded(filePath, Buffer.byteLength(text), maxBytes);
const descriptor = openSync(filePath, "a", 0o600);
try {
writeSync(descriptor, text);
fchmodSync(descriptor, 0o600);
}
finally {
closeSync(descriptor);
}
}
function serializeValue(value) {
if (typeof value === "string")
return safeText(value);
if (typeof value === "number" || typeof value === "boolean" || value === null)
return value;
if (typeof value === "bigint")
return value.toString();
return undefined;
}
function safeText(value) {
const redacted = value.replace(SENSITIVE_TEXT, "$1[redacted]");
return redacted.length <= MAX_STRING_LENGTH ? redacted : `${redacted.slice(0, MAX_STRING_LENGTH - 3)}...`;
}
//# sourceMappingURL=session-log.js.map