sources.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import { existsSync } from "node:fs";
  2. import { readdir, readFile, stat } from "node:fs/promises";
  3. import { homedir } from "node:os";
  4. import { basename, join, resolve } from "node:path";
  5. import { DatabaseSync } from "node:sqlite";
  6. import type {
  7. DbMessageRecord,
  8. DbObservation,
  9. DbPartRecord,
  10. DbSessionRecord,
  11. EventRecord,
  12. JsonRecord,
  13. LogRecord,
  14. ObservationOptions,
  15. SourceLoadResult,
  16. } from "./types.js";
  17. export function defaultLogDir(): string {
  18. return join(homedir(), ".zcode", "cli", "log");
  19. }
  20. export function defaultDbPath(): string {
  21. return join(homedir(), ".zcode", "cli", "db", "db.sqlite");
  22. }
  23. export async function loadLogs(options: ObservationOptions): Promise<SourceLoadResult<LogRecord>> {
  24. const logDir = resolve(options.logDir ?? defaultLogDir());
  25. const jsonl = await readJsonlFiles(logDir, "结构化日志");
  26. return {
  27. kind: "log",
  28. label: "结构化日志",
  29. path: logDir,
  30. records: jsonl.records.map(toLogRecord).filter((record) => record !== null),
  31. warning: jsonl.warning,
  32. };
  33. }
  34. export async function loadEventLog(
  35. options: ObservationOptions,
  36. ): Promise<SourceLoadResult<EventRecord>> {
  37. if (!options.eventPath) {
  38. return {
  39. kind: "eventlog",
  40. label: "Session 事件 JSONL",
  41. records: [],
  42. warning: "未配置 Session 事件 JSONL 路径。",
  43. };
  44. }
  45. const eventPath = resolve(options.eventPath);
  46. const jsonl = await readJsonlFiles(eventPath, "Session 事件 JSONL");
  47. return {
  48. kind: "eventlog",
  49. label: "Session 事件 JSONL",
  50. path: eventPath,
  51. records: jsonl.records.map(toEventRecord).filter((record) => record !== null),
  52. warning: jsonl.warning,
  53. };
  54. }
  55. export function loadSqlite(options: ObservationOptions): SourceLoadResult<DbObservation> {
  56. const dbPath = resolve(options.dbPath ?? defaultDbPath());
  57. if (!existsSync(dbPath)) {
  58. return {
  59. kind: "sqlite",
  60. label: "SQLite Session 数据库",
  61. path: dbPath,
  62. records: [],
  63. warning: "未找到 SQLite Session 数据库。",
  64. };
  65. }
  66. let db: DatabaseSync | undefined;
  67. try {
  68. db = new DatabaseSync(dbPath, { readOnly: true });
  69. const observation: DbObservation = {
  70. sessions: readSessions(db),
  71. messages: readMessages(db),
  72. parts: readParts(db),
  73. };
  74. return {
  75. kind: "sqlite",
  76. label: "SQLite Session 数据库",
  77. path: dbPath,
  78. records: [observation],
  79. };
  80. } catch (error) {
  81. return {
  82. kind: "sqlite",
  83. label: "SQLite Session 数据库",
  84. path: dbPath,
  85. records: [],
  86. warning: error instanceof Error ? error.message : String(error),
  87. };
  88. } finally {
  89. db?.close();
  90. }
  91. }
  92. interface JsonlReadResult {
  93. records: JsonRecord[];
  94. warning?: string;
  95. }
  96. async function readJsonlFiles(inputPath: string, label: string): Promise<JsonlReadResult> {
  97. if (!existsSync(inputPath)) {
  98. return { records: [], warning: `${label} 路径不存在。` };
  99. }
  100. const inputStat = await stat(inputPath);
  101. const files = inputStat.isDirectory()
  102. ? (await readdir(inputPath))
  103. .filter((entry) => entry.endsWith(".jsonl") || entry.endsWith(".log"))
  104. .sort()
  105. .map((entry) => join(inputPath, entry))
  106. : [inputPath];
  107. const records: JsonRecord[] = [];
  108. const warnings: string[] = [];
  109. for (const file of files) {
  110. try {
  111. const content = await readFile(file, "utf8");
  112. const lines = content.split(/\r?\n/);
  113. for (const [index, line] of lines.entries()) {
  114. if (!line.trim()) continue;
  115. try {
  116. const parsed = JSON.parse(line) as unknown;
  117. if (isRecord(parsed)) {
  118. records.push({ value: parsed, sourcePath: file, line: index + 1 });
  119. }
  120. } catch {
  121. warnings.push(`${basename(file)}:${index + 1} 不是合法 JSON。`);
  122. }
  123. }
  124. } catch (error) {
  125. warnings.push(error instanceof Error ? error.message : String(error));
  126. }
  127. }
  128. return {
  129. records,
  130. warning: warnings.length > 0 ? warnings.join(" ") : undefined,
  131. };
  132. }
  133. function toLogRecord(record: JsonRecord): LogRecord | null {
  134. const value = record.value;
  135. const message = stringValue(value.message);
  136. const event = stringValue(value.event);
  137. if (!message && !event) return null;
  138. return {
  139. timestamp: stringValue(value.timestamp),
  140. level: stringValue(value.level),
  141. event,
  142. module: stringValue(value.module),
  143. message,
  144. traceId: stringValue(value.traceId),
  145. sessionId: stringValue(value.sessionId),
  146. turnId: stringValue(value.turnId),
  147. spanId: stringValue(value.spanId),
  148. parentSpanId: stringValue(value.parentSpanId),
  149. toolCallId: stringValue(value.toolCallId),
  150. durationMs: numberValue(value.durationMs),
  151. status: stringValue(value.status),
  152. context: isRecord(value.context) ? value.context : undefined,
  153. error: value.error,
  154. sourcePath: record.sourcePath,
  155. line: record.line,
  156. };
  157. }
  158. function toEventRecord(record: JsonRecord): EventRecord | null {
  159. const value = record.value;
  160. const type = stringValue(value.type);
  161. if (!type) return null;
  162. return {
  163. id: stringValue(value.id) ?? stringValue(value.eventId) ?? `${record.sourcePath}:${record.line}`,
  164. type,
  165. timestamp:
  166. stringValue(value.timestamp) ?? stringValue(value.occurredAt) ?? stringValue(value.recordedAt),
  167. traceId: stringValue(value.traceId),
  168. sessionId: stringValue(value.sessionId),
  169. turnId: stringValue(value.turnId),
  170. spanId: stringValue(value.spanId),
  171. parentSpanId: stringValue(value.parentSpanId),
  172. sequenceNumber: numberValue(value.sequenceNumber),
  173. payload: isRecord(value.payload) ? value.payload : undefined,
  174. sourcePath: record.sourcePath,
  175. line: record.line,
  176. };
  177. }
  178. function readSessions(db: DatabaseSync): DbSessionRecord[] {
  179. const rows = db
  180. .prepare(
  181. `
  182. select id, project_id, title, directory, time_created, time_updated
  183. from session
  184. order by time_updated desc
  185. limit 200
  186. `,
  187. )
  188. .all() as Record<string, unknown>[];
  189. return rows.map((row) => ({
  190. id: String(row.id),
  191. projectId: String(row.project_id),
  192. title: String(row.title ?? ""),
  193. directory: String(row.directory ?? ""),
  194. createdAt: millisToIso(row.time_created),
  195. updatedAt: millisToIso(row.time_updated),
  196. }));
  197. }
  198. function readMessages(db: DatabaseSync): DbMessageRecord[] {
  199. const rows = db
  200. .prepare(
  201. `
  202. select id, session_id, time_created, time_updated, data
  203. from message
  204. order by time_created asc, rowid asc
  205. limit 1000
  206. `,
  207. )
  208. .all() as Record<string, unknown>[];
  209. return rows.map((row) => {
  210. const data = parseData(row.data);
  211. return {
  212. id: String(row.id),
  213. sessionId: String(row.session_id),
  214. role: stringValue(data.role),
  215. createdAt: millisToIso(row.time_created),
  216. updatedAt: millisToIso(row.time_updated),
  217. data,
  218. };
  219. });
  220. }
  221. function readParts(db: DatabaseSync): DbPartRecord[] {
  222. const rows = db
  223. .prepare(
  224. `
  225. select id, message_id, session_id, time_created, time_updated, data
  226. from part
  227. order by time_created asc, id asc
  228. limit 2000
  229. `,
  230. )
  231. .all() as Record<string, unknown>[];
  232. return rows.map((row) => {
  233. const data = parseData(row.data);
  234. return {
  235. id: String(row.id),
  236. messageId: String(row.message_id),
  237. sessionId: String(row.session_id),
  238. type: stringValue(data.type),
  239. createdAt: millisToIso(row.time_created),
  240. updatedAt: millisToIso(row.time_updated),
  241. data,
  242. };
  243. });
  244. }
  245. function parseData(value: unknown): Record<string, unknown> {
  246. if (typeof value !== "string") return {};
  247. try {
  248. const parsed = JSON.parse(value) as unknown;
  249. return isRecord(parsed) ? parsed : {};
  250. } catch {
  251. return {};
  252. }
  253. }
  254. function millisToIso(value: unknown): string | undefined {
  255. const millis = numberValue(value);
  256. return millis === undefined ? undefined : new Date(millis).toISOString();
  257. }
  258. export function isRecord(value: unknown): value is Record<string, unknown> {
  259. return value !== null && typeof value === "object" && !Array.isArray(value);
  260. }
  261. export function stringValue(value: unknown): string | undefined {
  262. return typeof value === "string" && value.length > 0 ? value : undefined;
  263. }
  264. export function numberValue(value: unknown): number | undefined {
  265. return typeof value === "number" && Number.isFinite(value) ? value : undefined;
  266. }