@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,1137 @@
1
+ import { toolsForAllow } from '../core/tool-schema.js';
2
+ import { normalizeToolAllow, parseGrant } from '../core/tools.js';
3
+ import { parseState } from '../core/persist.js';
4
+ import { logWarn } from '../core/log.js';
5
+ import { stat } from 'node:fs/promises';
6
+ import { join } from 'node:path';
7
+ import { assertSafeThreadId, loadState, nodeSink, readGroupBuffer, writeGroupBuffer, saveState, } from '../core/workspace-node.js';
8
+ import { completeDshChat, listDshModels, modelContextWindow } from './dsh-llm.js';
9
+ import { preflightMembers } from './preflight.js';
10
+ import { appendIntent, appendOutcome } from './receipt-store.js';
11
+ import { createIntent } from '../core/receipt.js';
12
+ import { executePersonaTool } from './persona-tools.js';
13
+ import { parseCatalogModelId, resolveModelBinding } from './models.js';
14
+ import { appendMetrics } from './metrics-store.js';
15
+ import { gcAttachments, MIN_GC_AGE_MS } from './attachment-gc.js';
16
+ import { createTurnToolCache } from './tool-cache.js';
17
+ import { describeFailure, dumpNativeDiag } from './agent-session.js';
18
+ import { defaultRootsFile, listStateRoots, readKnownRoots, recordKnownRoot } from './state-roots.js';
19
+ import { detectHostCapabilities, usageKeysInChunk } from './capabilities.js';
20
+ import { budgetViewOf, groupBudgetForThread, groupBudgetSignature, groupEntriesForThread, } from '../core/context-budget.js';
21
+ import { appendCalibrationSample, readCalibrationSamples } from './calibration-samples-store.js';
22
+ import { buildSample } from '../core/calibration-samples.js';
23
+ import { buildCalibrationReport } from '../core/calibrator.js';
24
+ import { planBudget } from '../core/budget-plan.js';
25
+ import { buildMemoryIndex } from './memory-index.js';
26
+ const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
27
+ const MAX_FILE_BYTES = 20 * 1024 * 1024;
28
+ const MAX_INLINE_TEXT = 20_000;
29
+ const TEXT_EXTENSIONS = new Set([
30
+ 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'json', 'md', 'txt', 'css', 'scss',
31
+ 'yml', 'yaml', 'toml', 'py', 'go', 'rs', 'java', 'sh', 'ps1', 'csv', 'log', 'xml', 'html',
32
+ ]);
33
+ function safeAttachmentName(name) {
34
+ const base = name.replace(/[^\w.\-\u4e00-\u9fa5]/g, '_').replace(/^\.+/, '');
35
+ if (!base)
36
+ return 'attachment';
37
+ const dot = base.lastIndexOf('.');
38
+ // 保留扩展名:长文件名只截主体,不能把 .png/.ts 截掉(否则回读 mediaType 会变 octet-stream)。
39
+ if (dot > 0 && dot < base.length - 1) {
40
+ const ext = base.slice(dot, dot + 12);
41
+ return base.slice(0, Math.max(1, 80 - ext.length)) + ext;
42
+ }
43
+ return base.slice(0, 80);
44
+ }
45
+ /** 文本预览:先排除 NUL(二进制),再按 UTF-8 解码并去掉被字节截断留下的替换字符。 */
46
+ function inlineTextPreview(data) {
47
+ const head = data.subarray(0, Math.min(data.length, 16 * 1024));
48
+ if (head.includes(0))
49
+ return undefined;
50
+ const slice = data.subarray(0, Math.min(data.length, MAX_INLINE_TEXT * 4 + 4));
51
+ const truncated = slice.length < data.length;
52
+ // 前半段查 NUL 判二进制(取舍:只看前 16KB,大文件后半段可能是二进制)。
53
+ const text = new TextDecoder('utf-8', { fatal: false }).decode(slice);
54
+ // 只在本轮确实截断时才剥尾部 U+FFFD;正文本来就有替换字符时不能吞。
55
+ const cleaned = truncated ? text.replace(/\uFFFD+$/, '') : text;
56
+ return Array.from(cleaned).slice(0, MAX_INLINE_TEXT).join('');
57
+ }
58
+ function mediaTypeFor(name, declared) {
59
+ if (declared?.trim())
60
+ return declared.trim();
61
+ const ext = name.split('.').pop()?.toLowerCase() ?? '';
62
+ if (['png'].includes(ext))
63
+ return 'image/png';
64
+ if (['jpg', 'jpeg'].includes(ext))
65
+ return 'image/jpeg';
66
+ if (ext === 'webp')
67
+ return 'image/webp';
68
+ if (ext === 'gif')
69
+ return 'image/gif';
70
+ if (['md', 'txt', 'log', 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'css', 'scss', 'yml', 'yaml', 'toml', 'py', 'go', 'rs', 'java', 'sh', 'ps1', 'csv', 'xml', 'html'].includes(ext))
71
+ return 'text/plain';
72
+ if (ext === 'json')
73
+ return 'application/json';
74
+ return 'application/octet-stream';
75
+ }
76
+ function isTextLike(name, mediaType) {
77
+ if (mediaType.startsWith('text/'))
78
+ return true;
79
+ if (['application/json', 'application/xml'].includes(mediaType))
80
+ return true;
81
+ const ext = name.split('.').pop()?.toLowerCase() ?? '';
82
+ return TEXT_EXTENSIONS.has(ext);
83
+ }
84
+ /** 内容嗅探:声明/扩展名说是图片、实际不是时降级为文件(不当安全边界,只做校正常识)。 */
85
+ function sniffMediaType(data) {
86
+ const bytes = (offset, length) => String.fromCharCode(...data.subarray(offset, offset + length));
87
+ const starts = (...sig) => sig.every((value, index) => data[index] === value);
88
+ if (starts(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a))
89
+ return 'image/png';
90
+ if (starts(0xff, 0xd8, 0xff))
91
+ return 'image/jpeg';
92
+ if (starts(0x47, 0x49, 0x46, 0x38))
93
+ return 'image/gif';
94
+ if (data.length > 11 && bytes(0, 4) === 'RIFF' && bytes(8, 4) === 'WEBP')
95
+ return 'image/webp';
96
+ if (starts(0x25, 0x50, 0x44, 0x46))
97
+ return 'application/pdf';
98
+ if (starts(0x50, 0x4b, 0x03, 0x04))
99
+ return 'application/zip';
100
+ return undefined;
101
+ }
102
+ let warnedMissingAttachmentStore = false;
103
+ /** store 为空时可选链不会抛,也不会进 catch。整个进程只警告一次。 */
104
+ function warnMissingAttachmentStore() {
105
+ if (warnedMissingAttachmentStore)
106
+ return;
107
+ warnedMissingAttachmentStore = true;
108
+ logWarn('[dsh-im] ctx.attachments 取不到,图片只能本地预览,模型看不到内容');
109
+ }
110
+ /** 没有宿主模型服务时的统一错误:明确告诉调用方要去 DSH 里跑。 */
111
+ function noLlmService() {
112
+ return Object.assign(new Error('DSH 模型服务未就绪:插件必须在 DSH 宿主里运行'), { status: 503 });
113
+ }
114
+ export function createImApi(deps) {
115
+ /** 根去重键:Windows 大小写不敏感;其它平台保留大小写(大小写敏感盘上是两个真目录)。 */
116
+ /** toolAllow 来自客户端 JSON:数组以外的形状直接 400,非法授权条目也 400(不静默吞)。 */
117
+ const assertToolAllowShape = (value) => {
118
+ if (value !== undefined && !Array.isArray(value)) {
119
+ throw Object.assign(new Error('toolAllow 必须是字符串数组'), { status: 400 });
120
+ }
121
+ if (!Array.isArray(value))
122
+ return;
123
+ const bad = value.filter((entry) => typeof entry !== 'string' || parseGrant(entry) === null);
124
+ if (bad.length) {
125
+ throw Object.assign(new Error(`toolAllow 含非法授权条目:${bad.map((entry) => String(entry)).join('、')}`), { status: 400 });
126
+ }
127
+ };
128
+ const rootKey = (path) => {
129
+ const normalized = path.replaceAll('\\', '/').replace(/\/+$/, '');
130
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
131
+ };
132
+ /** 客户端透传的预算快照:结构化、不含正文;形状不对一律丢弃(审计字段不能是可信输入)。 */
133
+ const budgetReceiptOf = (body) => {
134
+ const value = body.budget;
135
+ if (!value || typeof value !== 'object')
136
+ return undefined;
137
+ const numbers = ['windowChars', 'summaryChars', 'digestChars', 'chapterChars', 'memoryChars', 'tokens', 'ratio'];
138
+ for (const key of numbers) {
139
+ const raw = value[key];
140
+ if (raw === null)
141
+ continue;
142
+ if (typeof raw !== 'number' || !Number.isFinite(raw))
143
+ return undefined;
144
+ }
145
+ if (typeof value.tier !== 'string' || typeof value.signature !== 'string')
146
+ return undefined;
147
+ if (typeof value.source !== 'string' || typeof value.version !== 'string')
148
+ return undefined;
149
+ return value;
150
+ };
151
+ /** 客户端透传的预算变更事件:只在显式输入变化时出现;形状不对一律丢弃。 */
152
+ const budgetChangedOf = (body) => {
153
+ const value = body.budgetChanged;
154
+ if (!value || typeof value !== 'object' || !value.from || !value.to)
155
+ return undefined;
156
+ if (typeof value.reason !== 'string')
157
+ return undefined;
158
+ return value;
159
+ };
160
+ /** 客户端透传的句柄协议回执:结构化、无正文;形状不对一律丢弃(审计字段不能是可信输入)。 */
161
+ const memoryReceiptOf = (body) => {
162
+ const value = body.memoryContext;
163
+ if (!value || typeof value !== 'object')
164
+ return undefined;
165
+ if (!Array.isArray(value.snippetSeqs) || !Array.isArray(value.handleSeqs))
166
+ return undefined;
167
+ if (!Array.isArray(value.segmentIds) || !Array.isArray(value.backpressure))
168
+ return undefined;
169
+ return value;
170
+ };
171
+ /** 模型窗口缓存:同一 (provider,model) 只向宿主 resolveModelInfo 查一次(含失败缓存,防抖动)。 */
172
+ const modelWindowCache = new Map();
173
+ async function cachedModelWindow(llm, provider, model) {
174
+ const key = `${provider}::${model}`;
175
+ if (modelWindowCache.has(key))
176
+ return modelWindowCache.get(key) ?? undefined;
177
+ const window = await modelContextWindow(llm, provider, model);
178
+ modelWindowCache.set(key, window ?? null);
179
+ return window;
180
+ }
181
+ /**
182
+ * 本轮工具执行的群级预算(缺陷修复:`/api/im/complete` 直调时请求里没有 budget,
183
+ * 旧逻辑让多跳展开退化成 fallback=600;现在 host 自己从**请求/状态**推导)。
184
+ *
185
+ * 优先级:请求里的 `budget.windowChars`(客户端已算好)> 显式 `memoryBudgetChars/budgetChars`
186
+ * > 从数据根 state + 成员模型窗口现算 > undefined(才允许 fallback,且执行器会显式标注)。
187
+ */
188
+ async function resolveTurnBudget(input) {
189
+ const receipt = budgetReceiptOf(input.body);
190
+ if (receipt && typeof receipt.windowChars === 'number' && receipt.windowChars > 0) {
191
+ return { chars: receipt.windowChars, receipt };
192
+ }
193
+ const direct = [input.body.memoryBudgetChars, input.body.budgetChars]
194
+ .find((value) => typeof value === 'number' && Number.isFinite(value) && value > 0);
195
+ if (direct !== undefined)
196
+ return { chars: direct };
197
+ try {
198
+ const state = await loadState(input.projectRoot);
199
+ const thread = state?.threads.find((item) => item.id === input.threadId);
200
+ if (!state || !thread)
201
+ return {};
202
+ const personas = new Map(state.personas.map((persona) => [persona.id, persona]));
203
+ const windows = new Map();
204
+ await Promise.all([...new Set(thread.members.map((member) => member.personaId))]
205
+ .map(async (personaId) => {
206
+ const persona = personas.get(personaId);
207
+ if (!persona?.model)
208
+ return;
209
+ const parsed = parseCatalogModelId(persona.model, persona.provider);
210
+ if (!parsed?.model)
211
+ return;
212
+ const window = await cachedModelWindow(input.llm, parsed.route || persona.provider || '', parsed.model);
213
+ if (typeof window === 'number' && window > 0)
214
+ windows.set(personaId, window);
215
+ }));
216
+ const tier = input.body.budgetTier ?? 'standard';
217
+ const policy = {
218
+ tier,
219
+ contextWindowForPersona: (personaId) => windows.get(personaId),
220
+ modelForPersona: (personaId) => personas.get(personaId)?.model,
221
+ };
222
+ const group = groupBudgetForThread(thread, policy);
223
+ if (!group)
224
+ return {};
225
+ const entries = groupEntriesForThread(thread, policy);
226
+ return {
227
+ chars: group.windowChars,
228
+ receipt: budgetViewOf(group, { tier, signature: groupBudgetSignature(entries, tier) }),
229
+ };
230
+ }
231
+ catch {
232
+ // 推导失败只意味着"预算不可得":执行器会走 fallback 并在输出里显式标注,不是静默降级。
233
+ return {};
234
+ }
235
+ }
236
+ /**
237
+ * 「用过的数据根」缓存(key → 原始路径)。
238
+ *
239
+ * 这是 2026-11-02 P0「团队数据没了」的除根点:以前授权白名单只有 DSH 工作区注册表,
240
+ * DSH 重建/重装工作区表后,数据还在盘上但面板一律 400。现在白名单 =
241
+ * 当前工作区 + 已注册工作区 + 用过的数据根 —— 后者存在 `~/.dsh-im/known-roots.json`,
242
+ * 不随工作区变化。**只收「目录还在、且确实是 dsh-im 数据根(有 .dsh-im/)」的根**:
243
+ * 已删除/从来没写过的路径不进白名单,避免把「数据不在」伪装成「空数据」。
244
+ */
245
+ const knownRoots = new Map();
246
+ let knownRootsLoaded = false;
247
+ let knownRootsLoading;
248
+ /** Phase 0:真实流式调用里观察到的 usage 字段路径(没有观察过就是空)。 */
249
+ const observedUsageKeys = [];
250
+ const rootsFileOf = () => deps.rootsFile?.() ?? defaultRootsFile();
251
+ async function loadKnownRoots() {
252
+ if (knownRootsLoaded)
253
+ return;
254
+ knownRootsLoading ??= (async () => {
255
+ try {
256
+ const list = await readKnownRoots(rootsFileOf());
257
+ for (const path of list) {
258
+ const key = rootKey(path);
259
+ if (knownRoots.has(key))
260
+ continue;
261
+ try {
262
+ await stat(join(path, '.dsh-im'));
263
+ knownRoots.set(key, path);
264
+ }
265
+ catch {
266
+ // 目录已不存在 / 不是数据根:不进白名单(继续走 400,宁可报错也不静默给空数据)。
267
+ }
268
+ }
269
+ }
270
+ catch {
271
+ // 记忆文件读不到就当没有历史根:授权退回注册表(不是错误)。
272
+ }
273
+ knownRootsLoaded = true;
274
+ })();
275
+ return knownRootsLoading;
276
+ }
277
+ /** 成功读写后记住这个根:内存立刻生效(本次会话后续请求可用),落盘异步且不阻塞主流程。 */
278
+ function rememberRoot(root) {
279
+ knownRoots.set(rootKey(root), root);
280
+ void recordKnownRoot(root, rootsFileOf());
281
+ }
282
+ const rootOf = (requested, strict = false) => {
283
+ const fallback = deps.projectRoot();
284
+ const req = requested?.trim();
285
+ if (!req)
286
+ return fallback;
287
+ // 和 GC/读侧共用 rootKey:Windows 折叠大小写,其它平台保留大小写。
288
+ if (rootKey(req) === rootKey(fallback))
289
+ return fallback;
290
+ const allowed = (deps.workspaces?.() ?? []).map((item) => item.path).filter((path) => Boolean(path));
291
+ const known = knownRoots.get(rootKey(req));
292
+ // 没有注册表时生产宿主不能静默回退;测试/旧宿主可显式豁免由 deps 决定。
293
+ if (allowed.length === 0 && knownRoots.size === 0) {
294
+ if (strict)
295
+ throw Object.assign(new Error(`没有可用工作区,拒绝根:${req}`), { status: 400 });
296
+ return fallback;
297
+ }
298
+ const hit = allowed.find((path) => rootKey(path) === rootKey(req)) ?? known;
299
+ if (hit)
300
+ return hit;
301
+ if (strict) {
302
+ const reason = allowed.length === 0 ? '没有可用工作区' : '未注册的工作区根';
303
+ throw Object.assign(new Error(`${reason}:${req}`), { status: 400 });
304
+ }
305
+ return fallback;
306
+ };
307
+ /** 模型绑定解析:provider::model 精确匹配;老数据按“角色的提供方”解析;失败让用户重选。 */
308
+ async function resolveBinding(llm, body) {
309
+ let binding = body.model?.includes('::')
310
+ ? parseCatalogModelId(body.model)
311
+ : null;
312
+ if (!binding?.route) {
313
+ const listed = await listDshModels(llm);
314
+ binding = resolveModelBinding(listed, body.model, body.provider);
315
+ }
316
+ if (!binding?.route) {
317
+ throw Object.assign(new Error('请在角色里重新选择 DSH 已配置的模型'), { status: 400 });
318
+ }
319
+ return { route: binding.route, model: binding.model };
320
+ }
321
+ return {
322
+ async getState(projectRoot) {
323
+ await loadKnownRoots();
324
+ const root = rootOf(projectRoot, true);
325
+ const state = await loadState(root);
326
+ if (state)
327
+ rememberRoot(root);
328
+ return state;
329
+ },
330
+ async putState(raw, projectRoot) {
331
+ await loadKnownRoots();
332
+ const state = parseState(raw);
333
+ const root = rootOf(projectRoot, true);
334
+ const saved = await saveState(root, state);
335
+ rememberRoot(root);
336
+ // 派生数据(事件/facts/摘要/指标)落盘失败时如实回报,不再让客户端以为「存好了」。
337
+ return saved.warnings.length ? { path: saved.path, warnings: saved.warnings } : { path: saved.path };
338
+ },
339
+ /**
340
+ * 数据根发现(只读):当前根 + DSH 注册工作区 + 以前用过的根,各自有没有数据。
341
+ * 面板加载失败时用它列出「哪个根里还有数据」,而不是静默显示空。
342
+ */
343
+ async stateRoots() {
344
+ const file = deps.rootsFile?.() ?? defaultRootsFile();
345
+ const knownRoots = await readKnownRoots(file);
346
+ return listStateRoots({
347
+ workspaces: deps.workspaces?.() ?? [],
348
+ current: deps.projectRoot(),
349
+ knownRoots,
350
+ });
351
+ },
352
+ /** 上传一个附件:字节落到本群 attachments/,图片/文件再登记到 DSH 附件存储(给模型用)。 */
353
+ async uploadAttachment(body) {
354
+ const threadId = (body.threadId ?? '').trim();
355
+ const name = (body.name ?? '').trim();
356
+ const data = body.data;
357
+ if (!threadId)
358
+ throw Object.assign(new Error('threadId 必填'), { status: 400 });
359
+ assertSafeThreadId(threadId);
360
+ if (!name)
361
+ throw Object.assign(new Error('name 必填'), { status: 400 });
362
+ if (!data || data.byteLength === 0)
363
+ throw Object.assign(new Error('附件是空的'), { status: 400 });
364
+ await loadKnownRoots();
365
+ const projectRoot = rootOf(body.projectRoot, true);
366
+ const declared = mediaTypeFor(name, body.mediaType);
367
+ const sniffed = sniffMediaType(data);
368
+ let kind = declared.startsWith('image/') ? 'image' : 'file';
369
+ let mediaType = declared;
370
+ let downgraded = false;
371
+ // 声明是图片但内容不是图片:降级为文件(按 20MB 限流),避免把二进制当图片走 8MB 上限。
372
+ if (kind === 'image' && !sniffed?.startsWith('image/')) {
373
+ kind = 'file';
374
+ mediaType = sniffed ?? 'application/octet-stream';
375
+ downgraded = true;
376
+ }
377
+ else if (kind === 'image' && sniffed) {
378
+ mediaType = sniffed;
379
+ }
380
+ const limit = kind === 'image' ? MAX_IMAGE_BYTES : MAX_FILE_BYTES;
381
+ if (data.byteLength > limit) {
382
+ throw Object.assign(new Error(`附件太大(${Math.round(data.byteLength / 1024)}KB,上限 ${Math.round(limit / 1024)}KB)`), { status: 413 });
383
+ }
384
+ const id = 'a_' + crypto.randomUUID().replaceAll('-', '').slice(0, 12);
385
+ const rel = `attachments/${id}_${safeAttachmentName(name)}`;
386
+ await writeGroupBuffer(projectRoot, threadId, rel, data);
387
+ const attachment = {
388
+ id,
389
+ kind,
390
+ name,
391
+ mediaType,
392
+ bytes: data.byteLength,
393
+ path: rel,
394
+ ...(downgraded ? { downgraded: true } : {}),
395
+ };
396
+ const store = deps.attachments?.();
397
+ // 文本预览与宿主 store 无关:没有 store / store 不支持的文本文件,本地也要能看正文。
398
+ // 降级文件(假 png)媒体类型是 octet-stream,但内容无 NUL 时仍按文本内联。
399
+ const noNul = !data.subarray(0, Math.min(data.length, 16 * 1024)).includes(0);
400
+ const textLike = isTextLike(name, mediaType) || (downgraded && !sniffed && noNul);
401
+ if (kind !== 'image' && textLike) {
402
+ const text = inlineTextPreview(data);
403
+ if (text)
404
+ attachment.text = text;
405
+ }
406
+ if (!store) {
407
+ warnMissingAttachmentStore();
408
+ await appendMetrics(projectRoot, threadId, [{
409
+ at: Date.now(),
410
+ kind: 'attachment_host_save',
411
+ fields: { ok: false, reason: 'no-store', name: name.slice(0, 80), mediaType },
412
+ }]).catch(() => undefined);
413
+ }
414
+ try {
415
+ if (!store) {
416
+ // 本地预览已在上方计算,无需再走宿主 store。
417
+ }
418
+ else if (kind === 'image' && typeof store.saveImages !== 'function') {
419
+ await appendMetrics(projectRoot, threadId, [{
420
+ at: Date.now(),
421
+ kind: 'attachment_host_save',
422
+ fields: { ok: false, reason: 'no-saveImages', name: name.slice(0, 80), mediaType },
423
+ }]).catch(() => undefined);
424
+ }
425
+ else if (kind === 'image') {
426
+ const refs = await store.saveImages?.([{ data, mediaType, name }]);
427
+ const ref = refs?.[0];
428
+ if (ref?.attachmentId) {
429
+ attachment.attachmentId = ref.attachmentId;
430
+ if (typeof ref.width === 'number')
431
+ attachment.width = ref.width;
432
+ if (typeof ref.height === 'number')
433
+ attachment.height = ref.height;
434
+ }
435
+ else {
436
+ await appendMetrics(projectRoot, threadId, [{
437
+ at: Date.now(),
438
+ kind: 'attachment_host_save',
439
+ fields: { ok: false, reason: 'no-ref', name: name.slice(0, 80), mediaType },
440
+ }]).catch(() => undefined);
441
+ }
442
+ }
443
+ else if (typeof store.saveFile !== 'function') {
444
+ await appendMetrics(projectRoot, threadId, [{
445
+ at: Date.now(),
446
+ kind: 'attachment_host_save',
447
+ fields: { ok: false, reason: 'no-saveFile', name: name.slice(0, 80), mediaType },
448
+ }]).catch(() => undefined);
449
+ }
450
+ else {
451
+ const ref = await store.saveFile({ data, name });
452
+ if (ref?.attachmentId)
453
+ attachment.attachmentId = ref.attachmentId;
454
+ else {
455
+ await appendMetrics(projectRoot, threadId, [{
456
+ at: Date.now(),
457
+ kind: 'attachment_host_save',
458
+ fields: { ok: false, reason: 'no-ref', name: name.slice(0, 80), mediaType },
459
+ }]).catch(() => undefined);
460
+ }
461
+ }
462
+ }
463
+ catch (error) {
464
+ // 宿主附件存储不可用(或纯文本后端不支持某些类型)不影响本地保存与预览;记一条指标便于排查。
465
+ await appendMetrics(projectRoot, threadId, [{
466
+ at: Date.now(),
467
+ kind: 'attachment_host_save',
468
+ fields: {
469
+ ok: false,
470
+ name: name.slice(0, 80),
471
+ mediaType,
472
+ ...(downgraded ? { downgraded: true } : {}),
473
+ error: (error instanceof Error ? error.message : String(error)).slice(0, 160),
474
+ },
475
+ }]).catch(() => undefined);
476
+ }
477
+ attachment.modelVisible = Boolean(attachment.attachmentId);
478
+ const query = new URLSearchParams({ threadId, file: rel });
479
+ return { attachment, url: `/api/im/attachment?${query.toString()}`, modelVisible: attachment.modelVisible };
480
+ },
481
+ /** 读本群 attachments/ 下的附件字节(给界面预览/下载)。 */
482
+ async attachmentFile(body) {
483
+ const threadId = (body.threadId ?? '').trim();
484
+ const file = (body.file ?? '').replaceAll('\\', '/').trim();
485
+ if (!threadId || !file)
486
+ throw Object.assign(new Error('threadId/file 必填'), { status: 400 });
487
+ if (!file.startsWith('attachments/')) {
488
+ throw Object.assign(new Error('只能读 attachments/ 下的附件'), { status: 400 });
489
+ }
490
+ // 不再要求客户端传绝对路径:显式根接受「注册工作区 + 用过的数据根」;没传则在各根里找该群。
491
+ await loadKnownRoots();
492
+ const candidates = body.projectRoot
493
+ ? [rootOf(body.projectRoot, true)]
494
+ : [...new Map([deps.projectRoot(), ...(deps.workspaces?.() ?? []).map((item) => item.path).filter((path) => Boolean(path)), ...knownRoots.values()]
495
+ .map((path) => [rootKey(path), path])).values()];
496
+ let fallbackHit;
497
+ for (const root of candidates) {
498
+ let bytes;
499
+ try {
500
+ bytes = await readGroupBuffer(root, threadId, file);
501
+ }
502
+ catch (error) {
503
+ if (error instanceof Error && /invalid threadId/.test(error.message)) {
504
+ throw Object.assign(new Error('threadId 非法'), { status: 400 });
505
+ }
506
+ continue;
507
+ }
508
+ const state = await loadState(root).catch(() => null);
509
+ const thread = state?.threads.find((item) => item.id === threadId);
510
+ const recorded = thread?.messages
511
+ .flatMap((message) => message.attachments ?? [])
512
+ .find((attachment) => attachment.path?.replaceAll('\\', '/') === file)?.mediaType;
513
+ const sniffed = sniffMediaType(bytes);
514
+ const byPath = mediaTypeFor(file);
515
+ const result = { bytes, mediaType: recorded ?? sniffed ?? (byPath.startsWith('image/') ? 'application/octet-stream' : byPath) };
516
+ // 优先返回 state 里确实有这个 thread 的根,避免跨根同名群读错工作区。
517
+ if (thread)
518
+ return result;
519
+ fallbackHit ??= result;
520
+ }
521
+ if (fallbackHit)
522
+ return fallbackHit;
523
+ throw Object.assign(new Error('附件不存在'), { status: 404 });
524
+ },
525
+ /** 附件垃圾回收:默认 dryRun,只报告孤儿;显式 dryRun=false 才删除。 */
526
+ async attachmentGc(body) {
527
+ const threadId = (body.threadId ?? '').trim();
528
+ if (!threadId)
529
+ throw Object.assign(new Error('threadId 必填'), { status: 400 });
530
+ const dryRun = body.dryRun ?? true;
531
+ const requestedAge = body.minAgeMs ?? 24 * 60 * 60 * 1000;
532
+ // 非 dryRun 必须给足宽限期,防止客户端传 0 直接清空;路径也必须用面板根,不信客户端 projectRoot。
533
+ if (!dryRun && requestedAge < MIN_GC_AGE_MS) {
534
+ throw Object.assign(new Error(`minAgeMs 不能小于 ${MIN_GC_AGE_MS}ms(1h)`), { status: 400 });
535
+ }
536
+ const roots = [];
537
+ const seenRoots = new Set();
538
+ for (const root of [deps.projectRoot(), ...(deps.workspaces?.() ?? []).map((item) => item.path).filter((path) => Boolean(path))]) {
539
+ const key = rootKey(root);
540
+ if (seenRoots.has(key))
541
+ continue;
542
+ seenRoots.add(key);
543
+ roots.push(root);
544
+ }
545
+ const results = [];
546
+ let lastAbort;
547
+ for (const root of roots) {
548
+ try {
549
+ const result = await gcAttachments(root, threadId, {
550
+ dryRun,
551
+ minAgeMs: Math.max(MIN_GC_AGE_MS, requestedAge),
552
+ });
553
+ results.push({ root, ...result });
554
+ }
555
+ catch (error) {
556
+ // 该根里没有这个群:继续看下一个注册根;都找不到时再抛。
557
+ if (error.code === 'GC_ABORT')
558
+ lastAbort = error;
559
+ else
560
+ throw error;
561
+ }
562
+ }
563
+ if (results.length === 0)
564
+ throw lastAbort ?? Object.assign(new Error('GC_ABORT:没有可扫描的根'), { code: 'GC_ABORT' });
565
+ const sum = (key) => results.reduce((total, item) => total + item[key], 0);
566
+ return {
567
+ root: results[0]?.root ?? roots[0],
568
+ coveredRoots: results.map((item) => item.root),
569
+ results,
570
+ orphanEntries: results.flatMap((item) => item.orphans.map((path) => ({ root: item.root, path }))),
571
+ scanned: sum('scanned'),
572
+ referenced: sum('referenced'),
573
+ orphans: results.flatMap((item) => item.orphans),
574
+ freed: sum('freed'),
575
+ wouldFree: sum('wouldFree'),
576
+ failed: sum('failed'),
577
+ statFailed: sum('statFailed'),
578
+ errored: sum('errored'),
579
+ noDir: sum('noDir'),
580
+ dryRun,
581
+ };
582
+ },
583
+ async models() {
584
+ const llm = deps.llm();
585
+ if (!llm)
586
+ throw noLlmService();
587
+ return listDshModels(llm);
588
+ },
589
+ async preflight(body) {
590
+ if (!body.threadId)
591
+ throw Object.assign(new Error('threadId 必填'), { status: 400 });
592
+ await loadKnownRoots();
593
+ const state = await loadState(rootOf(body.projectRoot, true));
594
+ if (!state)
595
+ throw Object.assign(new Error('还没有任何群数据'), { status: 404 });
596
+ const thread = state.threads.find((item) => item.id === body.threadId);
597
+ if (!thread)
598
+ throw Object.assign(new Error('群不存在'), { status: 404 });
599
+ const members = thread.members
600
+ .map((member) => state.personas.find((persona) => persona.id === member.personaId))
601
+ .filter((persona) => Boolean(persona))
602
+ .map((persona) => ({
603
+ personaId: persona.id,
604
+ name: persona.name,
605
+ post: persona.post,
606
+ model: persona.model,
607
+ provider: persona.provider,
608
+ }));
609
+ return preflightMembers(deps.llm(), members);
610
+ },
611
+ async complete(body) {
612
+ if (!body.model || (!body.messages?.length && typeof body.user !== 'string')) {
613
+ throw Object.assign(new Error('model 与 messages 必填'), { status: 400 });
614
+ }
615
+ assertToolAllowShape(body.toolAllow);
616
+ await loadKnownRoots();
617
+ const projectRoot = rootOf(body.projectRoot, true);
618
+ const threadId = body.threadId || 'im';
619
+ const llm = deps.llm();
620
+ if (!llm?.stream)
621
+ throw noLlmService();
622
+ const binding = await resolveBinding(llm, body);
623
+ const toolAllow = normalizeToolAllow(body.toolAllow);
624
+ // 缺陷修复:请求里没带 budget 时(例如直调 /api/im/complete),host 从 state+成员模型窗口推导,
625
+ // 让多跳执行器拿到真实群级预算;推导不到才 fallback(执行器会显式标注)。
626
+ // 只有"本轮可能调工具"时才推导(extract/curate 是后台结构化调用,不需要工具预算)。
627
+ const mayCallTools = toolsForAllow(toolAllow).length > 0
628
+ && body.purpose !== 'extract'
629
+ && body.purpose !== 'curate';
630
+ const turnBudget = mayCallTools
631
+ ? await resolveTurnBudget({ body, projectRoot, threadId, llm })
632
+ : { chars: undefined, receipt: undefined };
633
+ const effectiveBudget = budgetReceiptOf(body) ?? turnBudget.receipt;
634
+ const memoryBudgetChars = typeof body.budget?.windowChars === 'number'
635
+ ? body.budget.windowChars
636
+ : turnBudget.chars;
637
+ // 同文件/同目录/同关键词在一轮里重复调用:返回“已看过”提示,不再真实读盘。
638
+ const toolCache = createTurnToolCache();
639
+ const onTool = (name, args) => executePersonaTool({
640
+ name,
641
+ args,
642
+ projectRoot,
643
+ threadId,
644
+ ...(body.personaId ? { personaId: body.personaId } : {}),
645
+ ...(memoryBudgetChars === undefined ? {} : { budgetChars: memoryBudgetChars }),
646
+ cache: toolCache,
647
+ });
648
+ // 两阶段回执:调用前记 intent,完成后补 outcome(best-effort,不影响回复)。
649
+ const turnId = crypto.randomUUID();
650
+ const startedAt = Date.now();
651
+ const windowSeqs = (Array.isArray(body.windowSeqs) ? body.windowSeqs : [])
652
+ .filter((seq) => typeof seq === 'number' && Number.isFinite(seq));
653
+ const hitIds = (Array.isArray(body.retrievalHitIds) ? body.retrievalHitIds : [])
654
+ .filter((seq) => typeof seq === 'number' && Number.isFinite(seq));
655
+ const selectedIds = (Array.isArray(body.retrievalSelectedIds) ? body.retrievalSelectedIds : [])
656
+ .filter((seq) => typeof seq === 'number' && Number.isFinite(seq));
657
+ await appendIntent(projectRoot, threadId, createIntent({
658
+ turnId,
659
+ personaId: body.personaId ?? '',
660
+ provider: binding.route,
661
+ model: binding.model,
662
+ windowSeqs,
663
+ summaryUntil: typeof body.summaryUntil === 'number' ? body.summaryUntil : 0,
664
+ systemPrompt: body.system ?? '',
665
+ prompt: JSON.stringify(body.messages ?? []),
666
+ untrusted: Boolean(body.messages?.some((message) => message.role === 'user')),
667
+ ...(body.factsVersion ? { versions: { factsVersion: body.factsVersion } } : {}),
668
+ ...(body.stateSnapshotHash ? { stateSnapshotHash: body.stateSnapshotHash } : {}),
669
+ ...(body.retrievalQuery ? {
670
+ retrieval: {
671
+ query: body.retrievalQuery,
672
+ hitIds,
673
+ selectedIds,
674
+ indexVersion: body.indexVersion ?? '',
675
+ },
676
+ } : {}),
677
+ ...(memoryReceiptOf(body) ? { memoryContext: memoryReceiptOf(body) } : {}),
678
+ ...(effectiveBudget ? { budget: effectiveBudget } : {}),
679
+ ...(budgetChangedOf(body) ? { budgetChanged: budgetChangedOf(body) } : {}),
680
+ at: startedAt,
681
+ })).catch(() => undefined);
682
+ let text;
683
+ const steps = [];
684
+ /** Phase 1b:宿主流里观察到的用量(没有就不猜)。 */
685
+ let observedUsage;
686
+ /** 用于校准 chars/token 的输入字符数:system + 本轮消息正文。 */
687
+ const promptChars = (body.system ?? '').length + (body.messages ?? [{ role: 'user', content: body.user ?? '' }])
688
+ .reduce((sum, message) => sum + (typeof message.content === 'string' ? message.content.length : JSON.stringify(message.content).length), 0);
689
+ /** 工具循环统计(toolCalls / toolBudgetExhausted 写进 metrics 与 trace 的 reply 步)。 */
690
+ let toolStats;
691
+ try {
692
+ text = await completeDshChat({
693
+ llm,
694
+ provider: binding.route,
695
+ model: binding.model,
696
+ system: body.system ?? '',
697
+ messages: body.messages ?? [{ role: 'user', content: body.user ?? '' }],
698
+ toolAllow,
699
+ onTool: toolsForAllow(toolAllow).length ? onTool : undefined,
700
+ onStep: (step) => { steps.push({ ...step, step: steps.length + 1 }); },
701
+ onTurnStats: (stats) => { toolStats = stats; },
702
+ purpose: body.purpose ?? 'reply',
703
+ onUsage: (usage) => { observedUsage = usage; },
704
+ });
705
+ }
706
+ catch (err) {
707
+ // 失败也要留指标:成功率/失败码在 metrics.jsonl 里能查到。
708
+ await appendMetrics(projectRoot, threadId, [{
709
+ at: startedAt,
710
+ kind: 'llm_call',
711
+ value: Date.now() - startedAt,
712
+ fields: {
713
+ ok: false,
714
+ purpose: body.purpose ?? 'reply',
715
+ provider: binding.route,
716
+ model: binding.model,
717
+ personaId: body.personaId ?? '',
718
+ error: (err instanceof Error ? err.message : String(err)).slice(0, 160),
719
+ },
720
+ }]).catch(() => undefined);
721
+ await appendOutcome(projectRoot, threadId, turnId, {
722
+ ms: Date.now() - startedAt,
723
+ finish: 'error',
724
+ }).catch(() => undefined);
725
+ throw err;
726
+ }
727
+ const ms = Date.now() - startedAt;
728
+ await Promise.all([
729
+ appendOutcome(projectRoot, threadId, turnId, {
730
+ ms,
731
+ finish: 'stop',
732
+ ...(observedUsage?.inputTokens === undefined ? {} : { tokensIn: observedUsage.inputTokens }),
733
+ ...(observedUsage?.outputTokens === undefined ? {} : { tokensOut: observedUsage.outputTokens }),
734
+ }).catch(() => undefined),
735
+ appendMetrics(projectRoot, threadId, [{
736
+ at: startedAt,
737
+ kind: 'llm_call',
738
+ value: ms,
739
+ fields: {
740
+ ok: true,
741
+ purpose: body.purpose ?? 'reply',
742
+ provider: binding.route,
743
+ model: binding.model,
744
+ personaId: body.personaId ?? '',
745
+ windowCount: windowSeqs.length,
746
+ summaryUntil: typeof body.summaryUntil === 'number' ? body.summaryUntil : 0,
747
+ factsVersion: body.factsVersion ?? '',
748
+ dedupedCalls: toolCache.hits(),
749
+ retrievalHits: hitIds.length,
750
+ retrievalSelected: selectedIds.length,
751
+ hasState: Boolean(body.stateSnapshotHash),
752
+ // 工具循环护栏观测:本轮请求/执行了几次工具、是否因上限被强制收尾。
753
+ ...(toolStats ? {
754
+ toolCalls: toolStats.toolCalls,
755
+ toolExecuted: toolStats.toolExecuted,
756
+ toolRounds: toolStats.toolRounds,
757
+ toolCallLimit: toolStats.toolCallLimit,
758
+ toolBudgetExhausted: toolStats.toolBudgetExhausted,
759
+ } : {}),
760
+ ...(body.indexVersion ? { indexVersion: body.indexVersion } : {}),
761
+ // Phase 1b:用量 + 本次 prompt 字符数(反推 chars/token 系数的原料)。
762
+ ...(observedUsage ? {
763
+ ...(observedUsage.inputTokens === undefined ? {} : { inputTokens: observedUsage.inputTokens }),
764
+ ...(observedUsage.outputTokens === undefined ? {} : { outputTokens: observedUsage.outputTokens }),
765
+ ...(observedUsage.totalTokens === undefined ? {} : { totalTokens: observedUsage.totalTokens }),
766
+ promptChars,
767
+ ...(observedUsage.inputTokens ? { charsPerInputToken: Math.round((promptChars / observedUsage.inputTokens) * 100) / 100 } : {}),
768
+ } : {}),
769
+ },
770
+ }]).catch(() => undefined),
771
+ ]);
772
+ // A-1:预算变更事件(只在显式输入变化时出现)单独落一条指标,便于离线对账。
773
+ if (body.budgetChanged) {
774
+ await appendMetrics(projectRoot, threadId, [{
775
+ at: startedAt,
776
+ kind: 'budget_changed',
777
+ value: typeof body.budget?.windowChars === 'number' ? body.budget.windowChars : 0,
778
+ fields: {
779
+ reason: body.budgetChanged.reason,
780
+ fromWindowChars: body.budgetChanged.from.windowChars,
781
+ toWindowChars: body.budgetChanged.to.windowChars,
782
+ fromTokens: body.budgetChanged.from.tokens ?? -1,
783
+ toTokens: body.budgetChanged.to.tokens ?? -1,
784
+ fromTier: body.budgetChanged.from.tier,
785
+ toTier: body.budgetChanged.to.tier,
786
+ },
787
+ }]).catch(() => undefined);
788
+ }
789
+ // L1 计量正确性:整条样本(原始 usage + 口径 + 构成)落 calibration-samples.jsonl,判据可离线复算。
790
+ {
791
+ const messageText = (body.messages ?? [{ role: 'user', content: body.user ?? '' }])
792
+ .map((message) => (typeof message.content === 'string'
793
+ ? message.content
794
+ : message.content.filter((part) => part.type === 'text').map((part) => part.text).join('\n')))
795
+ .join('\n');
796
+ const sample = buildSample({
797
+ at: startedAt,
798
+ provider: binding.route,
799
+ model: binding.model,
800
+ purpose: body.purpose ?? 'reply',
801
+ transport: 'ctx.llm',
802
+ systemText: body.system ?? '',
803
+ messageText,
804
+ toolCalls: steps.filter((step) => step.kind === 'tool').length,
805
+ toolCount: toolsForAllow(toolAllow).length,
806
+ usage: observedUsage ?? {},
807
+ });
808
+ void appendCalibrationSample(projectRoot, sample);
809
+ }
810
+ return { text, ...(steps.length ? { trace: steps } : {}) };
811
+ },
812
+ /**
813
+ * 用 ctx.llm.stream 复刻一次和原生会话相近的请求,把原始异常(含 cause)原样返回。
814
+ * 不经过 agent 循环的 failure 投影。
815
+ */
816
+ async llmProbe(body) {
817
+ const llm = deps.llm();
818
+ if (!llm?.stream)
819
+ return { ok: false, failure: { message: 'llm.stream 不存在' } };
820
+ const started = Date.now();
821
+ const textParts = [];
822
+ let binding;
823
+ try {
824
+ binding = await resolveBinding(llm, body);
825
+ const stream = llm.stream.call(llm, {
826
+ provider: binding.route,
827
+ model: binding.model,
828
+ system: body.system ?? '你是实测甲。用一句话回答。',
829
+ messages: [{ role: 'user', content: [{ type: 'text', text: body.prompt ?? '只说一个字好' }] }],
830
+ maxTokens: body.maxTokens ?? 256_000,
831
+ reasoningEffort: body.reasoningEffort ?? 'high',
832
+ ...(body.systemPromptUpdate ? { systemPromptUpdate: body.systemPromptUpdate } : {}),
833
+ ...(body.tools ? { tools: body.tools } : {}),
834
+ signal: AbortSignal.timeout(60_000),
835
+ });
836
+ for await (const chunk of stream) {
837
+ // Phase 0 能力探测:记录流里是否带 usage(决定 Phase 1 能否做 token 校准)。
838
+ for (const key of usageKeysInChunk(chunk)) {
839
+ if (!observedUsageKeys.includes(key))
840
+ observedUsageKeys.push(key);
841
+ }
842
+ if (chunk?.type === 'text-delta' && chunk.text)
843
+ textParts.push(chunk.text);
844
+ if (chunk?.type === 'finish' && (chunk.reason?.kind === 'error' || chunk.reason?.kind === 'aborted')) {
845
+ const failure = chunk.reason?.failure;
846
+ throw Object.assign(new Error(failure?.message || chunk.reason?.kind || 'llm finish error'), {
847
+ code: failure?.code,
848
+ cause: failure,
849
+ });
850
+ }
851
+ }
852
+ return { ok: true, ms: Date.now() - started, provider: binding.route, model: binding.model, text: textParts.join('').slice(0, 500) };
853
+ }
854
+ catch (error) {
855
+ return {
856
+ ok: false,
857
+ ms: Date.now() - started,
858
+ provider: binding?.route,
859
+ model: binding?.model,
860
+ failure: describeFailure(error),
861
+ };
862
+ }
863
+ },
864
+ /** M2.1 原生 session 是否可用(客户端据此选择 transport;默认关)。 */
865
+ nativeStatus() {
866
+ const bridge = deps.native?.();
867
+ if (!bridge)
868
+ return { enabled: false, reason: '原生会话已关闭(DSH_IM_NATIVE_SESSION=0)' };
869
+ return bridge.status();
870
+ },
871
+ /** 诊断:原生会话当前派生消息(排查空回复用;不含敏感 prompt)。 */
872
+ nativeDebug() {
873
+ const bridge = deps.native?.();
874
+ if (!bridge)
875
+ return { enabled: false, sessions: [] };
876
+ return { enabled: true, ...(bridge.debug?.() ?? { sessions: [] }) };
877
+ },
878
+ /**
879
+ * Phase 0 宿主能力探测:tokenizer / usage / embeddings 有没有。
880
+ * 只做形状探测 + 已观察到的 usage 字段;不主动发模型调用(那由 /llm-probe 触发)。
881
+ */
882
+ capabilities() {
883
+ return detectHostCapabilities(deps.llm(), { usageKeys: observedUsageKeys });
884
+ },
885
+ /** Phase 1b:当前数据根的 chars/token 校准(面板启动读取,用于把 token 预算换算成字符预算)。 */
886
+ /**
887
+ * L1/L2/L3 观测:校准样本报告 + 影子决策 + 各桶「若启用」预算。
888
+ * `charsPerToken`(客户端预算实际用的)**只在显式 shadow→calibrated 后才返回**,
889
+ * 其余情况返回空对象 + 完整 shadow 报告(零行为变更)。
890
+ */
891
+ async tokenCalibration(projectRoot) {
892
+ await loadKnownRoots();
893
+ const root = rootOf(projectRoot, true);
894
+ const calibrated = process.env.DSH_IM_CALIBRATION_MODE === 'calibrated';
895
+ const samples = await readCalibrationSamples(root);
896
+ const report = buildCalibrationReport(samples, { allowCalibrated: calibrated });
897
+ const charsPerToken = {};
898
+ if (calibrated) {
899
+ for (const bucket of report.buckets) {
900
+ if (bucket.mode !== 'calibrated' || bucket.shadowRatio === undefined)
901
+ continue;
902
+ const modelKey = bucket.bucket.split('::').slice(0, 2).join('::');
903
+ charsPerToken[modelKey] = bucket.shadowRatio;
904
+ }
905
+ }
906
+ const buckets = report.buckets.map((bucket) => {
907
+ const plan = planBudget({
908
+ ...(bucket.shadowRatio === undefined ? {} : { ratio: bucket.shadowRatio, ratioSource: 'calibrated' }),
909
+ tier: 'standard',
910
+ mode: 'shadow',
911
+ });
912
+ return {
913
+ bucket: bucket.bucket,
914
+ samples: bucket.samples,
915
+ valid: bucket.validSamples,
916
+ invalidShare: bucket.invalidShare,
917
+ prior: bucket.priorRatio,
918
+ median: bucket.medianRatio,
919
+ shadowRatio: bucket.shadowRatio,
920
+ mode: bucket.mode,
921
+ wouldClamp: bucket.wouldClamp,
922
+ reasons: bucket.reasons,
923
+ wouldBeWindowChars: plan.windowChars,
924
+ wouldBeTokens: plan.tokenBudget,
925
+ };
926
+ });
927
+ return {
928
+ mode: calibrated ? 'calibrated' : 'shadow',
929
+ totals: report.totals,
930
+ buckets,
931
+ charsPerToken,
932
+ };
933
+ },
934
+ /**
935
+ * Phase 0 记忆索引预览:构建/增量更新指定群的派生索引,返回统计(默认**不落盘**)。
936
+ * 只读诊断用;`persist:true` 才写 `.dsh-im/groups/<id>/index.json`。
937
+ */
938
+ async memoryIndex(body) {
939
+ const threadId = (body.threadId ?? '').trim();
940
+ if (!threadId)
941
+ throw Object.assign(new Error('threadId 必填'), { status: 400 });
942
+ await loadKnownRoots();
943
+ const root = rootOf(body.projectRoot, true);
944
+ const state = await loadState(root);
945
+ if (!state)
946
+ throw Object.assign(new Error('还没有任何群数据'), { status: 404 });
947
+ const thread = state.threads.find((item) => item.id === threadId);
948
+ if (!thread)
949
+ throw Object.assign(new Error('群不存在'), { status: 404 });
950
+ const result = await buildMemoryIndex(root, threadId, {
951
+ ...(thread.consensusState ? { consensus: thread.consensusState } : {}),
952
+ persist: body.persist === true,
953
+ });
954
+ return {
955
+ rebuilt: result.rebuilt,
956
+ reason: result.reason,
957
+ stats: result.index.stats,
958
+ cursor: result.index.cursor,
959
+ sample: result.index.entries.slice(-5),
960
+ };
961
+ },
962
+ /**
963
+ * 动态工具目录:内置 4 能力 + 宿主来源组(浏览器/MCP server/其他)。
964
+ * 面板每次打开/刷新都重新发现,用户新装的工具无需改代码即可出现在角色编辑器里。
965
+ */
966
+ toolGroups() {
967
+ const catalog = deps.toolGroups?.();
968
+ if (!catalog)
969
+ return { capabilities: [], groups: [], native: false };
970
+ const bridge = deps.native?.();
971
+ return { ...catalog, native: Boolean(bridge?.status().enabled) };
972
+ },
973
+ async nativeComplete(body) {
974
+ const bridge = deps.native?.();
975
+ if (!bridge || !bridge.status().enabled) {
976
+ throw Object.assign(new Error('原生会话不可用:宿主没有 ctx.agents 或未开启'), { status: 503 });
977
+ }
978
+ const frame = body.frame ?? body.nativeFrame;
979
+ const prompt = body.prompt?.trim()
980
+ || (body.messages ?? []).map((message) => String(message.content ?? '')).join('\n\n').trim();
981
+ if (!body.sessionKey?.trim() || (!prompt && !frame)) {
982
+ throw Object.assign(new Error('sessionKey 与 prompt/messages 或 frame 必填'), { status: 400 });
983
+ }
984
+ assertToolAllowShape(body.toolAllow);
985
+ const toolAllow = normalizeToolAllow(body.toolAllow);
986
+ const llm = deps.llm();
987
+ if (!llm)
988
+ throw noLlmService();
989
+ const binding = await resolveBinding(llm, body);
990
+ const listed = (() => {
991
+ try {
992
+ return (llm.listProviders?.() ?? []).map((row) => (typeof row === 'string' ? row : (row.id || row.name || ''))).filter(Boolean);
993
+ }
994
+ catch (error) {
995
+ return [`listProviders failed: ${error instanceof Error ? error.message : String(error)}`];
996
+ }
997
+ })();
998
+ const providerOverride = process.env.DSH_IM_NATIVE_PROVIDER?.trim();
999
+ const agentProvider = providerOverride || binding.route;
1000
+ dumpNativeDiag(JSON.stringify({
1001
+ at: Date.now(),
1002
+ route: binding.route,
1003
+ model: binding.model,
1004
+ agentProvider,
1005
+ listProviders: listed,
1006
+ routeInList: listed.includes(binding.route),
1007
+ }));
1008
+ await loadKnownRoots();
1009
+ const projectRoot = rootOf(body.projectRoot, true);
1010
+ const threadId = body.threadId || 'im';
1011
+ const turnId = crypto.randomUUID();
1012
+ const startedAt = Date.now();
1013
+ const windowSeqs = (Array.isArray(body.windowSeqs) ? body.windowSeqs : [])
1014
+ .filter((seq) => typeof seq === 'number' && Number.isFinite(seq));
1015
+ await appendIntent(projectRoot, threadId, createIntent({
1016
+ turnId,
1017
+ personaId: body.personaId ?? '',
1018
+ provider: binding.route,
1019
+ model: binding.model,
1020
+ windowSeqs,
1021
+ summaryUntil: typeof body.summaryUntil === 'number' ? body.summaryUntil : 0,
1022
+ systemPrompt: body.system ?? '',
1023
+ prompt,
1024
+ untrusted: true,
1025
+ ...(body.factsVersion ? { versions: { factsVersion: body.factsVersion } } : {}),
1026
+ ...(memoryReceiptOf(body) ? { memoryContext: memoryReceiptOf(body) } : {}),
1027
+ ...(budgetReceiptOf(body) ? { budget: budgetReceiptOf(body) } : {}),
1028
+ ...(budgetChangedOf(body) ? { budgetChanged: budgetChangedOf(body) } : {}),
1029
+ at: startedAt,
1030
+ })).catch(() => undefined);
1031
+ let text;
1032
+ let trace;
1033
+ let toolStats;
1034
+ try {
1035
+ const done = await bridge.complete({
1036
+ sessionKey: body.sessionKey,
1037
+ provider: agentProvider,
1038
+ model: binding.model,
1039
+ cwd: body.cwd?.trim() || projectRoot,
1040
+ threadId,
1041
+ system: body.system ?? '',
1042
+ prompt,
1043
+ ...(frame ? { frame } : {}),
1044
+ ...(toolAllow ? { toolAllow } : {}),
1045
+ ...(body.personaName ? { personaName: body.personaName } : {}),
1046
+ ...(body.setupMode ? { setupMode: body.setupMode } : {}),
1047
+ ...(body.sessionIdOverride ? { sessionIdOverride: body.sessionIdOverride } : {}),
1048
+ ...(typeof body.maxTokens === 'number' ? { maxTokens: body.maxTokens } : {}),
1049
+ ...(body.reasoningEffort ? { reasoningEffort: body.reasoningEffort } : {}),
1050
+ ...(typeof body.maxToolCalls === 'number' ? { maxToolCalls: body.maxToolCalls } : {}),
1051
+ ...(typeof body.budget?.windowChars === 'number' ? { memoryBudgetChars: body.budget.windowChars } : {}),
1052
+ });
1053
+ text = done.text;
1054
+ trace = done.trace;
1055
+ toolStats = done.toolStats;
1056
+ }
1057
+ catch (err) {
1058
+ await Promise.all([
1059
+ appendOutcome(projectRoot, threadId, turnId, { ms: Date.now() - startedAt, finish: 'error' }).catch(() => undefined),
1060
+ appendMetrics(projectRoot, threadId, [{
1061
+ at: startedAt,
1062
+ kind: 'llm_call',
1063
+ value: Date.now() - startedAt,
1064
+ fields: {
1065
+ ok: false,
1066
+ purpose: 'native',
1067
+ provider: binding.route,
1068
+ model: binding.model,
1069
+ personaId: body.personaId ?? '',
1070
+ error: (err instanceof Error ? err.message : String(err)).slice(0, 2000),
1071
+ },
1072
+ }]).catch(() => undefined),
1073
+ ]);
1074
+ throw err;
1075
+ }
1076
+ const ms = Date.now() - startedAt;
1077
+ await Promise.all([
1078
+ appendOutcome(projectRoot, threadId, turnId, { ms, finish: 'stop' }).catch(() => undefined),
1079
+ appendMetrics(projectRoot, threadId, [{
1080
+ at: startedAt,
1081
+ kind: 'llm_call',
1082
+ value: ms,
1083
+ fields: {
1084
+ ok: true,
1085
+ purpose: 'native',
1086
+ provider: binding.route,
1087
+ model: binding.model,
1088
+ personaId: body.personaId ?? '',
1089
+ windowCount: windowSeqs.length,
1090
+ summaryUntil: typeof body.summaryUntil === 'number' ? body.summaryUntil : 0,
1091
+ // 工具循环护栏观测(native 与 ctx.llm 同口径)。
1092
+ ...(toolStats ? {
1093
+ toolCalls: toolStats.toolCalls,
1094
+ toolExecuted: toolStats.toolExecuted,
1095
+ toolCallLimit: toolStats.toolCallLimit,
1096
+ toolBudgetExhausted: toolStats.toolBudgetExhausted,
1097
+ } : {}),
1098
+ },
1099
+ }]).catch(() => undefined),
1100
+ ]);
1101
+ // A-1:native 通道的预算变更事件同样落指标(预算只用于观测,不参与 native usage 校准)。
1102
+ if (body.budgetChanged) {
1103
+ await appendMetrics(projectRoot, threadId, [{
1104
+ at: startedAt,
1105
+ kind: 'budget_changed',
1106
+ value: typeof body.budget?.windowChars === 'number' ? body.budget.windowChars : 0,
1107
+ fields: {
1108
+ reason: body.budgetChanged.reason,
1109
+ fromWindowChars: body.budgetChanged.from.windowChars,
1110
+ toWindowChars: body.budgetChanged.to.windowChars,
1111
+ fromTokens: body.budgetChanged.from.tokens ?? -1,
1112
+ toTokens: body.budgetChanged.to.tokens ?? -1,
1113
+ fromTier: body.budgetChanged.from.tier,
1114
+ toTier: body.budgetChanged.to.tier,
1115
+ transport: 'native',
1116
+ },
1117
+ }]).catch(() => undefined);
1118
+ }
1119
+ return { text, ...(trace?.length ? { trace } : {}), ...(toolStats ? { toolStats } : {}) };
1120
+ },
1121
+ async writeFile(body) {
1122
+ if (!body.threadId || !body.relativePath || typeof body.content !== 'string') {
1123
+ throw Object.assign(new Error('threadId, relativePath, content required'), { status: 400 });
1124
+ }
1125
+ await loadKnownRoots();
1126
+ const path = await nodeSink.writeThreadFile(rootOf(body.projectRoot, true), body.threadId, body.relativePath, body.content);
1127
+ return { path };
1128
+ },
1129
+ async workspace(projectRoot) {
1130
+ await loadKnownRoots();
1131
+ const path = rootOf(projectRoot, true);
1132
+ return { path };
1133
+ },
1134
+ /** 宿主挂载时预热「用过的数据根」缓存,避免首个请求在缓存空的时候被判 400。 */
1135
+ loadKnownRoots,
1136
+ };
1137
+ }