dsh-team-control 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,1984 @@
1
+ // dsh-team-control — 把本地 dsh-team sidecar 暴露为模型可调用工具。
2
+ //
3
+ // 设计约束(来自本仓 docs/CONTRACT.md 与 PRD):
4
+ // - 本插件只做「适配 + 生命周期」,编排/权限/事件流全部在 sidecar 进程内,不在这里重写。
5
+ // - 零第三方 import:只用 Node 内置模块,避免 profile 依赖解析问题;
6
+ // 工具用普通 ToolDefinition 对象注册(JSON Schema 参数),不依赖 defineTool。
7
+ // - sidecar 未运行时,autoStart=true 会在首次工具调用时拉起 `dsh-team up`;
8
+ // 插件卸载时只回收「自己拉起」的进程,不影响用户手工起的服务。
9
+ import { spawn } from 'node:child_process';
10
+ import { randomUUID } from 'node:crypto';
11
+ import fs from 'node:fs';
12
+ import { createRequire } from 'node:module';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+ import { FILE_TOOLS, changeKind, countDiff, displayPath, readTextSafe, targetFile, unifiedDiff } from './changes.js';
17
+ import { priceUsage } from './pricing.js';
18
+
19
+ /** Cordis plugin name. */
20
+ export const name = 'dsh-team';
21
+ /** Services required by this plugin. */
22
+ export const inject = ['tools'];
23
+
24
+ const PKG_DIR = path.dirname(fileURLToPath(import.meta.url));
25
+ const LOCAL_ENTRY = path.resolve(PKG_DIR, '..', 'bin', 'dsh-team.mjs');
26
+ /** 本地克隆时入口在同级 `bin/`;npm 安装时从依赖 `dsh-team-control-cli` 里解析。 */
27
+ function resolveDefaultEntry() {
28
+ if (fs.existsSync(LOCAL_ENTRY)) return LOCAL_ENTRY;
29
+ try {
30
+ return createRequire(import.meta.url).resolve('dsh-team-control-cli/bin/dsh-team.mjs');
31
+ } catch {
32
+ return LOCAL_ENTRY;
33
+ }
34
+ }
35
+ const DEFAULT_ENTRY = resolveDefaultEntry();
36
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
37
+
38
+ function resolveConfig(config) {
39
+ const c = config || {};
40
+ const baseUrl = String(c.baseUrl || process.env.DSH_TEAM_URL || 'http://127.0.0.1:4317').replace(/\/+$/, '');
41
+ let port = 4317;
42
+ try { port = Number(new URL(baseUrl).port) || 4317; } catch { /* keep default */ }
43
+ return {
44
+ baseUrl,
45
+ port,
46
+ home: path.resolve(c.home || process.env.DSH_TEAM_HOME || path.join(os.homedir(), '.dsh', 'team')),
47
+ autoStart: c.autoStart !== false,
48
+ entry: path.resolve(c.sidecarEntry || DEFAULT_ENTRY),
49
+ startTimeoutMs: Number(c.startTimeoutMs) || 20000,
50
+ requestTimeoutMs: Number(c.requestTimeoutMs) || 60000,
51
+ // 把每次工具调用作为 trace span 上报到 sidecar(成员看板瀑布实时展示)
52
+ reportToolCalls: c.reportToolCalls !== false,
53
+ // 把成员 write/edit 的改动作为 unified diff 上报到 sidecar(面板「审阅」页只读展示)
54
+ reportChanges: c.reportChanges !== false,
55
+ // 把每次 LLM 调用的 token 用量与折算金额作为 span 上报(瀑布里的 ¥/$ 金额来源)
56
+ reportLlmCalls: c.reportLlmCalls !== false,
57
+ // 覆盖/扩展单价表(键为 provider id,结构见 pricing.js 的 DEFAULT_PRICE_TABLES)
58
+ pricingTables: c.pricingTables && typeof c.pricingTables === 'object' ? c.pricingTables : null,
59
+ traceInputMax: Number(c.traceInputMax) || 1200,
60
+ // 把成员的上下文占用(system/tools/文件/结果/对话)上报到 sidecar(面板「上下文分析」页)
61
+ reportContext: c.reportContext !== false,
62
+ contextReportMs: Number(c.contextReportMs) || 6000,
63
+ // 把 DSH 工作区注册表同步到 sidecar(面板左侧「工作区」下拉)
64
+ reportWorkspaces: c.reportWorkspaces !== false,
65
+ workspaceReportMs: Number(c.workspaceReportMs) || 8000,
66
+ // 模型目录(provider/model 清单):插件启动即同步,之后定时刷新,不再依赖 lead 调工具
67
+ reportLlmCatalog: c.reportLlmCatalog !== false,
68
+ llmCatalogMs: Number(c.llmCatalogMs) || 60000,
69
+ // agent 运行时:成员在 sidecar 认领任务后,由本插件用 subagents.sendMessage 派发
70
+ agentAutoDispatch: c.agentAutoDispatch !== false,
71
+ agentDispatchMs: Number(c.agentDispatchMs) || 1500,
72
+ agentDispatchMax: Number(c.agentDispatchMax) || 16,
73
+ // sidecar 建任务后留 200ms 的「声明依赖」窗口,派发前先等过这段时间
74
+ agentSettleMs: Number(c.agentSettleMs) || 250,
75
+ // 成员 idle 的落库稳定窗口:DSH 在维护阶段(上下文压缩等)也会报 idle,立刻落库会把在途任务误判完成
76
+ agentIdleSettleMs: c.agentIdleSettleMs == null ? 12000 : Math.max(0, Number(c.agentIdleSettleMs) || 0),
77
+ // 成员状态心跳:本地认为在跑、sidecar 却回落到 idle 时补报 running(任务仍在跑说明回合没结束)
78
+ agentHeartbeatMs: Number(c.agentHeartbeatMs) || 15000,
79
+ // spawnTeammate 的 provider:默认与 dsh-experimental-tool-agent-team 一致
80
+ freshProvider: String(c.freshProvider || 'spawn'),
81
+ forkProvider: String(c.forkProvider || 'fork'),
82
+ };
83
+ }
84
+
85
+ function tryReadToken(home) {
86
+ try { return fs.readFileSync(path.join(home, 'token'), 'utf8').trim() || null; } catch { return null; }
87
+ }
88
+
89
+ async function isUp(baseUrl) {
90
+ try {
91
+ const res = await fetch(baseUrl + '/api/health', { signal: AbortSignal.timeout(1500) });
92
+ if (!res.ok) return false;
93
+ const body = await res.json();
94
+ return body && body.ok === true;
95
+ } catch { return false; }
96
+ }
97
+
98
+ function spawnSidecar(s) {
99
+ const child = spawn(process.execPath, [s.entry, 'up', '--port', String(s.port), '--data', s.home], {
100
+ cwd: path.dirname(s.entry),
101
+ env: { ...process.env },
102
+ stdio: 'ignore',
103
+ windowsHide: true,
104
+ });
105
+ const state = { child, error: null };
106
+ child.on('error', (e) => { state.error = e; });
107
+ child.on('exit', (code, signal) => {
108
+ if (code !== 0 && code !== null) state.error = new Error(`sidecar 进程退出 code=${code}${signal ? ` signal=${signal}` : ''}`);
109
+ });
110
+ return state;
111
+ }
112
+
113
+ async function ensureSidecar(s) {
114
+ if (!s.token) s.token = tryReadToken(s.home);
115
+ if (await isUp(s.baseUrl)) return s;
116
+ if (!s.autoStart) {
117
+ throw new Error(`dsh-team sidecar 不可达:${s.baseUrl}。请先运行:node "${s.entry}" up --port ${s.port} --data "${s.home}",或在插件 config 里设 autoStart: true。`);
118
+ }
119
+ if (!s.starting) {
120
+ s.starting = (async () => {
121
+ const spawned = spawnSidecar(s);
122
+ s.spawned = spawned;
123
+ const deadline = Date.now() + s.startTimeoutMs;
124
+ while (Date.now() < deadline) {
125
+ if (spawned.error) throw spawned.error;
126
+ if (await isUp(s.baseUrl)) return;
127
+ await sleep(150);
128
+ }
129
+ throw new Error(`dsh-team sidecar 启动超时(${s.startTimeoutMs}ms):${s.baseUrl}。入口:${s.entry}`);
130
+ })().finally(() => { s.starting = null; });
131
+ }
132
+ await s.starting;
133
+ for (let i = 0; i < 20 && !s.token; i++) { s.token = tryReadToken(s.home); if (!s.token) await sleep(50); }
134
+ return s;
135
+ }
136
+
137
+ async function request(s, pathname, { method = 'GET', body, raw = false } = {}) {
138
+ await ensureSidecar(s);
139
+ const run = async () => fetch(s.baseUrl + pathname, {
140
+ method,
141
+ headers: {
142
+ 'Content-Type': 'application/json',
143
+ ...(s.token ? { Authorization: `Bearer ${s.token}` } : {}),
144
+ },
145
+ body: body === undefined ? undefined : JSON.stringify(body),
146
+ signal: AbortSignal.timeout(s.requestTimeoutMs),
147
+ });
148
+ let res = await run();
149
+ if (res.status === 401) { s.token = tryReadToken(s.home); res = await run(); }
150
+ const text = await res.text();
151
+ if (!res.ok) {
152
+ let detail = text.slice(0, 400);
153
+ try { const j = JSON.parse(text); detail = `${j.error?.code || ''} ${j.error?.message || ''}`.trim() || detail; } catch { /* keep text */ }
154
+ throw new Error(`dsh-team API ${res.status} on ${method} ${pathname}: ${detail}`);
155
+ }
156
+ if (raw) return text;
157
+ try { return JSON.parse(text); } catch { return text; }
158
+ }
159
+
160
+ const panelUrl = (s) => `${s.baseUrl}/panel`;
161
+ const qs = (obj) => {
162
+ const p = new URLSearchParams();
163
+ for (const [k, v] of Object.entries(obj || {})) if (v !== undefined && v !== null && v !== '') p.set(k, String(v));
164
+ const s = p.toString();
165
+ return s ? '?' + s : '';
166
+ };
167
+
168
+ // ---------- agent 运行时:成员 = 真 DSH sub-agent ----------
169
+ //
170
+ // 分工:sidecar 仍是任务/DAG/事件/审批的唯一状态源;本插件负责 agent 生命周期
171
+ // (spawnTeammate / sendMessage / interrupt)和派发,因为只有 Host 进程能创建 DSH agent。
172
+ //
173
+ // 流程:
174
+ // team_spawn(runtime=agent)→ spawnTeammate → POST /api/agents/register 绑定 session
175
+ // team_task 建任务 → sidecar 置 ready → POST /api/agents/dispatch 原子认领(running)
176
+ // → sendMessage(lead → member) 把任务说明投进成员信箱
177
+ // 成员跑完 → team_report_task(精确摘要)/ agent/status=idle(兜底)→ 任务 done → evaluate 推进依赖
178
+ // → 再跑一轮 dispatch,把新 ready 的任务投给 idle 成员
179
+
180
+ /** teamId → 最近一次调用 team_* 工具的 Lead Agent(发消息必须由 live Lead 发出)。 */
181
+ const leadByTeam = new Map();
182
+ /** teamId → 'worker' | 'agent',建团/查团缓存,省掉每次多一次 GET。 */
183
+ const runtimeByTeam = new Map();
184
+ /** DSH sessionId → { teamId, memberId }:把成员的工具 span 归到成员节点下。 */
185
+ const sessionMember = new Map();
186
+ /** DSH sessionId → 上次采集产物时的会话 seq:成员复用同一会话时只上报新产生的文件。 */
187
+ const lastArtifactSeq = new Map();
188
+ /** teamId → 正在派发(防定时器与工具调用重入)。 */
189
+ const dispatching = new Set();
190
+
191
+ /**
192
+ * `subagents` 服务:成员就是它起出来的 continuable 子会话。
193
+ * 只用 optional 访问(`ctx.get`),宿主没装 dsh-subagent 时给出可读的报错,而不是加载失败。
194
+ */
195
+ /** 调用者对应的成员绑定;返回 null 说明调用者是 Lead。成员调用不得覆盖 Lead 句柄。 */
196
+ const memberOfCaller = (agent) => {
197
+ const sid = agent?.sessionId ?? agent?.id ?? null;
198
+ return sid != null ? (sessionMember.get(String(sid)) || null) : null;
199
+ };
200
+ const subagentsOf = (ctx) => { try { return ctx.get('subagents'); } catch { return undefined; } };
201
+ const subagentNames = (ctx) => { const svc = subagentsOf(ctx); return svc && typeof svc.list === 'function' ? svc.list() : []; };
202
+
203
+ /** `sessions` / `workspaceChanges`:读成员自己会话里的交付文件(都是可选依赖)。 */
204
+ const sessionsOf = (ctx) => { try { return ctx.get('sessions'); } catch { return undefined; } };
205
+ const workspaceChangesOf = (ctx) => { try { return ctx.get('workspaceChanges'); } catch { return undefined; } };
206
+
207
+ /**
208
+ * 从成员会话采集产物:
209
+ * 1) `present` 工具声明过的交付文件(带 description,最接近用户在 DSH 里看到的文件卡片);
210
+ * 2) 会话里 `workspace/changes` 事件记录的改动文件(Host 保存 summary,按 seq 取)。
211
+ * 采集失败一律返回空数组——产物只是锦上添花,不能影响任务汇报。
212
+ */
213
+ function collectArtifacts(ctx, sessionId) {
214
+ const sessions = sessionsOf(ctx);
215
+ const session = sessions && typeof sessions.get === 'function' && sessionId ? sessions.get(String(sessionId)) : undefined;
216
+ if (!session) return [];
217
+ let events = [];
218
+ try { events = session.snapshotEvents(); } catch { return []; }
219
+ // 成员复用同一会话跑多个任务:只看上次上报之后的事件,避免把旧产物重复挂到新任务上。
220
+ const key = String(sessionId);
221
+ const since = lastArtifactSeq.get(key) ?? 0;
222
+ const files = new Map();
223
+ const counts = new Map();
224
+ /** 写文件时按行统计(present 只声明文件,不提供行数;workspace 摘要也不一定可用)。 */
225
+ const bump = (p, add, del) => {
226
+ const prev = counts.get(p) || { added: 0, deleted: 0, display: '' };
227
+ counts.set(p, { added: prev.added + add, deleted: prev.deleted + del, display: prev.display });
228
+ };
229
+ const lineCount = (text) => (typeof text === 'string' && text.length ? text.split('\n').length : 0);
230
+ const changes = workspaceChangesOf(ctx);
231
+ for (const ev of events) {
232
+ if (!ev || !ev.type) continue;
233
+ if (Number(ev.seq) <= since) continue;
234
+ if (ev.type === 'tool/call') {
235
+ if (!ev.data) continue;
236
+ const tool = ev.data.name;
237
+ let parsed;
238
+ try { parsed = JSON.parse(ev.data.arguments || '{}'); } catch { parsed = null; }
239
+ if (tool === 'write' && parsed && typeof parsed.file_path === 'string') {
240
+ bump(parsed.file_path, lineCount(parsed.content), 0);
241
+ continue;
242
+ }
243
+ if (tool === 'edit' && parsed && typeof parsed.file_path === 'string') {
244
+ const add = lineCount(parsed.new_string) * (parsed.replace_all ? 1 : 1);
245
+ const del = lineCount(parsed.old_string);
246
+ bump(parsed.file_path, add, del);
247
+ continue;
248
+ }
249
+ if (tool !== 'present') continue;
250
+ for (const f of Array.isArray(parsed?.files) ? parsed.files : []) {
251
+ if (!f || typeof f.path !== 'string' || !f.path.trim()) continue;
252
+ const p = f.path.trim();
253
+ files.set(p, { path: p, label: typeof f.description === 'string' ? f.description : '', source: 'present' });
254
+ }
255
+ } else if (ev.type === 'workspace/changes') {
256
+ let summary;
257
+ try { summary = changes && typeof changes.summary === 'function' ? changes.summary(session.id, ev.seq) : undefined; } catch { summary = undefined; }
258
+ for (const f of Array.isArray(summary?.files) ? summary.files : []) {
259
+ if (!f || typeof f.path !== 'string' || !f.path) continue;
260
+ // 同一文件出现在多轮 summary 里:行数累加;已有工具调用统计时以工具调用为准(更贴近实际写入行数)。
261
+ const prev = counts.get(f.path) || { added: 0, deleted: 0, display: '' };
262
+ if (!prev.added && !prev.deleted) {
263
+ counts.set(f.path, {
264
+ added: prev.added + (Number(f.added) || 0),
265
+ deleted: prev.deleted + (Number(f.deleted) || 0),
266
+ display: typeof f.display === 'string' ? f.display : '',
267
+ });
268
+ }
269
+ if (files.has(f.path)) continue;
270
+ files.set(f.path, { path: f.path, label: '', source: 'workspace' });
271
+ }
272
+ }
273
+ }
274
+ try { lastArtifactSeq.set(key, Number(session.seq) || 0); } catch { /* ignore */ }
275
+ const sameFile = (a, b) => a === b || String(a).endsWith(String(b)) || String(b).endsWith(String(a));
276
+ const findCounts = (p) => {
277
+ const direct = counts.get(p);
278
+ if (direct) return direct;
279
+ for (const [key, c] of counts) if (sameFile(key, p)) return c;
280
+ return undefined;
281
+ };
282
+ const out = [];
283
+ for (const item of files.values()) {
284
+ const c = findCounts(item.path);
285
+ out.push({
286
+ ...item,
287
+ label: item.label || (c && c.display) || '',
288
+ ...(c ? { added: c.added, deleted: c.deleted } : {}),
289
+ });
290
+ }
291
+ for (const [p, c] of counts) {
292
+ let seen = files.has(p);
293
+ if (!seen) for (const item of files.values()) if (sameFile(item.path, p)) { seen = true; break; }
294
+ if (seen) continue;
295
+ out.push({ path: p, label: c.display || '', source: 'workspace', added: c.added, deleted: c.deleted });
296
+ }
297
+ return out.slice(-12);
298
+ }
299
+
300
+ // ---------- 成员上下文分析 ----------
301
+ //
302
+ // 「上下文窗口被什么占满」的唯一事实来源是 DSH 会话:
303
+ // tokenMeter.measure(session) → 当前 surface 上每个事件的价格(seq → tokens)
304
+ // sessionProjections.snapshot(...) → system / tools / messages 三段拆分 + contextWindow
305
+ // session.snapshotEvents() → 事件类型、工具名、压缩记录
306
+ // 这里把它们折叠成面板 ContextMap 需要的 blocks;Host 只算不存,算完 POST 给 sidecar。
307
+ const CONTEXT_FILE_TOOLS = new Set(['read', 'write', 'edit', 'present', 'glob', 'grep', 'ls', 'list', 'glob_files', 'search']);
308
+
309
+ /** 一段消息的可见文本(用于 tile 的 hover 明细)。 */
310
+ function contentText(message) {
311
+ const parts = Array.isArray(message?.content) ? message.content : [];
312
+ for (const part of parts) if (part && typeof part.text === 'string' && part.text.trim()) return part.text;
313
+ return '';
314
+ }
315
+
316
+ /** 第一行、压掉空白,截断到 max。 */
317
+ function firstLine(text, max = 60) {
318
+ return String(text || '').replace(/\s+/g, ' ').trim().slice(0, max);
319
+ }
320
+
321
+ /**
322
+ * 从成员会话折出上下文快照;拿不到会话/事件时返回 null(观测功能不能影响任务)。
323
+ * 返回的结构与 sidecar POST /api/contexts 的 body 对齐(不含 teamId/memberId)。
324
+ */
325
+ function collectContext(ctx, sessionId) {
326
+ const sessions = sessionsOf(ctx);
327
+ const session = sessions && typeof sessions.get === 'function' && sessionId ? sessions.get(String(sessionId)) : undefined;
328
+ if (!session) return null;
329
+ let events = [];
330
+ try { events = session.snapshotEvents(); } catch { return null; }
331
+ const tokenMeter = (() => { try { return ctx.get('tokenMeter'); } catch { return undefined; } })();
332
+ const projections = (() => { try { return ctx.get('sessionProjections'); } catch { return undefined; } })();
333
+
334
+ let measurement = null;
335
+ try {
336
+ if (tokenMeter && typeof tokenMeter.measure === 'function') measurement = tokenMeter.measure(session);
337
+ } catch { measurement = null; }
338
+ let projection = {};
339
+ try {
340
+ if (projections && typeof projections.snapshot === 'function') {
341
+ projection = projections.snapshot(session, ['contextBreakdown', 'contextPressure'])?.values || {};
342
+ }
343
+ } catch { projection = {}; }
344
+ const breakdown = projection.contextBreakdown || {};
345
+ const pressure = projection.contextPressure || {};
346
+
347
+ // 当前 surface 上的事件才计价:被压缩掉的事件不在 nodes 里。
348
+ const priceBySeq = new Map();
349
+ for (const node of Array.isArray(measurement?.nodes) ? measurement.nodes : []) {
350
+ if (!node) continue;
351
+ const tokens = Number(node.tokens) || Number(node.heuristicTokens) || 0;
352
+ priceBySeq.set(Number(node.seq), tokens);
353
+ }
354
+
355
+ const callInfo = new Map(); // callId → { name, target }
356
+ const groups = new Map(); // block id → block
357
+ const push = (id, kind, label, tokens, itemLabel) => {
358
+ let group = groups.get(id);
359
+ if (!group) { group = { id, kind, label, tokens: 0, items: [] }; groups.set(id, group); }
360
+ group.tokens += Math.max(0, Math.round(tokens || 0));
361
+ if (itemLabel && group.items.length < 12) group.items.push({ label: itemLabel });
362
+ return group;
363
+ };
364
+
365
+ let compaction = null;
366
+ let surfaceCount = 0;
367
+ for (const ev of events) {
368
+ if (!ev || !ev.type) continue;
369
+ const data = ev.data || {};
370
+ if (ev.type === 'tool/call') {
371
+ if (data.callId != null) {
372
+ let parsed = null;
373
+ try { parsed = JSON.parse(data.arguments || '{}'); } catch { parsed = null; }
374
+ const target = typeof parsed?.file_path === 'string' ? parsed.file_path
375
+ : typeof parsed?.path === 'string' ? parsed.path
376
+ : typeof parsed?.pattern === 'string' ? parsed.pattern
377
+ : typeof parsed?.command === 'string' ? parsed.command : '';
378
+ callInfo.set(String(data.callId), { name: String(data.name || 'tool'), target: firstLine(target, 80) });
379
+ }
380
+ continue;
381
+ }
382
+ if (ev.type === 'compaction/summary' || ev.type === 'compaction/prune') {
383
+ // 同一次压缩的 summary + prune 只记最后一次(面板只展示最近一次压缩的前后对比)
384
+ compaction = { atSeq: Number(ev.seq) || null, shadowedTokens: Number(data.shadowedTokenCount) || null, summary: 'summary' };
385
+ continue;
386
+ }
387
+ const seq = Number(ev.seq);
388
+ if (!priceBySeq.has(seq)) continue;
389
+ const tokens = priceBySeq.get(seq);
390
+ surfaceCount += 1;
391
+ if (ev.type === 'system/message') { push('system', 'system', 'System prompt', tokens); continue; }
392
+ if (ev.type === 'developer/message') { push('memory', 'memory', 'Memory · 开发者指令', tokens, 'developer message'); continue; }
393
+ if (ev.type === 'user/message') {
394
+ if (ev.surfaceOp && ev.surfaceOp.op === 'replace') { push('summary', 'summary', 'Compaction summary', tokens, '压缩摘要'); continue; }
395
+ push('chat', 'chat', 'Chat · 对话', tokens, firstLine(contentText(data.message)) || 'user message');
396
+ continue;
397
+ }
398
+ if (ev.type === 'assistant/message') { push('chat', 'chat', 'Chat · 对话', tokens); continue; }
399
+ if (ev.type === 'tool/result') {
400
+ const info = callInfo.get(String(data.message?.toolCallId ?? ''));
401
+ const name = info?.name || 'tool';
402
+ const isFile = CONTEXT_FILE_TOOLS.has(name);
403
+ push(`${isFile ? 'file' : 'result'}:${name}`, isFile ? 'file' : 'result', `${isFile ? 'File' : 'Tool result'} · ${name}`, tokens, info?.target || name);
404
+ }
405
+ }
406
+
407
+ let route = {};
408
+ try { route = (typeof session.requestHeader === 'function' ? session.requestHeader()?.config : null) || {}; } catch { route = {}; }
409
+
410
+ const systemTokens = groups.get('system')?.tokens || Number(breakdown.systemTokens) || 0;
411
+ const toolsTokens = Number(breakdown.toolsTokens) || 0;
412
+ const blocks = [];
413
+ if (systemTokens) blocks.push({ id: 'system', label: 'System prompt', kind: 'system', tokens: systemTokens, detail: '系统提示(每次请求固定随行)' });
414
+ if (toolsTokens) blocks.push({ id: 'tools', label: 'Tools', kind: 'tools', tokens: toolsTokens, detail: '工具 schema(每次请求固定随行)' });
415
+ for (const prefix of ['memory', 'file', 'result', 'chat', 'summary']) {
416
+ for (const group of groups.values()) {
417
+ if (!group.id.startsWith(prefix)) continue;
418
+ const detail = group.items.length ? `${group.items.length} 条` : '已进入上下文';
419
+ blocks.push({ id: group.id, label: group.label, kind: group.kind, tokens: group.tokens, detail, items: group.items });
420
+ }
421
+ }
422
+ // 没有可计价节点(tokenMeter 缺席)时退回投影的三段拆分,至少让面板有数据。
423
+ if (!blocks.length) {
424
+ if (Number(breakdown.systemTokens)) blocks.push({ id: 'system', label: 'System prompt', kind: 'system', tokens: Number(breakdown.systemTokens) });
425
+ if (Number(breakdown.toolsTokens)) blocks.push({ id: 'tools', label: 'Tools', kind: 'tools', tokens: Number(breakdown.toolsTokens) });
426
+ if (Number(breakdown.messageTokens)) blocks.push({ id: 'chat', label: 'Chat · 对话', kind: 'chat', tokens: Number(breakdown.messageTokens) });
427
+ }
428
+
429
+ const priced = blocks.reduce((sum, b) => sum + (Number(b.tokens) || 0), 0);
430
+ const used = Number(measurement?.totalTokens) || Number(pressure.pressureTokens) || priced;
431
+ const limit = Number(pressure.contextWindow) || 0;
432
+ return {
433
+ model: route.model ? String(route.model) : null,
434
+ provider: route.provider ? String(route.provider) : null,
435
+ limit,
436
+ used: Math.max(used, priced),
437
+ breakdown: {
438
+ system: systemTokens,
439
+ tools: toolsTokens,
440
+ messages: Number(breakdown.messageTokens) || Math.max(0, used - systemTokens - toolsTokens),
441
+ },
442
+ blocks,
443
+ compaction,
444
+ status: null,
445
+ asOfSeq: Number(session.seq) || null,
446
+ surfaceCount,
447
+ };
448
+ }
449
+
450
+ /** 上次上报时间(按会话节流:period 泵与 agent/status 事件可能同时触发)。 */
451
+ const contextReportAt = new Map();
452
+
453
+ /** 工作区注册表快照:DSH 的 ctx.workspaceRegistry.list() → sidecar,面板左侧工作区下拉用。 */
454
+ function collectWorkspaces(ctx) {
455
+ const registry = ctx.get('workspaceRegistry');
456
+ if (!registry || typeof registry.list !== 'function') return null;
457
+ let list = [];
458
+ try { list = registry.list() || []; } catch { return null; }
459
+ return list.slice(0, 200).map((w, i) => ({
460
+ id: String(w?.id ?? ''),
461
+ title: String(w?.title ?? '').slice(0, 200),
462
+ path: String(w?.path ?? ''),
463
+ position: i,
464
+ })).filter((w) => w.id);
465
+ }
466
+
467
+ /** 工作区列表上报:POST 到 sidecar;返回是否成功(失败时调用方会快速重试)。 */
468
+ async function reportWorkspaces(s, ctx) {
469
+ const items = collectWorkspaces(ctx);
470
+ if (!items) return false;
471
+ try {
472
+ const res = await fetch(s.baseUrl + '/api/workspaces', {
473
+ method: 'POST',
474
+ headers: { 'content-type': 'application/json', ...(s.token ? { authorization: `Bearer ${s.token}` } : {}) },
475
+ body: JSON.stringify({ items }),
476
+ signal: AbortSignal.timeout(1500),
477
+ });
478
+ return res.ok;
479
+ } catch { return false; }
480
+ }
481
+
482
+ /** 子会话 label:`name: description`,上限 200 字符。 */
483
+ const memberLabel = (name, description) => `${name}: ${description}`.slice(0, 200);
484
+
485
+ /** 上下文快照上报:后台 POST,失败即弃。 */
486
+ function reportContextSnapshot(s, ctx, sessionId, { status = null, force = false } = {}) {
487
+ const key = String(sessionId);
488
+ const binding = sessionMember.get(key);
489
+ if (!binding) return;
490
+ const nowMs = Date.now();
491
+ if (!force && nowMs - (contextReportAt.get(key) || 0) < 2000) return;
492
+ contextReportAt.set(key, nowMs);
493
+ const snapshot = collectContext(ctx, key);
494
+ if (!snapshot) return;
495
+ const { surfaceCount, ...payload } = snapshot;
496
+ void fetch(s.baseUrl + '/api/contexts', {
497
+ method: 'POST',
498
+ headers: { 'content-type': 'application/json', ...(s.token ? { authorization: `Bearer ${s.token}` } : {}) },
499
+ body: JSON.stringify({
500
+ ...payload,
501
+ teamId: binding.teamId,
502
+ memberId: binding.memberId,
503
+ sessionId: key,
504
+ status: status || binding.status || null,
505
+ }),
506
+ signal: AbortSignal.timeout(1500),
507
+ }).catch(() => { /* ignore */ });
508
+ }
509
+
510
+ /** 子会话 label:`name: description`,上限 200 字符。 */
511
+
512
+ /** spawnTeammate 需要 provider 名:优先配置值,未注册时退回已注册的第一个可用 provider。 */
513
+ function providerFor(ctx, s, context) {
514
+ const want = context === 'fork' ? s.forkProvider : s.freshProvider;
515
+ const names = subagentNames(ctx);
516
+ if (!names.length || names.includes(want)) return want;
517
+ for (const alt of ['spawn', 'fork', 'default', 'continuable']) if (names.includes(alt)) return alt;
518
+ return names[0];
519
+ }
520
+
521
+ // ---------- 模型路由:DSH ctx.llm 目录 → sidecar 映射 ----------
522
+ //
523
+ // 目录的唯一来源是 Host 的 ctx.llm;这里只把 provider/model 的映射、展示名和
524
+ // 模态同步给 sidecar。sidecar 保存用户勾选的子集与备注,team_spawn 只接受
525
+ // 启用项。本插件不代理 LLM 请求、不保存任何凭据。
526
+ const llmOf = (ctx) => { try { return ctx.get('llm'); } catch { return undefined; } };
527
+
528
+ let llmSyncInFlight = null;
529
+
530
+ /** 同步一次模型目录(并发去重;由插件启动泵与 adapters-updated 事件驱动,不再由工具触发)。 */
531
+ async function syncLlmCatalog(s, ctx) {
532
+ const llm = llmOf(ctx);
533
+ if (!llm || typeof llm.listProviders !== 'function' || typeof llm.listModels !== 'function') {
534
+ return { ok: false, reason: 'llm-unavailable' };
535
+ }
536
+ if (llmSyncInFlight) return llmSyncInFlight;
537
+ llmSyncInFlight = (async () => {
538
+ const seen = new Set();
539
+ const providers = [];
540
+ for (const p of (llm.listProviders() || [])) {
541
+ if (!p || !p.id || seen.has(String(p.id))) continue;
542
+ seen.add(String(p.id));
543
+ providers.push({ id: String(p.id), name: String(p.name || p.id), source: 'live' });
544
+ }
545
+ const models = [];
546
+ let partial = false;
547
+ for (const p of providers) {
548
+ try {
549
+ for (const m of await llm.listModels(p.id)) {
550
+ if (!m || !m.id) continue;
551
+ models.push({
552
+ provider: p.id, model: String(m.id), name: m.name || String(m.id),
553
+ description: m.description || null, modalities: m.inputModalities || null,
554
+ });
555
+ }
556
+ } catch (e) {
557
+ // 单个提供商读取失败:标记 partial,让 sidecar 保留该 provider 已有的勾选
558
+ p.error = clip(String(e?.message || e), 300);
559
+ partial = true;
560
+ }
561
+ }
562
+ // 只上报真正能列出模型的 provider;没模型的(含未配置的 dormant)不进目录,
563
+ // 面板与 team_models 就不会出现空分组。
564
+ const withModels = providers.filter((p) => models.some((m) => m.provider === p.id));
565
+ if (!withModels.length) return { ok: true, providers: 0, models: 0, empty: true };
566
+ await request(s, '/api/llm/catalog', { method: 'POST', body: { providers: withModels, models, partial } });
567
+ return { ok: true, providers: withModels.length, models: models.length, partial };
568
+ })().finally(() => { llmSyncInFlight = null; });
569
+ return llmSyncInFlight;
570
+ }
571
+
572
+ /** Lead 当前 route:请求头优先,创建选项兜底(与 resolveChildAgentOptions 一致)。 */
573
+ function leadRouteOf(caller) {
574
+ if (!caller) return { provider: null, model: null, reasoningEffort: null };
575
+ let cfg;
576
+ try { cfg = typeof caller.session?.requestHeader === 'function' ? caller.session.requestHeader()?.config : undefined; } catch { cfg = undefined; }
577
+ if (cfg) return { provider: cfg.provider ?? null, model: cfg.model ?? null, reasoningEffort: cfg.reasoningEffort ?? null };
578
+ const o = caller.options || {};
579
+ return { provider: o.provider ?? null, model: o.model ?? null, reasoningEffort: o.reasoningEffort ?? null };
580
+ }
581
+
582
+ /** 指定 route 必须在用户启用的子集里;目录尚未同步(为空)时不限制,保持向后兼容。 */
583
+ async function assertRouteEnabled(s, ctx, provider, model) {
584
+ if (!provider && !model) return;
585
+ let cat;
586
+ try { cat = await request(s, '/api/llm/catalog'); } catch { return; }
587
+ const all = (cat.providers || []).flatMap((p) => p.models || []);
588
+ if (!all.length) return;
589
+ // 目录里查不到的 route(例如适配器临时提供、未在 listModels 中声明)不拦,避免误伤;
590
+ // 能查到但被停用的,无论是显式指定还是继承 Lead,都拒绝。
591
+ const known = all.filter((m) => (!provider || m.provider === provider) && (!model || m.model === model));
592
+ if (!known.length) return;
593
+ const enabled = all.filter((m) => m.enabled);
594
+ if (!enabled.length) throw new Error('所有模型路由都已停用:请先在面板「模型路由」页启用,或调用 team_models 查看。');
595
+ if (known.some((m) => m.enabled)) return;
596
+ const sample = enabled.slice(0, 8).map((m) => `${m.provider}/${m.model}`).join(', ');
597
+ throw new Error(`模型路由未启用:${[provider, model].filter(Boolean).join('/')}。可用(前 8 条):${sample}。完整列表见 team_models,或在面板「模型路由」页启用。`);
598
+ }
599
+
600
+ function rememberMember(sessionId, teamId, memberId, cwd) {
601
+ if (sessionId == null) return;
602
+ const key = String(sessionId);
603
+ const prev = sessionMember.get(key);
604
+ // 会话 cwd 只有 spawn 时知道(= team.workspace);派发路径会重复登记同一个会话,
605
+ // 这里不能把它冲成空,否则成员用相对路径写文件时 diff 找不到落盘位置。
606
+ sessionMember.set(key, { teamId: String(teamId), memberId: String(memberId), cwd: cwd || prev?.cwd || '' });
607
+ }
608
+
609
+ async function runtimeOfTeam(s, teamId) {
610
+ const cached = runtimeByTeam.get(teamId);
611
+ if (cached) return cached;
612
+ try {
613
+ const team = await request(s, `/api/teams/${encodeURIComponent(teamId)}`);
614
+ runtimeByTeam.set(teamId, team.runtime || 'worker');
615
+ return team.runtime || 'worker';
616
+ } catch { return 'worker'; }
617
+ }
618
+
619
+ const clip = (text, max) => {
620
+ const v = String(text ?? '');
621
+ return v.length > max ? v.slice(0, max) + '…' : v;
622
+ };
623
+
624
+ /** 成员收到的一条任务说明:必须包含 teamId / taskId 和「跑完怎么回报」。 */
625
+ function taskBrief(teamId, task, member) {
626
+ const plan = (task.plan || []).map((p, i) => {
627
+ const kind = p.op?.kind || p.action || p.phase || 'do';
628
+ const target = p.target ? ` → ${p.target}` : '';
629
+ const args = p.op?.args ? ` ${clip(JSON.stringify(p.op.args), 300)}` : '';
630
+ return `${i + 1}. [${p.step || `S${i + 1}`}] ${kind}${target}${args}`;
631
+ });
632
+ const deps = (task.dependsOn || []).length ? `\n依赖(已完成):${task.dependsOn.join(', ')}` : '';
633
+ const scopes = (task.writeScopes || []).length ? `\n写域(写入请限制在这些前缀内):${task.writeScopes.join(', ')}` : '';
634
+ const acceptance = task.acceptance ? `\n验收标准:${task.acceptance}` : '';
635
+ return [
636
+ '【dsh-team 任务派发】',
637
+ `teamId=${teamId}`,
638
+ `memberId=${member.id}`,
639
+ `memberName=${member.name}`,
640
+ `taskId=${task.id}`,
641
+ `subject:${task.subject}`,
642
+ ...(plan.length ? ['计划步骤:', ...plan] : []),
643
+ ...(deps ? [deps.trim()] : []),
644
+ ...(scopes ? [scopes.trim()] : []),
645
+ ...(acceptance ? [acceptance.trim()] : []),
646
+ '',
647
+ '执行要求:',
648
+ '1) 直接在本会话里做这件事(用你自己的工具,不要委派给别的 agent)。',
649
+ '2) 每开始或完成一步、以及验收通过后,调用 team_todo 更新该任务的计划清单(teamId/taskId 同上)。',
650
+ '3) 完成或失败后必须调用 team_report_task,例如:',
651
+ ` team_report_task({ teamId: "${teamId}", taskId: "${task.id}", status: "done", summary: "一句话结果 + 关键产物路径" })`,
652
+ '4) 需要 Lead 决策或补充信息时用 team_send(teamId 同上,to: "lead"),不要自己猜测。',
653
+ ].join('\n');
654
+ }
655
+
656
+ /** 把任务投递给成员:由 Lead 发一条消息进成员信箱(running 时在最近 step 边界送达)。 */
657
+ async function deliverTask(s, ctx, lead, teamId, task, member) {
658
+ const subs = subagentsOf(ctx);
659
+ if (!subs || typeof subs.sendMessage !== 'function') throw new Error('subagents 服务不可用,无法派发给 agent 成员');
660
+ if (!member.agentSessionId) throw new Error(`成员 ${member.name} 还没有绑定 sub-agent 会话`);
661
+ const brief = taskBrief(teamId, task, member);
662
+ // 简报本身就是一条 Lead→成员的消息:先落信箱,面板【消息与回执】才有「提问 → 回复」可配对;
663
+ // 记录失败不影响派发本身。
664
+ let messageId = null;
665
+ try {
666
+ const recorded = await request(s, '/api/messages', {
667
+ method: 'POST',
668
+ body: { teamId, from: 'lead', to: member.id, kind: 'note', payload: { text: brief, taskId: task.id } },
669
+ });
670
+ messageId = recorded?.message?.id || null;
671
+ } catch { messageId = null; }
672
+ const content = [{ type: 'text', text: brief }];
673
+ await subs.sendMessage(lead, String(member.agentSessionId), content, { signal: AbortSignal.timeout(s.requestTimeoutMs) });
674
+ await markDelivered(s, messageId);
675
+ }
676
+
677
+ /**
678
+ * 泵一次派发:反复「认领 + 投递」直到没有 idle 成员或没有 ready 任务。
679
+ * 调用者尽量是 Lead 自己的工具调用(此时 lead 一定 live);兜底用缓存的 Lead。
680
+ */
681
+ async function dispatchLoop(s, ctx, teamId) {
682
+ const lead = leadByTeam.get(teamId);
683
+ if (!lead) return { dispatched: [], reason: 'no_lead_agent' };
684
+ if (dispatching.has(teamId)) return { dispatched: [], reason: 'busy' };
685
+ dispatching.add(teamId);
686
+ const dispatched = [];
687
+ try {
688
+ for (let i = 0; i < s.agentDispatchMax; i++) {
689
+ let r;
690
+ try {
691
+ r = await request(s, '/api/agents/dispatch', { method: 'POST', body: { teamId } });
692
+ } catch (err) {
693
+ return { dispatched, error: String(err?.message || err) };
694
+ }
695
+ if (!r || !r.dispatched) {
696
+ return {
697
+ dispatched,
698
+ ...(r && r.reason ? { reason: r.reason } : {}),
699
+ // sidecar 的附加诊断(建图窗口等)原样透传,别让 Lead 看到「no_ready_task」就以为依赖写错了
700
+ ...(r && r.settled ? { settled: r.settled } : {}),
701
+ ...(r && r.hint ? { hint: r.hint } : {}),
702
+ };
703
+ }
704
+ const { task, member } = r;
705
+ // 先记绑定再投递:成员第一轮 LLM 调用可能在 sendMessage 返回后就已开始
706
+ if (member.agentSessionId) rememberMember(member.agentSessionId, teamId, member.id);
707
+ // 任务已投递:先按「在跑」记账,agent/status 的 running 事件可能因为状态未变化而不发
708
+ if (member.agentSessionId) agentStatusBySession.set(String(member.agentSessionId), 'running');
709
+ try {
710
+ await deliverTask(s, ctx, lead, teamId, task, member);
711
+ } catch (err) {
712
+ // 投递失败:把任务交回 sidecar(走失败重试),不要把任务挂死在 running
713
+ await request(s, '/api/agents/report', {
714
+ method: 'POST',
715
+ body: { sessionId: member.agentSessionId, status: 'failed', summary: `派发失败:${String(err?.message || err)}` },
716
+ }).catch(() => { /* ignore */ });
717
+ return { dispatched, error: `sendMessage failed: ${String(err?.message || err)}` };
718
+ }
719
+ dispatched.push({ taskId: task.id, task: task.subject, member: member.name });
720
+ }
721
+ return { dispatched, reason: 'max_rounds' };
722
+ } finally {
723
+ dispatching.delete(teamId);
724
+ }
725
+ }
726
+
727
+ /** agent/status 回写 sidecar:idle 时兜底收尾在途任务,running 时置 running。 */
728
+ function reportAgentStatus(s, sessionId, status, detail) {
729
+ if (!sessionId) return;
730
+ const body = JSON.stringify({ sessionId: String(sessionId), status, ...(detail ? { detail: clip(detail, 500) } : {}) });
731
+ void fetch(s.baseUrl + '/api/agents/status', {
732
+ method: 'POST',
733
+ headers: { 'content-type': 'application/json', ...(s.token ? { authorization: `Bearer ${s.token}` } : {}) },
734
+ body,
735
+ signal: AbortSignal.timeout(1500),
736
+ }).catch(() => { /* ignore */ });
737
+ }
738
+
739
+ /** 成员会话最近一次上报给 sidecar 的状态(心跳据此判断有没有漏报)。 */
740
+ const agentStatusBySession = new Map();
741
+ /** sessionId → 待落库的 idle 上报定时器。 */
742
+ const idleTimers = new Map();
743
+
744
+ function cancelIdleReport(sessionId) {
745
+ const timer = idleTimers.get(sessionId);
746
+ if (timer) { clearTimeout(timer); idleTimers.delete(sessionId); }
747
+ }
748
+
749
+ /** 直接读 sidecar /status(不经 request:心跳/镜像不能顺手把 sidecar 拉起来)。 */
750
+ async function readStatus(s) {
751
+ try {
752
+ const res = await fetch(s.baseUrl + '/api/status', {
753
+ headers: s.token ? { authorization: `Bearer ${s.token}` } : undefined,
754
+ signal: AbortSignal.timeout(2000),
755
+ });
756
+ if (!res.ok) return null;
757
+ return await res.json();
758
+ } catch { return null; }
759
+ }
760
+
761
+ /** DSH 内置 todo 的状态 → sidecar 计划步骤的状态。 */
762
+ const TODO_TO_PLAN = { pending: 'open', in_progress: 'active', completed: 'done' };
763
+
764
+ /**
765
+ * 成员没用 team_todo、而是用了内置 todo_write 时,把 DSH 的 `todos` 投影镜像成 sidecar 计划。
766
+ * todo_write 每次整份替换,这里也整份替换(POST /api/tasks/<taskId>/todos),
767
+ * 于是「todo 完成 → 计划步骤完成」自动同步,面板与团队校验都能看到成员的真实 plan。
768
+ */
769
+ async function mirrorTodos(s, ctx, sessionId) {
770
+ const sid = sessionId != null ? String(sessionId) : '';
771
+ if (!sid || !sessionMember.has(sid)) return;
772
+ const sessions = sessionsOf(ctx);
773
+ const session = sessions && typeof sessions.get === 'function' ? sessions.get(sid) : undefined;
774
+ if (!session) return;
775
+ const projections = (() => { try { return ctx.get('sessionProjections'); } catch { return undefined; } })();
776
+ let todos = null;
777
+ try {
778
+ if (projections && typeof projections.stateOf === 'function') todos = projections.stateOf(session, 'todos');
779
+ else if (projections && typeof projections.snapshot === 'function') todos = projections.snapshot(session, ['todos'])?.values?.todos;
780
+ } catch { todos = null; }
781
+ if (!Array.isArray(todos) || todos.length === 0) return;
782
+ const items = todos.slice(0, 50).map((todo) => ({
783
+ title: clip(String(todo?.content || ''), 200),
784
+ status: TODO_TO_PLAN[String(todo?.status || '')] || 'open',
785
+ })).filter((item) => item.title);
786
+ if (items.length === 0) return;
787
+ const status = await readStatus(s);
788
+ const member = ((status && status.members) || []).find((m) => m && String(m.agentSessionId || '') === sid);
789
+ if (!member || !member.currentTaskId) return; // 还没有在途任务:等派发后下一次 todo_write/收工再镜像
790
+ await request(s, `/api/tasks/${encodeURIComponent(member.currentTaskId)}/todos`, {
791
+ method: 'POST',
792
+ body: { items, by: member.id },
793
+ }).catch(() => { /* 计划镜像失败不影响任务本身 */ });
794
+ }
795
+
796
+ /** 心跳:本地认为在跑、sidecar 却回落到 idle(且有在途任务)时补报 running。 */
797
+ async function heartbeatAgentStatus(s) {
798
+ if (sessionMember.size === 0) return;
799
+ const status = await readStatus(s);
800
+ if (!status) return;
801
+ const bySession = new Map();
802
+ for (const member of status.members || []) {
803
+ if (member && member.agentSessionId) bySession.set(String(member.agentSessionId), member);
804
+ }
805
+ for (const sessionId of sessionMember.keys()) {
806
+ if (idleTimers.has(sessionId)) continue; // idle 正在等稳定窗口,别把它救回 running
807
+ if (agentStatusBySession.get(sessionId) !== 'running') continue;
808
+ const member = bySession.get(sessionId);
809
+ if (!member || !member.currentTaskId) continue; // 没有在途任务:可能真的闲下来了
810
+ if (member.status === 'running') continue;
811
+ reportAgentStatus(s, sessionId, 'running', 'heartbeat');
812
+ }
813
+ }
814
+
815
+ /** 消息推进成员信箱后补记「送达」:面板不再把已送达的消息显示成 queued。 */
816
+ async function markDelivered(s, messageId) {
817
+ if (!messageId) return;
818
+ await request(s, `/api/messages/${encodeURIComponent(messageId)}/ack`, {
819
+ method: 'POST',
820
+ body: { state: 'delivered' },
821
+ }).catch(() => { /* 回执补记失败不影响投递 */ });
822
+ }
823
+
824
+ /** 成员会话这一轮最后的助手正文:收工时落库成 member→lead 的回复消息。 */
825
+ const lastReplyBySession = new Map();
826
+
827
+ /** 从 assistant/message 的 content 里取正文;纯工具调用步骤没有正文,返回空串。 */
828
+ function assistantReplyText(message) {
829
+ const content = message && Array.isArray(message.content) ? message.content : [];
830
+ const parts = [];
831
+ for (const block of content) {
832
+ if (block && block.type === 'text' && typeof block.text === 'string' && block.text.trim()) {
833
+ parts.push(block.text.trim());
834
+ }
835
+ }
836
+ return parts.join('\n').trim();
837
+ }
838
+
839
+ /**
840
+ * 把成员这一轮的结论作为 member→lead 的消息落库(kind=response)。
841
+ * 成员用 send_message / team_report_task 回话都不经过消息总线,面板里只剩 Lead 单向提问;
842
+ * 收工时补一条回复,【消息与回执】才能配对成双向箭头并展示两条正文。
843
+ */
844
+ async function flushMemberReply(s, sessionId) {
845
+ const sid = sessionId != null ? String(sessionId) : '';
846
+ if (!sid) return;
847
+ const binding = sessionMember.get(sid);
848
+ const text = lastReplyBySession.get(sid) || '';
849
+ lastReplyBySession.delete(sid);
850
+ if (!binding || !text) return;
851
+ await request(s, '/api/messages', {
852
+ method: 'POST',
853
+ body: {
854
+ teamId: binding.teamId,
855
+ from: binding.memberId,
856
+ to: 'lead',
857
+ kind: 'response',
858
+ payload: { text: clip(text, 4000) },
859
+ },
860
+ }).catch(() => { /* 回复落库失败不影响任务收尾 */ });
861
+ }
862
+
863
+ // ---------- 工具 schema 片段 ----------
864
+ const PLAN_STEP = {
865
+ type: 'object',
866
+ additionalProperties: true,
867
+ description: 'One observable action executed by a worker process through the sidecar permission broker.',
868
+ properties: {
869
+ step: { type: 'string', description: 'Step label, e.g. S1.' },
870
+ phase: {
871
+ type: 'string',
872
+ description: 'Event phase used in the timeline: init|read|write|exec|net|env|msg|wait|verify|done|fail.',
873
+ },
874
+ action: { type: 'string', description: 'Verb shown in the timeline, e.g. write / read / exec.' },
875
+ target: { type: 'string', description: 'File path, command, host, or env name this step touches.' },
876
+ op: {
877
+ type: 'object',
878
+ additionalProperties: true,
879
+ description: 'The proxied action. kind: fs.read{path} | fs.write{path,content,expectVersion?} | fs.append{path,marker,retries?} | fs.list{path} | exec{argv,cwd?,timeoutMs?} | net{url,method?,headers?,body?} | env{name} | sleep{ms} | escape{} | scope{domain,target,reason,then?} | fail{message,retryable?} | noop.',
880
+ properties: { kind: { type: 'string' } },
881
+ required: ['kind'],
882
+ },
883
+ onDenied: { type: 'string', enum: ['scope'], description: "Escalate a denied action into a scope request instead of failing the task." },
884
+ scopeReason: { type: 'string' },
885
+ scopeTimeoutMs: { type: 'integer' },
886
+ fatal: { type: 'boolean' },
887
+ },
888
+ required: ['step', 'op'],
889
+ };
890
+
891
+ const MEMBER_FIELDS = {
892
+ id: { type: 'string' },
893
+ name: { type: 'string' },
894
+ status: { type: 'string' },
895
+ step: { type: ['string', 'null'] },
896
+ seq: { type: 'integer' },
897
+ pct: { type: ['number', 'null'] },
898
+ next: { type: ['string', 'null'] },
899
+ stale: { type: 'boolean' },
900
+ };
901
+
902
+ const jsonOutput = (description) => ({
903
+ schema: { type: 'object', additionalProperties: true, description },
904
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
905
+ });
906
+ const textOutput = () => ({
907
+ schema: { type: 'object', additionalProperties: true },
908
+ render: (_args, value) => [{ type: 'text', text: String(value?.markdown ?? value) }],
909
+ });
910
+
911
+ /** 构造全部工具(普通 ToolDefinition,不依赖 defineTool;参数即 JSON Schema)。 */
912
+ function buildTools(s, ctx) {
913
+ const tools = [];
914
+
915
+ tools.push({
916
+ name: 'team_create',
917
+ description: 'START HERE to build a working team of agents. Order: team_create({name, workspace, runtime:"agent"}) → team_models() to see the enabled provider/model routes → team_spawn({teamId, name, prompt, agentProvider?, model?, reasoningEffort?}) once per member, choosing a cheap/fast route for mechanical work and a strong-reasoning route for architecture, debugging, or review → team_task({teamId, subject, assignee?, acceptance}) per DAG node → each member finishes by calling team_report_task → inspect with team_status / team_report. `runtime` is the one field that changes what a member IS: `agent` spawns real DSH sub-agent sessions (own model, tools, context) that you talk to and that report back; `worker` (default) creates inert plan-step slots that only run proxied fs/exec/net/env ops from a task `plan` and cannot think. If the user says "create an agent team", pass runtime:"agent". A team owns members, a task DAG, and the four-domain (fs/exec/net/env) permission policy. `workspace` is an absolute directory shared by the members (worker members may only touch it through the sidecar broker; agent members get it as their cwd). Keep teamId from this response (result.team.id): every later call needs it. For the full recipe with per-field pitfalls, load the skill "dsh-agent-team".',
918
+ parameters: {
919
+ type: 'object',
920
+ additionalProperties: false,
921
+ properties: {
922
+ name: { type: 'string', description: 'Team name.' },
923
+ workspace: { type: 'string', description: 'Absolute directory shared by workers; created if missing.' },
924
+ runtime: { type: 'string', enum: ['worker', 'agent'], description: "Member runtime. `agent` spawns real DSH sub-agent members (real models, real tool calls). Default worker." },
925
+ maxMembers: { type: 'integer', description: 'Member cap, 0 means unlimited. Default 64. Extra members are queued, never errors.' },
926
+ maxConcurrency: { type: 'integer', description: 'Max simultaneously running tasks. Default 8.' },
927
+ failurePolicy: { type: 'string', enum: ['continue', 'abort'], description: 'Team-level default failure policy.' },
928
+ maxAttempts: { type: 'integer', description: 'Per-task retry cap. Default 3.' },
929
+ },
930
+ required: ['name', 'workspace'],
931
+ },
932
+ output: jsonOutput('{ team, panel }'),
933
+ async execute(args, exec) {
934
+ const team = await request(s, '/api/teams', {
935
+ method: 'POST',
936
+ body: {
937
+ name: args.name,
938
+ workspace: args.workspace,
939
+ ...(args.runtime !== undefined ? { runtime: args.runtime } : {}),
940
+ ...(args.maxMembers !== undefined ? { maxMembers: args.maxMembers } : {}),
941
+ ...(args.maxConcurrency !== undefined ? { maxConcurrency: args.maxConcurrency } : {}),
942
+ ...(args.failurePolicy !== undefined ? { failurePolicy: args.failurePolicy } : {}),
943
+ ...(args.maxAttempts !== undefined ? { maxAttempts: args.maxAttempts } : {}),
944
+ ...(exec?.agent && exec.agent.id != null ? { leadSessionId: String(exec.agent.id) } : {}),
945
+ },
946
+ });
947
+ runtimeByTeam.set(team.id, team.runtime || 'worker');
948
+ if (exec?.agent) leadByTeam.set(team.id, exec.agent);
949
+ return { team, panel: panelUrl(s) };
950
+ },
951
+ });
952
+
953
+ tools.push({
954
+ name: 'team_spawn',
955
+ description: "Add one member to a team; returns the member `id` you use as team_task's `assignee`. On a `worker` team this is a sandboxed Node slot that executes plan steps through the sidecar permission broker. On an `agent` team this SPAWNS A REAL DSH SUB-AGENT session (`subagents.startActivation`, continuable child) that owns its own model, context, tools and message inbox; `prompt` is required there and becomes the member's first instruction — the member cannot see your conversation, so state the team id, its job, the workspace, and end with: finish by calling team_report_task({teamId, taskId, status, summary}). Over the member cap the member becomes `queued` instead of failing. Members are reusable: they run one task at a time and return to `idle`. Model routing (agent teams): call team_models first, then pass `agentProvider` + `model` to fit the task — a cheap/fast route for mechanical edits and lookups, a strong-reasoning route for architecture, debugging, or review. Pass `reasoningEffort` when the model exposes one; omitting it inherits the Lead's effort only while the route stays the same, otherwise the model's default applies. Omit agentProvider/model to inherit the Lead's route.",
956
+ parameters: {
957
+ type: 'object',
958
+ additionalProperties: false,
959
+ properties: {
960
+ teamId: { type: 'string', description: 'Team id from team_create.' },
961
+ name: { type: 'string', description: 'Unique member name inside the team; this is the addressable target.' },
962
+ role: { type: 'string', description: 'Role label, also usable as a policy subject (subjectType=role).' },
963
+ agentProvider: { type: 'string', description: 'LLM provider route id for an agent member, as returned by team_models. Omit to inherit the Lead\'s provider. Must be an enabled route in the team panel.' },
964
+ model: { type: 'string', description: 'LLM model id for an agent member, as returned by team_models. On worker teams it is only a display label. Changing the route clears inherited reasoning effort unless reasoningEffort is set explicitly.' },
965
+ reasoningEffort: { type: 'string', description: 'Adapter-defined reasoning effort id for an agent member (for example low / medium / high, when the model supports them). Omit to inherit the Lead\'s effort while the route is unchanged; a changed route falls back to the model default.' },
966
+ contextMode: { type: 'string', enum: ['isolated', 'fresh', 'fork'], description: 'Context isolation: `fresh` starts with no Lead history, `fork` inherits completed Lead turns (agent teams only). Default isolated/fresh.' },
967
+ prompt: { type: 'string', description: 'agent teams only (required there): the member’s first instruction. Tell it its role, workspace, and that it must call team_report_task when done.' },
968
+ description: { type: 'string', description: 'agent teams only: one-line description of what this member is responsible for.' },
969
+ },
970
+ required: ['teamId', 'name'],
971
+ },
972
+ output: jsonOutput('{ member, agent?, panel }'),
973
+ async execute(args, exec) {
974
+ const runtime = await runtimeOfTeam(s, args.teamId);
975
+ if (runtime !== 'agent') {
976
+ const member = await request(s, `/api/teams/${encodeURIComponent(args.teamId)}/members`, {
977
+ method: 'POST',
978
+ body: {
979
+ name: args.name,
980
+ ...(args.role !== undefined ? { role: args.role } : {}),
981
+ ...(args.model !== undefined ? { model: args.model } : {}),
982
+ ...(args.contextMode !== undefined ? { contextMode: args.contextMode } : {}),
983
+ },
984
+ });
985
+ return { member, panel: panelUrl(s) };
986
+ }
987
+
988
+ // ---- agent 团队:用 subagents 服务起一个 continuable 真子会话 ----
989
+ const subs = subagentsOf(ctx);
990
+ if (!subs || typeof subs.startActivation !== 'function') {
991
+ throw new Error('subagents 服务不可用:无法在 agent 团队里创建 sub-agent 成员(需要宿主启用 dsh-subagent)。');
992
+ }
993
+ const caller = exec?.agent;
994
+ if (!caller) throw new Error('team_spawn (agent) 需要 Lead 会话上下文(exec.agent 缺失:不能在非 agent 调用里起成员)。');
995
+ if (!args.prompt) throw new Error('agent 团队的 team_spawn 需要 prompt(成员的初始指令)。');
996
+
997
+ const context = args.contextMode === 'fork' ? 'fork' : 'fresh';
998
+ const provider = providerFor(ctx, s, context);
999
+ // 实际 route:显式参数覆盖 Lead;effort 只在 route 未变时继承(与 DSH 子会话合并规则一致)
1000
+ const leadRoute = leadRouteOf(caller);
1001
+ const route = { provider: args.agentProvider || leadRoute.provider, model: args.model || leadRoute.model };
1002
+ const routeChanged = route.provider !== leadRoute.provider || route.model !== leadRoute.model;
1003
+ route.reasoningEffort = args.reasoningEffort || (routeChanged ? null : leadRoute.reasoningEffort);
1004
+ // 继承 Lead 的 route 也要过启用闸门:停用项不该被成员继续使用。
1005
+ await assertRouteEnabled(s, ctx, route.provider, route.model);
1006
+ const agentOptions = {};
1007
+ if (args.agentProvider) agentOptions.provider = String(args.agentProvider);
1008
+ if (args.model) agentOptions.model = String(args.model);
1009
+ if (args.reasoningEffort) agentOptions.reasoningEffort = String(args.reasoningEffort);
1010
+ const memberName = String(args.name).trim();
1011
+ const description = String(args.description || args.role || memberName).slice(0, 200);
1012
+ const sessionId = randomUUID();
1013
+ const team = await request(s, `/api/teams/${encodeURIComponent(args.teamId)}`).catch(() => null);
1014
+ const started = await subs.startActivation({
1015
+ delivery: 'parent',
1016
+ childId: sessionId,
1017
+ provider,
1018
+ label: memberLabel(memberName, description),
1019
+ request: {
1020
+ prompt: [{ type: 'text', text: String(args.prompt) }],
1021
+ parent: caller,
1022
+ ...(team && team.workspace ? { cwd: team.workspace } : {}),
1023
+ ...(Object.keys(agentOptions).length ? { agentOptions } : {}),
1024
+ },
1025
+ signal: exec.signal || AbortSignal.timeout(s.requestTimeoutMs),
1026
+ });
1027
+ // 成员跑的是一整轮 agent loop,结果由 team_report_task 汇报;这里只防止未处理的 rejection。
1028
+ if (started && started.result && typeof started.result.catch === 'function') started.result.catch(() => {});
1029
+ const spawned = { member: { id: sessionId, name: memberName, role: 'teammate', status: 'running', model: route.model || null, diagnostics: [] } };
1030
+
1031
+ const registered = await request(s, '/api/agents/register', {
1032
+ method: 'POST',
1033
+ body: {
1034
+ teamId: args.teamId,
1035
+ name: memberName,
1036
+ sessionId,
1037
+ role: args.role || 'teammate',
1038
+ model: args.model || spawned.member.model || null,
1039
+ contextMode: context,
1040
+ },
1041
+ });
1042
+ rememberMember(sessionId, args.teamId, registered.member.id, team?.workspace);
1043
+ leadByTeam.set(args.teamId, caller);
1044
+ return {
1045
+ member: registered.member,
1046
+ agent: {
1047
+ sessionId,
1048
+ name: spawned.member.name,
1049
+ status: spawned.member.status,
1050
+ role: spawned.member.role,
1051
+ provider,
1052
+ context,
1053
+ model: route.model || null,
1054
+ route,
1055
+ diagnostics: spawned.member.diagnostics || [],
1056
+ },
1057
+ panel: panelUrl(s),
1058
+ };
1059
+ },
1060
+ });
1061
+
1062
+ tools.push({
1063
+ name: 'team_models',
1064
+ description: 'List the model routes enabled for this team: provider id, model id, display name, note, and modalities. Use it before team_spawn when a task should run on a different model or reasoning effort than the Lead — a cheap/fast route for mechanical work, a strong-reasoning route for architecture, debugging, or review. Only the user-enabled subset is listed; the panel curates it. Pass a listed pair to team_spawn({ agentProvider, model, reasoningEffort }).',
1065
+ parameters: {
1066
+ type: 'object',
1067
+ additionalProperties: false,
1068
+ properties: {},
1069
+ },
1070
+ output: jsonOutput('{ asOf, total, models: [{ provider, model, name, description, note, modalities }], hint? }'),
1071
+ isConcurrencySafe: () => true,
1072
+ async execute() {
1073
+ let cat = null;
1074
+ try { cat = await request(s, '/api/llm/catalog'); } catch { /* catalog unavailable */ }
1075
+ const all = cat ? (cat.providers || []).flatMap((p) => p.models || []) : [];
1076
+ const models = all.filter((m) => m.enabled).map((m) => ({
1077
+ provider: m.provider,
1078
+ model: m.model,
1079
+ name: m.name,
1080
+ ...(m.description ? { description: m.description } : {}),
1081
+ ...(m.note ? { note: m.note } : {}),
1082
+ ...(m.modalities ? { modalities: m.modalities } : {}),
1083
+ }));
1084
+ const hint = models.length
1085
+ ? '在 team_spawn 里用 agentProvider + model;reasoningEffort 由模型适配器定义,省略时只在 route 不变时继承 Lead 的 effort。'
1086
+ : '没有启用的模型路由:请让用户在面板「模型路由」页勾选需要的 provider/model。';
1087
+ return {
1088
+ asOf: cat?.asOf || new Date().toISOString(),
1089
+ total: models.length,
1090
+ models,
1091
+ hint,
1092
+ };
1093
+ },
1094
+ });
1095
+
1096
+ tools.push({
1097
+ name: 'team_status',
1098
+ description: 'Read a live snapshot instead of guessing progress. detail=summary returns every member with status/step/seq/percent/next/blockers/lease/stale; detail=dag returns the task DAG with dependencies, readiness, joins and the critical path. `asOf` marks the snapshot time.',
1099
+ parameters: {
1100
+ type: 'object',
1101
+ additionalProperties: false,
1102
+ properties: {
1103
+ teamId: { type: 'string' },
1104
+ detail: { type: 'string', enum: ['summary', 'dag'], description: 'Default summary.' },
1105
+ },
1106
+ required: ['teamId'],
1107
+ },
1108
+ output: jsonOutput('{ asOf, version, panel, members? , ready?, criticalPath?, nodes?, edges? }'),
1109
+ isConcurrencySafe: () => true,
1110
+ async execute(args) {
1111
+ if ((args.detail || 'summary') === 'dag') {
1112
+ const dag = await request(s, `/api/dag${qs({ team: args.teamId })}`);
1113
+ return { ...dag, panel: panelUrl(s) };
1114
+ }
1115
+ const st = await request(s, `/api/status${qs({ team: args.teamId })}`);
1116
+ return {
1117
+ asOf: st.asOf,
1118
+ version: st.version,
1119
+ panel: panelUrl(s),
1120
+ runtime: st.runtime || runtimeByTeam.get(args.teamId) || 'worker',
1121
+ members: (st.members || []).map((m) => ({
1122
+ name: m.name,
1123
+ status: m.status,
1124
+ step: m.step,
1125
+ seq: m.seq,
1126
+ pct: m.pct,
1127
+ next: m.next,
1128
+ last: m.last,
1129
+ currentTaskId: m.currentTaskId,
1130
+ leaseUntil: m.leaseUntil,
1131
+ blockers: m.blockers,
1132
+ stale: m.stale,
1133
+ agentSessionId: m.agentSessionId || null,
1134
+ agentStatus: m.agentStatus || null,
1135
+ })),
1136
+ staleMembers: st.staleMembers,
1137
+ degraded: st.degraded,
1138
+ };
1139
+ },
1140
+ });
1141
+
1142
+ tools.push({
1143
+ name: 'team_task',
1144
+ description: 'Declare one task (DAG node) and hand it to a member. Two runtimes: on a `worker` team each plan step is one proxied action executed through the sidecar broker (the worker process has no direct IO, so a denied step fails hard); on an `agent` team the plan is a BRIEF sent to the member’s own sub-agent session, which does the work with its own tools and calls team_report_task when finished — write the brief self-contained (the member does not see this conversation). `assignee` takes a member **id** from team_spawn, not its name; omit it to let the scheduler pick an idle member. The scheduler satisfies dependencies itself — never poll. Creating a task on an agent team dispatches it immediately to an idle member when dependencies are already satisfied.',
1145
+ parameters: {
1146
+ type: 'object',
1147
+ additionalProperties: false,
1148
+ properties: {
1149
+ teamId: { type: 'string' },
1150
+ subject: { type: 'string', description: 'Concise task title.' },
1151
+ assignee: { type: 'string', description: 'Member id (not name). Omit to let the scheduler pick an idle member.' },
1152
+ plan: { type: 'array', items: PLAN_STEP, description: 'Ordered steps. Worker teams: proxied actions. Agent teams: the task brief (usually omit and describe the work in `subject` + `acceptance`). May be empty for a pure heartbeat task.' },
1153
+ deps: {
1154
+ type: 'array',
1155
+ description: 'Upstream dependencies declared atomically with the task: [{from, condition?, artifactPath?}].',
1156
+ items: {
1157
+ type: 'object',
1158
+ additionalProperties: false,
1159
+ properties: {
1160
+ from: { type: 'string', description: 'Upstream task id.' },
1161
+ condition: { type: 'string', enum: ['all_success', 'any_success', 'on_failure', 'artifact_exists'] },
1162
+ artifactPath: { type: 'string', description: 'Workspace-relative path for condition=artifact_exists.' },
1163
+ },
1164
+ required: ['from'],
1165
+ },
1166
+ },
1167
+ writeScopes: { type: 'array', items: { type: 'string' }, description: 'Advisory write scope prefixes (sidecar policies are the enforced ones).' },
1168
+ acceptance: { type: 'string' },
1169
+ priority: { type: 'integer', description: 'Smaller runs first. Default 0.' },
1170
+ failurePolicy: { type: 'string', enum: ['continue', 'skip', 'abort_team', 'retry'] },
1171
+ maxAttempts: { type: 'integer' },
1172
+ dispatch: { type: 'boolean', description: 'Agent teams only: dispatch immediately after creating (default true). Pass false to build the DAG first and dispatch later with team_dispatch.' },
1173
+ },
1174
+ required: ['teamId', 'subject', 'plan'],
1175
+ },
1176
+ output: jsonOutput('{ task, dispatched? }'),
1177
+ async execute(args, exec) {
1178
+ if (exec?.agent && !memberOfCaller(exec.agent)) leadByTeam.set(args.teamId, exec.agent);
1179
+ const task = await request(s, '/api/tasks', {
1180
+ method: 'POST',
1181
+ body: {
1182
+ teamId: args.teamId,
1183
+ subject: args.subject,
1184
+ ...(args.assignee !== undefined ? { assignee: args.assignee } : {}),
1185
+ plan: args.plan || [],
1186
+ ...(args.deps !== undefined ? { deps: args.deps } : {}),
1187
+ ...(args.writeScopes !== undefined ? { writeScopes: args.writeScopes } : {}),
1188
+ ...(args.acceptance !== undefined ? { acceptance: args.acceptance } : {}),
1189
+ ...(args.priority !== undefined ? { priority: args.priority } : {}),
1190
+ ...(args.failurePolicy !== undefined ? { failurePolicy: args.failurePolicy } : {}),
1191
+ ...(args.maxAttempts !== undefined ? { maxAttempts: args.maxAttempts } : {}),
1192
+ },
1193
+ });
1194
+ if (args.dispatch === false || (await runtimeOfTeam(s, args.teamId)) !== 'agent') return { task };
1195
+ await sleep(s.agentSettleMs);
1196
+ const dispatched = await dispatchLoop(s, ctx, args.teamId);
1197
+ return { task, dispatched };
1198
+ },
1199
+ });
1200
+
1201
+ tools.push({
1202
+ name: 'team_send',
1203
+ description: "Send a message that a member will actually read. On `agent` teams the text is injected into the target sub-agent's message inbox (a running member sees it at its next step boundary, an idle member is woken); on `worker` teams it is queued on the sidecar and surfaced at the worker's next step boundary. `to` is a member NAME on agent teams (member id also accepted) or '*' to broadcast. Every send is also recorded on the sidecar so the panel shows the conversation.",
1204
+ parameters: {
1205
+ type: 'object',
1206
+ additionalProperties: false,
1207
+ properties: {
1208
+ teamId: { type: 'string' },
1209
+ to: { type: 'string', description: "Member name (agent teams) or member id, or '*' for broadcast." },
1210
+ message: { type: 'string', description: 'Message body.' },
1211
+ correlationId: { type: 'string', description: 'Optional correlation id to pair a request with its response.' },
1212
+ },
1213
+ required: ['teamId', 'to', 'message'],
1214
+ },
1215
+ output: jsonOutput('{ message, messages?, delivered? }'),
1216
+ async execute(args, exec) {
1217
+ // 调用者可能是 Lead,也可能是某个成员(成员用 send_message 工具调用本工具时 exec.agent 就是成员会话)。
1218
+ const callerSessionId = exec?.agent?.sessionId ?? exec?.agent?.id ?? null;
1219
+ const callerMember = callerSessionId ? sessionMember.get(String(callerSessionId)) : null;
1220
+ // 只有 Lead 才更新 Lead 句柄:成员调用不能覆盖它,否则后续派发/转发会拿错会话。
1221
+ if (exec?.agent && !callerMember) leadByTeam.set(args.teamId, exec.agent);
1222
+ const from = callerMember ? callerMember.memberId : 'lead';
1223
+ const toLead = String(args.to).trim().toLowerCase() === 'lead';
1224
+ const runtime = await runtimeOfTeam(s, args.teamId);
1225
+ // sidecar 的收件人只能是成员 id、'*' 或虚拟收件人 'lead',所以先把 name / id 统一解析成成员行。
1226
+ const st = runtime === 'agent' ? await request(s, `/api/status${qs({ team: args.teamId })}`) : null;
1227
+ const members = st?.members || [];
1228
+ const resolve = (v) => members.find((m) => m.name === v || m.id === v) || null;
1229
+ if (!toLead && args.to !== '*' && (members.length ? !resolve(args.to) : false)) {
1230
+ throw new Error(`team_send: 找不到成员 ${args.to}(可用成员 name 或 memberId;广播用 '*';给 Lead 留言用 to:"lead")`);
1231
+ }
1232
+ const recorded = await request(s, '/api/messages', {
1233
+ method: 'POST',
1234
+ body: {
1235
+ teamId: args.teamId,
1236
+ from,
1237
+ to: toLead ? 'lead' : (args.to === '*' ? '*' : (resolve(args.to)?.id || args.to)),
1238
+ payload: { text: args.message },
1239
+ ...(args.correlationId !== undefined ? { correlationId: args.correlationId } : {}),
1240
+ },
1241
+ });
1242
+ // 成员→Lead 只落信箱(面板可见),不打扰 Lead 会话;worker 团队也没有可唤醒的 sub-agent。
1243
+ if (runtime !== 'agent' || toLead) return recorded;
1244
+
1245
+ const subs = subagentsOf(ctx);
1246
+ // 成员之间互通必须借 Lead 的 agent 句柄:成员会话都挂在 Lead 下,成员直发会「belongs to another parent session」。
1247
+ const caller = leadByTeam.get(args.teamId) || exec?.agent;
1248
+ if (!subs || typeof subs.sendMessage !== 'function' || !caller) return { ...recorded, delivered: false };
1249
+ const content = [{ type: 'text', text: String(args.message) }];
1250
+ const candidates = args.to === '*' ? members : [resolve(args.to)].filter(Boolean);
1251
+ const targets = candidates.filter((m) => m.agentSessionId);
1252
+ const delivered = [];
1253
+ const failed = [];
1254
+ if (!targets.length) failed.push({ target: args.to, error: '该成员没有绑定 sub-agent 会话(可能还没 spawn 或已回收)' });
1255
+ for (const target of targets) {
1256
+ try {
1257
+ await subs.sendMessage(caller, String(target.agentSessionId), content, { signal: AbortSignal.timeout(s.requestTimeoutMs) });
1258
+ delivered.push(target.name);
1259
+ // 投递成功才补记送达:这一条消息确实进了成员会话
1260
+ const row = (recorded.messages || [recorded.message]).find((m) => m && String(m.to) === String(target.id));
1261
+ await markDelivered(s, row?.id);
1262
+ } catch (err) {
1263
+ failed.push({ target: target.name, error: String(err?.message || err) });
1264
+ }
1265
+ }
1266
+ return { ...recorded, delivered, ...(failed.length ? { failed } : {}) };
1267
+ },
1268
+ });
1269
+
1270
+ tools.push({
1271
+ name: 'team_todo',
1272
+ description: '设置或更新一个任务的执行计划清单(todo)。与内置 todo_write 不同:这份清单落盘在 sidecar,面板主页 Plan 区域实时渲染,Lead 与成员都能看到(内置 todo 只属于当前会话)。语义是整体替换——每次提交完整清单(最多 50 条),用 status 标注进度:open(未开始)/ active(进行中)/ done(已完成)/ blocked(被阻塞)。Lead 在派发前/后用它给任务补计划;成员每开始或完成一步、以及通过验收后调用它更新状态。',
1273
+ parameters: {
1274
+ type: 'object',
1275
+ additionalProperties: false,
1276
+ properties: {
1277
+ teamId: { type: 'string' },
1278
+ taskId: { type: 'string', description: 'Task id whose checklist you are setting.' },
1279
+ items: {
1280
+ type: 'array',
1281
+ maxItems: 50,
1282
+ description: 'Complete ordered checklist (replace-all).',
1283
+ items: {
1284
+ type: 'object',
1285
+ additionalProperties: false,
1286
+ properties: {
1287
+ title: { type: 'string', description: 'One-line step, imperative.' },
1288
+ status: { type: 'string', enum: ['open', 'active', 'done', 'blocked'], description: 'Default open.' },
1289
+ blockedBy: { type: 'array', items: { type: 'string' }, description: 'Optional reasons / ids this step waits on.' },
1290
+ },
1291
+ required: ['title'],
1292
+ },
1293
+ },
1294
+ by: { type: 'string', description: 'Who updates it (Lead or memberId). Defaults to the calling session, else "lead".' },
1295
+ },
1296
+ required: ['teamId', 'taskId', 'items'],
1297
+ },
1298
+ output: jsonOutput('{ taskId, items }'),
1299
+ async execute(args, exec) {
1300
+ if (!Array.isArray(args.items)) throw new Error('items must be an array');
1301
+ const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
1302
+ const binding = sessionId ? sessionMember.get(sessionId) : null;
1303
+ const by = args.by || binding?.memberId || 'lead';
1304
+ return await request(s, `/api/tasks/${encodeURIComponent(args.taskId)}/todos`, { method: 'POST', body: { items: args.items, by } });
1305
+ },
1306
+ });
1307
+
1308
+ tools.push({
1309
+ name: 'team_report_task',
1310
+ description: 'Report the outcome of ONE task you were dispatched (agent members: call this as the last thing you do). It marks the task done/failed/blocked on the sidecar, releases the member back to idle, advances the DAG (dependents become ready and are dispatched), and applies the team failure policy. `summary` is what the Lead and the panel will see — put the result, key file paths and any blocker in it.',
1311
+ parameters: {
1312
+ type: 'object',
1313
+ additionalProperties: false,
1314
+ properties: {
1315
+ teamId: { type: 'string' },
1316
+ taskId: { type: 'string' },
1317
+ status: { type: 'string', enum: ['done', 'failed', 'blocked'], description: 'done = acceptance met; failed = attempted and broken; blocked = cannot proceed without a decision.' },
1318
+ summary: { type: 'string', description: 'One-line result plus the artifacts (paths) and anything the Lead must know.' },
1319
+ },
1320
+ required: ['teamId', 'taskId', 'status', 'summary'],
1321
+ },
1322
+ output: jsonOutput('{ task, member, dispatched? }'),
1323
+ async execute(args, exec) {
1324
+ const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
1325
+ const body = {
1326
+ sessionId,
1327
+ teamId: args.teamId,
1328
+ taskId: args.taskId,
1329
+ status: args.status,
1330
+ summary: args.summary,
1331
+ };
1332
+ const res = await request(s, '/api/agents/report', { method: 'POST', body });
1333
+ if (exec?.agent && !memberOfCaller(exec.agent)) leadByTeam.set(args.teamId, exec.agent);
1334
+ try {
1335
+ const items = collectArtifacts(ctx, sessionId);
1336
+ if (items.length) {
1337
+ const binding = sessionId ? sessionMember.get(sessionId) : null;
1338
+ await request(s, '/api/artifacts', { method: 'POST', body: { teamId: args.teamId, taskId: args.taskId, memberId: binding?.memberId ?? null, items } });
1339
+ }
1340
+ } catch { /* 产物采集失败不影响任务汇报 */ }
1341
+ const dispatched = await dispatchLoop(s, ctx, args.teamId).catch(() => null);
1342
+ return { ...res, ...(dispatched ? { dispatched } : {}) };
1343
+ },
1344
+ });
1345
+
1346
+ tools.push({
1347
+ name: 'team_dispatch',
1348
+ description: 'Pump the agent-team dispatcher once: claim ready tasks for idle members and send each member its brief. Normally unnecessary — team_task dispatches automatically and team_report_task dispatches the next wave — but useful after team_control/resume, after approving a scope request, or when a member went idle without reporting. Safe to call repeatedly; it returns when no idle member or no ready task is left.',
1349
+ parameters: {
1350
+ type: 'object',
1351
+ additionalProperties: false,
1352
+ properties: { teamId: { type: 'string' } },
1353
+ required: ['teamId'],
1354
+ },
1355
+ output: jsonOutput('{ dispatched, reason?, settled?, hint?, error? }'),
1356
+ async execute(args, exec) {
1357
+ if (exec?.agent && !memberOfCaller(exec.agent)) leadByTeam.set(args.teamId, exec.agent);
1358
+ return await dispatchLoop(s, ctx, args.teamId);
1359
+ },
1360
+ });
1361
+
1362
+ tools.push({
1363
+ name: 'team_scope',
1364
+ description: 'Four-domain permission workflow. action=list shows pending or decided out-of-scope requests (fs/exec/net/env). action=request files one for a blocked action (the worker normally does this automatically when onDenied="scope"). action=decide approves or denies it: the decision is persisted transactionally and an approval creates a single-use, TTL-bounded grant — the same target needs a fresh request afterwards. Explicit deny always beats allow.',
1365
+ parameters: {
1366
+ type: 'object',
1367
+ additionalProperties: false,
1368
+ properties: {
1369
+ action: { type: 'string', enum: ['list', 'request', 'decide'], description: 'Required operation.' },
1370
+ teamId: { type: 'string', description: 'Required for list and request.' },
1371
+ status: { type: 'string', description: 'For list: pending | approved | denied | expired.' },
1372
+ memberId: { type: 'string', description: 'For request: the blocked member.' },
1373
+ domain: { type: 'string', enum: ['fs', 'exec', 'net', 'env'] },
1374
+ target: { type: 'string', description: 'Relative path, argv string, host:port, or env var name.' },
1375
+ reason: { type: 'string' },
1376
+ diffSize: { type: 'integer' },
1377
+ risk: { type: 'string' },
1378
+ blockedStep: { type: 'string' },
1379
+ fallback: { type: 'string', description: 'What the member should do if denied.' },
1380
+ requestId: { type: 'string', description: 'For decide.' },
1381
+ decision: { type: 'string', enum: ['approved', 'denied'], description: 'For decide.' },
1382
+ decidedBy: { type: 'string', description: 'Who decided; defaults to lead.' },
1383
+ ttlSeconds: { type: 'integer', description: 'Grant lifetime in seconds. Default 60.' },
1384
+ singleUse: { type: 'boolean', description: 'Default true: one use, then re-request.' },
1385
+ },
1386
+ required: ['action'],
1387
+ },
1388
+ output: jsonOutput('{ items? , scopeRequest?, decision?, grant? }'),
1389
+ async execute(args) {
1390
+ const action = args.action;
1391
+ if (action === 'list') {
1392
+ if (!args.teamId) throw new Error('team_scope list requires teamId');
1393
+ return await request(s, `/api/scope-requests${qs({ team: args.teamId, status: args.status })}`);
1394
+ }
1395
+ if (action === 'request') {
1396
+ if (!args.teamId || !args.memberId || !args.domain || !args.target) {
1397
+ throw new Error('team_scope request requires teamId, memberId, domain, target');
1398
+ }
1399
+ const scopeRequest = await request(s, '/api/scope-requests', {
1400
+ method: 'POST',
1401
+ body: {
1402
+ memberId: args.memberId,
1403
+ teamId: args.teamId,
1404
+ domain: args.domain,
1405
+ target: args.target,
1406
+ reason: args.reason || '',
1407
+ ...(args.diffSize !== undefined ? { diffSize: args.diffSize } : {}),
1408
+ ...(args.risk !== undefined ? { risk: args.risk } : {}),
1409
+ ...(args.blockedStep !== undefined ? { blockedStep: args.blockedStep } : {}),
1410
+ ...(args.fallback !== undefined ? { fallback: args.fallback } : {}),
1411
+ },
1412
+ });
1413
+ return { scopeRequest };
1414
+ }
1415
+ if (action === 'decide') {
1416
+ if (!args.requestId || !args.decision) throw new Error('team_scope decide requires requestId and decision');
1417
+ return await request(s, `/api/scope-requests/${encodeURIComponent(args.requestId)}/decide`, {
1418
+ method: 'POST',
1419
+ body: {
1420
+ decision: args.decision,
1421
+ decidedBy: args.decidedBy || 'lead',
1422
+ ...(args.reason !== undefined ? { reason: args.reason } : {}),
1423
+ ...(args.ttlSeconds !== undefined ? { ttlSeconds: args.ttlSeconds } : {}),
1424
+ ...(args.singleUse !== undefined ? { singleUse: args.singleUse } : {}),
1425
+ },
1426
+ });
1427
+ }
1428
+ throw new Error(`team_scope unknown action: ${action}`);
1429
+ },
1430
+ });
1431
+
1432
+ tools.push({
1433
+ name: 'team_control',
1434
+ description: 'Control one member. On `agent` teams interrupt aborts the sub-agent’s current turn (`subagents.interrupt`) and marks the member interrupted on the sidecar; resume re-arms it and dispatches the task again. On `worker` teams interrupt writes status synchronously (no zombie `running`) and keeps the task resumable. assign hands a ready task to an idle member on either runtime.',
1435
+ parameters: {
1436
+ type: 'object',
1437
+ additionalProperties: false,
1438
+ properties: {
1439
+ action: { type: 'string', enum: ['interrupt', 'resume', 'assign'] },
1440
+ teamId: { type: 'string', description: 'Required to control an agent-team member.' },
1441
+ memberId: { type: 'string' },
1442
+ taskId: { type: 'string', description: 'Required for assign.' },
1443
+ reason: { type: 'string', description: 'For interrupt.' },
1444
+ },
1445
+ required: ['action', 'memberId'],
1446
+ },
1447
+ output: jsonOutput('{ member, ... }'),
1448
+ async execute(args, exec) {
1449
+ const id = encodeURIComponent(args.memberId);
1450
+ if (args.action === 'interrupt') {
1451
+ const res = await request(s, `/api/members/${id}/interrupt`, { method: 'POST', body: { reason: args.reason || 'lead interrupt' } });
1452
+ const runtime = args.teamId ? await runtimeOfTeam(s, args.teamId) : 'worker';
1453
+ if (runtime === 'agent' && res?.member?.agentSessionId) {
1454
+ const subs = subagentsOf(ctx);
1455
+ const caller = exec?.agent;
1456
+ if (subs && caller && typeof subs.interrupt === 'function') {
1457
+ const interrupted = await Promise.resolve()
1458
+ .then(() => subs.interrupt(String(res.member.agentSessionId), { kind: 'ancestor', agent: caller }))
1459
+ .then(() => ({ ok: true, previousStatus: res.member.agentStatus ?? null }),
1460
+ (err) => ({ ok: false, error: String(err?.message || err) }));
1461
+ return { ...res, agent: interrupted };
1462
+ }
1463
+ }
1464
+ return res;
1465
+ }
1466
+ if (args.action === 'resume') return await request(s, `/api/members/${id}/resume`, { method: 'POST', body: {} });
1467
+ if (args.action === 'assign') {
1468
+ if (!args.taskId) throw new Error('team_control assign requires taskId');
1469
+ return await request(s, `/api/members/${id}/assign`, { method: 'POST', body: { taskId: args.taskId } });
1470
+ }
1471
+ throw new Error(`team_control unknown action: ${args.action}`);
1472
+ },
1473
+ });
1474
+
1475
+ tools.push({
1476
+ name: 'team_report',
1477
+ description: 'Export a Markdown run report: members, tasks/DAG, persisted decisions, and the audit table with actor, domain, action, target, and full before/after SHA-256 hashes. Use it for review, handoff, or proving who changed which file.',
1478
+ parameters: {
1479
+ type: 'object',
1480
+ additionalProperties: false,
1481
+ properties: { teamId: { type: 'string' } },
1482
+ required: ['teamId'],
1483
+ },
1484
+ output: textOutput(),
1485
+ isConcurrencySafe: () => true,
1486
+ async execute(args) {
1487
+ const markdown = await request(s, `/api/report${qs({ team: args.teamId, format: 'md' })}`, { raw: true });
1488
+ return { markdown: String(markdown).slice(0, 200000) };
1489
+ },
1490
+ });
1491
+
1492
+ return tools;
1493
+ }
1494
+
1495
+ // ---------- trace 上报:把每次工具调用写成 span(running → done/failed) ----------
1496
+ /** 会话 → 团队 的粘性绑定:参数里出现 teamId 或 team_create 返回后记住,后续调用自动归属。 */
1497
+ const teamBySession = new Map();
1498
+
1499
+ const clipText = (value, max) => {
1500
+ if (value == null) return null;
1501
+ let text;
1502
+ try { text = typeof value === 'string' ? value : JSON.stringify(value); } catch { text = String(value); }
1503
+ return text.length > max ? text.slice(0, max) + '…' : text;
1504
+ };
1505
+
1506
+ /** 后台 POST,1.2s 超时;sidecar 未起/网络抖动绝不影响工具调用本身。 */
1507
+ function postSpan(s, payload) {
1508
+ if (!payload.teamId) return;
1509
+ const body = JSON.stringify(payload);
1510
+ void fetch(s.baseUrl + '/api/spans', {
1511
+ method: 'POST',
1512
+ headers: { 'content-type': 'application/json' },
1513
+ body,
1514
+ signal: AbortSignal.timeout(1200),
1515
+ }).catch(() => { /* ignore */ });
1516
+ }
1517
+
1518
+ function bindSessionTeam(sessionId, args, resultValue) {
1519
+ if (!sessionId) return null;
1520
+ const teamId = args?.teamId || resultValue?.team?.id || resultValue?.teamId
1521
+ || (Array.isArray(resultValue?.items) && resultValue.items[0]?.team?.id);
1522
+ if (teamId) teamBySession.set(sessionId, String(teamId));
1523
+ return sessionId ? (teamBySession.get(sessionId) || null) : null;
1524
+ }
1525
+
1526
+ /**
1527
+ * `tools/execute` waterfall:进入前报 running,返回/抛错后报终态。
1528
+ * 同一 spanId 幂等 upsert,因此面板可在调用进行中就先画出增长中的条。
1529
+ */
1530
+ async function traceToolCall(s, ctx, exec, next) {
1531
+ const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
1532
+ const callId = exec?.callId != null ? String(exec.callId) : `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1533
+ const spanId = `tool:${sessionId || 'host'}:${callId}`;
1534
+ const name = String(exec?.name || 'tool');
1535
+ const args = exec?.arguments && typeof exec.arguments === 'object' ? exec.arguments : {};
1536
+ const startMs = Date.now();
1537
+ const member = sessionId ? sessionMember.get(sessionId) : null;
1538
+ const teamId = (args.teamId && String(args.teamId)) || member?.teamId || (sessionId && teamBySession.get(sessionId)) || null;
1539
+ const memberId = member?.memberId || null;
1540
+ if (teamId) {
1541
+ postSpan(s, {
1542
+ teamId, sessionId, spanId, name, kind: 'tool', status: 'running', startMs,
1543
+ ...(memberId ? { memberId } : {}),
1544
+ detail: Object.keys(args).length ? clipText(args, 160) : null,
1545
+ input: clipText(args, s.traceInputMax),
1546
+ });
1547
+ }
1548
+ let result;
1549
+ try {
1550
+ result = await next();
1551
+ } catch (err) {
1552
+ if (teamId) {
1553
+ postSpan(s, {
1554
+ teamId, sessionId, spanId, name, kind: 'tool', status: 'failed', startMs, endMs: Date.now(),
1555
+ error: clipText(err && err.message ? err.message : String(err), 2000),
1556
+ });
1557
+ }
1558
+ throw err;
1559
+ }
1560
+ const failed = !!result && (result.isError === true || result.error != null);
1561
+ const bound = bindSessionTeam(sessionId, args, failed ? null : result?.value);
1562
+ const finalTeam = teamId || bound;
1563
+ if (finalTeam) {
1564
+ postSpan(s, {
1565
+ teamId: finalTeam, sessionId, spanId, name, kind: 'tool',
1566
+ status: failed ? 'failed' : 'done', startMs, endMs: Date.now(),
1567
+ ...(memberId ? { memberId } : {}),
1568
+ output: failed ? null : clipText(result?.value, s.traceInputMax),
1569
+ error: failed ? clipText(result?.error?.message || result?.value || 'tool error', 2000) : null,
1570
+ });
1571
+ }
1572
+ return result;
1573
+ }
1574
+
1575
+ // ---------- 成员改动(审阅):write/edit 落盘前后的 unified diff ----------
1576
+ // 只上报成员(子 agent)的改动:Lead 自己改文件不进审阅页。read 失败 / 工具失败一律静默跳过,
1577
+ // 绝不影响工具调用本身。
1578
+ async function reportFileChange(s, ctx, exec, next) {
1579
+ const name = String(exec?.name || '');
1580
+ const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
1581
+ const binding = sessionId ? sessionMember.get(sessionId) : null;
1582
+ if (!binding || !FILE_TOOLS.has(name)) return next();
1583
+ const args = exec?.arguments && typeof exec.arguments === 'object' ? exec.arguments : null;
1584
+ const raw = args ? targetFile(name, args) : '';
1585
+ if (!raw) return next();
1586
+ // 成员会话的当前目录:spawn 时设成 team.workspace,这里优先用登记值;Agent 上没有 cwd 字段,
1587
+ // 再问 workingDirectory 服务;都拿不到才退回宿主进程 cwd(此时相对路径多半解析不到,diff 会被跳过)。
1588
+ let agentCwd = typeof exec?.agent?.cwd === 'string' ? exec.agent.cwd : '';
1589
+ if (!agentCwd && binding.cwd) agentCwd = binding.cwd;
1590
+ if (!agentCwd && exec?.agent?.session && typeof ctx?.workingDirectory?.get === 'function') {
1591
+ try { agentCwd = ctx.workingDirectory.get(exec.agent.session) || ''; } catch { /* 忽略 */ }
1592
+ }
1593
+ const baseDir = agentCwd || process.cwd();
1594
+ const abs = path.isAbsolute(raw) ? raw : path.resolve(baseDir, raw);
1595
+ const before = readTextSafe(abs);
1596
+ const result = await next();
1597
+ const failed = !!result && (result.isError === true || result.error != null);
1598
+ if (failed) return result;
1599
+ const after = readTextSafe(abs);
1600
+ if (after === null) return result;
1601
+ // 新建的空文件没有可审内容
1602
+ if (before === null && after === '') return result;
1603
+ const shown = displayPath(abs, baseDir);
1604
+ const diff = unifiedDiff(shown, before ?? '', after);
1605
+ if (!diff) return result;
1606
+ const { added, deleted } = countDiff(diff);
1607
+ void request(s, '/api/changes', {
1608
+ method: 'POST',
1609
+ body: {
1610
+ teamId: binding.teamId,
1611
+ memberId: binding.memberId,
1612
+ sessionId,
1613
+ items: [{ path: shown, kind: changeKind(before, after), diff, added, deleted }],
1614
+ },
1615
+ }).catch(() => { /* 上报失败不影响工具调用 */ });
1616
+ return result;
1617
+ }
1618
+
1619
+ // ---------- LLM 调用 span:真实 token 用量 + 按单价表折算的金额 ----------
1620
+ // DSH 内核只上报 token,不报钱;金额由 pricing.js 折算。查不到单价就只报 token。
1621
+ let llmSpanSeq = 0;
1622
+
1623
+ const fmtTokens = (v) => {
1624
+ const n = Number(v) || 0;
1625
+ if (n >= 1e6) return `${(n / 1e6).toFixed(2)}M`;
1626
+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
1627
+ return String(Math.round(n));
1628
+ };
1629
+
1630
+ const PURPOSE_LABEL = { compaction: '上下文压缩', 'session-title': '会话标题' };
1631
+
1632
+ /**
1633
+ * `llm/stream` waterfall:包住一次流式模型调用,抓 usage 后再补一条终态 span。
1634
+ * 没有团队归属的会话(普通对话、非团队成员)直接透传,零开销。
1635
+ */
1636
+ function traceLlmCall(s, options, next) {
1637
+ const stream = next();
1638
+ if (!s.reportLlmCalls) return stream;
1639
+ const sessionId = options?.sessionId != null ? String(options.sessionId) : null;
1640
+ const member = sessionId ? sessionMember.get(sessionId) : null;
1641
+ const teamId = member?.teamId || (sessionId ? teamBySession.get(sessionId) : null) || null;
1642
+ if (!teamId) return stream;
1643
+
1644
+ const provider = options?.provider != null ? String(options.provider) : null;
1645
+ const model = options?.model != null ? String(options.model) : null;
1646
+ const purpose = options?.purpose || null;
1647
+ const startMs = Date.now();
1648
+ const spanId = `llm:${sessionId || 'host'}:${startMs.toString(36)}-${++llmSpanSeq}`;
1649
+ const base = {
1650
+ teamId, sessionId, spanId, kind: 'llm', name: model || provider || 'llm', model, provider,
1651
+ ...(member?.memberId ? { memberId: member.memberId } : {}),
1652
+ };
1653
+ postSpan(s, {
1654
+ ...base, status: 'running', startMs,
1655
+ detail: PURPOSE_LABEL[purpose] || null,
1656
+ meta: { provider, purpose },
1657
+ });
1658
+
1659
+ return (async function* traced() {
1660
+ let usage = null;
1661
+ try {
1662
+ for await (const chunk of stream) {
1663
+ if (chunk && chunk.type === 'usage' && chunk.usage) usage = chunk.usage;
1664
+ yield chunk;
1665
+ }
1666
+ } catch (err) {
1667
+ postSpan(s, {
1668
+ ...base, status: 'failed', startMs, endMs: Date.now(),
1669
+ detail: PURPOSE_LABEL[purpose] || null,
1670
+ error: clipText(err?.message || String(err), 2000),
1671
+ });
1672
+ throw err;
1673
+ }
1674
+ const endMs = Date.now();
1675
+ const tokensIn = usage
1676
+ ? (Number(usage.inputTokens) || 0) + (Number(usage.cacheReadTokens) || 0) + (Number(usage.cacheWriteTokens) || 0)
1677
+ : null;
1678
+ const tokensOut = usage ? (Number(usage.outputTokens) || 0) : null;
1679
+ const priced = usage ? priceUsage({ provider, model, usage, atMs: endMs, tables: s.pricingTables }) : null;
1680
+ const parts = [];
1681
+ if (usage) parts.push(`${fmtTokens(tokensIn)} in · ${fmtTokens(tokensOut)} out`);
1682
+ if (usage && Number(usage.cacheReadTokens) > 0) parts.push(`缓存命中 ${fmtTokens(usage.cacheReadTokens)}`);
1683
+ if (priced && priced.peak) parts.push('高峰价');
1684
+ if (PURPOSE_LABEL[purpose]) parts.push(PURPOSE_LABEL[purpose]);
1685
+ postSpan(s, {
1686
+ ...base, status: 'done', startMs, endMs,
1687
+ tokensIn, tokensOut,
1688
+ cost: priced ? priced.cost : null,
1689
+ detail: parts.join(' · ') || null,
1690
+ meta: { provider, purpose, currency: priced?.currency ?? null, peak: priced?.peak ?? null, usage: usage ?? null },
1691
+ });
1692
+ })();
1693
+ }
1694
+
1695
+ // ---- 技能:把包内 `skills/` 注册成 skills provider ----
1696
+ // 装上插件就带 `dsh-agent-team` 技能,不需要用户手动 `cp -r skills/... ~/.dsh/skills/`。
1697
+ // 本地克隆读 `<repo>/skills`;npm 安装读依赖包 `dsh-team-control-cli` 里的 `skills/`(同一份文件)。
1698
+ const SKILL_RANK = 600; // 与官方 BUNDLED_SKILL_RANK 一致:打包来源的标准优先级
1699
+
1700
+ function skillRoots() {
1701
+ const roots = [path.resolve(PKG_DIR, '..', 'skills')];
1702
+ try {
1703
+ const cliPkg = createRequire(import.meta.url).resolve('dsh-team-control-cli/package.json');
1704
+ roots.push(path.join(path.dirname(cliPkg), 'skills'));
1705
+ } catch { /* 本地布局下可能没有该依赖 */ }
1706
+ const seen = new Set();
1707
+ return roots.filter((dir) => {
1708
+ if (seen.has(dir) || !fs.existsSync(dir)) return false;
1709
+ seen.add(dir);
1710
+ return true;
1711
+ });
1712
+ }
1713
+
1714
+ /** 解析 SKILL.md 的 YAML frontmatter(只处理 `key: value` 这一层,够用且零依赖)。 */
1715
+ export function parseSkillFrontmatter(text) {
1716
+ const meta = {};
1717
+ if (!text.startsWith('---')) return meta;
1718
+ const end = text.indexOf('\n---', 3);
1719
+ if (end < 0) return meta;
1720
+ for (const line of text.slice(3, end).split(/\r?\n/)) {
1721
+ const m = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
1722
+ if (!m) continue;
1723
+ let value = m[2].trim();
1724
+ if (value.length >= 2 && ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))) {
1725
+ value = value.slice(1, -1);
1726
+ }
1727
+ meta[m[1]] = value === 'true' ? true : value === 'false' ? false : value;
1728
+ }
1729
+ return meta;
1730
+ }
1731
+
1732
+ function stripSkillFrontmatter(text) {
1733
+ if (!text.startsWith('---')) return text;
1734
+ const end = text.indexOf('\n---', 3);
1735
+ if (end < 0) return text;
1736
+ const after = text.indexOf('\n', end + 4);
1737
+ return (after < 0 ? '' : text.slice(after + 1)).replace(/^\r?\n/, '');
1738
+ }
1739
+
1740
+ /** 扫描可用目录,产出 skills 服务的候选条目(纯函数,便于测试)。 */
1741
+ export function discoverTeamSkills() {
1742
+ const out = [];
1743
+ for (const root of skillRoots()) {
1744
+ let entries = [];
1745
+ try { entries = fs.readdirSync(root, { withFileTypes: true }); } catch { continue; }
1746
+ for (const entry of entries) {
1747
+ if (!entry.isDirectory()) continue;
1748
+ const dir = path.join(root, entry.name);
1749
+ const file = path.join(dir, 'SKILL.md');
1750
+ let meta;
1751
+ try { meta = parseSkillFrontmatter(fs.readFileSync(file, 'utf8')); } catch { continue; }
1752
+ const name = String(meta.name || entry.name);
1753
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) continue;
1754
+ out.push({
1755
+ name,
1756
+ description: String(meta.description || ''),
1757
+ ...(meta.whenToUse ? { whenToUse: String(meta.whenToUse) } : {}),
1758
+ invocation: { modelInvocable: true, userInvocable: meta['user-invocable'] !== false },
1759
+ source: 'bundled',
1760
+ provider: 'dsh-team',
1761
+ rank: SKILL_RANK,
1762
+ path: file,
1763
+ resourceBase: { kind: 'directory', path: dir },
1764
+ locator: { file, dir },
1765
+ metadata: meta,
1766
+ });
1767
+ }
1768
+ }
1769
+ return out;
1770
+ }
1771
+
1772
+ /** 读取候选对应的完整正文(frontmatter 已剥离)。 */
1773
+ function loadTeamSkill(candidate) {
1774
+ const file = candidate?.locator?.file ?? candidate?.path;
1775
+ if (!file) return undefined;
1776
+ let text;
1777
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return undefined; }
1778
+ return {
1779
+ name: candidate.name,
1780
+ description: candidate.description,
1781
+ ...(candidate.whenToUse ? { whenToUse: candidate.whenToUse } : {}),
1782
+ invocation: candidate.invocation,
1783
+ source: candidate.source,
1784
+ provider: candidate.provider,
1785
+ path: candidate.path,
1786
+ resourceBase: candidate.resourceBase,
1787
+ metadata: candidate.metadata,
1788
+ content: stripSkillFrontmatter(text),
1789
+ };
1790
+ }
1791
+
1792
+ /** Cordis apply:注册全局工具,接管自动拉起的 sidecar,并把 agent 生命周期桥接到 sidecar。 */
1793
+ export function apply(ctx, config) {
1794
+ const s = resolveConfig(config);
1795
+ ctx.effect(() => {
1796
+ const disposers = buildTools(s, ctx).map((tool) => ctx.tools.register(tool));
1797
+ return () => {
1798
+ for (const dispose of disposers.reverse()) { try { dispose(); } catch { /* ignore */ } }
1799
+ leadByTeam.clear(); runtimeByTeam.clear(); sessionMember.clear(); dispatching.clear(); teamBySession.clear(); contextReportAt.clear();
1800
+ for (const timer of idleTimers.values()) clearTimeout(timer);
1801
+ idleTimers.clear(); agentStatusBySession.clear(); lastReplyBySession.clear();
1802
+ const spawned = s.spawned;
1803
+ if (spawned?.child && spawned.child.exitCode === null) {
1804
+ try { spawned.child.kill(); } catch { /* ignore */ }
1805
+ }
1806
+ };
1807
+ }, 'dsh-team.tools()');
1808
+
1809
+ // 技能:skills 服务在场时把包内 `skills/` 注册成 provider,装上插件就带 `dsh-agent-team` 技能;
1810
+ // 服务缺失(老版本/测试假 ctx)时静默跳过,不影响工具面。
1811
+ if (typeof ctx.inject === 'function') {
1812
+ ctx.inject(['skills'], (scope) => {
1813
+ scope.skills.registerProvider(() => ({
1814
+ name: 'dsh-team',
1815
+ list: async () => discoverTeamSkills(),
1816
+ get: async (candidate) => loadTeamSkill(candidate),
1817
+ }));
1818
+ });
1819
+ }
1820
+
1821
+ if (s.reportToolCalls) {
1822
+ ctx.on('tools/execute', (exec, next) => traceToolCall(s, ctx, exec, next));
1823
+ }
1824
+
1825
+ // 成员写/改文件 → unified diff 上报(面板「审阅」页):只给子成员,Lead 的改动不进审阅。
1826
+ // 钩子打上 dshTeamHook 标记:测试与排障能在多个 tools/execute 拦截器里认出它。
1827
+ if (s.reportChanges) {
1828
+ const fileChangeHook = (exec, next) => reportFileChange(s, ctx, exec, next);
1829
+ fileChangeHook.dshTeamHook = 'file-change';
1830
+ ctx.on('tools/execute', fileChangeHook);
1831
+ }
1832
+
1833
+ // 成员用内置 todo_write 维护计划(没建 team_todo)时,把 DSH 的 `todos` 投影镜像成
1834
+ // sidecar 计划步骤:面板/团队校验能看到真实 plan,todo 勾完计划步骤也跟着完成。
1835
+ ctx.on('tools/execute', async (exec, next) => {
1836
+ const result = await next();
1837
+ const sid = exec?.agent?.id != null ? String(exec.agent.id) : null;
1838
+ const failed = !!result && (result.isError === true || result.error != null);
1839
+ if (sid && String(exec?.name || '') === 'todo_write' && !failed) {
1840
+ void mirrorTodos(s, ctx, sid).catch(() => { /* ignore */ });
1841
+ }
1842
+ return result;
1843
+ });
1844
+
1845
+ // 每次 LLM 调用的 token 用量 → 金额(瀑布里的 ¥/$ 就来自这条 span)
1846
+ if (s.reportLlmCalls) {
1847
+ ctx.on('llm/stream', (options, next) => traceLlmCall(s, options, next));
1848
+ }
1849
+
1850
+ // 模型目录变化(provider 配置/适配器注册变化)→ 立刻重新同步(force + in-flight 去重)
1851
+ ctx.on('llm/adapters-updated', () => {
1852
+ if (s.reportLlmCatalog) void syncLlmCatalog(s, ctx).catch(() => { /* ignore */ });
1853
+ });
1854
+
1855
+ // 成员 sub-agent 的 running/idle 回写 sidecar:面板实时、idle 兜底收尾在途任务。
1856
+ // idle 不立刻落库:DSH 把 maintenance(压缩/整理)也算 idle,立刻落库会把正在干活的成员
1857
+ // 判成收工、把在途任务兜底判 done(页面上一段时间灰显)。等一个稳定窗口再落库。
1858
+ ctx.on('agent/status', ({ agent, status } = {}) => {
1859
+ const sessionId = agent?.id != null ? String(agent.id) : null;
1860
+ if (!sessionId) return;
1861
+ const binding = sessionMember.get(sessionId);
1862
+ if (!binding) return;
1863
+ // DSH 的 status getter 把 maintenance(上下文压缩/整理)也算 idle,但它不是收工:
1864
+ // 这类事件直接忽略,避免把在途任务误判 done(页面上一段时间显示灰色的根因)。
1865
+ const phaseKind = agent && agent.phase && agent.phase.kind;
1866
+ if (status === 'idle' && phaseKind === 'maintenance') {
1867
+ cancelIdleReport(sessionId);
1868
+ agentStatusBySession.set(sessionId, 'running');
1869
+ return;
1870
+ }
1871
+ if (status !== 'idle') {
1872
+ cancelIdleReport(sessionId);
1873
+ agentStatusBySession.set(sessionId, status);
1874
+ reportAgentStatus(s, sessionId, status);
1875
+ return;
1876
+ }
1877
+ cancelIdleReport(sessionId);
1878
+ agentStatusBySession.set(sessionId, 'idle');
1879
+ // 收工前把内置 todo 的影子计划同步一次,保证「todo 完成 → 计划完成」不丢最后一步
1880
+ void mirrorTodos(s, ctx, sessionId).catch(() => { /* ignore */ });
1881
+ const settle = Math.max(0, Number(s.agentIdleSettleMs) || 0);
1882
+ const finish = () => {
1883
+ idleTimers.delete(sessionId);
1884
+ if (agentStatusBySession.get(sessionId) !== 'idle') return; // 窗口内又跑起来了
1885
+ reportAgentStatus(s, sessionId, 'idle');
1886
+ void flushMemberReply(s, sessionId).catch(() => { /* ignore */ });
1887
+ if (s.agentAutoDispatch) {
1888
+ void dispatchLoop(s, ctx, binding.teamId).catch(() => { /* ignore */ });
1889
+ }
1890
+ };
1891
+ if (!settle) { finish(); return; }
1892
+ const timer = setTimeout(finish, settle);
1893
+ timer.unref?.();
1894
+ idleTimers.set(sessionId, timer);
1895
+ });
1896
+
1897
+ // 成员回合的助手正文:只在收工时(agent/status idle 稳定窗口后)落库成回复消息。
1898
+ // 每轮先攒着,纯工具步骤没有正文就清掉缓存,避免把上一轮结论当成这一轮的回复。
1899
+ ctx.on('session/event', (session, event) => {
1900
+ const sessionId = session?.id != null ? String(session.id) : null;
1901
+ if (!sessionId || !sessionMember.has(sessionId)) return;
1902
+ if (!event || event.type !== 'assistant/message') return;
1903
+ const text = assistantReplyText(event.data?.message);
1904
+ if (text) lastReplyBySession.set(sessionId, text);
1905
+ else lastReplyBySession.delete(sessionId);
1906
+ });
1907
+
1908
+ // 状态心跳:本地认为在跑、sidecar 却回落到 idle 且有在途任务时补报 running
1909
+ ctx.effect(() => {
1910
+ const timer = setInterval(() => {
1911
+ void heartbeatAgentStatus(s).catch(() => { /* ignore */ });
1912
+ }, Math.max(2000, s.agentHeartbeatMs));
1913
+ timer.unref?.();
1914
+ return () => clearInterval(timer);
1915
+ }, 'dsh-team.agent-heartbeat()');
1916
+
1917
+ // 成员上下文快照:面板「上下文分析」页的数据来源。周期泵覆盖进行中的回合,
1918
+ // agent/status 变化时补报一次(回合结束/中断后上下文占用才定型)。
1919
+ if (s.reportContext) {
1920
+ ctx.on('agent/status', ({ agent } = {}) => {
1921
+ const sessionId = agent?.id != null ? String(agent.id) : null;
1922
+ if (sessionId && sessionMember.has(sessionId)) reportContextSnapshot(s, ctx, sessionId, { force: true });
1923
+ });
1924
+ ctx.effect(() => {
1925
+ const timer = setInterval(() => {
1926
+ for (const sessionId of sessionMember.keys()) reportContextSnapshot(s, ctx, sessionId);
1927
+ }, Math.max(2000, s.contextReportMs));
1928
+ timer.unref?.();
1929
+ return () => clearInterval(timer);
1930
+ }, 'dsh-team.context-pump()');
1931
+ }
1932
+
1933
+ // 工作区注册表 → sidecar:插件一启动就推一次;sidecar 可能还没监听(同一个 apply 里刚 spawn),
1934
+ // 失败就 1.5s 后重试,成功后再转入低频轮询。
1935
+ if (s.reportWorkspaces) {
1936
+ ctx.effect(() => {
1937
+ let stopped = false;
1938
+ let timer = null;
1939
+ const run = async () => {
1940
+ const ok = await reportWorkspaces(s, ctx);
1941
+ if (stopped) return;
1942
+ timer = setTimeout(run, ok ? Math.max(5000, s.workspaceReportMs) : 1500);
1943
+ timer.unref?.();
1944
+ };
1945
+ void run();
1946
+ return () => { stopped = true; if (timer) clearTimeout(timer); };
1947
+ }, 'dsh-team.workspace-pump()');
1948
+ }
1949
+
1950
+ // 模型目录泵:面板「模型路由」页不再依赖 lead 调 team_models。
1951
+ // 启动即同步(sidecar 可能刚 spawn,失败 2s 重试),成功后按 llmCatalogMs 定时刷新。
1952
+ if (s.reportLlmCatalog) {
1953
+ ctx.effect(() => {
1954
+ let stopped = false;
1955
+ let timer = null;
1956
+ const run = async () => {
1957
+ let delay = 2000;
1958
+ try {
1959
+ const r = await syncLlmCatalog(s, ctx);
1960
+ // adapter 还没注册完时目录是空的:10s 后再试(adapters-updated 事件也会立刻补一次)
1961
+ delay = r?.ok ? (r.empty ? 10000 : Math.max(10000, s.llmCatalogMs)) : 2000;
1962
+ } catch { delay = 2000; }
1963
+ if (stopped) return;
1964
+ timer = setTimeout(run, delay);
1965
+ timer.unref?.();
1966
+ };
1967
+ void run();
1968
+ return () => { stopped = true; if (timer) clearTimeout(timer); };
1969
+ }, 'dsh-team.llm-catalog-pump()');
1970
+ }
1971
+
1972
+ // 保底泵:负责 lead 不在工具调用栈里时(例如成员直接回报)把 ready 任务继续发出去。
1973
+ if (s.agentAutoDispatch) {
1974
+ ctx.effect(() => {
1975
+ const timer = setInterval(() => {
1976
+ for (const teamId of leadByTeam.keys()) {
1977
+ void dispatchLoop(s, ctx, teamId).catch(() => { /* ignore */ });
1978
+ }
1979
+ }, Math.max(500, s.agentDispatchMs));
1980
+ timer.unref?.();
1981
+ return () => clearInterval(timer);
1982
+ }, 'dsh-team.agent-pump()');
1983
+ }
1984
+ }