dsh-better-chat/lib/host.js

181 lines
6.1 KiB
JavaScript

// src/log.ts
const REDACTED = "[REDACTED]";
const SECRET_KEYS = /* @__PURE__ */ new Set([
"authorization",
"proxyauthorization",
"cookie",
"setcookie",
"token",
"accesstoken",
"refreshtoken",
"idtoken",
"apikey",
"apisecret",
"secret",
"clientsecret",
"password",
"passwd",
"credential",
"credentials",
"signature",
"sig",
"jwt",
"bearer",
"privatekey",
"xapikey",
"xauthtoken",
"xaccesstoken",
"auth"
]);
function normalizeKey(key) {
return key.toLowerCase().replace(/[^a-z0-9]/g, "");
}
function isSecretKey(key) {
const normalized = normalizeKey(key);
if (SECRET_KEYS.has(normalized)) return true;
if (normalized === "requestid" || normalized === "xrequestid") return false;
return /(?:^|[^a-z])(?:token|secret|password|api[-_]?key)$/i.test(key);
}
function redactString(value) {
return value.replace(/([?&#])([^&#=]+)=([^&#]*)/g, (match, sep, rawKey) => {
let key;
try {
key = decodeURIComponent(rawKey.replace(/\+/g, " "));
} catch {
key = rawKey;
}
return isSecretKey(key) ? `${sep}${rawKey}=${REDACTED}` : match;
}).replace(/\b(Bearer|Basic)\s+\S+/gi, `$1 ${REDACTED}`).replace(/\b((?:access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|authorization|token|secret))(\s*[:=]\s*)([^\s&]+)/gi, `$1$2${REDACTED}`);
}
function redact(value) {
return redactValue(void 0, value, 0, /* @__PURE__ */ new WeakSet());
}
function redactValue(key, value, depth, seen) {
if (key !== void 0 && isSecretKey(key)) return REDACTED;
if (depth > 8) return REDACTED;
if (typeof value === "string") return redactString(value);
if (typeof value === "number" || typeof value === "boolean" || value === null || value === void 0) return value;
if (typeof value !== "object") return REDACTED;
if (value instanceof Date) return value.toISOString();
if (value instanceof Error) return redactValue(void 0, {
name: value.name,
message: value.message
}, depth + 1, seen);
if (seen.has(value)) return REDACTED;
seen.add(value);
if (Array.isArray(value)) return value.map((item) => redactValue(void 0, item, depth + 1, seen));
const output = {};
for (const [childKey, childValue] of Object.entries(value)) output[childKey] = redactValue(childKey, childValue, depth + 1, seen);
return output;
}
function createLogger(options = {}) {
const write = options.write ?? ((line) => {
console.log(line);
});
const clock = options.clock ?? (() => /* @__PURE__ */ new Date());
const emit = (level, msg, fields) => {
const details = redact({
...options.base,
...fields
});
const record = {
...details !== null && typeof details === "object" ? details : {},
time: clock().toISOString(),
level,
msg: redactString(msg)
};
try {
write(JSON.stringify(record));
} catch {
write(JSON.stringify({
time: record.time,
level,
msg: record.msg,
error: "log record was not serializable"
}));
}
};
return {
info: (msg, fields) => emit("info", msg, fields),
warn: (msg, fields) => emit("warn", msg, fields),
error: (msg, fields) => emit("error", msg, fields)
};
}
// src/host.ts
const name = "dsh-better-chat";
const inject = [];
const log = createLogger({ base: { plugin: name } });
const AUTO_REVIEW_PRESET = "auto";
/**
* 判断宿主会话是否为「尚未开始对话、且用户未手动改过权限」的新建空白顶层会话。
* - 排除子代理会话(`origin === 'subagent'`)与 fork/seed 会话;
* - 排除已开始轮次或已有用户消息的会话;
* - 排除用户已显式执行过 `/permission` 命令的会话。
*/
function isFreshAutoEligibleSession(session) {
if (!session || typeof session !== "object") return false;
const header = session.header;
if (header?.origin === "subagent") return false;
if (header?.isSeeded === true) return false;
if (typeof session.inheritedEventCount === "number" && session.inheritedEventCount > 0) return false;
if (typeof session.snapshotEvents === "function") try {
const events = session.snapshotEvents();
for (const event of events) if (event?.type === "turn/start" || event?.type === "user/message" || event?.type === "session/end-seed" || event?.type === "command/run" && event?.data?.name === "permission") return false;
} catch {
return false;
}
return true;
}
function applyHostAutoReview(permissionPresets, session, handled) {
if (!permissionPresets || !session) return false;
const id = typeof session.id === "string" ? session.id : typeof session.header?.id === "string" ? session.header.id : void 0;
if (id && handled.has(id)) return false;
if (!isFreshAutoEligibleSession(session)) {
if (id) handled.add(id);
return false;
}
const names = permissionPresets.names;
if (!Array.isArray(names) || !names.includes(AUTO_REVIEW_PRESET)) return false;
if (id) handled.add(id);
try {
if (permissionPresets.current?.(session) === AUTO_REVIEW_PRESET) return false;
permissionPresets.set?.(session, AUTO_REVIEW_PRESET);
return true;
} catch (err) {
log.info("auto review preset switch skipped", {
sessionId: id ?? "",
error: err instanceof Error ? err.message : String(err)
});
return false;
}
}
function mountAutoReviewListeners(targetCtx) {
const handled = /* @__PURE__ */ new Set();
const scanAll = () => {
const presets = targetCtx.permissionPresets;
const list = targetCtx.agents?.list?.() ?? [];
for (const agent of list) if (agent?.session) applyHostAutoReview(presets, agent.session, handled);
};
targetCtx.effect?.(() => {
const offCreated = targetCtx.on?.("agent/created", ({ agent }) => {
if (agent?.session) applyHostAutoReview(targetCtx.permissionPresets, agent.session, handled);
});
const offCatalog = targetCtx.on?.("permission-presets/catalog-changed", () => {
scanAll();
});
scanAll();
return () => {
if (typeof offCreated === "function") offCreated();
if (typeof offCatalog === "function") offCatalog();
};
}, "dsh-better-chat: default auto-review preset for new sessions");
}
function apply(ctx) {
log.info("[dsh-better-chat] loaded");
const anyCtx = ctx;
if (typeof anyCtx.inject === "function") anyCtx.inject(["permissionPresets", "agents"], (childCtx) => {
mountAutoReviewListeners(childCtx);
});
}
export { apply, applyHostAutoReview, inject, isFreshAutoEligibleSession, name };