@dabuliu_wsy/dsh-im 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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +197 -3
  3. package/cordis.patch.yml +4 -0
  4. package/dist/core/agent-state.d.ts +38 -0
  5. package/dist/core/agent-state.js +59 -0
  6. package/dist/core/arbiter-bridge.d.ts +25 -0
  7. package/dist/core/arbiter-bridge.js +20 -0
  8. package/dist/core/arbiter.d.ts +29 -0
  9. package/dist/core/arbiter.js +59 -0
  10. package/dist/core/avatar-brands.d.ts +23 -0
  11. package/dist/core/avatar-brands.js +75 -0
  12. package/dist/core/avatar-presets.d.ts +21 -0
  13. package/dist/core/avatar-presets.js +38 -0
  14. package/dist/core/avatar.d.ts +1 -0
  15. package/dist/core/avatar.js +18 -0
  16. package/dist/core/blocked.d.ts +12 -0
  17. package/dist/core/blocked.js +23 -0
  18. package/dist/core/budget-plan.d.ts +41 -0
  19. package/dist/core/budget-plan.js +69 -0
  20. package/dist/core/calibration-samples.d.ts +77 -0
  21. package/dist/core/calibration-samples.js +168 -0
  22. package/dist/core/calibrator.d.ts +57 -0
  23. package/dist/core/calibrator.js +125 -0
  24. package/dist/core/chapter-tree.d.ts +128 -0
  25. package/dist/core/chapter-tree.js +400 -0
  26. package/dist/core/consensus.d.ts +135 -0
  27. package/dist/core/consensus.js +394 -0
  28. package/dist/core/context-budget.d.ts +153 -0
  29. package/dist/core/context-budget.js +183 -0
  30. package/dist/core/curator.d.ts +28 -0
  31. package/dist/core/curator.js +190 -0
  32. package/dist/core/dual-window.d.ts +86 -0
  33. package/dist/core/dual-window.js +175 -0
  34. package/dist/core/events.d.ts +110 -0
  35. package/dist/core/events.js +117 -0
  36. package/dist/core/facts.d.ts +114 -0
  37. package/dist/core/facts.js +400 -0
  38. package/dist/core/fence.d.ts +34 -0
  39. package/dist/core/fence.js +129 -0
  40. package/dist/core/floor.d.ts +18 -0
  41. package/dist/core/floor.js +80 -0
  42. package/dist/core/ids.d.ts +11 -0
  43. package/dist/core/ids.js +29 -0
  44. package/dist/core/im.d.ts +167 -0
  45. package/dist/core/im.js +1307 -0
  46. package/dist/core/index.d.ts +33 -0
  47. package/dist/core/index.js +33 -0
  48. package/dist/core/log.d.ts +21 -0
  49. package/dist/core/log.js +63 -0
  50. package/dist/core/memory-claims.d.ts +67 -0
  51. package/dist/core/memory-claims.js +164 -0
  52. package/dist/core/memory-context.d.ts +121 -0
  53. package/dist/core/memory-context.js +303 -0
  54. package/dist/core/memory-visibility.d.ts +58 -0
  55. package/dist/core/memory-visibility.js +36 -0
  56. package/dist/core/memory.d.ts +12 -0
  57. package/dist/core/memory.js +73 -0
  58. package/dist/core/metrics.d.ts +49 -0
  59. package/dist/core/metrics.js +89 -0
  60. package/dist/core/multi-hop.d.ts +116 -0
  61. package/dist/core/multi-hop.js +278 -0
  62. package/dist/core/persist.d.ts +21 -0
  63. package/dist/core/persist.js +94 -0
  64. package/dist/core/proactive.d.ts +54 -0
  65. package/dist/core/proactive.js +108 -0
  66. package/dist/core/prompt.d.ts +82 -0
  67. package/dist/core/prompt.js +164 -0
  68. package/dist/core/receipt.d.ts +107 -0
  69. package/dist/core/receipt.js +86 -0
  70. package/dist/core/retrieval.d.ts +69 -0
  71. package/dist/core/retrieval.js +260 -0
  72. package/dist/core/role-state.d.ts +16 -0
  73. package/dist/core/role-state.js +65 -0
  74. package/dist/core/runtime.d.ts +137 -0
  75. package/dist/core/runtime.js +574 -0
  76. package/dist/core/summary.d.ts +19 -0
  77. package/dist/core/summary.js +96 -0
  78. package/dist/core/text.d.ts +10 -0
  79. package/dist/core/text.js +45 -0
  80. package/dist/core/time.d.ts +22 -0
  81. package/dist/core/time.js +84 -0
  82. package/dist/core/tool-schema.d.ts +12 -0
  83. package/dist/core/tool-schema.js +92 -0
  84. package/dist/core/tools.d.ts +137 -0
  85. package/dist/core/tools.js +348 -0
  86. package/dist/core/types.d.ts +400 -0
  87. package/dist/core/types.js +1 -0
  88. package/dist/core/window.d.ts +6 -0
  89. package/dist/core/window.js +7 -0
  90. package/dist/core/workspace-node.d.ts +28 -0
  91. package/dist/core/workspace-node.js +232 -0
  92. package/dist/core/workspace.d.ts +9 -0
  93. package/dist/core/workspace.js +45 -0
  94. package/dist/host/agent-session.d.ts +279 -0
  95. package/dist/host/agent-session.js +935 -0
  96. package/dist/host/attachment-gc.d.ts +37 -0
  97. package/dist/host/attachment-gc.js +97 -0
  98. package/dist/host/calibration-samples-store.d.ts +5 -0
  99. package/dist/host/calibration-samples-store.js +67 -0
  100. package/dist/host/capabilities.d.ts +45 -0
  101. package/dist/host/capabilities.js +67 -0
  102. package/dist/host/derived-store.d.ts +36 -0
  103. package/dist/host/derived-store.js +199 -0
  104. package/dist/host/dsh-llm.d.ts +143 -0
  105. package/dist/host/dsh-llm.js +395 -0
  106. package/dist/host/event-store.d.ts +47 -0
  107. package/dist/host/event-store.js +154 -0
  108. package/dist/host/fs-atomic.d.ts +1 -0
  109. package/dist/host/fs-atomic.js +26 -0
  110. package/dist/host/im-api.d.ts +352 -0
  111. package/dist/host/im-api.js +1137 -0
  112. package/dist/host/index.d.ts +103 -0
  113. package/dist/host/index.js +453 -0
  114. package/dist/host/memory-index.d.ts +65 -0
  115. package/dist/host/memory-index.js +181 -0
  116. package/dist/host/metrics-store.d.ts +7 -0
  117. package/dist/host/metrics-store.js +104 -0
  118. package/dist/host/models.d.ts +39 -0
  119. package/dist/host/models.js +67 -0
  120. package/dist/host/persona-tools.d.ts +57 -0
  121. package/dist/host/persona-tools.js +226 -0
  122. package/dist/host/preflight.d.ts +31 -0
  123. package/dist/host/preflight.js +29 -0
  124. package/dist/host/receipt-store.d.ts +26 -0
  125. package/dist/host/receipt-store.js +68 -0
  126. package/dist/host/run-check.d.ts +51 -0
  127. package/dist/host/run-check.js +190 -0
  128. package/dist/host/state-roots.d.ts +50 -0
  129. package/dist/host/state-roots.js +163 -0
  130. package/dist/host/tool-cache.d.ts +25 -0
  131. package/dist/host/tool-cache.js +90 -0
  132. package/dist/host/tool-call-budget.d.ts +29 -0
  133. package/dist/host/tool-call-budget.js +38 -0
  134. package/dsh-plugin.json +25 -0
  135. package/lib/client.inner.cjs +3346 -0
  136. package/lib/client.js +3354 -0
  137. package/package.json +86 -6
@@ -0,0 +1,935 @@
1
+ /**
2
+ * M2.1 原生 session(实验开关,默认关):
3
+ * 一个“角色 × 群”一个 DSH 原生 agent 会话,而不是每轮临时调 `/complete`。
4
+ *
5
+ * 用到的宿主能力(都可缺省,缺省时本模块不可用、插件回退 ctx.llm):
6
+ * - `ctx.agents.create({ sessionId, meta:{cwd}, agentOptions:{provider,model} })` → `{ agent, dispose }`
7
+ * - `agent.followup(message)` + `agent.whenIdle()` + `agent.session.deriveMessages()`
8
+ * - `ctx.workspaceRegistry.archiveSession(sessionId)`:会话不进行侧栏
9
+ *
10
+ * 说明:交接文档写的是“一角色一原生 session”,这里按“角色 × 群”做隔离——
11
+ * 同一个角色在不同群共用一个原生会话会把 A 群上下文带进 B 群,违反串台约束。
12
+ */
13
+ import { randomUUID } from 'node:crypto';
14
+ import { appendFileSync, mkdirSync } from 'node:fs';
15
+ import { dirname } from 'node:path';
16
+ import { stableHash } from '../core/receipt.js';
17
+ import { BUILTIN_TOOL_GROUPS, discoverToolGroups, effectiveHostTools, inheritedToolIds, nativeCapabilityGap, personaHostToolDenial, pluginToolsForAllow, PLUGIN_TOOL_NAMES, toolLabel, } from '../core/tools.js';
18
+ import { executePersonaTool, personaToolDefinition, traceToolStep } from './persona-tools.js';
19
+ import { createToolCallBudget, toolCallLimitFromEnv } from './tool-call-budget.js';
20
+ import { createTurnToolCache } from './tool-cache.js';
21
+ const DEFAULT_NATIVE_TTL_MS = 30 * 60 * 1000;
22
+ /** 读 DSH_IM_NATIVE_TTL_MS;非法或未设置时用 30 分钟。 */
23
+ export function nativeTtlMs(raw = process.env.DSH_IM_NATIVE_TTL_MS) {
24
+ const parsed = Number(raw);
25
+ if (Number.isFinite(parsed) && parsed > 0)
26
+ return parsed;
27
+ return DEFAULT_NATIVE_TTL_MS;
28
+ }
29
+ /**
30
+ * 角色能力集不再映射成宿主工具名。
31
+ * 读/搜索/写/跑检查要等插件工具注册进 agent 之后才走原生;在那之前客户端直接回退。
32
+ * 空数组表示不调用 restrict。越权拦截靠 guard。
33
+ * DSH_IM_NATIVE_TOOL_ALLOW 非空时整表覆盖,只给排查用;guard 仍会拒绝名单以外的工具。
34
+ */
35
+ export function resolveNativeToolAllow(toolAllow) {
36
+ void toolAllow;
37
+ const env = process.env.DSH_IM_NATIVE_TOOL_ALLOW;
38
+ if (env && env.trim())
39
+ return env.split(',').map((item) => item.trim()).filter(Boolean);
40
+ return [];
41
+ }
42
+ /** 插件工具需要的角色能力。list_dir 单独处理:读或搜索都能用。 */
43
+ const PLUGIN_TOOL_CAPABILITY = {
44
+ read_file: 'read',
45
+ search_files: 'search',
46
+ write_file: 'write',
47
+ run_check: 'check',
48
+ };
49
+ export function nativeToolAllowDenial(name, toolAllow) {
50
+ // undefined 的语义是“继承主会话全部能力”,显式化,不靠隐式放行。
51
+ const allowed = toolAllow ?? inheritedToolIds();
52
+ if (name === 'list_dir') {
53
+ if (allowed.includes('read') || allowed.includes('search'))
54
+ return undefined;
55
+ return '专家角色没有「read」或「search」能力,不能使用 list_dir';
56
+ }
57
+ const capability = PLUGIN_TOOL_CAPABILITY[name];
58
+ if (!capability || allowed.includes(capability))
59
+ return undefined;
60
+ return `专家角色没有「${capability}」能力,不能使用宿主工具 ${name}`;
61
+ }
62
+ function knownGlobalTools(message) {
63
+ const marker = 'known global tools: ';
64
+ const at = message.indexOf(marker);
65
+ if (at < 0)
66
+ return [];
67
+ const rest = message.slice(at + marker.length).trim();
68
+ if (!rest || rest.startsWith('(none)'))
69
+ return [];
70
+ return rest.split(',').map((item) => item.trim()).filter(Boolean);
71
+ }
72
+ function capsFromToolNames(names) {
73
+ const caps = [];
74
+ if (names.includes('read_file'))
75
+ caps.push('read');
76
+ if (names.includes('search_files'))
77
+ caps.push('search');
78
+ if (names.includes('write_file'))
79
+ caps.push('write');
80
+ if (names.includes('run_check'))
81
+ caps.push('check');
82
+ return caps;
83
+ }
84
+ /**
85
+ * 角色能力集里,宿主上真实存在的同名工具。
86
+ * 对不上就返回空,不偷偷换成浏览器或 MCP 工具。
87
+ * 空数组表示不调用 restrict。越权拦截靠 guard,不靠这份名单。
88
+ */
89
+ export function pickNativeAllow(wanted, schemas) {
90
+ if (!schemas.length)
91
+ return wanted;
92
+ const known = new Set(schemas);
93
+ return wanted.filter((name) => known.has(name));
94
+ }
95
+ const PLUGIN_SOURCE = { kind: 'plugin', plugin: 'dsh-im' };
96
+ /** followup 用 user 才会被循环当成一轮提示词领走。plugin 来源进队但不打开步骤,whenIdle 立刻返回,messages 保持 0。 */
97
+ const TURN_SOURCE = { kind: 'user' };
98
+ function withTimeout(task, ms, onTimeout) {
99
+ return new Promise((resolve, reject) => {
100
+ const timer = setTimeout(() => {
101
+ try {
102
+ onTimeout();
103
+ }
104
+ catch { /* ignore */ }
105
+ reject(Object.assign(new Error(`原生会话 ${Math.round(ms / 1000)}s 未完成(可能在等审批)`), { code: 'NATIVE_TIMEOUT' }));
106
+ }, ms);
107
+ task.then((value) => { clearTimeout(timer); resolve(value); }, (error) => { clearTimeout(timer); reject(error); });
108
+ });
109
+ }
110
+ export function nativeSessionId(sessionKey) {
111
+ const digest = stableHash(sessionKey).split(':').at(-1) ?? '0';
112
+ return `im-${digest}`;
113
+ }
114
+ /**
115
+ * 从原生会话消息里只取**正文** block(type='text')。
116
+ * DSH 的 assistant content 会同时带 ReasoningBlock {type:'reasoning', text}(思维链),
117
+ * 之前这里“凡是有 text 字段就拼”把思维链也当回复落库/显示了;现在只认 type==='text'。
118
+ */
119
+ function messageText(content) {
120
+ if (typeof content === 'string')
121
+ return content;
122
+ if (!Array.isArray(content))
123
+ return '';
124
+ return content
125
+ .map((block) => {
126
+ if (!block || typeof block !== 'object')
127
+ return '';
128
+ const record = block;
129
+ if (record.type !== 'text')
130
+ return '';
131
+ return typeof record.text === 'string' ? record.text : '';
132
+ })
133
+ .join('');
134
+ }
135
+ export function dumpNativeDiag(line) {
136
+ try {
137
+ const causeLog = process.env.DSH_IM_NATIVE_CAUSE_LOG?.trim();
138
+ if (!causeLog)
139
+ return;
140
+ mkdirSync(dirname(causeLog), { recursive: true });
141
+ appendFileSync(causeLog, line + '\n', 'utf8');
142
+ }
143
+ catch {
144
+ // 诊断文件写失败不影响主路径。
145
+ }
146
+ }
147
+ export function describeFailure(error, depth = 0) {
148
+ if (depth > 3 || error == null)
149
+ return error == null ? undefined : String(error);
150
+ if (typeof error !== 'object')
151
+ return String(error);
152
+ const item = error;
153
+ const stack = typeof item.stack === 'string' ? item.stack.split('\n').slice(0, 5) : undefined;
154
+ return {
155
+ name: item.name,
156
+ code: item.code,
157
+ message: item.message,
158
+ ...(stack ? { stack } : {}),
159
+ ...(item.cause !== undefined ? { cause: describeFailure(item.cause, depth + 1) } : {}),
160
+ ...(item.failure !== undefined ? { failure: describeFailure(item.failure, depth + 1) } : {}),
161
+ };
162
+ }
163
+ function errorChain(payload) {
164
+ const record = payload;
165
+ const target = record?.error ?? payload;
166
+ try {
167
+ return JSON.stringify(describeFailure(target));
168
+ }
169
+ catch {
170
+ return record?.message ?? String(payload);
171
+ }
172
+ }
173
+ function summarizeEvent(payload) {
174
+ try {
175
+ return JSON.stringify(payload).slice(0, 180);
176
+ }
177
+ catch {
178
+ return String(payload).slice(0, 180);
179
+ }
180
+ }
181
+ function safeMessageCount(agent) {
182
+ try {
183
+ return agent.session.deriveMessages().length;
184
+ }
185
+ catch {
186
+ return -1;
187
+ }
188
+ }
189
+ /** 取会话里最后一条 assistant 文本(原生会话的回复来源)。 */
190
+ export function lastAssistantText(messages) {
191
+ for (let index = messages.length - 1; index >= 0; index--) {
192
+ const message = messages[index];
193
+ if (message?.role !== 'assistant')
194
+ continue;
195
+ const text = messageText(message.content).trim();
196
+ if (text)
197
+ return text;
198
+ }
199
+ return '';
200
+ }
201
+ /** 这一轮里宿主自己执行的工具(浏览器、画图)。插件工具已经在 execute 里记过,这里跳过。 */
202
+ export function hostToolSteps(messages) {
203
+ const pending = [];
204
+ const steps = [];
205
+ for (const message of messages) {
206
+ const blocks = Array.isArray(message?.content) ? message.content : [];
207
+ for (const block of blocks) {
208
+ if (!block || typeof block !== 'object')
209
+ continue;
210
+ const record = block;
211
+ if (record.type === 'tool-call' && typeof record.name === 'string') {
212
+ pending.push({ name: record.name, args: record.arguments });
213
+ }
214
+ }
215
+ if (message?.role !== 'tool' || !pending.length)
216
+ continue;
217
+ const call = pending.shift();
218
+ if (!call || PLUGIN_TOOL_NAMES.includes(call.name))
219
+ continue;
220
+ const text = messageText(message.content);
221
+ const started = Date.now();
222
+ const denied = /不能使用|没有授予|没有「/.test(text) || /^Error[::]/.test(text.trim());
223
+ steps.push(traceToolStep(steps.length + 1, call.name, call.args, text, !denied, started));
224
+ }
225
+ return steps;
226
+ }
227
+ function scopedService(ctx, name) {
228
+ if (!ctx || typeof ctx !== 'object')
229
+ return undefined;
230
+ const bag = ctx;
231
+ try {
232
+ const viaGet = typeof bag.get === 'function' ? bag.get(name) : undefined;
233
+ if (viaGet)
234
+ return viaGet;
235
+ }
236
+ catch {
237
+ // 这个作用域没有该服务。
238
+ }
239
+ const direct = ctx[name];
240
+ return direct === undefined ? undefined : direct;
241
+ }
242
+ function renderLine(line) {
243
+ const head = `[#${line.seq}]`;
244
+ if (line.kind === 'system')
245
+ return `${head}[系统] ${line.text}`;
246
+ if (line.kind === 'user')
247
+ return `${head}[用户 ${line.authorName}] ${line.text}`;
248
+ return `${head}[角色 ${line.authorName}] ${line.text}`;
249
+ }
250
+ function factsSectionText(frame) {
251
+ const lines = (frame?.factsL2 ?? []).map((line) => line.trim()).filter(Boolean);
252
+ if (!lines.length)
253
+ return '';
254
+ return [`[不可压缩事实 截止 #${frame?.factsUntilSeq ?? 0}]`, ...lines].join('\n');
255
+ }
256
+ function rememberFacts(prompt, factsText) {
257
+ const dispose = prompt.section?.({ name: 'dsh-im:facts-l2', order: 9100, text: factsText });
258
+ return typeof dispose === 'function' ? dispose : undefined;
259
+ }
260
+ function schemaNames(listed) {
261
+ if (!Array.isArray(listed))
262
+ return [];
263
+ return listed.map((item) => {
264
+ if (typeof item === 'string')
265
+ return item;
266
+ if (item && typeof item === 'object' && typeof item.name === 'string') {
267
+ return item.name;
268
+ }
269
+ return '';
270
+ }).filter(Boolean);
271
+ }
272
+ export class NativeAgentSessions {
273
+ options;
274
+ sessions = new Map();
275
+ ttlMs;
276
+ now;
277
+ lastChecks;
278
+ constructor(options) {
279
+ this.options = options;
280
+ this.ttlMs = options.ttlMs ?? nativeTtlMs();
281
+ this.now = options.now ?? Date.now;
282
+ }
283
+ status() {
284
+ const agents = this.options.agents();
285
+ if (!agents)
286
+ return { enabled: false, reason: '宿主没有 ctx.agents' };
287
+ const host = this.options.hostTools?.();
288
+ const registerReady = typeof host?.register === 'function';
289
+ const guardReady = typeof host?.guard === 'function';
290
+ // 缺注册/守卫时不半残运行:能力契约保证不了就整体回退 ctx.llm(诚实降级)。
291
+ if (this.options.executeTool && (!registerReady || !guardReady)) {
292
+ return {
293
+ enabled: false,
294
+ reason: '宿主缺少 agent 作用域的工具注册/守卫(tools.register / tools.guard),原生会话无法保证能力契约;本轮回退 ctx.llm',
295
+ };
296
+ }
297
+ const covered = Boolean(this.options.executeTool) && registerReady;
298
+ const capabilities = { read: covered, search: covered, write: covered, check: covered };
299
+ const hostToolGroups = this.discoverHostGroups().length;
300
+ if (!this.lastChecks)
301
+ return { enabled: true, capabilities, hostToolGroups };
302
+ return { enabled: true, checks: this.lastChecks, capabilities, hostToolGroups };
303
+ }
304
+ declaredGroups() {
305
+ const configured = this.options.toolGroups ?? [];
306
+ return configured.length ? [...BUILTIN_TOOL_GROUPS, ...configured] : [...BUILTIN_TOOL_GROUPS];
307
+ }
308
+ /** 宿主全局工具名(host-plane)。来源组发现、会话重建判定共用。 */
309
+ hostToolNames() {
310
+ const host = this.options.hostTools?.();
311
+ if (!host || typeof host.schemas !== 'function') {
312
+ try {
313
+ return schemaNames(host?.schemas?.());
314
+ }
315
+ catch {
316
+ return [];
317
+ }
318
+ }
319
+ try {
320
+ return schemaNames(host.schemas());
321
+ }
322
+ catch {
323
+ return [];
324
+ }
325
+ }
326
+ discoverHostGroups() {
327
+ return discoverToolGroups(this.hostToolNames(), this.declaredGroups());
328
+ }
329
+ /** 当前授权下应当生效的宿主工具 + 签名(签名变化 → 重建会话)。 */
330
+ desiredHostGrant(input) {
331
+ const names = effectiveHostTools(this.hostToolNames(), input.toolAllow, this.declaredGroups());
332
+ return { names, signature: JSON.stringify(names) };
333
+ }
334
+ /** 事实投影变了就换掉 dsh-im:facts-l2。没变不碰,避免每轮重注册。 */
335
+ refreshFacts(entry, input) {
336
+ const mount = entry.mount;
337
+ const prompt = mount?.prompt;
338
+ if (!mount || !prompt || typeof prompt.section !== 'function')
339
+ return;
340
+ const next = factsSectionText(input.frame);
341
+ if (next === (mount.factsText ?? ''))
342
+ return;
343
+ try {
344
+ mount.factsDispose?.();
345
+ }
346
+ catch { /* 旧段卸不掉就盖一层 */ }
347
+ mount.factsDispose = undefined;
348
+ mount.factsText = next;
349
+ if (!next)
350
+ return;
351
+ try {
352
+ mount.factsDispose = rememberFacts(prompt, next);
353
+ }
354
+ catch (error) {
355
+ this.options.logger?.warn?.(`[dsh-im] 更新事实段失败:${error instanceof Error ? error.message : String(error)}`);
356
+ }
357
+ }
358
+ /** 释放空闲超时的原生会话(惰性清扫,避免定时器常驻)。 */
359
+ sweep() {
360
+ const now = this.now();
361
+ for (const [key, entry] of this.sessions) {
362
+ if (now - entry.lastUsedAt < this.ttlMs)
363
+ continue;
364
+ this.sessions.delete(key);
365
+ void this.hideFromSidebar(entry.sessionId).finally(() => {
366
+ void entry.handle.dispose().catch(() => undefined);
367
+ });
368
+ }
369
+ }
370
+ async complete(input) {
371
+ const turnStartedAt = this.now();
372
+ const agents = this.options.agents();
373
+ if (!agents)
374
+ throw Object.assign(new Error('宿主没有 ctx.agents,原生会话不可用'), { code: 'NATIVE_UNAVAILABLE' });
375
+ this.sweep();
376
+ let fresh = !this.sessions.has(input.sessionKey);
377
+ let resumed = false;
378
+ let rebuilt = false;
379
+ let entry = this.sessions.get(input.sessionKey);
380
+ // 授权/来源组变了:工具可见性在 agent 创建时固定,不能原地放宽 → 重建会话。
381
+ if (entry?.mount) {
382
+ const desired = this.desiredHostGrant(input);
383
+ if (desired.signature !== entry.mount.hostSignature) {
384
+ this.options.logger?.warn?.(`[dsh-im] 原生会话授权/来源组变化,重建 key=${input.sessionKey}(旧授权工具 ${entry.mount.hostGranted.length} 个,新 ${desired.names.length} 个)`);
385
+ this.sessions.delete(input.sessionKey);
386
+ await entry.handle.dispose().catch(() => undefined);
387
+ entry = undefined;
388
+ fresh = true;
389
+ rebuilt = true;
390
+ }
391
+ }
392
+ if (!entry) {
393
+ const forceSessionId = rebuilt ? `${nativeSessionId(input.sessionKey)}-${this.now().toString(36)}` : undefined;
394
+ const created = await this.createEntry(agents, input, forceSessionId);
395
+ entry = created.entry;
396
+ resumed = created.resumed;
397
+ // 以宿主探测结果作为后续比较的规范签名(setup 内部的视图可能更窄)。
398
+ if (entry.mount)
399
+ entry.mount.hostSignature = this.desiredHostGrant(input).signature;
400
+ }
401
+ entry.lastUsedAt = this.now();
402
+ // 授权变更(插件能力勾选)走同步;宿主工具授权变更已在上面的签名比较里重建。
403
+ if (entry.toolAllow && !input.toolAllow) {
404
+ this.options.logger?.warn?.('[dsh-im] 本轮 toolAllow 缺省,原生会话从“已收窄”放宽为“继承全部”');
405
+ }
406
+ entry.toolAllow = input.toolAllow;
407
+ this.refreshFacts(entry, input);
408
+ if (entry.mount) {
409
+ entry.mount.projectRoot = input.cwd ?? entry.mount.projectRoot;
410
+ entry.mount.threadId = input.threadId ?? entry.mount.threadId;
411
+ entry.mount.memoryBudgetChars = input.memoryBudgetChars;
412
+ // 每轮重置工具调用预算(缺陷修复:原生路径单轮工具也可能失控)。
413
+ entry.mount.toolBudget = createToolCallBudget(input.maxToolCalls ?? toolCallLimitFromEnv());
414
+ entry.mount.toolExecuted = 0;
415
+ entry.mount.cache = createTurnToolCache();
416
+ entry.mount.steps = [];
417
+ if (entry.mount.tools && this.options.executeTool) {
418
+ await this.syncPersonaTools(entry.mount, input.toolAllow);
419
+ entry.allow = [...entry.mount.disposers.keys()];
420
+ }
421
+ }
422
+ const fed = this.feedText(entry, input, fresh && !resumed);
423
+ entry.feedChars.push(fed.text.length);
424
+ const handle = entry.handle;
425
+ this.options.logger?.warn?.(`[dsh-im] native turn key=${input.sessionKey} fresh=${fresh} setupCalls=${entry.setupCalls} feedLines=${fed.lines} feedChars=${fed.text.length} lastSeq=${entry.lastDeliveredSeq} allow=${entry.allow.join(',')}`);
426
+ const beforeCount = safeMessageCount(handle.agent);
427
+ this.options.logger?.warn?.(`[dsh-im] native before followup status=${handle.agent.status ?? ''} messages=${beforeCount}`);
428
+ handle.agent.followup({
429
+ // 必须给完整 user message:DSH 的 followup 不会补 role/id(缺 role 会让
430
+ // deepseek 适配器 serialize 崩成 TRANSPORT)。见 NativeUserMessage 注释。
431
+ id: randomUUID(),
432
+ role: 'user',
433
+ content: [{ type: 'text', text: fed.text }],
434
+ source: TURN_SOURCE,
435
+ });
436
+ // 原生 agent 可能要等审批/工具,不能让请求无限挂着;超时就取消并报错。
437
+ await withTimeout(handle.agent.whenIdle(), 120_000, () => {
438
+ try {
439
+ handle.agent.cancel?.('dsh-im native timeout');
440
+ }
441
+ catch { /* ignore */ }
442
+ });
443
+ const messages = handle.agent.session.deriveMessages();
444
+ this.options.logger?.warn?.(`[dsh-im] native after idle status=${handle.agent.status ?? ''} messages=${messages.length}`);
445
+ const text = lastAssistantText(messages);
446
+ const hostSteps = hostToolSteps(messages.slice(Math.max(0, beforeCount)));
447
+ if (entry.mount) {
448
+ for (const step of hostSteps) {
449
+ entry.mount.steps.push({ ...step, step: entry.mount.steps.length + 1 });
450
+ }
451
+ }
452
+ entry.lastUsedAt = this.now();
453
+ if (!text.trim()) {
454
+ const roles = messages.slice(-6).map((message) => String(message?.role ?? '?')).join(',');
455
+ const detail = entry.lastError ? `;agent 错误:${entry.lastError}` : '';
456
+ const statusDetail = entry.statusLog.length ? `;status:${entry.statusLog.join(' | ')}` : '';
457
+ const empty = new Error(`原生会话返回空内容(session ${entry.sessionId},messages=${messages.length},roles=${roles}${detail}${statusDetail})`);
458
+ dumpNativeDiag(empty.message);
459
+ throw Object.assign(empty, { code: 'NATIVE_EMPTY' });
460
+ }
461
+ const toolStats = entry.mount?.toolBudget
462
+ ? {
463
+ toolCalls: entry.mount.toolBudget.used(),
464
+ toolExecuted: entry.mount.toolExecuted ?? 0,
465
+ toolBudgetExhausted: entry.mount.toolBudget.used() >= entry.mount.toolBudget.limit,
466
+ toolCallLimit: entry.mount.toolBudget.limit,
467
+ }
468
+ : undefined;
469
+ if (toolStats && entry.mount) {
470
+ // trace 里明确记一笔:本轮工具调用统计(即使没有宿主工具步骤也要可审计)。
471
+ entry.mount.steps.push({
472
+ step: entry.mount.steps.length + 1,
473
+ kind: 'reply',
474
+ name: 'tool-budget',
475
+ result: `toolCalls=${toolStats.toolCalls} toolExecuted=${toolStats.toolExecuted} toolCallLimit=${toolStats.toolCallLimit} toolBudgetExhausted=${toolStats.toolBudgetExhausted}`,
476
+ ok: !toolStats.toolBudgetExhausted,
477
+ at: Date.now(),
478
+ ms: Date.now() - turnStartedAt,
479
+ toolCalls: toolStats.toolCalls,
480
+ toolExecuted: toolStats.toolExecuted,
481
+ toolBudgetExhausted: toolStats.toolBudgetExhausted,
482
+ });
483
+ }
484
+ return {
485
+ text,
486
+ ...(entry.mount && entry.mount.steps.length ? { trace: [...entry.mount.steps] } : {}),
487
+ ...(toolStats ? { toolStats } : {}),
488
+ };
489
+ }
490
+ /** 诊断:当前原生会话的派生消息角色与最近文本。 */
491
+ debug() {
492
+ return {
493
+ sessions: [...this.sessions.entries()].map(([sessionKey, entry]) => {
494
+ let roles = [];
495
+ let lastText = '';
496
+ try {
497
+ const messages = entry.handle.agent.session.deriveMessages();
498
+ roles = messages.slice(-8).map((message) => String(message?.role ?? '?'));
499
+ lastText = lastAssistantText(messages).slice(0, 200);
500
+ }
501
+ catch {
502
+ // debug 尽力而为
503
+ }
504
+ return {
505
+ sessionKey,
506
+ sessionId: entry.sessionId,
507
+ ...(entry.lastError ? { lastError: entry.lastError } : {}),
508
+ roles,
509
+ lastText,
510
+ setupCalls: entry.setupCalls,
511
+ lastDeliveredSeq: entry.lastDeliveredSeq,
512
+ feedChars: [...entry.feedChars],
513
+ allow: [...entry.allow],
514
+ schemas: [...entry.schemas],
515
+ ...(entry.mount ? { hostGranted: [...entry.mount.hostGranted] } : {}),
516
+ ...(entry.mount ? { toolGroups: entry.mount.groups.map((group) => group.id) } : {}),
517
+ ...(entry.toolAllow ? { toolAllow: [...entry.toolAllow] } : {}),
518
+ };
519
+ }),
520
+ };
521
+ }
522
+ /** 按当前授权注册插件工具,并卸掉这次没勾的。宿主工具按来源组授权收窄可见性,guard 再兜一层。 */
523
+ async syncPersonaTools(mount, toolAllow) {
524
+ const executeTool = this.options.executeTool;
525
+ if (!executeTool)
526
+ return;
527
+ const tools = mount.tools;
528
+ const wanted = pluginToolsForAllow(toolAllow);
529
+ const wantedSet = new Set(wanted);
530
+ for (const [name, dispose] of mount.disposers) {
531
+ if (wantedSet.has(name))
532
+ continue;
533
+ try {
534
+ await dispose();
535
+ }
536
+ catch { /* 卸不掉时 guard 仍会拒绝 */ }
537
+ mount.disposers.delete(name);
538
+ }
539
+ if (wanted.length && typeof tools?.register !== 'function') {
540
+ const labels = nativeCapabilityGap(toolAllow, []).map(toolLabel).join('、');
541
+ throw Object.assign(new Error(`原生会话还没挂上这些能力:${labels}。本轮应走兼容路径。`), { status: 409 });
542
+ }
543
+ if (tools && !mount.hostSignature)
544
+ await this.hideHostTools(mount, tools, mount.scope, toolAllow);
545
+ for (const name of wanted) {
546
+ if (mount.disposers.has(name) || !tools?.register)
547
+ continue;
548
+ try {
549
+ const dispose = await tools.register(personaToolDefinition(name, async (args) => {
550
+ const started = Date.now();
551
+ const grant = mount.toolBudget?.tryReserve();
552
+ if (grant && !grant.ok) {
553
+ // 到上限:明确拒绝并让 agent 停止调工具、直接作答(不是静默丢弃)。
554
+ mount.steps.push(traceToolStep(mount.steps.length + 1, name, args, grant.message, false, started));
555
+ this.options.logger?.warn?.(`[dsh-im] native 工具调用到上限:${grant.message}`);
556
+ return grant.message;
557
+ }
558
+ const text = await executeTool({
559
+ name,
560
+ args: args ?? {},
561
+ projectRoot: mount.projectRoot,
562
+ threadId: mount.threadId,
563
+ ...(mount.personaId ? { personaId: mount.personaId } : {}),
564
+ ...(mount.memoryBudgetChars === undefined ? {} : { budgetChars: mount.memoryBudgetChars }),
565
+ cache: mount.cache,
566
+ });
567
+ mount.toolExecuted = (mount.toolExecuted ?? 0) + 1;
568
+ mount.steps.push(traceToolStep(mount.steps.length + 1, name, args, text, true, started));
569
+ return text;
570
+ }));
571
+ mount.disposers.set(name, typeof dispose === 'function' ? dispose : () => undefined);
572
+ }
573
+ catch (error) {
574
+ const message = error instanceof Error ? error.message : String(error);
575
+ if (/already registered/i.test(message)) {
576
+ mount.disposers.set(name, () => undefined);
577
+ continue;
578
+ }
579
+ const labels = nativeCapabilityGap(toolAllow, capsFromToolNames([...mount.disposers.keys()])).map(toolLabel).join('、');
580
+ throw Object.assign(new Error(`原生会话还没挂上这些能力:${labels || toolLabel(name)}。本轮应走兼容路径。`), { status: 409 });
581
+ }
582
+ }
583
+ mount.covered = capsFromToolNames([...mount.disposers.keys()]);
584
+ if (typeof tools?.schemas === 'function') {
585
+ try {
586
+ mount.visible = schemaNames(tools.schemas(mount.scope));
587
+ }
588
+ catch {
589
+ mount.visible = [...mount.disposers.keys()];
590
+ }
591
+ }
592
+ else {
593
+ mount.visible = [...mount.disposers.keys()];
594
+ }
595
+ }
596
+ /**
597
+ * 按来源组授权收窄宿主工具可见性:
598
+ * - 被授予的组/单工具保留;
599
+ * - 其余全部 restrict deny(restrict 只挡继承工具,own-scope 注入的工具由 guard 兜);
600
+ * - 同时记录 hostGranted 签名,授权变化时由 complete() 重建会话。
601
+ */
602
+ async hideHostTools(mount, tools, scope, toolAllow) {
603
+ if (typeof tools.schemas !== 'function' || typeof tools.restrict !== 'function')
604
+ return;
605
+ const read = () => {
606
+ try {
607
+ return schemaNames(tools.schemas?.(scope));
608
+ }
609
+ catch {
610
+ return [];
611
+ }
612
+ };
613
+ const before = read();
614
+ const declared = mount.declared;
615
+ const hostBefore = before.filter((name) => !PLUGIN_TOOL_NAMES.includes(name));
616
+ const granted = effectiveHostTools(hostBefore, toolAllow, declared);
617
+ const grantedSet = new Set(granted);
618
+ mount.groups = discoverToolGroups(hostBefore, declared);
619
+ mount.hostGranted = granted;
620
+ mount.hostSignature = JSON.stringify(granted);
621
+ const hidden = hostBefore.filter((name) => !grantedSet.has(name));
622
+ let errorMessage = '';
623
+ if (hidden.length) {
624
+ try {
625
+ await tools.restrict({ deny: hidden });
626
+ }
627
+ catch (error) {
628
+ errorMessage = error instanceof Error ? error.message : String(error);
629
+ const known = knownGlobalTools(errorMessage).filter((name) => hidden.includes(name));
630
+ if (known.length) {
631
+ try {
632
+ await tools.restrict({ deny: known });
633
+ errorMessage = '';
634
+ }
635
+ catch (again) {
636
+ errorMessage = again instanceof Error ? again.message : String(again);
637
+ }
638
+ }
639
+ }
640
+ }
641
+ await Promise.resolve();
642
+ const after = read();
643
+ dumpNativeDiag(JSON.stringify({
644
+ at: Date.now(),
645
+ before: before.length,
646
+ after: after.length,
647
+ granted,
648
+ hiddenCount: hidden.length,
649
+ groups: mount.groups.map((group) => `${group.id}(${group.tools.length})`),
650
+ hostLeft: after.filter((name) => !PLUGIN_TOOL_NAMES.includes(name)).slice(0, 12),
651
+ error: errorMessage.slice(0, 500),
652
+ }));
653
+ if (errorMessage) {
654
+ this.options.logger?.warn?.(`[dsh-im] 隐藏未授权宿主工具失败,改由 guard 拒绝:${errorMessage}`);
655
+ }
656
+ }
657
+ /** 有 frame 且系统提示词已注册时只喂增量;否则整段投喂(旧调用 / 宿主没有 systemPrompt)。 */
658
+ feedText(entry, input, fresh) {
659
+ const whole = [input.system?.trim(), input.prompt?.trim()].filter(Boolean).join('\n\n');
660
+ const windowLines = input.frame?.windowLines ?? [];
661
+ if (!input.frame || entry.fullFeed)
662
+ return { text: whole, lines: whole ? whole.split('\n').length : 0 };
663
+ const selfName = input.personaName ?? '';
664
+ const unseen = (line) => fresh || line.seq > entry.lastDeliveredSeq;
665
+ const notSelf = (line) => line.authorName !== selfName;
666
+ const lines = windowLines.filter(notSelf).filter(unseen);
667
+ const current = input.frame.currentLine;
668
+ const includeCurrent = Boolean(current && notSelf(current) && !lines.some((line) => line.seq === current.seq));
669
+ const memoryBlock = input.frame?.memoryBlock?.trim();
670
+ // 双层窗口:L1 摘要 + 冷区章节目录按"本轮用户文本"追加(只在记忆层 on 时由 runtime 填)。
671
+ const contextBlock = input.frame?.contextBlock?.trim();
672
+ const rendered = [
673
+ ...lines.map(renderLine),
674
+ ...(includeCurrent && current ? [renderLine(current)] : []),
675
+ ...(memoryBlock ? [memoryBlock] : []),
676
+ ...(contextBlock ? [contextBlock] : []),
677
+ ];
678
+ const seqs = lines.map((line) => line.seq);
679
+ if (includeCurrent && current)
680
+ seqs.push(current.seq);
681
+ if (seqs.length)
682
+ entry.lastDeliveredSeq = Math.max(entry.lastDeliveredSeq, ...seqs);
683
+ return { text: rendered.join('\n'), lines: rendered.length };
684
+ }
685
+ async createEntry(agents, input, forceSessionId) {
686
+ let sessionId = forceSessionId ?? input.sessionIdOverride?.trim() ?? nativeSessionId(input.sessionKey);
687
+ let entry;
688
+ let setupCalls = 0;
689
+ let fullFeed = false;
690
+ let allow = [];
691
+ let schemas = [];
692
+ let resumed = false;
693
+ let guarded = false;
694
+ const declared = this.declaredGroups();
695
+ const mount = {
696
+ disposers: new Map(),
697
+ projectRoot: input.cwd ?? '',
698
+ threadId: input.threadId ?? 'im',
699
+ // 会话归属是「角色×群」:sessionKey = personaId:threadId,缺 personaId 时从这里推。
700
+ ...(input.personaId ?? (input.sessionKey ? String(input.sessionKey).split(':')[0] : '')
701
+ ? { personaId: input.personaId ?? String(input.sessionKey).split(':')[0] }
702
+ : {}),
703
+ cache: createTurnToolCache(),
704
+ steps: [],
705
+ covered: [],
706
+ declared,
707
+ groups: [],
708
+ hostGranted: [],
709
+ hostSignature: '',
710
+ };
711
+ const setup = async (agentCtx) => {
712
+ try {
713
+ const ctx = agentCtx;
714
+ ctx.on?.('agent/status', (payload) => {
715
+ const status = payload && typeof payload === 'object' && 'status' in payload
716
+ ? String(payload.status)
717
+ : summarizeEvent(payload);
718
+ const line = `${Date.now()} ${status}`;
719
+ if (entry)
720
+ entry.statusLog.push(line);
721
+ this.options.logger?.warn?.(`[dsh-im] native agent/status ${line}`);
722
+ });
723
+ ctx.on?.('agent/created', (payload) => {
724
+ this.options.logger?.warn?.(`[dsh-im] native agent/created ${summarizeEvent(payload)}`);
725
+ });
726
+ const remember = (payload) => {
727
+ if (!entry)
728
+ return;
729
+ entry.lastError = errorChain(payload).slice(0, 4000);
730
+ this.options.logger?.warn?.(`[dsh-im] native agent error ${entry.lastError}`);
731
+ };
732
+ ctx.on?.('agent/request-error', remember);
733
+ ctx.on?.('agent/error', remember);
734
+ }
735
+ catch {
736
+ // 版本不支持该事件时忽略。
737
+ }
738
+ const mode = input.setupMode ?? 'all';
739
+ const prompt = scopedService(agentCtx, 'systemPrompt');
740
+ const factsText = factsSectionText(input.frame);
741
+ if (mode === 'restrict' || mode === 'bcdp' || mode === 'mcp') {
742
+ // 这一刀不注册段。
743
+ }
744
+ else if (prompt && typeof prompt.section === 'function') {
745
+ mount.prompt = prompt;
746
+ prompt.section({ name: 'dsh-im:persona', order: 9000, text: input.system?.trim() ?? '' });
747
+ mount.factsText = factsText;
748
+ if (factsText)
749
+ mount.factsDispose = rememberFacts(prompt, factsText);
750
+ setupCalls += 1;
751
+ }
752
+ else {
753
+ fullFeed = true;
754
+ this.options.logger?.warn?.('[dsh-im] 宿主无 systemPrompt 服务,原生会话退回整段投喂');
755
+ }
756
+ const tools = scopedService(agentCtx, 'tools');
757
+ if (tools && typeof tools.guard === 'function') {
758
+ tools.guard((exec) => {
759
+ const name = typeof exec?.name === 'string' ? exec.name : '';
760
+ const current = entry ? entry.toolAllow : input.toolAllow;
761
+ return personaHostToolDenial(name, current, declared) ?? nativeToolAllowDenial(name, current);
762
+ });
763
+ guarded = true;
764
+ }
765
+ if (this.options.executeTool && mode === 'all') {
766
+ mount.tools = tools;
767
+ mount.scope = agentCtx;
768
+ await this.syncPersonaTools(mount, input.toolAllow);
769
+ allow = [...mount.disposers.keys()];
770
+ schemas = mount.visible ?? allow;
771
+ }
772
+ else {
773
+ const wanted = resolveNativeToolAllow(input.toolAllow);
774
+ if (tools && typeof tools.schemas === 'function') {
775
+ try {
776
+ schemas = schemaNames(tools.schemas(agentCtx));
777
+ }
778
+ catch {
779
+ schemas = [];
780
+ }
781
+ }
782
+ if (mode === 'bcdp')
783
+ allow = schemas.includes('bcdp_help') || !schemas.length ? ['bcdp_help'] : [];
784
+ else if (mode === 'mcp')
785
+ allow = schemas.includes('read_mcp_resource') || !schemas.length ? ['read_mcp_resource'] : [];
786
+ else
787
+ allow = pickNativeAllow(wanted, schemas);
788
+ if (mode === 'sections')
789
+ allow = [];
790
+ const missing = wanted.filter((name) => schemas.length > 0 && !allow.includes(name));
791
+ if (missing.length) {
792
+ this.options.logger?.warn?.(`[dsh-im] 宿主没有这些工具,已从白名单去掉:${missing.join(',')};可见:${schemas.join(',')}`);
793
+ }
794
+ if (tools && typeof tools.restrict === 'function' && allow.length) {
795
+ await tools.restrict({ allow });
796
+ if (typeof tools.schemas === 'function') {
797
+ try {
798
+ // schemas(scope) 省略 scope 时是全局视图,看不到这次 restrict。用服务自己的 ctx。
799
+ const scope = tools.ctx ?? agentCtx;
800
+ const visible = schemaNames(tools.schemas(scope));
801
+ const narrowed = visible.filter((name) => allow.includes(name));
802
+ if (narrowed.length)
803
+ schemas = narrowed;
804
+ }
805
+ catch { /* 保留收窄前的名单 */ }
806
+ }
807
+ }
808
+ else if (!allow.length) {
809
+ this.options.logger?.warn?.('[dsh-im] 原生工具白名单为空,不调用 restrict');
810
+ }
811
+ }
812
+ };
813
+ const mode = input.setupMode ?? 'all';
814
+ const createOptions = {
815
+ sessionId,
816
+ meta: input.cwd ? { cwd: input.cwd } : {},
817
+ agentOptions: {
818
+ provider: input.provider,
819
+ model: input.model,
820
+ ...(input.maxTokens ? { maxTokens: input.maxTokens } : {}),
821
+ ...(input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}),
822
+ },
823
+ ...(mode === 'off' ? {} : { setup }),
824
+ };
825
+ let handle;
826
+ try {
827
+ handle = await agents.create(createOptions);
828
+ }
829
+ catch (error) {
830
+ const message = error instanceof Error ? error.message : String(error);
831
+ if (!/already exists/i.test(message))
832
+ throw error;
833
+ setupCalls = 0;
834
+ fullFeed = false;
835
+ allow = [];
836
+ schemas = [];
837
+ if (typeof agents.resume === 'function') {
838
+ try {
839
+ handle = await agents.resume(createOptions);
840
+ resumed = true;
841
+ }
842
+ catch (resumeError) {
843
+ this.options.logger?.warn?.(`[dsh-im] resume native session failed: ${resumeError instanceof Error ? resumeError.message : String(resumeError)}`);
844
+ }
845
+ }
846
+ if (!resumed) {
847
+ sessionId = `${nativeSessionId(input.sessionKey)}-${this.now().toString(36)}`;
848
+ handle = await agents.create({ ...createOptions, sessionId });
849
+ }
850
+ }
851
+ if (!handle)
852
+ throw new Error('原生会话没有创建出来');
853
+ // 默认不在 create 后归档:归档写入会把紧接着的第一步收成 blocked。
854
+ // DSH_IM_NATIVE_ARCHIVE=live 时用 stopActivity:false 试「隐藏但不停驱动」。
855
+ if (process.env.DSH_IM_NATIVE_ARCHIVE === 'live') {
856
+ await this.hideFromSidebar(sessionId, false);
857
+ }
858
+ const windowLines = input.frame?.windowLines ?? [];
859
+ const priorSeq = resumed && windowLines.length
860
+ ? Math.max(...windowLines.map((line) => line.seq))
861
+ : 0;
862
+ entry = {
863
+ handle,
864
+ sessionId,
865
+ lastUsedAt: this.now(),
866
+ lastDeliveredSeq: priorSeq,
867
+ setupCalls,
868
+ feedChars: [],
869
+ statusLog: [],
870
+ allow,
871
+ schemas,
872
+ fullFeed,
873
+ toolAllow: input.toolAllow,
874
+ mount,
875
+ };
876
+ this.lastChecks = {
877
+ promptSection: setupCalls > 0,
878
+ toolRestricted: mount.hostGranted.length > 0 || allow.length > 0,
879
+ guard: guarded,
880
+ allow: [...allow, ...mount.hostGranted.map((name) => `tool:${name}`)],
881
+ };
882
+ this.sessions.set(input.sessionKey, entry);
883
+ return { entry, resumed };
884
+ }
885
+ /** 插件卸载/重载时释放全部原生会话。释放时才归档,避免活会话被归档门禁挡住。 */
886
+ async disposeAll() {
887
+ const entries = [...this.sessions.values()];
888
+ this.sessions.clear();
889
+ await Promise.all(entries.map(async (entry) => {
890
+ await this.hideFromSidebar(entry.sessionId);
891
+ await entry.handle.dispose().catch(() => undefined);
892
+ }));
893
+ }
894
+ async hideFromSidebar(sessionId, stopActivity = false) {
895
+ try {
896
+ const workspace = this.options.workspace?.();
897
+ const archive = workspace?.archiveSession;
898
+ if (!archive)
899
+ return;
900
+ await archive.call(workspace, sessionId, { stopActivity });
901
+ }
902
+ catch (error) {
903
+ const message = error instanceof Error ? error.message : String(error);
904
+ this.options.logger?.warn?.(`[dsh-im] archive native session failed: ${message}`);
905
+ dumpNativeDiag(JSON.stringify({ at: Date.now(), archive: message, stopActivity, sessionId }));
906
+ }
907
+ }
908
+ /** 测试/调试:当前活着的原生会话。 */
909
+ liveSessionIds() {
910
+ return [...this.sessions.values()].map((entry) => entry.sessionId);
911
+ }
912
+ }
913
+ /** host 侧组装:从 ctx 里拿 agents/workspaceRegistry;未启用或宿主缺 agents 时返回 undefined。 */
914
+ export function createNativeRuntime(options) {
915
+ if (!options.enabled)
916
+ return { disposeAll: async () => undefined };
917
+ const sessions = new NativeAgentSessions({
918
+ agents: options.agents,
919
+ workspace: options.workspace,
920
+ logger: options.logger,
921
+ ttlMs: options.ttlMs ?? nativeTtlMs(),
922
+ now: options.now,
923
+ executeTool: (call) => executePersonaTool(call),
924
+ ...(options.hostTools ? { hostTools: options.hostTools } : {}),
925
+ ...(options.toolGroups ? { toolGroups: options.toolGroups } : {}),
926
+ });
927
+ return {
928
+ bridge: {
929
+ status: () => sessions.status(),
930
+ complete: (input) => sessions.complete(input),
931
+ debug: () => sessions.debug(),
932
+ },
933
+ disposeAll: () => sessions.disposeAll(),
934
+ };
935
+ }