dsh-team-control 0.2.7 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -1
  2. package/index.js +706 -53
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -95,7 +95,8 @@ dsh plugin --profile web add dsh-team-control
95
95
  | `startTimeoutMs` | `20000` | 自动拉起的等待上限 |
96
96
  | `requestTimeoutMs` | `60000` | 单次 API 调用超时 |
97
97
  | `approvalTimeoutMs` | `600000` | 成员审批等待 Lead 的上限;超时自动拒绝 |
98
- | `autoApproveLowRisk` | `true` | 低风险 shell 命令自动放行(不通知 Lead,镜像 `decidedBy:auto`) |
98
+ | `autoApproveLowRisk` | `true` | 低风险 shell 命令自动放行(含只读管道与常见 PowerShell 只读命令;不通知 Lead,镜像 `decidedBy:auto`) |
99
+ | `autoApproveTools` | `[]` | 工具级自动放行白名单(支持 `*` 通配),命中工具名的审批直接放行,不看参数 |
99
100
  | `sensitiveCommandPatterns` | `[]` | 追加的敏感命令正则;命中即转 Lead 审批 |
100
101
  | `reportToolCalls` | `true` | 监听 `tools/execute`,把每次工具调用上报为 `POST /api/spans` 的 span |
101
102
  | `traceInputMax` | `1200` | 上报参数/结果预览的截断长度(字符) |
package/index.js CHANGED
@@ -6,7 +6,7 @@
6
6
  // 工具用普通 ToolDefinition 对象注册(JSON Schema 参数),不依赖 defineTool。
7
7
  // - sidecar 未运行时,autoStart=true 会在首次工具调用时拉起 `dsh-team up`;
8
8
  // 插件卸载时只回收「自己拉起」的进程,不影响用户手工起的服务。
9
- import { spawn } from 'node:child_process';
9
+ import { spawn, execFileSync } from 'node:child_process';
10
10
  import { randomUUID } from 'node:crypto';
11
11
  import fs from 'node:fs';
12
12
  import { createRequire } from 'node:module';
@@ -86,13 +86,18 @@ function resolveConfig(config) {
86
86
  agentStartTimeoutMs: Number(c.agentStartTimeoutMs) || 120000,
87
87
  // 成员触发权限审批(permission preset 的 approval=ask)后,等待 Lead 调 team_approve 的上限
88
88
  approvalTimeoutMs: Number(c.approvalTimeoutMs) || 600000,
89
- // 审批降噪:命令明确是「已知安全程序 + 无管道/重定向/命令替换」时直接 allowed-once,
89
+ // 审批降噪:命令明确是「已知安全程序 + 无重定向/命令替换/脚本块」时直接 allowed-once,
90
90
  // 不打扰 Lead;敏感命令(见 DEFAULT_SENSITIVE_COMMAND_PATTERNS)仍转 Lead 审批
91
91
  autoApproveLowRisk: c.autoApproveLowRisk !== false,
92
92
  // 追加的敏感命令正则(字符串数组):命中即视为敏感,仍走 Lead 审批
93
93
  sensitiveCommandPatterns: Array.isArray(c.sensitiveCommandPatterns)
94
94
  ? c.sensitiveCommandPatterns.map((p) => String(p)).filter(Boolean)
95
95
  : [],
96
+ // 工具级自动放行白名单(字符串数组,支持 `*` 通配):命中工具名的审批直接 allowed-once。
97
+ // 默认空;用于把「非 shell 但明确安全」的工具(如只读 MCP 发现类工具)从审批流里摘出去。
98
+ autoApproveTools: Array.isArray(c.autoApproveTools)
99
+ ? c.autoApproveTools.map((p) => String(p).trim()).filter(Boolean)
100
+ : [],
96
101
  // spawnTeammate 的 provider:默认与 dsh-experimental-tool-agent-team 一致
97
102
  freshProvider: String(c.freshProvider || 'spawn'),
98
103
  forkProvider: String(c.forkProvider || 'fork'),
@@ -223,6 +228,8 @@ const memberOfCaller = (agent) => {
223
228
  return sid != null ? (sessionMember.get(String(sid)) || null) : null;
224
229
  };
225
230
  const subagentsOf = (ctx) => { try { return ctx.get('subagents'); } catch { return undefined; } };
231
+ /** DSH `agents` 注册表:`subagents.sendMessage` 要求 sender 是「精确的活跃 Agent」,必须从注册表取。 */
232
+ const agentsOf = (ctx) => { try { return ctx.get('agents'); } catch { return undefined; } };
226
233
  const subagentNames = (ctx) => { const svc = subagentsOf(ctx); return svc && typeof svc.list === 'function' ? svc.list() : []; };
227
234
 
228
235
  /** `sessions` / `workspaceChanges`:读成员自己会话里的交付文件(都是可选依赖)。 */
@@ -567,6 +574,13 @@ function providerFor(ctx, s, context) {
567
574
  return names[0];
568
575
  }
569
576
 
577
+ // subagents.startActivation 的 delegation request 形状在 DSH 0.2.2 变了:
578
+ // 旧宿主从 spec.request 读 prompt/parent/cwd/agentOptions/agentPreset,新宿主直接读 spec 顶层。
579
+ // 两种形状一起带:新宿主忽略 request,旧宿主忽略摊平字段,一份调用同时兼容。
580
+ function activationSpec(request, base) {
581
+ return { ...base, ...request, request };
582
+ }
583
+
570
584
  // ---------- 模型路由:DSH ctx.llm 目录 → sidecar 映射 ----------
571
585
  //
572
586
  // 目录的唯一来源是 Host 的 ctx.llm;这里只把 provider/model 的映射、展示名和
@@ -692,7 +706,15 @@ async function assertRouteEnabled(s, ctx, provider, model, effort = null) {
692
706
  // 目录里查不到的 route(例如适配器临时提供、未在 listModels 中声明)不拦,避免误伤;
693
707
  // 能查到但被停用的,无论是显式指定还是继承 Lead,都拒绝。
694
708
  const known = all.filter((m) => (!provider || m.provider === provider) && (!model || m.model === model));
695
- if (!known.length) return;
709
+ if (!known.length) {
710
+ // 常见错法:agentProvider 填了模型名(如 "glm-5.3")。这会在成员回合里才炸成
711
+ // `no adapter registered for provider "glm-5.3"`,白起一轮;这里提前拦。
712
+ const owners = [...new Set(all.filter((m) => !model || m.model === model).map((m) => m.provider))];
713
+ if (provider && model && owners.length && !owners.includes(provider)) {
714
+ throw new Error(`agentProvider「${provider}」不是模型「${model}」所属的 provider:应填 ${owners.join(' 或 ')}。agentProvider 要的是 provider id(见 team_models),不是模型名。`);
715
+ }
716
+ return;
717
+ }
696
718
  const enabled = all.filter((m) => m.enabled);
697
719
  if (!enabled.length) throw new Error('所有模型路由都已停用:请先在面板「模型路由」页启用,或调用 team_models 查看。');
698
720
  if (!known.some((m) => m.enabled)) {
@@ -777,6 +799,13 @@ async function resolveAgentPreset(ctx, requested, fallback, store = null) {
777
799
  if (ids.length && !ids.includes(preset)) {
778
800
  throw new Error(`agentPreset「${preset}」不存在;可用预设:${ids.join(', ')}`);
779
801
  }
802
+ // 宿主挂载失败的预设会在 startActivation 才抛出「xxx: never started」,看不出原因,
803
+ // 也看不出该换哪个;用 list() 的 broken 提前给可操作提示。
804
+ const row = Array.isArray(rows) ? rows.find((r) => r && r.id === preset) : null;
805
+ if (row && row.broken) {
806
+ const usable = (Array.isArray(rows) ? rows : []).filter((r) => r && r.id && !r.broken).map((r) => r.id);
807
+ throw new Error(`agentPreset「${preset}」在宿主里启动失败:${String(row.broken).split('\n')[0]}${usable.length ? `。可用预设:${usable.join('、')}(显式传 agentPreset 绕过)` : ''}`);
808
+ }
780
809
  return preset;
781
810
  }
782
811
 
@@ -1141,6 +1170,14 @@ const SAFE_COMMAND_PROGRAMS = new Set([
1141
1170
  'cargo', 'rustc', 'go', 'dotnet', 'javac', 'java', 'mvn', 'gradle',
1142
1171
  'ls', 'dir', 'cat', 'type', 'head', 'tail', 'rg', 'grep', 'find', 'fd', 'where', 'which',
1143
1172
  'git', 'echo', 'cd', 'pwd', 'mkdir', 'touch',
1173
+ // PowerShell 只读命令:成员在 Windows 上排查时的大量噪声来自 Get-*/Select-*/Format-*。
1174
+ // ForEach-Object 等能执行脚本块的 cmdlet 故意不收录(脚本块另有 `{}` 拦截)。
1175
+ 'get-childitem', 'get-content', 'get-item', 'get-itemproperty', 'get-location', 'get-command',
1176
+ 'get-process', 'get-date', 'get-acl', 'get-help', 'get-member', 'get-module', 'get-variable',
1177
+ 'select-string', 'select-object', 'where-object', 'measure-object', 'sort-object',
1178
+ 'format-table', 'format-list', 'out-string', 'out-host', 'write-output',
1179
+ 'test-path', 'resolve-path', 'join-path', 'split-path', 'compare-object', 'group-object',
1180
+ 'convertto-json', 'convertfrom-json', 'get-filehash',
1144
1181
  ]);
1145
1182
  // 解释器带 -e/-c 等价于任意代码执行,不自动放行。
1146
1183
  const INTERPRETER_PROGRAMS = new Set(['node', 'python', 'python3', 'py', 'deno', 'bun']);
@@ -1199,28 +1236,48 @@ function cachedPreExecuteArgs(sessionId, callId) {
1199
1236
  }
1200
1237
 
1201
1238
  /**
1202
- * 低风险命令判定:白名单程序 + 禁止管道/重定向/命令替换 + 敏感规则。
1239
+ * 低风险命令判定:白名单程序 + 禁止重定向/命令替换/脚本块 + 敏感规则。
1240
+ * 允许管道(每段都按白名单校验)与 `&&`/`||`/`;` 串联,覆盖 `git status | head`、
1241
+ * `Get-ChildItem | Where-Object` 这类只读排查命令。
1203
1242
  * 这是启发式而非完整 shell 解析——宁可漏放行(转 Lead),也不误放行。
1204
1243
  */
1205
1244
  function isLowRiskCommand(command, extraPatterns = []) {
1206
1245
  const text = String(command || '').trim();
1207
1246
  if (!text || text.length > 2000) return false;
1208
- if (/[|<>`]|\$\(|\n|\r/.test(text)) return false;
1247
+ // `<>` 重定向、反引号、$() 命令替换、换行、{} 脚本块(ForEach-Object/Where-Object 的代码)
1248
+ if (/[<>`{}]|\$\(|\n|\r/.test(text)) return false;
1209
1249
  if (DEFAULT_SENSITIVE_COMMAND_PATTERNS.test(text)) return false;
1210
1250
  for (const pattern of extraPatterns) {
1211
1251
  try { if (new RegExp(pattern, 'i').test(text)) return false; } catch { /* 非法正则忽略 */ }
1212
1252
  }
1213
- for (const seg of text.split(/&&|\|\||;/)) {
1214
- const part = seg.trim();
1215
- if (!part) continue;
1216
- const words = part.split(/\s+/);
1217
- const prog = words[0].replace(/^.*[\\/]/, '').replace(/\.(exe|cmd|bat|ps1)$/i, '').toLowerCase();
1218
- if (!SAFE_COMMAND_PROGRAMS.has(prog)) return false;
1219
- if (INTERPRETER_PROGRAMS.has(prog) && words.slice(1).some((w) => /^(-e|-c|--eval|--command|\/c)$/i.test(w))) return false;
1253
+ // 先按命令分隔符切成简单命令,再按单管道切段;空段(尾随 `|`)视为异常,宁可转 Lead。
1254
+ for (const chain of text.split(/&&|\|\||;/)) {
1255
+ if (!chain.trim()) continue;
1256
+ for (const seg of chain.split('|')) {
1257
+ const part = seg.trim();
1258
+ if (!part) return false;
1259
+ const words = part.split(/\s+/);
1260
+ const prog = words[0].replace(/^.*[\\/]/, '').replace(/\.(exe|cmd|bat|ps1)$/i, '').toLowerCase();
1261
+ if (!SAFE_COMMAND_PROGRAMS.has(prog)) return false;
1262
+ if (INTERPRETER_PROGRAMS.has(prog) && words.slice(1).some((w) => /^(-e|-c|--eval|--command|\/c)$/i.test(w))) return false;
1263
+ }
1220
1264
  }
1221
1265
  return true;
1222
1266
  }
1223
1267
 
1268
+ /** 工具名匹配:精确或 `*` 通配(大小写不敏感),用于 autoApproveTools 白名单。 */
1269
+ function toolNameMatches(pattern, name) {
1270
+ const target = String(name || '');
1271
+ if (!pattern || !target) return false;
1272
+ if (!pattern.includes('*')) return pattern.toLowerCase() === target.toLowerCase();
1273
+ const re = new RegExp(`^${pattern.split('*').map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`, 'i');
1274
+ return re.test(target);
1275
+ }
1276
+
1277
+ function isAutoApprovedTool(patterns, ...names) {
1278
+ return (patterns || []).some((pattern) => names.some((name) => toolNameMatches(pattern, name)));
1279
+ }
1280
+
1224
1281
  function settleApproval(s, requestId, decision, reason, decidedBy) {
1225
1282
  const entry = pendingApprovals.get(requestId);
1226
1283
  if (!entry) return null;
@@ -1275,6 +1332,68 @@ async function notifyLeadOfApproval(s, ctx, req, info) {
1275
1332
  return true;
1276
1333
  }
1277
1334
 
1335
+ /** 已经通知过 Lead 的中断(recover 用 memberId:seq,回合失败用 sessionId:序号),避免同一次中断反复打扰。 */
1336
+ const interruptNotified = new Set();
1337
+
1338
+ /**
1339
+ * 成员意外中断时主动推给 Lead(sidecar 重启 recover、模型回合报错、会话被异常终止)。
1340
+ *
1341
+ * 审批有 notifyLeadOfApproval 这条唯一通道,中断却一条都没有:Lead 挂起(会话空闲/等消息)后
1342
+ * 成员断了,事件流里只有一行 recover 或 failed,Lead 永远不会被唤醒(task_mwgbawyif5cuwf 现场)。
1343
+ * `subagents.sendMessage` 要求 sender 是精确的活跃 Agent,所以从 `agents` 注册表按会话 id 取成员;
1344
+ * 会话已经回收时发不出去——那种情况事件流/面板里仍有记录,不阻塞其它泵。
1345
+ */
1346
+ async function notifyLeadOfMemberInterrupt(s, ctx, info) {
1347
+ const subs = subagentsOf(ctx);
1348
+ if (!subs || typeof subs.sendMessage !== 'function' || !info) return false;
1349
+ const sessionId = info.sessionId != null ? String(info.sessionId) : null;
1350
+ const teamId = info.teamId != null ? String(info.teamId) : null;
1351
+ if (!sessionId || !teamId) return false;
1352
+ const agents = agentsOf(ctx);
1353
+ const sender = agents && typeof agents.get === 'function' ? agents.get(sessionId) : undefined;
1354
+ if (!sender) return false;
1355
+ let leadId = info.leadSessionId != null ? String(info.leadSessionId) : null;
1356
+ if (!leadId) {
1357
+ const cached = leadByTeam.get(teamId);
1358
+ leadId = cached?.id != null ? String(cached.id) : null;
1359
+ }
1360
+ if (!leadId) {
1361
+ const team = await teamOf(s, teamId).catch(() => null);
1362
+ leadId = team?.leadSessionId != null ? String(team.leadSessionId) : null;
1363
+ }
1364
+ if (!leadId || leadId === sessionId) return false;
1365
+ const key = info.dedupeKey || `${info.memberId || sessionId}:${info.status || 'interrupted'}`;
1366
+ if (interruptNotified.has(key)) return false;
1367
+ interruptNotified.add(key);
1368
+ const lines = [
1369
+ '【dsh-team 成员中断】',
1370
+ `teamId=${teamId}`,
1371
+ ...(info.memberId ? [`memberId=${info.memberId}`] : []),
1372
+ ...(info.memberName ? [`memberName=${info.memberName}`] : []),
1373
+ ...(info.taskId ? [`taskId=${info.taskId}`] : []),
1374
+ `成员状态:${info.status || 'interrupted'}`,
1375
+ ...(info.reason ? [`原因:${clip(String(info.reason), 500)}`] : []),
1376
+ '',
1377
+ info.status === 'failed'
1378
+ ? '该成员的回合以错误结束,任务按失败重试策略处理(可能已重新派发);反复失败需要你介入。'
1379
+ : '该成员没有正常收工,任务不会被当成完成;中断后它需要你确认才能继续。',
1380
+ info.status === 'failed'
1381
+ ? `下一步:team_status({ teamId: "${teamId}" }) 看进度;需要人工接手时用 team_task/team_member 调整。`
1382
+ : (info.memberId
1383
+ ? `下一步:team_status({ teamId: "${teamId}" }) 看进度;确认后 team_control({ teamId: "${teamId}", memberId: "${info.memberId}", action: "resume" }) 继续。`
1384
+ : `下一步:team_status({ teamId: "${teamId}" }) 看进度;确认后 team_dispatch 重新派发。`),
1385
+ ];
1386
+ try {
1387
+ await subs.sendMessage(sender, leadId, [{ type: 'text', text: lines.join('\n') }], {
1388
+ signal: AbortSignal.timeout(s.requestTimeoutMs),
1389
+ });
1390
+ return true;
1391
+ } catch {
1392
+ interruptNotified.delete(key); // 这次没送出去:下一跳重试
1393
+ return false;
1394
+ }
1395
+ }
1396
+
1278
1397
  async function onApprovalRequest(s, ctx, req, next) {
1279
1398
  const sessionId = req?.agent?.id != null ? String(req.agent.id) : null;
1280
1399
  const binding = sessionId ? sessionMember.get(sessionId) : null;
@@ -1295,24 +1414,31 @@ async function onApprovalRequest(s, ctx, req, next) {
1295
1414
  // 同一个请求重复进入(理论上不会)直接拒绝,避免两个 waiter 争同一个 id。
1296
1415
  if (pendingApprovals.has(requestId)) return 'rejected';
1297
1416
 
1298
- // 低风险命令自动放行:审批噪声主要来自成员跑 npm/node/git 这类命令时的沙箱升级。
1299
- // 必须同时满足「工具名像 shell」「参数里带 command」「命令通过白名单校验」才放行。
1417
+ // 自动放行(两条独立通道,命中即 allowed-once,镜像 decidedBy:"auto",不打扰 Lead):
1418
+ // ① autoApproveTools:显式工具白名单(支持 *),不依赖参数;
1419
+ // ② autoApproveLowRisk:工具名像 shell、参数里带 command、且命令通过白名单校验。
1300
1420
  const cached = sessionId && req?.callId != null ? cachedPreExecuteArgs(sessionId, String(req.callId)) : null;
1421
+ const cachedToolName = String(cached?.name || '');
1422
+ const autoApprove = (autoReason) => {
1423
+ void request(s, '/api/approvals', {
1424
+ method: 'POST',
1425
+ body: {
1426
+ id: requestId, teamId: info.teamId, memberId: info.memberId,
1427
+ sessionId, toolName: info.toolName, reason: autoReason,
1428
+ },
1429
+ }).then(() => request(s, `/api/approvals/${encodeURIComponent(requestId)}/decide`, {
1430
+ method: 'POST', body: { decision: 'allowed', decidedBy: 'auto', reason: autoReason },
1431
+ })).catch(() => { /* 镜像失败不影响放行 */ });
1432
+ return 'allowed-once';
1433
+ };
1434
+ if (isAutoApprovedTool(s.autoApproveTools, cachedToolName, info.toolName)) {
1435
+ return autoApprove(`工具白名单自动放行:${info.toolName || cachedToolName}`);
1436
+ }
1301
1437
  if (s.autoApproveLowRisk && cached) {
1302
1438
  const toolName = String(cached.name || info.toolName || '');
1303
1439
  const command = cached.args?.command;
1304
1440
  if (SHELL_TOOL_RE.test(toolName) && typeof command === 'string' && isLowRiskCommand(command, s.sensitiveCommandPatterns)) {
1305
- const autoReason = `低风险命令自动放行:${clip(command, 300)}`;
1306
- void request(s, '/api/approvals', {
1307
- method: 'POST',
1308
- body: {
1309
- id: requestId, teamId: info.teamId, memberId: info.memberId,
1310
- sessionId, toolName: info.toolName, reason: autoReason,
1311
- },
1312
- }).then(() => request(s, `/api/approvals/${encodeURIComponent(requestId)}/decide`, {
1313
- method: 'POST', body: { decision: 'allowed', decidedBy: 'auto', reason: autoReason },
1314
- })).catch(() => { /* 镜像失败不影响放行 */ });
1315
- return 'allowed-once';
1441
+ return autoApprove(`低风险命令自动放行:${clip(command, 300)}`);
1316
1442
  }
1317
1443
  }
1318
1444
 
@@ -1463,6 +1589,8 @@ async function readStatus(s) {
1463
1589
 
1464
1590
  /** sessionId → 最近一次从 sidecar 看到的成员状态;用于只强制中断一次。 */
1465
1591
  const forceStopSeen = new Map();
1592
+ /** teamId → 最近一次已处理的停止时间戳:面板停团队时顺带取消 Lead 的当前回合。 */
1593
+ const leadStopSeen = new Map();
1466
1594
 
1467
1595
  /**
1468
1596
  * 面板/看板停止只走 sidecar(不经过 Host 插件),sidecar 改不了 DSH 会话。
@@ -1486,6 +1614,9 @@ async function forceStopPump(s, ctx) {
1486
1614
  if (heldSessions.has(sid)) continue;
1487
1615
  const parentSessionId = m.parentSessionId != null ? String(m.parentSessionId) : null;
1488
1616
  if (!parentSessionId) continue;
1617
+ // recover(sidecar 重启恢复现场)不是 Lead 主动中断:必须主动通知 Lead,
1618
+ // 否则 Lead 挂起时只会看到成员「没声了」,永远等不到中断说明。
1619
+ const recover = (m.blockers || []).some((b) => b && b.kind === 'recover');
1489
1620
  heldSessions.add(sid);
1490
1621
  cancelIdleReport(sid);
1491
1622
  cancelStartWatchdog(sid);
@@ -1497,8 +1628,36 @@ async function forceStopPump(s, ctx) {
1497
1628
  heldSessions.delete(sid);
1498
1629
  forceStopSeen.delete(sid);
1499
1630
  }
1631
+ if (recover) {
1632
+ void notifyLeadOfMemberInterrupt(s, ctx, {
1633
+ teamId: m.teamId,
1634
+ memberId: m.id,
1635
+ memberName: m.name,
1636
+ taskId: m.currentTaskId ?? null,
1637
+ sessionId: sid,
1638
+ leadSessionId: parentSessionId,
1639
+ status: 'interrupted',
1640
+ reason: 'sidecar 重启恢复现场:成员会话的在途回合被判定为中断(recover)',
1641
+ dedupeKey: `recover:${m.id}:${m.seq}`,
1642
+ }).catch(() => { /* 通知尽力而为,不影响冻结 */ });
1643
+ }
1500
1644
  }
1501
1645
  for (const sid of forceStopSeen.keys()) if (!live.has(sid)) forceStopSeen.delete(sid);
1646
+
1647
+ // 停止团队不只是中断成员:Lead 会话(团队创建者)也必须在当前回合被停下,
1648
+ // 否则面板显示「已停止」而 Lead 仍在派发/写代码。sidecar 只记录停止时间戳,
1649
+ // 真正取消由 Host 做(canceling 等价于用户按停止键)。
1650
+ const agents = agentsOf(ctx);
1651
+ for (const t of status.teams || []) {
1652
+ const sid = t?.leadSessionId != null ? String(t.leadSessionId) : null;
1653
+ const stamp = t?.stopRequestedAt != null ? String(t.stopRequestedAt) : '';
1654
+ if (!sid || !stamp || leadStopSeen.get(t.id) === stamp) continue;
1655
+ const agent = agents && typeof agents.get === 'function' ? agents.get(sid) : null;
1656
+ if (!agent) continue; // 会话不归本进程管:留到下次轮询或由 DSH 自身收尾
1657
+ leadStopSeen.set(t.id, stamp);
1658
+ if (agent.status !== 'running') continue; // 已经空闲,没有可取消的回合
1659
+ try { agent.cancel({ kind: 'user' }); } catch { leadStopSeen.delete(t.id); }
1660
+ }
1502
1661
  }
1503
1662
 
1504
1663
  /** DSH 内置 todo 的状态 → sidecar 计划步骤的状态。 */
@@ -1708,6 +1867,7 @@ const textOutput = () => ({
1708
1867
  // ---------------------------------------------------------------------------
1709
1868
  const boardSessions = new Map(); // sessionId -> { taskId, phase, handle, sawRunning }
1710
1869
  const boardSessionIds = new Set();
1870
+ const boardStopSeen = new Map(); // taskId -> 已处理的 stopRequestedAt(取消过一次就不再取消)
1711
1871
 
1712
1872
  function boardUserMessage(text) {
1713
1873
  return {
@@ -1762,12 +1922,240 @@ function boardSetPermission(ctx, agent, preset) {
1762
1922
  }
1763
1923
  }
1764
1924
 
1925
+ /**
1926
+ * 把同一个会话下一次请求的模型切到执行路由。
1927
+ *
1928
+ * 走 DSH 的会话级模型选择(`agent.model.select`,与 Web UI 里切换模型同一条链路):
1929
+ * 追加一条 durable `model/selection` 事件,下一步装配请求时生效,并自动补一条
1930
+ * "model changed" 通知;会话历史、工具结果、todo、已经改过的文件全部留在原地,
1931
+ * 不新建会话、也不改部署默认模型。失败时保持原模型继续执行,不阻断任务。
1932
+ */
1933
+ function boardSelectionOf(route) {
1934
+ return {
1935
+ ...(route?.provider ? { provider: route.provider } : {}),
1936
+ model: route?.model,
1937
+ ...(route?.reasoningEffort ? { reasoningEffort: route.reasoningEffort } : {}),
1938
+ };
1939
+ }
1940
+
1941
+ function boardSameSelection(a, b) {
1942
+ return !!a && !!b
1943
+ && a.model === b.model
1944
+ && (a.provider || undefined) === (b.provider || undefined)
1945
+ && (a.reasoningEffort || undefined) === (b.reasoningEffort || undefined);
1946
+ }
1947
+
1948
+ /**
1949
+ * 规划路由与执行路由是否不同:只看显式配置的执行路由(task.leadRoute / settings.lead),
1950
+ * 没有配置时不猜部署默认模型,保持原模型继续。
1951
+ */
1952
+ function boardExecutionRouteDiffers(ctx, task, settings) {
1953
+ if (!task || task.executionMode !== 'same') return false;
1954
+ const exec = boardRoute(task, settings || {}, 'inprogress');
1955
+ if (!exec?.model) return false;
1956
+ const plan = boardRouteOrDefault(ctx, task, settings || {}, 'planning');
1957
+ return !boardSameSelection(boardSelectionOf(plan), boardSelectionOf(exec));
1958
+ }
1959
+
1960
+ async function boardApplyExecutionModel(ctx, agent, task, settings) {
1961
+ const target = boardRoute(task, settings || {}, 'inprogress');
1962
+ if (!target?.model) return { switched: false, reason: '没有可用的执行模型' };
1963
+ const model = agent?.model;
1964
+ let current;
1965
+ if (model && typeof model.current === 'function') {
1966
+ try { current = model.current(); } catch { current = undefined; }
1967
+ }
1968
+ let selection = boardSelectionOf(target);
1969
+ // 只配了模型没配 provider 时沿用当前 provider,避免写入非法选择。
1970
+ if (!selection.provider && current?.provider) selection.provider = current.provider;
1971
+ if (!selection.provider) {
1972
+ try { selection.provider = ctx.get('agentDefaultModel')?.currentSelection?.()?.provider; } catch { /* ignore */ }
1973
+ }
1974
+ if (!selection.provider) return { switched: false, reason: '执行模型缺少 provider' };
1975
+ const llm = llmOf(ctx);
1976
+ if (llm && typeof llm.resolveCallConfig === 'function') {
1977
+ try {
1978
+ const resolved = await llm.resolveCallConfig(selection);
1979
+ selection = {
1980
+ ...(resolved?.provider ? { provider: resolved.provider } : selection),
1981
+ model: resolved?.model || selection.model,
1982
+ ...(resolved?.reasoningEffort ? { reasoningEffort: resolved.reasoningEffort } : {}),
1983
+ };
1984
+ } catch (err) {
1985
+ console.warn(`[dsh-team] prewalk: 执行模型不可用(${String(err?.message || err)}),保持规划模型继续执行`);
1986
+ return { switched: false, reason: '执行模型不可用' };
1987
+ }
1988
+ }
1989
+ if (model && typeof model.select === 'function') {
1990
+ if (boardSameSelection(current, selection)) return { switched: false, reason: '已经是执行模型' };
1991
+ try {
1992
+ model.select(selection);
1993
+ } catch (err) {
1994
+ console.warn(`[dsh-team] prewalk: 切换模型失败(${String(err?.message || err)}),保持规划模型继续执行`);
1995
+ return { switched: false, reason: '切换模型失败' };
1996
+ }
1997
+ console.log(`[dsh-team] prewalk: 会话 ${String(agent.id)} 切到 ${selection.provider || '默认'}/${selection.model} 继续执行`);
1998
+ return { switched: true, selection };
1999
+ }
2000
+ // 兼容旧 Host:sessionController 的会话级选择(当前 DSH 已不提供)。
2001
+ let controller;
2002
+ try { controller = ctx.get('sessionController'); } catch { controller = undefined; }
2003
+ const sessions = controller?.agents;
2004
+ if (!sessions || typeof sessions.selectionFor !== 'function' || typeof sessions.selectForNextRequest !== 'function') {
2005
+ console.warn('[dsh-team] prewalk: 当前 Host 不支持会话内切换模型,保持规划模型继续执行');
2006
+ return { switched: false, reason: 'Host 不支持会话内切换模型' };
2007
+ }
2008
+ if (!current) {
2009
+ try { current = sessions.selectionFor(agent)?.current; } catch { current = undefined; }
2010
+ }
2011
+ if (boardSameSelection(current, selection)) return { switched: false, reason: '已经是执行模型' };
2012
+ try {
2013
+ sessions.selectForNextRequest(agent, selection);
2014
+ } catch (err) {
2015
+ console.warn(`[dsh-team] prewalk: 切换模型失败(${String(err?.message || err)}),保持规划模型继续执行`);
2016
+ return { switched: false, reason: '切换模型失败' };
2017
+ }
2018
+ console.log(`[dsh-team] prewalk: 会话 ${String(agent.id)} 切到 ${selection.provider || '默认'}/${selection.model} 继续执行`);
2019
+ return { switched: true, selection };
2020
+ }
2021
+
2022
+ /**
2023
+ * 触发 prewalk 交接的「实现动作」。
2024
+ *
2025
+ * 对齐官方语义:不在计划提交时切换,而是等规划模型在同一条会话里落下第一笔实现
2026
+ * 动作之后(首个 edit/write 类工具结果;团队任务则是 Lead 的首次 team_task 派发),
2027
+ * 再把剩下的活交给执行模型,避免便宜模型接手后才发现计划不可执行。
2028
+ */
2029
+ const PREWALK_EDIT_TOOLS = new Set(['write', 'edit', 'str_replace_editor']);
2030
+ const PREWALK_DISPATCH_TOOLS = new Set(['team_task']);
2031
+
2032
+ /** 执行阶段已武装、等待首次实现动作的会话:sessionId → { task, settings }。 */
2033
+ const prewalkArmed = new Map();
2034
+
2035
+ function boardPrewalkWantsTool(name) {
2036
+ return PREWALK_EDIT_TOOLS.has(name) || PREWALK_DISPATCH_TOOLS.has(name);
2037
+ }
2038
+
2039
+ /** 会话里是否已经出现过实现动作(插件重启 / 会话恢复后据此立即补一次交接)。 */
2040
+ function boardSessionStartedImplementation(agent) {
2041
+ try {
2042
+ const session = agent?.session;
2043
+ if (!session || typeof session.eventAt !== 'function' || typeof session.seq !== 'number') return false;
2044
+ const callIds = new Set();
2045
+ for (let seq = 0; seq < session.seq; seq += 1) {
2046
+ const event = session.eventAt(seq);
2047
+ if (!event) continue;
2048
+ if (event.type === 'tool/call' && boardPrewalkWantsTool(String(event.data?.name || ''))) {
2049
+ callIds.add(String(event.data?.callId || ''));
2050
+ } else if (event.type === 'tool/result') {
2051
+ const ok = event.data?.message?.isError !== true;
2052
+ if (ok && callIds.has(String(event.data?.message?.toolCallId || ''))) return true;
2053
+ }
2054
+ }
2055
+ return false;
2056
+ } catch { return false; }
2057
+ }
2058
+
2059
+ /**
2060
+ * 交接 steering:只说「继续」。
2061
+ * 计划、todo、已读文件与已做改动都在会话上下文里,任何附加清单都会诱导接手模型
2062
+ * 逐条核对、重新读文件;让它接着上文做完即可。规划刚提交时用「继续执行计划」,
2063
+ * 明确告诉接手模型规划阶段已经结束。
2064
+ */
2065
+ function boardHandoffSteering(kind) {
2066
+ return kind === 'plan-submitted' ? '继续执行计划' : '继续';
2067
+ }
2068
+
2069
+ /** 交接:切到执行模型并注入一条简短的继续指令;一次任务只做一次。 */
2070
+ async function boardHandoffExecution(ctx, agent, task, settings, kind) {
2071
+ const sessionId = agent?.id != null ? String(agent.id) : null;
2072
+ if (sessionId) prewalkArmed.delete(sessionId);
2073
+ const result = await boardApplyExecutionModel(ctx, agent, task, settings || {});
2074
+ if (!result?.switched) return result;
2075
+ const steering = boardHandoffSteering(kind);
2076
+ try {
2077
+ if (typeof agent.steer === 'function') agent.steer(boardUserMessage(steering));
2078
+ else if (typeof agent.followup === 'function') agent.followup(boardUserMessage(steering));
2079
+ console.log(`[dsh-team] prewalk: 继续指令已注入会话 ${sessionId}`);
2080
+ } catch (err) {
2081
+ console.warn(`[dsh-team] prewalk: 注入继续指令失败(${String(err?.message || err)})`);
2082
+ }
2083
+ return result;
2084
+ }
2085
+
2086
+ /**
2087
+ * 武装 prewalk:记录待交接,等首个实现动作再切模型。
2088
+ * 恢复/重启时如果实现动作已经发生过,直接交接,避免规划模型继续用着贵模型干完。
2089
+ */
2090
+ async function armBoardPrewalk(ctx, agent, task, settings) {
2091
+ const sessionId = agent?.id != null ? String(agent.id) : null;
2092
+ if (!sessionId || !agent || !task?.prewalk) return false;
2093
+ if (boardSessionStartedImplementation(agent)) {
2094
+ await boardHandoffExecution(ctx, agent, task, settings);
2095
+ return true;
2096
+ }
2097
+ if (!prewalkArmed.has(sessionId)) prewalkArmed.set(sessionId, { task, settings: settings || {} });
2098
+ return false;
2099
+ }
2100
+
1765
2101
  function boardPromptModels(task) {
1766
2102
  return Array.isArray(task.teamModels) && task.teamModels.length
1767
2103
  ? task.teamModels.map((m) => (typeof m === 'string' ? m : `${m.provider ? m.provider + '/' : ''}${m.model}`)).join('\n')
1768
2104
  : '不限制';
1769
2105
  }
1770
2106
 
2107
+ // 看板任务的 git 分支:任务开启分支时,spawn 前先切好(不存在就从当前 HEAD 新建)。
2108
+ // git 是可选能力:目录不是仓库 / 没装 git / 切换失败都不阻断任务,只在 prompt 里降级说明。
2109
+ function gitRun(cwd, args) {
2110
+ return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
2111
+ }
2112
+
2113
+ function ensureBoardGitBranch(task) {
2114
+ const branch = String(task?.gitBranch || '').trim();
2115
+ if (!branch) return { branch: null, ok: true };
2116
+ const cwd = String(task.workspacePath || '').trim();
2117
+ if (!cwd) return { branch, ok: false, reason: '工作区路径为空' };
2118
+ try {
2119
+ if (gitRun(cwd, ['rev-parse', '--is-inside-work-tree']).trim() !== 'true') {
2120
+ return { branch, ok: false, reason: '工作区不是 git 仓库' };
2121
+ }
2122
+ } catch {
2123
+ return { branch, ok: false, reason: '工作区不是 git 仓库,或本机没有 git' };
2124
+ }
2125
+ try {
2126
+ const cur = gitRun(cwd, ['rev-parse', '--abbrev-ref', 'HEAD']).trim();
2127
+ if (cur === branch) return { branch, ok: true };
2128
+ } catch { /* 空仓库没有 HEAD,继续尝试新建分支 */ }
2129
+ let exists = false;
2130
+ try {
2131
+ gitRun(cwd, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]);
2132
+ exists = true;
2133
+ } catch { exists = false; }
2134
+ try {
2135
+ gitRun(cwd, exists ? ['checkout', branch] : ['checkout', '-b', branch]);
2136
+ return { branch, ok: true, created: !exists };
2137
+ } catch (err) {
2138
+ const msg = String(err?.stderr || err?.message || err).trim().split(/\r?\n/).filter(Boolean).slice(-2).join(' ');
2139
+ console.warn(`[dsh-team] board git branch ${branch} checkout failed: ${msg}`);
2140
+ return { branch, ok: false, reason: msg || 'git 切分支失败' };
2141
+ }
2142
+ }
2143
+
2144
+ // prompt 里的分支说明:正常时一句话告知「已在目标分支上」;失败时允许自行补救但不强制。
2145
+ function boardBranchLines(task) {
2146
+ const branch = String(task?.gitBranch || '').trim();
2147
+ if (!branch) return [];
2148
+ const st = task.gitBranchState;
2149
+ if (!st || st.ok) {
2150
+ return [`git 分支:${branch}(会话开始前已切好,直接在该分支上改文件;不要自行 checkout 其他分支)`];
2151
+ }
2152
+ return [
2153
+ `git 分支:目标是 ${branch},但自动切分支失败(${st.reason || '未知原因'})。`
2154
+ + `可以用 shell 执行 git checkout -b ${branch}(已存在则 git checkout ${branch})后继续;`
2155
+ + '如果仍失败,就在当前分支继续完成工作,并在最终汇报里明确说明分支未切换。',
2156
+ ];
2157
+ }
2158
+
1771
2159
  function boardPlanningPrompt(task, settings) {
1772
2160
  const useTeam = task.useTeam !== false;
1773
2161
  // 同会话模式:规划与执行是同一个会话,board_plan_submit 会直接领执行槽位,
@@ -1784,6 +2172,7 @@ function boardPlanningPrompt(task, settings) {
1784
2172
  : '规划完成后不要开始执行;调度器会在执行槽位空出后,在同一会话里让你继续。',
1785
2173
  '',
1786
2174
  `工作区:${task.workspacePath}`,
2175
+ ...boardBranchLines(task),
1787
2176
  '任务描述:',
1788
2177
  task.description || '(无)',
1789
2178
  '',
@@ -1832,9 +2221,20 @@ function boardLeadRules(task) {
1832
2221
  + '在原团队里用 team_task 追加剩余工作继续推进;已经完成的成员任务不要重复创建。'
1833
2222
  + '只有原团队已被删除或全部不可用时,才允许 team_create 新团队(若既有团队需要继续保留、只是要并行新建,必须显式传 force: true)。'
1834
2223
  : '1. 先调用 team_create 创建团队;name 用任务标题,workspace 用上面的路径。需要多个团队就多次创建,所有团队都会自动绑定到本任务。';
2224
+ // 用户嘴里的「新任务」经常被 Lead 误当成当前团队的 DAG 节点:先强制做归属判断。
2225
+ const scopeRules = [
2226
+ '先判断用户这次说的事是不是「新任务」:',
2227
+ '- 同一目标 / 同一模块或文件 / 同一验收 / 同一分支 → 是本任务的一部分,在本任务(或本团队)里继续推进。',
2228
+ '- 交付物或验收不同、需要单独分支或单独规划、做完之后不再依赖本任务上下文 → 这是独立的一件事:调用 board_task_create 给它建一张看板卡(workspaceId / workspacePath 沿用本任务),不要用 team_task 塞进当前团队。',
2229
+ '- 用户明确说「建看板任务 / 加一张卡 / 单开一个会话」→ 一律 board_task_create,禁止 team_task。',
2230
+ '- 判断不清就先问用户一句「这算当前任务的一部分,还是另开一张卡?」,不要猜。',
2231
+ '记住:team_task 只拆解当前任务,它不会出现在用户的看板上;用户说的「任务」通常指看板卡片。',
2232
+ ];
1835
2233
  const teamRules = [
1836
2234
  '开始执行前,先加载 `dsh-agent-team` 技能(调用 skill 工具,参数 {"name":"dsh-agent-team"}),按技能里的团队编排流程、工具字段与常见错法执行,不要凭记忆猜参数。',
1837
2235
  '',
2236
+ ...scopeRules,
2237
+ '',
1838
2238
  '规则:',
1839
2239
  teamRule,
1840
2240
  '2. 调用 team_models 查看可用路由;只能使用以下模型:',
@@ -1847,6 +2247,8 @@ function boardLeadRules(task) {
1847
2247
  const soloRules = [
1848
2248
  '本任务不开启团队:由你自己直接完成所有工作,不要调用 team_create / team_spawn / team_task。',
1849
2249
  '',
2250
+ ...scopeRules,
2251
+ '',
1850
2252
  '规则:',
1851
2253
  '1. 按任务描述直接修改文件、运行命令并验证结果。',
1852
2254
  '2. 每轮结束前必须先调用 board_task_status 对齐状态:全部完成→done(附完成摘要),失败→failed(附原因),仍需继续或等待用户→inprogress。不能只在开始时调用一次。',
@@ -1863,12 +2265,14 @@ function boardLeadPrompt(task, sameSession) {
1863
2265
  if (sameSession) {
1864
2266
  return [
1865
2267
  `现在开始执行「${task.title}」。计划就在同一会话的上文里,不要重复输出计划。`,
2268
+ ...boardBranchLines(task),
1866
2269
  '',
1867
2270
  ...rules,
1868
2271
  ].join('\n');
1869
2272
  }
1870
2273
  const lines = [
1871
2274
  `你是任务「${task.title}」的${useTeam ? ' Lead' : '执行 Agent'}。工作区:${task.workspacePath}`,
2275
+ ...boardBranchLines(task),
1872
2276
  needPlan ? '以下是规划会话产出的计划,现在开始执行。' : '本任务不需要规划,直接开始执行。',
1873
2277
  '',
1874
2278
  '任务描述:',
@@ -1951,6 +2355,10 @@ async function spawnBoardSession(s, ctx, item) {
1951
2355
  // 以及 new 模式完成后用户追问,都不能再新建会话。
1952
2356
  const sameSession = kind === 'inprogress' && !!task.leadSessionId;
1953
2357
 
2358
+ // 任务指定 git 分支时,在拉起/复用任何会话之前切好:分支是仓库级状态,会话 cwd 不变,
2359
+ // 同会话续跑也直接落在目标分支上。结果只挂到本地 task 供本轮 prompt 文案使用。
2360
+ task.gitBranchState = ensureBoardGitBranch(task);
2361
+
1954
2362
  // 同会话执行:复用规划会话,只切权限 + 投执行 prompt。
1955
2363
  if (sameSession) {
1956
2364
  const sessionId = String(task.leadSessionId);
@@ -1974,6 +2382,15 @@ async function spawnBoardSession(s, ctx, item) {
1974
2382
  rec.sawRunning = false;
1975
2383
  boardSessions.set(sessionId, rec);
1976
2384
  boardSessionIds.add(sessionId);
2385
+ // prewalk:只武装交接。规划模型先在同一会话里落下第一笔成功的实现动作,
2386
+ // 再由 tools/execute 钩子切模型并注入「继续」;实现动作已经发生(恢复/重启)
2387
+ // 则 armBoardPrewalk 会立即交接,不必等下一笔改动。
2388
+ if (task.prewalk) await armBoardPrewalk(ctx, agent, task, settings);
2389
+ // 规划模型 ≠ 执行模型:复用会话续跑前先静默切到执行模型,
2390
+ // 让紧随其后的执行 prompt(或用户追问)直接由执行模型处理。
2391
+ else if (boardExecutionRouteDiffers(ctx, task, settings)) {
2392
+ await boardApplyExecutionModel(ctx, agent, task, settings);
2393
+ }
1977
2394
  // 用户追问触发 done→inprogress 时,真实用户消息已经在会话里;
1978
2395
  // 这里只恢复状态与权限,不再注入重复的执行 prompt。
1979
2396
  if (!task.resumed) agent.followup(boardUserMessage(boardLeadPrompt(task, true)));
@@ -2038,6 +2455,28 @@ async function boardPump(s, ctx) {
2038
2455
  try {
2039
2456
  const live = await request(s, '/api/board/live');
2040
2457
  for (const task of live?.tasks || []) {
2458
+ // 用户在面板/看板停止任务:sidecar 已把 status 置 failed 并记 stop_requested_at,
2459
+ // 但会话里的回合不会自己停(solo 任务没有团队,连 stopTeam 都走不到)。
2460
+ // 这里对任务当前的 Lead/规划会话取消一次当前回合,语义同用户按停止键。
2461
+ const stopStamp = task?.stopRequestedAt != null ? String(task.stopRequestedAt) : '';
2462
+ if (stopStamp && boardStopSeen.get(task.id) !== stopStamp) {
2463
+ // 只在停止后 2 分钟内取消:插件重启后 boardStopSeen 是空的,旧停止戳不该
2464
+ // 再去打断用户后来对终态任务 Lead 的新追问。
2465
+ const age = Date.now() - Date.parse(stopStamp);
2466
+ if (!Number.isFinite(age) || age > 120_000) { boardStopSeen.set(task.id, stopStamp); continue; }
2467
+ const sid = String(task.leadSessionId || task.planningSessionId || '');
2468
+ const rec = sid ? boardSessions.get(sid) : null;
2469
+ let agent = rec?.handle?.agent || null;
2470
+ if (!agent && sid) {
2471
+ try { agent = agents.get(sid); } catch { agent = null; }
2472
+ }
2473
+ if (agent) {
2474
+ boardStopSeen.set(task.id, stopStamp);
2475
+ if (agent.status === 'running') {
2476
+ try { agent.cancel({ kind: 'user' }); } catch { boardStopSeen.delete(task.id); }
2477
+ }
2478
+ }
2479
+ }
2041
2480
  // 插件重启后 boardSessions 是空的:能找回 live agent 就接管,找不回就把
2042
2481
  // 永远不可能再推进的任务置 failed,避免占着槽位。
2043
2482
  if (task.status === 'done' || task.status === 'failed') {
@@ -2249,20 +2688,19 @@ function buildTools(s, ctx) {
2249
2688
  const memberName = String(args.name).trim();
2250
2689
  const description = String(args.description || args.role || memberName).slice(0, 200);
2251
2690
  const sessionId = randomUUID();
2252
- const started = await subs.startActivation({
2691
+ const started = await subs.startActivation(activationSpec({
2692
+ prompt: [{ type: 'text', text: String(args.prompt) }],
2693
+ parent: caller,
2694
+ ...(team && team.workspace ? { cwd: team.workspace } : {}),
2695
+ ...(Object.keys(agentOptions).length ? { agentOptions } : {}),
2696
+ ...(agentPreset ? { agentPreset } : {}),
2697
+ }, {
2253
2698
  delivery: 'parent',
2254
2699
  childId: sessionId,
2255
2700
  provider,
2256
2701
  label: memberLabel(memberName, description),
2257
- request: {
2258
- prompt: [{ type: 'text', text: String(args.prompt) }],
2259
- parent: caller,
2260
- ...(team && team.workspace ? { cwd: team.workspace } : {}),
2261
- ...(Object.keys(agentOptions).length ? { agentOptions } : {}),
2262
- ...(agentPreset ? { agentPreset } : {}),
2263
- },
2264
2702
  signal: exec.signal || AbortSignal.timeout(s.requestTimeoutMs),
2265
- });
2703
+ }));
2266
2704
  // 成员跑的是一整轮 agent loop,结果由 team_report_task 汇报;这里只防止未处理的 rejection。
2267
2705
  if (started && started.result && typeof started.result.catch === 'function') started.result.catch(() => {});
2268
2706
  // 子会话发布后立刻把 preset 落到会话(会覆盖 subagent 继承来的 approval=never)。
@@ -2314,26 +2752,31 @@ function buildTools(s, ctx) {
2314
2752
 
2315
2753
  tools.push({
2316
2754
  name: 'team_models',
2317
- 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 }).',
2755
+ description: 'List the model routes enabled for this team: provider id, model id, display name, note, providerNote (the vendor-level strength the user wrote, e.g. "适合逻辑处理" / "适合做设计"), 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 }).',
2318
2756
  parameters: {
2319
2757
  type: 'object',
2320
2758
  additionalProperties: false,
2321
2759
  properties: {},
2322
2760
  },
2323
- output: jsonOutput('{ asOf, total, models: [{ provider, model, name, description, note, modalities, efforts?, defaultEffort? }], hint? }'),
2761
+ output: jsonOutput('{ asOf, total, models: [{ provider, model, name, description, note, providerNote, modalities, efforts?, defaultEffort? }], hint? }'),
2324
2762
  isConcurrencySafe: () => true,
2325
2763
  async execute() {
2326
2764
  let cat = null;
2327
2765
  try { cat = await request(s, '/api/llm/catalog'); } catch { /* catalog unavailable */ }
2766
+ // 厂商级备注(用户在面板分组头写的「这个厂商擅长什么」)随每个 route 一起下发,
2767
+ // 让模型在派活时能按「擅长逻辑 / 擅长设计」这类语义选厂商,而不只看模型 id。
2768
+ const providerNotes = new Map((cat?.providers || []).map((p) => [p.id, p.note || null]));
2328
2769
  const all = cat ? (cat.providers || []).flatMap((p) => p.models || []) : [];
2329
2770
  const models = all.filter((m) => m.enabled).map((m) => {
2330
2771
  // 只报用户允许的 effort;allowedEfforts=null 表示全部允许。未声明 efforts 的 route 不报该字段。
2331
2772
  const effortIds = Array.isArray(m.efforts) ? m.efforts.map((e) => e.id) : [];
2332
2773
  const allowed = Array.isArray(m.allowedEfforts) ? effortIds.filter((id) => m.allowedEfforts.includes(id)) : effortIds;
2774
+ const providerNote = providerNotes.get(m.provider);
2333
2775
  return {
2334
2776
  provider: m.provider,
2335
2777
  model: m.model,
2336
2778
  name: m.name,
2779
+ ...(providerNote ? { providerNote } : {}),
2337
2780
  ...(m.description ? { description: m.description } : {}),
2338
2781
  ...(m.note ? { note: m.note } : {}),
2339
2782
  ...(m.modalities ? { modalities: m.modalities } : {}),
@@ -2341,7 +2784,8 @@ function buildTools(s, ctx) {
2341
2784
  };
2342
2785
  });
2343
2786
  const hint = models.length
2344
- ? '在 team_spawn 里用 agentProvider + model;efforts 是该 route 允许派发的 reasoningEffort 列表(省略时只在 route 不变时继承 Lead 的 effort,被禁止的 effort 会被拒绝)。'
2787
+ ? '在 team_spawn 里用 agentProvider + model;providerNote 是该厂商整体强项(用户填写的厂商备注),note 是单模型差异;'
2788
+ + 'efforts 是该 route 允许派发的 reasoningEffort 列表(省略时只在 route 不变时继承 Lead 的 effort,被禁止的 effort 会被拒绝)。'
2345
2789
  : '没有启用的模型路由:请让用户在面板「模型路由」页勾选需要的 provider/model。';
2346
2790
  return {
2347
2791
  asOf: cat?.asOf || new Date().toISOString(),
@@ -2454,9 +2898,37 @@ function buildTools(s, ctx) {
2454
2898
  },
2455
2899
  });
2456
2900
 
2901
+ tools.push({
2902
+ name: 'team_task_get',
2903
+ description: 'Read ONE DAG task of a team instead of the whole status: subject/status/assignee/attempts/maxAttempts/failurePolicy, its plan and acceptance, plus ledger node info (dependsOn, ready, blocked, blockers). Use it to confirm a task was dispatched, to check whether it is blocked on a dependency or a member, and to decide whether to retry or re-dispatch it. teamId is optional when the caller is already bound to that team.',
2904
+ parameters: {
2905
+ type: 'object',
2906
+ additionalProperties: false,
2907
+ properties: {
2908
+ taskId: { type: 'string', description: 'Task id returned by team_task (task_…).' },
2909
+ teamId: { type: 'string', description: 'Optional ownership check; inferred from the caller session when omitted.' },
2910
+ },
2911
+ required: ['taskId'],
2912
+ },
2913
+ output: jsonOutput('{ task, node }'),
2914
+ isConcurrencySafe: () => true,
2915
+ async execute(args) {
2916
+ const task = await request(s, `/api/tasks/${encodeURIComponent(args.taskId)}`);
2917
+ const teamId = String(args.teamId || task.teamId || '');
2918
+ if (!teamId) throw new Error('team_task_get 无法确定 teamId:请显式传入');
2919
+ if (args.teamId && String(task.teamId) !== String(args.teamId)) {
2920
+ throw new Error(`task ${task.id} 不属于 team ${args.teamId}`);
2921
+ }
2922
+ // DAG 节点提供依赖/就绪/阻塞信息,task 行本身不存这些派生状态。
2923
+ const dag = await request(s, `/api/dag${qs({ team: teamId })}`).catch(() => null);
2924
+ const node = dag?.nodes?.find((n) => n.taskId === task.id) || null;
2925
+ return { task, node };
2926
+ },
2927
+ });
2928
+
2457
2929
  tools.push({
2458
2930
  name: 'team_task',
2459
- description: 'Declare one task (DAG node) and hand it to a member. 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 it 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. `deps[].from` takes a **task** id returned by an earlier team_task (member ids are rejected). The scheduler satisfies dependencies itself — never poll. The task dispatches immediately to an idle member once dependencies are satisfied; pass dispatch:false to build the DAG first.',
2931
+ description: 'Only for decomposing the CURRENT task: declare one task (DAG node) and hand it to a member. When the user asks for a new, separate task card (own deliverable or acceptance, own branch/session), use board_task_create instead — team_task items never appear on the board. 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 it 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. `deps[].from` takes a **task** id returned by an earlier team_task (member ids are rejected). The scheduler satisfies dependencies itself — never poll. The task dispatches immediately to an idle member once dependencies are satisfied; pass dispatch:false to build the DAG first.',
2460
2932
  parameters: {
2461
2933
  type: 'object',
2462
2934
  additionalProperties: false,
@@ -2513,7 +2985,7 @@ function buildTools(s, ctx) {
2513
2985
 
2514
2986
  tools.push({
2515
2987
  name: 'team_send',
2516
- description: "Send a message that a member will actually read: the text is injected into the target sub-agent's message inbox. By default a running member's current turn is interrupted first, so the message immediately starts a fresh turn instead of waiting for the next step boundary; pass `interrupt: false` to keep the current turn and deliver at the next step boundary. An idle member is woken. `to` is a member NAME (member id also accepted) or '*' to broadcast; use to:'lead' to reply to the Lead. Every send is also recorded on the sidecar so the panel shows the conversation.",
2988
+ description: "Send a message that a member will actually read: the text is injected into the target sub-agent's message inbox. By default a running member's current turn is interrupted first, so the message immediately starts a fresh turn instead of waiting for the next step boundary; pass `interrupt: false` to keep the current turn and deliver at the next step boundary. An idle member is woken. `to` is a member NAME (member id also accepted) or '*' to broadcast; use to:'lead' to reply to the Lead. Every send is also recorded on the sidecar so the panel shows the conversation. Returns delivery status only, never the member's reply: the reply arrives asynchronously as a new message in a later turn. Never wait for it with sleep/Start-Sleep/delayed scripts, polling loops, or repeated team_status calls — after sending, continue independent work or end the turn.",
2517
2989
  parameters: {
2518
2990
  type: 'object',
2519
2991
  additionalProperties: false,
@@ -3074,20 +3546,19 @@ function buildTools(s, ctx) {
3074
3546
  if (route.reasoningEffort) agentOptions.reasoningEffort = String(route.reasoningEffort);
3075
3547
 
3076
3548
  const sessionId = randomUUID();
3077
- const started = await subs.startActivation({
3549
+ const started = await subs.startActivation(activationSpec({
3550
+ prompt: [{ type: 'text', text: `你是团队成员 ${current.name}(${role || 'teammate'})。配置刚刚更新,这是新的会话;当前没有任务,等待 Lead 派发。收到任务后按简报执行,完成时调用 team_report_task。` }],
3551
+ parent: caller,
3552
+ ...(team.workspace ? { cwd: team.workspace } : {}),
3553
+ ...(Object.keys(agentOptions).length ? { agentOptions } : {}),
3554
+ ...(agentPreset ? { agentPreset } : {}),
3555
+ }, {
3078
3556
  delivery: 'parent',
3079
3557
  childId: sessionId,
3080
3558
  provider,
3081
3559
  label: memberLabel(current.name, String(role || current.name)),
3082
- request: {
3083
- prompt: [{ type: 'text', text: `你是团队成员 ${current.name}(${role || 'teammate'})。配置刚刚更新,这是新的会话;当前没有任务,等待 Lead 派发。收到任务后按简报执行,完成时调用 team_report_task。` }],
3084
- parent: caller,
3085
- ...(team.workspace ? { cwd: team.workspace } : {}),
3086
- ...(Object.keys(agentOptions).length ? { agentOptions } : {}),
3087
- ...(agentPreset ? { agentPreset } : {}),
3088
- },
3089
3560
  signal: exec.signal || AbortSignal.timeout(s.requestTimeoutMs),
3090
- });
3561
+ }));
3091
3562
  if (started && started.result && typeof started.result.catch === 'function') started.result.catch(() => {});
3092
3563
  const presetResult = applyPermissionPreset(ctx, sessionId, permissionPreset);
3093
3564
 
@@ -3179,7 +3650,27 @@ function buildTools(s, ctx) {
3179
3650
  // 同会话模式:sidecar 保存计划时已经 claim 执行槽位并 attach 回本会话,
3180
3651
  // 这里只切权限、改 phase,让同一个回合直接继续执行(不再补发第二条 prompt)。
3181
3652
  if (task?.status === 'inprogress') {
3182
- if (task.leadPermissionPreset) boardSetPermission(ctx, rec?.handle?.agent || exec?.agent, task.leadPermissionPreset);
3653
+ const agent = rec?.handle?.agent || exec?.agent;
3654
+ if (task.leadPermissionPreset) boardSetPermission(ctx, agent, task.leadPermissionPreset);
3655
+ // prewalk:这里只武装、不切模型。规划模型先按计划落下第一笔实现动作
3656
+ // (首次 edit/write 或首次 team_task 派发),确认计划可执行后再交给执行模型。
3657
+ if (task.prewalk) {
3658
+ const boardSettings = await request(
3659
+ s,
3660
+ `/api/board/settings?workspaceId=${encodeURIComponent(task.workspaceId)}`,
3661
+ ).catch(() => null);
3662
+ await armBoardPrewalk(ctx, agent, task, boardSettings || {});
3663
+ } else if (task.executionMode === 'same') {
3664
+ // 规划模型 ≠ 执行模型:规划一提交就交接,让新模型在同一会话里接着执行,
3665
+ // 而不是继续用规划模型把执行阶段干完。
3666
+ const boardSettings = await request(
3667
+ s,
3668
+ `/api/board/settings?workspaceId=${encodeURIComponent(task.workspaceId)}`,
3669
+ ).catch(() => null);
3670
+ if (boardExecutionRouteDiffers(ctx, task, boardSettings || {})) {
3671
+ await boardHandoffExecution(ctx, agent, task, boardSettings || {}, 'plan-submitted');
3672
+ }
3673
+ }
3183
3674
  if (rec) { rec.phase = 'execution'; rec.sawRunning = false; }
3184
3675
  } else if (rec) {
3185
3676
  rec.phase = 'planned';
@@ -3220,6 +3711,120 @@ function buildTools(s, ctx) {
3220
3711
  },
3221
3712
  });
3222
3713
 
3714
+ tools.push({
3715
+ name: 'board_task_create',
3716
+ description: 'Create a new workspace-board task card (the user-facing queue the board scheduler picks up) — use it when the user asks for a new task that is a separate deliverable or deserves its own session/branch (not a step of the current task, which is team_task). This is NOT a team DAG task: team_* tools stay inside the current team. workspaceId defaults to the caller own board task, then to the only registered workspace; pass it when either is ambiguous. Pass gitBranch to run the new task on a git branch ("" = auto `task/<id>`, omitted = no branch).',
3717
+ parameters: {
3718
+ type: 'object',
3719
+ additionalProperties: false,
3720
+ properties: {
3721
+ title: { type: 'string', description: 'Card title; the card is created in todo.' },
3722
+ description: { type: 'string', description: 'Full instructions for the session that will run this card.' },
3723
+ workspaceId: { type: 'string', description: 'Board workspace id; inferred from the caller board task or the single registered workspace.' },
3724
+ workspacePath: { type: 'string', description: 'Workspace path; defaults to the registered workspace path.' },
3725
+ auto: { type: 'boolean', description: 'Queue immediately (default false: stays in todo until started).' },
3726
+ needPlan: { type: 'boolean', description: 'Run a planning session first (default true).' },
3727
+ useTeam: { type: 'boolean', description: 'Let the Lead orchestrate a team (default true).' },
3728
+ executionMode: { type: 'string', enum: ['same', 'new'], description: 'same = plan and execute in one session; new = execute in a fresh session.' },
3729
+ gitBranch: { type: 'string', description: 'Git branch to switch to before spawning; "" auto-generates task/<id>.' },
3730
+ },
3731
+ required: ['title'],
3732
+ },
3733
+ output: jsonOutput('{ task }'),
3734
+ async execute(args, exec) {
3735
+ const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
3736
+ let workspaceId = args.workspaceId ? String(args.workspaceId) : null;
3737
+ let workspacePath = args.workspacePath ? String(args.workspacePath) : null;
3738
+ // 优先沿用调用者自己那张看板卡的工作区:它一定和当前会话的 cwd 一致。
3739
+ if (!workspaceId && sessionId) {
3740
+ const cur = await request(s, `/api/board/by-session/${encodeURIComponent(sessionId)}`).catch(() => null);
3741
+ if (cur && cur.ok !== false && cur.id) {
3742
+ workspaceId = cur.workspaceId;
3743
+ workspacePath = workspacePath || cur.workspacePath;
3744
+ }
3745
+ }
3746
+ const list = await request(s, '/api/workspaces').catch(() => null);
3747
+ const items = Array.isArray(list?.items) ? list.items : [];
3748
+ const samePath = (a, b) => String(a || '') === String(b || '');
3749
+ if (!workspaceId) {
3750
+ const byPath = workspacePath ? items.find((w) => samePath(w.path, workspacePath)) : null;
3751
+ if (byPath) {
3752
+ workspaceId = byPath.id;
3753
+ workspacePath = workspacePath || byPath.path;
3754
+ } else if (items.length === 1) {
3755
+ workspaceId = items[0].id;
3756
+ workspacePath = workspacePath || items[0].path;
3757
+ }
3758
+ }
3759
+ if (!workspaceId) throw new Error('board_task_create 需要 workspaceId:当前会话不属于任何看板任务,且工作区不唯一');
3760
+ // 手填的 workspaceId 可能根本不存在(模型常填 00000000-… 占位 UUID)。这种卡会挂到
3761
+ // 一个 UI 上不存在的“幽灵工作区”,看板按 workspace_id 过滤后完全看不到,所以这里必须
3762
+ // 先解析:按 workspacePath 改挂到已注册工作区;DSH 注册表里确实存在(sidecar 还没同步)
3763
+ // 才放行;否则直接报错,别落库。
3764
+ if (!items.some((w) => String(w.id) === workspaceId)) {
3765
+ const byPath = workspacePath ? items.find((w) => samePath(w.path, workspacePath)) : null;
3766
+ if (byPath) {
3767
+ workspaceId = byPath.id;
3768
+ workspacePath = byPath.path || workspacePath;
3769
+ } else {
3770
+ const registry = (() => { try { return ctx.get('workspaceRegistry'); } catch { return undefined; } })();
3771
+ const known = registry && typeof registry.get === 'function' ? registry.get(workspaceId) : null;
3772
+ if (!known) {
3773
+ throw new Error(`board_task_create 的 workspaceId 不存在:${workspaceId}。可用工作区:${items.map((w) => `${w.id}(${w.title || w.path})`).join('、') || '(sidecar 还没同步到工作区)'}`);
3774
+ }
3775
+ }
3776
+ }
3777
+ const task = await request(s, '/api/board/tasks', {
3778
+ method: 'POST',
3779
+ body: {
3780
+ workspaceId,
3781
+ ...(workspacePath ? { workspacePath } : {}),
3782
+ title: args.title,
3783
+ description: args.description || '',
3784
+ ...(args.auto !== undefined ? { auto: args.auto } : {}),
3785
+ ...(args.needPlan !== undefined ? { needPlan: args.needPlan } : {}),
3786
+ ...(args.useTeam !== undefined ? { useTeam: args.useTeam } : {}),
3787
+ ...(args.executionMode !== undefined ? { executionMode: args.executionMode } : {}),
3788
+ ...(args.gitBranch !== undefined ? { gitBranch: args.gitBranch } : {}),
3789
+ },
3790
+ });
3791
+ return { task };
3792
+ },
3793
+ });
3794
+
3795
+ tools.push({
3796
+ name: 'board_task_get',
3797
+ description: 'Read the current workspace-board task of this session (status/planSummary/lastError/gitBranch/sessions) when taskId is omitted, or any board card by taskId. Cheap and safe to call every turn: it returns the status snapshot, not the whole plan body. Use it to decide whether to keep working, wait, or report via board_task_status.',
3798
+ parameters: {
3799
+ type: 'object',
3800
+ additionalProperties: false,
3801
+ properties: {
3802
+ taskId: { type: 'string', description: 'Board task id (bt_…); omit to read the caller own card.' },
3803
+ },
3804
+ },
3805
+ output: jsonOutput('{ task }'),
3806
+ isConcurrencySafe: () => true,
3807
+ async execute(args, exec) {
3808
+ const pick = (t) => ({
3809
+ id: t.id, workspaceId: t.workspaceId, title: t.title, status: t.status,
3810
+ executionMode: t.executionMode, needPlan: t.needPlan, useTeam: t.useTeam,
3811
+ gitBranch: t.gitBranch || null,
3812
+ planSummary: t.planSummary || null, lastError: t.lastError || null,
3813
+ planningSessionId: t.planningSessionId || null, leadSessionId: t.leadSessionId || null,
3814
+ teams: t.teams || [], archivedAt: t.archivedAt || null, updatedAt: t.updatedAt,
3815
+ });
3816
+ if (args.taskId) {
3817
+ const task = await request(s, `/api/board/tasks/${encodeURIComponent(args.taskId)}`);
3818
+ return { task: pick(task) };
3819
+ }
3820
+ const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
3821
+ if (!sessionId) throw new Error('board_task_get 需要 taskId,或从看板会话里调用');
3822
+ const found = await request(s, `/api/board/by-session/${encodeURIComponent(sessionId)}`).catch(() => null);
3823
+ if (!found || found.ok === false || !found.id) throw new Error('当前会话没有关联的看板任务');
3824
+ return { task: pick(found) };
3825
+ },
3826
+ });
3827
+
3223
3828
  return tools;
3224
3829
  }
3225
3830
 
@@ -3318,8 +3923,14 @@ async function reportFileChange(s, ctx, exec, next) {
3318
3923
  // 再问 workingDirectory 服务;都拿不到才退回宿主进程 cwd(此时相对路径多半解析不到,diff 会被跳过)。
3319
3924
  let agentCwd = typeof exec?.agent?.cwd === 'string' ? exec.agent.cwd : '';
3320
3925
  if (!agentCwd && binding.cwd) agentCwd = binding.cwd;
3321
- if (!agentCwd && exec?.agent?.session && typeof ctx?.workingDirectory?.get === 'function') {
3322
- try { agentCwd = ctx.workingDirectory.get(exec.agent.session) || ''; } catch { /* 忽略 */ }
3926
+ if (!agentCwd && exec?.agent?.session) {
3927
+ // Cordis 的 ctx 是 Proxy:读未 inject 的服务(ctx.workingDirectory)会直接抛
3928
+ // 「cannot get property "workingDirectory" without inject」,可选链也拦不住。
3929
+ // 必须走 ctx.get()(不要求 inject);拿不到再退回宿主 cwd。
3930
+ try {
3931
+ const wd = ctx?.get?.('workingDirectory');
3932
+ if (wd && typeof wd.get === 'function') agentCwd = wd.get(exec.agent.session) || '';
3933
+ } catch { /* 忽略:目录拿不到时退回宿主 cwd */ }
3323
3934
  }
3324
3935
  const baseDir = agentCwd || process.cwd();
3325
3936
  const abs = path.isAbsolute(raw) ? raw : path.resolve(baseDir, raw);
@@ -3527,10 +4138,11 @@ export function apply(ctx, config) {
3527
4138
  const disposers = buildTools(s, ctx).map((tool) => ctx.tools.register(tool));
3528
4139
  return () => {
3529
4140
  for (const dispose of disposers.reverse()) { try { dispose(); } catch { /* ignore */ } }
3530
- leadByTeam.clear(); teamCache.clear(); sessionMember.clear(); dispatching.clear(); teamBySession.clear(); contextReportAt.clear();
4141
+ leadByTeam.clear(); teamCache.clear(); sessionMember.clear(); dispatching.clear(); teamBySession.clear(); contextReportAt.clear(); prewalkArmed.clear();
3531
4142
  for (const timer of idleTimers.values()) clearTimeout(timer);
3532
4143
  for (const timer of startTimers.values()) clearTimeout(timer);
3533
4144
  idleTimers.clear(); startTimers.clear(); agentStatusBySession.clear(); lastReplyBySession.clear();
4145
+ interruptNotified.clear();
3534
4146
  const spawned = s.spawned;
3535
4147
  if (spawned?.child && spawned.child.exitCode === null) {
3536
4148
  try { spawned.child.kill(); } catch { /* ignore */ }
@@ -3575,7 +4187,7 @@ export function apply(ctx, config) {
3575
4187
 
3576
4188
  // 审批分类需要工具参数,但 approval/request 只带 toolName/callId:
3577
4189
  // 在 pre-execute 里按 callId 缓存成员这一轮的入参(只记成员,带 TTL),供低风险命令自动放行判定。
3578
- if (s.autoApproveLowRisk) {
4190
+ if (s.autoApproveLowRisk || s.autoApproveTools.length) {
3579
4191
  ctx.on('tools/pre-execute', (exec, next) => {
3580
4192
  try { rememberPreExecuteArgs(exec); } catch { /* ignore */ }
3581
4193
  return typeof next === 'function' ? next() : undefined;
@@ -3604,6 +4216,34 @@ export function apply(ctx, config) {
3604
4216
  ctx.on('tools/execute', fileChangeHook);
3605
4217
  }
3606
4218
 
4219
+ // prewalk(实验性):先在原模型上做第一笔实现动作,再交接同一条会话。
4220
+ // 只有武装过的看板会话参与;交接失败不影响工具结果,也不阻断任务。
4221
+ const prewalkHook = async (exec, next) => {
4222
+ const result = await next();
4223
+ try {
4224
+ const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
4225
+ const entry = sessionId ? prewalkArmed.get(sessionId) : null;
4226
+ if (!entry) return result;
4227
+ const name = String(exec?.name || '');
4228
+ // 任务收工(done/failed)时清掉未触发的武装,避免会话结束后残留。
4229
+ if (name === 'board_task_status' && exec?.arguments?.status !== 'inprogress') {
4230
+ prewalkArmed.delete(sessionId);
4231
+ return result;
4232
+ }
4233
+ if (!boardPrewalkWantsTool(name)) return result;
4234
+ // 工具报错(参数错、权限拒绝等)不算「已经落到实现」:保持武装,等下一次
4235
+ // 成功的 edit/write(或 team_task)再交接,避免接手模型先替规划模型收拾失败。
4236
+ if (result && (result.isError === true || result.error != null)) return result;
4237
+ prewalkArmed.delete(sessionId);
4238
+ await boardHandoffExecution(ctx, exec.agent, entry.task, entry.settings);
4239
+ } catch (err) {
4240
+ console.warn(`[dsh-team] prewalk: 交接失败(${String(err?.message || err)})`);
4241
+ }
4242
+ return result;
4243
+ };
4244
+ prewalkHook.dshTeamHook = 'prewalk';
4245
+ ctx.on('tools/execute', prewalkHook);
4246
+
3607
4247
  // 成员用内置 todo_write 维护计划(没建 team_todo)时,把 DSH 的 `todos` 投影镜像成
3608
4248
  // sidecar 计划步骤:面板/团队校验能看到真实 plan,todo 勾完计划步骤也跟着完成。
3609
4249
  ctx.on('tools/execute', async (exec, next) => {
@@ -3697,6 +4337,19 @@ export function apply(ctx, config) {
3697
4337
  cancelIdleReport(sessionId);
3698
4338
  agentStatusBySession.set(sessionId, 'idle');
3699
4339
  reportAgentStatus(s, sessionId, 'failed', `模型回合失败:${msg}`);
4340
+ // 会话以 error 结束同样算「成员意外中断」:不通知,挂起的 Lead 只会在下一次主动查状态时才发现。
4341
+ const bind = sessionMember.get(sessionId);
4342
+ if (bind) {
4343
+ void notifyLeadOfMemberInterrupt(s, ctx, {
4344
+ teamId: bind.teamId,
4345
+ memberId: bind.memberId,
4346
+ memberName: bind.name || null,
4347
+ sessionId,
4348
+ status: 'failed',
4349
+ reason: `模型回合失败:${msg}`,
4350
+ dedupeKey: `failed:${sessionId}:${event.seq ?? event.data?.turn ?? ''}:${msg}`,
4351
+ }).catch(() => { /* 通知尽力而为 */ });
4352
+ }
3700
4353
  }
3701
4354
  return;
3702
4355
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-team-control",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
4
4
  "type": "module",
5
5
  "description": "Expose the local dsh-team sidecar as model-facing tools (team_create / team_spawn / team_status / team_task / team_send / team_report_task / team_dispatch / team_control / team_approve / team_report), spawn real DSH sub-agent members with per-member permission presets, forward member approvals to the Lead, and manage the sidecar lifecycle.",
6
6
  "icon": "./icon.svg",
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "license": "MIT",
23
23
  "dependencies": {
24
- "dsh-team-control-cli": "^0.2.8"
24
+ "dsh-team-control-cli": "^0.2.9"
25
25
  },
26
26
  "exports": {
27
27
  ".": "./index.js",