@wangnanshan/dsh-nanshan-session-manager 1.1.9 → 1.5.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.
Files changed (3) hide show
  1. package/client.js +1231 -194
  2. package/index.js +411 -0
  3. package/package.json +1 -1
package/index.js CHANGED
@@ -40,8 +40,10 @@ export function apply(ctx) {
40
40
  const dataRoot = join(home, 'nanshan-session-manager')
41
41
  const titlesPath = join(dataRoot, 'titles.json')
42
42
  const trashRoot = join(dataRoot, 'trash')
43
+ const rulesPath = join(dataRoot, 'rules.json')
43
44
 
44
45
  let titlesCache = null
46
+ let rulesCache = null
45
47
  let mutationChain = Promise.resolve()
46
48
  let cachedCompression = null
47
49
 
@@ -132,6 +134,254 @@ export function apply(ctx) {
132
134
  return cachedCompression
133
135
  }
134
136
 
137
+ // ─────────────────────────────────────────────────────────────
138
+ // Rule Manager persistence
139
+ // ─────────────────────────────────────────────────────────────
140
+ const RULE_SCOPES = new Set(['global', 'workspace', 'session'])
141
+ const MAX_RULES_PER_SCOPE = 500
142
+ const MAX_RULE_TITLE = 120
143
+ const MAX_RULE_CONTENT = 10_000
144
+
145
+ function uuidRule() {
146
+ // Deterministic but unique enough id; crypto.randomUUID() when available.
147
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID()
148
+ return `rule-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
149
+ }
150
+
151
+ async function loadRules() {
152
+ if (rulesCache !== null) return rulesCache
153
+ try {
154
+ const raw = await readFile(rulesPath, 'utf8')
155
+ const parsed = JSON.parse(raw)
156
+ const rules = {}
157
+ if (parsed && typeof parsed.rules === 'object' && parsed.rules !== null) {
158
+ for (const [id, rule] of Object.entries(parsed.rules)) {
159
+ if (!rule || typeof rule !== 'object') continue
160
+ if (!RULE_SCOPES.has(rule.scope)) continue
161
+ // Backward-compatible: accept both target (single) and targets (array)
162
+ let targets = []
163
+ if (Array.isArray(rule.targets)) {
164
+ targets = rule.targets
165
+ .map((t) => String(t).trim().slice(0, 1024))
166
+ .filter(Boolean)
167
+ } else if (rule.target) {
168
+ targets = [String(rule.target).trim().slice(0, 1024)].filter(Boolean)
169
+ }
170
+ rules[id] = {
171
+ id,
172
+ title: String(rule.title || '').slice(0, MAX_RULE_TITLE),
173
+ content: String(rule.content || '').slice(0, MAX_RULE_CONTENT),
174
+ scope: rule.scope,
175
+ targets,
176
+ enabled: rule.enabled !== false,
177
+ createdAt: Number(rule.createdAt) || Date.now(),
178
+ updatedAt: Number(rule.updatedAt) || Date.now(),
179
+ }
180
+ }
181
+ }
182
+ rulesCache = rules
183
+ } catch (error) {
184
+ if (error && error.code === 'ENOENT') {
185
+ rulesCache = {}
186
+ } else {
187
+ throw error
188
+ }
189
+ }
190
+ return rulesCache
191
+ }
192
+
193
+ async function saveRules(rules) {
194
+ await mkdir(dataRoot, { recursive: true })
195
+ const payload = JSON.stringify({ version: 1, rules }, null, 2)
196
+ const tmpPath = `${rulesPath}.tmp`
197
+ await writeFile(tmpPath, payload, 'utf8')
198
+ await rename(tmpPath, rulesPath)
199
+ rulesCache = rules
200
+ }
201
+
202
+ async function listRules() {
203
+ const rules = await loadRules()
204
+ return { rules }
205
+ }
206
+
207
+ function validateRuleInput(body) {
208
+ const errors = []
209
+ if (!body || typeof body !== 'object') {
210
+ errors.push('invalid-payload')
211
+ return { errors }
212
+ }
213
+ const title = String(body.title || '').trim()
214
+ const content = String(body.content || '').trim()
215
+ const scope = String(body.scope || '').trim()
216
+ const rawTargets = Array.isArray(body.targets) ? body.targets : []
217
+ const targets = rawTargets
218
+ .map((t) => String(t).trim().slice(0, 1024))
219
+ .filter(Boolean)
220
+
221
+ if (!title) errors.push('title-empty')
222
+ if (title.length > MAX_RULE_TITLE) errors.push('title-too-long')
223
+ if (!content) errors.push('content-empty')
224
+ if (content.length > MAX_RULE_CONTENT) errors.push('content-too-long')
225
+ if (!RULE_SCOPES.has(scope)) errors.push('scope-invalid')
226
+ if (scope !== 'global' && targets.length === 0) errors.push('targets-required')
227
+ if (scope === 'global' && targets.length > 0) errors.push('targets-not-allowed')
228
+ if (scope !== 'global' && targets.length > 20) errors.push('targets-too-many')
229
+
230
+ return {
231
+ errors,
232
+ sanitized: {
233
+ title: title.slice(0, MAX_RULE_TITLE),
234
+ content: content.slice(0, MAX_RULE_CONTENT),
235
+ scope,
236
+ targets,
237
+ },
238
+ }
239
+ }
240
+
241
+ async function createRule(body) {
242
+ const { errors, sanitized } = validateRuleInput(body)
243
+ if (errors.length > 0) {
244
+ const err = new Error(`rule-create: ${errors.join(',')}`)
245
+ err.status = 400
246
+ err.errors = errors
247
+ throw err
248
+ }
249
+ const rules = await loadRules()
250
+ const count = Object.keys(rules).filter((id) => rules[id].scope === sanitized.scope).length
251
+ if (count >= MAX_RULES_PER_SCOPE) {
252
+ const err = new Error(`rule-create: scope-limit`)
253
+ err.status = 409
254
+ throw err
255
+ }
256
+ const now = Date.now()
257
+ const id = uuidRule()
258
+ const enabled = body && typeof body.enabled === 'boolean' ? body.enabled : true
259
+ const rule = {
260
+ id,
261
+ title: sanitized.title,
262
+ content: sanitized.content,
263
+ scope: sanitized.scope,
264
+ targets: sanitized.targets,
265
+ enabled,
266
+ createdAt: now,
267
+ updatedAt: now,
268
+ }
269
+ rules[id] = rule
270
+ await saveRules(rules)
271
+ return { rule }
272
+ }
273
+
274
+ async function updateRule(id, body) {
275
+ const rules = await loadRules()
276
+ if (!rules[id]) {
277
+ const err = new Error(`rule-update: not-found`)
278
+ err.status = 404
279
+ throw err
280
+ }
281
+ const existing = rules[id]
282
+ const patch = {}
283
+ let updated = false
284
+
285
+ if (body && typeof body === 'object') {
286
+ if ('title' in body) {
287
+ const title = String(body.title || '').trim()
288
+ if (!title) {
289
+ const err = new Error(`rule-update: title-empty`)
290
+ err.status = 400
291
+ throw err
292
+ }
293
+ patch.title = title.slice(0, MAX_RULE_TITLE)
294
+ updated = true
295
+ }
296
+ if ('content' in body) {
297
+ const content = String(body.content || '').trim()
298
+ if (!content) {
299
+ const err = new Error(`rule-update: content-empty`)
300
+ err.status = 400
301
+ throw err
302
+ }
303
+ patch.content = content.slice(0, MAX_RULE_CONTENT)
304
+ updated = true
305
+ }
306
+ if ('scope' in body) {
307
+ const scope = String(body.scope || '').trim()
308
+ if (!RULE_SCOPES.has(scope)) {
309
+ const err = new Error(`rule-update: scope-invalid`)
310
+ err.status = 400
311
+ throw err
312
+ }
313
+ patch.scope = scope
314
+ updated = true
315
+ }
316
+ if ('targets' in body) {
317
+ if (!Array.isArray(body.targets)) {
318
+ const err = new Error(`rule-update: targets-invalid`)
319
+ err.status = 400
320
+ throw err
321
+ }
322
+ patch.targets = body.targets
323
+ .map((t) => String(t).trim().slice(0, 1024))
324
+ .filter(Boolean)
325
+ if (patch.targets.length > 20) {
326
+ const err = new Error(`rule-update: targets-too-many`)
327
+ err.status = 400
328
+ throw err
329
+ }
330
+ updated = true
331
+ }
332
+ if ('enabled' in body) {
333
+ patch.enabled = body.enabled !== false
334
+ updated = true
335
+ }
336
+ }
337
+
338
+ // Scope vs targets consistency re-check
339
+ const nextScope = patch.scope || existing.scope
340
+ const nextTargets = patch.targets !== undefined ? patch.targets : existing.targets
341
+ if (nextScope !== 'global' && (!Array.isArray(nextTargets) || nextTargets.length === 0)) {
342
+ const err = new Error(`rule-update: targets-required`)
343
+ err.status = 400
344
+ throw err
345
+ }
346
+ if (nextScope === 'global' && Array.isArray(nextTargets) && nextTargets.length > 0) {
347
+ const err = new Error(`rule-update: targets-not-allowed`)
348
+ err.status = 400
349
+ throw err
350
+ }
351
+
352
+ if (updated) {
353
+ rules[id] = { ...existing, ...patch, updatedAt: Date.now() }
354
+ await saveRules(rules)
355
+ }
356
+ return { rule: rules[id] }
357
+ }
358
+
359
+ async function deleteRule(id) {
360
+ const rules = await loadRules()
361
+ if (!rules[id]) {
362
+ const err = new Error(`rule-delete: not-found`)
363
+ err.status = 404
364
+ throw err
365
+ }
366
+ const rule = rules[id]
367
+ delete rules[id]
368
+ await saveRules(rules)
369
+ return { rule }
370
+ }
371
+
372
+ async function toggleRule(id, enabled) {
373
+ const rules = await loadRules()
374
+ if (!rules[id]) {
375
+ const err = new Error(`rule-toggle: not-found`)
376
+ err.status = 404
377
+ throw err
378
+ }
379
+ rules[id].enabled = enabled !== false
380
+ rules[id].updatedAt = Date.now()
381
+ await saveRules(rules)
382
+ return { rule: rules[id] }
383
+ }
384
+
135
385
  async function buildList() {
136
386
  const records = await listRecords()
137
387
  const cache = await readProjectionCache()
@@ -1159,6 +1409,15 @@ export function apply(ctx) {
1159
1409
  const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
1160
1410
  return sendDownload(response, `nanshan-sessions-${stamp}.json`, bundle)
1161
1411
  }
1412
+ if (pathname === `${API}/rules`) {
1413
+ if (request.method === 'HEAD') {
1414
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
1415
+ response.end()
1416
+ return
1417
+ }
1418
+ const result = await listRules()
1419
+ return sendJson(response, 200, { ok: true, ...result })
1420
+ }
1162
1421
  return sendJson(response, 404, { ok: false, error: 'not-found', message: '未知的会话管理接口。' })
1163
1422
  }
1164
1423
 
@@ -1192,6 +1451,29 @@ export function apply(ctx) {
1192
1451
  const result = await exclusive(() => purgeTrash(trashIds))
1193
1452
  return sendJson(response, 200, { ok: true, ...result })
1194
1453
  }
1454
+ if (pathname === `${API}/rules/create`) {
1455
+ const result = await exclusive(() => createRule(body))
1456
+ return sendJson(response, 200, { ok: true, ...result })
1457
+ }
1458
+ if (pathname === `${API}/rules/update`) {
1459
+ const id = body?.id ? String(body.id).trim() : ''
1460
+ if (!id) return sendJson(response, 400, { ok: false, error: 'id', message: '缺少规则 id。' })
1461
+ const result = await exclusive(() => updateRule(id, body))
1462
+ return sendJson(response, 200, { ok: true, ...result })
1463
+ }
1464
+ if (pathname === `${API}/rules/delete`) {
1465
+ const id = body?.id ? String(body.id).trim() : ''
1466
+ if (!id) return sendJson(response, 400, { ok: false, error: 'id', message: '缺少规则 id。' })
1467
+ const result = await exclusive(() => deleteRule(id))
1468
+ return sendJson(response, 200, { ok: true, ...result })
1469
+ }
1470
+ if (pathname === `${API}/rules/toggle`) {
1471
+ const id = body?.id ? String(body.id).trim() : ''
1472
+ if (!id) return sendJson(response, 400, { ok: false, error: 'id', message: '缺少规则 id。' })
1473
+ const enabled = body?.enabled !== false
1474
+ const result = await exclusive(() => toggleRule(id, enabled))
1475
+ return sendJson(response, 200, { ok: true, ...result })
1476
+ }
1195
1477
  return sendJson(response, 404, { ok: false, error: 'not-found', message: '未知的会话管理接口。' })
1196
1478
  } catch (error) {
1197
1479
  const status = error && Number.isInteger(error.status) ? error.status : 500
@@ -1209,6 +1491,135 @@ export function apply(ctx) {
1209
1491
  () => ctx.webServer.register({ kind: 'prefix', path: API, handler }),
1210
1492
  'nanshan-session-manager: session management api',
1211
1493
  )
1494
+
1495
+ // Inject enabled rules into every agent step as durable instruction context.
1496
+ ctx.on('agent/pre-step', async (payload, next) => {
1497
+ const decision = await next()
1498
+ if (!decision || decision.kind === 'reject') return decision
1499
+ try {
1500
+ const agent = payload.agent
1501
+ const session = agent && agent.session
1502
+ const sessionId = session && session.id
1503
+ if (!sessionId) return decision
1504
+
1505
+ const rules = await loadRules()
1506
+ const enabled = Object.values(rules).filter((rule) => rule.enabled)
1507
+ if (enabled.length === 0) return decision
1508
+
1509
+ const cwd = await resolveAgentCwd(service, agent, payload.signal)
1510
+ const workspaceId = resolveWorkspaceId(service, cwd)
1511
+ const matched = enabled.filter((rule) => ruleMatches(rule, { sessionId, cwd, workspaceId }))
1512
+ if (matched.length === 0) return decision
1513
+
1514
+ const digest = ruleContextDigest(matched)
1515
+ if (sessionHasRuleContext(session, digest)) return decision
1516
+
1517
+ const batch = Array.isArray(decision.messages) ? decision.messages : []
1518
+ if (batch.some((message) => message && message.source
1519
+ && message.source.kind === RULE_SOURCE_KIND
1520
+ && message.source.digest === digest)) return decision
1521
+
1522
+ // An empty first entry owns a no-step turn; keep context pending for the next real prompt.
1523
+ if (payload.step === 1 && batch.length === 0) return decision
1524
+
1525
+ const message = {
1526
+ id: randomUUID(),
1527
+ role: 'user',
1528
+ content: [{ type: 'text', text: renderRuleContext(matched) }],
1529
+ source: { kind: RULE_SOURCE_KIND, digest },
1530
+ }
1531
+ return { ...decision, messages: [...batch, message] }
1532
+ } catch (error) {
1533
+ ctx.logger?.warn?.('nanshan-session-manager: rule injection failed: %o', error)
1534
+ return decision
1535
+ }
1536
+ })
1537
+ }
1538
+
1539
+ const RULE_SOURCE_KIND = 'nanshan-rule-context'
1540
+
1541
+ async function resolveAgentCwd(service, agent, signal) {
1542
+ try {
1543
+ const workingDirectory = service('workingDirectory')
1544
+ if (workingDirectory && typeof workingDirectory.ensure === 'function') {
1545
+ const cwd = await workingDirectory.ensure(agent, signal)
1546
+ if (typeof cwd === 'string' && cwd !== '') return cwd
1547
+ }
1548
+ } catch {
1549
+ // Fall through to the session header when the provider is unavailable.
1550
+ }
1551
+ const header = agent && agent.session && agent.session.header
1552
+ const fallback = header && (header.cwd || header.directory)
1553
+ return typeof fallback === 'string' && fallback !== '' ? fallback : null
1554
+ }
1555
+
1556
+ function resolveWorkspaceId(service, cwd) {
1557
+ if (!cwd) return null
1558
+ try {
1559
+ const registry = service('workspaceRegistry')
1560
+ if (!registry || typeof registry.list !== 'function') return null
1561
+ const list = registry.list()
1562
+ let best = null
1563
+ for (const workspace of Array.isArray(list) ? list : []) {
1564
+ const path = workspace && (workspace.path || workspace.directory)
1565
+ if (typeof path !== 'string' || path === '') continue
1566
+ if (cwd === path || cwd.startsWith(path.endsWith('/') ? path : `${path}/`)) {
1567
+ if (!best || path.length > best.path.length) best = { id: workspace.id, path }
1568
+ }
1569
+ }
1570
+ return best ? best.id : null
1571
+ } catch {
1572
+ return null
1573
+ }
1574
+ }
1575
+
1576
+ function ruleMatches(rule, { sessionId, cwd, workspaceId }) {
1577
+ const targets = Array.isArray(rule.targets) ? rule.targets : []
1578
+ if (rule.scope === 'global') return true
1579
+ if (rule.scope === 'session') return targets.includes(sessionId)
1580
+ if (rule.scope === 'workspace') {
1581
+ if (workspaceId && targets.includes(workspaceId)) return true
1582
+ if (cwd) {
1583
+ return targets.some((target) => {
1584
+ if (typeof target !== 'string' || target === '') return false
1585
+ return cwd === target || cwd.startsWith(target.endsWith('/') ? target : `${target}/`)
1586
+ })
1587
+ }
1588
+ }
1589
+ return false
1590
+ }
1591
+
1592
+ function ruleContextDigest(rules) {
1593
+ const payload = rules
1594
+ .map((rule) => `${rule.id}\u0000${rule.updatedAt}\u0000${rule.title}\u0000${rule.content}`)
1595
+ .join('\u0001')
1596
+ return createHash('sha256').update(payload).digest('hex').slice(0, 16)
1597
+ }
1598
+
1599
+ function renderRuleContext(rules) {
1600
+ const body = rules.map((rule) => `## ${rule.title}\n\n${rule.content}`).join('\n\n')
1601
+ return [
1602
+ '<nanshan-rules>',
1603
+ '以下规则由用户在【南山】规则管理中启用,请在本会话的所有回复中遵守。',
1604
+ '若此前出现过 <nanshan-rules> 块,以本条为最新版本。',
1605
+ '',
1606
+ body,
1607
+ '</nanshan-rules>',
1608
+ ].join('\n')
1609
+ }
1610
+
1611
+ function sessionHasRuleContext(session, digest) {
1612
+ if (!session) return false
1613
+ const surface = session.surface
1614
+ const nodes = surface && surface.nodes
1615
+ if (!nodes || typeof session.eventAt !== 'function') return false
1616
+ const seqs = Array.from(nodes)
1617
+ for (let index = seqs.length - 1; index >= 0; index -= 1) {
1618
+ const event = session.eventAt(seqs[index])
1619
+ const source = event && event.type === 'user/message' && event.data && event.data.source
1620
+ if (source && source.kind === RULE_SOURCE_KIND && source.digest === digest) return true
1621
+ }
1622
+ return false
1212
1623
  }
1213
1624
 
1214
1625
  function httpError(status, message) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wangnanshan/dsh-nanshan-session-manager",
3
- "version": "1.1.9",
3
+ "version": "1.5.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "【南山】会话管理助手:在左侧栏筛选、按 ID 搜索、删除、恢复、导出和导入 DeepSeek Harness 的全部会话。",