dsh-session-guard 4.2.9 → 4.2.10

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/CHANGELOG.md CHANGED
@@ -1,4 +1,8 @@
1
- # Changelog
1
+ # Changelog
2
+
3
+ ## 4.2.10
4
+
5
+ - 终端面(dsh-tui / Desktop 命令面板同源):/guard 终端面 + 拉门时向会话追加 plugin 源消息(TUI 一行反馈)。
2
6
 
3
7
  4.2.3: host enumeration addendum for DSH 0.2.1-rc.3 (declaration-only bump; contract plane zero diff).
4
8
 
package/README.md CHANGED
@@ -377,4 +377,15 @@ weekendMode 升级为休息日语义:法定假日(含落在工作日的)
377
377
 
378
378
  ## License
379
379
 
380
- MIT — 见 [LICENSE](LICENSE)。
380
+ MIT — 见 [LICENSE](LICENSE)。
381
+
382
+ ## TUI 终端面(dsh-tui)
383
+
384
+ dsh-tui 不加载插件的 client 半边(面板/卡片/设置页),也调不到插件自有 RPC;工具调用只显示一行摘要。人可读、人可操作的面只剩宿主斜杠命令。输出约定:单行 ≤100 字符、总行 ≤40、无 ANSI、两空格对齐;写操作默认 dry、加 `--yes` 才执行;`--json` 输出单行 JSON。
385
+
386
+ | 命令 | 作用 |
387
+ |---|---|
388
+ | `/guard status` | 门状态与 live state |
389
+ | `/guard pause|resume|cancel` | 包装既有 `/pause` `/resume` `/cancel`;**`/resume` 在 dsh-tui 下被本地命令遮蔽,必须走 `/guard resume`** |
390
+
391
+ 命令由插件自己在宿主侧注册(`ctx.inject(['commands'], …)`):命令服务缺席的老宿主线上不激活、不报错。
package/dsh.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-external/dsh-session-guard",
3
- "version": "4.2.9",
3
+ "version": "4.2.10",
4
4
  "main": "./src/index.js",
5
5
  "description": "高峰自动会话门:step 级门控 + 周末模式 + 高峰自动暂停 + 官方源二维判定 + 会话级冻结 + 后端自动重试。",
6
6
  "engines": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-session-guard",
3
- "version": "4.2.9",
3
+ "version": "4.2.10",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org",
6
6
  "tag": "latest"
package/src/index.js CHANGED
@@ -33,7 +33,7 @@ import { registerSettingsBridgeRoutes } from './settings-bridge.js'
33
33
  export const Config = SettingsSchema
34
34
 
35
35
  export const name = 'session-guard'
36
- export const inject = ['agents', 'webServer', 'timer', 'commands', 'goals']
36
+ export const inject = ['agents', 'webServer', 'timer', 'goals']
37
37
 
38
38
  export { NS, DEFAULT_SETTINGS }
39
39
 
@@ -146,6 +146,8 @@ export function apply(ctx, config = {}) {
146
146
  const pauseStore = createPauseStore()
147
147
  let pauseGateRef = null
148
148
  let wiringRef = null
149
+ /** 已发过 TUI 门控提示的门控键(`sessionId:since:step`),防止同一门控刷屏。 */
150
+ const notifiedHolds = new Set()
149
151
  const stepGate = createStepGate({
150
152
  getSettings: readCfg,
151
153
  shouldHoldSession: (cfg, id) => (wiringRef ? wiringRef.shouldPauseSession(cfg, id) : true),
@@ -154,6 +156,33 @@ export function apply(ctx, config = {}) {
154
156
  pauseGate: { pause: (id, opts) => pauseGateRef.pause(id, opts) },
155
157
  logger: ctx.logger,
156
158
  onChange: (id, snapshot) => broadcastStep(id, snapshot),
159
+ // TUI 可见反馈:dsh-tui 会把 source.kind !== 'user' 的消息折成一行 `· …`,
160
+ // 所以拉门时向会话追加一条 plugin 源 user/message(同一个门控只发一次)。
161
+ // 失败静默:老宿主没有 session.append 时退回只能 `/guard status` 查。
162
+ onHold: (id, agent, info) => {
163
+ try {
164
+ const session = agent && agent.session
165
+ if (!session || typeof session.append !== 'function') return
166
+ const since = Number(info && info.since) || 0
167
+ const key = `${id}:${since}:${info && info.step}`
168
+ if (notifiedHolds.has(key)) return
169
+ notifiedHolds.add(key)
170
+ if (notifiedHolds.size > 200) notifiedHolds.clear()
171
+ const reason = info && info.manual
172
+ ? '手动暂停'
173
+ : (info && info.why === 'peak' ? '高峰拦截' : `门控(${(info && info.why) || 'hold'})`)
174
+ const text = `⏳ session-guard:${reason} — 本回合已在 step 边界挂起`
175
+ + `(step ${(info && info.step) || '?'})。/guard status 查看,/guard resume 继续。`
176
+ session.append('user/message', {
177
+ id: `guard-${(info && info.since) || Date.now()}`,
178
+ role: 'user',
179
+ content: [{ type: 'text', text }],
180
+ source: { kind: 'plugin', name: 'session-guard' },
181
+ }, { surfaceOp: 'append' })
182
+ } catch (e) {
183
+ ctx.logger?.warn?.(`session-guard: tui notice failed: ${String((e && e.message) || e)}`)
184
+ }
185
+ },
157
186
  })
158
187
  const pauseGate = createPauseGate({ ctx, pauseStore, stepGate })
159
188
  pauseGateRef = pauseGate
@@ -194,9 +223,12 @@ export function apply(ctx, config = {}) {
194
223
  ctx.effect(() => () => wiring.dispose(), 'session-guard: wiring dispose')
195
224
 
196
225
  // ── 手动会话门命令(/pause /resume /cancel,全量移植)──
197
- if (typeof ctx.commands?.register === 'function') {
226
+ // 门控:命令注册走 inject(['commands']),不写进顶层 inject——否则缺 commands 服务的
227
+ // 老宿主线会把整个插件挂死(兼容闸见 _tools/tui-audit.mjs)。
228
+ const installSessionGuardCommands = (commandCtx) => {
229
+ if (typeof commandCtx?.commands?.register !== 'function') return
198
230
  const tokensOf = (rawInput) => String(rawInput ?? '').trim().split(/\s+/).filter(Boolean)
199
- ctx.effect(() => ctx.commands.register({
231
+ ctx.effect(() => commandCtx.commands.register({
200
232
  name: 'pause',
201
233
  description: 'pause the running task (safe: defers to the safe boundary; force: interrupts tools and reasoning now; wait: let reasoning finish; bare /pause follows the pause settings)',
202
234
  input: { hint: '[force|safe] [stop|wait]' },
@@ -211,7 +243,7 @@ export function apply(ctx, config = {}) {
211
243
  return pauseGate.pause(sid, opts)
212
244
  },
213
245
  }))
214
- ctx.effect(() => ctx.commands.register({
246
+ ctx.effect(() => commandCtx.commands.register({
215
247
  name: 'resume',
216
248
  description: 'resume the paused task and continue from the pause point (a force-paused task with an interrupted tool needs `confirm`, plus `rerun`/`skip` for the tool)',
217
249
  input: { hint: '[confirm] [rerun|skip]' },
@@ -227,7 +259,7 @@ export function apply(ctx, config = {}) {
227
259
  })
228
260
  },
229
261
  }))
230
- ctx.effect(() => ctx.commands.register({
262
+ ctx.effect(() => commandCtx.commands.register({
231
263
  name: 'cancel',
232
264
  description: 'cancel the running task (stops the current turn immediately, keeps the queue)',
233
265
  handler: (invocation) => {
@@ -237,7 +269,71 @@ export function apply(ctx, config = {}) {
237
269
  return pauseGate.cancel(sid)
238
270
  },
239
271
  }))
272
+
273
+ // ── dsh-tui 终端面:`/guard` ───────────────────────────────────
274
+ // TUI 的 routeSlash 先命中本地命令表,`/resume` 在那里被 dsh-tui 自己的
275
+ // “恢复会话”吃掉 → 宿主的 resume 在 TUI 里永远不可达。`/guard resume` 是
276
+ // 不依赖那个名字的入口;status 则补上“门到底关没关”这一眼。
277
+ ctx.effect(() => commandCtx.commands.register({
278
+ name: 'guard',
279
+ description: 'session guard console: status / pause / resume / cancel (TUI-safe wrapper; /resume is shadowed by dsh-tui local commands)',
280
+ input: { hint: '[status|pause|resume|cancel] [force|safe] [confirm] [rerun|skip]' },
281
+ handler: (invocation) => {
282
+ const sid = String(invocation?.agent?.id ?? '')
283
+ if (!sid) return { kind: 'error', text: 'guard: no session for this command' }
284
+ const tokens = tokensOf(invocation?.rawInput)
285
+ const wantsJson = tokens.includes('--json')
286
+ const sub = String(tokens.shift() ?? 'status').toLowerCase()
287
+ if (sub === 'status') {
288
+ let state = {}
289
+ try { state = bridge.state(sid) ?? {} } catch { state = {} }
290
+ const primitives = Object.entries(state)
291
+ .filter(([, value]) => ['string', 'number', 'boolean'].includes(typeof value))
292
+ .slice(0, 10)
293
+ .map(([key, value]) => `${key}=${String(value)}`)
294
+ const paused = state.paused === true || state.queueLocked === true
295
+ // 契约:单行 <=100(上限),实际取 80 —— 80 列终端下也不横向溢出。
296
+ const clipLine = (text, width = 80) => {
297
+ const value = String(text ?? '').replace(/[\r\n]+/g, ' ').replace(/\s+$/, '')
298
+ return value.length <= width ? value : `${value.slice(0, width - 1)}…`
299
+ }
300
+ const lines = [
301
+ clipLine(`guard — ${paused ? 'paused/locked' : 'open'}`),
302
+ clipLine(` state ${primitives.join(' ') || '(no live state in this host)'}`),
303
+ clipLine(' map /guard resume [confirm] [rerun|skip] · /guard pause [force|safe] · /guard cancel'),
304
+ ]
305
+ if (wantsJson) {
306
+ return {
307
+ kind: 'success',
308
+ text: JSON.stringify({ ok: true, cmd: 'guard', sub: 'status', data: { paused, state: primitives } }),
309
+ }
310
+ }
311
+ return { kind: 'success', text: lines.join('\n') }
312
+ }
313
+ if (sub === 'pause') {
314
+ const opts = {}
315
+ for (const token of tokens) {
316
+ if (token === 'force' || token === 'safe') opts.mode = token
317
+ if (token === 'stop' || token === 'wait') opts.reason = token
318
+ }
319
+ return pauseGate.pause(sid, opts)
320
+ }
321
+ if (sub === 'resume') {
322
+ bridge.stepResume(sid, { bypass: true, reason: 'command' })
323
+ return pauseGate.resume(sid, {
324
+ confirm: tokens.includes('confirm'),
325
+ choice: tokens.includes('skip') ? 'skip' : 'rerun',
326
+ })
327
+ }
328
+ if (sub === 'cancel') {
329
+ bridge.stepResume(sid, { bypass: false, reason: 'command' })
330
+ return pauseGate.cancel(sid)
331
+ }
332
+ return { kind: 'error', text: `guard: unknown subcommand "${sub}"\n next: /guard status` }
333
+ },
334
+ }))
240
335
  }
336
+ ctx.inject?.(['commands'], installSessionGuardCommands)
241
337
 
242
338
  // ── 后端自动重试(D9):冻结/门控期间让路,绝不绕过会话门 ──
243
339
  createRetry({
package/src/step-gate.js CHANGED
@@ -93,6 +93,7 @@ export function decideStepHold({
93
93
  * @param {typeof clearTimeout} [deps.clearTimer]
94
94
  * @param {boolean} [deps.unrefTimers]
95
95
  * @param {(sessionId:string, state:object)=>void} [deps.onChange] 门控状态变化回调(SSE 推送用)
96
+ * @param {(sessionId:string, agent:object, info:object)=>void} [deps.onHold] 真正拉门时的回调(TUI 可见反馈用)
96
97
  */
97
98
  export function createStepGate({
98
99
  getSettings,
@@ -106,6 +107,7 @@ export function createStepGate({
106
107
  clearTimer = clearTimeout,
107
108
  unrefTimers = true,
108
109
  onChange,
110
+ onHold,
109
111
  } = {}) {
110
112
  /** sessionId -> { sessionId, step, turn, since, resolve, timer, signal, onAbort } */
111
113
  const holds = new Map()
@@ -349,6 +351,16 @@ export function createStepGate({
349
351
  holds.set(id, entry)
350
352
  emitChange(id)
351
353
 
354
+ // TUI/终端可见反馈:dsh-tui 把 source.kind !== 'user' 的消息折叠成一行 `· …`,
355
+ // 所以拉门时向会话追加一条 plugin 源 user/message(一次门控只发一次,由 onHold 去重)。
356
+ try {
357
+ if (typeof onHold === 'function') {
358
+ onHold(id, agent, { why: decision.why, step: entry.step, turn: entry.turn, manual, since: entry.since })
359
+ }
360
+ } catch (e) {
361
+ warn(`step gate onHold failed: ${String((e && e.message) || e)}`)
362
+ }
363
+
352
364
  // abort(agent.cancel / 冻结 / /pause / /cancel)→ 释放,让 loop 的 throwIfAborted 收尾
353
365
  if (entry.signal && typeof entry.signal.addEventListener === 'function') {
354
366
  entry.onAbort = () => release(id, 'abort')