dsh-talk-map 0.1.68 → 0.1.69

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/client/client.js CHANGED
@@ -279,6 +279,13 @@ var talkMapApi = {
279
279
  lastUserMessages(sessionIds) {
280
280
  return postJson("/talk-map/last-user", { sessionIds });
281
281
  },
282
+ /**
283
+ * The live window: what the model is given right now, minus everything compaction
284
+ * already pruned. Powers the fork panel's "current context" mode.
285
+ */
286
+ contextWindow(sessionId, maxChars) {
287
+ return postJson("/talk-map/context-window", { sessionId, ...maxChars !== void 0 ? { maxChars } : {} });
288
+ },
282
289
  /**
283
290
  * Full-text search across every conversation, done Host-side. This is the
284
291
  * fallback when the shared connection's RPC surface is unavailable, so the
@@ -367,6 +374,14 @@ var zh = {
367
374
  "spawn.cancel": "取消",
368
375
  "spawn.mode.none": "不继承",
369
376
  "spawn.mode.digest": "摘要注入",
377
+ "spawn.mode.context": "当前上下文",
378
+ "spawn.contextHint": "注入这段对话「当前」发给模型的上下文(已经被压缩掉的历史不在里面)。可以编辑后再开:",
379
+ "spawn.contextLoading": "正在读取当前上下文……",
380
+ "spawn.contextEmpty": "这段对话暂时没有可注入的内容(可能刚压缩完,或还没有消息)。",
381
+ "spawn.contextLoaded": "已读取 {n} 个字符、{m} 条记录。",
382
+ "spawn.contextTruncated": "内容过长,只保留最近 {n} 个字符。",
383
+ "inject.contextHeader": "【上下文注入 · 当前上下文 · 来自】",
384
+ "inject.contextNote": "(以上是母对话当前仍在上下文里的内容;更早的部分已被压缩,不在其中。)",
370
385
  "spawn.mode.full": "完整对话",
371
386
  "spawn.noneHint": "全新对话,只保留一条关联线。输入第一句话(回车发送):",
372
387
  "spawn.fullHint": "新对话将携带这段对话的完整历史继续(dsh 原生分叉)。",
@@ -465,7 +480,7 @@ var zh = {
465
480
  "digest.empty": "这条对话还没有摘要,先刷新摘要再来看。",
466
481
  "digest.copy": "复制",
467
482
  "digest.close": "关闭",
468
- "global.searchPlaceholder": "b68 · 搜地图上的卡片(标题/正文)",
483
+ "global.searchPlaceholder": "b69 · 搜地图上的卡片(标题/正文)",
469
484
  "global.searchRun": "搜索",
470
485
  "global.searchTitle": "搜索地图",
471
486
  "font.group": "文字大小",
@@ -542,6 +557,14 @@ var en = {
542
557
  "spawn.cancel": "Cancel",
543
558
  "spawn.mode.none": "No context",
544
559
  "spawn.mode.digest": "Inject digest",
560
+ "spawn.mode.context": "Current context",
561
+ "spawn.contextHint": "Inject the context this conversation is currently given (already-compressed history is excluded). Edit it before you start:",
562
+ "spawn.contextLoading": "Reading the current context…",
563
+ "spawn.contextEmpty": "Nothing to inject right now (freshly compacted, or no messages yet).",
564
+ "spawn.contextLoaded": "Read {n} characters across {m} records.",
565
+ "spawn.contextTruncated": "Too long: kept the most recent {n} characters.",
566
+ "inject.contextHeader": "[Context injection · current context · from]",
567
+ "inject.contextNote": "(The above is what the parent still has in context; earlier parts were compacted away.)",
545
568
  "spawn.mode.full": "Full history",
546
569
  "spawn.noneHint": "A fresh conversation, linked visually only. Type the first message (Enter sends):",
547
570
  "spawn.fullHint": "The new conversation continues with this one's FULL history (dsh-native fork).",
@@ -633,7 +656,7 @@ var en = {
633
656
  "menu.noGroup": "Remove from group (free card)",
634
657
  "menu.open": "Open conversation",
635
658
  "menu.markUnread": "Mark as unread",
636
- "global.searchPlaceholder": "b68 · Search cards on the map",
659
+ "global.searchPlaceholder": "b69 · Search cards on the map",
637
660
  "global.searchRun": "Search",
638
661
  "global.searchTitle": "Search the map",
639
662
  "font.group": "Text size",
@@ -12723,6 +12746,8 @@ function SpawnPreview(props) {
12723
12746
  const [mode, setMode] = (0, import_react9.useState)("full");
12724
12747
  const [text, setText] = (0, import_react9.useState)(() => buildInjectionText(pending.parent.title, digest));
12725
12748
  const [firstMessage, setFirstMessage] = (0, import_react9.useState)("");
12749
+ const [contextBusy, setContextBusy] = (0, import_react9.useState)(false);
12750
+ const [contextNote, setContextNote] = (0, import_react9.useState)(void 0);
12726
12751
  const [busy, setBusy] = (0, import_react9.useState)(false);
12727
12752
  const [error, setError] = (0, import_react9.useState)(void 0);
12728
12753
  (0, import_react9.useEffect)(() => {
@@ -12739,6 +12764,29 @@ function SpawnPreview(props) {
12739
12764
  release();
12740
12765
  };
12741
12766
  }, []);
12767
+ (0, import_react9.useEffect)(() => {
12768
+ if (mode !== "context") return;
12769
+ let alive = true;
12770
+ setContextBusy(true);
12771
+ setContextNote(void 0);
12772
+ void talkMapApi.contextWindow(pending.parent.sessionId).then((page) => {
12773
+ if (!alive) return;
12774
+ const body = page.text.trim();
12775
+ setText(body === "" ? "" : `${t("inject.contextHeader")}「${pending.parent.title}」
12776
+
12777
+ ${body}
12778
+
12779
+ ${t("inject.contextNote")}`);
12780
+ setContextNote(body === "" ? t("spawn.contextEmpty") : page.truncated ? t("spawn.contextTruncated", { n: String(page.chars) }) : t("spawn.contextLoaded", { n: String(page.chars), m: String(page.entries) }));
12781
+ }).catch((error2) => {
12782
+ if (alive) setContextNote(String(error2?.message ?? error2));
12783
+ }).finally(() => {
12784
+ if (alive) setContextBusy(false);
12785
+ });
12786
+ return () => {
12787
+ alive = false;
12788
+ };
12789
+ }, [mode, pending.parent.sessionId]);
12742
12790
  const addCardAndEdge = (sessionId, kind, injectedText) => {
12743
12791
  const cardId = newCardId();
12744
12792
  const card = {
@@ -12793,6 +12841,16 @@ function SpawnPreview(props) {
12793
12841
  jumpIn(created2.sessionId);
12794
12842
  return;
12795
12843
  }
12844
+ if (mode === "context") {
12845
+ if (text.trim() === "") throw new Error(t("spawn.needText"));
12846
+ const created2 = await createSession();
12847
+ await talkMapApi.injectContext(created2.sessionId, [
12848
+ { sessionId: pending.parent.sessionId, text }
12849
+ ]);
12850
+ addCardAndEdge(created2.sessionId, "context", text);
12851
+ jumpIn(created2.sessionId);
12852
+ return;
12853
+ }
12796
12854
  if (mode === "full") {
12797
12855
  const childId = await forkSessionInUi(pending.parent.sessionId);
12798
12856
  addCardAndEdge(childId, "full");
@@ -12816,6 +12874,7 @@ function SpawnPreview(props) {
12816
12874
  };
12817
12875
  const modes = [
12818
12876
  { id: "digest", label: t("spawn.mode.digest") },
12877
+ { id: "context", label: t("spawn.mode.context") },
12819
12878
  { id: "full", label: t("spawn.mode.full") }
12820
12879
  ];
12821
12880
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: talk_map_default["spawnPanel"], role: "dialog", "aria-label": t("spawn.heading"), children: [
@@ -12851,6 +12910,21 @@ function SpawnPreview(props) {
12851
12910
  }
12852
12911
  }
12853
12912
  )
12913
+ ] }) : mode === "context" ? /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_jsx_runtime11.Fragment, { children: [
12914
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: talk_map_default["spawnHint"], children: t("spawn.contextHint") }),
12915
+ contextNote !== void 0 ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: talk_map_default["spawnHint"], children: contextNote }) : null,
12916
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
12917
+ "textarea",
12918
+ {
12919
+ className: `${talk_map_default["spawnTextarea"]} nodrag nowheel`,
12920
+ value: contextBusy ? t("spawn.contextLoading") : text,
12921
+ readOnly: contextBusy,
12922
+ rows: 9,
12923
+ onChange: (event) => {
12924
+ setText(event.target.value);
12925
+ }
12926
+ }
12927
+ )
12854
12928
  ] }) : mode === "none" ? /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_jsx_runtime11.Fragment, { children: [
12855
12929
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: talk_map_default["spawnHint"], children: t("spawn.noneHint") }),
12856
12930
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
@@ -12892,7 +12966,7 @@ function SpawnPreview(props) {
12892
12966
  onClick: () => {
12893
12967
  void confirm();
12894
12968
  },
12895
- disabled: busy || mode === "digest" && text.trim() === "" || mode === "none" && firstMessage.trim() === "",
12969
+ disabled: busy || contextBusy || mode === "digest" && text.trim() === "" || mode === "context" && text.trim() === "" || mode === "none" && firstMessage.trim() === "",
12896
12970
  children: busy ? t("spawn.busy") : t("spawn.confirm")
12897
12971
  }
12898
12972
  )
package/lib/index.js CHANGED
@@ -1,22 +1,14 @@
1
1
  import { createHash } from "node:crypto";
2
- import { mkdir, appendFile } from "node:fs/promises";
2
+ import { mkdir } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { resolve, sep } from "node:path";
5
5
  import { z } from "zod";
6
- //#region src/host/digest/extract.ts
6
+ // src/host/digest/extract.ts
7
7
  const MAX_CHARS = 24e3;
8
- function textOfBlocks(content) {
8
+ function textOfBlocks$1(content) {
9
9
  if (!Array.isArray(content)) return "";
10
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
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
12
  function extractFromSurface(events, capturedThroughSeq) {
21
13
  const lines = [];
22
14
  let todoNext;
@@ -26,14 +18,14 @@ function extractFromSurface(events, capturedThroughSeq) {
26
18
  if (event.type === "user/message") {
27
19
  const message = event.data;
28
20
  if ((message?.source)?.kind === "tool") continue;
29
- const text = textOfBlocks(message?.content);
21
+ const text = textOfBlocks$1(message?.content);
30
22
  if (text !== "") lines.push({
31
23
  role: "user",
32
24
  text
33
25
  });
34
26
  } else if (event.type === "assistant/message") {
35
27
  const data = event.data;
36
- const text = textOfBlocks(data?.message?.content);
28
+ const text = textOfBlocks$1(data?.message?.content);
37
29
  if (text !== "") lines.push({
38
30
  role: "assistant",
39
31
  text
@@ -50,8 +42,7 @@ function extractFromSurface(events, capturedThroughSeq) {
50
42
  messageCount: recent.length
51
43
  };
52
44
  }
53
- //#endregion
54
- //#region src/host/digest/prompt.ts
45
+ // src/host/digest/prompt.ts
55
46
  /**
56
47
  * Digest prompt: three fields, strict JSON, the conversation's own language.
57
48
  * Structure follows compaction-basic's summarizer style (structured, bounded)
@@ -90,8 +81,7 @@ function parseDigestOutput(raw) {
90
81
  nextStep: parsed.nextStep.slice(0, 120)
91
82
  };
92
83
  }
93
- //#endregion
94
- //#region src/host/digest/pipeline.ts
84
+ // src/host/digest/pipeline.ts
95
85
  /**
96
86
  * Digest pipeline: turn/end → per-session debounce → single-flight queue →
97
87
  * readSurface → extract → hash-skip → one LLM call → digests table.
@@ -101,7 +91,7 @@ function parseDigestOutput(raw) {
101
91
  * previous digest fields survive, with `error` set for the card badge.
102
92
  */
103
93
  const DIGEST_DEFAULTS = {
104
- enabled: false,
94
+ enabled: true,
105
95
  idleMs: 3e4
106
96
  };
107
97
  const MIN_MESSAGES = 2;
@@ -124,9 +114,7 @@ var DigestPipeline = class {
124
114
  /** Wire the turn/end trigger; returns the disposer. */
125
115
  start() {
126
116
  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;
117
+ if (!this.config.enabled) return;
130
118
  const session = args[0];
131
119
  if (args[1]?.type !== "turn/end" || typeof session?.id !== "string") return;
132
120
  this.schedule(session.id);
@@ -154,13 +142,6 @@ var DigestPipeline = class {
154
142
  async refresh(sessionId) {
155
143
  return await this.run(sessionId, { force: true });
156
144
  }
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
145
  /** Queue sessions that have no digest yet (imported/backlog cards). */
165
146
  backfill(sessionIds) {
166
147
  for (const sessionId of sessionIds) this.enqueue(sessionId);
@@ -251,7 +232,8 @@ var DigestPipeline = class {
251
232
  text: digestUserPrompt(transcript)
252
233
  }],
253
234
  source: {
254
- kind: "plugin:dsh-talk-map"
235
+ kind: "plugin",
236
+ plugin: "dsh-talk-map"
255
237
  }
256
238
  };
257
239
  let text = "";
@@ -270,8 +252,7 @@ var DigestPipeline = class {
270
252
  return text;
271
253
  }
272
254
  };
273
- //#endregion
274
- //#region src/host/spawn.ts
255
+ // src/host/spawn.ts
275
256
  /** Typed so the HTTP layer can answer with a structured code instead of
276
257
  * clients substring-matching a stringified error. */
277
258
  var SessionNotLiveError = class extends Error {
@@ -313,11 +294,7 @@ var Spawner = class {
313
294
  summary: `Context injected from session ${parent.sessionId}`
314
295
  }
315
296
  };
316
- try {
317
- agent.inject(message);
318
- } catch (error) {
319
- throw new Error("talk-map: 注入被拒(" + String(error?.message ?? error) + ")");
320
- }
297
+ agent.inject(message);
321
298
  }
322
299
  }
323
300
  /** Live handles: dropping one disposes the agent AND removes its session from the live store — keep them. */
@@ -360,11 +337,7 @@ var Spawner = class {
360
337
  summary: `Context injected from session ${parent.sessionId}`
361
338
  }
362
339
  };
363
- try {
364
- handle.agent.inject(message);
365
- } catch (error) {
366
- throw new Error("talk-map: 注入被拒(" + String(error?.message ?? error) + ")");
367
- }
340
+ handle.agent.inject(message);
368
341
  }
369
342
  const cardId = `card-${crypto.randomUUID()}`;
370
343
  const card = {
@@ -387,8 +360,6 @@ var Spawner = class {
387
360
  kind: "digest",
388
361
  injectedText: parent.text
389
362
  },
390
- // The line just delivered: the map's sync animation keys off this.
391
- lastPushAt: Date.now(),
392
363
  createdAt: Date.now()
393
364
  };
394
365
  await store.edges.put(edgeId, edge);
@@ -403,8 +374,7 @@ var Spawner = class {
403
374
  };
404
375
  }
405
376
  };
406
- //#endregion
407
- //#region src/host/store.ts
377
+ // src/host/store.ts
408
378
  /**
409
379
  * The talk-map storage domain: canvas-private data only. Session content,
410
380
  * titles, and lineage stay with dsh's own services — this domain stores what
@@ -555,9 +525,17 @@ async function openTalkMapStore(storageDomain) {
555
525
  });
556
526
  return store;
557
527
  }
558
- //#endregion
559
- //#region src/host/routes.ts
528
+ // src/host/routes.ts
560
529
  const MAX_BODY_BYTES = 1048576;
530
+ /** Concatenate the text blocks of a message payload (tool results have none). */
531
+ function textOfBlocks(content) {
532
+ if (!Array.isArray(content)) return "";
533
+ return content.filter((block) => typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n").trim();
534
+ }
535
+ function isHumanMessage(source) {
536
+ const kind = source?.kind;
537
+ return kind === void 0 || kind === "user";
538
+ }
561
539
  function sendJson(response, status, body) {
562
540
  const payload = JSON.stringify(body);
563
541
  response.writeHead(status, {
@@ -669,43 +647,6 @@ function mountTalkMapRoutes(services, storeReady, runtime) {
669
647
  });
670
648
  return;
671
649
  }
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
650
  if (route === "GET /talk-map/events") {
710
651
  response.writeHead(200, {
711
652
  "content-type": "text/event-stream",
@@ -798,84 +739,185 @@ if (route === "POST /talk-map/last-user") {
798
739
  sendJson(response, 200, { ok: true });
799
740
  return;
800
741
  }
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 });
742
+ if (route === "POST /talk-map/spawn") {
743
+ if (runtime.spawner === void 0) {
744
+ sendJson(response, 503, { error: "spawn layer unavailable (agents service missing)" });
806
745
  return;
807
746
  }
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) });
747
+ const body = spawnBody.parse(await readJsonBody(request));
748
+ sendJson(response, 200, await runtime.spawner.spawn(body));
749
+ return;
750
+ }
751
+ if (route === "POST /talk-map/fs/ensure-dir") {
752
+ const body = ensureDirBody.parse(await readJsonBody(request));
753
+ const target = resolve(body.path);
754
+ const home = homedir();
755
+ if (target !== home && !target.startsWith(home + sep)) {
756
+ sendJson(response, 400, { error: "path must be inside the home directory" });
757
+ return;
813
758
  }
759
+ await mkdir(target, { recursive: true });
760
+ sendJson(response, 200, {
761
+ ok: true,
762
+ path: target
763
+ });
814
764
  return;
815
765
  }
816
- if (route === "POST /talk-map/search-session") {
766
+ /**
767
+ * Full-text search over every conversation, on the Host's own service.
768
+ * The drawer prefers the shared connection's session/search, but falls
769
+ * back here so the feature cannot degrade to title-only matching.
770
+ */
771
+ if (route === "POST /talk-map/search") {
817
772
  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: [] });
773
+ const query = typeof body?.query === "string" ? body.query.trim() : "";
774
+ const search = runtime.search;
775
+ if (query === "" || search === void 0) {
776
+ sendJson(response, 200, {
777
+ items: [],
778
+ hasMore: false
779
+ });
822
780
  return;
823
781
  }
824
782
  try {
825
- sendJson(response, 200, await runtime.searchSession(sessionId, query));
783
+ const page = await search(query);
784
+ sendJson(response, 200, {
785
+ items: page?.items ?? [],
786
+ hasMore: page?.hasMore === true
787
+ });
826
788
  } catch (error) {
827
- sendJson(response, 200, { blocks: [], seqs: [], error: String(error?.message ?? error) });
789
+ sendJson(response, 500, { error: String(error?.message ?? error) });
828
790
  }
829
791
  return;
830
792
  }
793
+ /** The passage around one hit — read on demand (hover), never with search. */
831
794
  if (route === "POST /talk-map/search-context") {
832
795
  const body = await readJsonBody(request);
833
796
  const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
834
797
  const seq = typeof body?.seq === "number" ? body.seq : null;
835
798
  const query = typeof body?.query === "string" ? body.query : "";
836
- if (sessionId === "" || seq === null || runtime.searchContext === void 0) {
799
+ const read = runtime.searchContext;
800
+ if (sessionId === "" || seq === null || read === void 0) {
837
801
  sendJson(response, 200, { lines: [] });
838
802
  return;
839
803
  }
840
804
  try {
841
- sendJson(response, 200, await runtime.searchContext(sessionId, seq, query));
805
+ sendJson(response, 200, await read(sessionId, seq, query));
842
806
  } catch (error) {
843
- sendJson(response, 200, { lines: [], error: String(error?.message ?? error) });
807
+ sendJson(response, 200, {
808
+ lines: [],
809
+ error: String(error?.message ?? error)
810
+ });
844
811
  }
845
812
  return;
846
813
  }
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));
814
+ if (route === "POST /talk-map/last-user") {
815
+ const body = await readJsonBody(request);
816
+ const ids = Array.isArray(body.sessionIds) ? body.sessionIds.filter((id) => typeof id === "string").slice(0, 200) : [];
817
+ const texts = {};
818
+ const query = runtime.sessionQuery;
819
+ if (query !== void 0) await Promise.all(ids.map(async (sessionId) => {
820
+ try {
821
+ const surface = await query.readSurface(sessionId);
822
+ let text = "";
823
+ for (const raw of surface.events) {
824
+ const event = raw;
825
+ if (event.type !== "user/message") continue;
826
+ if (!isHumanMessage(event.data?.source)) continue;
827
+ const body = textOfBlocks(event.data?.content);
828
+ if (body !== "") text = body;
829
+ }
830
+ if (text !== "") texts[sessionId] = text.length > 240 ? text.slice(0, 240) : text;
831
+ } catch {}
832
+ }));
833
+ sendJson(response, 200, { texts });
854
834
  return;
855
835
  }
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" });
836
+ if (route === "POST /talk-map/context-window") {
837
+ const body = await readJsonBody(request);
838
+ const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
839
+ if (sessionId === "") {
840
+ sendJson(response, 400, { error: "sessionId is required" });
862
841
  return;
863
842
  }
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)" });
843
+ const requested = typeof body?.maxChars === "number" ? Math.round(body.maxChars) : 4e4;
844
+ const maxChars = Math.min(Math.max(requested, 4e3), 4e5);
845
+ const query = runtime.sessionQuery;
846
+ if (query === void 0) {
847
+ sendJson(response, 503, { error: "session surface unavailable" });
874
848
  return;
875
849
  }
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 });
850
+ const surface = await query.readSurface(sessionId);
851
+ const pruned = /* @__PURE__ */ new Set();
852
+ for (const raw of surface.events) {
853
+ const event = raw;
854
+ if (event.type !== "compaction/prune") continue;
855
+ const seqs = event.data?.shadowedSeqs;
856
+ if (!Array.isArray(seqs)) continue;
857
+ for (const seq of seqs) if (typeof seq === "number") pruned.add(seq);
858
+ }
859
+ const lines = [];
860
+ for (const raw of surface.events) {
861
+ const event = raw;
862
+ const seq = typeof event.seq === "number" ? event.seq : -1;
863
+ if (pruned.has(seq)) continue;
864
+ if (event.type === "user/message") {
865
+ const said = textOfBlocks(event.data?.content);
866
+ if (said !== "") lines.push(`USER: ${said}`);
867
+ } else if (event.type === "assistant/message") {
868
+ const said = textOfBlocks(event.data?.message?.content);
869
+ if (said !== "") lines.push(`ASSISTANT: ${said}`);
870
+ } else if (event.type === "tool/call") {
871
+ const name = typeof event.data?.name === "string" ? event.data.name : typeof event.data?.toolName === "string" ? event.data.toolName : "tool";
872
+ let args = "";
873
+ try {
874
+ args = JSON.stringify(event.data?.arguments ?? event.data?.input ?? {});
875
+ } catch {
876
+ args = "";
877
+ }
878
+ lines.push(`TOOL ${name}(${args.slice(0, 160)})`);
879
+ } else if (event.type === "tool/result") {
880
+ const said = textOfBlocks(event.data?.content);
881
+ const body = said !== "" ? said : typeof event.data?.output === "string" ? event.data.output : "";
882
+ if (body !== "") lines.push(`RESULT: ${body.length > 240 ? `${body.slice(0, 240)}…` : body}`);
883
+ }
884
+ }
885
+ const essential = lines.filter((line) => !line.startsWith("TOOL ") && !line.startsWith("RESULT: "));
886
+ const tooling = lines.filter((line) => line.startsWith("TOOL ") || line.startsWith("RESULT: "));
887
+ let text = essential.join("\n\n");
888
+ let truncated = false;
889
+ if (text.length > maxChars) {
890
+ text = text.slice(text.length - maxChars);
891
+ const cut = text.indexOf("\n\n");
892
+ if (cut > 0 && cut < 400) text = text.slice(cut + 2);
893
+ truncated = true;
894
+ } else {
895
+ const room = maxChars - text.length;
896
+ const kept = [];
897
+ let used = 0;
898
+ for (let index = tooling.length - 1; index >= 0; index -= 1) {
899
+ const line = tooling[index];
900
+ if (used + line.length + 2 > room) {
901
+ truncated = true;
902
+ break;
903
+ }
904
+ kept.push(line);
905
+ used += line.length + 2;
906
+ }
907
+ if (kept.length > 0) {
908
+ kept.reverse();
909
+ text = `${text}\n\n[tool activity]\n${kept.join("\n\n")}`;
910
+ }
911
+ if (kept.length < tooling.length) truncated = true;
912
+ }
913
+ sendJson(response, 200, {
914
+ sessionId,
915
+ text,
916
+ chars: text.length,
917
+ entries: lines.length,
918
+ prunedRecords: pruned.size,
919
+ truncated
920
+ });
879
921
  return;
880
922
  }
881
923
  if (route === "POST /talk-map/digest/refresh") {
@@ -907,8 +949,7 @@ if (route === "POST /talk-map/last-user") {
907
949
  unregister();
908
950
  };
909
951
  }
910
- //#endregion
911
- //#region src/index.ts
952
+ // src/index.ts
912
953
  const name = "dsh-talk-map";
913
954
  function apply(ctx) {
914
955
  const runtime = {};
@@ -953,228 +994,31 @@ function apply(ctx) {
953
994
  ], (injected) => {
954
995
  const services = injected;
955
996
  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
- );
997
+ const pipeline = new DigestPipeline(services, storeReady);
1023
998
  const stop = pipeline.start();
1024
999
  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
1000
  /**
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) => {
1001
+ * Full-text search across every conversation, exposed to the drawer through
1002
+ * POST /talk-map/search (see routes.ts).
1003
+ *
1004
+ * Uses the corpus query service, not sessionController.search: the latter
1005
+ * is the API-domain wrapper and needs an owning Agent (it answers
1006
+ * SessionQueryError when the Host itself asks).
1007
+ */
1008
+ runtime.search = async (query) => {
1135
1009
  const corpus = runtime.sessionQuery;
1136
1010
  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);
1011
+ const page = await corpus.searchSessions({
1012
+ query,
1013
+ limit: 20
1014
+ }, { signal: new AbortController().signal });
1015
+ return {
1016
+ items: (page.items ?? []).map((hit) => ({
1017
+ sessionId: hit.header?.id ?? "",
1018
+ snippet: hit.bestMatch?.snippet ?? ""
1019
+ })).filter((item) => item.sessionId !== ""),
1020
+ hasMore: page.nextCursor !== void 0
1148
1021
  };
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
1022
  };
1179
1023
  storeReady.then((store) => {
1180
1024
  if (runtime.digest !== pipeline) return;
@@ -1232,5 +1076,4 @@ const events = [window?.target, ...(window?.events ?? [])]
1232
1076
  }, "dsh-talk-map: spawner");
1233
1077
  });
1234
1078
  }
1235
- //#endregion
1236
1079
  export { apply, name };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-talk-map",
3
- "version": "0.1.68",
3
+ "version": "0.1.69",
4
4
  "description": "Visual conversation map for DeepSeek Harness: an infinite whiteboard where every session is a card — drag to arrange, double-click to start a chat in place, draw an edge to fork a new session with injected context. Built for ADHD-friendly spatial memory. · DSH 可视化对话地图:会话即卡片,双击即聊,连线分叉带上下文的新对话。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -19,7 +19,7 @@
19
19
  "session-manager"
20
20
  ],
21
21
  "scripts": {
22
- "build": "tsdown && node scripts/normalize-client-banner.mjs",
22
+ "build": "tsdown && node scripts/copy-host.mjs && node scripts/normalize-client-banner.mjs",
23
23
  "build:client": "node scripts/build-client.mjs",
24
24
  "harness": "node test/serve.mjs 8791",
25
25
  "probe": "node test/probe.mjs",