dsh-talk-map 0.0.0-stage → 0.1.3
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/LICENSE +21 -0
- package/README.md +60 -2
- package/README.zh.md +61 -0
- package/client/client.js +15064 -0
- package/cordis.patch.yml +7 -0
- package/lib/index.js +1236 -0
- package/package.json +85 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,1236 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, appendFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { resolve, sep } from "node:path";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
//#region src/host/digest/extract.ts
|
|
7
|
+
const MAX_CHARS = 24e3;
|
|
8
|
+
function textOfBlocks(content) {
|
|
9
|
+
if (!Array.isArray(content)) return "";
|
|
10
|
+
return content.filter((block) => typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n").trim();
|
|
11
|
+
}
|
|
12
|
+
/** What the human actually typed: drop the per-turn envelopes the runtime
|
|
13
|
+
* appends (sampling remark, <system-reminder>, runtime-memory snapshot,
|
|
14
|
+
* "Current runtime context"). An envelope-only message becomes empty, and the
|
|
15
|
+
* caller walks back to the previous one. */
|
|
16
|
+
function isHumanMessage(source) {
|
|
17
|
+
const kind = source?.kind;
|
|
18
|
+
return kind === void 0 || kind === "user";
|
|
19
|
+
}
|
|
20
|
+
function extractFromSurface(events, capturedThroughSeq) {
|
|
21
|
+
const lines = [];
|
|
22
|
+
let todoNext;
|
|
23
|
+
let lastSeq = capturedThroughSeq ?? 0;
|
|
24
|
+
for (const event of events) {
|
|
25
|
+
if (event.seq > lastSeq) lastSeq = event.seq;
|
|
26
|
+
if (event.type === "user/message") {
|
|
27
|
+
const message = event.data;
|
|
28
|
+
if ((message?.source)?.kind === "tool") continue;
|
|
29
|
+
const text = textOfBlocks(message?.content);
|
|
30
|
+
if (text !== "") lines.push({
|
|
31
|
+
role: "user",
|
|
32
|
+
text
|
|
33
|
+
});
|
|
34
|
+
} else if (event.type === "assistant/message") {
|
|
35
|
+
const data = event.data;
|
|
36
|
+
const text = textOfBlocks(data?.message?.content);
|
|
37
|
+
if (text !== "") lines.push({
|
|
38
|
+
role: "assistant",
|
|
39
|
+
text
|
|
40
|
+
});
|
|
41
|
+
} else if (event.type === "todo/write") todoNext = (event.data?.todos?.find((item) => item.status !== "completed"))?.content;
|
|
42
|
+
}
|
|
43
|
+
const recent = lines.slice(-40);
|
|
44
|
+
let transcript = recent.map((line) => `${line.role === "user" ? "USER" : "ASSISTANT"}: ${line.text}`).join("\n\n");
|
|
45
|
+
if (transcript.length > MAX_CHARS) transcript = transcript.slice(transcript.length - MAX_CHARS);
|
|
46
|
+
return {
|
|
47
|
+
transcript,
|
|
48
|
+
...todoNext !== void 0 && todoNext !== "" ? { todoNext } : {},
|
|
49
|
+
lastSeq,
|
|
50
|
+
messageCount: recent.length
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
//#endregion
|
|
54
|
+
//#region src/host/digest/prompt.ts
|
|
55
|
+
/**
|
|
56
|
+
* Digest prompt: three fields, strict JSON, the conversation's own language.
|
|
57
|
+
* Structure follows compaction-basic's summarizer style (structured, bounded)
|
|
58
|
+
* but collapsed to what a card front and an injection preview actually need.
|
|
59
|
+
*/
|
|
60
|
+
const DIGEST_SYSTEM_PROMPT = [
|
|
61
|
+
"You are a conversation digester for a visual conversation map.",
|
|
62
|
+
"Read the conversation transcript and output STRICT JSON, nothing else:",
|
|
63
|
+
"{\"summary\": string, \"keyFindings\": string[], \"nextStep\": string}",
|
|
64
|
+
"",
|
|
65
|
+
"Rules:",
|
|
66
|
+
"- Use the language the conversation itself is in (Chinese conversation → Chinese output).",
|
|
67
|
+
"- summary: what this conversation is about and where it stands, ≤120 characters.",
|
|
68
|
+
"- keyFindings: at most 5 short bullet strings — decisions made, facts established, artifacts produced.",
|
|
69
|
+
"- nextStep: ONE imperative sentence naming the next concrete action to take, ≤40 characters.",
|
|
70
|
+
" The reader has ADHD and returns after days away — nextStep must be directly actionable,",
|
|
71
|
+
" never vague (\"continue working\" is forbidden; \"run the M2 browser test\" is right).",
|
|
72
|
+
"- If the conversation is finished with nothing left to do, nextStep is an empty string.",
|
|
73
|
+
"- Output raw JSON only: no markdown fences, no commentary."
|
|
74
|
+
].join("\n");
|
|
75
|
+
function digestUserPrompt(transcript) {
|
|
76
|
+
return `Conversation transcript (oldest first):\n\n${transcript}\n\nOutput the JSON digest now.`;
|
|
77
|
+
}
|
|
78
|
+
/** Tolerant parse: strips fences, grabs the outermost object, validates shape. */
|
|
79
|
+
function parseDigestOutput(raw) {
|
|
80
|
+
let text = raw.trim();
|
|
81
|
+
if (text.startsWith("```")) text = text.replace(/^```[a-z]*\s*/i, "").replace(/```\s*$/, "").trim();
|
|
82
|
+
const start = text.indexOf("{");
|
|
83
|
+
const end = text.lastIndexOf("}");
|
|
84
|
+
if (start === -1 || end <= start) throw new Error("digest output contains no JSON object");
|
|
85
|
+
const parsed = JSON.parse(text.slice(start, end + 1));
|
|
86
|
+
if (typeof parsed.summary !== "string" || typeof parsed.nextStep !== "string" || !Array.isArray(parsed.keyFindings)) throw new Error("digest output missing required fields");
|
|
87
|
+
return {
|
|
88
|
+
summary: parsed.summary.slice(0, 300),
|
|
89
|
+
keyFindings: parsed.keyFindings.filter((finding) => typeof finding === "string").slice(0, 5).map((finding) => finding.slice(0, 200)),
|
|
90
|
+
nextStep: parsed.nextStep.slice(0, 120)
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/host/digest/pipeline.ts
|
|
95
|
+
/**
|
|
96
|
+
* Digest pipeline: turn/end → per-session debounce → single-flight queue →
|
|
97
|
+
* readSurface → extract → hash-skip → one LLM call → digests table.
|
|
98
|
+
*
|
|
99
|
+
* Deliberately NOT ctx.compaction (destructive, needs a live agent, holds a
|
|
100
|
+
* log lock). Failure degrades gracefully: the todo/write "next step" and any
|
|
101
|
+
* previous digest fields survive, with `error` set for the card badge.
|
|
102
|
+
*/
|
|
103
|
+
const DIGEST_DEFAULTS = {
|
|
104
|
+
enabled: false,
|
|
105
|
+
idleMs: 3e4
|
|
106
|
+
};
|
|
107
|
+
const MIN_MESSAGES = 2;
|
|
108
|
+
var DigestPipeline = class {
|
|
109
|
+
services;
|
|
110
|
+
storeReady;
|
|
111
|
+
config;
|
|
112
|
+
onFresh;
|
|
113
|
+
timers = /* @__PURE__ */ new Map();
|
|
114
|
+
queue = [];
|
|
115
|
+
queued = /* @__PURE__ */ new Set();
|
|
116
|
+
draining = false;
|
|
117
|
+
disposed = false;
|
|
118
|
+
constructor(services, storeReady, config = DIGEST_DEFAULTS, onFresh) {
|
|
119
|
+
this.services = services;
|
|
120
|
+
this.storeReady = storeReady;
|
|
121
|
+
this.config = config;
|
|
122
|
+
this.onFresh = onFresh;
|
|
123
|
+
}
|
|
124
|
+
/** Wire the turn/end trigger; returns the disposer. */
|
|
125
|
+
start() {
|
|
126
|
+
const off = this.services.on("session/event", (...args) => {
|
|
127
|
+
// Off by default: only sessions that feed an auto-push edge get digested,
|
|
128
|
+
// and even then the LLM call is skipped when nothing changed.
|
|
129
|
+
if (!this.config.enabled && !(this.config.shouldAuto?.(session.id) ?? false)) return;
|
|
130
|
+
const session = args[0];
|
|
131
|
+
if (args[1]?.type !== "turn/end" || typeof session?.id !== "string") return;
|
|
132
|
+
this.schedule(session.id);
|
|
133
|
+
});
|
|
134
|
+
return () => {
|
|
135
|
+
this.disposed = true;
|
|
136
|
+
off();
|
|
137
|
+
for (const timer of this.timers.values()) clearTimeout(timer);
|
|
138
|
+
this.timers.clear();
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** Debounced trigger: a busy session settles idleMs before digesting. */
|
|
142
|
+
schedule(sessionId) {
|
|
143
|
+
if (this.disposed) return;
|
|
144
|
+
const existing = this.timers.get(sessionId);
|
|
145
|
+
if (existing !== void 0) clearTimeout(existing);
|
|
146
|
+
const timer = setTimeout(() => {
|
|
147
|
+
this.timers.delete(sessionId);
|
|
148
|
+
this.enqueue(sessionId);
|
|
149
|
+
}, this.config.idleMs);
|
|
150
|
+
timer.unref?.();
|
|
151
|
+
this.timers.set(sessionId, timer);
|
|
152
|
+
}
|
|
153
|
+
/** Manual refresh: skips the debounce, forces regeneration (ignores hash). */
|
|
154
|
+
async refresh(sessionId) {
|
|
155
|
+
return await this.run(sessionId, { force: true });
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Regenerate only if the conversation actually moved on: identical transcript
|
|
159
|
+
* → the stored digest comes back untouched, no LLM call.
|
|
160
|
+
*/
|
|
161
|
+
async ensure(sessionId) {
|
|
162
|
+
return await this.run(sessionId, { force: false });
|
|
163
|
+
}
|
|
164
|
+
/** Queue sessions that have no digest yet (imported/backlog cards). */
|
|
165
|
+
backfill(sessionIds) {
|
|
166
|
+
for (const sessionId of sessionIds) this.enqueue(sessionId);
|
|
167
|
+
}
|
|
168
|
+
enqueue(sessionId) {
|
|
169
|
+
if (this.queued.has(sessionId)) return;
|
|
170
|
+
this.queued.add(sessionId);
|
|
171
|
+
this.queue.push(sessionId);
|
|
172
|
+
this.drain();
|
|
173
|
+
}
|
|
174
|
+
async drain() {
|
|
175
|
+
if (this.draining) return;
|
|
176
|
+
this.draining = true;
|
|
177
|
+
try {
|
|
178
|
+
while (this.queue.length > 0 && !this.disposed) {
|
|
179
|
+
const sessionId = this.queue.shift();
|
|
180
|
+
if (sessionId === void 0) break;
|
|
181
|
+
this.queued.delete(sessionId);
|
|
182
|
+
try {
|
|
183
|
+
await this.run(sessionId, { force: false });
|
|
184
|
+
} catch (error) {
|
|
185
|
+
this.services.logger?.warn(`[dsh-talk-map] digest for ${sessionId} failed: ${String(error)}`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
} finally {
|
|
189
|
+
this.draining = false;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async run(sessionId, options) {
|
|
193
|
+
const store = await this.storeReady;
|
|
194
|
+
const surface = await this.services.sessionQuery.readSurface(sessionId);
|
|
195
|
+
const extracted = extractFromSurface(surface.events, surface.capturedThroughSeq);
|
|
196
|
+
const previous = store.digests.get(sessionId);
|
|
197
|
+
if (extracted.transcript === "" || extracted.messageCount < MIN_MESSAGES) {
|
|
198
|
+
const digest = {
|
|
199
|
+
atSeq: extracted.lastSeq,
|
|
200
|
+
summary: previous?.summary ?? "",
|
|
201
|
+
keyFindings: previous?.keyFindings ?? [],
|
|
202
|
+
nextStep: previous?.nextStep ?? "",
|
|
203
|
+
...extracted.todoNext !== void 0 ? { todoNext: extracted.todoNext } : {},
|
|
204
|
+
generatedAt: Date.now()
|
|
205
|
+
};
|
|
206
|
+
await store.digests.put(sessionId, digest);
|
|
207
|
+
return digest;
|
|
208
|
+
}
|
|
209
|
+
const inputHash = createHash("sha256").update(extracted.transcript).digest("hex");
|
|
210
|
+
if (!options.force && previous?.inputHash === inputHash && previous.error === void 0) return previous;
|
|
211
|
+
const route = this.services.agentDefaultModel.currentSelection();
|
|
212
|
+
try {
|
|
213
|
+
const parsed = parseDigestOutput(await this.generate(route, extracted.transcript, sessionId));
|
|
214
|
+
const digest = {
|
|
215
|
+
atSeq: extracted.lastSeq,
|
|
216
|
+
summary: parsed.summary,
|
|
217
|
+
keyFindings: parsed.keyFindings,
|
|
218
|
+
nextStep: parsed.nextStep,
|
|
219
|
+
...extracted.todoNext !== void 0 ? { todoNext: extracted.todoNext } : {},
|
|
220
|
+
generatedAt: Date.now(),
|
|
221
|
+
model: `${route.provider}/${route.model}`,
|
|
222
|
+
inputHash
|
|
223
|
+
};
|
|
224
|
+
await store.digests.put(sessionId, digest);
|
|
225
|
+
if (previous?.inputHash !== inputHash) try {
|
|
226
|
+
this.onFresh?.(sessionId, digest);
|
|
227
|
+
} catch (hookError) {
|
|
228
|
+
this.services.logger?.warn(`[dsh-talk-map] onFresh hook failed: ${String(hookError)}`);
|
|
229
|
+
}
|
|
230
|
+
return digest;
|
|
231
|
+
} catch (error) {
|
|
232
|
+
const digest = {
|
|
233
|
+
atSeq: extracted.lastSeq,
|
|
234
|
+
summary: previous?.summary ?? "",
|
|
235
|
+
keyFindings: previous?.keyFindings ?? [],
|
|
236
|
+
nextStep: previous?.nextStep ?? "",
|
|
237
|
+
...extracted.todoNext !== void 0 ? { todoNext: extracted.todoNext } : {},
|
|
238
|
+
generatedAt: Date.now(),
|
|
239
|
+
error: String(error).slice(0, 500)
|
|
240
|
+
};
|
|
241
|
+
await store.digests.put(sessionId, digest);
|
|
242
|
+
return digest;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
async generate(route, transcript, sessionId) {
|
|
246
|
+
const message = {
|
|
247
|
+
id: crypto.randomUUID(),
|
|
248
|
+
role: "user",
|
|
249
|
+
content: [{
|
|
250
|
+
type: "text",
|
|
251
|
+
text: digestUserPrompt(transcript)
|
|
252
|
+
}],
|
|
253
|
+
source: {
|
|
254
|
+
kind: "plugin:dsh-talk-map"
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
let text = "";
|
|
258
|
+
let failure;
|
|
259
|
+
for await (const chunk of this.services.llm.stream({
|
|
260
|
+
provider: route.provider,
|
|
261
|
+
model: route.model,
|
|
262
|
+
messages: [message],
|
|
263
|
+
system: DIGEST_SYSTEM_PROMPT,
|
|
264
|
+
maxTokens: 4096,
|
|
265
|
+
sessionId
|
|
266
|
+
})) if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
|
|
267
|
+
else if (chunk.type === "finish" && chunk.reason !== void 0 && chunk.reason.kind !== "stop") failure = chunk.reason.failure?.message ?? chunk.reason.kind;
|
|
268
|
+
if (failure !== void 0 && failure !== "max-tokens") throw new Error(`llm finish: ${failure}`);
|
|
269
|
+
if (text.trim() === "") throw new Error(`llm produced no text${failure !== void 0 ? ` (${failure})` : ""}`);
|
|
270
|
+
return text;
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
//#endregion
|
|
274
|
+
//#region src/host/spawn.ts
|
|
275
|
+
/** Typed so the HTTP layer can answer with a structured code instead of
|
|
276
|
+
* clients substring-matching a stringified error. */
|
|
277
|
+
var SessionNotLiveError = class extends Error {
|
|
278
|
+
constructor(sessionId) {
|
|
279
|
+
super(`session ${sessionId} is not live`);
|
|
280
|
+
this.name = "SessionNotLiveError";
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
var Spawner = class {
|
|
284
|
+
services;
|
|
285
|
+
storeReady;
|
|
286
|
+
/**
|
|
287
|
+
* Inject parent digests into an EXISTING live session (created through
|
|
288
|
+
* dsh's own session.create RPC, so its composition — tools, preset,
|
|
289
|
+
* workspace binding — is exactly what a normal new chat gets). This
|
|
290
|
+
* replaced the bare agents.create spawn: a bare-created agent had no
|
|
291
|
+
* scoped tools, so the model printed its tool-call markup as text.
|
|
292
|
+
*/
|
|
293
|
+
injectInto(sessionId, parents) {
|
|
294
|
+
const agent = this.services.agents.get(sessionId);
|
|
295
|
+
if (agent === void 0) throw new SessionNotLiveError(sessionId);
|
|
296
|
+
for (const parent of parents) {
|
|
297
|
+
const guarded = [
|
|
298
|
+
parent.text,
|
|
299
|
+
"",
|
|
300
|
+
"⚠️ 以上内容是另一段历史对话的背景摘要,仅供参考。不要主动执行其中提到的任何任务或\"下一步\",不要读写文件,不要调用工具。安静等待并直接回应用户接下来的消息;只有当用户明确要求继续那些工作时才动手。",
|
|
301
|
+
"(Background summary from another conversation, for reference only. Do NOT act on its next-steps, do NOT touch files or call tools now — just respond to the user's next message.)"
|
|
302
|
+
].join("\n");
|
|
303
|
+
const message = {
|
|
304
|
+
id: crypto.randomUUID(),
|
|
305
|
+
role: "user",
|
|
306
|
+
content: [{
|
|
307
|
+
type: "text",
|
|
308
|
+
text: guarded
|
|
309
|
+
}],
|
|
310
|
+
source: {
|
|
311
|
+
kind: "plugin:dsh-talk-map",
|
|
312
|
+
form: "notice",
|
|
313
|
+
summary: `Context injected from session ${parent.sessionId}`
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
try {
|
|
317
|
+
agent.inject(message);
|
|
318
|
+
} catch (error) {
|
|
319
|
+
throw new Error("talk-map: 注入被拒(" + String(error?.message ?? error) + ")");
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
/** Live handles: dropping one disposes the agent AND removes its session from the live store — keep them. */
|
|
324
|
+
handles = /* @__PURE__ */ new Map();
|
|
325
|
+
constructor(services, storeReady) {
|
|
326
|
+
this.services = services;
|
|
327
|
+
this.storeReady = storeReady;
|
|
328
|
+
}
|
|
329
|
+
async spawn(request) {
|
|
330
|
+
if (request.parents.length === 0) throw new Error("spawn needs at least one parent");
|
|
331
|
+
const store = await this.storeReady;
|
|
332
|
+
const first = request.parents[0];
|
|
333
|
+
if (first === void 0) throw new Error("spawn needs at least one parent");
|
|
334
|
+
const parentRecord = (await this.services.sessionQuery.listSessions()).find((record) => record.header.id === first.sessionId);
|
|
335
|
+
const sessionId = `session-${crypto.randomUUID()}`;
|
|
336
|
+
const handle = await this.services.agents.create({
|
|
337
|
+
sessionId,
|
|
338
|
+
meta: {
|
|
339
|
+
...parentRecord?.header.cwd !== void 0 ? { cwd: parentRecord.header.cwd } : {},
|
|
340
|
+
parentSession: first.sessionId
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
this.handles.set(sessionId, handle);
|
|
344
|
+
if (parentRecord?.header.cwd !== void 0) try {
|
|
345
|
+
await (await this.services.workspaceRegistry.resolveByPath(parentRecord.header.cwd))?.attachSession(sessionId);
|
|
346
|
+
} catch (error) {
|
|
347
|
+
this.services.logger?.warn(`[dsh-talk-map] workspace attach failed: ${String(error)}`);
|
|
348
|
+
}
|
|
349
|
+
for (const parent of request.parents) {
|
|
350
|
+
const message = {
|
|
351
|
+
id: crypto.randomUUID(),
|
|
352
|
+
role: "user",
|
|
353
|
+
content: [{
|
|
354
|
+
type: "text",
|
|
355
|
+
text: parent.text
|
|
356
|
+
}],
|
|
357
|
+
source: {
|
|
358
|
+
kind: "plugin:dsh-talk-map",
|
|
359
|
+
form: "notice",
|
|
360
|
+
summary: `Context injected from session ${parent.sessionId}`
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
try {
|
|
364
|
+
handle.agent.inject(message);
|
|
365
|
+
} catch (error) {
|
|
366
|
+
throw new Error("talk-map: 注入被拒(" + String(error?.message ?? error) + ")");
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const cardId = `card-${crypto.randomUUID()}`;
|
|
370
|
+
const card = {
|
|
371
|
+
boardId: request.boardId,
|
|
372
|
+
sessionId,
|
|
373
|
+
x: request.x,
|
|
374
|
+
y: request.y,
|
|
375
|
+
...request.wsOverride !== void 0 ? { wsOverride: request.wsOverride } : {},
|
|
376
|
+
createdAt: Date.now()
|
|
377
|
+
};
|
|
378
|
+
await store.cards.put(cardId, card);
|
|
379
|
+
const edges = {};
|
|
380
|
+
for (const parent of request.parents) {
|
|
381
|
+
const edgeId = `edge-${crypto.randomUUID()}`;
|
|
382
|
+
const edge = {
|
|
383
|
+
boardId: request.boardId,
|
|
384
|
+
fromCardId: parent.cardId,
|
|
385
|
+
toCardId: cardId,
|
|
386
|
+
injection: {
|
|
387
|
+
kind: "digest",
|
|
388
|
+
injectedText: parent.text
|
|
389
|
+
},
|
|
390
|
+
// The line just delivered: the map's sync animation keys off this.
|
|
391
|
+
lastPushAt: Date.now(),
|
|
392
|
+
createdAt: Date.now()
|
|
393
|
+
};
|
|
394
|
+
await store.edges.put(edgeId, edge);
|
|
395
|
+
edges[edgeId] = edge;
|
|
396
|
+
}
|
|
397
|
+
this.services.logger?.info?.(`[dsh-talk-map] spawned ${sessionId} from ${request.parents.length} parent(s)`);
|
|
398
|
+
return {
|
|
399
|
+
sessionId,
|
|
400
|
+
cardId,
|
|
401
|
+
card,
|
|
402
|
+
edges
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
//#endregion
|
|
407
|
+
//#region src/host/store.ts
|
|
408
|
+
/**
|
|
409
|
+
* The talk-map storage domain: canvas-private data only. Session content,
|
|
410
|
+
* titles, and lineage stay with dsh's own services — this domain stores what
|
|
411
|
+
* the map adds on top (positions, user-drawn injection edges, digests, and
|
|
412
|
+
* per-board camera). Persisted by the profile's storage-json backend under
|
|
413
|
+
* $DSH_HOME/storages/.
|
|
414
|
+
*
|
|
415
|
+
* CardId ≠ SessionId on purpose: a later "alias card" feature (the same
|
|
416
|
+
* session appearing on several boards) then needs no migration.
|
|
417
|
+
*/
|
|
418
|
+
/** Storage unit names must match /^[a-z][a-z0-9_]*$/ — no hyphens. */
|
|
419
|
+
const DOMAIN_NAME = "talk_map";
|
|
420
|
+
/** The bootstrap board every unfiled card lands on. */
|
|
421
|
+
const INBOX_BOARD_ID = "inbox";
|
|
422
|
+
const boardSchema = z.object({
|
|
423
|
+
name: z.string(),
|
|
424
|
+
color: z.string(),
|
|
425
|
+
order: z.number(),
|
|
426
|
+
createdAt: z.number(),
|
|
427
|
+
archivedAt: z.number().optional(),
|
|
428
|
+
shelvedAt: z.number().optional()
|
|
429
|
+
});
|
|
430
|
+
const cardSchema = z.object({
|
|
431
|
+
boardId: z.string(),
|
|
432
|
+
sessionId: z.string(),
|
|
433
|
+
x: z.number(),
|
|
434
|
+
y: z.number(),
|
|
435
|
+
colorTag: z.string().optional(),
|
|
436
|
+
/** Map-level group override (set by dragging a card into another frame).
|
|
437
|
+
* dsh @0.1.0-rc.6 has no cross-workspace session move RPC, so this is the
|
|
438
|
+
* canvas's own organizational layer — the sidebar keeps its own truth. */
|
|
439
|
+
wsOverride: z.string().optional(),
|
|
440
|
+
createdAt: z.number()
|
|
441
|
+
});
|
|
442
|
+
const edgeInjectionSchema = z.object({
|
|
443
|
+
/** 'link' = a plain association drawn between two EXISTING cards (no
|
|
444
|
+
* spawn, no text); 'none' = a fork edge whose child inherited nothing. */
|
|
445
|
+
kind: z.enum([
|
|
446
|
+
"digest",
|
|
447
|
+
"full",
|
|
448
|
+
"selection",
|
|
449
|
+
"none",
|
|
450
|
+
"link"
|
|
451
|
+
]),
|
|
452
|
+
/** What was actually injected (post-edit), kept for provenance display. */
|
|
453
|
+
injectedText: z.string().optional()
|
|
454
|
+
});
|
|
455
|
+
const edgeSchema = z.object({
|
|
456
|
+
boardId: z.string(),
|
|
457
|
+
fromCardId: z.string(),
|
|
458
|
+
toCardId: z.string(),
|
|
459
|
+
injection: edgeInjectionSchema,
|
|
460
|
+
/** Handle sides ('t'|'r'|'b'|'l') the edge attaches to; absent = legacy r→l. */
|
|
461
|
+
fromHandle: z.string().optional(),
|
|
462
|
+
toHandle: z.string().optional(),
|
|
463
|
+
/** Pipe mode: every substantive digest change of the source session is
|
|
464
|
+
* pushed along this edge into the target session automatically. */
|
|
465
|
+
autoSync: z.boolean().optional(),
|
|
466
|
+
/** Source-session title snapshot (the host cannot resolve titles; the
|
|
467
|
+
* client stamps it so auto-sync pushes can name their origin). */
|
|
468
|
+
fromTitle: z.string().optional(),
|
|
469
|
+
createdAt: z.number()
|
|
470
|
+
});
|
|
471
|
+
const digestSchema = z.object({
|
|
472
|
+
/** Last session event seq folded into this digest (staleness anchor). */
|
|
473
|
+
atSeq: z.number(),
|
|
474
|
+
summary: z.string(),
|
|
475
|
+
keyFindings: z.array(z.string()),
|
|
476
|
+
/** The ADHD field: one imperative sentence — the next concrete action. */
|
|
477
|
+
nextStep: z.string(),
|
|
478
|
+
/** Zero-cost fallback lifted from the session's todo/write events. */
|
|
479
|
+
todoNext: z.string().optional(),
|
|
480
|
+
generatedAt: z.number(),
|
|
481
|
+
model: z.string().optional(),
|
|
482
|
+
error: z.string().optional(),
|
|
483
|
+
/** sha256 of the transcript input — unchanged input skips regeneration. */
|
|
484
|
+
inputHash: z.string().optional()
|
|
485
|
+
});
|
|
486
|
+
const cameraSchema = z.object({
|
|
487
|
+
x: z.number(),
|
|
488
|
+
y: z.number(),
|
|
489
|
+
zoom: z.number()
|
|
490
|
+
});
|
|
491
|
+
const globalSchema = z.object({
|
|
492
|
+
version: z.number(),
|
|
493
|
+
activeBoard: z.string(),
|
|
494
|
+
cameraByBoard: z.record(z.string(), cameraSchema),
|
|
495
|
+
/** Auto-placement generation; absent = v1 (pre-workspace-grouping). */
|
|
496
|
+
layoutVersion: z.number().optional(),
|
|
497
|
+
/** Per-workspace color tags for the group frames. */
|
|
498
|
+
wsColors: z.record(z.string(), z.string()).optional(),
|
|
499
|
+
/** Manually sized frames (resize handle); absent = auto-fit to members. */
|
|
500
|
+
wsFrames: z.record(z.string(), z.object({
|
|
501
|
+
x: z.number(),
|
|
502
|
+
y: z.number(),
|
|
503
|
+
width: z.number(),
|
|
504
|
+
height: z.number()
|
|
505
|
+
})).optional(),
|
|
506
|
+
/** Map-toggle hotkey, e.g. "alt+KeyF" (modifiers + KeyboardEvent.code). */
|
|
507
|
+
hotkey: z.string().optional(),
|
|
508
|
+
/** Interface language of the map's own copy; absent = follow <html lang>. */
|
|
509
|
+
locale: z.enum([
|
|
510
|
+
"auto",
|
|
511
|
+
"zh",
|
|
512
|
+
"en"
|
|
513
|
+
]).optional(),
|
|
514
|
+
/** Last known placement per session — re-imports restore the arrangement. */
|
|
515
|
+
layoutMemory: z.record(z.string(), z.object({
|
|
516
|
+
x: z.number(),
|
|
517
|
+
y: z.number(),
|
|
518
|
+
colorTag: z.string().optional()
|
|
519
|
+
})).optional()
|
|
520
|
+
});
|
|
521
|
+
const TALK_MAP_SPEC = {
|
|
522
|
+
name: DOMAIN_NAME,
|
|
523
|
+
version: 1,
|
|
524
|
+
global: {
|
|
525
|
+
schema: globalSchema,
|
|
526
|
+
initial: {
|
|
527
|
+
version: 1,
|
|
528
|
+
activeBoard: INBOX_BOARD_ID,
|
|
529
|
+
cameraByBoard: {}
|
|
530
|
+
}
|
|
531
|
+
},
|
|
532
|
+
tables: {
|
|
533
|
+
boards: { valueSchema: boardSchema },
|
|
534
|
+
cards: { valueSchema: cardSchema },
|
|
535
|
+
edges: { valueSchema: edgeSchema },
|
|
536
|
+
digests: { valueSchema: digestSchema }
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
async function openTalkMapStore(storageDomain) {
|
|
540
|
+
const domain = await storageDomain.open(TALK_MAP_SPEC);
|
|
541
|
+
const store = {
|
|
542
|
+
domain,
|
|
543
|
+
boards: domain.table("boards"),
|
|
544
|
+
cards: domain.table("cards"),
|
|
545
|
+
edges: domain.table("edges"),
|
|
546
|
+
digests: domain.table("digests"),
|
|
547
|
+
global: () => domain.global.get(),
|
|
548
|
+
setGlobal: (value) => domain.global.set(value)
|
|
549
|
+
};
|
|
550
|
+
if (store.boards.get("inbox") === void 0) await store.boards.put(INBOX_BOARD_ID, {
|
|
551
|
+
name: "Inbox",
|
|
552
|
+
color: "gray",
|
|
553
|
+
order: 0,
|
|
554
|
+
createdAt: Date.now()
|
|
555
|
+
});
|
|
556
|
+
return store;
|
|
557
|
+
}
|
|
558
|
+
//#endregion
|
|
559
|
+
//#region src/host/routes.ts
|
|
560
|
+
const MAX_BODY_BYTES = 1048576;
|
|
561
|
+
function sendJson(response, status, body) {
|
|
562
|
+
const payload = JSON.stringify(body);
|
|
563
|
+
response.writeHead(status, {
|
|
564
|
+
"content-type": "application/json; charset=utf-8",
|
|
565
|
+
"cache-control": "no-store"
|
|
566
|
+
});
|
|
567
|
+
response.end(payload);
|
|
568
|
+
}
|
|
569
|
+
function sameOrigin(request) {
|
|
570
|
+
const origin = request.headers.origin;
|
|
571
|
+
if (origin === void 0) return true;
|
|
572
|
+
const host = request.headers.host;
|
|
573
|
+
if (host === void 0) return false;
|
|
574
|
+
try {
|
|
575
|
+
return new URL(origin).host === host;
|
|
576
|
+
} catch {
|
|
577
|
+
return false;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
async function readJsonBody(request) {
|
|
581
|
+
const chunks = [];
|
|
582
|
+
let size = 0;
|
|
583
|
+
for await (const chunk of request) {
|
|
584
|
+
const buffer = chunk;
|
|
585
|
+
size += buffer.length;
|
|
586
|
+
if (size > MAX_BODY_BYTES) throw new Error("body too large");
|
|
587
|
+
chunks.push(buffer);
|
|
588
|
+
}
|
|
589
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
590
|
+
return text === "" ? void 0 : JSON.parse(text);
|
|
591
|
+
}
|
|
592
|
+
function tableToRecord(table) {
|
|
593
|
+
const out = {};
|
|
594
|
+
for (const [key, value] of table.entries()) out[key] = value;
|
|
595
|
+
return out;
|
|
596
|
+
}
|
|
597
|
+
const upsertCardsBody = z.object({ cards: z.record(z.string(), cardSchema) });
|
|
598
|
+
const upsertEdgesBody = z.object({ edges: z.record(z.string(), edgeSchema) });
|
|
599
|
+
const deleteCardsBody = z.object({ ids: z.array(z.string()) });
|
|
600
|
+
const setGlobalBody = z.object({ global: globalSchema });
|
|
601
|
+
const spawnBody = z.object({
|
|
602
|
+
parents: z.array(z.object({
|
|
603
|
+
cardId: z.string(),
|
|
604
|
+
sessionId: z.string(),
|
|
605
|
+
text: z.string().min(1)
|
|
606
|
+
})).min(1),
|
|
607
|
+
boardId: z.string(),
|
|
608
|
+
x: z.number(),
|
|
609
|
+
y: z.number(),
|
|
610
|
+
wsOverride: z.string().optional()
|
|
611
|
+
});
|
|
612
|
+
const refreshDigestBody = z.object({ sessionId: z.string() });
|
|
613
|
+
const injectBody = z.object({
|
|
614
|
+
sessionId: z.string(),
|
|
615
|
+
parents: z.array(z.object({
|
|
616
|
+
sessionId: z.string(),
|
|
617
|
+
text: z.string().min(1)
|
|
618
|
+
})).min(1)
|
|
619
|
+
});
|
|
620
|
+
const ensureDirBody = z.object({ path: z.string().min(1) });
|
|
621
|
+
/**
|
|
622
|
+
* Register the /talk-map/ routes.
|
|
623
|
+
* @param services - host services (webServer + event bus).
|
|
624
|
+
* @param storeReady - resolves when the storage domain is open; handlers await it.
|
|
625
|
+
* @returns disposer removing the route registration and closing SSE clients.
|
|
626
|
+
*/
|
|
627
|
+
function mountTalkMapRoutes(services, storeReady, runtime) {
|
|
628
|
+
const sseClients = /* @__PURE__ */ new Set();
|
|
629
|
+
const offChanged = services.on("domain/changed", (...args) => {
|
|
630
|
+
const change = args[0];
|
|
631
|
+
if (change.domain !== "talk_map") return;
|
|
632
|
+
const frame = `event: change\ndata: ${JSON.stringify(change)}\n\n`;
|
|
633
|
+
for (const client of sseClients) client.write(frame);
|
|
634
|
+
});
|
|
635
|
+
const ping = setInterval(() => {
|
|
636
|
+
for (const client of sseClients) client.write(": ping\n\n");
|
|
637
|
+
}, 25e3);
|
|
638
|
+
ping.unref?.();
|
|
639
|
+
const unregister = services.webServer.register({
|
|
640
|
+
kind: "prefix",
|
|
641
|
+
path: "/talk-map",
|
|
642
|
+
handler: async (request, response) => {
|
|
643
|
+
const url = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`);
|
|
644
|
+
const route = `${request.method ?? "GET"} ${url.pathname}`;
|
|
645
|
+
try {
|
|
646
|
+
if (route === "GET /talk-map/state") {
|
|
647
|
+
const store = await storeReady;
|
|
648
|
+
sendJson(response, 200, {
|
|
649
|
+
boards: tableToRecord(store.boards),
|
|
650
|
+
cards: tableToRecord(store.cards),
|
|
651
|
+
edges: tableToRecord(store.edges),
|
|
652
|
+
digests: tableToRecord(store.digests),
|
|
653
|
+
global: store.global()
|
|
654
|
+
});
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
if (route === "GET /talk-map/defaults") {
|
|
658
|
+
let model = null;
|
|
659
|
+
let preset = null;
|
|
660
|
+
try {
|
|
661
|
+
model = runtime.modelDefault?.() ?? null;
|
|
662
|
+
} catch {}
|
|
663
|
+
try {
|
|
664
|
+
preset = runtime.presetDefault?.() ?? null;
|
|
665
|
+
} catch {}
|
|
666
|
+
sendJson(response, 200, {
|
|
667
|
+
model,
|
|
668
|
+
preset
|
|
669
|
+
});
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
if (route === "POST /talk-map/client-boot") {
|
|
673
|
+
const body = await readJsonBody(request);
|
|
674
|
+
const line = JSON.stringify({ at: new Date().toISOString(), pid: process.pid, ...body });
|
|
675
|
+
try {
|
|
676
|
+
await mkdir(join(homedir(), ".dsh"), { recursive: true });
|
|
677
|
+
await appendFile(join(homedir(), ".dsh", "talk-map-client-boot.log"), line + "\n");
|
|
678
|
+
} catch {}
|
|
679
|
+
sendJson(response, 200, { ok: true });
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
if (route === "POST /talk-map/last-user") {
|
|
683
|
+
const body = await readJsonBody(request);
|
|
684
|
+
const ids = Array.isArray(body?.sessionIds) ? body.sessionIds.filter((id) => typeof id === "string").slice(0, 200) : [];
|
|
685
|
+
const texts = {};
|
|
686
|
+
const query = runtime.sessionQuery;
|
|
687
|
+
if (query !== void 0) {
|
|
688
|
+
// One surface read per session costs ~250ms; a board has ~20 cards.
|
|
689
|
+
await Promise.all(ids.map(async (sessionId) => {
|
|
690
|
+
try {
|
|
691
|
+
const surface = await query.readSurface(sessionId);
|
|
692
|
+
let text = "";
|
|
693
|
+
for (const event of surface.events) {
|
|
694
|
+
if (event.type !== "user/message") continue;
|
|
695
|
+
// Only messages the human sent: the runtime tags everything it injects
|
|
696
|
+
// (runtime-context, time-context, dsh-mnemon, skill-catalog, …) with its own kind.
|
|
697
|
+
if (!isHumanMessage(event.data?.source)) continue;
|
|
698
|
+
if (!Array.isArray(event.data?.content)) continue;
|
|
699
|
+
const joined = event.data.content.filter((block) => typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n").trim();
|
|
700
|
+
if (joined !== "") text = joined;
|
|
701
|
+
}
|
|
702
|
+
if (text !== "") texts[sessionId] = text.length > 240 ? text.slice(0, 240) : text;
|
|
703
|
+
} catch {}
|
|
704
|
+
}));
|
|
705
|
+
}
|
|
706
|
+
sendJson(response, 200, { texts });
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
if (route === "GET /talk-map/events") {
|
|
710
|
+
response.writeHead(200, {
|
|
711
|
+
"content-type": "text/event-stream",
|
|
712
|
+
"cache-control": "no-store",
|
|
713
|
+
"connection": "keep-alive"
|
|
714
|
+
});
|
|
715
|
+
response.write(": connected\n\n");
|
|
716
|
+
sseClients.add(response);
|
|
717
|
+
request.on("close", () => {
|
|
718
|
+
sseClients.delete(response);
|
|
719
|
+
});
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
if (request.method === "POST" && !sameOrigin(request)) {
|
|
723
|
+
sendJson(response, 403, { error: "cross-origin request refused" });
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
if (route === "POST /talk-map/cards/upsert") {
|
|
727
|
+
const store = await storeReady;
|
|
728
|
+
const body = upsertCardsBody.parse(await readJsonBody(request));
|
|
729
|
+
for (const [id, card] of Object.entries(body.cards)) {
|
|
730
|
+
await store.cards.put(id, card);
|
|
731
|
+
const digest = store.digests.get(card.sessionId);
|
|
732
|
+
if (digest === void 0 || digest.summary === "") runtime.digest?.schedule(card.sessionId);
|
|
733
|
+
}
|
|
734
|
+
sendJson(response, 200, {
|
|
735
|
+
ok: true,
|
|
736
|
+
count: Object.keys(body.cards).length
|
|
737
|
+
});
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
if (route === "POST /talk-map/edges/upsert") {
|
|
741
|
+
const store = await storeReady;
|
|
742
|
+
const body = upsertEdgesBody.parse(await readJsonBody(request));
|
|
743
|
+
for (const [id, edge] of Object.entries(body.edges)) await store.edges.put(id, edge);
|
|
744
|
+
sendJson(response, 200, {
|
|
745
|
+
ok: true,
|
|
746
|
+
count: Object.keys(body.edges).length
|
|
747
|
+
});
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
if (route === "POST /talk-map/cards/delete") {
|
|
751
|
+
const store = await storeReady;
|
|
752
|
+
const body = deleteCardsBody.parse(await readJsonBody(request));
|
|
753
|
+
let removed = 0;
|
|
754
|
+
for (const id of body.ids) if (await store.cards.delete(id)) removed += 1;
|
|
755
|
+
for (const [edgeId, edge] of [...store.edges.entries()]) if (body.ids.includes(edge.fromCardId) || body.ids.includes(edge.toCardId)) await store.edges.delete(edgeId);
|
|
756
|
+
sendJson(response, 200, {
|
|
757
|
+
ok: true,
|
|
758
|
+
removed
|
|
759
|
+
});
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
if (route === "POST /talk-map/edges/delete") {
|
|
763
|
+
const store = await storeReady;
|
|
764
|
+
const body = deleteCardsBody.parse(await readJsonBody(request));
|
|
765
|
+
let removed = 0;
|
|
766
|
+
for (const id of body.ids) if (await store.edges.delete(id)) removed += 1;
|
|
767
|
+
sendJson(response, 200, {
|
|
768
|
+
ok: true,
|
|
769
|
+
removed
|
|
770
|
+
});
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
if (route === "POST /talk-map/global") {
|
|
774
|
+
const store = await storeReady;
|
|
775
|
+
const body = setGlobalBody.parse(await readJsonBody(request));
|
|
776
|
+
await store.setGlobal(body.global);
|
|
777
|
+
sendJson(response, 200, { ok: true });
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
if (route === "POST /talk-map/inject") {
|
|
781
|
+
if (runtime.spawner === void 0) {
|
|
782
|
+
sendJson(response, 503, { error: "spawn layer unavailable (agents service missing)" });
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
const body = injectBody.parse(await readJsonBody(request));
|
|
786
|
+
try {
|
|
787
|
+
runtime.spawner.injectInto(body.sessionId, body.parents);
|
|
788
|
+
} catch (error) {
|
|
789
|
+
if (error instanceof SessionNotLiveError) {
|
|
790
|
+
sendJson(response, 409, {
|
|
791
|
+
error: String(error),
|
|
792
|
+
code: "session-not-live"
|
|
793
|
+
});
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
throw error;
|
|
797
|
+
}
|
|
798
|
+
sendJson(response, 200, { ok: true });
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
if (route === "POST /talk-map/search") {
|
|
802
|
+
const body = await readJsonBody(request);
|
|
803
|
+
const query = typeof body?.query === "string" ? body.query.trim() : "";
|
|
804
|
+
if (query === "" || runtime.search === void 0) {
|
|
805
|
+
sendJson(response, 200, { items: [], hasMore: false });
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
try {
|
|
809
|
+
const page = await runtime.search(query, cwd);
|
|
810
|
+
sendJson(response, 200, { items: page?.items ?? [], hasMore: page?.hasMore === true });
|
|
811
|
+
} catch (error) {
|
|
812
|
+
sendJson(response, 500, { error: String(error?.message ?? error) });
|
|
813
|
+
}
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
if (route === "POST /talk-map/search-session") {
|
|
817
|
+
const body = await readJsonBody(request);
|
|
818
|
+
const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
|
|
819
|
+
const query = typeof body?.query === "string" ? body.query : "";
|
|
820
|
+
if (sessionId === "" || runtime.searchSession === void 0) {
|
|
821
|
+
sendJson(response, 200, { blocks: [], seqs: [] });
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
try {
|
|
825
|
+
sendJson(response, 200, await runtime.searchSession(sessionId, query));
|
|
826
|
+
} catch (error) {
|
|
827
|
+
sendJson(response, 200, { blocks: [], seqs: [], error: String(error?.message ?? error) });
|
|
828
|
+
}
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
if (route === "POST /talk-map/search-context") {
|
|
832
|
+
const body = await readJsonBody(request);
|
|
833
|
+
const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
|
|
834
|
+
const seq = typeof body?.seq === "number" ? body.seq : null;
|
|
835
|
+
const query = typeof body?.query === "string" ? body.query : "";
|
|
836
|
+
if (sessionId === "" || seq === null || runtime.searchContext === void 0) {
|
|
837
|
+
sendJson(response, 200, { lines: [] });
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
try {
|
|
841
|
+
sendJson(response, 200, await runtime.searchContext(sessionId, seq, query));
|
|
842
|
+
} catch (error) {
|
|
843
|
+
sendJson(response, 200, { lines: [], error: String(error?.message ?? error) });
|
|
844
|
+
}
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
if (route === "POST /talk-map/spawn") {
|
|
848
|
+
if (runtime.spawner === void 0) {
|
|
849
|
+
sendJson(response, 503, { error: "spawn layer unavailable (agents service missing)" });
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
const body = spawnBody.parse(await readJsonBody(request));
|
|
853
|
+
sendJson(response, 200, await runtime.spawner.spawn(body));
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
if (route === "POST /talk-map/fs/ensure-dir") {
|
|
857
|
+
const body = ensureDirBody.parse(await readJsonBody(request));
|
|
858
|
+
const target = resolve(body.path);
|
|
859
|
+
const home = homedir();
|
|
860
|
+
if (target !== home && !target.startsWith(home + sep)) {
|
|
861
|
+
sendJson(response, 400, { error: "path must be inside the home directory" });
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
await mkdir(target, { recursive: true });
|
|
865
|
+
sendJson(response, 200, {
|
|
866
|
+
ok: true,
|
|
867
|
+
path: target
|
|
868
|
+
});
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
if (route === "POST /talk-map/digest/ensure") {
|
|
872
|
+
if (runtime.digest === void 0) {
|
|
873
|
+
sendJson(response, 503, { error: "digest layer unavailable (llm service missing)" });
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
const ensureBody = refreshDigestBody.parse(await readJsonBody(request));
|
|
877
|
+
const ensured = await runtime.digest.ensure(ensureBody.sessionId);
|
|
878
|
+
sendJson(response, 200, { sessionId: ensureBody.sessionId, digest: ensured });
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
if (route === "POST /talk-map/digest/refresh") {
|
|
882
|
+
if (runtime.digest === void 0) {
|
|
883
|
+
sendJson(response, 503, { error: "digest layer unavailable (llm service missing)" });
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
const body = refreshDigestBody.parse(await readJsonBody(request));
|
|
887
|
+
const digest = await runtime.digest.refresh(body.sessionId);
|
|
888
|
+
sendJson(response, 200, {
|
|
889
|
+
sessionId: body.sessionId,
|
|
890
|
+
digest
|
|
891
|
+
});
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
sendJson(response, 404, { error: `no such route: ${route}` });
|
|
895
|
+
} catch (error) {
|
|
896
|
+
services.logger?.warn(`[dsh-talk-map] ${route} failed: ${String(error)}`);
|
|
897
|
+
if (!response.headersSent) sendJson(response, 400, { error: String(error) });
|
|
898
|
+
else response.end();
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
});
|
|
902
|
+
return () => {
|
|
903
|
+
clearInterval(ping);
|
|
904
|
+
offChanged();
|
|
905
|
+
for (const client of sseClients) client.end();
|
|
906
|
+
sseClients.clear();
|
|
907
|
+
unregister();
|
|
908
|
+
};
|
|
909
|
+
}
|
|
910
|
+
//#endregion
|
|
911
|
+
//#region src/index.ts
|
|
912
|
+
const name = "dsh-talk-map";
|
|
913
|
+
function apply(ctx) {
|
|
914
|
+
const runtime = {};
|
|
915
|
+
let resolveStore;
|
|
916
|
+
let rejectStore;
|
|
917
|
+
const storeReady = new Promise((resolve, reject) => {
|
|
918
|
+
resolveStore = resolve;
|
|
919
|
+
rejectStore = reject;
|
|
920
|
+
});
|
|
921
|
+
storeReady.catch(() => {});
|
|
922
|
+
ctx.inject(["storageDomain", "webServer"], (injected) => {
|
|
923
|
+
const services = injected;
|
|
924
|
+
services.effect(() => {
|
|
925
|
+
let disposed = false;
|
|
926
|
+
let store;
|
|
927
|
+
openTalkMapStore(services.storageDomain).then((opened) => {
|
|
928
|
+
if (disposed) {
|
|
929
|
+
opened.domain.close();
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
store = opened;
|
|
933
|
+
resolveStore(opened);
|
|
934
|
+
services.logger?.info?.("[dsh-talk-map] storage domain open, routes live at /talk-map/");
|
|
935
|
+
}).catch((error) => {
|
|
936
|
+
services.logger?.warn(`[dsh-talk-map] storage domain failed to open: ${String(error)}`);
|
|
937
|
+
rejectStore(error);
|
|
938
|
+
});
|
|
939
|
+
const unmountRoutes = mountTalkMapRoutes(services, storeReady, runtime);
|
|
940
|
+
return () => {
|
|
941
|
+
disposed = true;
|
|
942
|
+
unmountRoutes();
|
|
943
|
+
store?.domain.close();
|
|
944
|
+
};
|
|
945
|
+
}, "dsh-talk-map: domain + routes");
|
|
946
|
+
});
|
|
947
|
+
ctx.inject([
|
|
948
|
+
"sessions",
|
|
949
|
+
"sessionQuery",
|
|
950
|
+
"sessionController",
|
|
951
|
+
"llm",
|
|
952
|
+
"agentDefaultModel"
|
|
953
|
+
], (injected) => {
|
|
954
|
+
const services = injected;
|
|
955
|
+
services.effect(() => {
|
|
956
|
+
/** Host-side mirror of the client push text (digest-text.ts). */
|
|
957
|
+
const buildPushTextHost = (title, digest) => {
|
|
958
|
+
const now = new Date();
|
|
959
|
+
const stamp = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
|
|
960
|
+
const body = [];
|
|
961
|
+
if (digest?.summary) body.push(`摘要:${digest.summary}`);
|
|
962
|
+
if (Array.isArray(digest?.keyFindings) && digest.keyFindings.length > 0) {
|
|
963
|
+
body.push("关键结论:");
|
|
964
|
+
for (const finding of digest.keyFindings) body.push(`- ${finding}`);
|
|
965
|
+
}
|
|
966
|
+
const next = digest?.nextStep || digest?.todoNext || "";
|
|
967
|
+
if (next !== "") body.push(`下一步:${next}`);
|
|
968
|
+
body.push(`【提醒】以上是摘要提纲,不是完整对话。需要细节(具体命令、参数、结论出处)时,请随时回到原会话「${title}」查看完整对话记录。`);
|
|
969
|
+
return [`【来自「${title}」的更新 · ${stamp}】`, ...body].join("\n");
|
|
970
|
+
};
|
|
971
|
+
/** Sessions pulled from by at least one auto-push edge. */
|
|
972
|
+
const refreshAutoSources = async () => {
|
|
973
|
+
const store = await storeReady;
|
|
974
|
+
const set = new Set();
|
|
975
|
+
for (const [, edge] of store.edges.entries()) {
|
|
976
|
+
if (edge?.injection?.autoPush !== true) continue;
|
|
977
|
+
const card = store.cards.get(edge.fromCardId);
|
|
978
|
+
if (card !== void 0) set.add(card.sessionId);
|
|
979
|
+
}
|
|
980
|
+
runtime.autoPushSessions = set;
|
|
981
|
+
return set;
|
|
982
|
+
};
|
|
983
|
+
runtime.autoPushSessions = new Set();
|
|
984
|
+
void refreshAutoSources();
|
|
985
|
+
const pipeline = new DigestPipeline(
|
|
986
|
+
services,
|
|
987
|
+
storeReady,
|
|
988
|
+
{
|
|
989
|
+
...DIGEST_DEFAULTS,
|
|
990
|
+
shouldAuto: (sessionId) => runtime.autoPushSessions.has(sessionId),
|
|
991
|
+
},
|
|
992
|
+
/** Runs only when a digest really changed (hash differs). */
|
|
993
|
+
async (sessionId, digest) => {
|
|
994
|
+
const store = await storeReady;
|
|
995
|
+
const targets = [];
|
|
996
|
+
for (const [, edge] of store.edges.entries()) {
|
|
997
|
+
if (edge?.injection?.autoPush !== true) continue;
|
|
998
|
+
const from = store.cards.get(edge.fromCardId);
|
|
999
|
+
const to = store.cards.get(edge.toCardId);
|
|
1000
|
+
if (from?.sessionId !== sessionId || to === void 0) continue;
|
|
1001
|
+
targets.push({ sessionId: to.sessionId, edgeId: edge.id ?? edge.edgeId });
|
|
1002
|
+
}
|
|
1003
|
+
if (targets.length === 0) return;
|
|
1004
|
+
const records = await services.sessionQuery.listSessions().catch(() => []);
|
|
1005
|
+
const title = records.find((record) => record.header.id === sessionId)?.header.title ?? sessionId;
|
|
1006
|
+
const text = buildPushTextHost(title, digest);
|
|
1007
|
+
const pushedAt = Date.now();
|
|
1008
|
+
for (const target of targets) {
|
|
1009
|
+
try {
|
|
1010
|
+
await runtime.spawner.injectInto(target.sessionId, [{ sessionId, text }]);
|
|
1011
|
+
// Stamp the edge so the map can draw "synced" instead of "behind".
|
|
1012
|
+
if (typeof target.edgeId === "string") {
|
|
1013
|
+
const edge = await store.edges.get(target.edgeId);
|
|
1014
|
+
if (edge !== void 0) await store.edges.put(target.edgeId, { ...edge, lastPushAt: pushedAt });
|
|
1015
|
+
}
|
|
1016
|
+
services.logger?.info?.(`[dsh-talk-map] auto-pushed digest → ${target.sessionId}`);
|
|
1017
|
+
} catch (error) {
|
|
1018
|
+
services.logger?.warn(`[dsh-talk-map] auto push failed: ${String(error)}`);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
},
|
|
1022
|
+
);
|
|
1023
|
+
const stop = pipeline.start();
|
|
1024
|
+
runtime.digest = pipeline;
|
|
1025
|
+
// Full-text search over every conversation. `sessionController.search`
|
|
1026
|
+
// is the API-domain wrapper (it needs an owning Agent and answers
|
|
1027
|
+
// SessionQueryError when the Host itself asks), so this goes through the
|
|
1028
|
+
// corpus query service instead.
|
|
1029
|
+
/**
|
|
1030
|
+
* One corpus query, nothing else. Measured on the real corpus: a search that
|
|
1031
|
+
* also ran searchEvents per session took 12-15 s; this form just returns the
|
|
1032
|
+
* best match the index already computed. Extra hits inside one conversation
|
|
1033
|
+
* are fetched by /talk-map/search-session when the user asks for them.
|
|
1034
|
+
*/
|
|
1035
|
+
/** ±80/120 chars around the match, elided like a transcript snippet. */
|
|
1036
|
+
const excerptAround = (text, at, length) => {
|
|
1037
|
+
const start = Math.max(0, at - 80);
|
|
1038
|
+
const end = Math.min(text.length, at + length + 120);
|
|
1039
|
+
return (start > 0 ? "…" : "") + text.slice(start, end) + (end < text.length ? "…" : "");
|
|
1040
|
+
};
|
|
1041
|
+
/**
|
|
1042
|
+
* Only the text the transcript actually shows: your own messages and the
|
|
1043
|
+
* assistant's answers. Tool arguments and tool output are dropped, so a
|
|
1044
|
+
* conversation that matched only inside a command's stdout disappears.
|
|
1045
|
+
*/
|
|
1046
|
+
const visibleMatch = async (searchCorpus, sessionId, query) => {
|
|
1047
|
+
const docs = await searchCorpus.filterEvents(sessionId, [
|
|
1048
|
+
{ kind: "type", values: ["user/message", "assistant/message"] },
|
|
1049
|
+
{ kind: "text", text: query }
|
|
1050
|
+
]);
|
|
1051
|
+
const needle = query.toLowerCase();
|
|
1052
|
+
for (const doc of docs ?? []) {
|
|
1053
|
+
const text = typeof doc?.text === "string" ? doc.text : "";
|
|
1054
|
+
const at = text.toLowerCase().indexOf(needle);
|
|
1055
|
+
if (at < 0) continue;
|
|
1056
|
+
return {
|
|
1057
|
+
line: excerptAround(text, at, query.length),
|
|
1058
|
+
seq: typeof doc.seq === "number" ? doc.seq : null
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
return null;
|
|
1062
|
+
};
|
|
1063
|
+
runtime.search = async (query, cwd) => {
|
|
1064
|
+
const corpus = runtime.sessionQuery;
|
|
1065
|
+
if (corpus === void 0) throw new Error("sessionQuery unavailable");
|
|
1066
|
+
const signal = new AbortController().signal;
|
|
1067
|
+
const scoped = typeof cwd === "string" && cwd !== "";
|
|
1068
|
+
const page = await corpus.searchSessions(
|
|
1069
|
+
scoped ? { query, limit: 10, filters: [{ kind: "cwd", values: [cwd] }] } : { query, limit: 10 },
|
|
1070
|
+
{ signal }
|
|
1071
|
+
);
|
|
1072
|
+
// Only what the transcript actually shows: your messages and the
|
|
1073
|
+
// assistant's answers. Tool arguments, tool output, system/developer
|
|
1074
|
+
// envelopes are noise — and skipping them also makes the query cheaper.
|
|
1075
|
+
const searchable = new Set(["user/message", "assistant/message"]);
|
|
1076
|
+
const candidates = (page?.items ?? []).map((hit) => {
|
|
1077
|
+
const best = hit?.bestMatch;
|
|
1078
|
+
const snippet = typeof best?.snippet === "string" ? best.snippet.trim() : "";
|
|
1079
|
+
const line = snippet.split(/\r?\n/).map((part) => part.trim()).find((part) => part !== "") ?? "";
|
|
1080
|
+
return {
|
|
1081
|
+
sessionId: hit?.header?.id ?? hit?.sessionId ?? "",
|
|
1082
|
+
type: typeof best?.type === "string" ? best.type : "",
|
|
1083
|
+
line,
|
|
1084
|
+
seq: typeof best?.seq === "number" ? best.seq : null
|
|
1085
|
+
};
|
|
1086
|
+
}).filter((entry) => entry.sessionId !== "");
|
|
1087
|
+
// Verify the strongest hits against the visible transcript (in parallel,
|
|
1088
|
+
// capped) and take the snippet from there.
|
|
1089
|
+
const verified = await Promise.all(candidates.slice(0, 6).map(async (entry) => {
|
|
1090
|
+
if (entry.type !== "" && !searchable.has(entry.type)) return null;
|
|
1091
|
+
try {
|
|
1092
|
+
const match = await visibleMatch(corpus, entry.sessionId, query);
|
|
1093
|
+
if (match === null) return null;
|
|
1094
|
+
return { sessionId: entry.sessionId, blocks: [[match.line]], seqs: [match.seq] };
|
|
1095
|
+
} catch {
|
|
1096
|
+
return entry.line === "" ? null : { sessionId: entry.sessionId, blocks: [[entry.line]], seqs: [entry.seq] };
|
|
1097
|
+
}
|
|
1098
|
+
}));
|
|
1099
|
+
const items = verified.filter((item) => item !== null);
|
|
1100
|
+
return { items, hasMore: page?.nextCursor !== void 0 };
|
|
1101
|
+
};
|
|
1102
|
+
/** Every extra hit inside ONE conversation (asked for explicitly). */
|
|
1103
|
+
runtime.searchSession = async (sessionId, query) => {
|
|
1104
|
+
const corpus = runtime.sessionQuery;
|
|
1105
|
+
if (corpus === void 0) throw new Error("sessionQuery unavailable");
|
|
1106
|
+
const signal = new AbortController().signal;
|
|
1107
|
+
const events = await corpus.searchEvents(
|
|
1108
|
+
{
|
|
1109
|
+
sessionId, query, limit: 6,
|
|
1110
|
+
filters: [{ kind: "type", values: ["user/message", "assistant/message"] }]
|
|
1111
|
+
},
|
|
1112
|
+
{ signal }
|
|
1113
|
+
);
|
|
1114
|
+
const blocks = [];
|
|
1115
|
+
const seqs = [];
|
|
1116
|
+
for (const hit of events?.items ?? []) {
|
|
1117
|
+
const snippet = typeof hit?.snippet === "string" ? hit.snippet.trim() : "";
|
|
1118
|
+
if (snippet === "") continue;
|
|
1119
|
+
blocks.push([snippet.split(/\r?\n/).map((part) => part.trim()).find((part) => part !== "") ?? ""]);
|
|
1120
|
+
seqs.push(typeof hit?.seq === "number" ? hit.seq : null);
|
|
1121
|
+
}
|
|
1122
|
+
return { blocks, seqs, roles };
|
|
1123
|
+
};
|
|
1124
|
+
/**
|
|
1125
|
+
* The passage around one hit: the matched line plus up to three lines each
|
|
1126
|
+
* way. Read on demand (hover), because reading a session log is expensive.
|
|
1127
|
+
*/
|
|
1128
|
+
/**
|
|
1129
|
+
* The passage a hit came from. The event is found BY CONTENT — the seq
|
|
1130
|
+
* handed over by the search may point at a neighbouring event once a
|
|
1131
|
+
* message has been replayed — and if the query is not in the text we
|
|
1132
|
+
* return nothing rather than an unrelated paragraph.
|
|
1133
|
+
*/
|
|
1134
|
+
runtime.searchContext = async (sessionId, seq, query) => {
|
|
1135
|
+
const corpus = runtime.sessionQuery;
|
|
1136
|
+
if (corpus === void 0) throw new Error("sessionQuery unavailable");
|
|
1137
|
+
const signal = new AbortController().signal;
|
|
1138
|
+
const window = await corpus.readEvent({ sessionId, seq, before: 6, after: 6 }, signal);
|
|
1139
|
+
const wanted = String(query ?? "").toLowerCase();
|
|
1140
|
+
// user/message keeps its content on `data`, assistant/message on
|
|
1141
|
+
// `data.message` — handling only one shape returned the wrong event.
|
|
1142
|
+
const textOfEvent = (event) => {
|
|
1143
|
+
const data = event?.data ?? {};
|
|
1144
|
+
const content = Array.isArray(data.content)
|
|
1145
|
+
? data.content
|
|
1146
|
+
: Array.isArray(data.message?.content) ? data.message.content : [];
|
|
1147
|
+
return textOfBlocks(content);
|
|
1148
|
+
};
|
|
1149
|
+
// Only the conversation itself: a tool result or a document record is not
|
|
1150
|
+
// what the reader is looking for, and its JSON scaffolding is noise.
|
|
1151
|
+
const conversationEvents = new Set(["user/message", "assistant/message"]);
|
|
1152
|
+
const events = [window?.target, ...(window?.events ?? [])]
|
|
1153
|
+
.filter((event) => event !== void 0 && conversationEvents.has(String(event.type ?? "")));
|
|
1154
|
+
const pick = events
|
|
1155
|
+
.map((event) => ({ event, text: String(textOfEvent(event) ?? "").trim() }))
|
|
1156
|
+
.filter((entry) => entry.text !== "" && entry.text.toLowerCase().includes(wanted))
|
|
1157
|
+
.sort((a, b) => (b.event.seq ?? 0) - (a.event.seq ?? 0))[0];
|
|
1158
|
+
if (pick === undefined) return { lines: [] };
|
|
1159
|
+
const all = pick.text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "");
|
|
1160
|
+
const at = all.findIndex((line) => line.toLowerCase().includes(wanted));
|
|
1161
|
+
if (all.length <= 1) {
|
|
1162
|
+
// One long paragraph: hand back a wide character window instead.
|
|
1163
|
+
const flat = pick.text.replace(/\s+/g, " ");
|
|
1164
|
+
const index = Math.max(0, flat.toLowerCase().indexOf(wanted));
|
|
1165
|
+
const start = Math.max(0, index - 420);
|
|
1166
|
+
const end = Math.min(flat.length, index + 520);
|
|
1167
|
+
return { lines: [(start > 0 ? "…" : "") + flat.slice(start, end) + (end < flat.length ? "…" : "")] };
|
|
1168
|
+
}
|
|
1169
|
+
const index = at < 0 ? 0 : at;
|
|
1170
|
+
const from = Math.max(0, index - 6);
|
|
1171
|
+
const to = Math.min(all.length - 1, index + 6);
|
|
1172
|
+
const lines = all.slice(from, to + 1).map((line) => {
|
|
1173
|
+
if (line.length <= 400) return line;
|
|
1174
|
+
const hitAt = Math.max(0, line.toLowerCase().indexOf(wanted));
|
|
1175
|
+
return (hitAt > 140 ? "…" : "") + line.slice(Math.max(0, hitAt - 140), hitAt + 260) + "…";
|
|
1176
|
+
});
|
|
1177
|
+
return { lines };
|
|
1178
|
+
};
|
|
1179
|
+
storeReady.then((store) => {
|
|
1180
|
+
if (runtime.digest !== pipeline) return;
|
|
1181
|
+
const missing = [...new Set([...store.cards.entries()].map(([, card]) => card.sessionId))].filter((sessionId) => {
|
|
1182
|
+
const digest = store.digests.get(sessionId);
|
|
1183
|
+
return digest === void 0 || digest.summary === "";
|
|
1184
|
+
});
|
|
1185
|
+
pipeline.backfill(missing);
|
|
1186
|
+
}).catch(() => void 0);
|
|
1187
|
+
return () => {
|
|
1188
|
+
stop();
|
|
1189
|
+
if (runtime.digest === pipeline) delete runtime.digest;
|
|
1190
|
+
};
|
|
1191
|
+
}, "dsh-talk-map: digest pipeline");
|
|
1192
|
+
});
|
|
1193
|
+
ctx.inject(["agentDefaultModel"], (injected) => {
|
|
1194
|
+
const services = injected;
|
|
1195
|
+
services.effect(() => {
|
|
1196
|
+
runtime.modelDefault = () => services.agentDefaultModel.currentSelection();
|
|
1197
|
+
return () => {
|
|
1198
|
+
delete runtime.modelDefault;
|
|
1199
|
+
};
|
|
1200
|
+
}, "dsh-talk-map: model default");
|
|
1201
|
+
});
|
|
1202
|
+
ctx.inject(["sessionQuery"], (injected) => {
|
|
1203
|
+
const services = injected;
|
|
1204
|
+
services.effect(() => {
|
|
1205
|
+
runtime.sessionQuery = services.sessionQuery;
|
|
1206
|
+
return () => {
|
|
1207
|
+
if (runtime.sessionQuery === services.sessionQuery) delete runtime.sessionQuery;
|
|
1208
|
+
};
|
|
1209
|
+
}, "dsh-talk-map: session query");
|
|
1210
|
+
});
|
|
1211
|
+
ctx.inject(["agentPresets"], (injected) => {
|
|
1212
|
+
const services = injected;
|
|
1213
|
+
services.effect(() => {
|
|
1214
|
+
runtime.presetDefault = () => services.agentPresets.defaultId;
|
|
1215
|
+
return () => {
|
|
1216
|
+
delete runtime.presetDefault;
|
|
1217
|
+
};
|
|
1218
|
+
}, "dsh-talk-map: preset default");
|
|
1219
|
+
});
|
|
1220
|
+
ctx.inject([
|
|
1221
|
+
"agents",
|
|
1222
|
+
"sessionQuery",
|
|
1223
|
+
"workspaceRegistry"
|
|
1224
|
+
], (injected) => {
|
|
1225
|
+
const services = injected;
|
|
1226
|
+
services.effect(() => {
|
|
1227
|
+
const spawner = new Spawner(services, storeReady);
|
|
1228
|
+
runtime.spawner = spawner;
|
|
1229
|
+
return () => {
|
|
1230
|
+
if (runtime.spawner === spawner) delete runtime.spawner;
|
|
1231
|
+
};
|
|
1232
|
+
}, "dsh-talk-map: spawner");
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
//#endregion
|
|
1236
|
+
export { apply, name };
|