@wwwfz/dsh-agent-bridge 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/projects.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createReadStream } from 'node:fs';
2
+ import { createHash } from 'node:crypto';
2
3
  import { open, readdir, realpath, stat } from 'node:fs/promises';
3
4
  import path from 'node:path';
4
5
  import { fileURLToPath } from 'node:url';
@@ -16,6 +17,8 @@ const jsonlFile = /\.jsonl$/i;
16
17
  const compressedCodexFile = /\.jsonl\.zst$/i;
17
18
  const hasZstd = typeof zlib.createZstdDecompress === 'function';
18
19
  const conversationLimits = { messages: 600, characters: 160_000, messageLength: 24_000 };
20
+ const traceItemLimit = 600;
21
+ const traceTextLimit = 8_000;
19
22
 
20
23
  const agentLabels = {
21
24
  codex: 'Codex', claude: 'Claude Code', opencode: 'OpenCode', workbuddy: 'WorkBuddy',
@@ -543,16 +546,39 @@ function messageText(text) {
543
546
  return typeof text === 'string' ? stripRuntimeWrapper(text).trim() : '';
544
547
  }
545
548
 
546
- function appendMessage(result, role, text, timestamp) {
547
- if (role !== 'user' && role !== 'assistant') return;
549
+ function markSourcePartial(result) {
550
+ result.sourcePartial = true;
551
+ result.truncated = true;
552
+ }
553
+
554
+ function appendMessage(result, role, text, timestamp, { estimatedTime = false } = {}) {
555
+ if (role !== 'user' && role !== 'assistant') return false;
548
556
  const value = messageText(text);
549
- if (!value) return;
557
+ if (!value) return false;
550
558
  for (const match of value.matchAll(/<skill>\s*<name>([^<]+)<\/name>/gi)) addSkill(result, match[1]);
551
- if (value.startsWith('<skill>')) return;
559
+ if (value.startsWith('<skill>')) return false;
552
560
  const { limits } = result;
553
561
  if (limits) {
554
562
  const bounded = value.slice(0, limits.messageLength).replace(/[\uD800-\uDBFF]$/, '');
555
- result.messages.push({ role, text: bounded, agent: result.agent, time: dateMillis(timestamp) });
563
+ const time = dateMillis(timestamp);
564
+ const stats = result.readStats;
565
+ if (role === 'user') stats.userMessages++;
566
+ else stats.assistantMessages++;
567
+ if (time > 0 && !estimatedTime) {
568
+ stats.timedMessages++;
569
+ stats.firstAt = Math.min(stats.firstAt ?? time, time);
570
+ stats.lastAt = Math.max(stats.lastAt ?? time, time);
571
+ }
572
+ const entry = { role, text: bounded, agent: result.agent, time };
573
+ if (result.trace) {
574
+ const ref = ++result.messageSeq;
575
+ if (role === 'user') {
576
+ result.turn++;
577
+ result.turnRef = ref;
578
+ }
579
+ entry.turnRef = result.turnRef;
580
+ }
581
+ result.messages.push(entry);
556
582
  result.characters += bounded.length;
557
583
  if (value.length > bounded.length) result.truncated = true;
558
584
  while (result.messages.length > limits.messages || result.characters > limits.characters) {
@@ -562,15 +588,88 @@ function appendMessage(result, role, text, timestamp) {
562
588
  result.truncated = true;
563
589
  }
564
590
  } else {
565
- result.messages.push({ role, text: value.slice(0, maxMessageLength), agent: result.agent });
591
+ const entry = { role, text: value.slice(0, maxMessageLength), agent: result.agent };
592
+ result.messages.push(entry);
566
593
  if (result.messages.length > maxMessages) result.messages.shift();
567
594
  }
595
+ return true;
568
596
  }
569
597
 
570
598
  function addSkill(result, name) {
571
599
  if (typeof name === 'string' && /^[\p{L}\p{N}_:.\/-]{1,140}$/u.test(name.trim())) result.usedSkills.add(name.trim());
572
600
  }
573
601
 
602
+ function traceValue(value) {
603
+ if (typeof value === 'string') return value;
604
+ if (value === undefined || value === null) return '';
605
+ try { return JSON.stringify(value); } catch { return ''; }
606
+ }
607
+
608
+ function cleanTraceText(value) {
609
+ return traceValue(value).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, ' ').trim();
610
+ }
611
+
612
+ function addTrace(result, item) {
613
+ if (!result.trace) return undefined;
614
+ const text = cleanTraceText(item.text);
615
+ const bounded = text.slice(0, traceTextLimit).replace(/[\uD800-\uDBFF]$/, '');
616
+ const entry = {
617
+ id: `${item.kind}-${item.callId ?? item.id ?? result.traceOrder}`,
618
+ order: result.traceOrder++,
619
+ kind: item.kind,
620
+ ...(item.name ? { name: item.name } : {}),
621
+ ...(item.callId ? { callId: item.callId } : {}),
622
+ text: bounded,
623
+ status: item.status,
624
+ ...(text.length > bounded.length ? { truncated: true } : {}),
625
+ ...(item.time ? { time: item.time } : {}),
626
+ turnRef: result.turnRef,
627
+ turn: result.turn,
628
+ };
629
+ const key = entry.kind === 'summary'
630
+ ? `summary\0${entry.id}`
631
+ : `${entry.kind}\0${entry.callId ?? entry.id}`;
632
+ if (result.traceKeys.has(key)) return entry;
633
+ result.traceKeys.add(key);
634
+ result.trace.push(entry);
635
+ while (result.trace.length > traceItemLimit) {
636
+ result.truncated = true;
637
+ const removed = result.trace.shift();
638
+ result.traceKeys.delete(removed.kind === 'summary'
639
+ ? `summary\0${removed.id}` : `${removed.kind}\0${removed.callId ?? removed.id}`);
640
+ }
641
+ return entry;
642
+ }
643
+
644
+ function traceCallId(value) {
645
+ if (typeof value !== 'string' || !value) return undefined;
646
+ if (value.length <= 200) return value;
647
+ return `${value.slice(0, 120)}…${createHash('sha256').update(value).digest('hex')}`;
648
+ }
649
+
650
+ function addSummary(result, text, time, id) {
651
+ const value = cleanTraceText(text);
652
+ if (!value) return;
653
+ addTrace(result, { kind: 'summary', text: value, status: 'ok', time: dateMillis(time), id });
654
+ }
655
+
656
+ function addToolCall(result, name, callId, input, time) {
657
+ if (typeof name !== 'string' || !name.trim()) return;
658
+ addTrace(result, {
659
+ kind: 'tool_call', name: name.trim().slice(0, 120),
660
+ callId: traceCallId(callId),
661
+ text: cleanTraceText(input), status: 'pending', time: dateMillis(time),
662
+ });
663
+ }
664
+
665
+ function addToolResult(result, callId, output, failed) {
666
+ if (!result.trace || typeof callId !== 'string' || !callId) return;
667
+ addTrace(result, {
668
+ kind: 'tool_result', callId: traceCallId(callId), text: cleanTraceText(output),
669
+ status: failed === true ? 'error' : 'ok',
670
+ });
671
+ }
672
+
574
673
  function skillPaths(result, value) {
575
674
  if (typeof value !== 'string') return;
576
675
  for (const match of value.replace(/[\\/]+/g, '/').matchAll(/(?:^|\/)([\p{L}\p{N}_:.-]+)\/SKILL\.md\b/giu)) addSkill(result, match[1]);
@@ -594,8 +693,26 @@ function textBlocks(content, result) {
594
693
  for (const block of content) {
595
694
  if (typeof block === 'string') texts.push(block);
596
695
  if (['text', 'input_text', 'output_text'].includes(block?.type) && typeof block.text === 'string') texts.push(block.text);
597
- if (result && block?.type === 'tool_use') readTool(result, block.name, block.input);
598
- if (result && block?.type === 'tool') readTool(result, block.tool ?? block.name, block.state?.input ?? block.input ?? block.args);
696
+ if (result && block?.type === 'tool_use') {
697
+ readTool(result, block.name, block.input);
698
+ addToolCall(result, block.name, block.id, block.input);
699
+ }
700
+ if (result && block?.type === 'tool_result') {
701
+ const value = Array.isArray(block.content)
702
+ ? block.content.filter(part => part?.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n')
703
+ : block.content;
704
+ addToolResult(result, block.tool_use_id, value, block.is_error === true);
705
+ }
706
+ if (result && block?.type === 'tool') {
707
+ const input = block.state?.input ?? block.input ?? block.args;
708
+ readTool(result, block.tool ?? block.name, input);
709
+ const callId = block.callID ?? block.callId ?? block.id;
710
+ addToolCall(result, block.tool ?? block.name, callId, input);
711
+ const state = block.state ?? {};
712
+ if (state.status === 'completed' || state.status === 'error') {
713
+ addToolResult(result, callId, state.output ?? state.result ?? state.error, state.status === 'error');
714
+ }
715
+ }
599
716
  }
600
717
  // A Codex user message can contain several independent input_text blocks.
601
718
  // Filter each one so an internal block never hides a neighboring prompt.
@@ -631,7 +748,7 @@ async function readGeminiHistory(descriptor, cwd, config, result) {
631
748
  const marker = await scopedFile(path.resolve(path.dirname(file), '..', '.project_root'), base);
632
749
  if (!marker || !await sameDirectory((await prefix(marker, 32 * 1024)).text.trim(), cwd)) continue;
633
750
  const { text, truncated } = await prefix(file, maxTranscriptBytes);
634
- if (truncated) result.truncated = true;
751
+ if (truncated) markSourcePartial(result);
635
752
  const messages = json(text)?.messages ?? rowsFrom(text, truncated);
636
753
  if (!Array.isArray(messages)) continue;
637
754
  for (const row of messages) {
@@ -697,13 +814,15 @@ async function readCopilotHistory(descriptor, cwd, config, result) {
697
814
  const marker = json((await prefix(workspace, 32 * 1024)).text);
698
815
  if (!await sameDirectory(localDirectory(marker?.folder), cwd)) continue;
699
816
  const { text, truncated } = await prefix(file, maxTranscriptBytes);
700
- if (truncated) result.truncated = true;
817
+ if (truncated) markSourcePartial(result);
701
818
  const requests = copilotRequests(text, truncated);
702
819
  for (const request of result.limits ? requests : requests.slice(-maxMessages)) {
703
820
  appendMessage(result, 'user', request?.message?.text, request?.timestamp);
704
821
  const response = Array.isArray(request?.response) ? request.response : [];
705
- appendMessage(result, 'assistant', response.filter(item => !item?.kind || item.kind === 'markdownContent')
706
- .map(item => item?.value?.value ?? item?.value ?? '').filter(value => typeof value === 'string').join(''), request?.timestamp);
822
+ const answer = response.filter(item => !item?.kind || item.kind === 'markdownContent')
823
+ .map(item => item?.value?.value ?? item?.value ?? '').filter(value => typeof value === 'string').join('');
824
+ // Copilot stores the request time. Use it for transcript order only.
825
+ appendMessage(result, 'assistant', answer, request?.timestamp, { estimatedTime: true });
707
826
  for (const item of response) {
708
827
  if (item?.kind === 'toolInvocationSerialized') readTool(result, item.toolId, item.parameters);
709
828
  }
@@ -776,21 +895,62 @@ async function* compressedRows(file) {
776
895
 
777
896
  function readCodexRow(result, row) {
778
897
  if (row === null || row.type === 'compacted' || row.isCompactSummary) {
779
- if (result.limits) result.truncated = true;
898
+ if (result.limits) markSourcePartial(result);
780
899
  return;
781
900
  }
782
- if (row.isSidechain || row.isMeta || row.type !== 'response_item') return;
901
+ if (row.isSidechain || row.isMeta) return;
783
902
  const payload = row.payload;
784
- if (payload?.type === 'message') appendMessage(result, payload.role, textBlocks(payload.content, result), row.timestamp);
785
- if (payload?.type === 'function_call') readTool(result, payload.name, payload.arguments);
786
- if (payload?.type === 'custom_tool_call') readTool(result, payload.name, payload.input);
903
+ if (row.type === 'event_msg' && payload?.type === 'token_count' && result.readStats) {
904
+ // Codex repeats cumulative snapshots. The latest recorded total already
905
+ // includes earlier turns, and may be available even when only a tail was read.
906
+ const usage = payload.info?.total_token_usage;
907
+ if (Number.isSafeInteger(usage?.total_tokens) && usage.total_tokens >= 0) {
908
+ const tokens = { total: usage.total_tokens };
909
+ for (const name of ['input', 'output']) {
910
+ const value = usage[`${name}_tokens`];
911
+ if (Number.isSafeInteger(value) && value >= 0 && value <= tokens.total) tokens[name] = value;
912
+ }
913
+ result.readStats.tokens = tokens;
914
+ }
915
+ return;
916
+ }
917
+ if (row.type !== 'response_item') return;
918
+ if (payload?.type === 'message') {
919
+ appendMessage(result, payload.role, textBlocks(payload.content, result), row.timestamp);
920
+ return;
921
+ }
922
+ if (payload?.type === 'reasoning') {
923
+ // Only the visible summary is retained; encrypted reasoning has no text.
924
+ const summary = Array.isArray(payload.summary) ? payload.summary : [];
925
+ const text = summary.filter(item => item?.type === 'summary_text' && typeof item.text === 'string')
926
+ .map(item => item.text).join('\n\n');
927
+ if (text) addSummary(result, text, row.timestamp, payload.id);
928
+ return;
929
+ }
930
+ if (payload?.type === 'function_call' || payload?.type === 'custom_tool_call') {
931
+ readTool(result, payload.name, payload.arguments ?? payload.input);
932
+ addToolCall(result, payload.name, payload.call_id ?? payload.id, payload.arguments ?? payload.input, row.timestamp);
933
+ return;
934
+ }
935
+ if (payload?.type === 'function_call_output' || payload?.type === 'custom_tool_call_output') {
936
+ const output = payload.output ?? payload.content;
937
+ const text = Array.isArray(output)
938
+ ? output.filter(item => item?.type === 'input_text' && typeof item.text === 'string').map(item => item.text).join('\n')
939
+ : output;
940
+ const value = typeof text === 'string' ? text : '';
941
+ addToolResult(result, payload.call_id, value, payload.status === 'failed'
942
+ || /^(?:exit code: [1-9]|process exited with code [1-9])/im.test(value));
943
+ }
787
944
  }
788
945
 
789
946
  async function readCompressedCodex(file, cwd, result) {
790
947
  // Use a separate accumulator so a damaged file never contributes an
791
948
  // incomplete history or discards previously read project context.
792
949
  const local = { messages: [], usedSkills: new Set(), limits: result.limits,
793
- characters: 0, truncated: false, agent: result.agent };
950
+ characters: 0, truncated: false, agent: result.agent,
951
+ trace: result.trace ? [] : undefined, traceKeys: result.trace ? new Set() : undefined,
952
+ traceOrder: 0, messageSeq: 0, turn: 0, turnRef: undefined,
953
+ readStats: result.readStats && { userMessages: 0, assistantMessages: 0, timedMessages: 0 } };
794
954
  let validated = false;
795
955
  for await (const row of compressedRows(file)) {
796
956
  if (!validated) {
@@ -802,7 +962,9 @@ async function readCompressedCodex(file, cwd, result) {
802
962
  readCodexRow(local, row);
803
963
  }
804
964
  if (result.limits) {
965
+ const trace = result.trace ? [...result.trace, ...local.trace] : undefined;
805
966
  Object.assign(result, local);
967
+ if (result.trace) result.trace = trace;
806
968
  } else {
807
969
  result.messages.push(...local.messages);
808
970
  if (result.messages.length > maxMessages) result.messages.splice(0, result.messages.length - maxMessages);
@@ -855,9 +1017,9 @@ async function readJsonlHistory(descriptor, cwd, config, result) {
855
1017
 
856
1018
  // Active transcripts may have a torn last row. Large transcripts keep the latest bounded tail.
857
1019
  const { history } = transcript;
858
- if (transcript.truncated) result.truncated = true;
1020
+ if (transcript.truncated) markSourcePartial(result);
859
1021
  for (const row of history) {
860
- if (result.limits && row.isCompactSummary) result.truncated = true;
1022
+ if (result.limits && row.isCompactSummary) markSourcePartial(result);
861
1023
  if (row.isSidechain || row.isMeta || row.isCompactSummary) continue;
862
1024
  if (descriptor.kind === 'codex') {
863
1025
  readCodexRow(result, row);
@@ -932,7 +1094,7 @@ async function readDatabaseHistory(descriptor, cwd, config, result) {
932
1094
  }
933
1095
  for (const row of snapshot.legacy ?? []) appendMessage(result, row.role, textBlocks(row.parts, result), row.time);
934
1096
  if (result.limits && (snapshot.messages ?? snapshot.projection ?? snapshot.legacy ?? []).length > result.limits.messages) {
935
- result.truncated = true;
1097
+ markSourcePartial(result);
936
1098
  }
937
1099
  }
938
1100
 
@@ -946,8 +1108,30 @@ async function readHistory(archive, cwd, config, result) {
946
1108
  }
947
1109
 
948
1110
  export async function readConversationHistory(archive, cwd, config) {
949
- const result = { messages: [], usedSkills: new Set(), limits: conversationLimits, characters: 0, truncated: false };
1111
+ const result = {
1112
+ messages: [], usedSkills: new Set(), limits: conversationLimits, characters: 0, truncated: false,
1113
+ trace: [], traceKeys: new Set(), traceOrder: 0, messageSeq: 0, turn: 0, turnRef: undefined,
1114
+ readStats: { userMessages: 0, assistantMessages: 0, timedMessages: 0 },
1115
+ };
950
1116
  await readHistory(archive, cwd, config, result);
1117
+ const calls = new Map();
1118
+ for (const item of result.trace) {
1119
+ if (item.kind !== 'tool_call') continue;
1120
+ item.status = 'missing';
1121
+ if (item.callId) calls.set(item.callId, item);
1122
+ }
1123
+ for (const item of result.trace) {
1124
+ if (item.kind !== 'tool_result') continue;
1125
+ const call = calls.get(item.callId);
1126
+ item.turnRef = call?.turnRef;
1127
+ if (!call) {
1128
+ result.truncated = true;
1129
+ continue;
1130
+ }
1131
+ call.status = item.status;
1132
+ item.name = call.name;
1133
+ item.turn = call.turn;
1134
+ }
951
1135
  if (result.messages[0]?.role === 'assistant' && result.removedQuestion) {
952
1136
  // The latest retained replies may belong to a long turn whose question
953
1137
  // fell out of the sliding budget. Keep that real question with its replies.
@@ -958,7 +1142,32 @@ export async function readConversationHistory(archive, cwd, config) {
958
1142
  result.messages.unshift(question);
959
1143
  }
960
1144
  const start = result.messages.findIndex(message => message.role === 'user');
961
- return { messages: start < 0 ? [] : result.messages.slice(start), truncated: result.truncated || start > 0 };
1145
+ const retained = start < 0 ? [] : result.messages.slice(start);
1146
+ // The last displayed reply in each source turn is its disclosure anchor.
1147
+ // A turn without a reply is anchored to its own user message.
1148
+ const indexOf = new Map(retained.map((message, index) => [message.turnRef, index]));
1149
+ const trace = result.trace
1150
+ .filter(item => item.turnRef !== undefined && indexOf.has(item.turnRef))
1151
+ .map(({ turnRef, ...item }) => ({ ...item, messageIndex: indexOf.get(turnRef) }))
1152
+ .sort((a, b) => a.turn - b.turn || a.order - b.order);
1153
+ const byMessage = new Map()
1154
+ for (const item of trace) {
1155
+ if (!Number.isInteger(item.messageIndex)) continue;
1156
+ byMessage.set(item.messageIndex, [...(byMessage.get(item.messageIndex) ?? []), item.id]);
1157
+ }
1158
+ const { userMessages, assistantMessages, timedMessages, firstAt, lastAt, tokens } = result.readStats;
1159
+ const sourceStats = {
1160
+ userMessages, assistantMessages, importedMessages: retained.length, partial: result.sourcePartial === true,
1161
+ ...(timedMessages >= 2 && timedMessages === userMessages + assistantMessages ? { elapsedMs: lastAt - firstAt } : {}),
1162
+ ...(tokens ? { tokens } : {}),
1163
+ };
1164
+ return {
1165
+ messages: retained.map(({ turnRef, ...message }, index) => ({ ...message, ...(byMessage.has(index) ? { traceIds: byMessage.get(index) } : {}) })),
1166
+ trace,
1167
+ sourceStats,
1168
+ usedSkills: [...result.usedSkills].sort(),
1169
+ truncated: result.truncated || start > 0,
1170
+ };
962
1171
  }
963
1172
 
964
1173
  export async function readProjectHistory(project, config) {
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import path from 'node:path'
3
+ import { saveSessionTrace } from './session-trace.js'
3
4
 
4
5
  export function nativeSessionServices(ctx) {
5
6
  const sessions = ctx.get?.('sessions')
@@ -85,6 +86,19 @@ export async function saveNativeSession(services, record, cwd) {
85
86
  await handle.close()
86
87
  }
87
88
  }
89
+ // Save the reviewed source snapshot before attaching the new DSH session.
90
+ const hasTrace = Array.isArray(record.trace) && record.trace.length > 0
91
+ if (!record.traceStored && record.config && (hasTrace || record.sourceStats)) {
92
+ try {
93
+ const saved = await saveSessionTrace(record.config, record.sessionId, record.trace, record.sourceStats)
94
+ record.traceStored = saved.saved === true
95
+ } catch {
96
+ throw Object.assign(
97
+ new Error('会话历史已写入,但来源记录暂时无法保存。可重试。'),
98
+ { status: 503 },
99
+ )
100
+ }
101
+ }
88
102
  if (!workspace.sessionIds.includes(record.sessionId)) {
89
103
  projectionCache?.coldSnapshot(record.stored.header, 0, record.stored.events)
90
104
  await workspace.attachSession(record.sessionId)
@@ -0,0 +1,121 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { mkdir, open, readFile, rename, rm, stat } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+
5
+ const sessionIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
6
+ const kinds = new Set(['summary', 'tool_call', 'tool_result'])
7
+ const states = new Set(['ok', 'error', 'missing', 'pending', 'truncated'])
8
+ const maxTraceItems = 200
9
+ const maxTraceBytes = 96 * 1024
10
+
11
+ export function traceDirectory(config) {
12
+ const base = path.dirname(config.configFile ?? path.join(config.home ?? '.', 'agent-bridge.json'))
13
+ return path.join(base, 'agent-bridge-traces')
14
+ }
15
+
16
+ export function isSessionId(value) {
17
+ return typeof value === 'string' && sessionIdPattern.test(value)
18
+ }
19
+
20
+ function clean(value, limit) {
21
+ return String(value ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, ' ').slice(0, limit)
22
+ }
23
+
24
+ export function normalizeTrace(trace) {
25
+ if (!Array.isArray(trace)) return []
26
+ const items = []
27
+ for (const item of trace.slice(0, maxTraceItems)) {
28
+ if (!item || !kinds.has(item.kind)) continue
29
+ items.push({
30
+ id: clean(item.id, 200),
31
+ kind: item.kind,
32
+ ...(item.name ? { name: clean(item.name, 120) } : {}),
33
+ ...(item.callId ? { callId: clean(item.callId, 200) } : {}),
34
+ text: clean(item.text, item.kind === 'tool_result' ? 4096 : 8192),
35
+ status: states.has(item.status) ? item.status : 'ok',
36
+ ...(item.truncated === true ? { truncated: true } : {}),
37
+ ...(Number.isFinite(item.time) && item.time > 0 ? { time: item.time } : {}),
38
+ ...(Number.isInteger(item.messageIndex) && item.messageIndex >= 0 ? { messageIndex: item.messageIndex } : {}),
39
+ ...(Number.isSafeInteger(item.turn) && item.turn > 0 ? { turn: item.turn } : {}),
40
+ })
41
+ }
42
+ return items
43
+ }
44
+
45
+ export function countTrace(trace) {
46
+ const counts = { summary: 0, toolCall: 0, toolResult: 0, failed: 0, missing: 0 }
47
+ for (const item of trace) {
48
+ if (item.kind === 'summary') counts.summary++
49
+ else if (item.kind === 'tool_call') {
50
+ counts.toolCall++
51
+ if (item.status === 'error') counts.failed++
52
+ if (item.status === 'missing') counts.missing++
53
+ } else if (item.kind === 'tool_result') counts.toolResult++
54
+ }
55
+ return counts
56
+ }
57
+
58
+ function normalizeSourceStats(value) {
59
+ if (!value || typeof value !== 'object') return undefined
60
+ const { userMessages, assistantMessages, importedMessages, partial, elapsedMs, tokens } = value
61
+ const nonNegative = number => Number.isSafeInteger(number) && number >= 0
62
+ if (![userMessages, assistantMessages, importedMessages].every(nonNegative)
63
+ || userMessages === 0 || importedMessages === 0 || !Number.isSafeInteger(userMessages + assistantMessages)
64
+ || importedMessages > userMessages + assistantMessages) return undefined
65
+ const stats = { userMessages, assistantMessages, importedMessages, partial: partial === true }
66
+ if (nonNegative(elapsedMs)) stats.elapsedMs = elapsedMs
67
+ if (nonNegative(tokens?.total)) {
68
+ stats.tokens = { total: tokens.total }
69
+ for (const name of ['input', 'output']) {
70
+ if (nonNegative(tokens[name]) && tokens[name] <= tokens.total) stats.tokens[name] = tokens[name]
71
+ }
72
+ }
73
+ return stats
74
+ }
75
+
76
+ function traceFile(config, sessionId) {
77
+ if (!isSessionId(sessionId)) throw Object.assign(new Error('会话标识无效。'), { status: 400 })
78
+ return path.join(traceDirectory(config), `${sessionId.toLowerCase()}.json`)
79
+ }
80
+
81
+ export async function saveSessionTrace(config, sessionId, trace, sourceStats) {
82
+ const items = normalizeTrace(trace)
83
+ const stats = normalizeSourceStats(sourceStats)
84
+ if (!items.length && !stats) return { saved: false, items: 0 }
85
+ const target = traceFile(config, sessionId)
86
+ const body = `${JSON.stringify({
87
+ version: 1, sessionId: sessionId.toLowerCase(), savedAt: new Date().toISOString(), trace: items,
88
+ ...(stats ? { sourceStats: stats } : {}),
89
+ })}\n`
90
+ if (Buffer.byteLength(body) > maxTraceBytes) throw new RangeError('来源记录超过存储上限。')
91
+ const directory = traceDirectory(config)
92
+ await mkdir(directory, { recursive: true })
93
+ const temporary = path.join(directory, `.${path.basename(target)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`)
94
+ const handle = await open(temporary, 'wx', 0o600)
95
+ try {
96
+ try {
97
+ await handle.writeFile(body, 'utf8')
98
+ await handle.sync()
99
+ } finally {
100
+ await handle.close()
101
+ }
102
+ await rename(temporary, target)
103
+ } catch (error) {
104
+ await rm(temporary, { force: true })
105
+ throw error
106
+ }
107
+ return { saved: true, items: items.length, file: target }
108
+ }
109
+
110
+ export async function readSessionTrace(config, sessionId) {
111
+ const file = traceFile(config, sessionId)
112
+ let info
113
+ try { info = await stat(file) } catch { return undefined }
114
+ if (!info.isFile() || info.size > maxTraceBytes) return undefined
115
+ let parsed
116
+ try { parsed = JSON.parse(await readFile(file, 'utf8')) } catch { return undefined }
117
+ if (parsed?.version !== 1 || parsed.sessionId !== sessionId.toLowerCase() || !Array.isArray(parsed.trace)) return undefined
118
+ const stats = normalizeSourceStats(parsed.sourceStats)
119
+ return { sessionId: parsed.sessionId, savedAt: parsed.savedAt, trace: normalizeTrace(parsed.trace),
120
+ ...(stats ? { sourceStats: stats } : {}) }
121
+ }