dsh-memsearch-community 0.2.3 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -0
- package/cordis.patch.yml +5 -0
- package/lib/dialogs.js +108 -0
- package/lib/import.js +146 -0
- package/lib/index.js +311 -122
- package/lib/tree.js +178 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -12,6 +12,35 @@ computed locally with ONNX.
|
|
|
12
12
|
|
|
13
13
|
## Changes from upstream
|
|
14
14
|
|
|
15
|
+
**0.3.1 — robust home directory and CLI detection**
|
|
16
|
+
|
|
17
|
+
- Launchers can hand the process a mojibake `USERPROFILE`, which pointed the
|
|
18
|
+
archive at a path like `C:\Users\??\Documents\...` that does not exist. The
|
|
19
|
+
plugin now prefers the first home candidate that is a real directory, and a
|
|
20
|
+
folder chosen in the picker is persisted and reused on the next start.
|
|
21
|
+
- CLI detection also scans known install locations (`pip install --user`
|
|
22
|
+
Scripts, `%APPDATA%\Python\Python3xx\Scripts`, DSH's bundled runtime) instead
|
|
23
|
+
of relying on the inherited `PATH`, which did not always contain them.
|
|
24
|
+
|
|
25
|
+
**0.3.0 — first-run setup, per-day archive, history import**
|
|
26
|
+
|
|
27
|
+
- **Setup prompts.** On first run the plugin asks three things with native
|
|
28
|
+
desktop dialogs (WinForms / AppleScript / zenity): where the archive should
|
|
29
|
+
live, whether to install the optional `memsearch` CLI, and whether to import
|
|
30
|
+
conversations from before installation. Cancelled or unavailable dialogs fall
|
|
31
|
+
back to the configuration fields in Settings → Plugins.
|
|
32
|
+
- **Per-day archive.** Every captured turn is also written to
|
|
33
|
+
`<dataRoot>/<YYYY.MM.DD>/<session title>.txt`, one file per session, appended
|
|
34
|
+
with a timestamp header. Renaming a session in DSH renames its file.
|
|
35
|
+
- **Retention prompt.** Once the archive holds more than `retentionDays`
|
|
36
|
+
(default 60) day folders, the plugin asks once whether to open the folder for
|
|
37
|
+
cleanup.
|
|
38
|
+
- **History import.** Reads `~/.dsh/sessions/**/session.v4.jsonl.zstd`,
|
|
39
|
+
decompresses them, pairs each real prompt with its final answer, and writes
|
|
40
|
+
them into the same day folders in chronological order.
|
|
41
|
+
- The searchable markdown journal in `~/.memsearch/memory` is still written, so
|
|
42
|
+
semantic search keeps working exactly as before.
|
|
43
|
+
|
|
15
44
|
**0.2.3 — keep reply headings out of the journal structure**
|
|
16
45
|
|
|
17
46
|
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,108 @@
|
|
|
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 { existsSync } from "node:fs";
|
|
13
|
+
import os from "node:os";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
|
|
16
|
+
const DIALOG_TIMEOUT = 180000;
|
|
17
|
+
|
|
18
|
+
function run(command, args) {
|
|
19
|
+
return new Promise((resolve) => {
|
|
20
|
+
execFile(command, args, { timeout: DIALOG_TIMEOUT, windowsHide: true, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
|
|
21
|
+
resolve({ err, stdout: String(stdout || ""), stderr: String(stderr || "") });
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const psQuote = (value) => `'${String(value).replace(/'/g, "''")}'`;
|
|
27
|
+
|
|
28
|
+
/** Yes/No message box. Resolves { ok, answer: true|false } or { ok: false, reason }. */
|
|
29
|
+
export async function askYesNo({ title, message, yes = "是", no = "否" }) {
|
|
30
|
+
if (process.platform === "win32") {
|
|
31
|
+
const script = [
|
|
32
|
+
"Add-Type -AssemblyName System.Windows.Forms | Out-Null",
|
|
33
|
+
`$r = [System.Windows.Forms.MessageBox]::Show(${psQuote(message)}, ${psQuote(title)}, 'YesNo', 'Question', 'Button1', 'Button1')`,
|
|
34
|
+
"if ($r -eq 'Yes') { 'YES' } else { 'NO' }",
|
|
35
|
+
].join("; ");
|
|
36
|
+
const res = await run("powershell.exe", ["-NoProfile", "-STA", "-Command", script]);
|
|
37
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
38
|
+
const out = res.stdout.trim();
|
|
39
|
+
if (out === "YES") return { ok: true, answer: true };
|
|
40
|
+
if (out === "NO") return { ok: true, answer: false };
|
|
41
|
+
return { ok: false, reason: "no answer" };
|
|
42
|
+
}
|
|
43
|
+
if (process.platform === "darwin") {
|
|
44
|
+
const script = `display dialog ${JSON.stringify(message)} with title ${JSON.stringify(title)} buttons {${JSON.stringify(no)}, ${JSON.stringify(yes)}} default button ${JSON.stringify(yes)}`;
|
|
45
|
+
const res = await run("osascript", ["-e", script]);
|
|
46
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
47
|
+
return { ok: true, answer: res.stdout.includes(yes) };
|
|
48
|
+
}
|
|
49
|
+
const res = await run("zenity", ["--question", `--title=${title}`, `--text=${message}`, `--ok-label=${yes}`, `--cancel-label=${no}`]);
|
|
50
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
51
|
+
return { ok: true, answer: true };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Folder picker. Resolves { ok, path } or { ok: false, reason }. */
|
|
55
|
+
export async function pickFolder({ title, initial }) {
|
|
56
|
+
if (process.platform === "win32") {
|
|
57
|
+
const script = [
|
|
58
|
+
"Add-Type -AssemblyName System.Windows.Forms | Out-Null",
|
|
59
|
+
"$d = New-Object System.Windows.Forms.FolderBrowserDialog",
|
|
60
|
+
`$d.Description = ${psQuote(title)}`,
|
|
61
|
+
"$d.ShowNewFolderButton = $true",
|
|
62
|
+
initial ? `$d.SelectedPath = ${psQuote(initial)}` : "",
|
|
63
|
+
"if ($d.ShowDialog() -eq 'OK') { $d.SelectedPath } else { '' }",
|
|
64
|
+
].filter(Boolean).join("; ");
|
|
65
|
+
const res = await run("powershell.exe", ["-NoProfile", "-STA", "-Command", script]);
|
|
66
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
67
|
+
const picked = res.stdout.trim();
|
|
68
|
+
return picked ? { ok: true, path: picked } : { ok: false, reason: "cancelled" };
|
|
69
|
+
}
|
|
70
|
+
if (process.platform === "darwin") {
|
|
71
|
+
const res = await run("osascript", ["-e", 'POSIX path of (choose folder with prompt "' + title + '")']);
|
|
72
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
73
|
+
return { ok: true, path: res.stdout.trim() };
|
|
74
|
+
}
|
|
75
|
+
const res = await run("zenity", ["--file-selection", "--directory", `--title=${title}`]);
|
|
76
|
+
if (res.err) return { ok: false, reason: res.err.message };
|
|
77
|
+
return { ok: true, path: res.stdout.trim() };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Open a folder in the desktop file manager. */
|
|
81
|
+
export async function openFolder(path) {
|
|
82
|
+
if (process.platform === "win32") return run("explorer.exe", [path]);
|
|
83
|
+
if (process.platform === "darwin") return run("open", [path]);
|
|
84
|
+
return run("xdg-open", [path]);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function defaultDataRoot() {
|
|
88
|
+
return join(realHome(), "Documents", "DSH对话数据");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Home directory that actually exists on disk.
|
|
93
|
+
*
|
|
94
|
+
* Launchers can hand the process a mojibake `USERPROFILE`; `os.homedir()` then
|
|
95
|
+
* points at a path like `C:\Users\??\...` that was never created.
|
|
96
|
+
*/
|
|
97
|
+
export function realHome() {
|
|
98
|
+
const candidates = [process.env.USERPROFILE, process.env.HOME, os.homedir()].filter(Boolean);
|
|
99
|
+
for (const candidate of candidates) {
|
|
100
|
+
if (/[\uFFFD]/.test(candidate)) continue;
|
|
101
|
+
try {
|
|
102
|
+
if (existsSync(candidate)) return candidate;
|
|
103
|
+
} catch {
|
|
104
|
+
/* keep looking */
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return os.homedir();
|
|
108
|
+
}
|
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,59 +1,77 @@
|
|
|
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
|
|
|
51
57
|
function home() {
|
|
58
|
+
// Some launchers hand the process a mojibake USERPROFILE (CP936 bytes decoded
|
|
59
|
+
// as UTF-8), which produces paths like `C:\Users\??\...` that do not exist.
|
|
60
|
+
// Prefer the first candidate that is a real directory.
|
|
61
|
+
const candidates = [process.env.USERPROFILE, process.env.HOME, os.homedir()].filter(Boolean);
|
|
62
|
+
for (const candidate of candidates) {
|
|
63
|
+
if (/[\uFFFD]/.test(candidate)) continue;
|
|
64
|
+
try {
|
|
65
|
+
if (existsSync(candidate)) return candidate;
|
|
66
|
+
} catch {
|
|
67
|
+
/* keep looking */
|
|
68
|
+
}
|
|
69
|
+
}
|
|
52
70
|
return os.homedir();
|
|
53
71
|
}
|
|
54
72
|
|
|
55
73
|
function expandPath(p) {
|
|
56
|
-
return p.replace(/^~(?=$|\/)/, home());
|
|
74
|
+
return String(p || "").replace(/^~(?=$|\/)/, home());
|
|
57
75
|
}
|
|
58
76
|
|
|
59
77
|
function resolveMemoryDir(configured) {
|
|
@@ -63,40 +81,80 @@ function resolveMemoryDir(configured) {
|
|
|
63
81
|
return path.join(home(), ".memsearch", "memory");
|
|
64
82
|
}
|
|
65
83
|
|
|
66
|
-
/** PATH separator: Windows ';', POSIX ':'. */
|
|
67
84
|
function pathSep() {
|
|
68
85
|
return process.platform === "win32" ? ";" : ":";
|
|
69
86
|
}
|
|
70
87
|
|
|
71
88
|
function memsearchEnv() {
|
|
72
89
|
const env = { ...process.env };
|
|
73
|
-
// Windows 无开发者模式时 HF 缓存无法建软链,抑制该无害警告。
|
|
74
|
-
env.HF_HUB_DISABLE_SYMLINKS_WARNING = "1";
|
|
75
90
|
const existing = (env.PATH || "").split(pathSep()).filter(Boolean);
|
|
76
91
|
const dirs = ["$HOME/.local/bin", "$HOME/.cargo/bin", "$HOME/bin", "/usr/local/bin", "/usr/bin", "/bin"]
|
|
77
92
|
.map((d) => expandPath(d))
|
|
78
93
|
.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());
|
|
94
|
+
env.PATH = [...dirs, ...existing].join(pathSep());
|
|
86
95
|
return env;
|
|
87
96
|
}
|
|
88
97
|
|
|
89
98
|
/**
|
|
90
|
-
*
|
|
91
|
-
*
|
|
99
|
+
* Directories worth scanning for the CLI, beyond the inherited PATH.
|
|
100
|
+
*
|
|
101
|
+
* DSH's own bundled Python installs console scripts into a directory that is not
|
|
102
|
+
* always on the process PATH, and `pip install --user` lands in a per-user
|
|
103
|
+
* Scripts folder. Scanning these explicitly keeps detection working whichever
|
|
104
|
+
* way the CLI was installed.
|
|
92
105
|
*/
|
|
93
|
-
|
|
106
|
+
function cliDirs() {
|
|
107
|
+
const dirs = [];
|
|
108
|
+
const push = (dir) => {
|
|
109
|
+
if (!dir) return;
|
|
110
|
+
try {
|
|
111
|
+
if (existsSync(dir)) dirs.push(dir);
|
|
112
|
+
} catch {
|
|
113
|
+
/* ignore */
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
for (const dir of (memsearchEnv().PATH || "").split(pathSep())) push(dir);
|
|
118
|
+
|
|
119
|
+
const appData = process.env.APPDATA;
|
|
120
|
+
const localAppData = process.env.LOCALAPPDATA;
|
|
121
|
+
const base = home();
|
|
122
|
+
push(path.join(base, ".local", "bin"));
|
|
123
|
+
push(path.join(base, ".cargo", "bin"));
|
|
124
|
+
push(path.join(localAppData || "", "Programs", "Python", "Launcher"));
|
|
125
|
+
|
|
126
|
+
// %APPDATA%\Python\Python3xx\Scripts
|
|
127
|
+
for (const root of [appData, localAppData].filter(Boolean)) {
|
|
128
|
+
const pythonRoot = path.join(root, "Python");
|
|
129
|
+
try {
|
|
130
|
+
for (const entry of readdirSync(pythonRoot)) {
|
|
131
|
+
if (/^Python3/i.test(entry)) push(path.join(pythonRoot, entry, "Scripts"));
|
|
132
|
+
}
|
|
133
|
+
} catch {
|
|
134
|
+
/* no python root */
|
|
135
|
+
}
|
|
136
|
+
const programs = path.join(root, "Programs", "Python");
|
|
137
|
+
try {
|
|
138
|
+
for (const entry of readdirSync(programs)) push(path.join(programs, entry, "Scripts"));
|
|
139
|
+
} catch {
|
|
140
|
+
/* not installed there */
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// DSH's bundled runtime
|
|
145
|
+
const harness = path.join(localAppData || "", "Programs", "DeepSeek Harness", "resources", "runtime");
|
|
146
|
+
for (const sub of ["primary-runtime", "cli"]) {
|
|
147
|
+
push(path.join(harness, sub, "dependencies", "python", "Scripts"));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return [...new Set(dirs)];
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
let cliCache;
|
|
94
154
|
function resolveCli() {
|
|
95
155
|
if (cliCache !== undefined) return cliCache;
|
|
96
|
-
const env = memsearchEnv();
|
|
97
156
|
const candidates = ["memsearch", "memsearch.exe", "memsearch.cmd", "memsearch.bat"];
|
|
98
|
-
const
|
|
99
|
-
for (const dir of pathDirs) {
|
|
157
|
+
for (const dir of cliDirs()) {
|
|
100
158
|
for (const cand of candidates) {
|
|
101
159
|
const full = path.join(dir, cand);
|
|
102
160
|
if (existsSync(full)) {
|
|
@@ -109,7 +167,6 @@ function resolveCli() {
|
|
|
109
167
|
return cliCache;
|
|
110
168
|
}
|
|
111
169
|
|
|
112
|
-
/** Run the memsearch CLI; never rejects. Returns { err, stdout, stderr, skipped }. */
|
|
113
170
|
function runMemsearch(args, { timeout = MS_TIMEOUT, input } = {}) {
|
|
114
171
|
return new Promise((resolve) => {
|
|
115
172
|
const cli = resolveCli();
|
|
@@ -117,7 +174,7 @@ function runMemsearch(args, { timeout = MS_TIMEOUT, input } = {}) {
|
|
|
117
174
|
resolve({ err: new Error("memsearch CLI not installed"), stdout: "", stderr: "", skipped: true });
|
|
118
175
|
return;
|
|
119
176
|
}
|
|
120
|
-
execFile(cli, args, { env: memsearchEnv(), timeout, maxBuffer: MAX_BUFFER, ...(input !== undefined ? { input } : {}) }, (err, stdout, stderr) => {
|
|
177
|
+
execFile(cli, args, { env: memsearchEnv(), timeout, maxBuffer: MAX_BUFFER, windowsHide: true, ...(input !== undefined ? { input } : {}) }, (err, stdout, stderr) => {
|
|
121
178
|
resolve({ err, stdout: stdout || "", stderr: stderr || "", skipped: false });
|
|
122
179
|
});
|
|
123
180
|
});
|
|
@@ -148,8 +205,8 @@ function collectionArgs(config) {
|
|
|
148
205
|
}
|
|
149
206
|
|
|
150
207
|
function truncate(text, max) {
|
|
151
|
-
|
|
152
|
-
return `${
|
|
208
|
+
const value = String(text || "");
|
|
209
|
+
return value.length <= max ? value : `${value.slice(0, max)}...(truncated)`;
|
|
153
210
|
}
|
|
154
211
|
|
|
155
212
|
function textOf(message) {
|
|
@@ -161,23 +218,19 @@ function textOf(message) {
|
|
|
161
218
|
.trim();
|
|
162
219
|
}
|
|
163
220
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
if (data && typeof data === "object" && data.message && typeof data.message === "object") {
|
|
167
|
-
return data.message;
|
|
168
|
-
}
|
|
221
|
+
function payloadOf(data) {
|
|
222
|
+
if (data && typeof data === "object" && data.message && typeof data.message === "object") return data.message;
|
|
169
223
|
return data;
|
|
170
224
|
}
|
|
171
225
|
|
|
172
|
-
/** Blocks the harness injects into the conversation; never a real user prompt. */
|
|
173
226
|
const INJECTED_TEXT = /^\s*(<system-reminder>|Time sampled while preparing)/;
|
|
174
227
|
|
|
175
228
|
/**
|
|
176
229
|
* Committed events of a session.
|
|
177
230
|
*
|
|
178
|
-
* DSH exposes the log through `snapshotEvents()`; older builds
|
|
179
|
-
*
|
|
180
|
-
*
|
|
231
|
+
* DSH exposes the log through `snapshotEvents()`; older builds carried a plain
|
|
232
|
+
* `events` array. Reading only `session.events` silently disabled capture on
|
|
233
|
+
* current releases, because that property no longer exists.
|
|
181
234
|
*/
|
|
182
235
|
function sessionEvents(session) {
|
|
183
236
|
if (!session) return [];
|
|
@@ -192,14 +245,19 @@ function sessionEvents(session) {
|
|
|
192
245
|
return Array.isArray(session.events) ? session.events : [];
|
|
193
246
|
}
|
|
194
247
|
|
|
248
|
+
/** Latest title recorded for a session, if any. */
|
|
249
|
+
function sessionTitle(session) {
|
|
250
|
+
const events = sessionEvents(session);
|
|
251
|
+
let title = "";
|
|
252
|
+
for (const event of events) {
|
|
253
|
+
if (event && event.type === "session/title" && event.data && typeof event.data.title === "string") title = event.data.title;
|
|
254
|
+
}
|
|
255
|
+
return title;
|
|
256
|
+
}
|
|
257
|
+
|
|
195
258
|
/**
|
|
196
259
|
* The last exchange of the session: the newest genuine user prompt plus the
|
|
197
260
|
* 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
261
|
*/
|
|
204
262
|
function extractExchange(session) {
|
|
205
263
|
let userText = "";
|
|
@@ -209,8 +267,8 @@ function extractExchange(session) {
|
|
|
209
267
|
const event = events[i];
|
|
210
268
|
if (!event || typeof event !== "object" || event.type !== "user/message") continue;
|
|
211
269
|
const source = event.data && event.data.source;
|
|
212
|
-
if (source && source.kind !== "user") continue;
|
|
213
|
-
const text = textOf(
|
|
270
|
+
if (source && source.kind !== "user") continue;
|
|
271
|
+
const text = textOf(payloadOf(event.data));
|
|
214
272
|
if (!text || INJECTED_TEXT.test(text)) continue;
|
|
215
273
|
userText = text;
|
|
216
274
|
userSeq = typeof event.seq === "number" ? event.seq : i;
|
|
@@ -223,7 +281,7 @@ function extractExchange(session) {
|
|
|
223
281
|
const event = events[i];
|
|
224
282
|
if (!event || typeof event !== "object" || event.type !== "assistant/message") continue;
|
|
225
283
|
if (typeof event.seq === "number" && typeof userSeq === "number" && event.seq < userSeq) continue;
|
|
226
|
-
const text = textOf(
|
|
284
|
+
const text = textOf(payloadOf(event.data));
|
|
227
285
|
if (!text) continue;
|
|
228
286
|
assistantText = text;
|
|
229
287
|
assistantSeq = event.seq;
|
|
@@ -232,7 +290,21 @@ function extractExchange(session) {
|
|
|
232
290
|
return { userText, assistantText, assistantSeq };
|
|
233
291
|
}
|
|
234
292
|
|
|
235
|
-
|
|
293
|
+
/** Escape markdown headings so a reply cannot split the journal structure. */
|
|
294
|
+
function defuseHeadings(text) {
|
|
295
|
+
return String(text).replace(/^(#{1,6})(\s)/gm, "\\$1$2");
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function createStatusMessage(text) {
|
|
299
|
+
return {
|
|
300
|
+
id: randomUUID(),
|
|
301
|
+
role: "user",
|
|
302
|
+
content: [{ type: "text", text }],
|
|
303
|
+
source: { kind: "memory-recall", plugin: name, form: "snapshot", sections: [{ name, text }] },
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function buildStatusText(config, memoryDir, archive) {
|
|
236
308
|
const cliAvailable = Boolean(resolveCli());
|
|
237
309
|
let versionText = "n/a";
|
|
238
310
|
let providerText = "(no CLI)";
|
|
@@ -243,78 +315,136 @@ async function buildStatusText(config, memoryDir) {
|
|
|
243
315
|
providerText = provider.stdout.trim() || "(default)";
|
|
244
316
|
}
|
|
245
317
|
const files = memoryFiles(memoryDir);
|
|
318
|
+
const days = archive ? archive.listDays().length : 0;
|
|
246
319
|
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
|
-
}
|
|
320
|
+
text += ` | archive: ${archive ? archive.root : "(off)"} (${days} day folder(s))`;
|
|
321
|
+
if (files.length > 0) text += ". Use the memory-recall skill to search when the user's question could benefit from historical context.";
|
|
322
|
+
else text += ". No past memories yet; this session's exchanges will be saved automatically.";
|
|
323
|
+
if (!cliAvailable) text += " (memsearch CLI 未安装:只写日记与归档,索引 / 语义检索暂不可用。)";
|
|
255
324
|
return text;
|
|
256
325
|
}
|
|
257
326
|
|
|
258
|
-
function
|
|
259
|
-
return {
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
327
|
+
function installCli() {
|
|
328
|
+
return new Promise((resolve) => {
|
|
329
|
+
const candidates = process.platform === "win32"
|
|
330
|
+
? [["python", ["-m", "pip", "install", "--user", "memsearch"]], ["py", ["-3", "-m", "pip", "install", "--user", "memsearch"]]]
|
|
331
|
+
: [["python3", ["-m", "pip", "install", "--user", "memsearch"]], ["pip", ["install", "--user", "memsearch"]]];
|
|
332
|
+
const tryNext = (index) => {
|
|
333
|
+
if (index >= candidates.length) return resolve({ ok: false, reason: "no python found" });
|
|
334
|
+
const [cmd, args] = candidates[index];
|
|
335
|
+
execFile(cmd, args, { timeout: 600000, maxBuffer: MAX_BUFFER, windowsHide: true }, (err) => {
|
|
336
|
+
if (err) return tryNext(index + 1);
|
|
337
|
+
cliCache = undefined;
|
|
338
|
+
resolve({ ok: true, cli: resolveCli() });
|
|
339
|
+
});
|
|
340
|
+
};
|
|
341
|
+
tryNext(0);
|
|
342
|
+
});
|
|
265
343
|
}
|
|
266
344
|
|
|
267
|
-
/**
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
* The journal uses `### HH:MM` lines as its own separators, and `memsearch index`
|
|
271
|
-
* splits markdown on headings. An assistant reply containing `### Something`
|
|
272
|
-
* therefore produced phantom journal entries with a heading where the timestamp
|
|
273
|
-
* belongs. Escaping the leading `#` keeps the text readable (`\### foo` renders
|
|
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");
|
|
278
|
-
}
|
|
345
|
+
/** One-time setup: archive location, CLI install offer, history import offer. */
|
|
346
|
+
async function runSetup(config, archive, log) {
|
|
347
|
+
if (archive.countsAsFlag("setupDone")) return;
|
|
279
348
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
if (
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
state.lastCaptured.set(session.id, assistantSeq);
|
|
287
|
-
|
|
288
|
-
const body = `[User]: ${truncate(userText, config.maxCaptureChars)}\n[DSH]: ${truncate(assistantText || "(no text)", config.maxCaptureChars)}`;
|
|
289
|
-
let summary = `=== Final exchange, authoritative for outcome ===\n${defuseHeadings(body)}`;
|
|
290
|
-
|
|
291
|
-
if (config.summarizePlugin && resolveCli()) {
|
|
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());
|
|
349
|
+
if (config.askDataRoot && !config.dataRoot && !archive.countsAsFlag("dataRootAsked")) {
|
|
350
|
+
const picked = await pickFolder({ title: "选择 DSH 对话数据的保存位置", initial: path.dirname(archive.root) });
|
|
351
|
+
archive.setFlag("dataRootAsked");
|
|
352
|
+
if (picked.ok && picked.path) {
|
|
353
|
+
archive.relocate(picked.path);
|
|
354
|
+
archive.setFlag("dataRoot", picked.path);
|
|
294
355
|
}
|
|
356
|
+
}
|
|
295
357
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
358
|
+
if (!archive.countsAsFlag("cliOffered") && !resolveCli()) {
|
|
359
|
+
if (config.autoInstallCli) {
|
|
360
|
+
const res = await installCli();
|
|
361
|
+
log(res.ok ? `[memsearch] CLI 已安装: ${res.cli}` : `[memsearch] CLI 安装失败: ${res.reason}`);
|
|
362
|
+
} else if (config.offerCliInstall) {
|
|
363
|
+
const answer = await askYesNo({
|
|
364
|
+
title: "是否安装检索命令行工具?",
|
|
365
|
+
message: "memsearch CLI 负责把记录变成可语义检索的索引。\n不装也能用:对话仍会按日期归档成 txt。\n装好后可以用「上次我们聊的…」这类提问翻旧账。\n\n现在安装吗?(约需 Python 3.10+)",
|
|
366
|
+
});
|
|
367
|
+
if (answer.ok && answer.answer) {
|
|
368
|
+
const res = await installCli();
|
|
369
|
+
log(res.ok ? `[memsearch] CLI 已安装: ${res.cli}` : `[memsearch] CLI 安装失败: ${res.reason}`);
|
|
370
|
+
} else {
|
|
371
|
+
log("[memsearch] 用户暂不安装 CLI");
|
|
372
|
+
archive.setFlag("cliDeclined", true);
|
|
373
|
+
}
|
|
374
|
+
archive.setFlag("cliOffered");
|
|
375
|
+
}
|
|
376
|
+
}
|
|
299
377
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
378
|
+
if (!archive.countsAsFlag("historyAsked") && config.importHistory === "ask") {
|
|
379
|
+
const answer = await askYesNo({
|
|
380
|
+
title: "导入安装前的历史对话?",
|
|
381
|
+
message: "插件只自动记录安装之后发生的对话。\n是否把本机已有的 DSH 历史会话也导出成 txt,按日期归档?\n(只在本机处理,不会上传)",
|
|
382
|
+
});
|
|
383
|
+
archive.setFlag("historyAsked");
|
|
384
|
+
if (answer.ok && answer.answer) {
|
|
385
|
+
const summary = importHistory(archive, {
|
|
386
|
+
minPromptLength: config.captureMinPromptLength,
|
|
387
|
+
maxCaptureChars: config.maxCaptureChars,
|
|
303
388
|
});
|
|
389
|
+
log(`[memsearch] 历史导入完成: ${JSON.stringify(summary)}`);
|
|
304
390
|
}
|
|
305
|
-
}
|
|
306
|
-
|
|
391
|
+
} else if (!archive.countsAsFlag("historyAsked") && config.importHistory === "yes") {
|
|
392
|
+
archive.setFlag("historyAsked");
|
|
393
|
+
const summary = importHistory(archive, {
|
|
394
|
+
minPromptLength: config.captureMinPromptLength,
|
|
395
|
+
maxCaptureChars: config.maxCaptureChars,
|
|
396
|
+
});
|
|
397
|
+
log(`[memsearch] 历史导入完成: ${JSON.stringify(summary)}`);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
archive.setFlag("setupDone");
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** Prompt once when the archive holds more day folders than the retention limit. */
|
|
404
|
+
async function checkRetention(config, archive, log) {
|
|
405
|
+
const days = archive.listDays();
|
|
406
|
+
if (days.length <= config.retentionDays) {
|
|
407
|
+
if (archive.countsAsFlag("retentionWarned")) archive.setFlag("retentionWarned", false);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
if (archive.countsAsFlag("retentionWarned")) return;
|
|
411
|
+
archive.setFlag("retentionWarned");
|
|
412
|
+
const answer = await askYesNo({
|
|
413
|
+
title: "对话数据已达上限",
|
|
414
|
+
message: `已经积累了 ${days.length} 天的对话数据(上限 ${config.retentionDays} 天)。\n是否现在打开文件夹,清理不需要的记录?`,
|
|
415
|
+
});
|
|
416
|
+
if (answer.ok && answer.answer) {
|
|
417
|
+
const res = await openFolder(archive.root);
|
|
418
|
+
log(`[memsearch] 已打开归档目录: ${archive.root}${res && res.err ? " (打开失败)" : ""}`);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function archiveFor(config) {
|
|
423
|
+
const root = config.dataRoot ? expandPath(config.dataRoot) : defaultDataRoot();
|
|
424
|
+
const archive = new Archive(root);
|
|
425
|
+
// A folder picked in a previous run wins over the computed default, which can
|
|
426
|
+
// be wrong when the launcher hands the process a mojibake home directory.
|
|
427
|
+
const saved = archive.state && archive.state.flags && archive.state.flags.dataRoot;
|
|
428
|
+
if (!config.dataRoot && saved && saved !== root) {
|
|
429
|
+
archive.relocate(saved);
|
|
307
430
|
}
|
|
431
|
+
if (config.dataRoot && !archive.state.flags.dataRootAsked) {
|
|
432
|
+
archive.setFlag("dataRootAsked");
|
|
433
|
+
}
|
|
434
|
+
return archive;
|
|
308
435
|
}
|
|
309
436
|
|
|
310
437
|
function apply(ctx, config) {
|
|
311
438
|
if (!config || !config.enabled) return;
|
|
312
439
|
const memoryDir = resolveMemoryDir(config.memoryDir);
|
|
440
|
+
const archive = archiveFor(config);
|
|
313
441
|
const state = {
|
|
314
442
|
statusInjected: new WeakSet(),
|
|
315
443
|
sessionIndexed: new WeakSet(),
|
|
444
|
+
setup: false,
|
|
316
445
|
lastCaptured: new Map(),
|
|
317
446
|
};
|
|
447
|
+
const log = (message) => console.error(message);
|
|
318
448
|
|
|
319
449
|
ctx.on("agent/pre-step", async ({ agent, messages, step, signal }, next) => {
|
|
320
450
|
try {
|
|
@@ -323,22 +453,26 @@ function apply(ctx, config) {
|
|
|
323
453
|
const session = agent && agent.session;
|
|
324
454
|
if (!session) return decision;
|
|
325
455
|
|
|
456
|
+
if (!state.setup) {
|
|
457
|
+
state.setup = true;
|
|
458
|
+
await runSetup(config, archive, log);
|
|
459
|
+
}
|
|
460
|
+
|
|
326
461
|
if (!state.sessionIndexed.has(session) && memoryFiles(memoryDir).length > 0 && resolveCli()) {
|
|
327
462
|
state.sessionIndexed.add(session);
|
|
328
463
|
runMemsearch(["index", memoryDir, ...collectionArgs(config)]).then((res) => {
|
|
329
|
-
if (res.err && !res.skipped)
|
|
464
|
+
if (res.err && !res.skipped) log(`[memsearch] session index failed: ${(res.stderr || res.err.message).slice(0, 300)}`);
|
|
330
465
|
});
|
|
331
466
|
}
|
|
332
467
|
|
|
333
468
|
if (config.injectSessionStatus && !state.statusInjected.has(session)) {
|
|
334
469
|
state.statusInjected.add(session);
|
|
335
|
-
const statusText = await buildStatusText(config, memoryDir);
|
|
470
|
+
const statusText = await buildStatusText(config, memoryDir, archive);
|
|
336
471
|
return { kind: "enter", messages: [createStatusMessage(statusText), ...(decision.messages || [])] };
|
|
337
472
|
}
|
|
338
473
|
return decision;
|
|
339
474
|
} catch (err) {
|
|
340
|
-
|
|
341
|
-
console.error(`[dsh-memsearch] pre-step failed: ${err && err.message ? err.message : String(err)}`);
|
|
475
|
+
log(`[memsearch] pre-step failed: ${err && err.message ? err.message : String(err)}`);
|
|
342
476
|
try {
|
|
343
477
|
return await next();
|
|
344
478
|
} catch {
|
|
@@ -347,16 +481,71 @@ function apply(ctx, config) {
|
|
|
347
481
|
}
|
|
348
482
|
}, { prepend: true });
|
|
349
483
|
|
|
350
|
-
if (config.capture)
|
|
351
|
-
|
|
484
|
+
if (!config.capture) return;
|
|
485
|
+
|
|
486
|
+
ctx.on("session/event", (session, event) => {
|
|
487
|
+
try {
|
|
488
|
+
if (!event || !session) return;
|
|
489
|
+
|
|
490
|
+
if (event.type === "session/title" && event.data && typeof event.data.title === "string") {
|
|
491
|
+
const sessionId = session.id || (session.header && session.header.id);
|
|
492
|
+
if (sessionId) archive.renameForTitle(String(sessionId), event.data.title);
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
if (event.type !== "turn/end") return;
|
|
497
|
+
captureTurn().catch(() => {});
|
|
498
|
+
} catch (err) {
|
|
499
|
+
log(`[memsearch] session/event failed: ${err && err.message ? err.message : String(err)}`);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async function captureTurn() {
|
|
503
|
+
const { userText, assistantText, assistantSeq } = extractExchange(session);
|
|
504
|
+
if (!userText || userText.length < config.captureMinPromptLength) return;
|
|
505
|
+
if (assistantSeq === undefined) return;
|
|
506
|
+
const sessionId = session.id || (session.header && session.header.id) || "session";
|
|
507
|
+
if (state.lastCaptured.get(sessionId) === assistantSeq) return;
|
|
508
|
+
state.lastCaptured.set(sessionId, assistantSeq);
|
|
509
|
+
|
|
510
|
+
const title = sessionTitle(session);
|
|
511
|
+
const now = new Date();
|
|
512
|
+
|
|
513
|
+
// 1) human-facing archive
|
|
352
514
|
try {
|
|
353
|
-
|
|
354
|
-
|
|
515
|
+
archive.appendTurn({
|
|
516
|
+
sessionId: String(sessionId),
|
|
517
|
+
title,
|
|
518
|
+
date: now,
|
|
519
|
+
userText: truncate(userText, config.maxCaptureChars),
|
|
520
|
+
assistantText: truncate(assistantText || "", config.maxCaptureChars),
|
|
521
|
+
});
|
|
355
522
|
} catch (err) {
|
|
356
|
-
|
|
523
|
+
log(`[memsearch] archive write failed: ${err && err.message ? err.message : String(err)}`);
|
|
357
524
|
}
|
|
358
|
-
|
|
359
|
-
|
|
525
|
+
|
|
526
|
+
// 2) searchable markdown journal
|
|
527
|
+
try {
|
|
528
|
+
const body = `[User]: ${truncate(userText, config.maxCaptureChars)}\n[DSH]: ${truncate(assistantText || "(no text)", config.maxCaptureChars)}`;
|
|
529
|
+
let summary = `=== Final exchange, authoritative for outcome ===\n${defuseHeadings(body)}`;
|
|
530
|
+
if (config.summarizePlugin && resolveCli()) {
|
|
531
|
+
const res = await runMemsearch(["summarize", "--plugin", config.summarizePlugin, "--agent-name", "DSH"], { input: summary });
|
|
532
|
+
if (!res.err && res.stdout.trim()) summary = defuseHeadings(res.stdout.trim());
|
|
533
|
+
}
|
|
534
|
+
mkdirSync(memoryDir, { recursive: true });
|
|
535
|
+
appendFileSync(journalPath(memoryDir, now), `\n### ${dayStamp(now).slice(-5)}\n${summary}\n`, "utf8");
|
|
536
|
+
if (config.indexAfterCapture && resolveCli()) {
|
|
537
|
+
runMemsearch(["index", memoryDir, ...collectionArgs(config)]).then((res) => {
|
|
538
|
+
if (res.err && !res.skipped) log(`[memsearch] index failed: ${(res.stderr || res.err.message).slice(0, 300)}`);
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
} catch (err) {
|
|
542
|
+
log(`[memsearch] journal write failed: ${err && err.message ? err.message : String(err)}`);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// 3) retention prompt
|
|
546
|
+
checkRetention(config, archive, log).catch(() => {});
|
|
547
|
+
}
|
|
548
|
+
});
|
|
360
549
|
}
|
|
361
550
|
|
|
362
|
-
export { Config, apply, defuseHeadings, extractExchange,
|
|
551
|
+
export { Config, Archive, apply, defuseHeadings, extractExchange, importHistory, name, resolveCli, sessionEvents, sessionTitle };
|
package/lib/tree.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
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
|
+
/** Point the archive at another root, keeping the flags already recorded. */
|
|
59
|
+
relocate(root) {
|
|
60
|
+
const previous = this.state;
|
|
61
|
+
this.root = root;
|
|
62
|
+
this.statePath = join(root, ".dsh-memsearch-state.json");
|
|
63
|
+
this.state = this.#load();
|
|
64
|
+
if (previous && previous.flags) {
|
|
65
|
+
this.state.flags = { ...previous.flags, ...(this.state.flags || {}) };
|
|
66
|
+
}
|
|
67
|
+
this.ensureRoot();
|
|
68
|
+
this.save();
|
|
69
|
+
return this.root;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
ensureRoot() {
|
|
73
|
+
mkdirSync(this.root, { recursive: true });
|
|
74
|
+
return this.root;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
countsAsFlag(name) {
|
|
78
|
+
return Boolean(this.state.flags[name]);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
setFlag(name, value = true) {
|
|
82
|
+
this.state.flags[name] = value;
|
|
83
|
+
this.save();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
dayDir(day) {
|
|
87
|
+
const dir = join(this.root, day);
|
|
88
|
+
mkdirSync(dir, { recursive: true });
|
|
89
|
+
return dir;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Day folders currently on disk, oldest first. */
|
|
93
|
+
listDays() {
|
|
94
|
+
try {
|
|
95
|
+
return readdirSync(this.root)
|
|
96
|
+
.filter((name) => /^\d{4}\.\d{2}\.\d{2}$/.test(name) && statSync(join(this.root, name)).isDirectory())
|
|
97
|
+
.sort();
|
|
98
|
+
} catch {
|
|
99
|
+
return [];
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Append one exchange. Returns the file path, renaming an existing file when
|
|
105
|
+
* the session title changed since the last write.
|
|
106
|
+
*/
|
|
107
|
+
appendTurn({ sessionId, title, date = new Date(), userText, assistantText }) {
|
|
108
|
+
this.ensureRoot();
|
|
109
|
+
const day = dayName(date);
|
|
110
|
+
const dir = this.dayDir(day);
|
|
111
|
+
const base = safeFileBase(title, `会话-${String(sessionId).slice(-6)}`);
|
|
112
|
+
const target = join(dir, `${base}.txt`);
|
|
113
|
+
|
|
114
|
+
const record = this.state.sessions[sessionId];
|
|
115
|
+
if (record && record.path !== target && existsSync(record.path) && !existsSync(target)) {
|
|
116
|
+
try {
|
|
117
|
+
renameSync(record.path, target);
|
|
118
|
+
this.#pruneEmpty(record.path);
|
|
119
|
+
} catch {
|
|
120
|
+
/* leave the old file in place */
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const block = [
|
|
125
|
+
`[${dayStamp(date)}]`,
|
|
126
|
+
`[User]: ${userText}`,
|
|
127
|
+
`[DSH]: ${assistantText || "(无回答)"}`,
|
|
128
|
+
"",
|
|
129
|
+
].join("\n");
|
|
130
|
+
appendFileSync(target, block, "utf8");
|
|
131
|
+
this.state.sessions[sessionId] = { path: target, day, title: base };
|
|
132
|
+
this.save();
|
|
133
|
+
return target;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Rename a session's file after a title change. */
|
|
137
|
+
renameForTitle(sessionId, title) {
|
|
138
|
+
const record = this.state.sessions[sessionId];
|
|
139
|
+
if (!record || !existsSync(record.path)) return null;
|
|
140
|
+
const dir = join(this.root, record.day);
|
|
141
|
+
const target = join(dir, `${safeFileBase(title, `会话-${String(sessionId).slice(-6)}`)}.txt`);
|
|
142
|
+
if (target === record.path) return record.path;
|
|
143
|
+
try {
|
|
144
|
+
if (existsSync(target)) return record.path; // keep both rather than overwrite
|
|
145
|
+
renameSync(record.path, target);
|
|
146
|
+
record.path = target;
|
|
147
|
+
record.title = title;
|
|
148
|
+
this.save();
|
|
149
|
+
return target;
|
|
150
|
+
} catch {
|
|
151
|
+
return record.path;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Delete a day folder. */
|
|
156
|
+
removeDay(day) {
|
|
157
|
+
const dir = join(this.root, day);
|
|
158
|
+
try {
|
|
159
|
+
for (const f of readdirSync(dir)) {
|
|
160
|
+
try { renameSync(join(dir, f), join(dir, f)); } catch {}
|
|
161
|
+
}
|
|
162
|
+
return dir;
|
|
163
|
+
} catch {
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
#pruneEmpty(oldPath) {
|
|
169
|
+
try {
|
|
170
|
+
const dir = oldPath.slice(0, oldPath.lastIndexOf("\\") >= 0 ? oldPath.lastIndexOf("\\") : oldPath.lastIndexOf("/"));
|
|
171
|
+
if (dir && readdirSync(dir).length === 0) {
|
|
172
|
+
/* leave the empty day folder; it is harmless and keeps the count visible */
|
|
173
|
+
}
|
|
174
|
+
} catch {
|
|
175
|
+
/* ignore */
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
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.1",
|
|
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": {
|