dsh-offpeak-guard 0.2.0 → 0.3.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.
package/lib/store.js CHANGED
@@ -29,8 +29,20 @@ function normalizeRecord(record) {
29
29
  }
30
30
 
31
31
  function pruned(list, keep = MAX_RECORDS) {
32
- const protectedItems = list.filter((item) => item.status === 'paused' || item.status === 'queued');
33
- const loose = list.filter((item) => item.status !== 'paused' && item.status !== 'queued');
32
+ const protectedItems = list.filter(
33
+ (item) =>
34
+ item.status === 'paused' ||
35
+ item.status === 'queued' ||
36
+ item.status === 'waiting-turn' ||
37
+ item.status === 'waiting-children',
38
+ );
39
+ const loose = list.filter(
40
+ (item) =>
41
+ item.status !== 'paused' &&
42
+ item.status !== 'queued' &&
43
+ item.status !== 'waiting-turn' &&
44
+ item.status !== 'waiting-children',
45
+ );
34
46
  const trimmedLoose = loose.length > keep ? loose.slice(loose.length - keep) : loose;
35
47
  const merged = [...trimmedLoose, ...protectedItems];
36
48
  merged.sort((left, right) => Number(right.at ?? right.createdAt ?? 0) - Number(left.at ?? left.createdAt ?? 0));
@@ -38,7 +50,15 @@ function pruned(list, keep = MAX_RECORDS) {
38
50
  }
39
51
 
40
52
  export function emptyState() {
41
- return { version: STATE_VERSION, interrupted: [], plans: [], meta: { lastPhase: null, lastTick: 0 } };
53
+ return {
54
+ version: STATE_VERSION,
55
+ interrupted: [],
56
+ plans: [],
57
+ exemptSessions: {},
58
+ modelRules: {},
59
+ settings: { pauseMode: null },
60
+ meta: { lastPhase: null, lastTick: 0 },
61
+ };
42
62
  }
43
63
 
44
64
  export function normalizeState(raw) {
@@ -52,7 +72,24 @@ export function normalizeState(raw) {
52
72
  .map(normalizeRecord)
53
73
  .filter((item) => item !== null)
54
74
  .map((item) => ({ ...item, title: normalizeName(item.title, '未命名任务'), status: normalizeName(item.status, 'queued') }));
75
+ const exempt = raw.exemptSessions !== null && typeof raw.exemptSessions === 'object' ? raw.exemptSessions : {};
76
+ state.exemptSessions = {};
77
+ for (const [sessionId, record] of Object.entries(exempt)) {
78
+ state.exemptSessions[sessionId] = {
79
+ title: normalizeName(record?.title, null),
80
+ at: Number.isFinite(Number(record?.at)) ? Number(record.at) : 0,
81
+ };
82
+ }
83
+ const modelRules = raw.modelRules !== null && typeof raw.modelRules === 'object' ? raw.modelRules : {};
84
+ state.modelRules = {};
85
+ for (const [key, value] of Object.entries(modelRules)) {
86
+ if (typeof value === 'boolean') state.modelRules[key] = value;
87
+ }
55
88
  const meta = raw.meta !== null && typeof raw.meta === 'object' ? raw.meta : {};
89
+ const settings = raw.settings !== null && typeof raw.settings === 'object' ? raw.settings : {};
90
+ state.settings = {
91
+ pauseMode: settings.pauseMode === 'finish-turn' || settings.pauseMode === 'pause-now' ? settings.pauseMode : null,
92
+ };
56
93
  state.meta = {
57
94
  lastPhase: meta.lastPhase === 'peak' || meta.lastPhase === 'offpeak' ? meta.lastPhase : null,
58
95
  lastTick: Number.isFinite(Number(meta.lastTick)) ? Number(meta.lastTick) : 0,
package/lib/tools.js CHANGED
@@ -64,16 +64,30 @@ function guardLine(snapshot) {
64
64
  const guard = snapshot.guard;
65
65
  if (!guard.enabled) return '守卫:已关闭';
66
66
  const parts = [];
67
- if (guard.pauseRunningOnPeak) parts.push('峰时暂停运行中任务');
67
+ if (guard.pauseRunningOnPeak) parts.push(snapshot.pauseMode === 'finish-turn' ? '峰时完成当前轮后暂停' : '峰时立即暂停');
68
68
  if (guard.deferNewTurnsOnPeak) parts.push('峰时新任务延后');
69
69
  if (guard.resumeOnOffPeak) parts.push('谷价自动恢复');
70
70
  return `守卫:开启 · ${parts.join(' · ')}`;
71
71
  }
72
72
 
73
+ function exemptLine(snapshot) {
74
+ const count = snapshot.counts.exempt;
75
+ if (count === 0) return '会话豁免:无';
76
+ const lines = [`会话豁免:${count} 个(不参与暂停/恢复)`];
77
+ for (const item of snapshot.exemptSessions.slice(0, 5)) {
78
+ lines.push(` - ${item.title ?? item.sessionId}`);
79
+ }
80
+ return lines.join('\n');
81
+ }
82
+
73
83
  function pauseLine(snapshot) {
74
84
  const count = snapshot.counts.interrupted;
75
- if (count === 0) return '暂停中:无';
76
- const lines = [`暂停中:${count} 个任务(谷价开始后自动恢复)`];
85
+ const waiting = snapshot.counts.waiting ?? 0;
86
+ const parts = [];
87
+ if (count > 0) parts.push(`暂停中:${count} 个任务(谷价开始后自动恢复)`);
88
+ if (waiting > 0) parts.push(`等待中:${waiting} 个(当前轮结束或子代理结束后暂停)`);
89
+ if (parts.length === 0) return '暂停中:无';
90
+ const lines = [parts.join(';')];
77
91
  for (const item of snapshot.interrupted.slice(0, 5)) {
78
92
  const title = item.title === null ? item.sessionId : `${item.title}(${item.sessionId})`;
79
93
  lines.push(` - ${title} · 模型 ${item.model ?? '未知'} · ${formatAt(item.at)}`);
@@ -106,6 +120,7 @@ function statusText(desc, snapshot) {
106
120
  nextLine(desc),
107
121
  modelLine(snapshot),
108
122
  guardLine(snapshot),
123
+ exemptLine(snapshot),
109
124
  pauseLine(snapshot),
110
125
  planLine(snapshot),
111
126
  ].join('\n');
@@ -178,30 +193,46 @@ export function createOffpeakTools(guard) {
178
193
  {
179
194
  name: 'offpeak_guard',
180
195
  description:
181
- '峰谷守卫的手动控制:status 查看完整状态;pause_now 立刻暂停当前所有正在运行的峰谷计价任务(峰时才生效);' +
182
- 'resume_now 立刻恢复被暂停的任务(谷价时才自动恢复,手动可在任何时段强制恢复);run_plans_now 立刻执行排定的错峰规划。' +
183
- '用户明确要求「先停一下 / 现在就恢复」时使用。',
196
+ '峰谷守卫的手动控制:status 查看完整状态;pause_now 立刻按当前策略暂停峰谷计价任务(峰时才生效);' +
197
+ 'resume_now 立刻恢复被暂停的任务(谷价时才自动恢复,手动可在任何时段强制恢复);run_plans_now 立刻执行排定的错峰规划;' +
198
+ 'exempt / unexempt 让某个会话豁免/取消豁免;pauseMode 设置峰时是立即暂停还是完成当前轮后暂停。' +
199
+ '用户明确要求「先停一下 / 现在就恢复 / 这个会话别管」时使用。',
184
200
  parameters: {
185
201
  type: 'object',
186
202
  properties: {
187
203
  action: {
188
204
  type: 'string',
189
- enum: ['status', 'pause_now', 'resume_now', 'run_plans_now'],
205
+ enum: ['status', 'pause_now', 'resume_now', 'run_plans_now', 'exempt', 'unexempt', 'pause_mode'],
190
206
  description: '要执行的操作,默认 status',
191
207
  },
192
- sessionId: { type: 'string', description: 'resume_now 时只恢复这个会话;省略则恢复全部' },
208
+ sessionId: {
209
+ type: 'string',
210
+ description: 'resume_now 时只恢复这个会话;exempt/unexempt 时指定会话(省略用当前会话)',
211
+ },
212
+ mode: {
213
+ type: 'string',
214
+ enum: ['pause-now', 'finish-turn'],
215
+ description: 'pause_mode 时的策略:立即暂停或完成当前轮后暂停',
216
+ },
193
217
  },
194
218
  additionalProperties: false,
195
219
  },
196
220
  output: OUTPUT,
197
- async execute(args) {
221
+ async execute(args, exec) {
198
222
  const action = typeof args?.action === 'string' ? args.action : 'status';
199
223
  if (action === 'pause_now') {
200
- const paused = await guard.pauseNow();
201
- const names = paused.map((item) => item.title ?? item.sessionId).join('、');
224
+ const handled = await guard.pauseNow();
225
+ const paused = handled.filter((item) => item.status === 'paused');
226
+ const waiting = handled.filter((item) => item.status === 'waiting-turn' || item.status === 'waiting-children');
227
+ const names = handled.map((item) => item.title ?? item.sessionId).join('、');
202
228
  return result(
203
- paused.length === 0 ? '当前没有可暂停的任务(可能不在峰时,或任务模型不适用峰谷计价)。' : `已暂停 ${paused.length} 个任务:${names}。谷价开始后会自动恢复。`,
204
- { paused },
229
+ handled.length === 0
230
+ ? '当前没有可暂停的任务(可能不在峰时,或任务模型不适用峰谷计价)。'
231
+ : `已处理 ${handled.length} 个任务:${names}。` +
232
+ (paused.length > 0 ? ` 已暂停 ${paused.length} 个。` : '') +
233
+ (waiting.length > 0 ? ` ${waiting.length} 个等当前轮/子代理结束后暂停。` : '') +
234
+ ' 谷价开始后会自动恢复。',
235
+ { handled },
205
236
  );
206
237
  }
207
238
  if (action === 'resume_now') {
@@ -213,6 +244,21 @@ export function createOffpeakTools(guard) {
213
244
  const executed = await guard.runPlansNow();
214
245
  return result(executed.length === 0 ? '没有待执行的错峰规划。' : `已执行 ${executed.length} 项规划。`, { executed });
215
246
  }
247
+ if (action === 'exempt' || action === 'unexempt') {
248
+ const sessionId =
249
+ typeof args?.sessionId === 'string' && args.sessionId !== '' ? args.sessionId : exec?.agent?.id;
250
+ if (typeof sessionId !== 'string' || sessionId === '') throw new Error('需要 sessionId');
251
+ const resultState = await guard.setExempt(sessionId, action === 'exempt');
252
+ return result(
253
+ action === 'exempt' ? `已豁免会话 ${sessionId},守卫不会再暂停它。` : `已取消会话 ${sessionId} 的豁免。`,
254
+ resultState,
255
+ );
256
+ }
257
+ if (action === 'pause_mode') {
258
+ const mode = args?.mode === 'finish-turn' ? 'finish-turn' : 'pause-now';
259
+ await guard.setPauseMode(mode);
260
+ return result(mode === 'finish-turn' ? '已设置为:完成当前轮后暂停。' : '已设置为:峰时立即暂停。', { mode });
261
+ }
216
262
  const { desc, snapshot } = await guard.status();
217
263
  return result(statusText(desc, snapshot), snapshot);
218
264
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-offpeak-guard",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "DeepSeek peak/off-peak pricing guard for DSH: detects the price window and current model, pauses running tasks at peak, resumes them automatically when off-peak begins, and schedules work for the next off-peak window.",
5
5
  "private": false,
6
6
  "type": "module",