dsh-session-guard 0.4.0 → 3.0.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/client.js CHANGED
@@ -1,657 +1,657 @@
1
- window.__ModuleLoader__.load({
2
- id: "dsh-session-guard",
3
- factory: (require) => {
4
- var module = { exports: {} };
5
- var exports = module.exports;
6
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
- let react = require("react");
8
- let react_jsx_runtime = require("react/jsx-runtime");
9
- //#region src/client/badge-text.ts
10
- /** 阶段文案。 */
11
- const PHASE_LABELS = {
12
- peak: "高峰",
13
- "off-peak": "谷时",
14
- weekend: "周末"
15
- };
16
- /** 高峰期的徽标文案:二维判定开启时区分「只拦官方」与「全部暂停」。 */
17
- function peakLabel(status) {
18
- if (status.phase !== "peak") return PHASE_LABELS[status.phase];
19
- return status.providerGuard === true ? "高峰·拦官方" : "高峰·全部暂停";
20
- }
21
- /** 悬浮说明:把判定口径与当前挂起/延后数量写清楚。 */
22
- function badgeTitle(status) {
23
- const base = `${PHASE_LABELS[status.phase]} · ${status.timezone}${status.weekendMode ? " · 周末模式" : ""}`;
24
- if (status.phase !== "peak") return base;
25
- const mode = status.providerGuard === true ? "仅拦截 DeepSeek 官方源" : "全部会话暂停(未启用二维判定)";
26
- const held = status.held ?? 0;
27
- const deferred = status.deferred ?? 0;
28
- const stepHeld = status.stepHeld ?? 0;
29
- return `${base} · ${mode}${held > 0 || deferred > 0 || stepHeld > 0 ? ` · 挂起 ${held} · 延后 ${deferred} · step 挂起 ${stepHeld}` : ""}`;
30
- }
31
- //#endregion
32
- //#region src/client/styles.ts
33
- /**
34
- * dsh-session-guard — 客户端样式(与 composer 右侧 input-traffic 冻结按钮同一视觉语言)。
35
- *
36
- * 为什么注入 `<style>` 而不是 CSS Modules:本插件的 tsdown 配置没有 CSS Modules 管线
37
- * (input-traffic 有),而 settings-card 已经用 `<style data-plugin-css>` 的既有约定。
38
- * 这里只做一件事:把「暂停会话 / 继续会话」按钮与状态徽标对齐到同一行的其它控件
39
- * (高度 24px、圆角 6px、12px 字号、同样的 border / hover / pressed 令牌)。
40
- */
41
- /** 与 `dsh-input-traffic/src/client/freeze-button.module.css` 对齐的控件外观。 */
42
- const CLIENT_CSS = `
43
- .sg-pause{display:inline-flex;align-items:center;gap:4px;height:24px;padding:0 8px;border:1px solid var(--dsw-alias-border-l3,rgba(0,0,0,.12));border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary,#6b7280);font-size:12px;line-height:1;cursor:pointer;white-space:nowrap;flex:none}
44
- .sg-pause:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.04))}
45
- .sg-pause:disabled{opacity:.55;cursor:default}
46
- .sg-pause[aria-pressed='true']{border-color:var(--dsw-alias-state-warning-primary,#d97706);color:var(--dsw-alias-state-warning-primary,#d97706);background:color-mix(in srgb,var(--dsw-alias-state-warning-primary,#d97706) 8%,transparent)}
47
- .sg-status{display:inline-flex;align-items:center;height:24px;padding:0 8px;border:1px solid var(--dsw-alias-border-l3,rgba(0,0,0,.12));border-radius:6px;font-size:12px;line-height:1;color:var(--dsw-alias-label-secondary,#6b7280);white-space:nowrap;flex:none}
48
- .sg-status.sg-peak{border-color:var(--dsw-alias-state-warning-primary,#d97706);color:var(--dsw-alias-state-warning-primary,#d97706)}
49
- .sg-status.sg-weekend{border-color:var(--dsw-alias-state-success-primary,#30a46c);color:var(--dsw-alias-state-success-primary,#30a46c)}
50
- `;
51
- /** 注入一次(幂等;无 document 时静默跳过)。 */
52
- function injectClientCss() {
53
- if (typeof document === "undefined") return;
54
- if (document.querySelector("style[data-plugin-css=\"session-guard-client\"]") !== null) return;
55
- const tag = document.createElement("style");
56
- tag.dataset.plugin = "dsh-session-guard";
57
- tag.dataset.pluginCss = "session-guard-client";
58
- tag.textContent = CLIENT_CSS;
59
- document.head.appendChild(tag);
60
- }
61
- //#endregion
62
- //#region src/client/status-badge.tsx
63
- /**
64
- * dsh-session-guard — 状态徽标(纯展示,fail-open)。
65
- *
66
- * 轮询 host 的 /session-guard/status(全局当前阶段),显示 高峰/谷时/周末;
67
- * 高峰期按二维判定区分「只拦官方」与「全部暂停」(文案见 badge-text.ts)。
68
- * 仅展示,不做任何队列/会话动作;冻结按钮由 input-traffic 经桥接管(D6/D8)。
69
- */
70
- const POLL_MS$1 = 15e3;
71
- /** 状态徽标:轮询全局阶段,显示 高峰/谷时/周末(enabled 关闭或请求失败时静默隐藏)。 */
72
- function StatusBadge({ sessionId }) {
73
- const [status, setStatus] = (0, react.useState)(null);
74
- injectClientCss();
75
- (0, react.useEffect)(() => {
76
- if (!sessionId) return;
77
- let cancelled = false;
78
- const poll = async () => {
79
- try {
80
- const body = await (await fetch("/session-guard/status")).json().catch(() => null);
81
- if (!cancelled && body?.ok && body.status) setStatus(body.status);
82
- } catch {}
83
- };
84
- poll();
85
- const timer = setInterval(poll, POLL_MS$1);
86
- return () => {
87
- cancelled = true;
88
- clearInterval(timer);
89
- };
90
- }, [sessionId]);
91
- if (!status || !status.enabled) return null;
92
- const cls = status.phase === "peak" ? "sg-peak" : status.phase === "weekend" ? "sg-weekend" : "sg-off";
93
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
94
- className: `sg-status ${cls}`,
95
- title: badgeTitle(status),
96
- "data-sg-phase": status.phase,
97
- "data-sg-provider-guard": status.providerGuard === true ? "on" : "off",
98
- "data-sg-step-held": String(status.stepHeld ?? 0),
99
- children: peakLabel(status)
100
- });
101
- }
102
- //#endregion
103
- //#region src/client/settings-card.tsx
104
- /**
105
- * dsh-session-guard — 插件配置卡片(settings.plugin.item 面)。
106
- *
107
- * 对齐 dsh-thinking-levels / dsh-tidychat 的卡片语法:一个可展开的 `<li>`,
108
- * header 按钮(插件名 + 描述 + chevron)切换字段体;开关为 pill switch
109
- * (track + thumb),不是复选框对勾。
110
- *
111
- * 通过 `settingsScope.bind({ namespace: NS })` 绑定 host 已注册的
112
- * `session-guard` 命名空间;每次变更立即经 scope 提交(无 staged form)。
113
- * 仅依赖 react;CSS 经 `<style data-plugin-css>` 注入一次,控件为原生 HTML,
114
- * 客户端 bundle 无 value-import @deepseek-ai/* 平台包(类型导入被构建擦除)。
115
- */
116
- /** 卡片样式,注入一次(保持 bundle CSS-free)。 */
117
- const CARD_CSS = `
118
- .sgCard{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-3);border-radius:12px;list-style:none;transition:border-color .16s,background .16s}
119
- .sgCard:hover{border-color:var(--dsw-alias-label-dimmed)}
120
- .sgCard-open{background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-label-dimmed)}
121
- .sgCardHeader{appearance:none;width:100%;font:inherit;color:inherit;text-align:left;cursor:pointer;background:transparent;border:0;border-radius:12px;align-items:center;gap:12px;padding:14px 16px;display:flex}
122
- .sgCardHeadtext{flex-direction:column;flex:1;gap:4px;min-width:0;display:flex}
123
- .sgCardName{color:var(--dsw-alias-label-primary);font-size:15px;font-weight:600;line-height:1.4}
124
- .sgCardDesc{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.5}
125
- .sgCardChevron{color:var(--dsw-alias-label-tertiary);flex:none;transition:transform .16s}
126
- .sgCardChevron-open{transform:rotate(180deg)}
127
- .sgCardBody{border-top:1px solid var(--dsw-alias-border-l2);margin:0 16px;padding:4px 0 12px}
128
- .sgRow{border-bottom:1px solid var(--dsw-alias-border-l2);align-items:center;gap:8px;padding:16px 0;display:flex}
129
- .sgRow:last-child{border-bottom:0}
130
- .sgRowText{flex-direction:column;flex:1;gap:4px;min-width:0;padding-right:48px;display:flex}
131
- .sgRowText-wide{padding-right:0}
132
- .sgTitle{color:var(--dsw-alias-label-primary);font-size:14px;font-weight:400;line-height:22px}
133
- .sgDesc{color:var(--dsw-alias-label-tertiary);font-size:12px;font-weight:400;line-height:18px}
134
- .sgSwitch{position:relative;width:40px;height:22px;flex:none}
135
- .sgSwitch>input{position:absolute;inset:0;width:100%;height:100%;opacity:0;margin:0;cursor:pointer}
136
- .sgSwitch>input:disabled{cursor:not-allowed}
137
- .sgSwitchTrack{position:absolute;inset:0;border-radius:22px;background:var(--dsw-alias-interactive-bg-hover);transition:background .16s}
138
- .sgSwitch>input:checked+.sgSwitchTrack{background:var(--dsw-alias-button-primary-fill)}
139
- .sgSwitchThumb{position:absolute;top:2px;left:2px;width:18px;height:18px;border-radius:50%;background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.25);transition:transform .16s}
140
- .sgSwitch>input:checked~.sgSwitchThumb{transform:translateX(18px)}
141
- .sgInput{appearance:none;min-width:0;width:100%;font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:7px 10px;margin-top:8px}
142
- .sgInput:disabled{opacity:.6;cursor:not-allowed}
143
- .sgSelect{appearance:none;font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:7px 10px;min-width:160px;flex:none}
144
- .sgSelect:disabled{opacity:.6;cursor:not-allowed}
145
- .sgHint{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px;margin:6px 0 0}
146
- .sgReadonly{color:var(--dsw-alias-label-tertiary);font-size:12px;margin:8px 0 0}
147
- `;
148
- /** 注入一次卡片样式。 */
149
- function injectCss() {
150
- if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=\"session-guard-card\"]") === null) {
151
- const tag = document.createElement("style");
152
- tag.dataset.plugin = "dsh-session-guard";
153
- tag.dataset.pluginCss = "session-guard-card";
154
- tag.textContent = CARD_CSS;
155
- document.head.appendChild(tag);
156
- }
157
- }
158
- /** 一行 pill switch(滑块开关,绑定 scope)。 */
159
- function SwitchRow(props) {
160
- const { label, description, checked, disabled, onChange } = props;
161
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
162
- className: "sgRow",
163
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
164
- className: "sgRowText",
165
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
166
- className: "sgTitle",
167
- children: label
168
- }), description !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
169
- className: "sgDesc",
170
- children: description
171
- })]
172
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
173
- className: "sgSwitch",
174
- children: [
175
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
176
- type: "checkbox",
177
- checked,
178
- disabled,
179
- onChange: (e) => onChange(e.currentTarget.checked)
180
- }),
181
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "sgSwitchTrack" }),
182
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "sgSwitchThumb" })
183
- ]
184
- })]
185
- });
186
- }
187
- /** 一行文本输入(失焦提交;外部值变化时同步草稿)。 */
188
- function TextRow(props) {
189
- const { label, description, value, placeholder, disabled, onCommit } = props;
190
- const [draft, setDraft] = (0, react.useState)(value);
191
- (0, react.useEffect)(() => {
192
- setDraft(value);
193
- }, [value]);
194
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
195
- className: "sgRow",
196
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
197
- className: "sgRowText sgRowText-wide",
198
- children: [
199
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
200
- className: "sgTitle",
201
- children: label
202
- }),
203
- description !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
204
- className: "sgDesc",
205
- children: description
206
- }),
207
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
208
- className: "sgInput",
209
- type: "text",
210
- value: draft,
211
- placeholder,
212
- disabled,
213
- onChange: (e) => setDraft(e.currentTarget.value),
214
- onBlur: () => onCommit(draft)
215
- })
216
- ]
217
- })
218
- });
219
- }
220
- /** 一行「逗号/换行分隔」的字符串列表(失焦提交为数组)。 */
221
- function ListRow(props) {
222
- const { label, description, values, placeholder, disabled, onCommit } = props;
223
- const joined = values.join(", ");
224
- const [draft, setDraft] = (0, react.useState)(joined);
225
- (0, react.useEffect)(() => {
226
- setDraft(joined);
227
- }, [joined]);
228
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
229
- className: "sgRow",
230
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
231
- className: "sgRowText sgRowText-wide",
232
- children: [
233
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
234
- className: "sgTitle",
235
- children: label
236
- }),
237
- description !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
238
- className: "sgDesc",
239
- children: description
240
- }),
241
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
242
- className: "sgInput",
243
- type: "text",
244
- value: draft,
245
- placeholder,
246
- disabled,
247
- onChange: (e) => setDraft(e.currentTarget.value),
248
- onBlur: () => {
249
- const next = draft.split(/[,\n]/).map((s) => s.trim()).filter((s) => s !== "");
250
- onCommit(next);
251
- }
252
- })
253
- ]
254
- })
255
- });
256
- }
257
- /** 一行下拉选择。 */
258
- function SelectRow(props) {
259
- const { label, description, value, options, disabled, onChange } = props;
260
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
261
- className: "sgRow",
262
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
263
- className: "sgRowText",
264
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
265
- className: "sgTitle",
266
- children: label
267
- }), description !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
268
- className: "sgDesc",
269
- children: description
270
- })]
271
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("select", {
272
- className: "sgSelect",
273
- value,
274
- disabled,
275
- onChange: (e) => onChange(e.currentTarget.value),
276
- children: options.map((o) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
277
- value: o.value,
278
- children: o.label
279
- }, o.value))
280
- })]
281
- });
282
- }
283
- /** 插件配置卡片主体:可展开的 <li> + header 按钮 + pill switch 字段体。 */
284
- function SessionGuardCard({ scope }) {
285
- const snapshot = (0, react.useSyncExternalStore)((listener) => scope.subscribe(listener), () => scope.getSnapshot());
286
- const unavailable = snapshot.status === "unavailable";
287
- const readonly = unavailable || !snapshot.writable;
288
- const value = snapshot.value ?? {};
289
- const [open, setOpen] = (0, react.useState)(false);
290
- injectCss();
291
- const toggle = (field, next) => {
292
- scope.set(field, next);
293
- };
294
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("li", {
295
- className: "sgCard" + (open ? " sgCard-open" : ""),
296
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
297
- type: "button",
298
- className: "sgCardHeader",
299
- "aria-expanded": open,
300
- onClick: () => setOpen(!open),
301
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
302
- className: "sgCardHeadtext",
303
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
304
- className: "sgCardName",
305
- children: "会话守护门禁"
306
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
307
- className: "sgCardDesc",
308
- children: "高峰自动暂停运行会话,周末模式无视峰谷畅快跑"
309
- })]
310
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
311
- className: "sgCardChevron" + (open ? " sgCardChevron-open" : ""),
312
- viewBox: "0 0 14 14",
313
- width: 14,
314
- height: 14,
315
- fill: "none",
316
- "aria-hidden": "true",
317
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
318
- d: "M3.5 5.5L7 9l3.5-3.5",
319
- stroke: "currentColor",
320
- strokeWidth: 1.5,
321
- strokeLinecap: "round",
322
- strokeLinejoin: "round"
323
- })
324
- })]
325
- }), open && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
326
- className: "sgCardBody",
327
- children: unavailable ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
328
- style: {
329
- margin: "0",
330
- padding: "12px 0",
331
- fontSize: "13px",
332
- color: "var(--dsw-alias-label-tertiary)"
333
- },
334
- children: "设置命名空间不可用:请确认 dsh-session-guard 已装配进此 profile。"
335
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
336
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
337
- label: "高峰自动暂停冻结会话",
338
- description: "高峰时段自动暂停运行会话",
339
- checked: value.enabled ?? true,
340
- disabled: readonly,
341
- onChange: (next) => toggle("enabled", next)
342
- }),
343
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
344
- label: "step 级门控",
345
- description: "高峰在下一个 step 的模型请求前拉门(省 token 更彻底);关闭则回退为回合级暂停",
346
- checked: value.stepLevelPause ?? true,
347
- disabled: readonly,
348
- onChange: (next) => toggle("stepLevelPause", next)
349
- }),
350
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TextRow, {
351
- label: "step 门控超时(毫秒)",
352
- description: "到期释放 step 门并升级为回合级暂停(防死锁);0 或非法值用默认 300000",
353
- value: String(value.stepGateTimeoutMs ?? 3e5),
354
- placeholder: "300000",
355
- disabled: readonly,
356
- onCommit: (next) => {
357
- const n = Number(String(next).trim());
358
- scope.set("stepGateTimeoutMs", Number.isFinite(n) && n > 0 ? n : 3e5);
359
- }
360
- }),
361
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
362
- label: "官方源二维判定",
363
- description: "高峰期只拦 DeepSeek 官方源;本地/第三方 provider 照常跑",
364
- checked: value.providerGuard ?? true,
365
- disabled: readonly,
366
- onChange: (next) => toggle("providerGuard", next)
367
- }),
368
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ListRow, {
369
- label: "追加官方 provider id",
370
- description: "精确匹配,优先级最高(逗号分隔)",
371
- values: value.officialProviders ?? [],
372
- placeholder: "deepseek-official",
373
- disabled: readonly,
374
- onCommit: (next) => {
375
- scope.set("officialProviders", next);
376
- }
377
- }),
378
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ListRow, {
379
- label: "官方端点名单",
380
- description: "baseURL 归一化后的 host(逗号分隔)",
381
- values: value.officialBaseURLs ?? [],
382
- placeholder: "api.deepseek.com",
383
- disabled: readonly,
384
- onCommit: (next) => {
385
- scope.set("officialBaseURLs", next);
386
- }
387
- }),
388
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SelectRow, {
389
- label: "拦截方式",
390
- description: "挂起等待不报错;或报错并记入延后队列",
391
- value: value.deferredMode ?? "hold",
392
- options: [{
393
- value: "hold",
394
- label: "挂起等待(退峰自动放行)"
395
- }, {
396
- value: "error",
397
- label: "报错并延后(退峰续跑)"
398
- }],
399
- disabled: readonly,
400
- onChange: (next) => {
401
- scope.set("deferredMode", next);
402
- }
403
- }),
404
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
405
- label: "退峰自动继续",
406
- description: "关闭后延后的请求/会话不自动续跑,需手动 /resume",
407
- checked: value.deferredResume ?? true,
408
- disabled: readonly,
409
- onChange: (next) => toggle("deferredResume", next)
410
- }),
411
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TextRow, {
412
- label: "退峰续跑文案",
413
- description: "error 模式退峰时发送的消息内容",
414
- value: value.deferredResumeText ?? "",
415
- placeholder: "继续(高峰已过,自动继续)",
416
- disabled: readonly,
417
- onCommit: (next) => {
418
- scope.set("deferredResumeText", next);
419
- }
420
- }),
421
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
422
- label: "纳入子代理请求",
423
- description: "子代理请求同样计费,默认一并拦截",
424
- checked: value.guardSubagents ?? true,
425
- disabled: readonly,
426
- onChange: (next) => toggle("guardSubagents", next)
427
- }),
428
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
429
- label: "低谷自动恢复",
430
- description: "低峰时段自动恢复被暂停的会话",
431
- checked: value.offPeakAutoResume ?? true,
432
- disabled: readonly,
433
- onChange: (next) => toggle("offPeakAutoResume", next)
434
- }),
435
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
436
- label: "周末模式",
437
- description: "识别周末,无视峰谷畅快跑",
438
- checked: value.weekendMode ?? true,
439
- disabled: readonly,
440
- onChange: (next) => toggle("weekendMode", next)
441
- }),
442
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
443
- label: "回退锁队列",
444
- description: "无会话门时锁等待队列",
445
- checked: value.queueFallback ?? true,
446
- disabled: readonly,
447
- onChange: (next) => toggle("queueFallback", next)
448
- }),
449
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
450
- label: "自动重试",
451
- description: "后端重试,默认关(保守)",
452
- checked: value.retryEnabled ?? false,
453
- disabled: readonly,
454
- onChange: (next) => toggle("retryEnabled", next)
455
- }),
456
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
457
- className: "sgHint",
458
- children: "判定口径:显式 id 名单 → baseURL 端点 → catalog 默认端点 → 内置 id。 排查误判访问 /session-guard/provider?provider=<id> 看 matchedBy。"
459
- }),
460
- !snapshot.writable && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
461
- className: "sgReadonly",
462
- children: "当前只读,无法修改。"
463
- })
464
- ] })
465
- })]
466
- });
467
- }
468
- //#endregion
469
- //#region src/client/pause-button-text.ts
470
- /** 按钮文案。 */
471
- function pauseButtonLabel(state) {
472
- return state.paused === true ? "继续会话" : "暂停会话";
473
- }
474
- /** 悬浮说明:写清当前状态与点击后的语义。 */
475
- function pauseButtonTitle(state) {
476
- if (state.paused !== true) return "暂停会话:在下一次 step 的模型请求前暂停(高峰 + 官方源时会自动暂停)";
477
- const since = typeof state.heldSince === "number" && Number.isFinite(state.heldSince) ? new Date(state.heldSince) : null;
478
- const at = since === null ? null : `${String(since.getHours()).padStart(2, "0")}:${String(since.getMinutes()).padStart(2, "0")}`;
479
- const why = state.manual === true ? "手动暂停" : "高峰自动暂停";
480
- return `${at === null ? `已暂停(${why})` : `已暂停(${why},自 ${at})`} · 点击继续:放行当前 step,且本高峰内不再拦该会话`;
481
- }
482
- /** 把 `/session-guard/state` 的响应体投影为按钮状态(形状异常 → 未暂停,fail-open)。 */
483
- function readPauseState(body) {
484
- const b = body ?? {};
485
- if (b.ok !== true) return {
486
- paused: false,
487
- heldSince: null,
488
- manual: false
489
- };
490
- const manual = b.paused?.manual === true || b.stepGate?.manual === true || b.state?.stepManual === true;
491
- const paused = b.paused?.step === true || b.state?.pausedStep === true || manual;
492
- const raw = b.stepGate?.since ?? b.state?.stepHeldSince ?? null;
493
- return {
494
- paused,
495
- heldSince: typeof raw === "number" && Number.isFinite(raw) ? raw : null,
496
- manual
497
- };
498
- }
499
- /** 把 SSE `/session-guard/events` 的 `state` 快照投影为按钮状态。 */
500
- function readStepSnapshot(snapshot) {
501
- const s = snapshot ?? {};
502
- const manual = s.manual === true;
503
- return {
504
- paused: s.held === true || manual,
505
- heldSince: typeof s.since === "number" && Number.isFinite(s.since) ? s.since : null,
506
- manual
507
- };
508
- }
509
- //#endregion
510
- //#region src/client/pause-button.tsx
511
- /**
512
- * dsh-session-guard — 「暂停会话 / 继续会话」按钮(`conversation.input.right`,order 20)。
513
- *
514
- * 交互(v0.2.0 修订):
515
- * - 未暂停 → 「暂停会话」,**可点**:点击 POST `{action:'stepPause'}`,在**下一次 step 边界**暂停
516
- * (不打断当前 step;step 1 也拦,不受峰谷 / provider 限制);
517
- * - 已暂停(高峰自动拉门 **或** 手动请求已登记)→ 「继续会话」,点击 POST `{action:'stepResume'}`;
518
- * - 状态更新双通道:① SSE `/session-guard/events?session=<id>` 即时推送;② 10s 轮询兜底
519
- * (SSE 不可用 / 断线时仍能收敛)。全部 fail-open,绝不抛错。
520
- *
521
- * 与 input-traffic 的「❄ 冻结追加 / 恢复追加」并列(order 30 在其右侧),互不取代:
522
- * 本按钮控 step 门,冻结按钮控回合级冻结 + 队列摘除。
523
- */
524
- /** SSE 不可用时的兜底轮询间隔(正常路径由事件驱动,几乎不触发)。 */
525
- const POLL_MS = 1e4;
526
- const IDLE = {
527
- paused: false,
528
- heldSince: null,
529
- manual: false
530
- };
531
- /** 暂停 / 继续会话按钮。 */
532
- function PauseButton({ sessionId }) {
533
- const [state, setState] = (0, react.useState)(IDLE);
534
- const [busy, setBusy] = (0, react.useState)(false);
535
- injectClientCss();
536
- (0, react.useEffect)(() => {
537
- if (sessionId === void 0 || sessionId === "") return;
538
- let cancelled = false;
539
- const poll = async () => {
540
- try {
541
- const body = await (await fetch(`/session-guard/state?session=${encodeURIComponent(sessionId)}`)).json().catch(() => null);
542
- if (cancelled) return;
543
- setState(readPauseState(body));
544
- } catch {}
545
- };
546
- poll();
547
- const timer = setInterval(() => {
548
- poll();
549
- }, POLL_MS);
550
- let source;
551
- try {
552
- source = new EventSource(`/session-guard/events?session=${encodeURIComponent(sessionId)}`);
553
- source.onmessage = (ev) => {
554
- try {
555
- const msg = JSON.parse(ev.data);
556
- if (cancelled || msg?.type !== "step") return;
557
- setState(readStepSnapshot(msg.state));
558
- } catch {}
559
- };
560
- source.onerror = () => void 0;
561
- } catch {}
562
- return () => {
563
- cancelled = true;
564
- clearInterval(timer);
565
- try {
566
- source?.close();
567
- } catch {}
568
- };
569
- }, [sessionId]);
570
- if (sessionId === void 0 || sessionId === "") return null;
571
- const paused = state.paused === true;
572
- const onClick = async () => {
573
- if (busy) return;
574
- setBusy(true);
575
- try {
576
- if ((await (await fetch("/session-guard/rpc", {
577
- method: "POST",
578
- headers: { "content-type": "application/json" },
579
- body: JSON.stringify({
580
- sessionId,
581
- action: paused ? "stepResume" : "stepPause"
582
- })
583
- })).json().catch(() => null))?.ok === true) setState(paused ? IDLE : {
584
- paused: true,
585
- heldSince: null,
586
- manual: true
587
- });
588
- } catch {} finally {
589
- setBusy(false);
590
- }
591
- };
592
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
593
- type: "button",
594
- className: "sg-pause",
595
- disabled: busy,
596
- "aria-pressed": paused || void 0,
597
- title: pauseButtonTitle(state),
598
- "data-sg-step-paused": paused ? "on" : "off",
599
- onClick: () => {
600
- onClick();
601
- },
602
- children: pauseButtonLabel(state)
603
- });
604
- }
605
- //#endregion
606
- //#region src/client/index.ts
607
- /**
608
- * dsh-session-guard — 浏览器 half。
609
- *
610
- * 职责(全部 fail-open,D8):
611
- * - 在 composer 输入区右侧注册一个**纯展示**状态徽标(高峰/谷时/周末),轮询
612
- * /session-guard/status;
613
- * - 注册 `settings.plugin.item` 设置卡片,经 `settingsScope.bind({ namespace })`
614
- * 绑定 host 已注册的 `session-guard` 命名空间——这正是“插件配置”面板显示本
615
- * 插件的**必要**机制(对齐 dsh-thinking-levels / dsh-context);
616
- * - **不做**冻结/会话动作——冻结按钮由 input-traffic 接管并经 /session-guard/rpc
617
- * 桥接 host 会话门;本插件客户端不注册任何按钮,避免与 input-traffic 冲突。
618
- *
619
- * 构建:tsdown → lib/client.js(__ModuleLoader__.load 注册,与 input-traffic 同构)。
620
- */
621
- /** 客户端所需服务:slots(状态徽标 + 设置卡片)+ locale + settingsScope(设置卡片绑定)。 */
622
- const inject = [
623
- "slots",
624
- "locale",
625
- "settingsScope"
626
- ];
627
- /** host 侧 src/settings.js 注册的命名空间(保持一致)。 */
628
- const NS = "session-guard";
629
- function apply(ctx) {
630
- ctx.slots.inject("conversation.input.right", () => ctx.slots.register({
631
- name: "conversation.input.right",
632
- id: "session-guard-pause",
633
- order: 20,
634
- locale: "session-guard"
635
- }, PauseButton));
636
- ctx.slots.inject("conversation.input.right", () => ctx.slots.register({
637
- name: "conversation.input.right",
638
- id: "session-guard-status",
639
- order: 40,
640
- locale: "session-guard"
641
- }, StatusBadge));
642
- ctx.slots.inject("settings.plugin.item", () => ctx.slots.register({
643
- name: "settings.plugin.item",
644
- id: NS,
645
- key: NS,
646
- locale: "session-guard",
647
- inject: () => ({ scope: ctx.settingsScope.bind({ namespace: NS }) })
648
- }, SessionGuardCard));
649
- }
650
- //#endregion
651
- exports.apply = apply;
652
- exports.inject = inject;
653
- return module.exports;
654
- }
655
- });
656
-
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-session-guard",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ let react = require("react");
8
+ let react_jsx_runtime = require("react/jsx-runtime");
9
+ //#region src/client/badge-text.ts
10
+ /** 阶段文案。 */
11
+ const PHASE_LABELS = {
12
+ peak: "高峰",
13
+ "off-peak": "谷时",
14
+ weekend: "周末"
15
+ };
16
+ /** 高峰期的徽标文案:二维判定开启时区分「只拦官方」与「全部暂停」。 */
17
+ function peakLabel(status) {
18
+ if (status.phase !== "peak") return PHASE_LABELS[status.phase];
19
+ return status.providerGuard === true ? "高峰·拦官方" : "高峰·全部暂停";
20
+ }
21
+ /** 悬浮说明:把判定口径与当前挂起/延后数量写清楚。 */
22
+ function badgeTitle(status) {
23
+ const base = `${PHASE_LABELS[status.phase]} · ${status.timezone}${status.weekendMode ? " · 周末模式" : ""}`;
24
+ if (status.phase !== "peak") return base;
25
+ const mode = status.providerGuard === true ? "仅拦截 DeepSeek 官方源" : "全部会话暂停(未启用二维判定)";
26
+ const held = status.held ?? 0;
27
+ const deferred = status.deferred ?? 0;
28
+ const stepHeld = status.stepHeld ?? 0;
29
+ return `${base} · ${mode}${held > 0 || deferred > 0 || stepHeld > 0 ? ` · 挂起 ${held} · 延后 ${deferred} · step 挂起 ${stepHeld}` : ""}`;
30
+ }
31
+ //#endregion
32
+ //#region src/client/styles.ts
33
+ /**
34
+ * dsh-session-guard — 客户端样式(与 composer 右侧 input-traffic 冻结按钮同一视觉语言)。
35
+ *
36
+ * 为什么注入 `<style>` 而不是 CSS Modules:本插件的 tsdown 配置没有 CSS Modules 管线
37
+ * (input-traffic 有),而 settings-card 已经用 `<style data-plugin-css>` 的既有约定。
38
+ * 这里只做一件事:把「暂停会话 / 继续会话」按钮与状态徽标对齐到同一行的其它控件
39
+ * (高度 24px、圆角 6px、12px 字号、同样的 border / hover / pressed 令牌)。
40
+ */
41
+ /** 与 `dsh-input-traffic/src/client/freeze-button.module.css` 对齐的控件外观。 */
42
+ const CLIENT_CSS = `
43
+ .sg-pause{display:inline-flex;align-items:center;gap:4px;height:24px;padding:0 8px;border:1px solid var(--dsw-alias-border-l3,rgba(0,0,0,.12));border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary,#6b7280);font-size:12px;line-height:1;cursor:pointer;white-space:nowrap;flex:none}
44
+ .sg-pause:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.04))}
45
+ .sg-pause:disabled{opacity:.55;cursor:default}
46
+ .sg-pause[aria-pressed='true']{border-color:var(--dsw-alias-state-warning-primary,#d97706);color:var(--dsw-alias-state-warning-primary,#d97706);background:color-mix(in srgb,var(--dsw-alias-state-warning-primary,#d97706) 8%,transparent)}
47
+ .sg-status{display:inline-flex;align-items:center;height:24px;padding:0 8px;border:1px solid var(--dsw-alias-border-l3,rgba(0,0,0,.12));border-radius:6px;font-size:12px;line-height:1;color:var(--dsw-alias-label-secondary,#6b7280);white-space:nowrap;flex:none}
48
+ .sg-status.sg-peak{border-color:var(--dsw-alias-state-warning-primary,#d97706);color:var(--dsw-alias-state-warning-primary,#d97706)}
49
+ .sg-status.sg-weekend{border-color:var(--dsw-alias-state-success-primary,#30a46c);color:var(--dsw-alias-state-success-primary,#30a46c)}
50
+ `;
51
+ /** 注入一次(幂等;无 document 时静默跳过)。 */
52
+ function injectClientCss() {
53
+ if (typeof document === "undefined") return;
54
+ if (document.querySelector("style[data-plugin-css=\"session-guard-client\"]") !== null) return;
55
+ const tag = document.createElement("style");
56
+ tag.dataset.plugin = "dsh-session-guard";
57
+ tag.dataset.pluginCss = "session-guard-client";
58
+ tag.textContent = CLIENT_CSS;
59
+ document.head.appendChild(tag);
60
+ }
61
+ //#endregion
62
+ //#region src/client/status-badge.tsx
63
+ /**
64
+ * dsh-session-guard — 状态徽标(纯展示,fail-open)。
65
+ *
66
+ * 轮询 host 的 /session-guard/status(全局当前阶段),显示 高峰/谷时/周末;
67
+ * 高峰期按二维判定区分「只拦官方」与「全部暂停」(文案见 badge-text.ts)。
68
+ * 仅展示,不做任何队列/会话动作;冻结按钮由 input-traffic 经桥接管(D6/D8)。
69
+ */
70
+ const POLL_MS$1 = 15e3;
71
+ /** 状态徽标:轮询全局阶段,显示 高峰/谷时/周末(enabled 关闭或请求失败时静默隐藏)。 */
72
+ function StatusBadge({ sessionId }) {
73
+ const [status, setStatus] = (0, react.useState)(null);
74
+ injectClientCss();
75
+ (0, react.useEffect)(() => {
76
+ if (!sessionId) return;
77
+ let cancelled = false;
78
+ const poll = async () => {
79
+ try {
80
+ const body = await (await fetch("/session-guard/status")).json().catch(() => null);
81
+ if (!cancelled && body?.ok && body.status) setStatus(body.status);
82
+ } catch {}
83
+ };
84
+ poll();
85
+ const timer = setInterval(poll, POLL_MS$1);
86
+ return () => {
87
+ cancelled = true;
88
+ clearInterval(timer);
89
+ };
90
+ }, [sessionId]);
91
+ if (!status || !status.enabled) return null;
92
+ const cls = status.phase === "peak" ? "sg-peak" : status.phase === "weekend" ? "sg-weekend" : "sg-off";
93
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
94
+ className: `sg-status ${cls}`,
95
+ title: badgeTitle(status),
96
+ "data-sg-phase": status.phase,
97
+ "data-sg-provider-guard": status.providerGuard === true ? "on" : "off",
98
+ "data-sg-step-held": String(status.stepHeld ?? 0),
99
+ children: peakLabel(status)
100
+ });
101
+ }
102
+ //#endregion
103
+ //#region src/client/settings-card.tsx
104
+ /**
105
+ * dsh-session-guard — 插件配置卡片(settings.plugin.item 面)。
106
+ *
107
+ * 对齐 dsh-thinking-levels / dsh-tidychat 的卡片语法:一个可展开的 `<li>`,
108
+ * header 按钮(插件名 + 描述 + chevron)切换字段体;开关为 pill switch
109
+ * (track + thumb),不是复选框对勾。
110
+ *
111
+ * 通过 `settingsScope.bind({ namespace: NS })` 绑定 host 已注册的
112
+ * `session-guard` 命名空间;每次变更立即经 scope 提交(无 staged form)。
113
+ * 仅依赖 react;CSS 经 `<style data-plugin-css>` 注入一次,控件为原生 HTML,
114
+ * 客户端 bundle 无 value-import @deepseek-ai/* 平台包(类型导入被构建擦除)。
115
+ */
116
+ /** 卡片样式,注入一次(保持 bundle CSS-free)。 */
117
+ const CARD_CSS = `
118
+ .sgCard{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-3);border-radius:12px;list-style:none;transition:border-color .16s,background .16s}
119
+ .sgCard:hover{border-color:var(--dsw-alias-label-dimmed)}
120
+ .sgCard-open{background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-label-dimmed)}
121
+ .sgCardHeader{appearance:none;width:100%;font:inherit;color:inherit;text-align:left;cursor:pointer;background:transparent;border:0;border-radius:12px;align-items:center;gap:12px;padding:14px 16px;display:flex}
122
+ .sgCardHeadtext{flex-direction:column;flex:1;gap:4px;min-width:0;display:flex}
123
+ .sgCardName{color:var(--dsw-alias-label-primary);font-size:15px;font-weight:600;line-height:1.4}
124
+ .sgCardDesc{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.5}
125
+ .sgCardChevron{color:var(--dsw-alias-label-tertiary);flex:none;transition:transform .16s}
126
+ .sgCardChevron-open{transform:rotate(180deg)}
127
+ .sgCardBody{border-top:1px solid var(--dsw-alias-border-l2);margin:0 16px;padding:4px 0 12px}
128
+ .sgRow{border-bottom:1px solid var(--dsw-alias-border-l2);align-items:center;gap:8px;padding:16px 0;display:flex}
129
+ .sgRow:last-child{border-bottom:0}
130
+ .sgRowText{flex-direction:column;flex:1;gap:4px;min-width:0;padding-right:48px;display:flex}
131
+ .sgRowText-wide{padding-right:0}
132
+ .sgTitle{color:var(--dsw-alias-label-primary);font-size:14px;font-weight:400;line-height:22px}
133
+ .sgDesc{color:var(--dsw-alias-label-tertiary);font-size:12px;font-weight:400;line-height:18px}
134
+ .sgSwitch{position:relative;width:40px;height:22px;flex:none}
135
+ .sgSwitch>input{position:absolute;inset:0;width:100%;height:100%;opacity:0;margin:0;cursor:pointer}
136
+ .sgSwitch>input:disabled{cursor:not-allowed}
137
+ .sgSwitchTrack{position:absolute;inset:0;border-radius:22px;background:var(--dsw-alias-interactive-bg-hover);transition:background .16s}
138
+ .sgSwitch>input:checked+.sgSwitchTrack{background:var(--dsw-alias-button-primary-fill)}
139
+ .sgSwitchThumb{position:absolute;top:2px;left:2px;width:18px;height:18px;border-radius:50%;background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.25);transition:transform .16s}
140
+ .sgSwitch>input:checked~.sgSwitchThumb{transform:translateX(18px)}
141
+ .sgInput{appearance:none;min-width:0;width:100%;font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:7px 10px;margin-top:8px}
142
+ .sgInput:disabled{opacity:.6;cursor:not-allowed}
143
+ .sgSelect{appearance:none;font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:7px 10px;min-width:160px;flex:none}
144
+ .sgSelect:disabled{opacity:.6;cursor:not-allowed}
145
+ .sgHint{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px;margin:6px 0 0}
146
+ .sgReadonly{color:var(--dsw-alias-label-tertiary);font-size:12px;margin:8px 0 0}
147
+ `;
148
+ /** 注入一次卡片样式。 */
149
+ function injectCss() {
150
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=\"session-guard-card\"]") === null) {
151
+ const tag = document.createElement("style");
152
+ tag.dataset.plugin = "dsh-session-guard";
153
+ tag.dataset.pluginCss = "session-guard-card";
154
+ tag.textContent = CARD_CSS;
155
+ document.head.appendChild(tag);
156
+ }
157
+ }
158
+ /** 一行 pill switch(滑块开关,绑定 scope)。 */
159
+ function SwitchRow(props) {
160
+ const { label, description, checked, disabled, onChange } = props;
161
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
162
+ className: "sgRow",
163
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
164
+ className: "sgRowText",
165
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
166
+ className: "sgTitle",
167
+ children: label
168
+ }), description !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
169
+ className: "sgDesc",
170
+ children: description
171
+ })]
172
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
173
+ className: "sgSwitch",
174
+ children: [
175
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
176
+ type: "checkbox",
177
+ checked,
178
+ disabled,
179
+ onChange: (e) => onChange(e.currentTarget.checked)
180
+ }),
181
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "sgSwitchTrack" }),
182
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "sgSwitchThumb" })
183
+ ]
184
+ })]
185
+ });
186
+ }
187
+ /** 一行文本输入(失焦提交;外部值变化时同步草稿)。 */
188
+ function TextRow(props) {
189
+ const { label, description, value, placeholder, disabled, onCommit } = props;
190
+ const [draft, setDraft] = (0, react.useState)(value);
191
+ (0, react.useEffect)(() => {
192
+ setDraft(value);
193
+ }, [value]);
194
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
195
+ className: "sgRow",
196
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
197
+ className: "sgRowText sgRowText-wide",
198
+ children: [
199
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
200
+ className: "sgTitle",
201
+ children: label
202
+ }),
203
+ description !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
204
+ className: "sgDesc",
205
+ children: description
206
+ }),
207
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
208
+ className: "sgInput",
209
+ type: "text",
210
+ value: draft,
211
+ placeholder,
212
+ disabled,
213
+ onChange: (e) => setDraft(e.currentTarget.value),
214
+ onBlur: () => onCommit(draft)
215
+ })
216
+ ]
217
+ })
218
+ });
219
+ }
220
+ /** 一行「逗号/换行分隔」的字符串列表(失焦提交为数组)。 */
221
+ function ListRow(props) {
222
+ const { label, description, values, placeholder, disabled, onCommit } = props;
223
+ const joined = values.join(", ");
224
+ const [draft, setDraft] = (0, react.useState)(joined);
225
+ (0, react.useEffect)(() => {
226
+ setDraft(joined);
227
+ }, [joined]);
228
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
229
+ className: "sgRow",
230
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
231
+ className: "sgRowText sgRowText-wide",
232
+ children: [
233
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
234
+ className: "sgTitle",
235
+ children: label
236
+ }),
237
+ description !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
238
+ className: "sgDesc",
239
+ children: description
240
+ }),
241
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
242
+ className: "sgInput",
243
+ type: "text",
244
+ value: draft,
245
+ placeholder,
246
+ disabled,
247
+ onChange: (e) => setDraft(e.currentTarget.value),
248
+ onBlur: () => {
249
+ const next = draft.split(/[,\n]/).map((s) => s.trim()).filter((s) => s !== "");
250
+ onCommit(next);
251
+ }
252
+ })
253
+ ]
254
+ })
255
+ });
256
+ }
257
+ /** 一行下拉选择。 */
258
+ function SelectRow(props) {
259
+ const { label, description, value, options, disabled, onChange } = props;
260
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
261
+ className: "sgRow",
262
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
263
+ className: "sgRowText",
264
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
265
+ className: "sgTitle",
266
+ children: label
267
+ }), description !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
268
+ className: "sgDesc",
269
+ children: description
270
+ })]
271
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("select", {
272
+ className: "sgSelect",
273
+ value,
274
+ disabled,
275
+ onChange: (e) => onChange(e.currentTarget.value),
276
+ children: options.map((o) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
277
+ value: o.value,
278
+ children: o.label
279
+ }, o.value))
280
+ })]
281
+ });
282
+ }
283
+ /** 插件配置卡片主体:可展开的 <li> + header 按钮 + pill switch 字段体。 */
284
+ function SessionGuardCard({ scope }) {
285
+ const snapshot = (0, react.useSyncExternalStore)((listener) => scope.subscribe(listener), () => scope.getSnapshot());
286
+ const unavailable = snapshot.status === "unavailable";
287
+ const readonly = unavailable || !snapshot.writable;
288
+ const value = snapshot.value ?? {};
289
+ const [open, setOpen] = (0, react.useState)(false);
290
+ injectCss();
291
+ const toggle = (field, next) => {
292
+ scope.set(field, next);
293
+ };
294
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("li", {
295
+ className: "sgCard" + (open ? " sgCard-open" : ""),
296
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
297
+ type: "button",
298
+ className: "sgCardHeader",
299
+ "aria-expanded": open,
300
+ onClick: () => setOpen(!open),
301
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
302
+ className: "sgCardHeadtext",
303
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
304
+ className: "sgCardName",
305
+ children: "会话守护门禁"
306
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
307
+ className: "sgCardDesc",
308
+ children: "高峰自动暂停运行会话,周末模式无视峰谷畅快跑"
309
+ })]
310
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
311
+ className: "sgCardChevron" + (open ? " sgCardChevron-open" : ""),
312
+ viewBox: "0 0 14 14",
313
+ width: 14,
314
+ height: 14,
315
+ fill: "none",
316
+ "aria-hidden": "true",
317
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
318
+ d: "M3.5 5.5L7 9l3.5-3.5",
319
+ stroke: "currentColor",
320
+ strokeWidth: 1.5,
321
+ strokeLinecap: "round",
322
+ strokeLinejoin: "round"
323
+ })
324
+ })]
325
+ }), open && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
326
+ className: "sgCardBody",
327
+ children: unavailable ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
328
+ style: {
329
+ margin: "0",
330
+ padding: "12px 0",
331
+ fontSize: "13px",
332
+ color: "var(--dsw-alias-label-tertiary)"
333
+ },
334
+ children: "设置命名空间不可用:请确认 dsh-session-guard 已装配进此 profile。"
335
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
336
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
337
+ label: "高峰自动暂停冻结会话",
338
+ description: "高峰时段自动暂停运行会话",
339
+ checked: value.enabled ?? true,
340
+ disabled: readonly,
341
+ onChange: (next) => toggle("enabled", next)
342
+ }),
343
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
344
+ label: "step 级门控",
345
+ description: "高峰在下一个 step 的模型请求前拉门(省 token 更彻底);关闭则回退为回合级暂停",
346
+ checked: value.stepLevelPause ?? true,
347
+ disabled: readonly,
348
+ onChange: (next) => toggle("stepLevelPause", next)
349
+ }),
350
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TextRow, {
351
+ label: "step 门控超时(毫秒)",
352
+ description: "到期释放 step 门并升级为回合级暂停(防死锁);0 或非法值用默认 300000",
353
+ value: String(value.stepGateTimeoutMs ?? 3e5),
354
+ placeholder: "300000",
355
+ disabled: readonly,
356
+ onCommit: (next) => {
357
+ const n = Number(String(next).trim());
358
+ scope.set("stepGateTimeoutMs", Number.isFinite(n) && n > 0 ? n : 3e5);
359
+ }
360
+ }),
361
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
362
+ label: "官方源二维判定",
363
+ description: "高峰期只拦 DeepSeek 官方源;本地/第三方 provider 照常跑",
364
+ checked: value.providerGuard ?? true,
365
+ disabled: readonly,
366
+ onChange: (next) => toggle("providerGuard", next)
367
+ }),
368
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ListRow, {
369
+ label: "追加官方 provider id",
370
+ description: "精确匹配,优先级最高(逗号分隔)",
371
+ values: value.officialProviders ?? [],
372
+ placeholder: "deepseek-official",
373
+ disabled: readonly,
374
+ onCommit: (next) => {
375
+ scope.set("officialProviders", next);
376
+ }
377
+ }),
378
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ListRow, {
379
+ label: "官方端点名单",
380
+ description: "baseURL 归一化后的 host(逗号分隔)",
381
+ values: value.officialBaseURLs ?? [],
382
+ placeholder: "api.deepseek.com",
383
+ disabled: readonly,
384
+ onCommit: (next) => {
385
+ scope.set("officialBaseURLs", next);
386
+ }
387
+ }),
388
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SelectRow, {
389
+ label: "拦截方式",
390
+ description: "挂起等待不报错;或报错并记入延后队列",
391
+ value: value.deferredMode ?? "hold",
392
+ options: [{
393
+ value: "hold",
394
+ label: "挂起等待(退峰自动放行)"
395
+ }, {
396
+ value: "error",
397
+ label: "报错并延后(退峰续跑)"
398
+ }],
399
+ disabled: readonly,
400
+ onChange: (next) => {
401
+ scope.set("deferredMode", next);
402
+ }
403
+ }),
404
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
405
+ label: "退峰自动继续",
406
+ description: "关闭后延后的请求/会话不自动续跑,需手动 /resume",
407
+ checked: value.deferredResume ?? true,
408
+ disabled: readonly,
409
+ onChange: (next) => toggle("deferredResume", next)
410
+ }),
411
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TextRow, {
412
+ label: "退峰续跑文案",
413
+ description: "error 模式退峰时发送的消息内容",
414
+ value: value.deferredResumeText ?? "",
415
+ placeholder: "继续(高峰已过,自动继续)",
416
+ disabled: readonly,
417
+ onCommit: (next) => {
418
+ scope.set("deferredResumeText", next);
419
+ }
420
+ }),
421
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
422
+ label: "纳入子代理请求",
423
+ description: "子代理请求同样计费,默认一并拦截",
424
+ checked: value.guardSubagents ?? true,
425
+ disabled: readonly,
426
+ onChange: (next) => toggle("guardSubagents", next)
427
+ }),
428
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
429
+ label: "低谷自动恢复",
430
+ description: "低峰时段自动恢复被暂停的会话",
431
+ checked: value.offPeakAutoResume ?? true,
432
+ disabled: readonly,
433
+ onChange: (next) => toggle("offPeakAutoResume", next)
434
+ }),
435
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
436
+ label: "周末模式",
437
+ description: "识别周末,无视峰谷畅快跑",
438
+ checked: value.weekendMode ?? true,
439
+ disabled: readonly,
440
+ onChange: (next) => toggle("weekendMode", next)
441
+ }),
442
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
443
+ label: "回退锁队列",
444
+ description: "无会话门时锁等待队列",
445
+ checked: value.queueFallback ?? true,
446
+ disabled: readonly,
447
+ onChange: (next) => toggle("queueFallback", next)
448
+ }),
449
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SwitchRow, {
450
+ label: "自动重试",
451
+ description: "后端重试,默认关(保守)",
452
+ checked: value.retryEnabled ?? false,
453
+ disabled: readonly,
454
+ onChange: (next) => toggle("retryEnabled", next)
455
+ }),
456
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
457
+ className: "sgHint",
458
+ children: "判定口径:显式 id 名单 → baseURL 端点 → catalog 默认端点 → 内置 id。 排查误判访问 /session-guard/provider?provider=<id> 看 matchedBy。"
459
+ }),
460
+ !snapshot.writable && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
461
+ className: "sgReadonly",
462
+ children: "当前只读,无法修改。"
463
+ })
464
+ ] })
465
+ })]
466
+ });
467
+ }
468
+ //#endregion
469
+ //#region src/client/pause-button-text.ts
470
+ /** 按钮文案。 */
471
+ function pauseButtonLabel(state) {
472
+ return state.paused === true ? "继续会话" : "暂停会话";
473
+ }
474
+ /** 悬浮说明:写清当前状态与点击后的语义。 */
475
+ function pauseButtonTitle(state) {
476
+ if (state.paused !== true) return "暂停会话:在下一次 step 的模型请求前暂停(高峰 + 官方源时会自动暂停)";
477
+ const since = typeof state.heldSince === "number" && Number.isFinite(state.heldSince) ? new Date(state.heldSince) : null;
478
+ const at = since === null ? null : `${String(since.getHours()).padStart(2, "0")}:${String(since.getMinutes()).padStart(2, "0")}`;
479
+ const why = state.manual === true ? "手动暂停" : "高峰自动暂停";
480
+ return `${at === null ? `已暂停(${why})` : `已暂停(${why},自 ${at})`} · 点击继续:放行当前 step,且本高峰内不再拦该会话`;
481
+ }
482
+ /** 把 `/session-guard/state` 的响应体投影为按钮状态(形状异常 → 未暂停,fail-open)。 */
483
+ function readPauseState(body) {
484
+ const b = body ?? {};
485
+ if (b.ok !== true) return {
486
+ paused: false,
487
+ heldSince: null,
488
+ manual: false
489
+ };
490
+ const manual = b.paused?.manual === true || b.stepGate?.manual === true || b.state?.stepManual === true;
491
+ const paused = b.paused?.step === true || b.state?.pausedStep === true || manual;
492
+ const raw = b.stepGate?.since ?? b.state?.stepHeldSince ?? null;
493
+ return {
494
+ paused,
495
+ heldSince: typeof raw === "number" && Number.isFinite(raw) ? raw : null,
496
+ manual
497
+ };
498
+ }
499
+ /** 把 SSE `/session-guard/events` 的 `state` 快照投影为按钮状态。 */
500
+ function readStepSnapshot(snapshot) {
501
+ const s = snapshot ?? {};
502
+ const manual = s.manual === true;
503
+ return {
504
+ paused: s.held === true || manual,
505
+ heldSince: typeof s.since === "number" && Number.isFinite(s.since) ? s.since : null,
506
+ manual
507
+ };
508
+ }
509
+ //#endregion
510
+ //#region src/client/pause-button.tsx
511
+ /**
512
+ * dsh-session-guard — 「暂停会话 / 继续会话」按钮(`conversation.input.right`,order 20)。
513
+ *
514
+ * 交互(v0.2.0 修订):
515
+ * - 未暂停 → 「暂停会话」,**可点**:点击 POST `{action:'stepPause'}`,在**下一次 step 边界**暂停
516
+ * (不打断当前 step;step 1 也拦,不受峰谷 / provider 限制);
517
+ * - 已暂停(高峰自动拉门 **或** 手动请求已登记)→ 「继续会话」,点击 POST `{action:'stepResume'}`;
518
+ * - 状态更新双通道:① SSE `/session-guard/events?session=<id>` 即时推送;② 10s 轮询兜底
519
+ * (SSE 不可用 / 断线时仍能收敛)。全部 fail-open,绝不抛错。
520
+ *
521
+ * 与 input-traffic 的「❄ 冻结追加 / 恢复追加」并列(order 30 在其右侧),互不取代:
522
+ * 本按钮控 step 门,冻结按钮控回合级冻结 + 队列摘除。
523
+ */
524
+ /** SSE 不可用时的兜底轮询间隔(正常路径由事件驱动,几乎不触发)。 */
525
+ const POLL_MS = 1e4;
526
+ const IDLE = {
527
+ paused: false,
528
+ heldSince: null,
529
+ manual: false
530
+ };
531
+ /** 暂停 / 继续会话按钮。 */
532
+ function PauseButton({ sessionId }) {
533
+ const [state, setState] = (0, react.useState)(IDLE);
534
+ const [busy, setBusy] = (0, react.useState)(false);
535
+ injectClientCss();
536
+ (0, react.useEffect)(() => {
537
+ if (sessionId === void 0 || sessionId === "") return;
538
+ let cancelled = false;
539
+ const poll = async () => {
540
+ try {
541
+ const body = await (await fetch(`/session-guard/state?session=${encodeURIComponent(sessionId)}`)).json().catch(() => null);
542
+ if (cancelled) return;
543
+ setState(readPauseState(body));
544
+ } catch {}
545
+ };
546
+ poll();
547
+ const timer = setInterval(() => {
548
+ poll();
549
+ }, POLL_MS);
550
+ let source;
551
+ try {
552
+ source = new EventSource(`/session-guard/events?session=${encodeURIComponent(sessionId)}`);
553
+ source.onmessage = (ev) => {
554
+ try {
555
+ const msg = JSON.parse(ev.data);
556
+ if (cancelled || msg?.type !== "step") return;
557
+ setState(readStepSnapshot(msg.state));
558
+ } catch {}
559
+ };
560
+ source.onerror = () => void 0;
561
+ } catch {}
562
+ return () => {
563
+ cancelled = true;
564
+ clearInterval(timer);
565
+ try {
566
+ source?.close();
567
+ } catch {}
568
+ };
569
+ }, [sessionId]);
570
+ if (sessionId === void 0 || sessionId === "") return null;
571
+ const paused = state.paused === true;
572
+ const onClick = async () => {
573
+ if (busy) return;
574
+ setBusy(true);
575
+ try {
576
+ if ((await (await fetch("/session-guard/rpc", {
577
+ method: "POST",
578
+ headers: { "content-type": "application/json" },
579
+ body: JSON.stringify({
580
+ sessionId,
581
+ action: paused ? "stepResume" : "stepPause"
582
+ })
583
+ })).json().catch(() => null))?.ok === true) setState(paused ? IDLE : {
584
+ paused: true,
585
+ heldSince: null,
586
+ manual: true
587
+ });
588
+ } catch {} finally {
589
+ setBusy(false);
590
+ }
591
+ };
592
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
593
+ type: "button",
594
+ className: "sg-pause",
595
+ disabled: busy,
596
+ "aria-pressed": paused || void 0,
597
+ title: pauseButtonTitle(state),
598
+ "data-sg-step-paused": paused ? "on" : "off",
599
+ onClick: () => {
600
+ onClick();
601
+ },
602
+ children: pauseButtonLabel(state)
603
+ });
604
+ }
605
+ //#endregion
606
+ //#region src/client/index.ts
607
+ /**
608
+ * dsh-session-guard — 浏览器 half。
609
+ *
610
+ * 职责(全部 fail-open,D8):
611
+ * - 在 composer 输入区右侧注册一个**纯展示**状态徽标(高峰/谷时/周末),轮询
612
+ * /session-guard/status;
613
+ * - 注册 `settings.plugin.item` 设置卡片,经 `settingsScope.bind({ namespace })`
614
+ * 绑定 host 已注册的 `session-guard` 命名空间——这正是“插件配置”面板显示本
615
+ * 插件的**必要**机制(对齐 dsh-thinking-levels / dsh-context);
616
+ * - **不做**冻结/会话动作——冻结按钮由 input-traffic 接管并经 /session-guard/rpc
617
+ * 桥接 host 会话门;本插件客户端不注册任何按钮,避免与 input-traffic 冲突。
618
+ *
619
+ * 构建:tsdown → lib/client.js(__ModuleLoader__.load 注册,与 input-traffic 同构)。
620
+ */
621
+ /** 客户端所需服务:slots(状态徽标 + 设置卡片)+ locale + settingsScope(设置卡片绑定)。 */
622
+ const inject = [
623
+ "slots",
624
+ "locale",
625
+ "settingsScope"
626
+ ];
627
+ /** host 侧 src/settings.js 注册的命名空间(保持一致)。 */
628
+ const NS = "session-guard";
629
+ function apply(ctx) {
630
+ ctx.slots.inject("conversation.input.right", () => ctx.slots.register({
631
+ name: "conversation.input.right",
632
+ id: "session-guard-pause",
633
+ order: 20,
634
+ locale: "session-guard"
635
+ }, PauseButton));
636
+ ctx.slots.inject("conversation.input.right", () => ctx.slots.register({
637
+ name: "conversation.input.right",
638
+ id: "session-guard-status",
639
+ order: 40,
640
+ locale: "session-guard"
641
+ }, StatusBadge));
642
+ ctx.slots.inject("settings.plugin.item", () => ctx.slots.register({
643
+ name: "settings.plugin.item",
644
+ id: NS,
645
+ key: NS,
646
+ locale: "session-guard",
647
+ inject: () => ({ scope: ctx.settingsScope.bind({ namespace: NS }) })
648
+ }, SessionGuardCard));
649
+ }
650
+ //#endregion
651
+ exports.apply = apply;
652
+ exports.inject = inject;
653
+ return module.exports;
654
+ }
655
+ });
656
+
657
657
  //# sourceMappingURL=client.js.map