dsh-memsearch-community 0.3.0 → 0.3.2

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 CHANGED
@@ -12,6 +12,26 @@ computed locally with ONNX.
12
12
 
13
13
  ## Changes from upstream
14
14
 
15
+ **0.3.2 — edge cases found in review**
16
+
17
+ - A state file that is valid JSON but lacks `flags`/`sessions` crashed plugin
18
+ startup (`state.flags.dataRootAsked` on undefined). The state is normalised on
19
+ load, so hand-edited or older files no longer break activation.
20
+ - Windows dialogs now run from a BOM-prefixed `.ps1` instead of `-Command`, so
21
+ Chinese text reaches the native message box intact.
22
+ - Installing the CLI no longer blocks the first turn: `pip install` runs in the
23
+ background and the result is logged.
24
+
25
+ **0.3.1 — robust home directory and CLI detection**
26
+
27
+ - Launchers can hand the process a mojibake `USERPROFILE`, which pointed the
28
+ archive at a path like `C:\Users\??\Documents\...` that does not exist. The
29
+ plugin now prefers the first home candidate that is a real directory, and a
30
+ folder chosen in the picker is persisted and reused on the next start.
31
+ - CLI detection also scans known install locations (`pip install --user`
32
+ Scripts, `%APPDATA%\Python\Python3xx\Scripts`, DSH's bundled runtime) instead
33
+ of relying on the inherited `PATH`, which did not always contain them.
34
+
15
35
  **0.3.0 — first-run setup, per-day archive, history import**
16
36
 
17
37
  - **Setup prompts.** On first run the plugin asks three things with native
package/lib/dialogs.js CHANGED
@@ -9,7 +9,9 @@
9
9
  * back to configuration or a session message.
10
10
  */
11
11
  import { execFile } from "node:child_process";
12
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
12
13
  import os from "node:os";
14
+ import { join } from "node:path";
13
15
 
14
16
  const DIALOG_TIMEOUT = 180000;
15
17
 
@@ -23,15 +25,36 @@ function run(command, args) {
23
25
 
24
26
  const psQuote = (value) => `'${String(value).replace(/'/g, "''")}'`;
25
27
 
28
+ /**
29
+ * Run a PowerShell script from a UTF-8 file.
30
+ *
31
+ * Passing Chinese through `-Command` depends on the console code page and can
32
+ * arrive mojibake; a BOM-prefixed `.ps1` hands the text to PowerShell as UTF-8.
33
+ */
34
+ async function runPowerShell(script) {
35
+ const dir = mkdtempSync(join(os.tmpdir(), "dsh-memsearch-dialog-"));
36
+ const file = join(dir, "dialog.ps1");
37
+ try {
38
+ writeFileSync(file, "\uFEFF" + script, "utf8");
39
+ return await run("powershell.exe", ["-NoProfile", "-STA", "-ExecutionPolicy", "Bypass", "-File", file]);
40
+ } finally {
41
+ try {
42
+ rmSync(dir, { recursive: true, force: true });
43
+ } catch {
44
+ /* temp dir cleanup is best effort */
45
+ }
46
+ }
47
+ }
48
+
26
49
  /** Yes/No message box. Resolves { ok, answer: true|false } or { ok: false, reason }. */
27
50
  export async function askYesNo({ title, message, yes = "是", no = "否" }) {
28
51
  if (process.platform === "win32") {
29
52
  const script = [
30
53
  "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]);
54
+ `$r = [System.Windows.Forms.MessageBox]::Show(${psQuote(message)}, ${psQuote(title)}, 'YesNo', 'Question', 'Button1')`,
55
+ "if ($r -eq 'Yes') { Write-Output 'YES' } else { Write-Output 'NO' }",
56
+ ].join("\n");
57
+ const res = await runPowerShell(script);
35
58
  if (res.err) return { ok: false, reason: res.err.message };
36
59
  const out = res.stdout.trim();
37
60
  if (out === "YES") return { ok: true, answer: true };
@@ -57,10 +80,10 @@ export async function pickFolder({ title, initial }) {
57
80
  "$d = New-Object System.Windows.Forms.FolderBrowserDialog",
58
81
  `$d.Description = ${psQuote(title)}`,
59
82
  "$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]);
83
+ initial ? `if (Test-Path ${psQuote(initial)}) { $d.SelectedPath = ${psQuote(initial)} }` : "",
84
+ "if ($d.ShowDialog() -eq 'OK') { Write-Output $d.SelectedPath }",
85
+ ].filter(Boolean).join("\n");
86
+ const res = await runPowerShell(script);
64
87
  if (res.err) return { ok: false, reason: res.err.message };
65
88
  const picked = res.stdout.trim();
66
89
  return picked ? { ok: true, path: picked } : { ok: false, reason: "cancelled" };
@@ -83,5 +106,24 @@ export async function openFolder(path) {
83
106
  }
84
107
 
85
108
  export function defaultDataRoot() {
86
- return `${os.homedir()}\\Documents\\DSH对话数据`.replace(/\\/g, process.platform === "win32" ? "\\" : "/");
109
+ return join(realHome(), "Documents", "DSH对话数据");
110
+ }
111
+
112
+ /**
113
+ * Home directory that actually exists on disk.
114
+ *
115
+ * Launchers can hand the process a mojibake `USERPROFILE`; `os.homedir()` then
116
+ * points at a path like `C:\Users\??\...` that was never created.
117
+ */
118
+ export function realHome() {
119
+ const candidates = [process.env.USERPROFILE, process.env.HOME, os.homedir()].filter(Boolean);
120
+ for (const candidate of candidates) {
121
+ if (/[\uFFFD]/.test(candidate)) continue;
122
+ try {
123
+ if (existsSync(candidate)) return candidate;
124
+ } catch {
125
+ /* keep looking */
126
+ }
127
+ }
128
+ return os.homedir();
87
129
  }
package/lib/index.js CHANGED
@@ -55,6 +55,18 @@ const MS_STATUS_TIMEOUT = 15000;
55
55
  const MAX_BUFFER = 8 * 1024 * 1024;
56
56
 
57
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
+ }
58
70
  return os.homedir();
59
71
  }
60
72
 
@@ -83,12 +95,66 @@ function memsearchEnv() {
83
95
  return env;
84
96
  }
85
97
 
98
+ /**
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.
105
+ */
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
+
86
153
  let cliCache;
87
154
  function resolveCli() {
88
155
  if (cliCache !== undefined) return cliCache;
89
- const env = memsearchEnv();
90
156
  const candidates = ["memsearch", "memsearch.exe", "memsearch.cmd", "memsearch.bat"];
91
- for (const dir of (env.PATH || "").split(pathSep()).filter(Boolean)) {
157
+ for (const dir of cliDirs()) {
92
158
  for (const cand of candidates) {
93
159
  const full = path.join(dir, cand);
94
160
  if (existsSync(full)) {
@@ -284,25 +350,27 @@ async function runSetup(config, archive, log) {
284
350
  const picked = await pickFolder({ title: "选择 DSH 对话数据的保存位置", initial: path.dirname(archive.root) });
285
351
  archive.setFlag("dataRootAsked");
286
352
  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");
353
+ archive.relocate(picked.path);
354
+ archive.setFlag("dataRoot", picked.path);
291
355
  }
292
356
  }
293
357
 
294
358
  if (!archive.countsAsFlag("cliOffered") && !resolveCli()) {
359
+ // Never block the session on a package install: kick it off and report later.
360
+ const startInstall = () => {
361
+ installCli().then((res) => {
362
+ log(res.ok ? `[memsearch] CLI 已安装: ${res.cli}` : `[memsearch] CLI 安装失败: ${res.reason}`);
363
+ });
364
+ };
295
365
  if (config.autoInstallCli) {
296
- const res = await installCli();
297
- log(res.ok ? `[memsearch] CLI 已安装: ${res.cli}` : `[memsearch] CLI 安装失败: ${res.reason}`);
366
+ startInstall();
298
367
  } else if (config.offerCliInstall) {
299
368
  const answer = await askYesNo({
300
369
  title: "是否安装检索命令行工具?",
301
- message: "memsearch CLI 负责把记录变成可语义检索的索引。\n不装也能用:对话仍会按日期归档成 txt。\n装好后可以用「上次我们聊的…」这类提问翻旧账。\n\n现在安装吗?(约需 Python 3.10+)",
370
+ message: "memsearch CLI 负责把记录变成可语义检索的索引。\n不装也能用:对话仍会按日期归档成 txt。\n装好后可以用「上次我们聊的…」这类提问翻旧账。\n\n现在安装吗?(约需 Python 3.10+,后台进行)",
302
371
  });
303
372
  if (answer.ok && answer.answer) {
304
- const res = await installCli();
305
- log(res.ok ? `[memsearch] CLI 已安装: ${res.cli}` : `[memsearch] CLI 安装失败: ${res.reason}`);
373
+ startInstall();
306
374
  } else {
307
375
  log("[memsearch] 用户暂不安装 CLI");
308
376
  archive.setFlag("cliDeclined", true);
@@ -358,6 +426,12 @@ async function checkRetention(config, archive, log) {
358
426
  function archiveFor(config) {
359
427
  const root = config.dataRoot ? expandPath(config.dataRoot) : defaultDataRoot();
360
428
  const archive = new Archive(root);
429
+ // A folder picked in a previous run wins over the computed default, which can
430
+ // be wrong when the launcher hands the process a mojibake home directory.
431
+ const saved = archive.state && archive.state.flags && archive.state.flags.dataRoot;
432
+ if (!config.dataRoot && saved && saved !== root) {
433
+ archive.relocate(saved);
434
+ }
361
435
  if (config.dataRoot && !archive.state.flags.dataRootAsked) {
362
436
  archive.setFlag("dataRootAsked");
363
437
  }
@@ -478,4 +552,4 @@ function apply(ctx, config) {
478
552
  });
479
553
  }
480
554
 
481
- export { Config, Archive, apply, defuseHeadings, extractExchange, importHistory, name, sessionEvents, sessionTitle };
555
+ export { Config, Archive, apply, defuseHeadings, extractExchange, importHistory, name, resolveCli, sessionEvents, sessionTitle };
package/lib/tree.js CHANGED
@@ -40,7 +40,13 @@ export class Archive {
40
40
 
41
41
  #load() {
42
42
  try {
43
- return JSON.parse(readFileSync(this.statePath, "utf8"));
43
+ const parsed = JSON.parse(readFileSync(this.statePath, "utf8"));
44
+ const state = parsed && typeof parsed === "object" ? parsed : {};
45
+ // A hand-edited or older state file may lack either container; normalise
46
+ // so callers can index into `sessions` and `flags` without guarding.
47
+ if (!state.sessions || typeof state.sessions !== "object") state.sessions = {};
48
+ if (!state.flags || typeof state.flags !== "object") state.flags = {};
49
+ return state;
44
50
  } catch {
45
51
  return { sessions: {}, flags: {} };
46
52
  }
@@ -55,6 +61,20 @@ export class Archive {
55
61
  }
56
62
  }
57
63
 
64
+ /** Point the archive at another root, keeping the flags already recorded. */
65
+ relocate(root) {
66
+ const previous = this.state;
67
+ this.root = root;
68
+ this.statePath = join(root, ".dsh-memsearch-state.json");
69
+ this.state = this.#load();
70
+ if (previous && previous.flags) {
71
+ this.state.flags = { ...previous.flags, ...(this.state.flags || {}) };
72
+ }
73
+ this.ensureRoot();
74
+ this.save();
75
+ return this.root;
76
+ }
77
+
58
78
  ensureRoot() {
59
79
  mkdirSync(this.root, { recursive: true });
60
80
  return this.root;
@@ -138,19 +158,6 @@ export class Archive {
138
158
  }
139
159
  }
140
160
 
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
161
  #pruneEmpty(oldPath) {
155
162
  try {
156
163
  const dir = oldPath.slice(0, oldPath.lastIndexOf("\\") >= 0 ? oldPath.lastIndexOf("\\") : oldPath.lastIndexOf("/"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-memsearch-community",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
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",