@fubai-fenzhi/dsh-session-admin 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +9 -0
  2. package/lib/index.js +126 -0
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -40,6 +40,15 @@ dsh plugin install_bundle --target npm:@fubai-fenzhi/dsh-session-admin
40
40
  - 把 `team/mode` 写入当前 root 的会话日志;不需要 UI 开关
41
41
  - 错误:`E_SERVICE_UNAVAILABLE` / `E_NOT_ROOT` / `E_TEAM_ENABLE_FAILED`
42
42
 
43
+ ### session_sweep
44
+ ```json
45
+ { "dryRun": true, "minIdleMinutes": 10 }
46
+ ```
47
+ - 清僵尸会话:**默认 dryRun**(只列 candidates,不动);`dryRun:false` 才归档
48
+ - 判定写死:**调用瞬间现读名册** → 排除已归档、名册绑定、调用者自己、拿不到活动时间的会话;空闲 ≥ `minIdleMinutes`(低于 10 按 10)
49
+ - 每次最多归档 20 个,超了只报不删;`dryRun:false` 受 `allowedActors` 限制
50
+ - 每归档一个写一行审计:`action=sweep_archive`(actor、actorId、target、before title hash、result)
51
+
43
52
  ## 配置(cordis.patch.yml)
44
53
 
45
54
  | 键 | 默认 | 说明 |
package/lib/index.js CHANGED
@@ -15,6 +15,7 @@ export function normalizeConfig(raw = {}) {
15
15
  maxTitleBytes: Number.isInteger(source.maxTitleBytes) && source.maxTitleBytes > 0 ? source.maxTitleBytes : 120,
16
16
  allowedActors: Array.isArray(source.allowedActors) ? source.allowedActors.map(String) : [],
17
17
  rosterFile: typeof source.rosterFile === 'string' ? source.rosterFile.trim() : '',
18
+ workspaceStoreFile: typeof source.workspaceStoreFile === 'string' ? source.workspaceStoreFile.trim() : '',
18
19
  };
19
20
  }
20
21
 
@@ -246,6 +247,131 @@ export function apply(ctx, rawConfig) {
246
247
  presentCall: (args) => ({ card: 'generic', title: '会话归档', kind: 'other', rawInput: args }),
247
248
  });
248
249
 
250
+ function resolveWorkspaceStoreFile() {
251
+ if (cfg.workspaceStoreFile) return cfg.workspaceStoreFile;
252
+ try {
253
+ return join(homedir(), '.dsh', 'storages', 'workspace.json');
254
+ } catch {
255
+ return '';
256
+ }
257
+ }
258
+
259
+ function freshRosterBinding() {
260
+ const file = resolveRosterFile();
261
+ if (!file) return null;
262
+ try {
263
+ const state = JSON.parse(readFileSync(file, 'utf8'));
264
+ const bound = new Set();
265
+ for (const member of Array.isArray(state.members) ? state.members : []) {
266
+ if (member?.sessionId) bound.add(String(member.sessionId));
267
+ }
268
+ if (bound.size === 0) return null;
269
+ return bound;
270
+ } catch {
271
+ return null;
272
+ }
273
+ }
274
+
275
+ function readArchivedSet() {
276
+ const file = resolveWorkspaceStoreFile();
277
+ if (!file) return new Set();
278
+ try {
279
+ const store = JSON.parse(readFileSync(file, 'utf8'));
280
+ const ids = Array.isArray(store?.global?.archivedSessionIds)
281
+ ? store.global.archivedSessionIds
282
+ : Array.isArray(store?.archivedSessionIds) ? store.archivedSessionIds : [];
283
+ return new Set(ids.map(String));
284
+ } catch {
285
+ return new Set();
286
+ }
287
+ }
288
+
289
+ async function lastActivityOf(query, sessionId) {
290
+ try {
291
+ const events = await query.listEvents(sessionId);
292
+ let last = 0;
293
+ for (const event of events) if (Number(event.time) > last) last = Number(event.time);
294
+ return last > 0 ? last : undefined;
295
+ } catch {
296
+ return undefined;
297
+ }
298
+ }
299
+
300
+ ctx.tools.register({
301
+ name: 'session_sweep',
302
+ description: 'Archive idle orphan sessions that are not bound in the live coordination roster. Dry-run by default; reads the roster fresh at call time and refuses to archive the calling session, roster members, or sessions without a known last activity.',
303
+ parameters: objectSchema({
304
+ dryRun: { type: 'boolean', description: 'true (default) only lists candidates; false archives up to 20.' },
305
+ minIdleMinutes: { type: 'integer', description: 'Idle threshold in minutes; values below 10 are treated as 10.' },
306
+ }, []),
307
+ output: textOutput(objectSchema({
308
+ ok: { type: 'boolean' },
309
+ scanned: { type: 'integer' },
310
+ dryRun: { type: 'boolean' },
311
+ rosterBound: { type: 'integer' },
312
+ candidates: { type: 'array', items: objectSchema({ sessionId: { type: 'string' }, title: { type: 'string' }, reason: { type: 'string' } }, ['sessionId']) },
313
+ archived: { type: 'array', items: { type: 'string' } },
314
+ skipped: { type: 'array', items: objectSchema({ sessionId: { type: 'string' }, why: { type: 'string' } }, ['sessionId', 'why']) },
315
+ }, ['ok'])),
316
+ async execute(args = {}) {
317
+ const query = getService('sessionQuery');
318
+ const registry = getService('workspaceRegistry');
319
+ if (!query || typeof query.listSessions !== 'function') throw E('E_SERVICE_UNAVAILABLE', 'sessionQuery service unavailable');
320
+ const dryRun = args.dryRun !== false;
321
+ const minIdleMinutes = Math.max(10, Number.isInteger(args.minIdleMinutes) ? args.minIdleMinutes : 10);
322
+ const selfId = String(callingAgent()?.id ?? '');
323
+ const bound = freshRosterBinding();
324
+ if (!bound) throw E('E_ROSTER_UNAVAILABLE', 'roster unreadable or empty; refusing to sweep');
325
+ const archivedSet = readArchivedSet();
326
+ const records = await query.listSessions();
327
+ const now = Date.now();
328
+ const candidates = [];
329
+ const skipped = [];
330
+ for (const record of records) {
331
+ const sessionId = String(record?.header?.id ?? '');
332
+ if (!sessionId) continue;
333
+ if (archivedSet.has(sessionId)) { skipped.push({ sessionId, why: 'already-archived' }); continue; }
334
+ if (bound.has(sessionId)) { skipped.push({ sessionId, why: 'roster-bound' }); continue; }
335
+ if (selfId && sessionId === selfId) { skipped.push({ sessionId, why: 'self' }); continue; }
336
+ const last = await lastActivityOf(query, sessionId);
337
+ if (!last) { skipped.push({ sessionId, why: 'no-activity-time' }); continue; }
338
+ if (now - last < minIdleMinutes * 60000) { skipped.push({ sessionId, why: 'not-idle' }); continue; }
339
+ let title;
340
+ try {
341
+ const t = await query.readTitle(sessionId);
342
+ title = t?.title;
343
+ } catch {
344
+ title = undefined;
345
+ }
346
+ candidates.push({ sessionId, title, reason: `idle ${Math.round((now - last) / 60000)}m` });
347
+ }
348
+ if (dryRun) {
349
+ return { ok: true, scanned: records.length, dryRun: true, rosterBound: bound.size, candidates, archived: [], skipped };
350
+ }
351
+ assertArchiveActor();
352
+ if (!registry || typeof registry.archiveSession !== 'function') throw E('E_SERVICE_UNAVAILABLE', 'workspaceRegistry service unavailable');
353
+ const archived = [];
354
+ for (const candidate of candidates.slice(0, 20)) {
355
+ const liveBound = freshRosterBinding();
356
+ if (!liveBound) throw E('E_ROSTER_UNAVAILABLE', 'roster became unreadable during sweep; aborting');
357
+ if (liveBound.has(candidate.sessionId) || candidate.sessionId === String(callingAgent()?.id ?? '')) {
358
+ skipped.push({ sessionId: candidate.sessionId, why: 'recheck-rejected' });
359
+ continue;
360
+ }
361
+ try {
362
+ await registry.archiveSession(candidate.sessionId, {});
363
+ archived.push(candidate.sessionId);
364
+ audit({ action: 'sweep_archive', sessionId: candidate.sessionId, before: candidate.title ? titleDigest(candidate.title) : null, result: 'ok' });
365
+ } catch (error) {
366
+ skipped.push({ sessionId: candidate.sessionId, why: 'archive-failed: ' + String(error?.message ?? error) });
367
+ }
368
+ }
369
+ for (const candidate of candidates.slice(20)) skipped.push({ sessionId: candidate.sessionId, why: 'over-limit-20' });
370
+ return { ok: true, scanned: records.length, dryRun: false, rosterBound: bound.size, candidates, archived, skipped };
371
+ },
372
+ presentCall: (args) => ({ card: 'generic', title: '清理僵尸会话', kind: 'other', rawInput: args }),
373
+ });
374
+
249
375
  ctx.tools.register({
250
376
  name: 'session_team_enable',
251
377
  description: 'Enable or disable DSH Agent Teams for the calling root session. Only the current live root may call this; descendants inherit the selection. Persists team/mode in the root session log.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fubai-fenzhi/dsh-session-admin",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "main": "lib/index.js",
6
6
  "exports": {