dsh-team-control 0.1.6 → 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 (3) hide show
  1. package/README.md +55 -53
  2. package/index.js +1521 -163
  3. 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
 
@@ -184,7 +198,7 @@ const qs = (obj) => {
184
198
  /** teamId → 最近一次调用 team_* 工具的 Lead Agent(发消息必须由 live Lead 发出)。 */
185
199
  const leadByTeam = new Map();
186
200
  /** teamId → 'worker' | 'agent',建团/查团缓存,省掉每次多一次 GET。 */
187
- const runtimeByTeam = new Map();
201
+ const teamCache = new Map();
188
202
  /** DSH sessionId → { teamId, memberId }:把成员的工具 span 归到成员节点下。 */
189
203
  const sessionMember = new Map();
190
204
  /** DSH sessionId → 上次采集产物时的会话 seq:成员复用同一会话时只上报新产生的文件。 */
@@ -668,35 +682,308 @@ async function assertRouteEnabled(s, ctx, provider, model, effort = null) {
668
682
  }
669
683
  }
670
684
 
671
- function rememberMember(sessionId, teamId, memberId, cwd) {
685
+ function rememberMember(sessionId, teamId, memberId, cwd, permissionPreset = null, name = null) {
672
686
  if (sessionId == null) return;
673
687
  const key = String(sessionId);
674
688
  const prev = sessionMember.get(key);
675
689
  // 会话 cwd 只有 spawn 时知道(= team.workspace);派发路径会重复登记同一个会话,
676
690
  // 这里不能把它冲成空,否则成员用相对路径写文件时 diff 找不到落盘位置。
677
- 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
+ });
678
698
  }
679
699
 
680
- async function runtimeOfTeam(s, teamId) {
681
- // 模型偶尔会漏掉必填的 teamId。旧实现会把 undefined 拼进 URL(/api/teams/undefined),
682
- // 再被下面的 catch 静默回退成 worker,于是错误被拖到 POST /api/teams/undefined/members
683
- // 才爆成「team not found」,看不出真正原因是参数缺失。这里先显式挡住。
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
+ }
684
708
  if (teamId == null || String(teamId).trim() === '' || String(teamId) === 'undefined' || String(teamId) === 'null') {
685
- throw new Error('缺少 teamId:请把 team_create 返回的团队 id(形如 team_xxx)作为 teamId 参数传入后重试。');
709
+ throw new Error('缺少 teamId:请把 team_create 返回的 result.team.id(形如 team_xxx)作为 teamId 参数传入后重试。');
686
710
  }
687
711
  const key = String(teamId);
688
- const cached = runtimeByTeam.get(key);
689
- if (cached) return cached;
712
+ if (!refresh && teamCache.has(key)) return teamCache.get(key);
690
713
  try {
691
714
  const team = await request(s, `/api/teams/${encodeURIComponent(key)}`);
692
- runtimeByTeam.set(key, team.runtime || 'worker');
693
- return team.runtime || 'worker';
715
+ teamCache.set(key, team);
716
+ return team;
694
717
  } catch (err) {
695
- // 404 = 团队不存在(id 打错/已删除):明确报错,不能伪装成 worker 团队继续往下走。
696
718
  if (err && err.status === 404) {
697
719
  throw new Error(`团队不存在或 teamId 无效: ${key}(teamId 来自 team_create 返回值,请核对后重试)`);
698
720
  }
699
- return 'worker'; // sidecar 不可达等其余情况保留原兜底,后续调用会报出真实错误
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;
773
+ }
774
+
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) {
788
+ try {
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) };
700
987
  }
701
988
  }
702
989
 
@@ -708,13 +995,10 @@ const clip = (text, max) => {
708
995
  /** 成员收到的一条任务说明:必须包含 teamId / taskId 和「跑完怎么回报」。 */
709
996
  function taskBrief(teamId, task, member) {
710
997
  const plan = (task.plan || []).map((p, i) => {
711
- const kind = p.op?.kind || p.action || p.phase || 'do';
712
- const target = p.target ? ` → ${p.target}` : '';
713
- const args = p.op?.args ? ` ${clip(JSON.stringify(p.op.args), 300)}` : '';
714
- 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}`;
715
1000
  });
716
1001
  const deps = (task.dependsOn || []).length ? `\n依赖(已完成):${task.dependsOn.join(', ')}` : '';
717
- const scopes = (task.writeScopes || []).length ? `\n写域(写入请限制在这些前缀内):${task.writeScopes.join(', ')}` : '';
718
1002
  const acceptance = task.acceptance ? `\n验收标准:${task.acceptance}` : '';
719
1003
  return [
720
1004
  '【dsh-team 任务派发】',
@@ -725,7 +1009,6 @@ function taskBrief(teamId, task, member) {
725
1009
  `subject:${task.subject}`,
726
1010
  ...(plan.length ? ['计划步骤:', ...plan] : []),
727
1011
  ...(deps ? [deps.trim()] : []),
728
- ...(scopes ? [scopes.trim()] : []),
729
1012
  ...(acceptance ? [acceptance.trim()] : []),
730
1013
  '',
731
1014
  '执行要求:',
@@ -787,7 +1070,7 @@ async function dispatchLoop(s, ctx, teamId) {
787
1070
  }
788
1071
  const { task, member } = r;
789
1072
  // 先记绑定再投递:成员第一轮 LLM 调用可能在 sendMessage 返回后就已开始
790
- if (member.agentSessionId) rememberMember(member.agentSessionId, teamId, member.id);
1073
+ if (member.agentSessionId) rememberMember(member.agentSessionId, teamId, member.id, null, member.permissionPreset, member.name);
791
1074
  // 任务已投递:先按「在跑」记账,agent/status 的 running 事件可能因为状态未变化而不发
792
1075
  if (member.agentSessionId) agentStatusBySession.set(String(member.agentSessionId), 'running');
793
1076
  try {
@@ -810,6 +1093,124 @@ async function dispatchLoop(s, ctx, teamId) {
810
1093
  }
811
1094
  }
812
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
+
813
1214
  /** agent/status 回写 sidecar:idle 时兜底收尾在途任务,running 时置 running。 */
814
1215
  function reportAgentStatus(s, sessionId, status, detail) {
815
1216
  if (!sessionId) return;
@@ -828,6 +1229,8 @@ const agentStatusBySession = new Map();
828
1229
  const idleTimers = new Map();
829
1230
  /** sessionId → 派发后「成员会话是否真的跑起来」的监视定时器。 */
830
1231
  const startTimers = new Map();
1232
+ /** Lead 主动 interrupt 后冻结的会话:在 resume 前忽略其 idle / turn-error 回报。 */
1233
+ const heldSessions = new Set();
831
1234
 
832
1235
  function cancelIdleReport(sessionId) {
833
1236
  const timer = idleTimers.get(sessionId);
@@ -860,6 +1263,43 @@ function cancelStartWatchdog(sessionId) {
860
1263
  if (timer) { clearTimeout(timer); startTimers.delete(sessionId); }
861
1264
  }
862
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
+
863
1303
  /** 直接读 sidecar /status(不经 request:心跳/镜像不能顺手把 sidecar 拉起来)。 */
864
1304
  async function readStatus(s) {
865
1305
  try {
@@ -872,6 +1312,46 @@ async function readStatus(s) {
872
1312
  } catch { return null; }
873
1313
  }
874
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
+
875
1355
  /** DSH 内置 todo 的状态 → sidecar 计划步骤的状态。 */
876
1356
  const TODO_TO_PLAN = { pending: 'open', in_progress: 'active', completed: 'done' };
877
1357
 
@@ -935,6 +1415,63 @@ async function markDelivered(s, messageId) {
935
1415
  }).catch(() => { /* 回执补记失败不影响投递 */ });
936
1416
  }
937
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
+
938
1475
  /** 成员会话这一轮最后的助手正文:收工时落库成 member→lead 的回复消息。 */
939
1476
  const lastReplyBySession = new Map();
940
1477
 
@@ -978,28 +1515,19 @@ async function flushMemberReply(s, sessionId) {
978
1515
  const PLAN_STEP = {
979
1516
  type: 'object',
980
1517
  additionalProperties: true,
981
- 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.',
982
1519
  properties: {
983
1520
  step: { type: 'string', description: 'Step label, e.g. S1.' },
984
1521
  phase: {
985
1522
  type: 'string',
986
- 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.',
987
1524
  },
988
1525
  action: { type: 'string', description: 'Verb shown in the timeline, e.g. write / read / exec.' },
989
1526
  target: { type: 'string', description: 'File path, command, host, or env name this step touches.' },
990
- op: {
991
- type: 'object',
992
- additionalProperties: true,
993
- 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.',
994
- properties: { kind: { type: 'string' } },
995
- required: ['kind'],
996
- },
997
- onDenied: { type: 'string', enum: ['scope'], description: "Escalate a denied action into a scope request instead of failing the task." },
998
- scopeReason: { type: 'string' },
999
- scopeTimeoutMs: { type: 'integer' },
1527
+ op: { type: 'object', additionalProperties: true, description: 'Optional legacy detail (ignored by the sidecar).' },
1000
1528
  fatal: { type: 'boolean' },
1001
1529
  },
1002
- required: ['step', 'op'],
1530
+ required: ['step'],
1003
1531
  };
1004
1532
 
1005
1533
  const MEMBER_FIELDS = {
@@ -1022,35 +1550,403 @@ const textOutput = () => ({
1022
1550
  render: (_args, value) => [{ type: 'text', text: String(value?.markdown ?? value) }],
1023
1551
  });
1024
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
+
1025
1915
  /** 构造全部工具(普通 ToolDefinition,不依赖 defineTool;参数即 JSON Schema)。 */
1026
1916
  function buildTools(s, ctx) {
1027
1917
  const tools = [];
1028
1918
 
1029
1919
  tools.push({
1030
1920
  name: 'team_create',
1031
- 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".',
1032
1922
  parameters: {
1033
1923
  type: 'object',
1034
1924
  additionalProperties: false,
1035
1925
  properties: {
1036
1926
  name: { type: 'string', description: 'Team name.' },
1037
- workspace: { type: 'string', description: 'Absolute directory shared by workers; created if missing.' },
1038
- 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.' },
1039
1930
  maxMembers: { type: 'integer', description: 'Member cap, 0 means unlimited. Default 64. Extra members are queued, never errors.' },
1040
1931
  maxConcurrency: { type: 'integer', description: 'Max simultaneously running tasks. Default 8.' },
1041
1932
  failurePolicy: { type: 'string', enum: ['continue', 'abort'], description: 'Team-level default failure policy.' },
1042
1933
  maxAttempts: { type: 'integer', description: 'Per-task retry cap. Default 3.' },
1934
+ force: { type: 'boolean', description: '仅看板任务相关:该任务已关联团队时默认禁止重复建队(重试应继续用原团队);确认需要与之并行新建团队时传 true。' },
1043
1935
  },
1044
1936
  required: ['name', 'workspace'],
1045
1937
  },
1046
1938
  output: jsonOutput('{ team, panel }'),
1047
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);
1048
1943
  const team = await request(s, '/api/teams', {
1049
1944
  method: 'POST',
1050
1945
  body: {
1051
1946
  name: args.name,
1052
1947
  workspace: args.workspace,
1053
- ...(args.runtime !== undefined ? { runtime: args.runtime } : {}),
1948
+ permissionPreset,
1949
+ ...(agentPreset ? { agentPreset } : {}),
1054
1950
  ...(args.maxMembers !== undefined ? { maxMembers: args.maxMembers } : {}),
1055
1951
  ...(args.maxConcurrency !== undefined ? { maxConcurrency: args.maxConcurrency } : {}),
1056
1952
  ...(args.failurePolicy !== undefined ? { failurePolicy: args.failurePolicy } : {}),
@@ -1058,73 +1954,98 @@ function buildTools(s, ctx) {
1058
1954
  ...(exec?.agent && exec.agent.id != null ? { leadSessionId: String(exec.agent.id) } : {}),
1059
1955
  },
1060
1956
  });
1061
- runtimeByTeam.set(team.id, team.runtime || 'worker');
1957
+ teamCache.set(team.id, team);
1062
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);
1063
1962
  return { team, panel: panelUrl(s) };
1064
1963
  },
1065
1964
  });
1066
1965
 
1067
1966
  tools.push({
1068
1967
  name: 'team_spawn',
1069
- 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.",
1070
1969
  parameters: {
1071
1970
  type: 'object',
1072
1971
  additionalProperties: false,
1073
1972
  properties: {
1074
- teamId: { type: 'string', description: 'Team id from team_create.' },
1973
+ teamId: { type: 'string', description: 'team_create 返回的 result.team.id(形如 team_xxx)。漏传时自动使用当前会话刚创建的团队。' },
1075
1974
  name: { type: 'string', description: 'Unique member name inside the team; this is the addressable target.' },
1076
- role: { type: 'string', description: 'Role label, also usable as a policy subject (subjectType=role).' },
1077
- 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.' },
1078
- 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.' },
1079
- 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.' },
1080
- 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.' },
1081
- 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.' },
1082
- 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.' },
1083
1984
  },
1084
- required: ['teamId', 'name'],
1985
+ required: ['teamId', 'name', 'prompt'],
1085
1986
  },
1086
- output: jsonOutput('{ member, agent?, panel }'),
1987
+ output: jsonOutput('{ member, agent, panel, permissionPreset, agentPreset, agentPresetWarning?, permissionPresetApplied?, permissionPresetWarning? }'),
1087
1988
  async execute(args, exec) {
1088
- const runtime = await runtimeOfTeam(s, args.teamId);
1089
- if (runtime !== 'agent') {
1090
- const member = await request(s, `/api/teams/${encodeURIComponent(args.teamId)}/members`, {
1091
- method: 'POST',
1092
- body: {
1093
- name: args.name,
1094
- ...(args.role !== undefined ? { role: args.role } : {}),
1095
- ...(args.model !== undefined ? { model: args.model } : {}),
1096
- ...(args.contextMode !== undefined ? { contextMode: args.contextMode } : {}),
1097
- },
1098
- });
1099
- return { member, panel: panelUrl(s) };
1100
- }
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);
1101
1992
 
1102
- // ---- agent 团队:用 subagents 服务起一个 continuable 真子会话 ----
1993
+ // ---- 用 subagents 服务起一个 continuable 真子会话 ----
1103
1994
  const subs = subagentsOf(ctx);
1104
1995
  if (!subs || typeof subs.startActivation !== 'function') {
1105
- throw new Error('subagents 服务不可用:无法在 agent 团队里创建 sub-agent 成员(需要宿主启用 dsh-subagent)。');
1996
+ throw new Error('subagents 服务不可用:无法创建 sub-agent 成员(需要宿主启用 dsh-subagent)。');
1106
1997
  }
1107
1998
  const caller = exec?.agent;
1108
- if (!caller) throw new Error('team_spawn (agent) 需要 Lead 会话上下文(exec.agent 缺失:不能在非 agent 调用里起成员)。');
1109
- 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(成员的初始指令)。');
1110
2001
 
1111
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;
1112
2013
  const provider = providerFor(ctx, s, context);
1113
2014
  // 实际 route:显式参数覆盖 Lead;effort 只在 route 未变时继承(与 DSH 子会话合并规则一致)
1114
2015
  const leadRoute = leadRouteOf(caller);
1115
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
+ }
1116
2036
  const routeChanged = route.provider !== leadRoute.provider || route.model !== leadRoute.model;
1117
2037
  route.reasoningEffort = args.reasoningEffort || (routeChanged ? null : leadRoute.reasoningEffort);
1118
2038
  // 继承 Lead 的 route 也要过启用闸门:停用项不该被成员继续使用;effort 同理。
1119
2039
  await assertRouteEnabled(s, ctx, route.provider, route.model, route.reasoningEffort);
1120
2040
  const agentOptions = {};
1121
- if (args.agentProvider) agentOptions.provider = String(args.agentProvider);
1122
- if (args.model) agentOptions.model = String(args.model);
1123
- 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
+ }
1124
2046
  const memberName = String(args.name).trim();
1125
2047
  const description = String(args.description || args.role || memberName).slice(0, 200);
1126
2048
  const sessionId = randomUUID();
1127
- const team = await request(s, `/api/teams/${encodeURIComponent(args.teamId)}`).catch(() => null);
1128
2049
  const started = await subs.startActivation({
1129
2050
  delivery: 'parent',
1130
2051
  childId: sessionId,
@@ -1135,12 +2056,14 @@ function buildTools(s, ctx) {
1135
2056
  parent: caller,
1136
2057
  ...(team && team.workspace ? { cwd: team.workspace } : {}),
1137
2058
  ...(Object.keys(agentOptions).length ? { agentOptions } : {}),
2059
+ ...(agentPreset ? { agentPreset } : {}),
1138
2060
  },
1139
2061
  signal: exec.signal || AbortSignal.timeout(s.requestTimeoutMs),
1140
2062
  });
1141
2063
  // 成员跑的是一整轮 agent loop,结果由 team_report_task 汇报;这里只防止未处理的 rejection。
1142
2064
  if (started && started.result && typeof started.result.catch === 'function') started.result.catch(() => {});
1143
- 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);
1144
2067
 
1145
2068
  const registered = await request(s, '/api/agents/register', {
1146
2069
  method: 'POST',
@@ -1148,28 +2071,37 @@ function buildTools(s, ctx) {
1148
2071
  teamId: args.teamId,
1149
2072
  name: memberName,
1150
2073
  sessionId,
2074
+ parentSessionId: caller.id != null ? String(caller.id) : null,
1151
2075
  role: args.role || 'teammate',
1152
- model: args.model || spawned.member.model || null,
2076
+ model: args.model || route.model || null,
1153
2077
  contextMode: context,
2078
+ agentProvider: route.provider || null,
2079
+ permissionPreset,
2080
+ ...(agentPreset ? { agentPreset } : {}),
1154
2081
  // 实际生效的思考强度(含从 Lead 继承的值):面板成员卡片据此展示,之后不可变
1155
2082
  reasoningEffort: route.reasoningEffort || null,
1156
2083
  },
1157
2084
  });
1158
- rememberMember(sessionId, args.teamId, registered.member.id, team?.workspace);
2085
+ rememberMember(sessionId, args.teamId, registered.member.id, team?.workspace, registered.member.permissionPreset || permissionPreset, memberName);
1159
2086
  leadByTeam.set(args.teamId, caller);
1160
2087
  return {
1161
2088
  member: registered.member,
1162
2089
  agent: {
1163
2090
  sessionId,
1164
- name: spawned.member.name,
1165
- status: spawned.member.status,
1166
- role: spawned.member.role,
2091
+ name: memberName,
2092
+ status: 'running',
2093
+ role: args.role || 'teammate',
1167
2094
  provider,
1168
2095
  context,
1169
2096
  model: route.model || null,
1170
2097
  route,
1171
- diagnostics: spawned.member.diagnostics || [],
1172
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 } : {}),
1173
2105
  panel: panelUrl(s),
1174
2106
  };
1175
2107
  },
@@ -1215,9 +2147,63 @@ function buildTools(s, ctx) {
1215
2147
  },
1216
2148
  });
1217
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
+
1218
2204
  tools.push({
1219
2205
  name: 'team_status',
1220
- 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.',
1221
2207
  parameters: {
1222
2208
  type: 'object',
1223
2209
  additionalProperties: false,
@@ -1239,10 +2225,11 @@ function buildTools(s, ctx) {
1239
2225
  asOf: st.asOf,
1240
2226
  version: st.version,
1241
2227
  panel: panelUrl(s),
1242
- runtime: st.runtime || runtimeByTeam.get(args.teamId) || 'worker',
1243
2228
  members: (st.members || []).map((m) => ({
1244
2229
  name: m.name,
1245
2230
  model: m.model || null,
2231
+ permissionPreset: m.permissionPreset || null,
2232
+ agentPreset: m.agentPreset || null,
1246
2233
  reasoningEffort: m.reasoningEffort || null,
1247
2234
  status: m.status,
1248
2235
  step: m.step,
@@ -1251,7 +2238,6 @@ function buildTools(s, ctx) {
1251
2238
  next: m.next,
1252
2239
  last: m.last,
1253
2240
  currentTaskId: m.currentTaskId,
1254
- leaseUntil: m.leaseUntil,
1255
2241
  blockers: m.blockers,
1256
2242
  stale: m.stale,
1257
2243
  agentSessionId: m.agentSessionId || null,
@@ -1265,7 +2251,7 @@ function buildTools(s, ctx) {
1265
2251
 
1266
2252
  tools.push({
1267
2253
  name: 'team_task',
1268
- 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.',
1269
2255
  parameters: {
1270
2256
  type: 'object',
1271
2257
  additionalProperties: false,
@@ -1273,7 +2259,7 @@ function buildTools(s, ctx) {
1273
2259
  teamId: { type: 'string' },
1274
2260
  subject: { type: 'string', description: 'Concise task title.' },
1275
2261
  assignee: { type: 'string', description: 'Member id (not name). Omit to let the scheduler pick an idle member.' },
1276
- 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.' },
1277
2263
  deps: {
1278
2264
  type: 'array',
1279
2265
  description: 'Upstream dependencies declared atomically with the task: [{from, condition?, artifactPath?}].',
@@ -1288,12 +2274,11 @@ function buildTools(s, ctx) {
1288
2274
  required: ['from'],
1289
2275
  },
1290
2276
  },
1291
- writeScopes: { type: 'array', items: { type: 'string' }, description: 'Advisory write scope prefixes (sidecar policies are the enforced ones).' },
1292
2277
  acceptance: { type: 'string' },
1293
2278
  priority: { type: 'integer', description: 'Smaller runs first. Default 0.' },
1294
2279
  failurePolicy: { type: 'string', enum: ['continue', 'skip', 'abort_team', 'retry'] },
1295
2280
  maxAttempts: { type: 'integer' },
1296
- 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.' },
1297
2282
  },
1298
2283
  required: ['teamId', 'subject', 'plan'],
1299
2284
  },
@@ -1308,14 +2293,13 @@ function buildTools(s, ctx) {
1308
2293
  ...(args.assignee !== undefined ? { assignee: args.assignee } : {}),
1309
2294
  plan: args.plan || [],
1310
2295
  ...(args.deps !== undefined ? { deps: args.deps } : {}),
1311
- ...(args.writeScopes !== undefined ? { writeScopes: args.writeScopes } : {}),
1312
2296
  ...(args.acceptance !== undefined ? { acceptance: args.acceptance } : {}),
1313
2297
  ...(args.priority !== undefined ? { priority: args.priority } : {}),
1314
2298
  ...(args.failurePolicy !== undefined ? { failurePolicy: args.failurePolicy } : {}),
1315
2299
  ...(args.maxAttempts !== undefined ? { maxAttempts: args.maxAttempts } : {}),
1316
2300
  },
1317
2301
  });
1318
- if (args.dispatch === false || (await runtimeOfTeam(s, args.teamId)) !== 'agent') return { task };
2302
+ if (args.dispatch === false) return { task };
1319
2303
  await sleep(s.agentSettleMs);
1320
2304
  const dispatched = await dispatchLoop(s, ctx, args.teamId);
1321
2305
  return { task, dispatched };
@@ -1324,7 +2308,7 @@ function buildTools(s, ctx) {
1324
2308
 
1325
2309
  tools.push({
1326
2310
  name: 'team_send',
1327
- 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.",
1328
2312
  parameters: {
1329
2313
  type: 'object',
1330
2314
  additionalProperties: false,
@@ -1345,9 +2329,8 @@ function buildTools(s, ctx) {
1345
2329
  if (exec?.agent && !callerMember) leadByTeam.set(args.teamId, exec.agent);
1346
2330
  const from = callerMember ? callerMember.memberId : 'lead';
1347
2331
  const toLead = String(args.to).trim().toLowerCase() === 'lead';
1348
- const runtime = await runtimeOfTeam(s, args.teamId);
1349
2332
  // sidecar 的收件人只能是成员 id、'*' 或虚拟收件人 'lead',所以先把 name / id 统一解析成成员行。
1350
- 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 })}`);
1351
2334
  const members = st?.members || [];
1352
2335
  const resolve = (v) => members.find((m) => m.name === v || m.id === v) || null;
1353
2336
  if (!toLead && args.to !== '*' && (members.length ? !resolve(args.to) : false)) {
@@ -1363,8 +2346,8 @@ function buildTools(s, ctx) {
1363
2346
  ...(args.correlationId !== undefined ? { correlationId: args.correlationId } : {}),
1364
2347
  },
1365
2348
  });
1366
- // 成员→Lead 只落信箱(面板可见),不打扰 Lead 会话;worker 团队也没有可唤醒的 sub-agent。
1367
- if (runtime !== 'agent' || toLead) return recorded;
2349
+ // 成员→Lead 只落信箱(面板可见),不打扰 Lead 会话。
2350
+ if (toLead) return recorded;
1368
2351
 
1369
2352
  const subs = subagentsOf(ctx);
1370
2353
  // 成员之间互通必须借 Lead 的 agent 句柄:成员会话都挂在 Lead 下,成员直发会「belongs to another parent session」。
@@ -1484,110 +2467,102 @@ function buildTools(s, ctx) {
1484
2467
  });
1485
2468
 
1486
2469
  tools.push({
1487
- name: 'team_scope',
1488
- 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.',
1489
2472
  parameters: {
1490
2473
  type: 'object',
1491
2474
  additionalProperties: false,
1492
2475
  properties: {
1493
- action: { type: 'string', enum: ['list', 'request', 'decide'], description: 'Required operation.' },
1494
- teamId: { type: 'string', description: 'Required for list and request.' },
1495
- status: { type: 'string', description: 'For list: pending | approved | denied | expired.' },
1496
- memberId: { type: 'string', description: 'For request: the blocked member.' },
1497
- domain: { type: 'string', enum: ['fs', 'exec', 'net', 'env'] },
1498
- target: { type: 'string', description: 'Relative path, argv string, host:port, or env var name.' },
1499
- reason: { type: 'string' },
1500
- diffSize: { type: 'integer' },
1501
- risk: { type: 'string' },
1502
- blockedStep: { type: 'string' },
1503
- fallback: { type: 'string', description: 'What the member should do if denied.' },
1504
- requestId: { type: 'string', description: 'For decide.' },
1505
- decision: { type: 'string', enum: ['approved', 'denied'], description: 'For decide.' },
1506
- decidedBy: { type: 'string', description: 'Who decided; defaults to lead.' },
1507
- ttlSeconds: { type: 'integer', description: 'Grant lifetime in seconds. Default 60.' },
1508
- 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.' },
1509
2480
  },
1510
- required: ['action'],
2481
+ required: ['teamId', 'requestId', 'decision'],
1511
2482
  },
1512
- output: jsonOutput('{ items? , scopeRequest?, decision?, grant? }'),
1513
- async execute(args) {
1514
- const action = args.action;
1515
- if (action === 'list') {
1516
- if (!args.teamId) throw new Error('team_scope list requires teamId');
1517
- return await request(s, `/api/scope-requests${qs({ team: args.teamId, status: args.status })}`);
1518
- }
1519
- if (action === 'request') {
1520
- if (!args.teamId || !args.memberId || !args.domain || !args.target) {
1521
- throw new Error('team_scope request requires teamId, memberId, domain, target');
1522
- }
1523
- const scopeRequest = await request(s, '/api/scope-requests', {
1524
- method: 'POST',
1525
- body: {
1526
- memberId: args.memberId,
1527
- teamId: args.teamId,
1528
- domain: args.domain,
1529
- target: args.target,
1530
- reason: args.reason || '',
1531
- ...(args.diffSize !== undefined ? { diffSize: args.diffSize } : {}),
1532
- ...(args.risk !== undefined ? { risk: args.risk } : {}),
1533
- ...(args.blockedStep !== undefined ? { blockedStep: args.blockedStep } : {}),
1534
- ...(args.fallback !== undefined ? { fallback: args.fallback } : {}),
1535
- },
1536
- });
1537
- return { scopeRequest };
1538
- }
1539
- if (action === 'decide') {
1540
- if (!args.requestId || !args.decision) throw new Error('team_scope decide requires requestId and decision');
1541
- return await request(s, `/api/scope-requests/${encodeURIComponent(args.requestId)}/decide`, {
1542
- method: 'POST',
1543
- body: {
1544
- decision: args.decision,
1545
- decidedBy: args.decidedBy || 'lead',
1546
- ...(args.reason !== undefined ? { reason: args.reason } : {}),
1547
- ...(args.ttlSeconds !== undefined ? { ttlSeconds: args.ttlSeconds } : {}),
1548
- ...(args.singleUse !== undefined ? { singleUse: args.singleUse } : {}),
1549
- },
1550
- });
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 可以审批这个请求');
1551
2495
  }
1552
- 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 };
1553
2498
  },
1554
2499
  });
1555
2500
 
1556
2501
  tools.push({
1557
2502
  name: 'team_control',
1558
- 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.',
1559
2504
  parameters: {
1560
2505
  type: 'object',
1561
2506
  additionalProperties: false,
1562
2507
  properties: {
1563
- action: { type: 'string', enum: ['interrupt', 'resume', 'assign'] },
2508
+ action: { type: 'string', enum: ['interrupt', 'resume', 'assign', 'abort'] },
1564
2509
  teamId: { type: 'string', description: 'Required to control an agent-team member.' },
1565
- memberId: { type: 'string' },
1566
- taskId: { type: 'string', description: 'Required for assign.' },
1567
- 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.' },
1568
2513
  },
1569
- required: ['action', 'memberId'],
2514
+ required: ['action'],
1570
2515
  },
1571
2516
  output: jsonOutput('{ member, ... }'),
1572
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`);
1573
2536
  const id = encodeURIComponent(args.memberId);
1574
2537
  if (args.action === 'interrupt') {
1575
2538
  const res = await request(s, `/api/members/${id}/interrupt`, { method: 'POST', body: { reason: args.reason || 'lead interrupt' } });
1576
- const runtime = args.teamId ? await runtimeOfTeam(s, args.teamId) : 'worker';
1577
- if (runtime === 'agent' && res?.member?.agentSessionId) {
2539
+ if (res?.member?.agentSessionId) {
2540
+ const sid = String(res.member.agentSessionId);
1578
2541
  const subs = subagentsOf(ctx);
1579
2542
  const caller = exec?.agent;
1580
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');
1581
2550
  const interrupted = await Promise.resolve()
1582
- .then(() => subs.interrupt(String(res.member.agentSessionId), { kind: 'ancestor', agent: caller }))
2551
+ .then(() => subs.interrupt(sid, { kind: 'ancestor', agent: caller }))
1583
2552
  .then(() => ({ ok: true, previousStatus: res.member.agentStatus ?? null }),
1584
2553
  (err) => ({ ok: false, error: String(err?.message || err) }));
2554
+ if (!interrupted.ok) heldSessions.delete(sid);
1585
2555
  return { ...res, agent: interrupted };
1586
2556
  }
1587
2557
  }
1588
2558
  return res;
1589
2559
  }
1590
- 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
+ }
1591
2566
  if (args.action === 'assign') {
1592
2567
  if (!args.taskId) throw new Error('team_control assign requires taskId');
1593
2568
  return await request(s, `/api/members/${id}/assign`, { method: 'POST', body: { taskId: args.taskId } });
@@ -1596,9 +2571,191 @@ function buildTools(s, ctx) {
1596
2571
  },
1597
2572
  });
1598
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
+
1599
2756
  tools.push({
1600
2757
  name: 'team_report',
1601
- 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.',
1602
2759
  parameters: {
1603
2760
  type: 'object',
1604
2761
  additionalProperties: false,
@@ -1613,6 +2770,65 @@ function buildTools(s, ctx) {
1613
2770
  },
1614
2771
  });
1615
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
+
1616
2832
  return tools;
1617
2833
  }
1618
2834
 
@@ -1920,7 +3136,7 @@ export function apply(ctx, config) {
1920
3136
  const disposers = buildTools(s, ctx).map((tool) => ctx.tools.register(tool));
1921
3137
  return () => {
1922
3138
  for (const dispose of disposers.reverse()) { try { dispose(); } catch { /* ignore */ } }
1923
- 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();
1924
3140
  for (const timer of idleTimers.values()) clearTimeout(timer);
1925
3141
  for (const timer of startTimers.values()) clearTimeout(timer);
1926
3142
  idleTimers.clear(); startTimers.clear(); agentStatusBySession.clear(); lastReplyBySession.clear();
@@ -1931,6 +3147,29 @@ export function apply(ctx, config) {
1931
3147
  };
1932
3148
  }, 'dsh-team.tools()');
1933
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
+
1934
3173
  // 技能:skills 服务在场时把包内 `skills/` 注册成 provider,装上插件就带 `dsh-agent-team` 技能;
1935
3174
  // 服务缺失(老版本/测试假 ctx)时静默跳过,不影响工具面。
1936
3175
  if (typeof ctx.inject === 'function') {
@@ -1943,6 +3182,16 @@ export function apply(ctx, config) {
1943
3182
  });
1944
3183
  }
1945
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
+
1946
3195
  if (s.reportToolCalls) {
1947
3196
  ctx.on('tools/execute', (exec, next) => traceToolCall(s, ctx, exec, next));
1948
3197
  }
@@ -1993,6 +3242,13 @@ export function apply(ctx, config) {
1993
3242
  agentStatusBySession.set(sessionId, 'running');
1994
3243
  return;
1995
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
+ }
1996
3252
  if (status !== 'idle') {
1997
3253
  cancelIdleReport(sessionId);
1998
3254
  agentStatusBySession.set(sessionId, status);
@@ -2006,6 +3262,7 @@ export function apply(ctx, config) {
2006
3262
  const settle = Math.max(0, Number(s.agentIdleSettleMs) || 0);
2007
3263
  const finish = () => {
2008
3264
  idleTimers.delete(sessionId);
3265
+ if (heldSessions.has(sessionId)) { agentStatusBySession.set(sessionId, 'interrupted'); return; }
2009
3266
  if (agentStatusBySession.get(sessionId) !== 'idle') return; // 窗口内又跑起来了
2010
3267
  // 把这一轮最后的正文带给 sidecar:漏调 team_report_task 时,兜底收尾的 task.done 也有摘要可看
2011
3268
  const reply = lastReplyBySession.get(sessionId);
@@ -2033,6 +3290,8 @@ export function apply(ctx, config) {
2033
3290
  if (event && event.type === 'turn/end') {
2034
3291
  const reason = event.data?.reason;
2035
3292
  if (reason && reason.kind === 'error') {
3293
+ // 冻结中的会话:中断本身可能让回合以 error 结束,不要覆盖 sidecar 的 interrupted。
3294
+ if (heldSessions.has(sessionId)) return;
2036
3295
  const err = reason.error || {};
2037
3296
  const msg = String(err.message || err.code || 'unknown error').slice(0, 500);
2038
3297
  cancelIdleReport(sessionId);
@@ -2056,6 +3315,15 @@ export function apply(ctx, config) {
2056
3315
  return () => clearInterval(timer);
2057
3316
  }, 'dsh-team.agent-heartbeat()');
2058
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
+
2059
3327
  // 成员上下文快照:面板「上下文分析」页的数据来源。周期泵覆盖进行中的回合,
2060
3328
  // agent/status 变化时补报一次(回合结束/中断后上下文占用才定型)。
2061
3329
  if (s.reportContext) {
@@ -2111,6 +3379,87 @@ export function apply(ctx, config) {
2111
3379
  }, 'dsh-team.llm-catalog-pump()');
2112
3380
  }
2113
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
+
2114
3463
  // 保底泵:负责 lead 不在工具调用栈里时(例如成员直接回报)把 ready 任务继续发出去。
2115
3464
  if (s.agentAutoDispatch) {
2116
3465
  ctx.effect(() => {
@@ -2123,4 +3472,13 @@ export function apply(ctx, config) {
2123
3472
  return () => clearInterval(timer);
2124
3473
  }, 'dsh-team.agent-pump()');
2125
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()');
2126
3484
  }