pi-web-ui 0.100.0 → 0.102.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/CHANGELOG.md +53 -1
- package/README.md +46 -44
- package/README.zh-CN.md +41 -39
- package/bin/pi-web-ui.mjs +17 -19
- package/dist/server/agent-formatters.js +191 -0
- package/dist/server/agent-service-daemon.js +1266 -0
- package/dist/server/agent-service.js +9884 -12815
- package/dist/server/approval-default-rules.js +158 -0
- package/dist/server/approval-rules.js +41 -167
- package/dist/server/ask-user-question-tool.js +104 -0
- package/dist/server/attachment-store.js +38 -1
- package/dist/server/bash-tool.js +83 -0
- package/dist/server/browser-page-tool.js +207 -0
- package/dist/server/client-id-utils.js +51 -0
- package/dist/server/client-state.js +38 -2
- package/dist/server/compaction-markers.js +34 -1
- package/dist/server/context-budget-runner.js +43 -0
- package/dist/server/dangling-tools.js +18 -5
- package/dist/server/delegate-mode.js +1 -0
- package/dist/server/dispatch-domain-handlers.js +631 -0
- package/dist/server/dispatch-plugin-handlers.js +300 -0
- package/dist/server/dsh/dsh-agent-service.js +30 -5
- package/dist/server/dsh/runtime/goal-rpc.mjs +5 -1
- package/dist/server/goal-evidence.js +9 -2
- package/dist/server/goal-service.js +1 -1
- package/dist/server/hashline-engine.js +1 -1
- package/dist/server/index.js +191 -969
- package/dist/server/left-panel-running.js +115 -0
- package/dist/server/lsp-tool.js +40 -12
- package/dist/server/markers-list-tool.js +34 -0
- package/dist/server/market-service.js +277 -0
- package/dist/server/mcp-bridge.js +137 -30
- package/dist/server/mcp-hot-reload.js +84 -27
- package/dist/server/mcp-manager.js +215 -0
- package/dist/server/message-entry-resolver.js +32 -0
- package/dist/server/orphan-manager.js +44 -0
- package/dist/server/persona-chain.js +63 -0
- package/dist/server/plan-mode.js +2 -0
- package/dist/server/plan-update-tool.js +96 -0
- package/dist/server/plugin-api-catalog.js +20 -0
- package/dist/server/plugin-facilities.js +13 -3
- package/dist/server/plugin-installer.js +6 -1
- package/dist/server/plugin-ui-slots.js +39 -0
- package/dist/server/plugins.js +72 -38
- package/dist/server/preset-fields.js +35 -0
- package/dist/server/preset-share.js +9 -0
- package/dist/server/process-utils.js +30 -0
- package/dist/server/prompt-assembler.js +80 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/scm-commitmsg.js +74 -0
- package/dist/server/serialize.js +97 -7
- package/dist/server/session-branch.js +367 -0
- package/dist/server/session-parser.js +235 -0
- package/dist/server/session-search.js +158 -0
- package/dist/server/settings-service.js +28 -1
- package/dist/server/skill-content-filler.js +33 -0
- package/dist/server/subagent-handoff.js +18 -0
- package/dist/server/subagent-helpers.js +88 -0
- package/dist/server/terminals.js +155 -58
- package/dist/server/tool-guards.js +527 -0
- package/dist/server/tool-host-factories.js +217 -0
- package/dist/server/tool-manager.js +30 -5
- package/dist/server/wait-subscription-scan.js +46 -1
- package/dist/server/workspace-snapshot.js +18 -0
- package/extensions/webui.ts +90 -24
- package/package.json +1 -1
- package/plugin-sdk/README.md +17 -0
- package/plugin-sdk/index.d.ts +17 -0
- package/plugin-sdk/index.mjs +5 -0
- package/plugins/catalog.json +20 -0
- package/themes/aetheris.css +3 -1
- package/themes/translucent.css +8 -1
- package/themes/transparent.css +9 -1
- package/themes/zhupi-dark.css +3 -14
- package/themes/zhupi.css +2 -16
- package/web/dist/assets/{TerminalPanel-C3I1Mc-C.js → TerminalPanel-CYGOzbPT.js} +1 -1
- package/web/dist/assets/index-CP71PHb6.js +680 -0
- package/web/dist/assets/index-ytRwL6j0.css +1 -0
- package/web/dist/index.html +2 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-B-E2EM_0.css +0 -1
- package/web/dist/assets/index-BYumAaGi.js +0 -379
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session branch evaluation, leaf calibration, and transcript topological reordering.
|
|
3
|
+
*
|
|
4
|
+
* Background (issue #567):
|
|
5
|
+
* When multiple devices access the same session, or when extensions append metadata
|
|
6
|
+
* (e.g. type: "custom" such as plannotator entries) pointing to an older ancestor node,
|
|
7
|
+
* the appended entries appear at the physical tail of the JSONL file.
|
|
8
|
+
*
|
|
9
|
+
* In the SDK's SessionManager._buildIndex():
|
|
10
|
+
* for (const entry of this.fileEntries) {
|
|
11
|
+
* if (entry.type === "session") continue;
|
|
12
|
+
* this.byId.set(entry.id, entry);
|
|
13
|
+
* this.leafId = entry.id; // file tail becomes the active leaf!
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* If metadata was appended to an older branch (e.g. node 292 while the main branch
|
|
17
|
+
* continued to 557), reopening the session or restarting the backend will restore
|
|
18
|
+
* the older branch (292), making later task history (293..557) invisible even though
|
|
19
|
+
* it is still safely stored in the JSONL file.
|
|
20
|
+
*
|
|
21
|
+
* This module provides:
|
|
22
|
+
* 1. selectBestSessionLeaf: Evaluates branch candidates by message count, freshness,
|
|
23
|
+
* and depth, detecting metadata-only hijacking or stale branch reversion.
|
|
24
|
+
* 2. calibrateSessionLeaf: In-memory leaf calibration for any SessionManager instance.
|
|
25
|
+
* 3. reorderEntriesForMainBranch: Topological reordering of session entries to ensure
|
|
26
|
+
* the active main branch leaf resides at the physical tail of the transcript file
|
|
27
|
+
* without losing or modifying any custom/metadata entries.
|
|
28
|
+
*/
|
|
29
|
+
function parseEntryTimestamp(ts) {
|
|
30
|
+
if (typeof ts === "string") {
|
|
31
|
+
const parsed = Date.parse(ts);
|
|
32
|
+
if (!Number.isNaN(parsed))
|
|
33
|
+
return parsed;
|
|
34
|
+
}
|
|
35
|
+
else if (typeof ts === "number" && !Number.isNaN(ts)) {
|
|
36
|
+
return ts;
|
|
37
|
+
}
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Identify all branch leaves and compute branch metrics (from root to leaf).
|
|
42
|
+
*/
|
|
43
|
+
export function findBranchCandidates(entries) {
|
|
44
|
+
const validEntries = [];
|
|
45
|
+
const byId = new Map();
|
|
46
|
+
const childCount = new Map();
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
if (!entry || typeof entry.id !== "string" || !entry.id)
|
|
49
|
+
continue;
|
|
50
|
+
if (entry.type === "session")
|
|
51
|
+
continue;
|
|
52
|
+
validEntries.push(entry);
|
|
53
|
+
byId.set(entry.id, entry);
|
|
54
|
+
}
|
|
55
|
+
for (const entry of validEntries) {
|
|
56
|
+
const pid = typeof entry.parentId === "string" ? entry.parentId : null;
|
|
57
|
+
if (pid && byId.has(pid)) {
|
|
58
|
+
childCount.set(pid, (childCount.get(pid) ?? 0) + 1);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const leaves = [];
|
|
62
|
+
for (const entry of validEntries) {
|
|
63
|
+
const id = entry.id;
|
|
64
|
+
if ((childCount.get(id) ?? 0) === 0) {
|
|
65
|
+
leaves.push(entry);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (leaves.length === 0)
|
|
69
|
+
return [];
|
|
70
|
+
const candidates = [];
|
|
71
|
+
for (const leaf of leaves) {
|
|
72
|
+
const leafId = leaf.id;
|
|
73
|
+
const path = [];
|
|
74
|
+
const visited = new Set();
|
|
75
|
+
let cur = leafId;
|
|
76
|
+
while (cur !== null && byId.has(cur) && !visited.has(cur)) {
|
|
77
|
+
visited.add(cur);
|
|
78
|
+
const node = byId.get(cur);
|
|
79
|
+
path.push(node);
|
|
80
|
+
cur = typeof node.parentId === "string" ? node.parentId : null;
|
|
81
|
+
}
|
|
82
|
+
path.reverse(); // root -> ... -> leaf
|
|
83
|
+
let messageCount = 0;
|
|
84
|
+
let lastMessageTimestamp = 0;
|
|
85
|
+
for (const node of path) {
|
|
86
|
+
if (node.type === "message") {
|
|
87
|
+
messageCount += 1;
|
|
88
|
+
const ts = parseEntryTimestamp(node.timestamp);
|
|
89
|
+
if (ts > lastMessageTimestamp) {
|
|
90
|
+
lastMessageTimestamp = ts;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const tailTimestamp = parseEntryTimestamp(leaf.timestamp);
|
|
95
|
+
candidates.push({
|
|
96
|
+
leafId,
|
|
97
|
+
leafEntry: leaf,
|
|
98
|
+
totalEntries: path.length,
|
|
99
|
+
messageCount,
|
|
100
|
+
lastMessageTimestamp,
|
|
101
|
+
tailTimestamp,
|
|
102
|
+
pathIds: path.map((n) => n.id),
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
return candidates;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Find the lowest common ancestor (LCA) entry ID of two branches.
|
|
109
|
+
*/
|
|
110
|
+
function findLowestCommonAncestor(branchA, branchB) {
|
|
111
|
+
const setA = new Set(branchA.pathIds);
|
|
112
|
+
let lca = null;
|
|
113
|
+
for (const id of branchB.pathIds) {
|
|
114
|
+
if (setA.has(id)) {
|
|
115
|
+
lca = id;
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return lca;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Select the best branch leaf from all branch candidates.
|
|
125
|
+
*
|
|
126
|
+
* If multiple leaves exist, compares the currently selected leaf against the candidate
|
|
127
|
+
* pool. If the current leaf is on an abandoned metadata-only branch (e.g. extension
|
|
128
|
+
* wrote to an older node after a completed task) or significantly lags behind the main
|
|
129
|
+
* conversation in message count, selects the main branch leaf.
|
|
130
|
+
*/
|
|
131
|
+
export function selectBestSessionLeaf(entries, currentLeafId) {
|
|
132
|
+
const candidates = findBranchCandidates(entries);
|
|
133
|
+
if (candidates.length === 0)
|
|
134
|
+
return null;
|
|
135
|
+
if (candidates.length === 1) {
|
|
136
|
+
const single = candidates[0];
|
|
137
|
+
return {
|
|
138
|
+
bestLeafId: single.leafId,
|
|
139
|
+
currentLeafId: currentLeafId ?? null,
|
|
140
|
+
changed: currentLeafId !== undefined && currentLeafId !== null && currentLeafId !== single.leafId,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
// Sort candidates by preference:
|
|
144
|
+
// 1. Message count (descending)
|
|
145
|
+
// 2. Last message timestamp (descending)
|
|
146
|
+
// 3. Total entry depth (descending)
|
|
147
|
+
// 4. Leaf timestamp (descending)
|
|
148
|
+
const sorted = [...candidates].sort((a, b) => {
|
|
149
|
+
if (b.messageCount !== a.messageCount)
|
|
150
|
+
return b.messageCount - a.messageCount;
|
|
151
|
+
if (b.lastMessageTimestamp !== a.lastMessageTimestamp)
|
|
152
|
+
return b.lastMessageTimestamp - a.lastMessageTimestamp;
|
|
153
|
+
if (b.totalEntries !== a.totalEntries)
|
|
154
|
+
return b.totalEntries - a.totalEntries;
|
|
155
|
+
return b.tailTimestamp - a.tailTimestamp;
|
|
156
|
+
});
|
|
157
|
+
const bestCandidate = sorted[0];
|
|
158
|
+
if (!currentLeafId) {
|
|
159
|
+
return {
|
|
160
|
+
bestLeafId: bestCandidate.leafId,
|
|
161
|
+
currentLeafId: null,
|
|
162
|
+
changed: true,
|
|
163
|
+
reason: "No current leaf specified; selected deepest candidate",
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
const currentCandidate = candidates.find((c) => c.leafId === currentLeafId);
|
|
167
|
+
if (!currentCandidate) {
|
|
168
|
+
return {
|
|
169
|
+
bestLeafId: bestCandidate.leafId,
|
|
170
|
+
currentLeafId,
|
|
171
|
+
changed: true,
|
|
172
|
+
reason: `Current leaf "${currentLeafId}" not found in branch leaves`,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
if (currentCandidate.leafId === bestCandidate.leafId) {
|
|
176
|
+
return {
|
|
177
|
+
bestLeafId: bestCandidate.leafId,
|
|
178
|
+
currentLeafId,
|
|
179
|
+
changed: false,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
// Check if current leaf is a hijacked/stale branch:
|
|
183
|
+
const lca = findLowestCommonAncestor(currentCandidate, bestCandidate);
|
|
184
|
+
const lcaIndexCurrent = lca ? currentCandidate.pathIds.indexOf(lca) : -1;
|
|
185
|
+
const currentEntriesAfterLca = lcaIndexCurrent >= 0 ? currentCandidate.pathIds.slice(lcaIndexCurrent + 1) : [];
|
|
186
|
+
const byId = new Map();
|
|
187
|
+
for (const e of entries) {
|
|
188
|
+
if (e && typeof e.id === "string")
|
|
189
|
+
byId.set(e.id, e);
|
|
190
|
+
}
|
|
191
|
+
let currentMessagesAfterLca = 0;
|
|
192
|
+
for (const id of currentEntriesAfterLca) {
|
|
193
|
+
const node = byId.get(id);
|
|
194
|
+
if (node?.type === "message")
|
|
195
|
+
currentMessagesAfterLca += 1;
|
|
196
|
+
}
|
|
197
|
+
const lcaIndexBest = lca ? bestCandidate.pathIds.indexOf(lca) : -1;
|
|
198
|
+
const bestEntriesAfterLca = lcaIndexBest >= 0 ? bestCandidate.pathIds.slice(lcaIndexBest + 1) : [];
|
|
199
|
+
let bestMessagesAfterLca = 0;
|
|
200
|
+
for (const id of bestEntriesAfterLca) {
|
|
201
|
+
const node = byId.get(id);
|
|
202
|
+
if (node?.type === "message")
|
|
203
|
+
bestMessagesAfterLca += 1;
|
|
204
|
+
}
|
|
205
|
+
// Pattern A: Metadata-only branch hijacking (issue #567)
|
|
206
|
+
// Current branch has 0 messages after LCA (only custom / extension metadata),
|
|
207
|
+
// while best branch has real messages after LCA.
|
|
208
|
+
if (currentMessagesAfterLca === 0 && bestMessagesAfterLca > 0) {
|
|
209
|
+
return {
|
|
210
|
+
bestLeafId: bestCandidate.leafId,
|
|
211
|
+
currentLeafId,
|
|
212
|
+
changed: true,
|
|
213
|
+
reason: `Current branch has no messages after divergence (LCA=${lca}), while main branch has ${bestMessagesAfterLca} messages`,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
// Pattern B: Substantial message gap (stale branch restored after task completed elsewhere)
|
|
217
|
+
if (bestCandidate.messageCount > currentCandidate.messageCount) {
|
|
218
|
+
return {
|
|
219
|
+
bestLeafId: bestCandidate.leafId,
|
|
220
|
+
currentLeafId,
|
|
221
|
+
changed: true,
|
|
222
|
+
reason: `Main branch has ${bestCandidate.messageCount} messages vs current branch's ${currentCandidate.messageCount}`,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
// Otherwise, current branch has equal or valid intentional message history
|
|
226
|
+
return {
|
|
227
|
+
bestLeafId: currentCandidate.leafId,
|
|
228
|
+
currentLeafId,
|
|
229
|
+
changed: false,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Calibrate the active leaf of a SessionManager in memory.
|
|
234
|
+
*/
|
|
235
|
+
export function calibrateSessionLeaf(sessionManager) {
|
|
236
|
+
try {
|
|
237
|
+
const entries = sessionManager.getEntries();
|
|
238
|
+
const currentLeafId = sessionManager.getLeafId();
|
|
239
|
+
const result = selectBestSessionLeaf(entries, currentLeafId);
|
|
240
|
+
if (result && result.changed && result.bestLeafId) {
|
|
241
|
+
sessionManager.branch(result.bestLeafId);
|
|
242
|
+
return {
|
|
243
|
+
changed: true,
|
|
244
|
+
calibratedLeafId: result.bestLeafId,
|
|
245
|
+
previousLeafId: currentLeafId,
|
|
246
|
+
reason: result.reason,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
return { changed: false, calibratedLeafId: currentLeafId ?? undefined };
|
|
250
|
+
}
|
|
251
|
+
catch (err) {
|
|
252
|
+
return { changed: false, calibratedLeafId: sessionManager.getLeafId() ?? undefined, reason: String(err) };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Reorder entries topologically so that the main branch's leaf is at the tail of the transcript.
|
|
257
|
+
*
|
|
258
|
+
* Preserves all entries and valid parent-child relationships (every node still appears after
|
|
259
|
+
* its parent). Side-branch metadata attached to older nodes is placed before the main branch's
|
|
260
|
+
* continuing path so SDK SessionManager's sequential scan lands on the main branch leaf.
|
|
261
|
+
*/
|
|
262
|
+
export function reorderEntriesForMainBranch(entries) {
|
|
263
|
+
if (entries.length <= 1)
|
|
264
|
+
return { entries, changed: false };
|
|
265
|
+
const nonHeader = entries.filter((e) => e && e.type !== "session" && typeof e.id === "string");
|
|
266
|
+
if (nonHeader.length <= 1)
|
|
267
|
+
return { entries, changed: false };
|
|
268
|
+
const tail = nonHeader[nonHeader.length - 1];
|
|
269
|
+
const calibration = selectBestSessionLeaf(nonHeader, tail.id);
|
|
270
|
+
if (!calibration || !calibration.changed || !calibration.bestLeafId) {
|
|
271
|
+
return { entries, changed: false };
|
|
272
|
+
}
|
|
273
|
+
const bestLeafId = calibration.bestLeafId;
|
|
274
|
+
const candidates = findBranchCandidates(nonHeader);
|
|
275
|
+
const bestCandidate = candidates.find((c) => c.leafId === bestLeafId);
|
|
276
|
+
if (!bestCandidate)
|
|
277
|
+
return { entries, changed: false };
|
|
278
|
+
const bestPathSet = new Set(bestCandidate.pathIds);
|
|
279
|
+
// Separate entries into:
|
|
280
|
+
// 1. Header (type === "session")
|
|
281
|
+
// 2. Entries on the best path
|
|
282
|
+
// 3. Entries on side branches
|
|
283
|
+
const headerEntries = [];
|
|
284
|
+
const sideEntries = [];
|
|
285
|
+
const mainEntries = [];
|
|
286
|
+
for (const e of entries) {
|
|
287
|
+
if (e.type === "session") {
|
|
288
|
+
headerEntries.push(e);
|
|
289
|
+
}
|
|
290
|
+
else if (e.id && bestPathSet.has(e.id)) {
|
|
291
|
+
mainEntries.push(e);
|
|
292
|
+
}
|
|
293
|
+
else {
|
|
294
|
+
sideEntries.push(e);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
// If no side entries exist or main entries are empty, nothing to reorder
|
|
298
|
+
if (sideEntries.length === 0 || mainEntries.length === 0) {
|
|
299
|
+
return { entries, changed: false };
|
|
300
|
+
}
|
|
301
|
+
// We want to interleave side entries after their respective parent in main entries,
|
|
302
|
+
// BUT ensure that the continuation of the main branch ends with bestCandidate.leafId.
|
|
303
|
+
// A robust topological sort:
|
|
304
|
+
// Each side entry must come after its parent.
|
|
305
|
+
// Since side branches branched off an ancestor in mainEntries, we can place side entries
|
|
306
|
+
// as early as possible (immediately after their parent) so that the deep main branch entries
|
|
307
|
+
// remain at the end of the file.
|
|
308
|
+
const result = [...headerEntries];
|
|
309
|
+
const placed = new Set();
|
|
310
|
+
// Helper to place a side entry and its side descendants
|
|
311
|
+
const sideChildrenOf = new Map();
|
|
312
|
+
for (const s of sideEntries) {
|
|
313
|
+
const pid = typeof s.parentId === "string" ? s.parentId : "";
|
|
314
|
+
let list = sideChildrenOf.get(pid);
|
|
315
|
+
if (!list) {
|
|
316
|
+
list = [];
|
|
317
|
+
sideChildrenOf.set(pid, list);
|
|
318
|
+
}
|
|
319
|
+
list.push(s);
|
|
320
|
+
}
|
|
321
|
+
const placeSideDescendants = (parentId) => {
|
|
322
|
+
const children = sideChildrenOf.get(parentId);
|
|
323
|
+
if (!children)
|
|
324
|
+
return;
|
|
325
|
+
for (const child of children) {
|
|
326
|
+
if (child.id && !placed.has(child.id)) {
|
|
327
|
+
placed.add(child.id);
|
|
328
|
+
result.push(child);
|
|
329
|
+
placeSideDescendants(child.id);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
for (const m of mainEntries) {
|
|
334
|
+
if (m.id)
|
|
335
|
+
placed.add(m.id);
|
|
336
|
+
result.push(m);
|
|
337
|
+
if (m.id) {
|
|
338
|
+
placeSideDescendants(m.id);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
// Any dangling side entries with unknown parents placed before the final main entry if possible
|
|
342
|
+
for (const s of sideEntries) {
|
|
343
|
+
if (s.id && !placed.has(s.id)) {
|
|
344
|
+
placed.add(s.id);
|
|
345
|
+
// Insert before the last entry (which is the best leaf)
|
|
346
|
+
if (result.length > headerEntries.length + 1) {
|
|
347
|
+
result.splice(result.length - 1, 0, s);
|
|
348
|
+
}
|
|
349
|
+
else {
|
|
350
|
+
result.push(s);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
// Verify that the new last non-header entry is bestLeafId
|
|
355
|
+
const newNonHeader = result.filter((e) => e && e.type !== "session" && typeof e.id === "string");
|
|
356
|
+
const newTail = newNonHeader[newNonHeader.length - 1];
|
|
357
|
+
const successfullyReordered = newTail?.id === bestLeafId;
|
|
358
|
+
if (!successfullyReordered) {
|
|
359
|
+
// Fallback: don't alter if topological sort couldn't guarantee tail
|
|
360
|
+
return { entries, changed: false };
|
|
361
|
+
}
|
|
362
|
+
return {
|
|
363
|
+
entries: result,
|
|
364
|
+
changed: true,
|
|
365
|
+
reason: calibration.reason,
|
|
366
|
+
};
|
|
367
|
+
}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* session-parser — 会话转录快速轻量解析器与磁盘项目发现。
|
|
3
|
+
*
|
|
4
|
+
* 负责:
|
|
5
|
+
* - parseSessionInfoFast: 快速解析单个会话文件头部和消息,提取元信息,按需截断收集全文
|
|
6
|
+
* - discoverRecentProjectsFromDisk: 遍历会话根目录,按最近修改时间轻量发现使用过的项目路径
|
|
7
|
+
*
|
|
8
|
+
* 从 agent-service.ts 抽出为独立模块。
|
|
9
|
+
*/
|
|
10
|
+
import * as fsPromises from "node:fs/promises";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { normalizePathKey } from "./client-state.js";
|
|
13
|
+
import { MAX_SEARCH_TEXT_CHARS, readCwdFromSessionHeader } from "./session-search.js";
|
|
14
|
+
/**
|
|
15
|
+
* 快速轻量地从 SDK 会话目录中发现项目路径(仅读取会话文件的第一行头部获取 cwd,
|
|
16
|
+
* 绝不使用 SessionManager.listAll 遍历解析全部会话文本,避免大历史时阻塞数秒到数十秒)。
|
|
17
|
+
*/
|
|
18
|
+
export async function discoverRecentProjectsFromDisk(sessionRoots, limit = 30) {
|
|
19
|
+
const projects = new Map();
|
|
20
|
+
for (const root of sessionRoots) {
|
|
21
|
+
if (projects.size >= limit)
|
|
22
|
+
break;
|
|
23
|
+
try {
|
|
24
|
+
// 异步探测(issue #441):会话根可能在已断连的网络盘上,同步 existsSync 会冻结事件循环。
|
|
25
|
+
try {
|
|
26
|
+
await fsPromises.access(root);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
const entries = await fsPromises.readdir(root, { withFileTypes: true });
|
|
32
|
+
// 1. 扁平布局(PI_CODING_AGENT_SESSION_DIR):根目录下直接是 .jsonl
|
|
33
|
+
const flatFiles = entries.filter((e) => e.isFile() && e.name.endsWith(".jsonl"));
|
|
34
|
+
if (flatFiles.length > 0) {
|
|
35
|
+
const fileStats = await Promise.all(flatFiles.map(async (f) => {
|
|
36
|
+
const fp = join(root, f.name);
|
|
37
|
+
try {
|
|
38
|
+
const st = await fsPromises.stat(fp);
|
|
39
|
+
return { path: fp, mtime: st.mtimeMs };
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}));
|
|
45
|
+
fileStats.sort((a, b) => (b?.mtime ?? 0) - (a?.mtime ?? 0));
|
|
46
|
+
for (const s of fileStats) {
|
|
47
|
+
if (!s || projects.size >= limit)
|
|
48
|
+
break;
|
|
49
|
+
const cwd = await readCwdFromSessionHeader(s.path);
|
|
50
|
+
if (cwd) {
|
|
51
|
+
const key = normalizePathKey(cwd);
|
|
52
|
+
if (!projects.has(key)) {
|
|
53
|
+
try {
|
|
54
|
+
// 异步探测(issue #441):cwd 可能在已断连的网络盘上。
|
|
55
|
+
await fsPromises.access(cwd);
|
|
56
|
+
projects.set(key, { path: cwd, lastUsed: s.mtime });
|
|
57
|
+
}
|
|
58
|
+
catch { }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// 2. 默认子目录布局(<agentDir>/sessions/--<cwd>--/):每 cwd 一个子目录
|
|
64
|
+
const subdirs = entries.filter((e) => e.isDirectory() || e.isSymbolicLink()).map((e) => join(root, e.name));
|
|
65
|
+
if (subdirs.length > 0 && projects.size < limit) {
|
|
66
|
+
const CHUNK = 64;
|
|
67
|
+
const dirStats = [];
|
|
68
|
+
for (let i = 0; i < subdirs.length; i += CHUNK) {
|
|
69
|
+
const chunk = subdirs.slice(i, i + CHUNK);
|
|
70
|
+
const stats = await Promise.all(chunk.map(async (dir) => {
|
|
71
|
+
try {
|
|
72
|
+
const st = await fsPromises.stat(dir);
|
|
73
|
+
return { path: dir, mtime: st.mtimeMs };
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
}));
|
|
79
|
+
for (const s of stats)
|
|
80
|
+
if (s)
|
|
81
|
+
dirStats.push(s);
|
|
82
|
+
}
|
|
83
|
+
dirStats.sort((a, b) => b.mtime - a.mtime);
|
|
84
|
+
for (let i = 0; i < dirStats.length; i += 16) {
|
|
85
|
+
if (projects.size >= limit)
|
|
86
|
+
break;
|
|
87
|
+
const batch = dirStats.slice(i, i + 16);
|
|
88
|
+
const batchRes = await Promise.all(batch.map(async (d) => {
|
|
89
|
+
try {
|
|
90
|
+
const files = await fsPromises.readdir(d.path);
|
|
91
|
+
const jsonls = files.filter((f) => f.endsWith(".jsonl"));
|
|
92
|
+
if (jsonls.length === 0)
|
|
93
|
+
return null;
|
|
94
|
+
let newestFile = "";
|
|
95
|
+
let newestMtime = 0;
|
|
96
|
+
for (const f of jsonls) {
|
|
97
|
+
const fp = join(d.path, f);
|
|
98
|
+
try {
|
|
99
|
+
const st = await fsPromises.stat(fp);
|
|
100
|
+
if (st.mtimeMs > newestMtime) {
|
|
101
|
+
newestMtime = st.mtimeMs;
|
|
102
|
+
newestFile = fp;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
catch { }
|
|
106
|
+
}
|
|
107
|
+
if (!newestFile)
|
|
108
|
+
return null;
|
|
109
|
+
const cwd = await readCwdFromSessionHeader(newestFile);
|
|
110
|
+
if (!cwd)
|
|
111
|
+
return null;
|
|
112
|
+
return { path: cwd, lastUsed: newestMtime };
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
}));
|
|
118
|
+
for (const r of batchRes) {
|
|
119
|
+
if (!r)
|
|
120
|
+
continue;
|
|
121
|
+
const key = normalizePathKey(r.path);
|
|
122
|
+
if (!projects.has(key)) {
|
|
123
|
+
try {
|
|
124
|
+
// 异步探测(issue #441):cwd 可能在已断连的网络盘上。
|
|
125
|
+
await fsPromises.access(r.path);
|
|
126
|
+
projects.set(key, r);
|
|
127
|
+
}
|
|
128
|
+
catch { }
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
/* best effort */
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return [...projects.values()].sort((a, b) => b.lastUsed - a.lastUsed);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* 快速解析单个会话文件(提取 id/cwd/name/parentSessionPath/firstMessage/messageCount/modified,
|
|
142
|
+
* 以及可选的转录全文 allMessagesText)。仅用于会话列表发现与搜索,避免调用 SDK 重型的全量树解析。
|
|
143
|
+
*
|
|
144
|
+
* withAllMessagesText=false(默认,列表路径)时不收集转录全文,allMessagesText 返回空串 ——
|
|
145
|
+
* 全文单条可达 MB 级,绝不随列表进任何缓存(issue #440);true(搜索路径)时收集全文并在
|
|
146
|
+
* MAX_SEARCH_TEXT_CHARS 处截断。
|
|
147
|
+
*/
|
|
148
|
+
export async function parseSessionInfoFast(filePath, fileMtime, withAllMessagesText = false) {
|
|
149
|
+
try {
|
|
150
|
+
const content = await fsPromises.readFile(filePath, "utf8");
|
|
151
|
+
const lines = content.split("\n");
|
|
152
|
+
let id = "";
|
|
153
|
+
let cwd = "";
|
|
154
|
+
let name;
|
|
155
|
+
let parentSessionPath;
|
|
156
|
+
let firstMessage = "";
|
|
157
|
+
let messageCount = 0;
|
|
158
|
+
let lastActivityTime = 0;
|
|
159
|
+
let headerTime = 0;
|
|
160
|
+
const allMessages = withAllMessagesText ? [] : null;
|
|
161
|
+
for (const line of lines) {
|
|
162
|
+
if (!line.trim())
|
|
163
|
+
continue;
|
|
164
|
+
let entry;
|
|
165
|
+
try {
|
|
166
|
+
entry = JSON.parse(line);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
const rec = entry;
|
|
172
|
+
if (!rec)
|
|
173
|
+
continue;
|
|
174
|
+
if (rec.type === "session") {
|
|
175
|
+
id = typeof rec.id === "string" ? rec.id : "";
|
|
176
|
+
cwd = typeof rec.cwd === "string" ? rec.cwd : "";
|
|
177
|
+
if (typeof rec.timestamp === "string")
|
|
178
|
+
headerTime = new Date(rec.timestamp).getTime();
|
|
179
|
+
if (typeof rec.parentSession === "string")
|
|
180
|
+
parentSessionPath = rec.parentSession;
|
|
181
|
+
}
|
|
182
|
+
else if (rec.type === "session_info") {
|
|
183
|
+
if (typeof rec.name === "string" && rec.name.trim())
|
|
184
|
+
name = rec.name.trim();
|
|
185
|
+
}
|
|
186
|
+
else if (rec.type === "message") {
|
|
187
|
+
messageCount++;
|
|
188
|
+
const msg = rec.message;
|
|
189
|
+
if (msg) {
|
|
190
|
+
if (typeof msg.timestamp === "number")
|
|
191
|
+
lastActivityTime = Math.max(lastActivityTime, msg.timestamp);
|
|
192
|
+
let text = "";
|
|
193
|
+
if (typeof msg.content === "string") {
|
|
194
|
+
text = msg.content;
|
|
195
|
+
}
|
|
196
|
+
else if (Array.isArray(msg.content)) {
|
|
197
|
+
for (const part of msg.content) {
|
|
198
|
+
if (part && typeof part.text === "string") {
|
|
199
|
+
text += (text ? " " : "") + part.text;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (text) {
|
|
204
|
+
if (!firstMessage && msg.role === "user")
|
|
205
|
+
firstMessage = text;
|
|
206
|
+
allMessages?.push(text);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (!id)
|
|
212
|
+
return null;
|
|
213
|
+
const modified = lastActivityTime > 0 ? lastActivityTime : headerTime > 0 ? headerTime : fileMtime;
|
|
214
|
+
let allMessagesText = "";
|
|
215
|
+
if (allMessages) {
|
|
216
|
+
const joined = allMessages.join(" ");
|
|
217
|
+
allMessagesText = joined.length > MAX_SEARCH_TEXT_CHARS ? joined.slice(0, MAX_SEARCH_TEXT_CHARS) : joined;
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
path: filePath,
|
|
221
|
+
id,
|
|
222
|
+
cwd,
|
|
223
|
+
name,
|
|
224
|
+
parentSessionPath,
|
|
225
|
+
created: new Date(headerTime || fileMtime),
|
|
226
|
+
modified: new Date(modified),
|
|
227
|
+
messageCount,
|
|
228
|
+
firstMessage: firstMessage || "(no messages)",
|
|
229
|
+
allMessagesText,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
}
|