450 lines
15 KiB
JavaScript
450 lines
15 KiB
JavaScript
import { existsSync, readFileSync } from "node:fs";
|
||
import { dirname, posix, resolve, win32 } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { randomUUID } from "node:crypto";
|
||
import { spawn } from "node:child_process";
|
||
// src/flags.ts
|
||
const defaultFlags = { readerEnabled: true };
|
||
function locateFlags(start = dirname(fileURLToPath(import.meta.url))) {
|
||
let dir = start;
|
||
for (let depth = 0; depth < 6; depth += 1) {
|
||
const candidate = resolve(dir, "flags.json");
|
||
if (existsSync(candidate)) return candidate;
|
||
const parent = dirname(dir);
|
||
if (parent === dir) return void 0;
|
||
dir = parent;
|
||
}
|
||
}
|
||
function normalize(value) {
|
||
const record = value !== null && typeof value === "object" ? value : {};
|
||
return { readerEnabled: typeof record.readerEnabled === "boolean" ? record.readerEnabled : defaultFlags.readerEnabled };
|
||
}
|
||
function loadFlags(source) {
|
||
if (source !== void 0 && typeof source !== "string") return normalize(source);
|
||
try {
|
||
const path = typeof source === "string" ? source : locateFlags();
|
||
if (path === void 0 || !existsSync(path)) return { ...defaultFlags };
|
||
return normalize(JSON.parse(readFileSync(path, "utf8")));
|
||
} catch {
|
||
return { ...defaultFlags };
|
||
}
|
||
}
|
||
// src/log.ts
|
||
const REDACTED = "[REDACTED]";
|
||
const REQUEST_ID_HEADER = "x-request-id";
|
||
const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,200}$/;
|
||
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)
|
||
};
|
||
}
|
||
function requestIdOf(req) {
|
||
const raw = req.headers[REQUEST_ID_HEADER];
|
||
const value = Array.isArray(raw) ? raw[0] : raw;
|
||
if (typeof value === "string" && REQUEST_ID_PATTERN.test(value)) return value;
|
||
return randomUUID();
|
||
}
|
||
// src/metrics.ts
|
||
const ROUTE_REVEAL = "/better-display/reveal";
|
||
const ROUTE_METRICS = "/better-display/metrics";
|
||
const ROUTE_HITS = [ROUTE_REVEAL, ROUTE_METRICS];
|
||
const hits = new Map(ROUTE_HITS.map((route) => [route, 0]));
|
||
const timings = new Map(ROUTE_HITS.map((route) => [route, {
|
||
count: 0,
|
||
totalMs: 0,
|
||
maxMs: 0
|
||
}]));
|
||
function snapshotHits() {
|
||
return Object.fromEntries(hits);
|
||
}
|
||
function snapshotTimings() {
|
||
return Object.fromEntries([...timings].map(([route, timing]) => [route, { ...timing }]));
|
||
}
|
||
function recordRouteHit(route) {
|
||
const next = (hits.get(route) ?? 0) + 1;
|
||
hits.set(route, next);
|
||
return next;
|
||
}
|
||
function recordRouteDuration(route, elapsedMs) {
|
||
const ms = Number.isFinite(elapsedMs) && elapsedMs > 0 ? Math.round(elapsedMs) : 0;
|
||
const current = timings.get(route) ?? {
|
||
count: 0,
|
||
totalMs: 0,
|
||
maxMs: 0
|
||
};
|
||
const next = {
|
||
count: current.count + 1,
|
||
totalMs: current.totalMs + ms,
|
||
maxMs: Math.max(current.maxMs, ms)
|
||
};
|
||
timings.set(route, next);
|
||
return next;
|
||
}
|
||
function metricsPayload() {
|
||
return {
|
||
counters: { dsh_better_display_route_hits_total: snapshotHits() },
|
||
timingsMs: snapshotTimings()
|
||
};
|
||
}
|
||
// src/workspace-path.ts
|
||
/** Absolute paths accepted by both POSIX and Windows hosts. */
|
||
function isAbsoluteWorkspacePath(path) {
|
||
return /^(?:\/|[A-Za-z]:[/\\]|\\\\)/.test(path);
|
||
}
|
||
// \0@oxc-project+runtime@0.158.0/helpers/esm/usingCtx.js
|
||
function _usingCtx() {
|
||
var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
|
||
var n = Error();
|
||
return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
|
||
}, e = {}, n = [];
|
||
function using(r, e) {
|
||
if (null != e) {
|
||
if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
|
||
if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
|
||
if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
|
||
if ("function" != typeof o) throw new TypeError("Object is not disposable.");
|
||
t && (o = function o() {
|
||
try {
|
||
t.call(e);
|
||
} catch (r) {
|
||
return Promise.reject(r);
|
||
}
|
||
}), n.push({
|
||
v: e,
|
||
d: o,
|
||
a: r
|
||
});
|
||
} else r && n.push({
|
||
d: e,
|
||
a: r
|
||
});
|
||
return e;
|
||
}
|
||
return {
|
||
e,
|
||
u: using.bind(null, !1),
|
||
a: using.bind(null, !0),
|
||
d: function d() {
|
||
var o, t = this.e, s = 0;
|
||
function next() {
|
||
for (; o = n.pop();) try {
|
||
if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
|
||
if (o.d) {
|
||
var r = o.d.call(o.v);
|
||
if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
|
||
} else s |= 1;
|
||
} catch (r) {
|
||
return err(r);
|
||
}
|
||
if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
|
||
if (t !== e) throw t;
|
||
}
|
||
function err(n) {
|
||
return t = t !== e ? new r(n, t) : n, next();
|
||
}
|
||
return next();
|
||
}
|
||
};
|
||
}
|
||
// src/reveal.ts
|
||
async function revealRoots(ctx, sessionId) {
|
||
if (sessionId !== void 0) {
|
||
const cwd = (ctx.get?.("sessions"))?.get(sessionId)?.header.cwd;
|
||
if (cwd) return [cwd];
|
||
const query = ctx.get?.("sessionQuery");
|
||
if (query) try {
|
||
var _usingCtx$1 = _usingCtx();
|
||
const observation = _usingCtx$1.u(await query.observeSession(sessionId, { projectionMode: "none" }));
|
||
if (observation.header.cwd) return [observation.header.cwd];
|
||
} catch (_) {
|
||
_usingCtx$1.e = _;
|
||
} finally {
|
||
_usingCtx$1.d();
|
||
}
|
||
}
|
||
return ((ctx.get?.("workspaceRegistry"))?.list() ?? []).filter((workspace) => sessionId === void 0 || workspace.sessionIds.includes(sessionId)).map((workspace) => workspace.path);
|
||
}
|
||
function resolveRevealPath(path, roots, exists = existsSync) {
|
||
if (isAbsoluteWorkspacePath(path)) return path;
|
||
if (/^[A-Za-z]:|^\\/.test(path)) throw new Error("Path is not workspace-relative");
|
||
const matches = /* @__PURE__ */ new Set();
|
||
for (const root of roots) {
|
||
if (!isAbsoluteWorkspacePath(root)) continue;
|
||
const candidate = (/^[A-Za-z]:[/\\]|^\\\\/.test(root) ? win32 : posix).resolve(root, path);
|
||
if (exists(candidate)) matches.add(candidate);
|
||
}
|
||
if (matches.size !== 1) throw new Error(matches.size === 0 ? "Workspace path not found" : "Workspace path is ambiguous");
|
||
return [...matches][0];
|
||
}
|
||
function revealPath(path, platform = process.platform, spawnProcess = spawn) {
|
||
const options = {
|
||
detached: true,
|
||
stdio: "ignore"
|
||
};
|
||
if (platform === "darwin") spawnProcess("open", ["-R", path], options);
|
||
else if (platform === "win32") spawnProcess("explorer.exe", [`/select,"${path}"`], {
|
||
...options,
|
||
windowsVerbatimArguments: true
|
||
});
|
||
else spawnProcess("xdg-open", [path], options);
|
||
}
|
||
function createRevealHandler({ roots, reveal = revealPath }) {
|
||
return (req, res) => {
|
||
if (req.method !== "POST") {
|
||
res.statusCode = 405;
|
||
res.end();
|
||
return;
|
||
}
|
||
let body = "";
|
||
req.on("data", (chunk) => {
|
||
body += chunk;
|
||
});
|
||
req.on("end", async () => {
|
||
res.setHeader("Content-Type", "application/json");
|
||
try {
|
||
const data = JSON.parse(body);
|
||
const path = typeof data === "object" && data !== null && "path" in data && typeof data.path === "string" ? data.path.trim() : "";
|
||
if (!path) throw new Error("Empty path");
|
||
const sessionId = typeof data === "object" && data !== null && "sessionId" in data && typeof data.sessionId === "string" ? data.sessionId : void 0;
|
||
reveal(resolveRevealPath(path, isAbsoluteWorkspacePath(path) ? [] : await roots(sessionId)));
|
||
res.statusCode = 200;
|
||
res.end(JSON.stringify({ ok: true }));
|
||
} catch (err) {
|
||
res.statusCode = 400;
|
||
res.end(JSON.stringify({
|
||
ok: false,
|
||
error: String(err)
|
||
}));
|
||
}
|
||
});
|
||
};
|
||
}
|
||
// src/host.ts
|
||
const name = "dsh-better-chat";
|
||
const inject = ["webServer"];
|
||
const log = createLogger({ base: { plugin: name } });
|
||
function writeJson(res, status, body) {
|
||
res.setHeader("Content-Type", "application/json");
|
||
res.statusCode = status;
|
||
res.end(JSON.stringify(body));
|
||
}
|
||
function beginRequest(req, res, route) {
|
||
const requestId = requestIdOf(req);
|
||
res.setHeader("X-Request-ID", requestId);
|
||
recordRouteHit(route);
|
||
const started = performance.now();
|
||
res.on("finish", () => {
|
||
recordRouteDuration(route, performance.now() - started);
|
||
});
|
||
log.info("http request", {
|
||
requestId,
|
||
route,
|
||
method: req.method ?? "",
|
||
url: req.url ?? "",
|
||
headers: req.headers
|
||
});
|
||
return requestId;
|
||
}
|
||
const AUTO_REVIEW_PRESET = "auto";
|
||
/**
|
||
* 判断宿主会话是否为「尚未开始对话、且用户未手动改过权限」的新建空白顶层会话。
|
||
* - 排除子代理会话(`origin === 'subagent'`)与 fork/seed 会话(`isSeeded` / `inheritedEventCount > 0` / `session/end-seed`);
|
||
* - 排除已开始轮次或已有用户消息的会话(`turn/start` / `user/message`);
|
||
* - 排除用户已显式执行过 `/permission` 命令的会话(`command/run` 且 `name === '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, options) {
|
||
const flags = options?.flags ?? loadFlags();
|
||
log.info("[dsh-better-chat] loaded", { readerEnabled: flags.readerEnabled });
|
||
const anyCtx = ctx;
|
||
if (typeof anyCtx.inject === "function") anyCtx.inject(["permissionPresets", "agents"], (childCtx) => {
|
||
mountAutoReviewListeners(childCtx);
|
||
});
|
||
if (!flags.readerEnabled) {
|
||
log.info("route registration skipped", { readerEnabled: false });
|
||
return;
|
||
}
|
||
if (ctx.webServer) ctx.effect(() => {
|
||
const reveal = createRevealHandler({ roots: (sessionId) => revealRoots(ctx, sessionId) });
|
||
const disposeReveal = ctx.webServer.register({
|
||
kind: "exact",
|
||
path: ROUTE_REVEAL,
|
||
handler: (req, res) => {
|
||
beginRequest(req, res, ROUTE_REVEAL);
|
||
reveal(req, res);
|
||
}
|
||
});
|
||
const disposeMetrics = ctx.webServer.register({
|
||
kind: "exact",
|
||
path: ROUTE_METRICS,
|
||
handler: (req, res) => {
|
||
beginRequest(req, res, ROUTE_METRICS);
|
||
if (req.method !== "GET") {
|
||
res.statusCode = 405;
|
||
res.end();
|
||
return;
|
||
}
|
||
writeJson(res, 200, metricsPayload());
|
||
}
|
||
});
|
||
return () => {
|
||
disposeReveal();
|
||
disposeMetrics();
|
||
};
|
||
}, "dsh-better-chat: reveal and metrics routes");
|
||
}
|
||
export { apply, applyHostAutoReview, inject, isFreshAutoEligibleSession, name };
|