dsh-team-control 0.2.3 → 0.2.5

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 +7 -3
  2. package/index.js +170 -6
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -33,6 +33,7 @@
33
33
  - `team_create.permissionPreset`:团队默认值(默认 `workspace-write`)。
34
34
  - `team_spawn.permissionPreset`:成员覆盖;不传则继承团队。
35
35
  - 返回值里的 `permissionPresetApplied` 表示是否真的写进子会话;宿主没有这个服务或预设名未知时给 `permissionPresetWarning`,不阻断派发。
36
+ - `team_member({action:"update", permissionPreset})` 可对 **运行中** 的成员热改权限(直接 `permissionPresets.set`,无需 interrupt);换模型/上下文/组合仍要求先 `interrupt`。
36
37
 
37
38
  `agentPreset` 是另一套(组合:工具/skill/MCP + 系统提示词):团队默认 + 成员覆盖,用宿主 `agentPresets.list()` 校验;
38
39
  只在 `contextMode: 'fresh'` 时透传给 `startActivation`,`fork` 继承父方组合并返回 `agentPresetWarning`。
@@ -47,9 +48,10 @@
47
48
  成员触发的宿主审批不会静默失败,而是转发给 Lead:
48
49
 
49
50
  1. 全局监听 `approval/request`;请求的 agent 不属于任何团队成员 → 交给后面的 handler(`next()`)。
50
- 2. 属于成员 → `POST /api/approvals` 镜像一条 pending,并 `subagents.sendMessage` 通知 Lead,文本含 `requestId`、成员、工具、原因与 `team_approve` 调用示例。
51
- 3. Lead 调 `team_approve {teamId, requestId, decision: allow|deny, reason?}` → 插件 resolve 为 `allowed-once` / `rejected`,同时把 sidecar 记录改成 allowed/rejected。
52
- 4. 超过 `approvalTimeoutMs`(默认 10 分钟)自动拒绝并标记 expired;成员回合被取消时按 cancelled 处理。
51
+ 2. 属于成员 → 先做低风险判定:`tools/pre-execute` 按 `callId` 缓存入参,若工具名像 shell、参数带字符串 `command`,且命令是白名单程序、无管道/重定向/命令替换、不命中敏感规则 → 直接返回 `allowed-once` 并镜像 `decidedBy:"auto"`,不通知 Lead。
52
+ 3. 其余请求 → `POST /api/approvals` 镜像一条 pending,并 `subagents.sendMessage` 通知 Lead,文本含 `requestId`、成员、工具、原因与 `team_approve` 调用示例。
53
+ 4. Lead 调 `team_approve {teamId, requestId, decision: allow|deny, reason?}` → 插件 resolve 为 `allowed-once` / `rejected`,同时把 sidecar 记录改成 allowed/rejected。
54
+ 5. 超过 `approvalTimeoutMs`(默认 10 分钟)自动拒绝并标记 expired;成员回合被取消时按 cancelled 处理。
53
55
 
54
56
  ## 模型路由(每个成员不同的 provider / model / effort)
55
57
 
@@ -93,6 +95,8 @@ dsh plugin --profile web add dsh-team-control
93
95
  | `startTimeoutMs` | `20000` | 自动拉起的等待上限 |
94
96
  | `requestTimeoutMs` | `60000` | 单次 API 调用超时 |
95
97
  | `approvalTimeoutMs` | `600000` | 成员审批等待 Lead 的上限;超时自动拒绝 |
98
+ | `autoApproveLowRisk` | `true` | 低风险 shell 命令自动放行(不通知 Lead,镜像 `decidedBy:auto`) |
99
+ | `sensitiveCommandPatterns` | `[]` | 追加的敏感命令正则;命中即转 Lead 审批 |
96
100
  | `reportToolCalls` | `true` | 监听 `tools/execute`,把每次工具调用上报为 `POST /api/spans` 的 span |
97
101
  | `traceInputMax` | `1200` | 上报参数/结果预览的截断长度(字符) |
98
102
  | `agentAutoDispatch` | `true` | 调度器自动把 ready 任务派给 idle 成员 |
package/index.js CHANGED
@@ -86,6 +86,13 @@ 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,
90
+ // 不打扰 Lead;敏感命令(见 DEFAULT_SENSITIVE_COMMAND_PATTERNS)仍转 Lead 审批
91
+ autoApproveLowRisk: c.autoApproveLowRisk !== false,
92
+ // 追加的敏感命令正则(字符串数组):命中即视为敏感,仍走 Lead 审批
93
+ sensitiveCommandPatterns: Array.isArray(c.sensitiveCommandPatterns)
94
+ ? c.sensitiveCommandPatterns.map((p) => String(p)).filter(Boolean)
95
+ : [],
89
96
  // spawnTeammate 的 provider:默认与 dsh-experimental-tool-agent-team 一致
90
97
  freshProvider: String(c.freshProvider || 'spawn'),
91
98
  forkProvider: String(c.forkProvider || 'fork'),
@@ -356,11 +363,34 @@ function collectContext(ctx, sessionId) {
356
363
  let projection = {};
357
364
  try {
358
365
  if (projections && typeof projections.snapshot === 'function') {
359
- projection = projections.snapshot(session, ['contextBreakdown', 'contextPressure'])?.values || {};
366
+ projection = projections.snapshot(session, ['contextBreakdown', 'contextPressure', 'sessionStats', 'tokenUsage'])?.values || {};
360
367
  }
361
368
  } catch { projection = {}; }
362
369
  const breakdown = projection.contextBreakdown || {};
363
370
  const pressure = projection.contextPressure || {};
371
+ const sessionStats = projection.sessionStats || null;
372
+ const tokenUsage = projection.tokenUsage || null;
373
+ let stats = null;
374
+ if (sessionStats || tokenUsage) {
375
+ const uncached = Number(tokenUsage?.uncachedInputTokens) || 0;
376
+ const cacheRead = Number(tokenUsage?.cacheReadTokens) || 0;
377
+ const cacheWrite = Number(tokenUsage?.cacheWriteTokens) || 0;
378
+ const input = uncached + cacheRead + cacheWrite;
379
+ stats = {
380
+ turns: Number(sessionStats?.turns) || 0,
381
+ steps: Number(sessionStats?.steps) || 0,
382
+ llmMs: Number(sessionStats?.llmMs) || 0,
383
+ toolMs: Number(sessionStats?.toolMs) || 0,
384
+ ttftMs: Number(sessionStats?.ttftMs) || 0,
385
+ decodeMs: Number(sessionStats?.decodeMs) || 0,
386
+ decodeTokens: Number(sessionStats?.decodeTokens) || 0,
387
+ inputTokens: input,
388
+ outputTokens: Number(tokenUsage?.outputTokens) || 0,
389
+ cacheReadTokens: cacheRead,
390
+ cacheWriteTokens: cacheWrite,
391
+ cacheHitRate: input > 0 ? cacheRead / input : null,
392
+ };
393
+ }
364
394
 
365
395
  // 当前 surface 上的事件才计价:被压缩掉的事件不在 nodes 里。
366
396
  const priceBySeq = new Map();
@@ -459,6 +489,7 @@ function collectContext(ctx, sessionId) {
459
489
  },
460
490
  blocks,
461
491
  compaction,
492
+ stats,
462
493
  status: null,
463
494
  asOfSeq: Number(session.seq) || null,
464
495
  surfaceCount,
@@ -1097,6 +1128,99 @@ async function dispatchLoop(s, ctx, teamId) {
1097
1128
  // ---------- 权限审批转发:成员 preset 触发 approval/request → Lead 用 team_approve 决定 ----------
1098
1129
  const pendingApprovals = new Map();
1099
1130
 
1131
+ // 审批分类:approval/request 只带 toolName 与 callId,不带命令参数;
1132
+ // 在 tools/pre-execute 里按 callId 记住成员这一轮的入参,供低风险命令自动放行判定。
1133
+ const preExecuteArgs = new Map();
1134
+ const PRE_EXECUTE_TTL_MS = 5 * 60 * 1000;
1135
+ const PRE_EXECUTE_MAX = 500;
1136
+ const SHELL_TOOL_RE = /(^|[._-])(bash|shell|exec|command|powershell|pwsh|zsh|sh)($|[._-])/i;
1137
+ // 只有这些程序出现在命令首位才考虑自动放行;不在表里的(rm、curl、ssh、脚本解释执行等)仍转 Lead。
1138
+ const SAFE_COMMAND_PROGRAMS = new Set([
1139
+ 'node', 'npm', 'npx', 'pnpm', 'yarn', 'bun', 'deno', 'tsc', 'vitest', 'jest', 'mocha', 'eslint', 'prettier', 'biome',
1140
+ 'python', 'python3', 'py', 'pytest', 'uv', 'pip', 'pip3',
1141
+ 'cargo', 'rustc', 'go', 'dotnet', 'javac', 'java', 'mvn', 'gradle',
1142
+ 'ls', 'dir', 'cat', 'type', 'head', 'tail', 'rg', 'grep', 'find', 'fd', 'where', 'which',
1143
+ 'git', 'echo', 'cd', 'pwd', 'mkdir', 'touch',
1144
+ ]);
1145
+ // 解释器带 -e/-c 等价于任意代码执行,不自动放行。
1146
+ const INTERPRETER_PROGRAMS = new Set(['node', 'python', 'python3', 'py', 'deno', 'bun']);
1147
+ const DEFAULT_SENSITIVE_COMMAND_PATTERNS = new RegExp([
1148
+ String.raw`\brm\s+-[a-z]*[rf]`,
1149
+ String.raw`\bremove-item\b[^\n]*-(recurse|force)`,
1150
+ String.raw`\bdel\s+/[sfq]`,
1151
+ String.raw`\bformat\s+[a-z]:`,
1152
+ String.raw`\bmkfs\b`,
1153
+ String.raw`\bdiskpart\b`,
1154
+ String.raw`\bgit\s+push\b[^\n]*(--force|-f\b)`,
1155
+ String.raw`\bgit\s+reset\s+--hard\b`,
1156
+ String.raw`\bgit\s+clean\s+-[a-z]*f`,
1157
+ String.raw`\b(npm|pnpm|yarn)\s+publish\b`,
1158
+ String.raw`\b(curl|wget)\b[^\n|]*\|\s*(ba|z)?sh\b`,
1159
+ String.raw`\b(iex|invoke-expression)\b`,
1160
+ String.raw`\b(sudo|runas)\b`,
1161
+ String.raw`\breg\s+(add|delete)\b`,
1162
+ String.raw`\bsc\s+delete\b`,
1163
+ String.raw`\bnet\s+user\b`,
1164
+ String.raw`\b(icacls|takeown|bcdedit)\b`,
1165
+ String.raw`\b(shutdown|reboot|taskkill)\b`,
1166
+ String.raw`\bchmod\s+777\b`,
1167
+ String.raw`[\\/]\.ssh[\\/]id_`,
1168
+ String.raw`(^|[\\/\s])\.env\b`,
1169
+ String.raw`[\\/]\.aws[\\/]`,
1170
+ String.raw`[\\/]\.npmrc\b`,
1171
+ String.raw`[\\/]\.netrc\b`,
1172
+ ].join('|'), 'i');
1173
+
1174
+ function rememberPreExecuteArgs(exec) {
1175
+ const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
1176
+ const callId = exec?.callId != null ? String(exec.callId) : null;
1177
+ if (!sessionId || !callId || !sessionMember.has(sessionId)) return;
1178
+ preExecuteArgs.set(`${sessionId}:${callId}`, {
1179
+ name: String(exec.name || ''),
1180
+ args: exec.arguments && typeof exec.arguments === 'object' ? exec.arguments : {},
1181
+ at: Date.now(),
1182
+ });
1183
+ while (preExecuteArgs.size > PRE_EXECUTE_MAX) {
1184
+ const oldest = preExecuteArgs.keys().next().value;
1185
+ if (oldest == null) break;
1186
+ preExecuteArgs.delete(oldest);
1187
+ }
1188
+ }
1189
+
1190
+ function cachedPreExecuteArgs(sessionId, callId) {
1191
+ const key = `${sessionId}:${callId}`;
1192
+ const hit = preExecuteArgs.get(key);
1193
+ if (!hit) return null;
1194
+ if (Date.now() - hit.at > PRE_EXECUTE_TTL_MS) {
1195
+ preExecuteArgs.delete(key);
1196
+ return null;
1197
+ }
1198
+ return hit;
1199
+ }
1200
+
1201
+ /**
1202
+ * 低风险命令判定:白名单程序 + 禁止管道/重定向/命令替换 + 敏感规则。
1203
+ * 这是启发式而非完整 shell 解析——宁可漏放行(转 Lead),也不误放行。
1204
+ */
1205
+ function isLowRiskCommand(command, extraPatterns = []) {
1206
+ const text = String(command || '').trim();
1207
+ if (!text || text.length > 2000) return false;
1208
+ if (/[|<>`]|\$\(|\n|\r/.test(text)) return false;
1209
+ if (DEFAULT_SENSITIVE_COMMAND_PATTERNS.test(text)) return false;
1210
+ for (const pattern of extraPatterns) {
1211
+ try { if (new RegExp(pattern, 'i').test(text)) return false; } catch { /* 非法正则忽略 */ }
1212
+ }
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;
1220
+ }
1221
+ return true;
1222
+ }
1223
+
1100
1224
  function settleApproval(s, requestId, decision, reason, decidedBy) {
1101
1225
  const entry = pendingApprovals.get(requestId);
1102
1226
  if (!entry) return null;
@@ -1171,6 +1295,27 @@ async function onApprovalRequest(s, ctx, req, next) {
1171
1295
  // 同一个请求重复进入(理论上不会)直接拒绝,避免两个 waiter 争同一个 id。
1172
1296
  if (pendingApprovals.has(requestId)) return 'rejected';
1173
1297
 
1298
+ // 低风险命令自动放行:审批噪声主要来自成员跑 npm/node/git 这类命令时的沙箱升级。
1299
+ // 必须同时满足「工具名像 shell」「参数里带 command」「命令通过白名单校验」才放行。
1300
+ const cached = sessionId && req?.callId != null ? cachedPreExecuteArgs(sessionId, String(req.callId)) : null;
1301
+ if (s.autoApproveLowRisk && cached) {
1302
+ const toolName = String(cached.name || info.toolName || '');
1303
+ const command = cached.args?.command;
1304
+ 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';
1316
+ }
1317
+ }
1318
+
1174
1319
  // 先镜像到 sidecar,面板/报告可见;失败不影响审批。
1175
1320
  void request(s, '/api/approvals', {
1176
1321
  method: 'POST',
@@ -1273,6 +1418,9 @@ function forgetSession(sessionId) {
1273
1418
  heldSessions.delete(sid);
1274
1419
  agentStatusBySession.delete(sid);
1275
1420
  sessionMember.delete(sid);
1421
+ for (const key of [...preExecuteArgs.keys()]) {
1422
+ if (key.startsWith(`${sid}:`)) preExecuteArgs.delete(key);
1423
+ }
1276
1424
  }
1277
1425
 
1278
1426
  /**
@@ -2767,7 +2915,7 @@ function buildTools(s, ctx) {
2767
2915
 
2768
2916
  tools.push({
2769
2917
  name: 'team_member',
2770
- description: "Update or remove a team member. `update` changes role/permission/model/context and, when model, agentProvider, contextMode, agentPreset or reasoningEffort changes, rebuilds the member's DSH sub-agent session so the new config takes effect (old context is lost). The member must be idle or interrupted; interrupt a running member first. `retire` keeps the member row as retired and frees capacity; `remove` deletes the row and requires confirm:true. Both release the sub-agent session.",
2918
+ description: "Update or remove a team member. `update` changes role/permission/model/context. `permissionPreset` (and `role`) applies to a RUNNING member immediately, no interrupt needed; changing model, agentProvider, contextMode, agentPreset or reasoningEffort rebuilds the member's DSH sub-agent session (old context is lost) and therefore requires the member to be idle or interrupted. `retire` keeps the member row as retired and frees capacity; `remove` deletes the row and requires confirm:true. Both release the sub-agent session.",
2771
2919
  parameters: {
2772
2920
  type: 'object',
2773
2921
  additionalProperties: false,
@@ -2814,9 +2962,6 @@ function buildTools(s, ctx) {
2814
2962
 
2815
2963
  if (args.action !== 'update') throw new Error(`team_member unknown action: ${args.action}`);
2816
2964
  if (current.status === 'retired') throw new Error('member is retired; create a new member instead');
2817
- if (['running', 'provisioning', 'blocked'].includes(current.status)) {
2818
- throw new Error(`member is ${current.status}; interrupt it before updating configuration`);
2819
- }
2820
2965
 
2821
2966
  const has = (key) => Object.prototype.hasOwnProperty.call(args, key);
2822
2967
  const metadata = {};
@@ -2824,12 +2969,20 @@ function buildTools(s, ctx) {
2824
2969
  if (has(key)) metadata[key] = args[key];
2825
2970
  }
2826
2971
  const restart = ['model', 'agentProvider', 'contextMode', 'agentPreset', 'reasoningEffort'].some(has);
2972
+ // 运行中的成员只允许热改 role / permissionPreset(DSH 预设支持对 live session 直接 set);
2973
+ // 换模型/上下文/组合需要重建会话,仍要求先 interrupt。
2974
+ if (['running', 'provisioning', 'blocked'].includes(current.status) && restart) {
2975
+ throw new Error(`member is ${current.status}; interrupt it before changing model/provider/context/agentPreset. role and permissionPreset can be updated while it runs`);
2976
+ }
2827
2977
 
2828
2978
  if (!restart) {
2829
2979
  const updated = await request(s, `/api/members/${id}`, { method: 'PATCH', body: metadata });
2830
2980
  let presetApplied = null;
2831
2981
  if (has('permissionPreset') && updated.agentSessionId) {
2832
2982
  presetApplied = applyPermissionPreset(ctx, String(updated.agentSessionId), updated.permissionPreset);
2983
+ // 热更新后同步插件侧绑定,后续审批通知/分类按新预设走。
2984
+ const live = sessionMember.get(String(updated.agentSessionId));
2985
+ if (live) live.permissionPreset = updated.permissionPreset ?? null;
2833
2986
  }
2834
2987
  return {
2835
2988
  member: updated,
@@ -3376,6 +3529,15 @@ export function apply(ctx, config) {
3376
3529
  });
3377
3530
  }
3378
3531
 
3532
+ // 审批分类需要工具参数,但 approval/request 只带 toolName/callId:
3533
+ // 在 pre-execute 里按 callId 缓存成员这一轮的入参(只记成员,带 TTL),供低风险命令自动放行判定。
3534
+ if (s.autoApproveLowRisk) {
3535
+ ctx.on('tools/pre-execute', (exec, next) => {
3536
+ try { rememberPreExecuteArgs(exec); } catch { /* ignore */ }
3537
+ return typeof next === 'function' ? next() : undefined;
3538
+ });
3539
+ }
3540
+
3379
3541
  // 成员权限审批:preset 的 approval=ask 触发时,把请求转给 Lead,由 team_approve 决定。
3380
3542
  // 放在最前面(prepend),确保本插件的成员请求不会再弹出宿主审批 UI。
3381
3543
  ctx.effect(() => {
@@ -3588,11 +3750,13 @@ export function apply(ctx, config) {
3588
3750
  }
3589
3751
 
3590
3752
  // 看板会话的后续用户消息:done/failed 被追问时翻回 inprogress(sidecar 只对这些状态生效)。
3591
- // 自己注入的首条 prompt 也会触发,但此时状态是 planning/inprogress,sidecar 会拒绝,不会误翻。
3753
+ // 规划阶段例外:任务可能已被 idle 宽限判 failed,此时翻 inprogress 会让提交计划只认 planning
3754
+ // 的状态机报 404;保持原状,由 submitPlan 按 planning_session_id 复活。
3592
3755
  ctx.on('session/event', (session, event) => {
3593
3756
  const sessionId = session?.id != null ? String(session.id) : null;
3594
3757
  if (!sessionId || !boardSessionIds.has(sessionId)) return;
3595
3758
  if (!event || event.type !== 'user/message') return;
3759
+ if (boardSessions.get(sessionId)?.phase === 'planning') return;
3596
3760
  void request(s, '/api/board/agents/status', {
3597
3761
  method: 'POST', body: { sessionId, status: 'inprogress' },
3598
3762
  }).catch(() => { /* 非终态时 sidecar 会拒绝,忽略 */ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-team-control",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
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",