@frogmoo/dsh-supermemory 0.0.0-stage → 1.4.1
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 +442 -0
- package/INSTALL.md +193 -0
- package/LICENSE +21 -0
- package/README.md +220 -2
- package/cordis.patch.yml +9 -0
- package/lib/capability-T5x_17iK.js +2971 -0
- package/lib/client.js +4217 -0
- package/lib/clip-kqqR05NC.js +279 -0
- package/lib/export-XY8Bfglx.js +144 -0
- package/lib/filemap-CsF4oYtT.js +166 -0
- package/lib/group-CkFv7052.js +313 -0
- package/lib/hub-sessions-pzURuUmH.js +1010 -0
- package/lib/memory-collections-DaSVGbrR.js +686 -0
- package/lib/model-Z4_-9sAj.js +735 -0
- package/lib/rolldown-runtime-BJohB4LM.js +13 -0
- package/lib/skill-forge-DHxPo_w6.js +2348 -0
- package/lib/store-DD2L3GDr.js +531 -0
- package/lib/supermemory.js +15015 -0
- package/lib/toolize-B9Mbl7sp.js +426 -0
- package/package.json +67 -4
|
@@ -0,0 +1,1010 @@
|
|
|
1
|
+
import { r as workspaceKeyOf, t as newId } from "./store-DD2L3GDr.js";
|
|
2
|
+
import { g as updateMember, o as addMember, r as clipMarked } from "./clip-kqqR05NC.js";
|
|
3
|
+
import { b as injectionTitle } from "./model-Z4_-9sAj.js";
|
|
4
|
+
import { L as resolveRole } from "./capability-T5x_17iK.js";
|
|
5
|
+
/** Fallback title when both the topic-set title and the task are empty. */
|
|
6
|
+
const TITLE_FALLBACK = "新会话";
|
|
7
|
+
/**
|
|
8
|
+
* Ellipsis-clip: text longer than maxChars is cut and gets a trailing "…",
|
|
9
|
+
* and the marker counts toward the budget, so the result never exceeds
|
|
10
|
+
* maxChars characters. Use this for user-visible titles so an over-long
|
|
11
|
+
* value says it was clipped instead of ending mid-word.
|
|
12
|
+
*/
|
|
13
|
+
function clipEllipsis(text, maxChars) {
|
|
14
|
+
const chars = Array.from(String(text ?? ""));
|
|
15
|
+
if (chars.length <= maxChars) return chars.join("");
|
|
16
|
+
if (maxChars <= 1) return "…";
|
|
17
|
+
return chars.slice(0, maxChars - 1).join("") + "…";
|
|
18
|
+
}
|
|
19
|
+
/** First non-empty line of a text. */
|
|
20
|
+
function firstLine(text) {
|
|
21
|
+
for (const line of String(text ?? "").split(String.fromCharCode(10))) {
|
|
22
|
+
const trimmed = line.trim();
|
|
23
|
+
if (trimmed) return trimmed;
|
|
24
|
+
}
|
|
25
|
+
return "";
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Strip the descriptive lead-ins users and older rounds put in front of a task:
|
|
29
|
+
* 「R31:」「R31-B · 」「R32 」「第 3 轮:」「Round 3 」「项目:」「背景:」
|
|
30
|
+
* 「任务:」「分支 · 」… Two shapes:
|
|
31
|
+
* - a ROUND token («R32», «R41-B», «第 3 轮», «Round 3») strips after a
|
|
32
|
+
* separator OR a single space, because dispatch titles are exactly
|
|
33
|
+
* «R32 只读复核:…». It is anchored, so a round merely MENTIONED inside a
|
|
34
|
+
* sentence («参考 R31 的实现») is never touched;
|
|
35
|
+
* - a LABEL («项目:」「背景:」「仓库:」「任务:」「需求:」「派发:」
|
|
36
|
+
* 「请求:」…) keeps REQUIRING a separator, so a title that merely starts
|
|
37
|
+
* with a label word («需求分析:…») stays whole.
|
|
38
|
+
* Repeats up to three times so stacked prefixes («R31:任务:…») collapse to
|
|
39
|
+
* the task itself.
|
|
40
|
+
*/
|
|
41
|
+
const LEADING_DESCRIPTION = /^(?:(?:(?:R|r)\d{1,3}(?:-[A-Za-z]{1,3})?|第\s*\d+\s*轮|Round\s*\d+)\s*(?:[::·•・|\-—–]\s*|\s+)|(?:项目|背景|仓库|任务书|任务|工作内容|需求|派发|请求|分支)\s*(?:[::·•・|\-—–]|\s{2,})\s*)/i;
|
|
42
|
+
/** Remove leading descriptive tokens (round / 任务 / 分支 …) from one line. */
|
|
43
|
+
function stripLeadingDescription(text) {
|
|
44
|
+
let value = String(text ?? "").trim();
|
|
45
|
+
for (let round = 0; round < 3; round += 1) {
|
|
46
|
+
const next = value.replace(LEADING_DESCRIPTION, "").trim();
|
|
47
|
+
if (next === value) break;
|
|
48
|
+
value = next;
|
|
49
|
+
}
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* A session's display name as a DIRECT description of its work: markdown and
|
|
54
|
+
* brackets stripped, descriptive lead-ins removed, first line clipped with an
|
|
55
|
+
* ellipsis. An empty text falls back to the neutral {@link TITLE_FALLBACK}
|
|
56
|
+
* (「新会话」) — never a brand prefix and never an id token.
|
|
57
|
+
*/
|
|
58
|
+
function describeSessionTitle(text, maxChars = 48) {
|
|
59
|
+
const cleaned = firstLine(stripLeadingDescription(cleanTitleText(text)));
|
|
60
|
+
return cleaned ? clipEllipsis(cleaned, Math.max(4, Math.floor(maxChars))) : TITLE_FALLBACK;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Strip markdown and bracket markup before truncation: fences, inline code,
|
|
64
|
+
* emphasis markers, ATX headings, blockquotes, list bullets, task boxes and
|
|
65
|
+
* square/full-width bracket characters. Newlines are preserved so the caller can
|
|
66
|
+
* take the first meaningful line.
|
|
67
|
+
*/
|
|
68
|
+
function cleanTitleText(text) {
|
|
69
|
+
let value = String(text ?? "").replace(/\r\n?/g, String.fromCharCode(10));
|
|
70
|
+
value = value.replace(/```[\s\S]*?```/g, " ");
|
|
71
|
+
value = value.replace(/`[^`]*`/g, " ");
|
|
72
|
+
value = value.replace(/\*\*|__|~~/g, "");
|
|
73
|
+
value = value.replace(/^\s{0,3}#{1,6}\s*/gm, "");
|
|
74
|
+
value = value.replace(/^\s{0,3}>\s?/gm, "");
|
|
75
|
+
value = value.replace(/^\s{0,3}(?:[-+*]|\d{1,3}[.)])\s+/gm, "");
|
|
76
|
+
value = value.replace(/\[[ xX]?\]/g, " ");
|
|
77
|
+
value = value.replace(/[\[\]【】〔〕]/g, " ");
|
|
78
|
+
value = value.replace(/[ \t]+/g, " ");
|
|
79
|
+
value = value.replace(/[ \t]*\n[ \t]*/g, String.fromCharCode(10));
|
|
80
|
+
return value.trim();
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Compute one session title from a topic-set title and the task text.
|
|
84
|
+
* @param topicTitle - owning topic-set title (may be empty).
|
|
85
|
+
* @param task - dispatch/reply text (may be empty).
|
|
86
|
+
* @param existing - titles already used in the same topic set (for de-duplication).
|
|
87
|
+
* @param options - character budgets (tests and future config).
|
|
88
|
+
* @returns title of at most maxChars characters.
|
|
89
|
+
*/
|
|
90
|
+
function sessionTitleFor(topicTitle, task, existing = [], options = {}) {
|
|
91
|
+
const maxChars = Math.max(4, Math.floor(options.maxChars ?? 80));
|
|
92
|
+
const snippetChars = Math.max(1, Math.floor(options.snippetChars ?? 48));
|
|
93
|
+
const topic = firstLine(cleanTitleText(topicTitle));
|
|
94
|
+
const snippet = clipEllipsis(firstLine(cleanTitleText(task)), snippetChars);
|
|
95
|
+
const separator = " · ";
|
|
96
|
+
let base;
|
|
97
|
+
if (topic && snippet) base = clipEllipsis(topic, Math.max(4, maxChars - 3 - snippet.length)) + separator + snippet;
|
|
98
|
+
else if (topic) base = clipEllipsis(topic, maxChars);
|
|
99
|
+
else if (snippet) base = clipEllipsis(snippet, maxChars);
|
|
100
|
+
else base = TITLE_FALLBACK;
|
|
101
|
+
const used = /* @__PURE__ */ new Set();
|
|
102
|
+
for (const title of existing) {
|
|
103
|
+
const trimmed = String(title ?? "").trim();
|
|
104
|
+
if (trimmed) used.add(trimmed);
|
|
105
|
+
}
|
|
106
|
+
if (!used.has(base)) return base;
|
|
107
|
+
for (let index = 2; index <= 999; index += 1) {
|
|
108
|
+
const suffix = "(" + index + ")";
|
|
109
|
+
const candidate = clipEllipsis(base, Math.max(1, maxChars - suffix.length)) + suffix;
|
|
110
|
+
if (!used.has(candidate)) return candidate;
|
|
111
|
+
}
|
|
112
|
+
return base;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Persist the member title for one topic-set branch, computing it only when the
|
|
116
|
+
* member has no title yet (a reused branch keeps its first stable name).
|
|
117
|
+
* @param store - plugin store.
|
|
118
|
+
* @param topicSetId - owning topic set.
|
|
119
|
+
* @param member - branch identity and kind.
|
|
120
|
+
* @param topicTitle - topic-set title fallback when the row is gone.
|
|
121
|
+
* @param task - task text used for the snippet.
|
|
122
|
+
* @param options - `taskOnly` names a WORK BRANCH: the title is the task
|
|
123
|
+
* itself (no topic-set prefix), matching 「会话名称直接描述工作内容」.
|
|
124
|
+
* R43 需求③ widened that budget to {@link TITLE_BRANCH_TASK_CHARS} so the
|
|
125
|
+
* topic is not cut mid-clause.
|
|
126
|
+
* @returns the title now stored on the member.
|
|
127
|
+
*/
|
|
128
|
+
async function ensureMemberTitle(store, topicSetId, member, topicTitle, task, options = {}) {
|
|
129
|
+
const record = store.topicsets.get(topicSetId);
|
|
130
|
+
if (!record) return options.taskOnly ? describeSessionTitle(task, 60) : sessionTitleFor(topicTitle, task);
|
|
131
|
+
const current = record.members.find((entry) => entry.sessionId === member.sessionId);
|
|
132
|
+
if (current && current.title.trim()) return current.title;
|
|
133
|
+
const others = record.members.filter((entry) => entry.sessionId !== member.sessionId).map((entry) => entry.title);
|
|
134
|
+
const title = options.taskOnly ? describeSessionTitle(task, 60) : sessionTitleFor(record.title || topicTitle, task, others);
|
|
135
|
+
if (current) await updateMember(store, topicSetId, member.sessionId, { title });
|
|
136
|
+
else await addMember(store, topicSetId, {
|
|
137
|
+
sessionId: member.sessionId,
|
|
138
|
+
kind: member.kind,
|
|
139
|
+
title
|
|
140
|
+
});
|
|
141
|
+
return title;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Apply a title to the HOST session so the GUI session list stops showing it
|
|
145
|
+
* unnamed. Prefers `ctx.sessionTitle.rename` (host-owned normalization + pin),
|
|
146
|
+
* falls back to the exact `session/title` log append, and never throws.
|
|
147
|
+
* @param ctx - host context (structural view).
|
|
148
|
+
* @param sessionId - live session to name.
|
|
149
|
+
* @param title - proposed title (normalized again here).
|
|
150
|
+
* @param logger - warning sink.
|
|
151
|
+
* @returns where the title landed.
|
|
152
|
+
*/
|
|
153
|
+
function applySessionTitle(ctx, sessionId, title, logger, options = {}) {
|
|
154
|
+
const clean = clipEllipsis(firstLine(cleanTitleText(title)), 80);
|
|
155
|
+
if (!clean) return "none";
|
|
156
|
+
const session = ctx.sessions?.get(sessionId);
|
|
157
|
+
if (!session) return "none";
|
|
158
|
+
const service = (() => {
|
|
159
|
+
try {
|
|
160
|
+
return ctx.get?.("sessionTitle");
|
|
161
|
+
} catch {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
})();
|
|
165
|
+
if (!options.force) try {
|
|
166
|
+
if (service && typeof service.get === "function") {
|
|
167
|
+
const current = service.get(session);
|
|
168
|
+
if (current && typeof current.title === "string" && current.title.trim()) return "already";
|
|
169
|
+
}
|
|
170
|
+
} catch (error) {
|
|
171
|
+
logger.warn("supermemory: session title read skipped: " + String(error).slice(0, 160));
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
if (service && typeof service.rename === "function") {
|
|
175
|
+
service.rename(session, clean);
|
|
176
|
+
return "host";
|
|
177
|
+
}
|
|
178
|
+
} catch (error) {
|
|
179
|
+
logger.warn("supermemory: sessionTitle.rename failed, falling back to the log event: " + String(error).slice(0, 160));
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
const append = session.append;
|
|
183
|
+
if (typeof append === "function") {
|
|
184
|
+
append.call(session, "session/title", {
|
|
185
|
+
title: clean,
|
|
186
|
+
messageSeqs: [],
|
|
187
|
+
source: { kind: "user" }
|
|
188
|
+
});
|
|
189
|
+
return "fallback";
|
|
190
|
+
}
|
|
191
|
+
} catch (error) {
|
|
192
|
+
logger.warn("supermemory: session title log append failed: " + String(error).slice(0, 160));
|
|
193
|
+
}
|
|
194
|
+
return "none";
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* The live HOST title of one session, or undefined when the session is not
|
|
198
|
+
* tracked, carries no title, or the title service is unavailable. The
|
|
199
|
+
* one-time title migration uses it to detect a title that somebody else
|
|
200
|
+
* renamed, so it never overwrites a human's choice.
|
|
201
|
+
*/
|
|
202
|
+
function currentSessionTitle(ctx, sessionId) {
|
|
203
|
+
const session = ctx.sessions?.get(sessionId);
|
|
204
|
+
if (!session) return void 0;
|
|
205
|
+
try {
|
|
206
|
+
const current = (ctx.get?.("sessionTitle"))?.get?.(session);
|
|
207
|
+
if (current && typeof current.title === "string" && current.title.trim()) return current.title;
|
|
208
|
+
} catch {}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* R32 需求③: the best available title for a message's SOURCE session.
|
|
212
|
+
*
|
|
213
|
+
* Reads the live host title first, then the plugin's durable branch title
|
|
214
|
+
* mapping (a branch can be detached/reloaded while its dispatch row still
|
|
215
|
+
* carries the name), and returns '' when neither knows one — the card then
|
|
216
|
+
* falls back to the id's last four characters (see chat-card.ts).
|
|
217
|
+
*
|
|
218
|
+
* @param ctx - host context (structural view; never throws).
|
|
219
|
+
* @param store - durable plugin store (optional).
|
|
220
|
+
* @param sessionId - session whose title should label a card.
|
|
221
|
+
* @returns a trimmed title, or ''.
|
|
222
|
+
*/
|
|
223
|
+
function sessionTitleOf(ctx, store, sessionId) {
|
|
224
|
+
if (!sessionId) return "";
|
|
225
|
+
const live = currentSessionTitle(ctx, sessionId);
|
|
226
|
+
if (live && live.trim()) return live.trim();
|
|
227
|
+
if (!store) return "";
|
|
228
|
+
try {
|
|
229
|
+
for (const [, topicSet] of store.topicsets.entries()) for (const member of topicSet.members) if (member.sessionId === sessionId && typeof member.title === "string" && member.title.trim()) return member.title.trim();
|
|
230
|
+
} catch {}
|
|
231
|
+
return "";
|
|
232
|
+
}
|
|
233
|
+
/** Dispatch states that still owe the hub a relay (see observe.ts settle rules). */
|
|
234
|
+
const OPEN_STATUSES = /* @__PURE__ */ new Set([
|
|
235
|
+
"queued",
|
|
236
|
+
"dispatched",
|
|
237
|
+
"observed",
|
|
238
|
+
"summarized"
|
|
239
|
+
]);
|
|
240
|
+
/** Terminal failure states: the branch is idle, but the work did NOT land. */
|
|
241
|
+
const FAILED_STATUSES = /* @__PURE__ */ new Set(["failed", "interrupted"]);
|
|
242
|
+
/** True while a branch still has work that must reach the hub. */
|
|
243
|
+
function isOpenDispatch(record) {
|
|
244
|
+
return OPEN_STATUSES.has(record.status);
|
|
245
|
+
}
|
|
246
|
+
/** The first topic-set member row for a branch (archived sets included). */
|
|
247
|
+
function memberOf(store, branchSessionId) {
|
|
248
|
+
for (const [topicSetId, topicSet] of store.topicsets.entries()) {
|
|
249
|
+
const member = topicSet.members.find((row) => row.sessionId === branchSessionId);
|
|
250
|
+
if (member) return {
|
|
251
|
+
topicSetId,
|
|
252
|
+
topicSet,
|
|
253
|
+
member
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* A one-line task excerpt (the branch has no title yet / not a member).
|
|
259
|
+
*
|
|
260
|
+
* R47: delegates to the shared {@link clipMarked} so the cut lands on a
|
|
261
|
+
* sentence boundary (the old char-`slice` could stop mid-word) and always
|
|
262
|
+
* carries the `…` marker. The empty-text fallback is preserved.
|
|
263
|
+
*/
|
|
264
|
+
function taskExcerpt(task, max = 32) {
|
|
265
|
+
const text = String(task ?? "").replace(/\s+/g, " ").trim();
|
|
266
|
+
if (!text) return "(无任务描述)";
|
|
267
|
+
return clipMarked(text, max);
|
|
268
|
+
}
|
|
269
|
+
/** Human relative time for cards (coarse on purpose: the card is context, not a log). */
|
|
270
|
+
function relativeAgo(at, now = Date.now()) {
|
|
271
|
+
if (!Number.isFinite(at) || at <= 0) return "未知时间";
|
|
272
|
+
const delta = Math.max(0, now - at);
|
|
273
|
+
const minute = 6e4;
|
|
274
|
+
const hour = 60 * minute;
|
|
275
|
+
const day = 24 * hour;
|
|
276
|
+
if (delta < minute) return "刚刚";
|
|
277
|
+
if (delta < hour) return `${Math.floor(delta / minute)} 分钟前`;
|
|
278
|
+
if (delta < day) return `${Math.floor(delta / hour)} 小时前`;
|
|
279
|
+
return `${Math.floor(delta / day)} 天前`;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Project one group of dispatch rows into one branch row.
|
|
283
|
+
*
|
|
284
|
+
* `hubSessionId` only scopes the projection (which rows are considered); the
|
|
285
|
+
* resulting row still reports every hub that dispatched into the branch, so a
|
|
286
|
+
* shared branch is visibly shared rather than silently re-labelled per hub.
|
|
287
|
+
*/
|
|
288
|
+
function projectBranch(store, branchSessionId, rows) {
|
|
289
|
+
if (rows.length === 0) return void 0;
|
|
290
|
+
const sorted = [...rows].sort((a, b) => b.updatedAt - a.updatedAt || b.createdAt - a.createdAt);
|
|
291
|
+
const latest = sorted[0];
|
|
292
|
+
const memberInfo = memberOf(store, branchSessionId);
|
|
293
|
+
const member = memberInfo?.member;
|
|
294
|
+
const topicSetId = memberInfo?.topicSetId ?? latest.topicSetId;
|
|
295
|
+
const topicSet = memberInfo?.topicSet ?? (topicSetId ? store.topicsets.get(topicSetId) : void 0);
|
|
296
|
+
const hubs = [];
|
|
297
|
+
for (const row of sorted) if (row.hubSessionId && !hubs.includes(row.hubSessionId)) hubs.push(row.hubSessionId);
|
|
298
|
+
const openDispatches = rows.filter(isOpenDispatch).length;
|
|
299
|
+
const lastTerminal = sorted.find((row) => !isOpenDispatch(row));
|
|
300
|
+
const status = openDispatches > 0 ? "working" : lastTerminal && FAILED_STATUSES.has(lastTerminal.status) ? "failed" : "idle";
|
|
301
|
+
const lastActivityAt = Math.max(...rows.map((row) => Math.max(Number(row.updatedAt) || 0, Number(row.lastActivityAt) || 0)), Number(member?.lastActiveAt) || 0);
|
|
302
|
+
const titled = sorted.find((row) => String(row.title ?? "").trim());
|
|
303
|
+
const tagged = sorted.find((row) => (row.tags ?? []).length > 0);
|
|
304
|
+
const view = {
|
|
305
|
+
branchSessionId,
|
|
306
|
+
title: String(titled?.title ?? "").trim() || (member?.title ?? "").trim() || taskExcerpt(latest.task, 48),
|
|
307
|
+
tags: [...tagged?.tags ?? []],
|
|
308
|
+
task: latest.task,
|
|
309
|
+
hubSessionId: latest.hubSessionId,
|
|
310
|
+
status,
|
|
311
|
+
openDispatches,
|
|
312
|
+
dispatches: rows.length,
|
|
313
|
+
lastActivityAt,
|
|
314
|
+
hubs,
|
|
315
|
+
shared: hubs.length > 1
|
|
316
|
+
};
|
|
317
|
+
if (topicSetId) view.topicSetId = topicSetId;
|
|
318
|
+
if (topicSet) view.topicSetTitle = topicSet.title;
|
|
319
|
+
if (latest.groupId) view.groupId = latest.groupId;
|
|
320
|
+
return view;
|
|
321
|
+
}
|
|
322
|
+
/** Group dispatch rows by branch session id (insertion order of first sighting). */
|
|
323
|
+
function groupByBranch(rows) {
|
|
324
|
+
const out = /* @__PURE__ */ new Map();
|
|
325
|
+
for (const [, row] of rows) {
|
|
326
|
+
const branchId = String(row.branchSessionId ?? "");
|
|
327
|
+
if (!branchId) continue;
|
|
328
|
+
const bucket = out.get(branchId);
|
|
329
|
+
if (bucket) bucket.push(row);
|
|
330
|
+
else out.set(branchId, [row]);
|
|
331
|
+
}
|
|
332
|
+
return out;
|
|
333
|
+
}
|
|
334
|
+
/** Every branch of the store, keyed by branch id, carrying ALL hubs' rows. */
|
|
335
|
+
function allBranches(store) {
|
|
336
|
+
return groupByBranch([...store.dispatches.entries()]);
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Project the selected branch ids against the COMPLETE row set of each branch.
|
|
340
|
+
*
|
|
341
|
+
* This is what makes sharing honest: `listHubBranches` selects branches by the
|
|
342
|
+
* caller's hub, but a branch's status/activity/hub set must include dispatches
|
|
343
|
+
* from every hub, otherwise a shared branch would look idle to hub B while hub A
|
|
344
|
+
* is still working in it (and `shared` would always be false).
|
|
345
|
+
*/
|
|
346
|
+
function projectSelected(store, all, branchIds, limit, cap) {
|
|
347
|
+
const out = [];
|
|
348
|
+
for (const branchSessionId of branchIds) {
|
|
349
|
+
const view = projectBranch(store, branchSessionId, all.get(branchSessionId) ?? []);
|
|
350
|
+
if (view) out.push(view);
|
|
351
|
+
}
|
|
352
|
+
out.sort((a, b) => b.lastActivityAt - a.lastActivityAt);
|
|
353
|
+
return out.slice(0, Math.max(1, Math.min(cap, Number(limit) || cap)));
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Branches one hub dispatched into, newest activity first.
|
|
357
|
+
*
|
|
358
|
+
* @param store - plugin store (dispatch rows + topic-set membership).
|
|
359
|
+
* @param hubSessionId - the hub whose association is projected.
|
|
360
|
+
* @param limit - maximum rows (default {@link HUB_BRANCH_LIMIT}).
|
|
361
|
+
*/
|
|
362
|
+
function listHubBranches(store, hubSessionId, limit = 20) {
|
|
363
|
+
const id = String(hubSessionId ?? "").trim();
|
|
364
|
+
if (!store || !id) return [];
|
|
365
|
+
const all = allBranches(store);
|
|
366
|
+
const selected = /* @__PURE__ */ new Set();
|
|
367
|
+
for (const [dispatchId, row] of store.dispatches.entries()) if (row.hubSessionId === id && row.branchSessionId) selected.add(String(row.branchSessionId));
|
|
368
|
+
return projectSelected(store, all, selected, limit, 20);
|
|
369
|
+
}
|
|
370
|
+
/** Every branch of one topic set, whoever dispatched into it (共享视图). */
|
|
371
|
+
function listTopicSetBranches(store, topicSetId, limit = 20) {
|
|
372
|
+
const id = String(topicSetId ?? "").trim();
|
|
373
|
+
if (!store || !id) return [];
|
|
374
|
+
const all = allBranches(store);
|
|
375
|
+
const selected = /* @__PURE__ */ new Set();
|
|
376
|
+
for (const [dispatchId, row] of store.dispatches.entries()) if (row.topicSetId === id && row.branchSessionId) selected.add(String(row.branchSessionId));
|
|
377
|
+
return projectSelected(store, all, selected, limit, 20);
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Every branch of one workspace's topic sets (the console's cross-hub view).
|
|
381
|
+
*
|
|
382
|
+
* A dispatch row carries a topicSetId, not a workspaceKey, so the workspace is
|
|
383
|
+
* resolved through the set (sets are workspace-scoped since v1).
|
|
384
|
+
*/
|
|
385
|
+
function listWorkspaceBranches(store, workspaceKey, limit = 100) {
|
|
386
|
+
if (!store || !workspaceKey) return [];
|
|
387
|
+
const all = allBranches(store);
|
|
388
|
+
const selected = /* @__PURE__ */ new Set();
|
|
389
|
+
for (const [dispatchId, row] of store.dispatches.entries()) {
|
|
390
|
+
if (!row.topicSetId || !row.branchSessionId) continue;
|
|
391
|
+
const topicSet = store.topicsets.get(row.topicSetId);
|
|
392
|
+
if (!topicSet || topicSet.workspaceKey !== workspaceKey) continue;
|
|
393
|
+
selected.add(String(row.branchSessionId));
|
|
394
|
+
}
|
|
395
|
+
return projectSelected(store, all, selected, limit, 1e3);
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* branchSessionId → the latest task dispatched into it (newest row wins).
|
|
399
|
+
*
|
|
400
|
+
* The panel's topic-set branch rows carry this excerpt so a preserved branch
|
|
401
|
+
* stays identifiable after a restart: title + owning set + task summary, read
|
|
402
|
+
* from the durable ledger alone (no live handle required).
|
|
403
|
+
*/
|
|
404
|
+
function latestTaskByBranch(store) {
|
|
405
|
+
const latest = /* @__PURE__ */ new Map();
|
|
406
|
+
if (store) for (const [, row] of store.dispatches.entries()) {
|
|
407
|
+
const branchId = String(row.branchSessionId ?? "");
|
|
408
|
+
if (!branchId) continue;
|
|
409
|
+
const at = Math.max(Number(row.updatedAt) || 0, Number(row.createdAt) || 0);
|
|
410
|
+
const current = latest.get(branchId);
|
|
411
|
+
if (!current || at >= current.at) latest.set(branchId, {
|
|
412
|
+
task: String(row.task ?? ""),
|
|
413
|
+
at
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
const out = /* @__PURE__ */ new Map();
|
|
417
|
+
for (const [branchId, row] of latest) out.set(branchId, row.task);
|
|
418
|
+
return out;
|
|
419
|
+
}
|
|
420
|
+
/** branchSessionId → the hubs that dispatched into it (panel branch cards). */
|
|
421
|
+
function hubsByBranch(store) {
|
|
422
|
+
const map = /* @__PURE__ */ new Map();
|
|
423
|
+
if (!store) return map;
|
|
424
|
+
for (const [, row] of store.dispatches.entries()) {
|
|
425
|
+
const branchId = String(row.branchSessionId ?? "");
|
|
426
|
+
if (!branchId || !row.hubSessionId) continue;
|
|
427
|
+
const list = map.get(branchId);
|
|
428
|
+
if (list) {
|
|
429
|
+
if (!list.includes(row.hubSessionId)) list.push(row.hubSessionId);
|
|
430
|
+
} else map.set(branchId, [row.hubSessionId]);
|
|
431
|
+
}
|
|
432
|
+
return map;
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* The hub-facing context card (R19 需求②): "these are your branches right now".
|
|
436
|
+
*
|
|
437
|
+
* Deliberately terse and bounded: the card is appended on every user step, so a
|
|
438
|
+
* 20-branch list would tax every turn. It is omitted entirely when the hub has
|
|
439
|
+
* no associated branch, and it always ends with the dispatch rule that keeps the
|
|
440
|
+
* hub from re-dispatching a branch that is merely idle.
|
|
441
|
+
*
|
|
442
|
+
* R30 需求⑤.2: when the round's recall matched topic sets, the card also carries
|
|
443
|
+
* those sets' branch lists (标题/标签/状态/最后活动) — the "按话题集检索其下分支
|
|
444
|
+
* 会话" half of the retrieval routing, read from the durable ledger (no host
|
|
445
|
+
* call). Bounded like the hub section: at most the caller's sections, each
|
|
446
|
+
* capped at `maxItems` rows.
|
|
447
|
+
*/
|
|
448
|
+
function renderHubBranchesCard(rows, options = {}) {
|
|
449
|
+
const now = options.now ?? Date.now();
|
|
450
|
+
const maxItems = Math.max(1, Math.min(20, options.maxItems ?? 8));
|
|
451
|
+
const setSections = (options.topicSets ?? []).filter((section) => section.rows.length > 0);
|
|
452
|
+
if (rows.length === 0 && setSections.length === 0) return "";
|
|
453
|
+
const lines = [];
|
|
454
|
+
if (rows.length > 0) {
|
|
455
|
+
const working = rows.filter((row) => row.status === "working").length;
|
|
456
|
+
const failed = rows.filter((row) => row.status === "failed").length;
|
|
457
|
+
lines.push(injectionTitle("branch") + " 本会话在该话题集拉起的分支:");
|
|
458
|
+
for (const row of rows.slice(0, maxItems)) {
|
|
459
|
+
const parts = [
|
|
460
|
+
`${row.status === "working" ? "工作中" : row.status === "failed" ? "失败待处理" : "空闲"}`,
|
|
461
|
+
row.topicSetTitle ? `话题集「${row.topicSetTitle}」` : "无话题集",
|
|
462
|
+
relativeAgo(row.lastActivityAt, now)
|
|
463
|
+
];
|
|
464
|
+
if (row.tags.length > 0) parts.push(`标签 ${row.tags.join(" / ")}`);
|
|
465
|
+
if (row.shared) parts.push(`与另外 ${row.hubs.length - 1} 个中枢共享`);
|
|
466
|
+
lines.push(`- ${row.title}(${parts.join(" · ")})`);
|
|
467
|
+
}
|
|
468
|
+
if (rows.length > maxItems) lines.push(`- …另有 ${rows.length - maxItems} 个分支(面板可查看全部)`);
|
|
469
|
+
lines.push(`共 ${rows.length} 个分支:${working} 工作中 / ${failed} 失败 / ${rows.length - working - failed} 空闲。`);
|
|
470
|
+
lines.push("继续同一分支用 mode=continue(忙则排队);并行新任务用 tasks[],每个任务独占一个分支并统一汇总。");
|
|
471
|
+
}
|
|
472
|
+
for (const section of setSections) {
|
|
473
|
+
lines.push("");
|
|
474
|
+
lines.push(`话题集「${section.title}」的分支(按话题集检索,可继续/复用):`);
|
|
475
|
+
for (const row of section.rows.slice(0, maxItems)) {
|
|
476
|
+
const parts = [row.status === "working" ? "工作中" : row.status === "failed" ? "失败待处理" : "空闲", relativeAgo(row.lastActivityAt, now)];
|
|
477
|
+
if (row.tags.length > 0) parts.push(`标签 ${row.tags.join(" / ")}`);
|
|
478
|
+
if (row.shared) parts.push(`与另外 ${row.hubs.length - 1} 个中枢共享`);
|
|
479
|
+
lines.push(`- ${row.title}(${parts.join(" · ")})`);
|
|
480
|
+
}
|
|
481
|
+
if (section.rows.length > maxItems) lines.push(`- …另有 ${section.rows.length - maxItems} 个分支(面板可查看全部)`);
|
|
482
|
+
}
|
|
483
|
+
return lines.join("\n");
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* Is this agent a HUB session of its workspace?
|
|
487
|
+
*
|
|
488
|
+
* R33 需求②: a hub is a POSITIVE mark, never "a top-level session with no
|
|
489
|
+
* parentSession". That negation classified every ordinary conversation as a hub
|
|
490
|
+
* (the guard then denied bash/write/subagent in all of them) and contradicted
|
|
491
|
+
* the branch rule for a root member reused as a branch. {@link resolveRole}
|
|
492
|
+
* owns the single decision: branch facts win, hub marks are workspace-scoped,
|
|
493
|
+
* everything else is an ordinary session.
|
|
494
|
+
*
|
|
495
|
+
* Never throws: a store read failure answers `false` (ordinary), which keeps the
|
|
496
|
+
* prompt gate and the guard total.
|
|
497
|
+
*/
|
|
498
|
+
function isHubSession(store, agent) {
|
|
499
|
+
try {
|
|
500
|
+
return resolveRole(store, agent).role === "hub";
|
|
501
|
+
} catch {
|
|
502
|
+
return false;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
// src/memory-versions.ts
|
|
506
|
+
/** True when this store can persist memory history rows. */
|
|
507
|
+
function memoryVersionsSupported(store) {
|
|
508
|
+
const table = store?.memoryVersions;
|
|
509
|
+
return !!table && typeof table.put === "function" && typeof table.entries === "function";
|
|
510
|
+
}
|
|
511
|
+
/** 当前记忆的版本号(旧记录没有 version 字段时读作 1,与 zod 默认值一致)。 */
|
|
512
|
+
function currentVersionOf(memory) {
|
|
513
|
+
const version = Number(memory?.version);
|
|
514
|
+
return Number.isInteger(version) && version > 0 ? version : 1;
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* 版本化创建:写入 memories 行(version=1)并归档一条 v1 历史
|
|
518
|
+
* (changeType 'create')。返回新记忆 id;没有历史表时只写 memories 行。
|
|
519
|
+
*/
|
|
520
|
+
async function createMemoryVersioned(store, workspaceKey, input, now = Date.now()) {
|
|
521
|
+
const memoryId = newId("mem");
|
|
522
|
+
const memory = {
|
|
523
|
+
workspaceKey,
|
|
524
|
+
title: input.title ?? "",
|
|
525
|
+
text: input.text,
|
|
526
|
+
keywords: [...input.tags ?? []],
|
|
527
|
+
...input.key ? { key: input.key } : {},
|
|
528
|
+
...input.collectionId ? { collectionId: input.collectionId } : {},
|
|
529
|
+
sourceSessionId: input.sourceSessionId,
|
|
530
|
+
sourceSeq: input.sourceSeq,
|
|
531
|
+
status: "active",
|
|
532
|
+
version: 1,
|
|
533
|
+
createdAt: now,
|
|
534
|
+
updatedAt: now
|
|
535
|
+
};
|
|
536
|
+
await store.memories.put(memoryId, memory);
|
|
537
|
+
await archiveVersion(store, {
|
|
538
|
+
workspaceKey,
|
|
539
|
+
memoryId,
|
|
540
|
+
version: 1,
|
|
541
|
+
title: memory.title,
|
|
542
|
+
text: memory.text,
|
|
543
|
+
tags: memory.keywords,
|
|
544
|
+
collectionId: input.collectionId,
|
|
545
|
+
updatedAt: now,
|
|
546
|
+
changeType: "create"
|
|
547
|
+
});
|
|
548
|
+
return memoryId;
|
|
549
|
+
}
|
|
550
|
+
function sameText(left, right) {
|
|
551
|
+
return String(left ?? "").trim().toLowerCase() === String(right ?? "").trim().toLowerCase();
|
|
552
|
+
}
|
|
553
|
+
function sameTags(left, right) {
|
|
554
|
+
const a = (left ?? []).map((tag) => String(tag).trim().toLowerCase()).filter(Boolean);
|
|
555
|
+
const b = (right ?? []).map((tag) => String(tag).trim().toLowerCase()).filter(Boolean);
|
|
556
|
+
if (a.length !== b.length) return false;
|
|
557
|
+
const set = new Set(b);
|
|
558
|
+
return a.every((tag) => set.has(tag));
|
|
559
|
+
}
|
|
560
|
+
/** 内容是否变化(正文/标题/标签/集合任一不同即算变化,集合变更也记入历史)。 */
|
|
561
|
+
function contentChanged(memory, patch) {
|
|
562
|
+
if (patch.text !== void 0 && !sameText(memory.text, patch.text)) return true;
|
|
563
|
+
if (patch.title !== void 0 && (patch.title ?? "") !== (memory.title ?? "")) return true;
|
|
564
|
+
if (patch.tags !== void 0 && !sameTags(memory.keywords, patch.tags)) return true;
|
|
565
|
+
if (patch.collectionId !== void 0 && (patch.collectionId ?? "") !== (memory.collectionId ?? "")) return true;
|
|
566
|
+
if (patch.key !== void 0 && (patch.key ?? "") !== (memory.key ?? "")) return true;
|
|
567
|
+
return false;
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* 内容三要素(标题/正文/标签)是否都没变——集合归属另算。
|
|
571
|
+
*
|
|
572
|
+
* 写路径用它做「幂等快速判定」:内容没变时不必去解析集合归属,否则一次
|
|
573
|
+
* 完全相同内容的重写可能顺手新建一个空集合(记忆却没被挂上去)。
|
|
574
|
+
*/
|
|
575
|
+
function memoryContentUnchanged(memory, patch) {
|
|
576
|
+
if (patch.text !== void 0 && !sameText(memory.text, patch.text)) return false;
|
|
577
|
+
if (patch.title !== void 0 && (patch.title ?? "") !== (memory.title ?? "")) return false;
|
|
578
|
+
if (patch.tags !== void 0 && !sameTags(memory.keywords, patch.tags)) return false;
|
|
579
|
+
return true;
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* 版本化就地更新:同 key 不同内容时直接改当前记忆并 version+1,把新版本整体
|
|
583
|
+
* 归档进 memory_versions(旧版本从它创建/上一次更新起就已在档)。
|
|
584
|
+
*
|
|
585
|
+
* 幂等:内容完全相同 → 不升版、不写历史(status 'unchanged')。
|
|
586
|
+
* 记忆不存在 / 不属于该工作区时返回 undefined(调用方自行报错)。
|
|
587
|
+
*/
|
|
588
|
+
async function updateMemoryVersioned(store, workspaceKey, memoryId, patch, now = Date.now()) {
|
|
589
|
+
const memory = store.memories.get(memoryId);
|
|
590
|
+
if (!memory || memory.workspaceKey !== workspaceKey) return void 0;
|
|
591
|
+
const version = currentVersionOf(memory);
|
|
592
|
+
if (!contentChanged(memory, patch)) return {
|
|
593
|
+
status: "unchanged",
|
|
594
|
+
version,
|
|
595
|
+
memoryId
|
|
596
|
+
};
|
|
597
|
+
const next = {
|
|
598
|
+
...memory,
|
|
599
|
+
...patch.text !== void 0 ? { text: patch.text } : {},
|
|
600
|
+
...patch.title !== void 0 ? { title: patch.title } : {},
|
|
601
|
+
...patch.tags !== void 0 ? { keywords: [...patch.tags] } : {},
|
|
602
|
+
...patch.collectionId !== void 0 ? patch.collectionId ? { collectionId: patch.collectionId } : { collectionId: void 0 } : {},
|
|
603
|
+
...patch.key !== void 0 ? patch.key ? { key: patch.key } : { key: void 0 } : {},
|
|
604
|
+
version: version + 1,
|
|
605
|
+
updatedAt: now
|
|
606
|
+
};
|
|
607
|
+
await store.memories.update(memoryId, () => next);
|
|
608
|
+
await archiveVersion(store, {
|
|
609
|
+
workspaceKey,
|
|
610
|
+
memoryId,
|
|
611
|
+
version: next.version,
|
|
612
|
+
title: next.title,
|
|
613
|
+
text: next.text,
|
|
614
|
+
tags: next.keywords,
|
|
615
|
+
collectionId: next.collectionId,
|
|
616
|
+
updatedAt: now,
|
|
617
|
+
changeType: "update"
|
|
618
|
+
});
|
|
619
|
+
return {
|
|
620
|
+
status: "updated",
|
|
621
|
+
version: next.version,
|
|
622
|
+
memoryId
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
/** 归档一条历史版本(内部入口;没有历史表时静默跳过)。 */
|
|
626
|
+
async function archiveVersion(store, row) {
|
|
627
|
+
const table = store.memoryVersions;
|
|
628
|
+
if (!table) return;
|
|
629
|
+
const record = {
|
|
630
|
+
workspaceKey: row.workspaceKey,
|
|
631
|
+
memoryId: row.memoryId,
|
|
632
|
+
version: row.version,
|
|
633
|
+
title: row.title ?? "",
|
|
634
|
+
text: row.text,
|
|
635
|
+
tags: [...row.tags ?? []],
|
|
636
|
+
...row.collectionId ? { collectionId: row.collectionId } : {},
|
|
637
|
+
updatedAt: row.updatedAt,
|
|
638
|
+
changeType: row.changeType
|
|
639
|
+
};
|
|
640
|
+
await table.put(newId("memv"), record);
|
|
641
|
+
}
|
|
642
|
+
/** 一条记忆的全部历史版本(按版本号升序;没有历史表时返回空数组)。 */
|
|
643
|
+
function memoryHistoryOf(store, memoryId) {
|
|
644
|
+
const table = store.memoryVersions;
|
|
645
|
+
if (!table) return [];
|
|
646
|
+
const rows = [];
|
|
647
|
+
for (const [, row] of table.entries()) {
|
|
648
|
+
if (row.memoryId !== memoryId) continue;
|
|
649
|
+
rows.push(row);
|
|
650
|
+
}
|
|
651
|
+
rows.sort((a, b) => a.version - b.version || a.updatedAt - b.updatedAt);
|
|
652
|
+
return rows;
|
|
653
|
+
}
|
|
654
|
+
/** 同一工作区、active、带该 key 的记忆(用于「同 key → 就地更新」判定)。 */
|
|
655
|
+
function findMemoryByKey(store, workspaceKey, key) {
|
|
656
|
+
for (const entry of store.memories.entries()) {
|
|
657
|
+
const [id, memory] = entry;
|
|
658
|
+
if (memory.workspaceKey !== workspaceKey || memory.status !== "active") continue;
|
|
659
|
+
if (memory.key !== key) continue;
|
|
660
|
+
return [id, memory];
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* 惰性迁移:给「没有任何历史行」的旧记忆补一条 v1 历史(changeType 'migrate'),
|
|
665
|
+
* 不改写正文/标题/标签/集合,也不动 version(旧记录读时即 version=1)。
|
|
666
|
+
*
|
|
667
|
+
* 判重按 memoryId 查历史表,所以天然幂等:新写入的记忆create 时已在档,
|
|
668
|
+
* 不会重复补;可以像 migrateFlatMemories 一样在 recall/remember 前调用。
|
|
669
|
+
*/
|
|
670
|
+
async function migrateMemoryVersions(store, workspaceKey, now = Date.now()) {
|
|
671
|
+
const table = store.memoryVersions;
|
|
672
|
+
if (!table) return { migrated: 0 };
|
|
673
|
+
const seen = /* @__PURE__ */ new Set();
|
|
674
|
+
for (const [, row] of table.entries()) {
|
|
675
|
+
if (row.workspaceKey !== workspaceKey) continue;
|
|
676
|
+
seen.add(row.memoryId);
|
|
677
|
+
}
|
|
678
|
+
let migrated = 0;
|
|
679
|
+
for (const [id, memory] of store.memories.entries()) {
|
|
680
|
+
if (memory.workspaceKey !== workspaceKey) continue;
|
|
681
|
+
if (seen.has(id)) continue;
|
|
682
|
+
await archiveVersion(store, {
|
|
683
|
+
workspaceKey,
|
|
684
|
+
memoryId: id,
|
|
685
|
+
version: currentVersionOf(memory),
|
|
686
|
+
title: memory.title ?? "",
|
|
687
|
+
text: memory.text,
|
|
688
|
+
tags: memory.keywords ?? [],
|
|
689
|
+
collectionId: memory.collectionId,
|
|
690
|
+
updatedAt: memory.updatedAt ?? now,
|
|
691
|
+
changeType: "migrate"
|
|
692
|
+
});
|
|
693
|
+
migrated += 1;
|
|
694
|
+
}
|
|
695
|
+
return { migrated };
|
|
696
|
+
}
|
|
697
|
+
/** Prefix of every host-native session the plugin creates as a hub (`newId('session')` in panel.ts). */
|
|
698
|
+
const HUB_ID_PREFIX = "session-";
|
|
699
|
+
/**
|
|
700
|
+
* R31 需求①: the historical flavour prefix of plugin hub titles
|
|
701
|
+
* (`SuperMemory 中枢 · <id4>`). R41 stopped GENERATING it — a session name is now
|
|
702
|
+
* a direct description of its work — but the constant stays because the one-time
|
|
703
|
+
* migrations still recognize those old rows (hub records + rename pass).
|
|
704
|
+
*/
|
|
705
|
+
const HUB_TITLE_PREFIX = "SuperMemory 中枢";
|
|
706
|
+
/** The pre-R31 hub title prefix ('新会话 · <id4>'); hub-title-migration renames it. */
|
|
707
|
+
const LEGACY_HUB_TITLE_PREFIX = "新会话";
|
|
708
|
+
/**
|
|
709
|
+
* R42: does this HOST title still carry a legacy shape the plugin no longer
|
|
710
|
+
* generates? Two patterns: the brand prefix (SuperMemory 中枢 · <id4>, with or
|
|
711
|
+
* without the id token) and the pre-R31 neutral format (新会话 · <id4>). A bare
|
|
712
|
+
* 「新会话」 is the CURRENT neutral name (R41) and is NOT legacy — this
|
|
713
|
+
* distinction keeps the rail fallback from fighting an already-clean title.
|
|
714
|
+
*/
|
|
715
|
+
function isLegacyHubTitle(title) {
|
|
716
|
+
const value = String(title ?? "").trim();
|
|
717
|
+
if (!value) return false;
|
|
718
|
+
if (value.startsWith("SuperMemory 中枢")) return true;
|
|
719
|
+
return (/* @__PURE__ */ new RegExp("^新会话\\s*·\\s*.+$")).test(value);
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* R42: the DURABLE title the plugin recorded for one hub session — the
|
|
723
|
+
* positive hub_sessions row first, the topic-set root member title second. A
|
|
724
|
+
* pure store read (no live session, no host seam), so the rail can show the
|
|
725
|
+
* recorded name even while the host still carries a legacy title for a session
|
|
726
|
+
* that has not been opened since the rename.
|
|
727
|
+
*/
|
|
728
|
+
function durableHubTitle(store, sessionId) {
|
|
729
|
+
if (!store || !sessionId) return "";
|
|
730
|
+
try {
|
|
731
|
+
const row = store.hubs.get(sessionId);
|
|
732
|
+
if (row && typeof row.title === "string" && row.title.trim()) return row.title.trim();
|
|
733
|
+
} catch {}
|
|
734
|
+
try {
|
|
735
|
+
for (const [, topicSet] of store.topicsets.entries()) for (const member of topicSet.members) {
|
|
736
|
+
if (member.sessionId !== sessionId || member.kind !== "root") continue;
|
|
737
|
+
if (typeof member.title === "string" && member.title.trim()) return member.title.trim();
|
|
738
|
+
}
|
|
739
|
+
} catch {}
|
|
740
|
+
return "";
|
|
741
|
+
}
|
|
742
|
+
/** The readable label of a workspace path: its last segment (no drive/UNC). */
|
|
743
|
+
function workspaceLabel(cwd) {
|
|
744
|
+
const value = String(cwd ?? "").replace(/[\\/]+$/, "");
|
|
745
|
+
if (!value) return "";
|
|
746
|
+
const segments = value.split(/[\\/]/).filter((segment) => segment.length > 0);
|
|
747
|
+
return segments.length > 0 ? segments[segments.length - 1] : "";
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* R41 需求③ / R43 需求②③: the title a plugin-created hub session gets.
|
|
751
|
+
*
|
|
752
|
+
* R41 named it after the work alone, so a hub opened before its first message
|
|
753
|
+
* (sidebar 新建会话 / 「+新中枢会话」 with an empty composer) showed the bare
|
|
754
|
+
* neutral 「新会话」 — which says nothing about the session, and (see R43 ①)
|
|
755
|
+
* even made the shell's New-session capture interceptor treat the chat card of
|
|
756
|
+
* such a hub as a 新建会话 control. R43 makes the name meaningful by default:
|
|
757
|
+
*
|
|
758
|
+
* `<工作区名> · <主题/首条消息摘要>` (clipped to {@link HUB_TITLE_MAX_CHARS})
|
|
759
|
+
* `<工作区名> · 新会话` (no topic yet — still says WHICH workspace)
|
|
760
|
+
*
|
|
761
|
+
* No brand prefix and no id token. When no workspace path is available the
|
|
762
|
+
* shape degrades to the topic alone / the bare fallback, exactly as R41 did.
|
|
763
|
+
*
|
|
764
|
+
* @param _sessionId - kept in the signature for callers/tests; an id suffix is
|
|
765
|
+
* not a description and is never part of the title.
|
|
766
|
+
* @param firstMessage - opening message used as the work summary.
|
|
767
|
+
* @param cwd - workspace path (or its canonical key) for the label.
|
|
768
|
+
*/
|
|
769
|
+
function hubSessionTitle(sessionId, firstMessage = "", cwd = "") {
|
|
770
|
+
const workspace = workspaceLabel(cwd);
|
|
771
|
+
const topic = describeSessionTitle(firstMessage, 48);
|
|
772
|
+
if (topic && topic !== "新会话") return workspace ? clipEllipsis(`${workspace} · ${topic}`, 60) : topic;
|
|
773
|
+
return workspace ? `${workspace} · ${TITLE_FALLBACK}` : TITLE_FALLBACK;
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* R43 需求②: does this title carry NO topic — i.e. is it the neutral default of
|
|
777
|
+
* ANY generation? The upgrade paths (panel send, first-message event hook and
|
|
778
|
+
* the startup rename pass) use it so they never overwrite a name a person or
|
|
779
|
+
* the host title service chose. Recognised neutral shapes:
|
|
780
|
+
* - empty / the bare fallback 「新会话」;
|
|
781
|
+
* - the R31 brand prefix 「SuperMemory 中枢 …」 and the pre-R31 「新会话 · id」;
|
|
782
|
+
* - the R43 default `<工作区名> · 新会话` (with the caller's workspace, or any
|
|
783
|
+
* workspace when the path is unknown).
|
|
784
|
+
*/
|
|
785
|
+
function isNeutralHubTitle(title, cwd = "") {
|
|
786
|
+
const value = String(title ?? "").trim();
|
|
787
|
+
if (!value) return true;
|
|
788
|
+
if (value === "新会话") return true;
|
|
789
|
+
if (value.startsWith("SuperMemory 中枢")) return true;
|
|
790
|
+
if (/^新会话\s*·/.test(value)) return true;
|
|
791
|
+
const workspace = workspaceLabel(cwd);
|
|
792
|
+
if (workspace) return value === `${workspace} · ${TITLE_FALLBACK}`;
|
|
793
|
+
return /·\s*新会话$/.test(value);
|
|
794
|
+
}
|
|
795
|
+
/**
|
|
796
|
+
* Is this id minted by the plugin as a WORK BRANCH? Fresh dispatches use
|
|
797
|
+
* `branch-*` and forks `fork-*`. This is the static half of the hub/branch
|
|
798
|
+
* rule: dispatch records a fresh branch with `kind:'root'` (it is a root of its
|
|
799
|
+
* own new session, not a fork), so `kind` alone cannot distinguish it from a
|
|
800
|
+
* topic-set hub. The prefix can.
|
|
801
|
+
*/
|
|
802
|
+
function isPluginBranchId(sessionId) {
|
|
803
|
+
return sessionId.startsWith("branch-") || sessionId.startsWith("fork-");
|
|
804
|
+
}
|
|
805
|
+
function serviceOf(ctx, name) {
|
|
806
|
+
try {
|
|
807
|
+
return ctx.get?.(name);
|
|
808
|
+
} catch {
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Build the "is this session running right now?" probe for the rail's dot.
|
|
814
|
+
*
|
|
815
|
+
* `Agent.status` is the host's ONLY positive activity signal (`idle` ⇄
|
|
816
|
+
* `running`; agent disposal removes the registry entry — see dsh-agent
|
|
817
|
+
* runtime-types). Session attachment (`ctx.sessions` / `sessionQuery` `live`) is
|
|
818
|
+
* NOT activity: a session that ended its turn stays attached, which is exactly
|
|
819
|
+
* why the old `live` mapping showed green dots on ended conversations.
|
|
820
|
+
*
|
|
821
|
+
* One `agents.list()` enumeration is preferred (O(sessions)); a host that only
|
|
822
|
+
* exposes `agents.get()` degrades to one lookup per row. Every failure mode —
|
|
823
|
+
* no agents service, a thrown lookup, a malformed value — answers `false`,
|
|
824
|
+
* because the requirement is "unknown stays dark".
|
|
825
|
+
*/
|
|
826
|
+
function runningProbe(ctx) {
|
|
827
|
+
if (!ctx) return () => false;
|
|
828
|
+
const agents = serviceOf(ctx, "agents");
|
|
829
|
+
if (!agents) return () => false;
|
|
830
|
+
try {
|
|
831
|
+
if (typeof agents.list === "function") {
|
|
832
|
+
const rows = agents.list();
|
|
833
|
+
if (Array.isArray(rows)) {
|
|
834
|
+
const running = /* @__PURE__ */ new Set();
|
|
835
|
+
for (const agent of rows) {
|
|
836
|
+
if (agent?.status !== "running") continue;
|
|
837
|
+
const id = String(agent.id ?? "");
|
|
838
|
+
if (id) running.add(id);
|
|
839
|
+
}
|
|
840
|
+
return (sessionId) => running.has(sessionId);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
} catch {}
|
|
844
|
+
const get = agents.get;
|
|
845
|
+
if (typeof get !== "function") return () => false;
|
|
846
|
+
return (sessionId) => {
|
|
847
|
+
try {
|
|
848
|
+
return get.call(agents, sessionId)?.status === "running";
|
|
849
|
+
} catch {
|
|
850
|
+
return false;
|
|
851
|
+
}
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Every FORK member id of any topic set (archived sets included) — the actual
|
|
856
|
+
* branch sessions. Root members are the topic-set's own hub conversation and
|
|
857
|
+
* must stay in the rail.
|
|
858
|
+
*/
|
|
859
|
+
function topicSetBranchIds(store) {
|
|
860
|
+
const ids = /* @__PURE__ */ new Set();
|
|
861
|
+
if (!store) return ids;
|
|
862
|
+
for (const [, topicSet] of store.topicsets.entries()) for (const member of topicSet.members) if (member.kind === "fork") ids.add(member.sessionId);
|
|
863
|
+
return ids;
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* The active topic set that owns one session as its ROOT member, newest
|
|
867
|
+
* `lastActiveAt` first. Used to badge a hub conversation with its set.
|
|
868
|
+
*/
|
|
869
|
+
function topicSetOfRootMember(store, sessionId) {
|
|
870
|
+
if (!store) return void 0;
|
|
871
|
+
let best;
|
|
872
|
+
for (const [id, topicSet] of store.topicsets.entries()) {
|
|
873
|
+
if (topicSet.status !== "active") continue;
|
|
874
|
+
for (const member of topicSet.members) {
|
|
875
|
+
if (member.sessionId !== sessionId || member.kind !== "root") continue;
|
|
876
|
+
if (!best || member.lastActiveAt > best.at) best = {
|
|
877
|
+
id,
|
|
878
|
+
title: topicSet.title,
|
|
879
|
+
at: member.lastActiveAt
|
|
880
|
+
};
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
return best ? {
|
|
884
|
+
id: best.id,
|
|
885
|
+
title: best.title
|
|
886
|
+
} : void 0;
|
|
887
|
+
}
|
|
888
|
+
/** A fallback title when the title seam is unavailable. */
|
|
889
|
+
function fallbackTitle(sessionId) {
|
|
890
|
+
return `未命名会话 ${sessionId.slice(-4)}`;
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* Distinct branch sessions one hub dispatched into, and how many of those still
|
|
894
|
+
* have an open dispatch. Reads the dispatch table (the existing hub↔branch
|
|
895
|
+
* relation) instead of adding a second bookkeeping row.
|
|
896
|
+
*/
|
|
897
|
+
function branchStatsOf(store, hubSessionId) {
|
|
898
|
+
if (!store) return {
|
|
899
|
+
total: 0,
|
|
900
|
+
working: 0
|
|
901
|
+
};
|
|
902
|
+
const all = /* @__PURE__ */ new Set();
|
|
903
|
+
const working = /* @__PURE__ */ new Set();
|
|
904
|
+
for (const [, row] of store.dispatches.entries()) {
|
|
905
|
+
if (row.hubSessionId !== hubSessionId) continue;
|
|
906
|
+
const branchId = String(row.branchSessionId ?? "");
|
|
907
|
+
if (!branchId) continue;
|
|
908
|
+
all.add(branchId);
|
|
909
|
+
if (isOpenDispatch(row)) working.add(branchId);
|
|
910
|
+
}
|
|
911
|
+
return {
|
|
912
|
+
total: all.size,
|
|
913
|
+
working: working.size
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* List the hub sessions of one workspace, newest activity first.
|
|
918
|
+
*
|
|
919
|
+
* R35: despite the historical name/field (`origin: 'hub'`), this is a discovery
|
|
920
|
+
* list — see the module header ("DISCOVERY VIEW, NOT ROLE AUTHORITY"). Role
|
|
921
|
+
* authority is resolveRole only.
|
|
922
|
+
*
|
|
923
|
+
* @param ctx - host context (sessionQuery/sessions are read with `get`).
|
|
924
|
+
* @param store - the plugin store (topic-set membership + workspace facts).
|
|
925
|
+
* @param cwd - workspace root the panel currently points at.
|
|
926
|
+
* @param limit - maximum rows (default {@link HUB_SESSION_LIMIT}).
|
|
927
|
+
*/
|
|
928
|
+
async function listHubSessions(ctx, store, cwd, limit = 50) {
|
|
929
|
+
if (!ctx || !cwd) return [];
|
|
930
|
+
const workspaceKey = workspaceKeyOf(cwd);
|
|
931
|
+
const branchIds = topicSetBranchIds(store);
|
|
932
|
+
let records;
|
|
933
|
+
const query = serviceOf(ctx, "sessionQuery");
|
|
934
|
+
if (query && typeof query.listSessions === "function") try {
|
|
935
|
+
records = await query.listSessions();
|
|
936
|
+
} catch {
|
|
937
|
+
records = void 0;
|
|
938
|
+
}
|
|
939
|
+
if (!records) try {
|
|
940
|
+
const live = serviceOf(ctx, "sessions");
|
|
941
|
+
records = (typeof live?.list === "function" ? live.list() : []).map((session) => ({
|
|
942
|
+
header: session.header ?? { id: session.id },
|
|
943
|
+
live: true,
|
|
944
|
+
persisted: false
|
|
945
|
+
}));
|
|
946
|
+
} catch {
|
|
947
|
+
records = [];
|
|
948
|
+
}
|
|
949
|
+
const hubs = [];
|
|
950
|
+
for (const record of records) {
|
|
951
|
+
const header = record?.header ?? {};
|
|
952
|
+
const sessionId = String(header.id ?? "");
|
|
953
|
+
if (!sessionId) continue;
|
|
954
|
+
if (!header.cwd || workspaceKeyOf(header.cwd) !== workspaceKey) continue;
|
|
955
|
+
if (header.parentSession) continue;
|
|
956
|
+
if (header.origin === "subagent") continue;
|
|
957
|
+
if (isPluginBranchId(sessionId)) continue;
|
|
958
|
+
if (branchIds.has(sessionId)) continue;
|
|
959
|
+
hubs.push({
|
|
960
|
+
record,
|
|
961
|
+
sessionId
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
if (hubs.length === 0) return [];
|
|
965
|
+
const titles = /* @__PURE__ */ new Map();
|
|
966
|
+
if (query && typeof query.readTitleSnapshots === "function") try {
|
|
967
|
+
const observations = await query.readTitleSnapshots(hubs.map((hub) => hub.sessionId));
|
|
968
|
+
for (const observation of observations) {
|
|
969
|
+
if (!observation || observation.status !== "fulfilled") continue;
|
|
970
|
+
const sessionId = String(observation.sessionId ?? "");
|
|
971
|
+
const title = observation.value?.title?.title;
|
|
972
|
+
if (!sessionId || typeof title !== "string" || !title.trim()) continue;
|
|
973
|
+
titles.set(sessionId, {
|
|
974
|
+
title: title.trim(),
|
|
975
|
+
...typeof observation.value?.title?.updatedAt === "number" ? { updatedAt: observation.value.title.updatedAt } : {}
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
} catch {}
|
|
979
|
+
const isRunning = runningProbe(ctx);
|
|
980
|
+
const rows = hubs.map(({ record, sessionId }) => {
|
|
981
|
+
const title = titles.get(sessionId);
|
|
982
|
+
const createdAt = typeof record.header.createdAt === "number" ? record.header.createdAt : 0;
|
|
983
|
+
const sessionCwd = String(record.header.cwd ?? cwd);
|
|
984
|
+
const owner = topicSetOfRootMember(store, sessionId);
|
|
985
|
+
const branchStats = branchStatsOf(store, sessionId);
|
|
986
|
+
const hostTitle = title?.title ?? fallbackTitle(sessionId);
|
|
987
|
+
const durable = durableHubTitle(store, sessionId);
|
|
988
|
+
return {
|
|
989
|
+
sessionId,
|
|
990
|
+
title: (isLegacyHubTitle(hostTitle) || isNeutralHubTitle(hostTitle, sessionCwd)) && durable ? describeSessionTitle(durable) || hostTitle : hostTitle,
|
|
991
|
+
live: isRunning(sessionId),
|
|
992
|
+
online: record.live === true,
|
|
993
|
+
updatedAt: title?.updatedAt ?? createdAt,
|
|
994
|
+
createdAt,
|
|
995
|
+
origin: "hub",
|
|
996
|
+
cwd: sessionCwd,
|
|
997
|
+
workspaceKey: workspaceKeyOf(sessionCwd),
|
|
998
|
+
...owner ? {
|
|
999
|
+
topicSetId: owner.id,
|
|
1000
|
+
topicSetTitle: owner.title
|
|
1001
|
+
} : {},
|
|
1002
|
+
branches: branchStats.total,
|
|
1003
|
+
workingBranches: branchStats.working
|
|
1004
|
+
};
|
|
1005
|
+
});
|
|
1006
|
+
rows.sort((a, b) => b.updatedAt - a.updatedAt || b.createdAt - a.createdAt);
|
|
1007
|
+
const cap = Math.max(1, Math.min(50, Number(limit) || 50));
|
|
1008
|
+
return rows.slice(0, cap);
|
|
1009
|
+
}
|
|
1010
|
+
export { currentSessionTitle as A, listWorkspaceBranches as C, applySessionTitle as D, taskExcerpt as E, sessionTitleOf as F, ensureMemberTitle as M, firstLine as N, cleanTitleText as O, sessionTitleFor as P, listTopicSetBranches as S, renderHubBranchesCard as T, hubsByBranch as _, isLegacyHubTitle as a, latestTaskByBranch as b, listHubSessions as c, findMemoryByKey as d, memoryContentUnchanged as f, updateMemoryVersioned as g, migrateMemoryVersions as h, hubSessionTitle as i, describeSessionTitle as j, clipEllipsis as k, createMemoryVersioned as l, memoryVersionsSupported as m, HUB_TITLE_PREFIX as n, isNeutralHubTitle as o, memoryHistoryOf as p, LEGACY_HUB_TITLE_PREFIX as r, isPluginBranchId as s, HUB_ID_PREFIX as t, currentVersionOf as u, isHubSession as v, relativeAgo as w, listHubBranches as x, isOpenDispatch as y };
|