dsh-powertools 0.2.1 → 0.2.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/sessions.js CHANGED
@@ -82,6 +82,8 @@ export async function collectAllSessions(ctx, signal) {
82
82
  const liveSessions = typeof ctx.sessions?.list === 'function' ? ctx.sessions.list() : []
83
83
  const workspaces = typeof ctx.workspaceRegistry?.list === 'function' ? ctx.workspaceRegistry.list() : []
84
84
  const archivedSet = new Set(ctx.workspaceRegistry?.archivedSessionIds ?? [])
85
+ const pinnedList = Array.isArray(ctx.workspaceRegistry?.pinnedSessionIds) ? ctx.workspaceRegistry.pinnedSessionIds : []
86
+ const pinnedOrder = new Map(pinnedList.map((id, index) => [id, index]))
85
87
 
86
88
  const wsBySession = new Map()
87
89
  for (const ws of workspaces) {
@@ -109,6 +111,8 @@ export async function collectAllSessions(ctx, signal) {
109
111
  resident: false,
110
112
  running: false,
111
113
  archived: archivedSet.has(header.id),
114
+ pinned: pinnedOrder.has(header.id),
115
+ pinnedRank: pinnedOrder.get(header.id) ?? -1,
112
116
  sizeBytes: snap.sizeBytes ?? null,
113
117
  eventCount: snap.eventCount ?? null,
114
118
  location: snap.location ?? null,
@@ -136,6 +140,8 @@ export async function collectAllSessions(ctx, signal) {
136
140
  resident: true,
137
141
  running,
138
142
  archived: archivedSet.has(header.id),
143
+ pinned: pinnedOrder.has(header.id),
144
+ pinnedRank: pinnedOrder.get(header.id) ?? -1,
139
145
  sizeBytes: existing?.sizeBytes ?? null,
140
146
  eventCount: existing?.eventCount ?? null,
141
147
  location: existing?.location ?? null,
@@ -153,26 +159,26 @@ export async function collectAllSessions(ctx, signal) {
153
159
  const rootId = rootAncestor(item)
154
160
  const orphanSubagent = item.isSubagent && (!item.parentSessionId || !byId.has(item.parentSessionId))
155
161
  const cascadeIds = [item.id, ...descendantIds]
156
- let deletable = true
157
162
  let deleteReason = ''
163
+ let deleteBlocker
158
164
 
159
165
  for (const targetId of cascadeIds) {
160
166
  const target = byId.get(targetId)
161
167
  if (!target) continue
162
168
  if (target.running) {
163
- deletable = false
169
+ deleteBlocker = target.id === item.id ? 'running' : 'childRunning'
164
170
  deleteReason = target.id === item.id ? '会话正在运行中,请先停止后再删除。' : '关联子 Agent 正在运行中,请先停止后再删除。'
165
171
  break
166
172
  }
167
173
  if (target.resident) {
168
- deletable = false
174
+ deleteBlocker = target.id === item.id ? 'resident' : 'childResident'
169
175
  deleteReason = target.id === item.id
170
176
  ? '会话正由当前 DSH 进程打开持有,请关闭或重启 DSH 释放句柄后再删除。'
171
177
  : '关联子 Agent 正由当前 DSH 进程持有,请等待结束或重启 DSH 后再删除。'
172
178
  break
173
179
  }
174
180
  if (target.location?.kind !== 'jsonl' || !target.location?.path) {
175
- deletable = false
181
+ deleteBlocker = 'storage'
176
182
  deleteReason = '当前会话或关联子 Agent 未落盘为 JSONL 单会话目录(如 SQLite 后端),暂不支持安全删除。'
177
183
  break
178
184
  }
@@ -193,13 +199,16 @@ export async function collectAllSessions(ctx, signal) {
193
199
  resident: item.resident,
194
200
  running: item.running,
195
201
  archived: item.archived,
202
+ pinned: item.pinned,
203
+ pinnedRank: item.pinnedRank,
196
204
  sizeBytes: item.sizeBytes,
197
205
  eventCount: item.eventCount,
198
206
  backendKind: item.location?.kind ?? (item.persisted ? 'unknown' : 'pending'),
199
207
  workspaces: item.workspaces.map(({ workspaceId, title }) => ({ workspaceId, title })),
200
208
  directSubagentIds,
201
209
  descendantSubagentIds: descendantIds,
202
- deletable,
210
+ deletable: !deleteBlocker,
211
+ deleteBlocker,
203
212
  deleteReason: deleteReason || undefined,
204
213
  _location: item.location,
205
214
  }
@@ -360,8 +369,138 @@ export function sessionOperations(ctx) {
360
369
  return executeDelete(uniqueIds, null, signal)
361
370
  }
362
371
 
372
+ function extractEventPlainText(event) {
373
+ if (!event || typeof event !== 'object') return ''
374
+ if (event.type === 'user/message') {
375
+ const kind = event.data?.source?.kind
376
+ if (kind && kind !== 'user') return ''
377
+ const content = event.data?.content
378
+ if (!Array.isArray(content)) return ''
379
+ return content.filter(block => block?.type === 'text' && typeof block.text === 'string').map(block => block.text).join('\n').trim()
380
+ }
381
+ if (event.type === 'assistant/message') {
382
+ const content = event.data?.message?.content
383
+ if (!Array.isArray(content)) return ''
384
+ return content.filter(block => block?.type === 'text' && typeof block.text === 'string').map(block => block.text).join('\n').trim()
385
+ }
386
+ return ''
387
+ }
388
+
389
+ function buildSnippet(text, needleLower) {
390
+ const collapsed = text.replace(/\s+/g, ' ').trim()
391
+ const index = collapsed.toLowerCase().indexOf(needleLower)
392
+ if (index < 0) return ''
393
+ const start = Math.max(0, index - 40)
394
+ const end = Math.min(collapsed.length, index + needleLower.length + 100)
395
+ return `${start > 0 ? '…' : ''}${collapsed.slice(start, end)}${end < collapsed.length ? '…' : ''}`
396
+ }
397
+
398
+ async function scanSessionsFallback(sessionQuery, query, limit, signal) {
399
+ const all = await collectAllSessions(ctx, signal)
400
+ const ordered = [...all].sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0)).slice(0, 200)
401
+ const needleLower = query.toLowerCase()
402
+ const hits = []
403
+ let index = 0
404
+ const concurrency = 4
405
+
406
+ async function worker() {
407
+ while (index < ordered.length && hits.length < limit) {
408
+ signal?.throwIfAborted()
409
+ const row = ordered[index++]
410
+ if (!row) break
411
+ let snapshot
412
+ try {
413
+ snapshot = await sessionQuery.readSession(row.id)
414
+ } catch {
415
+ continue
416
+ }
417
+ const events = Array.isArray(snapshot?.events) ? snapshot.events : []
418
+ for (let i = events.length - 1; i >= 0; i--) {
419
+ const event = events[i]
420
+ const text = extractEventPlainText(event)
421
+ if (!text) continue
422
+ const snippet = buildSnippet(text, needleLower)
423
+ if (snippet) {
424
+ hits.push({
425
+ sessionId: row.id,
426
+ seq: event.seq ?? null,
427
+ type: event.type ?? '',
428
+ time: event.time ?? row.createdAt ?? 0,
429
+ snippet,
430
+ })
431
+ break
432
+ }
433
+ }
434
+ }
435
+ }
436
+
437
+ await Promise.all(Array.from({ length: Math.min(concurrency, ordered.length) }, () => worker()))
438
+ hits.sort((a, b) => (b.time ?? 0) - (a.time ?? 0))
439
+ return { query, hits: hits.slice(0, limit), hasMore: hits.length > limit }
440
+ }
441
+
442
+ async function search(body, signal) {
443
+ const query = typeof body.query === 'string' ? body.query.trim() : ''
444
+ requireValue(query && query.length <= 256, '请输入 256 字以内的搜索关键词。')
445
+ const sessionQuery = typeof ctx.get === 'function' ? ctx.get('sessionQuery') : ctx.sessionQuery
446
+ requireValue(
447
+ typeof sessionQuery?.searchSessions === 'function' || typeof sessionQuery?.readSession === 'function',
448
+ '当前 DSH 配置未启用会话正文检索服务。',
449
+ 503,
450
+ )
451
+ const rawLimit = Number(body.limit)
452
+ const limit = Number.isInteger(rawLimit) && rawLimit >= 1 && rawLimit <= 100 ? rawLimit : 50
453
+ if (typeof sessionQuery.searchSessions === 'function') {
454
+ try {
455
+ const page = await sessionQuery.searchSessions({ query, limit }, { signal })
456
+ const cleanSnippet = raw => typeof raw === 'string'
457
+ ? raw.replaceAll('\uFDD0', '').replaceAll('\uFDD1', '').replace(/\s+/g, ' ').trim()
458
+ : ''
459
+ const hits = (page?.items ?? []).map(hit => ({
460
+ sessionId: hit.header?.id ?? hit.bestMatch?.sessionId,
461
+ seq: hit.bestMatch?.seq ?? null,
462
+ type: hit.bestMatch?.type ?? '',
463
+ time: hit.bestMatch?.time ?? 0,
464
+ snippet: cleanSnippet(hit.bestMatch?.snippet),
465
+ })).filter(hit => hit.sessionId)
466
+ return { query, hits, hasMore: Boolean(page?.nextCursor) }
467
+ } catch (error) {
468
+ if (error?.code !== 'SESSION_QUERY_SEARCH_DISABLED' || typeof sessionQuery.readSession !== 'function') {
469
+ if (error instanceof RequestError) throw error
470
+ throw new RequestError('会话正文搜索未完成,请稍后重试。', 502)
471
+ }
472
+ }
473
+ }
474
+ return scanSessionsFallback(sessionQuery, query, limit, signal)
475
+ }
476
+
477
+ async function setPinned(body, pinned) {
478
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
479
+ requireValue(sessionId, '请指定要操作的会话 ID。')
480
+ const fn = pinned ? ctx.workspaceRegistry?.pinSession : ctx.workspaceRegistry?.unpinSession
481
+ requireValue(typeof fn === 'function', '当前 DSH 版本不支持会话置顶。', 501)
482
+ try {
483
+ await fn.call(ctx.workspaceRegistry, sessionId)
484
+ } catch (error) {
485
+ if (error?.name === 'WorkspaceArchivedSessionPinError') {
486
+ throw new RequestError('已归档的会话不能置顶,请先恢复会话。', 409)
487
+ }
488
+ if (error?.name === 'WorkspaceUnknownSessionError') {
489
+ throw new RequestError('目标会话不存在或已被移除,请刷新列表。', 404)
490
+ }
491
+ throw error
492
+ }
493
+ return { sessionId, pinned }
494
+ }
495
+
363
496
  return (body, signal) => {
364
497
  if (body.action === 'list') return list(signal)
498
+ if (body.action === 'search') return search(body, signal)
499
+ if (body.action === 'pin' || body.action === 'unpin') {
500
+ const pending = tail.then(() => setPinned(body, body.action === 'pin'))
501
+ tail = pending.catch(() => {})
502
+ return pending
503
+ }
365
504
  if (body.action === 'delete') {
366
505
  const pending = tail.then(() => remove(body, signal))
367
506
  tail = pending.catch(() => {})
package/lib/tasks.js ADDED
@@ -0,0 +1,244 @@
1
+ import { RequestError, requireValue } from './errors.js'
2
+
3
+ const liveJobStates = new Set(['running', 'stopping'])
4
+ const maxJobOutputBytes = 16 * 1024
5
+
6
+ function projectJob(view) {
7
+ return {
8
+ id: view.id,
9
+ kind: view.kind ?? 'job',
10
+ label: view.label ?? view.id,
11
+ owner: view.owner ?? null,
12
+ status: view.status,
13
+ progress: view.progress ?? undefined,
14
+ detail: view.detail ?? undefined,
15
+ exitCode: Number.isInteger(view.exitCode) ? view.exitCode : undefined,
16
+ startedAt: view.startedAt ?? 0,
17
+ finishedAt: view.finishedAt ?? undefined,
18
+ output: {
19
+ total: view.output?.total ?? 0,
20
+ earliest: view.output?.earliest ?? 0,
21
+ hasSpill: Boolean(view.output?.spillPaths?.length),
22
+ },
23
+ }
24
+ }
25
+
26
+ function collectAllJobs(ctx) {
27
+ const byId = new Map()
28
+ const addList = list => {
29
+ if (!Array.isArray(list)) return
30
+ for (const view of list) {
31
+ if (view?.id && !byId.has(view.id)) byId.set(view.id, view)
32
+ }
33
+ }
34
+ addList(ctx.jobs.list())
35
+ const sessions = typeof ctx.sessions?.list === 'function' ? ctx.sessions.list() : []
36
+ for (const session of sessions) {
37
+ const id = session?.header?.id
38
+ if (id) addList(ctx.jobs.list(id))
39
+ }
40
+ return [...byId.values()].sort((a, b) => {
41
+ const aLive = liveJobStates.has(a.status) ? 0 : 1
42
+ const bLive = liveJobStates.has(b.status) ? 0 : 1
43
+ if (aLive !== bLive) return aLive - bLive
44
+ return (b.startedAt ?? 0) - (a.startedAt ?? 0) || String(a.id).localeCompare(String(b.id))
45
+ })
46
+ }
47
+
48
+ export function jobOperations(ctx) {
49
+ return (body, signal) => {
50
+ signal?.throwIfAborted()
51
+ if (body.action === 'list') {
52
+ return { jobs: collectAllJobs(ctx).map(projectJob) }
53
+ }
54
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
55
+ requireValue(id, '请指定后台任务 ID。')
56
+ const all = collectAllJobs(ctx)
57
+ const found = all.find(item => item.id === id)
58
+ requireValue(found, '后台任务已不存在,请刷新列表。', 404)
59
+ const caller = found.owner ?? undefined
60
+
61
+ if (body.action === 'output') {
62
+ const total = found.output?.total ?? 0
63
+ const earliest = found.output?.earliest ?? 0
64
+ const from = Math.max(earliest, total - maxJobOutputBytes)
65
+ const read = ctx.jobs.readAt(id, from, caller)
66
+ const chunks = Array.isArray(read?.chunks) ? read.chunks : []
67
+ let text = chunks.map(chunk => chunk.text ?? '').join('')
68
+ const truncated = from > 0 || Boolean(read?.lossy) || Buffer.byteLength(text) > maxJobOutputBytes
69
+ if (Buffer.byteLength(text) > maxJobOutputBytes) {
70
+ text = Buffer.from(text, 'utf8').subarray(-maxJobOutputBytes).toString('utf8')
71
+ }
72
+ return {
73
+ id,
74
+ text,
75
+ truncated,
76
+ total,
77
+ earliest,
78
+ status: found.status,
79
+ }
80
+ }
81
+
82
+ if (body.action === 'kill') {
83
+ requireValue(body.confirm === id, '请确认要停止的后台任务。', 409)
84
+ const outcome = ctx.jobs.kill(id, caller, '由 DSH 工具箱手动停止')
85
+ return { id, outcome }
86
+ }
87
+
88
+ if (body.action === 'remove') {
89
+ requireValue(!liveJobStates.has(found.status), '运行中的任务无法清理记录,请先停止。', 409)
90
+ ctx.jobs.remove(id, caller)
91
+ return { id }
92
+ }
93
+
94
+ throw new RequestError('后台任务操作无效。')
95
+ }
96
+ }
97
+
98
+ function projectSchedule(entry) {
99
+ return {
100
+ id: entry.id,
101
+ kind: entry.kind,
102
+ title: entry.title ?? entry.id,
103
+ prompt: entry.prompt ?? '',
104
+ scheduledAt: entry.scheduledAt ?? '',
105
+ status: entry.status,
106
+ target: entry.target
107
+ ? {
108
+ kind: entry.target.kind,
109
+ sessionId: entry.target.sessionId ?? null,
110
+ cwd: entry.target.create?.cwd ?? null,
111
+ agentPreset: entry.target.create?.agentPreset ?? null,
112
+ }
113
+ : null,
114
+ involvedSessionIds: Array.isArray(entry.involvedSessionIds) ? entry.involvedSessionIds : [],
115
+ executionActive: Boolean(entry.executionActive),
116
+ createdAt: entry.createdAt ?? null,
117
+ updatedAt: entry.updatedAt ?? null,
118
+ lastDelivery: entry.lastDelivery
119
+ ? {
120
+ scheduledAt: entry.lastDelivery.scheduledAt,
121
+ deliveredAt: entry.lastDelivery.deliveredAt,
122
+ targetSessionId: entry.lastDelivery.targetSessionId,
123
+ }
124
+ : null,
125
+ afterSeconds: entry.afterSeconds ?? undefined,
126
+ everySeconds: entry.everySeconds ?? undefined,
127
+ time: entry.time ?? undefined,
128
+ timeZone: entry.timeZone ?? undefined,
129
+ weekdays: Array.isArray(entry.weekdays) ? entry.weekdays : undefined,
130
+ expression: entry.expression ?? undefined,
131
+ rrule: entry.rrule ?? undefined,
132
+ }
133
+ }
134
+
135
+ function mapScheduleError(error, fallback) {
136
+ if (error instanceof RequestError) return error
137
+ const code = error?.code ?? error?.rpcError?.code
138
+ if (code === 'schedule/target-archived') return new RequestError('目标会话已归档,请先恢复会话后再执行。', 409)
139
+ if (code === 'schedule/input-invalid') return new RequestError('定时任务参数无效,请检查后重试。', 400)
140
+ return new RequestError(fallback, 409)
141
+ }
142
+
143
+ export function scheduleOperations(ctx) {
144
+ let tail = Promise.resolve()
145
+
146
+ async function listAll() {
147
+ if (typeof ctx.schedule.catalog === 'function') {
148
+ const entries = await ctx.schedule.catalog()
149
+ return { schedules: entries.map(projectSchedule) }
150
+ }
151
+ const page = await ctx.schedule.list({ limit: 500 })
152
+ return { schedules: (page?.items ?? []).map(projectSchedule) }
153
+ }
154
+
155
+ async function runAction(body, signal) {
156
+ signal?.throwIfAborted()
157
+ if (body.action === 'list') return listAll()
158
+
159
+ if (body.action === 'delete-inactive') {
160
+ requireValue(body.confirm === true, '请确认清理已结束的定时任务。', 409)
161
+ requireValue(typeof ctx.schedule.deleteInactive === 'function', '当前 DSH 版本不支持批量清理已结束任务。', 501)
162
+ const result = await ctx.schedule.deleteInactive()
163
+ return { deleted: result?.deleted ?? 0 }
164
+ }
165
+
166
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
167
+ requireValue(id, '请指定定时任务 ID。')
168
+
169
+ if (body.action === 'history') {
170
+ requireValue(typeof ctx.schedule.history === 'function', '当前 DSH 版本不支持查看投递历史。', 501)
171
+ const result = await ctx.schedule.history({ id, limit: 20 })
172
+ if (result?.code === 'schedule_not_found') throw new RequestError('定时任务不存在,请刷新列表。', 404)
173
+ return {
174
+ id,
175
+ records: (result?.records ?? []).map(rec => ({
176
+ scheduledAt: rec.scheduledAt,
177
+ deliveredAt: rec.deliveredAt,
178
+ targetSessionId: rec.targetSessionId,
179
+ messageId: rec.messageId,
180
+ })),
181
+ earlierRecordsPruned: Boolean(result?.earlierRecordsPruned),
182
+ }
183
+ }
184
+
185
+ if (body.action === 'run') {
186
+ requireValue(typeof ctx.schedule.run === 'function', '当前 DSH 版本不支持手动触发定时任务。', 501)
187
+ let result
188
+ try {
189
+ result = await ctx.schedule.run({ id }, signal)
190
+ } catch (error) {
191
+ throw mapScheduleError(error, '无法立即触发此定时任务。')
192
+ }
193
+ if (result?.code === 'schedule_not_found') throw new RequestError('定时任务不存在,请刷新列表。', 404)
194
+ if (result?.code === 'schedule_execution_pending') throw new RequestError('此定时任务正在执行中或处于触发间隔保护期内,请稍后重试。', 409)
195
+ return { schedule: projectSchedule(result) }
196
+ }
197
+
198
+ if (body.action === 'toggle') {
199
+ requireValue(typeof body.active === 'boolean', '请指定要切换的状态。')
200
+ requireValue(typeof ctx.schedule.edit === 'function', '当前 DSH 版本不支持编辑定时任务状态。', 501)
201
+ let result
202
+ try {
203
+ result = await ctx.schedule.edit({
204
+ id,
205
+ action: 'update',
206
+ patch: { active: body.active },
207
+ ...(body.expectedUpdatedAt !== undefined ? { expectedUpdatedAt: body.expectedUpdatedAt } : {}),
208
+ })
209
+ } catch (error) {
210
+ throw mapScheduleError(error, '无法更新定时任务状态。')
211
+ }
212
+ if (result?.code === 'schedule_not_found') throw new RequestError('定时任务不存在,请刷新列表。', 404)
213
+ if (result?.code === 'schedule_conflict') throw new RequestError('定时任务已变化,请刷新后重试。', 409)
214
+ return { schedule: projectSchedule(result) }
215
+ }
216
+
217
+ if (body.action === 'delete') {
218
+ requireValue(body.confirm === id, '请确认要删除的定时任务。', 409)
219
+ requireValue(typeof ctx.schedule.edit === 'function', '当前 DSH 版本不支持删除定时任务。', 501)
220
+ let result
221
+ try {
222
+ result = await ctx.schedule.edit({
223
+ id,
224
+ action: 'delete',
225
+ ...(body.expectedUpdatedAt !== undefined ? { expectedUpdatedAt: body.expectedUpdatedAt } : {}),
226
+ })
227
+ } catch (error) {
228
+ throw mapScheduleError(error, '无法删除此定时任务。')
229
+ }
230
+ if (result?.code === 'schedule_not_found') throw new RequestError('定时任务不存在,请刷新列表。', 404)
231
+ if (result?.code === 'schedule_conflict') throw new RequestError('定时任务已变化,请刷新后重试。', 409)
232
+ return { id, deleted: true }
233
+ }
234
+
235
+ throw new RequestError('定时任务操作无效。')
236
+ }
237
+
238
+ return (body, signal) => {
239
+ if (body.action === 'list' || body.action === 'history') return runAction(body, signal)
240
+ const pending = tail.then(() => runAction(body, signal))
241
+ tail = pending.catch(() => {})
242
+ return pending
243
+ }
244
+ }
package/locale/en.json CHANGED
@@ -1 +1 @@
1
- {"meta":{"title":"DSH PowerTools","description":"Browse sessions, manage MCP servers and skills, and rewrite drafts in the composer before sending."}}
1
+ {"meta":{"title":"DSH PowerTools","description":"Manage sessions, MCP servers & credentials, skills & instruction files, background jobs & schedules, and rewrite composer drafts with undo."}}
package/locale/zh.json CHANGED
@@ -1 +1 @@
1
- {"meta":{"title":"DSH 工具箱","description":"浏览和归档会话,管理 MCP 与 Skill,在原生输入框中改写草稿并支持撤销。"}}
1
+ {"meta":{"title":"DSH 工具箱","description":"浏览和清理会话,管理 MCP 与凭据、Skill 与指令文件、后台任务与定时调度,并在原生输入框中改写草稿且支持撤销。"}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-powertools",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "DSH PowerTools for sessions, MCP, skills and prompt enhancement",
5
5
  "license": "MIT",
6
6
  "author": "MistRipple",
@@ -52,6 +52,7 @@
52
52
  "immediately": true,
53
53
  "inject": [
54
54
  "@deepseek-ai/dsh-client-ui-conversation",
55
+ "@deepseek-ai/dsh-client-ui-context-menu",
55
56
  "@deepseek-ai/dsh-client-ui-sidebar",
56
57
  "@deepseek-ai/dsh-client-ui-primitives"
57
58
  ]