@cubeai/dsh-feishu-channels 0.0.0-stage → 0.2.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.
Files changed (65) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +15 -0
  3. package/README.md +56 -2
  4. package/client.js +4189 -0
  5. package/cordis.patch.yml +4 -0
  6. package/docs/coexistence.md +112 -0
  7. package/docs/dsh-feishu-channels-plan.md +1406 -0
  8. package/docs/ui-revamp-plan.md +263 -0
  9. package/docs/verification.md +120 -0
  10. package/icon.svg +17 -0
  11. package/locale/en.json +6 -0
  12. package/locale/zh.json +6 -0
  13. package/package.json +76 -4
  14. package/src/channels/connection-state.js +12 -0
  15. package/src/channels/diagnostics.js +77 -0
  16. package/src/channels/factory.js +20 -0
  17. package/src/channels/feishu-app.js +267 -0
  18. package/src/channels/feishu.js +399 -0
  19. package/src/channels/media.js +9 -0
  20. package/src/channels/meta.js +24 -0
  21. package/src/channels/qr/feishu.js +84 -0
  22. package/src/channels/qr/hub.js +229 -0
  23. package/src/channels/qr/render.js +8 -0
  24. package/src/channels/qr/shared.js +50 -0
  25. package/src/engine/abort.js +35 -0
  26. package/src/engine/access.js +23 -0
  27. package/src/engine/agent-options.js +19 -0
  28. package/src/engine/approval.js +70 -0
  29. package/src/engine/assistant-settings.js +38 -0
  30. package/src/engine/assistant-text.js +11 -0
  31. package/src/engine/atomic-file.js +45 -0
  32. package/src/engine/chat-commands.js +752 -0
  33. package/src/engine/choice-delivery.js +20 -0
  34. package/src/engine/choices.js +103 -0
  35. package/src/engine/command-locale.js +70 -0
  36. package/src/engine/command-messages.js +434 -0
  37. package/src/engine/command-permissions.js +38 -0
  38. package/src/engine/command-replies.js +59 -0
  39. package/src/engine/credentials.js +54 -0
  40. package/src/engine/deferred-delivery.js +260 -0
  41. package/src/engine/delivery-history.js +39 -0
  42. package/src/engine/file-delivery.js +215 -0
  43. package/src/engine/file-input.js +52 -0
  44. package/src/engine/file-log.js +25 -0
  45. package/src/engine/gateway.js +1337 -0
  46. package/src/engine/image-input.js +31 -0
  47. package/src/engine/json-state.js +25 -0
  48. package/src/engine/keyed-queue.js +20 -0
  49. package/src/engine/merge.js +56 -0
  50. package/src/engine/message-progress.js +274 -0
  51. package/src/engine/question.js +201 -0
  52. package/src/engine/quiet-logger.js +25 -0
  53. package/src/engine/reply-stream.js +86 -0
  54. package/src/engine/router.js +713 -0
  55. package/src/engine/secure-file.js +8 -0
  56. package/src/engine/seen-store.js +43 -0
  57. package/src/engine/session-export.js +64 -0
  58. package/src/engine/session-history.js +30 -0
  59. package/src/engine/session-id.js +62 -0
  60. package/src/engine/session-store.js +109 -0
  61. package/src/engine/session-title.js +29 -0
  62. package/src/engine/split.js +291 -0
  63. package/src/engine/workspace-path.js +9 -0
  64. package/src/index.js +62 -0
  65. package/src/manager.js +1325 -0
@@ -0,0 +1,713 @@
1
+ import { createFeishuSessionId, parseFeishuSessionId, sessionKeyOf } from './session-id.js';
2
+ import { readHostDefaultModel, resolveImAgentOptions } from './agent-options.js';
3
+ import { KeyedSerialQueue } from './keyed-queue.js';
4
+ import { sameWorkspacePath } from './workspace-path.js';
5
+ import { replyText } from './command-locale.js';
6
+ import { readSessionTitle } from './session-title.js';
7
+ import { readSessionHistory } from './session-history.js';
8
+ const DEFAULT_DISPOSE_TIMEOUT_MS = 10_000;
9
+ function storedHeader(item) {
10
+ const value = item;
11
+ const header = (value?.header ?? item);
12
+ // 新版返回 stat.header,旧版直接返回 header;未知结构不能充当日志已删除的证据。
13
+ if (!header || typeof header.id !== 'string' || !header.id)
14
+ throw new Error(replyText('无法识别宿主持久化会话条目'));
15
+ return header;
16
+ }
17
+ export class SessionRouter {
18
+ ctx;
19
+ store;
20
+ config;
21
+ log;
22
+ resolveConfig;
23
+ live = new Map();
24
+ historical = new Map();
25
+ reloadDisposed = new Set();
26
+ channelOperations = new KeyedSerialQueue();
27
+ disposeTimeoutMs;
28
+ onDeliveryStopped;
29
+ constructor(ctx, store, config, log, resolveConfig = () => config, options = {}) {
30
+ this.ctx = ctx;
31
+ this.store = store;
32
+ this.config = config;
33
+ this.log = log;
34
+ this.resolveConfig = resolveConfig;
35
+ this.disposeTimeoutMs = Math.max(1, options.disposeTimeoutMs ?? DEFAULT_DISPOSE_TIMEOUT_MS);
36
+ this.onDeliveryStopped = options.onDeliveryStopped;
37
+ }
38
+ get(channelId, kind, chatId) {
39
+ return this.live.get(sessionKeyOf(channelId, kind, chatId));
40
+ }
41
+ lookup(channelId, kind, chatId) {
42
+ const live = this.get(channelId, kind, chatId);
43
+ if (live)
44
+ return live;
45
+ const rec = this.store.get(sessionKeyOf(channelId, kind, chatId));
46
+ if (!rec || rec.detached)
47
+ return undefined;
48
+ return {
49
+ key: sessionKeyOf(channelId, kind, chatId),
50
+ channelId,
51
+ kind,
52
+ chatId,
53
+ sessionId: rec.sessionId,
54
+ };
55
+ }
56
+ bindingForSession(sessionId) {
57
+ for (const item of this.live.values()) {
58
+ if (item.sessionId === sessionId)
59
+ return item;
60
+ }
61
+ const rec = this.store.findSession(sessionId);
62
+ if (!rec || rec.detached)
63
+ return undefined;
64
+ return {
65
+ key: sessionKeyOf(rec.channel, rec.kind, rec.chatId),
66
+ channelId: rec.channel,
67
+ kind: rec.kind,
68
+ chatId: rec.chatId,
69
+ sessionId: rec.sessionId,
70
+ };
71
+ }
72
+ sessionIdsForChannel(channelId) {
73
+ return [...new Set([
74
+ ...[...this.live.values()].filter((item) => item.channelId === channelId).map((item) => item.sessionId),
75
+ ...this.store.list().filter((item) => item.channel === channelId).map((item) => item.sessionId),
76
+ ])];
77
+ }
78
+ /** 某个聊天登记过的全部会话记录(含当前绑定),按最近更新排序。 */
79
+ chatRecords(channelId, kind, chatId) {
80
+ return this.store.list().filter((item) => !item.detached && item.channel === channelId && item.kind === kind && item.chatId === chatId);
81
+ }
82
+ /** 持久化解除投递关系,保留历史及句柄,供网页查看与渠道卸载。 */
83
+ unbindSession(channelId, kind, chatId, sessionId) {
84
+ const rec = this.store.findSession(sessionId);
85
+ if (!rec || rec.detached || rec.channel !== channelId || rec.kind !== kind || rec.chatId !== chatId)
86
+ return false;
87
+ const binding = this.bindingForSession(sessionId);
88
+ this.store.updateSession({ ...rec, detached: true });
89
+ // live 键按聊天而非会话组织:仅当 live 绑定指向被解绑的会话时才清除,避免误删新绑定。
90
+ const key = sessionKeyOf(channelId, kind, chatId);
91
+ if (this.store.get(key)?.sessionId === sessionId)
92
+ this.store.retain(key);
93
+ const live = this.live.get(key);
94
+ if (live?.sessionId === sessionId) {
95
+ this.historical.set(sessionId, live);
96
+ this.live.delete(key);
97
+ }
98
+ if (binding)
99
+ this.onDeliveryStopped?.(binding);
100
+ return true;
101
+ }
102
+ /** 切换绑定后清理:解除本聊天对除 keepSessionId 外全部会话的登记。返回被解除的会话 ID。 */
103
+ unbindOthersForChat(channelId, kind, chatId, keepSessionId) {
104
+ const removed = [];
105
+ for (const item of this.chatRecords(channelId, kind, chatId)) {
106
+ if (item.sessionId === keepSessionId)
107
+ continue;
108
+ if (this.unbindSession(channelId, kind, chatId, item.sessionId))
109
+ removed.push(item.sessionId);
110
+ }
111
+ return removed;
112
+ }
113
+ /** 静音/取消静音:保留登记但不(或恢复)向聊天投递该会话的输出事件。 */
114
+ setMuted(sessionId, muted) {
115
+ const rec = this.store.findSession(sessionId);
116
+ if (!rec || rec.detached)
117
+ return false;
118
+ this.store.updateSession({ ...rec, muted });
119
+ const binding = this.bindingForSession(sessionId);
120
+ if (muted && binding)
121
+ this.onDeliveryStopped?.(binding);
122
+ return true;
123
+ }
124
+ isMuted(sessionId) {
125
+ const record = this.store.findSession(sessionId);
126
+ return !!record && !record.detached && record.muted === true;
127
+ }
128
+ async getOrCreate(channelId, kind, chatId, title) {
129
+ return this.channelOperations.run(channelId, () => this.getOrCreateNow(channelId, kind, chatId, title));
130
+ }
131
+ async getOrCreateNow(channelId, kind, chatId, title) {
132
+ const key = sessionKeyOf(channelId, kind, chatId);
133
+ const live = this.live.get(key);
134
+ if (live?.handle) {
135
+ if (this.isArchived(live.sessionId)) {
136
+ this.log(`[router] 当前会话已归档,轮换 ${live.sessionId}`);
137
+ return this.rotateNow(channelId, kind, chatId, title);
138
+ }
139
+ return live;
140
+ }
141
+ const saved = this.store.get(key);
142
+ if (saved) {
143
+ if (this.isArchived(saved.sessionId)) {
144
+ this.log(`[router] 映射会话已归档,轮换 ${saved.sessionId}`);
145
+ return this.rotateNow(channelId, kind, chatId, title);
146
+ }
147
+ const resumed = await this.resume(saved);
148
+ if (resumed) {
149
+ this.live.set(key, resumed);
150
+ return resumed;
151
+ }
152
+ const known = await this.knownSessionIds();
153
+ if (known === undefined || known.has(saved.sessionId)) {
154
+ throw new Error(replyText('当前会话暂时无法恢复,已保留原绑定,请稍后重试。'));
155
+ }
156
+ this.log(`[router] 无法恢复会话,轮换 ${saved.sessionId}`);
157
+ return this.rotateNow(channelId, kind, chatId, title);
158
+ }
159
+ return this.create(channelId, kind, chatId, title);
160
+ }
161
+ async rotate(channelId, kind, chatId, title, options) {
162
+ return this.channelOperations.run(channelId, () => this.rotateNow(channelId, kind, chatId, title, options));
163
+ }
164
+ async rotateNow(channelId, kind, chatId, title, options) {
165
+ const key = sessionKeyOf(channelId, kind, chatId);
166
+ const old = this.live.get(key);
167
+ const record = this.store.get(key);
168
+ const cwd = options?.cwd || (record ? await this.sessionWorkspace(record) : undefined);
169
+ options?.signal?.throwIfAborted();
170
+ // 新会话准备成功后才替换当前映射,失败时旧句柄仍可继续使用。
171
+ const next = await this.create(channelId, kind, chatId, title, cwd, options?.signal);
172
+ // dispose 会触发宿主 api-session/removed,导致未刷新的网页拒绝打开历史。
173
+ // 轮换只转入历史,句柄在渠道停用或插件重载时统一释放。
174
+ if (old)
175
+ this.historical.set(old.sessionId, old);
176
+ this.unbindOthersForChat(channelId, kind, chatId, next.sessionId);
177
+ return next;
178
+ }
179
+ async sessionWorkspace(record) {
180
+ if (record.cwd)
181
+ return record.cwd;
182
+ const registry = this.ctx.get?.('workspaceRegistry');
183
+ const workspace = registry?.list?.()?.find(item => item.sessionIds?.includes(record.sessionId));
184
+ if (workspace)
185
+ return workspace.path;
186
+ const controller = this.ctx.get?.('sessionController');
187
+ if (controller?.list) {
188
+ const row = (await controller.list({}))?.items?.find(item => item.sessionId === record.sessionId);
189
+ if (row?.cwd)
190
+ return row.cwd;
191
+ }
192
+ if (record.adopted)
193
+ throw new Error(replyText('无法确定当前会话工作区,请使用 /workspace 重新选择。'));
194
+ return undefined;
195
+ }
196
+ rename(sessionId, title) {
197
+ return this.setTitle(sessionId, title, 'user');
198
+ }
199
+ isAdopted(sessionId) { return this.store.list().some(record => record.sessionId === sessionId && record.adopted); }
200
+ /** 只返回是否占用,不向列表暴露其他聊天身份。 */
201
+ isBoundElsewhere(sessionId, channelId, kind, chatId) {
202
+ const key = sessionKeyOf(channelId, kind, chatId);
203
+ return this.store.list().some(item => !item.detached && item.sessionId === sessionId && sessionKeyOf(item.channel, item.kind, item.chatId) !== key);
204
+ }
205
+ /** 显式换绑保留旧历史与运行句柄,不改变 Host 会话的归属或默认配置。 */
206
+ async bind(channelId, kind, chatId, sessionId, title, agent, cwd, signal) {
207
+ await this.channelOperations.run(channelId, async () => {
208
+ const key = sessionKeyOf(channelId, kind, chatId);
209
+ signal?.throwIfAborted();
210
+ const other = this.isBoundElsewhere(sessionId, channelId, kind, chatId);
211
+ if (other)
212
+ throw Object.assign(new Error(replyText('该会话已关联其他聊天,不能重复绑定。')), { code: 'im/session-in-use' });
213
+ const old = this.live.get(key);
214
+ const previous = this.store.list().find(item => item.sessionId === sessionId);
215
+ this.store.upsert(key, { ...previous, channel: channelId, kind, chatId, sessionId, title: previous?.titleSource === 'user' ? previous.title : title, ...(cwd ? { cwd } : {}), adopted: true, detached: false, muted: false, updatedAt: new Date().toISOString() });
216
+ if (old && old.sessionId !== sessionId)
217
+ this.historical.set(old.sessionId, old);
218
+ const binding = this.historical.get(sessionId) ?? { key, channelId, kind, chatId, sessionId, handle: { agent, dispose: async () => { } } };
219
+ Object.assign(binding, { key, channelId, kind, chatId });
220
+ this.historical.delete(sessionId);
221
+ this.live.set(key, binding);
222
+ this.unbindOthersForChat(channelId, kind, chatId, sessionId);
223
+ });
224
+ }
225
+ setTitle(sessionId, title, source) {
226
+ const rec = this.store.list().find((item) => item.sessionId === sessionId);
227
+ if (!rec)
228
+ return false;
229
+ const acceptsInitialMessage = rec.titleSource === 'pending' || (!rec.titleSource && !rec.title.trim());
230
+ if (!title.trim()
231
+ || (source === 'message' && !acceptsInitialMessage)
232
+ || (source === 'host' && rec.titleSource === 'user'))
233
+ return false;
234
+ if (rec.title === title && rec.titleSource === source)
235
+ return true;
236
+ this.store.updateSession({
237
+ ...rec,
238
+ title,
239
+ titleSource: source,
240
+ updatedAt: new Date().toISOString(),
241
+ });
242
+ return true;
243
+ }
244
+ async pruneMissingSessions() {
245
+ const known = await this.knownSessionIds();
246
+ if (known === undefined)
247
+ return 0;
248
+ let removed = 0;
249
+ for (const rec of this.store.list()) {
250
+ if (known.has(rec.sessionId))
251
+ continue;
252
+ await this.channelOperations.run(rec.channel, () => this.removeFromChannel(rec.sessionId, false));
253
+ removed += 1;
254
+ }
255
+ if (removed > 0)
256
+ this.log(`[router] 已清理 ${removed} 条宿主已删除的飞书会话映射`);
257
+ return removed;
258
+ }
259
+ async knownSessionIds() {
260
+ try {
261
+ // 未 inject sessions 时不能读 ctx.sessions,否则 Cordis 会直接把 Host 打挂
262
+ const live = this.ctx.get?.('sessions');
263
+ const persistence = this.ctx.get?.('sessionPersistence');
264
+ const canListLive = typeof live?.list === "function";
265
+ const canListStored = typeof persistence?.list === "function";
266
+ // 仅凭活会话列表不能判断已卸载的历史日志是否被删除。
267
+ if (!canListStored)
268
+ return undefined;
269
+ const ids = new Set();
270
+ if (canListLive && live.list) {
271
+ for (const session of live.list())
272
+ ids.add(String(session.id));
273
+ }
274
+ if (canListStored && persistence.list) {
275
+ for (const item of await persistence.list())
276
+ ids.add(storedHeader(item).id);
277
+ }
278
+ return ids;
279
+ }
280
+ catch {
281
+ return undefined;
282
+ }
283
+ }
284
+ async ensure(sessionId) {
285
+ const rec = this.store.list().find((item) => item.sessionId === sessionId);
286
+ if (!rec)
287
+ return false;
288
+ return this.channelOperations.run(rec.channel, async () => {
289
+ if (this.isArchived(sessionId))
290
+ return false;
291
+ const key = sessionKeyOf(rec.channel, rec.kind, rec.chatId);
292
+ const current = this.live.get(key);
293
+ if (this.historical.has(sessionId) || (current?.sessionId === sessionId && current.handle))
294
+ return true;
295
+ const binding = await this.resume(rec);
296
+ if (!binding)
297
+ return false;
298
+ if (this.store.get(key)?.sessionId === sessionId)
299
+ this.live.set(key, binding);
300
+ else
301
+ this.historical.set(sessionId, binding);
302
+ return true;
303
+ });
304
+ }
305
+ async disposeAll() {
306
+ const channels = [...new Set([...this.live.values(), ...this.historical.values()].map((item) => item.channelId))];
307
+ await Promise.all(channels.map((channelId) => this.disposeChannel(channelId)));
308
+ this.live.clear();
309
+ this.historical.clear();
310
+ }
311
+ /** 卸载不代表删除日志;只有可靠确认日志不存在才清除索引。 */
312
+ async onHostDisposed(sessionId) {
313
+ if (this.reloadDisposed.delete(sessionId)) {
314
+ this.historical.delete(sessionId);
315
+ for (const [key, item] of this.live) {
316
+ if (item.sessionId === sessionId)
317
+ this.live.delete(key);
318
+ }
319
+ return false;
320
+ }
321
+ const known = await this.knownSessionIds();
322
+ if (known === undefined || known.has(sessionId)) {
323
+ this.historical.delete(sessionId);
324
+ for (const [key, item] of this.live) {
325
+ if (item.sessionId === sessionId)
326
+ this.live.delete(key);
327
+ }
328
+ return false;
329
+ }
330
+ const record = this.store.list().find(item => item.sessionId === sessionId);
331
+ if (!record)
332
+ return false;
333
+ return this.channelOperations.run(record.channel, () => this.removeFromChannel(sessionId, false));
334
+ }
335
+ /**
336
+ * 投递一条普通用户消息。`steer` 模式在宿主 Agent 提供 next-step 注入时作为补充指令
337
+ * 立即进入运行中的任务;旧宿主没有 `steer` 时保持排队投递,消息不丢失、语义可预期。
338
+ */
339
+ followup(binding, message, mode = 'queue') {
340
+ const raw = binding.handle?.agent ?? this.ctx.agents?.get?.(binding.sessionId);
341
+ const agent = raw;
342
+ if (!agent?.followup)
343
+ throw new Error(`会话 ${binding.sessionId} 当前没有运行中的 agent`);
344
+ if (mode === 'steer' && typeof agent.steer === 'function') {
345
+ agent.steer(message);
346
+ return;
347
+ }
348
+ agent.followup(message);
349
+ }
350
+ async disposeChannel(channelId) {
351
+ await this.channelOperations.run(channelId, () => this.disposeChannelNow(channelId));
352
+ }
353
+ async resetChannelSessions(channelId) {
354
+ await this.channelOperations.run(channelId, async () => {
355
+ await this.disposeChannelNow(channelId);
356
+ // 工作区属于会话创建参数,不能拿旧 sessionId 在新目录恢复;仅解除映射,保留 Host 中的历史日志。
357
+ for (const record of this.store.list()) {
358
+ if (record.channel !== channelId)
359
+ continue;
360
+ this.store.retain(sessionKeyOf(record.channel, record.kind, record.chatId));
361
+ }
362
+ });
363
+ }
364
+ async disposeChannelNow(channelId) {
365
+ for (const [id, item] of this.historical) {
366
+ if (item.channelId !== channelId)
367
+ continue;
368
+ this.reloadDisposed.add(id);
369
+ await this.disposeHandle(item);
370
+ this.historical.delete(id);
371
+ }
372
+ const entries = [...this.live].filter(([, item]) => item.channelId === channelId);
373
+ for (const [, item] of entries)
374
+ this.reloadDisposed.add(item.sessionId);
375
+ await Promise.all(entries.map(async ([key, item]) => {
376
+ await this.disposeHandle(item);
377
+ this.live.delete(key);
378
+ }));
379
+ }
380
+ async disposeHandle(item) {
381
+ if (!item.handle)
382
+ return;
383
+ let timer;
384
+ const result = await Promise.race([
385
+ Promise.resolve().then(() => item.handle.dispose()).then(() => 'disposed', (error) => {
386
+ this.log(`[router] 卸载会话失败 ${item.sessionId}: ${error instanceof Error ? error.message : String(error)}`);
387
+ return 'failed';
388
+ }),
389
+ new Promise((resolve) => {
390
+ timer = setTimeout(() => resolve('timed-out'), this.disposeTimeoutMs);
391
+ }),
392
+ ]);
393
+ if (timer)
394
+ clearTimeout(timer);
395
+ if (result === 'timed-out')
396
+ this.log(`[router] 卸载会话超时 ${item.sessionId},已解除本地引用`);
397
+ }
398
+ async removeFromChannel(sessionId, retainArchived = true) {
399
+ const rec = this.store.list().find((item) => item.sessionId === sessionId);
400
+ if (!rec)
401
+ return false;
402
+ const key = sessionKeyOf(rec.channel, rec.kind, rec.chatId);
403
+ const current = this.live.get(key);
404
+ const live = current?.sessionId === sessionId ? current : this.historical.get(sessionId);
405
+ if (live?.handle) {
406
+ this.reloadDisposed.add(sessionId);
407
+ await this.disposeHandle(live);
408
+ }
409
+ if (current?.sessionId === sessionId)
410
+ this.live.delete(key);
411
+ this.historical.delete(sessionId);
412
+ if (retainArchived && this.isArchived(sessionId)) {
413
+ if (this.store.get(key)?.sessionId === sessionId)
414
+ this.store.retain(key);
415
+ }
416
+ else
417
+ this.store.removeSession(sessionId);
418
+ return true;
419
+ }
420
+ async remove(sessionId) {
421
+ const rec = this.store.list().find((item) => item.sessionId === sessionId);
422
+ if (!rec)
423
+ return false;
424
+ return this.channelOperations.run(rec.channel, () => this.removeFromChannel(sessionId));
425
+ }
426
+ /** 归档失败后,仅在可靠确认日志缺失时清理残留索引。 */
427
+ async cleanupMissing(sessionId) {
428
+ const rec = this.store.list().find(item => item.sessionId === sessionId);
429
+ if (!rec)
430
+ return true;
431
+ return this.channelOperations.run(rec.channel, async () => {
432
+ const persistence = this.ctx.get?.('sessionPersistence');
433
+ if (!persistence?.list)
434
+ return false;
435
+ try {
436
+ if ((await persistence.list()).map(storedHeader).some(header => header.id === sessionId))
437
+ return false;
438
+ }
439
+ catch {
440
+ return false;
441
+ }
442
+ return this.removeFromChannel(sessionId, false);
443
+ });
444
+ }
445
+ samePath(left, right) {
446
+ return sameWorkspacePath(left, right);
447
+ }
448
+ async create(channelId, kind, chatId, title, cwd, signal) {
449
+ const key = sessionKeyOf(channelId, kind, chatId);
450
+ const sessionId = createFeishuSessionId(channelId, kind, chatId);
451
+ const config = { ...this.resolveConfig(channelId), ...(cwd ? { cwd } : {}) };
452
+ const handle = await this.createHandle(sessionId, channelId, config);
453
+ try {
454
+ signal?.throwIfAborted();
455
+ await this.attachWorkspace(sessionId, channelId, config.cwd, true);
456
+ signal?.throwIfAborted();
457
+ }
458
+ catch (error) {
459
+ await this.disposeHandle({ key, channelId, kind, chatId, sessionId, handle });
460
+ throw error;
461
+ }
462
+ const record = {
463
+ sessionId,
464
+ channel: channelId,
465
+ kind,
466
+ chatId,
467
+ title,
468
+ titleSource: 'pending',
469
+ agentPreset: config.agentPreset || 'standard',
470
+ cwd: config.cwd || process.cwd(),
471
+ updatedAt: new Date().toISOString(),
472
+ };
473
+ try {
474
+ this.store.upsert(key, record);
475
+ }
476
+ catch (error) {
477
+ await this.disposeHandle({ key, channelId, kind, chatId, sessionId, handle });
478
+ throw error;
479
+ }
480
+ const binding = { key, channelId, kind, chatId, sessionId, handle };
481
+ this.live.set(key, binding);
482
+ this.log(`[router] 新建 IM 会话 ${sessionId}`);
483
+ return binding;
484
+ }
485
+ async resume(record) {
486
+ if (record.adopted) {
487
+ const controller = this.ctx.get?.('sessionController');
488
+ if (!controller?.resolveAgent)
489
+ return undefined;
490
+ const result = await controller.resolveAgent(record.sessionId);
491
+ if (!result.agent)
492
+ return undefined;
493
+ return { key: sessionKeyOf(record.channel, record.kind, record.chatId), channelId: record.channel, kind: record.kind, chatId: record.chatId,
494
+ sessionId: record.sessionId, handle: { agent: result.agent, dispose: async () => { } } };
495
+ }
496
+ const liveAgent = this.ctx.agents?.get?.(record.sessionId);
497
+ if (liveAgent) {
498
+ await this.syncStoredTitle(record.sessionId, liveAgent);
499
+ const binding = {
500
+ key: sessionKeyOf(record.channel, record.kind, record.chatId),
501
+ channelId: record.channel,
502
+ kind: record.kind,
503
+ chatId: record.chatId,
504
+ sessionId: record.sessionId,
505
+ };
506
+ await this.attachWorkspace(record.sessionId, record.channel, record.cwd);
507
+ return binding;
508
+ }
509
+ if (!this.ctx.agents?.resume)
510
+ return undefined;
511
+ try {
512
+ const handle = await this.ctx.agents.resume({
513
+ resumeSessionId: record.sessionId,
514
+ agentOptions: {
515
+ ...this.resolveAgentOptions(record.channel),
516
+ ...(this.resolveConfig(record.channel).reasoningEffort ? { reasoningEffort: this.resolveConfig(record.channel).reasoningEffort } : {}),
517
+ },
518
+ setup: this.presetSetup(record.channel, record.agentPreset, true),
519
+ });
520
+ await this.syncStoredTitle(record.sessionId, handle.agent);
521
+ await this.attachWorkspace(record.sessionId, record.channel, record.cwd);
522
+ return {
523
+ key: sessionKeyOf(record.channel, record.kind, record.chatId),
524
+ channelId: record.channel,
525
+ kind: record.kind,
526
+ chatId: record.chatId,
527
+ sessionId: record.sessionId,
528
+ handle,
529
+ };
530
+ }
531
+ catch (error) {
532
+ this.log(`[router] 恢复会话失败 ${record.sessionId}: ${error instanceof Error ? error.message : String(error)}`);
533
+ return undefined;
534
+ }
535
+ }
536
+ async createHandle(sessionId, channelId, config = this.resolveConfig(channelId)) {
537
+ const agents = this.ctx.agents;
538
+ if (!agents?.create)
539
+ throw new Error(replyText('当前 Host 没有 agents 服务,无法创建 IM 会话'));
540
+ // IM 保持普通会话(不设置 subagent origin);Chat prompt 会拒绝子代理所有权。
541
+ // IM 与任务的区分靠 sessionId 的 im: 前缀。
542
+ // 必须带上当前默认模型,否则 deployment:persona 的 {{model}} 组装会失败。
543
+ const agentOptions = this.resolveAgentOptions(channelId);
544
+ this.log(`[router] ${channelId} 使用模型 ${agentOptions.provider}/${agentOptions.model}${config.reasoningEffort ? ` ${config.reasoningEffort}` : ''}`);
545
+ const create = () => agents.create({
546
+ sessionId,
547
+ meta: {
548
+ cwd: config.cwd || process.cwd(),
549
+ ...(config.agentPreset ? { agentPreset: config.agentPreset } : {}),
550
+ },
551
+ agentOptions: {
552
+ ...agentOptions,
553
+ ...(config.reasoningEffort ? { reasoningEffort: config.reasoningEffort } : {}),
554
+ },
555
+ setup: this.presetSetup(channelId),
556
+ });
557
+ const handle = await (agents.withoutInitiator ? agents.withoutInitiator(create) : create());
558
+ // Chat's selectionFor() restores the durable pending selection, not this
559
+ // router's assembly hook. Seed NEW sessions so an image-first message uses
560
+ // the account model. Never rewrite a resumed session's current selection.
561
+ const session = handle.agent?.session;
562
+ if (config.provider && config.model && session?.append) {
563
+ try {
564
+ session.append('model/selection', {
565
+ provider: config.provider,
566
+ model: config.model,
567
+ ...(config.reasoningEffort ? { reasoningEffort: config.reasoningEffort } : {}),
568
+ });
569
+ }
570
+ catch (error) {
571
+ // Older Hosts may not register this event; preserve legacy text input.
572
+ this.log(`[router] 无法记录初始模型选择: ${error instanceof Error ? error.message : String(error)}`);
573
+ }
574
+ }
575
+ return handle;
576
+ }
577
+ async attachMappedSessions(active = () => true) {
578
+ const started = Date.now();
579
+ if (!active())
580
+ return;
581
+ await this.recoverHistory();
582
+ if (!active())
583
+ return;
584
+ await this.pruneMissingSessions();
585
+ for (const record of this.store.list()) {
586
+ if (!active())
587
+ return;
588
+ if (record.adopted || this.isArchived(record.sessionId))
589
+ continue;
590
+ await this.attachWorkspace(record.sessionId, record.channel, record.cwd);
591
+ }
592
+ this.log(`[boot] attachMappedSessions ${Date.now() - started}ms`);
593
+ }
594
+ async syncStoredTitle(sessionId, agent) {
595
+ const session = agent?.session;
596
+ const events = await readSessionHistory(this.ctx, session) ?? [];
597
+ const latest = readSessionTitle(events.findLast(event => event.type === 'session/title')?.data);
598
+ if (latest)
599
+ this.setTitle(sessionId, latest.title, latest.source);
600
+ }
601
+ async recoverHistory() {
602
+ try {
603
+ const persistence = this.ctx.get?.('sessionPersistence');
604
+ if (!persistence?.list)
605
+ return;
606
+ for (const item of await persistence.list()) {
607
+ let header;
608
+ try {
609
+ header = storedHeader(item);
610
+ }
611
+ catch (error) {
612
+ this.log(`[router] 跳过无法识别的历史条目: ${error instanceof Error ? error.message : String(error)}`);
613
+ continue;
614
+ }
615
+ const parsed = parseFeishuSessionId(header.id);
616
+ if (!parsed)
617
+ continue;
618
+ this.store.saveHistory({
619
+ sessionId: header.id, ...parsed,
620
+ title: parsed.chatId, ...(header.cwd ? { cwd: header.cwd } : {}),
621
+ updatedAt: new Date(Number.isFinite(header.createdAt) ? header.createdAt : 0).toISOString(),
622
+ });
623
+ }
624
+ }
625
+ catch (error) {
626
+ this.log(`[router] 恢复历史索引失败: ${error instanceof Error ? error.message : String(error)}`);
627
+ }
628
+ }
629
+ isArchived(sessionId) {
630
+ try {
631
+ const ids = this.ctx.get?.('workspaceRegistry')?.archivedSessionIds;
632
+ if (!ids)
633
+ return false;
634
+ return ids.some((id) => String(id) === sessionId);
635
+ }
636
+ catch {
637
+ return false;
638
+ }
639
+ }
640
+ async attachWorkspace(sessionId, channelId, cwd, strict = false) {
641
+ let workspaces = [];
642
+ try {
643
+ workspaces = this.ctx.get?.('workspaceRegistry')?.list?.() ?? [];
644
+ }
645
+ catch {
646
+ workspaces = [];
647
+ }
648
+ if (workspaces.length === 0) {
649
+ this.log(`[router] 当前没有工作区,网页点不开会话 ${sessionId}`);
650
+ return;
651
+ }
652
+ const preferred = cwd || this.resolveConfig(channelId).cwd || process.cwd();
653
+ const ordered = [...workspaces].sort((left, right) => {
654
+ const leftHit = this.samePath(left.path, preferred) ? 0 : 1;
655
+ const rightHit = this.samePath(right.path, preferred) ? 0 : 1;
656
+ return leftHit - rightHit;
657
+ });
658
+ let lastError = '';
659
+ for (const workspace of ordered.filter(item => !cwd || this.samePath(item.path, preferred))) {
660
+ try {
661
+ await workspace.attachSession(sessionId);
662
+ this.log(`[router] 已把 ${sessionId} 挂到工作区 ${workspace.path}`);
663
+ return;
664
+ }
665
+ catch (error) {
666
+ lastError = error instanceof Error ? error.message : String(error);
667
+ }
668
+ }
669
+ if (strict)
670
+ throw new Error(replyText('挂载会话失败 {0}:{1}', sessionId, lastError || replyText('目标工作区不可用')));
671
+ this.log(`[router] 挂载会话失败 ${sessionId}: ${lastError}`);
672
+ }
673
+ resolveAgentOptions(channelId) {
674
+ const config = this.resolveConfig(channelId);
675
+ return resolveImAgentOptions({
676
+ provider: config.provider,
677
+ model: config.model,
678
+ fallback: readHostDefaultModel(this.ctx),
679
+ });
680
+ }
681
+ presetSetup(channelId, savedPreset, restoring = false) {
682
+ const ctx = this.ctx;
683
+ const config = this.resolveConfig(channelId);
684
+ const preset = savedPreset || config.agentPreset || 'standard';
685
+ const permission = config.permissionPreset;
686
+ return async (agentCtx, explicitAgent) => {
687
+ // 0.1.5 显式传入 Agent;仅旧版单参数契约读取作用域属性。
688
+ const agent = explicitAgent ?? agentCtx.agent;
689
+ const session = agent?.session;
690
+ const events = await readSessionHistory(ctx, session);
691
+ // 在挂载前读取历史;来源不可读取时也不冒险覆盖已有权限。
692
+ const preservePermission = restoring && (!events || events.some(event => ['permission/preset', 'sandbox/mode', 'approval/policy'].includes(event.type ?? '')));
693
+ if (ctx.agentPresets?.mount)
694
+ await ctx.agentPresets.mount(agentCtx, preset);
695
+ // Account defaults belong in agentOptions (including on legacy Hosts),
696
+ // not a second installModelSelection middleware. Its outer after-next
697
+ // override would defeat Chat's session selection and image admission.
698
+ // New sessions also persist their initial selection in createHandle().
699
+ if (permission && !preservePermission) {
700
+ try {
701
+ const permissionPresets = ctx.permissionPresets;
702
+ if (!permissionPresets)
703
+ throw new Error(replyText('Host 未提供官方权限预设服务'));
704
+ if (agent?.session)
705
+ permissionPresets.set(agent.session, permission);
706
+ }
707
+ catch (error) {
708
+ this.log(`[router] 无法应用权限 ${permission}: ${error instanceof Error ? error.message : String(error)}`);
709
+ }
710
+ }
711
+ };
712
+ }
713
+ }