dsh-team-control 0.1.5 → 0.1.7

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 (4) hide show
  1. package/README.md +55 -53
  2. package/index.js +1632 -182
  3. package/locale/zh.json +1 -1
  4. package/package.json +2 -2
package/index.js CHANGED
@@ -44,6 +44,8 @@ function resolveConfig(config) {
44
44
  baseUrl,
45
45
  port,
46
46
  home: path.resolve(c.home || process.env.DSH_TEAM_HOME || path.join(os.homedir(), '.dsh', 'team')),
47
+ // Leader 自建 agentPreset 的固定目录:JSON 文档(JSON 是合法 YAML),插件启动时注册进宿主
48
+ presetDir: path.resolve(c.presetDir || process.env.DSH_TEAM_PRESET_DIR || path.join(os.homedir(), '.dsh', 'team', 'presets')),
47
49
  autoStart: c.autoStart !== false,
48
50
  entry: path.resolve(c.sidecarEntry || DEFAULT_ENTRY),
49
51
  startTimeoutMs: Number(c.startTimeoutMs) || 20000,
@@ -69,6 +71,8 @@ function resolveConfig(config) {
69
71
  // agent 运行时:成员在 sidecar 认领任务后,由本插件用 subagents.sendMessage 派发
70
72
  agentAutoDispatch: c.agentAutoDispatch !== false,
71
73
  agentDispatchMs: Number(c.agentDispatchMs) || 1500,
74
+ // 面板 steer 队列的投递泵间隔(面板排队消息 → 成员会话)
75
+ steerPollMs: Number(c.steerPollMs) || 1200,
72
76
  agentDispatchMax: Number(c.agentDispatchMax) || 16,
73
77
  // sidecar 建任务后留 200ms 的「声明依赖」窗口,派发前先等过这段时间
74
78
  agentSettleMs: Number(c.agentSettleMs) || 250,
@@ -76,11 +80,21 @@ function resolveConfig(config) {
76
80
  agentIdleSettleMs: c.agentIdleSettleMs == null ? 12000 : Math.max(0, Number(c.agentIdleSettleMs) || 0),
77
81
  // 成员状态心跳:本地认为在跑、sidecar 却回落到 idle 时补报 running(任务仍在跑说明回合没结束)
78
82
  agentHeartbeatMs: Number(c.agentHeartbeatMs) || 15000,
83
+ // 面板/看板停止后轮询 sidecar:发现成员被置 interrupted 就真正 subagents.interrupt
84
+ forceStopPollMs: Number(c.forceStopPollMs) || 1000,
79
85
  // 任务投递后成员会话迟迟没有任何事件(模型路由报错、会话没启动)就判定失败并交回 sidecar 重试
80
86
  agentStartTimeoutMs: Number(c.agentStartTimeoutMs) || 120000,
87
+ // 成员触发权限审批(permission preset 的 approval=ask)后,等待 Lead 调 team_approve 的上限
88
+ approvalTimeoutMs: Number(c.approvalTimeoutMs) || 600000,
81
89
  // spawnTeammate 的 provider:默认与 dsh-experimental-tool-agent-team 一致
82
90
  freshProvider: String(c.freshProvider || 'spawn'),
83
91
  forkProvider: String(c.forkProvider || 'fork'),
92
+ // 工作区看板:Host 侧调度器(claim → 建会话 → 投 prompt)。
93
+ // 默认开启;只有 auto=1 或用户点「开始执行」的任务才会入队,显式 false 可关闭。
94
+ boardEnabled: c.boardEnabled !== false,
95
+ boardDispatchMs: Number(c.boardDispatchMs) || 2000,
96
+ boardIdleGraceMs: c.boardIdleGraceMs == null ? 6000 : Math.max(0, Number(c.boardIdleGraceMs) || 0),
97
+ boardPlanningTimeoutMs: Number(c.boardPlanningTimeoutMs) || 30 * 60 * 1000,
84
98
  };
85
99
  }
86
100
 
@@ -153,7 +167,9 @@ async function request(s, pathname, { method = 'GET', body, raw = false } = {})
153
167
  if (!res.ok) {
154
168
  let detail = text.slice(0, 400);
155
169
  try { const j = JSON.parse(text); detail = `${j.error?.code || ''} ${j.error?.message || ''}`.trim() || detail; } catch { /* keep text */ }
156
- throw new Error(`dsh-team API ${res.status} on ${method} ${pathname}: ${detail}`);
170
+ const err = new Error(`dsh-team API ${res.status} on ${method} ${pathname}: ${detail}`);
171
+ err.status = res.status; // 调用方据此区分「团队不存在(404)」与服务/网络侧故障
172
+ throw err;
157
173
  }
158
174
  if (raw) return text;
159
175
  try { return JSON.parse(text); } catch { return text; }
@@ -182,7 +198,7 @@ const qs = (obj) => {
182
198
  /** teamId → 最近一次调用 team_* 工具的 Lead Agent(发消息必须由 live Lead 发出)。 */
183
199
  const leadByTeam = new Map();
184
200
  /** teamId → 'worker' | 'agent',建团/查团缓存,省掉每次多一次 GET。 */
185
- const runtimeByTeam = new Map();
201
+ const teamCache = new Map();
186
202
  /** DSH sessionId → { teamId, memberId }:把成员的工具 span 归到成员节点下。 */
187
203
  const sessionMember = new Map();
188
204
  /** DSH sessionId → 上次采集产物时的会话 seq:成员复用同一会话时只上报新产生的文件。 */
@@ -529,6 +545,56 @@ const llmOf = (ctx) => { try { return ctx.get('llm'); } catch { return undefined
529
545
 
530
546
  let llmSyncInFlight = null;
531
547
 
548
+ /**
549
+ * 一条 route 的思考强度元数据(适配器声明):数组 = 已知(可能为空),undefined = 取不到。
550
+ * resolveModel 对 pi-ai 是内存目录查询;对其他适配器可能触网,所以并发受限 + 超时兜底,
551
+ * 取不到就不上报(sidecar 保留上一次的值),不让 effort 能力拖垮整个目录同步。
552
+ */
553
+ async function effortsOfRoute(llm, provider, model) {
554
+ // llm 服务暴露的是 resolveModelInfo(带校验的精确模型元数据);resolveModel 是适配器基类方法,
555
+ // 部分环境/旧版本才直接挂在服务上。两个都试,优先服务公开面。
556
+ const resolve = typeof llm.resolveModelInfo === 'function'
557
+ ? (p, m, signal) => llm.resolveModelInfo(p, m, signal)
558
+ : typeof llm.resolveModel === 'function'
559
+ ? (p, m, signal) => llm.resolveModel(p, m, signal)
560
+ : null;
561
+ if (!resolve) return undefined;
562
+ const call = Promise.resolve()
563
+ .then(() => resolve(provider, model, AbortSignal.timeout(3000)))
564
+ .catch(() => undefined);
565
+ const info = await Promise.race([
566
+ call,
567
+ new Promise((resolve) => setTimeout(() => resolve(undefined), 3000)),
568
+ ]);
569
+ const reasoning = info && info.reasoning;
570
+ if (!reasoning || !Array.isArray(reasoning.efforts)) return undefined;
571
+ // 「off」等于关思考,不是可派发的强度:既不进面板胶囊,也不进 team_models,
572
+ // 否则用户能「允许派发 off」而实际语义相反。
573
+ const efforts = reasoning.efforts
574
+ .filter((e) => e && e.id && String(e.id) !== 'off')
575
+ .map((e) => ({ id: String(e.id), name: String(e.name || e.id), ...(e.description ? { description: String(e.description) } : {}) }));
576
+ if (!efforts.length) return undefined;
577
+ const defaultEffort = reasoning.defaultEffort ? String(reasoning.defaultEffort) : null;
578
+ return {
579
+ efforts,
580
+ defaultEffort: defaultEffort && defaultEffort !== 'off' && efforts.some((e) => e.id === defaultEffort) ? defaultEffort : null,
581
+ };
582
+ }
583
+
584
+ /** 小并发 map:effort 解析最多同时 4 条,避免一次同步打爆适配器。 */
585
+ async function mapLimit(items, limit, fn) {
586
+ const out = new Array(items.length);
587
+ let next = 0;
588
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
589
+ while (next < items.length) {
590
+ const i = next++;
591
+ out[i] = await fn(items[i], i);
592
+ }
593
+ });
594
+ await Promise.all(workers);
595
+ return out;
596
+ }
597
+
532
598
  /** 同步一次模型目录(并发去重;由插件启动泵与 adapters-updated 事件驱动,不再由工具触发)。 */
533
599
  async function syncLlmCatalog(s, ctx) {
534
600
  const llm = llmOf(ctx);
@@ -548,13 +614,17 @@ async function syncLlmCatalog(s, ctx) {
548
614
  let partial = false;
549
615
  for (const p of providers) {
550
616
  try {
551
- for (const m of await llm.listModels(p.id)) {
552
- if (!m || !m.id) continue;
553
- models.push({
617
+ const listed = await llm.listModels(p.id);
618
+ const withEfforts = await mapLimit(listed, 4, async (m) => {
619
+ if (!m || !m.id) return null;
620
+ const meta = await effortsOfRoute(llm, p.id, String(m.id));
621
+ return {
554
622
  provider: p.id, model: String(m.id), name: m.name || String(m.id),
555
623
  description: m.description || null, modalities: m.inputModalities || null,
556
- });
557
- }
624
+ ...(meta ? { efforts: meta.efforts, ...(meta.defaultEffort ? { defaultEffort: meta.defaultEffort } : {}) } : {}),
625
+ };
626
+ });
627
+ for (const row of withEfforts) if (row) models.push(row);
558
628
  } catch (e) {
559
629
  // 单个提供商读取失败:标记 partial,让 sidecar 保留该 provider 已有的勾选
560
630
  p.error = clip(String(e?.message || e), 300);
@@ -581,8 +651,8 @@ function leadRouteOf(caller) {
581
651
  return { provider: o.provider ?? null, model: o.model ?? null, reasoningEffort: o.reasoningEffort ?? null };
582
652
  }
583
653
 
584
- /** 指定 route 必须在用户启用的子集里;目录尚未同步(为空)时不限制,保持向后兼容。 */
585
- async function assertRouteEnabled(s, ctx, provider, model) {
654
+ /** 指定 route 必须在用户启用的子集里,且 effort 在该 route 允许的集合里;目录尚未同步(为空)时不限制。 */
655
+ async function assertRouteEnabled(s, ctx, provider, model, effort = null) {
586
656
  if (!provider && !model) return;
587
657
  let cat;
588
658
  try { cat = await request(s, '/api/llm/catalog'); } catch { return; }
@@ -594,28 +664,327 @@ async function assertRouteEnabled(s, ctx, provider, model) {
594
664
  if (!known.length) return;
595
665
  const enabled = all.filter((m) => m.enabled);
596
666
  if (!enabled.length) throw new Error('所有模型路由都已停用:请先在面板「模型路由」页启用,或调用 team_models 查看。');
597
- if (known.some((m) => m.enabled)) return;
598
- const sample = enabled.slice(0, 8).map((m) => `${m.provider}/${m.model}`).join(', ');
599
- throw new Error(`模型路由未启用:${[provider, model].filter(Boolean).join('/')}。可用(前 8 条):${sample}。完整列表见 team_models,或在面板「模型路由」页启用。`);
667
+ if (!known.some((m) => m.enabled)) {
668
+ const sample = enabled.slice(0, 8).map((m) => `${m.provider}/${m.model}`).join(', ');
669
+ throw new Error(`模型路由未启用:${[provider, model].filter(Boolean).join('/')}。可用(前 8 条):${sample}。完整列表见 team_models,或在面板「模型路由」页启用。`);
670
+ }
671
+ // effort 闸门:只有该 route 声明了 efforts 才校验;allowedEfforts=null 表示全部允许。
672
+ if (!effort) return;
673
+ const declared = known.filter((m) => Array.isArray(m.efforts) && m.efforts.length > 0);
674
+ if (!declared.length) return;
675
+ const ids = [...new Set(declared.flatMap((m) => m.efforts.map((e) => e.id)))];
676
+ const allowed = [...new Set(declared.flatMap((m) => (Array.isArray(m.allowedEfforts) ? m.allowedEfforts : ids)))];
677
+ if (!ids.includes(String(effort))) {
678
+ throw new Error(`模型路由 ${[provider, model].filter(Boolean).join('/')} 不支持 reasoningEffort「${effort}」:可用 ${ids.join(', ')}。`);
679
+ }
680
+ if (!allowed.includes(String(effort))) {
681
+ throw new Error(`模型路由 ${[provider, model].filter(Boolean).join('/')} 已禁止 reasoningEffort「${effort}」:面板「模型路由」页允许的为 ${allowed.join(', ') || '(无,省略该参数使用模型默认)'}。`);
682
+ }
600
683
  }
601
684
 
602
- function rememberMember(sessionId, teamId, memberId, cwd) {
685
+ function rememberMember(sessionId, teamId, memberId, cwd, permissionPreset = null, name = null) {
603
686
  if (sessionId == null) return;
604
687
  const key = String(sessionId);
605
688
  const prev = sessionMember.get(key);
606
689
  // 会话 cwd 只有 spawn 时知道(= team.workspace);派发路径会重复登记同一个会话,
607
690
  // 这里不能把它冲成空,否则成员用相对路径写文件时 diff 找不到落盘位置。
608
- sessionMember.set(key, { teamId: String(teamId), memberId: String(memberId), cwd: cwd || prev?.cwd || '' });
691
+ sessionMember.set(key, {
692
+ teamId: String(teamId),
693
+ memberId: String(memberId),
694
+ cwd: cwd || prev?.cwd || '',
695
+ permissionPreset: permissionPreset || prev?.permissionPreset || null,
696
+ name: name || prev?.name || null,
697
+ });
698
+ }
699
+
700
+ async function teamOf(s, teamId, { refresh = false, sessionId = null } = {}) {
701
+ // 模型偶尔会漏掉必填的 teamId。先显式挡住,避免 /api/teams/undefined 被误报成「团队不存在」;
702
+ // 同一会话内 team_create 过的团队可以直接兜底(DSH 对直接注册的工具不做 required 运行时校验)。
703
+ const missing = teamId == null || String(teamId).trim() === '' || String(teamId) === 'undefined' || String(teamId) === 'null';
704
+ if (missing && sessionId) {
705
+ const bound = sessionMember.get(String(sessionId))?.teamId || teamBySession.get(String(sessionId));
706
+ if (bound) teamId = bound;
707
+ }
708
+ if (teamId == null || String(teamId).trim() === '' || String(teamId) === 'undefined' || String(teamId) === 'null') {
709
+ throw new Error('缺少 teamId:请把 team_create 返回的 result.team.id(形如 team_xxx)作为 teamId 参数传入后重试。');
710
+ }
711
+ const key = String(teamId);
712
+ if (!refresh && teamCache.has(key)) return teamCache.get(key);
713
+ try {
714
+ const team = await request(s, `/api/teams/${encodeURIComponent(key)}`);
715
+ teamCache.set(key, team);
716
+ return team;
717
+ } catch (err) {
718
+ if (err && err.status === 404) {
719
+ throw new Error(`团队不存在或 teamId 无效: ${key}(teamId 来自 team_create 返回值,请核对后重试)`);
720
+ }
721
+ throw err;
722
+ }
723
+ }
724
+
725
+ const permissionPresetsOf = (ctx) => {
726
+ try { return ctx.get('permissionPresets'); } catch { return undefined; }
727
+ };
728
+
729
+ const agentPresetsOf = (ctx) => {
730
+ try { return ctx.get('agentPresets'); } catch { return undefined; }
731
+ };
732
+
733
+ /** 解析并校验 agentPreset(组合预设:工具/skill/MCP/系统提示词)。空 = 不指定(调用方需用宿主默认兜底)。 */
734
+ async function resolveAgentPreset(ctx, requested, fallback, store = null) {
735
+ if (store) await ensureTeamPresets(store, ctx).catch(() => null);
736
+ const preset = String(requested ?? fallback ?? '').trim();
737
+ if (!preset) return null;
738
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(preset)) {
739
+ throw new Error(`agentPreset 名称非法:「${preset}」`);
740
+ }
741
+ const svc = agentPresetsOf(ctx);
742
+ if (!svc || typeof svc.list !== 'function') return preset;
743
+ let rows = null;
744
+ try { rows = await svc.list(); } catch { rows = null; }
745
+ const ids = Array.isArray(rows) ? rows.map((r) => r && r.id).filter(Boolean) : [];
746
+ if (ids.length && !ids.includes(preset)) {
747
+ throw new Error(`agentPreset「${preset}」不存在;可用预设:${ids.join(', ')}`);
748
+ }
749
+ return preset;
750
+ }
751
+
752
+ /**
753
+ * 宿主默认 agentPreset 的 id。
754
+ *
755
+ * DSH 的 subagent 在 request 里省略 agentPreset 时,会继承父会话的实时组合
756
+ * (`composeFrom(parent)`),并不会自动套用宿主默认。因此 team_spawn 必须显式
757
+ * 把默认预设传下去,否则成员就只能拿到 Lead 根组合里的宿主级工具(比如没有 shell)。
758
+ */
759
+ async function hostDefaultAgentPreset(ctx) {
760
+ const svc = agentPresetsOf(ctx);
761
+ if (!svc) return null;
762
+ let id = '';
763
+ try {
764
+ if (typeof svc.defaultId === 'string') id = svc.defaultId.trim();
765
+ } catch { id = ''; }
766
+ if (!id && typeof svc.resolve === 'function') {
767
+ try {
768
+ const row = await svc.resolve(undefined);
769
+ if (row && row.id != null && row.broken === undefined) id = String(row.id).trim();
770
+ } catch { id = ''; }
771
+ }
772
+ return id || null;
609
773
  }
610
774
 
611
- async function runtimeOfTeam(s, teamId) {
612
- const cached = runtimeByTeam.get(teamId);
613
- if (cached) return cached;
775
+ // ---------------------------------------------------------------------------
776
+ // Leader 自建 agentPreset
777
+ //
778
+ // 内置 preset 不满足时,Lead 用 team_preset({action:'save'}) 把一份组合定义写到固定目录,
779
+ // 并立刻调用宿主 `agentPresets.register()` 生效(无需重启 DSH)。目录里的 JSON 文档
780
+ // (JSON 是合法 YAML)在插件启动时也会被重新注册,因此跨会话可复用。
781
+ // ---------------------------------------------------------------------------
782
+ const PRESET_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
783
+ const teamPresetDisposers = new Map();
784
+ let teamPresetsReady = null;
785
+ let teamPresetLoading = null;
786
+
787
+ function presetFiles(dir) {
614
788
  try {
615
- const team = await request(s, `/api/teams/${encodeURIComponent(teamId)}`);
616
- runtimeByTeam.set(teamId, team.runtime || 'worker');
617
- return team.runtime || 'worker';
618
- } catch { return 'worker'; }
789
+ return fs.readdirSync(dir).filter((f) => f.endsWith('.json')).sort();
790
+ } catch {
791
+ return [];
792
+ }
793
+ }
794
+
795
+ /** 读目录里全部 preset 文档;坏文件只记诊断,不阻塞其他文件。 */
796
+ function readTeamPresetFiles(dir) {
797
+ const docs = [];
798
+ const errors = [];
799
+ for (const file of presetFiles(dir)) {
800
+ const full = path.join(dir, file);
801
+ try {
802
+ const doc = JSON.parse(fs.readFileSync(full, 'utf8'));
803
+ if (!doc || typeof doc !== 'object') throw new Error('不是对象');
804
+ if (!PRESET_ID_RE.test(String(doc.id || ''))) throw new Error('id 非法');
805
+ if (!Array.isArray(doc.plugins) || doc.plugins.length === 0) throw new Error('plugins 必须是非空数组');
806
+ docs.push({ doc, file: full });
807
+ } catch (err) {
808
+ errors.push({ file: full, error: String(err?.message || err) });
809
+ }
810
+ }
811
+ return { docs, errors };
812
+ }
813
+
814
+ /** 启动时把目录里的 preset 注册进宿主;幂等,重复调用复用同一个 Promise。 */
815
+ function ensureTeamPresets(s, ctx) {
816
+ if (teamPresetsReady) return teamPresetsReady;
817
+ if (teamPresetLoading) return teamPresetLoading;
818
+ const serviceAvailable = () => {
819
+ const svc = ctx.get('agentPresets');
820
+ return !!(svc && typeof svc.register === 'function');
821
+ };
822
+ teamPresetLoading = (async () => {
823
+ const svc = ctx.get('agentPresets');
824
+ const result = { dir: s.presetDir, registered: [], skipped: [], errors: [] };
825
+ if (!svc || typeof svc.register !== 'function') {
826
+ result.errors.push({ file: s.presetDir, error: 'agentPresets 服务不可用(宿主未启用 agent-preset-registry)' });
827
+ return result;
828
+ }
829
+ const { docs, errors } = readTeamPresetFiles(s.presetDir);
830
+ result.errors.push(...errors);
831
+ let known = new Set();
832
+ try { known = new Set((await svc.list()).map((r) => r && r.id).filter(Boolean)); } catch { /* list 不可用就按空处理 */ }
833
+ for (const { doc, file } of docs) {
834
+ try {
835
+ if (known.has(doc.id)) { result.skipped.push({ id: doc.id, file, reason: '同名预设已由宿主定义' }); continue; }
836
+ const dispose = await svc.register(doc);
837
+ teamPresetDisposers.set(doc.id, dispose);
838
+ known.add(doc.id);
839
+ result.registered.push({ id: doc.id, file });
840
+ } catch (err) {
841
+ result.errors.push({ file, error: String(err?.message || err) });
842
+ }
843
+ }
844
+ return result;
845
+ })().finally(() => {
846
+ // 服务暂时不可用时不缓存失败,下次调用(例如宿主稍后启用 registry)再重试。
847
+ if (serviceAvailable()) teamPresetsReady = teamPresetLoading;
848
+ teamPresetLoading = null;
849
+ });
850
+ return teamPresetLoading;
851
+ }
852
+
853
+ /** 保存一个 preset 文档并立刻注册;同名的自建 preset 可覆盖,宿主内置的同名 preset 不允许覆盖。 */
854
+ async function saveTeamPreset(s, ctx, input) {
855
+ const id = String(input?.id || '').trim();
856
+ if (!PRESET_ID_RE.test(id)) throw new Error(`agentPreset 名称非法:「${id}」`);
857
+ if (!Array.isArray(input?.plugins) || input.plugins.length === 0) {
858
+ throw new Error('plugins 必须是非空数组,每项形如 { name, config?, id?, disabled? }');
859
+ }
860
+ const doc = { id };
861
+ if (input.name) doc.name = String(input.name);
862
+ if (input.description) doc.description = String(input.description);
863
+ if (Number.isFinite(Number(input.order))) doc.order = Number(input.order);
864
+ doc.plugins = input.plugins;
865
+ const file = path.join(s.presetDir, `${id}.json`);
866
+ if (fs.existsSync(file) && !input?.confirm) {
867
+ throw new Error(`团队预设「${id}」已存在;覆盖请传 confirm:true(内置预设始终不可覆盖)`);
868
+ }
869
+ const svc = ctx.get('agentPresets');
870
+ if (!svc || typeof svc.register !== 'function') {
871
+ fs.mkdirSync(s.presetDir, { recursive: true });
872
+ fs.writeFileSync(file, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
873
+ return { id, file, registered: false, warning: 'agentPresets 服务不可用:文件已保存,宿主启用该服务后会加载' };
874
+ }
875
+ let existing = null;
876
+ let hostIds = [];
877
+ try {
878
+ const rows = await svc.list();
879
+ hostIds = rows.map((r) => r && r.id).filter(Boolean);
880
+ existing = rows.find((r) => r && r.id === id) || null;
881
+ } catch { existing = null; }
882
+ if (existing && !teamPresetDisposers.has(id)) {
883
+ throw new Error(`agentPreset「${id}」已由宿主定义,换一个 id(内置预设:${hostIds.join(', ')})`);
884
+ }
885
+ fs.mkdirSync(s.presetDir, { recursive: true });
886
+ fs.writeFileSync(file, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
887
+ if (teamPresetDisposers.has(id)) {
888
+ const dispose = teamPresetDisposers.get(id);
889
+ teamPresetDisposers.delete(id);
890
+ try { await dispose(); } catch { /* 旧定义已失效就继续注册新定义 */ }
891
+ }
892
+ const dispose = await svc.register(doc);
893
+ teamPresetDisposers.set(id, dispose);
894
+ const row = (await svc.list().catch(() => [])).find((r) => r && r.id === id) || null;
895
+ return { id, file, registered: true, ...(row?.broken ? { broken: row.broken } : {}) };
896
+ }
897
+
898
+ /** 列出宿主 preset + 目录里的自建 preset(含未成功注册/解析失败的文件)。 */
899
+ async function listTeamPresets(s, ctx) {
900
+ await ensureTeamPresets(s, ctx).catch(() => null);
901
+ const { docs, errors } = readTeamPresetFiles(s.presetDir);
902
+ const fileById = new Map(docs.map(({ doc, file }) => [doc.id, file]));
903
+ const svc = ctx.get('agentPresets');
904
+ let rows = [];
905
+ try { rows = await svc?.list?.() || []; } catch { rows = []; }
906
+ const presets = rows.map((r) => ({
907
+ id: r.id,
908
+ ...(r.name ? { name: r.name } : {}),
909
+ ...(r.description ? { description: r.description } : {}),
910
+ ...(r.order !== undefined ? { order: r.order } : {}),
911
+ ...(r.broken ? { broken: r.broken } : {}),
912
+ source: fileById.has(r.id) ? 'team' : 'host',
913
+ ...(fileById.has(r.id) ? { file: fileById.get(r.id) } : {}),
914
+ }));
915
+ for (const { doc, file } of docs) {
916
+ if (!presets.some((p) => p.id === doc.id)) {
917
+ presets.push({ id: doc.id, ...(doc.name ? { name: doc.name } : {}), source: 'team', file, registered: false });
918
+ }
919
+ }
920
+ return { dir: s.presetDir, presets, errors };
921
+ }
922
+
923
+ /** 把目录镜像同步给 sidecar,供面板浏览(尽力而为,失败不影响主流程)。 */
924
+ async function syncPresetCatalog(s, ctx) {
925
+ try {
926
+ const catalog = await listTeamPresets(s, ctx);
927
+ const { docs } = readTeamPresetFiles(s.presetDir);
928
+ const docById = new Map(docs.map(({ doc }) => [doc.id, doc]));
929
+ const presets = catalog.presets.map(({ registered, ...row }) => ({ ...row, ...(docById.has(row.id) ? { doc: docById.get(row.id) } : {}) }));
930
+ await request(s, '/api/presets/sync', { method: 'POST', body: { presets } });
931
+ return catalog;
932
+ } catch { return null; }
933
+ }
934
+
935
+ /** 只删团队自建(目录里的 .json);内置预设不可删。 */
936
+ async function deleteTeamPreset(s, ctx, rawId) {
937
+ const id = String(rawId || '').trim();
938
+ if (!PRESET_ID_RE.test(id)) throw new Error(`agentPreset 名称非法:「${id}」`);
939
+ const file = path.join(s.presetDir, `${id}.json`);
940
+ if (!fs.existsSync(file)) throw new Error(`只有团队自建预设可以删除:「${id}」不在 ${s.presetDir}`);
941
+ const dispose = teamPresetDisposers.get(id);
942
+ teamPresetDisposers.delete(id);
943
+ if (dispose) { try { await dispose(); } catch { /* 已失效就继续删文件 */ } }
944
+ fs.rmSync(file, { force: true });
945
+ await syncPresetCatalog(s, ctx);
946
+ return { id, file, removed: true };
947
+ }
948
+
949
+ /** 面板点删除 → sidecar 排队 → 这里取队列执行并 ack(Host 服务只在本进程里可调)。 */
950
+ async function processPresetDeletes(s, ctx) {
951
+ let items = [];
952
+ try { items = (await request(s, '/api/presets/pending-deletes')).items || []; } catch { return; }
953
+ for (const item of items) {
954
+ if (Number(item.attempts) >= 5) continue; // 面板显示错误;不再无限重试
955
+ let error = null;
956
+ try { await deleteTeamPreset(s, ctx, item.id); } catch (err) { error = String(err?.message || err); }
957
+ try { await request(s, `/api/presets/pending-deletes/${encodeURIComponent(item.id)}/ack`, { method: 'POST', body: error ? { error } : {} }); } catch { /* 下次再 ack */ }
958
+ }
959
+ }
960
+
961
+ /** 解析并校验 permissionPreset:宿主注册了该服务时按 names 校验,否则原样交给宿主 set()。 */
962
+ function resolvePermissionPreset(ctx, requested, fallback) {
963
+ const preset = String(requested || fallback || 'workspace-write').trim();
964
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(preset)) {
965
+ throw new Error(`permissionPreset 名称非法:「${preset}」`);
966
+ }
967
+ const svc = permissionPresetsOf(ctx);
968
+ const names = svc && Array.isArray(svc.names) ? svc.names : null;
969
+ if (names && names.length && !names.includes(preset)) {
970
+ throw new Error(`permissionPreset「${preset}」不存在;可用预设:${names.join(', ')}`);
971
+ }
972
+ return preset;
973
+ }
974
+
975
+ /** 把预设落到已发布的子会话:sandbox + approval 两个 knob 一起写。 */
976
+ function applyPermissionPreset(ctx, sessionId, preset) {
977
+ const svc = permissionPresetsOf(ctx);
978
+ if (!svc || typeof svc.set !== 'function') return { applied: false, reason: 'permissionPresets 服务不可用' };
979
+ const sessions = sessionsOf(ctx);
980
+ const session = sessions && typeof sessions.get === 'function' ? sessions.get(String(sessionId)) : null;
981
+ if (!session) return { applied: false, reason: '子会话尚未发布' };
982
+ try {
983
+ svc.set(session, preset);
984
+ return { applied: true, preset };
985
+ } catch (err) {
986
+ return { applied: false, preset, error: String(err?.message || err) };
987
+ }
619
988
  }
620
989
 
621
990
  const clip = (text, max) => {
@@ -626,13 +995,10 @@ const clip = (text, max) => {
626
995
  /** 成员收到的一条任务说明:必须包含 teamId / taskId 和「跑完怎么回报」。 */
627
996
  function taskBrief(teamId, task, member) {
628
997
  const plan = (task.plan || []).map((p, i) => {
629
- const kind = p.op?.kind || p.action || p.phase || 'do';
630
- const target = p.target ? ` → ${p.target}` : '';
631
- const args = p.op?.args ? ` ${clip(JSON.stringify(p.op.args), 300)}` : '';
632
- return `${i + 1}. [${p.step || `S${i + 1}`}] ${kind}${target}${args}`;
998
+ const detail = p.detail || p.action || p.phase || 'do';
999
+ return `${i + 1}. [${p.step || `S${i + 1}`}] ${detail}`;
633
1000
  });
634
1001
  const deps = (task.dependsOn || []).length ? `\n依赖(已完成):${task.dependsOn.join(', ')}` : '';
635
- const scopes = (task.writeScopes || []).length ? `\n写域(写入请限制在这些前缀内):${task.writeScopes.join(', ')}` : '';
636
1002
  const acceptance = task.acceptance ? `\n验收标准:${task.acceptance}` : '';
637
1003
  return [
638
1004
  '【dsh-team 任务派发】',
@@ -643,7 +1009,6 @@ function taskBrief(teamId, task, member) {
643
1009
  `subject:${task.subject}`,
644
1010
  ...(plan.length ? ['计划步骤:', ...plan] : []),
645
1011
  ...(deps ? [deps.trim()] : []),
646
- ...(scopes ? [scopes.trim()] : []),
647
1012
  ...(acceptance ? [acceptance.trim()] : []),
648
1013
  '',
649
1014
  '执行要求:',
@@ -705,7 +1070,7 @@ async function dispatchLoop(s, ctx, teamId) {
705
1070
  }
706
1071
  const { task, member } = r;
707
1072
  // 先记绑定再投递:成员第一轮 LLM 调用可能在 sendMessage 返回后就已开始
708
- if (member.agentSessionId) rememberMember(member.agentSessionId, teamId, member.id);
1073
+ if (member.agentSessionId) rememberMember(member.agentSessionId, teamId, member.id, null, member.permissionPreset, member.name);
709
1074
  // 任务已投递:先按「在跑」记账,agent/status 的 running 事件可能因为状态未变化而不发
710
1075
  if (member.agentSessionId) agentStatusBySession.set(String(member.agentSessionId), 'running');
711
1076
  try {
@@ -728,6 +1093,124 @@ async function dispatchLoop(s, ctx, teamId) {
728
1093
  }
729
1094
  }
730
1095
 
1096
+ // ---------- 权限审批转发:成员 preset 触发 approval/request → Lead 用 team_approve 决定 ----------
1097
+ const pendingApprovals = new Map();
1098
+
1099
+ function settleApproval(s, requestId, decision, reason, decidedBy) {
1100
+ const entry = pendingApprovals.get(requestId);
1101
+ if (!entry) return null;
1102
+ pendingApprovals.delete(requestId);
1103
+ clearTimeout(entry.timer);
1104
+ entry.signal?.removeEventListener?.('abort', entry.onAbort);
1105
+ const outcome = decision === 'allow' || decision === 'allowed-once'
1106
+ ? 'allowed-once'
1107
+ : decision === 'cancelled' ? 'cancelled' : 'rejected';
1108
+ const recorded = outcome === 'allowed-once' ? 'allowed' : outcome;
1109
+ entry.resolve(outcome);
1110
+ void request(s, `/api/approvals/${encodeURIComponent(requestId)}/decide`, {
1111
+ method: 'POST',
1112
+ body: { decision: recorded, decidedBy: decidedBy || 'lead', ...(reason ? { reason } : {}) },
1113
+ }).catch(() => { /* 审计镜像失败不影响审批本身 */ });
1114
+ return entry;
1115
+ }
1116
+
1117
+ function cancelPendingApprovals() {
1118
+ for (const [requestId, entry] of [...pendingApprovals]) {
1119
+ pendingApprovals.delete(requestId);
1120
+ clearTimeout(entry.timer);
1121
+ entry.signal?.removeEventListener?.('abort', entry.onAbort);
1122
+ entry.resolve('cancelled');
1123
+ }
1124
+ }
1125
+
1126
+ async function notifyLeadOfApproval(s, ctx, req, info) {
1127
+ const subs = subagentsOf(ctx);
1128
+ if (!subs || typeof subs.sendMessage !== 'function' || !req?.agent) return false;
1129
+ const team = await teamOf(s, info.teamId);
1130
+ const leadId = leadByTeam.get(info.teamId)?.id != null
1131
+ ? String(leadByTeam.get(info.teamId).id)
1132
+ : (team.leadSessionId ? String(team.leadSessionId) : null);
1133
+ if (!leadId) return false;
1134
+ const minutes = Math.max(1, Math.round(s.approvalTimeoutMs / 60000));
1135
+ const text = [
1136
+ '【dsh-team 权限审批】',
1137
+ `teamId=${info.teamId}`,
1138
+ `memberId=${info.memberId}`,
1139
+ `memberName=${info.memberName || info.memberId}`,
1140
+ `toolName=${info.toolName || '(unknown)'}`,
1141
+ ...(info.reason ? [`reason:${clip(info.reason, 500)}`] : []),
1142
+ `requestId=${info.requestId}`,
1143
+ '',
1144
+ `成员因 permissionPreset「${info.preset || 'unknown'}」的审批策略暂停,等待你决定。`,
1145
+ `批准本次操作:team_approve({ teamId: "${info.teamId}", requestId: "${info.requestId}", decision: "allow" })`,
1146
+ `拒绝:把 decision 改成 "deny"(可加 reason)。`,
1147
+ `超过 ${minutes} 分钟未决定将自动拒绝。`,
1148
+ ].join('\n');
1149
+ await subs.sendMessage(req.agent, leadId, [{ type: 'text', text }], { signal: AbortSignal.timeout(s.requestTimeoutMs) });
1150
+ return true;
1151
+ }
1152
+
1153
+ async function onApprovalRequest(s, ctx, req, next) {
1154
+ const sessionId = req?.agent?.id != null ? String(req.agent.id) : null;
1155
+ const binding = sessionId ? sessionMember.get(sessionId) : null;
1156
+ // 不是本插件的成员:交回 DSH 原有审批链路(Lead 自己的审批仍走宿主 UI)。
1157
+ if (!binding) return next();
1158
+
1159
+ const requestId = String(req.id ?? req.requestId ?? `${sessionId}:${Date.now()}`);
1160
+ const info = {
1161
+ requestId,
1162
+ teamId: binding.teamId,
1163
+ memberId: binding.memberId,
1164
+ memberName: binding.name || null,
1165
+ sessionId,
1166
+ toolName: String(req.toolName || ''),
1167
+ reason: String(req.reason || ''),
1168
+ preset: binding.permissionPreset || null,
1169
+ };
1170
+ // 同一个请求重复进入(理论上不会)直接拒绝,避免两个 waiter 争同一个 id。
1171
+ if (pendingApprovals.has(requestId)) return 'rejected';
1172
+
1173
+ // 先镜像到 sidecar,面板/报告可见;失败不影响审批。
1174
+ void request(s, '/api/approvals', {
1175
+ method: 'POST',
1176
+ body: { id: requestId, teamId: info.teamId, memberId: info.memberId, sessionId, toolName: info.toolName, reason: info.reason },
1177
+ }).catch(() => { /* ignore */ });
1178
+
1179
+ const outcome = await new Promise((resolve) => {
1180
+ const timer = setTimeout(() => {
1181
+ if (!pendingApprovals.delete(requestId)) return;
1182
+ resolve('rejected');
1183
+ void request(s, `/api/approvals/${encodeURIComponent(requestId)}/decide`, {
1184
+ method: 'POST', body: { decision: 'expired', decidedBy: 'timeout', reason: 'approval timeout' },
1185
+ }).catch(() => {});
1186
+ }, s.approvalTimeoutMs);
1187
+ timer.unref?.();
1188
+
1189
+ const onAbort = () => {
1190
+ if (!pendingApprovals.delete(requestId)) return;
1191
+ clearTimeout(timer);
1192
+ resolve('cancelled');
1193
+ void request(s, `/api/approvals/${encodeURIComponent(requestId)}/decide`, {
1194
+ method: 'POST', body: { decision: 'cancelled', decidedBy: 'abort', reason: 'member turn aborted' },
1195
+ }).catch(() => {});
1196
+ };
1197
+
1198
+ pendingApprovals.set(requestId, { ...info, resolve, timer, signal: req.signal, onAbort });
1199
+ if (req.signal) req.signal.addEventListener?.('abort', onAbort, { once: true });
1200
+
1201
+ notifyLeadOfApproval(s, ctx, req, info).then((ok) => {
1202
+ if (ok) return;
1203
+ // 通知不到 Lead(服务缺失/没有 lead 会话):立刻拒绝,别让成员干等。
1204
+ const entry = pendingApprovals.get(requestId);
1205
+ if (entry) settleApproval(s, requestId, 'deny', '无法通知 Lead', 'system');
1206
+ }).catch(() => {
1207
+ const entry = pendingApprovals.get(requestId);
1208
+ if (entry) settleApproval(s, requestId, 'deny', '通知 Lead 失败', 'system');
1209
+ });
1210
+ });
1211
+ return outcome;
1212
+ }
1213
+
731
1214
  /** agent/status 回写 sidecar:idle 时兜底收尾在途任务,running 时置 running。 */
732
1215
  function reportAgentStatus(s, sessionId, status, detail) {
733
1216
  if (!sessionId) return;
@@ -746,6 +1229,8 @@ const agentStatusBySession = new Map();
746
1229
  const idleTimers = new Map();
747
1230
  /** sessionId → 派发后「成员会话是否真的跑起来」的监视定时器。 */
748
1231
  const startTimers = new Map();
1232
+ /** Lead 主动 interrupt 后冻结的会话:在 resume 前忽略其 idle / turn-error 回报。 */
1233
+ const heldSessions = new Set();
749
1234
 
750
1235
  function cancelIdleReport(sessionId) {
751
1236
  const timer = idleTimers.get(sessionId);
@@ -778,6 +1263,43 @@ function cancelStartWatchdog(sessionId) {
778
1263
  if (timer) { clearTimeout(timer); startTimers.delete(sessionId); }
779
1264
  }
780
1265
 
1266
+ /** 成员会话被替换/移除后,清掉插件侧所有指向旧 session 的绑定。 */
1267
+ function forgetSession(sessionId) {
1268
+ if (sessionId == null) return;
1269
+ const sid = String(sessionId);
1270
+ cancelIdleReport(sid);
1271
+ cancelStartWatchdog(sid);
1272
+ heldSessions.delete(sid);
1273
+ agentStatusBySession.delete(sid);
1274
+ sessionMember.delete(sid);
1275
+ }
1276
+
1277
+ /**
1278
+ * 释放成员子会话:优先 drainChildren(从父会话摘除并结束),
1279
+ * 旧版 subagents 没有该能力时退回 interrupt。
1280
+ */
1281
+ async function releaseSession(subs, caller, sessionId) {
1282
+ if (!sessionId) return { ok: true, method: 'none' };
1283
+ const sid = String(sessionId);
1284
+ if (typeof subs?.drainChildren === 'function') {
1285
+ try {
1286
+ await subs.drainChildren(caller, [sid]);
1287
+ return { ok: true, method: 'drainChildren' };
1288
+ } catch (err) {
1289
+ if (typeof subs?.interrupt !== 'function') return { ok: false, error: String(err?.message || err) };
1290
+ }
1291
+ }
1292
+ if (typeof subs?.interrupt === 'function') {
1293
+ try {
1294
+ await subs.interrupt(sid, { kind: 'ancestor', agent: caller });
1295
+ return { ok: true, method: 'interrupt' };
1296
+ } catch (err) {
1297
+ return { ok: false, error: String(err?.message || err) };
1298
+ }
1299
+ }
1300
+ return { ok: false, error: 'subagents 服务不支持 drainChildren/interrupt' };
1301
+ }
1302
+
781
1303
  /** 直接读 sidecar /status(不经 request:心跳/镜像不能顺手把 sidecar 拉起来)。 */
782
1304
  async function readStatus(s) {
783
1305
  try {
@@ -790,6 +1312,46 @@ async function readStatus(s) {
790
1312
  } catch { return null; }
791
1313
  }
792
1314
 
1315
+ /** sessionId → 最近一次从 sidecar 看到的成员状态;用于只强制中断一次。 */
1316
+ const forceStopSeen = new Map();
1317
+
1318
+ /**
1319
+ * 面板/看板停止只走 sidecar(不经过 Host 插件),sidecar 改不了 DSH 会话。
1320
+ * 这里轮询成员状态:一旦看到 running → interrupted,就用登记的直接父会话
1321
+ * 以 user 授权调用 subagents.interrupt,真正停掉成员当前回合,并冻结该会话,
1322
+ * 防止 DSH 中断后的 idle 又把成员改回 idle。
1323
+ */
1324
+ async function forceStopPump(s, ctx) {
1325
+ const subs = subagentsOf(ctx);
1326
+ if (!subs || typeof subs.interrupt !== 'function') return;
1327
+ const status = await readStatus(s);
1328
+ if (!status || !Array.isArray(status.members)) return;
1329
+ const live = new Set();
1330
+ for (const m of status.members) {
1331
+ const sid = m?.agentSessionId != null ? String(m.agentSessionId) : null;
1332
+ if (!sid) continue;
1333
+ live.add(sid);
1334
+ const prev = forceStopSeen.get(sid);
1335
+ forceStopSeen.set(sid, m.status);
1336
+ if (m.status !== 'interrupted' || prev === 'interrupted') continue;
1337
+ if (heldSessions.has(sid)) continue;
1338
+ const parentSessionId = m.parentSessionId != null ? String(m.parentSessionId) : null;
1339
+ if (!parentSessionId) continue;
1340
+ heldSessions.add(sid);
1341
+ cancelIdleReport(sid);
1342
+ cancelStartWatchdog(sid);
1343
+ agentStatusBySession.set(sid, 'interrupted');
1344
+ try {
1345
+ await Promise.resolve(subs.interrupt(sid, { kind: 'user', parentSessionId }));
1346
+ } catch {
1347
+ // 会话可能已经结束;撤销冻结并清掉 seen,让下一跳还能重试。
1348
+ heldSessions.delete(sid);
1349
+ forceStopSeen.delete(sid);
1350
+ }
1351
+ }
1352
+ for (const sid of forceStopSeen.keys()) if (!live.has(sid)) forceStopSeen.delete(sid);
1353
+ }
1354
+
793
1355
  /** DSH 内置 todo 的状态 → sidecar 计划步骤的状态。 */
794
1356
  const TODO_TO_PLAN = { pending: 'open', in_progress: 'active', completed: 'done' };
795
1357
 
@@ -853,6 +1415,63 @@ async function markDelivered(s, messageId) {
853
1415
  }).catch(() => { /* 回执补记失败不影响投递 */ });
854
1416
  }
855
1417
 
1418
+ /**
1419
+ * 面板 steer 队列的投递泵。
1420
+ *
1421
+ * 面板(或任何外部调用)只把 `kind='steer'` 的消息写进 sidecar 信箱,sidecar 不会自己送进成员会话;
1422
+ * 这里定时取 queued 的 steer 消息,用 `subagents.sendMessage` 推进成员会话后补记送达。
1423
+ * - `payload.immediate=true`(面板 ⌘/Ctrl+↵ 或队列 chip 的「Now」)排到最前,只是优先投递,不打断当前回合;
1424
+ * - 每个成员每轮只投一条,避免一次性灌爆成员上下文;
1425
+ * - 投递失败保持 queued,下一轮重试;成员已无会话(worker / 已回收)就留在队列里等人工处理。
1426
+ */
1427
+ const steerInFlight = new Set();
1428
+
1429
+ async function steerPump(s, ctx) {
1430
+ if (!sessionMember.size) return;
1431
+ const subs = subagentsOf(ctx);
1432
+ if (!subs || typeof subs.sendMessage !== 'function') return;
1433
+ const teams = new Set();
1434
+ for (const binding of sessionMember.values()) if (binding?.teamId) teams.add(binding.teamId);
1435
+
1436
+ for (const teamId of teams) {
1437
+ const caller = leadByTeam.get(teamId);
1438
+ if (!caller) continue;
1439
+ const res = await request(
1440
+ s,
1441
+ `/api/messages${qs({ team: teamId, status: 'queued', limit: 100 })}`,
1442
+ ).catch(() => null);
1443
+ const rows = Array.isArray(res) ? res : (Array.isArray(res?.items) ? res.items : []);
1444
+ const items = rows.filter(
1445
+ (m) => m && m.kind === 'steer' && m.to && m.to !== 'lead' && m.status === 'queued' && !steerInFlight.has(m.id),
1446
+ );
1447
+ items.sort((a, b) => {
1448
+ const priority = Number(!!b.payload?.immediate) - Number(!!a.payload?.immediate);
1449
+ return priority || String(a.sentAt || '').localeCompare(String(b.sentAt || ''));
1450
+ });
1451
+
1452
+ const taken = new Set();
1453
+ for (const message of items) {
1454
+ const target = String(message.to);
1455
+ if (taken.has(target)) continue; // 每个成员每轮只投一条
1456
+ const binding = [...sessionMember.entries()].find(
1457
+ ([, b]) => b && b.memberId === target && b.teamId === teamId,
1458
+ );
1459
+ if (!binding) continue; // 该成员没有 sub-agent 会话:留队列,等重新 spawn
1460
+ taken.add(target);
1461
+ const text = String(message.payload?.text || '').trim();
1462
+ if (!text) { await markDelivered(s, message.id); continue; }
1463
+ steerInFlight.add(message.id);
1464
+ try {
1465
+ await subs.sendMessage(caller, String(binding[0]), [{ type: 'text', text }], {
1466
+ signal: AbortSignal.timeout(s.requestTimeoutMs),
1467
+ });
1468
+ await markDelivered(s, message.id);
1469
+ } catch { /* 成员会话暂时不可写:保持 queued,下一轮重试 */ }
1470
+ finally { steerInFlight.delete(message.id); }
1471
+ }
1472
+ }
1473
+ }
1474
+
856
1475
  /** 成员会话这一轮最后的助手正文:收工时落库成 member→lead 的回复消息。 */
857
1476
  const lastReplyBySession = new Map();
858
1477
 
@@ -896,28 +1515,19 @@ async function flushMemberReply(s, sessionId) {
896
1515
  const PLAN_STEP = {
897
1516
  type: 'object',
898
1517
  additionalProperties: true,
899
- description: 'One observable action executed by a worker process through the sidecar permission broker.',
1518
+ description: 'One plan step / brief line handed to the member sub-agent. Purely descriptive: the member executes it with its own tools.',
900
1519
  properties: {
901
1520
  step: { type: 'string', description: 'Step label, e.g. S1.' },
902
1521
  phase: {
903
1522
  type: 'string',
904
- description: 'Event phase used in the timeline: init|read|write|exec|net|env|msg|wait|verify|done|fail.',
1523
+ description: 'Optional phase used in the timeline: init|read|write|exec|net|env|msg|wait|verify|done|fail.',
905
1524
  },
906
1525
  action: { type: 'string', description: 'Verb shown in the timeline, e.g. write / read / exec.' },
907
1526
  target: { type: 'string', description: 'File path, command, host, or env name this step touches.' },
908
- op: {
909
- type: 'object',
910
- additionalProperties: true,
911
- 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.',
912
- properties: { kind: { type: 'string' } },
913
- required: ['kind'],
914
- },
915
- onDenied: { type: 'string', enum: ['scope'], description: "Escalate a denied action into a scope request instead of failing the task." },
916
- scopeReason: { type: 'string' },
917
- scopeTimeoutMs: { type: 'integer' },
1527
+ op: { type: 'object', additionalProperties: true, description: 'Optional legacy detail (ignored by the sidecar).' },
918
1528
  fatal: { type: 'boolean' },
919
1529
  },
920
- required: ['step', 'op'],
1530
+ required: ['step'],
921
1531
  };
922
1532
 
923
1533
  const MEMBER_FIELDS = {
@@ -940,35 +1550,403 @@ const textOutput = () => ({
940
1550
  render: (_args, value) => [{ type: 'text', text: String(value?.markdown ?? value) }],
941
1551
  });
942
1552
 
1553
+
1554
+ // ---------------------------------------------------------------------------
1555
+ // 工作区看板:Host 侧调度
1556
+ //
1557
+ // sidecar 只负责状态/并发/claim;这里按 claim 结果创建根会话并投 prompt。
1558
+ // 规划默认只读,执行用 danger-full-access(无人值守会话不能停在审批 UI)。
1559
+ // ---------------------------------------------------------------------------
1560
+ const boardSessions = new Map(); // sessionId -> { taskId, phase, handle, sawRunning }
1561
+ const boardSessionIds = new Set();
1562
+
1563
+ function boardUserMessage(text) {
1564
+ return {
1565
+ id: randomUUID(),
1566
+ role: 'user',
1567
+ content: [{ type: 'text', text: String(text) }],
1568
+ source: { kind: 'user' },
1569
+ };
1570
+ }
1571
+
1572
+ function boardRoute(task, settings, kind) {
1573
+ const one = (provider, model, reasoningEffort) => (model
1574
+ ? { ...(provider ? { provider } : {}), model, ...(reasoningEffort ? { reasoningEffort } : {}) }
1575
+ : null);
1576
+ const list = kind === 'planning'
1577
+ ? [
1578
+ [task.planRoute?.provider, task.planRoute?.model, task.planRoute?.reasoningEffort],
1579
+ [settings.planProvider, settings.planModel, settings.planReasoningEffort],
1580
+ [task.leadRoute?.provider, task.leadRoute?.model, task.leadRoute?.reasoningEffort],
1581
+ [settings.leadProvider, settings.leadModel, settings.leadReasoningEffort],
1582
+ ]
1583
+ : [
1584
+ [task.leadRoute?.provider, task.leadRoute?.model, task.leadRoute?.reasoningEffort],
1585
+ [settings.leadProvider, settings.leadModel, settings.leadReasoningEffort],
1586
+ ];
1587
+ for (const [provider, model, effort] of list) {
1588
+ const route = one(provider, model, effort);
1589
+ if (route) return route;
1590
+ }
1591
+ return undefined;
1592
+ }
1593
+
1594
+ function boardRouteOrDefault(ctx, task, settings, kind) {
1595
+ const route = boardRoute(task, settings, kind);
1596
+ if (route) return route;
1597
+ try {
1598
+ const cur = ctx.get('agentDefaultModel')?.currentSelection?.();
1599
+ if (cur?.model) return { ...(cur.provider ? { provider: cur.provider } : {}), model: cur.model };
1600
+ } catch { /* ignore */ }
1601
+ return undefined;
1602
+ }
1603
+
1604
+ function boardSetPermission(ctx, agent, preset) {
1605
+ if (!preset) return { applied: false };
1606
+ const svc = permissionPresetsOf(ctx);
1607
+ if (!svc || typeof svc.set !== 'function') return { applied: false, reason: 'permissionPresets 不可用' };
1608
+ try {
1609
+ svc.set(agent.session, preset);
1610
+ return { applied: true, preset };
1611
+ } catch (err) {
1612
+ return { applied: false, preset, error: String(err?.message || err) };
1613
+ }
1614
+ }
1615
+
1616
+ function boardPlanningPrompt(task, settings) {
1617
+ const models = Array.isArray(task.teamModels) && task.teamModels.length
1618
+ ? task.teamModels.map((m) => (typeof m === 'string' ? m : `${m.provider ? m.provider + '/' : ''}${m.model}`)).join('\n')
1619
+ : '不限制';
1620
+ return [
1621
+ `你是「${task.title}」的规划 Agent。只做规划,不写代码、不修改文件、不创建团队。`,
1622
+ '规划完成后不要开始执行;调度器会在执行槽位空出后,在同一会话里让你继续。',
1623
+ '',
1624
+ `工作区:${task.workspacePath}`,
1625
+ '任务描述:',
1626
+ task.description || '(无)',
1627
+ '',
1628
+ '可用模型(成员分配只能从这里选):',
1629
+ models,
1630
+ '',
1631
+ '开始规划前,先加载 `dsh-agent-team` 技能(调用 skill 工具,参数 {"name":"dsh-agent-team"}),按技能里的团队编排流程与工具字段规划。',
1632
+ '',
1633
+ '请先阅读必要文件,然后输出一份可执行计划,必须包含:',
1634
+ '1. 目标与验收标准',
1635
+ '2. 实施步骤(到文件/模块级)',
1636
+ '3. 团队与成员建议(每个成员的角色、模型、依赖关系)',
1637
+ '4. 风险与回滚',
1638
+ '',
1639
+ '最后必须调用 board_plan_submit({ plan: "<完整 markdown>", summary: "<一句话>" })。',
1640
+ '不要只把计划写在回复里。提交后停下,等待执行指令。',
1641
+ ].join('\n');
1642
+ }
1643
+
1644
+ function boardLeadPrompt(task, sameSession) {
1645
+ const models = Array.isArray(task.teamModels) && task.teamModels.length
1646
+ ? task.teamModels.map((m) => (typeof m === 'string' ? m : `${m.provider ? m.provider + '/' : ''}${m.model}`)).join('\n')
1647
+ : '不限制';
1648
+ // 任务已有关联团队(重试、失败后继续、或完成后再次执行)时,在原团队上接着干,
1649
+ // 不要每轮都 team_create 出一个新团队。
1650
+ const teams = Array.isArray(task.teams) ? task.teams.filter(Boolean).map(String) : [];
1651
+ const teamRule = teams.length
1652
+ ? `1. 本任务已关联团队:${teams.join('、')}。不要调用 team_create 新建团队:先 team_status 查看这些团队的现状,`
1653
+ + '在原团队里用 team_task 追加剩余工作继续推进;已经完成的成员任务不要重复创建。'
1654
+ + '只有原团队已被删除或全部不可用时,才允许 team_create 新团队(若既有团队需要继续保留、只是要并行新建,必须显式传 force: true)。'
1655
+ : '1. 先调用 team_create 创建团队;name 用任务标题,workspace 用上面的路径。需要多个团队就多次创建,所有团队都会自动绑定到本任务。';
1656
+ return [
1657
+ `你是任务「${task.title}」的 Lead。工作区:${task.workspacePath}`,
1658
+ sameSession ? '你刚刚在同一会话完成了规划,现在开始执行。' : '以下是规划会话产出的计划,现在开始执行。',
1659
+ '',
1660
+ '任务描述:',
1661
+ task.description || '(无)',
1662
+ '',
1663
+ '已确认的计划:',
1664
+ task.planMd || '(无)',
1665
+ '',
1666
+ '开始执行前,先加载 `dsh-agent-team` 技能(调用 skill 工具,参数 {"name":"dsh-agent-team"}),按技能里的团队编排流程、工具字段与常见错法执行,不要凭记忆猜参数。',
1667
+ '',
1668
+ '规则:',
1669
+ teamRule,
1670
+ '2. 调用 team_models 查看可用路由;只能使用以下模型:',
1671
+ models,
1672
+ '3. 用 team_task 拆解并派发;用 team_status / team_report 跟踪。不要自己写代码,不要重复成员的工作。',
1673
+ '4. 全部任务成功后,必须调用 board_task_status({ status: "done", summary: "<完成摘要>" })。',
1674
+ '5. 无法完成时调用 board_task_status({ status: "failed", summary: "<原因>" })。',
1675
+ '6. 之后如果用户再次发消息,先调用 board_task_status({ status: "inprogress" }),再继续处理。',
1676
+ ].join('\n');
1677
+ }
1678
+
1679
+ async function boardTaskOf(s, sessionId) {
1680
+ if (!sessionId) return null;
1681
+ try {
1682
+ const r = await request(s, `/api/board/by-session/${encodeURIComponent(sessionId)}`);
1683
+ return r && r.id ? r : null;
1684
+ } catch { return null; }
1685
+ }
1686
+
1687
+ async function bindBoardTeam(s, exec, teamId) {
1688
+ const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
1689
+ if (!sessionId || !teamId) return;
1690
+ try {
1691
+ const task = await boardTaskOf(s, sessionId);
1692
+ if (task) await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/teams`, { method: 'POST', body: { teamId } });
1693
+ } catch { /* 绑定失败不影响团队创建 */ }
1694
+ }
1695
+
1696
+ /**
1697
+ * 重试/续跑出来的 Lead 会话(spawn 时任务已有团队)默认禁止重复建队:
1698
+ * 提示词是软约束,这里做成硬约束,避免模型不听话又多出一个团队。
1699
+ * 只有 `force:true` 或原团队全部已被删除/归档时才放行。
1700
+ */
1701
+ async function guardBoardTeamReuse(s, sessionId, force) {
1702
+ if (force || !sessionId) return;
1703
+ const rec = boardSessions.get(String(sessionId));
1704
+ if (!rec?.reusedRun) return;
1705
+ const task = await boardTaskOf(s, String(sessionId));
1706
+ const teamIds = Array.isArray(task?.teams) ? task.teams.filter(Boolean).map(String) : [];
1707
+ if (!teamIds.length) return;
1708
+ const alive = [];
1709
+ for (const id of teamIds) {
1710
+ try {
1711
+ const team = await request(s, `/api/teams/${encodeURIComponent(id)}`);
1712
+ if (team && !team.archivedAt) alive.push(`${team.id}(${team.name || '未命名'})`);
1713
+ } catch { /* 团队已不存在 */ }
1714
+ }
1715
+ if (!alive.length) return;
1716
+ throw new Error(
1717
+ `本任务已关联团队:${alive.join('、')}。重试/续跑请在原团队上继续:先用 team_status 查看现状,再用 team_task 追加剩余工作,不要重复 team_create。`
1718
+ + '确实需要与之并行新建团队时,调用 team_create 并显式传 force: true。',
1719
+ );
1720
+ }
1721
+
1722
+ /**
1723
+ * 把看板会话挂进 DSH 工作区会话账本,让它在「工作区会话」列表里可见。
1724
+ * 受看板设置 showTaskSessions 控制(缺省开启);失败只告警,不影响任务推进。
1725
+ */
1726
+ async function attachBoardSessionToWorkspace(ctx, task, sessionId) {
1727
+ try {
1728
+ const registry = ctx.get('workspaceRegistry');
1729
+ if (!registry || typeof registry.get !== 'function' || !task.workspaceId) return;
1730
+ const workspace = registry.get(task.workspaceId);
1731
+ if (!workspace || typeof workspace.attachSession !== 'function') return;
1732
+ await workspace.attachSession(String(sessionId));
1733
+ } catch (err) {
1734
+ console.warn(`[dsh-team] attach board session to workspace failed: ${String(err?.message || err)}`);
1735
+ }
1736
+ }
1737
+
1738
+ async function spawnBoardSession(s, ctx, item) {
1739
+ const { task, workspace, settings, fence } = item;
1740
+ const agents = (() => { try { return ctx.get('agents'); } catch { return undefined; } })();
1741
+ if (!agents || typeof agents.create !== 'function') throw new Error('agents 服务不可用:无法创建看板会话');
1742
+
1743
+ const kind = task.status === 'planning' ? 'planning' : 'inprogress';
1744
+ // spawn 时任务已有团队(重试、失败后续跑、或再次执行)→ 该会话属于续跑,
1745
+ // 允许复用既有团队但默认禁止再建新团队(见 guardBoardTeamReuse)。
1746
+ const hadTeams = Array.isArray(task.teams) && task.teams.filter(Boolean).length > 0;
1747
+ // 任何已有 Lead 会话的 inprogress 都复用该会话:same 模式的首轮、
1748
+ // 以及 new 模式完成后用户追问,都不能再新建会话。
1749
+ const sameSession = kind === 'inprogress' && !!task.leadSessionId;
1750
+
1751
+ // 同会话执行:复用规划会话,只切权限 + 投执行 prompt。
1752
+ if (sameSession) {
1753
+ const sessionId = String(task.leadSessionId);
1754
+ let agent = boardSessions.get(sessionId)?.handle?.agent;
1755
+ if (!agent && typeof agents.get === 'function') {
1756
+ try { agent = agents.get(sessionId); } catch { agent = undefined; }
1757
+ }
1758
+ if (!agent) {
1759
+ await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/release`, {
1760
+ method: 'POST', body: { kind: 'inprogress', error: 'session_not_live' },
1761
+ }).catch(() => {});
1762
+ return;
1763
+ }
1764
+ await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/attach`, {
1765
+ method: 'POST', body: { kind: 'inprogress', sessionId, fence },
1766
+ });
1767
+ boardSetPermission(ctx, agent, settings.leadPermissionPreset);
1768
+ if (settings.showTaskSessions !== false) await attachBoardSessionToWorkspace(ctx, task, sessionId);
1769
+ const rec = boardSessions.get(sessionId) || { taskId: task.id, handle: { agent }, sawRunning: false, reusedRun: hadTeams };
1770
+ rec.phase = 'execution';
1771
+ rec.sawRunning = false;
1772
+ boardSessions.set(sessionId, rec);
1773
+ boardSessionIds.add(sessionId);
1774
+ // 用户追问触发 done→inprogress 时,真实用户消息已经在会话里;
1775
+ // 这里只恢复状态与权限,不再注入重复的执行 prompt。
1776
+ if (!task.resumed) agent.followup(boardUserMessage(boardLeadPrompt(task, true)));
1777
+ return;
1778
+ }
1779
+
1780
+ // 新建会话:规划或「在新的会话执行」。
1781
+ const route = boardRouteOrDefault(ctx, task, settings, kind);
1782
+ const requestedPreset = kind === 'planning' ? settings.planAgentPreset : settings.leadAgentPreset;
1783
+ let presetId = null;
1784
+ try { presetId = await resolveAgentPreset(ctx, requestedPreset, null, s); } catch { presetId = null; }
1785
+ // 看板会话是根会话,没有父组合可继承;不显式挂 preset 就只剩宿主级工具
1786
+ // (没有 standard 的 shell/文件工具),成员再继承它也会一起缺。
1787
+ if (!presetId) presetId = await hostDefaultAgentPreset(ctx);
1788
+ const presetSvc = agentPresetsOf(ctx);
1789
+ let resolved = null;
1790
+ if (presetId && presetSvc && typeof presetSvc.resolve === 'function') {
1791
+ try { resolved = await presetSvc.resolve(presetId); } catch { resolved = null; }
1792
+ }
1793
+ const cwd = task.workspacePath || workspace.path;
1794
+ if (!cwd) throw new Error('工作区路径为空');
1795
+ fs.mkdirSync(cwd, { recursive: true });
1796
+ const sessionId = `session-${randomUUID()}`;
1797
+ let handle = null;
1798
+ let step = 'create';
1799
+ try {
1800
+ handle = await agents.create({
1801
+ sessionId,
1802
+ ...(route ? { agentOptions: route } : {}),
1803
+ meta: { cwd, ...(resolved ? { agentPreset: resolved.id } : {}) },
1804
+ setup: async (agentCtx) => {
1805
+ if (!resolved || !presetSvc || typeof presetSvc.mount !== 'function') return;
1806
+ await presetSvc.mount(agentCtx, resolved.id);
1807
+ },
1808
+ });
1809
+ boardSetPermission(ctx, handle.agent, kind === 'planning' ? settings.planPermissionPreset : settings.leadPermissionPreset);
1810
+ step = 'attach';
1811
+ await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/attach`, {
1812
+ method: 'POST', body: { kind, sessionId, fence },
1813
+ });
1814
+ if (settings.showTaskSessions !== false) await attachBoardSessionToWorkspace(ctx, task, sessionId);
1815
+ boardSessions.set(sessionId, { taskId: task.id, phase: kind, handle, sawRunning: false, reusedRun: hadTeams });
1816
+ boardSessionIds.add(sessionId);
1817
+ handle.agent.followup(boardUserMessage(kind === 'planning'
1818
+ ? boardPlanningPrompt(task, settings)
1819
+ : boardLeadPrompt(task, false)));
1820
+ } catch (err) {
1821
+ console.warn(`[dsh-team] board ${step} failed: ${String(err?.message || err)} cause=${String(err?.cause?.code || err?.cause || '')}`);
1822
+ try { await handle?.dispose?.(); } catch { /* ignore */ }
1823
+ await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/release`, {
1824
+ method: 'POST', body: { kind, error: String(err?.message || err) },
1825
+ }).catch(() => {});
1826
+ throw err;
1827
+ }
1828
+ }
1829
+
1830
+ async function boardPump(s, ctx) {
1831
+ if (!s.boardEnabled) return;
1832
+ const agents = (() => { try { return ctx.get('agents'); } catch { return undefined; } })();
1833
+ if (!agents || typeof agents.create !== 'function') return;
1834
+ // 规划超时:插件崩溃/会话卡死时,避免任务永久占着 planning 槽位。
1835
+ try {
1836
+ const live = await request(s, '/api/board/live');
1837
+ for (const task of live?.tasks || []) {
1838
+ // 插件重启后 boardSessions 是空的:能找回 live agent 就接管,找不回就把
1839
+ // 永远不可能再推进的任务置 failed,避免占着槽位。
1840
+ if (task.status === 'done' || task.status === 'failed') {
1841
+ // 规划被 stop/failed 后,规划会话已无用途,直接释放。
1842
+ const planSid = task.planningSessionId;
1843
+ const planRec = planSid ? boardSessions.get(String(planSid)) : null;
1844
+ if (planRec && planRec.phase === 'planning') {
1845
+ try { void planRec.handle?.dispose?.(); } catch { /* ignore */ }
1846
+ boardSessions.delete(String(planSid));
1847
+ boardSessionIds.delete(String(planSid));
1848
+ }
1849
+ // 终态任务的 Lead 会话仍可能收到用户追问;重启后把它重新纳入监听。
1850
+ const sid = task.leadSessionId;
1851
+ if (sid && !boardSessionIds.has(String(sid))) {
1852
+ let agent = null;
1853
+ try { agent = agents.get(String(sid)); } catch { agent = null; }
1854
+ if (agent) {
1855
+ boardSessions.set(String(sid), {
1856
+ taskId: task.id, phase: 'execution', handle: { agent }, sawRunning: false,
1857
+ });
1858
+ boardSessionIds.add(String(sid));
1859
+ }
1860
+ }
1861
+ continue;
1862
+ }
1863
+ if (task.status === 'planning' || task.status === 'inprogress') {
1864
+ const sid = task.status === 'planning' ? task.planningSessionId : task.leadSessionId;
1865
+ if (sid && !boardSessions.has(String(sid))) {
1866
+ let agent = null;
1867
+ try { agent = agents.get(String(sid)); } catch { agent = null; }
1868
+ if (agent) {
1869
+ boardSessions.set(String(sid), {
1870
+ taskId: task.id, phase: task.status === 'planning' ? 'planning' : 'execution',
1871
+ handle: { agent }, sawRunning: true,
1872
+ });
1873
+ boardSessionIds.add(String(sid));
1874
+ } else {
1875
+ await request(s, '/api/board/agents/status', {
1876
+ method: 'POST',
1877
+ body: { sessionId: sid, status: 'failed', summary: '会话已失效(插件重启或会话被关闭)' },
1878
+ }).catch(() => {});
1879
+ }
1880
+ }
1881
+ }
1882
+ if (task.status !== 'planning') continue;
1883
+ const at = Date.parse(task.updatedAt || task.claimedAt || '');
1884
+ if (!Number.isFinite(at) || Date.now() - at < s.boardPlanningTimeoutMs) continue;
1885
+ if (!task.planningSessionId) {
1886
+ await request(s, `/api/board/tasks/${encodeURIComponent(task.id)}/stop`, {
1887
+ method: 'POST', body: { reason: '规划超时(未 attach 会话)' },
1888
+ }).catch(() => {});
1889
+ continue;
1890
+ }
1891
+ await request(s, '/api/board/agents/status', {
1892
+ method: 'POST', body: { sessionId: task.planningSessionId, status: 'failed', summary: '规划超时' },
1893
+ }).catch(() => {});
1894
+ const rec = boardSessions.get(String(task.planningSessionId));
1895
+ if (rec) {
1896
+ try { void rec.handle?.dispose?.(); } catch { /* ignore */ }
1897
+ boardSessions.delete(String(task.planningSessionId));
1898
+ boardSessionIds.delete(String(task.planningSessionId));
1899
+ }
1900
+ }
1901
+ } catch { /* 查询失败不阻塞 claim */ }
1902
+ for (const kind of ['planning', 'inprogress']) {
1903
+ for (let i = 0; i < 4; i++) {
1904
+ let claimed;
1905
+ try {
1906
+ claimed = await request(s, '/api/board/claim', { method: 'POST', body: { kind } });
1907
+ } catch { return; }
1908
+ if (!claimed?.item) break;
1909
+ try { await spawnBoardSession(s, ctx, claimed.item); }
1910
+ catch (err) { console.warn(`[dsh-team] board spawn failed: ${String(err?.message || err)}`); }
1911
+ }
1912
+ }
1913
+ }
1914
+
943
1915
  /** 构造全部工具(普通 ToolDefinition,不依赖 defineTool;参数即 JSON Schema)。 */
944
1916
  function buildTools(s, ctx) {
945
1917
  const tools = [];
946
1918
 
947
1919
  tools.push({
948
1920
  name: 'team_create',
949
- 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".',
1921
+ description: 'START HERE to build a working team of agents. Order: team_create({name, workspace, permissionPreset?}) → team_models() to see the enabled provider/model routes → team_spawn({teamId, name, prompt, agentProvider?, model?, reasoningEffort?, permissionPreset?}) 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?, plan, acceptance}) per DAG node → each member finishes by calling team_report_task → inspect with team_status / team_report. Every member is a real DSH sub-agent session (own model, tools, context, message inbox). `permissionPreset` decides the member sandbox + approval policy (DSH permission presets, e.g. workspace-write or danger-full-access); the team value is the default and team_spawn can override it per member. When a member hits an operation its preset requires approval for, the approval is forwarded to the Lead, who decides with team_approve. `workspace` is an absolute directory shared by the members and becomes 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".',
950
1922
  parameters: {
951
1923
  type: 'object',
952
1924
  additionalProperties: false,
953
1925
  properties: {
954
1926
  name: { type: 'string', description: 'Team name.' },
955
- workspace: { type: 'string', description: 'Absolute directory shared by workers; created if missing.' },
956
- runtime: { type: 'string', enum: ['worker', 'agent'], description: "Member runtime. `agent` spawns real DSH sub-agent members (real models, real tool calls). Default worker." },
1927
+ workspace: { type: 'string', description: 'Absolute directory shared by members; created if missing.' },
1928
+ permissionPreset: { type: 'string', description: 'Default DSH permission preset for members (sandbox + approval policy). Default workspace-write. team_spawn can override it per member.' },
1929
+ agentPreset: { type: 'string', description: 'Default DSH agent preset (composition: tools/skills/MCP + system prompt) for members. Omit to use the host default. team_spawn can override it per member.' },
957
1930
  maxMembers: { type: 'integer', description: 'Member cap, 0 means unlimited. Default 64. Extra members are queued, never errors.' },
958
1931
  maxConcurrency: { type: 'integer', description: 'Max simultaneously running tasks. Default 8.' },
959
1932
  failurePolicy: { type: 'string', enum: ['continue', 'abort'], description: 'Team-level default failure policy.' },
960
1933
  maxAttempts: { type: 'integer', description: 'Per-task retry cap. Default 3.' },
1934
+ force: { type: 'boolean', description: '仅看板任务相关:该任务已关联团队时默认禁止重复建队(重试应继续用原团队);确认需要与之并行新建团队时传 true。' },
961
1935
  },
962
1936
  required: ['name', 'workspace'],
963
1937
  },
964
1938
  output: jsonOutput('{ team, panel }'),
965
1939
  async execute(args, exec) {
1940
+ await guardBoardTeamReuse(s, exec?.agent?.id, args.force);
1941
+ const permissionPreset = resolvePermissionPreset(ctx, args.permissionPreset, 'workspace-write');
1942
+ const agentPreset = await resolveAgentPreset(ctx, args.agentPreset, null, s);
966
1943
  const team = await request(s, '/api/teams', {
967
1944
  method: 'POST',
968
1945
  body: {
969
1946
  name: args.name,
970
1947
  workspace: args.workspace,
971
- ...(args.runtime !== undefined ? { runtime: args.runtime } : {}),
1948
+ permissionPreset,
1949
+ ...(agentPreset ? { agentPreset } : {}),
972
1950
  ...(args.maxMembers !== undefined ? { maxMembers: args.maxMembers } : {}),
973
1951
  ...(args.maxConcurrency !== undefined ? { maxConcurrency: args.maxConcurrency } : {}),
974
1952
  ...(args.failurePolicy !== undefined ? { failurePolicy: args.failurePolicy } : {}),
@@ -976,73 +1954,98 @@ function buildTools(s, ctx) {
976
1954
  ...(exec?.agent && exec.agent.id != null ? { leadSessionId: String(exec.agent.id) } : {}),
977
1955
  },
978
1956
  });
979
- runtimeByTeam.set(team.id, team.runtime || 'worker');
1957
+ teamCache.set(team.id, team);
980
1958
  if (exec?.agent) leadByTeam.set(team.id, exec.agent);
1959
+ // 会话级粘性绑定:即使后续 team_spawn 漏传 teamId,也能解析到本会话刚建的团队。
1960
+ if (exec?.agent?.id != null) teamBySession.set(String(exec.agent.id), String(team.id));
1961
+ await bindBoardTeam(s, exec, team.id);
981
1962
  return { team, panel: panelUrl(s) };
982
1963
  },
983
1964
  });
984
1965
 
985
1966
  tools.push({
986
1967
  name: 'team_spawn',
987
- 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.",
1968
+ description: "Add one member to a team; returns the member `id` you use as team_task's `assignee`. 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 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: 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. `permissionPreset` overrides the team default for this member (sandbox + approval policy); approval-required operations are forwarded to the Lead via team_approve.",
988
1969
  parameters: {
989
1970
  type: 'object',
990
1971
  additionalProperties: false,
991
1972
  properties: {
992
- teamId: { type: 'string', description: 'Team id from team_create.' },
1973
+ teamId: { type: 'string', description: 'team_create 返回的 result.team.id(形如 team_xxx)。漏传时自动使用当前会话刚创建的团队。' },
993
1974
  name: { type: 'string', description: 'Unique member name inside the team; this is the addressable target.' },
994
- role: { type: 'string', description: 'Role label, also usable as a policy subject (subjectType=role).' },
995
- 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.' },
996
- 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.' },
997
- 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.' },
998
- 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.' },
999
- 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.' },
1000
- description: { type: 'string', description: 'agent teams only: one-line description of what this member is responsible for.' },
1975
+ role: { type: 'string', description: 'Role label shown on the panel.' },
1976
+ permissionPreset: { type: 'string', description: "DSH permission preset for this member (sandbox + approval policy). Defaults to the team's permissionPreset." },
1977
+ agentPreset: { type: 'string', description: "DSH agent preset (composition: tools/skills/MCP + system prompt). Defaults to the team's agentPreset; omit both to join the host default. Only supported with contextMode 'fresh' (the fork provider inherits the Lead's composition)." },
1978
+ agentProvider: { type: 'string', description: 'LLM provider route id, as returned by team_models. Omit to inherit the Lead\'s provider. Must be an enabled route in the team panel.' },
1979
+ model: { type: 'string', description: 'LLM model id, as returned by team_models. Changing the route clears inherited reasoning effort unless reasoningEffort is set explicitly.' },
1980
+ reasoningEffort: { type: 'string', description: 'Adapter-defined reasoning effort id (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.' },
1981
+ contextMode: { type: 'string', enum: ['isolated', 'fresh', 'fork'], description: 'Context isolation: `fresh` starts with no Lead history, `fork` inherits completed Lead turns. Default isolated/fresh.' },
1982
+ prompt: { type: 'string', description: 'The member’s first instruction. Tell it its role, workspace, and that it must call team_report_task when done.' },
1983
+ description: { type: 'string', description: 'One-line description of what this member is responsible for.' },
1001
1984
  },
1002
- required: ['teamId', 'name'],
1985
+ required: ['teamId', 'name', 'prompt'],
1003
1986
  },
1004
- output: jsonOutput('{ member, agent?, panel }'),
1987
+ output: jsonOutput('{ member, agent, panel, permissionPreset, agentPreset, agentPresetWarning?, permissionPresetApplied?, permissionPresetWarning? }'),
1005
1988
  async execute(args, exec) {
1006
- const runtime = await runtimeOfTeam(s, args.teamId);
1007
- if (runtime !== 'agent') {
1008
- const member = await request(s, `/api/teams/${encodeURIComponent(args.teamId)}/members`, {
1009
- method: 'POST',
1010
- body: {
1011
- name: args.name,
1012
- ...(args.role !== undefined ? { role: args.role } : {}),
1013
- ...(args.model !== undefined ? { model: args.model } : {}),
1014
- ...(args.contextMode !== undefined ? { contextMode: args.contextMode } : {}),
1015
- },
1016
- });
1017
- return { member, panel: panelUrl(s) };
1018
- }
1989
+ const team = await teamOf(s, args.teamId, { sessionId: exec?.agent?.id });
1990
+ const permissionPreset = resolvePermissionPreset(ctx, args.permissionPreset, team.permissionPreset);
1991
+ let requestedAgentPreset = await resolveAgentPreset(ctx, args.agentPreset, team.agentPreset, s);
1019
1992
 
1020
- // ---- agent 团队:用 subagents 服务起一个 continuable 真子会话 ----
1993
+ // ---- 用 subagents 服务起一个 continuable 真子会话 ----
1021
1994
  const subs = subagentsOf(ctx);
1022
1995
  if (!subs || typeof subs.startActivation !== 'function') {
1023
- throw new Error('subagents 服务不可用:无法在 agent 团队里创建 sub-agent 成员(需要宿主启用 dsh-subagent)。');
1996
+ throw new Error('subagents 服务不可用:无法创建 sub-agent 成员(需要宿主启用 dsh-subagent)。');
1024
1997
  }
1025
1998
  const caller = exec?.agent;
1026
- if (!caller) throw new Error('team_spawn (agent) 需要 Lead 会话上下文(exec.agent 缺失:不能在非 agent 调用里起成员)。');
1027
- if (!args.prompt) throw new Error('agent 团队的 team_spawn 需要 prompt(成员的初始指令)。');
1999
+ if (!caller) throw new Error('team_spawn 需要 Lead 会话上下文(exec.agent 缺失:不能在非 agent 调用里起成员)。');
2000
+ if (!args.prompt) throw new Error('team_spawn 需要 prompt(成员的初始指令)。');
1028
2001
 
1029
2002
  const context = args.contextMode === 'fork' ? 'fork' : 'fresh';
2003
+ // 省略 preset 时 DSH 继承 Lead 的实时组合,不会套宿主默认;
2004
+ // fresh 成员必须显式拿宿主默认,否则 Lead 是看板裸会话时成员就没有 shell/文件工具。
2005
+ if (context !== 'fork' && !requestedAgentPreset) {
2006
+ requestedAgentPreset = await hostDefaultAgentPreset(ctx);
2007
+ }
2008
+ // fork provider 继承父方组装,DSH 会拒绝独立 agentPreset;这里显式降级为警告而不是静默传。
2009
+ const agentPreset = context === 'fork' ? null : requestedAgentPreset;
2010
+ const agentPresetWarning = context === 'fork' && requestedAgentPreset
2011
+ ? `contextMode=fork 继承 Lead 的组装,agentPreset「${requestedAgentPreset}」未生效`
2012
+ : undefined;
1030
2013
  const provider = providerFor(ctx, s, context);
1031
2014
  // 实际 route:显式参数覆盖 Lead;effort 只在 route 未变时继承(与 DSH 子会话合并规则一致)
1032
2015
  const leadRoute = leadRouteOf(caller);
1033
2016
  const route = { provider: args.agentProvider || leadRoute.provider, model: args.model || leadRoute.model };
2017
+ // 看板任务如果指定了团队模型白名单,成员 route 必须落在名单内;不指定时取第一条。
2018
+ let pickedByBoard = false;
2019
+ const callerId = caller?.id != null ? String(caller.id) : null;
2020
+ const boardTask = callerId && boardSessionIds.has(callerId) ? await boardTaskOf(s, callerId) : null;
2021
+ const allowedModels = Array.isArray(boardTask?.teamModels)
2022
+ ? boardTask.teamModels.map((m) => (typeof m === 'string'
2023
+ ? { provider: null, model: m, reasoningEffort: null }
2024
+ : { provider: m?.provider || null, model: m?.model || null, reasoningEffort: m?.reasoningEffort || null })).filter((m) => m.model)
2025
+ : [];
2026
+ if (allowedModels.length) {
2027
+ if (!args.model) {
2028
+ const first = allowedModels[0];
2029
+ route.provider = first.provider || route.provider;
2030
+ route.model = first.model;
2031
+ pickedByBoard = true;
2032
+ }
2033
+ const hit = allowedModels.find((m) => m.model === route.model && (!m.provider || m.provider === route.provider));
2034
+ if (!hit) throw new Error(`模型 ${route.provider || '?'}/${route.model || '?'} 不在看板任务的白名单内:${allowedModels.map((m) => m.model).join(', ')}`);
2035
+ }
1034
2036
  const routeChanged = route.provider !== leadRoute.provider || route.model !== leadRoute.model;
1035
2037
  route.reasoningEffort = args.reasoningEffort || (routeChanged ? null : leadRoute.reasoningEffort);
1036
- // 继承 Lead 的 route 也要过启用闸门:停用项不该被成员继续使用。
1037
- await assertRouteEnabled(s, ctx, route.provider, route.model);
2038
+ // 继承 Lead 的 route 也要过启用闸门:停用项不该被成员继续使用;effort 同理。
2039
+ await assertRouteEnabled(s, ctx, route.provider, route.model, route.reasoningEffort);
1038
2040
  const agentOptions = {};
1039
- if (args.agentProvider) agentOptions.provider = String(args.agentProvider);
1040
- if (args.model) agentOptions.model = String(args.model);
1041
- if (args.reasoningEffort) agentOptions.reasoningEffort = String(args.reasoningEffort);
2041
+ if (args.agentProvider || args.model || pickedByBoard) {
2042
+ if (route.provider) agentOptions.provider = String(route.provider);
2043
+ if (route.model) agentOptions.model = String(route.model);
2044
+ if (route.reasoningEffort && (args.reasoningEffort || pickedByBoard)) agentOptions.reasoningEffort = String(route.reasoningEffort);
2045
+ }
1042
2046
  const memberName = String(args.name).trim();
1043
2047
  const description = String(args.description || args.role || memberName).slice(0, 200);
1044
2048
  const sessionId = randomUUID();
1045
- const team = await request(s, `/api/teams/${encodeURIComponent(args.teamId)}`).catch(() => null);
1046
2049
  const started = await subs.startActivation({
1047
2050
  delivery: 'parent',
1048
2051
  childId: sessionId,
@@ -1053,12 +2056,14 @@ function buildTools(s, ctx) {
1053
2056
  parent: caller,
1054
2057
  ...(team && team.workspace ? { cwd: team.workspace } : {}),
1055
2058
  ...(Object.keys(agentOptions).length ? { agentOptions } : {}),
2059
+ ...(agentPreset ? { agentPreset } : {}),
1056
2060
  },
1057
2061
  signal: exec.signal || AbortSignal.timeout(s.requestTimeoutMs),
1058
2062
  });
1059
2063
  // 成员跑的是一整轮 agent loop,结果由 team_report_task 汇报;这里只防止未处理的 rejection。
1060
2064
  if (started && started.result && typeof started.result.catch === 'function') started.result.catch(() => {});
1061
- const spawned = { member: { id: sessionId, name: memberName, role: 'teammate', status: 'running', model: route.model || null, diagnostics: [] } };
2065
+ // 子会话发布后立刻把 preset 落到会话(会覆盖 subagent 继承来的 approval=never)。
2066
+ const presetResult = applyPermissionPreset(ctx, sessionId, permissionPreset);
1062
2067
 
1063
2068
  const registered = await request(s, '/api/agents/register', {
1064
2069
  method: 'POST',
@@ -1066,26 +2071,37 @@ function buildTools(s, ctx) {
1066
2071
  teamId: args.teamId,
1067
2072
  name: memberName,
1068
2073
  sessionId,
2074
+ parentSessionId: caller.id != null ? String(caller.id) : null,
1069
2075
  role: args.role || 'teammate',
1070
- model: args.model || spawned.member.model || null,
2076
+ model: args.model || route.model || null,
1071
2077
  contextMode: context,
2078
+ agentProvider: route.provider || null,
2079
+ permissionPreset,
2080
+ ...(agentPreset ? { agentPreset } : {}),
2081
+ // 实际生效的思考强度(含从 Lead 继承的值):面板成员卡片据此展示,之后不可变
2082
+ reasoningEffort: route.reasoningEffort || null,
1072
2083
  },
1073
2084
  });
1074
- rememberMember(sessionId, args.teamId, registered.member.id, team?.workspace);
2085
+ rememberMember(sessionId, args.teamId, registered.member.id, team?.workspace, registered.member.permissionPreset || permissionPreset, memberName);
1075
2086
  leadByTeam.set(args.teamId, caller);
1076
2087
  return {
1077
2088
  member: registered.member,
1078
2089
  agent: {
1079
2090
  sessionId,
1080
- name: spawned.member.name,
1081
- status: spawned.member.status,
1082
- role: spawned.member.role,
2091
+ name: memberName,
2092
+ status: 'running',
2093
+ role: args.role || 'teammate',
1083
2094
  provider,
1084
2095
  context,
1085
2096
  model: route.model || null,
1086
2097
  route,
1087
- diagnostics: spawned.member.diagnostics || [],
1088
2098
  },
2099
+ permissionPreset: registered.member?.permissionPreset || permissionPreset,
2100
+ agentPreset: registered.member?.agentPreset || agentPreset || null,
2101
+ ...(agentPresetWarning ? { agentPresetWarning } : {}),
2102
+ permissionPresetApplied: presetResult.applied,
2103
+ ...(presetResult.reason ? { permissionPresetWarning: presetResult.reason } : {}),
2104
+ ...(presetResult.error ? { permissionPresetWarning: presetResult.error } : {}),
1089
2105
  panel: panelUrl(s),
1090
2106
  };
1091
2107
  },
@@ -1099,22 +2115,28 @@ function buildTools(s, ctx) {
1099
2115
  additionalProperties: false,
1100
2116
  properties: {},
1101
2117
  },
1102
- output: jsonOutput('{ asOf, total, models: [{ provider, model, name, description, note, modalities }], hint? }'),
2118
+ output: jsonOutput('{ asOf, total, models: [{ provider, model, name, description, note, modalities, efforts?, defaultEffort? }], hint? }'),
1103
2119
  isConcurrencySafe: () => true,
1104
2120
  async execute() {
1105
2121
  let cat = null;
1106
2122
  try { cat = await request(s, '/api/llm/catalog'); } catch { /* catalog unavailable */ }
1107
2123
  const all = cat ? (cat.providers || []).flatMap((p) => p.models || []) : [];
1108
- const models = all.filter((m) => m.enabled).map((m) => ({
1109
- provider: m.provider,
1110
- model: m.model,
1111
- name: m.name,
1112
- ...(m.description ? { description: m.description } : {}),
1113
- ...(m.note ? { note: m.note } : {}),
1114
- ...(m.modalities ? { modalities: m.modalities } : {}),
1115
- }));
2124
+ const models = all.filter((m) => m.enabled).map((m) => {
2125
+ // 只报用户允许的 effort;allowedEfforts=null 表示全部允许。未声明 efforts 的 route 不报该字段。
2126
+ const effortIds = Array.isArray(m.efforts) ? m.efforts.map((e) => e.id) : [];
2127
+ const allowed = Array.isArray(m.allowedEfforts) ? effortIds.filter((id) => m.allowedEfforts.includes(id)) : effortIds;
2128
+ return {
2129
+ provider: m.provider,
2130
+ model: m.model,
2131
+ name: m.name,
2132
+ ...(m.description ? { description: m.description } : {}),
2133
+ ...(m.note ? { note: m.note } : {}),
2134
+ ...(m.modalities ? { modalities: m.modalities } : {}),
2135
+ ...(effortIds.length ? { efforts: allowed, ...(m.defaultEffort ? { defaultEffort: m.defaultEffort } : {}) } : {}),
2136
+ };
2137
+ });
1116
2138
  const hint = models.length
1117
- ? '在 team_spawn 里用 agentProvider + model;reasoningEffort 由模型适配器定义,省略时只在 route 不变时继承 Lead 的 effort。'
2139
+ ? '在 team_spawn 里用 agentProvider + model;efforts 是该 route 允许派发的 reasoningEffort 列表(省略时只在 route 不变时继承 Lead 的 effort,被禁止的 effort 会被拒绝)。'
1118
2140
  : '没有启用的模型路由:请让用户在面板「模型路由」页勾选需要的 provider/model。';
1119
2141
  return {
1120
2142
  asOf: cat?.asOf || new Date().toISOString(),
@@ -1125,9 +2147,63 @@ function buildTools(s, ctx) {
1125
2147
  },
1126
2148
  });
1127
2149
 
2150
+ tools.push({
2151
+ name: 'team_preset',
2152
+ description: 'Create, inspect, list, or delete team-owned agent presets when the host built-ins do not fit. A preset decides what a member OWNS (tool plugins, skill providers, MCP clients, persona/system prompt); permissionPreset decides what it MAY DO. action:list lists host presets plus presets the team already created; action:save writes one JSON document to the fixed team preset directory and registers it with the host immediately (no DSH restart), then the id can be passed to team_create({agentPreset}) / team_spawn({agentPreset}); action:show prints the saved document; action:delete removes a team-owned preset file and unregisters it (host built-ins are read-only). plugins must be a non-empty Cordis entry list, e.g. [{name:"@deepseek-ai/dsh-tool-fs"},{name:"@deepseek-ai/dsh-persona",config:{prefix:"You are a reviewer."}}]. Prefer copying the shape of an existing host preset: call team_preset({action:"show", id:"standard"}) and swap rows.',
2153
+ parameters: {
2154
+ type: 'object',
2155
+ additionalProperties: false,
2156
+ required: ['action'],
2157
+ properties: {
2158
+ action: { type: 'string', enum: ['list', 'save', 'show', 'delete'], description: 'list:列出可用预设;save:写入固定目录并立刻注册;show:读回已保存的文档;delete:删除团队自建预设并反注册。' },
2159
+ id: { type: 'string', description: '预设 id(save/show 必填),`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`。' },
2160
+ name: { type: 'string', description: '展示名(save 可选)。' },
2161
+ description: { type: 'string', description: '用途说明(save 可选)。' },
2162
+ order: { type: 'number', description: '排序权重(save 可选,越小越靠前)。' },
2163
+ confirm: { type: 'boolean', description: 'save 覆盖同名团队自建预设时必须显式 true;内置预设任何时候都不能覆盖。' },
2164
+ plugins: {
2165
+ type: 'array',
2166
+ description: 'save 必填:Cordis 插件条目列表,每项 { name, config?, id?, disabled? }。',
2167
+ items: {
2168
+ type: 'object',
2169
+ additionalProperties: true,
2170
+ required: ['name'],
2171
+ properties: { name: { type: 'string', description: '插件包名,如 @deepseek-ai/dsh-tool-fs。' } },
2172
+ },
2173
+ },
2174
+ },
2175
+ },
2176
+ output: jsonOutput('list → { dir, presets:[{id,name?,source:"host"|"team",file?,broken?}], errors };save → { id, file, registered, broken?, warning? };show → { id, file, doc };delete → { id, file, removed }'),
2177
+ isConcurrencySafe: () => true,
2178
+ async execute(args = {}) {
2179
+ const action = String(args.action || '');
2180
+ if (action === 'list') return listTeamPresets(s, ctx);
2181
+ if (action === 'show') {
2182
+ const id = String(args.id || '').trim();
2183
+ if (!PRESET_ID_RE.test(id)) throw new Error(`agentPreset 名称非法:「${id}」`);
2184
+ const file = path.join(s.presetDir, `${id}.json`);
2185
+ if (!fs.existsSync(file)) {
2186
+ const svc = ctx.get('agentPresets');
2187
+ let row = null;
2188
+ try { row = (await svc?.list?.() || []).find((r) => r && r.id === id) || null; } catch { row = null; }
2189
+ if (!row) throw new Error(`没有找到 preset「${id}」:既不在 ${s.presetDir},也不是宿主内置预设`);
2190
+ return { id, source: 'host', preset: row, hint: '宿主内置预设的文档在 DSH bundle 里,不能编辑;需要定制就新建一个 id。' };
2191
+ }
2192
+ return { id, source: 'team', file, doc: JSON.parse(fs.readFileSync(file, 'utf8')) };
2193
+ }
2194
+ if (action === 'save') {
2195
+ const saved = await saveTeamPreset(s, ctx, args);
2196
+ await syncPresetCatalog(s, ctx);
2197
+ return saved;
2198
+ }
2199
+ if (action === 'delete') return deleteTeamPreset(s, ctx, args.id);
2200
+ throw new Error(`未知 action「${action}」:只支持 list / save / show / delete`);
2201
+ },
2202
+ });
2203
+
1128
2204
  tools.push({
1129
2205
  name: 'team_status',
1130
- 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.',
2206
+ description: 'Read a live snapshot instead of guessing progress. detail=summary returns every member with status/step/seq/percent/next/blockers/stale and its permissionPreset; detail=dag returns the task DAG with dependencies, readiness, joins and the critical path. `asOf` marks the snapshot time.',
1131
2207
  parameters: {
1132
2208
  type: 'object',
1133
2209
  additionalProperties: false,
@@ -1149,9 +2225,12 @@ function buildTools(s, ctx) {
1149
2225
  asOf: st.asOf,
1150
2226
  version: st.version,
1151
2227
  panel: panelUrl(s),
1152
- runtime: st.runtime || runtimeByTeam.get(args.teamId) || 'worker',
1153
2228
  members: (st.members || []).map((m) => ({
1154
2229
  name: m.name,
2230
+ model: m.model || null,
2231
+ permissionPreset: m.permissionPreset || null,
2232
+ agentPreset: m.agentPreset || null,
2233
+ reasoningEffort: m.reasoningEffort || null,
1155
2234
  status: m.status,
1156
2235
  step: m.step,
1157
2236
  seq: m.seq,
@@ -1159,7 +2238,6 @@ function buildTools(s, ctx) {
1159
2238
  next: m.next,
1160
2239
  last: m.last,
1161
2240
  currentTaskId: m.currentTaskId,
1162
- leaseUntil: m.leaseUntil,
1163
2241
  blockers: m.blockers,
1164
2242
  stale: m.stale,
1165
2243
  agentSessionId: m.agentSessionId || null,
@@ -1173,7 +2251,7 @@ function buildTools(s, ctx) {
1173
2251
 
1174
2252
  tools.push({
1175
2253
  name: 'team_task',
1176
- 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. `deps[].from` takes a **task** id returned by an earlier team_task (member ids are rejected). 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.',
2254
+ 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.',
1177
2255
  parameters: {
1178
2256
  type: 'object',
1179
2257
  additionalProperties: false,
@@ -1181,7 +2259,7 @@ function buildTools(s, ctx) {
1181
2259
  teamId: { type: 'string' },
1182
2260
  subject: { type: 'string', description: 'Concise task title.' },
1183
2261
  assignee: { type: 'string', description: 'Member id (not name). Omit to let the scheduler pick an idle member.' },
1184
- 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.' },
2262
+ plan: { type: 'array', items: PLAN_STEP, description: 'Ordered plan steps / brief lines handed to the member. May be empty for a pure heartbeat task.' },
1185
2263
  deps: {
1186
2264
  type: 'array',
1187
2265
  description: 'Upstream dependencies declared atomically with the task: [{from, condition?, artifactPath?}].',
@@ -1196,12 +2274,11 @@ function buildTools(s, ctx) {
1196
2274
  required: ['from'],
1197
2275
  },
1198
2276
  },
1199
- writeScopes: { type: 'array', items: { type: 'string' }, description: 'Advisory write scope prefixes (sidecar policies are the enforced ones).' },
1200
2277
  acceptance: { type: 'string' },
1201
2278
  priority: { type: 'integer', description: 'Smaller runs first. Default 0.' },
1202
2279
  failurePolicy: { type: 'string', enum: ['continue', 'skip', 'abort_team', 'retry'] },
1203
2280
  maxAttempts: { type: 'integer' },
1204
- 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.' },
2281
+ dispatch: { type: 'boolean', description: 'Dispatch immediately after creating (default true). Pass false to build the DAG first and dispatch later with team_dispatch.' },
1205
2282
  },
1206
2283
  required: ['teamId', 'subject', 'plan'],
1207
2284
  },
@@ -1216,14 +2293,13 @@ function buildTools(s, ctx) {
1216
2293
  ...(args.assignee !== undefined ? { assignee: args.assignee } : {}),
1217
2294
  plan: args.plan || [],
1218
2295
  ...(args.deps !== undefined ? { deps: args.deps } : {}),
1219
- ...(args.writeScopes !== undefined ? { writeScopes: args.writeScopes } : {}),
1220
2296
  ...(args.acceptance !== undefined ? { acceptance: args.acceptance } : {}),
1221
2297
  ...(args.priority !== undefined ? { priority: args.priority } : {}),
1222
2298
  ...(args.failurePolicy !== undefined ? { failurePolicy: args.failurePolicy } : {}),
1223
2299
  ...(args.maxAttempts !== undefined ? { maxAttempts: args.maxAttempts } : {}),
1224
2300
  },
1225
2301
  });
1226
- if (args.dispatch === false || (await runtimeOfTeam(s, args.teamId)) !== 'agent') return { task };
2302
+ if (args.dispatch === false) return { task };
1227
2303
  await sleep(s.agentSettleMs);
1228
2304
  const dispatched = await dispatchLoop(s, ctx, args.teamId);
1229
2305
  return { task, dispatched };
@@ -1232,7 +2308,7 @@ function buildTools(s, ctx) {
1232
2308
 
1233
2309
  tools.push({
1234
2310
  name: 'team_send',
1235
- 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.",
2311
+ description: "Send a message that a member will actually read: 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). `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.",
1236
2312
  parameters: {
1237
2313
  type: 'object',
1238
2314
  additionalProperties: false,
@@ -1253,9 +2329,8 @@ function buildTools(s, ctx) {
1253
2329
  if (exec?.agent && !callerMember) leadByTeam.set(args.teamId, exec.agent);
1254
2330
  const from = callerMember ? callerMember.memberId : 'lead';
1255
2331
  const toLead = String(args.to).trim().toLowerCase() === 'lead';
1256
- const runtime = await runtimeOfTeam(s, args.teamId);
1257
2332
  // sidecar 的收件人只能是成员 id、'*' 或虚拟收件人 'lead',所以先把 name / id 统一解析成成员行。
1258
- const st = runtime === 'agent' ? await request(s, `/api/status${qs({ team: args.teamId })}`) : null;
2333
+ const st = await request(s, `/api/status${qs({ team: args.teamId })}`);
1259
2334
  const members = st?.members || [];
1260
2335
  const resolve = (v) => members.find((m) => m.name === v || m.id === v) || null;
1261
2336
  if (!toLead && args.to !== '*' && (members.length ? !resolve(args.to) : false)) {
@@ -1271,8 +2346,8 @@ function buildTools(s, ctx) {
1271
2346
  ...(args.correlationId !== undefined ? { correlationId: args.correlationId } : {}),
1272
2347
  },
1273
2348
  });
1274
- // 成员→Lead 只落信箱(面板可见),不打扰 Lead 会话;worker 团队也没有可唤醒的 sub-agent。
1275
- if (runtime !== 'agent' || toLead) return recorded;
2349
+ // 成员→Lead 只落信箱(面板可见),不打扰 Lead 会话。
2350
+ if (toLead) return recorded;
1276
2351
 
1277
2352
  const subs = subagentsOf(ctx);
1278
2353
  // 成员之间互通必须借 Lead 的 agent 句柄:成员会话都挂在 Lead 下,成员直发会「belongs to another parent session」。
@@ -1392,110 +2467,102 @@ function buildTools(s, ctx) {
1392
2467
  });
1393
2468
 
1394
2469
  tools.push({
1395
- name: 'team_scope',
1396
- 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.',
2470
+ name: 'team_approve',
2471
+ description: 'Decide a permission approval raised by a member. When a member runs an operation its permission preset requires approval for (sandbox escalation / write outside the sandbox), the DSH approval request is forwarded to the Lead and the member is paused. Read the requestId/member/tool/reason from the forwarded message, then call team_approve with decision "allow" (authorize this one operation) or "deny". Only the Lead of that team can decide. If nobody decides before the timeout, the request is rejected automatically.',
1397
2472
  parameters: {
1398
2473
  type: 'object',
1399
2474
  additionalProperties: false,
1400
2475
  properties: {
1401
- action: { type: 'string', enum: ['list', 'request', 'decide'], description: 'Required operation.' },
1402
- teamId: { type: 'string', description: 'Required for list and request.' },
1403
- status: { type: 'string', description: 'For list: pending | approved | denied | expired.' },
1404
- memberId: { type: 'string', description: 'For request: the blocked member.' },
1405
- domain: { type: 'string', enum: ['fs', 'exec', 'net', 'env'] },
1406
- target: { type: 'string', description: 'Relative path, argv string, host:port, or env var name.' },
1407
- reason: { type: 'string' },
1408
- diffSize: { type: 'integer' },
1409
- risk: { type: 'string' },
1410
- blockedStep: { type: 'string' },
1411
- fallback: { type: 'string', description: 'What the member should do if denied.' },
1412
- requestId: { type: 'string', description: 'For decide.' },
1413
- decision: { type: 'string', enum: ['approved', 'denied'], description: 'For decide.' },
1414
- decidedBy: { type: 'string', description: 'Who decided; defaults to lead.' },
1415
- ttlSeconds: { type: 'integer', description: 'Grant lifetime in seconds. Default 60.' },
1416
- singleUse: { type: 'boolean', description: 'Default true: one use, then re-request.' },
2476
+ teamId: { type: 'string', description: 'Team id from the forwarded approval message.' },
2477
+ requestId: { type: 'string', description: 'Approval request id from the forwarded message.' },
2478
+ decision: { type: 'string', enum: ['allow', 'deny'], description: 'allow = authorize this single operation; deny = reject it.' },
2479
+ reason: { type: 'string', description: 'Optional reason shown in the audit trail and to the member.' },
1417
2480
  },
1418
- required: ['action'],
2481
+ required: ['teamId', 'requestId', 'decision'],
1419
2482
  },
1420
- output: jsonOutput('{ items? , scopeRequest?, decision?, grant? }'),
1421
- async execute(args) {
1422
- const action = args.action;
1423
- if (action === 'list') {
1424
- if (!args.teamId) throw new Error('team_scope list requires teamId');
1425
- return await request(s, `/api/scope-requests${qs({ team: args.teamId, status: args.status })}`);
1426
- }
1427
- if (action === 'request') {
1428
- if (!args.teamId || !args.memberId || !args.domain || !args.target) {
1429
- throw new Error('team_scope request requires teamId, memberId, domain, target');
1430
- }
1431
- const scopeRequest = await request(s, '/api/scope-requests', {
1432
- method: 'POST',
1433
- body: {
1434
- memberId: args.memberId,
1435
- teamId: args.teamId,
1436
- domain: args.domain,
1437
- target: args.target,
1438
- reason: args.reason || '',
1439
- ...(args.diffSize !== undefined ? { diffSize: args.diffSize } : {}),
1440
- ...(args.risk !== undefined ? { risk: args.risk } : {}),
1441
- ...(args.blockedStep !== undefined ? { blockedStep: args.blockedStep } : {}),
1442
- ...(args.fallback !== undefined ? { fallback: args.fallback } : {}),
1443
- },
1444
- });
1445
- return { scopeRequest };
1446
- }
1447
- if (action === 'decide') {
1448
- if (!args.requestId || !args.decision) throw new Error('team_scope decide requires requestId and decision');
1449
- return await request(s, `/api/scope-requests/${encodeURIComponent(args.requestId)}/decide`, {
1450
- method: 'POST',
1451
- body: {
1452
- decision: args.decision,
1453
- decidedBy: args.decidedBy || 'lead',
1454
- ...(args.reason !== undefined ? { reason: args.reason } : {}),
1455
- ...(args.ttlSeconds !== undefined ? { ttlSeconds: args.ttlSeconds } : {}),
1456
- ...(args.singleUse !== undefined ? { singleUse: args.singleUse } : {}),
1457
- },
1458
- });
2483
+ output: jsonOutput('{ requestId, decision, memberId, toolName, reason }'),
2484
+ async execute(args, exec) {
2485
+ const requestId = String(args.requestId || '').trim();
2486
+ if (!requestId) throw new Error('team_approve requires requestId');
2487
+ const entry = pendingApprovals.get(requestId);
2488
+ if (!entry) throw new Error('审批请求不存在或已处理(可能已超时)。请以成员收到的审批消息里的 requestId 为准。');
2489
+ if (String(entry.teamId) !== String(args.teamId)) throw new Error('teamId 与审批请求不匹配');
2490
+ const callerId = exec?.agent?.id != null ? String(exec.agent.id) : null;
2491
+ const team = await teamOf(s, entry.teamId).catch(() => null);
2492
+ const leadId = team?.leadSessionId ? String(team.leadSessionId) : (leadByTeam.get(entry.teamId)?.id != null ? String(leadByTeam.get(entry.teamId).id) : null);
2493
+ if (leadId && callerId && leadId !== callerId) {
2494
+ throw new Error('只有该团队的 Lead 可以审批这个请求');
1459
2495
  }
1460
- throw new Error(`team_scope unknown action: ${action}`);
2496
+ settleApproval(s, requestId, args.decision, args.reason || '', callerId || 'lead');
2497
+ return { requestId, decision: args.decision, memberId: entry.memberId, toolName: entry.toolName, reason: args.reason || null };
1461
2498
  },
1462
2499
  });
1463
2500
 
1464
2501
  tools.push({
1465
2502
  name: 'team_control',
1466
- 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.',
2503
+ description: 'Control one member. interrupt stops the sub-agent’s current turn and pauses its in-flight task (no retry, no attempt consumed); resume re-arms it; assign hands a ready task to an idle member; abort permanently voids a task (taskId) without retry.',
1467
2504
  parameters: {
1468
2505
  type: 'object',
1469
2506
  additionalProperties: false,
1470
2507
  properties: {
1471
- action: { type: 'string', enum: ['interrupt', 'resume', 'assign'] },
2508
+ action: { type: 'string', enum: ['interrupt', 'resume', 'assign', 'abort'] },
1472
2509
  teamId: { type: 'string', description: 'Required to control an agent-team member.' },
1473
- memberId: { type: 'string' },
1474
- taskId: { type: 'string', description: 'Required for assign.' },
1475
- reason: { type: 'string', description: 'For interrupt.' },
2510
+ memberId: { type: 'string', description: 'Required for interrupt/resume/assign.' },
2511
+ taskId: { type: 'string', description: 'Required for assign and abort.' },
2512
+ reason: { type: 'string', description: 'For interrupt/abort.' },
1476
2513
  },
1477
- required: ['action', 'memberId'],
2514
+ required: ['action'],
1478
2515
  },
1479
2516
  output: jsonOutput('{ member, ... }'),
1480
2517
  async execute(args, exec) {
2518
+ if (args.action === 'abort') {
2519
+ if (!args.taskId) throw new Error('team_control abort requires taskId');
2520
+ const res = await request(s, `/api/tasks/${encodeURIComponent(args.taskId)}/abort`, { method: 'POST', body: { reason: args.reason || 'lead abort' } });
2521
+ if (!res?.wasRunning || !res?.member?.agentSessionId) return res;
2522
+ const sid = String(res.member.agentSessionId);
2523
+ const subs = subagentsOf(ctx);
2524
+ const caller = exec?.agent;
2525
+ if (!subs || !caller || typeof subs.interrupt !== 'function') return res;
2526
+ cancelIdleReport(sid);
2527
+ cancelStartWatchdog(sid);
2528
+ agentStatusBySession.set(sid, 'interrupted');
2529
+ const interrupted = await Promise.resolve()
2530
+ .then(() => subs.interrupt(sid, { kind: 'ancestor', agent: caller }))
2531
+ .then(() => ({ ok: true, previousStatus: res.member.agentStatus ?? null }),
2532
+ (err) => ({ ok: false, error: String(err?.message || err) }));
2533
+ return { ...res, agent: interrupted };
2534
+ }
2535
+ if (!args.memberId) throw new Error(`team_control ${args.action} requires memberId`);
1481
2536
  const id = encodeURIComponent(args.memberId);
1482
2537
  if (args.action === 'interrupt') {
1483
2538
  const res = await request(s, `/api/members/${id}/interrupt`, { method: 'POST', body: { reason: args.reason || 'lead interrupt' } });
1484
- const runtime = args.teamId ? await runtimeOfTeam(s, args.teamId) : 'worker';
1485
- if (runtime === 'agent' && res?.member?.agentSessionId) {
2539
+ if (res?.member?.agentSessionId) {
2540
+ const sid = String(res.member.agentSessionId);
1486
2541
  const subs = subagentsOf(ctx);
1487
2542
  const caller = exec?.agent;
1488
2543
  if (subs && caller && typeof subs.interrupt === 'function') {
2544
+ // 冻结会话:直到 Lead resume 前,忽略该会话的 idle / turn-error 回报,
2545
+ // 否则 DSH 中断后的 idle 会把 sidecar 的 interrupted 覆盖成 idle,派发泵又能唤醒它。
2546
+ heldSessions.add(sid);
2547
+ cancelIdleReport(sid);
2548
+ cancelStartWatchdog(sid);
2549
+ agentStatusBySession.set(sid, 'interrupted');
1489
2550
  const interrupted = await Promise.resolve()
1490
- .then(() => subs.interrupt(String(res.member.agentSessionId), { kind: 'ancestor', agent: caller }))
2551
+ .then(() => subs.interrupt(sid, { kind: 'ancestor', agent: caller }))
1491
2552
  .then(() => ({ ok: true, previousStatus: res.member.agentStatus ?? null }),
1492
2553
  (err) => ({ ok: false, error: String(err?.message || err) }));
2554
+ if (!interrupted.ok) heldSessions.delete(sid);
1493
2555
  return { ...res, agent: interrupted };
1494
2556
  }
1495
2557
  }
1496
2558
  return res;
1497
2559
  }
1498
- if (args.action === 'resume') return await request(s, `/api/members/${id}/resume`, { method: 'POST', body: {} });
2560
+ if (args.action === 'resume') {
2561
+ const res = await request(s, `/api/members/${id}/resume`, { method: 'POST', body: {} });
2562
+ const sid = res?.member?.agentSessionId ? String(res.member.agentSessionId) : null;
2563
+ if (sid) heldSessions.delete(sid);
2564
+ return res;
2565
+ }
1499
2566
  if (args.action === 'assign') {
1500
2567
  if (!args.taskId) throw new Error('team_control assign requires taskId');
1501
2568
  return await request(s, `/api/members/${id}/assign`, { method: 'POST', body: { taskId: args.taskId } });
@@ -1504,9 +2571,191 @@ function buildTools(s, ctx) {
1504
2571
  },
1505
2572
  });
1506
2573
 
2574
+ tools.push({
2575
+ name: 'team_member',
2576
+ 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.",
2577
+ parameters: {
2578
+ type: 'object',
2579
+ additionalProperties: false,
2580
+ properties: {
2581
+ action: { type: 'string', enum: ['update', 'retire', 'remove'] },
2582
+ teamId: { type: 'string', description: 'Team id; omit to resolve from the current Lead session.' },
2583
+ memberId: { type: 'string', description: 'Member id returned by team_spawn / team_status.' },
2584
+ role: { type: 'string', description: 'update: new role label.' },
2585
+ model: { type: 'string', description: 'update: new LLM model id (empty to inherit). Rebuilds the session.' },
2586
+ agentProvider: { type: 'string', description: 'update: new LLM provider route id. Rebuilds the session.' },
2587
+ contextMode: { type: 'string', enum: ['isolated', 'fresh', 'fork'], description: 'update: new context isolation. Rebuilds the session; old context is lost.' },
2588
+ reasoningEffort: { type: 'string', description: 'update: new reasoning effort id. Rebuilds the session.' },
2589
+ permissionPreset: { type: 'string', description: 'update: DSH permission preset (sandbox + approvals). Applies to the live session without rebuild.' },
2590
+ agentPreset: { type: 'string', description: 'update: DSH agent preset (composition). Rebuilds the session; not supported with contextMode fork.' },
2591
+ confirm: { type: 'boolean', description: 'Required true for action=remove.' },
2592
+ },
2593
+ required: ['action', 'memberId'],
2594
+ },
2595
+ output: jsonOutput('{ member, restarted?, agent?, removed?, panel }'),
2596
+ async execute(args, exec) {
2597
+ const id = encodeURIComponent(args.memberId);
2598
+ const current = await request(s, `/api/members/${id}`);
2599
+ if (!current) throw new Error(`member not found: ${args.memberId}`);
2600
+ const team = await teamOf(s, args.teamId || current.teamId, { sessionId: exec?.agent?.id });
2601
+ if (current.teamId !== team.id) throw new Error('member 不属于指定团队');
2602
+
2603
+ if (args.action === 'retire' || args.action === 'remove') {
2604
+ if (args.action === 'remove' && args.confirm !== true) throw new Error('team_member remove requires confirm:true');
2605
+ const mode = args.action === 'remove' ? 'remove' : 'retire';
2606
+ const res = await request(s, `/api/members/${id}?mode=${mode}${mode === 'remove' ? '&confirm=1' : ''}`, { method: 'DELETE' });
2607
+ let agent = null;
2608
+ if (current.agentSessionId) {
2609
+ const released = await releaseSession(subagentsOf(ctx), exec?.agent, current.agentSessionId);
2610
+ forgetSession(current.agentSessionId);
2611
+ agent = {
2612
+ sessionId: String(current.agentSessionId),
2613
+ released: released.ok,
2614
+ method: released.method || null,
2615
+ ...(released.error ? { error: released.error } : {}),
2616
+ };
2617
+ }
2618
+ return { ...res, agent, panel: panelUrl(s) };
2619
+ }
2620
+
2621
+ if (args.action !== 'update') throw new Error(`team_member unknown action: ${args.action}`);
2622
+ if (current.status === 'retired') throw new Error('member is retired; create a new member instead');
2623
+ if (['running', 'provisioning', 'blocked'].includes(current.status)) {
2624
+ throw new Error(`member is ${current.status}; interrupt it before updating configuration`);
2625
+ }
2626
+
2627
+ const has = (key) => Object.prototype.hasOwnProperty.call(args, key);
2628
+ const metadata = {};
2629
+ for (const key of ['role', 'model', 'agentProvider', 'contextMode', 'reasoningEffort', 'permissionPreset', 'agentPreset']) {
2630
+ if (has(key)) metadata[key] = args[key];
2631
+ }
2632
+ const restart = ['model', 'agentProvider', 'contextMode', 'agentPreset', 'reasoningEffort'].some(has);
2633
+
2634
+ if (!restart) {
2635
+ const updated = await request(s, `/api/members/${id}`, { method: 'PATCH', body: metadata });
2636
+ let presetApplied = null;
2637
+ if (has('permissionPreset') && updated.agentSessionId) {
2638
+ presetApplied = applyPermissionPreset(ctx, String(updated.agentSessionId), updated.permissionPreset);
2639
+ }
2640
+ return {
2641
+ member: updated,
2642
+ restarted: false,
2643
+ agent: { sessionId: updated.agentSessionId || null, permissionPresetApplied: presetApplied },
2644
+ panel: panelUrl(s),
2645
+ };
2646
+ }
2647
+
2648
+ const subs = subagentsOf(ctx);
2649
+ const caller = exec?.agent;
2650
+ if (!subs || typeof subs.startActivation !== 'function') throw new Error('subagents 服务不可用:无法重建成员会话');
2651
+ if (!caller) throw new Error('team_member update 需要 Lead 会话上下文(exec.agent 缺失)');
2652
+
2653
+ const leadRoute = leadRouteOf(caller);
2654
+ const oldRoute = {
2655
+ provider: current.agentProvider ?? leadRoute.provider ?? null,
2656
+ model: current.model ?? leadRoute.model ?? null,
2657
+ reasoningEffort: current.reasoningEffort ?? null,
2658
+ };
2659
+ const route = {
2660
+ provider: has('agentProvider') ? (args.agentProvider || null) : oldRoute.provider,
2661
+ model: has('model') ? (args.model || null) : oldRoute.model,
2662
+ reasoningEffort: has('reasoningEffort') ? (args.reasoningEffort || null) : oldRoute.reasoningEffort,
2663
+ };
2664
+ const routeChanged = route.provider !== oldRoute.provider || route.model !== oldRoute.model;
2665
+ if (routeChanged && !has('reasoningEffort')) route.reasoningEffort = null;
2666
+ await assertRouteEnabled(s, ctx, route.provider, route.model, route.reasoningEffort);
2667
+
2668
+ const context = has('contextMode')
2669
+ ? (args.contextMode === 'fork' ? 'fork' : 'fresh')
2670
+ : (current.contextMode === 'fork' ? 'fork' : 'fresh');
2671
+ let requestedAgentPreset = has('agentPreset')
2672
+ ? await resolveAgentPreset(ctx, args.agentPreset, team.agentPreset, s)
2673
+ : (current.agentPreset || team.agentPreset || null);
2674
+ if (context !== 'fork' && !requestedAgentPreset) {
2675
+ requestedAgentPreset = await hostDefaultAgentPreset(ctx);
2676
+ }
2677
+ const agentPreset = context === 'fork' ? null : requestedAgentPreset;
2678
+ const agentPresetWarning = context === 'fork' && requestedAgentPreset
2679
+ ? `contextMode=fork 继承 Lead 的组装,agentPreset「${requestedAgentPreset}」未生效`
2680
+ : undefined;
2681
+ const permissionPreset = has('permissionPreset')
2682
+ ? resolvePermissionPreset(ctx, args.permissionPreset, team.permissionPreset)
2683
+ : (current.permissionPreset || team.permissionPreset);
2684
+ const role = has('role') ? args.role : current.role;
2685
+
2686
+ const provider = providerFor(ctx, s, context);
2687
+ const agentOptions = {};
2688
+ if (route.provider) agentOptions.provider = String(route.provider);
2689
+ if (route.model) agentOptions.model = String(route.model);
2690
+ if (route.reasoningEffort) agentOptions.reasoningEffort = String(route.reasoningEffort);
2691
+
2692
+ const sessionId = randomUUID();
2693
+ const started = await subs.startActivation({
2694
+ delivery: 'parent',
2695
+ childId: sessionId,
2696
+ provider,
2697
+ label: memberLabel(current.name, String(role || current.name)),
2698
+ request: {
2699
+ prompt: [{ type: 'text', text: `你是团队成员 ${current.name}(${role || 'teammate'})。配置刚刚更新,这是新的会话;当前没有任务,等待 Lead 派发。收到任务后按简报执行,完成时调用 team_report_task。` }],
2700
+ parent: caller,
2701
+ ...(team.workspace ? { cwd: team.workspace } : {}),
2702
+ ...(Object.keys(agentOptions).length ? { agentOptions } : {}),
2703
+ ...(agentPreset ? { agentPreset } : {}),
2704
+ },
2705
+ signal: exec.signal || AbortSignal.timeout(s.requestTimeoutMs),
2706
+ });
2707
+ if (started && started.result && typeof started.result.catch === 'function') started.result.catch(() => {});
2708
+ const presetResult = applyPermissionPreset(ctx, sessionId, permissionPreset);
2709
+
2710
+ await request(s, '/api/agents/register', {
2711
+ method: 'POST',
2712
+ body: {
2713
+ teamId: team.id,
2714
+ name: current.name,
2715
+ sessionId,
2716
+ parentSessionId: caller.id != null ? String(caller.id) : null,
2717
+ role,
2718
+ model: route.model,
2719
+ contextMode: context,
2720
+ agentProvider: route.provider,
2721
+ permissionPreset,
2722
+ agentPreset, // explicit null = clear old override
2723
+ reasoningEffort: route.reasoningEffort,
2724
+ },
2725
+ });
2726
+ // 只把调用方显式改的字段写回元数据并记 member.update;不要用解析后的
2727
+ // 继承值覆盖成员覆盖项,否则团队预设以后变更时该成员不会再跟随。
2728
+ const updated = await request(s, `/api/members/${id}`, { method: 'PATCH', body: metadata });
2729
+ const release = await releaseSession(subs, caller, current.agentSessionId);
2730
+ forgetSession(current.agentSessionId);
2731
+ rememberMember(sessionId, team.id, updated.id, team.workspace, updated.permissionPreset || permissionPreset, current.name);
2732
+ leadByTeam.set(team.id, caller);
2733
+ return {
2734
+ member: updated,
2735
+ restarted: true,
2736
+ agent: {
2737
+ sessionId,
2738
+ previousSessionId: current.agentSessionId ? String(current.agentSessionId) : null,
2739
+ provider,
2740
+ context,
2741
+ model: route.model,
2742
+ route,
2743
+ release,
2744
+ },
2745
+ permissionPreset: updated.permissionPreset || permissionPreset,
2746
+ agentPreset: updated.agentPreset || agentPreset || null,
2747
+ ...(agentPresetWarning ? { agentPresetWarning } : {}),
2748
+ permissionPresetApplied: presetResult.applied,
2749
+ ...(presetResult.reason ? { permissionPresetWarning: presetResult.reason } : {}),
2750
+ ...(presetResult.error ? { permissionPresetWarning: presetResult.error } : {}),
2751
+ panel: panelUrl(s),
2752
+ };
2753
+ },
2754
+ });
2755
+
1507
2756
  tools.push({
1508
2757
  name: 'team_report',
1509
- 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.',
2758
+ description: 'Export a Markdown run report: members, tasks/DAG, permission approvals (who asked for what, who decided), and the audit table with actor, action, target, and full before/after SHA-256 hashes. Use it for review, handoff, or proving who changed which file.',
1510
2759
  parameters: {
1511
2760
  type: 'object',
1512
2761
  additionalProperties: false,
@@ -1521,6 +2770,65 @@ function buildTools(s, ctx) {
1521
2770
  },
1522
2771
  });
1523
2772
 
2773
+
2774
+ tools.push({
2775
+ name: 'board_plan_submit',
2776
+ description: 'Submit the finished plan for the current workspace-board task. Call this at the end of the planning session; the scheduler stores the plan and moves the task to planned. In same-session mode the task will later resume this session for execution.',
2777
+ parameters: {
2778
+ type: 'object',
2779
+ additionalProperties: false,
2780
+ properties: {
2781
+ plan: { type: 'string', description: 'Complete plan in markdown.' },
2782
+ summary: { type: 'string', description: 'One-line summary.' },
2783
+ },
2784
+ required: ['plan'],
2785
+ },
2786
+ output: jsonOutput('{ board task }'),
2787
+ async execute(args, exec) {
2788
+ const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
2789
+ if (!sessionId) throw new Error('board_plan_submit 只能在规划会话里调用');
2790
+ const task = await request(s, '/api/board/agents/plan', {
2791
+ method: 'POST',
2792
+ body: { sessionId, plan: args.plan, summary: args.summary || null },
2793
+ });
2794
+ const rec = boardSessions.get(sessionId);
2795
+ if (rec) rec.phase = 'planned';
2796
+ if (task?.executionMode === 'new' && rec) {
2797
+ const timer = setTimeout(() => {
2798
+ if (rec.phase !== 'planned') return;
2799
+ try { void rec.handle?.dispose?.(); } catch { /* ignore */ }
2800
+ boardSessions.delete(sessionId);
2801
+ boardSessionIds.delete(sessionId);
2802
+ }, 5000);
2803
+ timer.unref?.();
2804
+ }
2805
+ return task;
2806
+ },
2807
+ });
2808
+
2809
+ tools.push({
2810
+ name: 'board_task_status',
2811
+ description: 'Report the current workspace-board task status from the Lead session. Call status "done" after all team tasks succeed, "failed" when the task cannot be completed, and "inprogress" when the user sends a new message after a finished task.',
2812
+ parameters: {
2813
+ type: 'object',
2814
+ additionalProperties: false,
2815
+ properties: {
2816
+ status: { type: 'string', enum: ['done', 'failed', 'inprogress'] },
2817
+ summary: { type: 'string', description: 'Short result or failure reason.' },
2818
+ },
2819
+ required: ['status'],
2820
+ },
2821
+ output: jsonOutput('{ board task }'),
2822
+ async execute(args, exec) {
2823
+ const sessionId = exec?.agent?.id != null ? String(exec.agent.id) : null;
2824
+ if (!sessionId) throw new Error('board_task_status 只能在看板 Lead 会话里调用');
2825
+ return await request(s, '/api/board/agents/status', {
2826
+ method: 'POST',
2827
+ body: { sessionId, status: args.status, summary: args.summary || null },
2828
+ });
2829
+ },
2830
+ });
2831
+
1524
2832
  return tools;
1525
2833
  }
1526
2834
 
@@ -1828,7 +3136,7 @@ export function apply(ctx, config) {
1828
3136
  const disposers = buildTools(s, ctx).map((tool) => ctx.tools.register(tool));
1829
3137
  return () => {
1830
3138
  for (const dispose of disposers.reverse()) { try { dispose(); } catch { /* ignore */ } }
1831
- leadByTeam.clear(); runtimeByTeam.clear(); sessionMember.clear(); dispatching.clear(); teamBySession.clear(); contextReportAt.clear();
3139
+ leadByTeam.clear(); teamCache.clear(); sessionMember.clear(); dispatching.clear(); teamBySession.clear(); contextReportAt.clear();
1832
3140
  for (const timer of idleTimers.values()) clearTimeout(timer);
1833
3141
  for (const timer of startTimers.values()) clearTimeout(timer);
1834
3142
  idleTimers.clear(); startTimers.clear(); agentStatusBySession.clear(); lastReplyBySession.clear();
@@ -1839,6 +3147,29 @@ export function apply(ctx, config) {
1839
3147
  };
1840
3148
  }, 'dsh-team.tools()');
1841
3149
 
3150
+ // Leader 自建 agentPreset:启动时把固定目录里的 JSON 文档注册进宿主,卸载时反注册。
3151
+ // 注册失败不阻断插件:工具仍可 list/show/save,错误从返回值里看。
3152
+ ctx.effect(() => {
3153
+ teamPresetsReady = null;
3154
+ teamPresetLoading = null;
3155
+ void ensureTeamPresets(s, ctx).then(() => syncPresetCatalog(s, ctx)).catch(() => null);
3156
+ let presetTicks = 0;
3157
+ const presetTimer = setInterval(() => {
3158
+ void processPresetDeletes(s, ctx).catch(() => null);
3159
+ // sidecar 可能比插件晚就绪:每 30s 补一次目录同步,面板不会一直空着。
3160
+ if (++presetTicks % 6 === 0) void syncPresetCatalog(s, ctx).catch(() => null);
3161
+ }, 5000);
3162
+ presetTimer.unref?.();
3163
+ return () => {
3164
+ clearInterval(presetTimer);
3165
+ const pending = [...teamPresetDisposers.values()];
3166
+ teamPresetDisposers.clear();
3167
+ teamPresetsReady = null;
3168
+ teamPresetLoading = null;
3169
+ for (const dispose of pending) { try { void dispose(); } catch { /* ignore */ } }
3170
+ };
3171
+ }, 'dsh-team.presets()');
3172
+
1842
3173
  // 技能:skills 服务在场时把包内 `skills/` 注册成 provider,装上插件就带 `dsh-agent-team` 技能;
1843
3174
  // 服务缺失(老版本/测试假 ctx)时静默跳过,不影响工具面。
1844
3175
  if (typeof ctx.inject === 'function') {
@@ -1851,6 +3182,16 @@ export function apply(ctx, config) {
1851
3182
  });
1852
3183
  }
1853
3184
 
3185
+ // 成员权限审批:preset 的 approval=ask 触发时,把请求转给 Lead,由 team_approve 决定。
3186
+ // 放在最前面(prepend),确保本插件的成员请求不会再弹出宿主审批 UI。
3187
+ ctx.effect(() => {
3188
+ const off = ctx.on('approval/request', (req, next) => onApprovalRequest(s, ctx, req, next), { prepend: true });
3189
+ return () => {
3190
+ try { off?.(); } catch { /* ignore */ }
3191
+ cancelPendingApprovals();
3192
+ };
3193
+ }, 'dsh-team.approval()');
3194
+
1854
3195
  if (s.reportToolCalls) {
1855
3196
  ctx.on('tools/execute', (exec, next) => traceToolCall(s, ctx, exec, next));
1856
3197
  }
@@ -1901,6 +3242,13 @@ export function apply(ctx, config) {
1901
3242
  agentStatusBySession.set(sessionId, 'running');
1902
3243
  return;
1903
3244
  }
3245
+ // Lead interrupt 后会话处于冻结态:DSH 中断引发的 idle 不能把成员改回 idle,
3246
+ // 否则 sidecar 认为成员可派发,下一次派发泵又会把它唤醒。
3247
+ if (status === 'idle' && heldSessions.has(sessionId)) {
3248
+ cancelIdleReport(sessionId);
3249
+ agentStatusBySession.set(sessionId, 'interrupted');
3250
+ return;
3251
+ }
1904
3252
  if (status !== 'idle') {
1905
3253
  cancelIdleReport(sessionId);
1906
3254
  agentStatusBySession.set(sessionId, status);
@@ -1914,6 +3262,7 @@ export function apply(ctx, config) {
1914
3262
  const settle = Math.max(0, Number(s.agentIdleSettleMs) || 0);
1915
3263
  const finish = () => {
1916
3264
  idleTimers.delete(sessionId);
3265
+ if (heldSessions.has(sessionId)) { agentStatusBySession.set(sessionId, 'interrupted'); return; }
1917
3266
  if (agentStatusBySession.get(sessionId) !== 'idle') return; // 窗口内又跑起来了
1918
3267
  // 把这一轮最后的正文带给 sidecar:漏调 team_report_task 时,兜底收尾的 task.done 也有摘要可看
1919
3268
  const reply = lastReplyBySession.get(sessionId);
@@ -1941,6 +3290,8 @@ export function apply(ctx, config) {
1941
3290
  if (event && event.type === 'turn/end') {
1942
3291
  const reason = event.data?.reason;
1943
3292
  if (reason && reason.kind === 'error') {
3293
+ // 冻结中的会话:中断本身可能让回合以 error 结束,不要覆盖 sidecar 的 interrupted。
3294
+ if (heldSessions.has(sessionId)) return;
1944
3295
  const err = reason.error || {};
1945
3296
  const msg = String(err.message || err.code || 'unknown error').slice(0, 500);
1946
3297
  cancelIdleReport(sessionId);
@@ -1964,6 +3315,15 @@ export function apply(ctx, config) {
1964
3315
  return () => clearInterval(timer);
1965
3316
  }, 'dsh-team.agent-heartbeat()');
1966
3317
 
3318
+ // 面板/看板停止的强制收尾:sidecar 只把成员置 interrupted,真正中断 DSH 会话在这里做。
3319
+ ctx.effect(() => {
3320
+ const timer = setInterval(() => {
3321
+ void forceStopPump(s, ctx).catch(() => { /* ignore */ });
3322
+ }, Math.max(250, s.forceStopPollMs));
3323
+ timer.unref?.();
3324
+ return () => clearInterval(timer);
3325
+ }, 'dsh-team.force-stop-pump()');
3326
+
1967
3327
  // 成员上下文快照:面板「上下文分析」页的数据来源。周期泵覆盖进行中的回合,
1968
3328
  // agent/status 变化时补报一次(回合结束/中断后上下文占用才定型)。
1969
3329
  if (s.reportContext) {
@@ -2019,6 +3379,87 @@ export function apply(ctx, config) {
2019
3379
  }, 'dsh-team.llm-catalog-pump()');
2020
3380
  }
2021
3381
 
3382
+ // 看板会话审批:规划阶段只读,任何审批直接拒绝,避免无人值守卡住。
3383
+ // 执行阶段用 danger-full-access(never),正常情况下不会走到这里。
3384
+ if (s.boardEnabled) {
3385
+ ctx.effect(() => {
3386
+ const off = ctx.on('approval/request', (req, next) => {
3387
+ const sessionId = req?.agent?.id != null ? String(req.agent.id) : null;
3388
+ const rec = sessionId ? boardSessions.get(sessionId) : null;
3389
+ if (rec && rec.phase === 'planning') return 'rejected';
3390
+ return next();
3391
+ }, { prepend: true });
3392
+ return () => { try { off?.(); } catch { /* ignore */ } };
3393
+ }, 'dsh-team.board-approval()');
3394
+ }
3395
+
3396
+ // 看板会话的后续用户消息:done/failed 被追问时翻回 inprogress(sidecar 只对这些状态生效)。
3397
+ // 自己注入的首条 prompt 也会触发,但此时状态是 planning/inprogress,sidecar 会拒绝,不会误翻。
3398
+ ctx.on('session/event', (session, event) => {
3399
+ const sessionId = session?.id != null ? String(session.id) : null;
3400
+ if (!sessionId || !boardSessionIds.has(sessionId)) return;
3401
+ if (!event || event.type !== 'user/message') return;
3402
+ void request(s, '/api/board/agents/status', {
3403
+ method: 'POST', body: { sessionId, status: 'inprogress' },
3404
+ }).catch(() => { /* 非终态时 sidecar 会拒绝,忽略 */ });
3405
+ });
3406
+
3407
+ // 规划会话 idle 却没有提交计划:给工具收尾留一个宽限窗口,仍停在 planning 就判失败。
3408
+ ctx.on('agent/status', ({ agent, status } = {}) => {
3409
+ const sessionId = agent?.id != null ? String(agent.id) : null;
3410
+ const rec = sessionId ? boardSessions.get(sessionId) : null;
3411
+ if (!rec) return;
3412
+ if (status === 'running') { rec.sawRunning = true; return; }
3413
+ if (status !== 'idle' || rec.phase !== 'planning' || !rec.sawRunning) return;
3414
+ const timer = setTimeout(() => {
3415
+ void (async () => {
3416
+ if (rec.phase !== 'planning') return;
3417
+ try {
3418
+ const task = await request(s, `/api/board/tasks/${encodeURIComponent(rec.taskId)}`);
3419
+ if (task?.status !== 'planning') return;
3420
+ await request(s, '/api/board/agents/status', {
3421
+ method: 'POST', body: { sessionId, status: 'failed', summary: '规划会话空闲但未提交计划' },
3422
+ });
3423
+ } catch { /* ignore */ }
3424
+ })();
3425
+ }, Math.max(0, s.boardIdleGraceMs));
3426
+ timer.unref?.();
3427
+ });
3428
+
3429
+ // 把 DSH Web 的浏览器地址报给 sidecar:独立面板据此 window.open 到 `#dsh-session=<id>`
3430
+ // 深链,由 dsh-plugin-ui 的客户端半边接管并打开对应会话。
3431
+ ctx.effect(() => {
3432
+ const report = () => {
3433
+ try {
3434
+ const ws = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined;
3435
+ if (!ws || !ws.port) return;
3436
+ const host = String(ws.host || '127.0.0.1');
3437
+ const authority = host.includes(':') ? `[${host}]` : host;
3438
+ const proto = ws.config?.tls ? 'https' : 'http';
3439
+ void request(s, '/api/host/web', { method: 'POST', body: { url: `${proto}://${authority}:${ws.port}` } })
3440
+ .catch(() => { /* sidecar 未就绪时下一轮再报 */ });
3441
+ } catch { /* 宿主没有 webServer 服务时跳过 */ }
3442
+ };
3443
+ report();
3444
+ const timer = setInterval(report, 60000);
3445
+ timer.unref?.();
3446
+ return () => clearInterval(timer);
3447
+ }, 'dsh-team.host-web()');
3448
+
3449
+ // 看板调度泵:每个 tick 向 sidecar claim 规划/执行槽位,claim 到就建会话并投 prompt。
3450
+ if (s.boardEnabled) {
3451
+ ctx.effect(() => {
3452
+ const timer = setInterval(() => { void boardPump(s, ctx).catch(() => { /* ignore */ }); }, Math.max(500, s.boardDispatchMs));
3453
+ timer.unref?.();
3454
+ return () => {
3455
+ clearInterval(timer);
3456
+ for (const rec of boardSessions.values()) { try { void rec.handle?.dispose?.(); } catch { /* ignore */ } }
3457
+ boardSessions.clear();
3458
+ boardSessionIds.clear();
3459
+ };
3460
+ }, 'dsh-team.board-pump()');
3461
+ }
3462
+
2022
3463
  // 保底泵:负责 lead 不在工具调用栈里时(例如成员直接回报)把 ready 任务继续发出去。
2023
3464
  if (s.agentAutoDispatch) {
2024
3465
  ctx.effect(() => {
@@ -2031,4 +3472,13 @@ export function apply(ctx, config) {
2031
3472
  return () => clearInterval(timer);
2032
3473
  }, 'dsh-team.agent-pump()');
2033
3474
  }
3475
+
3476
+ // steer 泵:把面板排进 sidecar 的队列消息(kind='steer')推进成员会话。
3477
+ ctx.effect(() => {
3478
+ const timer = setInterval(() => {
3479
+ void steerPump(s, ctx).catch(() => { /* ignore */ });
3480
+ }, Math.max(500, s.steerPollMs));
3481
+ timer.unref?.();
3482
+ return () => clearInterval(timer);
3483
+ }, 'dsh-team.steer-pump()');
2034
3484
  }