dsh-context-switch 0.0.0-stage → 1.1.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/LICENSE +21 -0
- package/README.md +225 -2
- package/contexts/example/NOW.md +25 -0
- package/contexts/example/RULES.md +8 -0
- package/contexts/example/TODO.md +5 -0
- package/contexts/example/WHEN.md +4 -0
- package/contexts/example/index.md +7 -0
- package/cordis.patch.yml +100 -0
- package/lib/index.js +793 -0
- package/lib/now-card.mjs +407 -0
- package/lib/schedule.mjs +150 -0
- package/lib/switch-count.mjs +50 -0
- package/lib/ui.js +642 -0
- package/package.json +48 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,793 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-context-switch —— 换模型不丢进度(人格不动)
|
|
3
|
+
*
|
|
4
|
+
* **解决的真问题**:换个模型、开个新会话,AI 就不知道「我刚才在干什么」了。
|
|
5
|
+
*
|
|
6
|
+
* 做法:把「正在做 / 未做完 / 已做完 / 上次聊到哪」做成一张进度卡,
|
|
7
|
+
* 跟着上下文走。切过去,模型自己就知道接着干什么。
|
|
8
|
+
*
|
|
9
|
+
* 管什么:NOW(今天)/ TODO(手头的活)/ index(目录)/ RULES(硬约束)/ 进度卡
|
|
10
|
+
* 不管什么:人格(SOUL)。人格由别的机制负责,本插件一个字都不碰。
|
|
11
|
+
*
|
|
12
|
+
* 为什么能"静默":`ctx.systemPrompt.context({ text })` 的 `text` 是函数,
|
|
13
|
+
* 每轮拼 system prompt 时重新求值。切换只是让下次求值读到另一组文件——
|
|
14
|
+
* 不改会话 ID、不弹窗、不清历史。
|
|
15
|
+
*
|
|
16
|
+
* **入口只有一个**:Web 右下角的胶囊按钮。
|
|
17
|
+
* 2026-11-26 砍掉了 AI 工具(context_switch / context_list)和 /context 斜杠命令——
|
|
18
|
+
* 切上下文是「人想切」,不是「模型想切」;三个入口换来的是三套维护成本。
|
|
19
|
+
*
|
|
20
|
+
* ⚠️ 踩过的坑(2026-11-26,镜像实测):
|
|
21
|
+
* - `ctx.set()` 前必须先 `ctx.provide()`,否则整个插件加载失败、实例起不来
|
|
22
|
+
* - inject 里没声明的服务不能 ctx.get(`cannot get property "X" without inject`)
|
|
23
|
+
* - Web 服务键是 `webServer`(驼峰),不是配置树 entry id 的 `webserver`
|
|
24
|
+
* - `ctx.inject([a, b], cb)` 是「全部就绪」语义——写两个名字永远等不齐
|
|
25
|
+
* - `--dump-config` 通过 ≠ 能跑,必须真启动看 stderr
|
|
26
|
+
*/
|
|
27
|
+
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync, copyFileSync } from 'node:fs'
|
|
28
|
+
import { homedir } from 'node:os'
|
|
29
|
+
import { join, isAbsolute, dirname } from 'node:path'
|
|
30
|
+
import { fileURLToPath } from 'node:url'
|
|
31
|
+
import { buildNowCard, parseNow, readLastSessionTail } from './now-card.mjs'
|
|
32
|
+
import { pickBySchedule, listSchedule } from './schedule.mjs'
|
|
33
|
+
import { readSwitchCount, writeSwitchCount } from './switch-count.mjs'
|
|
34
|
+
|
|
35
|
+
export const name = 'dsh-context-switch'
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* inject 声明的服务:没 inject 就去 ctx.get() 会抛
|
|
39
|
+
* `cannot get property "X" without inject`。
|
|
40
|
+
*
|
|
41
|
+
* - systemPrompt:注入上下文块与进度卡
|
|
42
|
+
* - webServer 不在这里:它由 `ctx.inject(['webServer'], …)` 局部等(可选依赖)
|
|
43
|
+
*/
|
|
44
|
+
export const inject = ['systemPrompt']
|
|
45
|
+
|
|
46
|
+
const DEFAULTS = {
|
|
47
|
+
enabled: true,
|
|
48
|
+
contextDir: '~/.dsh/contexts',
|
|
49
|
+
active: '',
|
|
50
|
+
order: -300,
|
|
51
|
+
maxChars: 6000,
|
|
52
|
+
applyToActiveSession: true,
|
|
53
|
+
profilePatch: '',
|
|
54
|
+
/** NOW 卡:往 prompt 里塞一段摘要(只塞正在做 + 未做完前 3 条 + 已做完前 3 条) */
|
|
55
|
+
injectNowCard: true,
|
|
56
|
+
/**
|
|
57
|
+
* 新会话时把「上次会话的结尾」也塞进 prompt。
|
|
58
|
+
* 这是本插件的**核心价值**:换模型/开新会话,AI 自己就知道上次做到哪。
|
|
59
|
+
* 只在会话没有历史时注入一次,之后自动停——不会每轮重复塞。
|
|
60
|
+
*/
|
|
61
|
+
injectTailInFreshSession: true,
|
|
62
|
+
/** 「上个会话的尾巴」取几条消息(面板用全量;prompt 只用最后一进一出) */
|
|
63
|
+
tailMessages: 6,
|
|
64
|
+
/** 尾读会话文件的字节数上限(多帧 zstd,只读尾部几十 KB) */
|
|
65
|
+
sessionTailMaxBytes: 262144,
|
|
66
|
+
/** NOW 卡摘要进 prompt 时的字符上限 */
|
|
67
|
+
nowCardMaxChars: 1200,
|
|
68
|
+
/** 工作目录(用来找会话历史);空 = process.cwd() */
|
|
69
|
+
workspaceCwd: '',
|
|
70
|
+
|
|
71
|
+
// ── 自动挡(第三期)────────────────────────────────────────
|
|
72
|
+
/**
|
|
73
|
+
* 按时间段自动切换。每套上下文目录里放 `WHEN.md` 声明自己的生效时段,
|
|
74
|
+
* 插件每隔 `autoSwitchIntervalMs` 看一眼,到点就换。
|
|
75
|
+
* 关掉它就退回纯手动。
|
|
76
|
+
*/
|
|
77
|
+
autoSwitch: true,
|
|
78
|
+
/** 多久检查一次(毫秒)。默认 60 秒——切换不需要秒级精度。 */
|
|
79
|
+
autoSwitchIntervalMs: 60000,
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 四层上下文,从高优先级到低优先级。
|
|
84
|
+
* 排序即优先级:超预算时从后往前砍。
|
|
85
|
+
* 本插件没有「永不砍」的层——人格不在这里。
|
|
86
|
+
*/
|
|
87
|
+
const LAYERS = [
|
|
88
|
+
{ key: 'NOW', file: 'NOW.md', tag: '现在', required: false },
|
|
89
|
+
{ key: 'TODO', file: 'TODO.md', tag: '手头', required: false },
|
|
90
|
+
{ key: 'INDEX', file: 'index.md', tag: '目录', required: false },
|
|
91
|
+
{ key: 'RULES', file: 'RULES.md', tag: '规则', required: false },
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
/** mtime 缓存:文件没改就不重复读。 */
|
|
95
|
+
const CACHE = new Map()
|
|
96
|
+
|
|
97
|
+
function expandHome(p) {
|
|
98
|
+
const s = String(p || '').trim()
|
|
99
|
+
if (!s) return ''
|
|
100
|
+
if (s === '~') return homedir()
|
|
101
|
+
if (s.startsWith('~/') || s.startsWith('~\\')) return join(homedir(), s.slice(2))
|
|
102
|
+
return isAbsolute(s) ? s : join(process.cwd(), s)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 「换了几轮」的计数(实现搬去 switch-count.mjs,这里只管用) */
|
|
106
|
+
|
|
107
|
+
function readLayer(file) {
|
|
108
|
+
try {
|
|
109
|
+
if (!existsSync(file)) return ''
|
|
110
|
+
const st = statSync(file)
|
|
111
|
+
const hit = CACHE.get(file)
|
|
112
|
+
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.text
|
|
113
|
+
const text = readFileSync(file, 'utf8')
|
|
114
|
+
CACHE.set(file, { text, mtimeMs: st.mtimeMs, size: st.size })
|
|
115
|
+
return text
|
|
116
|
+
} catch {
|
|
117
|
+
return ''
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function resolveConfig(raw) {
|
|
122
|
+
const c = raw && typeof raw === 'object' ? raw : {}
|
|
123
|
+
const num = (v, d) => (Number.isFinite(Number(v)) ? Number(v) : d)
|
|
124
|
+
return {
|
|
125
|
+
enabled: c.enabled === undefined ? DEFAULTS.enabled : Boolean(c.enabled),
|
|
126
|
+
contextDir: expandHome(c.contextDir || DEFAULTS.contextDir),
|
|
127
|
+
active: typeof c.active === 'string' ? c.active.trim() : DEFAULTS.active,
|
|
128
|
+
order: num(c.order, DEFAULTS.order),
|
|
129
|
+
maxChars: Math.max(256, num(c.maxChars, DEFAULTS.maxChars)),
|
|
130
|
+
applyToActiveSession:
|
|
131
|
+
c.applyToActiveSession === undefined ? DEFAULTS.applyToActiveSession : Boolean(c.applyToActiveSession),
|
|
132
|
+
profilePatch: typeof c.profilePatch === 'string' ? expandHome(c.profilePatch) : '',
|
|
133
|
+
injectNowCard: c.injectNowCard === undefined ? DEFAULTS.injectNowCard : Boolean(c.injectNowCard),
|
|
134
|
+
injectTailInFreshSession:
|
|
135
|
+
c.injectTailInFreshSession === undefined
|
|
136
|
+
? DEFAULTS.injectTailInFreshSession
|
|
137
|
+
: Boolean(c.injectTailInFreshSession),
|
|
138
|
+
tailMessages: Math.max(0, num(c.tailMessages, DEFAULTS.tailMessages)),
|
|
139
|
+
sessionTailMaxBytes: Math.max(1024, num(c.sessionTailMaxBytes, DEFAULTS.sessionTailMaxBytes)),
|
|
140
|
+
nowCardMaxChars: Math.max(200, num(c.nowCardMaxChars, DEFAULTS.nowCardMaxChars)),
|
|
141
|
+
workspaceCwd: typeof c.workspaceCwd === 'string' ? expandHome(c.workspaceCwd) : '',
|
|
142
|
+
// 自动挡(第三期)。⚠️ 这里是**显式白名单**——新增配置项必须在这return里
|
|
143
|
+
// 补一行,否则外部传了也读不到,而且不会报错,只是默默用不了(踩过一次)。
|
|
144
|
+
autoSwitch: c.autoSwitch === undefined ? DEFAULTS.autoSwitch : Boolean(c.autoSwitch),
|
|
145
|
+
autoSwitchIntervalMs: Math.max(5000, num(c.autoSwitchIntervalMs, DEFAULTS.autoSwitchIntervalMs)),
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** 列出 contextDir 下所有可用上下文(含四层中任一文件的子目录)。 */
|
|
150
|
+
export function listContexts(contextDir) {
|
|
151
|
+
try {
|
|
152
|
+
if (!existsSync(contextDir)) return []
|
|
153
|
+
return readdirSync(contextDir, { withFileTypes: true })
|
|
154
|
+
.filter((d) => {
|
|
155
|
+
if (!d.isDirectory()) return false
|
|
156
|
+
const dir = join(contextDir, d.name)
|
|
157
|
+
return LAYERS.some((l) => existsSync(join(dir, l.file)))
|
|
158
|
+
})
|
|
159
|
+
.map((d) => d.name)
|
|
160
|
+
.sort()
|
|
161
|
+
} catch {
|
|
162
|
+
return []
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 组装一个上下文块。
|
|
168
|
+
* 超预算从低优先级往外砍(RULES → INDEX → TODO → NOW)。
|
|
169
|
+
* 返回 { text, dropped };一个字都没有时 text 为 ''。
|
|
170
|
+
*/
|
|
171
|
+
export function buildContextBlock(contextDir, contextName, maxChars) {
|
|
172
|
+
const dir = join(contextDir, contextName)
|
|
173
|
+
const layers = []
|
|
174
|
+
for (const layer of LAYERS) {
|
|
175
|
+
const text = readLayer(join(dir, layer.file)).trim()
|
|
176
|
+
if (text) layers.push({ ...layer, text })
|
|
177
|
+
}
|
|
178
|
+
if (!layers.length) return { text: '', dropped: [], empty: true }
|
|
179
|
+
|
|
180
|
+
const dropped = []
|
|
181
|
+
let total = layers.reduce((n, l) => n + l.text.length + 24, 0)
|
|
182
|
+
|
|
183
|
+
for (let i = layers.length - 1; i >= 0 && total > maxChars; i--) {
|
|
184
|
+
total -= layers[i].text.length + 24
|
|
185
|
+
dropped.unshift(layers[i].key)
|
|
186
|
+
layers.splice(i, 1)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (!layers.length) return { text: '', dropped, empty: true }
|
|
190
|
+
|
|
191
|
+
const parts = layers.map((l) => `<!-- ctx:${l.key} -->\n【${l.tag}】\n${l.text}`)
|
|
192
|
+
let header = `【当前上下文:${contextName}】`
|
|
193
|
+
if (dropped.length) header += `(预算不足,已省略:${dropped.join('、')})`
|
|
194
|
+
|
|
195
|
+
return { text: header + '\n\n' + parts.join('\n\n'), dropped, empty: false }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* 手动挡:把 active 写回 profile 的 cordis.patch.yml。
|
|
200
|
+
* 找不到 dsh-context-switch 那一节就硬加一节;改之前先备份。
|
|
201
|
+
*/
|
|
202
|
+
function persistActive(patchPath, nextActive) {
|
|
203
|
+
const text = readFileSync(patchPath, 'utf8')
|
|
204
|
+
const backup = `${patchPath}.bak-before-switch`
|
|
205
|
+
try {
|
|
206
|
+
copyFileSync(patchPath, backup)
|
|
207
|
+
} catch {}
|
|
208
|
+
|
|
209
|
+
const lines = text.split(/\r?\n/)
|
|
210
|
+
const idx = lines.findIndex((l) => /^- id:\s*dsh-context-switch\s*$/.test(l))
|
|
211
|
+
if (idx === -1) {
|
|
212
|
+
const block = ['- id: dsh-context-switch', ' name: dsh-context-switch', ' config:', ` active: ${nextActive}`]
|
|
213
|
+
writeFileSync(patchPath, text.replace(/\s*$/, '\n\n') + block.join('\n') + '\n', 'utf8')
|
|
214
|
+
return { added: true, backup }
|
|
215
|
+
}
|
|
216
|
+
// 找这一节里的 config 块,替换/插入 active
|
|
217
|
+
let cfgIdx = -1
|
|
218
|
+
for (let i = idx + 1; i < lines.length; i++) {
|
|
219
|
+
if (/^- /.test(lines[i])) break
|
|
220
|
+
if (/^\s+config:\s*$/.test(lines[i])) {
|
|
221
|
+
cfgIdx = i
|
|
222
|
+
break
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (cfgIdx === -1) {
|
|
226
|
+
lines.splice(idx + 1, 0, ' config:', ` active: ${nextActive}`)
|
|
227
|
+
} else {
|
|
228
|
+
let activeIdx = -1
|
|
229
|
+
for (let i = cfgIdx + 1; i < lines.length; i++) {
|
|
230
|
+
if (/^- /.test(lines[i]) || /^\s{0,1}\S/.test(lines[i])) break
|
|
231
|
+
if (/^\s+active:/.test(lines[i])) {
|
|
232
|
+
activeIdx = i
|
|
233
|
+
break
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (activeIdx === -1) lines.splice(cfgIdx + 1, 0, ` active: ${nextActive}`)
|
|
237
|
+
else lines[activeIdx] = ` active: ${nextActive}`
|
|
238
|
+
}
|
|
239
|
+
writeFileSync(patchPath, lines.join('\n'), 'utf8')
|
|
240
|
+
return { added: false, backup }
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
245
|
+
*/
|
|
246
|
+
export function apply(ctx, config = {}) {
|
|
247
|
+
const cfg = resolveConfig(config)
|
|
248
|
+
if (!cfg.enabled) return
|
|
249
|
+
if (!ctx?.systemPrompt?.context) {
|
|
250
|
+
ctx?.logger?.warn?.('context-switch: 宿主没有 systemPrompt.context,跳过')
|
|
251
|
+
return
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// 当前激活的上下文;改它就等于切换。
|
|
255
|
+
let active = cfg.active
|
|
256
|
+
/**
|
|
257
|
+
* `active` 这次是谁定的:
|
|
258
|
+
*
|
|
259
|
+
* - `'config'` —— 启动时从 cordis.patch.yml 读进来的
|
|
260
|
+
* - `'auto'` —— 定时器按 WHEN.md 自动切的
|
|
261
|
+
* - `'manual'` —— 你在面板上亲手点的
|
|
262
|
+
*
|
|
263
|
+
* **只有 `manual` 会让自动挡闭嘴。** 手动切开之后,时间表就哑了,
|
|
264
|
+
* 直到你在面板上点「恢复自动」——不然你刚切过去,下一分钟就被切回来,
|
|
265
|
+
* 那种插件是没法用的。
|
|
266
|
+
*/
|
|
267
|
+
let activeSource = 'config'
|
|
268
|
+
/** 换了几轮(手动切换计数,持久化在 contexts/.switch-count.json) */
|
|
269
|
+
let switchCount = readSwitchCount(cfg.contextDir)
|
|
270
|
+
/** 当前会话 id(从 systemPrompt 的 context 里顺手记下来的),用于排除自己 */
|
|
271
|
+
let currentSessionId = ''
|
|
272
|
+
/** 结构探测只打一次,别刷屏 */
|
|
273
|
+
let probedOnce = false
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* 把进度卡压成一小段进 prompt 的文字。
|
|
277
|
+
*
|
|
278
|
+
* 三块内容:
|
|
279
|
+
* 1. 正在做 / 未做完 / 已做完 —— 面板能看全,prompt 里省着给
|
|
280
|
+
* 2. **上次会话的结尾** —— 只在「新会话」时给一次
|
|
281
|
+
*
|
|
282
|
+
* 第 2 块是本插件的意义所在:换个模型、开个新会话,AI 就不记得
|
|
283
|
+
* 「我刚才在干什么」了。把上一场的一进一出递过去,它自己就能接着做。
|
|
284
|
+
*/
|
|
285
|
+
function buildNowSummary(c, name, context) {
|
|
286
|
+
try {
|
|
287
|
+
const card = parseNow(readFileSync(join(c.contextDir, name, 'NOW.md'), 'utf8'))
|
|
288
|
+
const parts = []
|
|
289
|
+
|
|
290
|
+
if (card.doing?.length) parts.push(`**正在做**\n${card.doing.join('\n')}`)
|
|
291
|
+
if (card.todo?.length) {
|
|
292
|
+
const head = card.todo.slice(0, 3).map((x) => `- ${x}`).join('\n')
|
|
293
|
+
const more = card.todo.length > 3 ? `\n…还有 ${card.todo.length - 3} 条` : ''
|
|
294
|
+
parts.push(`**未做完**(${card.todo.length})\n${head}${more}`)
|
|
295
|
+
}
|
|
296
|
+
if (card.done?.length) {
|
|
297
|
+
const head = card.done.slice(0, 3).map((x) => `- ${x}`).join('\n')
|
|
298
|
+
const more = card.done.length > 3 ? `\n…还有 ${card.done.length - 3} 条` : ''
|
|
299
|
+
parts.push(`**已做完**(${card.done.length})\n${head}${more}`)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ── 上次会话的结尾:只在新会话里给一次 ──────────────────
|
|
303
|
+
const isFresh = (context?.agent?.session?.events?.length ?? 0) === 0
|
|
304
|
+
if (c.injectTailInFreshSession && isFresh) {
|
|
305
|
+
const tailText = buildTailSummary(c)
|
|
306
|
+
if (tailText) parts.push(tailText)
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
if (!parts.length) return ''
|
|
310
|
+
let body = `## 当前进度(上下文:${name})\n\n${parts.join('\n\n')}`
|
|
311
|
+
if (body.length > c.nowCardMaxChars) body = body.slice(0, c.nowCardMaxChars) + '\n…(已截断)'
|
|
312
|
+
return body
|
|
313
|
+
} catch {
|
|
314
|
+
return ''
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* 「上次会话的结尾」——只取最后一进一出,压缩成两行。
|
|
320
|
+
*
|
|
321
|
+
* 面板里列 6 条是给人看的;prompt 里只要让模型知道「在聊什么」就够,
|
|
322
|
+
* 全列出来反而挤占上下文窗口。
|
|
323
|
+
*/
|
|
324
|
+
function buildTailSummary(c) {
|
|
325
|
+
try {
|
|
326
|
+
const tail = readLastSessionTail({
|
|
327
|
+
cwd: c.workspaceCwd || process.cwd(),
|
|
328
|
+
limit: c.tailMessages,
|
|
329
|
+
maxBytes: c.sessionTailMaxBytes,
|
|
330
|
+
excludeSessionId: currentSessionId || undefined,
|
|
331
|
+
})
|
|
332
|
+
if (!tail.messages?.length) return ''
|
|
333
|
+
|
|
334
|
+
const lastUser = [...tail.messages].reverse().find((m) => m.role === 'user')
|
|
335
|
+
const lastAssistant = [...tail.messages].reverse().find((m) => m.role === 'assistant')
|
|
336
|
+
if (!lastUser && !lastAssistant) return ''
|
|
337
|
+
|
|
338
|
+
const when = tail.mtime
|
|
339
|
+
? new Date(tail.mtime).toLocaleString('zh-CN', {
|
|
340
|
+
month: '2-digit',
|
|
341
|
+
day: '2-digit',
|
|
342
|
+
hour: '2-digit',
|
|
343
|
+
minute: '2-digit',
|
|
344
|
+
})
|
|
345
|
+
: ''
|
|
346
|
+
const clip = (s, n) => {
|
|
347
|
+
const t = String(s || '').replace(/\s+/g, ' ').trim()
|
|
348
|
+
return t.length > n ? t.slice(0, n) + '…' : t
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const lines = [`**上次会话的结尾**${when ? `(${when})` : ''}`]
|
|
352
|
+
if (lastUser) lines.push(`- 你:${clip(lastUser.text, 120)}`)
|
|
353
|
+
if (lastAssistant) lines.push(`- 我:${clip(lastAssistant.text, 200)}`)
|
|
354
|
+
return lines.join('\n')
|
|
355
|
+
} catch {
|
|
356
|
+
return ''
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function currentBlock(context) {
|
|
361
|
+
if (!active) return ''
|
|
362
|
+
try {
|
|
363
|
+
const r = buildContextBlock(cfg.contextDir, active, cfg.maxChars)
|
|
364
|
+
// 进度卡:正在做 / 未做完 / 已做完,新会话时再补一段「上次会话的结尾」
|
|
365
|
+
const nowText = cfg.injectNowCard ? buildNowSummary(cfg, active, context) : ''
|
|
366
|
+
if (r.empty && !nowText) {
|
|
367
|
+
if (!existsSync(join(cfg.contextDir, active))) {
|
|
368
|
+
ctx.logger?.warn?.(`context-switch: 上下文「${active}」不存在`)
|
|
369
|
+
}
|
|
370
|
+
return ''
|
|
371
|
+
}
|
|
372
|
+
return [r.empty ? '' : r.text, nowText].filter(Boolean).join('\n\n')
|
|
373
|
+
} catch (error) {
|
|
374
|
+
ctx.logger?.warn?.(`context-switch: 组装失败 ${error instanceof Error ? error.message : String(error)}`)
|
|
375
|
+
return ''
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const dispose = ctx.systemPrompt.context({
|
|
380
|
+
name: 'context-switch',
|
|
381
|
+
order: cfg.order,
|
|
382
|
+
text: (context) => {
|
|
383
|
+
try {
|
|
384
|
+
// 顺手记下当前会话 id —— 「上个会话的尾巴」要把它排除掉,
|
|
385
|
+
// 否则读到的就是自己刚才说的话。几种可能的位置都探一遍。
|
|
386
|
+
const sid =
|
|
387
|
+
context?.agent?.session?.id ??
|
|
388
|
+
context?.agent?.sessionId ??
|
|
389
|
+
context?.agent?.id ??
|
|
390
|
+
context?.session?.id ??
|
|
391
|
+
context?.sessionId
|
|
392
|
+
if (typeof sid === 'string' && sid) currentSessionId = sid
|
|
393
|
+
if (!currentSessionId && !probedOnce) {
|
|
394
|
+
probedOnce = true
|
|
395
|
+
try {
|
|
396
|
+
const desc = (o, d = 0) =>
|
|
397
|
+
d > 2 || !o
|
|
398
|
+
? typeof o
|
|
399
|
+
: `{${Object.keys(o).slice(0, 10).join(',')}}`
|
|
400
|
+
console.log(
|
|
401
|
+
`[ctx-switch] 探 context:${desc(context)} agent=${desc(context?.agent)} session=${desc(context?.agent?.session)}`,
|
|
402
|
+
)
|
|
403
|
+
} catch {}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
if (!cfg.applyToActiveSession) {
|
|
407
|
+
const agent = context?.agent
|
|
408
|
+
const hasHistory = agent?.session?.events?.length > 0
|
|
409
|
+
if (hasHistory) return ''
|
|
410
|
+
}
|
|
411
|
+
return currentBlock(context)
|
|
412
|
+
} catch {
|
|
413
|
+
return ''
|
|
414
|
+
}
|
|
415
|
+
},
|
|
416
|
+
})
|
|
417
|
+
|
|
418
|
+
// 注:不再在这里单独注册 `ctx.on('dispose')`。
|
|
419
|
+
// `apply()` 返回的 cleanup(见文件末尾)已经包了 dispose + 定时器两件事,
|
|
420
|
+
// cordis 会调用返回值;两处都注册会让 dispose 被调两次。
|
|
421
|
+
|
|
422
|
+
// ── 运行时切换服务 ──────────────────────────────────────────
|
|
423
|
+
// ⚠️ 先 provide 再 set,否则 cordis 抛 "cannot set property ... without provide"
|
|
424
|
+
try {
|
|
425
|
+
ctx.provide?.('contextSwitch')
|
|
426
|
+
ctx.set('contextSwitch', {
|
|
427
|
+
list: () => listContexts(cfg.contextDir),
|
|
428
|
+
get: () => active,
|
|
429
|
+
/** 切到某套上下文。persist=true 时同时写回 profile 配置(手动挡)。 */
|
|
430
|
+
set: (next, opts = {}) => {
|
|
431
|
+
const wanted = String(next || '').trim()
|
|
432
|
+
if (wanted && !listContexts(cfg.contextDir).includes(wanted)) {
|
|
433
|
+
throw new Error(`上下文「${wanted}」不存在。可用的:${listContexts(cfg.contextDir).join('、') || '(无)'}`)
|
|
434
|
+
}
|
|
435
|
+
const prev = active
|
|
436
|
+
active = wanted
|
|
437
|
+
let persisted = null
|
|
438
|
+
if (opts.persist) {
|
|
439
|
+
if (!cfg.profilePatch) {
|
|
440
|
+
active = prev
|
|
441
|
+
throw new Error('没有配置 profilePatch,无法持久化;请先在 cordis.patch.yml 里设 profilePatch')
|
|
442
|
+
}
|
|
443
|
+
if (!existsSync(cfg.profilePatch)) {
|
|
444
|
+
active = prev
|
|
445
|
+
throw new Error(`profilePatch 指向的文件不存在:${cfg.profilePatch}`)
|
|
446
|
+
}
|
|
447
|
+
try {
|
|
448
|
+
persisted = persistActive(cfg.profilePatch, wanted)
|
|
449
|
+
} catch (e) {
|
|
450
|
+
active = prev
|
|
451
|
+
throw new Error(`写回配置失败:${e instanceof Error ? e.message : String(e)}`)
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return { active, prev, persisted }
|
|
455
|
+
},
|
|
456
|
+
})
|
|
457
|
+
} catch (error) {
|
|
458
|
+
ctx.logger?.warn?.(`context-switch: 注册切换服务失败 ${error instanceof Error ? error.message : String(error)}`)
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// ── 唯一入口:Web 右下角胶囊按钮 ────────────────────────────
|
|
462
|
+
// 之前有过 AI 工具(context_switch / context_list)和 /context 斜杠命令,
|
|
463
|
+
// 2026-11-26 全砍了:切上下文是「人想切」,不是「模型想切」。
|
|
464
|
+
// 三个入口 = 三套错误处理 + 三套测试,换不来价值。
|
|
465
|
+
//
|
|
466
|
+
// DSH 的 Web 端没有正式的客户端插件 API,只有三个口子:
|
|
467
|
+
// `webServer.register` —— 注册 HTTP 端点
|
|
468
|
+
// `webServer.tapIndex` —— 往 renderIndex 出来的 HTML 上套 raw 转换
|
|
469
|
+
// `webserver/index-inject` —— 结构化注入行,renderIndex 的一等公民
|
|
470
|
+
// 所以这里走「注入一段自包含 JS」的路子,两条注入道都上(见下面第 4 步)。
|
|
471
|
+
// ⚠️ 2026-11-27 实测:Web 端 tapIndex 是通的(镜像 index.html 里能看到 <script>)。
|
|
472
|
+
// 但 Electron / 静态 dist 的渲染路径不可靠,只押一条迟早出事。
|
|
473
|
+
//
|
|
474
|
+
// ⚠️ 服务名是 `webServer`(驼峰)。配置树里的 entry id 叫 `webserver`,但**服务键**是
|
|
475
|
+
// 驼峰那个——读错了会抛 `cannot get property "webserver" without inject`。
|
|
476
|
+
// 而 `ctx.inject([a, b], cb)` 是「全部就绪」语义,写两个名字会永远等不齐,所以只写一个。
|
|
477
|
+
try {
|
|
478
|
+
ctx.inject?.(['webServer'], (webCtx) => {
|
|
479
|
+
let ws = null
|
|
480
|
+
try {
|
|
481
|
+
ws = webCtx.webServer
|
|
482
|
+
} catch (e) {
|
|
483
|
+
console.error(`[ctx-switch] 取 webServer 抛错: ${e instanceof Error ? e.message : String(e)}`)
|
|
484
|
+
}
|
|
485
|
+
if (!ws) {
|
|
486
|
+
console.error('[ctx-switch] 拿不到 webServer 实例,UI 跳过')
|
|
487
|
+
return
|
|
488
|
+
}
|
|
489
|
+
try {
|
|
490
|
+
// 成功信息走 stdout:stderr 留给真错误,否则「stderr 必须为空」的健康检查会误判
|
|
491
|
+
console.log(`[ctx-switch] webServer 就绪:register=${typeof ws.register} tapIndex=${typeof ws.tapIndex}`)
|
|
492
|
+
} catch {}
|
|
493
|
+
|
|
494
|
+
const disposers = []
|
|
495
|
+
const UI_PATH = join(dirname(fileURLToPath(import.meta.url)), 'ui.js')
|
|
496
|
+
/** 页面脚本的地址,两端(结构化注入 / raw tap)共用同一个,改一处就够 */
|
|
497
|
+
const UI_SRC = '/dsh-context-switch/ui.js'
|
|
498
|
+
|
|
499
|
+
// 1) 客户端脚本
|
|
500
|
+
disposers.push(
|
|
501
|
+
ws.register({
|
|
502
|
+
kind: 'exact',
|
|
503
|
+
path: '/dsh-context-switch/ui.js',
|
|
504
|
+
handler: (_req, res) => {
|
|
505
|
+
try {
|
|
506
|
+
res.writeHead(200, {
|
|
507
|
+
'content-type': 'application/javascript; charset=utf-8',
|
|
508
|
+
'cache-control': 'no-store',
|
|
509
|
+
})
|
|
510
|
+
res.end(readFileSync(UI_PATH))
|
|
511
|
+
} catch (e) {
|
|
512
|
+
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
|
|
513
|
+
res.end(`ui.js 读不到:${e instanceof Error ? e.message : String(e)}`)
|
|
514
|
+
}
|
|
515
|
+
},
|
|
516
|
+
}),
|
|
517
|
+
)
|
|
518
|
+
|
|
519
|
+
// 2) 状态查询
|
|
520
|
+
disposers.push(
|
|
521
|
+
ws.register({
|
|
522
|
+
kind: 'exact',
|
|
523
|
+
path: '/dsh-context-switch/api/state',
|
|
524
|
+
handler: (_req, res) => {
|
|
525
|
+
try {
|
|
526
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
527
|
+
res.end(
|
|
528
|
+
JSON.stringify({
|
|
529
|
+
active: active || '',
|
|
530
|
+
available: listContexts(cfg.contextDir),
|
|
531
|
+
contextDir: cfg.contextDir,
|
|
532
|
+
canPersist: Boolean(cfg.profilePatch),
|
|
533
|
+
// 这颗胶囊现在归谁管:config(启动时读的)/ auto(时间表)/
|
|
534
|
+
// manual(你点的)——面板据此显示「自动」「手动」小标
|
|
535
|
+
source: activeSource,
|
|
536
|
+
// 换了几轮(手动切换计数,面板里显示「已换 N 轮」)
|
|
537
|
+
switchCount,
|
|
538
|
+
// 每套上下文声明的时段,给面板显示用(没有 WHEN.md 的 slots 为空)
|
|
539
|
+
schedule: listSchedule(cfg.contextDir),
|
|
540
|
+
autoSwitch: cfg.autoSwitch,
|
|
541
|
+
}),
|
|
542
|
+
)
|
|
543
|
+
} catch (e) {
|
|
544
|
+
res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
|
|
545
|
+
res.end(JSON.stringify({ error: String(e instanceof Error ? e.message : e) }))
|
|
546
|
+
}
|
|
547
|
+
},
|
|
548
|
+
}),
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
// 3) NOW 卡(正在做 / 未做完 / 已做完 / 上个会话的尾巴)
|
|
552
|
+
disposers.push(
|
|
553
|
+
ws.register({
|
|
554
|
+
kind: 'exact',
|
|
555
|
+
path: '/dsh-context-switch/api/now',
|
|
556
|
+
handler: (req, res) => {
|
|
557
|
+
try {
|
|
558
|
+
const card = buildNowCard({
|
|
559
|
+
contextDir: cfg.contextDir,
|
|
560
|
+
active,
|
|
561
|
+
// 工作目录:配置里能指定;不指定就用进程 cwd(DSH 正常就是这个工作区)
|
|
562
|
+
cwd: cfg.workspaceCwd || process.cwd(),
|
|
563
|
+
tailMessages: cfg.tailMessages,
|
|
564
|
+
sessionTailMaxBytes: cfg.sessionTailMaxBytes,
|
|
565
|
+
// 排除当前会话,否则「尾巴」读到的是自己刚说的话
|
|
566
|
+
excludeSessionId: currentSessionId || undefined,
|
|
567
|
+
})
|
|
568
|
+
res.writeHead(200, {
|
|
569
|
+
'content-type': 'application/json; charset=utf-8',
|
|
570
|
+
'cache-control': 'no-store',
|
|
571
|
+
})
|
|
572
|
+
res.end(JSON.stringify(card))
|
|
573
|
+
} catch (e) {
|
|
574
|
+
// 降级:任何失败都返回空卡,不 5xx
|
|
575
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
576
|
+
res.end(
|
|
577
|
+
JSON.stringify({
|
|
578
|
+
active: active || null,
|
|
579
|
+
now: null,
|
|
580
|
+
tail: { messages: [], sessionId: null, mtime: null, error: e instanceof Error ? e.message : String(e) },
|
|
581
|
+
}),
|
|
582
|
+
)
|
|
583
|
+
}
|
|
584
|
+
},
|
|
585
|
+
}),
|
|
586
|
+
)
|
|
587
|
+
|
|
588
|
+
// 4) 切换
|
|
589
|
+
disposers.push(
|
|
590
|
+
ws.register({
|
|
591
|
+
kind: 'exact',
|
|
592
|
+
path: '/dsh-context-switch/api/switch',
|
|
593
|
+
handler: (req, res) => {
|
|
594
|
+
let body = ''
|
|
595
|
+
req.on('data', (chunk) => {
|
|
596
|
+
body += chunk
|
|
597
|
+
if (body.length > 8192) req.destroy()
|
|
598
|
+
})
|
|
599
|
+
req.on('end', () => {
|
|
600
|
+
try {
|
|
601
|
+
const args = body ? JSON.parse(body) : {}
|
|
602
|
+
const wanted = String(args.name ?? '').trim()
|
|
603
|
+
const persist = Boolean(args.persist)
|
|
604
|
+
const wantAuto = Boolean(args.auto)
|
|
605
|
+
const available = listContexts(cfg.contextDir)
|
|
606
|
+
|
|
607
|
+
// ── 恢复自动:把方向盘交还给时间表 ──────────────
|
|
608
|
+
if (wantAuto) {
|
|
609
|
+
activeSource = 'auto'
|
|
610
|
+
autoTick() // 立刻按「现在几点」判一次,不等下个 tick
|
|
611
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
612
|
+
res.end(
|
|
613
|
+
JSON.stringify({
|
|
614
|
+
active: active || '',
|
|
615
|
+
source: activeSource,
|
|
616
|
+
restored: true,
|
|
617
|
+
// 没命中时段时 active 可能没变,前端照实显示就行
|
|
618
|
+
matched: Boolean(
|
|
619
|
+
pickBySchedule(cfg.contextDir).matched,
|
|
620
|
+
),
|
|
621
|
+
}),
|
|
622
|
+
)
|
|
623
|
+
return
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
if (wanted && !available.includes(wanted)) {
|
|
627
|
+
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
628
|
+
res.end(JSON.stringify({ error: `没有「${wanted}」这套。可用:${available.join('、') || '(无)'}` }))
|
|
629
|
+
return
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const prev = active
|
|
633
|
+
active = wanted
|
|
634
|
+
// 你亲手点的 → 自动挡从这一刻起闭嘴(直到点「恢复自动」)
|
|
635
|
+
activeSource = 'manual'
|
|
636
|
+
// 数一数换了几轮:只记真换了套的(点同一套不重复计数)
|
|
637
|
+
if (wanted !== prev) {
|
|
638
|
+
switchCount += 1
|
|
639
|
+
writeSwitchCount(cfg.contextDir, switchCount)
|
|
640
|
+
}
|
|
641
|
+
let persisted = null
|
|
642
|
+
if (persist && wanted) {
|
|
643
|
+
if (!cfg.profilePatch || !existsSync(cfg.profilePatch)) {
|
|
644
|
+
active = prev
|
|
645
|
+
activeSource = 'auto'
|
|
646
|
+
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
647
|
+
res.end(JSON.stringify({ error: '没有可写的配置文件(profilePatch 未设置或不存在)' }))
|
|
648
|
+
return
|
|
649
|
+
}
|
|
650
|
+
try {
|
|
651
|
+
persisted = persistActive(cfg.profilePatch, wanted)
|
|
652
|
+
} catch (e) {
|
|
653
|
+
active = prev
|
|
654
|
+
activeSource = 'auto'
|
|
655
|
+
res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
|
|
656
|
+
res.end(JSON.stringify({ error: `写回失败:${e instanceof Error ? e.message : String(e)}` }))
|
|
657
|
+
return
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
662
|
+
res.end(
|
|
663
|
+
JSON.stringify({
|
|
664
|
+
active: active || '',
|
|
665
|
+
prev: prev || '',
|
|
666
|
+
available,
|
|
667
|
+
source: activeSource,
|
|
668
|
+
persisted: persisted ? { backup: persisted.backup, added: persisted.added } : null,
|
|
669
|
+
}),
|
|
670
|
+
)
|
|
671
|
+
} catch (e) {
|
|
672
|
+
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
673
|
+
res.end(JSON.stringify({ error: `请求无效:${e instanceof Error ? e.message : String(e)}` }))
|
|
674
|
+
}
|
|
675
|
+
})
|
|
676
|
+
},
|
|
677
|
+
}),
|
|
678
|
+
)
|
|
679
|
+
|
|
680
|
+
// 4) 把脚本塞进首页 —— 两条路都上
|
|
681
|
+
//
|
|
682
|
+
// 4a) 结构化注入(首选)。`webserver/index-inject` 是 DSH 的一等入口:
|
|
683
|
+
// `renderIndex()` 先把订阅方推的行渲染进 index.html,再套 raw tap。
|
|
684
|
+
// raw tap 在 Electron / 静态 dist 这类路径上会瘸,扛不住。
|
|
685
|
+
try {
|
|
686
|
+
disposers.push(
|
|
687
|
+
webCtx.on('webserver/index-inject', (table) => {
|
|
688
|
+
if (!Array.isArray(table)) return
|
|
689
|
+
// 别和别的订阅方或 raw tap 撞车
|
|
690
|
+
if (table.some((r) => r && r.src === UI_SRC)) return
|
|
691
|
+
table.push({ kind: 'script-src', placement: 'body', src: UI_SRC })
|
|
692
|
+
}),
|
|
693
|
+
)
|
|
694
|
+
} catch (e) {
|
|
695
|
+
webCtx.logger?.warn?.(`context-switch: index-inject 订阅失败 ${e instanceof Error ? e.message : String(e)}`)
|
|
696
|
+
}
|
|
697
|
+
//
|
|
698
|
+
// 4b) raw tap(兜底)。万一某条渲染路径没走注入表,这层还能补上。
|
|
699
|
+
// 两道都通也无妨 —— ui.js 自带 `window.__dshContextSwitchMounted` 锁,
|
|
700
|
+
// 只会挂一次,不会出现两个按钮。
|
|
701
|
+
try {
|
|
702
|
+
disposers.push(
|
|
703
|
+
ws.tapIndex((html) => {
|
|
704
|
+
if (String(html).includes(UI_SRC)) return html
|
|
705
|
+
const tag = `<script defer src="${UI_SRC}"></script>`
|
|
706
|
+
if (String(html).includes('</body>')) return String(html).replace('</body>', tag + '</body>')
|
|
707
|
+
return html + tag
|
|
708
|
+
}),
|
|
709
|
+
)
|
|
710
|
+
} catch (e) {
|
|
711
|
+
webCtx.logger?.warn?.(`context-switch: tapIndex 不可用 ${e instanceof Error ? e.message : String(e)}`)
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
webCtx.effect?.(() => {
|
|
715
|
+
return () => {
|
|
716
|
+
for (const d of disposers) {
|
|
717
|
+
try {
|
|
718
|
+
d?.()
|
|
719
|
+
} catch {}
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
})
|
|
723
|
+
ctx.logger?.info?.('context-switch: UI 已注册(脚本 + API 端点就绪),按钮由页面脚本挂载')
|
|
724
|
+
})
|
|
725
|
+
} catch (error) {
|
|
726
|
+
ctx.logger?.warn?.(`context-switch: 挂载 UI 失败 ${error instanceof Error ? error.message : String(error)}`)
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// ── 自动挡:按 WHEN.md 里的时段,到点自己换 ──────────────────
|
|
730
|
+
// 计时器用 unref() —— 不拖住进程退出。插件热重载时一定要 clearInterval,
|
|
731
|
+
// 否则每次重载都留一个野定时器,越积越多、还会对着旧闭包切上下文。
|
|
732
|
+
let autoTimer = null
|
|
733
|
+
|
|
734
|
+
/** 检查一次:现在该不该换?不该就什么都不做。 */
|
|
735
|
+
function autoTick() {
|
|
736
|
+
// 手动切过 → 时间表闭嘴,直到用户点「恢复自动」
|
|
737
|
+
if (activeSource === 'manual') return
|
|
738
|
+
|
|
739
|
+
const picked = pickBySchedule(cfg.contextDir)
|
|
740
|
+
// 没有任何一套命中时段 → 保持现状。
|
|
741
|
+
// 这一步很要紧:用户可能只给 night 写了时段,那白天就该留在原地,
|
|
742
|
+
// 而不是「没匹配到就随便挑一个」。
|
|
743
|
+
if (!picked.matched || !picked.name) return
|
|
744
|
+
if (picked.name === active) return
|
|
745
|
+
|
|
746
|
+
const prev = active
|
|
747
|
+
active = picked.name
|
|
748
|
+
activeSource = 'auto'
|
|
749
|
+
ctx.logger?.info?.(
|
|
750
|
+
`context-switch: 自动挡 ${prev || '(无)'} → ${active}(时段 ${picked.slot})`,
|
|
751
|
+
)
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
if (cfg.autoSwitch) {
|
|
755
|
+
try {
|
|
756
|
+
autoTick() // 启动时立刻判一次,别等第一个 interval
|
|
757
|
+
const ms = Math.max(5000, Number(cfg.autoSwitchIntervalMs) || 60000)
|
|
758
|
+
autoTimer = setInterval(autoTick, ms)
|
|
759
|
+
// unref:定时器不该让进程无法退出
|
|
760
|
+
if (typeof autoTimer?.unref === 'function') autoTimer.unref()
|
|
761
|
+
} catch (e) {
|
|
762
|
+
ctx.logger?.warn?.(`context-switch: 自动挡启动失败 ${e instanceof Error ? e.message : String(e)}`)
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* 统一的收尾:停定时器 + 交还给 systemPrompt 的 dispose。
|
|
768
|
+
* 两头都得放,漏一个就泄漏。
|
|
769
|
+
*
|
|
770
|
+
* 加 `done` 闸是因为:cordis 调返回值的同时,宿主有时也会自己触发一遍,
|
|
771
|
+
* 重复 dispose 虽然多半无害,但没必要冒这个险。
|
|
772
|
+
*/
|
|
773
|
+
let done = false
|
|
774
|
+
const cleanup = () => {
|
|
775
|
+
if (done) return
|
|
776
|
+
done = true
|
|
777
|
+
if (autoTimer) {
|
|
778
|
+
try {
|
|
779
|
+
clearInterval(autoTimer)
|
|
780
|
+
} catch {}
|
|
781
|
+
autoTimer = null
|
|
782
|
+
}
|
|
783
|
+
try {
|
|
784
|
+
dispose?.()
|
|
785
|
+
} catch {}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
ctx.logger?.info?.(
|
|
789
|
+
`context-switch: 已加载,上下文目录 ${cfg.contextDir},可用 ${listContexts(cfg.contextDir).length} 套,当前 ${active || '(未选,不注入)'}`,
|
|
790
|
+
)
|
|
791
|
+
|
|
792
|
+
return cleanup
|
|
793
|
+
}
|