dsh-memsearch-community 0.2.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -0
- package/cordis.patch.yml +5 -0
- package/lib/dialogs.js +87 -0
- package/lib/import.js +146 -0
- package/lib/index.js +243 -124
- package/lib/tree.js +164 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -12,6 +12,25 @@ computed locally with ONNX.
|
|
|
12
12
|
|
|
13
13
|
## Changes from upstream
|
|
14
14
|
|
|
15
|
+
**0.3.0 — first-run setup, per-day archive, history import**
|
|
16
|
+
|
|
17
|
+
- **Setup prompts.** On first run the plugin asks three things with native
|
|
18
|
+
desktop dialogs (WinForms / AppleScript / zenity): where the archive should
|
|
19
|
+
live, whether to install the optional `memsearch` CLI, and whether to import
|
|
20
|
+
conversations from before installation. Cancelled or unavailable dialogs fall
|
|
21
|
+
back to the configuration fields in Settings → Plugins.
|
|
22
|
+
- **Per-day archive.** Every captured turn is also written to
|
|
23
|
+
`<dataRoot>/<YYYY.MM.DD>/<session title>.txt`, one file per session, appended
|
|
24
|
+
with a timestamp header. Renaming a session in DSH renames its file.
|
|
25
|
+
- **Retention prompt.** Once the archive holds more than `retentionDays`
|
|
26
|
+
(default 60) day folders, the plugin asks once whether to open the folder for
|
|
27
|
+
cleanup.
|
|
28
|
+
- **History import.** Reads `~/.dsh/sessions/**/session.v4.jsonl.zstd`,
|
|
29
|
+
decompresses them, pairs each real prompt with its final answer, and writes
|
|
30
|
+
them into the same day folders in chronological order.
|
|
31
|
+
- The searchable markdown journal in `~/.memsearch/memory` is still written, so
|
|
32
|
+
semantic search keeps working exactly as before.
|
|
33
|
+
|
|
15
34
|
**0.2.3 — keep reply headings out of the journal structure**
|
|
16
35
|
|
|
17
36
|
The journal uses `### HH:MM` lines as separators and `memsearch index` splits
|
package/cordis.patch.yml
CHANGED
package/lib/dialogs.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Native dialogs for the host operating system.
|
|
3
|
+
*
|
|
4
|
+
* DeepSeek Harness exposes no modal API to Host plugins, so the plugin asks the
|
|
5
|
+
* desktop directly: Windows uses WinForms through PowerShell, macOS uses
|
|
6
|
+
* AppleScript, and Linux falls back to zenity/kdialog when present. Every entry
|
|
7
|
+
* point returns a result object instead of throwing, and resolves to
|
|
8
|
+
* `{ ok: false, reason }` when no prompt could be shown, so the caller can fall
|
|
9
|
+
* back to configuration or a session message.
|
|
10
|
+
*/
|
|
11
|
+
import { execFile } from "node:child_process";
|
|
12
|
+
import os from "node:os";
|
|
13
|
+
|
|
14
|
+
const DIALOG_TIMEOUT = 180000;
|
|
15
|
+
|
|
16
|
+
function run(command, args) {
|
|
17
|
+
return new Promise((resolve) => {
|
|
18
|
+
execFile(command, args, { timeout: DIALOG_TIMEOUT, windowsHide: true, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
|
|
19
|
+
resolve({ err, stdout: String(stdout || ""), stderr: String(stderr || "") });
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const psQuote = (value) => `'${String(value).replace(/'/g, "''")}'`;
|
|
25
|
+
|
|
26
|
+
/** Yes/No message box. Resolves { ok, answer: true|false } or { ok: false, reason }. */
|
|
27
|
+
export async function askYesNo({ title, message, yes = "是", no = "否" }) {
|
|
28
|
+
if (process.platform === "win32") {
|
|
29
|
+
const script = [
|
|
30
|
+
"Add-Type -AssemblyName System.Windows.Forms | Out-Null",
|
|
31
|
+
`$r = [System.Windows.Forms.MessageBox]::Show(${psQuote(message)}, ${psQuote(title)}, 'YesNo', 'Question', 'Button1', 'Button1')`,
|
|
32
|
+
"if ($r -eq 'Yes') { 'YES' } else { 'NO' }",
|
|
33
|
+
].join("; ");
|
|
34
|
+
const res = await run("powershell.exe", ["-NoProfile", "-STA", "-Command", script]);
|
|
35
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
36
|
+
const out = res.stdout.trim();
|
|
37
|
+
if (out === "YES") return { ok: true, answer: true };
|
|
38
|
+
if (out === "NO") return { ok: true, answer: false };
|
|
39
|
+
return { ok: false, reason: "no answer" };
|
|
40
|
+
}
|
|
41
|
+
if (process.platform === "darwin") {
|
|
42
|
+
const script = `display dialog ${JSON.stringify(message)} with title ${JSON.stringify(title)} buttons {${JSON.stringify(no)}, ${JSON.stringify(yes)}} default button ${JSON.stringify(yes)}`;
|
|
43
|
+
const res = await run("osascript", ["-e", script]);
|
|
44
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
45
|
+
return { ok: true, answer: res.stdout.includes(yes) };
|
|
46
|
+
}
|
|
47
|
+
const res = await run("zenity", ["--question", `--title=${title}`, `--text=${message}`, `--ok-label=${yes}`, `--cancel-label=${no}`]);
|
|
48
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
49
|
+
return { ok: true, answer: true };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Folder picker. Resolves { ok, path } or { ok: false, reason }. */
|
|
53
|
+
export async function pickFolder({ title, initial }) {
|
|
54
|
+
if (process.platform === "win32") {
|
|
55
|
+
const script = [
|
|
56
|
+
"Add-Type -AssemblyName System.Windows.Forms | Out-Null",
|
|
57
|
+
"$d = New-Object System.Windows.Forms.FolderBrowserDialog",
|
|
58
|
+
`$d.Description = ${psQuote(title)}`,
|
|
59
|
+
"$d.ShowNewFolderButton = $true",
|
|
60
|
+
initial ? `$d.SelectedPath = ${psQuote(initial)}` : "",
|
|
61
|
+
"if ($d.ShowDialog() -eq 'OK') { $d.SelectedPath } else { '' }",
|
|
62
|
+
].filter(Boolean).join("; ");
|
|
63
|
+
const res = await run("powershell.exe", ["-NoProfile", "-STA", "-Command", script]);
|
|
64
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
65
|
+
const picked = res.stdout.trim();
|
|
66
|
+
return picked ? { ok: true, path: picked } : { ok: false, reason: "cancelled" };
|
|
67
|
+
}
|
|
68
|
+
if (process.platform === "darwin") {
|
|
69
|
+
const res = await run("osascript", ["-e", 'POSIX path of (choose folder with prompt "' + title + '")']);
|
|
70
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
71
|
+
return { ok: true, path: res.stdout.trim() };
|
|
72
|
+
}
|
|
73
|
+
const res = await run("zenity", ["--file-selection", "--directory", `--title=${title}`]);
|
|
74
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
75
|
+
return { ok: true, path: res.stdout.trim() };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Open a folder in the desktop file manager. */
|
|
79
|
+
export async function openFolder(path) {
|
|
80
|
+
if (process.platform === "win32") return run("explorer.exe", [path]);
|
|
81
|
+
if (process.platform === "darwin") return run("open", [path]);
|
|
82
|
+
return run("xdg-open", [path]);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function defaultDataRoot() {
|
|
86
|
+
return `${os.homedir()}\\Documents\\DSH对话数据`.replace(/\\/g, process.platform === "win32" ? "\\" : "/");
|
|
87
|
+
}
|
package/lib/import.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Import conversations that happened before the plugin was installed.
|
|
3
|
+
*
|
|
4
|
+
* DSH keeps every session as `session.v4.jsonl.zstd` under `~/.dsh/sessions`.
|
|
5
|
+
* Each log is decompressed, real user prompts are paired with the final answer
|
|
6
|
+
* of their turn, and the result lands in the same day-folder archive the live
|
|
7
|
+
* capture uses. Files are named after the session title recorded in the log.
|
|
8
|
+
*/
|
|
9
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
10
|
+
import { join, basename } from "node:path";
|
|
11
|
+
import os from "node:os";
|
|
12
|
+
import { zstdDecompressSync } from "node:zlib";
|
|
13
|
+
|
|
14
|
+
const INJECTED_TEXT = /^\s*(<system-reminder>|Time sampled while preparing)/;
|
|
15
|
+
|
|
16
|
+
function textOf(message) {
|
|
17
|
+
if (!message || !Array.isArray(message.content)) return "";
|
|
18
|
+
return message.content
|
|
19
|
+
.filter((b) => b && b.type === "text" && typeof b.text === "string")
|
|
20
|
+
.map((b) => b.text)
|
|
21
|
+
.join("\n")
|
|
22
|
+
.trim();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function payloadOf(data) {
|
|
26
|
+
if (data && typeof data === "object" && data.message && typeof data.message === "object") return data.message;
|
|
27
|
+
return data;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Every exchange of a session log, in order:
|
|
32
|
+
* [{ time, userText, assistantText, title }]
|
|
33
|
+
*/
|
|
34
|
+
export function readSessionLog(events) {
|
|
35
|
+
const exchanges = [];
|
|
36
|
+
let title = "";
|
|
37
|
+
let pending = null;
|
|
38
|
+
|
|
39
|
+
const flush = () => {
|
|
40
|
+
if (pending) {
|
|
41
|
+
exchanges.push(pending);
|
|
42
|
+
pending = null;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
for (const event of events) {
|
|
47
|
+
if (!event || typeof event !== "object") continue;
|
|
48
|
+
if (event.type === "session/title" && event.data && typeof event.data.title === "string") {
|
|
49
|
+
title = event.data.title;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (event.type === "user/message") {
|
|
53
|
+
const source = event.data && event.data.source;
|
|
54
|
+
if (source && source.kind !== "user") continue;
|
|
55
|
+
const text = textOf(payloadOf(event.data));
|
|
56
|
+
if (!text || INJECTED_TEXT.test(text)) continue;
|
|
57
|
+
flush();
|
|
58
|
+
pending = { time: event.time, userText: text, assistantText: "", title };
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (event.type === "assistant/message" && pending) {
|
|
62
|
+
const text = textOf(payloadOf(event.data));
|
|
63
|
+
if (text) pending.assistantText = text; // last text of the turn wins
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
flush();
|
|
67
|
+
|
|
68
|
+
const finalTitle = title || exchanges.find((e) => e.userText)?.userText?.slice(0, 40) || "";
|
|
69
|
+
return exchanges
|
|
70
|
+
.filter((e) => e.userText && e.userText.length >= 10 && e.assistantText)
|
|
71
|
+
.map((e) => ({ ...e, title: title || finalTitle }));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function decompress(file) {
|
|
75
|
+
const buf = readFileSync(file);
|
|
76
|
+
try {
|
|
77
|
+
return zstdDecompressSync(buf).toString("utf8");
|
|
78
|
+
} catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Session logs under a DSH home directory. */
|
|
84
|
+
export function listSessionLogs(dshHome = join(os.homedir(), ".dsh")) {
|
|
85
|
+
const root = join(dshHome, "sessions");
|
|
86
|
+
const found = [];
|
|
87
|
+
if (!existsSync(root)) return found;
|
|
88
|
+
const walk = (dir) => {
|
|
89
|
+
for (const name of readdirSync(dir)) {
|
|
90
|
+
const full = join(dir, name);
|
|
91
|
+
let st;
|
|
92
|
+
try { st = statSync(full); } catch { continue; }
|
|
93
|
+
if (st.isDirectory()) walk(full);
|
|
94
|
+
else if (name === "session.v4.jsonl.zstd") found.push(full);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
walk(root);
|
|
98
|
+
return found;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Import every log into the archive. Returns a summary instead of throwing so
|
|
103
|
+
* the caller can report partial success.
|
|
104
|
+
*/
|
|
105
|
+
export function importHistory(archive, { minPromptLength = 10, maxCaptureChars = 8000, limit } = {}) {
|
|
106
|
+
const summary = { logs: 0, imported: 0, written: 0, skipped: 0, errors: 0 };
|
|
107
|
+
const logs = listSessionLogs();
|
|
108
|
+
summary.logs = logs.length;
|
|
109
|
+
|
|
110
|
+
for (const log of (limit ? logs.slice(0, limit) : logs)) {
|
|
111
|
+
let raw;
|
|
112
|
+
try { raw = decompress(log); } catch { summary.errors++; continue; }
|
|
113
|
+
if (!raw) { summary.errors++; continue; }
|
|
114
|
+
|
|
115
|
+
const events = [];
|
|
116
|
+
for (const line of raw.split("\n")) {
|
|
117
|
+
if (!line) continue;
|
|
118
|
+
try { events.push(JSON.parse(line)); } catch { /* skip */ }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
let exchanges = [];
|
|
122
|
+
try { exchanges = readSessionLog(events); } catch { summary.errors++; continue; }
|
|
123
|
+
const sessionId = basename(join(log, ".."));
|
|
124
|
+
const title = exchanges[0]?.title || sessionId.slice(-6);
|
|
125
|
+
|
|
126
|
+
for (const ex of exchanges) {
|
|
127
|
+
if (ex.userText.length < minPromptLength) { summary.skipped++; continue; }
|
|
128
|
+
const date = new Date(typeof ex.time === "number" ? ex.time : Date.now());
|
|
129
|
+
try {
|
|
130
|
+
archive.appendTurn({
|
|
131
|
+
sessionId,
|
|
132
|
+
title,
|
|
133
|
+
date,
|
|
134
|
+
userText: ex.userText.slice(0, maxCaptureChars),
|
|
135
|
+
assistantText: (ex.assistantText || "").slice(0, maxCaptureChars),
|
|
136
|
+
});
|
|
137
|
+
summary.imported++;
|
|
138
|
+
} catch {
|
|
139
|
+
summary.errors++;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
summary.written++;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return summary;
|
|
146
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -1,50 +1,56 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* dsh-memsearch —
|
|
2
|
+
* dsh-memsearch-community — automatic local memory for DeepSeek Harness.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* 不再让未接住的异常把 DSH 进程拖崩;
|
|
8
|
-
* 3. pre-step 钩子整体包 try/catch,任何异常降级为放行原决策;
|
|
9
|
-
* 4. 兼容 Windows:PATH 用 ; 分隔,CLI 解析同时覆盖 .cmd / .exe。
|
|
4
|
+
* Two stores are written on every captured turn:
|
|
5
|
+
* 1. `<dataRoot>/<YYYY.MM.DD>/<session title>.txt` — human-facing archive
|
|
6
|
+
* 2. `~/.memsearch/memory/YYYY-MM-DD.md` — indexed by the memsearch CLI
|
|
10
7
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
8
|
+
* First activation offers a short setup: where the archive lives, whether to
|
|
9
|
+
* install the optional search CLI, and whether to import conversations from
|
|
10
|
+
* before the plugin existed. Those prompts are native desktop dialogs; when no
|
|
11
|
+
* prompt can be shown the plugin falls back to its configuration.
|
|
15
12
|
*/
|
|
16
13
|
import z from "@deepseek-ai/schemastery";
|
|
17
14
|
import "@deepseek-ai/cordis";
|
|
18
15
|
import { randomUUID } from "node:crypto";
|
|
19
16
|
import { execFile } from "node:child_process";
|
|
20
|
-
import { appendFileSync, existsSync, mkdirSync, readdirSync,
|
|
17
|
+
import { appendFileSync, existsSync, mkdirSync, readdirSync, rmdirSync } from "node:fs";
|
|
21
18
|
import os from "node:os";
|
|
22
19
|
import path from "node:path";
|
|
20
|
+
import { askYesNo, defaultDataRoot, openFolder, pickFolder } from "./dialogs.js";
|
|
21
|
+
import { Archive, dayName, dayStamp } from "./tree.js";
|
|
22
|
+
import { importHistory } from "./import.js";
|
|
23
23
|
|
|
24
|
-
const name = "dsh-memsearch";
|
|
24
|
+
const name = "dsh-memsearch-community";
|
|
25
25
|
const inject = ["agents"];
|
|
26
26
|
|
|
27
27
|
const Config = z.object({
|
|
28
28
|
enabled: z.boolean().default(true),
|
|
29
|
-
/**
|
|
29
|
+
/** Archive root. Empty = ask once, then `~/Documents/DSH对话数据`. */
|
|
30
|
+
dataRoot: z.string().default(""),
|
|
31
|
+
/** Journal dir for the search index; empty = ~/.memsearch/memory. */
|
|
30
32
|
memoryDir: z.string().default(""),
|
|
31
|
-
/** Milvus collection passed to the CLI; empty = configured default. */
|
|
32
33
|
collection: z.string().default(""),
|
|
33
|
-
/** Inject the session-start memsearch status + recall hint. */
|
|
34
34
|
injectSessionStatus: z.boolean().default(true),
|
|
35
|
-
/** Auto-append a journal entry after each turn. */
|
|
36
35
|
capture: z.boolean().default(true),
|
|
37
|
-
/**
|
|
36
|
+
/** Skip turns whose user prompt is shorter than this. */
|
|
38
37
|
captureMinPromptLength: z.number().default(10),
|
|
39
|
-
/** Cap on the raw exchange text written per turn. */
|
|
40
38
|
maxCaptureChars: z.number().default(8000),
|
|
41
|
-
/** Optional summarize plugin id; "" = raw fallback. */
|
|
42
39
|
summarizePlugin: z.string().default(""),
|
|
43
|
-
/** Re-run `memsearch index` after appending a journal entry. */
|
|
44
40
|
indexAfterCapture: z.boolean().default(true),
|
|
41
|
+
/** Ask for the archive folder on first run. */
|
|
42
|
+
askDataRoot: z.boolean().default(true),
|
|
43
|
+
/** Offer to install the memsearch CLI when it is missing. */
|
|
44
|
+
offerCliInstall: z.boolean().default(true),
|
|
45
|
+
/** Install the CLI without asking (pip install memsearch). */
|
|
46
|
+
autoInstallCli: z.boolean().default(false),
|
|
47
|
+
/** Offer to import conversations from before installation. */
|
|
48
|
+
importHistory: z.union([z.const("ask"), z.const("yes"), z.const("no")]).default("ask"),
|
|
49
|
+
/** Day folders kept before the cleanup prompt appears. */
|
|
50
|
+
retentionDays: z.number().default(60),
|
|
45
51
|
});
|
|
46
52
|
|
|
47
|
-
const MS_TIMEOUT = 300000;
|
|
53
|
+
const MS_TIMEOUT = 300000;
|
|
48
54
|
const MS_STATUS_TIMEOUT = 15000;
|
|
49
55
|
const MAX_BUFFER = 8 * 1024 * 1024;
|
|
50
56
|
|
|
@@ -53,7 +59,7 @@ function home() {
|
|
|
53
59
|
}
|
|
54
60
|
|
|
55
61
|
function expandPath(p) {
|
|
56
|
-
return p.replace(/^~(?=$|\/)/, home());
|
|
62
|
+
return String(p || "").replace(/^~(?=$|\/)/, home());
|
|
57
63
|
}
|
|
58
64
|
|
|
59
65
|
function resolveMemoryDir(configured) {
|
|
@@ -63,40 +69,26 @@ function resolveMemoryDir(configured) {
|
|
|
63
69
|
return path.join(home(), ".memsearch", "memory");
|
|
64
70
|
}
|
|
65
71
|
|
|
66
|
-
/** PATH separator: Windows ';', POSIX ':'. */
|
|
67
72
|
function pathSep() {
|
|
68
73
|
return process.platform === "win32" ? ";" : ":";
|
|
69
74
|
}
|
|
70
75
|
|
|
71
76
|
function memsearchEnv() {
|
|
72
77
|
const env = { ...process.env };
|
|
73
|
-
// Windows 无开发者模式时 HF 缓存无法建软链,抑制该无害警告。
|
|
74
|
-
env.HF_HUB_DISABLE_SYMLINKS_WARNING = "1";
|
|
75
78
|
const existing = (env.PATH || "").split(pathSep()).filter(Boolean);
|
|
76
79
|
const dirs = ["$HOME/.local/bin", "$HOME/.cargo/bin", "$HOME/bin", "/usr/local/bin", "/usr/bin", "/bin"]
|
|
77
80
|
.map((d) => expandPath(d))
|
|
78
81
|
.filter((d) => existsSync(d) && !existing.includes(d));
|
|
79
|
-
|
|
80
|
-
const runtimeScripts = [
|
|
81
|
-
`${home()}/AppData/Local/Programs/DeepSeek Harness/resources/runtime/primary-runtime/dependencies/python/Scripts`,
|
|
82
|
-
]
|
|
83
|
-
.map((d) => expandPath(d))
|
|
84
|
-
.filter((d) => existsSync(d) && !existing.includes(d));
|
|
85
|
-
env.PATH = [...runtimeScripts, ...dirs, ...existing].join(pathSep());
|
|
82
|
+
env.PATH = [...dirs, ...existing].join(pathSep());
|
|
86
83
|
return env;
|
|
87
84
|
}
|
|
88
85
|
|
|
89
|
-
|
|
90
|
-
* Resolve the memsearch executable once per process.
|
|
91
|
-
* Returns null when the CLI is not installed; callers must treat null as "skip".
|
|
92
|
-
*/
|
|
93
|
-
let cliCache = undefined;
|
|
86
|
+
let cliCache;
|
|
94
87
|
function resolveCli() {
|
|
95
88
|
if (cliCache !== undefined) return cliCache;
|
|
96
89
|
const env = memsearchEnv();
|
|
97
90
|
const candidates = ["memsearch", "memsearch.exe", "memsearch.cmd", "memsearch.bat"];
|
|
98
|
-
const
|
|
99
|
-
for (const dir of pathDirs) {
|
|
91
|
+
for (const dir of (env.PATH || "").split(pathSep()).filter(Boolean)) {
|
|
100
92
|
for (const cand of candidates) {
|
|
101
93
|
const full = path.join(dir, cand);
|
|
102
94
|
if (existsSync(full)) {
|
|
@@ -109,7 +101,6 @@ function resolveCli() {
|
|
|
109
101
|
return cliCache;
|
|
110
102
|
}
|
|
111
103
|
|
|
112
|
-
/** Run the memsearch CLI; never rejects. Returns { err, stdout, stderr, skipped }. */
|
|
113
104
|
function runMemsearch(args, { timeout = MS_TIMEOUT, input } = {}) {
|
|
114
105
|
return new Promise((resolve) => {
|
|
115
106
|
const cli = resolveCli();
|
|
@@ -117,7 +108,7 @@ function runMemsearch(args, { timeout = MS_TIMEOUT, input } = {}) {
|
|
|
117
108
|
resolve({ err: new Error("memsearch CLI not installed"), stdout: "", stderr: "", skipped: true });
|
|
118
109
|
return;
|
|
119
110
|
}
|
|
120
|
-
execFile(cli, args, { env: memsearchEnv(), timeout, maxBuffer: MAX_BUFFER, ...(input !== undefined ? { input } : {}) }, (err, stdout, stderr) => {
|
|
111
|
+
execFile(cli, args, { env: memsearchEnv(), timeout, maxBuffer: MAX_BUFFER, windowsHide: true, ...(input !== undefined ? { input } : {}) }, (err, stdout, stderr) => {
|
|
121
112
|
resolve({ err, stdout: stdout || "", stderr: stderr || "", skipped: false });
|
|
122
113
|
});
|
|
123
114
|
});
|
|
@@ -148,8 +139,8 @@ function collectionArgs(config) {
|
|
|
148
139
|
}
|
|
149
140
|
|
|
150
141
|
function truncate(text, max) {
|
|
151
|
-
|
|
152
|
-
return `${
|
|
142
|
+
const value = String(text || "");
|
|
143
|
+
return value.length <= max ? value : `${value.slice(0, max)}...(truncated)`;
|
|
153
144
|
}
|
|
154
145
|
|
|
155
146
|
function textOf(message) {
|
|
@@ -161,23 +152,19 @@ function textOf(message) {
|
|
|
161
152
|
.trim();
|
|
162
153
|
}
|
|
163
154
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
if (data && typeof data === "object" && data.message && typeof data.message === "object") {
|
|
167
|
-
return data.message;
|
|
168
|
-
}
|
|
155
|
+
function payloadOf(data) {
|
|
156
|
+
if (data && typeof data === "object" && data.message && typeof data.message === "object") return data.message;
|
|
169
157
|
return data;
|
|
170
158
|
}
|
|
171
159
|
|
|
172
|
-
/** Blocks the harness injects into the conversation; never a real user prompt. */
|
|
173
160
|
const INJECTED_TEXT = /^\s*(<system-reminder>|Time sampled while preparing)/;
|
|
174
161
|
|
|
175
162
|
/**
|
|
176
163
|
* Committed events of a session.
|
|
177
164
|
*
|
|
178
|
-
* DSH exposes the log through `snapshotEvents()`; older builds
|
|
179
|
-
*
|
|
180
|
-
*
|
|
165
|
+
* DSH exposes the log through `snapshotEvents()`; older builds carried a plain
|
|
166
|
+
* `events` array. Reading only `session.events` silently disabled capture on
|
|
167
|
+
* current releases, because that property no longer exists.
|
|
181
168
|
*/
|
|
182
169
|
function sessionEvents(session) {
|
|
183
170
|
if (!session) return [];
|
|
@@ -192,14 +179,19 @@ function sessionEvents(session) {
|
|
|
192
179
|
return Array.isArray(session.events) ? session.events : [];
|
|
193
180
|
}
|
|
194
181
|
|
|
182
|
+
/** Latest title recorded for a session, if any. */
|
|
183
|
+
function sessionTitle(session) {
|
|
184
|
+
const events = sessionEvents(session);
|
|
185
|
+
let title = "";
|
|
186
|
+
for (const event of events) {
|
|
187
|
+
if (event && event.type === "session/title" && event.data && typeof event.data.title === "string") title = event.data.title;
|
|
188
|
+
}
|
|
189
|
+
return title;
|
|
190
|
+
}
|
|
191
|
+
|
|
195
192
|
/**
|
|
196
193
|
* The last exchange of the session: the newest genuine user prompt plus the
|
|
197
194
|
* final assistant reply that follows it.
|
|
198
|
-
*
|
|
199
|
-
* Injected context reaches the session as ordinary `user/message` events, so
|
|
200
|
-
* `source.kind` decides what counts: only `kind: "user"` (and a message with no
|
|
201
|
-
* source at all) is a real prompt. Everything else — `plugin`, `runtime-context`,
|
|
202
|
-
* `time-context`, `skill-catalog`, `model-selection` — is skipped.
|
|
203
195
|
*/
|
|
204
196
|
function extractExchange(session) {
|
|
205
197
|
let userText = "";
|
|
@@ -209,8 +201,8 @@ function extractExchange(session) {
|
|
|
209
201
|
const event = events[i];
|
|
210
202
|
if (!event || typeof event !== "object" || event.type !== "user/message") continue;
|
|
211
203
|
const source = event.data && event.data.source;
|
|
212
|
-
if (source && source.kind !== "user") continue;
|
|
213
|
-
const text = textOf(
|
|
204
|
+
if (source && source.kind !== "user") continue;
|
|
205
|
+
const text = textOf(payloadOf(event.data));
|
|
214
206
|
if (!text || INJECTED_TEXT.test(text)) continue;
|
|
215
207
|
userText = text;
|
|
216
208
|
userSeq = typeof event.seq === "number" ? event.seq : i;
|
|
@@ -223,7 +215,7 @@ function extractExchange(session) {
|
|
|
223
215
|
const event = events[i];
|
|
224
216
|
if (!event || typeof event !== "object" || event.type !== "assistant/message") continue;
|
|
225
217
|
if (typeof event.seq === "number" && typeof userSeq === "number" && event.seq < userSeq) continue;
|
|
226
|
-
const text = textOf(
|
|
218
|
+
const text = textOf(payloadOf(event.data));
|
|
227
219
|
if (!text) continue;
|
|
228
220
|
assistantText = text;
|
|
229
221
|
assistantSeq = event.seq;
|
|
@@ -232,7 +224,21 @@ function extractExchange(session) {
|
|
|
232
224
|
return { userText, assistantText, assistantSeq };
|
|
233
225
|
}
|
|
234
226
|
|
|
235
|
-
|
|
227
|
+
/** Escape markdown headings so a reply cannot split the journal structure. */
|
|
228
|
+
function defuseHeadings(text) {
|
|
229
|
+
return String(text).replace(/^(#{1,6})(\s)/gm, "\\$1$2");
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function createStatusMessage(text) {
|
|
233
|
+
return {
|
|
234
|
+
id: randomUUID(),
|
|
235
|
+
role: "user",
|
|
236
|
+
content: [{ type: "text", text }],
|
|
237
|
+
source: { kind: "memory-recall", plugin: name, form: "snapshot", sections: [{ name, text }] },
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function buildStatusText(config, memoryDir, archive) {
|
|
236
242
|
const cliAvailable = Boolean(resolveCli());
|
|
237
243
|
let versionText = "n/a";
|
|
238
244
|
let providerText = "(no CLI)";
|
|
@@ -243,78 +249,132 @@ async function buildStatusText(config, memoryDir) {
|
|
|
243
249
|
providerText = provider.stdout.trim() || "(default)";
|
|
244
250
|
}
|
|
245
251
|
const files = memoryFiles(memoryDir);
|
|
252
|
+
const days = archive ? archive.listDays().length : 0;
|
|
246
253
|
let text = `[memsearch ${versionText}] embedding: ${providerText} | journal: ${memoryDir} | ${files.length} past memory file(s)`;
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
}
|
|
252
|
-
if (!cliAvailable) {
|
|
253
|
-
text += " (memsearch CLI 未安装:本轮只写日记,索引 / 语义检索暂不可用。)";
|
|
254
|
-
}
|
|
254
|
+
text += ` | archive: ${archive ? archive.root : "(off)"} (${days} day folder(s))`;
|
|
255
|
+
if (files.length > 0) text += ". Use the memory-recall skill to search when the user's question could benefit from historical context.";
|
|
256
|
+
else text += ". No past memories yet; this session's exchanges will be saved automatically.";
|
|
257
|
+
if (!cliAvailable) text += " (memsearch CLI 未安装:只写日记与归档,索引 / 语义检索暂不可用。)";
|
|
255
258
|
return text;
|
|
256
259
|
}
|
|
257
260
|
|
|
258
|
-
function
|
|
259
|
-
return {
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
* as `### foo`) while leaving the heading structure to the journal itself.
|
|
275
|
-
*/
|
|
276
|
-
function defuseHeadings(text) {
|
|
277
|
-
return String(text).replace(/^(#{1,6})(\s)/gm, "\\$1$2");
|
|
261
|
+
function installCli() {
|
|
262
|
+
return new Promise((resolve) => {
|
|
263
|
+
const candidates = process.platform === "win32"
|
|
264
|
+
? [["python", ["-m", "pip", "install", "--user", "memsearch"]], ["py", ["-3", "-m", "pip", "install", "--user", "memsearch"]]]
|
|
265
|
+
: [["python3", ["-m", "pip", "install", "--user", "memsearch"]], ["pip", ["install", "--user", "memsearch"]]];
|
|
266
|
+
const tryNext = (index) => {
|
|
267
|
+
if (index >= candidates.length) return resolve({ ok: false, reason: "no python found" });
|
|
268
|
+
const [cmd, args] = candidates[index];
|
|
269
|
+
execFile(cmd, args, { timeout: 600000, maxBuffer: MAX_BUFFER, windowsHide: true }, (err) => {
|
|
270
|
+
if (err) return tryNext(index + 1);
|
|
271
|
+
cliCache = undefined;
|
|
272
|
+
resolve({ ok: true, cli: resolveCli() });
|
|
273
|
+
});
|
|
274
|
+
};
|
|
275
|
+
tryNext(0);
|
|
276
|
+
});
|
|
278
277
|
}
|
|
279
278
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
const res = await runMemsearch(["summarize", "--plugin", config.summarizePlugin, "--agent-name", "DSH"], { input: summary });
|
|
293
|
-
if (!res.err && res.stdout.trim()) summary = defuseHeadings(res.stdout.trim());
|
|
279
|
+
/** One-time setup: archive location, CLI install offer, history import offer. */
|
|
280
|
+
async function runSetup(config, archive, log) {
|
|
281
|
+
if (archive.countsAsFlag("setupDone")) return;
|
|
282
|
+
|
|
283
|
+
if (config.askDataRoot && !config.dataRoot && !archive.countsAsFlag("dataRootAsked")) {
|
|
284
|
+
const picked = await pickFolder({ title: "选择 DSH 对话数据的保存位置", initial: path.dirname(archive.root) });
|
|
285
|
+
archive.setFlag("dataRootAsked");
|
|
286
|
+
if (picked.ok && picked.path) {
|
|
287
|
+
archive.root = picked.path;
|
|
288
|
+
archive.statePath = path.join(picked.path, ".dsh-memsearch-state.json");
|
|
289
|
+
archive.ensureRoot();
|
|
290
|
+
archive.setFlag("dataRootAsked");
|
|
294
291
|
}
|
|
292
|
+
}
|
|
295
293
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
294
|
+
if (!archive.countsAsFlag("cliOffered") && !resolveCli()) {
|
|
295
|
+
if (config.autoInstallCli) {
|
|
296
|
+
const res = await installCli();
|
|
297
|
+
log(res.ok ? `[memsearch] CLI 已安装: ${res.cli}` : `[memsearch] CLI 安装失败: ${res.reason}`);
|
|
298
|
+
} else if (config.offerCliInstall) {
|
|
299
|
+
const answer = await askYesNo({
|
|
300
|
+
title: "是否安装检索命令行工具?",
|
|
301
|
+
message: "memsearch CLI 负责把记录变成可语义检索的索引。\n不装也能用:对话仍会按日期归档成 txt。\n装好后可以用「上次我们聊的…」这类提问翻旧账。\n\n现在安装吗?(约需 Python 3.10+)",
|
|
302
|
+
});
|
|
303
|
+
if (answer.ok && answer.answer) {
|
|
304
|
+
const res = await installCli();
|
|
305
|
+
log(res.ok ? `[memsearch] CLI 已安装: ${res.cli}` : `[memsearch] CLI 安装失败: ${res.reason}`);
|
|
306
|
+
} else {
|
|
307
|
+
log("[memsearch] 用户暂不安装 CLI");
|
|
308
|
+
archive.setFlag("cliDeclined", true);
|
|
309
|
+
}
|
|
310
|
+
archive.setFlag("cliOffered");
|
|
311
|
+
}
|
|
312
|
+
}
|
|
299
313
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
314
|
+
if (!archive.countsAsFlag("historyAsked") && config.importHistory === "ask") {
|
|
315
|
+
const answer = await askYesNo({
|
|
316
|
+
title: "导入安装前的历史对话?",
|
|
317
|
+
message: "插件只自动记录安装之后发生的对话。\n是否把本机已有的 DSH 历史会话也导出成 txt,按日期归档?\n(只在本机处理,不会上传)",
|
|
318
|
+
});
|
|
319
|
+
archive.setFlag("historyAsked");
|
|
320
|
+
if (answer.ok && answer.answer) {
|
|
321
|
+
const summary = importHistory(archive, {
|
|
322
|
+
minPromptLength: config.captureMinPromptLength,
|
|
323
|
+
maxCaptureChars: config.maxCaptureChars,
|
|
303
324
|
});
|
|
325
|
+
log(`[memsearch] 历史导入完成: ${JSON.stringify(summary)}`);
|
|
304
326
|
}
|
|
305
|
-
}
|
|
306
|
-
|
|
327
|
+
} else if (!archive.countsAsFlag("historyAsked") && config.importHistory === "yes") {
|
|
328
|
+
archive.setFlag("historyAsked");
|
|
329
|
+
const summary = importHistory(archive, {
|
|
330
|
+
minPromptLength: config.captureMinPromptLength,
|
|
331
|
+
maxCaptureChars: config.maxCaptureChars,
|
|
332
|
+
});
|
|
333
|
+
log(`[memsearch] 历史导入完成: ${JSON.stringify(summary)}`);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
archive.setFlag("setupDone");
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Prompt once when the archive holds more day folders than the retention limit. */
|
|
340
|
+
async function checkRetention(config, archive, log) {
|
|
341
|
+
const days = archive.listDays();
|
|
342
|
+
if (days.length <= config.retentionDays) {
|
|
343
|
+
if (archive.countsAsFlag("retentionWarned")) archive.setFlag("retentionWarned", false);
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
if (archive.countsAsFlag("retentionWarned")) return;
|
|
347
|
+
archive.setFlag("retentionWarned");
|
|
348
|
+
const answer = await askYesNo({
|
|
349
|
+
title: "对话数据已达上限",
|
|
350
|
+
message: `已经积累了 ${days.length} 天的对话数据(上限 ${config.retentionDays} 天)。\n是否现在打开文件夹,清理不需要的记录?`,
|
|
351
|
+
});
|
|
352
|
+
if (answer.ok && answer.answer) {
|
|
353
|
+
const res = await openFolder(archive.root);
|
|
354
|
+
log(`[memsearch] 已打开归档目录: ${archive.root}${res && res.err ? " (打开失败)" : ""}`);
|
|
307
355
|
}
|
|
308
356
|
}
|
|
309
357
|
|
|
358
|
+
function archiveFor(config) {
|
|
359
|
+
const root = config.dataRoot ? expandPath(config.dataRoot) : defaultDataRoot();
|
|
360
|
+
const archive = new Archive(root);
|
|
361
|
+
if (config.dataRoot && !archive.state.flags.dataRootAsked) {
|
|
362
|
+
archive.setFlag("dataRootAsked");
|
|
363
|
+
}
|
|
364
|
+
return archive;
|
|
365
|
+
}
|
|
366
|
+
|
|
310
367
|
function apply(ctx, config) {
|
|
311
368
|
if (!config || !config.enabled) return;
|
|
312
369
|
const memoryDir = resolveMemoryDir(config.memoryDir);
|
|
370
|
+
const archive = archiveFor(config);
|
|
313
371
|
const state = {
|
|
314
372
|
statusInjected: new WeakSet(),
|
|
315
373
|
sessionIndexed: new WeakSet(),
|
|
374
|
+
setup: false,
|
|
316
375
|
lastCaptured: new Map(),
|
|
317
376
|
};
|
|
377
|
+
const log = (message) => console.error(message);
|
|
318
378
|
|
|
319
379
|
ctx.on("agent/pre-step", async ({ agent, messages, step, signal }, next) => {
|
|
320
380
|
try {
|
|
@@ -323,22 +383,26 @@ function apply(ctx, config) {
|
|
|
323
383
|
const session = agent && agent.session;
|
|
324
384
|
if (!session) return decision;
|
|
325
385
|
|
|
386
|
+
if (!state.setup) {
|
|
387
|
+
state.setup = true;
|
|
388
|
+
await runSetup(config, archive, log);
|
|
389
|
+
}
|
|
390
|
+
|
|
326
391
|
if (!state.sessionIndexed.has(session) && memoryFiles(memoryDir).length > 0 && resolveCli()) {
|
|
327
392
|
state.sessionIndexed.add(session);
|
|
328
393
|
runMemsearch(["index", memoryDir, ...collectionArgs(config)]).then((res) => {
|
|
329
|
-
if (res.err && !res.skipped)
|
|
394
|
+
if (res.err && !res.skipped) log(`[memsearch] session index failed: ${(res.stderr || res.err.message).slice(0, 300)}`);
|
|
330
395
|
});
|
|
331
396
|
}
|
|
332
397
|
|
|
333
398
|
if (config.injectSessionStatus && !state.statusInjected.has(session)) {
|
|
334
399
|
state.statusInjected.add(session);
|
|
335
|
-
const statusText = await buildStatusText(config, memoryDir);
|
|
400
|
+
const statusText = await buildStatusText(config, memoryDir, archive);
|
|
336
401
|
return { kind: "enter", messages: [createStatusMessage(statusText), ...(decision.messages || [])] };
|
|
337
402
|
}
|
|
338
403
|
return decision;
|
|
339
404
|
} catch (err) {
|
|
340
|
-
|
|
341
|
-
console.error(`[dsh-memsearch] pre-step failed: ${err && err.message ? err.message : String(err)}`);
|
|
405
|
+
log(`[memsearch] pre-step failed: ${err && err.message ? err.message : String(err)}`);
|
|
342
406
|
try {
|
|
343
407
|
return await next();
|
|
344
408
|
} catch {
|
|
@@ -347,16 +411,71 @@ function apply(ctx, config) {
|
|
|
347
411
|
}
|
|
348
412
|
}, { prepend: true });
|
|
349
413
|
|
|
350
|
-
if (config.capture)
|
|
351
|
-
|
|
414
|
+
if (!config.capture) return;
|
|
415
|
+
|
|
416
|
+
ctx.on("session/event", (session, event) => {
|
|
417
|
+
try {
|
|
418
|
+
if (!event || !session) return;
|
|
419
|
+
|
|
420
|
+
if (event.type === "session/title" && event.data && typeof event.data.title === "string") {
|
|
421
|
+
const sessionId = session.id || (session.header && session.header.id);
|
|
422
|
+
if (sessionId) archive.renameForTitle(String(sessionId), event.data.title);
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
if (event.type !== "turn/end") return;
|
|
427
|
+
captureTurn().catch(() => {});
|
|
428
|
+
} catch (err) {
|
|
429
|
+
log(`[memsearch] session/event failed: ${err && err.message ? err.message : String(err)}`);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async function captureTurn() {
|
|
433
|
+
const { userText, assistantText, assistantSeq } = extractExchange(session);
|
|
434
|
+
if (!userText || userText.length < config.captureMinPromptLength) return;
|
|
435
|
+
if (assistantSeq === undefined) return;
|
|
436
|
+
const sessionId = session.id || (session.header && session.header.id) || "session";
|
|
437
|
+
if (state.lastCaptured.get(sessionId) === assistantSeq) return;
|
|
438
|
+
state.lastCaptured.set(sessionId, assistantSeq);
|
|
439
|
+
|
|
440
|
+
const title = sessionTitle(session);
|
|
441
|
+
const now = new Date();
|
|
442
|
+
|
|
443
|
+
// 1) human-facing archive
|
|
352
444
|
try {
|
|
353
|
-
|
|
354
|
-
|
|
445
|
+
archive.appendTurn({
|
|
446
|
+
sessionId: String(sessionId),
|
|
447
|
+
title,
|
|
448
|
+
date: now,
|
|
449
|
+
userText: truncate(userText, config.maxCaptureChars),
|
|
450
|
+
assistantText: truncate(assistantText || "", config.maxCaptureChars),
|
|
451
|
+
});
|
|
355
452
|
} catch (err) {
|
|
356
|
-
|
|
453
|
+
log(`[memsearch] archive write failed: ${err && err.message ? err.message : String(err)}`);
|
|
357
454
|
}
|
|
358
|
-
|
|
359
|
-
|
|
455
|
+
|
|
456
|
+
// 2) searchable markdown journal
|
|
457
|
+
try {
|
|
458
|
+
const body = `[User]: ${truncate(userText, config.maxCaptureChars)}\n[DSH]: ${truncate(assistantText || "(no text)", config.maxCaptureChars)}`;
|
|
459
|
+
let summary = `=== Final exchange, authoritative for outcome ===\n${defuseHeadings(body)}`;
|
|
460
|
+
if (config.summarizePlugin && resolveCli()) {
|
|
461
|
+
const res = await runMemsearch(["summarize", "--plugin", config.summarizePlugin, "--agent-name", "DSH"], { input: summary });
|
|
462
|
+
if (!res.err && res.stdout.trim()) summary = defuseHeadings(res.stdout.trim());
|
|
463
|
+
}
|
|
464
|
+
mkdirSync(memoryDir, { recursive: true });
|
|
465
|
+
appendFileSync(journalPath(memoryDir, now), `\n### ${dayStamp(now).slice(-5)}\n${summary}\n`, "utf8");
|
|
466
|
+
if (config.indexAfterCapture && resolveCli()) {
|
|
467
|
+
runMemsearch(["index", memoryDir, ...collectionArgs(config)]).then((res) => {
|
|
468
|
+
if (res.err && !res.skipped) log(`[memsearch] index failed: ${(res.stderr || res.err.message).slice(0, 300)}`);
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
} catch (err) {
|
|
472
|
+
log(`[memsearch] journal write failed: ${err && err.message ? err.message : String(err)}`);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// 3) retention prompt
|
|
476
|
+
checkRetention(config, archive, log).catch(() => {});
|
|
477
|
+
}
|
|
478
|
+
});
|
|
360
479
|
}
|
|
361
480
|
|
|
362
|
-
export { Config, apply, defuseHeadings, extractExchange,
|
|
481
|
+
export { Config, Archive, apply, defuseHeadings, extractExchange, importHistory, name, sessionEvents, sessionTitle };
|
package/lib/tree.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The human-facing conversation archive: `<root>/<YYYY.MM.DD>/<session title>.txt`.
|
|
3
|
+
*
|
|
4
|
+
* One folder per day, one text file per session, named after the session title
|
|
5
|
+
* so a title change in DSH renames the file too. Turns are appended with a
|
|
6
|
+
* timestamp header; the vector-search journal in `~/.memsearch/memory` stays the
|
|
7
|
+
* machine-readable copy.
|
|
8
|
+
*/
|
|
9
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync, appendFileSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
|
|
12
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
13
|
+
|
|
14
|
+
/** `2026.12.04` — the folder name for a local date. */
|
|
15
|
+
export function dayName(date = new Date()) {
|
|
16
|
+
return `${date.getFullYear()}.${pad(date.getMonth() + 1)}.${pad(date.getDate())}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function dayStamp(date = new Date()) {
|
|
20
|
+
return `${dayName(date)} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Windows-safe file name from a session title. */
|
|
24
|
+
export function safeFileBase(title, fallback) {
|
|
25
|
+
const cleaned = String(title || "")
|
|
26
|
+
.replace(/[\\/:*?"<>|\u0000-\u001f]/g, " ")
|
|
27
|
+
.replace(/\s+/g, " ")
|
|
28
|
+
.replace(/[. ]+$/, "")
|
|
29
|
+
.trim();
|
|
30
|
+
const base = cleaned || fallback || "未命名会话";
|
|
31
|
+
return base.length > 80 ? base.slice(0, 80).trim() : base;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class Archive {
|
|
35
|
+
constructor(root) {
|
|
36
|
+
this.root = root;
|
|
37
|
+
this.statePath = join(root, ".dsh-memsearch-state.json");
|
|
38
|
+
this.state = this.#load();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
#load() {
|
|
42
|
+
try {
|
|
43
|
+
return JSON.parse(readFileSync(this.statePath, "utf8"));
|
|
44
|
+
} catch {
|
|
45
|
+
return { sessions: {}, flags: {} };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
save() {
|
|
50
|
+
try {
|
|
51
|
+
mkdirSync(this.root, { recursive: true });
|
|
52
|
+
writeFileSync(this.statePath, JSON.stringify(this.state, null, 2), "utf8");
|
|
53
|
+
} catch {
|
|
54
|
+
/* state is best-effort */
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
ensureRoot() {
|
|
59
|
+
mkdirSync(this.root, { recursive: true });
|
|
60
|
+
return this.root;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
countsAsFlag(name) {
|
|
64
|
+
return Boolean(this.state.flags[name]);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
setFlag(name, value = true) {
|
|
68
|
+
this.state.flags[name] = value;
|
|
69
|
+
this.save();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
dayDir(day) {
|
|
73
|
+
const dir = join(this.root, day);
|
|
74
|
+
mkdirSync(dir, { recursive: true });
|
|
75
|
+
return dir;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Day folders currently on disk, oldest first. */
|
|
79
|
+
listDays() {
|
|
80
|
+
try {
|
|
81
|
+
return readdirSync(this.root)
|
|
82
|
+
.filter((name) => /^\d{4}\.\d{2}\.\d{2}$/.test(name) && statSync(join(this.root, name)).isDirectory())
|
|
83
|
+
.sort();
|
|
84
|
+
} catch {
|
|
85
|
+
return [];
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Append one exchange. Returns the file path, renaming an existing file when
|
|
91
|
+
* the session title changed since the last write.
|
|
92
|
+
*/
|
|
93
|
+
appendTurn({ sessionId, title, date = new Date(), userText, assistantText }) {
|
|
94
|
+
this.ensureRoot();
|
|
95
|
+
const day = dayName(date);
|
|
96
|
+
const dir = this.dayDir(day);
|
|
97
|
+
const base = safeFileBase(title, `会话-${String(sessionId).slice(-6)}`);
|
|
98
|
+
const target = join(dir, `${base}.txt`);
|
|
99
|
+
|
|
100
|
+
const record = this.state.sessions[sessionId];
|
|
101
|
+
if (record && record.path !== target && existsSync(record.path) && !existsSync(target)) {
|
|
102
|
+
try {
|
|
103
|
+
renameSync(record.path, target);
|
|
104
|
+
this.#pruneEmpty(record.path);
|
|
105
|
+
} catch {
|
|
106
|
+
/* leave the old file in place */
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const block = [
|
|
111
|
+
`[${dayStamp(date)}]`,
|
|
112
|
+
`[User]: ${userText}`,
|
|
113
|
+
`[DSH]: ${assistantText || "(无回答)"}`,
|
|
114
|
+
"",
|
|
115
|
+
].join("\n");
|
|
116
|
+
appendFileSync(target, block, "utf8");
|
|
117
|
+
this.state.sessions[sessionId] = { path: target, day, title: base };
|
|
118
|
+
this.save();
|
|
119
|
+
return target;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Rename a session's file after a title change. */
|
|
123
|
+
renameForTitle(sessionId, title) {
|
|
124
|
+
const record = this.state.sessions[sessionId];
|
|
125
|
+
if (!record || !existsSync(record.path)) return null;
|
|
126
|
+
const dir = join(this.root, record.day);
|
|
127
|
+
const target = join(dir, `${safeFileBase(title, `会话-${String(sessionId).slice(-6)}`)}.txt`);
|
|
128
|
+
if (target === record.path) return record.path;
|
|
129
|
+
try {
|
|
130
|
+
if (existsSync(target)) return record.path; // keep both rather than overwrite
|
|
131
|
+
renameSync(record.path, target);
|
|
132
|
+
record.path = target;
|
|
133
|
+
record.title = title;
|
|
134
|
+
this.save();
|
|
135
|
+
return target;
|
|
136
|
+
} catch {
|
|
137
|
+
return record.path;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Delete a day folder. */
|
|
142
|
+
removeDay(day) {
|
|
143
|
+
const dir = join(this.root, day);
|
|
144
|
+
try {
|
|
145
|
+
for (const f of readdirSync(dir)) {
|
|
146
|
+
try { renameSync(join(dir, f), join(dir, f)); } catch {}
|
|
147
|
+
}
|
|
148
|
+
return dir;
|
|
149
|
+
} catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
#pruneEmpty(oldPath) {
|
|
155
|
+
try {
|
|
156
|
+
const dir = oldPath.slice(0, oldPath.lastIndexOf("\\") >= 0 ? oldPath.lastIndexOf("\\") : oldPath.lastIndexOf("/"));
|
|
157
|
+
if (dir && readdirSync(dir).length === 0) {
|
|
158
|
+
/* leave the empty day folder; it is harmless and keeps the count visible */
|
|
159
|
+
}
|
|
160
|
+
} catch {
|
|
161
|
+
/* ignore */
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-memsearch-community",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Automatic local
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Automatic local memory for DeepSeek Harness: per-day conversation archive by session title, semantic search index, first-run setup prompts, optional history import.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
7
7
|
"exports": {
|