@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.
@@ -0,0 +1,313 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.js";
2
+ import { t as newId } from "./store-DD2L3GDr.js";
3
+ import { i as clipWithNote, m as topicSetIdsOf, n as clipAtBoundary, r as clipMarked } from "./clip-kqqR05NC.js";
4
+ // src/questions.ts
5
+ /** Dispatch states that no longer own the branch's work. */
6
+ const TERMINAL = /* @__PURE__ */ new Set([
7
+ "delivered",
8
+ "failed",
9
+ "interrupted"
10
+ ]);
11
+ /**
12
+ * Structural view of the questions table that tolerates a partial store
13
+ * (older test double / a medium opened before the table existed). Every reader
14
+ * goes through this instead of assuming `store.questions`.
15
+ */
16
+ function questionsOf(store) {
17
+ return store?.questions;
18
+ }
19
+ /** The dispatch a branch currently belongs to, preferring a still-open one. */
20
+ function dispatchOfBranch(store, branchSessionId) {
21
+ let newest;
22
+ let newestOpen;
23
+ for (const [dispatchId, record] of store.dispatches.entries()) {
24
+ if (record.branchSessionId !== branchSessionId) continue;
25
+ if (!newest || record.createdAt >= newest[1].createdAt) newest = [dispatchId, record];
26
+ if (TERMINAL.has(String(record.status))) continue;
27
+ if (!newestOpen || record.createdAt >= newestOpen[1].createdAt) newestOpen = [dispatchId, record];
28
+ }
29
+ return newestOpen ?? newest;
30
+ }
31
+ /** Open questions of one dispatch, oldest first. */
32
+ function openQuestionsOfDispatch(store, dispatchId) {
33
+ const table = questionsOf(store);
34
+ if (!table || !store) return [];
35
+ const rows = [];
36
+ for (const [, question] of table.entries()) {
37
+ if (question.status !== "open" || question.dispatchId !== dispatchId) continue;
38
+ rows.push(question);
39
+ }
40
+ rows.sort((a, b) => a.createdAt - b.createdAt);
41
+ return rows;
42
+ }
43
+ /** Open questions of one parallel group (all members), oldest first. */
44
+ function openQuestionsOfGroup(store, groupId) {
45
+ const table = questionsOf(store);
46
+ if (!table || !store) return [];
47
+ const rows = [];
48
+ for (const [, question] of table.entries()) {
49
+ if (question.status !== "open" || question.groupId !== groupId) continue;
50
+ rows.push(question);
51
+ }
52
+ rows.sort((a, b) => a.createdAt - b.createdAt);
53
+ return rows;
54
+ }
55
+ /**
56
+ * Open questions visible to one hub: everything whose topic set belongs to the
57
+ * hub's workspace, plus anything dispatched by this very hub (a dispatch always
58
+ * resolves a topic set, so the second arm is only a safety net).
59
+ */
60
+ function questionsForHub(store, workspaceKey, hubSessionId, status = "open") {
61
+ const table = questionsOf(store);
62
+ if (!table || !store) return [];
63
+ const ownSets = topicSetIdsOf(store, workspaceKey);
64
+ const rows = [];
65
+ for (const [id, question] of table.entries()) {
66
+ if (status !== "all" && question.status !== status) continue;
67
+ if (!(question.topicSetId ? ownSets.has(question.topicSetId) : false) && (!hubSessionId || question.hubSessionId !== hubSessionId)) continue;
68
+ rows.push({
69
+ id,
70
+ question
71
+ });
72
+ }
73
+ rows.sort((a, b) => a.question.createdAt - b.question.createdAt);
74
+ return rows;
75
+ }
76
+ function normalizeSeverity(raw) {
77
+ return raw === "low" || raw === "high" ? raw : "medium";
78
+ }
79
+ /**
80
+ * Normalise one stored string to its budget.
81
+ *
82
+ * R47: the LONG fields (question / progress / defaultPlan / answer) are clipped
83
+ * at a sentence boundary with an omission note instead of a raw `slice` — the
84
+ * hub reads these verbatim in the relay block, and a mid-sentence cut hid the
85
+ * fact that anything was missing. Short label fields keep the plain clip (a
86
+ * note would overwhelm them). Stored notes carry no re-fetch clue (`hint: ''`):
87
+ * a question is not a memory.
88
+ */
89
+ function clip(raw, max) {
90
+ return String(raw ?? "").trim().slice(0, max);
91
+ }
92
+ function clipLong(raw, max) {
93
+ const text = String(raw ?? "").trim();
94
+ if (Array.from(text).length <= max) return text;
95
+ return clipWithNote(text, max, "");
96
+ }
97
+ /**
98
+ * Persist one branch question against the dispatch that owns the branch.
99
+ *
100
+ * Refuses when the caller is not a branch: a hub that needs a user decision
101
+ * must use `ask_user_question` directly, never this channel (the hub is the one
102
+ * that aggregates, so a hub question stored here would never be asked).
103
+ */
104
+ async function raiseQuestion(store, branchSessionId, input) {
105
+ const table = questionsOf(store);
106
+ if (!table) return {
107
+ status: "error",
108
+ message: "问题存储不可用(存储域未打开),问题未上交;请把该问题写进最终汇报。"
109
+ };
110
+ const found = dispatchOfBranch(store, branchSessionId);
111
+ if (!found) return {
112
+ status: "error",
113
+ message: "memory_raise_question 仅分支会话使用:当前会话没有对应的派发记录。中枢需要用户裁决时直接用 ask_user_question;不需要裁决时按最合理解释继续。"
114
+ };
115
+ const [dispatchId, dispatch] = found;
116
+ const title = clip(input.title, 80);
117
+ const text = clipLong(input.question, 2e3);
118
+ if (!title) return {
119
+ status: "error",
120
+ message: "title 不能为空:给出一句可扫读的问题标题。"
121
+ };
122
+ if (!text) return {
123
+ status: "error",
124
+ message: "question 不能为空:写清要用户裁决什么。"
125
+ };
126
+ const options = (input.options ?? []).map((option) => clipMarked(option, 120)).filter(Boolean).slice(0, 8);
127
+ const blocking = input.blocking === true;
128
+ const now = Date.now();
129
+ const questionId = newId("q");
130
+ const record = {
131
+ dispatchId,
132
+ ...dispatch.groupId ? { groupId: dispatch.groupId } : {},
133
+ ...dispatch.topicSetId ? { topicSetId: dispatch.topicSetId } : {},
134
+ branchSessionId,
135
+ ...dispatch.hubSessionId ? { hubSessionId: dispatch.hubSessionId } : {},
136
+ branchTask: clipMarked(dispatch.task, 200),
137
+ title,
138
+ question: text,
139
+ options,
140
+ severity: normalizeSeverity(input.severity),
141
+ blocking,
142
+ progress: clipLong(input.progress, 1500),
143
+ defaultPlan: clipLong(input.defaultPlan, 1e3),
144
+ status: "open",
145
+ createdAt: now,
146
+ updatedAt: now
147
+ };
148
+ await table.put(questionId, record);
149
+ return {
150
+ status: "recorded",
151
+ questionId,
152
+ dispatchId,
153
+ blocking,
154
+ message: blocking ? `已上交中枢(${questionId})。这是阻塞问题:中枢汇总所有分支的问题后一次性向用户提问。请结束本轮并在汇报里写清已完成的进度与默认备选方案,不要在本分支里等待用户。` : `已上交中枢(${questionId})。blocking=false:不要等待用户,继续按最合理解释推进并完成实质工作,把做出的假设写进最终汇报。`
155
+ };
156
+ }
157
+ /** Mark questions resolved, optionally recording the user's answer. */
158
+ async function resolveQuestions(store, ids, answer) {
159
+ const table = questionsOf(store);
160
+ if (!table) return 0;
161
+ let resolved = 0;
162
+ const takenAnswer = clipLong(answer, 2e3);
163
+ for (const id of ids) {
164
+ const row = table.get(id);
165
+ if (!row || row.status === "resolved") continue;
166
+ await table.update(id, (record) => ({
167
+ ...record,
168
+ status: "resolved",
169
+ ...takenAnswer ? { answer: takenAnswer } : {},
170
+ updatedAt: Date.now()
171
+ }));
172
+ resolved++;
173
+ }
174
+ return resolved;
175
+ }
176
+ /** One rendered line block per question, shared by relays and the hub listing. */
177
+ function questionLines(question) {
178
+ const lines = [`- ${question.blocking ? "[阻塞]" : "[非阻塞]"} ${question.title}:${question.question}`];
179
+ if (question.options.length > 0) lines.push(` 可选:${question.options.join(" / ")}`);
180
+ if (question.progress) lines.push(` 已完成:${question.progress}`);
181
+ if (question.defaultPlan) lines.push(` 默认备选:${question.defaultPlan}`);
182
+ return lines;
183
+ }
184
+ /**
185
+ * The relay block a hub sees after a dispatch/group settles. Empty when the
186
+ * branch raised nothing, so existing relay texts stay byte-identical.
187
+ */
188
+ function renderQuestionsBlock(questions, title = "本分支上交的问题(中枢汇总后统一向用户提问):") {
189
+ if (questions.length === 0) return "";
190
+ const blocking = questions.filter((question) => question.blocking).length;
191
+ const lines = [`[supermemory-questions] ${title} 共 ${questions.length} 个(阻塞 ${blocking} / 非阻塞 ${questions.length - blocking})。`];
192
+ for (const question of questions) lines.push(...questionLines(question));
193
+ lines.push("请中枢调用 memory_questions 汇总所有分支的问题,用 ask_user_question 一次向用户提问;不要逐个转发。");
194
+ return lines.join("\n");
195
+ }
196
+ /** Hub-facing listing rows of `memory_questions`, including the source branch. */
197
+ function renderQuestionList(rows) {
198
+ if (rows.length === 0) return "(当前工作区没有待处理的已上交问题)";
199
+ const blocking = rows.filter((row) => row.question.blocking).length;
200
+ const lines = [`待处理问题 ${rows.length} 个(阻塞 ${blocking} / 非阻塞 ${rows.length - blocking}):`];
201
+ for (const row of rows) {
202
+ const question = row.question;
203
+ const task = question.branchTask ? ` · 分支任务「${clipMarked(question.branchTask, 40)}」` : "";
204
+ lines.push(`${question.blocking ? "⛔" : "•"} ${question.title}(${question.branchSessionId}${task})`);
205
+ lines.push(` ${question.question}`);
206
+ if (question.options.length > 0) lines.push(` 可选:${question.options.join(" / ")}`);
207
+ if (question.progress) lines.push(` 已完成:${question.progress}`);
208
+ if (question.defaultPlan) lines.push(` 默认备选:${question.defaultPlan}`);
209
+ if (question.severity !== "medium") lines.push(` 严重度:${question.severity}`);
210
+ }
211
+ lines.push("请去重、按主题合并后,用一次 ask_user_question 向用户提问;用户答复后把裁决派回对应分支(memory_dispatch)。");
212
+ return lines.join("\n");
213
+ }
214
+ // src/relay-text.ts
215
+ /**
216
+ * Relay safety valve, NOT a content policy: an answer larger than this is a
217
+ * runaway turn, and pushing it whole into the hub's context would crowd out
218
+ * everything else. The marker says so and names where the rest lives, instead
219
+ * of silently cutting the branch's work the way the old 400-char clip did.
220
+ */
221
+ const RELAY_RESULT_MAX_CHARS = 65536;
222
+ /** The branch's full answer: `result`, falling back to the short `summary` for
223
+ * episodes written before `result` existed. */
224
+ function episodeResult(episode) {
225
+ return episode?.result || episode?.summary || "";
226
+ }
227
+ /**
228
+ * Clip a relay body at the safety valve, saying so instead of cutting silently.
229
+ *
230
+ * R47: the cut now lands on a sentence boundary (the old raw `slice` could stop
231
+ * mid-sentence) and the note reports both sizes plus where the full answer
232
+ * lives, so a clipped result is visibly a clip and remains recoverable.
233
+ */
234
+ function clipRelayResult(text, branchSessionId) {
235
+ const source = String(text ?? "");
236
+ if (Array.from(source).length <= 65536) return source;
237
+ const kept = clipAtBoundary(source, RELAY_RESULT_MAX_CHARS);
238
+ const omitted = Array.from(source).length - Array.from(kept).length;
239
+ return `${kept}\n……(结果超过 ${RELAY_RESULT_MAX_CHARS} 字,已省略 ${omitted} 字,已截断;完整内容见分支会话 ${branchSessionId} 的记录)`;
240
+ }
241
+ // src/group.ts
242
+ var group_exports = /* @__PURE__ */ __exportAll({ groupMembers: () => groupMembers });
243
+ /** Members of one group, in creation order. */
244
+ function groupMembers(store, groupId) {
245
+ const out = [];
246
+ for (const [dispatchId, record] of store.dispatches.entries()) if (record.groupId === groupId) out.push([dispatchId, record]);
247
+ out.sort((a, b) => a[1].createdAt - b[1].createdAt);
248
+ return out;
249
+ }
250
+ /**
251
+ * Dispatch states that end a member's life. `interrupted` (timeout / stop /
252
+ * plugin reload) is terminal exactly like `failed`: excluding it kept
253
+ * `groupComplete` false forever, so one silent member withheld the WHOLE group's
254
+ * single relay. It is still annotated as an interruption, never as success.
255
+ */
256
+ const TERMINAL_MEMBER_STATUSES = /* @__PURE__ */ new Set([
257
+ "delivered",
258
+ "failed",
259
+ "interrupted"
260
+ ]);
261
+ /** True when every member reached a terminal state. */
262
+ function groupComplete(store, groupId) {
263
+ const members = groupMembers(store, groupId);
264
+ if (members.length === 0) return false;
265
+ return members.every(([, record]) => TERMINAL_MEMBER_STATUSES.has(record.status));
266
+ }
267
+ /** The hub-facing group relay text: one line per member, failures/interrupts annotated. */
268
+ function groupRelayText(store, groupId, episodes) {
269
+ const members = groupMembers(store, groupId);
270
+ const lines = [`[supermemory-group-relay ${groupId}]`, `共 ${members.length} 个分支任务:`];
271
+ let ok = 0;
272
+ let failed = 0;
273
+ let interrupted = 0;
274
+ members.forEach(([, record], index) => {
275
+ const label = clipMarked(record.task, 40);
276
+ if (record.status === "delivered") {
277
+ ok++;
278
+ const summary = episodes.get(record.branchSessionId) ?? "(已完成)";
279
+ lines.push(`${index + 1}. ✅ ${label}\n ${summary}`);
280
+ } else if (record.status === "interrupted") {
281
+ interrupted++;
282
+ lines.push(`${index + 1}. ⏹ ${label}\n 中断终态:${record.turnEndReason ?? "unknown"}(未伪装成答案)`);
283
+ } else {
284
+ failed++;
285
+ lines.push(`${index + 1}. ❌ ${label}\n 失败终态:${record.turnEndReason ?? "unknown"}(未伪装成答案)`);
286
+ }
287
+ });
288
+ lines.push(`汇总:${ok} 成功 / ${failed} 失败 / ${interrupted} 中断。`);
289
+ const questions = renderQuestionsBlock(openQuestionsOfGroup(store, groupId), "并行组各分支上交的问题(中枢汇总后统一向用户提问):");
290
+ if (questions) lines.push("", questions);
291
+ return lines.join("\n");
292
+ }
293
+ /** Collect the episode results (full answers) of a group's delivered members. */
294
+ function groupEpisodeSummaries(store, groupId) {
295
+ const out = /* @__PURE__ */ new Map();
296
+ const members = groupMembers(store, groupId);
297
+ const branchIds = new Set(members.map(([, r]) => r.branchSessionId));
298
+ for (const [, episode] of store.episodes.entries()) {
299
+ const text = episodeResult(episode);
300
+ if (episode.branchSessionId && branchIds.has(episode.branchSessionId) && text) out.set(episode.branchSessionId, clipRelayResult(text, episode.branchSessionId));
301
+ }
302
+ return out;
303
+ }
304
+ /** Whether a group relay was already enqueued (idempotency guard). */
305
+ function groupRelayExists(store, groupId) {
306
+ for (const [, item] of store.outbox.entries()) if (item.groupId === groupId) return true;
307
+ return false;
308
+ }
309
+ /** Stable group id for a dispatch round. */
310
+ function newGroupId() {
311
+ return newId("grp");
312
+ }
313
+ export { groupRelayText as a, clipRelayResult as c, questionsForHub as d, raiseQuestion as f, resolveQuestions as h, groupRelayExists as i, episodeResult as l, renderQuestionsBlock as m, groupEpisodeSummaries as n, group_exports as o, renderQuestionList as p, groupMembers as r, newGroupId as s, groupComplete as t, openQuestionsOfDispatch as u };