@michengai/dsh-im-connect 0.1.39 → 0.1.41

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.
Files changed (70) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/CHANGELOG.zh-CN.md +18 -0
  3. package/README.en.md +27 -7
  4. package/README.md +29 -9
  5. package/client.js +168 -100
  6. package/lib/channels/dingtalk.d.ts.map +1 -1
  7. package/lib/channels/dingtalk.js +4 -2
  8. package/lib/channels/dingtalk.js.map +1 -1
  9. package/lib/client.js +168 -100
  10. package/lib/engine/chat-commands.d.ts +30 -0
  11. package/lib/engine/chat-commands.d.ts.map +1 -0
  12. package/lib/engine/chat-commands.js +451 -0
  13. package/lib/engine/chat-commands.js.map +1 -0
  14. package/lib/engine/command-locale.d.ts +6 -0
  15. package/lib/engine/command-locale.d.ts.map +1 -0
  16. package/lib/engine/command-locale.js +21 -0
  17. package/lib/engine/command-locale.js.map +1 -0
  18. package/lib/engine/command-messages.d.ts +214 -0
  19. package/lib/engine/command-messages.d.ts.map +1 -0
  20. package/lib/engine/command-messages.js +214 -0
  21. package/lib/engine/command-messages.js.map +1 -0
  22. package/lib/engine/command-permissions.d.ts +15 -0
  23. package/lib/engine/command-permissions.d.ts.map +1 -0
  24. package/lib/engine/command-permissions.js +39 -0
  25. package/lib/engine/command-permissions.js.map +1 -0
  26. package/lib/engine/command-replies.d.ts +12 -0
  27. package/lib/engine/command-replies.d.ts.map +1 -0
  28. package/lib/engine/command-replies.js +36 -0
  29. package/lib/engine/command-replies.js.map +1 -0
  30. package/lib/engine/gateway.d.ts +6 -1
  31. package/lib/engine/gateway.d.ts.map +1 -1
  32. package/lib/engine/gateway.js +70 -33
  33. package/lib/engine/gateway.js.map +1 -1
  34. package/lib/engine/merge.d.ts +2 -0
  35. package/lib/engine/merge.d.ts.map +1 -1
  36. package/lib/engine/merge.js +2 -0
  37. package/lib/engine/merge.js.map +1 -1
  38. package/lib/engine/router.d.ts +19 -5
  39. package/lib/engine/router.d.ts.map +1 -1
  40. package/lib/engine/router.js +231 -61
  41. package/lib/engine/router.js.map +1 -1
  42. package/lib/engine/session-id.d.ts +7 -0
  43. package/lib/engine/session-id.d.ts.map +1 -1
  44. package/lib/engine/session-id.js.map +1 -1
  45. package/lib/engine/session-store.d.ts +6 -0
  46. package/lib/engine/session-store.d.ts.map +1 -1
  47. package/lib/engine/session-store.js +58 -1
  48. package/lib/engine/session-store.js.map +1 -1
  49. package/lib/engine/session-title.d.ts +8 -0
  50. package/lib/engine/session-title.d.ts.map +1 -0
  51. package/lib/engine/session-title.js +30 -0
  52. package/lib/engine/session-title.js.map +1 -0
  53. package/lib/manager.d.ts +7 -0
  54. package/lib/manager.d.ts.map +1 -1
  55. package/lib/manager.js +57 -9
  56. package/lib/manager.js.map +1 -1
  57. package/package.json +1 -1
  58. package/src/channels/dingtalk.ts +4 -2
  59. package/src/engine/chat-commands.ts +404 -0
  60. package/src/engine/command-locale.ts +20 -0
  61. package/src/engine/command-messages.ts +297 -0
  62. package/src/engine/command-permissions.ts +35 -0
  63. package/src/engine/command-replies.ts +37 -0
  64. package/src/engine/gateway.ts +59 -33
  65. package/src/engine/merge.ts +4 -0
  66. package/src/engine/router.ts +205 -60
  67. package/src/engine/session-id.ts +7 -0
  68. package/src/engine/session-store.ts +50 -1
  69. package/src/engine/session-title.ts +25 -0
  70. package/src/manager.ts +56 -10
@@ -0,0 +1,404 @@
1
+ import { replyText, withReplyLocale } from './command-locale.js'
2
+ /** IM 对 Chat 的薄适配:控制操作走 Host Controller,斜杠命令走同一注册表。 */
3
+ import { AsyncLocalStorage } from 'node:async_hooks'
4
+ import { randomUUID } from 'node:crypto'
5
+ import type { ChannelAdapter, ImMessage } from './types.js'
6
+ import { extensionHelp, extensionReply, oneLine, related } from './command-replies.js'
7
+ import type { SessionRouter } from './router.js'
8
+
9
+ const exportHint = () => replyText('请在网页 Chat 中打开这条会话,再执行 /export 导出 ZIP 日志。IM 文件回传暂未支持。')
10
+ const modelDefaultHint = () => replyText('与 Chat 一致,此操作也会尝试保存后续 Chat 新会话的默认模型选择;已有其他会话不会主动修改。')
11
+
12
+ interface Selection { provider: string; model: string; reasoningEffort?: string }
13
+ interface Model { id: string; name: string; reasoning?: { efforts: Array<{ id: string; name: string }>; defaultEffort?: string } }
14
+ interface Catalog { default: Selection; groups: Array<{ id: string; models: Model[] }> }
15
+ interface Row { sessionId: string; cwd?: string; running?: boolean; origin?: string; projections?: { values?: { title?: string } } }
16
+ interface Workspace { workspaceId: string; title?: string; path: string; sessionIds: string[] }
17
+ interface HistoryEvent { type: string; data?: { message?: { role?: string; content?: Array<{ type: string; text?: string }> }; content?: Array<{ type: string; text?: string }>; source?: { kind?: string } } }
18
+ interface Snapshot { projections?: { values?: { agentPreset?: string | null; permissions?: { currentValue: string; options: Array<{ value: string; name: string }> }; goal?: { goal: { phase: string } } | null; modelSelection?: { next?: Selection; lastUsed?: Selection } } }; records: Array<{ type: string; event?: HistoryEvent }> }
19
+ interface Descriptor { name: string; description: string }
20
+ export interface CommandHost { get(name: string): unknown }
21
+ export const chatControlHelp = () => [
22
+ replyText('IM 助理已连接 DeepSeek Harness。直接发送文字即可开始任务。'), replyText('例如:帮我整理今天的待办。'), '',
23
+ replyText('会话与工作区'),
24
+ replyText('/new — 新开会话(也可用 /clear);旧会话保留在频道列表'),
25
+ replyText('/sessions [页码] — 列出会话;/session 序号或ID — 切换会话'),
26
+ replyText('/workspaces — 列出工作区;/workspace 序号或已有路径 — 切换并新建'),
27
+ replyText('/history — 最近文字记录;/rename 新名称 — 改名;/fork — 分叉'), '',
28
+ replyText('模型与推理'),
29
+ replyText('/model — 当前模型;/models — 可选模型'),
30
+ replyText('/reasoning — 当前推理等级和可选项'), '',
31
+ replyText('任务控制'),
32
+ replyText('/status — 当前状态;/stop — 请求停止,保留队列'),
33
+ replyText('/steer 补充要求 — 提交补充指令;/queue — 查看队列与操作方法'), '',
34
+ replyText('切换模型:先发 /models,再发 /model 序号。'),
35
+ replyText('命令单独发送为文字;图片说明按普通消息处理。'),
36
+ ].join('\n')
37
+
38
+ export class ChatCommands {
39
+ private readonly lifetime = new AsyncLocalStorage<AbortSignal>()
40
+ private readonly choices = new Map<string, { values: string[]; time: number }>()
41
+ constructor(private readonly host: CommandHost, private readonly router: SessionRouter,
42
+ private readonly pending: (sessionId: string) => boolean,
43
+ private readonly onSession: (sessionId: string, msg: ImMessage) => void = () => { }) { }
44
+
45
+ clear(): void { this.choices.clear() }
46
+
47
+ private service(name: string): Record<string, (...args: unknown[]) => unknown> {
48
+ const value = this.host.get(name)
49
+ if (!value) throw new Error(replyText('当前 Host 未提供 {0},请升级 DSH。', name))
50
+ return value as Record<string, (...args: unknown[]) => unknown>
51
+ }
52
+
53
+ private async call<T>(service: string, method: string, ...args: unknown[]): Promise<T> {
54
+ this.lifetime.getStore()?.throwIfAborted()
55
+ const target = this.service(service)
56
+ if (typeof target[method] !== 'function') throw new Error(replyText('当前 Host 不支持 {0}。', method))
57
+ const value = (await target[method]!(...args)) as T
58
+ this.lifetime.getStore()?.throwIfAborted()
59
+ return value
60
+ }
61
+
62
+ private async agent(sessionId: string): Promise<unknown> {
63
+ const result = await this.call<{ agent?: unknown; error?: { message?: string } }>('sessionController', 'resolveAgent', sessionId)
64
+ if (!result.agent) throw new Error(result.error?.message || replyText('无法打开会话。'))
65
+ return result.agent
66
+ }
67
+
68
+ private async snapshot(sessionId: string, signal: AbortSignal): Promise<Snapshot> {
69
+ const stream = await this.call<AsyncIterable<Snapshot>>('sessionController', 'follow', { address: { kind: 'session', sessionId }, maxMessages: 10 }, signal)
70
+ for await (const frame of stream) return frame
71
+ throw new Error(replyText('无法读取会话快照。'))
72
+ }
73
+
74
+ private async workspaces(signal: AbortSignal): Promise<{ items: Workspace[]; archivedSessionIds: string[] }> {
75
+ const stream = await this.call<AsyncIterable<{ type: string; value: { items: Workspace[]; archivedSessionIds: string[] } }>>('workspaceController', 'follow', signal)
76
+ for await (const frame of stream) return frame.value
77
+ throw new Error(replyText('无法读取工作区。'))
78
+ }
79
+
80
+ private remember(key: string, values: string[]): void {
81
+ if (this.choices.size >= 256) this.choices.delete(this.choices.keys().next().value!)
82
+ this.choices.set(key, { values, time: Date.now() })
83
+ }
84
+
85
+ private resolve(key: string, value: string): string {
86
+ if (!/^\d+$/.test(value)) return value
87
+ const choice = this.choices.get(key)
88
+ const selected = choice && Date.now() - choice.time < 15 * 60_000 ? choice.values[Number(value) - 1] : undefined
89
+ if (!selected) throw new Error(replyText('序号无效或已过期,尚未切换。请发送 /{0} 获取新列表。', key.endsWith(':models') ? 'models' : key.endsWith(':workspaces') ? 'workspaces' : 'sessions'))
90
+ return selected
91
+ }
92
+
93
+ private async idle(sessionId: string | undefined, signal: AbortSignal, command: string): Promise<void> {
94
+ if (!sessionId) return
95
+ if (this.pending(sessionId)) throw new Error(replyText('请先完成当前问题或审批,再执行 /{0}。', command))
96
+ const list = await this.call<{ items: Row[] }>('sessionController', 'list', {}, signal)
97
+ if (list.items.find((row) => row.sessionId === sessionId)?.running) throw new Error(replyText('当前任务正在运行,请先 /stop,等待停止后再执行 /{0}。', command))
98
+ }
99
+
100
+ execute(channel: ChannelAdapter, msg: ImMessage, signal: AbortSignal): Promise<string> {
101
+ return withReplyLocale(this.host, () => this.lifetime.run(signal, async () => {
102
+ try { return await this.run(channel, msg, signal) }
103
+ catch (error) {
104
+ if ((error as { code?: string })?.code === 'im/session-in-use') throw new Error(replyText('该会话已关联其他聊天,不能重复接续。请用 /sessions 选择其他会话,或 /new 新建。'))
105
+ throw error
106
+ }
107
+ }))
108
+ }
109
+
110
+ /** 附加查询限时且独立降级,不能把已完成操作改报失败。 */
111
+ private async optional<T>(read: (signal: AbortSignal) => Promise<T>, parent: AbortSignal): Promise<T | undefined> {
112
+ const scope = new AbortController()
113
+ const signal = AbortSignal.any([parent, scope.signal])
114
+ let timer: ReturnType<typeof setTimeout> | undefined
115
+ try {
116
+ return await Promise.race([
117
+ Promise.resolve().then(() => this.lifetime.run(signal, () => read(signal))).catch(() => undefined),
118
+ new Promise<undefined>((resolve) => { timer = setTimeout(() => { scope.abort(); resolve(undefined) }, 800) }),
119
+ ])
120
+ } finally { clearTimeout(timer); scope.abort() }
121
+ }
122
+
123
+ private async newDetails(binding: { sessionId: string; handle?: { agent?: unknown } }, signal: AbortSignal): Promise<string> {
124
+ let cwd: string | undefined
125
+ let model: Selection | undefined
126
+ try {
127
+ const session = (binding.handle?.agent as | { session?: { header?: { cwd?: string }; snapshotEvents?: () => readonly { type: string; data?: Selection }[]; events?: readonly { type: string; data?: Selection }[] } } | undefined)?.session
128
+ cwd = session?.header?.cwd
129
+ model = (session?.snapshotEvents?.() ?? session?.events ?? []).findLast((event) => event.type === 'model/selection')?.data
130
+ } catch { /* 继续尝试宿主快照,不能改用账号默认值冒充实际配置。 */ }
131
+ const [snapshot, rows] = await Promise.all([
132
+ model?.provider && model.model ? undefined : this.optional((sig) => this.snapshot(binding.sessionId, sig), signal),
133
+ cwd ? undefined : this.optional((sig) => this.call<{ items: Row[] }>('sessionController', 'list', {}, sig), signal),
134
+ ])
135
+ model = model?.provider && model.model ? model : snapshot?.projections?.values?.modelSelection?.next
136
+ cwd ||= rows?.items.find((row) => row.sessionId === binding.sessionId)?.cwd
137
+ return [replyText('工作区:{0}', cwd || replyText('暂时无法读取')), model ? replyText('模型:{0}/{1} · {2}', model.provider, model.model, model.reasoningEffort || replyText('默认推理')) : replyText('模型:暂时无法读取')].join('\n')
138
+ }
139
+
140
+ private async run(channel: ChannelAdapter, msg: ImMessage, signal: AbortSignal): Promise<string> {
141
+ signal.throwIfAborted()
142
+ const match = /^\/([a-z][a-z0-9_-]*)([\s\S]*)$/i.exec(msg.text.trim())
143
+ if (!match) throw new Error(replyText('命令格式无效,请发送 /help。'))
144
+ const command = match[1]!.toLowerCase()
145
+ const input = match[2]!.trim()
146
+ const kind = msg.kind === 'group' ? 'group' : 'dm'
147
+ const scope = JSON.stringify([channel.id, kind, msg.chatId, msg.userId ?? ''])
148
+ if (msg.media?.length && ['help', 'new', 'clear', 'sessions', 'sessionlist', 'session', 'workspaces', 'workspacelist', 'workspace', 'models', 'status', 'current', 'stop', 'steer', 'rename', 'fork', 'model', 'reasoning', 'reasonings', 'reasoninglist', 'history', 'queue'].includes(command)) throw new Error(replyText('该控制命令不接受附件,请单独发送。'))
149
+ const current = this.router.lookup(channel.id, kind, msg.chatId)
150
+ const requireCurrent = () => { if (!current) throw new Error(replyText('当前没有会话,请先发送消息或 /new。')); return current.sessionId }
151
+ if (input && ['help', 'new', 'clear', 'workspaces', 'workspacelist', 'models', 'status', 'current', 'stop', 'fork', 'history', 'reasonings', 'reasoninglist', 'export'].includes(command)) throw new Error(replyText('/{0} 暂不支持参数。正确用法:/{1}', command, command))
152
+ if (command === 'export') return exportHint() + related(...(current ? [replyText('查找当前会话:/status'), replyText('最近文字:/history')] : [replyText('直接发送文字或 /new 创建会话')]))
153
+ if (command === 'help') {
154
+ let commands: Descriptor[] = []
155
+ let hint = current ? '' : replyText('\n发送消息创建会话后,可查看该会话的 Chat 命令。')
156
+ try {
157
+ if (current && this.host.get('commands') && this.host.get('sessionController')) commands = await this.call('commands', 'list', await this.agent(current.sessionId))
158
+ } catch {
159
+ signal.throwIfAborted()
160
+ hint = replyText('\n扩展命令暂时无法读取,以上内置帮助仍可使用;稍后重试 /help。')
161
+ }
162
+ const descriptions = extensionHelp()
163
+ return `${oneLine(channel.label || replyText('机器人'))}\n` + chatControlHelp()
164
+ + (commands.length ? replyText('\n\n扩展命令:\n') + commands.map((item) => `/${item.name} — ${descriptions[item.name] || oneLine(item.description)}`).join('\n') : '') + hint
165
+ }
166
+ if (command === 'new' || command === 'clear') {
167
+ if (current && this.host.get('sessionController')) await this.idle(current.sessionId, signal, command)
168
+ const next = await this.router.rotate(channel.id, kind, msg.chatId, msg.username || msg.chatId, { signal })
169
+ return [replyText('已开启新会话'), await this.newDetails(next, signal), replyText('旧会话已保留,直接发送消息即可开始。')].filter(Boolean).join('\n') + related(replyText('查看旧会话:/sessions'), replyText('查看当前配置:/status'))
170
+ }
171
+ if (command === 'sessions' || command === 'sessionlist') {
172
+ const page = input ? Number(input) : 1
173
+ if (!Number.isInteger(page) || page < 1) throw new Error(replyText('用法:/sessions [页码]'))
174
+ const rows = (await this.call<{ items: Row[] }>('sessionController', 'list', {}, signal)).items.filter((row) => !row.origin)
175
+ this.remember(scope + ':sessions', rows.map((row) => row.sessionId))
176
+ if (!rows.length) return replyText('暂无可接续会话。') + related(replyText('直接发送消息,或 /new 开始聊天'))
177
+ const pages = Math.ceil(rows.length / 10)
178
+ if (page > pages) return replyText('没有第 {0} 页,共 {1} 页。', page, pages) + related(replyText('返回列表:/sessions {0}', pages))
179
+ const visible = rows.slice((page - 1) * 10, page * 10)
180
+ const workspace = await this.optional((sig) => this.workspaces(sig), signal)
181
+ signal.throwIfAborted()
182
+ const archived = workspace ? new Set(workspace.archivedSessionIds) : undefined
183
+ const occupied = (row: Row) => this.router.isBoundElsewhere?.(row.sessionId, channel.id, kind, msg.chatId) === true
184
+ const available = visible.find((row) => row.sessionId !== current?.sessionId && !row.running && !occupied(row) && archived && !archived.has(row.sessionId))
185
+ return replyText('会话列表 · 第 {0}/{1} 页 · 共 {2} 个\n\n', page, pages, rows.length)
186
+ + visible.map((row, i) => `${(page - 1) * 10 + i + 1}. ${oneLine(row.projections?.values?.title || replyText('未命名会话'))}${row.sessionId === current?.sessionId ? replyText('〔当前〕') : ''}${archived?.has(row.sessionId) ? replyText('〔已归档,需先在网页恢复〕') : occupied(row) ? replyText('〔已关联其他聊天〕') : row.running ? replyText('〔运行中〕') : ''}\n${row.sessionId}`).join('\n\n')
187
+ + related(available ? replyText('切换:/session {0}', rows.indexOf(available) + 1) : '', !archived ? replyText('归档状态暂时无法读取,切换时会重新校验。') : '', page < pages ? replyText('下一页:/sessions {0}', page + 1) : '', replyText('序号 15 分钟内有效,也可使用完整会话 ID。'))
188
+ }
189
+ if (command === 'session') {
190
+ if (!input) {
191
+ if (!current) return replyText('当前没有会话。直接发送消息或 /new 开始。')
192
+ const rows = (await this.call<{ items: Row[] }>('sessionController', 'list', {}, signal)).items
193
+ const row = rows.find((item) => item.sessionId === current.sessionId)
194
+ return replyText('当前会话:{0}\n工作区:{1}\n会话 ID:{2}', oneLine(row?.projections?.values?.title || replyText('未命名会话')), row?.cwd || replyText('暂时无法读取'), current.sessionId) + related(replyText('切换会话:/sessions'), replyText('详细状态:/status'))
195
+ }
196
+ const id = this.resolve(scope + ':sessions', input)
197
+ const rows = (await this.call<{ items: Row[] }>('sessionController', 'list', {}, signal)).items
198
+ const row = rows.find((item) => item.sessionId === id && !item.origin)
199
+ if (!row) throw new Error(replyText('会话不存在或不是可接入的普通会话。'))
200
+ const workspace = await this.workspaces(signal)
201
+ if (workspace.archivedSessionIds.includes(id)) throw new Error(replyText('请先在 Chat 恢复该归档会话。'))
202
+ if (workspace.items.filter((item) => item.sessionIds.includes(id)).length !== 1) throw new Error(replyText('会话工作区归属无效。'))
203
+ if (row.running && id !== current?.sessionId) throw new Error(replyText('目标会话正在运行,请在 Chat 停止后再切换。'))
204
+ await this.idle(current?.sessionId, signal, command)
205
+ await this.router.bind(channel.id, kind, msg.chatId, id, row.projections?.values?.title || id, await this.agent(id), row.cwd || workspace.items.find((item) => item.sessionIds.includes(id))?.path)
206
+ return replyText('已切换会话:{0}\n工作区:{1}\n接下来的消息会发送到此会话。', oneLine(row.projections?.values?.title || id), row.cwd || workspace.items.find((item) => item.sessionIds.includes(id))?.path || replyText('暂时无法读取')) + related(replyText('最近记录:/history'), replyText('重新开始:/new'))
207
+ }
208
+ if (command === 'workspaces' || command === 'workspacelist' || command === 'workspace') {
209
+ const { items } = await this.workspaces(signal)
210
+ if (command !== 'workspace' || !input) {
211
+ this.remember(scope + ':workspaces', items.map((item) => item.workspaceId))
212
+ const alternative = items.findIndex(
213
+ (item) => !current || !item.sessionIds.includes(current.sessionId))
214
+ return items.length ? replyText('工作区列表 · 共 {0} 个\n\n', items.length) + items.map((item, i) => `${i + 1}. ${item.title ? oneLine(item.title) : oneLine(item.path)}${item.title ? `\n${item.path}` : ''}${current && item.sessionIds.includes(current.sessionId) ? replyText('〔当前〕') : ''}`).join('\n') + related(alternative >= 0
215
+ ? replyText('新建并切换:/workspace {0}', alternative + 1)
216
+ : replyText(
217
+ '当前只有这个工作区。直接发消息继续,或 /new 开启新会话。'), replyText('也可使用已列出的绝对路径;旧会话保留,账号默认目录不变。'), replyText('别名:/workspacelist;序号 15 分钟内有效。')) : replyText('还没有可用工作区。请先在网页添加,再发送 /workspaces。')
218
+ }
219
+ const target = this.resolve(scope + ':workspaces', input)
220
+ const workspace = items.find((item) => item.workspaceId === target || item.path === target)
221
+ if (!workspace) throw new Error(replyText('没有找到这个已添加的工作区,尚未切换。发送 /workspaces 查看可选项;新目录请先在网页添加。'))
222
+ await this.idle(current?.sessionId, signal, command)
223
+ await this.router.rotate(channel.id, kind, msg.chatId, msg.username || msg.chatId, { cwd: workspace.path, signal })
224
+ return replyText('已在「{0}」开启新会话。\n工作区:{1}\n旧会话已保留,可以直接发送任务。', oneLine(workspace.title || workspace.path),
225
+ workspace.path) + related(replyText('查看配置:/status'), replyText('切回旧会话:/sessions'))
226
+ }
227
+ if (command === 'models') {
228
+ const catalog = await this.call<Catalog>('sessionController', 'modelCatalog')
229
+ const models = catalog.groups.flatMap((group) => group.models.map((model) => ({ id: `${group.id}/${model.id}`, name: model.name })))
230
+ let selected: Selection | undefined
231
+ if (current) {
232
+ try { selected = (await this.snapshot(current.sessionId, signal)).projections?.values?.modelSelection?.next }
233
+ catch { signal.throwIfAborted() }
234
+ }
235
+ this.remember(scope + ':models', models.map((model) => model.id))
236
+ const alternative = selected
237
+ ? models.findIndex(
238
+ (model) => model.id !== `${selected.provider}/${selected.model}`)
239
+ : -1
240
+ return models.length ? replyText('可用模型 · 共 {0} 个\n\n', models.length) + models.map((model, i) => `${i + 1}. ${oneLine(model.name)}${model.id === (selected && `${selected.provider}/${selected.model}`) ? replyText('〔当前〕') : ''}\n${model.id}`).join('\n\n') + related(current && alternative >= 0
241
+ ? replyText('切换:/model {0}', alternative + 1) : current && selected
242
+ ? replyText('当前没有其他可切换模型,继续发送消息即可。')
243
+ : '', current ? replyText('查看当前模型:/model;推理选项:/reasoning') : replyText('先发消息或 /new 创建会话,再切换模型。'), replyText('序号 15 分钟内有效。')) : replyText('暂无可用模型。请在网页配置模型服务,再发送 /models。')
244
+ }
245
+ // Host 注册命令可直接用于首次会话,控制命令则要求已有目标。
246
+ const controls = ['status', 'current', 'stop', 'steer', 'rename', 'fork', 'model', 'reasoning', 'reasonings', 'reasoninglist', 'history', 'queue']
247
+ const sessionId = current ? current.sessionId : controls.includes(command) ? requireCurrent() : (await this.router.getOrCreate(channel.id, kind, msg.chatId, msg.username || msg.chatId)).sessionId
248
+ if (command === 'queue') {
249
+ if (!input) {
250
+ const stream = await this.call<AsyncIterable<{ value: { queues: Record<string, Array<{ id: string; placement: string; message: { content: Array<{ type: string; text?: string }> } }>> } }>>('sessionController', 'control', signal)
251
+ for await (const frame of stream) {
252
+ const items = frame.value.queues[sessionId] || []
253
+ if (!items.length) return replyText('当前没有排队消息。') + related(replyText('直接发消息继续'), replyText('查看状态:/status'))
254
+ return replyText('排队消息 · 共 {0} 条\n\n', items.length) + items.map((item) => replyText('{0}〔{1}〕\n{2}', item.id, item.placement === 'queued' ? replyText('等待执行') : item.placement === 'steer' ? replyText('补充指令') : replyText('排队中'), oneLine(item.message.content.filter((part) => part.type === 'text').map((part) => part.text || '').join('\n')) || replyText('附件消息'))).join('\n\n')
255
+ + related(replyText('移除:/queue remove {0}', items[0]!.id), replyText('修改:/queue edit {0} 新内容', items[0]!.id), replyText('改为补充指令:/queue steer {0}', items[0]!.id))
256
+ }
257
+ throw new Error(replyText('无法读取队列。'))
258
+ }
259
+ const action = /^(remove|steer|edit)\s+(\S+)(?:\s+([\s\S]+))?$/.exec(input)
260
+ if (!action || (action[1] === 'edit' && !action[3]) || (action[1] !== 'edit' && action[3])) throw new Error(replyText('用法:/queue remove|steer|edit <消息ID> [新内容]'))
261
+ await this.call('sessionController', 'updateQueue', { sessionId, itemId: action[2], action: action[1] === 'edit' ? { kind: 'edit', content: [{ type: 'text', text: action[3] }] } : { kind: action[1] } })
262
+ return replyText('{0}:{1}{2}', action[1] === 'remove' ? replyText('已移除排队消息') : action[1] === 'edit' ? replyText('已修改排队消息') : replyText('已将排队消息调整为补充指令'), action[2], action[1] === 'edit' ? replyText('\n新内容:') + oneLine(action[3]!) : '') + related(replyText('查看队列:/queue'), replyText('查看状态:/status'))
263
+ }
264
+ if (command === 'status' || command === 'current') {
265
+ const results = await Promise.allSettled([
266
+ this.call<{ items: Row[] }>('sessionController', 'list', {}, signal),
267
+ this.snapshot(sessionId, signal),
268
+ ])
269
+ signal.throwIfAborted()
270
+ const row = results[0].status === 'fulfilled' ? results[0].value.items.find((item) => item.sessionId === sessionId) : undefined
271
+ const values = results[1].status === 'fulfilled' ? results[1].value.projections?.values : undefined
272
+ const model = values?.modelSelection?.next
273
+ const details: string[] = []
274
+ let queueCount: number | undefined
275
+ if (values?.agentPreset) details.push(replyText('Agent 预设:{0}', oneLine(values.agentPreset)))
276
+ if (values?.permissions) details.push(replyText('权限:{0}', oneLine(values.permissions.options.find((item) => item.value === values.permissions!.currentValue)?.name || values.permissions.currentValue)))
277
+ if (values && 'goal' in values) {
278
+ const phases: Record<string, string> = { active: replyText('活跃'), paused: replyText('已暂停'), blocked: replyText('受阻'), complete: replyText('已完成') }
279
+ details.push(replyText('目标:{0}', values.goal ? phases[values.goal.goal.phase] || replyText('暂时无法读取') : replyText('无目标')))
280
+ }
281
+ try {
282
+ const stream = await this.call<AsyncIterable<{ value: { queues: Record<string, unknown[]> } }>>('sessionController', 'control', signal)
283
+ for await (const frame of stream) { queueCount = frame.value.queues[sessionId]?.length || 0; details.push(replyText('排队消息:{0} 条', queueCount)); break }
284
+ } catch { signal.throwIfAborted() }
285
+
286
+ const actions: string[] = []
287
+ if (values?.goal?.goal.phase === 'active') {
288
+ const registered = await this.optional(async () => this.call<Descriptor[]>('commands', 'list', await this.agent(sessionId)), signal)
289
+ if (registered?.some((item) => item.name === 'goal')) actions.push(replyText('暂停目标:/goal pause'))
290
+ }
291
+ if (row?.running === true) actions.push(replyText('补充要求:/steer 补充内容'), replyText('请求停止:/stop'))
292
+ if (queueCount) actions.push(replyText('查看队列:/queue'))
293
+ actions.push(replyText('最近记录:/history'), replyText('模型设置:/model'), replyText('切换会话:/sessions'))
294
+ return [replyText('会话:{0}', oneLine(row?.projections?.values?.title || sessionId)),
295
+ replyText('状态:{0}', row?.running === true ? replyText('运行中') : row?.running === false ? replyText('空闲') : replyText('暂时无法读取')),
296
+ replyText('工作区:{0}', row?.cwd || replyText('暂时无法读取')),
297
+ model ? replyText('模型:{0}/{1};推理:{2}', model.provider, model.model, model.reasoningEffort || replyText('默认')) : replyText('模型:暂时无法读取'),
298
+ ...details, replyText('渠道:{0}({1})', channel.label, channel.status()), replyText('会话 ID:{0}', sessionId),
299
+ ].join('\n') + related(...actions.slice(0, 3))
300
+ }
301
+ if (command === 'stop') {
302
+ await this.call('sessionController', 'cancel', { sessionId })
303
+ const after = await this.optional((sig) => this.call<{ items: Row[] }>('sessionController', 'list', {}, sig), signal)
304
+ const idleNow = after?.items.find((row) => row.sessionId === sessionId)?.running === false
305
+ let goalHint = ''
306
+ try {
307
+ const goals = this.host.get('goals') as | { get(agent: unknown): { phase?: string } | undefined } | undefined
308
+ if (goals) {
309
+ const state = await this.optional(async () => ({ goal: goals.get(await this.agent(sessionId)) }), signal)
310
+ goalHint = !state || (state.goal && !state.goal.phase)
311
+ ? replyText('如已启用目标任务,请用 /goal pause 暂停目标。')
312
+ : state.goal?.phase === 'active' ? replyText('当前目标仍处于活跃状态,请用 /goal pause 暂停目标。') : ''
313
+ }
314
+ } catch { /* 停止已提交,附加状态查询失败不能把停止报告为失败。 */ }
315
+ return [idleNow ? replyText('已请求停止。当前没有正在执行的任务;排队消息保留,可用 /queue 查看。') : replyText('已请求停止当前运行;排队消息保留,可用 /queue 查看。'), goalHint].filter(Boolean).join('\n') + related(replyText('确认运行状态:/status'))
316
+ }
317
+ if (command === 'steer') {
318
+ if (!input) throw new Error(replyText('请填写补充要求。例如:/steer 只修改登录页面,保留现有配色\n查看状态:/status'))
319
+ this.onSession(sessionId, msg)
320
+ await this.call('sessionController', 'prompt', { sessionId, requestId: randomUUID(), mode: 'steer', content: [{ type: 'text', text: input }] }, signal)
321
+ return replyText('补充指令已提交。\n{0}', oneLine(input)) + related(replyText('查看状态:/status'), replyText('请求停止:/stop'))
322
+ }
323
+ if (command === 'rename') {
324
+ if (!input) throw new Error(replyText('请填写新名称,例如:/rename 九月出行计划'))
325
+ const before = await this.optional((sig) => this.call<{ items: Row[] }>('sessionController', 'list', {}, sig), signal)
326
+ const oldTitle = before?.items.find((row) => row.sessionId === sessionId)?.projections?.values?.title
327
+ const result = await this.call<{ title: string }>('sessionController', 'rename', { sessionId, title: input })
328
+ this.router.rename(sessionId, result.title)
329
+ if (oldTitle === result.title)
330
+ return replyText('当前名称已是:{0}', oneLine(result.title)) +
331
+ related(replyText('查看会话列表:/sessions'))
332
+ return replyText('当前会话已改名:{0}', oldTitle ? `${oneLine(oldTitle)} → ${oneLine(result.title)}` : oneLine(result.title)) + related(replyText('查看会话列表:/sessions'))
333
+ }
334
+ if (command === 'fork') {
335
+ await this.idle(sessionId, signal, command)
336
+ const workspace = (await this.workspaces(signal)).items.find((item) => item.sessionIds.includes(sessionId))
337
+ if (!workspace) throw new Error(replyText('当前会话工作区不可用,无法分叉。'))
338
+ let createdId: string | undefined
339
+ try {
340
+ signal.throwIfAborted()
341
+ // 必须先保留创建结果,再检查取消,避免已创建的分叉失去可追踪 ID。
342
+ const controller = this.service('sessionController')
343
+ if (typeof controller.fork !== 'function') throw new Error(replyText('当前 Host 不支持 fork。'))
344
+ const result = (await controller.fork({ sessionId })) as { sessionId: string }
345
+ createdId = result.sessionId
346
+ signal.throwIfAborted()
347
+ await this.router.bind(channel.id, kind, msg.chatId, createdId, createdId, await this.agent(createdId), workspace.path, signal)
348
+ return replyText('已分叉并切换会话:{0}\n工作区:{1}\n新消息将继续这个分叉,原会话保留。', createdId, oneLine(workspace.path)) + related(replyText('查看继承记录:/history'), replyText('切回原会话:/sessions'))
349
+ } catch (error) {
350
+ const partial = error as { code?: string; details?: { sessionId?: string } }
351
+ const attachFailed = partial?.code === 'session/workspace-attach-failed'
352
+ if (!createdId && attachFailed && typeof partial.details?.sessionId === 'string') createdId = partial.details.sessionId
353
+ if (!createdId && partial?.code === 'session/fork-unavailable') throw new Error(replyText('当前会话还没有可分叉的完整回合。请完成一轮对话后再发送 /fork;也可用 /new 开始。'))
354
+ if (!createdId) throw error
355
+ return replyText('分叉已创建:{0},但未能切换,当前绑定仍保留原会话。\n{1}发送 /session {2} 接续。', createdId, attachFailed ? replyText('请先在网页检查并修复该分叉的工作区归属,然后') : replyText('可稍后'), createdId)
356
+ }
357
+ }
358
+ if (command === 'model' || command === 'reasoning' || command === 'reasonings' || command === 'reasoninglist') {
359
+ const catalog = await this.call<Catalog>('sessionController', 'modelCatalog')
360
+ const snapshot = await this.snapshot(sessionId, signal)
361
+ const selected = snapshot.projections?.values?.modelSelection?.next || catalog.default
362
+ if (command === 'model') {
363
+ if (!input) {
364
+ const name = catalog.groups.find((group) => group.id === selected.provider)?.models.find((item) => item.id === selected.model)?.name
365
+ return replyText('当前模型:{0}\n模型 ID:{1}/{2}\n推理等级:{3}', oneLine(name || selected.model), selected.provider, selected.model, selected.reasoningEffort || replyText('默认')) + related(replyText('选择其他模型:/models'), replyText('查看推理选项:/reasoning'), replyText('切换用法:/model {0}/{1} [推理等级ID]', selected.provider, selected.model))
366
+ }
367
+ if (input.split(/\s+/).length > 2) throw new Error(replyText('参数过多。用法:/model 序号或provider/model [推理等级ID];可用模型:/models'))
368
+ const [choice, reasoningEffort] = input.split(/\s+/)
369
+ const id = this.resolve(scope + ':models', choice!)
370
+ const slash = id.indexOf('/')
371
+ if (slash < 1) throw new Error(replyText('用法:/model <序号或provider/model> [推理等级]'))
372
+ const result = await this.call<{ selected: Selection }>('sessionController', 'selectModel', { sessionId, provider: id.slice(0, slash), model: id.slice(slash + 1), ...(reasoningEffort ? { reasoningEffort } : {}) })
373
+ return replyText('已切换模型:{0}/{1};推理:{2}\n{3}', result.selected.provider, result.selected.model, result.selected.reasoningEffort || replyText('默认'), modelDefaultHint()) + related(replyText('调整推理:/reasoning'), replyText('查看模型:/models'))
374
+ }
375
+ const model = catalog.groups.find((group) => group.id === selected.provider)?.models.find((item) => item.id === selected.model)
376
+ const efforts = model?.reasoning?.efforts || []
377
+ if (!input || command !== 'reasoning') return replyText('模型:{0}\n当前推理:{1}\n{2}', oneLine(model?.name || selected.model), selected.reasoningEffort || replyText('默认'), efforts.length ? replyText('可选等级:\n') + efforts.map((item) => `${item.id} — ${oneLine(item.name)}`).join('\n') : replyText('当前模型没有可选推理等级。')) + related(...(efforts.length ? [replyText('切换:/reasoning {0}', efforts[0]!.id), replyText('恢复默认:/reasoning --default'), replyText('当前模型:/model')] : [replyText('当前模型:/model'), replyText('选择其他模型:/models')]))
378
+ if (input !== '--default' && !efforts.some((item) => item.id === input)) throw new Error(replyText('推理等级无效,请先 /reasoning 查看。'))
379
+ await this.call('sessionController', 'selectModel', { sessionId, provider: selected.provider, model: selected.model, ...(input === '--default' ? {} : { reasoningEffort: input }) })
380
+ return replyText('推理等级已设为:{0}\n{1}', input === '--default' ? replyText('默认') : input, modelDefaultHint()) + related(replyText('查看当前模型:/model'), replyText('查看推理选项:/reasoning'))
381
+ }
382
+ if (command === 'history') {
383
+ const snapshot = await this.snapshot(sessionId, signal)
384
+ const history = snapshot.records.flatMap((record) => record.type === 'event' && record.event ? [record.event] : []).filter((record) => record.type === 'assistant/message' || (record.type === 'user/message' && record.data?.source?.kind === 'user'))
385
+ .flatMap((record) => {
386
+ const text = (record.data?.message?.content || record.data?.content || []).filter((part) => part.type === 'text').map((part) => part.text || '').join('\n')
387
+ return text.trim() ? [replyText('{0}:{1}', record.type === 'assistant/message' ? replyText('助手') : replyText('用户'), text)] : []
388
+ }).join('\n\n')
389
+ return (history ? replyText('最近文字记录(不是完整历史)\n\n') + history : replyText('最近记录中没有可展示的文字,图片或文件请在网页查看。')) + related(replyText('继续此会话:直接发消息'), replyText('换一个会话:/sessions'), replyText('完整记录:在网页打开当前会话'))
390
+ }
391
+ const agent = await this.agent(sessionId)
392
+ const images = (msg.media || []).map((media) => {
393
+ if (media.kind !== 'image' || !media.data || !media.mediaType) throw new Error(replyText('Chat 命令只支持文字和图片附件。'))
394
+ return { mediaType: media.mediaType, data: Buffer.from(media.data).toString('base64'), ...(media.name ? { name: media.name } : {}) }
395
+ })
396
+ this.onSession(sessionId, msg)
397
+ const result = await this.call<{ result: { kind: string; text?: string } } | undefined>('commands', 'execute', agent, msg.text.trim(), images, signal)
398
+ let goal: { phase?: string; activation?: string } | undefined
399
+ if (command === 'goal') {
400
+ try { goal = (this.host.get('goals') as | { get(agent: unknown): typeof goal } | undefined)?.get(agent) } catch { /* 保留宿主原始结果,附加状态查询不改变操作结果。 */ }
401
+ }
402
+ return result ? extensionReply(command, result.result, goal) : replyText('未知命令 /{0}。发送 /help 查看当前 Chat 支持的命令。', command)
403
+ }
404
+ }
@@ -0,0 +1,20 @@
1
+ /** 与网页共用宿主保存的语言偏好;IM 无浏览器语言时兼容默认中文。 */
2
+ import { AsyncLocalStorage } from 'node:async_hooks'
3
+ import { commandEnglish } from './command-messages.js'
4
+
5
+ const localeScope = new AsyncLocalStorage<'zh' | 'en'>()
6
+ export function withReplyLocale<T>(host: { get(name: string): unknown }, run: () => T): T {
7
+ let locale: 'zh' | 'en' = 'zh'
8
+ try {
9
+ const settings = host.get('settings') as { get(namespace: string): { preference?: unknown } | undefined } | undefined
10
+ const preference = settings?.get('locale')?.preference
11
+ if (typeof preference === 'string' && /^en(?:-|$)/i.test(preference)) locale = 'en'
12
+ } catch { /* 语言服务不可用不能阻止命令执行,保留既有中文默认。 */ }
13
+ return localeScope.run(locale, run)
14
+ }
15
+
16
+ export function replyText(key: keyof typeof commandEnglish, ...values: unknown[]): string {
17
+ const template = localeScope.getStore() === 'en' ? commandEnglish[key] : key
18
+ // 一次替换,用户内容中的占位符、命令和路径不再次解析。
19
+ return template.replace(/\{(\d+)\}/g, (token, index: string) => Number(index) < values.length ? String(values[Number(index)]) : token)
20
+ }