dsh-agent-soul 0.2.0 → 0.4.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/lib/registry.js CHANGED
@@ -1,236 +1,236 @@
1
- /**
2
- * registry.js —— 项目登记表 + 本机工作区清单。
3
- *
4
- * 为什么要有它(2026-10-28 真问题):
5
- * DSH 的设置页是**全局弹层**,某些版本不往 settings.section 传会话的 cwd ——
6
- * 于是 PersonaTab 算不出「当前工作目录」,「项目人格」药丸永远是灰的,
7
- * 用户想给某个目录写人格无从下手。
8
- *
9
- * dsh-agent-md 的解法是三条腿,这里照搬:
10
- * ① 登记表(projects.json):见过的工作区记下来,下拉里随时可切;
11
- * ② 工作区清单:DSH 的 workspace.json + 会话目录名 + 登记表,三源合并去重;
12
- * ③ 任意目录:手填路径或弹系统选择器,登记即切。
13
- *
14
- * ⚠️ projects.json 与 dsh-agent-md **共用同一个文件**(agents/projects.json):
15
- * 它登记过的工作区这里直接可见,反之亦然。字段结构不能单方面改。
16
- */
17
- import { readdirSync, statSync } from 'node:fs'
18
- import { join } from 'node:path'
19
- import {
20
- agentsDir,
21
- atomicWrite,
22
- dshHome,
23
- displayNameFor,
24
- ensureDirs,
25
- exists,
26
- normalizePathKey,
27
- readText,
28
- slugFor,
29
- } from './paths.js'
30
- import { note } from './env.js'
31
-
32
- /** 登记表位置(与 dsh-agent-md 同一个文件)。 */
33
- export function registryPath() {
34
- return join(agentsDir(), 'projects.json')
35
- }
36
-
37
- /** 读登记表(坏文件回退空表:列工作区失败不能拖垮设置页)。 */
38
- export function readRegistry() {
39
- const raw = readText(registryPath())
40
- if (raw.trim() === '') return { version: 1, projects: [] }
41
- try {
42
- const parsed = JSON.parse(raw)
43
- if (parsed !== null && typeof parsed === 'object' && Array.isArray(parsed.projects)) {
44
- return parsed
45
- }
46
- } catch {
47
- // 解析失败:当作空表(下次写入即修复)
48
- }
49
- return { version: 1, projects: [] }
50
- }
51
-
52
- /**
53
- * 登记一个工作区(幂等:同 key 更新 lastSeen)。
54
- * 只留最近 200 个 —— 登记表是展示用的,不是真相来源(真相在人格文件本身)。
55
- */
56
- export function registerProject(cwd, patch = {}) {
57
- const key = normalizePathKey(cwd)
58
- if (key === '') return readRegistry()
59
- const registry = readRegistry()
60
- const { slug, personaPath: path } = slugFor(cwd)
61
- const now = new Date().toISOString()
62
- // 32-bit FNV-1a slug 的碰撞检测:算法为兼容 dsh-agent-md 不能改(换算法=换命名空间),
63
- // 只能在这里盯住 —— 不同 cwd 算出同 slug 会共用同一份人格/记忆文件,需人工处理。
64
- // 概率极低(几百个工作区里 32bit 足够稀疏),但撞了就静默丢文件,不值得赌。
65
- const collided = registry.projects.find((p) => p !== null && typeof p === 'object' && p.key !== key && p.slug === slug)
66
- if (collided !== undefined) {
67
- note('persona', `⚠️ slug 碰撞:${cwd} 与 ${collided.cwd} 都算出 ${slug}(共享同一份人格/记忆文件)`)
68
- }
69
- const existing = registry.projects.find((p) => p !== null && typeof p === 'object' && p.key === key)
70
- if (existing !== undefined) {
71
- existing.cwd = cwd
72
- existing.slug = slug
73
- existing.path = path
74
- existing.lastSeen = now
75
- if (typeof patch.active === 'boolean') existing.active = patch.active
76
- } else {
77
- registry.projects.push({
78
- key,
79
- cwd,
80
- displayName: displayNameFor(cwd),
81
- slug,
82
- path,
83
- lastSeen: now,
84
- active: patch.active === true,
85
- })
86
- }
87
- registry.projects.sort((a, b) => String(b.lastSeen || '').localeCompare(String(a.lastSeen || '')))
88
- registry.projects = registry.projects.slice(0, 200)
89
- try {
90
- // agents/ 目录可能还没建(插件冷启动 / 测试环境):写盘前先建齐
91
- ensureDirs()
92
- atomicWrite(registryPath(), `${JSON.stringify(registry, null, 2)}\n`)
93
- } catch {
94
- // 写失败不影响注入
95
- }
96
- return registry
97
- }
98
-
99
- // ---- 本机所有工作区(DSH workspace 表 + 会话目录 + 插件登记表)-------------
100
-
101
- /** DSH 自己维护的工作区表:<DSH_HOME>/storages/workspace.json。 */
102
- export function workspaceStorePath() {
103
- return join(dshHome(), 'storages', 'workspace.json')
104
- }
105
-
106
- /** 会话目录根:<DSH_HOME>/sessions(DSH 给每个工作区一个目录)。 */
107
- export function sessionsRoot() {
108
- return join(dshHome(), 'sessions')
109
- }
110
-
111
- /**
112
- * DSH 会话目录名 → 工作目录。
113
- *
114
- * DSH 把 cwd 编码成目录名:`D:\肥鱼` → `--D-~80A5~9C7C--`。规则是**盘符冒号与
115
- * 路径分隔符都写成 `-`**,非 ASCII/不安全字符写成 `~XXXX`(UTF-16 码元)。
116
- * 这是枚举「本机用过哪些工作区」的兜底来源,所以哪怕带点启发式也留着。
117
- */
118
- export function decodeSessionDirName(name) {
119
- if (typeof name !== 'string' || name.length < 5) return ''
120
- if (!name.startsWith('--') || !name.endsWith('--')) return ''
121
- const body = name.slice(2, -2)
122
- if (body === '') return ''
123
- const sep = process.platform === 'win32' ? '\\' : '/'
124
- let text = ''
125
- for (let i = 0; i < body.length; i += 1) {
126
- if (body[i] === '~' && /^[0-9A-Fa-f]{4}$/.test(body.slice(i + 1, i + 5))) {
127
- text += String.fromCharCode(parseInt(body.slice(i + 1, i + 5), 16))
128
- i += 4
129
- continue
130
- }
131
- text += body[i] === '-' ? sep : body[i]
132
- }
133
- // 盘符的冒号也被写成了 `-`(`D-team` 其实是 `D:\team`),这里补回来
134
- return text.replace(/^([A-Za-z])[\\/]/, `$1:${sep}`).replace(/[\\/]+$/, '')
135
- }
136
-
137
- /** 读 DSH 的工作区表(坏文件回退空表)。 */
138
- export function readWorkspaceStore() {
139
- const raw = readText(workspaceStorePath())
140
- if (raw.trim() === '') return []
141
- try {
142
- const parsed = JSON.parse(raw)
143
- const table = parsed !== null && typeof parsed === 'object' && parsed.tables !== undefined
144
- ? parsed.tables.workspaces
145
- : undefined
146
- if (table === null || table === undefined || typeof table !== 'object') return []
147
- return Object.values(table).filter(
148
- (w) => w !== null && typeof w === 'object' && typeof w.path === 'string' && w.path.trim() !== ''
149
- )
150
- } catch {
151
- return []
152
- }
153
- }
154
-
155
- /**
156
- * 本机所有已知工作区(设置页「工作区」下拉的清单)。
157
- *
158
- * 三个来源合并去重,按最近活跃倒序:
159
- * 1. DSH 的工作区表(最权威,带 title / updatedAt);
160
- * 2. 插件自己的项目登记表(写过人格的,sources 标 persona);
161
- * 3. `~/.dsh/sessions` 目录名(老工作区、没进工作区表的也捞得回来)。
162
- */
163
- export function listWorkspaces() {
164
- const map = new Map()
165
- const ensure = (cwd) => {
166
- if (typeof cwd !== 'string' || cwd.trim() === '') return null
167
- const key = normalizePathKey(cwd)
168
- if (key === '') return null
169
- let entry = map.get(key)
170
- if (entry === undefined) {
171
- entry = { key, cwd, title: '', sources: [], lastActive: '', sessionCount: 0, registered: false }
172
- map.set(key, entry)
173
- }
174
- return entry
175
- }
176
- const mark = (entry, source) => {
177
- if (entry !== null && !entry.sources.includes(source)) entry.sources.push(source)
178
- }
179
-
180
- for (const w of readWorkspaceStore()) {
181
- const entry = ensure(w.path)
182
- if (entry === null) continue
183
- mark(entry, 'workspace')
184
- if (typeof w.title === 'string' && w.title !== '') entry.title = w.title
185
- if (typeof w.updatedAt === 'string' && w.updatedAt > entry.lastActive) entry.lastActive = w.updatedAt
186
- if (Array.isArray(w.sessionIds)) entry.sessionCount = Math.max(entry.sessionCount, w.sessionIds.length)
187
- }
188
-
189
- for (const p of readRegistry().projects) {
190
- const entry = ensure(typeof p.cwd === 'string' ? p.cwd : '')
191
- if (entry === null) continue
192
- mark(entry, 'persona')
193
- entry.registered = true
194
- if (typeof p.lastSeen === 'string' && p.lastSeen > entry.lastActive) entry.lastActive = p.lastSeen
195
- }
196
-
197
- let dirs = []
198
- try {
199
- dirs = readdirSync(sessionsRoot(), { withFileTypes: true })
200
- } catch {
201
- dirs = []
202
- }
203
- for (const d of dirs) {
204
- if (d.isDirectory() !== true) continue
205
- const cwd = decodeSessionDirName(d.name)
206
- if (!/^[A-Za-z]:[\\/]/.test(cwd) && !cwd.startsWith('/')) continue
207
- const entry = ensure(cwd)
208
- if (entry === null) continue
209
- mark(entry, 'sessions')
210
- try {
211
- const iso = statSync(join(sessionsRoot(), d.name)).mtime.toISOString()
212
- if (iso > entry.lastActive) entry.lastActive = iso
213
- } catch {
214
- // 读不到时间就只按目录名收录
215
- }
216
- }
217
-
218
- const out = []
219
- for (const entry of map.values()) {
220
- const { slug, personaPath: file } = slugFor(entry.cwd)
221
- out.push({
222
- key: entry.key,
223
- slug,
224
- cwd: entry.cwd,
225
- displayName: entry.title !== '' ? entry.title : displayNameFor(entry.cwd),
226
- sources: entry.sources,
227
- lastActive: entry.lastActive,
228
- sessionCount: entry.sessionCount,
229
- registered: entry.registered,
230
- path: file,
231
- exists: exists(file),
232
- })
233
- }
234
- out.sort((a, b) => String(b.lastActive || '').localeCompare(String(a.lastActive || '')))
235
- return out
236
- }
1
+ /**
2
+ * registry.js —— 项目登记表 + 本机工作区清单。
3
+ *
4
+ * 为什么要有它(2026-10-28 真问题):
5
+ * DSH 的设置页是**全局弹层**,某些版本不往 settings.section 传会话的 cwd ——
6
+ * 于是 PersonaTab 算不出「当前工作目录」,「项目人格」药丸永远是灰的,
7
+ * 用户想给某个目录写人格无从下手。
8
+ *
9
+ * dsh-agent-md 的解法是三条腿,这里照搬:
10
+ * ① 登记表(projects.json):见过的工作区记下来,下拉里随时可切;
11
+ * ② 工作区清单:DSH 的 workspace.json + 会话目录名 + 登记表,三源合并去重;
12
+ * ③ 任意目录:手填路径或弹系统选择器,登记即切。
13
+ *
14
+ * ⚠️ projects.json 与 dsh-agent-md **共用同一个文件**(agents/projects.json):
15
+ * 它登记过的工作区这里直接可见,反之亦然。字段结构不能单方面改。
16
+ */
17
+ import { readdirSync, statSync } from 'node:fs'
18
+ import { join } from 'node:path'
19
+ import {
20
+ agentsDir,
21
+ atomicWrite,
22
+ dshHome,
23
+ displayNameFor,
24
+ ensureDirs,
25
+ exists,
26
+ normalizePathKey,
27
+ readText,
28
+ slugFor,
29
+ } from './paths.js'
30
+ import { note } from './env.js'
31
+
32
+ /** 登记表位置(与 dsh-agent-md 同一个文件)。 */
33
+ export function registryPath() {
34
+ return join(agentsDir(), 'projects.json')
35
+ }
36
+
37
+ /** 读登记表(坏文件回退空表:列工作区失败不能拖垮设置页)。 */
38
+ export function readRegistry() {
39
+ const raw = readText(registryPath())
40
+ if (raw.trim() === '') return { version: 1, projects: [] }
41
+ try {
42
+ const parsed = JSON.parse(raw)
43
+ if (parsed !== null && typeof parsed === 'object' && Array.isArray(parsed.projects)) {
44
+ return parsed
45
+ }
46
+ } catch {
47
+ // 解析失败:当作空表(下次写入即修复)
48
+ }
49
+ return { version: 1, projects: [] }
50
+ }
51
+
52
+ /**
53
+ * 登记一个工作区(幂等:同 key 更新 lastSeen)。
54
+ * 只留最近 200 个 —— 登记表是展示用的,不是真相来源(真相在人格文件本身)。
55
+ */
56
+ export function registerProject(cwd, patch = {}) {
57
+ const key = normalizePathKey(cwd)
58
+ if (key === '') return readRegistry()
59
+ const registry = readRegistry()
60
+ const { slug, personaPath: path } = slugFor(cwd)
61
+ const now = new Date().toISOString()
62
+ // 32-bit FNV-1a slug 的碰撞检测:算法为兼容 dsh-agent-md 不能改(换算法=换命名空间),
63
+ // 只能在这里盯住 —— 不同 cwd 算出同 slug 会共用同一份人格/记忆文件,需人工处理。
64
+ // 概率极低(几百个工作区里 32bit 足够稀疏),但撞了就静默丢文件,不值得赌。
65
+ const collided = registry.projects.find((p) => p !== null && typeof p === 'object' && p.key !== key && p.slug === slug)
66
+ if (collided !== undefined) {
67
+ note('persona', `⚠️ slug 碰撞:${cwd} 与 ${collided.cwd} 都算出 ${slug}(共享同一份人格/记忆文件)`)
68
+ }
69
+ const existing = registry.projects.find((p) => p !== null && typeof p === 'object' && p.key === key)
70
+ if (existing !== undefined) {
71
+ existing.cwd = cwd
72
+ existing.slug = slug
73
+ existing.path = path
74
+ existing.lastSeen = now
75
+ if (typeof patch.active === 'boolean') existing.active = patch.active
76
+ } else {
77
+ registry.projects.push({
78
+ key,
79
+ cwd,
80
+ displayName: displayNameFor(cwd),
81
+ slug,
82
+ path,
83
+ lastSeen: now,
84
+ active: patch.active === true,
85
+ })
86
+ }
87
+ registry.projects.sort((a, b) => String(b.lastSeen || '').localeCompare(String(a.lastSeen || '')))
88
+ registry.projects = registry.projects.slice(0, 200)
89
+ try {
90
+ // agents/ 目录可能还没建(插件冷启动 / 测试环境):写盘前先建齐
91
+ ensureDirs()
92
+ atomicWrite(registryPath(), `${JSON.stringify(registry, null, 2)}\n`)
93
+ } catch {
94
+ // 写失败不影响注入
95
+ }
96
+ return registry
97
+ }
98
+
99
+ // ---- 本机所有工作区(DSH workspace 表 + 会话目录 + 插件登记表)-------------
100
+
101
+ /** DSH 自己维护的工作区表:<DSH_HOME>/storages/workspace.json。 */
102
+ export function workspaceStorePath() {
103
+ return join(dshHome(), 'storages', 'workspace.json')
104
+ }
105
+
106
+ /** 会话目录根:<DSH_HOME>/sessions(DSH 给每个工作区一个目录)。 */
107
+ export function sessionsRoot() {
108
+ return join(dshHome(), 'sessions')
109
+ }
110
+
111
+ /**
112
+ * DSH 会话目录名 → 工作目录。
113
+ *
114
+ * DSH 把 cwd 编码成目录名:`D:\肥鱼` → `--D-~80A5~9C7C--`。规则是**盘符冒号与
115
+ * 路径分隔符都写成 `-`**,非 ASCII/不安全字符写成 `~XXXX`(UTF-16 码元)。
116
+ * 这是枚举「本机用过哪些工作区」的兜底来源,所以哪怕带点启发式也留着。
117
+ */
118
+ export function decodeSessionDirName(name) {
119
+ if (typeof name !== 'string' || name.length < 5) return ''
120
+ if (!name.startsWith('--') || !name.endsWith('--')) return ''
121
+ const body = name.slice(2, -2)
122
+ if (body === '') return ''
123
+ const sep = process.platform === 'win32' ? '\\' : '/'
124
+ let text = ''
125
+ for (let i = 0; i < body.length; i += 1) {
126
+ if (body[i] === '~' && /^[0-9A-Fa-f]{4}$/.test(body.slice(i + 1, i + 5))) {
127
+ text += String.fromCharCode(parseInt(body.slice(i + 1, i + 5), 16))
128
+ i += 4
129
+ continue
130
+ }
131
+ text += body[i] === '-' ? sep : body[i]
132
+ }
133
+ // 盘符的冒号也被写成了 `-`(`D-team` 其实是 `D:\team`),这里补回来
134
+ return text.replace(/^([A-Za-z])[\\/]/, `$1:${sep}`).replace(/[\\/]+$/, '')
135
+ }
136
+
137
+ /** 读 DSH 的工作区表(坏文件回退空表)。 */
138
+ export function readWorkspaceStore() {
139
+ const raw = readText(workspaceStorePath())
140
+ if (raw.trim() === '') return []
141
+ try {
142
+ const parsed = JSON.parse(raw)
143
+ const table = parsed !== null && typeof parsed === 'object' && parsed.tables !== undefined
144
+ ? parsed.tables.workspaces
145
+ : undefined
146
+ if (table === null || table === undefined || typeof table !== 'object') return []
147
+ return Object.values(table).filter(
148
+ (w) => w !== null && typeof w === 'object' && typeof w.path === 'string' && w.path.trim() !== ''
149
+ )
150
+ } catch {
151
+ return []
152
+ }
153
+ }
154
+
155
+ /**
156
+ * 本机所有已知工作区(设置页「工作区」下拉的清单)。
157
+ *
158
+ * 三个来源合并去重,按最近活跃倒序:
159
+ * 1. DSH 的工作区表(最权威,带 title / updatedAt);
160
+ * 2. 插件自己的项目登记表(写过人格的,sources 标 persona);
161
+ * 3. `~/.dsh/sessions` 目录名(老工作区、没进工作区表的也捞得回来)。
162
+ */
163
+ export function listWorkspaces() {
164
+ const map = new Map()
165
+ const ensure = (cwd) => {
166
+ if (typeof cwd !== 'string' || cwd.trim() === '') return null
167
+ const key = normalizePathKey(cwd)
168
+ if (key === '') return null
169
+ let entry = map.get(key)
170
+ if (entry === undefined) {
171
+ entry = { key, cwd, title: '', sources: [], lastActive: '', sessionCount: 0, registered: false }
172
+ map.set(key, entry)
173
+ }
174
+ return entry
175
+ }
176
+ const mark = (entry, source) => {
177
+ if (entry !== null && !entry.sources.includes(source)) entry.sources.push(source)
178
+ }
179
+
180
+ for (const w of readWorkspaceStore()) {
181
+ const entry = ensure(w.path)
182
+ if (entry === null) continue
183
+ mark(entry, 'workspace')
184
+ if (typeof w.title === 'string' && w.title !== '') entry.title = w.title
185
+ if (typeof w.updatedAt === 'string' && w.updatedAt > entry.lastActive) entry.lastActive = w.updatedAt
186
+ if (Array.isArray(w.sessionIds)) entry.sessionCount = Math.max(entry.sessionCount, w.sessionIds.length)
187
+ }
188
+
189
+ for (const p of readRegistry().projects) {
190
+ const entry = ensure(typeof p.cwd === 'string' ? p.cwd : '')
191
+ if (entry === null) continue
192
+ mark(entry, 'persona')
193
+ entry.registered = true
194
+ if (typeof p.lastSeen === 'string' && p.lastSeen > entry.lastActive) entry.lastActive = p.lastSeen
195
+ }
196
+
197
+ let dirs = []
198
+ try {
199
+ dirs = readdirSync(sessionsRoot(), { withFileTypes: true })
200
+ } catch {
201
+ dirs = []
202
+ }
203
+ for (const d of dirs) {
204
+ if (d.isDirectory() !== true) continue
205
+ const cwd = decodeSessionDirName(d.name)
206
+ if (!/^[A-Za-z]:[\\/]/.test(cwd) && !cwd.startsWith('/')) continue
207
+ const entry = ensure(cwd)
208
+ if (entry === null) continue
209
+ mark(entry, 'sessions')
210
+ try {
211
+ const iso = statSync(join(sessionsRoot(), d.name)).mtime.toISOString()
212
+ if (iso > entry.lastActive) entry.lastActive = iso
213
+ } catch {
214
+ // 读不到时间就只按目录名收录
215
+ }
216
+ }
217
+
218
+ const out = []
219
+ for (const entry of map.values()) {
220
+ const { slug, personaPath: file } = slugFor(entry.cwd)
221
+ out.push({
222
+ key: entry.key,
223
+ slug,
224
+ cwd: entry.cwd,
225
+ displayName: entry.title !== '' ? entry.title : displayNameFor(entry.cwd),
226
+ sources: entry.sources,
227
+ lastActive: entry.lastActive,
228
+ sessionCount: entry.sessionCount,
229
+ registered: entry.registered,
230
+ path: file,
231
+ exists: exists(file),
232
+ })
233
+ }
234
+ out.sort((a, b) => String(b.lastActive || '').localeCompare(String(a.lastActive || '')))
235
+ return out
236
+ }